From cjw at sympatico.ca Mon Nov 26 16:21:48 2007 From: cjw at sympatico.ca (Colin J. Williams) Date: Mon, 26 Nov 2007 16:21:48 -0500 Subject: the annoying, verbose self In-Reply-To: <474b1b44$0$20133$426a74cc@news.free.fr> References: <3c954a31-9fb9-4c0f-b784-cef9ee057ca6@g30g2000hsb.googlegroups.com> <4068d518-cba9-4eac-bd91-11f676c17b3d@w34g2000hsg.googlegroups.com> <5qq6quF10jrh5U2@mid.uni-berlin.de> <5qqoslF10jrh5U6@mid.uni-berlin.de> <474b1b44$0$20133$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: [snip]> > Too bad : in Python, everything's an object, so 'methods' are attributes > too. What do you see as a problem here? Surely it gives useful flexibility. Colin W. From phil at riverbankcomputing.co.uk Fri Nov 23 03:43:00 2007 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Fri, 23 Nov 2007 08:43:00 +0000 Subject: Qt Designer required for PyQt? In-Reply-To: References: Message-ID: <200711230843.00047.phil@riverbankcomputing.co.uk> On Friday 23 November 2007, Kevin Walzer wrote: > is it possible to write the GUI code for PyQt applications by hand or > is using the Qt Designer an essential part of the process? Coming from a > Tkinter background, with a little exposure to wxPython, I'm very > comfortable and productive writing GUI code by hand. I understand the > appeal of using the GUI builder to visualize how your GUI will look, but > it also can add a layer of complexity. Does anyone write complex PyQt > apps without using Designer? Do whatever fits your brain the best. Typically I would do both in an application. One particular advantage of the Designer approach is that you can sit down with a user and quickly produce a working GUI that they are happy with. Phil From antroy at gmail.com Thu Nov 1 09:23:20 2007 From: antroy at gmail.com (Ant) Date: Thu, 01 Nov 2007 06:23:20 -0700 Subject: What is Jython? In-Reply-To: <1193917020.873344.252710@y42g2000hsy.googlegroups.com> References: <1193900068.263686.174020@v23g2000prn.googlegroups.com> <1193906235.560348.226380@v3g2000hsg.googlegroups.com> <1193917020.873344.252710@y42g2000hsy.googlegroups.com> Message-ID: <1193923400.063743.233670@50g2000hsm.googlegroups.com> On Nov 1, 11:37 am, Ze'ev wrote: ... > ...> Jython is currently significantly slower than Python. > > ... > Not according to this :http://blogs.warwick.ac.uk/dwatkins/entry/benchmarking_parallel_pytho... Well I'm damned - I thought that I'd be writing about this being a parallel example, and Java (and hence Jython)'s better threading support. Decided to run a few of my old "mathchallenge" scripts through both Python and Jython, and on some of the examples Python was running almost 4 times slower... So that's parallel processing and mathematical processing that seems faster in Jython. It's be interesting to see a proper comparison of how different types of program run. The VM startup overhead is much slower mind, but then that's only an issue for very small programs. Cheers, -- Ant. From horpner at yahoo.com Tue Nov 6 10:48:11 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Tue, 06 Nov 2007 15:48:11 GMT Subject: Is pyparsing really a recursive descent parser? References: <5p0dhgFnj4rbU1@mid.uni-berlin.de> <1194007658.200713.178210@57g2000hsv.googlegroups.com> <1194104971.263256.66640@d55g2000hsg.googlegroups.com> <43rXi.397547$6L.130044@fe03.news.easynews.com> <1194223837.104424.242360@o3g2000hsb.googlegroups.com> Message-ID: On 2007-11-05, Just Another Victim of the Ambient Morality wrote: > "Kay Schluehr" wrote in message > news:1194223837.104424.242360 at o3g2000hsb.googlegroups.com... >> I'm not sure one needs to start again with a naive approach >> just to avoid any parser theory. For a user of a parser it is >> quite important whether she has to wait 50 seconds for a parse >> to run or 50 milliseconds. I don't like to compromise speed >> for implementation simplicity here. > > This attitude is all too prevalent among computer > professionals... Of course it's a useful thing to shield users > from the intricacies of parser theory! Just as much as it is > useful to shield drivers from needing automotive engineering or > software users from programing. How many people have come to > this newsgroup asking about anomalous pyparsing behaviour, > despite their grammars being mathematically correct. You might be interested in the Early parsing algorithm. It is more efficient than the naive approach used in your prototype, and still handles ambiguous grammars. There is a Python module SPARK that provides generic classes for building small language compilers using an Early parser, and I was able to get it to parse your ambiguous grammar without trouble. It is not as convenient or as well documented as PyParsing, but the parsing algorithm provides the power you're looking for. It might serve as a backend for the library you're currently working on. http://www.cpsc.ucalgary.ca/~aycock/spark/ -- Neil Cerutti From sjmachin at lexicon.net Tue Nov 20 16:40:55 2007 From: sjmachin at lexicon.net (John Machin) Date: Tue, 20 Nov 2007 13:40:55 -0800 (PST) Subject: regex problem with re and fnmatch References: Message-ID: On Nov 21, 8:05 am, Fabian Braennstroem wrote: > Hi, > > I would like to use re to search for lines in a files with > the word "README_x.org", where x is any number. > E.g. the structure would look like this: > [[file:~/pfm_v99/README_1.org]] > > I tried to use these kind of matchings: > # org_files='.*README\_1.org]]' > org_files='.*README\_*.org]]' > if re.match(org_files,line): First tip is to drop the leading '.*' and use search() instead of match(). The second tip is to use raw strings always for your patterns. > > Unfortunately, it matches all entries with "README.org", but > not the wanted number!? \_* matches 0 or more occurrences of _ (the \ is redundant). You need to specify one or more digits -- use \d+ or [0-9]+ The . in .org matches ANY character except a newline. You need to escape it with a \. >>> pat = r'README_\d+\.org' >>> re.search(pat, 'xxxxREADME.org') >>> re.search(pat, 'xxxxREADME_.org') >>> re.search(pat, 'xxxxREADME_1.org') <_sre.SRE_Match object at 0x00B899C0> >>> re.search(pat, 'xxxxREADME_9999.org') <_sre.SRE_Match object at 0x00B899F8> >>> re.search(pat, 'xxxxREADME_9999Zorg') >>> > > After some splitting and replacing I am able to check, if > the above file exists. If it does not, I start to search for > it using the 'walk' procedure: I presume that you mean something like: """.. check if the above file exists in some directory. If it does not, I start to search for it somewhere else ...""" > > for root, dirs, files in > os.walk("/home/fab/org"): > for name in dirs: > dirs=os.path.join(root, name) + '/' The above looks rather suspicious ... for thing in container: container = something_else ???? What are you trying to do? > for name in files: > files=os.path.join(root, name) and again .... > if fnmatch.fnmatch(str(files), "README*"): Why str(name) ? > print "File Found" > print str(files) > break fnmatch is not as capable as re; in particular it can't express "one or more digits". To search a directory tree for the first file whose name matches a pattern, you need something like this: def find_one(top, pat): for root, dirs, files in os.walk(top): for fname in files: if re.match(pat + '$', fname): return os.path.join(root, fname) > As soon as it finds the file, "the" file or "a" file??? Ummm ... aren't you trying to locate a file whose EXACT name you found in the first exercise?? def find_it(top, required): for root, dirs, files in os.walk(top): if required in files: return os.path.join(root, required) > it should stop the searching > process; but there is the same matching problem like above. HTH, John From esj at harvee.org Wed Nov 14 08:10:16 2007 From: esj at harvee.org (Eric S. Johansson) Date: Wed, 14 Nov 2007 08:10:16 -0500 Subject: Using Python To Change The World :) In-Reply-To: <1195009751.327435.182540@i13g2000prf.googlegroups.com> References: <1195009751.327435.182540@i13g2000prf.googlegroups.com> Message-ID: <473AF3B8.8020204@harvee.org> dominiquevalentine at gmail.com wrote: > Hello, I'm a teen trying to do my part in improving the world, and me > and my pal came up with some concepts to improve the transportation > system. > > I have googled up and down for examples of using python to create a > city street but I can not find any. http://www.gis.usu.edu/~sanduku/public_html/dissertation/outline/node23.html """Automobile traffic has a very extensive body of literature involving simulation. Most people in the industrialized world deal with automobile traffic on a daily basis, and many studies are funded annually to alleviate existing or potential traffic problems. Several academic journals are dedicated exclusively to automobile traffic dynamics, new textbooks on the subject are published regularly, and the number of articles published each year dealing with automobile traffic number in the hundreds. """ while they may not be in Python, I'm sure you can find modeling systems to do a you want to do for far less effort than it would take to re-create them from scratch. -- Speech-recognition in use. It makes mistakes, I correct some. From arne at vajhoej.dk Wed Nov 14 20:37:23 2007 From: arne at vajhoej.dk (=?UTF-8?B?QXJuZSBWYWpow7hq?=) Date: Wed, 14 Nov 2007 20:37:23 -0500 Subject: SPAM In-Reply-To: References: <1195065929.848318.25100@i13g2000prf.googlegroups.com> <473b46c3$0$79945$742ec2ed@news.sonic.net> <473b4fdf$0$79951$742ec2ed@news.sonic.net> Message-ID: <473ba2c8$0$90265$14726298@news.sunsite.dk> Lew wrote: > Yes, but it's not SPAM. > > SPAM is a registered trademark of Hormel Foods Corporation for a canned > pork product. > > Spam is unwanted messages or email. It should be rather obvious what is was. Why not leave it to Hormel to complain ? Arne From bscrivener42 at gmail.com Sat Nov 3 11:28:52 2007 From: bscrivener42 at gmail.com (BartlebyScrivener) Date: Sat, 03 Nov 2007 15:28:52 -0000 Subject: Python IDE In-Reply-To: References: Message-ID: <1194103732.450284.300420@o3g2000hsb.googlegroups.com> On Nov 3, 9:11 am, Simon Pickles wrote: >I need a Python IDE and debugger . . . I use vim on both Windows XP and Debian, but I used to use Komodo for big projects. Try the free trial of Komodo http://www.activestate.com/Products/komodo_ide/ It has what you want, and it comes with licenses for both Windows and Linux. rd From larry.bates at websafe.com Mon Nov 12 11:57:57 2007 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 12 Nov 2007 10:57:57 -0600 Subject: Moving from java to python. In-Reply-To: <1194882167.587530.8510@k79g2000hse.googlegroups.com> References: <1194881119.674022.326040@22g2000hsm.googlegroups.com> <1194882167.587530.8510@k79g2000hse.googlegroups.com> Message-ID: Paul Hankin wrote: > On Nov 12, 3:25 pm, "PeterBrad... at googlemail.com" > wrote: >> Hi, >> >> I have recently been learning python, and coming from a java >> background there are many new ways of doing things that I am only just >> getting to grips with. >> >> I wondered if anyone could take a look at a few pieces of code I have >> written to see if there are any places where I am still using java- >> esque techniques, and letting me know the appropriate python way of >> doing things. >> >> Here is a node class I wrote for use in graph traversal algorithms: >> >> #==== >> >> class Node: >> """ >> Node models a single piece of connected data. >> >> Author: Peter Braden >> Last Modified : Nov. '07 >> """ >> >> def __init__(self, connections = None, uid = None): >> """ >> Args: >> [connections - a list of (connected node, weight) tuples. ] >> [uid - an identifier for comparisons.] >> """ >> self._connected = [] >> self._weights = [] >> >> if connections: >> for i in connections: >> self.connected.append(i[0]) >> self.weights.append(i[1]) >> >> if not uid: >> self.id = id(self) >> else: >> self.id = uid >> >> def __eq__(self, other): >> return self.id == other.id >> >> def getConnected(self): >> return self._connected >> >> def getWeights(self): >> return self._weights >> >> def getConnections(self): >> connections = [] >> for i in range(len(connected)): >> connections.append((self._connected[i],self._weight[i])) >> return connections >> >> connected = property(getConnected, None) >> weights = property (getWeights, None) >> connections = property(getConnections, None) >> >> def addConnection(self, node, weight = 0): >> self.connected.append(node) >> self.weights.append(weight) >> >> def removeConnection(self, node): >> i = self._connected.index(node) >> del self._connected[i] >> del self._weights[i] > > There's no reason to make 'connected' and 'weights' properties: just > use them directly. > > Make 'connections' default to [] rather than None, and replace the > slightly clumsy initialisation with more direct code: > > self.connected = [i[0] for i in connections] > self.weights = [i[1] for i in connections] > > getConnections can be much simpler... > > def getConnections(self): > return zip(self.connected, self.weights) > > The 'uid' business makes me suspicious: what's it for? If you need it, > you probably need to initialise with an explicit test for None rather > than just 'if uid' which will be wrong if you use a uid of 0... > > self.id = uid if uid is not None else id(self) > > HTH > -- > Paul Hankin > Be VERY careful with using [] as default arguments. Mutables are only evaluated once (not at every call). This question comes up about once a week on this forum where people don't understand this. I would recommend using (if you can): def __init__(self, connected = None, weights=None, uid = None): self.connected = connected or [] self.weights = weights or [] If you want to stay with single connections list do this: def __init__(self, connections = None, uid = None): if connections is not None: self.connected=[c[0] for c in connections] self.weights=[c(1) for c in connections] else: self.connected=[] self.weights=[] Others have addressed the lack of need for accessors. -Larry From ihatespam at hotmail.com Sun Nov 4 23:30:13 2007 From: ihatespam at hotmail.com (Just Another Victim of the Ambient Morality) Date: Mon, 05 Nov 2007 04:30:13 GMT Subject: Is pyparsing really a recursive descent parser? References: <5p0dhgFnj4rbU1@mid.uni-berlin.de> <1194007658.200713.178210@57g2000hsv.googlegroups.com> <1194104971.263256.66640@d55g2000hsg.googlegroups.com> <43rXi.397547$6L.130044@fe03.news.easynews.com> <1194223837.104424.242360@o3g2000hsb.googlegroups.com> <6xvXi.39855$G23.18679@newsreading01.news.tds.net> Message-ID: "Neil Cerutti" wrote in message news:6xvXi.39855$G23.18679 at newsreading01.news.tds.net... > On 2007-11-05, Just Another Victim of the Ambient Morality > wrote: >> >> "Kay Schluehr" wrote in message >> news:1194223837.104424.242360 at o3g2000hsb.googlegroups.com... >>> On Nov 4, 10:44 pm, "Just Another Victim of the Ambient Morality" >>> >>> >>>> I believe there is a cure and it's called recursive descent parsing. >>>> It's slow, obviously, but it's correct and, sometimes (arguably, >>>> often), >>>> that's more important the execution speed. >>> >>> Recursive decendent parsing is not necessarily slow but from your >>> remarks above I infer you want a general RD parser with backtracking: >>> when one rule doesn't match, try another one to derive the current >>> symbol in the input stream. >> >> I think I've just discovered a major hurdle in my understand of the >> problem. >> You keep saying "with backtracking." Why? Isn't "backtracking" >> inherent in recursion? So, why can't these alleged "recursive descent >> parsers" find valid parsings? How are they not already backtracking? >> What >> was the point of being recursive if not to take advantage of the inherent >> backtracking in it? >> Obviously, these parsers aren't recursing through what I think they >> should be recursing. The question is "why not?" > > There are different kinds of recursion. Compare: > > def fac1(x, y=1): > """ Compute factorials with a recursive function (it calls > itself), but the stack is not actually used for storing > anything important, i.e., it is tail-recursive. """ > if x < 0: > raise ValueError('non-negative integer') > elif x == 0: > return y > else: > return fac1(x-1, y*x) > > to > > def fac2(x): > """ Computes factorials with a recursive process, keeping > the state of the calculation on the stack. """ > if x < 0: > raise ValueError('non-negative integer') > if x == 0: > return 1 > else: > return fac2(x-1) * x > > to > > def Ack(x, y): > """ The Ackermann function. Creates a humongous mess even > with quite tiny numbers. """ > if x < 0 or y < 0: > raise ValueError('non-negative integer') > elif x == 0: > return y + 1 > elif y == 0: > return foo3(x-1, 1) > else: > return foo3(x-1, foo3(x, y-1)) > > There's probably a word for the type of recursive process built > by fac2; the RDP's I'm most familiar with create a fac2 sort of > process, which stores valuable info on the stack. > > And even though fac1 defines an iterative process, the code > itself is recursive, and you can call it a recursive function if > you wish (and in Python you might as well). While interesting, none of this actually addresses the point I was making. I wasn't saying that there was no recursion (at least, not in this paragraph), I was saying that it wasn't recursing through what I thought it should be recursing through. It recurses through a set of rules without any regard to how these rules interact with each other. That's why it fails to parse valid strings. In my opinion, it should recurse through appropriate combinations of rules to determine validity, rather than by arbitrary categorization... >> Correct me if I'm wrong but I'm beginning to think that >> pyparsing doesn't typically use recursion, at all. It only >> employs it if you create one, using the Forward class. >> Otherwise, it does everything iteratively, hence the lack of >> "backtracking." > > It's recursive because each production rule calls other > production rules to define itself. A rule regularly ends up > calling itself. Consider the Parser class I built earlier. > list_tail keeps calling itself to continue consuming characters > in an ab_list. The stack is used to keep track of where we are in > the grammar; at any time you can look up the stack and see how > you got where you are--you 'descend' down from the topmost > productions to the most primitive productions, and then back up > once everything has been sorted out. Take another look > at the exception raised in my Parsing class example for an > illustrative traceback. I guess that all the And and Or class in pyparsing call methods of each other from each other, even if they are doing so from different instantiations. I still say they're not recursing through the right things... >>> I'm not sure one needs to start again with a naive approach just to >>> avoid any parser theory. For a user of a parser it is quite important >>> whether she has to wait 50 seconds for a parse to run or 50 >>> milliseconds. I don't like to compromise speed for implementation >>> simplicity here. >> >> Finally, I can't believe you complain about potential speed >> problems. First, depending on the size of the string, it's >> likely to be the difference between 2ms and 200ms. Secondly, >> if speed were an issue, you wouldn't go with a recursive >> descent parser. You'd go with LALR or the many other parsing >> techniques available. Recursive descent parsing is for those >> situations where you need correctness, regardless of execution >> time. These situations happen... > > RDP is plenty fast; speed has never been one of it's > disadvantages, as far as I know. Today there are many > excellent parser generators and compiler builders that compose an > RDP under the hood, e.g., Antlr and Gentle. I think I read somewhere that LALR was O(n) while RDP was O(e^n). Most people would consider that, at least, slower... I think your examples may exemplify how little speed matters rather than how fast RDPs are... >> I've said this before, albeit for a different language, but >> it applies to Python just as well. I don't use Python to write >> fast code, I use it to write code fast. >> If _you_ "don't like to compromise speed for implementation >> simplicity" then you have a plethora choices available to you. >> What about the guy who needs to parse correctly and is >> unconcerned about speed? > > You have to be concerned about speed when something runs so > slowly in common circumstances compared to other well-known > algotithms that you can't practically wait for an answer. Would > you consider bubble-sort a suitable general-purpose sorting > algorithm for Python? What you've stated is an hypothetical. You need to be concerned about speed when "you can't practically wait for an answer." Encryption is based on this, for example. I'm not sure what you're getting at with "compared to other well known algorithms." Generally, the Python virtual machine is pitifully slow when compared to a compiled C program, however, the comparison is unnecessary. For most tasks, Python is plenty fast. Context is key. Things don't have to be fast, they just need to be fast enough... As I have said before, if you need speed, there are many options. Often, speed is not important, especially with the power of computing available today. Development time is increasingly valuable. So, for us who are not overly concerned with speed, what are our options? Now, if my RDP takes two minutes to parse four characters of text, I'd sympathize with your point of view. However, it really isn't noticeably slow. I may be nervous parsing an entire text file with it but I'd feel safe parsing individual lines of a .conf file, for instance... And I'll have you know that when I was still learning to program (that is, before I knew sort() was part of the C standard), I would routinely implement bubble sort 'cause it was so trivial to implement. I wouldn't even short cut, necessarily. Just iterate it as many times as there are elements in the list! Also, it should probably be noted that bubble sort is very fast for nearly sorted lists; much faster than quicksort. So, while it shouldn't be the default sorting algorithm, you could have it somewhere in the library... From matt at tplus1.com Wed Nov 7 11:53:04 2007 From: matt at tplus1.com (Matthew Wilson) Date: Wed, 07 Nov 2007 16:53:04 GMT Subject: Need help writing coroutine Message-ID: I'm working on two coroutines -- one iterates through a huge stream, and emits chunks in pieces. The other routine takes each chunk, then scores it as good or bad and passes that score back to the original routine, so it can make a copy of the stream with the score appended on. I have the code working, but it just looks really ugly. Here's a vastly simplified version. One function yields some numbers, and the other function tells me if they are even or odd. def parser(): "I just parse and wait for feedback." for i in 1, 2, 3, 4, 5: score = (yield i) if score: print "%d passed!" % i def is_odd(n): "I evaluate each number n, and return True if I like it." if n and n % 2: return True def m(): try: number_generator = parser() i = None while 1: i = number_generator.send(is_odd(i)) except StopIteration: pass and here's the results when I run this: In [90]: m() 1 passed! 3 passed! 5 passed! So, clearly, the code works. But it is nonintuitive for the casual reader. I don't like the while 1 construct, I don't like manually trapping the StopIteration exception, and this line is really ugly: i = number_generator.send(is_odd(i)) I really like the old for i in parser(): deal, but I can't figure out how to use .send(...) with that. Can anyone help me pretty this up? I want to make this as intuitive as possible. TIA Matt From db3l.net at gmail.com Sat Nov 3 17:08:47 2007 From: db3l.net at gmail.com (David Bolen) Date: Sat, 03 Nov 2007 17:08:47 -0400 Subject: Low-overhead GUI toolkit for Linux w/o X11? References: <13ipjvic6aj8c69@corp.supernews.com> Message-ID: David Bolen writes: > When I was looking for an embedded graphics library for a prior > platform (ELAN 486, 2MB flash, 6MB RAM) under DOS, we took a look at > these: > > * GRX (http://grx.gnu.de/index.html) (...) > There aren't any Python wrappers for GRX, but the library is straight > C which should be easy to wrap (manually or with something like SWIG). > No built-in widget support at all (some sample button processing code > in a demo module), but easy enough to implement your own if your needs > are modest. I had forgotten, since we didn't use it, but there is an external mGui library (http://web.tiscalinet.it/morello/MGui/index.html) that can layer on top of GRX to provide higher level functionality. Of course, it would also have to be wrapped for use from Python. -- David From andy at britishideas.com Fri Nov 16 17:54:51 2007 From: andy at britishideas.com (andy at britishideas.com) Date: Fri, 16 Nov 2007 14:54:51 -0800 (PST) Subject: Embedded Python - Blocking Python Function References: <1195081362.973396.98060@z24g2000prh.googlegroups.com> <1bd11e17-bfb9-4228-b985-4e0788efee8c@s36g2000prg.googlegroups.com> <1057f690-ebbf-4d54-ba6f-a21ddd0f8b2c@d27g2000prf.googlegroups.com> Message-ID: <908717e9-8a27-4f5b-8dd7-bf254c1459ea@s12g2000prg.googlegroups.com> On Nov 15, 5:03 pm, "Gabriel Genellina" wrote: > En Thu, 15 Nov 2007 16:18:45 -0300, escribi?: > > > On Nov 15, 9:43 am, a... at britishideas.com wrote: > >> On Nov 14, 4:20 pm, "Gabriel Genellina" > >> wrote: > > >> > Not forcibly - you need some cooperation from the Main function. Maybe > >> > setting a global variable that Main checks periodically. > > > It works but the problem is that the script will be written by the end > > user. If they make a mistake and the cancel flag isn't perodically > > checked then it seems I have no way of cleanly ending the interpreter. > > If I wait for a specific time after requesting the Main function stop > > I need to be able to kill the interpreter without a runtime error. Any > > ideas? > > You could use PyThreadState_SetAsyncExc - it's supposed to raise an > exception in another thread. There is a Cookbook recipe using it here > > I've never actually used it, but I want to try it some day, so please > report back your findings if you decide to use this function. > > -- > Gabriel Genellina It seems this is the function I need, however the following gave an access violation: PyEval_AcquireLock(); PyThreadState_Swap(thread); // stop interpreter by sending system exit exception to it's thread PyThreadState_SetAsyncExc(thread->thread_id, PyExc_SystemExit); PyThreadState_Swap(maininterpreter); PyEval_ReleaseLock(); Andy From musiccomposition at gmail.com Fri Nov 30 19:27:49 2007 From: musiccomposition at gmail.com (Benjamin) Date: Fri, 30 Nov 2007 16:27:49 -0800 (PST) Subject: Bundling Python on Mac References: <5r7bstF135rvoU1@mid.uni-berlin.de> <5raf60F13oi0pU1@mid.uni-berlin.de> Message-ID: On Nov 30, 6:48 am, "Diez B. Roggisch" wrote: > Benjamin schrieb: > > > On Nov 29, 2:34 am, "Diez B. Roggisch" wrote: > >> Benjamin schrieb: > > >>> Hello, I'm writing a Python/PyQt application. For my Mac distribution. > >>> I would like to include all the needed libraries in the Mac bundle. > >>> How should I go about doing this? > >> The py2app distutils extension should do that for you. It works flawless > >> for PyObjc-apps for me - it _should_ do so for Qt as well, but I have to > >> admit that it sometimes had errors related to Qt when creating bundles - > >> so maybe you need to tweak the support a bit. > > Does it bundle the Python library with it, so there are no (excepting > > system) dependencies? > > It does. Beautiful! > > Diez From zhushenli at gmail.com Tue Nov 6 06:18:33 2007 From: zhushenli at gmail.com (Davy) Date: Tue, 06 Nov 2007 03:18:33 -0800 Subject: List to Tuple and Tuple to List? Message-ID: <1194347913.942763.250640@i38g2000prf.googlegroups.com> Hi all, I am curious about whether there is function to fransform pure List to pure Tuple and pure Tuple to pure List? For example, I have list L = [[1,2,3],[4,5,6]] something list2tuple() will have T=list2tuple(L)=((1,2,3),(4,5,6)) And the tuple2list() Any suggestions are welcome! Best regards, Davy From spe.stani.be at gmail.com Sat Nov 3 22:07:06 2007 From: spe.stani.be at gmail.com (SPE - Stani's Python Editor) Date: Sat, 03 Nov 2007 19:07:06 -0700 Subject: Python IDE In-Reply-To: References: Message-ID: <1194142026.649852.219030@k79g2000hse.googlegroups.com> On 3 nov, 15:11, Simon Pickles wrote: > Hi, > > I have recently moved from Windows XP to Ubuntu Gutsy. > > I need a Python IDE and debugger, but have yet to find one as good as > Pyscripter for Windows. Can anyone recommend anything? What are you all > using? > > Coming from a Visual Studio background, editing text files and using the > terminal to execute them offends my sensibilities :) > > Thanks > > Si SPE is developped on and works well with Ubuntu Gutsy. It includes a debugger and gui builers. Get it from subversion: http://pythonide.blogspot.com/2007/02/how-to-download-latest-spe-from_26.html Stani -- http://photobatch.stani.be http://pythonide.stani.be From sjdevnull at yahoo.com Thu Nov 8 17:30:05 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: Thu, 08 Nov 2007 14:30:05 -0800 Subject: Using python as primary language In-Reply-To: References: <1194508354.226023.232050@v3g2000hsg.googlegroups.com> Message-ID: <1194561005.427982.263160@s15g2000prm.googlegroups.com> On Nov 8, 2:09 pm, "Michael Bacarella" wrote: > > In our company we are looking for one language to be used as default > > language. So far Python looks like a good choice (slacking behind > > Java). A few requirements that the language should be able cope with > > are: > > How do you feel about multithreading support? > > A multithreaded application in Python will only use a single CPU on > multi-CPU machines due to big interpreter lock, whereas the "right thing" > happens in Java. Note that this is untrue for many common uses of threading (e.g. using threads to wait on network connections, or calling out to most common compute-intensive C extensions), where the GIL is released and multiple CPUs are used just fine. From sjmachin at lexicon.net Mon Nov 12 18:12:19 2007 From: sjmachin at lexicon.net (John Machin) Date: Mon, 12 Nov 2007 15:12:19 -0800 Subject: preparing data for visualization In-Reply-To: <1194904559.143487.152770@57g2000hsv.googlegroups.com> References: <1194904559.143487.152770@57g2000hsv.googlegroups.com> Message-ID: <1194909139.806760.125350@s15g2000prm.googlegroups.com> Bryan.Fodn... at gmail.com wrote: > I would like to have my data in a format so that I can create a > contour plot. > > My data is in a file with a format, where there may be multiple fields > > field = 1 > > 1a 0 > 2a 0 The above is NOT consistent with the later listing of your data file. [big snip > 10b 0 > > where the value is how far from the center it will be displaced, > > a b a > b a b > 10 0000000000|0000000000 0000000000|0000000000 0000000000| [big snip of seemingly irrelevant stuff] > 1 0000000000|0000000000 0000000000|0000000000 0000000000| > 0000000000 > > I could possibly have many of these that I will add together and > normalize to one. > > Also, there are 60 a and b blocks, the middle 40 are 0.5 times the > width of the outer 20. > > I thought about filling an array, but there is not a one to one > symmetry. > > I cannot seem to get my head around this. Can anybody help me get > started? > > I have tried to use a dictionary, but cannot seem to get it to work > the way I want. > > I try this, > > --------------------------------------------------------------------------------- > > f = open('TEST1.MLC') > > fields = {} > > for line in f: > if line.split()[0] == 'Field': > > field = int(line.split()[-1]) Do line.split() ONCE per line. > > elif line.split()[0] == 'Leaf': > fields[field] = line.split()[-1] > else: > line = f.next() Don't mix for line in f and line = f.next() otherwise you will you will skip lines that you don't want to skip and/ or become confused. > > --------------------------------------------------------------------------------- > > and get, > > --------------------------------------------------------------------------------- > > Traceback (most recent call last): > File "", line 1, in > line.split()[0] > IndexError: list index out of range This indicates that you have a list for which 0 is not a valid index. If it had 1 or more elements, then 0 would be a valid index. I conclude that the list is empty. This would happen if line contained no characters other than whitespace. > Here is my data file, > > --------------------------------------------------------------------------------- > > File Rev = G > Treatment = Dynamic Dose > Last Name = Fodness > First Name = Bryan > Patient ID = 0001 > Number of Fields = 4 > Number of Leaves = 120 > Tolerance = 0.50 > > Field = 10 > Index = 0.0000 > Carriage Group = 1 > Operator = > Collimator = 0.0 > Leaf 1A = 0.00 > Leaf 2A = 0.00 [snip] > Leaf 20A = 0.00 > Leaf 21A = 5.00 > Leaf 22A = 5.00 [snip] > Leaf 40A = 5.00 [big snip -- your code failed no later than the 10th line in the data file] To find out what is going on, print out some variables: 8<--- fodness.py ---- f = open('fodness.dat') fields = {} for lino, line in enumerate(f): tokens = line.split() print "Line %d: tokens = %r" % (lino, tokens) if not tokens: continue # blank/empty line tok0 = tokens[0] if tok0 == 'Field': field = int(tokens[-1]) elif tok0 == 'Leaf': fields[field] = tokens[-1] else: continue print " Fields:", fields 8<--- Results [truncated]: C:\junk>fodness.py | more Line 0: tokens = [] Line 1: tokens = ['File', 'Rev', '=', 'G'] [snip] Line 8: tokens = ['Tolerance', '=', '0.50'] Line 9: tokens = [] Line 10: tokens = ['Field', '=', '10'] Fields: {} Line 11: tokens = ['Index', '=', '0.0000'] Line 12: tokens = ['Carriage', 'Group', '=', '1'] Line 13: tokens = ['Operator', '='] Line 14: tokens = ['Collimator', '=', '0.0'] Line 15: tokens = ['Leaf', '1A', '=', '0.00'] Fields: {10: '0.00'} <<<<<<<<<<====== Don't you need a float instead of a string?? Line 16: tokens = ['Leaf', '2A', '=', '0.00'] Fields: {10: '0.00'} Line 17: tokens = ['Leaf', '3A', '=', '0.00'] Fields: {10: '0.00'} Line 18: tokens = ['Leaf', '4A', '=', '0.00'] Fields: {10: '0.00'} Don't you want/need to use the leaf IDs (1A, 2A, etc)?? I guess that you want to end up with NESTED dictonaries, like this: fields = { 10: { '1A': 0.0, '2A': 0.0, etc, }, 8: { etc, }, etc, } HTH, John From cjw at sympatico.ca Sat Nov 24 08:45:58 2007 From: cjw at sympatico.ca (Colin J. Williams) Date: Sat, 24 Nov 2007 08:45:58 -0500 Subject: the annoying, verbose self In-Reply-To: <47475451.3050509@gmx.net> References: <3c954a31-9fb9-4c0f-b784-cef9ee057ca6@g30g2000hsb.googlegroups.com> <6f67fccf-fbec-4c75-baea-5d0277e07883@w40g2000hsb.googlegroups.com> <4745dc0b$0$3051$426a74cc@news.free.fr> <023aa14b-98b3-4e1c-8282-b3fece7e35d2@s19g2000prg.googlegroups.com> <4746D20F.6060507@sympatico.ca> <47475451.3050509@gmx.net> Message-ID: <47482B16.70500@sympatico.ca> Kay Schluehr wrote: > Colin J. Williams schrieb: >> Kay Schluehr wrote: >>> On Nov 22, 8:43 pm, Bruno Desthuilliers >>> wrote: >>>> Colin J. Williams a ?crit : >>>> >>>> >>>> >>>>> bearophileH... at lycos.com wrote: >>>>>> Alexy: >>>>>>> Sometimes I >>>>>>> avoid OO just not to deal with its verbosity. In fact, I try to >>>>>>> use >>>>>>> Ruby anywhere speed is not crucial especially for @ prefix is >>>>>>> better- >>>>>>> looking than self. >>>>>> Ruby speed will increase, don't worry, as more people will use it. >>>>>> Bye, >>>>>> bearophile >>>>> I don't see this as a big deal, but suppose that the syntax were >>>>> expanded so that, in a method, a dot ".", as a precursor to an >>>>> identifier, >>>>> was treated as "self." is currently treated? >>>> >>>> >>>> Python's "methods" are thin wrapper around functions, created at >>>> lookup >>>> time (by the __get__ method of the function type). What you define >>>> in a >>>> class statement are plain functions, period. So there's just no way to >>>> do what you're suggesting. >>>> >>>> >>> >>> The object model is irrelevant here. The substitution is purely >>> syntactical and gets resolved at compile time: >>> >>> def foo(first, ...): >>> .bar = ... >>> >>> is always equivalent with: >>> >>> def foo(first, ...): >>> first.bar = ... >>> >>> and generates the same bytecode. >>> >>> Whether this is helpfull, beautifull or necessary is another issue. >>> >>> Kay >> >> I had never thought of trying the above, which is, essentially what I >> was >> suggesting, as the syntax specifies: >> >> primary ::= >> atom | attributeref >> | subscription | slicing | call >> >> attributeref ::= >> primary "." identifier >> >> I did try it and get: >> >> # tmp.py >> class Z(): >> def __init__(self): >> a= 1 >> self.b= 2 >> #.c= 3 Marked as a syntax error by PyScripter >> >> def y(self): >> self.a= 4 >> #.b= 5 Marked as a syntax error by PyScripter >> >> It seems that some, probably simple, change in the parsing is needed. >> >> Colin W. > > Sure. Since you cite the grammar let me say that I find it somewhat > confusing that the grammar in the Python documentation doesn't > correspond to the grammar used by the CPython parser. For the following > I will use the notations of the Grammar file used by the CPython parser. > > In order to adapt the syntax take a look at > > atom: ('(' [yield_expr|testlist_gexp] ')' | > '[' [listmaker] ']' | > '{' [dictmaker] '}' | > '`' testlist1 '`' | > NAME | NUMBER | STRING+) > > The last row must be changed to > > ['.'] NAME | NUMBER | STRING+) > ~~~~~ > > But then you run into conflict with the definition of the ellipsis in > rule > > subscript: '.' '.' '.' | test | [test] ':' [test] [sliceop] > > because you need two token of lookahead. Pythons LL(1) parser might not > manage this. > > This problem vanishes with Python 3.0 which defines an own ellipsis > literal: > > atom: ('(' [yield_expr|testlist_comp] ')' | > '[' [testlist_comp] ']' | > '{' [dictorsetmaker] '}' | > NAME | NUMBER | STRING+ | '...' | 'None' | 'True' | 'False') > > Kay > Many thanks for this clarification. I hope that those beavering away on Python 3000 will give further consideration to this matter. Colin W. > > From fomcl at yahoo.com Thu Nov 22 05:03:24 2007 From: fomcl at yahoo.com (Albert-jan Roskam) Date: Thu, 22 Nov 2007 02:03:24 -0800 (PST) Subject: Zipf test in Python In-Reply-To: Message-ID: <842554.4588.qm@web32703.mail.mud.yahoo.com> Hi, I have hospital data for 5 groups of hospitals. Each group of hospitals used a different tool to register medical procedures. Since the medical procedures are probably Zipf distributed, I want to formally test whether the hospitals differ in terms of procedure-ditribution. Is there a Python module that can do that? All I could find was ZipfR, a package for R. Best wishes, Albert-Jan Cheers! Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Did you know that 87.166253% of all statistics claim a precision of results that is not justified by the method employed? [HELMUT RICHTER] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ____________________________________________________________________________________ Be a better sports nut! Let your teams follow you with Yahoo Mobile. Try it now. http://mobile.yahoo.com/sports;_ylt=At9_qDKvtAbMuh1G1SQtBI7ntAcJ From shanesclark at hotmail.com Tue Nov 20 11:17:32 2007 From: shanesclark at hotmail.com (Shane Clark) Date: Tue, 20 Nov 2007 11:17:32 -0500 Subject: Getting name of control under mouse in Windows? In-Reply-To: References: Message-ID: > From: shanesclark at hotmail.com > To: gagsl-py2 at yahoo.com.ar; python-list at python.org > Subject: RE: Getting name of control under mouse in Windows? > Date: Mon, 19 Nov 2007 17:16:13 -0500 > > > ---------------------------------------- > > To: python-list at python.org > > From: gagsl-py2 at yahoo.com.ar > > Subject: Re: Getting name of control under mouse in Windows? > > Date: Mon, 19 Nov 2007 03:33:24 -0300 > > > > En Sun, 18 Nov 2007 21:10:18 -0300, Shane Clark > > escribi?: > > > >>> From: gagsl-py2 at yahoo.com.ar > >>> > >>> En Fri, 16 Nov 2007 16:16:25 -0300, Shane Clark > >>> escribi?: > >>> > >>>> I am trying to get my python app to output the name of the control > >>>> under > >>>> the mouse each time it is clicked. Currently, I am trying to do this > >>>> with a combination of pyhook and pyAA, but pyAA gives me "pyAA.Error: > >>>> -2147417843" for almost any control in Microsoft Office apps, for > >>>> example. If it matters, I am trying to retrieve the control's name > >>>> based > >>>> on the mouse position coordinates. > >>> > >>> pywinauto does that. > >>> > >> Thanks for the response. Pywinauto is more or less incompatible with > >> Office apps so far as I can tell. According to what I have read, this is > >> because Office does not use standard Windows controls. For more info: > >> http://forums.openqa.org/message.jspa?messageID=28199 > > > > Ouch. In that case I think you won't gain much by knowing the control name > > anyway... > > > > -- > > Gabriel Genellina > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > Actually, the name of the control is all that I am after. I am working on a forensics toolkit for a professor of mine and I just want to know the name of the button that was clicked. Anyone have other suggestions? > > Shane Clark > _________________________________________________________________ > Your smile counts. The more smiles you share, the more we donate. Join in. > www.windowslive.com/smile?ocid=TXT_TAGLM_Wave2_oprsmilewlhmtagline > -- > http://mail.python.org/mailman/listinfo/python-list I got it working using comtypes. Thank you for the suggestions. Here is my code if anyone else is interested. import pythoncom, pyHook from threading import Timer from ctypes import oledll, windll, byref, POINTER from ctypes.wintypes import POINT from comtypes.client import wrap from comtypes.automation import VARIANT from comtypes import IUnknown oleacc = oledll.oleacc def AccessibleObjectFromPoint(x, y): pacc = POINTER(IUnknown)() var = VARIANT() oleacc.AccessibleObjectFromPoint(POINT(x, y), byref(pacc), byref(var)) return wrap(pacc), var.value def ShowButton(): pythoncom.CoInitialize() x,y, = GetCursorPos() pacc, value = AccessibleObjectFromPoint(x, y) print pacc.accName() def GetCursorPos(): pt = POINT() windll.user32.GetCursorPos(byref(pt)) return pt.x, pt.y def OnMouseClick(event): #pythoncom.CoInitialize() t = Timer(0.01, ShowButton) t.start() # return True to pass the event to other handlers return True if __name__ == "__main__": #pythoncom.CoInitialize() # create a hook manager hm = pyHook.HookManager() # watch for left-click events hm.MouseLeftDown = OnMouseClick # set the hook hm.HookMouse() # wait forever pythoncom.PumpMessages() -Shane Clark _________________________________________________________________ Your smile counts. The more smiles you share, the more we donate.? Join in. www.windowslive.com/smile?ocid=TXT_TAGLM_Wave2_oprsmilewlhmtagline -------------- next part -------------- An HTML attachment was scrubbed... URL: From saluk64007 at gmail.com Sat Nov 24 03:58:35 2007 From: saluk64007 at gmail.com (Patrick Mullen) Date: Sat, 24 Nov 2007 00:58:35 -0800 Subject: Catching a segfault in a Python library In-Reply-To: <4747e3b4$0$90269$14726298@news.sunsite.dk> References: <7x1wagp8vu.fsf@ruckus.brouhaha.com> <4747e3b4$0$90269$14726298@news.sunsite.dk> Message-ID: On 24 Nov 2007 08:41:24 GMT, Ayaz Ahmed Khan wrote: > Donn Ingle wrote: > > Already done, the code within PIL is causing the crash. It gets ugly and > > out of my remit. It's a freetype/Pil thing and I simply want to a way to > > catch it when it happens. > > Since a segfault ends the process, I am asking about "wrappers" around > > code > > to catch a segfault. > > > > \d > > Wouldn't it be better to narrow down to what in your code is invoking PIL > in a manner in which PIL exhibits such behaviour, and handle it within > your code? > > Just a thought! > > -- > Ayaz Ahmed Khan > > -- > http://mail.python.org/mailman/listinfo/python-list > I think the idea is, certain fonts in his collection may be corrupt, and he wants to just scan through and load them, ignoring the ones that make the program crash. The bug in this case lies with a third party and isn't something he can easily fix (although he can file reports to the third party (PIL)). This has come up for me as well with loading meshes in a 3d application. The user or someone may include a corrupt file, and it's not nice for the application to just crash when that happens, asking them if they want to debug it. I haven't really found a solution, just have tried to prevent corrupted files in the system for now. Let me know if you get this solved :) From robert.kern at gmail.com Mon Nov 5 13:29:12 2007 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 05 Nov 2007 12:29:12 -0600 Subject: Python good for data mining? In-Reply-To: <1194286739.234725.181460@d55g2000hsg.googlegroups.com> References: <1194141739.683498.206780@k79g2000hse.googlegroups.com> <1194234136.556841.246740@v3g2000hsg.googlegroups.com> <1194270693.957593.55250@19g2000hsx.googlegroups.com> <1194276582.961527.101890@57g2000hsv.googlegroups.com> <1194286739.234725.181460@d55g2000hsg.googlegroups.com> Message-ID: Jens wrote: > On 5 Nov., 16:29, Maarten wrote: >> On Nov 5, 1:51 pm, Jens wrote: > >> "Premature optimization is the root of all evil", to quote a famous >> person. And he's right, as most people working larger codes will >> confirm. > > I guess I'll have to agree with that. Still, I would like to get some > kind of indication of if it's a good idea to use NumPy from the start > of the project - for example. Yes. -- 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 arkanes at gmail.com Wed Nov 7 16:43:08 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 7 Nov 2007 15:43:08 -0600 Subject: Is pyparsing really a recursive descent parser? In-Reply-To: <9WpYi.124193$g82.92783@fe07.news.easynews.com> References: <43rXi.397547$6L.130044@fe03.news.easynews.com> <1194223837.104424.242360@o3g2000hsb.googlegroups.com> <9HoYi.50838$m72.33706@fe06.news.easynews.com> <9WpYi.124193$g82.92783@fe07.news.easynews.com> Message-ID: <4866bea60711071343o60a68badg2775f4e9babdc762@mail.gmail.com> On Nov 7, 2007 3:15 PM, Just Another Victim of the Ambient Morality wrote: > > In short, it hasn't really evovled into a user-friendly package > > yet. > > Thank you. > How is it that I seem to be the only one in the market for a correct > parser? Earley has a runtine of O(n^3) in the worst case and O(n^2) > typically. I have trouble believing that everyone else in the world has > such intense run-time requirements that they're willing to forego > correctness. Why can't I find a pyparsing-esque library with this > implementation? I'm tempted to roll my own except that it's a fairly > complicated algorithm and I don't really understand how it's any more > efficient than the naive approach... > > You have an unusual definition of correctness. Many people would say that an ambiguous grammar is a bug, not something to support. In fact, I often use pyparsing precisely in order to disambiguate (according to specific rules, which are embodied by the parser) ambiguous input, like bizarre hand-entered datetime value. From larry.bates at websafe.com Tue Nov 13 19:49:51 2007 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 13 Nov 2007 18:49:51 -0600 Subject: Equivalent of TCL's "subst" ? In-Reply-To: <1194994835.078939.112210@k79g2000hse.googlegroups.com> References: <1194994835.078939.112210@k79g2000hse.googlegroups.com> Message-ID: gamename wrote: > Hi, > > In TCL, you can do things like: > set foobar "HI!" > set x foo > set y bar > subst $$x$y > HI! > > Is there a way to do this type of evaluation in python? > > TIA, > -T > myStore={} myStore['foobar']="HI!" x='foo' y='bar' print myStore[x+y] -Larry From bignose+hates-spam at benfinney.id.au Wed Nov 28 19:04:56 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 29 Nov 2007 11:04:56 +1100 Subject: Listing subtypes References: <80700bc1-2b61-4bac-81b0-00ce4835e6ce@y5g2000hsf.googlegroups.com> Message-ID: <87ir3lsyqf.fsf@benfinney.id.au> Samuel writes: > I remember seeing an easy way to list all subtypes of a specific type > but I haven't been able to find it anymore. What I am trying to do is > this: Given a class, get a list of all classes that derive from it. > Pretty much like __mro__ but downwards rather then upwards. Any ideas? A class knows its parents; it doesn't know its children. (Or, in other words, children need to know who their parents are, but aren't required to notify their parents about anything.) To find the latter, you need to go find those children yourself and ask them whether the class you're interested in is an ancestor. Untested code:: classes = [obj for obj in globals() if type(obj) == type] ancestor = FooClass descendants = [cls for cls in classes if issubclass(cls, ancestor)] Substitute the appropriate namespace for 'globals()', and the class you're interested in for 'FooClass'. -- \ "If you can't beat them, arrange to have them beaten." -- | `\ George Carlin | _o__) | Ben Finney From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Nov 2 18:10:34 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 02 Nov 2007 23:10:34 +0100 Subject: python newbie References: <472b2b84$0$13761$6e1ede2f@read.cnntp.org> <5p0s6vFp47k9U1@mid.individual.net> <472b43f8$0$13761$6e1ede2f@read.cnntp.org> Message-ID: <5p1liqFobh43U1@mid.individual.net> Jim Hendricks wrote: > This sounds like an issue of terminology. I understand that I > don't declare variables like I would in C or Java, but that they > are implicitly declared via the first assignment. I think yes, it's an issue of terminology. As mentioned I used the terms I know from C/C++, where declaration (telling the compiler what type it is) is included in definition (allocating memory). http://en.wikipedia.org/wiki/Declaration_(computer_science) > And the define objects and bind a name to them makes no sense to > me. By "defining", I mean "tell the interpreter what it is", and "bind a name to it" is standard Python terminology for, well, assignments. > I can only assume that if I say: my_file = open( ... the "techy" > explaination is that the open function defines a file object and > binds the name my_file to it. That's what I meant. > To me, it's easier to say that the open function creates a file > object and assigns a reference to the my_file variable. This is non-standard terminology, but the concept is the same. > If my_file does not exist, it is created, if my_file does exist, > prior to the assignment, the type of my_file is checked to ensure > type safety. It isn't at all, Python has dynamic typing. If you afterwards say my_file = 42 , the things Python does are - create an int object with value 42 - unbind your file object (if there are no more names assigned to it it is free for garbage collection) - bind the name my_file to the int object > You state that globals need to be defined before you can access > them using "global", so, now the question is, how to define in the > global scope. Just write my_global = "ni" somewhere in global context above the point where the function is executed. > I guess I'm too function driven as a programmer. I have a > function which opens a file. I have a bunch of other functions > which access that opened file. Traditionally, I would declare the > file_handle var as a global, then my function which opens the file > can assign the file_handle, and all the functions that access the > file can also access the file_handle. IMHO, that's strange even for "function driven" (procedural) programming. The traditional way is: data_file = open("/path/to/file") read_data(data_file) write_stuff(data_file) data_file.close() > Since Python you do not declare variables, and from what I've read > so far, Python is type strict, I don't know how I would outside a > function create my file_var without actually opening my file > outside a function. Excuse me, why shouldn't you open that file outside of a function? If you don't like it you can also do my_file = my_file_opening_function(parameter_1, parameter_2) or the like. > What I didn't understand is that if a module is an object, then > a function is a method of the module, Not really; I'm sorry that I used the term "method" so sloppy before, it just adds to the confusion :( In Python terminology, objects aren't comprised of just fields and methods, it is much more liberal: Python objects only have "attributes". Attributes can be anything: An integer, a function, a class, a class instance, ... they are just names in the object's namespace which are bound to (= refer to) different objects. Python methods, OTOH, are specially wrapped function attributes that class objects can have. The only thing that's special about them is that if you call them from outside, they'll automatically get the class instance or class (for class methods) you called them on as first parameter. Please someone correct me if I'm wrong. > K, then that gives further argument that making a distinction > between the term function and method, or the term field and > variable is just an exercise in confusion. As you saw, there _is_ a real difference between a Python function and a Python method (this case is often referred to as "syntactic sugar"). The terms "field" and "variable" are, as explained before, uncommon in Python since there are really only attributes. Regards, Bj?rn -- BOFH excuse #307: emissions from GSM-phones From kyosohma at gmail.com Mon Nov 26 15:53:37 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 26 Nov 2007 12:53:37 -0800 (PST) Subject: gnosis XML objectify References: <21051b4a-9690-4f48-a6bd-8ae467987261@r31g2000hsg.googlegroups.com> Message-ID: <0fed8e56-baa3-40ac-8abc-3e3315aaf31f@b40g2000prf.googlegroups.com> On Nov 26, 2:33 pm, "Wang, Harry" wrote: > Full Traceback enclosed: > > Test Suite Started @ 2007-11-26 11:34:46.617000 > Traceback (most recent call last): > File "C:\UDR2\UDRxmlGateway.py", line 370, in > ParseAll() > File "C:\UDR2\UDRxmlGateway.py", line 286, in ParseAll > py_obj = gnosis.xml.objectify.XML_Objectify(InputFile).make_instance() > File "C:\python25\Lib\site-packages\gnosis\xml\objectify\_objectify.py", line 160, in make_instance > o = self.ParseFile(self._fh) > File "C:\python25\Lib\site-packages\gnosis\xml\objectify\_objectify.py", line 190, in ParseFile > self._myparser.ParseFile(file) > xml.parsers.expat.ExpatError: not well-formed (invalid token): line 68, column 0 > > Harry C. Wang > Sr. Test Engineer (Automation) > AOL Mobile > Phone 206 - 268 - 7502 > temporary e-mail: hw... at ciber.com > Personal e-mail: hcw... at comcast.net > > ________________________________ > > From: python-list-bounces+hwang=ciber.... at python.org on behalf of kyoso... at gmail.com > Sent: Mon 11/26/2007 12:19 PM > To: python-l... at python.org > Subject: Re: gnosis XML objectify > > On Nov 26, 1:46 pm, "Wang, Harry" wrote: > > > The gnosis xml libs should not be version specific, but when I try to use Python 2.5, I am getting "not well formed (invalid token)" errors. > > > Harry > > When does this happen? When you import the module? When you pass it > some xml? Do you have a full traceback? > > Mike > --http://mail.python.org/mailman/listinfo/python-list Googling the error seems to indicate that the problem may be an encoding issue. Check the following threads: http://www.mail-archive.com/kid-template-discuss at lists.sourceforge.net/msg00787.html http://article.gmane.org/gmane.comp.python.devel/90093 http://mail.python.org/pipermail/python-list/2007-July/450288.html Mike From lasses_weil at klapptsowieso.net Fri Nov 2 09:10:19 2007 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Fri, 02 Nov 2007 14:10:19 +0100 Subject: new style class In-Reply-To: <5p0kqvFopmkaU1@mid.individual.net> References: <1194002609.296417.111050@v3g2000hsg.googlegroups.com> <1194004712.691884.249570@v3g2000hsg.googlegroups.com> <5p0kqvFopmkaU1@mid.individual.net> Message-ID: <472b21bb$0$27140$9b4e6d93@newsspool1.arcor-online.net> Bjoern Schliessmann wrote: > gert wrote: >> Could not one of you just say "@staticmethod" for once damnit :) > > No, since everyone's crystal balls are in repair. > I don't even have crystal balls! /W From ptmcg at austin.rr.com Mon Nov 5 10:23:18 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 05 Nov 2007 07:23:18 -0800 Subject: pyparsing frames and tweens - take 2 In-Reply-To: References: <1194254785.718898.256060@o80g2000hse.googlegroups.com> Message-ID: <1194276198.521699.215410@o38g2000hse.googlegroups.com> Here is a first cut at processing the parsed objects, given a list of Property objects representing the frames at each '#': class Property(object): def __init__(self,**kwargs): self.__dict__.update(kwargs) def copy(self): return Property(**self.__dict__) @staticmethod def tween(prev,next,n,i): dt = 1.0/(n+1) x = prev.x + (next.x-prev.x)*dt*(i+1) y = prev.y + (next.y-prev.y)*dt*(i+1) r = prev.r + (next.r-prev.r)*dt*(i+1) g = prev.g + (next.g-prev.g)*dt*(i+1) b = prev.b + (next.b-prev.b)*dt*(i+1) a = prev.a + (next.a-prev.a)*dt*(i+1) return Property(x=x,y=y,r=r,g=g,b=b,a=a) @staticmethod def makeBlank(): return Property(x=0,y=0,r=0,g=0,b=0,a=0) def __repr__(self): return "Property(x=%(x).3f, y=%(y).3f, r=%(r).3f, g=%(g).3f, b= %(b).3f, a=%(a).3f)" % self.__dict__ def makeAllFrames(propFrameList, animationList): ret = [] propFrameIndex = 0 for animIndex,animObj in enumerate(animationList): if isinstance(animObj, Prop): ret.append( propFrameList[propFrameIndex] ) propFrameIndex += 1 if isinstance(animObj, Blank): ret.append( Property.makeBlank() ) if isinstance(animObj, CopyPrevious): ret.append( ret[-1].copy() ) if isinstance(animObj, Tween): # compute delta x,y,r,g,b,a between prev frame and next frame prev = propFrameList[propFrameIndex-1] next = propFrameList[propFrameIndex] numFrames = animObj.tweenLength print `prev`, `next` tweens = [ Property.tween(prev,next,numFrames,i) for i in range(numFrames) ] ret += tweens return ret prop1 = Property(x=10,y=10,r=1,g=1,b=1,a=0) prop2 = Property(x=20,y=10,r=0,g=0,b=1,a=1) prop3 = Property(x=10,y=100,r=1,g=1,b=1,a=1) prop4 = Property(x=100,y=200,r=1,g=1,b=1,a=1) propFrames = [ prop1, prop2, prop3, prop4 ] allFramesList = makeAllFrames( propFrames, animation.parseString("#--- #--#===_#") ) from pprint import pprint pprint( allFramesList ) Gives: [Property(x=10.000, y=10.000, r=1.000, g=1.000, b=1.000, a=0.000), Property(x=12.500, y=10.000, r=0.750, g=0.750, b=1.000, a=0.250), Property(x=15.000, y=10.000, r=0.500, g=0.500, b=1.000, a=0.500), Property(x=17.500, y=10.000, r=0.250, g=0.250, b=1.000, a=0.750), Property(x=20.000, y=10.000, r=0.000, g=0.000, b=1.000, a=1.000), Property(x=16.667, y=40.000, r=0.333, g=0.333, b=1.000, a=1.000), Property(x=13.333, y=70.000, r=0.667, g=0.667, b=1.000, a=1.000), Property(x=10.000, y=100.000, r=1.000, g=1.000, b=1.000, a=1.000), Property(x=10.000, y=100.000, r=1.000, g=1.000, b=1.000, a=1.000), Property(x=10.000, y=100.000, r=1.000, g=1.000, b=1.000, a=1.000), Property(x=10.000, y=100.000, r=1.000, g=1.000, b=1.000, a=1.000), Property(x=0.000, y=0.000, r=0.000, g=0.000, b=0.000, a=0.000), Property(x=100.000, y=200.000, r=1.000, g=1.000, b=1.000, a=1.000)] -- Paul From duncan.booth at invalid.invalid Tue Nov 13 03:46:23 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 13 Nov 2007 08:46:23 GMT Subject: Define key in nlargest() of heapq? References: <1194922587.656458.228340@e34g2000pro.googlegroups.com> Message-ID: Davy wrote: > Hi all, > > I have a dictionary with n elements, and I want to get the m(m<=n) > keys with the largest values. > > For example, I have dic that includes n=4 elements, I want m=2 keys > have the largest values) > dic = {0:4,3:1,5:2,7:8} > So, the the largest values are [8,4], so the keys are [7,0]. > > How to do this by nlargest() of heapq? I have tried > nlargest(2,dic,key), > the interpreter give out: > Traceback (most recent call last): > File "", line 1, in > NameError: name 'key' is not defined > > Best regards, > Davy > You could use the code I posted for you yesterday. See message http://groups.google.co.uk/group/comp.lang.python/browse_frm/thread/83c10e0c67e566d8/a605259c41c78fa0?lnk=gst&q=duncan+booth#a605259c41c78fa0 From bdesth.quelquechose at free.quelquepart.fr Sun Nov 4 11:10:01 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 04 Nov 2007 17:10:01 +0100 Subject: python newbie In-Reply-To: References: <472b2b84$0$13761$6e1ede2f@read.cnntp.org><5p0s6vFp47k9U1@mid.individual.net> <472b5251$0$6238$426a34cc@news.free.fr> Message-ID: <472def03$0$30484$426a74cc@news.free.fr> Hendrik van Rooyen a ?crit : > "Bruno Desthuilliers" wrote: > > >>functions are *not* methods of their module. > > > Now I am confused - if I write: > > result = foo.bar(param) > > Then if foo is a class, we probably all agree that bar is > a method of foo. We probably agree that it's an attribute of foo, and that this attribute is callable. Chances are that the object returned by the lookup is either a classmethod or a staticmethod, but not necessarily, and nothing in the above snippet can tell us - IOW, you have to either inspect foo.bar or have a look at the implementation to know what foo.bar yields. > But the same syntax would work if I had imported some > module as foo. It would also work if foo was an instance an bar a function: class Foo(object): def bar(self): print "bar", self def baaz(param): return param * 2 foo = Foo() foo.baaz = baaz result = foo.baaz(21) While we're at it, notice that modules are *not* classes. They are instances of class 'module'. > So what's the difference ? Why can't bar be called a method > of foo, Depends. If type(foo.bar) is types.MethodType yields True, then you can obviously call bar a method of foo. Else, it's a callable attribute. FWIW, if foo is a module and Bar a class defined in this module, would you call foo.Bar a method of foo ? > or is it merely a convention that classes have > methods and modules have functions? It's not a convention. Ok, time for some in-depth (even if greatly simplified) explanation. First point is that Python objects have two special attributes: __dict__ and __class__. The first stores the object's attributes, and the second a reference to the object's class (which is itself an object...). Class objects also have an __mro__ special attributes that stores the superclasses. Attributes are first looked up in the object's __dict__, then in the object's class __dict__, then in the superclasses __dict__'s. Second point : there's something in Python named the "protocol descriptor". This protocol mandates that, when an attribute lookup is performed, if 1/ the attribute belongs to a class object, and 2/ have a (callable) attribute named __get__, then this callable attribute is called with the instance (or None if the attribute is directly looked up on the class) as first argument and the class as second argument, and the lookup mechanism yields the result of this call instead of the attribute itself. Third point: function objects actually implement the descriptor protocol, in such a way that their __get__ method returns a method object - in fact, either a bound (if the attribute was looked up on the instance) or unbound instancemethod (if the attribute was looked up on the class), wrapping the class, the instance (for bound instancemethods) and the function itself. This is this method object which is responsible for fetching the instance as first argument to the function when called. There are also the classmethod and staticmethod types - used as function decorators-, which themselves implements the descriptor protocol in a somewhat different way, but I won't say more about this, since what they do should be somewhat obvious now. Now if you re-read all this carefully, you'll note that (classmethods and staticmethods set aside), the real attribute *is* a function object. It's only at lookup time that the method object is created, and only if it's an attribute of the class. You can easily check this by yourself: print Foo.bar print Foo.__dict__['bar'] So if you set a function as an attribute of a non-class object, the descriptor protocol won't be invoked, and you'll get the function object itself. Which is what happens with modules (which are instances, not types) and functions. As a last note: all this only applies to the so-called "new-style" object model introduced in Python 2.3 (IIRC). The old object model (usually refered to as 'old-style' or 'classic' classes) works somewhat differently - but with mostly similar results. > Note that I am purposely refraining from mentioning a module > that has a class that has a method. You shouldn't. Every element must be observed to solve a puzzle. And while we're at it, you also forgot to mention the methods of the class's class - since classes are themselves instances of another class !-) HTH From madsornomads at gmail.com Tue Nov 27 13:32:07 2007 From: madsornomads at gmail.com (madsornomads at gmail.com) Date: Tue, 27 Nov 2007 10:32:07 -0800 (PST) Subject: read/write to java socket in python References: <01fa2650-22cb-43de-9e47-c490e5e2d8cf@i29g2000prf.googlegroups.com> Message-ID: On Nov 27, 4:29 pm, hdante wrote: > On Nov 27, 1:08 pm, madsornom... at gmail.com wrote: > > > > > Hi all, > > > I have a problem with reading from a Java server after I have written > > to it - it just hangs. It works fine if I just write to the server and > > not try to write. I have read the HOWTO on sockets - and it states > > that there is a problem (something about flushing), but not what the > > solutions is. Nor do google. Can somebody please help? > > > A few lines down you can see the example code that sums up the > > problem. Just change the name of the Python HOST-variable. > > > Thanks > > Mads > > > This is the client in Python: > > #! /usr/bin/env python > > > import sys > > from socket import * > > [Snip - a little Python] > > > And this the server in Java: > > import java.io.*; > > import java.net.*; > > [Snip - a lot of Java] > > > } > > I don't know, but it's amazing to compare the python client with the > java server. Yes, Python is really handy :) /Mads From Afro.Systems at gmail.com Thu Nov 22 09:53:37 2007 From: Afro.Systems at gmail.com (Tzury Bar Yochay) Date: Thu, 22 Nov 2007 06:53:37 -0800 (PST) Subject: 100% CPU Usage when a tcp client is disconnected Message-ID: <2aae621c-35e7-48a5-9121-ca2446a0ee04@y43g2000hsy.googlegroups.com> The following is a code I am using for a simple tcp echo server. When I run it and then connect to it (with Telnet for example) if I shout down the telnet the CPU tops 100% of usage and saty there forever. Can one tell what am I doing wrong? #code.py import SocketServer class MyServer(SocketServer.BaseRequestHandler ): def setup(self): print self.client_address, 'connected!' self.request.send('hi ' + str(self.client_address) + '\n') def handle(self): while 1: data = self.request.recv(1024) self.request.send(data) if data.strip() == 'bye': return def finish(self): print self.client_address, 'disconnected!' self.request.send('bye ' + str(self.client_address) + '\n') #server host is a tuple ('host', port) server = SocketServer.ThreadingTCPServer(('', 50008), MyServer) server.serve_forever() From rdm at rcblue.com Wed Nov 14 00:55:48 2007 From: rdm at rcblue.com (Dick Moores) Date: Tue, 13 Nov 2007 21:55:48 -0800 Subject: mpmath puzzle Message-ID: <20071114060326.70C7C1E47A5@bag.python.org> For 1234 ** 10.9, why the wrong result from mpmath.power()? ======================================== #!/usr/bin/env python #coding=utf-8 from mpmath import * mpf.dps = 32 x = mpf(1234) y = mpf(10.9) print power(x,y) print "4.9583278648155041477415234438717e+33" # from Windows calculator """ output: 4.9583278648155166864966558721921e+33 4.9583278648155041477415234438717e+33 """ ======================================== (Code is also at ) Thanks, Dick Moores From gagsl-py2 at yahoo.com.ar Thu Nov 1 23:44:51 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 02 Nov 2007 00:44:51 -0300 Subject: Need some help... References: <1193560272.637389.315680@e34g2000pro.googlegroups.com> <47271907$1_6@news.bluewin.ch> <4729e9a8$1_4@news.bluewin.ch> <472A5D74.1050603@bigfoot.com> Message-ID: En Thu, 01 Nov 2007 20:12:52 -0300, Ricardo Ar?oz escribi?: >>>>>> def sumToOneDigit(num) : >>> if num < 10 : >>> return num >>> else : >>> return sumToOneDigit(sum(int(i) for i in str(num))) >>> def sumToOneDigit(num): return num % 9 or 9 Valid when num>=1, which is guaranteed by the OP context. -- Gabriel Genellina From invalid at example.com Tue Nov 13 05:58:04 2007 From: invalid at example.com (invalid at example.com) Date: Tue, 13 Nov 2007 10:58:04 +0000 Subject: A JEW hacker in California admits distributing malware that let him steal usernames and passwords for Paypal accounts. References: <1194732615.277219.168670@o38g2000hse.googlegroups.com> <1194890656.529348.85610@v65g2000hsc.googlegroups.com> Message-ID: You are comparing white collar criminals with Islamic terrorists who strap on explosive vests and blow themselves up inside the mosques of those who follow a slightly different version of Islam. The internet needs licensing so we can revoke yours. zionist.news at gmail.com wrote: >The Jews and Israelis the top notch WHITE COLLAR CRIMINALS, YET, they >are harassing MOSLEMS in CALIFORNIA. Do you know why ? BECAUSE ALL THE >POLITICIANS ARE IN THEIR POCKET. >Los Angeles Police Department Deputy Chief Michael P. Downing, who >heads the bureau, defended the undertaking as a way to help Muslim >communities avoid the influence of those who would radicalize Islamic >residents and advocate "violent, ideologically-based extremism." > >"We are seeking to identify at-risk communities," Downing said in an >interview Thursday evening. "We are looking for communities and >enclaves based on risk factors that are likely to become >isolated. . . . We want to know where the Pakistanis, Iranians and >Chechens are so we can reach out to those communities." >911 carried out by evil jews and mossad >Rothschilds financed APARTHEID in South Africa. They corrupted Cecil >Rhodes, the son of an anglican minister, by TEACHING him evil >techniques of apartheid. Apartheid was taught to him by the father >zionists themselves. >Was Hitler's father a bastard son of Rothschilds? Did the Salomon >Mayer von Rothschild perhaps rape Maria Anna Schicklgruber in dark so >that she could not ever claim with certainty who the real father was? >Look at his facial features, typical central asian khazar. What was >the cause of Hitler's fanatical hatred for the Jews ? From foul_ole_ron1 at yahoo.com Fri Nov 9 09:00:16 2007 From: foul_ole_ron1 at yahoo.com (Marc Oldenhof) Date: Fri, 09 Nov 2007 06:00:16 -0800 Subject: get the shape of a numpy ndarray in C++ code [boost.python] Message-ID: <1194616816.979860.281100@v23g2000prn.googlegroups.com> [sorry is half a post appeared earlier. Bloody Google groups...] Hello, I'm trying to use a numpy array in C++ (win2000) using boost.python. Test code: void test( numeric::array& nsP) { object shape = nsP.getshape(); int rows = extract(shape[0]); int cols = extract(shape[1]); } At first, running it in Python got me this message: ArgumentError: Python argument types in d3d.wr_conn(numpy.ndarray) did not match C++ signature: wr_conn(class boost::python::numeric::array {lvalue}) I fixed this using this line: numeric::array::set_module_and_type( "numpy", "ndarray"); [was that right?] At least it got me one step further; the array is accepted. Now the message is this: AttributeError: 'numpy.ndarray' object has no attribute 'getshape' Now I'm stumped. The only thing I can find is http://www.thescripts.com/forum/showthread.php?t=644270 which regrettably ends with the same question. What's wrong here? greets, Marc From ptmcg at austin.rr.com Mon Nov 5 09:38:17 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 05 Nov 2007 06:38:17 -0800 Subject: pyparsing frames and tweens - take 2 In-Reply-To: References: <1194254785.718898.256060@o80g2000hse.googlegroups.com> Message-ID: <1194273497.217575.141520@50g2000hsm.googlegroups.com> Donn - The exception you posted is from using an old version of pyparsing. You can get the latest from SourceForge - if you download the Windows binary install, please get the docs package too. It has a full doc directory (generated with epydoc), plus example scripts for a variety of applications. There is also an e-book available from O'Reilly that just came out in early October. To add an optional lead-in of one or more blanks,just change animation from: animation = OneOrMore((frame + Optional( (tween + FollowedBy(frame)) | OneOrMore(copy | blank) ) ) ) to: animation = Optional(OneOrMore(blank)) + \ OneOrMore((frame + Optional( (tween + FollowedBy(frame)) | OneOrMore(copy | blank) ) ) ) I modified your test, and there were no problems parsing strings with and without the leading '_'s. -- Paul From kyosohma at gmail.com Fri Nov 9 10:49:03 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Fri, 09 Nov 2007 15:49:03 -0000 Subject: Python Extension Building Network In-Reply-To: References: <1194617297.075298.238880@i13g2000prf.googlegroups.com> Message-ID: <1194623343.121618.65350@v3g2000hsg.googlegroups.com> On Nov 9, 8:36 am, Tim Golden wrote: > kyoso... at gmail.com wrote: > > Hi, > > > I am trying to get a small group of volunteers together to create > > Windows binaries for any Python extension developer that needs them, > > much like the package/extension builders who volunteer their time to > > create Linux RPMs. > > > The main thing I need are people willing to test the binaries to make > > sure the extension is stable. This would require installing the binary > > and probably downloading the source too to get the developer's test > > code. I've been able to get some of the tests to run great while > > others are pretty finicky and some extensions don't come with tests. > > It would be nice to know which extensions are most in need of this > > too. > > > While I can create the binaries on my own for a while, if I get too > > many requests, there will be a backlog, so it would be nice to have > > help with that too. I'm also looking for knowledgeable people to be > > sounding boards (i.e. give advice). > > > Developers: all I would require is a request, a link to the source, > > and a well-written setup.py file for a cross-platform extension. > > > You can find the few that I've already done here:http:// > >www.pythonlibrary.org/python_modules.htm > > > I have also posted a way to create the binaries using the MinGW > > compiler. I have VS2003 installed on my PC and MinGW is installed in a > > VM, so I can compile the extensions both ways. > > Mike, this is great news. Whenever I have time means it sincerely> I'll try to run through some of the modules > you've compiled. > > As a slight aside, the main problem I've found when I've tried > to build extensions (and I've been doing it recently with AVBin and > Pyglet) is that Windows just doesn't have the build environment, the > directory structures, the env vars and all that that a ./configure or > even a python setup.py install sometimes expects. eg if I were to > offer to build a MySQL extension (as someone who doesn't use MySQL > and wouldn't have the source libs installed if I did) there would > be a fair bit of pain to go through. You've obviously gone through > that pain barrier for at least some of the extensions on the modules > page. Was it tough? The hardest part was finding accurate information. Most people on the user groups have been unhelpful or sarcastic. I had better luck contacting developers directly who had already created Windows binaries. They didn't mind giving me some pointers. The directions for MinGW were usually only partially correct. So I went through the two sets of directions I found (links on the site) and mixed and matched until I got it right. There are no directions on how to use Visual Studio 2003 that I've found, just some old free edition. those directions were incompatible with VS2003. I'll post VS2003's correct usage eventually, but it's basically just installing it and then using distutils. > > TJG > > (PS SendKeys link on this page is dead:http://www.pythonlibrary.org/automation.htm) I've noticed some of the stuff I thought I uploaded seems to have gone MIA. I'll get that fixed tonight. Thanks for the bug report and offer of help. Mike From gregpinero at gmail.com Wed Nov 7 18:22:30 2007 From: gregpinero at gmail.com (gregpinero at gmail.com) Date: Wed, 07 Nov 2007 23:22:30 -0000 Subject: pydoc - generating HTML docs from string input In-Reply-To: References: <1194459359.897225.246430@o80g2000hse.googlegroups.com> Message-ID: <1194477750.696567.73630@v3g2000hsg.googlegroups.com> On Nov 7, 4:47 pm, Laszlo Nagy wrote: > gregpin... at gmail.com wrote: > > Has anyone ever tried mucking with pydoc to the point where you can > > get it to give you output from a string input? For example I'd like > > to give it a whole module to generate documentation for but all within > > a string: > > > #little sample > > > module_code=''' > > """Module docstring""" > > > def func1(): > > """ some docstring""" > > pass > > > ... > > > ''' > > > pydoc.html(module_code) -> HTML output as a string > > > Any ideas? > > The problem with this is that your module can do relative imports, and > it DOES matter where your module is located in the filesystem. > > In the very unlikely case when you store your modules in an external > system (e.g in a database), and you use __import__ hacks to run your > code, I would recommend to write a program that exports your stored > modules into a real filesystem and run pydoc there. > > Regards, > > Laszlo That's a good point. I was mainly thinking about the case of simple modules with no other imports. But looking at pydoc's code, it looks like it would be quite a bit of work to make it work at all. -Greg From fperez.net at gmail.com Tue Nov 6 19:59:17 2007 From: fperez.net at gmail.com (Fernando Perez) Date: Tue, 06 Nov 2007 17:59:17 -0700 Subject: Confused about closures and scoping rules References: <5pcergFqe0kfU1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > It's a FAQ. The reason is that the created closures don't capture the > _value_, but the _name_. Plus of course the locals()-dictionary outside > the function a to perform the lookup of that name. Which has the value > bound to it in the last iteration. > > Common cure for this is to create an a-local name that shadows the outer > variable and is simultaneously bound to the desired value: Many thanks (also to JP) for the clear explanation. Greatly appreciated. Cheers, f From borreguero at gmail.com Fri Nov 2 22:21:30 2007 From: borreguero at gmail.com (jmborr) Date: Sat, 03 Nov 2007 02:21:30 -0000 Subject: how to pass a function name and its arguments inside the arguments of other function? Message-ID: <1194056490.069739.150900@o38g2000hse.googlegroups.com> I need something like this: 1: superfoo( non-keyword-args, keyword-args, methodname, *kargs, *kwargs): 2: """non-keyword-args and keyword-args are arguments that 3: apply to superfoo, while *kargs and **kwargs are arguments 4: that apply to methodname. See below""" 5: object=someClass() 6: result=getattr(object,methodname)(*kargs,**kwargs) 7: return result The problem is: how can I pass both arguments for superfoo and methodname in line 1: ? Is it possible? -Jose From mwilson at the-wire.com Wed Nov 28 10:04:39 2007 From: mwilson at the-wire.com (Mel) Date: Wed, 28 Nov 2007 10:04:39 -0500 Subject: Unexpected behavior when initializing class References: <8763zmhiuw.fsf@rudin.co.uk> Message-ID: Paul Rudin wrote: > "alfred.fazio at gmail.com" writes: > A common paradigm to get round this - assuming you want a different > empty list each time - is something like: > > def __init__(self, v = None): > self.values = v if v else [] > > (or maybe test explicitly for None, but you get the idea.) Do test explicitly for None. Otherwise, if you do a = [] x = ThatClass (a) it will so happen that x.values will be an empty list, but it won't be the same list as a. Mel. From deets at nospam.web.de Fri Nov 30 10:00:13 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 30 Nov 2007 16:00:13 +0100 Subject: Unicode string formating In-Reply-To: <407dd33a-df20-4445-b997-bf81f70f26f5@e23g2000prf.googlegroups.com> References: <407dd33a-df20-4445-b997-bf81f70f26f5@e23g2000prf.googlegroups.com> Message-ID: <5rams4F12utjjU2@mid.uni-berlin.de> nico schrieb: > Hi, > I need to do a lot of string formating, and I have strings and/or > unicode strings and when I do the following: > "%s %s" % (u'Salut', 'H\xe4llo'), I get an exception : > UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position > 1: ordinal not in range(128) > > How can I insure I don't get an exception? By not mixing unicode and str together. Either you decode your str to become unicode objects using the proper encoding - or you encode the unicode-objects before: string = "a string" u_string = string.decode("ascii") # or whatever you need print u"%s %s" % (u'Salut', u_string) Or: salut_string = u"Salut".encode("utf-8") # whatever encoding you need print u"%s %s" % (salut_string, "foo") Diez From grante at visi.com Sat Nov 3 22:03:39 2007 From: grante at visi.com (Grant Edwards) Date: Sun, 04 Nov 2007 02:03:39 -0000 Subject: Low-overhead GUI toolkit for Linux w/o X11? References: <13ipjvic6aj8c69@corp.supernews.com> <13ipvnvoqoh735f@corp.supernews.com> <5p4jqmFog9g5U1@mid.individual.net> Message-ID: <13iqa3rbns0c975@corp.supernews.com> On 2007-11-04, Bjoern Schliessmann wrote: > Grant Edwards wrote: >> Yes, it's "modern" enough to run Linux/X11 -- horsepower-wise >> it's sort of in the PDA class of devices. wxWidgets has been >> tried, but it's pretty sluggish. Hence the search for something >> a littler lighter weight. > > Erm, wxWidgets is implemented in C++ Are you saying C++ software can't be large and slow? > and wxPython is just a wrapper. Yes, I know. If we though Python was the problem, I wouldn't be asking about other toolkits that had Python bindings. > I don't think the "sluggishness" comes from wxWidgets. wxWidgets and GTK+ are both pretty large, and X11 is huge. > PyQt and PySDL are AFAIK not much "less weight". They don't use X11. That's a _lot_ "less weight". -- From horpner at yahoo.com Thu Nov 1 12:28:00 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Thu, 01 Nov 2007 16:28:00 GMT Subject: How can I have one element list or tuple? References: <1193934100.089677.134530@22g2000hsm.googlegroups.com> Message-ID: On 2007-11-01, nico wrote: > The following example returns a string type, but I need a tuple... >>>> var = ("Hello") >>>> print type(var) > > > I need that for a method parameter. var = "hello", -- Neil Cerutti From arkanes at gmail.com Tue Nov 13 15:14:07 2007 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 13 Nov 2007 14:14:07 -0600 Subject: Override method name and original method access In-Reply-To: References: <4866bea60711121156p42e5da5cy4574db5d9eae79ce@mail.gmail.com> Message-ID: <4866bea60711131214p4d96816agdc8a56d87c11ec1e@mail.gmail.com> On Nov 13, 2007 3:00 AM, Gabriel Genellina wrote: > En Tue, 13 Nov 2007 01:45:31 -0300, Donn Ingle > escribi?: > > >> You need to be a new-style class (that is, you must inherit from > >> object) for super() to work. > > Problem is that my classes inherit already, from others I wrote. So, > > should > > I explicitly put (object) into the ones at the top? > > Changing from old-style to new-style classes may have some unintended side > effects. Extremely unlikely, though. It's very doubtful that the OP is doing anything that requires old-style classes. >You may prefer keeping your old-style classes and avoid using > super, if you don't have multiple inheritance. Just call explicitely the > base class. > It's a lot harder to change your object hierarchy to use super() after the fact than it is to do explicit superclass calling in some class that you decide to use different signatures for. The use of super() (and new style classes) should be the default implementation, and you should only move away from that with an explicit reason. Telling people not to use super when there's no reason not to doesn't help anything. > >> Other than that, you are using it > >> correctly here. > > Well, even with it seems to be calling to local > > overridden > > method. In a bit of a hurry, so can't test again right now. > > Remember that you must pass `self` explicitely. That is: > > class One: > def __init__(self): > self.stuff = [] > def add (self, stuff): > self.stuff.append(stuff) > > class Two(One): > def __init__(self, otherstuff): > One.__init__(self) > One.add(self, otherstuff) > self.unrelated = [] > def add (self, data): > self.unrelated.append(data) > > py> x = One() > py> x.add(1) > py> x.stuff > [1] > py> y = Two(2) > py> y.add(3) > py> y.stuff > [2] > py> y.unrelated > [3] > > -- > Gabriel Genellina > > > -- > http://mail.python.org/mailman/listinfo/python-list > From luojiang2 at tom.com Wed Nov 7 03:56:39 2007 From: luojiang2 at tom.com (Ginger) Date: Wed, 7 Nov 2007 16:56:39 +0800 Subject: command-line arguments in IDLE References: <1194396984.553516.158420@e34g2000pro.googlegroups.com> Message-ID: <00d101c8211c$1c8c5960$4de1a8c0@amd.com> it does have one in activepython Thanks and Regards, Ginger ----- Original Message ----- From: "Russ P." To: Sent: Wednesday, November 07, 2007 8:56 AM Subject: command-line arguments in IDLE > Is it possible to pass command-line arguments when running a program > in IDLE? The "Run" menu does not seem to provide that option. Thanks. > > > From python.list at tim.thechases.com Wed Nov 28 15:37:00 2007 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 28 Nov 2007 14:37:00 -0600 Subject: string parsing / regexp question In-Reply-To: <772cf584-1fac-46bd-bf99-678169177305@y5g2000hsf.googlegroups.com> References: <05f1f72a-c4b3-411f-b695-5c08d4b023b4@o42g2000hsc.googlegroups.com> <772cf584-1fac-46bd-bf99-678169177305@y5g2000hsf.googlegroups.com> Message-ID: <474DD16C.20406@tim.thechases.com> Paul McGuire wrote: > On Nov 28, 1:23 pm, Paul McGuire wrote: >> As Tim Grove points out, ... > > s/Grove/Chase/ > > Sorry, Tim! No problem...it's not like there aren't enough Tim's on the list as it is. :) -tkc From steve at REMOVE-THIS-cybersource.com.au Sat Nov 10 01:54:44 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 10 Nov 2007 06:54:44 -0000 Subject: Returning actual argument expression to a function call? References: <1194674580.142801.244840@57g2000hsv.googlegroups.com> Message-ID: <13jaldkc4is505b@corp.supernews.com> On Fri, 09 Nov 2007 22:03:00 -0800, Paddy wrote: > Hi, > # If I have a function definition ... > # The problem is that for my application to work, > # Python newbies would have to write lambda when they > # know they are after the result. I don't understand why you think this is the case. > Its my program > # that would require the lambda (or def), which > # is a distraction from their problem. ... > Any ideas on implementing f1 so I can do f2? I've read your post three times now, and I'm still not absolutely sure what you're trying to accomplish. I think you want something like this: You have a function f1(*args) which returns a result. You want a global flag that tells f1 to stick it's arguments in a global variable. Am I close? If so, something like this should work: # Define someplace to store the arguments. last_args = (None, None) # And a flag. capturecall = True # A decorator to wrap a function. def capture_args(func): def f(*args, **kwargs): if capturecall: global last_args last_args = (args, kwargs) return func(*args, **kwargs) f.__name__ = "capturing_" + func.__name__ return f Now you can do this: >>> def f1(x, y=3): ... return x + y ... >>> f1 = capture_args(f1) >>> f1(5) 8 >>> last_args ((5,), {}) >>> @capture_args ... def f2(x): ... return 2**x ... >>> f2(0.4+1) 2.6390158215457884 >>> last_args ((1.3999999999999999,), {}) In the second example, if you are trying to capture the expression "0.4 +1", I don't think that is possible. As far as I know, there is no way for the called function to find out how its arguments were created. I think if you need that, you need to create your own parser. -- Steven. From lesande at gmail.com Mon Nov 12 10:38:57 2007 From: lesande at gmail.com (Lee Sander) Date: Mon, 12 Nov 2007 07:38:57 -0800 Subject: regex that is equivalent to perl's syntax Message-ID: <1194881937.166971.228390@19g2000hsx.googlegroups.com> hi, does python's re library have a similar capability of the perls regular expression to search for pattern that appears a variable number of times within the lower and upper bounds given? For example, what is the python's equivalent to the following perl's search string? m/^\S{1,8}\.\S{0,3}/ which seeks to find all strings with 8 characters followed by a dot and then three more characters as in filename.txt Actually, i need to find a pattern such as ABCDXLMNO with the character X repeated 5 to 8 times. thanks lee From bborcic at gmail.com Fri Nov 16 08:50:14 2007 From: bborcic at gmail.com (Boris Borcic) Date: Fri, 16 Nov 2007 14:50:14 +0100 Subject: sorting contacts alphabetically, sorted by surname In-Reply-To: References: Message-ID: Marie Hughes wrote: > HI > > I have to write a program that contains a text file in the following format: > > Academic Position Room Ext. Email > Prof Marie Maguire Head of > School M9002 0000 lp.muire at ulioooor.ac.uk > > > And produce a output file where conatcts are sorted alphabetically- > sorted by surname. > > Has anyone any ideas. You mean "write a program" or "copy a program" ? From nospam at nospam.com Tue Nov 20 21:24:03 2007 From: nospam at nospam.com (Gilles Ganault) Date: Wed, 21 Nov 2007 03:24:03 +0100 Subject: [regex] Basic rewriting Message-ID: Hello I've been reading tutorials on regexes in Python, but I still don't get it: ======== #!/usr/bin/python #myscript.py 0123456789 import sys,re #Turn 0123456789 into 01.23.45.67.89 p = re.compile('(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)') phone = p.sub('\1.\2.\3.\4.\5',sys.argv[1]) print phone ======== => Python displays "...." instead. Any idea what I'm doing wrong? Thank you. From deets at nospam.web.de Tue Nov 13 12:22:40 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 13 Nov 2007 18:22:40 +0100 Subject: module data member? References: Message-ID: <5pu4r0Fsji73U1@mid.uni-berlin.de> Peter J. Bismuti wrote: > How do you define a "module data member" (I want to understand out how > this works before making converting to a Class)? > > Right now I'm defining variables in a module that get put into the global > namespace. Instead I want to put them in a "module global" namespace that > will be the same regardless of whether not this module is imported or run > as __main__. There is no "real" global namespace, unless you count __builtins__ - which you shouldn't :) All your defined top-level (global) module vars are local to that module. BUT there is of course one tiny probleme here, that arises when using a module as main script: then the module will be known under two distinct names, module-name & __main__. The former of course only if someone imports the module itself. The common remedy for this is this: ... # lots of code of module myself def main(): # do mainy stuff here if __name__ == "__main__": import myself myself.main() This of course won't prevent __main__ to be existant, nor running possible initialization code twice. But if the module is supposed to do some work, it will operate on the one data all the other importing modules see. You can take this one step further, using an explicit init()-function that creates global state (remember, it's only module-global). Diez From rzantow at gmail.com Sun Nov 18 10:41:38 2007 From: rzantow at gmail.com (rzed) Date: Sun, 18 Nov 2007 15:41:38 +0000 Subject: What is python????? References: <7ab5b781-3c6c-4fb5-9be1-703d5e7e73a6@s12g2000prg.googlegroups.com> Message-ID: Cope wrote in news:7ab5b781-3c6c- 4fb5-9be1-703d5e7e73a6 at s12g2000prg.googlegroups.com: > please tell me what is python.This group is so crowded. > I see nobody has chosen to answer your question seriously. I'll give you an answer, but it is probably not to the question you are asking, either. Python is not one thing. Python is the name of a computer language, which you can determine easily through Google or Wikipedia or other means. That's what comp(uter).lang(uage).python is here for, nominally. Python is also a package of programs that implement the language and create a Python runtime environment. The most common implementation is of a virtual machine that runs Python bytecodes, though other variations run Java or .NET bytecodes. And Python is also a set of packages that provide utilities and features that allow users of the packages to do useful things on their computers without unnecessary fuss and bother. Some of these utilities come with a basic Python installation (code name: "batteries included"), while others are available elsewhere, often from the Python Package Index (codename: "cheese shop"), but from other sources as well. Some people conflate these meanings of "Python", which can lead to confusion at times. Much of the crowdedness of the group has to do with discussion related to the batteries-included features and to the other packages written to run in the Python environment. Hope that helps. -- rzed From spamless.aurelien.campeas at free.fr Mon Nov 12 15:36:21 2007 From: spamless.aurelien.campeas at free.fr (=?ISO-8859-1?Q?Aur=E9lien_Camp=E9as?=) Date: Mon, 12 Nov 2007 21:36:21 +0100 Subject: Questions about remembering and caching function arguments In-Reply-To: <1194848814.147365.318930@d55g2000hsg.googlegroups.com> References: <1194848814.147365.318930@d55g2000hsg.googlegroups.com> Message-ID: <4738b945$0$5998$426a74cc@news.free.fr> thebjorn a ?crit : > On Nov 12, 1:05 am, "Anand Patil" > wrote: >> Hi all, >> >> I have two questions about a class, which we'll call MyWrapperClass, >> in a package to which I'm contributing. >> >> 1) MyWrapperClass wraps functions. Each instance has an attribute >> called 'value' and a method called 'eval', which calls the wrapped >> function. An instance D that depends on instances A, B and C can be >> created as follows: >> >> @mywrapperclass >> def D(A, B, C): >> return foo(A.value, B.value, C.value) >> >> Now that D exists, the call D.eval() will work without any arguments >> (D remembers that the arguments are A, B and C and passes their values >> to foo). What is the standard terminology for such classes, and does >> anyone know of a package that implements them in a nice way? (It's >> easy enough to roll our own, but reading about other implementations >> might give us good ideas). >> >> 2) D.eval() will frequently be called multiple times in succession >> before A.value, B.value or C.value has had the chance to change. It >> would be _extremely_ helpful to have D detect this situation and skip >> recomputation. I'm looking for the fastest safe way to do this. >> There's no restriction on what kind of object A.value, etc. are, so >> unfortunately they might be mutable. >> >> Our current solution is to have D compare A.value, B.value and C.value >> to an internal cache using the 'is' operator (and put a big warning in >> the docs about not changing 'value' attributes in-place). Not exactly >> safe, but the speed savings over comparison with '==' will be >> significant. Is this OK, bad or an abomination? >> >> Again it would be helpful to know the terminology associated with the >> behavior I'm looking for and any packages that implement it nicely. >> >> Many thanks in advance and apologies for the long post, >> Anand > > Cells (A dataflow extension to CLOS) seems like what you want: > > http://common-lisp.net/project/cells/ > > I think there was talk of a Python version a while back... > > -- bjorn > pycells : http://pycells.pdxcb.net/ but also trellis : http://peak.telecommunity.com/DevCenter/Trellis From Graham.Dumpleton at gmail.com Tue Nov 20 16:39:01 2007 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Tue, 20 Nov 2007 13:39:01 -0800 (PST) Subject: Python web frameworks References: <226020ef-3955-43e8-b1f6-2ba9ba43d45e@c29g2000hsa.googlegroups.com> <5qga2mFvuljgU1@mid.uni-berlin.de> <160f8bbc-70be-4dcb-8874-de72588c1d10@d61g2000hsa.googlegroups.com> Message-ID: On Nov 21, 2:33 am, Istvan Albert wrote: > On Nov 20, 9:42 am, "Diez B. Roggisch" wrote: > > > > 12/7. Django comes with its own little server so that you don't have > > > to set up Apache on your desktop to play with it. > > > I was rather shocked to learn that django only has this tiny server and does > > not come with a stand-alone server > > Alas it is even worse than that, the development server is single > threaded and that can be a big problem when developing sites that make > multiple simultaneous requests at the same time (say if one of those > requests stalls for some reason). It is trivial to add multi threading > via a mixin (takes about two lines of code) but it does not seem to be > a priority to do so. > > For large traffic though, Django is better than just about anything > other framework because it is built as multiprocess framework through > mod_python (rather than threaded). This only holds if actually hosted on Apache. As Django these days supports WSGI interface there is nothing to stop it being run with other hosting solutions that support WSGI. So, you could host it under paster or CherryPy WSGI servers. You could even run it under CGI if you were really desperate using a CGI-WSGI adapter. So, it isn't strictly correct to say it is as a multiprocess framework specifically for mod_python, although the developers will admit in the first instance that they didn't design the internals with multithreading in mind. That said, there aren't believed to be any multithreading issues in Django itself at this time. > So there is no global interpreter > lock, thread switching etc. Use of worker MPM (multiprocess+multithreaded) in Apache in place of prefork MPM (multiprocess+single threaded) is also still more than acceptable a solution to hosting Python web applications using either mod_python or mod_wsgi. People keep pushing this barrow about the GIL and multithreading being a huge problem, when in the context of Apache it is isn't, at least not to the degree people make out. The reason for this is that when using worker MPM it sill acts as a multi process web server even though each process is also multithreaded. Within those worker MPM child processes there is also a lot going on that doesn't involve Python code nor the GIL, for example initial request process and serving up of static files etc. Result is that the Python GIL is no impediment when using Apache on UNIX to making good use of multiple processors or cores, even when Apache worker MPM is used. For where I have talked about this before see: http://blog.dscpl.com.au/2007/09/parallel-python-discussion-and-modwsgi.html Graham From tinkerbarbet at gmail.com Mon Nov 26 17:40:45 2007 From: tinkerbarbet at gmail.com (tinkerbarbet at gmail.com) Date: Mon, 26 Nov 2007 14:40:45 -0800 (PST) Subject: Best ways of managing text encodings in source/regexes? References: <474B4858.50905@v.loewis.de> Message-ID: <98ffe42c-41f3-4fdf-8cbb-03d02493a522@i29g2000prf.googlegroups.com> On Nov 27, 12:27 am, "Martin v. L?wis" wrote: > > * When I say "# -*- coding: utf-8 -*-" and confirm my IDE is saving > > the source file as UTF-8, do I still need to prefix all the strings > > constructed in the source with u as in myStr = u"blah", even when > > those strings contain only ASCII or ISO-8859-1 chars? (It would be a > > bother for me to do this for the complete source I'm working on, where > > I rarely need chars outside the ISO-8859-1 range.) > > Depends on what you want to achieve. If you don't prefix your strings > with u, they will stay byte string objects, and won't become Unicode > strings. That should be fine for strings that are pure ASCII; for > ISO-8859-1 strings, I recommend it is safer to only use Unicode > objects to represent such strings. > > In Py3k, that will change - string literals will automatically be > Unicode objects. > > > * Will python figure it out if I use different encodings in different > > modules -- say a main source file which is "# -*- coding: utf-8 -*-" > > and an imported module which doesn't say this (for which python will > > presumably use a default encoding)? > > Yes, it will. The encoding declaration is per-module. > > > * If I want to use a Unicode char in a regex -- say an en-dash, U+2013 > > -- in an ASCII- or ISO-8859-1-encoded source file, can I say > > > myASCIIRegex = re.compile('[A-Z]') > > myUniRegex = re.compile(u'\u2013') # en-dash > > > then read the source file into a unicode string with codecs.read(), > > then expect re to match against the unicode string using either of > > those regexes if the string contains the relevant chars? Or do I need > > to do make all my regex patterns unicode strings, with u""? > > It will work fine if the regular expression restricts itself to ASCII, > and doesn't rely on any of the locale-specific character classes (such > as \w). If it's beyond ASCII, or does use such escapes, you better make > it a Unicode expression. > > I'm not actually sure what precisely the semantics is when you match > an expression compiled from a byte string against a Unicode string, > or vice versa. I believe it operates on the internal representation, > so \xf6 in a byte string expression matches with \u00f6 in a Unicode > string; it won't try to convert one into the other. > > Regards, > Martin Thanks Martin, that's a very helpful response to what I was concerned might be an overly long query. Yes, I'd read that in Py3k the distinction between byte strings and Unicode strings would disappear -- I look forward to that... Tim From sullivanz.pku at gmail.com Sat Nov 3 03:18:17 2007 From: sullivanz.pku at gmail.com (Sullivan WxPyQtKinter) Date: Sat, 03 Nov 2007 07:18:17 -0000 Subject: Can local function access local variables in main program? Message-ID: <1194074297.822435.92380@o3g2000hsb.googlegroups.com> I am confused by the following program: def f(): print x x=12345 f() result is: >>> 12345 however: def f(): print x x=0 x=12345 f() result is: Traceback (most recent call last): File "...\test.py", line 5, in ? f() File "...\test.py", line 2, in f print x UnboundLocalError: local variable 'x' referenced before assignment I am using Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)] on win32 I also tested it on python 2.5, which gives the same result. From antroy at gmail.com Thu Nov 1 05:56:35 2007 From: antroy at gmail.com (Ant) Date: Thu, 01 Nov 2007 02:56:35 -0700 Subject: permuting over nested dicts? In-Reply-To: <1193908332.223564.3040@z24g2000prh.googlegroups.com> References: <1193908332.223564.3040@z24g2000prh.googlegroups.com> Message-ID: <1193910995.935300.222010@z9g2000hsf.googlegroups.com> On Nov 1, 9:12 am, Anand wrote: ... > This code works for dictionaries of any nested level. At least up to the max recursion depth. -- Ant. From gnewsg at gmail.com Thu Nov 29 17:12:42 2007 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Thu, 29 Nov 2007 14:12:42 -0800 (PST) Subject: os.path.islink documentation error? References: <39860dba-58b3-4b6c-8700-bd6c1b3d4f60@s36g2000prg.googlegroups.com> <5r33fkF12800qU1@mid.uni-berlin.de> Message-ID: <5de8f36e-14bb-4230-a9d5-00803f53a3b2@s12g2000prg.googlegroups.com> :) You're right... My skimpy English cheated me. From ruili_gc at earthlink.net Thu Nov 29 13:56:31 2007 From: ruili_gc at earthlink.net (Rui Li) Date: Thu, 29 Nov 2007 18:56:31 -0000 Subject: only test Message-ID: <13ku2qv82ngn638@corp.supernews.com> this is a test From tjreedy at udel.edu Fri Nov 9 00:01:44 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 9 Nov 2007 00:01:44 -0500 Subject: Using python as primary language References: <1194508354.226023.232050@v3g2000hsg.googlegroups.com> <1194561005.427982.263160@s15g2000prm.googlegroups.com> <004801c8225e$49843350$dc8c99f0$@com><4866bea60711081538m2b24ab48v3d223adca8b4bd7c@mail.gmail.com> <004901c82264$3b10f460$b132dd20$@com> Message-ID: "Michael Bacarella" wrote in message news:004901c82264$3b10f460$b132dd20$@com... | > It's pretty uncommon. There are relatively few CPU bound tasks that | > are a) highly parallel and b) can't be easily scaled between | > processes. Python is not (by itself) an especially good tool for those | > tasks. | | Is there any reason for this besides economics? If by 'this' you mean the global interpreter lock, yes, there are good technical reasons. All attempts so far to remove it have resulted in an interpeter that is substantially slower on a single processor. From fabian at syameses.com Mon Nov 19 13:12:19 2007 From: fabian at syameses.com (=?ISO-8859-1?Q?Fabian_L=F3pez?=) Date: Mon, 19 Nov 2007 19:12:19 +0100 Subject: Efficient: put Content of HTML file into mysql database Message-ID: <851acc320711191012q470f252biccf2e0bec86c8c08@mail.gmail.com> Hi colegues, do you know the most efficient way to put the content of an html file into a mySQL database?Could it be this one?: 1.- I have the html document in my hard disk. 2.- Then I Open the file (maybe with fopen??) 3.- Read the content (fread or similar) 4.- Write all the content it in a SQL sentence. What happens if the html file is very big? Thanks! FAbian -------------- next part -------------- An HTML attachment was scrubbed... URL: From ihatespam at hotmail.com Sun Nov 4 16:44:32 2007 From: ihatespam at hotmail.com (Just Another Victim of the Ambient Morality) Date: Sun, 04 Nov 2007 21:44:32 GMT Subject: Is pyparsing really a recursive descent parser? References: <5p0dhgFnj4rbU1@mid.uni-berlin.de> <1194007658.200713.178210@57g2000hsv.googlegroups.com> <1194104971.263256.66640@d55g2000hsg.googlegroups.com> Message-ID: <43rXi.397547$6L.130044@fe03.news.easynews.com> "Neil Cerutti" wrote in message news:nPnXi.39845$G23.30920 at newsreading01.news.tds.net... > On 2007-11-04, Just Another Victim of the Ambient Morality > wrote: >>> Consider writing a recursive decent parser by hand to parse >>> the language '[ab]+b'. >>> >>> goal --> ab_list 'b' >>> ab_list --> 'a' list_tail >>> ab_list --> 'b' list_tail >>> list_tail --> 'a' list_tail >>> list_tail --> 'b' list_tail >>> list_tail --> null >>> >>> >>> The above has the exact same bug (and probably some others--I'm >>> sorry unable to test it just now) as the PyParsing solution. >>> >>> The error is in the grammar. It might be fixed by specifying that >>> 'b' must be followed by EOF, and then it could be coded by using >>> more than one character of lookahead. >> >> I don't exactly understand the syntax you used to describe the >> productions of your recursive descent parser so not only did I not follow >> it >> but I couldn't make out the rest of your post. Could you explain in a >> little more detail? The last part that points to 'null' is especially >> confusing... > > It's the BNF spelling of > > goal --> ab_list 'b' > ab_list --> ab { ab } > ab --> 'a' | 'b' > > The null is to say that list_tail can match nothing, i.e, an > empty string. > > Then, in the Parser class, every method (except for match, which > is used as a central place to consume characters) corresponds to > one of the productions in the BNF. Breaking things down into > BNF-based productions often makes implementation, debugging and > code generation easier. > > PyParsing saves me that stop, since I can often directly > implement the EBNF using PyParsing. Okay, I see that now, thank you. Your statement from the previous post: >> Consider writing a recursive decent parser by hand to parse >> the language '[ab]+b'. >> >> goal --> ab_list 'b' >> ab_list --> 'a' list_tail >> ab_list --> 'b' list_tail >> list_tail --> 'a' list_tail >> list_tail --> 'b' list_tail >> list_tail --> null >> >> >> The above has the exact same bug (and probably some others--I'm >> sorry unable to test it just now) as the PyParsing solution. ...merely demonstrates that this grammar is similarly ambiguous. There are many ways to parse this correctly and pyparsing chooses none of these! Instead, it returns the same error it does when the string has no solutions... >> As demonstrated earlier, it's not just the grammar. There are >> situations that are unambiguous that pyparsing can't parse >> simply and there's no reason for it. > > Yes, many parser generators have many more limitations than just > the requirement of an unambiguous grammar. Yes, but a recursive descent parser? I expect such things from LALR and others, but not only do I expect a recursive descent parser to correctly parse grammars but I expect it to even parse ambiguous ones, in that it is the only technique prepared to find more than one solution... >> Besides, ambiguous grammars are a fact of life and some of us >> need to parse them. It's usually okay, too. Consider a >> previous example: >> >> grammar = OneOrMore(Word(alphas)) + Literal('end') >> >> While you may consider this inherently ambiguous, it's usually >> not. That is to say, as long as it is rare that 'end' is used >> not at the end of the string, this will simply parse and, yet, >> pyparsing will consistently fail to parse it... > > I believe there's no cure for the confusion you're having except > for implementing a parser for your proposed grammar. > Alternatively, try implementing your grammar in one of your other > favorite parser generators. I believe there is a cure and it's called recursive descent parsing. It's slow, obviously, but it's correct and, sometimes (arguably, often), that's more important the execution speed. I spent this morning whipping up a proof of concept parser whose interface greatly resembles pyparsing but, baring unknown bugs, works and works as I'd expect a recursive descent parser to work. I don't know Python very well so the parser is pretty simple. It only lexes single characters as tokens. It only supports And, Or, Optional, OneOrMore and ZeroOrMore rules but I already think this is a rich set of rules. I'm sure others can be added. Finally, I'm not sure it's safely copying all its parameter input the same way pyparsing does but surely those bugs can be worked out. It's merely a proof of concept to demonstrate a point. Everyone, please look it over and tell me what you think. Unfortunately, my news client is kind of poor, so I can't simply cut and paste the code into here. All the tabs get turned into single spacing, so I will post this link, instead: http://theorem.ca/~dlkong/new_pyparsing.zip I hope you can all deal with .zip files. Let me know if this is a problem. Thank you... From James.w.Howard at gmail.com Mon Nov 5 14:32:24 2007 From: James.w.Howard at gmail.com (JamesHoward) Date: Mon, 05 Nov 2007 19:32:24 -0000 Subject: Thread Profiling Message-ID: <1194291144.653896.216480@d55g2000hsg.googlegroups.com> Are there any good thread profilers available that can profile a thread as it is running instead of after execution is completed? I would like to find a python class which looks at a currently running thread and if its memory exceeds a certain amount than kill it. Ideally I would like the program to track memory used not just by that thread, but by any threads or processes that it may spawn. If there isn't anything like that, then something that lets me set the maximum memory allowed to be allocated within a thread would be acceptable also. Thanks in advance, James Howard From ht at computerdefense.org Thu Nov 29 15:42:16 2007 From: ht at computerdefense.org (Tyler Reguly) Date: Thu, 29 Nov 2007 15:42:16 -0500 Subject: Outbound HTML Authentication In-Reply-To: References: Message-ID: <1f313f070711291242v564a7b68l8fe205832222f113@mail.gmail.com> Hello, You should probably read the HTTP RFC is you're going to write a screen scraper... but either way. 401 tells you that Auth is required.... there are several types of "server-based auth" (Different from form based auth)... They include - Basic - Digest - NTLM (or Negotiate) Basic is easy to implement... Digest is slightly more complex... NTLM requires that you have an understanding of how NTLM works in general. There are a couple things you can do... 1. Find a public implementation of NTLM in python (I don't believe one exists... but if it does, I'd love if someone could point it out) 2. Use the NTLM Authentication Proxy Server ( http://www.geocities.com/rozmanov/ntlm/ ) 3. Follow Ronald Tschal?r's write-up on NTLM over HTTP and implement it yourself ( http://www.innovation.ch/personal/ronald/ntlm.html ) I actually did the recently for a project that I'm working on... and looked fairly deeply at Ronald's write-up... It is fairly decent... and I may actually implement it at some point in the future as a released Python module... for now though you'll have to do it yourself. -- Tyler Reguly http://www.computerdefense.org On 11/29/07, Mudcat wrote: > > Hi, > > I was trying to do a simple web scraping tool, but the network they > use at work does some type of internal authentication before it lets > the request out of the network. As a result I'm getting the '401 - > Authentication Error' from the application. > > I know when I use a web browser or other application that it uses the > information from my Windows AD to validate my user before it accesses > a website. I'm constantly getting asked to enter in this info before I > use Firefox, and I assume that IE picks it up automatically. > > However I'm not sure how to tell the request that I'm building in my > python script to either use the info in my AD account or enter in my > user/pass automatically. > > Anyone know how to do this? > > Thanks > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From wittem at kpnplanet.nl Fri Nov 16 15:28:45 2007 From: wittem at kpnplanet.nl (martyw) Date: Fri, 16 Nov 2007 21:28:45 +0100 Subject: Sorting Countries by Region In-Reply-To: <4375355d-b23e-4a1c-8f4b-183156a163c5@f13g2000hsa.googlegroups.com> References: <4375355d-b23e-4a1c-8f4b-183156a163c5@f13g2000hsa.googlegroups.com> Message-ID: <473dfd8c$0$1898$9a622dc7@news.kpnplanet.nl> patrick.waldo at gmail.com wrote: > Hi all, > > I'm analyzing some data that has a lot of country data. What I need > to do is sort through this data and output it into an excel doc with > summary information. The countries, though, need to be sorted by > region, but the way I thought I could do it isn't quite working out. > So far I can only successfully get the data alphabetically. > > Any ideas? > > import xlrd > import pyExcelerator > > def get_countries_list(list): it isn't a good idea to use a built-in object as a variable name > countries_list=[] > for country in countries:ii > if country not in countries_list: > countries_list.append(country) > > EU = ["Austria","Belgium", "Cyprus","Czech Republic", > "Denmark","Estonia", "Finland"] > NA = ["Canada", "United States"] > AP = ["Australia", "China", "Hong Kong", "India", "Indonesia", > "Japan"] > Regions_tot = {'European Union':EU, 'North America':NA, 'Asia > Pacific':AP,} i would create a class to capture country information, e.g. class country(object): def __init__(self, name, size = 0, population = 0): self.name = name self.size = size self.poplation = population def __cmp__(self, other): if self.name < other.name: return -1 elif self.name > other.name: return 1 else: return 0 then you can set up the world as world = {'NA': [country("United States"), country("Canada")], \ 'Europe': [country("Belgium"), country("Austria")]} now you can sort and print it easy for region in world: print region lands = world[region] lands.sort() for land in lands: print land.name the sort works because the country objects have a method __cmp__ > > path_file = "c:\\1\country_data.xls" > book = xlrd.open_workbook(path_file) > Counts = book.sheet_by_index(1) > countries= Counts.col_values(0,start_rowx=1, end_rowx=None) > > get_countries_list(countries) > > wb=pyExcelerator.Workbook() > matrix = wb.add_sheet("matrix") > > n=1 > for country in unique_countries: > matrix.write(n,1, country) > n = n+1 > > wb.save('c:\\1\\matrix.xls') > > > i'm not familiar with the excel modules so i can't help you with that From python.list at tim.thechases.com Wed Nov 28 16:49:40 2007 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 28 Nov 2007 15:49:40 -0600 Subject: Bit Operations In-Reply-To: <5504f9ac0711281301g225eed41gb74abcab57e37ed1@mail.gmail.com> References: <474DCD8C.3000106@tim.thechases.com> <5504f9ac0711281301g225eed41gb74abcab57e37ed1@mail.gmail.com> Message-ID: <474DE274.7050302@tim.thechases.com> >> >>> 0xff & (((0xff & a) << 4) | (0xff & b)) >> 150 >> >> or, if you're sloppy, >> >> >>> (a << 4) | b >> 150 > > Slightly OT, maybe - why exactly is the second alternative 'sloppy?' > I believe you, because I had a problem once (in Java) with bytes not > having the value I expected unless I did the and-magic, but I wasn't > clear on why. Is it an issue with the word otherwise possibly not > being zeroed out? Whoops...extra "f"s slipped into my nibble-mask "Sloppy" lets through things like >>> a = int('11111', 2) # overflows a nibble >>> b = int('11111', 2) >>> (a<<4) | b 511 >>> 0xff & (((0xf & a) << 4) | (0xf & b)) 255 It clamps each nibble to a true nibble, and the output to a true byte. If you validate your nibbles, you could be lazy yet accurate with >>> result = ((0xf & a) << 4) | (0xf & b) >>> result 255 To get the nibbles back out of the resulting byte, one can simply >>> a = 0xf & (result >> 4) >>> b = result & 0xf -tkc From deets at nospam.web.de Tue Nov 13 06:08:53 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 13 Nov 2007 12:08:53 +0100 Subject: why there is no pythonscript insine web browsers? References: <13jimqdi6q2ea08@corp.supernews.com> <1194947509.595747.86990@d55g2000hsg.googlegroups.com> Message-ID: <5pteu5Fs1kc5U1@mid.uni-berlin.de> bramble wrote: > On Nov 13, 3:07 am, Dennis Lee Bieber wrote: >> On Mon, 12 Nov 2007 20:07:38 +0200, Timu?in K?z?lay >> declaimed the following in comp.lang.python: >> >> > python support? there is even a vbscript support inside MS-IE but there >> > is no python support. it would be really nice and easy for me to use >> > python instead of javascript to write those ajax scripts. >> >> Javascript is meant to, basically, control the browser and the >> contents of HTML pages sent to it. [snip] Python can not >> be safely sand-boxed (and the early restricted mode modules have been >> removed for that reason). >> > > Why can't it be safely sandboxed? > > That is, why not just have a Python interpreter and some safe subset > of the Python standard library run with the browser? I mean, aside > from the work involved with combing out the unneeded or dangerous > parts of the standard lib, it seems like it would be much nicer to > just use Python syntax and modules rather than having to fool around > with Javascript. The problem is that building such an environment would mean building it up from scratch instead of trying to secure the existing one - wich quite a few people tried, and failed. So it's more than "just" creating a sandbox, it's keeping track with CPython's language features and lib-advances as well. There are two projects I aware of that might help, IronPython & Jython. The latter had some hard times getting up to python 2.2 (important for the new style classes support), but now it's finished in that respect so hopefully we will see more frequent releases of it, with newer python version support. And all this still doesn't tackle the fact that at least one, not to say THE browser vendor won't adopt python just for the fun of it - they even don't taclke the flaws of the existing product. Diez From besturk at gmail.com Fri Nov 2 09:51:58 2007 From: besturk at gmail.com (Abandoned) Date: Fri, 02 Nov 2007 06:51:58 -0700 Subject: Copy database with python.. Message-ID: <1194011518.553434.278940@o3g2000hsb.googlegroups.com> Hi. I want to copy my database but python give me error when i use this command. cursor.execute("pg_dump mydata > old.dump") What is the problem ? And how can i copy the database with python ? Note: The database's size is 200 GB From fredrik.johansson at gmail.com Sun Nov 18 20:33:07 2007 From: fredrik.johansson at gmail.com (Fredrik Johansson) Date: Mon, 19 Nov 2007 02:33:07 +0100 Subject: Help with sympy, please In-Reply-To: <20071119012410.DBDA01E4005@bag.python.org> References: <13k1jg03l3cgdef@corp.supernews.com> <20071119001219.5B7111E4021@bag.python.org> <3d0cebfb0711181626u432dbdd3je049093f5343b716@mail.gmail.com> <20071119012410.DBDA01E4005@bag.python.org> Message-ID: <3d0cebfb0711181733m5458bd5cic89ac1f45b108a31@mail.gmail.com> On Nov 19, 2007 2:23 AM, Dick Moores wrote: > OK, I tried mpmath again, and to my surprise, it went well! > > =================================== > #!/usr/bin/env python > #coding=utf-8 > from mpmath import * > mpf.dps = 50 > n = 1 > k = 0 > prod = mpf(1) > while k < 100000: > k += 1 > term = exp(1.0/n)/exp(1.0/(n+1)) > prod *= term > n += 2 > print prod, term > ====================================== > Output: > 1.9999950000187499635016028080844735182389158683797 > 1.0000000000250001250004074790133889386806610626172 You're getting slightly wrong results, though, because 1.0/n and 1.0/(n+1) just performs regular float division with ~16-digit precision when n is a Python int. You should convert either 1.0 or n to an mpf before dividing. Fredrik From bedouglas at earthlink.net Tue Nov 6 21:25:32 2007 From: bedouglas at earthlink.net (bruce) Date: Tue, 6 Nov 2007 18:25:32 -0800 Subject: Parallel Python environments.. In-Reply-To: Message-ID: <118c01c820e5$78e17420$0301a8c0@tmesa.com> hi gabriel... i have my reasons, for some testing that i'm doing on a project. that said, i'm still trying to figure out how to make this occur... 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 Gabriel Genellina Sent: Tuesday, November 06, 2007 2:07 PM To: python-list at python.org Subject: Re: Parallel Python environments.. En Tue, 06 Nov 2007 18:43:10 -0300, bruce escribi?: > if i have python 2.4.3 installed, it gets placed in the python2.4 dir.. > if i > don't do anything different, and install python 2.4.2, it too will get > placed in the python2.4 tree... which is not what i want. Any reason you want to keep 2.4.2 *and* 2.4.3 separate? The latter is only a bugfix over the 2.4 version - anything working on 2.4.2 should work on 2.4.3. And 2.4.4, the latest bugfix on that series. Binaries, shared libraries, extensions, etc. targetted to 2.4x should work with 2.4.4 You may want to have separate directories for 2.4 and 2.5, yes; binaries, shared libraries and extensions do NOT work across versions changing the SECOND digit. But changes on the THIRD digit should not have compatibility problems. -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list From kaaveland at gmail.com Mon Nov 26 21:48:30 2007 From: kaaveland at gmail.com (=?iso-8859-1?q?Robin_K=E5veland?= Hansen) Date: Tue, 27 Nov 2007 02:48:30 +0000 (UTC) Subject: Installing Python 3000 on Leopard (Mac OS) fails... References: Message-ID: "=?ISO-8859-1?Q?Andr=E9?=" wrote (Mon, 26 Nov 2007 17:59:21 -0800): > While I made some progress in trying to install Py3k from source (for > the first time), it has failed... > > Here are the steps I went through (not necessarily in that order - > except for those that matter). > > 1. After installing Leopard, install Xcode tools from the dvd - even > if you had done so with a previous version (they need to be updated - > trust me :-) > > 2. Download Python 3.0a1 > > 3. Unpack the archive. > > 4. Go to /usr/local and make a directory "sudo mkdir py3k" (This is > probably not needed, but that's what I did). > > 5. From the directory where the Python 3.0a1 was unpacked run > ./configure --prefix=/usr/local/py3k > > 6. run "make" > > This last step failed with the following error message: > > gcc -fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno-fused- > madd -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include - > DPy_BUILD_CORE -c ./Modules/posixmodule.c -o Modules/posixmodule.o > ./Modules/posixmodule.c: In function 'posix_setpgrp': > ./Modules/posixmodule.c:3769: error: too few arguments to function > 'setpgrp' > make: *** [Modules/posixmodule.o] Error 1 > > Any suggestions? > > Andr? The posix-man-page on setpgrp declares the setpgrp prototype as pid_t setpgrp(void);, which makes this sort of weird I guess. You could check if it worked to change the relevant function call from setpgrp() to setpgrp(0, 0)? Just search for posix_setpgrp, and make sure that the function isn't called with an empty argument list. Though I believe this is something for the core python developers and not for me to fix, or even advice in, so if you want to be on the safe side to ensure no breakage, don't touch it on my advice. -- regards, Robin From robert.kern at gmail.com Mon Nov 26 05:34:17 2007 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 26 Nov 2007 04:34:17 -0600 Subject: Installing modules via setuptools in a script In-Reply-To: References: <5qqnq8F11ghnqU1@mid.individual.net> Message-ID: Thorsten Kampe wrote: > * Robert Kern (Sat, 24 Nov 2007 16:33:37 -0600) >> Thorsten Kampe wrote: >>> can anyone give me a short code snippet how to install a missing >>> module via setuptools (assuming setuptools is already installed)?! >>> >>> Something like this: >>> >>> try: >>> import missing_module >>> except import_error >>> import setuptools >>> setuptools.whatever.install(missing_module) >> The recommended way to handle dependencies using setuptools is to specify them >> in the install_requires metadata in the setup() function call in your setup.py: > > It's just a simple script - no package. So I don't even have a > setup.py. > >> However, if you have special needs that really do require downloading the >> dependency at runtime instead of install-time: >> >> # >> http://peak.telecommunity.com/DevCenter/PkgResources#workingset-methods-and-attributes >> >> import pkg_resources >> pkg_resources.resolve('some_package >= 1.0') >> pkg_resources.resolve('another_package') >> >> import some_package >> import another_package > > [5]>>> pkg_resources.working_set.resolve('betterprint') > ---------------------------------------------------------------------- > ----- > AttributeError Traceback (most recent call > last) > > F:\program files\python\ in () > > F:\program files\python\lib\site-packages\setuptools-0.6c5-py2.5.egg > \pkg_resou > rces.py in resolve(self= 0x01457710>, requi > rements=['n', 'i', 'r', 'p', 'r', 'e', 't', 't', 'e', 'b'], env=None, > installe > r=None) > 472 # Ignore cyclic or redundant dependencies > 473 continue > --> 474 dist = best.get(req.key) > dist = undefined > best.get = > req.key = undefined > 475 if dist is None: > 476 # Find the best distribution and add it to the > map > > AttributeError: 'str' object has no attribute 'key' My apologies for misleading you. There is no easy way to do this. Here is a roundabout way which might be suitable for a throwaway hack script. If it's not a throwaway hack script, then please heed Ben's advice. Alternatively, just distribute betterprint along with your script and save yourself the headache. In [1]: import betterprint --------------------------------------------------------------------------- ImportError Traceback (most recent call last) /Users/rkern/ in () ImportError: No module named betterprint In [2]: import pkg_resources In [3]: from setuptools.dist import Distribution In [4]: pkg_resources.working_set.resolve(pkg_resources.parse_requirements('betterprint'), installer=Distribution().fetch_build_egg) zip_safe flag not set; analyzing archive contents... Installed /Users/rkern/betterprint-0.1-py2.5.egg Out[4]: [betterprint 0.1 (/Users/rkern/betterprint-0.1-py2.5.egg)] -- 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 gandalf at shopzeus.com Thu Nov 15 06:19:10 2007 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Thu, 15 Nov 2007 12:19:10 +0100 Subject: Volume id In-Reply-To: References: Message-ID: <473C2B2E.8060705@shopzeus.com> Gabor Urban wrote: > Hi, > > I have a problem, which may be trivial, but I could not find an answer. > > I have to write a Python script, which does a directory tree walking > on given mounted disk. But I do need to extract the volume id, > somehow. And that's the problem. An additional issue, the script will > be used on unix type systems, and on MS XP or Vista, too.... > > Any ideas are wellcome. I believe (although not 100% sure) that "volume id" always belongs to a FAT partition (maybe an NTFS partition?). When you format a partition, it will give you a - hopefully unique - volume identifier. I don't think that unix partitions (like reiserfs, ext2, ext3, ufs2 etc.) has that identifier. I may be wrong, others will probably correct me. Do you want to know the identifier (serial number?) of the disk device instead? E.g. not the partition but the hard disk? Can you list the platforms/operating systems where you want to use your program? It might help to look at the documentation/source code or the various hardware diagnostic utilities. Best, Laszlo From danfolkes at gmail.com Wed Nov 28 12:54:19 2007 From: danfolkes at gmail.com (Daniel Folkes) Date: Wed, 28 Nov 2007 09:54:19 -0800 (PST) Subject: Python Nmap script linux version Message-ID: I made this script for fun. you need to have Nmap installed on your linux computer and it will find all the computers on the network and then run Nmap on it. Hope you enjoy! import os fn = 'i.result' ip = '192.168.1.1-255' ip1 = ip[:3] ips = [] os.system("nmap -sP 192.168.1.1-255 > "+fn) f = open(fn) try: for line in f: if ip1 in line: ips.append(line[5:-19]) finally: f.close() os.system("clear") for i in ips: print '=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=' os.system("nmap "+i) print '=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=' raw_input('press to continue...') Tell me what you think.... From hdante at gmail.com Fri Nov 23 19:56:24 2007 From: hdante at gmail.com (hdante at gmail.com) Date: Fri, 23 Nov 2007 16:56:24 -0800 (PST) Subject: the annoying, verbose self References: <3c954a31-9fb9-4c0f-b784-cef9ee057ca6@g30g2000hsb.googlegroups.com> Message-ID: <4068d518-cba9-4eac-bd91-11f676c17b3d@w34g2000hsg.googlegroups.com> Hi, Python uses "self" (and textual notation when possible) because its designers consider that symbols reduce readability. Self won't go away. :-P The issue is related to the first and seventh lines in The Zen of Python, 1. "Beautiful is better than ugly" 7. "Readability counts." My opinion is that "self" is a minor issue in python that we can all live with. On Nov 21, 9:51 pm, braver wrote: > Is there any trick to get rid of having to type the annoying, > character-eating "self." prefix everywhere in a class? Sometimes I > avoid OO just not to deal with its verbosity. In fact, I try to use > Ruby anywhere speed is not crucial especially for @ prefix is better- > looking than self. > > But things grow -- is there any metaprogramming tricks or whatnot we > can throw on the self? > > Cheers, > Alexy From ironfroggy at gmail.com Fri Nov 30 09:10:51 2007 From: ironfroggy at gmail.com (Calvin Spealman) Date: Fri, 30 Nov 2007 09:10:51 -0500 Subject: Can't Find Headers on OSX Message-ID: <76fd5acf0711300610i257c5b4br7235a648acac5eb7@mail.gmail.com> I'm still on 10.4 and I'm trying to build pyOpenSSL, but I'm failing with Python.h trying to include and failing to find any of the shared libraries. I can't figure this one out because i just don't compile anything non trivial often. ironfroggy:~/Desktop/pyOpenSSL-0.6 ironfroggy$ python setup.py build running build running build_py running build_ext building 'OpenSSL.crypto' extension gcc -arch ppc -arch i386 -isysroot /Developer/SDKs/MacOSX10.4u.sdk -fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno-fused-madd -fno-common -dynamic -DNDEBUG -g -O3 -I/sw/include -I/Library/Frameworks/Python.framework/Versions/2.4/include/python2.4 -c src/crypto/crypto.c -o build/temp.macosx-10.4-fat-2.4/src/crypto/crypto.o In file included from src/crypto/crypto.c:11: /Library/Frameworks/Python.framework/Versions/2.4/include/python2.4/Python.h:18:20: error: limits.h: No such file or directory /Library/Frameworks/Python.framework/Versions/2.4/include/python2.4/Python.h:21:2: error: #error "Something's broken. UCHAR_MAX should be defined in limits.h." /Library/Frameworks/Python.framework/Versions/2.4/include/python2.4/Python.h:25:2: error: #error "Python's source code assumes C's unsigned char is an 8-bit type." /Library/Frameworks/Python.framework/Versions/2.4/include/python2.4/Python.h:32:19: error: stdio.h: No such file or directory /Library/Frameworks/Python.framework/Versions/2.4/include/python2.4/Python.h:34:5: error: #error "Python.h requires that stdio.h define NULL." /Library/Frameworks/Python.framework/Versions/2.4/include/python2.4/Python.h:37:20: error: string.h: No such file or directory /Library/Frameworks/Python.framework/Versions/2.4/include/python2.4/Python.h:38:19: error: errno.h: No such file or directory /Library/Frameworks/Python.framework/Versions/2.4/include/python2.4/Python.h:39:20: error: stdlib.h: No such file or directory /Library/Frameworks/Python.framework/Versions/2.4/include/python2.4/Python.h:41:20: error: unistd.h: No such file or directory /Library/Frameworks/Python.framework/Versions/2.4/include/python2.4/Python.h:53:20: error: assert.h: No such file or directory In file included from src/crypto/crypto.c:11In file included from /Library/Frameworks/Python.framework/Versions/2.4/include/python2.4/Python.h:55, from src/crypto/crypto.c:11: /Library/Frameworks/Python.framework/Versions/2.4/include/python2.4/pyport.h:7:20: error: : ... -- Read my blog! I depend on your acceptance of my opinion! I am interesting! http://ironfroggy-code.blogspot.com/ From carsten at uniqsys.com Fri Nov 2 10:06:40 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 02 Nov 2007 10:06:40 -0400 Subject: Copy database with python.. In-Reply-To: <1194011518.553434.278940@o3g2000hsb.googlegroups.com> References: <1194011518.553434.278940@o3g2000hsb.googlegroups.com> Message-ID: <1194012400.3450.7.camel@dot.uniqsys.com> On Fri, 2007-11-02 at 06:51 -0700, Abandoned wrote: > Hi. > I want to copy my database but python give me error when i use this > command. > cursor.execute("pg_dump mydata > old.dump") cursor.execute executes SQL queries. pg_dump is not an SQL query, it is an operating system command. To execute OS commands, use os.system("...") or the subprocess module. Hope this helps, -- Carsten Haese http://informixdb.sourceforge.net From chiendarret at yahoo.com Thu Nov 29 11:07:46 2007 From: chiendarret at yahoo.com (Francesco Pietra) Date: Thu, 29 Nov 2007 08:07:46 -0800 (PST) Subject: Science list In-Reply-To: <474ed805$0$239$e4fe514c@news.xs4all.nl> Message-ID: <923629.52641.qm@web57609.mail.re1.yahoo.com> Do you know if "free" yahoo.com allows threaded view for python only? I was unable to set that. This also means that there are mailing lists I am interested to view all that is going on (which is two orders less that python), so that i can't sett threated viw for all mailing lists. f. --- nmp
wrote: > Bjoern Schliessmann wrote: > > > Francesco Pietra wrote: > >> Nonetheless, this extremely useful list is so crowded that if checking > >> email is not carried out every few hours, it is difficult to detect > >> other messages in the plethora of pythons and spams arrived. > > > > Why don't you use a newsreader to access comp.lang.python? It's suited > > much better for tracking long and many threads. > > Or switch to threaded view in your mail program, most mailers can do it > nowadays. > -- > http://mail.python.org/mailman/listinfo/python-list > ____________________________________________________________________________________ Get easy, one-click access to your favorites. Make Yahoo! your homepage. http://www.yahoo.com/r/hs From devnew at gmail.com Mon Nov 12 00:03:33 2007 From: devnew at gmail.com (devnew at gmail.com) Date: Sun, 11 Nov 2007 21:03:33 -0800 Subject: how to know if folder contents have changed Message-ID: <1194843813.901372.246490@k35g2000prh.googlegroups.com> hi i am trying to create a cache of digitized values of around 100 image files in a folder..In my program i would like to know from time to time if a new image has been added or removed from the folder.. one scheme suggested was to create a string from the names of sorted image files and give it as the cache name.. ie ,if i have one.jpg,three.jpg,new.jpg , i will name the cache as 'newonethree.cache' and everytime i want to check if new image added/removed i wd create a string from the contents of folder and compare it with cachename. this scheme is ok for a small number of files,.. can someone suggest a better way? i know it is a general programming problem..but i wish to know if a python solution exists From davisn90210 at gmail.com Tue Nov 27 19:14:58 2007 From: davisn90210 at gmail.com (davisn90210 at gmail.com) Date: Tue, 27 Nov 2007 16:14:58 -0800 (PST) Subject: [RFC] PyMultimethods Message-ID: I've written a small project that implements multimethods for python. I'd like anyone who's interested to check out the code and give me some feedback, such as what features they would like to see added, what could be improved, etc. This is actually one of my first projects I did with python. I did do quite a bit of refactoring from its original form, but if you have suggestions on what could be made more "pythonic", I'd like to hear them. Documentation is a bit lacking at this point, but there is a "Getting Started" page, as well as the beginnings of a tutorial. That's probably your best bet for learning basic usage. Homepage: http://pymultimethods.wiki.sourceforge.net SourceForge Project: http://sourceforge.net/projects/pymultimethods/ There is no official "release" yet, so you will have to checkout the code from the subversion repository using the following command: svn co https://pymultimethods.svn.sourceforge.net/svnroot/pymultimethods/trunk pymultimethods Alternatively, you may browse the repository at http://pymultimethods.svn.sourceforge.net/viewvc/pymultimethods/ Thank you for your comments, --Nathan Davis From salgerman at gmail.com Tue Nov 27 05:42:18 2007 From: salgerman at gmail.com (gsal) Date: Tue, 27 Nov 2007 02:42:18 -0800 (PST) Subject: Find & Replace hyperlinks in a string References: Message-ID: <87da6e3f-929f-46e1-8070-59ac4e71032c@d4g2000prg.googlegroups.com> You mean in Python? 'cause if it is a one time shot kind of thing, I would simply open the file in my favorite editor (NEdit) and use a Search and Replace, check the regexp box and type my expression...something along the lines of ([^:]+)://([^:/]+)(: ([0-9]+))?(/.*) to find URLs and then replace with \0 ...if I remember correctly that \0 is the entire match, \1 the first parenthesised match, etc. gsal From deets at nospam.web.de Tue Nov 13 10:02:11 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 13 Nov 2007 16:02:11 +0100 Subject: os walk() and threads problems (os.walk are thread safe?) References: Message-ID: <5ptsjjFsvk9kU1@mid.uni-berlin.de> Marcus Alves Grando wrote: > Hello list, > > I have a strange problem with os.walk and threads in python script. I > have one script that create some threads and consume Queue. For every > value in Queue this script run os.walk() and printing root dir. But if i > increase number of threads the result are inconsistent compared with one > thread. > > For example, run this code plus sort with one thread and after run again > with ten threads and see diff(1). I don't see any difference. I ran it with 1 and 10 workers + sorted the output. No diff whatsoever. And I don't know what you mean by diff(1) - was that supposed to be some output? Diez From mnordhoff at mattnordhoff.com Wed Nov 21 06:44:35 2007 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Wed, 21 Nov 2007 06:44:35 -0500 Subject: sorting a list of list In-Reply-To: <47439030.2050407@tim.thechases.com> References: <1d1d0685-08d2-45ec-b721-e73c1dfea2f4@e25g2000prg.googlegroups.com> <47439030.2050407@tim.thechases.com> Message-ID: <47441A23.1090709@mattnordhoff.com> Tim Chase wrote: >> are there available library or pythonic algorithm for sorting a list >> of list depending on the index of the list inside the list of my >> choice? > > The built-in sorted() function and the sort() method on various > collections take an optional "key=function" keyword paramater > with which you can pass a function (lambdas are convenient) to > extract the bit on which you want to compare: > >>>> d_list = [ > ... ['a', 1, 9], > ... ['b', 2, 8], > ... ['c', 3, 7], > ... ['d', 4, 6], > ... ['e', 5, 5], > ... ] >>>> print sorted.__doc__ > sorted(iterable, cmp=None, key=None, reverse=False) --> new > sorted list >>>> sorted(d_list, key=lambda x: x[2]) # sort by the 3rd item > [['e', 5, 5], ['d', 4, 6], ['c', 3, 7], ['b', 2, 8], ['a', 1, 9]] >>>> sorted(d_list, key=lambda x: x[1]) # sort by the 2nd item > [['a', 1, 9], ['b', 2, 8], ['c', 3, 7], ['d', 4, 6], ['e', 5, 5]] >>>> sorted(d_list, key=lambda x: x[0]) # sort by the 1st item > [['a', 1, 9], ['b', 2, 8], ['c', 3, 7], ['d', 4, 6], ['e', 5, 5]] Not to be too complicated, but there are functions that return a callable that is faster than a lambda. >>> import operator Then, instead of "lambda x: x[2]" use "operator.itemgetter(2)" and instead of "lambda x: x.foo" use "operator.attrgetter('foo')". -- From usenet at solar-empire.de Sat Nov 17 08:39:39 2007 From: usenet at solar-empire.de (Marc Christiansen) Date: Sat, 17 Nov 2007 14:39:39 +0100 Subject: class='something' as kwarg References: Message-ID: Vladimir Rusinov wrote: > I'm using beautiful soup html parser, and I need to get all '
class=g>...
' tags. > It can be done by: > > import BeautifulSoup as BSoup from BeautifulSoup import BeautifulSoup as BSoup > > ... > > soup = BSoup(page) > for div in soup.findAll('div', class='g'): for div in soup.findAll('div', attrs={'class':'g'}): > > > But how can I use `class` as kwarg name? You can't. But you can use the attrs argument (see above). HTH Marc From nytrokiss at gmail.com Mon Nov 5 18:41:09 2007 From: nytrokiss at gmail.com (James Matthews) Date: Tue, 6 Nov 2007 00:41:09 +0100 Subject: Thread Profiling In-Reply-To: <4866bea60711051509rac0104m9774fbcfdaea92fd@mail.gmail.com> References: <1194291144.653896.216480@d55g2000hsg.googlegroups.com> <4866bea60711051509rac0104m9774fbcfdaea92fd@mail.gmail.com> Message-ID: <8a6b8e350711051541o19b1c144ic0f9a46d120a116b@mail.gmail.com> Try passing the verbose=1 flag when creating the tread! On 11/6/07, Chris Mellon wrote: > > On Nov 5, 2007 1:32 PM, JamesHoward wrote: > > Are there any good thread profilers available that can profile a > > thread as it is running instead of after execution is completed? > > > > I would like to find a python class which looks at a currently running > > thread and if its memory exceeds a certain amount than kill it. > > Killing a non-cooperative thread is undefined behavior. You can't do > it with the Python threading API and even OS thread implementations > that permit it don't guarantee that your process will be in a sane > state afterward. > > > Ideally I would like the program to track memory used not just by that > > thread, but by any threads or processes that it may spawn. > > > > If there isn't anything like that, then something that lets me set the > > maximum memory allowed to be allocated within a thread would be > > acceptable also. > > > > Memory isn't allocated on a per-thread basis and there's not really > any way to know what should be charged to a particular thread. That's > on top of the normal caveats about trying to judge memory usage within > Python > > > > Thanks in advance, > > James Howard > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.goldwatches.com/ http://www.jewelerslounge.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Tue Nov 27 12:49:19 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 27 Nov 2007 18:49:19 +0100 Subject: Unsupported operator for Decimal: + (or -) In-Reply-To: References: Message-ID: <5r33l3F12800qU2@mid.uni-berlin.de> Todd O'Bryan schrieb: > This seems to have come up earlier... > > http://mail.python.org/pipermail/python-list/2007-July/451187.html > > but no resolution. > > We're seeing the same thing. We're using Django's DecimalField type > and when we try to add or subtract values--which should be > decimal.Decimal objects--we occasionally get an error about the > operator not being supported. It doesn't always happen and we can't > seem to reproduce it when we try to. Try putting an try/except clause around the problem that drops into the debugger: try: foo = a - b except TypeError: import pdb; pdb.set_trace() Then you can see what a & b _really_ are. Diez From deets at nospam.web.de Wed Nov 14 05:01:40 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 14 Nov 2007 11:01:40 +0100 Subject: Using Python To Change The World :) References: <1195009751.327435.182540@i13g2000prf.googlegroups.com> Message-ID: <5pvvc4FtkgvgU1@mid.uni-berlin.de> dominiquevalentine at gmail.com wrote: > Hello, I'm a teen trying to do my part in improving the world, and me > and my pal came up with some concepts to improve the transportation > system. > > I have googled up and down for examples of using python to create a > city street but I can not find any. > > my objective is to replicate a section of los angeles using python, > and program the street lights and cars and whatnot. Should I be > looking towards 3D to do this? > > so here is MY question: > how would you replicate a street intersection in python? and > furthermore, how would you do you have the cars move up and down those > "streets". > > my question to YOU is: > can you point me in the right direction? I will search on my own, but > I would greatly appreciate any help :) > > and if anyone is interested in learning more about this project (we've > got some nifty things planned), or if you wanna help, give a shout ;] It's hard to tell you what to do with so sparse information about what you try to accomplish in the end. Of course if you want to have more or less realistic imaging for whatever purpose, 3D is the way to go. If you are after traffic-simulations, it's unneeded complexity. Regarding the "moving cars": you can also go from simply defining paths cars can take and parametrize these to full-blown physics - depending on what you want. Diez From bdesth.quelquechose at free.quelquepart.fr Sun Nov 4 11:14:45 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 04 Nov 2007 17:14:45 +0100 Subject: python newbie In-Reply-To: <5p341jFp4918U3@mid.individual.net> References: <472b2b84$0$13761$6e1ede2f@read.cnntp.org><5p0s6vFp47k9U1@mid.individual.net> <472b5251$0$6238$426a34cc@news.free.fr> <5p341jFp4918U3@mid.individual.net> Message-ID: <472df01f$0$30484$426a74cc@news.free.fr> Bjoern Schliessmann a ?crit : > Hendrik van Rooyen wrote: > > >>So what's the difference ? Why can't bar be called a method >>of foo, or is it merely a convention that classes have >>methods and modules have functions? > > > In depends on which terminology you use. As Steven told, Python > methods are special functions. Nope. They are callable objects wrapping a function, a class and (usually) an instance of the class. From musiccomposition at gmail.com Thu Nov 29 19:55:00 2007 From: musiccomposition at gmail.com (Benjamin) Date: Thu, 29 Nov 2007 16:55:00 -0800 (PST) Subject: Bundling Python on Mac References: <5r7bstF135rvoU1@mid.uni-berlin.de> Message-ID: On Nov 29, 2:34 am, "Diez B. Roggisch" wrote: > Benjamin schrieb: > > > Hello, I'm writing a Python/PyQt application. For my Mac distribution. > > I would like to include all the needed libraries in the Mac bundle. > > How should I go about doing this? > > The py2app distutils extension should do that for you. It works flawless > for PyObjc-apps for me - it _should_ do so for Qt as well, but I have to > admit that it sometimes had errors related to Qt when creating bundles - > so maybe you need to tweak the support a bit. Does it bundle the Python library with it, so there are no (excepting system) dependencies? > > Diez From gandalf at shopzeus.com Wed Nov 28 14:43:28 2007 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Wed, 28 Nov 2007 20:43:28 +0100 Subject: Control mouse position and clicking In-Reply-To: <0b474190-7527-4946-884b-b8c8d4ed246e@i12g2000prf.googlegroups.com> References: <4f209559-4454-4f8a-8ba3-18cbb50db094@b40g2000prf.googlegroups.com> <0b474190-7527-4946-884b-b8c8d4ed246e@i12g2000prf.googlegroups.com> Message-ID: <474DC4E0.2070000@shopzeus.com> Paul McGuire wrote: > On Nov 28, 1:29 pm, Glich wrote: > >> hi, how can I, control mouse position and clicking from python? >> >> I want to interact with a flash application inside firefox. thanks. >> >> ps: I am not using windows. >> > > Ooof, I was about to suggest using pywinauto, because I was able to > interact with a flash app with that module, until I saw your p.s. > > So even though you are not using windows and can't use this technique > directly, I am just posting to give you some encouragement that, at > least theoretically, such a thing can be done. > It is for sure - VNC server does that. It might be a (very bad) solution to install a VNC server on one computer, and controll it from Windows using a VNC client. (It works but it was a joke, of course...) Laszlo From piet at cs.uu.nl Wed Nov 14 10:42:59 2007 From: piet at cs.uu.nl (Piet van Oostrum) Date: Wed, 14 Nov 2007 16:42:59 +0100 Subject: why there is no pythonscript insine web browsers? References: <1194992388.373707.327500@o38g2000hse.googlegroups.com> Message-ID: >>>>> kyosohma at gmail.com (k) wrote: >k> On Nov 12, 12:07 pm, Timu?in K z lay wrote: >>> I'm an old programmer coming from a cobol background and started to >>> learn python. I'm using javasript for web based applications but after I >>> started to learn python, the javascript language started to seem ugly to >>> me. Now I'm wondering why there is java support on web browsers but no >>> python support? there is even a vbscript support inside MS-IE but there >>> is no python support. it would be really nice and easy for me to use >>> python instead of javascript to write those ajax scripts. >>> >>> Please tell me, is there a python substitude for JRE ? >k> You can also use Python's cgi module. It's pretty cool, from what I've >k> read: CGI is server-side. The OP was asking for client-side embedding of Python. -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From vladimir at greenmice.info Thu Nov 22 04:50:58 2007 From: vladimir at greenmice.info (Vladimir Rusinov) Date: Thu, 22 Nov 2007 12:50:58 +0300 Subject: python safe scripting In-Reply-To: References: Message-ID: On 11/21/07, Guilherme Polo wrote: > > 2007/11/21, Vladimir Rusinov : > > Hello! > > > > In one my project (it's logfile manager) I want to implement 'smart' > > configuration files, e.g. > > > > logfile("/var/log/messages") > > if (size() > 10*1024*1024) and (lavg() < 5): > > execute("my_log_alerter") > > rotate(save=10, compress='bzip2') > > > > how can I safely do this? > > > logging already provides the rotating > Yes, but apache, nginx and others does not uses logger. I wanna write an application which would handle all my (Linux) logs: rotating, compressing, analysing and so on (logrotate replacement), it would require some nontrivial configuration, something like "If size of this log bigger then 2Mb or today is sunday. If size of this log bigger then 30 Mb, and today is not sunday, then rotate it, and make alert". Is there any module to parse such configuration files? -- Vladimir Rusinov GreenMice Solutions: IT-??????? ?? ???? Linux http://greenmice.info/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From donn.ingle at gmail.com Sat Nov 17 03:07:56 2007 From: donn.ingle at gmail.com (Donn Ingle) Date: Sat, 17 Nov 2007 10:07:56 +0200 Subject: overriding methods - two questions References: <473dd35a$0$7999$426a34cc@news.free.fr> <13js4tebjlucv16@corp.supernews.com> <13jt7gukmjc31a2@corp.supernews.com> Message-ID: > This is strictly a documentation matter, in my mind. Python does not > offer any means to enforce the calling sequence of an "override method". Yes, I hear you. > You might be able to wrap YOUR calling code with a try/except block > to trap errors if the callback doesn't like the "documented API" > arguments. Good plan. Thanks, dunno why I didn't think of that! /d From steve at REMOVE-THIS-cybersource.com.au Wed Nov 14 06:58:07 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Wed, 14 Nov 2007 11:58:07 -0000 Subject: Arrays References: <1194917023.976618@www.vif.com> <1194918994.934367.28860@v3g2000hsg.googlegroups.com> <1194937100.432126.53690@k35g2000prh.googlegroups.com> <1194971181.168508@www.vif.com> <13jk6af1vs5g89@corp.supernews.com> Message-ID: <13jlomf7su5qte8@corp.supernews.com> On Tue, 13 Nov 2007 22:31:57 -0200, Jorge Godoy wrote: > Steven D'Aprano wrote: > >> "The only intuitive interface is the nipple. After that, it's all >> learned." -- Bruce Ediger on user interfaces. > > And after we learn its other "uses", not even the nipple is so easy... > Who haven't heard (or said, if you're a woman) "Don't bite it like that, > it hurts!"? :-) Or even "Please Sir, bite it like that! Thank you Sir!" *ducks and hides* -- Steven From steve at REMOVE-THIS-cybersource.com.au Wed Nov 7 17:16:37 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Wed, 07 Nov 2007 22:16:37 -0000 Subject: Is pyparsing really a recursive descent parser? References: <5p0dhgFnj4rbU1@mid.uni-berlin.de> <1194007658.200713.178210@57g2000hsv.googlegroups.com> <1194104971.263256.66640@d55g2000hsg.googlegroups.com> <43rXi.397547$6L.130044@fe03.news.easynews.com> <1194223837.104424.242360@o3g2000hsb.googlegroups.com> <9HoYi.50838$m72.33706@fe06.news.easynews.com> <9WpYi.124193$g82.92783@fe07.news.easynews.com> Message-ID: <13j4ea5ph6okj80@corp.supernews.com> On Wed, 07 Nov 2007 21:15:50 +0000, Just Another Victim of the Ambient Morality wrote: > Why can't I find a pyparsing-esque library with this implementation? > I'm tempted to roll my own except that it's a fairly complicated > algorithm and I don't really understand how it's any more efficient than > the naive approach... I think you may have just answered your own question :) -- Steven. From deets at nospam.web.de Mon Nov 19 06:24:36 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 19 Nov 2007 12:24:36 +0100 Subject: What is python????? References: <7ab5b781-3c6c-4fb5-9be1-703d5e7e73a6@s12g2000prg.googlegroups.com> Message-ID: <5qda3kFv123mU1@mid.uni-berlin.de> > You're having a conversation with a spambot. Spam - certainly. But bot - no. Unless there have been some really remarkable improvements in KI lately. It's amazing that recently so many spam is written by some guys actually _reading_ this group. I presume they somehow want to create credibility in their postings by provoking real threads that then at some point contain the actual information. Can't beat Turing if the other side actually _is_ human... Diez From mathivram at yahoo.com Mon Nov 12 04:17:02 2007 From: mathivram at yahoo.com (ashik) Date: Mon, 12 Nov 2007 01:17:02 -0800 Subject: comp.lang.python 2007 Message-ID: <1194859022.910295.102990@e9g2000prf.googlegroups.com> sdfg dsv vcjgsdgsy http://www.freewebs.com/thuiss/ http://indianfriendfinder.com/go/g906725-pmem From paddy3118 at googlemail.com Fri Nov 2 03:15:51 2007 From: paddy3118 at googlemail.com (Paddy) Date: Fri, 02 Nov 2007 07:15:51 -0000 Subject: AOP and pep 246 In-Reply-To: <1193935586.110516.105630@50g2000hsm.googlegroups.com> References: <1193935586.110516.105630@50g2000hsm.googlegroups.com> Message-ID: <1193987751.993561.144510@d55g2000hsg.googlegroups.com> On Nov 1, 4:46 pm, Kay Schluehr wrote: > On 1 Nov., 16:18, "Rustom Mody" wrote: > > > I am interested in AOP in python. From here one naturally (or > > google-ly) reaches peak. > > But peak seems to be discontinued. > > Whereas pep-246 on adaptors seems to be rejected in favor of something else. > > > What?? > > > Can someone please throw some light on whats the current state of the art? > > AOP was a research that gone nowhere - at least not in its orginal > AspectJ form: If you Verify integrated circuits then you might know of the Specman e language (http://en.wikipedia.org/wiki/Specman), That pre-dates AspectJ and is very much alive. Its AOP feature-set is different to that of AspectJ. Our Verification engineers find the AOP paradigm to be very productive. It allows them to write a testbench in e and use AOP to extend it to create different testcases. Just found a version of the LRM online (search for 'extend'): http://www.ieee1647.org/downloads/prelim_e_lrm.pdf - Paddy. From bjourne at gmail.com Fri Nov 23 19:21:01 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Sat, 24 Nov 2007 00:21:01 +0000 Subject: the annoying, verbose self In-Reply-To: <13keq168fnu9328@corp.supernews.com> References: <3c954a31-9fb9-4c0f-b784-cef9ee057ca6@g30g2000hsb.googlegroups.com> <6f67fccf-fbec-4c75-baea-5d0277e07883@w40g2000hsb.googlegroups.com> <47458D4E.5030302@sympatico.ca> <13keq168fnu9328@corp.supernews.com> Message-ID: <740c3aec0711231621g501e69f3ua503e8f6f4900875@mail.gmail.com> On Nov 23, 2007 11:54 PM, Steven D'Aprano wrote: > On Fri, 23 Nov 2007 23:38:24 +0000, BJ?rn Lindqvist > wrote: > > > I like that a lot. This saves 12 characters for the original example and > > removes the need to wrap it. > > > > 7 return math.sqrt(.x * .x + .y * .y + .z * .z) > > > > +1 Readability counts, even on small screens. [gibberish] > which to my eyes has too much whitespace, but the alternative is worse: > math.sqrt(.x*.x + .y*.y + .z*.z) This is merely your personal preference and as such, it is not possible to argue or put in absolute terms. > and this is positively painful to try to read, it looks like line-noise: > math.sqrt(.x*.x+.y*.y+.z*.z) At least it is 12 characters less line-noise than math.sqrt(self.x*self.y+self.y*self.y+self.z*self.z). > The correct solution to your example is to get rid of the attribute > lookups from the expression completely: No it is not. The "solution" is nothing more than a silly band-aid thrown out by people who cannot comprehend that Python may not be perfect in every little detail. > def abs(self): > x, y, z = self.x, self.y, self.z > return math.sqrt(x**2 + y**2 + z**2) > > > It's probably also faster, because it looks up the attributes only once > each, instead of twice. timeit -- mvh Bj?rn From gslindstrom at gmail.com Mon Nov 5 07:24:07 2007 From: gslindstrom at gmail.com (Greg Lindstrom) Date: Mon, 5 Nov 2007 07:24:07 -0500 Subject: Python good for data mining? Message-ID: > ---------- Forwarded message ---------- > From: "D.Hering" > To: python-list at python.org > Date: Sun, 04 Nov 2007 19:42:16 -0800 > Subject: Re: Python good for data mining? > On Nov 3, 9:02 pm, Jens wrote: > > I'm starting a project indatamining, and I'm considering Python and > > Java as possible platforms. > > > > I'm conserned by performance. Most benchmarks report that Java is > > about 10-15 times faster than Python, and my own experiments confirms > > this. I could imagine this to become a problem for very large > > datasets. > > > I really like Python for a number of reasons, and would like to avoid > > Java. I've been working with databases -- many in the terabyte size -- for over 20 years and my advice to you is to learn how to use SQL to do most of the work for you. There is (almost) nothing you can't do with a good database (we use Oracle and Postgres, but I hear that MySQL is good, too). We have over 100 stored procedures and some of our queries are a bit long; some with over 30 JOINS, but our queries are fast enough. We even generate XML and EDI-X12 directly from the database via stored procedures. I used to pull as much as I could back from the database and them manipulate it with C using abstract data types and record layouts with lots of pointers. Now I use Python to access the base and let the database do most of the heavy lifting. Life is good. --greg -------------- next part -------------- An HTML attachment was scrubbed... URL: From Anthon.van.der.Neut at googlemail.com Sun Nov 18 14:00:06 2007 From: Anthon.van.der.Neut at googlemail.com (Anthon) Date: Sun, 18 Nov 2007 11:00:06 -0800 (PST) Subject: keyword parameter order References: Message-ID: Hi Tim, Thanks for the comments, I obviously hadn't thought beyond the simple case. I am happy I wrote (and that you Martin answered) instead of trying to program myself into a halffunctional implementation %-) Regards Anthon On Nov 18, 1:40 pm, Tim Chase wrote: > > I am looking for a way to determine the order of keyword parameters > > passed on to a class method. > > I'm fairly certain it's not possible, as how would code like this > behave: > > def my_func(**kwd): > kwd = OrderedDict(kwd) #magic happens here? > return do_something(kwd) > > my_dict = {'hello':42, 'world':3.14159} > print my_func(**my_dict) > > This is regularly used in lots of code. The ordering of the > contents of my_dict is already lost before the my_func() ever > gets a chance to see it. And in case one suggests trying to > sniff the source-code for the ordering, it's easy to break with > things like > > my_dict = read_dict_from_file(get_filename_from_user()) > > where the dict and its source are completely outside the scope of > the code. > > The only way around it I see is to force the user to pass in an > ordered dict explicitly: > > def my_func(ordered_dict_of_kwdargs): > return do_something(ordered_dict_of_kwdargs) > my_dict = OrderedDict() > my_dict['hello'] = 42 > my_dict['world'] = 3.14159 > print my_func(my_dict) > > -tkc From bborcic at gmail.com Fri Nov 9 07:01:35 2007 From: bborcic at gmail.com (Boris Borcic) Date: Fri, 09 Nov 2007 13:01:35 +0100 Subject: How to link different site-packages to different Python? In-Reply-To: <1194603553.861256.56380@i13g2000prf.googlegroups.com> References: <1194603553.861256.56380@i13g2000prf.googlegroups.com> Message-ID: <47344c58$1_7@news.bluewin.ch> Davy wrote: > Hi all, > > I have Python 2.4 and 2.5 in my PC. And PythonWin is installed as IDE. > > When I tried to use site-packages "Numpy", I installed the both > version (i.e. for 2.4 and 2.5). > > Python 2.4 and Numpy for it work together well. > > But when I type "from numpy import *" in Python 2.5. It throw out an > error indicate that the numpy library is link to Python 2.4 package? > How to fix this problem? Shouldn't occur if you properly installed python+pythonwin+numpy from their respective installer once for each of python 2.4 and 2.5. You may use the (Tools/Browse Pythonpath) and (Tools/Edit PythonPath) menu items in each of Pythonwin 2.4 and 2.5 to sort things out. If your lazyness isn't caused by your impatience, a possibility is to deinstall and then reinstall everything :) From http Sat Nov 24 01:27:35 2007 From: http (Paul Rubin) Date: 23 Nov 2007 22:27:35 -0800 Subject: Catching a segfault in a Python library References: <7x1wagp8vu.fsf@ruckus.brouhaha.com> <7xbq9k1be4.fsf@ruckus.brouhaha.com> Message-ID: <7xwss817l4.fsf@ruckus.brouhaha.com> Donn Ingle writes: > Okay, that's a good start. Thanks, I'll go for a python starts wxpython > thing with os.wait() to sniff the outcome. You may have to roll your own fork/exec to start the wxpython, instead of using popen or the subprocess module. I'm not terribly conversant in those modules but they may start a shell which would isolate your program from the wxpython exit code. From tim.arnold at sas.com Fri Nov 16 12:54:23 2007 From: tim.arnold at sas.com (Tim Arnold) Date: Fri, 16 Nov 2007 12:54:23 -0500 Subject: insert comments into elementtree Message-ID: Hi, I'm using the TidyHTMLTreeBuilder to generate some elementtrees from html. One by-product is that I'm losing comments embedded in the html. So I'm trying to put them back in, but I'm doing something wrong: here's the code snippet of how I generate the Trees: from elementtree import ElementTree as ET from elementtidy import TidyHTMLTreeBuilder XHTML = "{http://www.w3.org/1999/xhtml}" htmfile = os.path.join(self.htmloc,filename) fd = open(htmfile) tidyTree = TidyHTMLTreeBuilder.TidyHTMLTreeBuilder('utf-8') tidyTree.feed(fd.read()) fd.close() try: tmp = tidyTree.close() except: print 'Bad file: %s\nSkipping.' % filename continue tree = ET.ElementTree(tmp) and here's the method I use to put the comments back in: def addComments(self,tree): body = tree.find('./%sbody' % XHTML) for elem in body: if elem.tag == '%sdiv' % XHTML and elem.get('class'): if elem.get('class') == 'remapped': comElem = ET.SubElement(elem,ET.Comment('stopindex')) self.addComments(tree) filename = os.path.join(self.deliverloc,name) self.htmlcontent.write(tree,filename,encoding=self.encoding when I try this I get errors from the ElementTree _write method: TypeError: cannot concatenate 'str' and 'instance' objects thanks for any help! --Tim Arnold From gardsted at yahoo.com Sun Nov 18 18:50:57 2007 From: gardsted at yahoo.com (gardsted) Date: Mon, 19 Nov 2007 00:50:57 +0100 Subject: regular expression In-Reply-To: <4740ad46$0$21929$157c6196@dreader1.cybercity.dk> References: <4740ad46$0$21929$157c6196@dreader1.cybercity.dk> Message-ID: <4740cfe2$0$21927$157c6196@dreader1.cybercity.dk> Ups - got it - there are no flags in finditer;-) So rtfm, once again, jorgen! gardsted wrote: > I just can't seem to get it: > I was having some trouble with finding the first following with this regex: > > Should these two approaches behave similarly? > I used hours before I found the second one, > but then again, I'm not so smart...: > > kind retards > jorgen / de mente > using python 2.5.1 > ------------------------------------------- > import re > > TESTTXT=""" SAMPLES "" "" > > > MAINSEND 1 > ACT 1 > > > ACT 1 > > > > > > > """ > print "The First approach - flags in finditer" > rex = re.compile(r'^<(?P[a-zA-Z0-9_]*)') > for i in rex.finditer(TESTTXT,re.MULTILINE): > print i,i.groups() > > print "The Second approach - flags in pattern " > rex = re.compile(r'(?m)^<(?P[a-zA-Z0-9_]*)') > for i in rex.finditer(TESTTXT): > print i,i.groups() From vinay_sajip at yahoo.co.uk Tue Nov 20 07:26:52 2007 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Tue, 20 Nov 2007 04:26:52 -0800 (PST) Subject: logging.SocketHandler connections References: <23cfe277-7ece-4bef-a16f-1e64b1847f1c@a28g2000hsc.googlegroups.com> <7dfca907-f2e6-45b6-84f1-e60772c24c3d@w34g2000hsg.googlegroups.com> <5a39cd02-1f21-417d-8dd2-f96f10a2ac8f@v4g2000hsf.googlegroups.com> <4623a151-3246-4405-a770-23c70b4b45f1@w34g2000hsg.googlegroups.com> Message-ID: <58ef16cc-f2e4-4447-8939-30897e0bb35a@w28g2000hsf.googlegroups.com> On Nov 20, 12:08 pm, oj wrote: > On Nov 19, 5:30 pm, Vinay Sajip wrote: > > > > > On Nov 19, 10:27 am, oj wrote: > > > > On Nov 16, 2:31 pm, Vinay Sajip wrote: > > > > Here is the server code. Pretty much directly copied from the example, > > > aside from not having the the handler loop forever, and queing the > > > records instead of dealing with the directly. > > > > After further investigation, running the client with a long timeout, > > > without the server, so that every connection will fail, produces > > > results much closer to what I would expect. Connections attempted for > > > each message initially, but not for all of the later messages as the > > > retry time increases. > > > > The point is kinda moot now, since I guess not closing the connection > > > is the 'right way' to do this, but I'm still interested in why I see > > > this behaviour when the server closes the connection. > > > I've investigated this and the issue appears not to be related to > > closing connections. Your server code differs from the example in the > > docs in one crucial way: there is a while loop which you have left out > > in the handle() function, which deals with multipleloggingevents > > received in one packet. Add this back in, and all 9 events are > > received. > > > def handle(self): > > while 1: > > chunk = self.connection.recv(4) > > > if len(chunk) < 4: > > break > > > slen = struct.unpack(">L", chunk)[0] > > chunk = self.connection.recv(slen) > > > while len(chunk) < slen: > > chunk = chunk + self.connection.recv(slen - > > len(chunk)) > > > obj = self.unPickle(chunk) > > record =logging.makeLogRecord(obj) > > queue_lock.acquire() > > queue.insert(0, record) > > queue_lock.release() > > > So it appears that due to buffering, 3 socket events are sent in each > > packet sent over the wire. You were only processing the first of each > > set of three, viz. nos. 0, 3, 6 and 9. Mystery solved, it appears! > > > Regards, > > > Vinay Sajip > > I don't think buffering explains the behaviour I was seeing. Can you confirm that if you add the while loop back in, all messages are seen by the server? It worked for me. Vinay Sajip From mccredie at gmail.com Mon Nov 5 14:26:50 2007 From: mccredie at gmail.com (Matimus) Date: Mon, 05 Nov 2007 19:26:50 -0000 Subject: instance as a sequence In-Reply-To: <1194285577.259839.131240@o3g2000hsb.googlegroups.com> References: <1194283930.922568.258040@k79g2000hse.googlegroups.com> <1194284424.362046.294570@k79g2000hse.googlegroups.com> <1194285577.259839.131240@o3g2000hsb.googlegroups.com> Message-ID: <1194290810.316608.162270@v23g2000prn.googlegroups.com> On Nov 5, 9:59 am, snd... at gmail.com wrote: > On Nov 5, 9:40 am, Paul McGuire wrote: > > > On Nov 5, 11:32 am, snd... at gmail.com wrote: > > > > suppose i want to > > > make foo.childNodes[bar] available as foo[bar] > > > (while still providing access to the printxml/printprettyxml() > > > functions > > > and other functionality of dom/minidom instance). > > > > What is a good way to accomplish that? > > > define __getitem__(self, index) method on foo's class, and have the > > method return foo.childNodes[index]. > > > If you don't have access to foo's class, then just do this: > > > foo.__getitem__ = delegatingGetItemMethod > > > and define delegatingGetItemMethod as described above. > > could i plug it into the (exiting) xml.dom.minidom class rather than > the instance? If you want that type of functionality it is better to just create a new class, inherit from Document and use the new class. class MyDocument(xml.dom.minidom.Document): def __getitem__(self, index): #blah ... You could then do this: `xml.dom.minidom.Document = MyDocument', but changing the Document class itself, especially for such a trivial improvement is just confusing to whoever might be reading your code. Like another poster said, if you want a more convenient way to modify and read XML use ElementTree. minidom works the way it does because it it following a W3C specification. If you start modifying it for convenience you will 1. break the specification and 2. reinvent the wheel because there already exists more convenient means of accessing XML. Matt From kyosohma at gmail.com Thu Nov 15 11:18:54 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 15 Nov 2007 08:18:54 -0800 (PST) Subject: why there is no pythonscript insine web browsers? References: <1194992388.373707.327500@o38g2000hse.googlegroups.com> Message-ID: <19dd5c95-47ed-465b-91ab-248d1b800db3@p69g2000hsa.googlegroups.com> On Nov 14, 9:42 am, Piet van Oostrum wrote: > >>>>> kyoso... at gmail.com (k) wrote: > >k> On Nov 12, 12:07 pm, Timu?in K z lay wrote: > >>> I'm an old programmer coming from a cobol background and started to > >>> learn python. I'm using javasript for web based applications but after I > >>> started to learn python, the javascript language started to seem ugly to > >>> me. Now I'm wondering why there is java support on web browsers but no > >>> python support? there is even a vbscript support inside MS-IE but there > >>> is no python support. it would be really nice and easy for me to use > >>> python instead of javascript to write those ajax scripts. > > >>> Please tell me, is there a python substitude for JRE ? > >k> You can also use Python's cgi module. It's pretty cool, from what I've > >k> read: > > CGI is server-side. The OP was asking for client-side embedding of Python. > -- > Piet van Oostrum > URL:http://www.cs.uu.nl/~piet[PGP 8DAE142BE17999C4] > Private email: p... at vanoostrum.org Oh...oops...mis-read again. Mike From roy at panix.com Tue Nov 27 04:20:20 2007 From: roy at panix.com (Roy Smith) Date: Tue, 27 Nov 2007 04:20:20 -0500 Subject: the annoying, verbose self References: <3c954a31-9fb9-4c0f-b784-cef9ee057ca6@g30g2000hsb.googlegroups.com> <4068d518-cba9-4eac-bd91-11f676c17b3d@w34g2000hsg.googlegroups.com> <5qq6quF10jrh5U2@mid.uni-berlin.de> <5qqoslF10jrh5U6@mid.uni-berlin.de> <474b1b44$0$20133$426a74cc@news.free.fr> <474bdf4f$0$19226$426a74cc@news.free.fr> Message-ID: In article <474bdf4f$0$19226$426a74cc at news.free.fr>, Bruno Desthuilliers wrote: > Steven D'Aprano a ??crit : > > On Mon, 26 Nov 2007 21:48:36 +0100, Ton van Vliet wrote: > > > >> On Mon, 26 Nov 2007 20:14:50 +0100, Bruno Desthuilliers > >> wrote: > >> > >>>> However, I was more thinking in terms of attributes only > >>> Too bad : in Python, everything's an object, so 'methods' are attributes > >>> too. > >> Right, but I'm sure *you* know a way to distinguish between them > > Yes : reading the doc. But that's something the compiler will have hard > time doing. > > >> (I'm > >> just a beginner ;-) > > > > All methods are attributes. Not all attributes are methods. The usual way > > to see if something is a method is to try calling it and see what > > happens, but if you want a less informal test, try type(): > > > > > >>>> type(''.join) > > > >>>> type(Foo().foo) # with the obvious definition of Foo > > > > > > > Fine. Now since Python let you define your own callable types and your > own descriptors, you can as well have an attribute that behave just like > a method without being an instance of any of the method types - so the > above test defeats duck typing. And since you can have callable > attributes that are definitively not methods, you can't rely on the fact > that an attribute is callable neither. If you want to have a little fun: class peverse: def __call__(self): raise AttributeError ("peverse instance has no __call__ method") x = peverse() x() From aahz at pythoncraft.com Sun Nov 25 00:57:10 2007 From: aahz at pythoncraft.com (Aahz) Date: 24 Nov 2007 21:57:10 -0800 Subject: OPLC purchase period extended References: Message-ID: In article , David Boddie wrote: >On Sat Nov 24 19:30:03 CET 2007, Grant Edwards wrote: >> >> The XO laptop comes with a built-in Python IDE, so everybody on >> c.l.p ought to have one... > >A nice idea in theory, but... > > 2. XO laptops will be shipped only to G1G1 participants and only to the > street addresses they provide for themselves in the fifty United States, > Puerto Rico, Guam, the U.S. Virgin Islands, the District of Columbia and > Canada. > > [http://laptopgiving.org/en/terms-and-conditions.php] I'm sure that some people would be willing to serve as middleware... -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Typing is cheap. Thinking is expensive." --Roy Smith From trekker182 at comcast.net Tue Nov 27 15:36:27 2007 From: trekker182 at comcast.net (Shawn Minisall) Date: Tue, 27 Nov 2007 15:36:27 -0500 Subject: get mouse Message-ID: <474C7FCB.7000100@comcast.net> I'm just trying to test and see if the get mouse statements are working in my program. If they are, in the console window, it should go back to the prompt. It doesn't for all of them, just the last rectangle...sometimes. Am I setting them up correctly? here's the relevant code...thx The first two numbers are x1,x2 and the last two are y1, y2. rectMathButton = CreateRect(4,6,7,8,"grey") rectMathButton.draw(win) rectScienceButton = CreateRect(3.5,6.5,5,6,"grey") rectScienceButton.draw(win) rectHistoryButton = CreateRect(3.5,6.5,3,4,"grey") rectHistoryButton.draw(win) rectGeographyButton = CreateRect(3.1,7,1,2,"grey") rectGeographyButton.draw(win) #math p1 = win.getMouse() while p1.getX()> 6 or p1.getX()< 4 or p1.getY()> 8 or p1.getY()< 7: p1 = win.getMouse() #science p2 = win.getMouse() while p2.getX()> 6.5 or p2.getX()< 3.5 or p2.getY()> 6 or p2.getY()< 5: p2 = win.getMouse() #history p3 = win.getMouse() while p3.getX()> 6.5 or p3.getX()< 3.5 or p3.getY()> 4 or p3.getY()< 3: p3 = win.getMouse() #geography p4 = win.getMouse() while p4.getX()> 7 or p4.getX()< 3.1 or p4.getY()> 2 or p4.getY()< 1.1: p4 = win.getMouse() From MonkeeSage at gmail.com Mon Nov 19 02:34:40 2007 From: MonkeeSage at gmail.com (MonkeeSage) Date: Sun, 18 Nov 2007 23:34:40 -0800 (PST) Subject: newbie Q: sequence membership References: <8a934485-efd4-4e89-ac1b-d7c277978686@l22g2000hsc.googlegroups.com> <17880eed-b3c1-4d77-854a-cf8e24a56746@w73g2000hsf.googlegroups.com> Message-ID: On Nov 19, 12:32 am, saccade wrote: > I am not a programmer so I feel odd commenting about language design > decisions. When my Prof. introduced python the first question that > popped into mind was that since "x=9; y=9; print x is y and x == y" > prints "True" is there a way to change the value of 9? He said that > was silly but after class showed me that statements "True = []" work > but suggested it was harmless and not quite a bug. > > So if I am permitted to think of integers as immutable objects with > predefined labels (i.e. the integers used in the text of the program > code) that cannot de or re referenced then what a similar treatment of > characters will look like seams to be an arbitary (a design) decition. > > In this vein it seams reasonable to expect 'a'[0] and 'ba'[1] to refer > to the same object. If one follows the convention used with integers > (9 and 9 refer to the same object) then 'ab' and 'ab' would be the > same. An equally reasonable assumption would be that 'ab' and 'ab' are > two different sequences and so not equal (I do not see the problem > here). The problem is with side-effets. With "pure" code, your reasoning would be sound; but given that side-effects may alter the execution path, ab[@T1] and ab[@T2] may _not_ refer to the same object. This observation, is, of course, highly superfluous. ;) Regards, Jordan From thorsten at thorstenkampe.de Tue Nov 6 11:18:33 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Tue, 6 Nov 2007 16:18:33 -0000 Subject: Parallel Python environments.. References: Message-ID: * bruce (Tue, 6 Nov 2007 07:13:43 -0800) > If I wanted to be able to build/test/use parallel python versions, what > would I need to do/set (paths/libs/etc...) nothing > and where would I need to place the 2nd python version, so as not to > screw up my initial python dev env. Anywhere you like (probably ~/bin would be best) > Any sites/pointers describing the process would be helpuful. In particular, > any changfes to the bashrc/profile/etc... files to allow me to accomplish > this would be helpful. Nothing like that. Just change the shebang. Thorsten From deliverable at gmail.com Thu Nov 22 10:24:39 2007 From: deliverable at gmail.com (braver) Date: Thu, 22 Nov 2007 07:24:39 -0800 (PST) Subject: eof References: <92a2c0c9-e6a1-4344-aeac-830940200f20@t47g2000hsc.googlegroups.com> <79i9k35vs76cqgqnino7dj3ql623us3euq@4ax.com> <6c04c760-6cf1-4715-9ec9-30f43ebaa01f@d27g2000prf.googlegroups.com> <062a9497-7626-440a-93eb-b897e6dec01f@p69g2000hsa.googlegroups.com> <5qlkf3F10drl7U1@mid.uni-berlin.de> Message-ID: On Nov 22, 6:10 pm, "Diez B. Roggisch" wrote: > Granted, they aren't part of the stdlib - but then, lots > of things aren't. As Hendrik noticed, I can't even add my own f.eof() if I want to have buffering -- is that right? The tradeoff between speed and convenience is something I'd rather determine and enable myself, if I have the right tools. Cheers, Alexy From wleftwich at gmail.com Sat Nov 17 10:38:56 2007 From: wleftwich at gmail.com (Wade Leftwich) Date: Sat, 17 Nov 2007 07:38:56 -0800 (PST) Subject: Excellent sci-fi novel featuring Python References: <45ae31dd-0aaf-4065-ba9e-b1e5cf78b105@c30g2000hsa.googlegroups.com> Message-ID: <1d65c516-196c-411e-96d8-55d7c5c43007@v4g2000hsf.googlegroups.com> On Nov 17, 10:37 am, Wade Leftwich wrote: > I'm about halfway through Charles Stross' excellent new novel, > "Halting State". It's set in Edinburgh in the year 2018, and one of > the main characters is a game programmer whose primary language is > something called "Python 3000". > > The cover features blurbs from William Gibson, Vernor Vinge, John > Carnack, and Bruce Scheier. > > What, they couldn't pop for an advance copy for Guido? > > -- Wade Leftwich > Ithaca, NY Damn keyboard. The last two endorsers are John Carmack and Bruce Schneier. From enleverlesX.XmcX at XmclaveauX.com Fri Nov 30 04:50:04 2007 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Fri, 30 Nov 2007 10:50:04 +0100 Subject: PIL + show() + Vista In-Reply-To: <1196386241_1353@sp12lax.superfeed.net> References: <474f5197$0$27369$ba4acef3@news.orange.fr> <1196386241_1353@sp12lax.superfeed.net> Message-ID: <474fdf53$0$27367$ba4acef3@news.orange.fr> Hi! Not a true solution ; because people who don't have IrfanView don't use it. @-salutations Michel Claveau From deets at nospam.web.de Tue Nov 20 17:58:56 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 20 Nov 2007 23:58:56 +0100 Subject: mimicking a file in memory In-Reply-To: References: <3ea3babb-29f1-4950-9d5b-c31f67d4e54a@i29g2000prf.googlegroups.com> <13k6mjapuemsre6@corp.supernews.com> Message-ID: <5qh75iFv1tthU1@mid.uni-berlin.de> p. schrieb: > On Nov 20, 2:06 pm, Grant Edwards wrote: >> On 2007-11-20, Jarek Zgoda wrote: >> >>>> Here is my dilemma: I don't want to copy the files into a >>>> local directory for mutagen's sake, only to have to remove >>>> them afterward. Instead, I'd like to load the files into >>>> memory and still be able to hand the built-in "file" function >>>> a filename to access the file in memory. >>>> Any ideas on how to do this? >> By "memory" I presume you mean virtual memory? RAM with >> disk-blocks as backing store? On any real OS, tempfiles are >> just RAM with disk-blocks as backing store. >> >> Sound similar? The only difference is the API used to access >> the bytes. You want a file-I/O API, so you can either use the >> extensively tested and and highly optimized filesystem code in >> the OS to make disk-backed-RAM look like a file, or you can try >> to write Python code that does the same thing. >> >> Which do you think is going to work faster/better? >> >> [The kernel is generally better at knowing what needs to be in >> RAM than you are -- let it do its job.] >> >> IOW: just use a temp file. Life will be simple. The bytes >> probably won't ever hit the platters (if they do, then that >> means they would have the other way too). >> >> -- >> Grant Edwards grante Yow! It's a hole all the >> at way to downtown Burbank! >> visi.com > > Thanks all. > > Grant, are temp files automatically put into ram for all linux > distros? at any rate, i could set up ram disk. much better solution > than using python...except that i've never done a ram disk before. > more reading to do... You misunderstood Grant. Let the OS decide what needs to be dumped to the HD or not - instead of creating a RAM-disk eating up precious ram. All modern OS, including Linux, have hard-disc-caches in RAM. Which your downloaded file ends in, whilst being stored to the HD in the background - without affecting your performance. If you then pass it to some other process that reads from the file, it will be fed from the HD-cache - fast. So - if it makes your life easier to use tempfiles because then you have an actual filename, use them and don't mind. Diez From deets at nospam.web.de Mon Nov 26 14:00:58 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 26 Nov 2007 20:00:58 +0100 Subject: Should proxy objects lie about their class name? In-Reply-To: <87d4txudv2.fsf@pobox.com> References: <87lk8szlnm.fsf@pobox.com> <87d4txudv2.fsf@pobox.com> Message-ID: <5r0jfgF1219j2U1@mid.uni-berlin.de> John J. Lee schrieb: > jjl at pobox.com (John J. Lee) writes: > >> Not much to add to the subject line. I mean something like this: >> >> ProxyClass.__name__ = ProxiedClass.__name__ >> >> >> I've been told that this is common practice. Is it? Would this >> surprise you if you ran into it in a debugging session? > > Does nobody have an opinion on this? Pull your socks up, c.l.py! > > I've written quite a few proxies, but none of them did that. IMHO this is similar to using isinstance overeagerly: it works against the duck-typing principle to guard code by requiring certain base-classes, instead of just relying on protocol. The same applies here. There might be of course cases where you have code lying around that does do some distinctions based on the class-name (I'm certainly I've seen such stuff once or tiwce, but always regarded it a WTF). Then doing as you do above might help in getting things work. Diez From tbabula at gmail.com Sun Nov 4 02:00:28 2007 From: tbabula at gmail.com (Tom_chicollegeboy) Date: Sun, 04 Nov 2007 07:00:28 -0000 Subject: how to iterate through each set In-Reply-To: <1194155896.243516.171220@o38g2000hse.googlegroups.com> References: <1194150610.798025.282330@y42g2000hsy.googlegroups.com> <13iqn7piblqqb20@corp.supernews.com> <1194155896.243516.171220@o38g2000hse.googlegroups.com> Message-ID: <1194159628.552549.243540@v3g2000hsg.googlegroups.com> I figured out problem. here is my code. now it works as it should! Thank you everyone! def speed(): infile = open('speed.in', 'r') line = infile.readline() read = int(line) while '-1' not in line: i = 0 t0 = 0 v = 0 if len(line.split())==1: read = int(line) while i References: <47316bf2$0$239$e4fe514c@news.xs4all.nl> <13j3lf56qatpv5a@corp.supernews.com> Message-ID: <47334029$0$241$e4fe514c@news.xs4all.nl> thanks very much! Grant Edwards wrote: > On 2007-11-07, Paul Sijben wrote: > >> To automate/ease configuration in my app I am trying to find >> out to which serial port a certain bluetooth device is >> connected. With pybluez I can find out which bluetooth devices >> I have, but it will not tell me the serial port they are >> mapped to. >> >> Is there a way to figure this out from python? (I am >> insterested in the platforms WinXP and linux primarily) > > Under linux, the "right" thing to do is to write a udev rule so > that the device has a predictiable name (or symlink). > > http://reactivated.net/writing_udev_rules.html > > If you don't want to write a udev rule, you'll need to bascally > re-implement udev by parsing the sysfs directory tree until you > find the device you're looking for. Here's how to do it for USB > (I assume BT works in a similar fashion). > > Let's say I know the device has vendor ID 0403, product ID > 6001, and serial number 123456. > > I search through the directories under /sys/devices until I > find a directory containing three files named > > idProduct > idVendor > serial > > Which contain the three strings I'm looking for. > > In this case: > > # cat /sys/devices/pci0000:00/0000:00:10.3/usb5/5-1/idVendor > 0403 > # cat /sys/devices/pci0000:00/0000:00:10.3/usb5/5-1/idProduct > 6001 > # cat /sys/devices/pci0000:00/0000:00:10.3/usb5/5-1/serial > 12345678 > > Once you've found that directory, you can look at the other > entries to find out whatever you want to know about the device: > > /sys/devices/pci0000:00/0000:00:10.3/usb5/5-1/ > |-- 5-1:1.0 > | |-- bAlternateSetting > | |-- bInterfaceClass > | |-- bInterfaceNumber > | |-- bInterfaceProtocol > | |-- bInterfaceSubClass > | |-- bNumEndpoints > | |-- bus -> ../../../../../../bus/usb > | |-- driver -> ../../../../../../bus/usb/drivers/ftdi_sio > | |-- ep_02 -> ../../../../../../devices/pci0000:00/0000:00:10.3/usb5/5-1/5-1:1.0/usbdev5.42_ep02 > | |-- ep_81 -> ../../../../../../devices/pci0000:00/0000:00:10.3/usb5/5-1/5-1:1.0/usbdev5.42_ep81 > | |-- interface > | |-- modalias > | |-- power > | | |-- state > | | `-- wakeup > | |-- subsystem -> ../../../../../../bus/usb > | |-- ttyUSB0 > | | |-- bus -> ../../../../../../../bus/usb-serial > | | |-- driver -> ../../../../../../../bus/usb-serial/drivers/ftdi_sio > | | |-- power > | | | |-- state > | | | `-- wakeup > | | |-- subsystem -> ../../../../../../../bus/usb-serial > | | |-- tty:ttyUSB0 -> ../../../../../../../class/tty/ttyUSB0 > | | `-- uevent > | |-- uevent > | |-- usb_endpoint:usbdev5.42_ep02 -> ../../../../../../devices/pci0000:00/0000:00:10.3/usb5/5-1/5-1:1.0/usbdev5.42_ep02 > | |-- usb_endpoint:usbdev5.42_ep81 -> ../../../../../../devices/pci0000:00/0000:00:10.3/usb5/5-1/5-1:1.0/usbdev5.42_ep81 > | |-- usbdev5.42_ep02 > | | |-- bEndpointAddress > | | |-- bInterval > | | |-- bLength > | | |-- bmAttributes > | | |-- dev > | | |-- device -> ../../../../../../../devices/pci0000:00/0000:00:10.3/usb5/5-1/5-1:1.0 > | | |-- direction > | | |-- interval > | | |-- power > | | | |-- state > | | | `-- wakeup > | | |-- subsystem -> ../../../../../../../class/usb_endpoint > | | |-- type > | | |-- uevent > | | `-- wMaxPacketSize > | `-- usbdev5.42_ep81 > | |-- bEndpointAddress > | |-- bInterval > | |-- bLength > | |-- bmAttributes > | |-- dev > | |-- device -> ../../../../../../../devices/pci0000:00/0000:00:10.3/usb5/5-1/5-1:1.0 > | |-- direction > | |-- interval > | |-- power > | | |-- state > | | `-- wakeup > | |-- subsystem -> ../../../../../../../class/usb_endpoint > | |-- type > | |-- uevent > | `-- wMaxPacketSize > |-- bConfigurationValue > |-- bDeviceClass > |-- bDeviceProtocol > |-- bDeviceSubClass > |-- bMaxPacketSize0 > |-- bMaxPower > |-- bNumConfigurations > |-- bNumInterfaces > |-- bcdDevice > |-- bmAttributes > |-- bus -> ../../../../../bus/usb > |-- configuration > |-- devnum > |-- driver -> ../../../../../bus/usb/drivers/usb > |-- ep_00 -> ../../../../../devices/pci0000:00/0000:00:10.3/usb5/5-1/usbdev5.42_ep00 > |-- event_char > |-- idProduct > |-- idVendor > |-- manufacturer > |-- maxchild > |-- power > | |-- state > | `-- wakeup > |-- product > |-- serial > |-- speed > |-- subsystem -> ../../../../../bus/usb > |-- uevent > |-- usb_device:usbdev5.42 -> ../../../../../class/usb_device/usbdev5.42 > |-- usb_endpoint:usbdev5.42_ep00 -> ../../../../../devices/pci0000:00/0000:00:10.3/usb5/5-1/usbdev5.42_ep00 > |-- usbdev5.42_ep00 > | |-- bEndpointAddress > | |-- bInterval > | |-- bLength > | |-- bmAttributes > | |-- dev > | |-- device -> ../../../../../../devices/pci0000:00/0000:00:10.3/usb5/5-1 > | |-- direction > | |-- interval > | |-- power > | | |-- state > | | `-- wakeup > | |-- subsystem -> ../../../../../../class/usb_endpoint > | |-- type > | |-- uevent > | `-- wMaxPacketSize > `-- version > > > If you want to search by something other than the product id, > vendor id and serial number, then pick some other of the files > above that will have identifiable contents and look for that. > From horpner at yahoo.com Tue Nov 27 09:38:21 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Tue, 27 Nov 2007 14:38:21 GMT Subject: the annoying, verbose self References: <3c954a31-9fb9-4c0f-b784-cef9ee057ca6@g30g2000hsb.googlegroups.com> <4068d518-cba9-4eac-bd91-11f676c17b3d@w34g2000hsg.googlegroups.com> <5qq6quF10jrh5U2@mid.uni-berlin.de> <5qqoslF10jrh5U6@mid.uni-berlin.de> <474b1caa$0$20133$426a74cc@news.free.fr> Message-ID: On 2007-11-26, Bruno Desthuilliers wrote: > Patrick Mullen a ?crit : > (snip) >> Still an unnecessary lookup on tmp though :) And it would be useless >> to use it for one assignment, the idea is to eliminate all the typing >> with this: >> >> self.var1 = 5 >> self.var2 = "a value" >> self.var3 = stuff >> self.var4 = [2,54,7,7] >> self.var5 = "dingaling" >> self.var6 = 6.4 >> self.var7 = 1 >> self.var8 = False >> self.var9 = True > > self.__dict__.update(dict(var1=5, var2="a value", var3 = stuff, )) > > Someone else ? Or are we done with this DeadHorse ? I was really upset about having to type 'self' all the time, until I learned that in ABC, one of Python's precursors, you had to use '__anInstanceOf_This_TYPE_or_Maybe_A__SubClassOfItInstead_arg0_'. -- Neil Cerutti Sermon Outline: I. Delineate your fear II. Disown your fear III. Displace your rear --Church Bulletin Blooper From arkanes at gmail.com Wed Nov 28 12:23:42 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 28 Nov 2007 11:23:42 -0600 Subject: How to Teach Python "Variables" In-Reply-To: <8cca3871-2bb1-4eeb-96bc-f9dacc20c0a4@o6g2000hsd.googlegroups.com> References: <4749bb94$1@news.bezeqint.net> <5qvf6pF122r3mU1@mid.individual.net> <87abp1qqth.fsf@mulj.homelinux.net> <2d7c881d-e5c0-43ec-a8eb-b7c81a118c21@w40g2000hsb.googlegroups.com> <8cca3871-2bb1-4eeb-96bc-f9dacc20c0a4@o6g2000hsd.googlegroups.com> Message-ID: <4866bea60711280923q49134914r9756fa411cf36164@mail.gmail.com> On Nov 28, 2007 10:57 AM, hdante wrote: > On Nov 28, 2:12 pm, "Chris Mellon" wrote: > > > > Right. Python variables are pointers, except for all the ways that > > they are different. By the same criteria, they are also puppies. Give > > it a rest. > > I'm sorry if your notion of pointer is incorrect. A pointer (or, more > formally, a reference) is an object that points to some value. A > python variable isn't different than that in any way. > A python name isn't an object. The difference between names and objects is at the core of this entire conversation. In fact, you are exactly the sort of person this discussion was targeted at, because you don't understand the difference. You can play semantic games if you want and just declare that everything is the same at some fundamental level. It's a little like taking your ball and going home, because insisting on names that don't indicate the differences between things is useless at best and harmful at worst. Whether you like it or not, the term "pointer" has a specific common meanings. They do not mean "any means by which you may reference a value". "variable" is certainly less clear and is used much more loosely, but in the specific context of comparison to C, python name/object bindings are not the same as C variables. Pointers are values. They also point at other values, and those values may be other pointers, ad infinitum. Understanding this is core to understanding and using pointers. Python names are *not* values, and all they do is tag a specific object in a specific namespace. You can't have a name that refers to another name, names can only refer to objects. Understanding this is core to understanding and using the Python object model, *especially* if some nitwit has been telling you that they're the same as pointers. From arkanes at gmail.com Tue Nov 13 09:53:34 2007 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 13 Nov 2007 08:53:34 -0600 Subject: Looking for a good Python environment In-Reply-To: <1194947762.178169.318430@57g2000hsv.googlegroups.com> References: <1194389774.159051.55580@19g2000hsx.googlegroups.com> <1194434140.836932.10670@k79g2000hse.googlegroups.com> <1194686473.581666.203870@k79g2000hse.googlegroups.com> <87d4uimnwk.fsf@rudin.co.uk> <1194947762.178169.318430@57g2000hsv.googlegroups.com> Message-ID: <4866bea60711130653u1955b551qbeba31cebb3e477b@mail.gmail.com> On Nov 13, 2007 3:56 AM, bramble wrote: > On Nov 10, 4:48 am, Paul Rudin wrote: > > jwelby writes: > > > > > The main reason I have used Eclipse for larger, team based, projects > > > is for the source control plug-ins. Eclipse has plug-in support for > > > cvs and svn. PyScripter may have this too - perhaps I've missed it. > > > (I'm away from my Windows box at the moment, otherwise I would check). > > > Of course, there are other ways to implement source control without it > > > needing to be integrated in the IDE, so even this need not put off > > > anyone who wants to use PyScripter with source control. > > > > > [snip] > > > > I'm not sure if you count emacs as "lightweight" but it's certainly > > less resource hungry than eclipse/pydev, and does have integrated > > cvs/svn functionality. > > I've never understood the desire for using your version control > software via your IDE. Why not just Alt-Tab over to your terminal > window and run the svn/bzr/hg/git/whatever commands yourself right > from there? > Because I'm already in my IDE and I'm already managing files from there. The version integration in Eclipse also has some other handy features, like showing history in the live document (I can do an svn blame for the line I'm looking at directly in the editor, without needing to context switch to a different environment). In the particular case of Eclipse, Eclipse has it's own "workspace" and project metaphors, it doesn't work with just any old file it happens to find. This can be very frustrating at times, but since that's how Eclipse works it's nice to have source control integrated into that. > > -- > http://mail.python.org/mailman/listinfo/python-list > From mal at egenix.com Sat Nov 10 14:12:27 2007 From: mal at egenix.com (M.-A. Lemburg) Date: Sat, 10 Nov 2007 20:12:27 +0100 Subject: Python Extension Building Network In-Reply-To: <1194655483.880861.120570@o38g2000hse.googlegroups.com> References: <1194617297.075298.238880@i13g2000prf.googlegroups.com> <1194623343.121618.65350@v3g2000hsg.googlegroups.com> <1194655483.880861.120570@o38g2000hse.googlegroups.com> Message-ID: <4736029B.106@egenix.com> On 2007-11-10 01:44, kyosohma at gmail.com wrote: >>> The directions for MinGW were usually only partially correct. So I >>> went through the two sets of directions I found (links on the site) >>> and mixed and matched until I got it right. >>> There are no directions on how to use Visual Studio 2003 that I've >>> found, just some old free edition. those directions were incompatible >>> with VS2003. I'll post VS2003's correct usage eventually, but it's >>> basically just installing it and then using distutils. >> Getting VS2003 ready to compile Python extensions is really easy: >> >> 1. open a command shell >> 2. run vcvars32.bat >> 3. make sure the Python version you are targetting is on the >> PATH >> 4. "python setup.py bdist_wininst" or "python setup.py bdist_msi" >> 5. pick up the installer in the build\ directory. >> > > > I didn't need to run vcvars32.bat to make mine work. But that's good > to know...I think. > > >> Note: bdist_msi is only available in Python 2.5 and later. >> >> You need VC6 if you want to compile extensions for Python 1.5-2.3 >> and VC7.1 for Python 2.4 and later. >> > > I was aware of that you needed VC6 for 2.3, but I didn't realize it > went that far back. And I knew you needed 7.1 for 2.4 and 2.5, but > I've heard that they're moving to VS2005 soon. AFAIK, Martin (who's building the Windows installers for Python) is going to skip VS2005 and go straight for VS2008, but I may be wrong. > Thanks for the feedback, Marc-Andre! You're welcome :-) -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Nov 10 2007) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From oruccim at gmail.com Wed Nov 14 15:04:21 2007 From: oruccim at gmail.com (oruccim at gmail.com) Date: Wed, 14 Nov 2007 12:04:21 -0800 Subject: general information In-Reply-To: <1195070186.925479.106980@o3g2000hsb.googlegroups.com> References: <1195070186.925479.106980@o3g2000hsb.googlegroups.com> Message-ID: <1195070661.016137.138660@d55g2000hsg.googlegroups.com> yyyyyyyyyyGyUykypy{y?y?y?y?y ?y?y?y?y?y?y?y?y?y?yzzz)z,z?z?z?z?z?z?{? {||g|l|l|l|l|l|r|?|?|?|?| ?|}??? ?'????? ???????????U,?,?, ,?,? ,?,?,?,?,? ?F?????????????????????$,,',,l,,g...k...n... ?... ...?...3?C?F?I?L?U?c?|?|????'???????????? ?X? [?^?d?g?g?j?m?r?u?????!????? ??????????????????? ?D?G?G?T?W?_?i?l?l? ??"?????????????????> i am trying with notepad but there ara similar this From erik at myemma.com Mon Nov 26 11:05:04 2007 From: erik at myemma.com (Erik Jones) Date: Mon, 26 Nov 2007 10:05:04 -0600 Subject: basic if stuff- testing ranges In-Reply-To: References: <4749c63a$0$19678$426a74cc@news.free.fr> Message-ID: <1B00AA56-574B-444C-B9AE-FD7D7332E932@myemma.com> On Nov 26, 2007, at 2:29 AM, Peter Otten wrote: > Donn Ingle wrote: > >>> x in range(1,20) ? >> Sure, that's okay, but it has clarity issues, and is calling a func. > > and it requires that x is integral (1.0 is in the range, 1.001 is > not), > and becomes dog slow when the range gets larger. Not a good idea. That is because range() is not a range in the abstract sense (i.e. simply defining bounds that can be tested for set membership) but are used to create lists (or, in the case of xrange(), successive values) between the bounds given in the params. So, saying x in range(1,20) is not asking if x is between 1 and 20 but, rather, if x is a member of the values genereated by the range function with params 1 and 20. So, yes, using range() Erik Jones Software Developer | Emma? erik at myemma.com 800.595.4401 or 615.292.5888 615.292.0777 (fax) Emma helps organizations everywhere communicate & market in style. Visit us online at http://www.myemma.com From rolf.wester at ilt.fraunhofer.de Fri Nov 16 06:38:03 2007 From: rolf.wester at ilt.fraunhofer.de (Rolf Wester) Date: Fri, 16 Nov 2007 12:38:03 +0100 Subject: Memory problem In-Reply-To: <473c1d40$1@news.fhg.de> References: <473c1d40$1@news.fhg.de> Message-ID: <473d811c$1@news.fhg.de> Hi, thank you for your comments and your hints (I probably deserve some kind of subtle irony). I found the problem: I thought a numpy array A has shape (n,) but actually it had shape (n,1). In the loop I sampled a value from that array: v.append(A[i]) So what happened was that I got a view of A not a single number and append obviously appended the whole array not just a single element array. And n is about 64000. So sorry for bothering you with that stupid fault. Regards Rolf From luc.goossens at cern.ch Tue Nov 20 05:24:20 2007 From: luc.goossens at cern.ch (Luc Goossens) Date: Tue, 20 Nov 2007 11:24:20 +0100 Subject: marked-up Python code Message-ID: Hi, I would like to experiment with marked-up Python source code. A more elaborate explanation of the use-case is at the end of this mail. The short story is that I would like to do things like assign colors to pieces of text in my editor and have this information saved _in my source code_ smth like else : print "ERROR" return -1 "all" the Python parser has to do is skip the mark-up. Has something like this been done before? Is there a way to do this without changing the Python executable? If not, where in the source code should I start looking? cheers, Luc PS1 I know I can put the mark-up after a # and the problem is solved trivially, but this will not work for all cases (e.g. mark-up of single identifiers) and to be honest I was thinking of recycling some mark-up capable editor and an existing mark-up language PS2 here's the real use case I have a small application in Python. The code shares a recurring feature: within methods 20% of the code lines is about the actual handling of the correct case, 40% is about the handling of the incorrect cases, 40% is instrumenting (logging and timing). A case for aspect oriented programming? I would certainly think so, but unfortunately there is no obvious way to map this to the prevailing aspect-advice-joint point-point cut model. Moreover, I really do not want this code to become fragmented over multiple source code files, I just want the aspects to be readily visible in my editor, and be able to selectively show/hide some of them (like expanding/collapsing code blocks). From gagsl-py2 at yahoo.com.ar Thu Nov 15 23:26:40 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 16 Nov 2007 01:26:40 -0300 Subject: Interfaces. References: <1ecf1cca-f05f-44b5-8128-a93208815f15@y5g2000hsf.googlegroups.com> Message-ID: En Thu, 15 Nov 2007 22:55:13 -0300, PeterBraden1 at googlemail.com escribi?: > Does anyone know what the state of progress with interfaces for python > (last I can see is http://www.python.org/dev/peps/pep-0245/) You may be interested in PEP3119 -- Gabriel Genellina From dwahli at gmail.com Fri Nov 16 06:34:35 2007 From: dwahli at gmail.com (dwahli at gmail.com) Date: Fri, 16 Nov 2007 03:34:35 -0800 (PST) Subject: cx_Oracle: Non-ASCII characters handling with different versions References: <5pu25tFsqglkU1@mid.individual.net> <5q0a1oFtggf7U1@mid.individual.net> Message-ID: <08d185de-644d-4173-af06-663e028aa484@e4g2000hsg.googlegroups.com> On Nov 14, 2:03 pm, Benjamin Hell wrote: > It's solved: Because of a local full Oracle DB installation the > "working" box had the registry key > HKEY_LOCAL_SYSTEM\SOFTWARE\ORACLE\KEY_OraBD10g_home1\NLS_LANG set to > "AMERICAN_AMERICA.WE8MSWIN1252". A similar key was missing on the > other box. I added HKEY_LOCAL_SYSTEM\SOFTWARE\ORACLE\NLS_LANG with > the same value and now it works. You could use environment variable NLS_LANG to set it at run time with: os.environ["NLS_LANG"] = "AMERICAN_AMERICA.WE8MSWIN1252" import cx_Oracle ... This way you don't have to deal with registry on each box. Note that os.environ["NLS_LANG"] must be BEFORE import cx_Oracle. Domino From python.list at tim.thechases.com Thu Nov 29 15:27:10 2007 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 29 Nov 2007 14:27:10 -0600 Subject: How to Split a String In-Reply-To: <0b724d25-24ea-41ba-b084-a8d59a9558b8@w40g2000hsb.googlegroups.com> References: <0b724d25-24ea-41ba-b084-a8d59a9558b8@w40g2000hsb.googlegroups.com> Message-ID: <474F209E.5010706@tim.thechases.com> > I need to convert the string: '(a, b, "c", d, "e")' into the > following list ['a', 'b', 'c', 'd', 'e']. Much like a csv > reader does. I usually use the split function, but this > mini-monster wouldn't properly get split up due to those > random quotations postgresql returns to me. Uh...use the csv reader? :) No need to reinvent the parsing wheel. >>> import csv >>> from StringIO import StringIO >>> s = 'a,b,"c",d,"e"' >>> csv.reader(StringIO(s)).next() ['a', 'b', 'c', 'd', 'e'] If you really have the parens in your string too, you can peal them off first with "s[1:-1]" >>> s = '(a,b,"c",d,"e")' >>> csv.reader(StringIO(s[1:-1])).next() ['a', 'b', 'c', 'd', 'e'] or strip any/all parens: >>> s = '(a,b,"c",d,"e")' >>> csv.reader(StringIO(s.lstrip('(').rstrip(')'))).next() ['a', 'b', 'c', 'd', 'e'] -tkc From chiendarret at yahoo.com Tue Nov 20 04:16:53 2007 From: chiendarret at yahoo.com (Francesco Pietra) Date: Tue, 20 Nov 2007 01:16:53 -0800 (PST) Subject: Recursive insertion of a line In-Reply-To: Message-ID: <463943.49694.qm@web57606.mail.re1.yahoo.com> Please, see below. --- Gabriel Genellina wrote: > En Mon, 19 Nov 2007 21:15:16 -0300, Henry > escribi?: > > > On 19/11/2007, Francesco Pietra wrote: > >> > >> How to insert "TER" records recursively, i.e. some thousand fold, in a > >> file > >> like in the following example? "H2 WAT" is the only constant > >> characteristic of > >> the line after which to insert "TER"; that distinguishes also for lines > > > > If every molecule is water, and therefore 3 atoms, > you can use this fact > > to > > insert TER in the right place. You don't need recursion: > > > > f = open( "atoms.txt", "rt" ) > > lineCount = 0 > > for line in f.xreadlines( ): > > lineCount = lineCount + 1 > > print line > > if lineCount == 3: > > lineCount = 0 > > print "TER" > > f.close( ) > > A small variation can handle the original, more generic condition "insert > TER after the line containing H2 > WAT" > > f = open("atoms.txt", "r") > for line in f: > print line > if "H2 WAT" in line: > print "TER" > f.close() > > (also, note that unless you're using Python 2.2 or earlier, the xreadlines > call does no good) I tried the latter script (which works also if there are other molecules in the file, as it is my case) encountering two problems: (1) "TER" records were inserted, as seen on the shell window. Though, the file on disk was not modified. Your script named "ter_insert.py", in order to get the modified file I used the classic $ python ter_insert.py 2>&1 | tee file.out Now, "file .out" had "TER" inserted where I wanted. It might well be that it was my incorrect use of your script. (2) An extra line is inserted (which was not a problem of outputting the file as I did), except between "TER" and the next line, as shown below: TER ATOM 27400 O WAT 4178 20.289 4.598 26.491 1.00 0.00 W20 O ATOM 27401 H1 WAT 4178 19.714 3.835 26.423 1.00 0.00 W20 H ATOM 27402 H2 WAT 4178 21.173 4.237 26.554 1.00 0.00 W20 H TER ATOM 27403 O WAT 4585 23.340 3.428 25.621 1.00 0.00 W20 O ATOM 27404 H1 WAT 4585 22.491 2.985 25.602 1.00 0.00 W20 H ATOM 27405 H2 WAT 4585 23.826 2.999 26.325 1.00 0.00 W20 H TER ATOM 27406 O WAT 4966 22.359 0.555 27.001 1.00 0.00 W20 O ATOM 27407 H1 WAT 4966 21.820 1.202 27.456 1.00 0.00 W20 H ATOM 27408 H2 WAT 4966 22.554 -0.112 27.659 1.00 0.00 W20 H TER END Where "END" is how Protein Data Bank (pdb) files end. As these files are extremely sensitive, can the script be modified to avoid these extra lines? Not tried (it takes time, because I have to go to the big cluster) if the extra lines really create problems, though, they take a lot of space on the shell window. A nearly perfect script. Thank you francesco > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > ____________________________________________________________________________________ Never miss a thing. Make Yahoo your home page. http://www.yahoo.com/r/hs From python.list at tim.thechases.com Sat Nov 17 09:21:20 2007 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 17 Nov 2007 08:21:20 -0600 Subject: Python too complex ?!?!?! In-Reply-To: <7hC%i.28332$mv3.17248@newsfe10.phx> References: <7hC%i.28332$mv3.17248@newsfe10.phx> Message-ID: <473EF8E0.7010105@tim.thechases.com> > programmer, but he claims that the install, config, and > library models for C# have proved to be less > problematic than Python. So both his courses (intro, > data structs, algorithms) are taught in C#. A little anecdotal comparison from some of my experience with two web apps deployed at my current company: One web app, written in C#/ASP.net one written in Python. Moved each app to new servers (C#/ASP.net on a new Windows box, Python app on a shiny new Debian box). C#/ASP.net app: had to find and install the right version of the .net libraries. That's an afternoon of my life I won't get back. Python app: copied my app C#/ASP.net app: couldn't find VS2003 (in which the app had been written) any more so had to upgrade to VS2005. Python app: Continued to use the same development environment. C#/ASP.net app: (ASP specific) generally requires following a particular convention. Writing a RESTful web app is next to impossible given the reliance on the postbacks; and the server environment doesn't make it easy to make clean URLs Python app: Django makes web-app development easy and clean/RESTful (other frameworks may as well...I speak from Django experience) and push you to Do The Right Thing (tm) C#/ASP.net app: had to re-partition my server containers so that it could deploy .Net 2.0 and .Net 3.0 apps side-by-side Python app: I've had Python 2.3, 2.4 and 2.5 running on the same machine without a thought C#/ASP.net app: libraries are often written to a particular framework version, so if any new functionality requires the new version the whole app needs to be migrated. Python app: most of the libraries I use come built in, or they work with 2.3 or later. C#/ASP.net app: Installing new libraries, same as upgrading currently-used libraries. Usually requires paying for, then manually installing various libraries, clearing distribution rights, etc. Python app: There are an abundance libraries that are just an apt-get away in terms of difficulty, and they are Free Software so I can install them and deploy them without additional costs. C#/ASP.net app: 3rd party libraries usually come as source-less DLLs that you can't peer into Python app: 3rd party libraries are usually pure python which you can modify or step into as needed C#/ASP.net app: really only works well on Windows Python app: works well on Windows, Linux, BSD, Mac OS X... C#/ASP.net app: really requires Visual Studio Python app: works well with Eclipse, Vim, Emacs, Wing IDE, Komodo, Idle, and piles of other development environments. Heck, I've written the occasional python program using "ed" or "cat > x.py". C#/ASP.net app: files are scattered all over. You've got source apps, you've got templates, you've got resource files, you've got GUID files. And VS hides the complexity so when (not "if") something breaks you get a crash course in what goes on under the covers. Python app: I've got .py files (and sometimes templates for my Django code, and could have I18N files for translations). Very easy to track down where everything is. C#/ASP.net app: Code/syntax is horridly opaque, requires braces and lots of additional overhead code to get things done. Compare the clutter of a basic C# script with a similarly function Python script. How much is pure syntactic overhead? Python app: Code/syntax is rather easy to read (once you understand list comprehensions and the __foo__ methods) Yeah, I'd take Python any day...for implementation *OR* for teaching someone how to program. -tkc From kf9150 at gmail.com Mon Nov 26 11:27:49 2007 From: kf9150 at gmail.com (Kelie) Date: Mon, 26 Nov 2007 08:27:49 -0800 (PST) Subject: better way to write this function References: <4b4d9cc5-3759-421e-b3a2-3cb25bdaae7a@b40g2000prf.googlegroups.com> <42f62547-3cc7-46dd-95e0-52d1885d7e09@d61g2000hsa.googlegroups.com> <7xlk8lgzjo.fsf@ruckus.brouhaha.com> Message-ID: On Nov 25, 10:51 pm, Paul Rubin wrote: > Really though, this grouping function gets reimplemented so often that > it should be built into the stdlib, maybe in itertools. thanks Paul. itertools? that was actually the first module i checked. From chadmounteny at gmail.com Sun Nov 25 21:54:31 2007 From: chadmounteny at gmail.com (chadmounteny at gmail.com) Date: Sun, 25 Nov 2007 18:54:31 -0800 (PST) Subject: mod_python References: Message-ID: On Nov 24, 1:19 am, Vernon Wenberg III wrote: > Why do I receive a "File not found" error on a perfect good and simple > script but properly receive errors when I deliberately add errors in the > script? The file is there, it just doesn't do anything. > > Any help would be appreciated. why don't you start with including the problem code From sergio.correia at gmail.com Sat Nov 24 01:02:17 2007 From: sergio.correia at gmail.com (Sergio Correia) Date: Sat, 24 Nov 2007 01:02:17 -0500 Subject: How do I convert escaped HTML into a string? In-Reply-To: References: Message-ID: This may help: http://effbot.org/zone/re-sub.htm#strip-html You should take care that there are several issues about going from html to txt 1)

What should wedo about
this?

You need to strip all tags.. 2) ", &, <, and >... and I could keep going.. we need to convert all those 3) we need to remove all whitespace.. tab, new lines, etc. (Maybe breaks should be considered as new lines in the new text?) The link above solve several of this issues, it can serve as a good starting point. Best, Sergio On Nov 24, 2007 12:42 AM, Just Another Victim of the Ambient Morality wrote: > I've done a google search on this but, amazingly, I'm the first guy to > ever need this! Everyone else seems to need the reverse of this. Actually, > I did find some people who complained about this and rolled their own > solution but I refuse to believe that Python doesn't have a built-in > solution to what must be a very common problem. > So, how do I convert HTML to plaintext? Something like this: > > >
Thisisastring.
> > > ...into: > > > This is a string. > > > Actually, the ideal would be a function that takes an HTML string and > convert it into a string that the HTML would correspond to. For instance, > converting: > > >
This & that > or the other thing.
> > > ...into: > > > This & that or the other thing. > > > ...since HTML seems to convert any amount and type of whitespace into a > single space (a bizarre design choice if I've ever seen one). > Surely, Python can already do this, right? > Thank you... > > > -- > http://mail.python.org/mailman/listinfo/python-list > From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Nov 30 15:11:13 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 30 Nov 2007 21:11:13 +0100 Subject: How to Split a String References: <0b724d25-24ea-41ba-b084-a8d59a9558b8@w40g2000hsb.googlegroups.com> <5r8lf4F13mdtuU1@mid.individual.net> Message-ID: <5rb931F13o9ehU1@mid.individual.net> Siah wrote: > The basic split/strip method wouldn't split '(a, b, "c,...", d)', > which is why I chose not to use it. Could you please explain which part of my example doesn't work? split takes arguments which enables it to split your string as desired. > The csv solution seems to work well, that helped me much here > (thank you), but I am looking to see if I can get it solved with > some regular expression. This is how far I've come so far, but it > needs much work: re.compile('"*,"*').split(x[1:-1]) Have fun. Would be too easy without regexps, wouldn't it? Regards, Bj?rn -- BOFH excuse #382: Someone was smoking in the computer room and set off the halon systems. From gagsl-py2 at yahoo.com.ar Thu Nov 15 23:18:47 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 16 Nov 2007 01:18:47 -0300 Subject: Memory problem References: <473c1d40$1@news.fhg.de> <5q2lf4Ftr3plU1@mid.uni-berlin.de> <473c23e1$1@news.fhg.de> Message-ID: En Thu, 15 Nov 2007 10:10:06 -0300, Peter Otten <__peter__ at web.de> escribi?: > Rolf Wester wrote: > >> Sorry, of course your are wright. I'm running Python2.5 on Linux, my >> program imports numpy, matplotlib, sys and a python module of my own. >> This module uses numpy and scipy.weave for imbedded C-code but no >> extension modules. I though the code to be to large to show, I hoped you >> could give me hint on what I could try. > > I think it is now safe to say that the embedded C code is a more likely > culprit than the relative humidity of the moon... Sure; and among all things that could be wrong, I'd start checking the reference counts. Get it wrong by -1 and your objects suddenly dissapear; get it wrong by +1 and your objects will never be destroyed, demanding more and more memory like in this case. -- Gabriel Genellina From mensanator at aol.com Sat Nov 17 13:19:35 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Sat, 17 Nov 2007 10:19:35 -0800 (PST) Subject: What is python????? References: <7ab5b781-3c6c-4fb5-9be1-703d5e7e73a6@s12g2000prg.googlegroups.com> <959349ce-34ad-4d8e-aea0-b7bcbbc6112f@f13g2000hsa.googlegroups.com> <4a92044d-ef1b-47b0-82e0-45946e08a794@n20g2000hsh.googlegroups.com> <828cecd6-40b9-4aaf-bb07-8386b6c7518e@f3g2000hsg.googlegroups.com> Message-ID: <279e6128-a5bd-4003-adf9-262a6a4a7392@v4g2000hsf.googlegroups.com> On Nov 17, 10:00?am, Neil Cerutti wrote: > On 2007-11-17, mensana... at aol.com wrote: > > > > > > > On Nov 16, 3:10?pm, Alan wrote: > >> On Nov 16, 8:29 pm, kyoso... at gmail.com wrote: > > >> > I still don't get it and I've been haunting this group for months... > > >> > Mike > > >> Go on then ?... > > >> What ? > > >> The punchline, do the punchline > > > Punchline? I don't think there's a punchline scheduled, is > > there? Where are we? A week 39.4 ...no, it's Friday, isn't it - > > 39.7. Oh...here we are. Oh! Ha, ha, ha, very good. Ha, ha, ha, > > very good. What a good punchline. Pity we missed that. > > def punchline(): > ? return random.choice(['What's all this, then?', > ? ? ? ? ? ? ? ? ? ? ? ? 'Do you want to come back to my place?', 'that you were willfully and persistently a foreiner']) > > -- > Neil Cerutti- Hide quoted text - > > - Show quoted text - From donn at u.washington.edu Tue Nov 27 12:50:23 2007 From: donn at u.washington.edu (Donn Cave) Date: Tue, 27 Nov 2007 09:50:23 -0800 Subject: How to Teach Python "Variables" References: <4749bb94$1@news.bezeqint.net> <4749c888$0$14869$426a74cc@news.free.fr> <4749cc7c$1@news.bezeqint.net> Message-ID: In article , Aaron Watters wrote: > I would try to avoid talking > in generalities about python variables versus C or > lisp or whatever, unless I was teaching an upper division > college programming languages survey class. > > Instead, I'd fire up the interactive interpreter and > illustrate how things work via examples, avoiding the > weird cases at all costs. If they ask about the > relationship to C or java or whatever > I would encourage them to not worry about it, > and only go deeper if pressed. I don't know if that explains enough on its own - I suppose it depends on how ambitious your programmer is. But the key point is that by approaching it this way, you're teaching them how to teach themselves as required: write an example, see what happens. A programmer who does this by reflex and remains confused about how the language works is, in my opinion, not going to get very far anyway. (This may have changed somewhat in recent years as more esoteric junk has has been stuffed into the language, I haven't really been keeping track.) In contrast, I suspect that someone who learns Python concepts in terms of explanations like `boxes' or `pointers' or whatnot is at some disadvantage while that lasts, like translating a foreign language to your own instead of attaching meaning directly. Donn Cave, donn at u.washington.edu From kyosohma at gmail.com Fri Nov 30 09:20:02 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Fri, 30 Nov 2007 06:20:02 -0800 (PST) Subject: Yet another database question, please References: <47500ee6$0$228$e4fe514c@news.xs4all.nl> Message-ID: <7aa00027-db8e-4151-a75b-3a711979ee55@e67g2000hsc.googlegroups.com> On Nov 30, 7:23 am, nmp wrote: > Hello to all. I am only just learning both Python and PyGTK (with Glade). > I also need to learn how to use databases in my programs. My preliminary > research leads me in the direction of SQLAlchemy, which seems to be what > everybody else is using. > > So, does anyone have a good example that shows how to tie these things > toegether? I would like to have the GUI dialogs and treeviews directly > interacting with the underlying tables and/or views. > > [cough]Like Borland Delphi 1.0, in the nineties...[/cough] > > Another question: I found that in Ubuntu, I was able to install the Glade > widgets for libgnomedb (libgnomedb3-glade3). Would these be usable with > Python/PyGTK, too? As is too common, the documentation provided is > somewhat scarce. > > Any sort of pointers or suggestions welcome, of course. You should try Dabo. It sounds like what you want to do and what Dabo does dovetails nicely. http://dabodev.com/ Mike From steve at REMOVE-THIS-cybersource.com.au Thu Nov 15 16:07:58 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 15 Nov 2007 21:07:58 -0000 Subject: Resolving declaring class of a method at runtime References: Message-ID: <13jpd9ek4ss4qc2@corp.supernews.com> On Thu, 15 Nov 2007 13:01:27 +0200, Janne H?rk?nen wrote: > Hello, > > Is there a simple way to resolve declaring class of a method at runtime > ? Have you tried looking at dir(TheClass) to see what it lists? Also helpful is TheClass.__dict__.keys(). Python has powerful introspection abilities. Learn to use them, and you too will be able to impress your friends with your Python knowledge. >>>> class X: > ... def x(self): > ... pass > ... X is an "old style" class. Most people probably shouldn't use old style classes, for various reasons. To use new style classes, you inherit from object: class X(object) -- Steven. From zentraders at gmail.com Sat Nov 3 20:49:10 2007 From: zentraders at gmail.com (Zentrader) Date: Sat, 03 Nov 2007 17:49:10 -0700 Subject: Python IDE In-Reply-To: References: Message-ID: <1194137350.420182.5840@v29g2000prd.googlegroups.com> This is a discussion on the Ubuntu forums-something like 51 pages worth. Even though you are using Gutsy, you want to take a look at KDevelop. It will install without problems even though it is KDE. A lot of people use Geany or Eclipse also. Anyway, you can page through as much of this thread as you like. http://ubuntuforums.org/showthread.php?t=6762 From barronmo at gmail.com Thu Nov 1 12:54:24 2007 From: barronmo at gmail.com (barronmo) Date: Thu, 01 Nov 2007 09:54:24 -0700 Subject: choose from a list In-Reply-To: <1193808770.776610.50280@o80g2000hse.googlegroups.com> References: <1193767382.430635.303370@d55g2000hsg.googlegroups.com> <1193770225.374384.52290@k79g2000hse.googlegroups.com> <1193782113.429067.132740@57g2000hsv.googlegroups.com> <1193785411.032673.147860@v3g2000hsg.googlegroups.com> <1193791188.338141.123020@v3g2000hsg.googlegroups.com> <1193808770.776610.50280@o80g2000hse.googlegroups.com> Message-ID: <1193936064.768638.152900@v3g2000hsg.googlegroups.com> This is really remarkable. My previous experience with programming was in VB for Applications; doing the same thing seemed much more complicated. This little function is only about 15 lines of code and it forms the basis for my entire application. With a few simple modifications I'll be able to get anything out of the database with a minimum of entries from the user. It turns out that 'results' was a tuple of dictionaries. I got an error trying to call the tuple; converting it to a list worked. Here is the current function: import MySQLdb def name_find(namefrag): conn = MySQLdb.connect(host = "localhost", user = "root", passwd = "Barron85", db = "meds") cursor = conn.cursor(MySQLdb.cursors.DictCursor) cursor.execute("SELECT patient_ID, firstname, lastname FROM demographics WHERE lastname LIKE '%s%%'" % (namefrag)) results = cursor.fetchall() for index, row in enumerate(results): print "%d %s %s %s" % (index, row["patient_ID"], row["firstname"], row["lastname"]) indx = int(raw_input("Select the record you want: ")) results_list = list(results) return results_list[indx]['patient_ID'] cursor.close() conn.close() This returns the patient_ID after selecting a name from the list, eg 615L. I'm not sure why the "L" is there but it shouldn't be hard to remove. Mensanator, thanks a lot for your help. This has been quite a lot to digest--huge leap in my understanding of Python. Michael Barron On Oct 31, 12:32 am, "mensana... at aol.com" wrote: > On Oct 30, 7:39?pm, barronmo wrote: > > > I didn't know "result" was alist! > > I don't use MySQL but that's how others work. > Eachlistitem is a record, each record a tuple > of field values. > > > Can all that info be stored in alist? > > If you don't fetch too many records at once. > This is a test of my word database using ODBC > and MS-ACCESS (the SQL is very simple since > all the actual work is done in MS-ACCESS, Python > is just retrieving the final results). > > import dbi > import odbc > con = odbc.odbc("words") > cursor = con.cursor() > cursor.execute("SELECT * FROM signature_anagram_summary") > results = cursor.fetchall() > > Here, results (the recipient of .fetchall) is alistof tuples. > The contents are: > > [(9, 10, 'anoretics', '10101000100001100111000000'), > (9, 10, 'atroscine', '10101000100001100111000000'), > (9, 10, 'certosina', '10101000100001100111000000'), > (9, 10, 'creations', '10101000100001100111000000'), > (9, 10, 'narcotise', '10101000100001100111000000'), > (9, 10, 'ostracine', '10101000100001100111000000'), > (9, 10, 'reactions', '10101000100001100111000000'), > (9, 10, 'secration', '10101000100001100111000000'), > (9, 10, 'tinoceras', '10101000100001100111000000'), > (9, 10, 'tricosane', '10101000100001100111000000')] > > > How do the columns work? > > I don't know, I don't get column names. It looked like > from your example that you can use names, I would have > to use indexes, such as results[3][2] to get 'creations'. > Maybe MySQL returns dictionaries instead of tuples. > > > I was curious to see what the data > > looked like but I can't seem to print "result" from the prompt. Do > > variables used inside functions live or die once the function > > executes? > > Yeah, they die. You would have to have the function return > the resultslistand indx, then you could use it's contents > as criteria for further queries. > > So you might want to say > > name_find_results,indx = name_find(namefrag) > > > If they die, how do I get around this? > > Add 'return results,indx' to the function. Or better still, > just return the record the user selected > return results[indx] > You wouldn't need indx anymore since there's only 1 record. > > > I tried defining 'r > > = ""' in the module before the function and then using it instead of > > "result" but that didn't help. > > > Mike From jeffober at gmail.com Tue Nov 20 13:12:38 2007 From: jeffober at gmail.com (Jeff) Date: Tue, 20 Nov 2007 10:12:38 -0800 (PST) Subject: Python web frameworks References: Message-ID: <5a2cff37-c0df-4003-905f-d991bf51ae2e@n20g2000hsh.googlegroups.com> On Nov 20, 10:00 am, Thomas Wittek wrote: > Jeff: > > > I don't know much about the others. Turbo gears uses Mochikit, which > > hasn't had a new stable release in some time. I prefer jQuery myself. > > You can use jQuery with TurboGears if you develop custom widgets (I do so). > No problem here. That's good to know, but I was intending to mean that TurboGears has built-in support for Mochikit, while Django has no built-in Javascript or Ajax support. From sndive at gmail.com Mon Nov 19 16:45:41 2007 From: sndive at gmail.com (sndive at gmail.com) Date: Mon, 19 Nov 2007 13:45:41 -0800 (PST) Subject: sockets: why doesn't my connect() block? References: Message-ID: <4be3154c-bdec-402e-b8d2-85e2cbf872c7@p69g2000hsa.googlegroups.com> On Nov 17, 11:32 pm, 7stud wrote: > According to "Python in a Nutshell(2nd)", p. 523: > > connect: s.connect((host, port)) > ... > Blocks until the server accepts or rejects the connection attempt. > > However, my client program ends immediately after the call to > connect()--even though my server program does not call accept(): > > #server---------------- > import socket > > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > port = 3200 > s.bind( ('', port) ) > s.listen(5) > > import time > time.sleep(20) > > #client---------------- > import socket > > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > host = 'localhost' > port = 3200 > > s.connect( (host, port) ) > print 'done' > > If I start my server program and then start my client program, the > client ends immediately and displays: done. I expected the client > program to block indefinitely. a better question is why you are not using higher level libraries, such as twisted From rocky at panix.com Tue Nov 27 02:21:15 2007 From: rocky at panix.com (R. Bernstein) Date: 27 Nov 2007 02:21:15 -0500 Subject: how to change current working directory while using pdb within emacs References: Message-ID: duyanning writes: > I have written a pyhton script that will process data file in current > working directory. > My script is in an different directory to data file. > When I debug this script using pdb within emacs, emacs will change the > current working directory to the directory which include the script, > so my script cannot find the data file. > > I think this is the problem of emacs because when I start pdb from > console directly, it will not change current working directory to the > one of script being debugged. > > please help me. > thank you. pydb (http://bashdb.sf.net/pydb) has an option to set the current working directory on invocation. For example, from emacs I can run: M-x pydb --cd=/tmp --annotate=3 ~/python/hanoi.py 3 And then when I type import os; os.getcwd() I get: '/tmp' Inside pydb, there is a "cd" command saving you the trouble of importing os; the "directory" command can be used to set a search path for source files. All same as you would do in gdb. Begin digression --- The --annotate option listed above, is similar to gdb's annotation mode. It is a very recent addition and is only in CVS. With annotation mode turned on, the effect is similar to running gdb (gdb-ui.el) in Emacs 22. Emacs internal buffers track the state of local variables, breakpoints and the stack automatically as the code progresses. If the variable pydb-many-windows is set to true, the each of these buffers appear in a frame. For those of you who don't start pydb initially bug enter via a call such as set_trace() or debugger() and do this inside an Emacs comint shell with pydb-tracking turned on, issue "set annotation 3" same as you would if you were in gdb. From algotrhythm at gmail.com Fri Nov 16 16:15:39 2007 From: algotrhythm at gmail.com (Alan) Date: Fri, 16 Nov 2007 13:15:39 -0800 (PST) Subject: Sorting Countries by Region References: <4375355d-b23e-4a1c-8f4b-183156a163c5@f13g2000hsa.googlegroups.com> <473dfd8c$0$1898$9a622dc7@news.kpnplanet.nl> Message-ID: <611db713-717f-4bce-89c4-39efa7d3eabd@e1g2000hsh.googlegroups.com> On Nov 16, 8:28 pm, martyw wrote: > > i would create a class to capture country information, e.g. What is the advantage of this: > def __cmp__(self, other): > if self.name < other.name: > return -1 > elif self.name > other.name: > return 1 > else: > return 0 > over def __cmp__(self,other): return cmp(self.name,other.name) ? -- Alan From kyosohma at gmail.com Sun Nov 11 09:24:12 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Sun, 11 Nov 2007 14:24:12 -0000 Subject: Python Extension Building Network In-Reply-To: References: <1194617297.075298.238880@i13g2000prf.googlegroups.com> Message-ID: <1194791052.046673.76870@o80g2000hse.googlegroups.com> On Nov 10, 11:03 pm, Yu-Xi Lim wrote: > kyoso... at gmail.com wrote: > > Hi, > > > I am trying to get a small group of volunteers together to create > > Windows binaries for any Python extension developer that needs them, > > much like the package/extension builders who volunteer their time to > > create Linux RPMs. > > > Mike > > It's not entirely clear to me what you're compiling. Most of the modules > you have there do not have native code. I'm guessing your main focus is > building .exe installers for Windows users. The main objective is to make it easier for Windows users to install the modules, so that's what the .exe is for. Admittedly developers should know how to install from source, but the newbs don't always know how and I've had some trouble with some of the more complex ones myself. > > If it's just installers of pure Python code, why the extra effort of > using both VS and MingW? AFAIK, they both yield functionally identical > results---the exact same .py files get installed. > I am using both because Steve Holden asked me to try MinGW. I was just going to use Visual Studio. However, I thought it might be a good idea to try it both ways to make sure it could be done in a completely open source environment. I'm pretty sure you can use MinGW on impure Python extensions too, although it takes more work. > I'm also not sure how big a task this is or the issues involved, but > here's my take based on what I've read: > > Throwing more manpower at the task is not the solution. The actual > process can be and SHOULD BE highly automated. All that's needed are a > proper distutils script, and proper tests. Both responsibilities should > fall on the shoulders of the module authors, though I guess experienced > volunteers can help out with the former. > I would like to do this and I was trying to come up with a way to do just that. For some reason, when I mentioned that idea to one of my more knowledgeable contacts, he didn't see the need for it. > If the module is pure Python, there should be little need for testing > the installer specifically on Windows. If there's a failure, then the > module itself is buggy (e.g. making platform-specific assumptions) or > there's similar problem with the install script. > > For a large number of modules on PyPI, building the installer is trivial > (assuming pure Python, and a setup script). Compiling them can be easily > automated: 1) check PyPI for updates 2) download the latest update 3) > build the .exe 3) upload to a website. All that remains is the need for > some hardware (a build farm) and the occasional manual intervention. > > If I'm not mistaken, distutils can build Windows installers on other > platforms. Maybe you could set up a Linux LiveCD with the necessary > tools installed and distribute that. Module authors who want to build > Windows installers can easily use that CD. Volunteers wanting to help > can do so easily without having to repeat the task of setting up the > toolchain separately. I've been told that distutils can build Windows installers on other platforms, but I think that may apply only to pure Python extensions only. > > I've done some work as a port maintainer (aka package maintainer) for > FreeBSD. The BSD port system is somewhat closer to PEAK's Easy Install, > however binary packages (similar to RPMs or DEBs) are also available. > The port maintainer's job is solely to ensure that the Makefile (build > script) is working and up to date. The actual testing of the code is > done by the authors of the software itself and the port maintainer only > ensures that the install script works right. Binary packages are built > by an automated system using a cluster of computers for various > architectures and supported OS versions. Errors during builds are sent > to to port maintainers. > > A similar system is used for most Linux distributions with a central > repository for packages. I like this idea quite a bit. It's nice to know that other people are thinking along the same lines as I am. However, I am not sure how to do this myself. I assume when you mean by creating a Linux Live CD with the proper tools, you mean that it should include MinGW and Python. I suppose the only problem with that is the dependency issue. There's a number of modules that require arbitrary modules for the setup.py file to run. Mechanize is one such module as it require ClientForm. Some of the others I've done required various versions of Easy Setup or ElementTree. I'm not sure how this is resolved unless you can just download these items during the Live CD session and install them to memory. However, I don't think this is currently possible, correct? I'll float your ideas by Holden and see what he thinks though. Thanks for the ideas. Mike From deets at nospam.web.de Tue Nov 13 11:47:25 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 13 Nov 2007 17:47:25 +0100 Subject: os walk() and threads problems (os.walk are thread safe?) References: <5ptsjjFsvk9kU1@mid.uni-berlin.de> Message-ID: <5pu2otFsm96nU1@mid.uni-berlin.de> Marcus Alves Grando wrote: > Diez B. Roggisch wrote: >> Marcus Alves Grando wrote: >> >>> Hello list, >>> >>> I have a strange problem with os.walk and threads in python script. I >>> have one script that create some threads and consume Queue. For every >>> value in Queue this script run os.walk() and printing root dir. But if i >>> increase number of threads the result are inconsistent compared with one >>> thread. >>> >>> For example, run this code plus sort with one thread and after run again >>> with ten threads and see diff(1). >> >> I don't see any difference. I ran it with 1 and 10 workers + sorted the >> output. No diff whatsoever. > > Do you test in one dir with many subdirs? like /usr or /usr/ports (in > freebsd) for example? Yes, over 1000 subdirs/files. >> >> And I don't know what you mean by diff(1) - was that supposed to be some >> output? > > No. One thread produce one result and ten threads produce another result > with less lines. > > Se example below: > > @@ -13774,8 +13782,6 @@ > /usr/compat/linux/proc/44 > /usr/compat/linux/proc/45 > /usr/compat/linux/proc/45318 > -/usr/compat/linux/proc/45484 > -/usr/compat/linux/proc/45532 > /usr/compat/linux/proc/45857 > /usr/compat/linux/proc/45903 > /usr/compat/linux/proc/46 I'm not sure what that directory is, but to me that looks like the linux /proc dir, containing process ids. Which incidentially changes between the two runs, as more threads will have process id aliases. Try your script on another directory. Diez From yeef.cn at gmail.com Fri Nov 30 23:33:44 2007 From: yeef.cn at gmail.com (Yeef) Date: Sat, 1 Dec 2007 12:33:44 +0800 Subject: "Python" is not a good name, should rename to "Athon" In-Reply-To: <7e55b84a-43b3-43c6-8adb-3760bc8b3a92@d21g2000prf.googlegroups.com> References: <7e55b84a-43b3-43c6-8adb-3760bc8b3a92@d21g2000prf.googlegroups.com> Message-ID: <197f543d0711302033hf3b7bc7n1df03dd227c6f039@mail.gmail.com> we search "python" in google, emule, many results are not programming resource. If we search PHP, all results are programming resource. i'm agree! On Dec 1, 2007 12:08 PM, wrote: > Pytn > > New name "Pytn" may be better, do you think so ? > -- > http://mail.python.org/mailman/listinfo/python-list > -- new city new thoughts new men please choose the freesoftware to:yeef.cn at gmail.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From horpner at yahoo.com Sun Nov 4 21:52:48 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Mon, 05 Nov 2007 02:52:48 GMT Subject: Is pyparsing really a recursive descent parser? References: <5p0dhgFnj4rbU1@mid.uni-berlin.de> <1194007658.200713.178210@57g2000hsv.googlegroups.com> <1194104971.263256.66640@d55g2000hsg.googlegroups.com> <43rXi.397547$6L.130044@fe03.news.easynews.com> <1194223837.104424.242360@o3g2000hsb.googlegroups.com> <6xvXi.39855$G23.18679@newsreading01.news.tds.net> Message-ID: <4AvXi.39856$G23.84@newsreading01.news.tds.net> On 2007-11-05, Neil Cerutti wrote: > def Ack(x, y): > """ The Ackermann function. Creates a humongous mess even > with quite tiny numbers. """ > if x < 0 or y < 0: > raise ValueError('non-negative integer') > elif x == 0: > return y + 1 > elif y == 0: > return foo3(x-1, 1) > else: > return foo3(x-1, foo3(x, y-1)) Urk! Of course those foo3 calls should have been Ack calls. -- Neil Cerutti From thunderfoot at gmail.com Wed Nov 7 16:50:35 2007 From: thunderfoot at gmail.com (thunderfoot at gmail.com) Date: Wed, 07 Nov 2007 13:50:35 -0800 Subject: command-line arguments in IDLE In-Reply-To: <1194397079.632843.16240@t8g2000prg.googlegroups.com> References: <1194397079.632843.16240@t8g2000prg.googlegroups.com> Message-ID: <1194472235.503835.98730@o3g2000hsb.googlegroups.com> On Nov 7, 6:27 am, "Russ P." wrote: > Is it possible to pass command-line arguments when running a program > in IDLE? The "Run" menu does not seem to provide that option. Thanks. Can't you just fake the command line args by setting sys.argv? This isn't too sophisticated, but it appears to work: import sys try: __file__ except: sys.argv = ['scriptname.py', 'this','is','a','test','within','idle'] for arg in sys.argv: print arg Running from within IDLE: >>> scriptname.py this is a test within idle >>> Running from the command prompt: C:\Python24>python.exe mystuff/argtest.py this is yet another test mystuff/argtest.py this is yet another test C:\Python24> HTH, Don From nytrokiss at gmail.com Mon Nov 26 13:43:45 2007 From: nytrokiss at gmail.com (James Matthews) Date: Mon, 26 Nov 2007 19:43:45 +0100 Subject: Tk 8.5 In-Reply-To: <00d901c82eac$5e83aec0$6501a8c0@aristotle> References: <00d901c82eac$5e83aec0$6501a8c0@aristotle> Message-ID: <8a6b8e350711261043u29cdc611w9a33cb26c18b94ed@mail.gmail.com> I also cannot wait! On Nov 24, 2007 4:12 PM, Ron Provost wrote: > Hello, > > According to the tk wiki, the final release of Tcl/Tk is just weeks away > (see http://wiki.tcl.tk/12753). Does anyone know if the Tk enhancements > will be in Python 2.6? Since I don't use tk but I do use Python and > Tkinter (and Tix) extensively, I'm excited about these long-awaited changes. > > Thanks, > Ron > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://search.goldwatches.com/?Search=Movado+Watches http://www.jewelerslounge.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From a.harrowell at gmail.com Thu Nov 22 17:47:12 2007 From: a.harrowell at gmail.com (TYR) Date: Thu, 22 Nov 2007 14:47:12 -0800 (PST) Subject: Python web frameworks References: <226020ef-3955-43e8-b1f6-2ba9ba43d45e@c29g2000hsa.googlegroups.com> <5qga2mFvuljgU1@mid.uni-berlin.de> <160f8bbc-70be-4dcb-8874-de72588c1d10@d61g2000hsa.googlegroups.com> <1b343163-e755-44f8-b5c3-4af56c61e817@c29g2000hsa.googlegroups.com> <93a92a82-cf3c-4ebb-a93f-180374e5f75a@e4g2000hsg.googlegroups.com> <00c0167e-3b4c-4476-b473-1f938a54db63@e1g2000hsh.googlegroups.com> Message-ID: <2672de28-2c94-4967-83f5-18f2823492ee@b15g2000hsa.googlegroups.com> Perhaps we need a pythonic FRONTEND. If you're meant to be able to run java code in a browser vm; and flash; and javascript...why not a reduced version of python? I'm thinking a sandboxed interpreter, perhaps based on EmbeddedPython, and a restricted set of classes; core logic, string and maths, some good graphics stuff (perhaps similar to nodebox), SSL support, filesystem access to a cache, network, xml, soap support. A standard model for development defining graphic entities on one hand, and controls on the other that the graphics are bound to. Perhaps a single class for "RemoteControls" covering web service calls intended to be bound to a graphical entity at one end and a mod_python function at the other? Force pre-compiling into .pyc; include an app to do interactive interpreter in a browser and some basic IDE functions with each plugin download. From davisn90210 at gmail.com Tue Nov 20 16:09:54 2007 From: davisn90210 at gmail.com (davisn90210 at gmail.com) Date: Tue, 20 Nov 2007 13:09:54 -0800 (PST) Subject: Create thumbnail image (jpg/png) of PDF file using Python References: <104837c4-898a-4f67-98ab-37df8ff76f0f@e25g2000prg.googlegroups.com> Message-ID: <59684142-059d-4882-b6a3-c8518f73c664@l1g2000hsa.googlegroups.com> On Nov 20, 11:36 am, sophie_newbie wrote: > Is there any way to do this directly within python? > > If not is there any other good way to achieve it? > > Thanks in advance for any help! Take a look at PIL -- http://www.pythonware.com/products/pil/. Among other things, it allows you to easily create thumbnails. --Nathan Davis From rhamph at gmail.com Fri Nov 9 12:52:34 2007 From: rhamph at gmail.com (Rhamphoryncus) Date: Fri, 09 Nov 2007 17:52:34 -0000 Subject: Using python as primary language In-Reply-To: References: <1194508354.226023.232050@v3g2000hsg.googlegroups.com> <1194561005.427982.263160@s15g2000prm.googlegroups.com> <004801c8225e$49843350$dc8c99f0$@com> <4866bea60711081538m2b24ab48v3d223adca8b4bd7c@mail.gmail.com> <004901c82264$3b10f460$b132dd20$@com> <878x57yd2s.fsf@mulj.homelinux.net> Message-ID: <1194630754.747825.318560@t8g2000prg.googlegroups.com> On Nov 9, 9:14 am, "Chris Mellon" wrote: > The heavy use of dicts is one of the problems - they're all over the > place and even if you removed the GIL, a "global dict lock" would give > essentially the same effect. And a per-dict lock means that there will > be a *lot* more locking and unlocking, which means a slower > interpreter. It's worse than that. Not only are they slower for a single thread, but when using multiple threads the cores will contend over the cache lines containing the locks, leaving you yet slower still! I've starting putting together a site explaining my approach to solving these problems: http://code.google.com/p/python-safethread/ -- Adam Olsen, aka Rhamphoryncus From davisn90210 at gmail.com Tue Nov 13 17:23:40 2007 From: davisn90210 at gmail.com (davisn90210 at gmail.com) Date: Tue, 13 Nov 2007 22:23:40 -0000 Subject: NumPy Question - numpy.put in multi-dimensional array In-Reply-To: <1194981752.080834.255380@19g2000hsx.googlegroups.com> References: <1194981752.080834.255380@19g2000hsx.googlegroups.com> Message-ID: <1194992620.093152.117630@d55g2000hsg.googlegroups.com> On Nov 13, 1:22 pm, "Bryan.Fodn... at gmail.com" wrote: > from numpy import * > > a = zeros((2,40), int) > > fields = {} > field = 10 > fields[field] = '30A', 5 > > iy = int(fields[field][1]) > ix = int(fields[field][0].rstrip('AB')) > > for i in range(2): > for j in range(iy): > # put(a,[39 - j],[1]) #1d > > Can someone help me figure out how I would do it for multiple rows? > > I thought, > > put(a,[i][39-j],[1]) > > but, > > Traceback (most recent call last): > put(a,[i][39 - j],[1]) > IndexError: list index out of range Try put(a, [(i, 39-j)], [1] Note, however, that in this case you could just as easily use a[i, 39-j] = 1 instead. --Nathan Davis From donn.ingle at gmail.com Mon Nov 5 05:41:49 2007 From: donn.ingle at gmail.com (Donn Ingle) Date: Mon, 05 Nov 2007 12:41:49 +0200 Subject: parsing string to a list of objects - help! References: <1194254785.718898.256060@o80g2000hse.googlegroups.com> Message-ID: Wow Paul, you have given me much to chew. I'll start testing it in my slow way -- it looks so simple! Thank you. \d From arkanes at gmail.com Fri Nov 2 17:32:27 2007 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 2 Nov 2007 16:32:27 -0500 Subject: error ...1 value to unpack In-Reply-To: References: Message-ID: <4866bea60711021432v2e878a2dpd3944c4f8c14d669@mail.gmail.com> On Nov 2, 2007 3:04 PM, Beema shafreen wrote: > hi everybody, > i have a file: > > A_16_P21360207#304 > A_14_P136880#783 > A_16_P21360209#795 > A_16_P21360210#173 > A_16_P03641959#1177 > A_16_P03641960#1944 > A_16_P03641962#999 > A_16_P41563648#-31 > A_16_P03641963#3391 > A_16_P41563649#3626 > A_16_P03641964#180 > A_16_P41563655#1216 > A_16_P03641965#1170 > A_16_P03641966#194 > A_16_P21360229#290 > A_16_P03641967#425 > A_16_P21360231#1091 > A_16_P03641968#1167 > A_16_P03641969#421 > A_16_P03641970#63 > A_16_P21360234#290 > A_16_P21360235#289 > A_16_P03641971#398 > A_16_P21360237#418 > A_16_P03641972#122 > A_16_P21360239#16 > A_16_P03641973#2187 > A_16_P41563669#2881 > A_16_P03641974#1101fh = open('complete_span','r') > data = fh.readline().split('#') > old_probe = data[0].strip() > old_value = data[1].strip() > #print old_probe, old_value > count = 1 > while fh: > current_probe, current_value = fh.readline().strip().split('#')[0:2] > probe =current_probe.strip() > value = current_value.strip() > if old_value > value: > res_value='%s\t%s'%(old_value, old_probe) > print res_value > if count == 244000: > break > old_probe,old_value =probe, value > fh.close() > and i face this error:Traceback (most recent call last): > File "count_values.py", line 8, in > current_probe, current_value = fh.readline().strip().split('#')[0:2] > ValueError: need more than 1 value to unpack > > > why do i get this what is the solution for this.... > regards > shafreen > One of your lines doesn't have a # in it, so split is returning a one element list. From zhushenli at gmail.com Tue Nov 13 00:33:33 2007 From: zhushenli at gmail.com (Davy) Date: Mon, 12 Nov 2007 21:33:33 -0800 Subject: Define key in nlargest() of heapq? In-Reply-To: <1194924787.678372.129870@y27g2000pre.googlegroups.com> References: <1194922587.656458.228340@e34g2000pro.googlegroups.com> <1194924787.678372.129870@y27g2000pre.googlegroups.com> Message-ID: <1194932013.686706.62430@y27g2000pre.googlegroups.com> Hi Raymond, Your code work well, thank you :) Best regards, Davy On Nov 13, 11:33 am, Raymond Hettinger wrote: > On Nov 12, 6:56 pm, Davy wrote: > > > I have a dictionary with n elements, and I want to get the m(m<=n) > > keys with the largest values. > > > For example, I have dic that includes n=4 elements, I want m=2 keys > > have the largest values) > > dic = {0:4,3:1,5:2,7:8} > > So, the the largest values are [8,4], so the keys are [7,0]. > > > How to do this by nlargest() of heapq? I have tried > > nlargest(2,dic,key), > > Try this: > > >>> from heapq import nlargest > >>> dic = {0:4,3:1,5:2,7:8} > >>> from operator import itemgetter > >>> nlargest(2, dic, dic.__getitem__) > > [7, 0] > > Raymond From hniksic at xemacs.org Tue Nov 27 18:21:38 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Wed, 28 Nov 2007 00:21:38 +0100 Subject: Global variables within classes. References: <4734b3d4$0$5462$426a34cc@news.free.fr> <1194687103.483318.20370@s15g2000prm.googlegroups.com> <5pm3oiFri447U1@mid.uni-berlin.de> <5pm8loFri447U3@mid.uni-berlin.de> <63128071-931a-49b2-a9cd-2ccb2a9f4202@t47g2000hsc.googlegroups.com> Message-ID: <87lk8j2s1p.fsf@mulj.homelinux.net> Kevac Marko writes: > When changing default value, is there any way to change class > attribute and all referenced attributes too? > > class M: > name = u"Marko" > > a, b = M(), M() > a.name = u"Kevac" > print M.name, a.name, b.name > -> Marko Kevac Marko > > Is there any way to get here -> Kevac Kevac Kevac ? > Or what is the right way of keeping global variables in classes? Simply assign to M.name instead of to a.name. Assigning to a.name creates an a-specific attribute that overrides the global one. If you insist on being able to assign to a.name to change M.name, look up "descriptors" -- but that feels like fighting the language. From greg at cosc.canterbury.ac.nz Fri Nov 23 20:05:18 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Sat, 24 Nov 2007 14:05:18 +1300 Subject: foldr function in Python In-Reply-To: <5qnkuqF10t5hgU2@mid.uni-berlin.de> References: <9bf5a2bb-eac7-4859-a5de-b1e84573c77a@t47g2000hsc.googlegroups.com> <0d8c76de-3510-4711-959a-34aad4a33acd@r60g2000hsc.googlegroups.com> <5qnkuqF10t5hgU2@mid.uni-berlin.de> Message-ID: <5qpbv9F10sforU1@mid.individual.net> Marc 'BlackJack' Rintsch wrote: > The name is definitely not so good because there is a `foldr` in Haskell > that just works like `reduce()`. Because currying is ubiquitous in Haskell, you can use the same function in either a curried or non-curried fashion. But in Python you need different functions for the different usage styles. My feeling is that Python shouldn't provide a bunch of different versions of the same function that differ only in the degree of currying. If you want a particular curried combination, it's easy enough to create it as needed using lambda, nested functions or partial(). -- Greg From billy.omahony at gmail.com Mon Nov 12 07:56:22 2007 From: billy.omahony at gmail.com (billy.omahony at gmail.com) Date: Mon, 12 Nov 2007 04:56:22 -0800 Subject: PyGilState_Ensure interrupts python critical sections Message-ID: <1194872182.400646.234820@d55g2000hsg.googlegroups.com> Hi, I have a native windows thread in a c python module which calls into python code and adds an item to a data structure (a home-grown circular buffer). At the same time my main python application is removing items from this data structure. Unlike native python containers adding and removing items from the circular buffer is not atomic. So I need to put access to it in a critical section. Using threading.Lock will work for native python threads competing for access. But when access is from a windows thread this will not work. That is because my call to PyGilState_ensure will preempt my native python thread ***even when it is inside the critical section***. What is going on looks something like this (I think). Py Python Windows Py threading.Lock resource Sched Thread Thread Code | | | | | | | |Go (GIL)# | | | | | # | | | | | # | | | | | #...Doit.....|...........>| | | | # | |. acquire...>| | |<-PyGILState_Ensure--| | | | | ... ... ... ... |Stop # |-------`| | |----Ensure rtns-----># PyObject_ | | | : |CallMethod | | | | : |.(Doit)...> |. acquire...>| DEADLOCK | : : :.how does python thread tell PyScheduler not to give away Gil until we are done with critical section?? So my question is how in python do I tell the scheduler not to prempt the current python thread. Especially how to tell it not to give the GIL to any calls to PyGILState_ensure until further notice (i.e. until I am outside my critical section?? It sounds like a reasonable request - surely this exists already but I can't find it. One thing that may work (though the documentation does not specifically say so) is using setcheckinterval() to set the check interval to a very large value, acessing my shared structure and then setting the check interval back to the previous value. Provided my access to the shared structure takes less byte codes than what I set checkinterval to I should be okay. However that would be very dependant on the exact fine detail of how the check interval works and may not be compatible with other Python releases Maybe someone familiar with the python source code would know for sure? I am using Python 2.4.3 on windows XP. Thanks for any help/suggestions offered! BR, Billy. From rhamph at gmail.com Mon Nov 12 12:41:17 2007 From: rhamph at gmail.com (Rhamphoryncus) Date: Mon, 12 Nov 2007 17:41:17 -0000 Subject: Using python as primary language In-Reply-To: References: <1194508354.226023.232050@v3g2000hsg.googlegroups.com> <1194652106.191133.295200@e9g2000prf.googlegroups.com> Message-ID: <1194889277.378649.141000@v29g2000prd.googlegroups.com> On Nov 12, 2:28 am, "Martin Vilcans" wrote: > On Nov 10, 2007 12:48 AM, Rhamphoryncus wrote: > > > On Nov 9, 1:45 pm, "Terry Reedy" wrote: > > > 2. If micro-locked Python ran, say, half as fast, then you can have a lot > > > of IPC (interprocess communition) overhead and still be faster with > > > multiple processes rather than multiple threads. > > > Of course you'd be faster still if you rewrote key portions in C. > > That's usually not necessary though, so long as Python gives a roughly > > constant overhead compared to C, which in this case would be true so > > long as Python scaled up near 100% with the number of cores/threads. > > > The bigger question is one of usability. We could make a usability/ > > performance tradeoff if we had more options, and there's a lot that > > can give good performance, but at this point they all offer poor to > > moderate usability, none having good usability. The crux of the > > "multicore crisis" is that lack of good usability. > > Certainly. I guess it would be possible to implement GIL-less > threading in Python quite easily if we required the programmer to > synchronize all data access (like the synchronized keyword in Java for > example), but that gets harder to use. Am I right that this is the > problem? > > Actually, I would prefer to do parallell programming at a higher > level. If Python can't do efficient threading at low level (such as in > Java or C), then so be it. Perhaps multiple processes with message > passing is the way to go. It just that it seems so... primitive. What you've got to ask is "what is a message?" Can you define your own class and use it as a message? Doing so seems very useful. If you allow that you end up with something like Concurrent Pascal's monitors (which enforce their boundary, so they lack the memory model needed by java or C.) Once you make message passing easy to use you end up with something that looks very much like threads anyway, just lacking the shared- state and the resulting memory model. -- Adam Olsen, aka Rhamphoryncus From gert.cuykens at gmail.com Fri Nov 2 12:24:50 2007 From: gert.cuykens at gmail.com (gert) Date: Fri, 02 Nov 2007 16:24:50 -0000 Subject: new style class In-Reply-To: <472b3caa$1_3@news.bluewin.ch> References: <1194002609.296417.111050@v3g2000hsg.googlegroups.com> <1194004712.691884.249570@v3g2000hsg.googlegroups.com> <472b3caa$1_3@news.bluewin.ch> Message-ID: <1194020690.132021.200010@o80g2000hse.googlegroups.com> On Nov 2, 4:04 pm, Boris Borcic wrote: > gert wrote: > > Could not one of you just say "@staticmethod" for once damnit :) > > I did, did I not ? i am sorry, yes you did :) From m.uebelacker at googlemail.com Thu Nov 29 06:03:06 2007 From: m.uebelacker at googlemail.com (Mathias Uebelacker) Date: Thu, 29 Nov 2007 12:03:06 +0100 Subject: wxPython and Tkinter In-Reply-To: <0be0b410-c53b-4b1a-9a30-1c9e76faae61@g30g2000hsb.googlegroups.com> References: <0be0b410-c53b-4b1a-9a30-1c9e76faae61@g30g2000hsb.googlegroups.com> Message-ID: Hello, take a look here [1]. I think its a got place to start. br Mathias [1] http://sebsauvage.net/python/gui/#import 2007/11/29, whatazor : > > Hi all, > I migrate some code from tkinter to wxpython. I need the equivalent > Tkinter method Tkinter.Tk.after > in wxPython, but I'm not able to find it. It exist or there are other > trick to emulate it? > > thank you > w > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Sat Nov 17 02:30:43 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 17 Nov 2007 07:30:43 -0000 Subject: Interfaces. References: <1ecf1cca-f05f-44b5-8128-a93208815f15@y5g2000hsf.googlegroups.com> Message-ID: <13jt653h3rr554@corp.supernews.com> On Fri, 16 Nov 2007 21:13:17 -0800, Chris M wrote: >> > Status: Rejected >> >> Thank you for pointing out the obvious. But *truly* helpful would be >> insight into "While at some point I expect that Python will have >> interfaces." Look for that sentence under the "rejected" part. >> >> James >> >> -- >> James Stroud >> UCLA-DOE Institute for Genomics and Proteomics Box 951570 >> Los Angeles, CA 90095 >> >> http://www.jamesstroud.com > > Then answer his question yourself instead of wasting everyones bandwidth > going on some moral crusade. There's something to be said about users > with signatures longer than their messages... Speaking of wasting bandwidth, please snip out the parts of the post you're replying to that are no longer relevant. Also, you may notice that James *did* answer the question, pointing out the relevant parts of the PEP that you neglected to mention. Note too that James' signature is seventy-three characters SHORTER than his message. There's something to be said about users who, having made an unhelpful and almost pointless post, then follow it up by spewing venom and bile at the person who made a gentle and reasonable comment about that unhelpfulness. I guess some people just can't take criticism, no matter how well-founded or how gently it is put. -- Steven. From steve at REMOVE-THIS-cybersource.com.au Sat Nov 17 03:18:10 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 17 Nov 2007 08:18:10 -0000 Subject: overriding methods - two questions References: <473dd35a$0$7999$426a34cc@news.free.fr> <13js4tebjlucv16@corp.supernews.com> Message-ID: <13jt8u2r3l8in30@corp.supernews.com> On Sat, 17 Nov 2007 06:47:18 +0200, Donn Ingle wrote: >>> While technically possible (using inspect.getargspec), trying to make >>> your code idiot-proof is a lost fight and a pure waste of time. > >> Worse: it's actually counter-productive! The whole idea of being able >> to subclass a class means that the user should be able to override >> foo() *including* the signature. > > Steven, > In this case, the def in question is named Draw. It's args are context > and > framenumber. The body is 'pass'. I want users to use the exact signature > (but they can change the varnames to suit) because the draw() method is > *not* being called by the user but *by* my API (in a timeout loop). You don't know that. How can you possibly guarantee that the user won't find some other use for the draw() method as well as passing it to your API? Maybe your application turns out to be a huge success, and people start extending it in all sorts of ways you never ever imagined -- or at least they would if you didn't needlessly lock down the classes they can use. Or, if you can't imagine that, imagine that in six months time *you* decide to extend the application, and have another purpose for that same draw() callback, but need a slightly different signature. Which suggests that maybe your API should specify keyword arguments rather than positional args. That way you can do something like this: # (I'm guessing) in the main video editing loop: blah.Draw(context=cario.context, frame=currentFrame) # we want to display the third frame as we draw blah.Draw(context=another_context, frame=3, window=preview) # don't forget to flip the title frame blah.Draw(flip=True, context=cairo.context, frame=title) BTW, it is a convention for method names to be lower case, and classes to be Title case. Seeing something like obj.Draw, most(?) Python developers will expect that the Draw attribute of obj is itself a class: >>> class MyClass(object): ... class Draw(object): ... pass ... >>> x = MyClass() >>> x.Draw -- Steven. From gagsl-py2 at yahoo.com.ar Fri Nov 2 20:32:34 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 02 Nov 2007 21:32:34 -0300 Subject: Assertion for python scripts References: <1194027247.325466.14300@o80g2000hse.googlegroups.com> <1194033192.175104.130440@q5g2000prf.googlegroups.com> Message-ID: En Fri, 02 Nov 2007 16:53:12 -0300, matthias escribi?: > On Nov 2, 12:12 pm, "Matt McCredie" wrote: >> On 11/2/07, matthias wrote: >> >> > I know that "-O" turns off assertions in general. However, how do I >> > pass thus parameter to >> > python to an executable script ? >> Use: >> python -O -mcompileall path >> > This indeed creates a file with the name assert.pyo. That must be the > optimized one. > > Now I try this: > > # ./assert.py > Traceback (most recent call last): > File "./assert.py", line 3, in ? > assert 1 > 1, "ASSERTTION !" > AssertionError: ASSERTTION ! > > Ok, so it still uses the unoptimized version. > > Now I try this: > > # chmod 755 assert.pyo > # ./assert.pyo > bash: ./assert.pyo: cannot execute binary file > > Here is my problem: I want to have an optimized executable version of > assert.py. Move all your code into modules; those modules can be pre-compiled with -O as above. Your main script should contain just a few lines; import the other modules from inside your main script. When you import "foo", if python finds "foo.pyo" and it's up to date, it will use it instead of foo.py; foo.py doesn't have to be available either. -- Gabriel Genellina From haraldarminmassa at gmail.com Tue Nov 27 14:09:47 2007 From: haraldarminmassa at gmail.com (GHUM) Date: Tue, 27 Nov 2007 11:09:47 -0800 (PST) Subject: create pywintypes.CreateGuid() compatible guids on Linux ? Message-ID: <40dcb955-5884-4a0e-88d5-0c526ad6c934@x69g2000hsx.googlegroups.com> Hello, I created lots of guids via pywintypes.CreateGuid() on windows. Now I would like to run the same software on Linux / Solaris / FreeBSD. So I should produce "compatible" GUIDS on that systems. "compatible" having the meaining: "Providing similiar likelehood of collisions". of course "google python guid" leads directly to http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/163604, but ... will it blend? any ideas what could help me to research? Harald From martin at v.loewis.de Mon Nov 26 23:17:54 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 27 Nov 2007 05:17:54 +0100 Subject: Installing Python 3000 on Leopard (Mac OS) fails... In-Reply-To: References: Message-ID: <474B9A72.3060806@v.loewis.de> > gcc -fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno-fused- > madd -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include - > DPy_BUILD_CORE -c ./Modules/posixmodule.c -o Modules/posixmodule.o > ./Modules/posixmodule.c: In function 'posix_setpgrp': > ./Modules/posixmodule.c:3769: error: too few arguments to function > 'setpgrp' > make: *** [Modules/posixmodule.o] Error 1 > > Any suggestions? This is a known bug: http://bugs.python.org/issue1358 Apparently, Apple has managed to change the header files of Leopard in a way that breaks building Python, and also managed to break the autoconf procedure that was designed to deal with the uncertainty of the setpgrp declaration. An expert of OSX will need to look into this and propose a solution; if you think you need to get this working, just remove setpgrp from posixmodule. Regards, Martin From mike5160 at gmail.com Wed Nov 21 11:17:05 2007 From: mike5160 at gmail.com (mike5160) Date: Wed, 21 Nov 2007 08:17:05 -0800 (PST) Subject: Fwd: Formatting question. References: Message-ID: On Nov 20, 9:13 pm, "Sergio Correia" wrote: > Hey Mike, > Welcome to Python! > > About your first issue, just change the line > outfile.write( "'%s'," % (LoL[x][y])) > With > outfile.write( "'%s'," % (LoL[x][y][:-1])) > > Why? Because when you do the line.split, you are including the '\n' at > the end, so a new line is created. > > Now, what you are doing is not very pythonic (batteries are included > in python, so you could just use the CSV module). Also, the for x in > range(len(somelist)) is not recommended, you can just do something > like: > > ======================== > import csv > > infile = open("mydata.txt", "rb") > outfile = open("out.txt", "wb") > > reader = csv.reader(infile, delimiter='\t') > writer = csv.writer(outfile, quotechar=None, delimiter = "\\") > > for row in reader: > data = "'" + "', '".join(row) + "'" > base = " ( Insert NBUSER.Grochamber Values %s, )" > writer.writerow([base % data]) > > infile.close() > outfile.close() > ======================== > The above lines works like your program, writing exactly what you asked. > Again, all lists are iterable, you don't need to iterate an integer > from 1 to len(list). (isn't python wonderful?) > > HTH, > Sergio > > On Nov 20, 2007 6:11 PM, mike5160 wrote: > > > Hi all, > > > My input file looks like this : ( the data is separated by tabs ) > > > 11/26/2007 56.366 898.90 -10.086 23.11 1212.3 > > 11/26/2007 52.25 897.6 -12.5 12.6 13333.5 > > 11/26/2007 52.25 897.6 -12.5 12.6 133.5 > > > The output I'm trying to get is as follows : > > > ( Insert NBUSER.Grochamber Values > > '11/26/2007','56.366','898.90','-10.086','23.11','1212.3', ) > > ( Insert NBUSER.Grochamber Values > > '11/26/2007','52.25','897.6','-12.5','12.6','13333.5', ) > > ( Insert NBUSER.Grochamber Values > > '11/26/2007','52.25','897.6','-12.5','12.6','133.5', ) > > > The following is the program i have written so far : > > > LoL = [] > > > for line in open('mydata.txt'): > > LoL.append(line.split("\t")) > > > print "read from a file: ", LoL, > > > outfile = open("out.dat", "w") > > > lilength = len(LoL) > > liwidelength = len(LoL[1]) > > > print "length of list is " , lilength, "long" > > print "length of list is " , liwidelength, "long" > > > for x in range(lilength): > > outfile.write(" ( ") > > outfile.write('Insert NBUSER.Grochamber Values ') > > for y in range(liwidelength): > > outfile.write( "'%s'," % (LoL[x][y])) > > outfile.write(" ) \n") > > > outfile.close() > > > I have 3 questions : > > > 1. The formatting in the first line comes out wrong all the time. I m > > using windows python 2.5.1. The last part of the first line is always > > on the second line. > > > 2. How do I avoid the "," symbol after the last entry in the line? > > (this are supposed to be sql-queries - importing excel based tabbed > > data to sql database) > > > 3. What do I do when the data is missing? Like missing data? > > > Thanks for all your help! > > > Mike > > > -- > >http://mail.python.org/mailman/listinfo/python-list76 HI Sergio, First of all, thanks for your reply and yes I'm new to Python. Did a google on CSV and I am reading the documentation about it right now. In the post I mentioned I was using Windows. I also have a laptop with linux installed on it. When I ran the same program on my linux laptop I did see the \n included in the list. Somehow, I did not see it on windows, or missed it. So that cleared up the first problem. Also, I will be doing a lot of this data importing from excel etc. can you point me to a tutorial/document/book etc. where I can find snippets of using various python utilities. For eg. something which has the sample for using "line.split("\t") " or " outfile.write( "'%s'," % (LoL[x][y][:-1])) " , explaining the various options available. The default "Idle gui help" is not too informative to a newbie like me. Thanks again for your reply, Mike. From donn.ingle at gmail.com Fri Nov 16 07:40:34 2007 From: donn.ingle at gmail.com (Donn Ingle) Date: Fri, 16 Nov 2007 14:40:34 +0200 Subject: Looking for docs Message-ID: Hi, I have seen strange looking things in various Python code like: staticmethod and also lines starting with an @ sign, just before method defs - I can't find an example right now. I have Python 2.5 installed with it's docs, but I can't find any discussion of 'new style' classes and other info. I'm not even sure what subject that @ sign stuff falls under. Anyone have a link? /d From mail at timgolden.me.uk Thu Nov 15 11:21:17 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 15 Nov 2007 16:21:17 +0000 Subject: Volume id In-Reply-To: References: <473C2B2E.8060705@shopzeus.com> Message-ID: <473C71FD.9040002@timgolden.me.uk> Gabor Urban wrote: > OK, you are right... Problem was not precise enough. I need to process CDs > to create a list. Does it ring a bell for you? On Windows, at least, you can do this with WMI: import win32com.client wmi = win32com.client.GetObject ("winmgmts:") for result in wmi.ExecQuery ( """SELECT VolumeSerialNumber FROM Win32_LogicalDisk WHERE DriveType=5""" ): print result.Properties_ ("VolumeSerialNumber") If you do anything non-trivial with WMI, I recommend my WMI module: http://timgolden.me.uk/python/wmi.html TJG From steven at REMOVE.THIS.cybersource.com.au Wed Nov 21 22:12:19 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 22 Nov 2007 03:12:19 -0000 Subject: eof References: <92a2c0c9-e6a1-4344-aeac-830940200f20@t47g2000hsc.googlegroups.com> Message-ID: On Wed, 21 Nov 2007 15:17:14 -0800, braver wrote: > I'd like to check, for a filehandle f, that EOF has been reached on it. > What's the way to do it? I don't want to try/except on EOF, I want to > check, after I read a line, that now we're in the EOF state. Why? For some file-like objects, the OS can't tell if you're at EOF until you actually try to read. The usual way to deal with EOF in Python is not to bother. fp = open("filename", "r") for line in fp: do_something_with(line) # When we exit the loop, we're at EOF. What are you doing that needs more hands-on control? -- Steven. From tim at tdw.net Tue Nov 27 19:26:17 2007 From: tim at tdw.net (Tim Williams) Date: Wed, 28 Nov 2007 00:26:17 +0000 Subject: Pulling data from a .asps site In-Reply-To: References: Message-ID: <9afea2ac0711271626p150ff391pf4d96c33fce22dc1@mail.gmail.com> On 27/11/2007, hall.jeff at gmail.com wrote: > There's a government website which shows public data for banks. We'd > like to pull the data down programmatically but the data is "hidden" > behind .aspx... > > Is there anyway in Python to hook in directly to a browser (firefox or > IE) to do the following... > > 1) Fill the search criteria > 2) Press the "Search" button > 3) Press another button (the CSV button) on the resulting page > 4) Then grab the data out of the notepad file that pops up > > If this is a wild good chase, let me know... (or if there's a better > way besides Python... I may have to explore writing a firefox plug-in > or something)... Amongst others, IEC will allow you to open an IE browser window, navigate around sites (including pushing buttons), and retrieve text. http://www.mayukhbose.com/python/IEC/index.php HTH :) From zhushenli at gmail.com Wed Nov 14 02:51:57 2007 From: zhushenli at gmail.com (Davy) Date: Wed, 14 Nov 2007 07:51:57 -0000 Subject: function call problem in class? Message-ID: <1195026717.343184.33900@i38g2000prf.googlegroups.com> Hi all, I have write a simple class, I want the function two() to call private function __one(), but there is an error : NameError: global name '_simple__one' is not defined, how to work around it class simple: def __one(self): print "Hello" def two(self): __one() print "world" if __name__ == '__main__': s = simple() s.two() Any suggestion is welcome! Best regards, Davy From chris.monsanto at gmail.com Sat Nov 17 00:13:17 2007 From: chris.monsanto at gmail.com (Chris M) Date: Fri, 16 Nov 2007 21:13:17 -0800 (PST) Subject: Interfaces. References: <1ecf1cca-f05f-44b5-8128-a93208815f15@y5g2000hsf.googlegroups.com> Message-ID: On Nov 16, 12:26 am, James Stroud wrote: > Chris M wrote: > > On Nov 15, 8:55 pm, "PeterBrad... at googlemail.com" > > wrote: > >> Hi, > > >> Does anyone know what the state of progress with interfaces for python > >> (last I can see ishttp://www.python.org/dev/peps/pep-0245/) > > >> I would argue that interfaces/(similar feature) are necessary in any > >> modern language because they provide a way of separating the > >> specification from the implementation of a module. > > >> I also had a new idea - when specifying the functionality of a module, > >> it would be nice to combine examples of valid behaviour / some sort of > >> testing. > > >> It might therefore be possible to combine unit testing with > >> interfaces. > > >> What do you all think? > > >> Peter > >> (new to python so be nice :) > > > Status: Rejected > > Thank you for pointing out the obvious. But *truly* helpful would be > insight into "While at some point I expect that Python will have > interfaces." Look for that sentence under the "rejected" part. > > James > > -- > James Stroud > UCLA-DOE Institute for Genomics and Proteomics > Box 951570 > Los Angeles, CA 90095 > > http://www.jamesstroud.com Then answer his question yourself instead of wasting everyones bandwidth going on some moral crusade. There's something to be said about users with signatures longer than their messages... From duncan.booth at invalid.invalid Fri Nov 23 03:45:14 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 23 Nov 2007 08:45:14 GMT Subject: Function stopping a function References: Message-ID: Sorin Schwimmer wrote: > For instance, lenghty_function() executes, when an > external event triggers cancel(), which is supposed to > abruptly stop lengthy_function(), reset some variables > and exit immediately. > def lenghty_function(some, arguments, abort=lambda: False): while not abort(): do some part of the function then you just pass in whatever abort function is appropriate: it can check some flag to see whether the function should continue, or it might just check the current time and return True if the function has been going too long. Just make sure that the badly spelled function calls abort() often. From Colin.Prepscius at morganstanley.com Thu Nov 8 18:30:15 2007 From: Colin.Prepscius at morganstanley.com (Prepscius, Colin (IT)) Date: Thu, 8 Nov 2007 18:30:15 -0500 Subject: Creating a cell 'by hand' In-Reply-To: <004801c8225e$49843350$dc8c99f0$@com> References: <1194508354.226023.232050@v3g2000hsg.googlegroups.com> <1194561005.427982.263160@s15g2000prm.googlegroups.com> <004801c8225e$49843350$dc8c99f0$@com> Message-ID: The last argument to new.function takes a closure, which is a tuple of cell objects. Does anybody know how to create those cell objects 'by hand'? Thanks! Colin -------------------------------------------------------- NOTICE: If received in error, please destroy and notify sender. Sender does not intend to waive confidentiality or privilege. Use of this email is prohibited when received in error. From gnewsg at gmail.com Thu Nov 29 16:17:43 2007 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Thu, 29 Nov 2007 13:17:43 -0800 (PST) Subject: Is os.lstat available on all platforms? Message-ID: <7eea5c47-cf1d-4bc5-8dca-aa0d137cbf66@a35g2000prf.googlegroups.com> Hi there. In a code of mine I'd like to use os.lstat whenever possible. My only concern is if it's available on all platforms. It could be safe using always os.lstat instead of: try: os.lstat except AttributeError: os.stat ...? As far as I know where symlinks are not supported os.lstat should be an alias for os.stat but I'm not 100% sure. From hdante at gmail.com Fri Nov 23 10:07:49 2007 From: hdante at gmail.com (hdante at gmail.com) Date: Fri, 23 Nov 2007 07:07:49 -0800 (PST) Subject: Function stopping a function References: Message-ID: <622401ec-3db7-4dc3-bf5e-e47cb98593d9@w40g2000hsb.googlegroups.com> Note, this only works in Unix systems: import os, signal def long_process(): while True: print "I'm messing with your terminal ! ", def short_process(long_process_id): raw_input('Press [Enter] to kill the bad process') os.kill(long_process_id, signal.SIGKILL) print print 'Hehe !' def main(): print 'Starting two processes (press [Enter]): ' raw_input() pid = os.fork() if (pid != 0): short_process(pid) else: long_process() main() On Nov 23, 2:30 am, Sorin Schwimmer wrote: > Hi All, > > We all know that a function can launch the execution > of another function. How can a function stop the > execution of another function? > > For instance, lenghty_function() executes, when an > external event triggers cancel(), which is supposed to > abruptly stop lengthy_function(), reset some variables > and exit immediately. > > Thanks for your advice > SxN > From pgurumur at gmail.com Thu Nov 8 01:34:14 2007 From: pgurumur at gmail.com (Prabhu Gurumurthy) Date: Wed, 07 Nov 2007 22:34:14 -0800 Subject: help parsing ipv6 addresses and subnets Message-ID: <4732ADE6.8070100@gmail.com> Hello list, I would like to parse IPv6 addresses and subnet using re module in python. I am able to either parse the ipv6 address or ipv6 network but not both using single line. any help appreciated. BTW is there a metacharacter for hex digits. Thanks Prabhu - --------------------------------------------------------------------- #!/usr/bin/env python2.5 # $Id: $ import re, os, Queue, sys from optparse import OptionParser # for debug purposes only import pdb argc = len(sys.argv) (dirname, program) = os.path.split(sys.argv[0]) def error(Message): if Message: global program print "%s: %s" %(program, Message) sys.exit(1) def cisco_parse(FileName): if FileName: fh = None if os.path.exists(FileName): try: fh = open(FileName, "r") except IOError, message: error(message) else: count = 0 flag = True while flag: try: lines = fh.next() except StopIteration: flag = False else: line = lines.strip() rehex = "[A-Fa-f0-9]" # to parse ipv6 address format = \ "((%s{1,4}:?:){1,7}%s{1,4})" %(rehex, rehex) # to parse ipv6 subnet # format = \ # "((%s{1,4}:?:){1,7}%s{1,4}(?=(::/\d{1,3})))" %(rehex, rehex) reip6 = re.compile(format) match = reip6.search(line) if match is not None: tupleLen = len(match.groups()) if tupleLen == 2: print count, match.groups()[0] elif tupleLen == 3: print count, match.groups()[0] + match.groups()[2] count += 1 fh.close() fh = None def ParseCmdLine(): parser = OptionParser(usage="%prog [options]", version="%prog 1.0") parser.add_option("-f", "--filename", help="cisco config to read", dest="file") (options, args) = parser.parse_args() fileName = None if options.file: fileName = options.file if fileName: cisco_parse(fileName) if __name__ == "__main__": if argc <= 1: error("too few arguments, use -h or --help to view all options") else: ParseCmdLine() From gregc at cgl.ucsf.edu Wed Nov 14 14:17:45 2007 From: gregc at cgl.ucsf.edu (Greg Couch) Date: 14 Nov 2007 19:17:45 GMT Subject: webbrowser.open still gives problem with file:// References: Message-ID: "Gabriel Genellina" writes: >En Mon, 12 Nov 2007 16:18:06 -0300, krishnakant Mane > escribi?: >> some days bac I posted a problem about webbrowser.open() not opening >> the file on the local machine. >> I get a few responses and I tryed working it out. >> I also refered to the cookbook example posted on that thread. >> I still can't figure out why >> webbrowser.open("file:///home/krishna/documents/tut.html") does not >> open the file. >> as I mentioned earlier the url in the addressbar of mozilla firefox 3 >> alpha is "file:///home/krishna/"/home/krishna/documents/tut.html" >> which is indeed wrong. >I can think of two alternatives: >1) omit the file: protocol, and just use the absolute file path, like >webbrowser.open("/home/krishna/documents/tut.html") >2) use this recipe > which >lets you display content inside a browser window without requiring a >temporary file. >-- >Gabriel Genellina You didn't say which platform you're on. I found that on older Mac OS X systems that one needs to give file://localhost/path instead of file:///path but the localhost version didn't always work on other platforms. The other thing you need to do is to use Python 2.5's version of webbrowser.py instead of the earlier ones. It's easy to backport and works *much* better. Greg Couch UCSF Computer Graphics Lab From jcd at sdf.lonestar.org Fri Nov 2 11:45:45 2007 From: jcd at sdf.lonestar.org (J. Clifford Dyer) Date: Fri, 2 Nov 2007 11:45:45 -0400 Subject: python newbie In-Reply-To: <472b3e97$0$13759$6e1ede2f@read.cnntp.org> References: <472b2b84$0$13761$6e1ede2f@read.cnntp.org> <1194014916.893875.188770@19g2000hsx.googlegroups.com> <472b3e97$0$13759$6e1ede2f@read.cnntp.org> Message-ID: <20071102154545.GA2439@sdf.lonestar.org> On Fri, Nov 02, 2007 at 11:13:00AM -0400, Jim Hendricks wrote regarding Re: python newbie: > > BartlebyScrivener wrote: > > On Nov 2, 8:51 am, Jim Hendricks wrote: > >> New to python, programming in 15 or so langs for 24 years. > >> > >> Couple of questions the tuts I've looked at don't explain: > > > > Did you look at THE tut? You would seem to be the perfect reader for > > it, because you are already a programmer. > > > > http://docs.python.org/tut/node6.html#SECTION006600000000000000000 > > > > rd > > > > I initially looked at THE tut, and it came across so techy that it's > such a slow read. Therefore, I looked to other tuts that were very easy > reads and could give me the basic lowdown of the language. Problem of > course is the easy read tuts don't get into the details. > > That said, I looked at the section of the tutorial you provided (thanks) > and I am still confused. It specifies a global var cannot be assigned > unless it's specified in the global statement. > > Here's an example of what I am asking: > > def my_function(): > global x > > x = open( .... > > before calling my_function, x does not exist in my program. So, my > question is in my_function, the combination of using the global > statement, then implicitly creating x via assignment to the result of > the open function, is x created in the global namespace? Yes. >>> y Traceback (most recent call last): File "", line 1, in y NameError: name 'y' is not defined >>> def f(): global y y = 123 >>> f() >>> y 123 >>> Remember, the interactive interpreter is your friend. Just type 'python' at the command line and hammer away. (It's even better through a decent IDE). Oh yeah, you have to actually call f before y will get defined. Cheers, Cliff From uzi18 at o2.pl Fri Nov 2 17:30:49 2007 From: uzi18 at o2.pl (Bart.) Date: Fri, 2 Nov 2007 22:30:49 +0100 Subject: Assertion for python scripts In-Reply-To: <1194037662.311760.110850@y42g2000hsy.googlegroups.com> References: <1194027247.325466.14300@o80g2000hse.googlegroups.com> <1194037662.311760.110850@y42g2000hsy.googlegroups.com> Message-ID: <200711022230.50574.uzi18@o2.pl> Friday 02 of November 2007 22:07:42 matthias napisa?(a): > > check this: > > > > python ./assert.pyo > > Yes, I know that this works. Thanx. However, that's not what I was > going for. > > Essentially, I am targeting a build system that allows me to build > debug / release versions > of my Python code. I know how to build the Python code, but how do I > package it so that I > can simply dump it on the test system with either build type and the > same calling interface ? > how about distutils ? look on the egg paskages :) From kyosohma at gmail.com Tue Nov 13 09:10:53 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 13 Nov 2007 14:10:53 -0000 Subject: pyopenglcontext binaries for 2.5 on win32 In-Reply-To: <1194933816.838109.45470@v3g2000hsg.googlegroups.com> References: <1194933816.838109.45470@v3g2000hsg.googlegroups.com> Message-ID: <1194963053.718571.218820@v65g2000hsc.googlegroups.com> On Nov 13, 12:03 am, gz wrote: > no, I don't have them... I need them :) > > I'd like to thank Giovanni Bajo for providing binaries for the various > package dependencies, and geting me going with pyopengl. > > Unfortunately I only menaged to run a basic example, where there's no > animation. The glwindow only get's redrawn when it's resized, moved... > well generally redrawed as a window. > > I would greatly appreciate some hints, about how to process the gui > events in the gl portion, and how to run a continous animation in wx + > pyopengl? > > I suspect the whole thing would be way easier with pyopenglcontext, > but I can't seem to find a binary for python 2.5 > I can't get it to install with mingw and don't have vc currently > installed. If someone has successfully built it, plesase share. > > Although, I think, an example of a running opengl spinning cube, > embedded in some wx menu + buttons, capable of handling, say, mouse > clicks in the glwindow, would work best for me. > > I'm not even that keen on wx. I choose it, purely, on the basis that > wx is generaly brought up here frequenter than qt. > (Didn't qt have some licensing change in the last few months that > could potentially change that?) I would highly recommend that you post this to the wxPython group. I think I saw a similar question about using wx and openGL there in the last couple of weeks. See http://www.wxpython.org/maillist.php I tried to compile it just now, but it requires the .NET SDK (but doesn't say which one). I'm downloading the 2.0 SDK and when I've got it, I'll give it another go. Mike From e at mail Sat Nov 3 11:06:29 2007 From: e at mail (M.O.) Date: Sat, 03 Nov 2007 16:06:29 +0100 Subject: Python IDE References: Message-ID: Simon Pickles wrote: > Hi, > > I have recently moved from Windows XP to Ubuntu Gutsy. > > I need a Python IDE and debugger, but have yet to find one as good as > Pyscripter for Windows. Can anyone recommend anything? What are you all > using? I use Eric. Works very well for me. http://www.die-offenbachs.de/eric/index.html Morten From jdsmith2816 at gmail.com Fri Nov 30 16:14:12 2007 From: jdsmith2816 at gmail.com (JD Smith) Date: Fri, 30 Nov 2007 13:14:12 -0800 (PST) Subject: issue with cookielib.LWPCookieJar Message-ID: <468c2718-0e62-41b2-bf09-cd67f5978594@e25g2000prg.googlegroups.com> Greetings: My cookiejar contains the cookie that I need however when I do cj.save(file) it does not actually save out to the cookies.lwj Does anyone have any clue what would keep this from saving? It CREATED my cookies.lwj file so I know it's not permissions. cookies.lwp: #LWP-Cookies-2.0 test.py: def requestXML(frag, server='US', data=None): import urllib import urllib2 import os.path import cookielib base_urls = { "US":"http://www.wowarmory.com/", "EU":"http://eu.wowarmory.com/", "US_SECURE":"https://www.wowarmory.com/", "EU_SECURE":"https://eu.wowarmory.com/" } COOKIEFILE = 'cookies.lwp' cj = cookielib.LWPCookieJar() if os.path.isfile(COOKIEFILE): cj.load(COOKIEFILE) opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) try: if data is not None: data = urllib.urlencode(data) req = urllib2.Request(base_urls[server] + frag, data) req.add_header('User-agent', 'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.8.1.10) Gecko/20071115 Firefox/2.0.0.10') handle = opener.open(req) except IOError, e: if hasattr(e, 'code'): return 'We failed to open "%s".' % base_urls[server] + frag elif hasattr(e, 'reason'): return "The error object hast he following 'reason' attribute: %s" % e.reason headers = handle.info() xml = handle.read() print xml print headers print data for index, cookie in enumerate(cj): print index, ' : ', cookie From deets at nospam.web.de Thu Nov 1 20:06:58 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 02 Nov 2007 01:06:58 +0100 Subject: PyQt with embedded python in Qt App In-Reply-To: References: <1193924163.660753.179140@o38g2000hse.googlegroups.com> <200711012324.42322.uzi18@o2.pl> <200711012232.02979.phil@riverbankcomputing.co.uk> Message-ID: <5ov81oFof171U1@mid.uni-berlin.de> Bart. schrieb: > Thursday 01 of November 2007 23:32:02 Phil Thompson napisa?(a): >> On Thursday 01 November 2007, Bart. wrote: >>> Thursday 01 of November 2007 15:13:55 Phil Thompson napisa?(a): >>>> On Thursday 01 November 2007, cgrebeld wrote: >>>>> Is it possible for a Qt C++ application, which embeds the python >>>>> interpreter, to import and use PyQt? There can be only one >>>>> QApplication, which is created in the C++ side, so how would I use >>>>> that from the python side? >>>> QtGui.QApplication.instance() >>> What I can do with this pointer? >> It's not a pointer, it's a Python object that wraps the C++ pointer. > > So how to pass this object into embeded python interpreter (executed script)? > Anyone know any example? You don't pass it, you _retrieve_ it in the embedded interpreter by invoking the code given to you. Diez From bignose+hates-spam at benfinney.id.au Thu Nov 8 16:18:25 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 09 Nov 2007 08:18:25 +1100 Subject: Some "pythonic" suggestions for Python References: <5PGdnWmWZIdZ967anZ2dnUVZ_uuqnZ2d@cavtel.net> Message-ID: <87lk98bfmm.fsf@benfinney.id.au> Frank Samuelson writes: > I love Python, and it is one of my 2 favorite > languages. I would suggest that Python steal some > aspects of the S language. I would suggest each of these be discussed in a separate thread, each with a specific Subject field, rather than three loosely-related questions in a single thread. -- \ "People are very open-minded about new things, as long as | `\ they're exactly like the old ones." -- Charles F. Kettering | _o__) | Ben Finney From grante at visi.com Sat Nov 24 19:51:15 2007 From: grante at visi.com (Grant Edwards) Date: Sun, 25 Nov 2007 00:51:15 -0000 Subject: OPLC purchase period extended References: <13kgrdbf8eb7l34@corp.supernews.com> Message-ID: <13khho3mb3pp27e@corp.supernews.com> >>I've ordered mine, but I still haven't gotten an answer on how to sign >>up for the year of free T-Mobile WiFi access that's included in the >>offer. The T-Mobile site says you need a PIN from your "confirmation >>letter". I never I've gotten neither a confirmation letter nor a >>response to the e-mail I sent to OLPC asking about it. :/ > > Given past experience with T-Mobile, you probably need to give them both > social security number and a credit card, so I probably won't take them > up on their "free" offer. I got an e-mail today from the OLPC support staff saying that the PIN would be e-mailed. >>The XO laptop comes with a built-in Python IDE, so everybody on >>c.l.p ought to have one... > > That was more-or-less my reasoning for getting one, but the > clincher was finding out on Tday that my sibling and spouse > had independently decided to get one for my nibling, so I > really needed to get one in order to help them. > > Supposedly with the monochrome screen the battery life is good > enough to use the XO as an eBook reader... I know that was the goal. I read somewhere that they're still working on power-management issues. It's running a tweaked RedHat linux, and the tools to build a custom ROM image are freely available -- including a Qemu-based emulator that lets you run rom images on a simulated XO. The most imporant thing is that the "control" key is to the left of the "A" keay where god intened. Not too surprising when you realized the design was headed by folks from the media lab at MIT. MIT requires everybody to use Emacs, right? -- Grant From ppetrick at gmail.com Tue Nov 20 17:33:35 2007 From: ppetrick at gmail.com (p.) Date: Tue, 20 Nov 2007 14:33:35 -0800 (PST) Subject: mimicking a file in memory References: <3ea3babb-29f1-4950-9d5b-c31f67d4e54a@i29g2000prf.googlegroups.com> <13k6mjapuemsre6@corp.supernews.com> Message-ID: On Nov 20, 2:06 pm, Grant Edwards wrote: > On 2007-11-20, Jarek Zgoda wrote: > > >> Here is my dilemma: I don't want to copy the files into a > >> local directory for mutagen's sake, only to have to remove > >> them afterward. Instead, I'd like to load the files into > >> memory and still be able to hand the built-in "file" function > >> a filename to access the file in memory. > > >> Any ideas on how to do this? > > By "memory" I presume you mean virtual memory? RAM with > disk-blocks as backing store? On any real OS, tempfiles are > just RAM with disk-blocks as backing store. > > Sound similar? The only difference is the API used to access > the bytes. You want a file-I/O API, so you can either use the > extensively tested and and highly optimized filesystem code in > the OS to make disk-backed-RAM look like a file, or you can try > to write Python code that does the same thing. > > Which do you think is going to work faster/better? > > [The kernel is generally better at knowing what needs to be in > RAM than you are -- let it do its job.] > > IOW: just use a temp file. Life will be simple. The bytes > probably won't ever hit the platters (if they do, then that > means they would have the other way too). > > -- > Grant Edwards grante Yow! It's a hole all the > at way to downtown Burbank! > visi.com Thanks all. Grant, are temp files automatically put into ram for all linux distros? at any rate, i could set up ram disk. much better solution than using python...except that i've never done a ram disk before. more reading to do... From grante at visi.com Tue Nov 20 18:14:22 2007 From: grante at visi.com (Grant Edwards) Date: Tue, 20 Nov 2007 23:14:22 -0000 Subject: mimicking a file in memory References: <3ea3babb-29f1-4950-9d5b-c31f67d4e54a@i29g2000prf.googlegroups.com> <13k6mjapuemsre6@corp.supernews.com> Message-ID: <13k6qie8ah5qh64@corp.supernews.com> On 2007-11-20, p. wrote: >> By "memory" I presume you mean virtual memory? RAM with >> disk-blocks as backing store? On any real OS, tempfiles are >> just RAM with disk-blocks as backing store. >> >> Sound similar? The only difference is the API used to access >> the bytes. You want a file-I/O API, so you can either use the >> extensively tested and and highly optimized filesystem code in >> the OS to make disk-backed-RAM look like a file, or you can try >> to write Python code that does the same thing. >> >> Which do you think is going to work faster/better? >> >> [The kernel is generally better at knowing what needs to be in >> RAM than you are -- let it do its job.] >> >> IOW: just use a temp file. Life will be simple. The bytes >> probably won't ever hit the platters (if they do, then that >> means they would have the other way too). > > Grant, are temp files automatically put into ram for all linux > distros? All files are put into ram for all linux distros that use virtual memory. (You'll know if you're not using virtual.) > at any rate, i could set up ram disk. much better solution > than using python...except that i've never done a ram disk > before. more reading to do... You don't have set up a ram disk. You already have one. All your disks are ram disks. It's just that some of them have magnetic platters as backing store so they get preserved during a reboot. On some Linux distros, the /tmp directory is a filesystem without prmanent magnetic backing-store. On others it does have a permanent backing store. If you do a "mount" command, you'll probably see a "filesystem" who's type is "tmpfs". That's a filesystem with no permanent magnetic backing-store[1]. See http://en.wikipedia.org/wiki/TMPFS /tmp might or might not be in a tmpfs filesystem (depends on the distro). In any case, you probably don't need to worry about it. Just call tempfile.NamedTemporaryFile() and tell it you want an unbuffered file (that way you don't have to remember to flush the file after writing to it). It will return a file object: f = tempfile.NamedTemporaryFile(bufsize=0) Write the data to that file object and flush it: f.write(mydata) Pass the file's name to whatever broken library it is that insists on a file name instead of a file-like object: brokenLib.brokenModule(f.name). When you're done, delete the file object: del f NB: This particular approach won't work on Windows. On Windows you'll have to use tempfile.mktemp(), which can have race conditions. It returns a name, so you'll have to create the file, write to it, and then pass the name to the broken module. [1] Tmpfs pages use the swap partition for temporary backing store the same as for all other memory pages. If you're using tmpfs for big stuff, make sure your swap partition is large enough to hold whatever you're doing in tmpfs plus whatever normal swapping capacity you need. ------------------------------demo.py------------------------------ def brokenModule(filename): f = file(filename) d = f.read() print d f.close() import tempfile,os f = tempfile.NamedTemporaryFile(bufsize=0) n = f.name print f,":",n os.system("ls -l %s\n" % n) f.write("hello world") brokenModule(n) del f os.system("ls -l %s\n" % n) ------------------------------demo.py------------------------------ If you run this you'll see something like this: $ python demo.py ', mode 'w+b' at 0xb7c37728> : /tmp/tmpgqSj8p -rw------- 1 grante users 0 2007-11-20 17:11 /tmp/tmpgqSj8p hello world ls: cannot access /tmp/tmpgqSj8p: No such file or directory -- Grant Edwards grante Yow! I want to mail a at bronzed artichoke to visi.com Nicaragua! From ptmcg at austin.rr.com Sat Nov 3 11:49:31 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sat, 03 Nov 2007 08:49:31 -0700 Subject: Is pyparsing really a recursive descent parser? In-Reply-To: References: <5p0dhgFnj4rbU1@mid.uni-berlin.de> <1194007658.200713.178210@57g2000hsv.googlegroups.com> Message-ID: <1194104971.263256.66640@d55g2000hsg.googlegroups.com> On Nov 3, 12:33 am, "Just Another Victim of the Ambient Morality" wrote: > It has recursion in it but that's not sufficient to call it a recursive > descent parser any more than having a recursive implementation of the > factorial function. The important part is what it recurses through... > In my opinion, the rule set I mentioned in my original post: > > grammar = OneOrMore(Word(alphas)) + Literal('end') > > ...should be translated (internally) to something like this: > > word = Word(alphas) > grammar = Forward() > grammar << ((word + grammar) | (word + Literal(end))) > > This allows a recursive search to find the string correct without any > need for "backtracking," if I understand what you mean by that. Couldn't > pyparsing have done something like this? > Dear JAVotAM - This was a great post! (Although I'm not sure the comment in the first paragraph was entirely fair - I know the difference between recursive string parsing and recursive multiplication.) You really got me thinking more about how this recursion actually behaves, especially with respect to elements such as OneOrMore. Your original question is really quite common, and up until now, my stock answer has been to use negative lookahead. The expression you posted is the first time I've seen this solution, and it *does* work. I was all set to write a cocky response on why your expression wouldn't work. I've seen it many times before, where people (usually coming from EBNF experience) implement listOfXs = OneOrMore(x) as: listOfXs = Forward() listOfXs << ( x + listOfXs | x ) Actually, what they usually write is: listOfXs << ( listOfXs + x ) but this sends pyparsing into a recursive tailspin. So I fired up SciTE and copy/pasted your code into the editor and ran it, and it worked just fine - this was a shock! I studied this for a few minutes, and then realized what was happening. First of all, I misread what you posted. You posted this: grammar << ((word + grammar) | (word + Literal(end))) which works. I *thought* you posted this: grammar << ((word + grammar) | word) + Literal(end) which doesn't work. In fact this behaves the same as your original post, except it iterates over the input string's words recursively, vs. repetition ins a for-loop, as is done by OneOrMore. So going back to your working version, I had to see why it works. Initially, the first term in the MatchFirst (the '|' operator creates MatchFirst instances) is just the same, and by grammar referencing itself, it just goes word by word through the input trying to find a match. I'll try to visualize the steps: level "First Second Third end" 1 word grammar 2 word grammar 3 word grammar 4 word grammar <- fails! 4 word end <- fails! (therefore level 3 grammar fails!) 3 word end <-- success!!! grammar has 2 options: to match a word followed by a grammar, or to match a word followed by 'end'. At 4 levels deep into the Forward's recursion, the first option fails, because after parsing "end" as the initial word, there is no more text to try to match against grammar. Level 4's Forward then also tries to match a word followed by 'end', but this fails for the same reason. So at this point, the 4th level Forward fails to match either of its options, so it throws its exception back up to level 3, indicating that the first alternative, word followed by grammar, failed. Level 3 then moves on to see if word followed by the literal 'end' matches, and it does - success! Here's where I am stuck now. In the original grammar that you posted, which you want to render into this behavior, grammar is defined as: grammar = OneOrMore(Word(alphas)) + Literal('end') Unfortunately, when the OneOrMore gets constructed, it does not have any visibility beyond knowing what is to be repeated. Again, here is the data structure that is being built: - And - OneOrMore - Word(alphas) - Literal('end') Only at the level of the And is there any awareness that the OneOrMore is followed by anything, let alone by something which could be misinterpreted as something matching the OneOrMore's repetition expression. Can you suggest a way I could generalize this, so that OneOrMore stops matching before it gets to 'end'? -- Paul From aaron.watters at gmail.com Fri Nov 2 15:36:49 2007 From: aaron.watters at gmail.com (Aaron Watters) Date: Fri, 02 Nov 2007 19:36:49 -0000 Subject: marshal vs pickle In-Reply-To: <1193926370.053580.323560@z9g2000hsf.googlegroups.com> References: <1193838300.998229.33380@v3g2000hsg.googlegroups.com> <1193852239.801436.326320@z24g2000prh.googlegroups.com> <1193858836.163776.31900@o3g2000hsb.googlegroups.com> <1193868648.073348.126810@t8g2000prg.googlegroups.com> <1193926370.053580.323560@z9g2000hsf.googlegroups.com> Message-ID: <1194032209.263041.182520@o38g2000hse.googlegroups.com> On Nov 1, 10:12 am, Aaron Watters wrote: > On Oct 31, 6:10 pm, Raymond Hettinger wrote: > > Alright already. Here is the patched file you want > > http://nucular.sourceforge.net/kisstree_pickle.py This file has been removed. After consideration, I don't want to create the moral hazard that someone might distribute automatically executed malicious code pickled inside a nucular index. If you grabbed it, please destroy it. I'm going back to using marshal. I'd like to thank Raymond and others for motivating me to think this over. The possibilities for abuse are astounding. Honestly, if you download any package containing a pickle: delete it. -- Aaron Watters === How many mice does it take to screw in a light bulb? 2. From Dave.Baum at motorola.com Tue Nov 27 17:59:07 2007 From: Dave.Baum at motorola.com (Dave Baum) Date: Tue, 27 Nov 2007 16:59:07 -0600 Subject: read/write to java socket in python References: Message-ID: Your server program is using readLine(), which will block until a newline is received. The server code does not write a newline, so it is waiting at recv() for data from the server, and the server is still waiting for a newline. If you change the client to do the following, it should work: s.send("Hi Java Server\n"); Dave In article , madsornomads at gmail.com wrote: > Hi all, > > I have a problem with reading from a Java server after I have written > to it - it just hangs. It works fine if I just write to the server and > not try to write. I have read the HOWTO on sockets - and it states > that there is a problem (something about flushing), but not what the > solutions is. Nor do google. Can somebody please help? > > A few lines down you can see the example code that sums up the > problem. Just change the name of the Python HOST-variable. > > Thanks > Mads > > > This is the client in Python: > #! /usr/bin/env python > > import sys > from socket import * > > PORT = 3122 > HOST = 'app-5' > SUCCESS = 'Success' > FAILURE = 'Failure' > > s = socket(AF_INET, SOCK_STREAM) > s.connect((HOST, PORT)) > s.send("Hi Java Server"); > print "Have written, waiting to recieve.." > print s.recv(1014) > s.close() > > And this the server in Java: > import java.io.*; > import java.net.*; > > public class Server{ > public static void main(String args[]){ > > int port = 3122; > int backLog = 50; > > ServerSocket ss = null; > try{ > > InetAddress localhost = > InetAddress.getLocalHost(); > ss = new ServerSocket(port, backLog, > localhost); > while(true){ > final Socket client = ss.accept(); > new Thread(){ > public void run(){ > try{ > > > InputStream is = > client.getInputStream(); > BufferedReader buf = > new BufferedReader(new InputStreamReader(is)); > print(buf.readLine()); > > PrintWriter out = new > PrintWriter(client.getOutputStream()); > out.write("Hi Python > Client."); > out.flush(); > client.close(); > }catch(Exception e) > {print(e);} > } > }.start(); > } > }catch(Exception e){print(e);} > } > > private static void print(Object o){System.out.println(o);} > } From apardon at forel.vub.ac.be Thu Nov 8 09:51:18 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 8 Nov 2007 14:51:18 GMT Subject: Can local function access local variables in main program? References: <1194074297.822435.92380@o3g2000hsb.googlegroups.com> <472c25a8$0$20499$9b622d9e@news.freenet.de> <1194111045.737329.181360@19g2000hsx.googlegroups.com> <13ipkpv4ktr661c@corp.supernews.com> Message-ID: On 2007-11-03, Dennis Lee Bieber wrote: > On Sat, 03 Nov 2007 17:30:45 -0000, Sullivan WxPyQtKinter > declaimed the following in comp.lang.python: > >> Actually I am quite satisfied with and error, which is my expectation. >> But the implicit global variable access seems quite uncomfortable to >> me. Why is that necessary? > > Would you want to have to write things like: Well it would be explicit and explicit is better than implicit. > import os > import os.path > import sys > > def dFunc(more): > return "The full path of the item is: %s" % more > > def aFunc(something): > global os.path > global sys > global dFunc > sys.stdout.write(dFunc(os.path.join("nonsense", something))) > > Your "variable" follows the same logic used for name look ups of all > items -- "read" access will, after exhausting the local scope, search > the module level names (note that you don't need "global" to modify a > mutable object in module level -- it is only the rebinding of the name > itself that needs "global") -- Antoon Pardon From esa.peuha at helsinki.fi Fri Nov 9 19:38:57 2007 From: esa.peuha at helsinki.fi (Esa A E Peuha) Date: 10 Nov 2007 02:38:57 +0200 Subject: Valgrind and Python Message-ID: <86psl3fhr32.fsf@ruuvi.it.helsinki.fi> Running Python 2.5.1 under Valgrind is interesting; just starting it and then pressing Ctrl-D produces this: ==27082== ERROR SUMMARY: 713 errors from 56 contexts (suppressed: 10 from 1) ==27082== malloc/free: in use at exit: 1,243,153 bytes in 508 blocks. ==27082== malloc/free: 3,002 allocs, 2,494 frees, 2,748,487 bytes allocated. ==27082== For counts of detected errors, rerun with: -v ==27082== searching for pointers to 508 not-freed blocks. ==27082== checked 1,399,984 bytes. ==27082== ==27082== LEAK SUMMARY: ==27082== definitely lost: 0 bytes in 0 blocks. ==27082== possibly lost: 17,072 bytes in 58 blocks. ==27082== still reachable: 1,226,081 bytes in 450 blocks. ==27082== suppressed: 0 bytes in 0 blocks. ==27082== Reachable blocks (those to which a pointer was found) are not shown. ==27082== To see them, rerun with: --show-reachable=yes A lot of those 713 errors occur in the various deallocation functions. -- Esa Peuha student of mathematics at the University of Helsinki http://www.helsinki.fi/~peuha/ From jjl at pobox.com Mon Nov 26 12:16:01 2007 From: jjl at pobox.com (John J. Lee) Date: Mon, 26 Nov 2007 17:16:01 GMT Subject: Should proxy objects lie about their class name? References: <87lk8szlnm.fsf@pobox.com> Message-ID: <87d4txudv2.fsf@pobox.com> jjl at pobox.com (John J. Lee) writes: > Not much to add to the subject line. I mean something like this: > > ProxyClass.__name__ = ProxiedClass.__name__ > > > I've been told that this is common practice. Is it? Would this > surprise you if you ran into it in a debugging session? Does nobody have an opinion on this? Pull your socks up, c.l.py! John From martin at v.loewis.de Mon Nov 19 16:19:27 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 19 Nov 2007 22:19:27 +0100 Subject: compiling python 2.5, missing zlib In-Reply-To: References: Message-ID: <4741FDDF.8070505@v.loewis.de> > Neither seems to work. What am I missing here? You forgot to install the zlib header files, which come in an RPM provided by Redhat (probably called zlib-dev or some such). Regards, Martin From pofuk at email.t-com.hr Mon Nov 12 18:15:40 2007 From: pofuk at email.t-com.hr (SMALLp) Date: Tue, 13 Nov 2007 00:15:40 +0100 Subject: Help needed! Message-ID: I'm new in python and i got lost. Ima building an aplication that add's 2 panels and menu bar to the window. So i made base class that makes window, menuBarClass that inherits mainWindowClass. Problem is with PanelClass that would need to inherit MainWindowClass to add panels. So if someone has time to write simple example it would be realy helpfull. From MonkeeSage at gmail.com Sun Nov 18 20:04:47 2007 From: MonkeeSage at gmail.com (MonkeeSage) Date: Sun, 18 Nov 2007 17:04:47 -0800 (PST) Subject: A proposal for attribute lookup failures References: <0eb5426d-3eea-4b8a-93d5-a3b22ff8032a@f3g2000hsg.googlegroups.com> <46b6a6e8-d88c-49f9-ac62-f938a1275172@f3g2000hsg.googlegroups.com> <2e1247b4-8cd2-4004-8efc-6fbe797985ae@f3g2000hsg.googlegroups.com> <57ddf35c-b22a-40ea-88ab-be2ee9e32572@c30g2000hsa.googlegroups.com> Message-ID: <2fa5b30a-2e9b-4da2-9541-04b920cef104@w28g2000hsf.googlegroups.com> On Nov 18, 5:59 pm, Kay Schluehr wrote: > No need to excuse. I think Ruby provides a nice context for discussing > the semantics of top level "open classes". But I think those are > entirely different than your contextual bindings. Note I find your > proposal somewhat confusing since I expect that an attribute is > "owned" by an object and is not an arbitrary contextual property. I obviously like ruby as well as python, I just didn't want to turn the discussion into a "I can do this in ruby, can you do that in python" thread, so my apology was more along those lines that an apology for using ruby at all. :) As far as "ownership" of an object, that's what object abstraction is all about is it not? Multiple instances can "own" a method via polymorphic substitution, without a strict interface definition. My proposal simply adds a new scope within which to look for "ownership". Of course, there are problems with that, as noted above. > Regarding open classes in Python, what about "extension classes"? > > class +object: > def len(self): > return self.__len__() > > This either adds the len method to the namespace of object or it > creates a new namespace which is associated with the namespace of > object s.t. each object can lookup attributes in this namespace when > default lookup fails. I'm not entirely sure about scope. I think the > lifetime of an extension class shall be determined by the lifetime of > the extended class and not by the scope in which the extension class > is defined. What do you think? Sounds like a interesting approach! Worth looking into, imo. > PS. you can use EasyExtend when you want to provide a language > extension without hacking the CPython runtime. EE was made for such > kinds of experiments. Hadn't seen that before, thanks for the reference. :) Regards, Jordan From steve at REMOVE-THIS-cybersource.com.au Fri Nov 9 18:08:52 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Fri, 09 Nov 2007 23:08:52 -0000 Subject: Some "pythonic" suggestions for Python References: <5PGdnWmWZIdZ967anZ2dnUVZ_uuqnZ2d@cavtel.net> <47338e4c$0$30952$426a74cc@news.free.fr> <9qGdnadjs6a76ananZ2dnUVZ_q2hnZ2d@cavtel.net> Message-ID: <13j9q44ea25sf68@corp.supernews.com> On Fri, 09 Nov 2007 11:41:24 -0500, Frank Samuelson wrote: >> The ideas are >> *never* fully thought out or materialized, and they invariably invite >> scorn from the user community. > > Of course, they're thought out: They're stolen from another language. > Specifically, the language in which I am most productive. No, they aren't fully thought out *at all*. To wit: * you've suggested crippling tracebacks, throwing away the most important piece of information they currently provide, just because you don't like the def statement; * you've suggested allowing sequences as indices into lists, completely unaware that your two suggestions for what it should mean are mutually incompatible; * you've suggested getting rid of the slice syntax for no advantage; * you've suggested making the function constructor itself a function, and seem to be completely unaware that your request would need a very different syntax to that Python already uses; * you suggest two different versions for the function constructor, one that is an expression and one that is a suite, but judging by your comments you don't even realize they are two different versions. Need I go on? If you want your suggestions to be taken seriously, you need to think them through carefully. Well-designed programming languages are not like chop suey, where you grab whatever left-overs you have in the fridge and mix them all together because you like the individual ingredients. -- Steven. From simon at brunningonline.net Tue Nov 6 11:57:13 2007 From: simon at brunningonline.net (Simon Brunning) Date: Tue, 6 Nov 2007 16:57:13 +0000 Subject: python equivalent to heckle In-Reply-To: <1194366154.558239.151740@y27g2000pre.googlegroups.com> References: <1194366154.558239.151740@y27g2000pre.googlegroups.com> Message-ID: <8c7f10c60711060857x227da51fl2e107fc499704a7@mail.gmail.com> On 11/6/07, rustom wrote: > heckle in ruby is inspired by jester for java. I quote: > > Heckle is a mutation tester. It modifies your code and runs your tests > to make sure they fail. The idea is that if code can be changed and > your tests don't notice, either that code isn't being covered or it > doesn't do anything. > from http://glu.ttono.us/articles/2006/12/19/tormenting-your-tests-with-heckle > > Is there anything similar for python?? Pester - . -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues From robert.kern at gmail.com Thu Nov 1 20:39:20 2007 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 01 Nov 2007 19:39:20 -0500 Subject: (MAC) CoreGraphics module??? In-Reply-To: <22uki39arp3a83topaimrka4s37uo1okm5@4ax.com> References: <22uki39arp3a83topaimrka4s37uo1okm5@4ax.com> Message-ID: David C. Ullrich wrote: > Running OS X 10.4 "Tiger". Various references > by Apple and others say that there exists a > module that gives Quartz bindings, allowing > all sort of graphics things in Python. > > Sure enough, after installing Xcode I have > some sample scripts. They all start with > > from CoreGraphics import * > > (as do all the examples in two books, both > of which say they're talking about Tiger.) > > I get an ImportError trying to import CoreGraphics. > I found a CoreGraphics.py in a folder named Carbon; > when I change the script to read > > import Carbon > from Carbon.CoreGraphics import * > > there's no import error, but all of the Quartz > things are NameErrors. I look at CoreGraphics.py, > it's just about twenty lines long, defining a few > constants with Quartz-sounding names. That's different than the one that is referenced. The one those articles reference is only available in the Python that came with the system in /System/Library/Frameworks/Python.framework, not one that you might have installed from www.python.org into /Library/Frameworks/Python.framework. The module was made by Apple, and they have not released the source code, so it cannot be made to work with the www.python.org distribution. -- 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 jzgoda at o2.usun.pl Tue Nov 20 16:37:47 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Tue, 20 Nov 2007 22:37:47 +0100 Subject: mimicking a file in memory In-Reply-To: <3ea3babb-29f1-4950-9d5b-c31f67d4e54a@i29g2000prf.googlegroups.com> References: <3ea3babb-29f1-4950-9d5b-c31f67d4e54a@i29g2000prf.googlegroups.com> Message-ID: p. pisze: > I am using the mutagen module to extract id3 information from mp3 > files. In order to do this, you give mutagen a filename, which it > converts into a file object using the python built-in "file" function. > > Unfortunately, my mp3 files don't live locally. They are on a number > of remote servers which I access using urllib2. > > Here is my dilemma: > I don't want to copy the files into a local directory for mutagen's > sake, only to have to remove them afterward. Instead, I'd like to load > the files into memory and still be able to hand the built-in "file" > function a filename to access the file in memory. > > Any ideas on how to do this? Try with StringIO/cStringIO, these modules are supposed to give you in-memory objects compatible with file object interface. -- Jarek Zgoda http://zgodowie.org/ From danfike at gmail.com Fri Nov 16 13:17:25 2007 From: danfike at gmail.com (danfike at gmail.com) Date: Fri, 16 Nov 2007 10:17:25 -0800 (PST) Subject: Trouble building pywin32 with Visual Studio 2005 References: <1195065704.281487.52130@o38g2000hse.googlegroups.com> <473b4bce$0$6411$9b622d9e@news.freenet.de> <1195072749.484949.66920@v65g2000hsc.googlegroups.com> Message-ID: <471ae0d7-fe93-49bf-8af1-69417d2324b8@n20g2000hsh.googlegroups.com> > > If you know what you are doing, you can override the logic of distutils. > > Set up an SDK environment (with LIBRARY, INCLUDE and everything), then > > also set the MSSdk environment variable (which should get set if you > > use the standard environment batch file from the SDK), and then also > > set DISTUTILS_USE_SDK. Then distutils will trust that the environment > > you set up works correctly, and will use it without further questioning. > > I'll see if I can get that working. During my internet searches, I > came across a mail/post/blog or two indicating DISTUTILS_USE_SDK does > not work in Visual Studio 2005. I'll see what I can do. I didn't have much luck with this. It looks like my solution is going to be to just ignore this problem for now. In most cases, the binary modules one downloads are written well enough that these DLLs aren't going to step on eachother's toes. In fact, I haven't found a function aside from win32com.server.register.RegisterClasses which has the same problem. Now, if everybody moves to VS2008 for Python 3000, this problem would work itself out. :) Thanks for your help, Martin. -Dan From __peter__ at web.de Fri Nov 23 04:14:30 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 23 Nov 2007 10:14:30 +0100 Subject: may be a bug in string.rstrip References: Message-ID: Scott SA wrote: > There are a lot of cool things you can do with regex, one of them in > relation to your needs, is the ability to replace substrings: > > >>> import re > >>> reg = re.compile('(.exe)$') # the $ means end of line > >>> reg.sub('','123.exe') > '123' Unfortunately there are also many opportunities for subtle errors: >>> re.compile("(.exe)$").sub("", "abcexe") 'ab' >>> re.compile(r"(\.exe)$").sub("", "abcexe") 'abcexe' >>> re.compile(r"(\.exe)$").sub("", "abc.exe") 'abc' A dot normally matches any character except newline, so you have to escape it. Peter From cjw at sympatico.ca Sun Nov 25 08:01:43 2007 From: cjw at sympatico.ca (Colin J. Williams) Date: Sun, 25 Nov 2007 08:01:43 -0500 Subject: the annoying, verbose self In-Reply-To: <13keq168fnu9328@corp.supernews.com> References: <3c954a31-9fb9-4c0f-b784-cef9ee057ca6@g30g2000hsb.googlegroups.com> <6f67fccf-fbec-4c75-baea-5d0277e07883@w40g2000hsb.googlegroups.com> <47458D4E.5030302@sympatico.ca> <13keq168fnu9328@corp.supernews.com> Message-ID: <47497237.6000409@sympatico.ca> Steven D'Aprano wrote: > On Fri, 23 Nov 2007 23:38:24 +0000, BJ??rn Lindqvist > wrote: > >> I like that a lot. This saves 12 characters for the original example and >> removes the need to wrap it. >> >> 7 return math.sqrt(.x * .x + .y * .y + .z * .z) >> >> +1 Readability counts, even on small screens. > > -2 Readability counts, and your example is a lot less readable. > > For your example to be even *slightly* readable, you have to fill the > expression with excessive whitespace. A little bit of whitespace is good. > Too much breaks the flow of the expression and hurts readability. > > Or perhaps I should say: > > T o o m u c h b r e a k s t h e f l o w . . . > > > You write: math.sqrt(.x * .x + .y * .y + .z * .z) > > which to my eyes has too much whitespace, but the alternative is worse: > math.sqrt(.x*.x + .y*.y + .z*.z) > > and this is positively painful to try to read, it looks like line-noise: > math.sqrt(.x*.x+.y*.y+.z*.z) > > > > The correct solution to your example is to get rid of the attribute > lookups from the expression completely: > > > def abs(self): > x, y, z = self.x, self.y, self.z > return math.sqrt(x**2 + y**2 + z**2) > > > It's probably also faster, because it looks up the attributes only once > each, instead of twice. > > Alternatively, as someone else suggested, an analogue of the Pascal "with" could be used: def abs(self): with self: return math.sqrt(x**2 + y**2 + z**2) As has already been pointed out, "with" has been pre-empted (unfortunately, in my view) for another purpose. This form could be generalized to "with aa" where aa is any object with attributes accessible with the z= aa.z or aa.z.= z style. This should not apply to special names, such as __add__ etc. Colin W. > From keeftm at gmail.com Mon Nov 12 16:50:23 2007 From: keeftm at gmail.com (KeefTM) Date: Mon, 12 Nov 2007 21:50:23 -0000 Subject: imaplib unexpected error In-Reply-To: References: <1194900700.087265.139390@s15g2000prm.googlegroups.com> Message-ID: <1194904223.855321.51790@y27g2000pre.googlegroups.com> On Nov 12, 1:46 pm, Laszlo Nagy wrote: > KeefTM wrote: > > Hello, I am getting an odd error when trying to establish an IMAP > > connection: > > > File "/Library/Frameworks/Python.framework/Versions/2.4//lib/python2.4/ > > imaplib.py", line 904, in _get_response > > raise self.abort("unexpected response: '%s'" % resp) > > imaplib.abort: unexpected response: '220 libertydistribution.com ESMTP > > CommuniGate Pro 5.0.9 is glad to see you!' > > > I thought 220 was the correct response, so I don't understand why I am > > getting the error. Thanks! > > You are connecting to an SMTP server. :-) Maybe it is using the IMAP > port? More likely you tried to connect to port 25 which is - usually - > reserved for SMTP. > > Regards, > > Laszlo That's what it was. I put the wrong port number in :) Thanks! From davisn90210 at gmail.com Mon Nov 26 23:26:58 2007 From: davisn90210 at gmail.com (davisn90210 at gmail.com) Date: Mon, 26 Nov 2007 20:26:58 -0800 (PST) Subject: How to Teach Python "Variables" References: <4749bb94$1@news.bezeqint.net> <5qvf6pF122r3mU1@mid.individual.net> <87abp1qqth.fsf@mulj.homelinux.net> <7c2eaf31-9549-4f13-83c6-5f41149b5005@j44g2000hsj.googlegroups.com> Message-ID: Chris Mellon wrote: > On Nov 26, 2007 1:21 PM, davisn90210 at gmail.com wrote: > > Hrvoje Niksic wrote: > > > greg writes: > > > > > > > none wrote: > > > >> IIRC, I once saw an explanation how Python doesn't have > > > >> "variables" in the sense that, say, C does, and instead has bindings > > > >> from names to objects. > > > > > > > > IMHO, this is nonsense. All that variables are (in any language) are > > "bindings" for names. Pretending python does anything novel with > > regard to "variables" is confusing and, ultimately, simply results in > > a redefinition of terms programmers are already familiar with. I > > mean, it's kind of like saying my computer is not a computer but is > > actually a device that follows input directions. Of course that > > description may be true (and I may even use it to explain to students > > *what* a computer is), but it is no less a computer for it. > > > > Long real-life experience that people with previous programming > experience, especially C programmers, have a great deal of trouble > with this concept. Python "variables" do not work the way they do in > other languages, where variables are compile-time bindings for memory > locations. Even Java references aren't the same (there's no such thing > as a null reference in Python, for example). > I myself learned C++ first, then transitioned to Java, then Python. Once I got the hang of C++ pointers, I personally did not have any significant difficulties with Java's references, and even less so with Python's . Granted that's just my experience, which doesn't mean others don't have that difficulty, but that *is* my experience. Also, to say that "there's no such thing as a null reference in Python," is, IMHO, another example of nonesense. Null is a *concept*, not a particular *value*, and simply means "there's no real value here." The fact that Python's null is called "None" does not change that. Furthermore, the fact that Python's designers were good enough to create a "smarter" null than most languages have does not change that. None is still a special value that is used to represent the fact that there is "nothing here". > > > > If you're talking to C programmers, just tell them that Python > > > > variables always contain pointers. That should give them the right > > > > mental model to build on. > > > > > > That is a convenient shortcut when it works, but in my experience it > > > tends to confuse the issue. The reason is that one of the main uses > > > of pointers in C is implementing pass-by-reference. A C programmer > > > told that Python variables internally hold pointers expects this code: > > > > > > > I think most C programmers are smart enough to figure out the supposed > > differences, with only a little additional explanation on the part of > > the instructor. Python's "variable model" is practically identical to > > that of Java, after all, and I don't recall any discussion of > > cataclysmic proportions over the differences between C "pointers" and > > Java "references". There are "differences" (or more accurately > > "points of emphasis"), but of the sort that take a paragraph or two of > > explanation/clarification -- not a completely new model. > > > > C programmers, when told that Python works like this almost *always* > get this wrong, because they want to pretend that Python is C-like > pass by reference and it isn't. > Which is why you need the "points of emphasis"/"caveats". I never claimed this is a slam-dunk. > The very first thing they want to do is to get at "the pointer" > underneath the object so they can simulate C style pass by reference > with ints. It takes a lot of bandwidth (both mental and electronic) > before they get that there is no underlying pointer and they can't do > this. > Well, Java calls them "references" instead of "pointers", which may not be a bad idea if only to emphasize that there are, in fact, differences. Java seems to have gotten away with explaining these differences in a pretty concise manner. I don't see any reason why Python can't do likewise. > The second thing they want to do is to intercept rebinding actions, > like you might do in C++ with operator overloads. If you explain it to > them in these terms, it is not clear (and will not be, until you use > other terms) that rebinding a name (assignment) and mutating an object > are fundamentally different operations. > I assume you are talking about overloading "operator =" in C++, but that only works for non-pointers. How do you "intercept" rebinding of a *pointer* in C/C++? > I see these questions on a daily basis in #python and somewhat less > frequently in c.l.p. Your assertion that C programmers will "just get > it" if it's explained in those terms is simply not borne out by real > world results. > Again, I never said C programmers will "just get it." That's why I used the phrase "with only a little additional explanation." Maybe I misinterpreted the original post, but my main point is simply that we should call a spade a spade. Variables are variables whether they are C pointers, Java references, or Python "name bindings. To say otherwise just confuses the matter IMHO. There are differences, but let's focus on the *differences* instead of re-naming things. Sorry if I come off a little strong on a few points. Please keep in mind that this is just my opinion of the matter. --Nathan Davis From rustompmody at gmail.com Fri Nov 2 08:24:22 2007 From: rustompmody at gmail.com (Rustom Mody) Date: Fri, 2 Nov 2007 17:54:22 +0530 Subject: compiling python 3000 on debian etch Message-ID: Ive been trying to compile python 3000 on debian etch And on running test I get: 4 skips unexpected on linux2: test_tcl test_dbm test_ssl test_bsddb Can someone tell me what packages I am missing? From deets at nospam.web.de Wed Nov 14 17:59:42 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 14 Nov 2007 23:59:42 +0100 Subject: dependency algorithm In-Reply-To: References: Message-ID: <5q1d02Ftpsb9U1@mid.uni-berlin.de> Tom Jones schrieb: > Hi, > > Consider tuples of the above numbers in the form: > (a,b) > > Suppose this relation means: > a depends on b > > Given a list of tuples, I would like an algorithm to return the proper > ordering of the elements...and if the ordering has a loop (which in this > case, prevents a proper ordering), then it should return None. > > For example, > > > [(1,2),(2,3),(3,4)] > should give: > [4,3,2,1] > > > [(3,2),(1,3),(2,4)] > should give: > [4,2,3,1] > > > [(1,4),(4,3),(2,3)] > should give: > [3,2,4,1] or [3,4,2,1] (which one doesn't matter) > > > [(1,2), (2,3), (3,2)] > should give > None, since it cannot be resolved > > > I'm sure this is a standard problem (mro, resolving inheritance?), but > this is a simplified case since each element can directly depend on only > one other element (thus, multiple inheritance is not allowed)...but many > elements can depend on the same element (no limit on the number of > classes which subclass another class). A quick hack is simple enough to > code, but I am wondering if there are 'standard' ways of performing this > task in this limited scope. http://en.wikipedia.org/wiki/Topological_sorting Diez From usenet-mail at markshroyer.com Sat Nov 10 06:34:49 2007 From: usenet-mail at markshroyer.com (Mark Shroyer) Date: Sat, 10 Nov 2007 11:34:49 GMT Subject: Portrait of a "real life" __metaclass__ References: <1194680507.652797.111620@v23g2000prn.googlegroups.com> Message-ID: On 2007-11-10, Jonathan Gardner wrote: > On Nov 9, 7:12 pm, Mark Shroyer wrote: >> I guess this sort of falls under the "shameless plug" category, but >> here it is: Recently I used a custom metaclass in a Python program >> I've been working on, and I ended up doing a sort of write-up on it, >> as an example of what a "real life" __metaclass__ might do for those >> who may never have seen such a thing themselves. >> >> http://markshroyer.com/blog/2007/11/09/tilting-at-metaclass-windmills/ >> >> So what's the verdict? Incorrect? Missed the point completely? >> Needs to get his head checked? I'd love to hear what >> comp.lang.python has to (anthropomorphically) say about it. >> > > Kinda wordy. Yeah, my fingers sort of latch onto the keyboard sometimes and just won't let go. Sorry about that ;) > Let me see if I got the point: > > - You already had a bunch of classes that did age matching on date > time objects. > > - You were building a class that matched emails. > > - You wanted to reuse the code for age matching to do email matching > (based on the message's age) > > - So you wrote a metaclass that replaced the match() method with a > proxy that would either dispatch to the old match() method (if it was > a datetime object) or dispatch to the new match() method (which > matched based on the message's date.) Close, but not quite. The proxy *always* dispatches to AgeSpec.match(), but if the result of that method is an AgeSpec itself, then the proxy wraps the result back up in a Matcher, which works out rather conveniently for the rest of the application. > Sounds Java-y, if that's even a word. Yeah, you pretty much nailed my original background right there. On the other hand, I've also done a lot of work in Perl and C, and pride myself on striving not to resort to OO patterns where they aren't really useful. So let me try to defend my reasoning, if it is in fact defensible... > Too many classes, not enough functions. You can tell you are doing > Java in Python when you feel the urge to give everything a name > that is a noun, even if it is completely based of a verb, such as > "matcher". My opinion is that if you want to talk about doing > something in Python such as matching, starting writing functions > that match and forget the classes. Classes are for real nouns, > nouns that can do several distinct things. > > What would I have done? I wouldn't have had an age matching class. I > would have had a function that, given the datetime and a range > specification, would return true or false. Then I would've written > another function for matching emails. Again, it takes a specification > and the email and returns true or false. There isn't much difference between match_calendar_month(2007, 11, message) and m = CalendarMonthMatcher(2007, 11) m.match(message) so of course you're right that, were that all I'm doing with these matchers, it would be a waste to implement them as classes. But take for example two of my app's mailbox actions -- these aren't their real names, but for clarity let's call them ArchiveByMonth and SaveAttachmentsByMonth. The former moves messages from previous months into an archival mbox file ./archives/YYYY/MM.mbox corresponding to each message's month, and the latter saves message attachments into a directory ./attachments/YYYY/MM/. Each of these actions would work by using either match_calendar_month() or CalendarMonthMatcher().match() to perform its action on all messages within a given month; then it iterates through previous months and repeats until there are no more messages left to be processed. In my object-oriented implementation, this iteration is performed by calling m.previous() on the current matcher, much like the simplified example in my write-up. Without taking the OO approach, on the other hand, both types of actions would need to compute the previous month themselves; sure that's not an entirely burdensome task, but it really seems like the wrong place for that code to reside. (And if you tackle this by writing another method to return the requisite (year, month) tuple, and apply that method alongside wherever match_calendar_month() is used... well, at that point you're really just doing object-oriented code without the "class" keyword.) Furthermore, suppose I want to save attachments by week instead of month: I could then hand the SaveAttachmentsByPeriod action a WeekMatcher instead of a MonthMatcher, and the action, using the matcher's common interface, does the job just as expected. (This is an actual configuration file option in the application; the nice thing about taking an OO approach to this app is that there's a very straightforward mapping between the configuration file syntax and the actual implementation.) It could be that I'm still "thinking in Java," as you rather accurately put it, but here the object-oriented approach seems genuinely superior -- cleaner and, well, with better encapsulated functionality, to use the buzzword. > If I really wanted to pass around the specifications as objects, I > would do what the re module does: have one generic object for all the > different kinds of age matching possible, and one generic object for > all the email objects possible. These would be called, > "AgeMatchSpecification", etc... These are noun-y things. Here, > however, they are really a way of keeping your data organized so you > can tell that that particular dict over there is an > AgeMatchSpecification and that one is an EmailMatchSpecification. And > remember, the specifications don't do the matching--they merely tell > the match function what it is you wanted matched. Oddly enough, the re module was sort of my inspiration here: my_regex = re.compile("abc") my_regex.match("some string") (Sure, re.compile() is a factory function that produces SRE_Pattern instances rather than the name of an actual class, but it's still used in much the same way.) > Now, part of the email match specification would probably include bits > of the date match specification, because you'd want to match the > various dates attached to an email. That's really not rocket science > though. > > There wouldn't be any need to integrate the classes anymore if I did > it that way. Plus, I wouldn't have to remember a bunch of class names. > I'd just have to remember the various parameters to the match > specification for age matching and a different set of parameters for > the email matching. You're sort of missing the bigger picture of this application, although that's entirely not your fault as I never fully described it to begin with. The essence of this project is that I have a family of mailbox actions (delete, copy, archive to mailbox, archive by time period, ...) and a family of email matching rules (match read messages, match messages with attachments, match messages of a certain size, match messages by date, ...) of which matching by date is only one subtype -- but there are even many different ways to match by date (match by number of days old, match by specific calendar month, match by specific calendar month *or older*, match by day of the week, ...); not to mention arbitrary Boolean combinations of other matching rules (and, or, not). My goal is to create a highly configurable and extensible app, in which the user can mix and match different "action" and "matcher" instances to the highest degree possible. And using class definitions really facilitates that, to my Java-poisoned mind. For example, if the user writes in the config file actions = ( ( # Save attachments from read messages at least 10 days old mailbox => ( path => '/path/to/maildir', type => 'maildir', ), match => ( type => And, p => ( type => MarkedRead, state => True, ), q => ( type => DaysOld, days => 10, ), ), action => ( type => SaveAttachments, destination => '/some/directory/', ), ), ) (can you tell I've been working with Lighttpd lately?) then my app can easily read in this dictionary and map the user-specified actions directly into Matcher and Action instances; and this without me having to write a bunch of code to process boolean logic, matching types, action parameters, and so on into a program flow that has a structure needlessly divergent from the configuration file syntax. It also means that, should a user augment the program with his own Matcher or Action implementation, as I intend to make it easy to do, then those implementations can be used straightaway without even touching the code for the configuration file reader. As for the decision to use a metaclass proxy to my AgeSpec classes, I'm fully prepared to admit wrongdoing there. But I still believe that an object-oriented design is the best approach to this problem, at least considering my design goals. Or am I *still* missing the point? Thanks for your input! Mark -- Mark Shroyer http://markshroyer.com/ From arkanes at gmail.com Tue Nov 13 14:46:45 2007 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 13 Nov 2007 13:46:45 -0600 Subject: os walk() and threads problems (os.walk are thread safe?) In-Reply-To: <4739F5AC.10003@sbh.eng.br> References: <5ptsjjFsvk9kU1@mid.uni-berlin.de> <5pu2otFsm96nU1@mid.uni-berlin.de> <4739F5AC.10003@sbh.eng.br> Message-ID: <4866bea60711131146k553de85ds2dc0d71be890dd8b@mail.gmail.com> On Nov 13, 2007 1:06 PM, Marcus Alves Grando wrote: > Diez B. Roggisch wrote: > > Marcus Alves Grando wrote: > > > >> Diez B. Roggisch wrote: > >>> Marcus Alves Grando wrote: > >>> > >>>> Hello list, > >>>> > >>>> I have a strange problem with os.walk and threads in python script. I > >>>> have one script that create some threads and consume Queue. For every > >>>> value in Queue this script run os.walk() and printing root dir. But if i > >>>> increase number of threads the result are inconsistent compared with one > >>>> thread. > >>>> > >>>> For example, run this code plus sort with one thread and after run again > >>>> with ten threads and see diff(1). > >>> I don't see any difference. I ran it with 1 and 10 workers + sorted the > >>> output. No diff whatsoever. > >> Do you test in one dir with many subdirs? like /usr or /usr/ports (in > >> freebsd) for example? > > > > Yes, over 1000 subdirs/files. > > Strange, because to me accurs every time. > > > > >>> And I don't know what you mean by diff(1) - was that supposed to be some > >>> output? > >> No. One thread produce one result and ten threads produce another result > >> with less lines. > >> > >> Se example below: > >> > >> @@ -13774,8 +13782,6 @@ > >> /usr/compat/linux/proc/44 > >> /usr/compat/linux/proc/45 > >> /usr/compat/linux/proc/45318 > >> -/usr/compat/linux/proc/45484 > >> -/usr/compat/linux/proc/45532 > >> /usr/compat/linux/proc/45857 > >> /usr/compat/linux/proc/45903 > >> /usr/compat/linux/proc/46 > > > > I'm not sure what that directory is, but to me that looks like the > > linux /proc dir, containing process ids. Which incidentially changes > > between the two runs, as more threads will have process id aliases. > > My example are not good enough. I run this script in ports directory of > freebsd and imap folders in my linux server, same thing. > > @@ -182,7 +220,6 @@ > /usr/ports/archivers/p5-POE-Filter-Bzip2 > /usr/ports/archivers/p5-POE-Filter-LZF > /usr/ports/archivers/p5-POE-Filter-LZO > -/usr/ports/archivers/p5-POE-Filter-LZW > /usr/ports/archivers/p5-POE-Filter-Zlib > /usr/ports/archivers/p5-PerlIO-gzip > /usr/ports/archivers/p5-PerlIO-via-Bzip2 > @@ -234,7 +271,6 @@ > /usr/ports/archivers/star-devel > /usr/ports/archivers/star-devel/files > /usr/ports/archivers/star/files > -/usr/ports/archivers/stuffit > /usr/ports/archivers/szip > /usr/ports/archivers/tardy > /usr/ports/archivers/tardy/files > > Are you just diffing the output? There's no guarantee that os.path.walk() will always have the same order, or that your different working threads will produce the same output in the same order. On my system, for example, I get a different order of subdirectory output when I run with 10 threads than with 1. walk() requires that stat() works for the next directory that will be walked. It might be remotely possible that stat() is failing for some reason and some directories are being lost (this is probably not going to be reproducible). If you can reproduce it, trying using pdb to see what's going on inside walk(). From snewman18 at gmail.com Thu Nov 15 15:28:28 2007 From: snewman18 at gmail.com (snewman18 at gmail.com) Date: Thu, 15 Nov 2007 12:28:28 -0800 (PST) Subject: Python Design Patterns - composition vs. inheritance Message-ID: In learning about design patterns, I've seen discussion about using inheritance when an object's relationship to another object is 'is-a' and composition when the relationship is 'has-a'. Since this is all new and I'm still learning, I was hoping someone can give me some pointers on best practices on applying these ideas. If my logic is incorrect on anything, please don't hesitate to tell me where I'm wrong - I'm completely open to any help offered. As a very simplified example, if I had two classes, Pet and Owner, it seems that I would not have Pet inherit from Owner, since a pet 'has an' owner, but not 'is an' owner. If this is correct, does my code below reflect this? I passed the owner object into the pet object's constructor - is this the right way to do it? Also, I've seen talk that ideally you shouldn't have too many "dots" in your method calls, instead using delegates to the methods and attributes. Can anyone elaborate on this? Ideally, should I be writing getattr() methods so I can do pet.address instead of pet.owner.address? Should I be doing the same with owner's methods like I did with get_foo()? Thanks in advance to anyone who can share their experience with me - it's very appreciated. class Owner(object): def __init__(self): self.address = '123 Fake Street' def get_foo(self): return 'bar' class Pet(object): def __init__(self, owner): self.owner = owner def __getattr__(self, name): if name == 'address': return self.owner.address else: raise AttributeError, name def get_foo(self): return self.owner.get_foo() owner = Owner() pet = Pet(owner) From geekmug at gmail.com Fri Nov 2 22:36:05 2007 From: geekmug at gmail.com (Scott Dial) Date: Fri, 02 Nov 2007 19:36:05 -0700 Subject: Instances of BaseException and family don't provide __module__? Message-ID: <1194057365.385329.41570@k79g2000hse.googlegroups.com> I have started working on a new project using ZSI and perhaps one can argue this is a bug in ZSI, but I found it odd. The ZSI dispatcher needs to catch all exceptions and pass that over to the client; in doing so, it passes along the name of the exception that occurred so that the client can know more than just "it failed." Anyways, I am getting off the point, the mechanics of this code in ZSI goes more or less like this: >>> try: >>> doSomething() >>> except Exception, ex: >>> sendFault(':'.join([ex.__module__, ex.__class__.__name__])) This works just fine for user-defined exceptions like: >>> class UserException(Exception): >>> pass >>> uex = UserException() >>> print ':'.join([uex.__module__, uex.__class__.__name__]) # __main__.UserException But falls on its face with built-in exceptions: >>> ex = Exception() >>> print ':'.join([ex.__module__, ex.__class__.__name__]) # AttributeError! , because the built-in exception instances don't have the __module__ attribute (as of 2.5). The only way this works in 2.4 as well as 2.5 is to do: >>> print ':'.join([ex.__class__.__module__, ex.__class__.__name__]) # exceptions:Exception >>> print ':'.join([uex.__class__.__module__, uex.__class__.__name__]) # __main__:NewException But this is a bit obscure and I don't understand why user-defined exception instances should have a different set of attributes than the built-in exception instances. As well as this is a change from 2.4- >2.5 that breaks existing code for no apparent reason. This smells like it was an overlooked mistake and not a feature. I am tempted to open a bug against python for it, but I didn't know if someone could give a rational reason why that attribute is missing? Thanks, -Scott From faltet at carabos.com Tue Nov 13 11:27:11 2007 From: faltet at carabos.com (Francesc Altet) Date: Tue, 13 Nov 2007 17:27:11 +0100 Subject: Populating a dictionary, fast [SOLVED] In-Reply-To: <009401c82552$00034760$0009d620$@com> References: <13jgj48s1dto4db@corp.supernews.com> <009401c82552$00034760$0009d620$@com> Message-ID: <200711131727.11849.faltet@carabos.com> A Monday 12 November 2007, Michael Bacarella escrigu?: > As for the solution, after trying a half-dozen different integer > hashing functions > and hash table sizes (the brute force approach), on a total whim I > switched to a > model with two dictionary tiers and got whole orders of magnitude > better performance. > > The tiering is, for a given key of type long: > > id2name[key >> 40][key & 0x10000000000] = name > > Much, much better. A few minutes versus hours this way. > > I suspect it could be brought down to seconds with a third level of > tiers but this is no longer posing the biggest bottleneck... ;) I don't know exactly why do you need a dictionary for keeping the data, but in case you want ultra-fast access to values, there is no replacement for keeping a sorted list of keys and a list with the original indices to values, and the proper list of values. Then, to access a value, you only have to do a binary search on the sorted list, another lookup in the original indices list and then go straight to the value in the value list. This should be the faster approach I can think of. Another possibility is using an indexed column in a table in a DB. Lookups there should be much faster than using a dictionary as well. HTH, -- >0,0< Francesc Altet ? ? http://www.carabos.com/ V V C?rabos Coop. V. ??Enjoy Data "-" From rich at worldsinfinite.com Mon Nov 5 12:40:54 2007 From: rich at worldsinfinite.com (Rich Harkins) Date: Mon, 05 Nov 2007 12:40:54 -0500 Subject: Descriptors and side effects In-Reply-To: <472f449d$0$30491$426a34cc@news.free.fr> References: <1194248333.382804.260390@y42g2000hsy.googlegroups.com> <472f449d$0$30491$426a34cc@news.free.fr> Message-ID: <472F55A6.1050806@worldsinfinite.com> Bruno Desthuilliers wrote: [snip] > I'm sorry, but this looks like a very complicated way to do a simple thing: > > class MySimpleClass(object): > def __init__(self, x): > self.x = x > self.y = x ** 2 > > Sure, for the absurdly simplified case I posed as an example. ;) Here's another: class Path(tuple): @ConstProperty def pathstr(self): print "DEBUG: Generating string" return '/'.join(self) def __add__(self, other): if isinstance(other, tuple): return Path(tuple.__add__(self, other)) else: return Path(tuple.__add__(self, (other,))) >>> ROOT = Path(()) >>> path = ROOT + 'x' + 'y' + 'z' >>> path.pathstr DEBUG: Generating string /x/y/z >>> path.pathstr /x/y/z Basically, you can use ConstProperty above for items you don't want to calculate automatically, but only when someone actually WANTS it. After it is applied, then the penalties for function call of the property and the computation are wiped out once the second access is requested. Now, in the original example, len() might be considered too little for this use and should be just generated in the constructor "for free". OTOH, that assumes that __len__ hasn't been overridden to do something more complicated and time consuming. If the antecedent object is static, and the derivative consequent is also static, then ConstProperty works very well and shouldn't cost more on the first access than any other built-in property function. BTW, another use is to avoid creating lots of unnecessary objects for free unless they are accessed. Another quickie example: class Node(object): hasChildList = False hasAttributesDict = False @ConstProperty def children(self): self.hasChildList = True return [] @ConstProperty def attributes(self): self.hasAttributesDict = True return {} The extra class/object attributes can be used to test for whether the associated objects were created. When used in a large tree, not creating a lot of extra lists and dictionaries can save a lot of memory and CPU as the children and attributes are not created or explored unless they were manipulated. Rich From steve at REMOVE-THIS-cybersource.com.au Sat Nov 10 18:02:19 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 10 Nov 2007 23:02:19 -0000 Subject: String/Decimal issues References: Message-ID: <13jce3r1dvu1nab@corp.supernews.com> On Sat, 10 Nov 2007 09:02:01 -0800, Mike Howarth wrote: > Hi > > Seem to be having a bit of brainfreeze this evening. > > Basically I'm reducing an array of prices like so: >>> subtotal = reduce(operator.add, itemprices) > > This gives me a string of '86.00.00' which I am trying to use with > decimal objects. Python 2.4 is not particularly happy with this. Let me guess... your test data is: itemprices = ['86.0', '0.00'] What happens if you use test data like this? itemprices = ['86.0', '0.00', '1.99', '12.03'] The first problem that you have is that your prices are strings. Is that deliberate? This is not necessarily a fault. Your second problem is that the + operator concatenates strings, not adds them. "1.0" + "2.0" = "1.02.0", not "3.0". This, on the other hand, is absolutely a fault. Your code is producing invalid data. > Additionally I can't simply convert the string to a decimal as it would > be invalid given it has multiple decimal points. Yes. Rather than trying to fix the invalid data after it is produced, you should fix your code so it doesn't produce the wrong answer in the first place. > Being relatively new to python, I'm not sure how I could round the > string or similar. Anyone got any ideas? This is NOT the answer you NEED, but this is the answer you ask for. To cut out the extra decimal places, use this: >>> subtotal = '86.00.00' >>> subtotal[:-3] '86.00' Now that I've told you how to do it, let me re-iterate that you shouldn't do it. Your problem isn't that your result has an extra ".00" at the end of the result. Your problem is that your result is WRONG. Fix the result in the first place. I'd be looking at something like this: # start with a list of strings itemprices = ['86.0', '0.00', '1.99', '12.03'] # convert them into decimal objects itemprices = map(decimal.Decimal, itemprices) # and add them subtotal = sum(itemprices) -- Steven. From tinkerbarbet at gmail.com Mon Nov 26 14:32:16 2007 From: tinkerbarbet at gmail.com (tinkerbarbet at gmail.com) Date: Mon, 26 Nov 2007 11:32:16 -0800 (PST) Subject: Best ways of managing text encodings in source/regexes? Message-ID: Hi I've read around quite a bit about Unicode and python's support for it, and I'm still unclear about how it all fits together in certain scenarios. Can anyone help clarify? * When I say "# -*- coding: utf-8 -*-" and confirm my IDE is saving the source file as UTF-8, do I still need to prefix all the strings constructed in the source with u as in myStr = u"blah", even when those strings contain only ASCII or ISO-8859-1 chars? (It would be a bother for me to do this for the complete source I'm working on, where I rarely need chars outside the ISO-8859-1 range.) * Will python figure it out if I use different encodings in different modules -- say a main source file which is "# -*- coding: utf-8 -*-" and an imported module which doesn't say this (for which python will presumably use a default encoding)? This seems inevitable given that standard library modules such as re don't declare an encoding, presumably because in that case I don't see any non-ASCII chars in the source. * If I want to use a Unicode char in a regex -- say an en-dash, U+2013 -- in an ASCII- or ISO-8859-1-encoded source file, can I say myASCIIRegex = re.compile('[A-Z]') myUniRegex = re.compile(u'\u2013') # en-dash then read the source file into a unicode string with codecs.read(), then expect re to match against the unicode string using either of those regexes if the string contains the relevant chars? Or do I need to do make all my regex patterns unicode strings, with u""? I've been trying to understand this for a while so any clarification would be a great help. Tim From nick at craig-wood.com Tue Nov 27 05:30:04 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 27 Nov 2007 04:30:04 -0600 Subject: spawning a process with subprocess References: <8b45ae31-a3e2-470f-93d0-ad31d8717176@s36g2000prg.googlegroups.com> <5r0iqtF11gmauU1@mid.uni-berlin.de> <078233a7-a296-4910-a544-786098e0cc46@d4g2000prg.googlegroups.com> <5r0n7iF128ic7U1@mid.uni-berlin.de> <9d3f3be1-de62-4d25-94e4-3764e5e6c12c@w40g2000hsb.googlegroups.com> Message-ID: MonkeeSage wrote: > Couple of things. You should use poll() on the Popen instance, and > should check it explicitly against None (since a 0 return code, > meaning exit successfully, will be treated as a false condition the > same as None). Also, in your second example, you block the program > when you call readlines on the pipe, since readlines blocks until it > reaches eof (i.e., until pipe closes stdout, i.e., process is > complete). Oh, and you don't have to split the input to the args > option yourself, you can just pass a string. Though passing an array is good practice if you want to avoid passing user data through the shell. > So, putting it all together, you want something like: > > import subprocess, time > > cmd = "cat somefile" > proc = subprocess.Popen(args=cmd, shell=True, > stdout=subprocess.PIPE, stdin=subprocess.PIPE, > stderr=subprocess.STDOUT, close_fds=True) > > while 1: > time.sleep(1) > if proc.poll() != None: > break > else: > print "waiting on child..." > > print "returncode =", proc.returncode This works fine unless the command generates a lot of output (more than 64k on linux) when the output pipe will fill up and the process will block until it is emptied. If you run the below with `seq 10000` then it works fine but as written the subprocess will block forever writing its output pipe (under linux 2.6.23). #------------------------------------------------------------ import subprocess, time cmd = """ for i in `seq 20000`; do echo $i done exit 42 """ proc = subprocess.Popen(args=cmd, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT, close_fds=True) while 1: time.sleep(1) if proc.poll() != None: break else: print "waiting on child..." print "returncode =", proc.returncode lines = 0 total = 0 for line in proc.stdout: lines += 1 total += len(line) print "Received %d lines of %d bytes total" % (lines, total) #------------------------------------------------------------ So you do need to read stuff from your subprocess, but there isn't a way in the standard library to do that without potentially blocking. There are a few solutions 1) use the python expect module (not windows) http://pexpect.sourceforge.net/ 2) set your file descriptors non blocking. The following recipe shows a cross platform module to do it. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440554 Or just do it with the fcntl module 3) Use a thread to read stuff from your subprocess and allow it to block on proc.stdout.read() Here is an example of 2) #------------------------------------------------------------ import subprocess, time, os from fcntl import fcntl, F_GETFL, F_SETFL from errno import EAGAIN cmd = """ for i in `seq 100000`; do echo $i done exit 42 """ proc = subprocess.Popen(args=cmd, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT, close_fds=True) # Set non blocking (unix only) fcntl(proc.stdout, F_SETFL, fcntl(proc.stdout, F_GETFL) | os.O_NONBLOCK) def read_all(fd): out = "" while 1: try: bytes = fd.read(4096) except IOError, e: if e[0] != EAGAIN: raise break if not bytes: break out += bytes return out rx = "" while 1: time.sleep(1) if proc.poll() != None: break else: print "waiting on child..." rx += read_all(proc.stdout) rx += read_all(proc.stdout) print "returncode =", proc.returncode lines = 0 total = 0 for line in rx.split("\n"): lines += 1 total += len(line) print "Received %d lines of %d bytes total" % (lines, total) #------------------------------------------------------------ Which runs like this on my machine $ python subprocess-shell-nb.py waiting on child... waiting on child... waiting on child... waiting on child... waiting on child... waiting on child... waiting on child... waiting on child... returncode = 42 Received 100001 lines of 488895 bytes total -- Nick Craig-Wood -- http://www.craig-wood.com/nick From feliphil at gmx.net Tue Nov 6 06:58:02 2007 From: feliphil at gmx.net (Wolfgang Keller) Date: Tue, 06 Nov 2007 12:58:02 +0100 Subject: Pythonic ORM with support for composite primary/foreign keys? Message-ID: Hello, so far it seems to me as if the only ORM module for Python which supports composite primary/foreign keys was SQLAlchemy. Which looks a little bit "overbloated" for my needs: I "just" need to be able to define a "logical model" (? la UML) in Python and have the ORM connect to a database (running on PostgreSQL in my case) which uses a corresponding (pre-defined) "physical model" as its schema. Modeling really does look exactly like what I need. Among others, it seems to be understandable even for a Clueless Python Scripting Dilettant like me. But support for primary keys is not yet completely built-in (and tested). So, is there another ORM module for Python besides SQLAlchemy which supports composite porimary (and foreign) keys, and maybe also other more "advanced", maybe even some of the PostgreSQL-specific features (such as e.g. composite types)? TIA, Sincerely, Wolfgang Keller From larry.bates at websafe.com Wed Nov 7 20:05:26 2007 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 07 Nov 2007 19:05:26 -0600 Subject: zipfile handling In-Reply-To: <1194399792.245511.132740@v3g2000hsg.googlegroups.com> References: <1194399792.245511.132740@v3g2000hsg.googlegroups.com> Message-ID: ad-hoc wrote: > is there a rename utility for zipfile that can rename a directory > inside a zipfile? also what's the best way to change the a file > content inside a zip? > > So if i have the following file in the zip file: > > A/a1.txt > A/a2.txt > B/b1.txt > > I want to rename A to be A1, and B to be B1, as well as changing the > content of a1.txt and b1.txt. > > I can certainly extract them to filesystem then rezip, but there might > be a better way to do this? > > thanks. > Nope not a better way. The zipping requires that you go through the process to get a proper zip file. -Larry From upton at virginia.edu Mon Nov 26 16:58:21 2007 From: upton at virginia.edu (Dan Upton) Date: Mon, 26 Nov 2007 16:58:21 -0500 Subject: fork/exec with input redirection Message-ID: <5504f9ac0711261358p31c2b9f1ud24aec5829d8707e@mail.gmail.com> I have a Python script that does a fork/exec, so the parent process can get the child's PID and monitor /proc/PID/stat (on a CentOS system). Most of my processes' command lines are straightforward enough to do this with, but I have a handful that use < on the command line, eg ./gobmk_base.linux_x86 --quiet --mode gtp < 13x13.tst The only thing I could really think of to try was os.execv("./gobmk_base.linux_x86", ["./gobmk_base.linux_x86", "--quiet", "--mode", "gtp", "<", "13x13.tst"]) but this apparently doesn't work. Is there some other way to accomplish what I'm going for? Thanks, -dan From rishiyoor at gmail.com Sat Nov 10 12:45:47 2007 From: rishiyoor at gmail.com (rishiyoor at gmail.com) Date: Sat, 10 Nov 2007 09:45:47 -0800 Subject: Coding Help Message-ID: <1194716747.634041.204620@k79g2000hse.googlegroups.com> I need help coding my flowchart. The C's are conditions, the S's are statements. The statements do not affect the conditions except for S5 which is an increment for C0. The left is True, and the right is False. I would probably use a while loop (or for loop without S5) for the first condition C0, and I am thinking of evaluating the rest of the conditions using if statements. But if I use if-statements, I am not able to accomodate the breaks. Program ????????????????????????????????? ??< C0 >?????????? ? ? | ? ? ?????< C1 >??????????? ? ? ????< C2 >????? ???< C3 >??? ? ? ??< C4 >?? [S1] ?? ? ? [S2] [S3] ???????????? ? ? ? ? ??< C4 >??? ? ? ? ? [S4] ?? ? ? ? ? ??????????? ? ???????????????????????????? ? ? [S5] ? ? ?????????????????????????????? Program From bj_666 at gmx.net Sat Nov 10 13:35:01 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 10 Nov 2007 18:35:01 GMT Subject: Coding Help References: <1194716747.634041.204620@k79g2000hse.googlegroups.com> Message-ID: <5pmbulFri447U4@mid.uni-berlin.de> On Sat, 10 Nov 2007 09:45:47 -0800, rishiyoor wrote: > I need help coding my flowchart. The C's are conditions, the S's are > statements. The statements do not affect the conditions except for S5 > which is an increment for C0. The left is True, and the right is > False. > > I would probably use a while loop (or for loop without S5) for the > first condition C0, and I am thinking of evaluating the rest of the > conditions using if statements. But if I use if-statements, I am not > able to accomodate the breaks. > > Program > ????????????????????????????????? > ??< C0 >?????????? ? > ? | ? > ? ?????< C1 >??????????? ? > ? ????< C2 >????? ???< C3 >??? > ? ? ??< C4 >?? [S1] ?? > ? ? [S2] [S3] ???????????? > ? ? ? ? ??< C4 >??? > ? ? ? ? [S4] ?? > ? ? ? ? ??????????? > ? ???????????????????????????? ? > ? [S5] ? > ? ?????????????????????????????? > Program Sounds pretty much like homework to me. Ciao, Marc 'BlackJack' Rintsch From oruccim at gmail.com Wed Nov 14 14:56:26 2007 From: oruccim at gmail.com (oruccim at gmail.com) Date: Wed, 14 Nov 2007 11:56:26 -0800 Subject: general information Message-ID: <1195070186.925479.106980@o3g2000hsb.googlegroups.com> hi my friends ; i keep one's mind; can i read this document ?? http://rapidshare.com/files/69725750/MTU.TRK pls somebody tell me it From zhushenli at gmail.com Mon Nov 19 21:13:03 2007 From: zhushenli at gmail.com (Davy) Date: Mon, 19 Nov 2007 18:13:03 -0800 (PST) Subject: Tkinter Problem? Message-ID: Hi all, I have written a simple Tkinter program, that is draw a rectangle in a canvas, when I press Up key, the rectangle move up. But the program seems work not properly? My environment is Python2.5+PythonWin. ##---------------------- from Tkinter import * class MyApp: def __init__(self,parent): self.myContainer1 = Frame(parent) self.myContainer1.pack() self.canv = Canvas(relief=SUNKEN) self.canv.config(width = 300,height=300) self.canv.pack() self.canv.create_rectangle(100,100,150,150,tags="rect") self.canv.bind('',self._onUpKey) self.canv.bind('', self._onReturnKey) def _onUpKey(self,event): self.canv.move(tagOrId,xAmount=0,yAmount=10) def _onReturnKey(self,event): print 'Hello world' root = Tk() myapp = MyApp(root) root.mainloop() ##---------------------- Best regards, Davy From antroy at gmail.com Wed Nov 14 06:47:46 2007 From: antroy at gmail.com (Ant) Date: Wed, 14 Nov 2007 03:47:46 -0800 Subject: Using Python To Change The World :) In-Reply-To: <1195009751.327435.182540@i13g2000prf.googlegroups.com> References: <1195009751.327435.182540@i13g2000prf.googlegroups.com> Message-ID: <1195040866.173845.173360@v65g2000hsc.googlegroups.com> On Nov 14, 3:09 am, dominiquevalent... at gmail.com wrote: ... > so here is MY question: > how would you replicate a street intersection in python? and > furthermore, how would you do you have the cars move up and down those > "streets". I've never used it, but I'd have thought that pygame would satisfy the graphical side of things. -- Ant From IRosquist at irq.org Mon Nov 5 19:55:34 2007 From: IRosquist at irq.org (Ivar Rosquist) Date: Tue, 06 Nov 2007 00:55:34 GMT Subject: >>> CIA Squashes Democracy in Pakistan <<< References: <1194298989.746423.199810@o3g2000hsb.googlegroups.com> Message-ID: On Mon, 05 Nov 2007 21:43:09 +0000, zionist.news wrote: > http://www.youtube.com/watch?v=BdB2r1ss5Wk > > http://www.jewwatch.com/ <----- excellent source for well researched > news on world events and the big movers of history What democracy? Pakistan will be either a military dictatorship or theocratic one. A country with such a high proportion of moslem fundamentalists is not likely to develop into a democracy any time soon. From http Mon Nov 12 14:31:00 2007 From: http (Paul Rubin) Date: 12 Nov 2007 11:31:00 -0800 Subject: Populating a dictionary, fast [SOLVED] References: <13jgj48s1dto4db@corp.supernews.com> Message-ID: <7xoddz1csr.fsf@ruckus.brouhaha.com> "Michael Bacarella" writes: > > id2name[key >> 40][key & 0x10000000000] = name > Oops, typo. It's actually: > Id2name[key >> 40][key & 0xffffffffff] = name Are you saying this is a patch that appeared after python 2.3? Somehow I don't think it's come up in this thread whether you've tried any later versions. From ricaraoz at gmail.com Thu Nov 1 19:12:52 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Thu, 01 Nov 2007 20:12:52 -0300 Subject: Need some help... In-Reply-To: <4729e9a8$1_4@news.bluewin.ch> References: <1193560272.637389.315680@e34g2000pro.googlegroups.com> <47271907$1_6@news.bluewin.ch> <4729e9a8$1_4@news.bluewin.ch> Message-ID: <472A5D74.1050603@bigfoot.com> Boris Borcic wrote: > Ricardo Ar?oz wrote: >> Boris Borcic wrote: >>> hyozan.ux3 at gmail.com wrote: >>>> I want to create a program that I type in a word. >>>> >>>> for example... >>>> >>>> chaos >>>> >>>> each letter equals a number.... >>>> >>>> A=1 >>>> B=20 >>>> >>>> and so on. >>>> >>>> So Chaos would be >>>> >>>> C=13 H=4 A=1 O=7 S=5 >>>> >>>> I want to then have those numbers >>>> 13+4+1+7+5 added together to be 30. >>>> >>>> How can I do that? >>>> >>>> Also, just curious, but, how could I then have the 3 and 0 added >>>> together to be 3? >>>> >>>> Please help me out. >>>> >>>> Thank you..... >>>> >>> >>> sum(dict(C=13,H=4,A=1,O=7,S=5)[_] for _ in 'CHAOS') >>> 30 >>> >>> sum(eval(ch) for ch in str(_)) >>> 3 >> >>>>> def sumToOneDigit(num) : >> if num < 10 : >> return num >> else : >> return sumToOneDigit(sum(int(i) for i in str(num))) >> >> >>>>> sumToOneDigit(sum(ord(ch) for ch in 'chaos'.upper())) >> 6 >> >> >> >> HTH > > HTH what ? HTH : Hope that helps Citing your post : """ Also, just curious, but, how could I then have the 3 and 0 added together to be 3? """ you have the function "sumToOneDigit" that adds the digits of a number till you get one digit (isn't that what you where curious about?) And answering the main question : sum(ord(ch) for ch in 'chaos'.upper()) which is inside the "sumToOneDigit" funtion in my answer. Sorry if that is not enough for you, but the answer is probably worth what you paid for it. From bobkolker at comcast.net Tue Nov 13 08:03:49 2007 From: bobkolker at comcast.net (Robert J. Kolker) Date: Tue, 13 Nov 2007 08:03:49 -0500 Subject: A JEW hacker in California admits distributing malware that let him steal usernames and passwords for Paypal accounts. In-Reply-To: <1194732615.277219.168670@o38g2000hse.googlegroups.com> References: <1194732615.277219.168670@o38g2000hse.googlegroups.com> Message-ID: <-6KdnWO6wMsrPaTanZ2dnUVZ_rXinZ2d@comcast.com> zionist.news at gmail.com wrote: > A Jew hacker in California admits distributing malware that let him > steal usernames and passwords for Paypal accounts. Just like all the Goy hackers who have done the same kind of wrongful deed. Bob Kolker From martin at v.loewis.de Mon Nov 5 00:37:59 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 05 Nov 2007 06:37:59 +0100 Subject: bsddb in python 2.5.1 In-Reply-To: <1194208600.990196.47970@z24g2000prh.googlegroups.com> References: <1194131555.834711.183750@q3g2000prf.googlegroups.com> <472D7D16.3060808@v.loewis.de> <1194208600.990196.47970@z24g2000prh.googlegroups.com> Message-ID: <472eac38$0$15232$9b622d9e@news.freenet.de> > I have two versions of bsddb3 installed (only one is active) this is > from /usr/lib/python2.5/site-packages: > drwxr-xr-x 3 root root 4096 2007-11-03 15:01 bsddb3 > -rw-r--r-- 1 root root 905 2007-11-03 15:39 bsddb3-4.4.2.egg-info > -rw-r--r-- 1 root root 905 2007-11-03 15:49 bsddb3-4.5.0.egg-info This makes two installations, but how do you know that they really link with two different versions of Berkeley DB? > I'm really at a loss of what I could do, except for reverting > back to Ubuntu 7.05. What's wrong with upgrading the database files to 4.5? Just run the proper db_upgrade binary. Regards, Martin From john.m.roach at gmail.com Thu Nov 8 12:21:14 2007 From: john.m.roach at gmail.com (john.m.roach at gmail.com) Date: Thu, 08 Nov 2007 17:21:14 -0000 Subject: How to output newline or carriage return with optparse In-Reply-To: References: <1194538920.777563.156260@v23g2000prn.googlegroups.com> Message-ID: <1194542474.366933.144210@e9g2000prf.googlegroups.com> On Nov 8, 11:46 am, Tim Chase wrote: > > I'm trying to implement some simple command line options. > > Some of the 'help' sections are long and I would like to > > control line breaks. How do you do this? > > I had this problem earlier and solved it here: > > http://groups.google.com/group/comp.lang.python/browse_frm/thread/6df... > > thanks to a little guidance from Ben Finney on where to look. > > It came up again last month here: > > http://groups.google.com/group/comp.lang.python/browse_frm/thread/e72... > > which should solve the problem for you. > > ASIDE: I've started refactoring this bit out in my local > source...how would I go about contributing it back to the Python > code-base? I didn't get any feedback from posting to the Optik > site. My refactor basically takes an optional pre-processing > function to parse your string into the output that gets passed to > textwrap.wrap() and textwrap.fill(), defaulting to the old > behavior, but offering a function for splitting it into > paragraphs based on newlines. > > -tkc Thanks for the help Tim. I just copied and pasted your code into a file in my $PYTHONPATH (IndentedHelpFormatterWithNL.py), but I'm getting the following error: class IndentedHelpFormatterWithNL(IndentedHelpFormatter): NameError: name 'IndentedHelpFormatter' is not defined I tried adding: from optparse imoport IndentedHelpFormatter into the aforementioned file, but no luck again. What am I missing??? Thanks. From samwyse at gmail.com Sat Nov 24 12:38:58 2007 From: samwyse at gmail.com (samwyse) Date: Sat, 24 Nov 2007 09:38:58 -0800 (PST) Subject: How can I create customized classes that have similar properties as 'str'? References: <67954d23-9400-4ac9-ba45-bec04fab51a2@s6g2000prc.googlegroups.com> <8eebf8fb-74cc-452a-bbef-2fe93556491f@i29g2000prf.googlegroups.com> <5qqeroF11703eU2@mid.individual.net> <1f2e037f-3667-4070-97cd-f4f6486c9d79@i12g2000prf.googlegroups.com> Message-ID: <774894e9-7fd4-4434-970b-42a51fb239a3@g30g2000hsb.googlegroups.com> On Nov 24, 5:44 am, Licheng Fang wrote: > Yes, millions. In my natural language processing tasks, I almost > always need to define patterns, identify their occurrences in a huge > data, and count them. Say, I have a big text file, consisting of > millions of words, and I want to count the frequency of trigrams: > > trigrams([1,2,3,4,5]) == [(1,2,3),(2,3,4),(3,4,5)] BTW, if the components of your trigrams are never larger than a byte, then encode the tuples as integers and don't worry about pointer comparisons. >>> def encode(s): return (ord(s[0])*256+ord(s[1]))*256+ord(s[2]) >>> def trigram(s): return [ encode(s[i:i+3]) for i in range(0, len(s)-2)] >>> trigram('abcde') [6382179, 6447972, 6513765] From deets at nospam.web.de Thu Nov 8 16:24:49 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 08 Nov 2007 22:24:49 +0100 Subject: Python on Leopard issues In-Reply-To: References: Message-ID: <5phd5tFran4qU1@mid.uni-berlin.de> Chris schrieb: > Are others having fundamental issues on OSX 10.5 with python 2.5.1? I was > excited that Python 2.5 was included, but this excitement was very short > lived. Almost nothing works. Upon startup I get this message: > > 'import site' failed; use -v for traceback > > and sure enough, all of the built-in packages are non-existent. I'm not sure > why Apple bothered including an improperly-configured version. Does > anyone have an easy fix for this, or should I go to ActiveState and install a > version that works? While Apple is far from being perfect, I strongly doubt that they ship a python as damaged as this - after all, they rely for some system stuff on the shipped interpreter. But I bet you didn't install leopard fresh, but upgraded? And did you by any chance have a python 2.5 installed before? Anyway, without much more information (where is the python framework located and so forth) there is no chance of being more helpful. Diez From pydev at rscorp.ab.ca Fri Nov 23 02:28:06 2007 From: pydev at rscorp.ab.ca (Scott SA) Date: Fri, 23 Nov 2007 00:28:06 -0700 Subject: may be a bug in string.rstrip Message-ID: On 11/23/07, kyo guan (kyoguan at gmail.com) wrote: > Please look at this code: > >>>> 'exe.torrent'.rstrip('.torrent') >'ex' <----- it should be 'exe', why? > >but this is a right answer: > >>>> '120.exe'.rstrip('.exe') >'120' <------ this is a right value. > > there is a bug in the rstrip, lstrip there isn't this problem. Since your error has been addressed, I'd like to offer a point not expressed by others (that I've seen yet). To perform this task, there are a couple of options i.e. string.replace: >>> string.replace('120.exe','.exe','') '120' ... but it has a side-effect of mid-string replacements: >>> string.replace('123.exe.more','.exe','') '123.more' or maybe: >>> if x[-4:] == '.exe': ... x[:-4] '123' ... is functional, but not elegant i.e. quick 'n dirty esp. as one line. The better option, IMO, is probably to use regex. The module you would use is "re". There are a lot of cool things you can do with regex, one of them in relation to your needs, is the ability to replace substrings: >>> import re >>> reg = re.compile('(.exe)$') # the $ means end of line >>> reg.sub('','123.exe') '123' >>> reg.sub('','123.exe.more') # test for mid-string placement '123.exe.more' Clearly, it is more typing than your original string.strip approach. But as you see, it has the ability to expressly match what you were looking for. Of course, it has the ability to do case-insensitive replacements too... and the elegance _starts_ to show here: >>> reg = re.compile('.(exe|ini|com|fred|wendy)$',re.IGNORECASE) >>> reg.sub('','123.exe') '123' >>> reg.sub('','123.EXE') '123' >>> reg.sub('','123.WenDy') '123' ... would you like fries with that? Just imagine what this would look like using the previous non-regex examples, or maybe not as halloween was _last_ month (scary stuff indeed!). Here are some links to some great docs 8^): S&R, what you want, is described in more detail here: And more links at: HTH Scott From ojeeves at gmail.com Mon Nov 19 05:27:56 2007 From: ojeeves at gmail.com (oj) Date: Mon, 19 Nov 2007 02:27:56 -0800 (PST) Subject: logging.SocketHandler connections References: <23cfe277-7ece-4bef-a16f-1e64b1847f1c@a28g2000hsc.googlegroups.com> <7dfca907-f2e6-45b6-84f1-e60772c24c3d@w34g2000hsg.googlegroups.com> Message-ID: On Nov 16, 2:31 pm, Vinay Sajip wrote: > On Nov 15, 3:23 pm, oj wrote: > > > > > However, initially, I had tried it with a server that closed the > > connection after receiving each record, and the SocketHandler doesn't > > seem to behave as advertised. > > > My test script was simply this: > > [snip] > > The SocketHandler documentation says that it will re-establish the > > connection if it has been closed. After a bit of digging, I found a > > patch had been submitted and accepted that made it back off > > exponentially. However, this should be time based. Even if I make my > > sleep here 30 seconds, my server still only receives messages 0, 3, 6 > > and 9. > > > I'm concerned that if a connection is lost at some point, I will > > always lose at least 2 log messages. > > > Is there some reason for this that I am not aware of? Have I > > misunderstood something, or is this a bug? > > Not sure yet - can you please post your test server code? Feel free to > add it as a bug on bugs.python.org, with the code attached, and I'll > look into it. Include "logging" in the subject/summary line. > > Thanks, > > Vinay Sajip Here is the server code. Pretty much directly copied from the example, aside from not having the the handler loop forever, and queing the records instead of dealing with the directly. After further investigation, running the client with a long timeout, without the server, so that every connection will fail, produces results much closer to what I would expect. Connections attempted for each message initially, but not for all of the later messages as the retry time increases. The point is kinda moot now, since I guess not closing the connection is the 'right way' to do this, but I'm still interested in why I see this behaviour when the server closes the connection. #!/usr/bin/python import thread import cPickle import logging import logging.handlers import SocketServer import select import struct import sys import time port = 12345 queue = [] queue_lock = thread.allocate_lock() class LogRecordStreamHandler(SocketServer.StreamRequestHandler): def handle(self): chunk = self.connection.recv(4) if len(chunk) < 4: print "failed to get 4 bytes in first read" return slen = struct.unpack(">L", chunk)[0] chunk = self.connection.recv(slen) while len(chunk) < slen: chunk = chunk + self.connection.recv(slen - len(chunk)) obj = self.unPickle(chunk) record = logging.makeLogRecord(obj) queue_lock.acquire() queue.insert(0, record) queue_lock.release() def unPickle(self, data): return cPickle.loads(data) class LogRecordSocketReceiver(SocketServer.ThreadingTCPServer): def __init__(self, host='localhost', port=port, handler=LogRecordStreamHandler): SocketServer.ThreadingTCPServer.__init__(self, (host, port), handler) self.abort = 0 self.timeout = 1 self.logname = None def serve_until_stopped(self): abort = 0 while not abort: rd, wr, ex = select.select([self.socket.fileno()], [], [], self.timeout) if rd: self.handle_request() abort = self.abort def listen(): server = LogRecordSocketReceiver() server.serve_until_stopped() def main(): global queue, queue_lock logger = logging.getLogger() logger.addHandler(logging.StreamHandler(sys.stdout)) while True: record = None locked = queue_lock.acquire(0) if locked: if len(queue): record = queue.pop() queue_lock.release() if record: logger.handle(record) else: time.sleep(1) if __name__ == '__main__': thread.start_new_thread(listen, ()) main() From sjdevnull at yahoo.com Tue Nov 20 19:08:14 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: Tue, 20 Nov 2007 16:08:14 -0800 (PST) Subject: Python too complex ?!?!?! References: <7hC%i.28332$mv3.17248@newsfe10.phx> <7bde7627-adf1-4bc6-a936-2159370485a1@e1g2000hsh.googlegroups.com> <672dfa43-bd56-44fa-b85d-15eca7682c84@s36g2000prg.googlegroups.com> <46601afd-9c1d-48d1-8d1c-9330b726211e@a39g2000pre.googlegroups.com> Message-ID: <715436e9-357e-47b2-af58-2e148b711676@b15g2000hsa.googlegroups.com> On Nov 20, 5:01 pm, "Patrick Mullen" wrote: > (Oops, sent as private, reposting to list) > > On Nov 20, 2007 12:36 PM, sjdevn... at yahoo.com wrote: > > > > > FWIW it's trivial to run pyflakes on your code (automatically behind > > the scenes) to get syntax checking; in vim, my syntax errors get > > underlined immediately for python code. It's especially nice for > > large web applications, where having to go reload a page only to > > discover you typed "if a=1:" or some silliness actually takes some > > amount of time. > > > I also get function prototypes on the status line (so, e.g., the > > elsethread example of confusing list.extend and list.append is > > mitigated to a large degree). > > > Dynamic typing loses some info, but you can get most of the big > > benefits with it. > > > -- > >http://mail.python.org/mailman/listinfo/python-list > > That sounds really cool. What do I have to do to set up vim so it > does that for me? I'm leaving for the holidays in 5 minutes, I'll post my configs when I return (Monday-ish). Feel free to email me a reminder on Monday... The basic concept should work fine in emacs, but the glue would need someone to implement it (my grand scheme plan is to do it over with the NetBeans integration interface so that vim/xemacs/whatever would pick it up okay, but I'm not sure if that API is featureful enough). From aaron.watters at gmail.com Mon Nov 26 11:24:58 2007 From: aaron.watters at gmail.com (Aaron Watters) Date: Mon, 26 Nov 2007 08:24:58 -0800 (PST) Subject: mod_python References: Message-ID: On Nov 24, 1:19 am, Vernon Wenberg III wrote: > Why do I receive a "File not found" error on a perfect good and simple > script but properly receive errors when I deliberately add errors in the > script? The file is there, it just doesn't do anything. > > Any help would be appreciated. I'm guessing the file is okay, but something involving naming is wrong. Check the error log file(s). It may show that mod_py is looking inside the module and not finding the right function/method. As others have said, some sample code would help us help you... -- Aaron Watters === http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=generate+muck From aaron.watters at gmail.com Thu Nov 29 10:15:00 2007 From: aaron.watters at gmail.com (Aaron Watters) Date: Thu, 29 Nov 2007 07:15:00 -0800 (PST) Subject: Python web frameworks References: <226020ef-3955-43e8-b1f6-2ba9ba43d45e@c29g2000hsa.googlegroups.com> <5qga2mFvuljgU1@mid.uni-berlin.de> <160f8bbc-70be-4dcb-8874-de72588c1d10@d61g2000hsa.googlegroups.com> <1b343163-e755-44f8-b5c3-4af56c61e817@c29g2000hsa.googlegroups.com> <93a92a82-cf3c-4ebb-a93f-180374e5f75a@e4g2000hsg.googlegroups.com> <00c0167e-3b4c-4476-b473-1f938a54db63@e1g2000hsh.googlegroups.com> <2672de28-2c94-4967-83f5-18f2823492ee@b15g2000hsa.googlegroups.com> <8adb0024-e74b-4ea9-a819-9da9f64a460a@j20g2000hsi.googlegroups.com> Message-ID: <14b156e7-2637-4b71-9735-9f4d662dac2f@s19g2000prg.googlegroups.com> On Nov 22, 11:22 pm, SamFeltus wrote: > """Perhaps we need a pythonic FRONTEND. """ > > Should have happened years ago. It did. Mark Hammond embedded Python under MSIE about the same time javascript and java applets came along (94, maybe?) It didn't fly because of political and marketing problems, I think. One technical killer was that C-Python can be crashed relatively easily by malicious code, and browser providers don't like that too much. Also, the stuff you need to do to make it crash proof would make the interpreter a lot slower (which may be why javascript is pretty slow). -- Aaron Watters === http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=msie+de-facto+recognized+dim From michele.simionato at gmail.com Thu Nov 1 13:18:08 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Thu, 01 Nov 2007 17:18:08 -0000 Subject: AOP and pep 246 In-Reply-To: References: Message-ID: <1193937488.399694.235180@o80g2000hse.googlegroups.com> On Nov 1, 4:18 pm, "Rustom Mody" wrote: > I am interested in AOP in python. From here one naturally (or > google-ly) reaches peak. > But peak seems to be discontinued. > Whereas pep-246 on adaptors seems to be rejected in favor of something else. > > What?? > > Can someone please throw some light on whats the current state of the art? See http://www.python.org/dev/peps/pep-3119 Michele Simionato From cjw at sympatico.ca Sun Nov 25 09:16:01 2007 From: cjw at sympatico.ca (Colin J. Williams) Date: Sun, 25 Nov 2007 09:16:01 -0500 Subject: the annoying, verbose self In-Reply-To: References: <3c954a31-9fb9-4c0f-b784-cef9ee057ca6@g30g2000hsb.googlegroups.com> <6f67fccf-fbec-4c75-baea-5d0277e07883@w40g2000hsb.googlegroups.com> <47458D4E.5030302@sympatico.ca> <13keq168fnu9328@corp.supernews.com> Message-ID: <474983A1.4000102@sympatico.ca> Andrew Koenig wrote: > "Colin J. Williams" wrote in message > news:mailman.1557.1195995738.13605.python-list at python.org... > >> Alternatively, as someone else suggested, an analogue of the Pascal "with" >> could be used: >> >> def abs(self): >> with self: >> return math.sqrt(x**2 + y**2 + z**2) > > How does your suggested "with" statement know to transform x into self.x but > not transform math.sqrt into self.math.sqrt? > > I am not advocating this, but this could be: def abs(self): with self: with math: return sqrt(x**2 + y**2 + z**2) The idea being that "with self" use creates a new namespace: newGlobal= oldGlobal + oldLocal newLocal= names from self Similarly, "with math" creates a newer namespace: newerGlobal= newGlobal + newLocal newerLocal= names from math My guess is that there would be little use for nesting the "with". Colin W. From janne.t.harkonen at gmail.com Fri Nov 16 12:02:25 2007 From: janne.t.harkonen at gmail.com (=?ISO-8859-1?Q?Janne_H=E4rk=F6nen?=) Date: Fri, 16 Nov 2007 19:02:25 +0200 Subject: Resolving declaring class of a method at runtime In-Reply-To: <13jpd9ek4ss4qc2@corp.supernews.com> References: <13jpd9ek4ss4qc2@corp.supernews.com> Message-ID: On Nov 15, 2007 11:07 PM, Steven D'Aprano wrote: > On Thu, 15 Nov 2007 13:01:27 +0200, Janne H?rk?nen > wrote: > > Have you tried looking at dir(TheClass) to see what it lists? This is the first thing I did, but it shows both the inherited and own methods. > Also helpful is TheClass.__dict__.keys(). This actually does the trick, thanks for the tip! > Python has powerful introspection abilities. Learn to use them, and you > too will be able to impress your friends with your Python knowledge. I actually use introspection very frequently, but almost always through dir(). > X is an "old style" class. Most people probably shouldn't use old style > classes, for various reasons. To use new style classes, you inherit from > object: I am also aware of old and new style classes, this was the fastest way to type it in console :) -- __janne From jstroud at mbi.ucla.edu Sat Nov 17 22:27:37 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 17 Nov 2007 19:27:37 -0800 Subject: Mac os x 10.4.11: Error installing Python 2.5.1 In-Reply-To: <5aded601-3773-4cc4-a68d-d84f561aea88@e10g2000prf.googlegroups.com> References: <5aded601-3773-4cc4-a68d-d84f561aea88@e10g2000prf.googlegroups.com> Message-ID: David wrote: > Running OS X 10.4.11 PPC. No Intel. > > I downloaded: > > http://www.python.org/ftp/python/2.5.1/python-2.5.1-macosx.dmg > > I started the install, accepted the license, selected easy install, > then upgrade, entered my password for the mac, but the installation > process finished with: > > There were errors installing the software. Please try installing > again. > > Is there a log file somewhere I can examine? Anyone else experience > this? Workaround? Usually this happens when you are not an administrator. If you aren't log out and log in again as one. If that doesn't do it, what does your /Applications/Utilities/Console say? James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com From bborcic at gmail.com Thu Nov 1 10:57:52 2007 From: bborcic at gmail.com (Boris Borcic) Date: Thu, 01 Nov 2007 15:57:52 +0100 Subject: Need some help... In-Reply-To: References: <1193560272.637389.315680@e34g2000pro.googlegroups.com> <47271907$1_6@news.bluewin.ch> Message-ID: <4729e9a8$1_4@news.bluewin.ch> Ricardo Ar?oz wrote: > Boris Borcic wrote: >> hyozan.ux3 at gmail.com wrote: >>> I want to create a program that I type in a word. >>> >>> for example... >>> >>> chaos >>> >>> each letter equals a number.... >>> >>> A=1 >>> B=20 >>> >>> and so on. >>> >>> So Chaos would be >>> >>> C=13 H=4 A=1 O=7 S=5 >>> >>> I want to then have those numbers >>> 13+4+1+7+5 added together to be 30. >>> >>> How can I do that? >>> >>> Also, just curious, but, how could I then have the 3 and 0 added >>> together to be 3? >>> >>> Please help me out. >>> >>> Thank you..... >>> >> >>> sum(dict(C=13,H=4,A=1,O=7,S=5)[_] for _ in 'CHAOS') >> 30 >> >>> sum(eval(ch) for ch in str(_)) >> 3 > > >>>> def sumToOneDigit(num) : > if num < 10 : > return num > else : > return sumToOneDigit(sum(int(i) for i in str(num))) > > >>>> sumToOneDigit(sum(ord(ch) for ch in 'chaos'.upper())) > 6 > > > > HTH HTH what ? From ayaz at dev.null Thu Nov 22 14:24:18 2007 From: ayaz at dev.null (Ayaz Ahmed Khan) Date: 22 Nov 2007 19:24:18 GMT Subject: the annoying, verbose self References: <3c954a31-9fb9-4c0f-b784-cef9ee057ca6@g30g2000hsb.googlegroups.com> Message-ID: <4745d762$0$90264$14726298@news.sunsite.dk> braver wrote: > Is there any trick to get rid of having to type the annoying, > character-eating "self." prefix everywhere in a class? Sometimes I > avoid OO just not to deal with its verbosity. In fact, I try to use > Ruby anywhere speed is not crucial especially for @ prefix is better- > looking than self. I've never really understood why some people find that annoying to do. I make it a point to use, for example, the `this` operator when writing C++ code to avoid implicilty calling/accessing attributes of objects as much as possible. -- Ayaz Ahmed Khan From tarundevnani at gmail.com Tue Nov 13 05:48:08 2007 From: tarundevnani at gmail.com (tarun) Date: Tue, 13 Nov 2007 16:18:08 +0530 Subject: Issue with wxPython GUI In-Reply-To: <473955DA.9040709@shopzeus.com> References: <473955DA.9040709@shopzeus.com> Message-ID: Hi Laszlo Nagy, Thanks a lot. But the issue over here is that how will the child thread acknowledge the main thread that it has completed its task. For this I'll have to set some flag in the child thread and poll for it in the main thread. This will create a problem. Any alternatives?? Thanks & Regards, Tarun On 11/13/07, Laszlo Nagy wrote: > > > > > > *New Problem: *I am opening and executing a script from the GUI. The > > script has a many log messages, > > which it posts on some shared memory. The GUI reads the messages from > > the shared memory, > > in the Idle loop. But the script is huge and so the logging is not > > run-time. > > Rather this happens only after the script has executed. Moreover, the > > GUI becomes > > un-responsive till the script has completely executed. > > > This is (probably) because you are running your script in your main > thread. While the main thread of the application is running, your > windowing system cannot process message queues. Since the updating of a > text control uses window messages, it has no chance to process them. I > recommend that you run your script in a separate (terminateable?) > thread, send your messages into a Queue instance, and load messages from > that queue in your main thread. > > > > Do you have any suggestions for this? > Well, if you do not want to create more threads, it migth work if you > call this periodically from your main thread (but I did not try this): > > > wxApp::Dispatch > > *virtual void* *Dispatch*() > > Dispatches the next event in the windowing system event queue. > > This can be used for programming event loops, e.g. > > while (app.Pending()) > Dispatch(); > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From http Sun Nov 25 15:16:14 2007 From: http (Paul Rubin) Date: 25 Nov 2007 12:16:14 -0800 Subject: OPLC purchase period extended References: <13kgrdbf8eb7l34@corp.supernews.com> <13khho3mb3pp27e@corp.supernews.com> Message-ID: <7xejeeaxo1.fsf@ruckus.brouhaha.com> Grant Edwards writes: > The most imporant thing is that the "control" key is to the > left of the "A" keay where god intened. Not too surprising > when you realized the design was headed by folks from the media > lab at MIT. MIT requires everybody to use Emacs, right? You've got to remember that the OLPC was made for little kids, and as such, the keyboard is quite small. Also, because of its expected physical environment, the keyboard is water resistant (membrane cover). These two things make the OLPC difficult enough for a grown-up to type on that although I've played with a few, I don't remember where the control key was, and as an Emacs user I usually do notice things like that. If you get an OLPC and plan to use it much, you'll probably want an external USB keyboard. The built-in keyboard is ok for occasional portable use checking email and stuff like that. It's really unsuitable for a full-time computer. From hniksic at xemacs.org Thu Nov 29 05:11:18 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Thu, 29 Nov 2007 11:11:18 +0100 Subject: Very basic, sorting a list ??? References: <474E064C.9040303@gmail.com> <29080$474e8916$83aef404$7726@news1.tudelft.nl> Message-ID: <87y7chcqex.fsf@mulj.homelinux.net> Stef Mientki writes: > although I find it rather non-intuitive. > I didn't expect a copy, but a reference to itself wouldn't be asked > too much ? If you didn't expect a copy, why rely on the return value? You could simply continue using the sorted list. Your first post says "I'm trying to sort a list, using the same list at the commandline works, but in a program it doesn't." > Why does it return None, instead of the sorted object itself ? > I guess it would cost almost exactly the same processing power. It's not about processing power at all, it's about clarity. Code that says: foo = [5, 2, 3, 1] bar = foo.sort() might run into a nasty surprise upon finding that both foo and bar point to the same (sorted) list. Returning None ensures that the error is detected as early as possible. Returning a list strongly indicates that a copy is being made. For example, the following Perl code: @foo = (3, 2, 1); @bar = sort @foo; makes @bar sorted, but leaves @foo alone. From andy at britishideas.com Thu Nov 15 14:18:45 2007 From: andy at britishideas.com (andy at britishideas.com) Date: Thu, 15 Nov 2007 11:18:45 -0800 (PST) Subject: Embedded Python - Blocking Python Function References: <1195081362.973396.98060@z24g2000prh.googlegroups.com> <1bd11e17-bfb9-4228-b985-4e0788efee8c@s36g2000prg.googlegroups.com> Message-ID: <1057f690-ebbf-4d54-ba6f-a21ddd0f8b2c@d27g2000prf.googlegroups.com> On Nov 15, 9:43 am, a... at britishideas.com wrote: > On Nov 14, 4:20 pm, "Gabriel Genellina" > wrote: > > > Not forcibly - you need some cooperation from the Main function. Maybe > > setting a global variable that Main checks periodically. > > Thanks. I'll give that a try! > > Andy It works but the problem is that the script will be written by the end user. If they make a mistake and the cancel flag isn't perodically checked then it seems I have no way of cleanly ending the interpreter. If I wait for a specific time after requesting the Main function stop I need to be able to kill the interpreter without a runtime error. Any ideas? Andy From __peter__ at web.de Tue Nov 13 11:05:12 2007 From: __peter__ at web.de (Peter Otten) Date: Tue, 13 Nov 2007 17:05:12 +0100 Subject: how can I interpret a file within the interactive interpreter References: Message-ID: Peter J. Bismuti wrote: > I want to interpret a file (or whatever you call it) and then keep the > interactive interpreter alive so I can then continue to issue commands. That's what the -i option is for. > How can this be done? I saw online a -m flag but it does not seem to work. -m is used to load a module via python's import mechanism. $ echo 'print "Hello from", __name__' > tmp.py $ python -m tmp Hello from __main__ $ python -i tmp.py Hello from __main__ >>> You can combine both options: $ python -i -m tmp Hello from __main__ >>> Peter From mccredie at gmail.com Fri Nov 2 15:12:54 2007 From: mccredie at gmail.com (Matt McCredie) Date: Fri, 2 Nov 2007 12:12:54 -0700 Subject: Assertion for python scripts In-Reply-To: <1194027247.325466.14300@o80g2000hse.googlegroups.com> References: <1194027247.325466.14300@o80g2000hse.googlegroups.com> Message-ID: <9e95df10711021212n6ecb6e4dj92ec81580571f0da@mail.gmail.com> On 11/2/07, matthias wrote: > Howdy ! > > I started using the assert() stmt and found it quite useful :-) I > have only one problem: I don't > know how to turn them off again. > > I know that "-O" turns off assertions in general. However, how do I > pass thus parameter to > python to an executable script ? > > I have tried the following: > > 1. > !#/usr/bin/env python -O > > -> Fails with this msg: /usr/bin/env: python -O: No such file or > directory > > Also, putting it in quotes won't do it. > > 2. > Passing the "-O" to the runnable script won't work either. > > > Here is my question: How do I maintain debug / release builds that > allow me to switch > debug stmts, like assert, on / off ? > > Thanx, > Matthias Use: python -O -mcompileall path That command will compile all of the files in the given path and produce .pyo files. If the .pyo file is present and up-to-date it will be used instead of the .py file. Alternatively you could do this: python -O -mpy_compile somefile.py which can be used to compile one file at a time. Many Python programs and modules include a compile step as part of their installation process. There is also a -OO option, which will strip doc-strings as well. Matt From cjw at sympatico.ca Thu Nov 8 12:49:44 2007 From: cjw at sympatico.ca (Colin J. Williams) Date: Thu, 08 Nov 2007 12:49:44 -0500 Subject: Old version of sqlite3 Message-ID: sqlalchemy gives the following error message for sqlite: C:\Python25\lib\site-packages\sqlalchemy\databases\sqlite.py:167: RuntimeWarning: The installed version of sqlite (3.3.4) is out-dated, and will cause errors in some cases. Version 3.3.13 or greater is recommended. warnings.warn(RuntimeWarning("The installed version of sqlite (%s) is out-dated, and will cause errors in some cases. Version 3.3.13 or greater is recommended." % self.dbapi.sqlite_version)) The installed version is in C:\Python25\DLLs\sqlite3dll dated 18-Apr-07. sqlite3 has been updated since then. I am using Python 2.5.1 with Windows XP. Any suggestions for a workaround? Colin W. From spamless.aurelien.campeas at free.fr Mon Nov 12 15:29:33 2007 From: spamless.aurelien.campeas at free.fr (=?ISO-8859-1?Q?Aur=E9lien_Camp=E9as?=) Date: Mon, 12 Nov 2007 21:29:33 +0100 Subject: Python-URL! - weekly Python news and links (Nov 12) In-Reply-To: References: Message-ID: <4738b7ad$0$5998$426a74cc@news.free.fr> Laszlo Nagy a ?crit : > Gabriel Genellina wrote: >> QOTW: "AOP is a programming paradigm in the same way indie is a genre of >> film." - Carl Banks >> http://groups.google.com/group/comp.lang.python/msg/224e922a3e1a8638 >> > I was following links and hit PEP 246 here: > > http://www.python.org/dev/peps/pep-0246/ > > > On that page, Guido wrote this: > > I'm rejecting this PEP. Something much better is about to happen; it's > too early to say exactly what, but it's not going to resemble the > proposal in this PEP too closely so it's better to start a new > PEP. GvR. > > > This is so mysterious, and I'm so excited about adaptation. Now that I > read PEP 246 and PEP 245, I want to know what can be better? Do any of > you have any idea what will happen? I can't stand waiting! :-D > > Laszlo > > > PEP 3124, but there haven't been any news of progress for a while From gagsl-py2 at yahoo.com.ar Tue Nov 13 05:12:53 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 13 Nov 2007 07:12:53 -0300 Subject: error :list out of range References: Message-ID: En Tue, 13 Nov 2007 06:23:02 -0300, Beema shafreen escribi?: > for k in range(0,len(res_value),3): > check = res_value[k:k+4] > if check[0] < check[4]: > print check > error: File "app.py", line 16, in > if check[0] < check[4]: > IndexError: list index out of range > i get an error like this how do i sort the error out to get result Look at the exception: IndexError: list index out of range. That's pretty explicit: "some index" used as a subscript on "some list" is out of the allowed range. Most of the time, that means that the index is greater than or equal to the list length. Now look at the source line: if check[0] < check[4]. The possible out-of-range indexes are 0 and 4. 0 may be an invalid index when the list is empty; but the 4 is much more suspicious. We have to determine the length of the "check" list; that's easy looking one line above; res_value[k:k+4] has length 4. Valid indexes include 0, 1, 2, and 3; 4 is an invalid index. Now you should have enough info to fix your code. But, why use a flat list? Your data has certain structure, and you already read it line by line and use different variable names for each field. If you maintain that structure instead of flattening it into a list with anonymous elements, your code will be easier to write (and read, and understand). Your file looks like a CSV file, and you could use the cvs module to read it. Let's read the file the same way you did, but using an object per row: class ProbeData: # please choose a better name! "Holds current_span, probe, and length" def __init__(self, current_span, probe, length): self.current_span = current_span self.probe = probe self.length = length def __str__(self): return "%d %s %d" % (self.current_span, self.probe, self.length) __repr__ = __str__ dataset = [] fh = open('test','r') for line in fh: # note that I've removed readlines() data = line.strip().split('\t') current_span = int(data[3].strip()) # assuming it's an integer probe = data[2].strip() length = int(data[4].strip()) # assuming it's an integer too probe_data = ProbeData(current_span, probe, length) dataset.append(probe_data) fh.close() for k in range(len(dataset)-1): this_probe = dataset[k] next_probe = dataset[k+1] if this_probe.current_span < next_probe.current_span: # Please check the condition above, it's just an example print this_probe -- Gabriel Genellina From http Sat Nov 17 18:08:13 2007 From: http (Paul Rubin) Date: 17 Nov 2007 15:08:13 -0800 Subject: Variable-width lookbehind References: Message-ID: <7xve8031ya.fsf@ruckus.brouhaha.com> "OKB (not okblacke)" writes: > For years now Python has not supported variable-length lookbehinds. I'm not sure what that is and the perl links you gave don't work, but it sounds evil. Basically it sounds like an even uglier form of regexp backtracking than what we have now. Regexps are just not the right framework for implementing such complex parsers. We should instead have some more general parser library instead of keeping on jamming more crap into regexps. There's a famous Zawinski quote that I won't repeat here since I don't want to wear it out. From steve at REMOVE-THIS-cybersource.com.au Fri Nov 16 22:13:43 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 17 Nov 2007 03:13:43 -0000 Subject: implement random selection in Python References: Message-ID: <13jsn37ria5hqc8@corp.supernews.com> On Fri, 16 Nov 2007 16:47:16 -0800, Bruza wrote: > I think I need to explain on the probability part: the "prob" is a > relative likelihood that the object will be included in the output list. > So, in my example input of > > items = [('Mary',30), ('John', 10), ('Tom', 45), ('Jane', 15)] > > So, for any size of N, 'Tom' (with prob of 45) will be more likely to be > included in the output list of N distinct member than 'Mary' (prob of > 30) and much more likely than that of 'John' (with prob of 10). Since there are only four items, you can't select more than four distinct items, because the fifth has to be a duplicate of one of the others. And the probability/likelihood doesn't work either: if you insist on getting distinct items, then your results are are much limited: N = 0, result: [] N = 1, four possible results: ['Mary'] ['John'] ['Tom'] or ['Jane'] N = 2, six possible results (assuming order doesn't matter): ['Mary', 'John'] ['Mary', 'Tom'] ['Mary', 'Jane'] ['John', 'Tom'] ['John', 'Jane'] or ['Tom', 'Jane'] N = 3, four possible results: ['Mary', 'John', 'Tom'] ['Mary', 'John', 'Jane'] ['Mary', 'Tom', 'Jane'] or ['John', 'Tom', 'Jane'] N = 4, one possible result: ['Mary', 'John', 'Tom', 'Jane'] > I know "prob" is not exactly the "probability" in the context of > returning a multiple member list. But what I want is a way to "favor" > some member in a selection process. I don't think this is really well defined, but I'll take a stab in the dark at it. Let's take the example above for N = 3: items = [('Mary',30), ('John', 10), ('Tom', 45), ('Jane', 15)] # use the lowest common factor for simplicity items = [('Mary',6), ('John', 2), ('Tom', 9), ('Jane', 3)] # N = 3 has four possible results: R = ['Mary', 'John', 'Tom'] S = ['Mary', 'John', 'Jane'] T = ['Mary', 'Tom', 'Jane'] U = ['John', 'Tom', 'Jane'] You want to bias the four possible results above so that having Mary is three times more likely than having John. It sounds simple, but it isn't. To do so, you need to solve a whole series of simultaneous equations: Pr(Mary) = Pr(R) + Pr(S) + Pr(T) Pr(John) = Pr(R) + Pr(S) + Pr(U) Pr(Mary) = 3*Pr(John) And so on for all the other items. This is a HARD problem to solve, and for most sets of likelihoods you might give, there won't be a solution. For example, you can't have a set of results where Mary is three times more likely than John, John is twice as likely as Tom, and Tom is four times more likely than Mary. It simply can't happen. So we can't interpret the numbers as probabilities. We can't even interpret them more loosely as "likelihoods". Proof of that is to consider the case of N=4. There is only one possible result with four distinct items. So all of Mary, John, Tom and Jane are equally likely, in fact all of them are certain. The weightings you gave (30, 10, 45, 15) are meaningless. So, given that what you are asking for is impossible, can you explain what you are actually trying to accomplish? Maybe there's a more feasible alternative. -- Steven. From deets at nospam.web.de Wed Nov 14 11:21:26 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 14 Nov 2007 17:21:26 +0100 Subject: Problem using os.environ.get References: <1195056743.978655.125270@z24g2000prh.googlegroups.com> Message-ID: <5q0lk6Ftd47gU1@mid.uni-berlin.de> paragon.john at gmail.com wrote: > Hello, > > I am trying to retrieve a linux environment variable using > os.environ.get, however it does not appear to be working properly. It > returns none for a variable that does, in fact exist. > > # echo $HOSTTYPE > x86_64 > # python >>>> import os >>>> print os.environ.get('HOSTTYPE') > None > > If I do the same thing with a different variable (XILINX, in this > case), it works fine. > > # echo $XILINX > /Xilinx > # python >>>> import os >>>> print os.environ.get('XILINX') > /Xilinx > > Any thoughts on why it is behaving this way? is HOSTTYPE exported? If not, it will not be included in subprocess-environments by the shell. Diez From kyosohma at gmail.com Wed Nov 14 20:42:15 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Wed, 14 Nov 2007 17:42:15 -0800 (PST) Subject: pyopenglcontext binaries for 2.5 on win32 References: <1194933816.838109.45470@v3g2000hsg.googlegroups.com> Message-ID: On Nov 13, 12:03 am, gz wrote: > no, I don't have them... I need them :) > > I'd like to thank Giovanni Bajo for providing binaries for the various > package dependencies, and geting me going with pyopengl. > > Unfortunately I only menaged to run a basic example, where there's no > animation. The glwindow only get's redrawn when it's resized, moved... > well generally redrawed as a window. > > I would greatly appreciate some hints, about how to process the gui > events in the gl portion, and how to run a continous animation in wx + > pyopengl? > > I suspect the whole thing would be way easier with pyopenglcontext, > but I can't seem to find a binary for python 2.5 > I can't get it to install with mingw and don't have vc currently > installed. If someone has successfully built it, plesase share. > > Although, I think, an example of a running opengl spinning cube, > embedded in some wx menu + buttons, capable of handling, say, mouse > clicks in the glwindow, would work best for me. > > I'm not even that keen on wx. I choose it, purely, on the basis that > wx is generaly brought up here frequenter than qt. > (Didn't qt have some licensing change in the last few months that > could potentially change that?) OK. I got OpenGLContext to compile on my home machine after some tinkering with numpy. I uploaded the resulting .exe to my web page at: http://www.pythonlibrary.org/python_modules.htm Let me know if it works for you. Mike From ubanus at users.sf.net Wed Nov 28 08:04:25 2007 From: ubanus at users.sf.net (Jakub Wilk) Date: Wed, 28 Nov 2007 13:04:25 +0000 (UTC) Subject: string conversion latin2 to ascii References: Message-ID: * Martin Landa , 2007-11-27: > I have unicode string (or better say latin2 encoding) containing > non-ascii characters, e.g. > > s = "Uk?zka_mo?nosti_vyu?it?_programu_OpenJUMP_v_SOA" > > I would like to convert this string to plain ascii (using some lookup > table for latin2) > > to get > > -> Ukazka_moznosti_vyuziti_programu_OpenJUMP_v_SOA You may try python-elinks : >>> import elinks >>> print "Uk?zka_mo\236nosti_vyu\236it?_programu_OpenJUMP_v_SOA".decode('Windows-1250').encode('ASCII', 'elinks') Ukazka_moznosti_vyuziti_programu_OpenJUMP_v_SOA -- Jakub Wilk From mail at microcorp.co.za Sat Nov 17 01:24:04 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 17 Nov 2007 08:24:04 +0200 Subject: Populating a dictionary, fast [SOLVED SOLVED] References: <818643.92017.qm@web915.biz.mail.mud.yahoo.com><47374D00.7080500@gmail.com> <1195051438.889160.137120@50g2000hsm.googlegroups.com> <87fxz8kas6.fsf@mulj.homelinux.net><13jn10p1r88u19f@corp.supernews.com> <13jpdgnbg077rb2@corp.supernews.com><264a4c62-5f32-4cae-84c9-016a9eb69c87@b15g2000hsa.googlegroups.com> <005701c8287d$28fb25b0$7af17110$@com> Message-ID: <009601c828e2$74058d60$03000080@hendrik> "Michael Bacarella" wrote: > I am so sorry to have ruined the decorum. Oh dear! I confidently predict that this thread will now degenerate to include such things as dignitas and gravitas. - Hendrik From david at nospam.spam Thu Nov 1 01:22:49 2007 From: david at nospam.spam (david) Date: Thu, 01 Nov 2007 16:22:49 +1100 Subject: basic threading question In-Reply-To: <0_XVi.51817$RX.28748@newssvr11.news.prodigy.net> References: <13ifh9hf5eor49f@corp.supernews.com> <1193789794.782609.197860@z9g2000hsf.googlegroups.com> <13igdq81vlpfk4b@corp.supernews.com> <0_XVi.51817$RX.28748@newssvr11.news.prodigy.net> Message-ID: <13iiol31gf3h47c@corp.supernews.com> thanx :~) From duncan.booth at invalid.invalid Sat Nov 3 13:37:27 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 3 Nov 2007 17:37:27 GMT Subject: Poor python and/or Zope performance on Sparc References: Message-ID: Jean-Paul Calderone wrote: > The T1000 isn't a very good machine for general server purposes. It > has advantages when running software with a lot of hardware-level > parallelism, but Zope isn't such a piece of software. Zope can scale well on multi-processor machines, but you have to configure it correctly. You need to run multiple instances of Zope all talking to a common Zeo backend. In this case you could try running up to 32 single-threaded zope instances, although you'll need to watch the memory consumption so depending on the application you might not get away with that many. From exarkun at divmod.com Sun Nov 18 10:18:25 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Sun, 18 Nov 2007 10:18:25 -0500 Subject: sockets: why doesn't my connect() block? In-Reply-To: Message-ID: <20071118151825.8162.1244355197.divmod.quotient.37230@ohm> On Sat, 17 Nov 2007 21:32:50 -0800 (PST), 7stud wrote: >According to "Python in a Nutshell(2nd)", p. 523: > >connect: s.connect((host, port)) >... >Blocks until the server accepts or rejects the connection attempt. > >However, my client program ends immediately after the call to >connect()--even though my server program does not call accept(): > Your platform's TCP implementation acknowledges the connection attempt before your application calls accept(). This is fairly usual. Jean-Paul From fgmoyles at nospam.com Thu Nov 22 06:33:50 2007 From: fgmoyles at nospam.com (Frank Moyles) Date: Thu, 22 Nov 2007 11:33:50 +0000 Subject: Python Windows installation Message-ID: does anyone know how I can automate installation of the Windows Python distribution, using python1.5.1.msi ? I want to be able to run the installation without user interaction, and pass default parameters (instead of user entries), during the installation process. This can be done with other .msi packages and I was wondering if anyone has done this for the python setup package. From S.Mientki-nospam at mailbox.kun.nl Thu Nov 29 05:36:52 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Thu, 29 Nov 2007 11:36:52 +0100 Subject: Very basic, sorting a list ??? In-Reply-To: <87y7chcqex.fsf@mulj.homelinux.net> References: <474E064C.9040303@gmail.com> <29080$474e8916$83aef404$7726@news1.tudelft.nl> <87y7chcqex.fsf@mulj.homelinux.net> Message-ID: <92690$474e9644$83aef404$18389@news1.tudelft.nl> Hrvoje Niksic wrote: > Stef Mientki writes: > >> although I find it rather non-intuitive. >> I didn't expect a copy, but a reference to itself wouldn't be asked >> too much ? > > If you didn't expect a copy, why rely on the return value? You could > simply continue using the sorted list. Your first post says "I'm > trying to sort a list, using the same list at the commandline works, > but in a program it doesn't." > >> Why does it return None, instead of the sorted object itself ? >> I guess it would cost almost exactly the same processing power. > > It's not about processing power at all, it's about clarity. Code that > says: > > foo = [5, 2, 3, 1] > bar = foo.sort() > > might run into a nasty surprise upon finding that both foo and bar > point to the same (sorted) list. Returning None ensures that the > error is detected as early as possible. Aha, that might be a valid reasoning. thanks, Stef Mientki From pydecker at gmail.com Fri Nov 30 10:52:00 2007 From: pydecker at gmail.com (Peter Decker) Date: Fri, 30 Nov 2007 10:52:00 -0500 Subject: Yet another database question, please In-Reply-To: <7aa00027-db8e-4151-a75b-3a711979ee55@e67g2000hsc.googlegroups.com> References: <47500ee6$0$228$e4fe514c@news.xs4all.nl> <7aa00027-db8e-4151-a75b-3a711979ee55@e67g2000hsc.googlegroups.com> Message-ID: On Nov 30, 2007 9:20 AM, wrote: > > On Nov 30, 7:23 am, nmp wrote: > > Hello to all. I am only just learning both Python and PyGTK (with Glade). > > I also need to learn how to use databases in my programs. My preliminary > > research leads me in the direction of SQLAlchemy, which seems to be what > > everybody else is using. > > > > So, does anyone have a good example that shows how to tie these things > > toegether? I would like to have the GUI dialogs and treeviews directly > > interacting with the underlying tables and/or views. > > > > [cough]Like Borland Delphi 1.0, in the nineties...[/cough] > > > > Another question: I found that in Ubuntu, I was able to install the Glade > > widgets for libgnomedb (libgnomedb3-glade3). Would these be usable with > > Python/PyGTK, too? As is too common, the documentation provided is > > somewhat scarce. > > > > Any sort of pointers or suggestions welcome, of course. > > You should try Dabo. It sounds like what you want to do and what Dabo > does dovetails nicely. > > http://dabodev.com/ Dabo doesn't work with PyGTK, so if he goes with Dabo, he'll have to settle for a GUI toolkit that looks native on all platforms instead of just Gnome. ;-) -- # p.d. From Florian.Lindner at xgm.de Sat Nov 10 13:56:07 2007 From: Florian.Lindner at xgm.de (Florian Lindner) Date: Sat, 10 Nov 2007 19:56:07 +0100 Subject: Coding Help References: <1194716747.634041.204620@k79g2000hse.googlegroups.com> <5pmbulFri447U4@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch wrote: > On Sat, 10 Nov 2007 09:45:47 -0800, rishiyoor wrote: > >> I need help coding my flowchart. The C's are conditions, the S's are >> statements. The statements do not affect the conditions except for S5 >> which is an increment for C0. The left is True, and the right is >> False. >> >> I would probably use a while loop (or for loop without S5) for the >> first condition C0, and I am thinking of evaluating the rest of the >> conditions using if statements. But if I use if-statements, I am not >> able to accomodate the breaks. >> >> Program >> ????????????????????????????????? >> ??< C0 >?????????? ? >> ? | ? >> ? ?????< C1 >??????????? ? >> ? ????< C2 >????? ???< C3 >??? >> ? ? ??< C4 >?? [S1] ?? >> ? ? [S2] [S3] ???????????? >> ? ? ? ? ??< C4 >??? >> ? ? ? ? [S4] ?? >> ? ? ? ? ??????????? >> ? ???????????????????????????? ? >> ? [S5] ? >> ? ?????????????????????????????? >> Program > > Sounds pretty much like homework to me. It's nothing bad ask about help for a homework as long as noone expects to get the entire solution. To the OP: What is your problem? Florian From ptmcg at austin.rr.com Mon Nov 19 12:17:27 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 19 Nov 2007 09:17:27 -0800 (PST) Subject: Efficient (HUGE) prime modulus References: <144c4524-fb8d-4a11-8851-ea6761dad9e7@l1g2000hsa.googlegroups.com> Message-ID: <2fd188c1-e730-473f-9185-8ffe64d06020@n20g2000hsh.googlegroups.com> On Nov 19, 10:32 am, blaine wrote: > Hey guys, > For my Network Security class we are designing a project that will, > among other things, implement a Diffie Hellman secret key exchange. > The rest of the class is doing Java, while myself and a classmate are > using Python (as proof of concept). I am having problems though with > crunching huge numbers required for calculations. As an alternative I > can use Java - but I'd rather have a pure python implementation. The > problem is that Python takes a very long time (I haven't had it finish > yet) - but Java does it in 3 seconds. Suggestions? Did you try the 3-argument version of the built-in pow? A = pow(G,a,P) Takes about .1 second on my machine, with your values. (I didn't verify that the answer I got was correct, though.) -- Paul From martin at v.loewis.de Thu Nov 1 03:38:49 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 01 Nov 2007 08:38:49 +0100 Subject: _tkinter installation in python 2.5 on mandriva with a default 2.4 In-Reply-To: <1193886564.331628.93620@22g2000hsm.googlegroups.com> References: <1193775761.764547.148730@i38g2000prf.googlegroups.com> <4727b1e6$0$13390$9b622d9e@news.freenet.de> <1193813238.978699.154830@57g2000hsv.googlegroups.com> <47288E4D.6010301@v.loewis.de> <1193847896.441329.315560@o80g2000hse.googlegroups.com> <4728afce$0$7845$9b622d9e@news.freenet.de> <1193853812.998544.113780@y27g2000pre.googlegroups.com> <4728cda0$0$4583$9b622d9e@news.freenet.de> <1193886564.331628.93620@22g2000hsm.googlegroups.com> Message-ID: <4729828a$0$13483$9b622d9e@news.freenet.de> > but no tcllib !!! > perhaps that's the problem? Did I assume that it was installed by the > tk mandriva module ? I see. I would have never guessed that you can manage to install Tk but not Tcl on Mandriva... Regards, Martin From no-spam at not-existing.invalid Sun Nov 18 17:24:08 2007 From: no-spam at not-existing.invalid (robert) Date: Sun, 18 Nov 2007 23:24:08 +0100 Subject: Auto locate Python's .so on Linux (for cx_Freeze's --shared-lib-name) In-Reply-To: References: Message-ID: Neal Becker wrote: > robert wrote: > >> In a makefile I want to locate the .so for a dynamically linked >> Python on Linux. (for cx_Freeze's --shared-lib-name) >> e.g. by running a small script with that Python. How to? >> >> Robert > > How about run python -v yourscript and filter the output? > for examples here python -v delivers many other python module paths, but not Python's .so. For example /usr/lib/libpython2.4.so.1.0 Robert From lists at cheimes.de Thu Nov 29 16:37:00 2007 From: lists at cheimes.de (Christian Heimes) Date: Thu, 29 Nov 2007 22:37:00 +0100 Subject: Is os.lstat available on all platforms? In-Reply-To: <7eea5c47-cf1d-4bc5-8dca-aa0d137cbf66@a35g2000prf.googlegroups.com> References: <7eea5c47-cf1d-4bc5-8dca-aa0d137cbf66@a35g2000prf.googlegroups.com> Message-ID: <474F30FC.10705@cheimes.de> Giampaolo Rodola' wrote: > As far as I know where symlinks are not supported os.lstat should be > an alias for os.stat but I'm not 100% sure. You are right, it should be an alias. os.lstat is available on Windows, too. Christian From samwyse at gmail.com Sat Nov 24 11:27:56 2007 From: samwyse at gmail.com (samwyse) Date: Sat, 24 Nov 2007 08:27:56 -0800 (PST) Subject: the annoying, verbose self References: <3c954a31-9fb9-4c0f-b784-cef9ee057ca6@g30g2000hsb.googlegroups.com> <4068d518-cba9-4eac-bd91-11f676c17b3d@w34g2000hsg.googlegroups.com> <220d59b8-bcce-4496-beab-0976a5a83f80@g21g2000hsh.googlegroups.com> <5qqbf9F10jrh5U3@mid.uni-berlin.de> <3c561098-9229-4434-9e3b-c0aef8a4ddcd@n20g2000hsh.googlegroups.com> <5qqoguF10jrh5U5@mid.uni-berlin.de> Message-ID: On Nov 24, 7:50 am, Marc 'BlackJack' Rintsch wrote: > On Sat, 24 Nov 2007 02:54:27 -0800, samwyse wrote: > > On Nov 24, 4:07 am, Marc 'BlackJack' Rintsch wrote: > >> On Sat, 24 Nov 2007 01:55:38 -0800, samwyse wrote: > >> > I've had the same thought, along with another. You see, on of my pet > >> > peeves about all OO languages that that when creating new code, I > >> > generally begin by writing something like this: > > >> > cat = 'felix' > >> > dog = 'rover' > >> > def example(): > >> > global cat, dog # not always required, but frequently needed > >> > return ', '.join((cat, dog)) > > >> Ouch that's bad design IMHO. The need to use ``global`` is a design > >> smell, if needed *frequently* it starts to stink. > > > I'm not sure what you mean. In the example that I gave, the 'global' > > statement isn't needed. However, here's a different example: > > I mean that global names that are (re)bound from within functions couple > these functions in a non-obvious way and make the code and data flow harder > to follow and understand. Also it makes refactoring and testing more > difficult because of the dependencies. The whole point of this sub-thread is the difficulty of turning global vars and functions into class vars and functions, and that is something that is usually done precisely because the code and data flow has become harder to follow and understand. From dmitrey.kroshko at scipy.org Tue Nov 20 14:41:55 2007 From: dmitrey.kroshko at scipy.org (dmitrey) Date: Tue, 20 Nov 2007 11:41:55 -0800 (PST) Subject: Python strings question (vertical stack) References: <1c156ae2-c7ff-45b4-839b-ac54e3d48426@v4g2000hsf.googlegroups.com> Message-ID: <9a9d16a9-1e80-42a5-9027-afd84dd0ba93@l1g2000hsa.googlegroups.com> Thanks all, I have solved the problem: a=""" %s %s %s """ % ('asdf', 'asdf2', 'asdf3') print a D. From chris.cenotti at gmail.com Thu Nov 1 10:07:29 2007 From: chris.cenotti at gmail.com (chris.cenotti at gmail.com) Date: Thu, 01 Nov 2007 14:07:29 -0000 Subject: C extension question Message-ID: <1193926049.622742.56840@o3g2000hsb.googlegroups.com> I am currently trying to port some Python and Python C extension code to C#, and am having trouble understanding what is happening in a piece of the code. The pertinent pieces of code are below, and my question follows the snippets: in foo.py: (mgrid,xgrid,ygrid,zgrid,ngrids) = IP.CreateGridCell() in IP.c: static PyObject *PyCreateGridCell() { GRIDCELL *grid = alloc(...); for(i=0; i References: <1194710640.804970.28150@19g2000hsx.googlegroups.com> <4736294d$0$16656$9b4e6d93@newsspool3.arcor-online.net> <1194762719.318014.92090@o38g2000hse.googlegroups.com> Message-ID: <13je7eaiq2jg340@corp.supernews.com> oruccim at gmail.com wrote: > On 10 Kas m, 23:57, Wildemar Wildenburger > I have setuped pyx i wonder i have mistake? So far you seem to be treating this group as a free help desk for a program you have paid thousands of dollars for. See http://www.catb.org/~esr/faqs/smart-questions.html You've given a full traceback, but you have spent no effort describing what your goal is or what different things you've done to solve _your_ problem. -Scott From newsgroups at debain.org Tue Nov 20 14:04:29 2007 From: newsgroups at debain.org (Samuel) Date: Tue, 20 Nov 2007 19:04:29 +0000 (UTC) Subject: ANNOUNCE: Exscript 0.9.11 Message-ID: Introduction ------------- Exscript is a scripting language for automating Telnet or SSH sessions. It supports a wide range of features, such as parallelization, AAA authentication methods, TACACS, and a very simple template language. Please refer to the project page for updated documentation (see the links at the bottom of this announcement). New since 0.9.10 ------------------ * Support for Huawei routers was added. * It is now possible to use a different authentication and authorization passwords when using AAA. (The -a switch was added.) * It is now possible to skip the authentication procedure all-together. (The -n switch was added.) * The --no-prompt switch was added. * The priority of the "not" operator was decreased. Please refer to the documentation. * Support for regular expression modifiers was added. * The operating system and device detection mechanism was improved. * The default timeout was increased to 30 seconds (previous was 10s). * The "extract" keyword now supports a "from" operator for extracting a string from a variable. * The interpreter now has a --version flag. * Windows newline characters are now supported in exscripts. * The performance of prompt matching was greatly improved. * Cisco router detection was improved. * Fix: The "is not" operator was broken. * Fix: Escaping of "/" characters would not work. * Fix: "while" and "until" loops would sometimes not work. * Fix: Arithmetic operations with 0 no longer fail. Dependencies ------------- * Python 2.2 or greater * Python-crypto * Python-pexpect (optional, for SSH support) * ssh (optional, for SSH support) Download Exscript ------------------ Release: http://exscript.googlecode.com/files/exscript-0.9.11.tgz SVN instructions: http://code.google.com/p/exscript/source Links ------ Exscript project page: http://code.google.com/p/exscript/ Mailing list: http://groups.google.com/group/exscript Bug tracker: http://code.google.com/p/exscript/issues/list Browse the source: http://exscript.googlecode.com/svn/trunk/ From ramdaz at gmail.com Wed Nov 21 01:30:01 2007 From: ramdaz at gmail.com (Ramdas) Date: Tue, 20 Nov 2007 22:30:01 -0800 (PST) Subject: creating color gradients using PIL Message-ID: <7cb96038-9272-47ba-8c99-7e481e62ac1d@d50g2000hsf.googlegroups.com> Any ideas how we can create a color gradient using Python Imaging Library. Has any got some sample code that can give me some idea. I need to create a horizontal and vertical color gradient for a college project Thanks From steven.bethard at gmail.com Mon Nov 12 17:33:55 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 12 Nov 2007 15:33:55 -0700 Subject: optional arguments with compact reporting in optparse In-Reply-To: <1194896744.566872.191090@v65g2000hsc.googlegroups.com> References: <1194535803.845082.171590@q5g2000prf.googlegroups.com> <1194896744.566872.191090@v65g2000hsc.googlegroups.com> Message-ID: <2_-dnbaoJ59OSaXanZ2dnUVZ_gCdnZ2d@comcast.com> braver wrote: > Steve -- thanks for your pointer to argparse, awesome progress -- > optional arguments. > > However, I still wonder how I do reporting. The idea is that there > should be a list with tuples of the form: > > (short, long, value, help) > > -- for all options, regardless of whether they were specified on the > command line or not. > > Moreover, a way to create such list should be incremental -- in ruby I > define things around each option definition and add a new tuple to the > reporting list right after the block defining the option. > > The idea is, -- help should report on all options with their actual or > default values, and everything pertaining to one option -- its > definition, callbacks, and adding it to the reporting list -- must be > in vicinity of each other, so I don't forget to output some stuff > about an option ten options below... The snippet I've shown pretty > much does it in Ruby. I guess I still don't understand how that's different from what add_argument (or add_option) and print_help currently do:: >>> parser = argparse.ArgumentParser() >>> parser.add_argument('-P', nargs='?', const='data', help='PP') >>> parser.add_argument('--foo', help='FOO') >>> parser.print_help() usage: [-h] [-P [P]] [--foo FOO] optional arguments: -h, --help show this help message and exit -P [P] PP --foo FOO FOO Everything pertaining to one option is grouped together in a single add_argument call (add_option if you're using optparse). And you don't forget what to output because the print_help() method already takes care of it all. Or are you asking for more information (e.g. default values) to be included in the help output? I've been hesitant to do that automatically because often the default values do not have a useful printable form (e.g. when the default is a function or class object). > Ah, yeah, and another thing -- I want to define a module with about 10 > options common for a project. Then I'd import it in scripts, and > there should be three things doable with the preexisting default > options: > > -- turn off any of them > -- supply new defaults to any of them > -- add new options in the same way > > Wonder how brave pythonistas do that! With argparse, it would look something like:: import mod parser = argparse.ArgumentParser(parents=[mod.parser]) # supply new default parser.set_defaults(foo='bar') # add new option parser.add_argument('--bar', ...) The parents= keyword argument is documented here: http://argparse.python-hosting.com/wiki/ArgumentParser/parents Currently, there isn't a way to turn off an argument. I'd instead suggest that you create a new parser that doesn't have the extra options, and have the parser with more options include that one using parents=. STeVe From stef.mientki at gmail.com Wed Nov 28 19:22:36 2007 From: stef.mientki at gmail.com (stef mientki) Date: Thu, 29 Nov 2007 01:22:36 +0100 Subject: Very basic, sorting a list ??? Message-ID: <474E064C.9040303@gmail.com> hello, I'm trying to sort a list, using the same list at the commandline works, but in a program it doesn't. Here is the code print 'xx1',type(ordered_list) print 'xx2',ordered_list print 'xx3',ordered_list.sort() And this is the result xx1 xx2 [14, 12, 10] xx3 None What am I doing wrong ? thanks, Stef Mientki From seabruce at comcast.net Tue Nov 13 01:00:47 2007 From: seabruce at comcast.net (Bruce) Date: Mon, 12 Nov 2007 22:00:47 -0800 Subject: Can we get rid of unrelated non-python posts? Message-ID: <20071113060951.E36011E400B@bag.python.org> I joined this to read about python. Please don't respond and move to another list. Thanks! -Bruce From hv at tbz-pariv.de Tue Nov 27 08:35:34 2007 From: hv at tbz-pariv.de (Thomas Guettler) Date: Tue, 27 Nov 2007 14:35:34 +0100 Subject: Different kinds of Import Errors Message-ID: <5r2kpcF107tb7U1@mid.individual.net> If you look at this code, you see there are two kind of ImportErrors: 1. app_name has no attribute or file managment.py: That's OK. 2. managment.py exists, but raises an ImportError: That's not OK: reraise # Import the 'management' module within each installed app, to register # dispatcher events. for app_name in settings.INSTALLED_APPS: try: __import__(app_name + '.management', {}, {}, ['']) except ImportError, exc: if exc.args[0]!='No module named management': raise I am searching a better solution, since in a future version of python the string 'No module namend management' might be changed. Any better solution? From ricaraoz at gmail.com Sun Nov 11 14:18:55 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Sun, 11 Nov 2007 16:18:55 -0300 Subject: Populating a dictionary, fast In-Reply-To: <818643.92017.qm@web915.biz.mail.mud.yahoo.com> References: <818643.92017.qm@web915.biz.mail.mud.yahoo.com> Message-ID: <4737559F.50308@bigfoot.com> Michael Bacarella wrote: >>> This would seem to implicate the line id2name[id] = name as being > excruciatingly slow. >> As others have pointed out there is no way that this takes 45 >> minutes.Must be something with your system or setup. >> >> A functionally equivalent code for me runs in about 49 seconds! >> (it ends up using about twice as much ram as the data on disk) > > You can download the list of keys from here, it's 43M gzipped: > http://www.sendspace.com/file/9530i7 > > and see it take about 45 minutes with this: > > $ cat cache-keys.py > #!/usr/bin/python > v = {} > for line in open('keys.txt'): > v[long(line.strip())] = True Have you tried taking the long away? I mean : v[line.strip()] = True From austin.keeley at gmail.com Thu Nov 29 10:59:07 2007 From: austin.keeley at gmail.com (austin.keeley at gmail.com) Date: Thu, 29 Nov 2007 07:59:07 -0800 (PST) Subject: Books on Python References: Message-ID: <656b2c42-66a7-42d1-9a55-b43d0b69ecc2@e1g2000hsh.googlegroups.com> I've read "Begining Python" written by Hetland from Apress. I enjoyed it a lot. I also liked reading "Dive into Python" (also from Apress) for those who already know a language. A free edition is at diveintopython.org. From mensanator at aol.com Fri Nov 16 14:16:24 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Fri, 16 Nov 2007 11:16:24 -0800 (PST) Subject: What is python????? References: <7ab5b781-3c6c-4fb5-9be1-703d5e7e73a6@s12g2000prg.googlegroups.com> Message-ID: On Nov 16, 8:14 am, Thorsten Kampe wrote: > * Cope (Fri, 16 Nov 2007 06:09:31 -0800 (PST)) > > > please tell me what is python.This group is so crowded. > > A Python is dangerous snake[1]. This group here mainly consists of > misguided snake worshippers. You'd better run before they come to your > place... > > Thorsten > [1]http://en.wikipedia.org/wiki/Pythonidae Don't listen to him, he was joking. "Python" is short for "Monty Python's Flying Circus", a British television comedy originally from 1969-1971 (although movies, records, books and Broadway shows continue to the present). Read the documention, you'll see numerous references to spam (used in one of their famous routines) and other Pythonisms. Anyway, all the posting in this group is comedy. If you aren't getting it, run out and buy and study all the DVD's. When you've reached the point where you have The Argument Clinic dialogue memorized, come back here and all this will make sense. Just be careful, some of the Python routines aren't SUPPOSED to make sense ("cabbage crates over the how's your father"), that's the joke. From jkugler at bigfoot.com Fri Nov 30 22:12:10 2007 From: jkugler at bigfoot.com (Joshua Kugler) Date: Fri, 30 Nov 2007 18:12:10 -0900 Subject: (More) Re: Is __import__ known to be slow in windows? References: <0f6ea8d5-87f2-4c03-af82-ebb5f8187732@s36g2000prg.googlegroups.com> Message-ID: Ok, so we have this code: t = timeit.Timer(stmt='r()', setup='from __main__ import r') sys.path.insert(0,'/path/to/code') def r(): for m in ['three','module','names']: try: x = __import__(m) except ImportError, e: if not e.message.startswith('No module named'): raise x = None Each of those three module names is a directory under /path/to/code with an empty __init_.py. On Linux, the run of that code for 1000 iterations takes 0.014 CPU seconds with 0.007 of that spent in __import__(). On Windows (with on-access checking turned off), 1000 iterations takes 7.9 seconds, with 7.851 seconds of that spent in __import__(). Let's try something...let's modify the code a bit: sys.path = ['/path/to/code'] def r(): for m in ['three','module','names']: x = __import__(m) x = None cProfile.run('t.timeit(number=%s)' % number, 'stat_file') p = pstats.Stats('stat_file') p.sort_stats('time', 'cum').print_stats(.5) Now, with only my directory in sys.path, the run times are: Linux: 0.0013 (0.006 spent in __import__) Windows: 0.0012 (0.007 spent in __import__) So, it appears walking the directory trees is what is costing the time. sys.path on Windows: ['', 'C:\\Python25\\lib\\site-packages\\paste-1.5.1-py2.5.egg', 'C:\\WINDOWS\\system32\\python25.zip', 'C:\\Python25\\DLLs', 'C:\\Python25\\lib', 'C:\\Python25\\lib\\plat-win', 'C:\\Python25\\lib\\lib-tk', 'C:\\Python25', 'C:\\Python25\\lib\\site-packages', 'C:\\Python25\\lib\\site-packages\\win32', 'C:\\Python25\\lib\\site-packages\\win32\\lib', 'C:\\Python25\\lib\\site-packages\\Pythonwin'] On Linux: ['', '/usr/lib/python2.5/site-packages/setuptools-0.6c7-py2.5.egg', '/usr/lib/python2.5/site-packages/simplejson-1.7.3-py2.5-linux-i686.egg', '/usr/lib/python2.5/site-packages/Paste-1.5.1-py2.5.egg', '/usr/lib/python2.5/site-packages/TracWebAdmin-0.1.2dev-py2.5.egg', '/home/jkugler/programming', '/usr/lib/python25.zip', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/local/lib/python2.5/site-packages', '/usr/lib/python2.5/site-packages', '/var/lib/python-support/python2.5', '/usr/lib/site-python'] So, not identical (actually, longer on linux) but similar. Interesting, at any rate. j From andre.roberge at gmail.com Wed Nov 28 21:39:13 2007 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Wed, 28 Nov 2007 18:39:13 -0800 (PST) Subject: Any Pythonista knowing Estonian on this list? Message-ID: <2f7be902-7929-46ec-9924-a82366e2f221@r60g2000hsc.googlegroups.com> Some of the tasks that are part of Google's H.O.P. involved translation (i18n) of some well-known ... and some lesser known projects. I have received a translation in Estonian for Crunchy - probably of the order of a 100 phrases. I just want to make sure that no practical joke has been played in doing the translations ... my Estonian is None. Anyone with basic reading knowledge of Estonian is more than welcome to contact me. Andr? From kyosohma at gmail.com Mon Nov 19 11:44:07 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 19 Nov 2007 08:44:07 -0800 (PST) Subject: Python too complex ?!?!?! References: <7hC%i.28332$mv3.17248@newsfe10.phx> Message-ID: <22654bec-75de-449a-9104-2c822e5e0944@w34g2000hsg.googlegroups.com> On Nov 19, 9:57 am, "Chris Mellon" wrote: > On Nov 19, 2007 8:52 AM, wrote: > > > > > > > On Nov 17, 7:46 am, Brian wrote: > > > Had a unsettling conversation with a CS instructor that > > > teaches at local high schools and the community > > > college. This person is a long-term Linux/C/Python > > > programmer, but he claims that the install, config, and > > > library models for C# have proved to be less > > > problematic than Python. So both his courses (intro, > > > data structs, algorithms) are taught in C#. > > > > I am a low-end (3-year) journeyman Pythonista, and I > > > was attracted to the language because of its > > > simplicity. And I have come to enjoy the richness of > > > available libraries. > > > > Many of the good people of this NG may be 'too close' > > > to answer, but has Python, as a general devel platform, > > > lost its simplicity ? Is library install too complex > > > and unreliable ? Will my dog go to heaven ? > > > If this professor was only using Windows for his environment, then I > > might be able to understand his argument better. There are many more > > external modules for Python that don't have Windows installers than > > there are with binaries. And I've had more than my fair share of > > broken setup.py files. > > > On the other hand, if all that is needed are the standard libraries, > > than it's a breeze to install Python since they're all included. > > > Mike > > These modules exist, but aren't that common. Certainly anything you're > likely to be using in an introductory compsci course is well packaged. > And even if it's not, it's really not that hard to create packages or > installers - a days work of course prep would take care of the > potential problem. I stand corrected. Thanks for the clarification. Mike From aclarke11 at yahoo.co.uk Thu Nov 15 16:19:19 2007 From: aclarke11 at yahoo.co.uk (Tony) Date: Thu, 15 Nov 2007 13:19:19 -0800 (PST) Subject: Python beginner! References: <473cb2a4$0$27124$9b4e6d93@newsspool1.arcor-online.net> Message-ID: On Nov 15, 8:57 pm, Wildemar Wildenburger wrote: > > Please read this: > > > Then ask again. > > /W Give me back the old comp.lang.python, where anyone could ask anything and be sure of a range of replies, instead of this sort of pedanticism. Sorry, nothing personal, maybe Python users have become too professional and geeky to remember that Python's main objective is fun, that is why it is called Python. Telling the asker to go and learn how to ask properly is not fun, it reeks of arrogance, high handedness and rejection of newcomers. Nothing personal Wildemar, I have seen lots of others reply in a similar fashion. Am I alone in thinking this group has changed in these ways? Tony From jjl at pobox.com Tue Nov 20 15:50:37 2007 From: jjl at pobox.com (John J. Lee) Date: Tue, 20 Nov 2007 20:50:37 GMT Subject: Should proxy objects lie about their class name? Message-ID: <87lk8szlnm.fsf@pobox.com> Not much to add to the subject line. I mean something like this: ProxyClass.__name__ = ProxiedClass.__name__ I've been told that this is common practice. Is it? Would this surprise you if you ran into it in a debugging session? One very real advantage that I can see is avoiding breaking existing doctests. Thanks in advance for your views John From ptmcg at austin.rr.com Mon Nov 19 12:42:00 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 19 Nov 2007 09:42:00 -0800 (PST) Subject: regular expression References: <4740ad46$0$21929$157c6196@dreader1.cybercity.dk> <5qbqkdFv8380U1@mid.uni-berlin.de> <474164b9$0$7607$157c6196@dreader2.cybercity.dk> Message-ID: Sorry about your coffee cup! Would you be interested in a pyparsing rendition? -- Paul from pyparsing import * def defineGrammar(): ParserElement.setDefaultWhitespaceChars(" \t") ident = Word(alphanums+"_") LT,GT = map(Suppress,"<>") NL = LineEnd().suppress() real = Word(nums,nums+".") integer = Word(nums) quotedString = QuotedString('"') dataValue = real | integer | Word(alphas,alphanums) | quotedString dataDef = ident + ZeroOrMore(dataValue) + NL tagDef = Forward() tagDef << LT + ident + ZeroOrMore(dataValue) + NL + \ Dict(ZeroOrMore(Group(dataDef) | Group(tagDef))) + GT + NL tagData = Dict(OneOrMore(Group(tagDef))) return tagData results = defineGrammar().parseString(TESTTXT) print( results.dump() ) print results.REAPER_PROJECT.TRACK.keys() print results.REAPER_PROJECT.TRACK.PANENV2 print results.REAPER_PROJECT.TRACK.PANENV2.ACT prints out: [['REAPER_PROJECT', '0.1', ['METRONOME', '6', '2.000000', ['SAMPLES', '', '']], ['TRACK', ['MAINSEND', '1'], ['VOLENV2', ['ACT', '1']], ['PANENV2', ['ACT', '1']]]]] - REAPER_PROJECT: ['0.1', ['METRONOME', '6', '2.000000', ['SAMPLES', '', '']], ['TRACK', ['MAINSEND', '1'], ['VOLENV2', ['ACT', '1']], ['PANENV2', ['ACT', '1']]]] - METRONOME: ['6', '2.000000', ['SAMPLES', '', '']] - SAMPLES: ['', ''] - TRACK: [['MAINSEND', '1'], ['VOLENV2', ['ACT', '1']], ['PANENV2', ['ACT', '1']]] - MAINSEND: 1 - PANENV2: [['ACT', '1']] - ACT: 1 - VOLENV2: [['ACT', '1']] - ACT: 1 ['PANENV2', 'MAINSEND', 'VOLENV2'] [['ACT', '1']] 1 From bjourne at gmail.com Tue Nov 13 10:07:05 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Tue, 13 Nov 2007 16:07:05 +0100 Subject: Iterator for circulating a list In-Reply-To: <1194964982.3486.5.camel@dot.uniqsys.com> References: <740c3aec0711130612rce48033u1273ee48391ac55b@mail.gmail.com> <1194964982.3486.5.camel@dot.uniqsys.com> Message-ID: <740c3aec0711130707p687dafa3jd38d6ba1b7351bcd@mail.gmail.com> On Nov 13, 2007 3:43 PM, Carsten Haese wrote: > On Tue, 2007-11-13 at 15:12 +0100, BJ?rn Lindqvist wrote: > > L = somelist > > > > idx = 0 > > while True: > > item = L[idx] > > # Do something with item > > idx = (idx + 1) % len(L) > For begin=0 and step=1, itertools.cycle does exactly that. For arbitrary > offsets or different steps, you'd have to combine cycle with islice. *slap forehead* Figures.. I actually read the itertools.cycle documentation but I didn't realize that it was (almost) equivalent to my code. Thanks for that. -- mvh Bj?rn From hv at tbz-pariv.de Wed Nov 28 05:37:01 2007 From: hv at tbz-pariv.de (Thomas Guettler) Date: Wed, 28 Nov 2007 11:37:01 +0100 Subject: tcp traceroute Message-ID: <5r4umeF12ln4cU1@mid.individual.net> Hi, I want to write a small tcp traceroute script. I works, but how can I get the IP of the hop that send 'no route to host'? Result: python tmp/tcptraceroute.py a.b.c.d 80 ttl=01: (113, 'No route to host') ttl=02: (113, 'No route to host') ttl=03: (113, 'No route to host') ttl=04: timed out ttl=05: timed out ttl=06: timed out ttl=07: timed out ttl=08: timed out ttl=09: OK #!/usr/bin/env python # tcptraceroute.py # This script is in the public domain import os import sys import struct import socket def usage(): print '''Usage: %s host port Tries to connect to host at TCP port with increasing TTL (Time to live). ''' % os.path.basename(sys.argv[0]) def main(): if not len(sys.argv)==3: usage() sys.exit(1) ttl=1 host, port = sys.argv[1:] port=int(port) for ttl in range(1, 30): s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.IPPROTO_IP, socket.IP_TTL, struct.pack('I', ttl)) s.settimeout(2) try: s.connect((host, port)) except (socket.error, socket.timeout), err: print 'ttl=%02d: %s' % (ttl, err) s.close() continue except KeyboardInterrupt: print 'ttl=%02d (KeyboardInterrupt)' % ttl break print 'ttl=%02d: OK' % (ttl) break if __name__=='__main__': main() From kyosohma at gmail.com Thu Nov 8 15:52:11 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 08 Nov 2007 12:52:11 -0800 Subject: Anyone had success using NetUseAdd() on shares accessed through a Windows 2003 DFS root? In-Reply-To: References: Message-ID: <1194555131.308081.298890@i38g2000prf.googlegroups.com> On Nov 8, 2:23 pm, Sean Peterson wrote: > Has anyone had success using NetUseAdd() on shares that were replica links on a Windows 2003 DFS root? In my code, I'm getting error: > > pywintypes.error: (67, 'NetUseAdd', 'The network name cannot be found.') > > This is my scenario: > > Win2003 Server hosting DFS root #NTS-03 > \\NTS-03.central.purdue.lcl\MI > > Win2003 Server hosting file share > \\itifs03.itap.purdue.edu\itea_zonedirs\MI > > > > import win32net > > # this works -- > win32net.NetUseAdd(None,1,{'remote':r'//itifs03.itap.purdue.edu/itea_zonedirs/MI/TEAMDIRS/DCS > Zone','local':'W:'}) > > # this doesn't work -- > win32net.NetUseAdd(None,1,{'remote':r'//NTS-03.central.purdue.lcl/MI/TEAMDIRS/DCS > Zone','local':'W:'}) > > > > Any help greatly appreciated. > > -Sean. I'm not seeing any typos in your code...but it looks like you're trying to map two different locations to the same drive letter. Maybe that's throwing an error in and of itself? From mail at timgolden.me.uk Fri Nov 2 04:29:13 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 02 Nov 2007 08:29:13 +0000 Subject: Syntax coloring in Python interpreter In-Reply-To: References: <1193939152.721480.140500@22g2000hsm.googlegroups.com> Message-ID: <472ADFD9.10609@timgolden.me.uk> Neil Cerutti wrote: > On 2007-11-01, Chris Mellon wrote: >> On Nov 1, 2007 3:01 PM, Neil Cerutti wrote: >>> On 2007-11-01, Lee Capps wrote: >>>> On Nov 1, 2007, at 1:45 PM, braver wrote: >>>>> Greetings -- as a long time user of both Python and Ruby >>>>> interpreters, I got used to the latter's syntax-coloring gem, >>>>> wirble, which colorizes Ruby syntax on the fly. Is there >>>>> anything similar for Python? >>>>> >>>> I believe IPython can do this: >>>> >>>> http://ipython.scipy.org/moin/ >>> IPython's syntax coloring doesn't work with Windows 2000 and >>> up, since (last I checked) it relies on a readline.py file, >>> which relies on ANSI.SYS, which is not supported by the >>> Windows console. >> If you scroll down about half a page in the above link you'll >> find a link to a readline implementation for Windows. > > That pyreadline.py appears to be an improvement on the Windows > support when I last looked (6 months or so ago). Thanks for the > heads up. > And it's worth looking at ipykit[1] which is a standalone bundle of ipython py2exe-ed for Windows users. TJG [1] http://ipython.scipy.org/moin/IpyKit From cadet.bramble at gmail.com Thu Nov 22 15:53:42 2007 From: cadet.bramble at gmail.com (bramble) Date: Thu, 22 Nov 2007 12:53:42 -0800 (PST) Subject: tidy project file organization (modules and tests) Message-ID: What's the customary way to organize your project files -- particularly modules? Does the following look correct? my_project/ main_script.py doc/ [...] whatever/ [...] lib/ mymod1.py mymod2.py test/ test_mymod1.py test_mymod2.py some_pkg/ __init__.py goodmod1.py goodmod2.py test/ test_goodmod1.py test_goodmod2.py That is, my project may contain some local project-specific modules (mymod1, mymod2), but also some in a package that I reuse here and there in other projects too (some_pkg.goodmod1, some_pkg.goodmod2). What's the usual name and placement of the file that runs all the tests? Finally, if anyone could point me toward any exemplary modules in the cheeshop that have a tidy project file layout, it would be most helpful. Thanks. From tavspamnofwd at googlemail.com Wed Nov 14 12:56:25 2007 From: tavspamnofwd at googlemail.com (tavspamnofwd at googlemail.com) Date: Wed, 14 Nov 2007 17:56:25 -0000 Subject: making a typing speed tester Message-ID: <1195062985.208745.156930@o38g2000hse.googlegroups.com> Referred here from the tutor list. > I'm trying to write a program to test someones typing speed and show > them their mistakes. However I'm getting weird results when looking > for the differences in longer (than 100 chars) strings: > > import difflib > > # a tape measure string (just makes it easier to locate a given index) > a = > '1-3-5-7-9-12-15-18-21-24-27-30-33-36-39-42-45-48-51-54-57-60-63-66-69 > -72-75-78-81-84-87-90-93-96-99-103-107-111-115-119-123-127-131-135-139 > -143-147-151-155-159-163-167-171-175-179-183-187-191-195--200' > > # now with a few mistakes > b = '1-3-5-7- > l-12-15-18-21-24-27-30-33-36-39o42-45-48-51-54-57-60-63-66-69-72-75-78 > -81-84-8k-90-93-96-9l-103-107-111-115-119-12b-1v7-131-135-139-143-147- > 151-m55-159-163-167-a71-175j179-183-187-191-195--200' > > s = difflib.SequenceMatcher(None, a ,b) > ms = s.get_matching_blocks() > > print ms > >>>> [(0, 0, 8), (200, 200, 0)] > > Have I made a mistake or is this function designed to give up when the > input strings get too long? If so what could I use instead to compute > the mistakes in a typed text? ---------- Forwarded message ---------- From: Evert Rol Hi Tom, Ok, I wasn't on the list last year, but I was a few days ago, so persistence pays off; partly, as I don't have a full answer. I got curious and looked at the source of difflib. There's a method __chain_b() which sets up the b2j variable, which contains the occurrences of characters in string b. So cutting b to 199 characters, it looks like this: b2j= 19 {'a': [168], 'b': [122], 'm': [152], 'k': [86], 'v': [125], '-': [1, 3, 5, 7, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99, 103, 107, 111, 115, 119, 123, 127, 131, 135, 139, 143, 147, 151, 155, 159, 163, 167, 171, 179, 183, 187, 191, 195, 196], 'l': [8, 98], 'o': [39], 'j': [175], '1': [0, 10, 13, 16, 20, 50, 80, 100, 104, 108, 109, 110, 112, 113, 116, 117, 120, 124, 128, 130, 132, 136, 140, 144, 148, 150, 156, 160, 164, 170, 172, 176, 180, 184, 188, 190, 192], '0': [29, 59, 89, 101, 105, 198], '3': [2, 28, 31, 32, 34, 37, 62, 92, 102, 129, 133, 137, 142, 162, 182], '2': [11, 19, 22, 25, 41, 71, 121, 197], '5': [4, 14, 44, 49, 52, 55, 74, 114, 134, 149, 153, 154, 157, 174, 194], '4': [23, 40, 43, 46, 53, 83, 141, 145], '7': [6, 26, 56, 70, 73, 76, 106, 126, 146, 166, 169, 173, 177, 186], '6': [35, 58, 61, 64, 65, 67, 95, 161, 165], '9': [38, 68, 88, 91, 94, 97, 118, 138, 158, 178, 189, 193], '8': [17, 47, 77, 79, 82, 85, 181, 185]} This little detour is because of how b2j is built. Here's a part from the comments of __chain_b(): # Before the tricks described here, __chain_b was by far the most # time-consuming routine in the whole module! If anyone sees # Jim Roskind, thank him again for profile.py -- I never would # have guessed that. And the part of the actual code reads: b = self.b n = len(b) self.b2j = b2j = {} populardict = {} for i, elt in enumerate(b): if elt in b2j: indices = b2j[elt] if n >= 200 and len(indices) * 100 > n: # <--- !! populardict[elt] = 1 del indices[:] else: indices.append(i) else: b2j[elt] = [i] So you're right: it has a stop at the (somewhat arbitrarily) limit of 200 characters. How that exactly works, I don't know (needs more delving into the code), though it looks like there also need to be a lot of indices (len(indices*100>n); I guess that's caused in your strings by the dashes, '1's and '0's (that's why I printed the b2j string). If you feel safe enough and on a fast platform, you can probably up that limit (or even put it somewhere as an optional variable in the code, which I would think is generally better). Not sure who the author of the module is (doesn't list in the file itself), but perhaps you can find out and email him/her, to see what can be altered. Hope that helps. Evert From sndive at gmail.com Tue Nov 13 17:59:56 2007 From: sndive at gmail.com (sndive at gmail.com) Date: Tue, 13 Nov 2007 22:59:56 -0000 Subject: private data stashed in local/global execution context of PyEval_EvalCode disappears down the execution stack In-Reply-To: References: <1194402317.678614.142450@y42g2000hsy.googlegroups.com> <1194988694.381313.202490@v65g2000hsc.googlegroups.com> Message-ID: <1194994796.459038.310970@v2g2000hsf.googlegroups.com> On Nov 13, 3:31 pm, "Chris Mellon" wrote: > On Nov 13, 2007 3:18 PM, wrote: > > > On Nov 9, 5:36 pm, "Gabriel Genellina" wrote: > > > En Tue, 06 Nov 2007 23:25:17 -0300, escribi?: > > > > One should make a lot of assumptions about your code because it's not > > > complete. Please post a minimal complete example showing your problem. > > > It's a rather large program. My assumption was that just posting the > > snippet around the call site and the callee pathetic attempt > > to extract interp would be sufficient :( > > The creation of a minimal runnable sample is a fantastic way to find > any bugs in your code, and has the benefit of (if the bug is not in > your code) giving other people a simple way to recreate the bug. If I > were to check this (and I'm not, but I would if you'd posted runnable > code) I'll have to write the code myself from your textual > description. Then, if the code works, I'll have to post the code that > I wrote as well as my negative response, and go through several back > and forths trying to isolate any differences between what I wrote and > what you wrote but didn't show. That's way more work than I'm willing > to do to solve someone else's problem. > > In my experience, creating a minimal sample that demonstrates the bug > will lead you to the actual bug more than half the time. That's a lot > of time (yours and other peoples) that can be saved if you do it. working on a smaller example. i could not get pyNode_root invoked yet and PyRun_String("import node\nprint node.root()\n", Py_file_input, exec, g_maindict); triggers Py_CompileString failure with Traceback (most recent call last): File "", line 1, in ? ImportError: __import__ not found without RyRun_String call program runs but the pyNode_root is not invoked #undef _POSIX_C_SOURCE #include #ifndef PyMODINIT_FUNC /* declarations for DLL import/export */ #define PyMODINIT_FUNC void #endif PyObject *g_mainmod; PyObject *g_maindict; bool worked = false; static PyObject * pyNode_root(PyObject *self, PyObject *args) { PyObject *dict = PyEval_GetGlobals(); PyObject *co = PyDict_GetItemString(dict, "interp"); assert(PyCObject_Check(co)); void *interp = PyCObject_AsVoidPtr(co); assert(interp); // ... printf("root() worked\n"); worked=true; return 0; } static PyMethodDef module_methods[] = { /* no need to create pyNode from python programs {"new", pyNode_new, METH_VARARGS, PyDoc_STR("new() -> new Node object")}, */ {"root", pyNode_root, METH_VARARGS, PyDoc_STR("root('dm') -> wrapper for the rootnode")}, {NULL} /* Sentinel */ }; int main() { Py_Initialize(); g_mainmod = PyImport_AddModule("__main__"); assert(g_mainmod); g_maindict = PyModule_GetDict(g_mainmod); assert(g_maindict); Py_INCREF(g_maindict); // it was a borrowed reference PyObject* m = Py_InitModule("node", module_methods); if (m == NULL) return 1; PyObject *exec = PyDict_New(); void *handle = (void*)0xdeadc0ed; PyObject *ih = PyCObject_FromVoidPtr(handle, NULL); int st= PyDict_SetItemString(exec, "interp", ih); assert(!st); PyRun_String("import node\nprint node.root()\n", Py_file_input, exec, g_maindict); PyObject *mScriptHandle= Py_CompileString("import node\nprint node.root()\n", "comp", Py_file_input); if(!mScriptHandle) { PyErr_Print(); return 2; } PyObject *res = PyEval_EvalCode((PyCodeObject*)mScriptHandle, exec, g_maindict); assert(res=Py_None); // compiled as file_input assert(worked); } From nulla.epistola at web.de Wed Nov 21 15:02:47 2007 From: nulla.epistola at web.de (Hertha Steck) Date: Wed, 21 Nov 2007 21:02:47 +0100 Subject: import pysqlite2 or import sqlite3? Message-ID: Hello, I'm using Python 2.5.1, Pysqlite 2.3.5 and SQLite 3.4.1 on Gentoo Linux. I've always imported pysqlite using from pysqlite2 import dbapi2 and that works. If I try import sqlite3 I get Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.5/sqlite3/__init__.py", line 24, in from dbapi2 import * File "/usr/lib/python2.5/sqlite3/dbapi2.py", line 27, in from _sqlite3 import * ImportError: No module named _sqlite3 And I thought that's normal, there is no Python module called sqlite3. Then, after a discussion in the Gentoo forum, I saw this in the Python library reference: > To use the module, you must first create a Connection object that represents the database. Here the data will be stored in the /tmp/example file: > > conn = sqlite3.connect('/tmp/example') > No import statement, though, so the module might have been renamed in that statement. Possibly not a really good idea in the documentation. But now I see an old post to c.p.l: > I'm using Ubuntu Feisty: > * Python 2.5.1 (r251:54863, May 2 2007, 16:56:35) > [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 > * SQLite version 3.3.13 > > Suppose I run the following program: > import sqlite3 > > conn = sqlite3.connect('example') ... And from the rest of the posting that import seems to work. Has that module different names for different Linux distributions? Or what's the matter here? From peter.j.bismuti at boeing.com Tue Nov 13 10:34:30 2007 From: peter.j.bismuti at boeing.com (Peter J. Bismuti) Date: Tue, 13 Nov 2007 07:34:30 -0800 Subject: how can I interpret a file within the interactive interpreter Message-ID: <200711130734.30605.peter.j.bismuti@boeing.com> I want to interpret a file (or whatever you call it) and then keep the interactive interpreter alive so I can then continue to issue commands. How can this be done? I saw online a -m flag but it does not seem to work. Thanks -- Peter Bismuti Boeing From arkanes at gmail.com Mon Nov 26 11:50:39 2007 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 26 Nov 2007 10:50:39 -0600 Subject: better way to write this function In-Reply-To: <87y7clpdep.fsf@rudin.co.uk> References: <4b4d9cc5-3759-421e-b3a2-3cb25bdaae7a@b40g2000prf.googlegroups.com> <87y7clpdep.fsf@rudin.co.uk> Message-ID: <4866bea60711260850o614d832fs344186f765394f5d@mail.gmail.com> On Nov 26, 2007 3:24 AM, Paul Rudin wrote: > Kelie writes: > > > Hello, > > > > This function does I what I want. But I'm wondering if there is an > > easier/better way. To be honest, I don't have a good understanding of > > what "pythonic" means yet. > > > > def divide_list(lst, n): > > """Divide a list into a number of lists, each with n items. Extra > > items are > > ignored, if any.""" > > cnt = len(lst) / n > > rv = [[None for i in range(n)] for i in range(cnt)] > > for i in range(cnt): > > for j in range(n): > > rv[i][j] = lst[i * n + j] > > return rv > > > > Thanks! > > See the last recipe from: > http://docs.python.org/lib/itertools-recipes.html. It's not doing > quite the same thing, but gives an illustration of one way to approach > this sort of thing. > > -- > http://mail.python.org/mailman/listinfo/python-list > The one in the sample consumes the entire sequence up front, too. It's trivial to write a fully generator based one (and only slightly more work to implement an iterator that doesn't rely on generators, if you want to avoid the slight performance hit), but there's a few subtle issues and I too think that we really should have a good one ready for use in itertools. Maybe I should write a patch. From samwyse at gmail.com Sat Nov 24 11:50:57 2007 From: samwyse at gmail.com (samwyse) Date: Sat, 24 Nov 2007 08:50:57 -0800 (PST) Subject: the annoying, verbose self References: <3c954a31-9fb9-4c0f-b784-cef9ee057ca6@g30g2000hsb.googlegroups.com> <4068d518-cba9-4eac-bd91-11f676c17b3d@w34g2000hsg.googlegroups.com> <5qq6quF10jrh5U2@mid.uni-berlin.de> <5qqoslF10jrh5U6@mid.uni-berlin.de> Message-ID: <7727e296-993e-4d41-99b7-26f083aa6e17@e25g2000prg.googlegroups.com> On Nov 24, 10:07 am, Duncan Booth wrote: > Ton van Vliet wrote: > > > It would boil down to choice: explicit/speed vs implicit/readability > > No, it would boil down to explicit+speed+readability+maintainability vs > implicit+error prone. > > It would mean that as well as the interpreter having to search the > instance to work out whether each name referenced an attribute or a global > the reader would also have to perform the same search. It would mean that > adding a new attribute to an instance would change the meaning of the > methods which is a recipe for disaster. Besides Pascal, Visual Basic also offers a 'with' statement that behaves almost in this way. That in itself should be an indication that the whole thing is a bad idea. ;-) The way it works, however, is that you do have to prefix members with a '.' and the interpreter tries to bind with each nested 'with' variable in turn. It's tolerable with one 'with' statment, but once you start nesting them it becomes dangerous. My idea in a parallel thread is to treat a '.' prefix like '../' in file paths; each one moves you up a level in the symbol table. In a top-level function, it means a global name; in a class method it means a member. The @classmethod and @staticmethod decorators would need to fix things so that '.' refers to the appropriate things. There's no reason why a 'using' statement couldn't perform nesting as well: '.' refers to the 'using' variable, '..' refers to what '.' previously referred to, etc. OTOH, the point of 'using' is to reduce typing, so you might instead add 'as' clauses as an alternate way to reduce confusion: >>> using myclass.new() as p: p.do_something() p.something_else() Of course, now its starting to look more like a Python 'with' statement, and I think there's a way to do basically this already. From sndive at gmail.com Wed Nov 14 20:15:23 2007 From: sndive at gmail.com (sndive at gmail.com) Date: Wed, 14 Nov 2007 17:15:23 -0800 (PST) Subject: problem calling ElementTree._ElementInterface.find with PyObject_CallObject Message-ID: <2f354255-3ad8-42ad-aeca-5fc6966b6b8c@w28g2000hsf.googlegroups.com> I have a weid problem. If i do this: import elementtree.ElementTree as ET ... tree = ET.parse("whatever") root = tree.getroot() r = root.find('last') print r return root where last is not an immediate child of root node i get back None. However if i comment the r = root.find('last') print r part out and PyObject_CallObject on root from c++ space i get Traceback (most recent call last): File "/var/tmp/build/x86-ezx/lib/python2.4/site-packages/elementtree/ ElementTree.py", line 329, in find return ElementPath.find(self, path) File "/var/tmp/build/x86-ezx/lib/python2.4/site-packages/elementtree/ ElementPath.py", line 188, in find return _compile(path).find(element) File "/var/tmp/build/x86-ezx/lib/python2.4/site-packages/elementtree/ ElementPath.py", line 178, in _compile p = Path(path) File "/var/tmp/build/x86-ezx/lib/python2.4/site-packages/elementtree/ ElementPath.py", line 70, in __init__ tokens = xpath_tokenizer(path) AttributeError: _ElementInterface instance has no attribute 'last' (the call to PyObject_CallObject works fine if root.find on the requested attribute was performed first from python space!!!) this is with ElementTree 1.2.6 if that matters here at all From alfred.fazio at gmail.com Wed Nov 28 03:37:07 2007 From: alfred.fazio at gmail.com (alfred.fazio at gmail.com) Date: Wed, 28 Nov 2007 00:37:07 -0800 (PST) Subject: Unexpected behavior when initializing class References: <8763zmhiuw.fsf@rudin.co.uk> Message-ID: <593cea76-4f72-4a7b-89f2-be31d670e76a@b40g2000prf.googlegroups.com> On Nov 28, 3:31 am, Paul Rudin wrote: > You have to understand that the default value for v - an empty list - > is made at compile time - and it's the *same* list every time it's > used i.e. if you don't pass in a value for v when you make new > instances of your class. *smack*!! That's me smacking myself on the forehead. I now remember reading a long time ago that this was an FAQ! Thanks for the reply, Paul. :) Alfred J. Fazio, alfred.fazio at gmail.com From bignose+hates-spam at benfinney.id.au Thu Nov 8 19:15:02 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 09 Nov 2007 11:15:02 +1100 Subject: [OT] Stupid email disclaimers (was: Creating a cell 'by hand') References: <1194508354.226023.232050@v3g2000hsg.googlegroups.com> <1194561005.427982.263160@s15g2000prm.googlegroups.com> <004801c8225e$49843350$dc8c99f0$@com> Message-ID: <87wsss9svt.fsf_-_@benfinney.id.au> "Prepscius, Colin (IT)" writes: > NOTICE: If received in error, If I've received it, it's not "received in error", it's received successfully. If, instead, you're referring to the actual recipient being different from the intended recipient, why are you putting this judgement onto the actual recipient? Surely they're in no position to judge the intentions of the sender. > please destroy and notify sender. (Insert humour regarding different parsings of the grammar in the above.) In that order? If I'm supposed to notify the sender, I have to re-transmit the message or at least part of it. That seems quite the opposite of destroying it. > Sender does not intend to waive confidentiality or privilege. Then perhaps sender should not be posting to a public forum. There is *no* confidentiality or privilege in postings to this forum, so this disclaimer is null and void. > Use of this email is prohibited when received in error. There's no way for a recipient to know whether they're in such a "prohibited" zone. Don't make such threatening statements to an entire community, please. In general: Please, don't attach these disclaimers and threats to messages ? *especially* on a public forum. If you're choosing to apply them to your messages, please stop. If, on the other hand, your organisation is applying them indiscriminately to every outgoing message, even in cases where there's no such thing as "confidentiality" or "privilege", then they're mindlessly undermining the meaning of those terms. Please get your organisation to *only* apply these threats and disclaimers where they have meaning. -- \ "Earth gets its price for what Earth gives us." -- James | `\ Russell Lowell | _o__) | Ben Finney From theller at ctypes.org Fri Nov 2 06:03:57 2007 From: theller at ctypes.org (Thomas Heller) Date: Fri, 02 Nov 2007 11:03:57 +0100 Subject: trapping DLL import issues without blocking pop up window In-Reply-To: References: Message-ID: alf schrieb: > Hi, > > there is following issue: "import cx_Oracle" on windows pops up a nice > 'DLL missing' window in case there indeed is no CLI.DLL (or something > like that). Then the exception is raised. > > Catching the exception is obviously not a problem, but the popup > practically blocks the application and requires user intervention. > > There could be a legitimate case where Oracle environment is not > available yet the program might want to get around it somehow. Executing this code before 'import cx_Oracle' should help: import ctypes; ctypes.windll.kernel32.SetErrorMode(1) See also http://msdn2.microsoft.com/en-us/library/ms680621.aspx Thomas From bborcic at gmail.com Mon Nov 26 12:01:04 2007 From: bborcic at gmail.com (Boris Borcic) Date: Mon, 26 Nov 2007 18:01:04 +0100 Subject: How to write Regular Expression for recursive matching? In-Reply-To: References: Message-ID: lisong wrote: > Hi All, > > I have problem to split a string like this: > > 'abc.defg.hij.klmnop' > > and I want to get all substrings with only one '.' in mid. so the > output I expect is : > > 'abc.defg', 'defg.hij', 'hij.klmnop' > > a simple regular expression '\w+.\w' will only return: > 'abc.defg', 'hij.klmnop' > > is there a way to get 'defg.hij' using regular expression? > > Thanks, > Do you need it to be a regular expression ? >>> def f(s) : ws = s.split('.') return map('.'.join,zip(ws,ws[1:])) >>> f('abc.defg.hij.klmnop') ['abc.defg', 'defg.hij', 'hij.klmnop'] From ptmcg at austin.rr.com Tue Nov 27 01:00:53 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 26 Nov 2007 22:00:53 -0800 (PST) Subject: can any one tell me where to get graphics module in windows? References: Message-ID: <6a36bdad-5fc3-464c-8ba0-14b5b001991f@s12g2000prg.googlegroups.com> On Nov 26, 11:49 pm, evilcraft_mj wrote: > when i type > from graphics import * > > error shown that there is no such module called graphics. > > help me find this...... Googling for "python graphics module" turns up this link: http://mcsp.wartburg.edu/zelle/python/graphics/graphics/index.html -- Paul From khemkaamit at gmail.com Sat Nov 17 07:00:03 2007 From: khemkaamit at gmail.com (Amit Khemka) Date: Sat, 17 Nov 2007 17:30:03 +0530 Subject: What is python????? In-Reply-To: References: <7ab5b781-3c6c-4fb5-9be1-703d5e7e73a6@s12g2000prg.googlegroups.com> <959349ce-34ad-4d8e-aea0-b7bcbbc6112f@f13g2000hsa.googlegroups.com> <4a92044d-ef1b-47b0-82e0-45946e08a794@n20g2000hsh.googlegroups.com> <828cecd6-40b9-4aaf-bb07-8386b6c7518e@f3g2000hsg.googlegroups.com> Message-ID: <1360b7230711170400s2ee9cf4by7bc38b9b57cbcbae@mail.gmail.com> On 11/17/07, Cope wrote: > > In our place we eat pythons for curry. Its delicious. > And how about your python? > > Cope Not much of the difference here, it is just a bit more flexible. My python goes and brings me whatever I wish to eat. Cheers, -- -- Amit Khemka From bj_666 at gmx.net Fri Nov 9 12:22:02 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 9 Nov 2007 17:22:02 GMT Subject: Some "pythonic" suggestions for Python References: <5PGdnWmWZIdZ967anZ2dnUVZ_uuqnZ2d@cavtel.net> <47338e4c$0$30952$426a74cc@news.free.fr> <9qGdnadjs6a76ananZ2dnUVZ_q2hnZ2d@cavtel.net> Message-ID: <5pjj9qFqjhclU5@mid.uni-berlin.de> On Fri, 09 Nov 2007 11:41:24 -0500, Frank Samuelson wrote: >> There are at least 2 posts a month by someone who decides that they >> want to re-wire Python syntax. Usually it's because of some particular >> idiom they're used to in another language, > > And python does not use idioms from other languages? It does. So what? Does that mean any idiom from any other language makes sense in Python? >> in other cases it's because they've got some particular issue with >> "consistency". > > My impression was that "consistency" was important to Python. It is but to quote a headline from the Python style guide: `A Foolish Consistency is the Hobgoblin of Little Minds`. > "Consistency" improves my productivity because I don't have to keep > referring to the manual. Things work the way I expect them to work. I expect meaningful function names in tracebacks. >> The ideas are *never* fully thought out or materialized, and they >> invariably invite scorn from the user community. > > Of course, they're thought out: They're stolen from another language. > Specifically, the language in which I am most productive. They are not thought out. You just ripped an aspect from that other language and threw it into a Python environment. This doesn't mean it will fit into the language or scales beyond the small toy examples. What about function names in tracebacks? What about nesting these anonymous multiline functions? What about the impact on the grammar? Ciao, Marc 'BlackJack' Rintsch From peter.j.bismuti at boeing.com Tue Nov 13 12:39:21 2007 From: peter.j.bismuti at boeing.com (Peter J. Bismuti) Date: Tue, 13 Nov 2007 09:39:21 -0800 Subject: module data member? In-Reply-To: <5pu4r0Fsji73U1@mid.uni-berlin.de> References: <5pu4r0Fsji73U1@mid.uni-berlin.de> Message-ID: <200711130939.21362.peter.j.bismuti@boeing.com> This did the trick for the most part, but it still leaves a copy of the variable A in the "non-module" global namespace (see output below). I want A declared global to the module (so as not to be local within the functions of the module) but not visible outside of the module namespace (like B, see below). How can this be done? Thanks again python -i test.py :>>> print test.A 10 :>>> print A 0 :>>> print B Traceback (most recent call last): File "", line 1, in ? NameError: name 'B' is not defined ____test.py___ A = 0 def getA(): global A return A def run(): global A A = 10 if (__name__=="__main__"): import test test.run() ______ > def main(): > # do mainy stuff here > > if __name__ == "__main__": > import myself > myself.main() > > This of course won't prevent __main__ to be existant, nor running possible > initialization code twice. But if the module is supposed to do some work, > it will operate on the one data all the other importing modules see. > > You can take this one step further, using an explicit init()-function that > creates global state (remember, it's only module-global). > > Diez -- Peter Bismuti Boeing Information Technology Renton, WA (425) 234-0873 W (425) 442-7775 C From samfeltus at gmail.com Wed Nov 21 10:57:27 2007 From: samfeltus at gmail.com (SamFeltus) Date: Wed, 21 Nov 2007 07:57:27 -0800 (PST) Subject: Python web frameworks + adobe flex References: Message-ID: I never used the Django AMF, I use JSON to go between Python and Flex. It works well, but lacks easy 2 way communication of course. Interfacing with Flex is a gaping hole in the Python libraries. Python needs a web framework that embraces Flex from the ground up, HTML being such a limited web display technology. There's not much of a standard for Python and Flex, and in a short period of time, you have to start rolling your own. That being said, Django and Flex do blend well. On Nov 21, 7:25 am, "Sells, Fred" wrote: > slight shift of topic here. > > I'm a newbie at standard web stuff. Mostly java webstart and a little mod_python. > > I experimented with Adobe Flex and really loved it for doing the front end. The backend needs to provide xml, json or AMF (an adobe proprietary binary format). For prototyping, I was able to put xml or json responses in text files and used that to work out the UI and do some cool demos. But I never got past prototyping, getting stuck in the "which python webfamework is best" mobius loop. > > My Question: Does anyone have experience with Flex+Python and especially with Adobe's AMF. I've got some time to try to setup a "standard" and am a bit short on hands-on experinece. From hat at se-162.se.wtb.tue.nl Wed Nov 21 03:05:15 2007 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Wed, 21 Nov 2007 09:05:15 +0100 Subject: Web update library in python? References: <5qgd6hFuhcubU1@mid.uni-berlin.de> Message-ID: On 2007-11-20, Diez B. Roggisch wrote: > Jorgen Bodde wrote: > >> Hi, A.T.Hofkamp (sorry for not knowing your first name ;-), Well Jorgen, it is at the bottom of each post (usually)... ;-) >> SCM sounds like a term I can google for, if the tool needed is very >> easy to install, maybe even accompany with my application to run as a >> service for the updating, it is worth a try to find something that can >> handle the synchronizing of distributed repositories. >> >> Talking a bit more about it and hearing various solutions gave me more >> insight in how it might be solved. Thanks everybody for your input! > > SCM mean source code management - like SVN or CVS. > > Diez Diez is right, except my choice of the phrase 'SCM' was not exactly right. SCM is a general term for two kinds of activities, namely version control (VC) and configuration control. VC is what everybody does with SVN, CVS, darcs, bzr, git, mercurial, etc in the context of software development (hence these tools are known as version control systems (VCS)). You may want to add 'distributed' to your search term. Configuration management is much less often done. It is about controlling deployment of some system or software. Imagine you are managing a few (hundreds) of web sites. They all use LAMP, but exactly what Apache, Py-Mod, Linux, hardware, is different each time. This of course also holds for the various initialization and configuration files. Keeping track of this data over time is called configuration management. (and if you think this is complicated, consider what Boeing is doing for all its air-planes... :) ). > SVN isn't distributed, but AFAIK darcs is. > As Diez already guessed, SVN and CVS are organized around a central repository, darcs, bzr, git, and mercurial do not need a central repository (although they often can handle one if the project wants it). The nice thing is that at least bzr and mercurial are written in Python!! What I found very enlightening was to find the web-site of these tools, and then read the docs about their strong and weak points w.r.t. their competitors. Of course each of these is biased, but if you read them all, it kind of balances out.... :) Also, they all explain what their world model is, you should check whether that matches with your problem. Good luck with your search, Albert From jcd at sdf.lonestar.org Thu Nov 22 10:40:26 2007 From: jcd at sdf.lonestar.org (J. Clifford Dyer) Date: Thu, 22 Nov 2007 10:40:26 -0500 Subject: eof In-Reply-To: <9e25e813-f4a7-48c6-9f0e-ef04223e29a0@e23g2000prf.googlegroups.com> References: <92a2c0c9-e6a1-4344-aeac-830940200f20@t47g2000hsc.googlegroups.com> <79i9k35vs76cqgqnino7dj3ql623us3euq@4ax.com> <6c04c760-6cf1-4715-9ec9-30f43ebaa01f@d27g2000prf.googlegroups.com> <062a9497-7626-440a-93eb-b897e6dec01f@p69g2000hsa.googlegroups.com> <9e25e813-f4a7-48c6-9f0e-ef04223e29a0@e23g2000prf.googlegroups.com> Message-ID: <20071122154026.GC7117@sdf.lonestar.org> On Thu, Nov 22, 2007 at 07:17:41AM -0800, braver wrote regarding Re: eof: > > On Nov 22, 6:08 pm, "J. Clifford Dyer" wrote: > > > > So why Python's IO cannot yield f.eof() as easily as Ruby's can? :) > > > Because that's not how you compare languages. You compare languages by stating what you are actually trying to do, and figuring out the most natural solution in each language. Not "I can do this in x--how come I can't do it in y?" > > Python doesn't have f.eof() because it doesn't compare to Ruby? Or > because I'm trying to compare them? :) That's giving up to Ruby too > early! > No and no, to your two questions. I'm not giving up on Ruby at all. In fact, I've never tried Ruby. My point isn't that the languages don't compare. My point is that your question shouldn't be "why doesn't python have an eof method on its file objects?" Your question should be "I want to do something different with the last line of a file that I iterate over. How do I do that best in python?" You've been given a couple solutions, and a very valid reason (performance) why buffered file objects are not the default. You may also consider trying subclassing file with a buffered file object that provides self.eof. (I recommend making it an attribute rather than a method. Set it when you hit eof.) That way you have the fast version, and the robust version. You may find something of interest in the for/else construction as well for line in file: pass else: # This gets processed at the end unless you break out of the for loop. pass > Ruby has iterators and generators too, but it also has my good ol' > f.eof(). I challenge the assumption here of some majectically Python- > wayist spirit forbidding Python to have f.eof(), while Ruby, which has > all the same features, has it. Saying "it's not the Python way" is > not a valid argument. > No, but showing a different python way is more valid, and if you were more forthcoming about your use case from the get-go, you would have gotten fewer vague answers. > The suspicion lurking in the thread above was that that has to do with > Python IO buffering, that it somehow can't tell the f.eof() with > automatic look-ahead/push-back/simulate read, as transparently an > effectively as (in practice) Ruby does without much fuss. The reason > why such a useful feature -- useful not in Ruby or Perl or Pascal, but > algorithmically -- is not present in Python is a recurrent mystery, > evidenced in this group recurrently. > A mystery which has been answered a couple times in this thread--it causes a performance hit, and python is designed so that you don't suffer that performance hit, unless you want it, so you have to program for it yourself. You yourself said that performance is a complaint of yours regarding Ruby, so why claim that Ruby's way is clearly better in a case where it causes a known performance hit? > Cheers, > Alexy Cheers, Cliff From ganesh.borse at credit-suisse.com Fri Nov 16 06:54:57 2007 From: ganesh.borse at credit-suisse.com (Borse, Ganesh) Date: Fri, 16 Nov 2007 19:54:57 +0800 Subject: How to evaluate the code object returned by PyParser_SimplePa rseString function? Message-ID: Thanks this is helpful. -----Original Message----- From: Gabriel Genellina [mailto:gagsl-py2 at yahoo.com.ar] Sent: 15 November 2007 12:26 To: python-list at python.org Subject: Re: How to evaluate the code object returned by PyParser_SimplePa rseString function? En Wed, 14 Nov 2007 23:20:14 -0300, Borse, Ganesh escribi?: > Py_CompileString takes the source code from file, isn't it? > As can be seen from the syntax of this function: PyObject* > Py_CompileString(char *str, char *filename, int start) > > I want to parse the code which is in memory - loaded from database. > In that case, may I know, how to use the Py_CompileString? The first argument is the actual source code string, a char*; the filename argument is only used to generate pretty error messages, you may pass in some meaningful name or ''. > If it is mandatory to read from file for this function? > Reading from file increases startup time of my application. > So, I was thinking of using PyParser_SimpleParseString, which takes > the code to be parsed in the "char*" format. Quit suitable to my need. No, both Py_CompileString and PyParser_SimpleParseString take the same first argument, a char* with the source code. > Can I use the output of the function PyParser_SimpleParseString as > input to PyEval_EvalCode? Not directly, you must compile the parsed input first. See pythonrun.c for examples, but you will end duplicating what Py_CompileString already does. -- Gabriel Genellina ============================================================================== Please access the attached hyperlink for an important electronic communications disclaimer: http://www.credit-suisse.com/legal/en/disclaimer_email_ib.html ============================================================================== From MrJean1 at gmail.com Sat Nov 24 14:49:39 2007 From: MrJean1 at gmail.com (MrJean1) Date: Sat, 24 Nov 2007 11:49:39 -0800 (PST) Subject: Catching a segfault in a Python library References: <7x1wagp8vu.fsf@ruckus.brouhaha.com> <4747e3b4$0$90269$14726298@news.sunsite.dk> Message-ID: <7716b3fd-a198-41d2-b561-db8a6d1a7b96@e6g2000prf.googlegroups.com> Try catching SIGSEGV using the Python signal module An example (for SIGALRM) is on the next page However, it may not work since a SIGSEGV fault is pretty much the end of everything :-( /Jean Brouwers On Nov 24, 6:22 am, Donn Ingle wrote: > > I think the idea is, certain fonts in his collection may be corrupt, > > and he wants to just scan through and load them, ignoring the ones > > that make the program crash. > > Ya got me! Sheesh, I can't hide anywhere :D > > > The bug in this case lies with a third > > party and isn't something he can easily fix (although he can file > > reports to the third party (PIL)). > > I've a bad memory and can't recall what I told PIL at the time. It might > have been a case of waiting to see what new versions can do. > > > not nice for the application to just crash when that happens, asking > > them if they want to debug it. > > Zigactly! You can wrap try/except around the calls that (by debugging) you > know are the culprits, but a segfault is a segfault and bam! you are at the > command line again. > > > I haven't really found a solution, > > just have tried to prevent corrupted files in the system for now. Let > > me know if you get this solved > > I'll certainly pop a note. I think, though, that the answer may reside in > the basic theme of this thread: > > runapp > result = runActualApp( ) > while True: > if result == allokay: break > else: > > > Unless a segfault goes through that too, like Krypton through Superman. > \d From bj_666 at gmx.net Sat Nov 24 08:42:48 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 24 Nov 2007 13:42:48 GMT Subject: How can I create customized classes that have similar properties as 'str'? References: <67954d23-9400-4ac9-ba45-bec04fab51a2@s6g2000prc.googlegroups.com> <8eebf8fb-74cc-452a-bbef-2fe93556491f@i29g2000prf.googlegroups.com> <5qqeroF11703eU2@mid.individual.net> <1f2e037f-3667-4070-97cd-f4f6486c9d79@i12g2000prf.googlegroups.com> <5qqke8F10pmr7U1@mid.individual.net> Message-ID: <5qqo2oF10jrh5U4@mid.uni-berlin.de> On Sat, 24 Nov 2007 13:40:40 +0100, Bjoern Schliessmann wrote: > Licheng Fang wrote: >> On Nov 24, 7:05 pm, Bjoern Schliessmann >> Wow, I didn't know this. But exactly how Python manage these >> strings? > > I don't know (use the source, Luke). :) Or perhaps there is a Python > Elder here that knows? AFAIK strings of length 1 and strings that would be valid Python identifiers are treated this way. Ciao, Marc 'BlackJack' Rintsch From steven at REMOVE.THIS.cybersource.com.au Mon Nov 19 04:19:37 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 19 Nov 2007 09:19:37 -0000 Subject: Finding lowest value in dictionary of objects, how? References: <642d8c24-a6bf-488d-9416-5ad37cc91ea5@d4g2000prg.googlegroups.com> Message-ID: On Mon, 19 Nov 2007 00:18:33 -0800, davenet wrote: > Hi, > > I'm new to Python and working on a school assignment. Thank you for your honesty. > I have setup a dictionary where the keys point to an object. Each object > has two member variables. I need to find the smallest value contained in > this group of objects. > > The objects are defined as follows: > > class Block: > def __init__(self,addr): > self.addr = addr > self.age = 0 > > My dictionary is defined as: > blocks = {} One possible approach is to define your Block data-type so that it defines less-than and greater-than comparisons. Then you can just ask Python to find the minimum Block by passing a list (not a dictionary) of Blocks to the function min(). > I have added 1000 (will hold more after I get this working) objects. I > need to find the lowest age in the dictionary. If there is more than one > age that is lowest (like if several of them are '1', etc), then I can > just pick randomly any that equal the lowest value. I don't care which > one I get. Question: you don't explain how you have added them to the dict. A dict has a key and a value. What are the keys, and what are the values? > I saw the following code here but I don't know how to use this sample to > get at the values I need in the blocks object. > > def key_of_lowest(self,addr) > lowest = min(self.blocks.values()) > return [k for k in self.blocks if self.blocks[k]==val][0] > > This one returns the lowest value Object, but not the lowest value of > age in all the Objects of the table. That code doesn't make much sense. It looks like a method rather than a function (the argument "self" is the giveaway). What is self.blocks and what is val? > I hope someone can help me figure out the syntax for what I'm trying to > do. The first step you should do is write down how YOU would solve the problem. "Let's see now... if I had a list of objects, and I wanted to find the smallest one, I would look at the first object, and compare it to all the other objects. If it was smaller than or equal to every other object in the list, I've found the smallest object and I'm finished! If not, I'd take the second object, and compare it to all the other objects. If it is smaller than or equal to everything else, I've found the smallest object, and I'm finished. If not, I would do the same for the third, and fourth, and fifth, and so forth, until I've found the smallest object." Now start converting it to Python, step by step: # Start with English instructions: with each item in the list of objects: if item is smaller than all the other items: item is the smallest, and we're done # Turn it into a function: function find the smallest(list of objects): with each item in the list of objects: if item is smaller than all the other items: item is the smallest, and we're done # Now start using Python syntax: def find_smallest(list_of_objects): for item in list_of_objects: if item is smaller than all the other items: return item # And continue: def find_smallest(list_of_objects): for item in list_of_objects: for x in list_of_objects: if item <= x: return item What I've done there is re-write the min() function in one of the slowest, most inefficient ways possible. If you try doing it by hand, you'll quickly see it's VERY inefficient. The better ways should be obvious once you actually do it. Then go through the process of writing it as Python code. Hope this helps, -- Steven. From zhushenli at gmail.com Tue Nov 20 23:32:19 2007 From: zhushenli at gmail.com (Davy) Date: Tue, 20 Nov 2007 20:32:19 -0800 (PST) Subject: (Tkinter) Can I bind a key to Canvas? References: <31a8e53c-afc0-47e7-a4ef-eeb32de8468d@a28g2000hsc.googlegroups.com> Message-ID: <9821aec7-2768-4ce6-9442-6272e307e812@o6g2000hsd.googlegroups.com> I have tried key and mouse click (when receive a event, print some diagnose information ). I found mouse click work well in canvas but key not work well. It seems canvas cannot get key event? self.canv.bind('',self._onUpKey) ## don't work self.canv.bind('', self._onClick) ## work Any suggestion? Best regards, Davy From robin at reportlab.com Thu Nov 22 06:05:10 2007 From: robin at reportlab.com (Robin Becker) Date: Thu, 22 Nov 2007 11:05:10 +0000 Subject: Research-oriented Python mailing list? In-Reply-To: <14092.39489.qm@web32708.mail.mud.yahoo.com> References: <14092.39489.qm@web32708.mail.mud.yahoo.com> Message-ID: <47456266.60105@chamonix.reportlab.co.uk> Albert-jan Roskam wrote: > Hi again, > > One more Q: I was wondering if there exists a more > research-oriented Python listserv. This one is good > (or so it seems, I'm just a newbie!), but the topics > are very broad. Suggestions, anyone? > > Thanks in advance! > > Cheers!!! > Albert-Jan > > Cheers! > Albert-Jan I guess that depends on what you want to research. If you're into developing python I'd start lurking on the python dev list; if you're into compilers and basic blocks then the pypy list is just the thing etc etc etc -- Robin Becker From kyosohma at gmail.com Tue Nov 6 14:18:57 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 06 Nov 2007 19:18:57 -0000 Subject: How do I get the PC's Processor speed? Message-ID: <1194376737.430731.60750@o80g2000hse.googlegroups.com> Hi, We use a script here at work that runs whenever someone logs into their machine that logs various bits of information to a database. One of those bits is the CPU's model and speed. While this works in 95% of the time, we have some fringe cases where the only thing returned is the processor name. We use this data to help us decide which PCs need to be updated, so it would be nice to have the processor speed in all cases. Currently, this script is run on Windows boxes only, most of which have Windows XP on them. Right now I am having Python check the following registry key for the CPU info: HKEY_LOCAL_MACHINE\HARDWARE\ \DESCRIPTION\\System\\CentralProcessor\\0 I've also used Tim Golden's WMI module like so: import wmi c = wmi.WMI() for i in c.Win32_Processor (): cputype = i.Name On the problem PCs, both of these methods give me the same information (i.e. only the processor name). However, if I go to "System Properties" and look at the "General" tab, it lists the CPU name and processor speed. Does anyone else know of another way to get at this information? Thanks! Mike From rustompmody at gmail.com Sun Nov 4 12:33:05 2007 From: rustompmody at gmail.com (rustom) Date: Sun, 04 Nov 2007 17:33:05 -0000 Subject: pygresql In-Reply-To: <1194191107.382274.313370@o3g2000hsb.googlegroups.com> References: <1194191107.382274.313370@o3g2000hsb.googlegroups.com> Message-ID: <1194197585.963453.90030@q3g2000prf.googlegroups.com> On Nov 4, 8:45 pm, JD wrote: > Hi there. > > I'm trying to use python with postgresql. I decided to use psycopg to > interact with the postgresql server. When installing psycopg it > appeared that I needed mxDateTime. So I decided to install the mxbase > package. > > I received the following error message (the interesting bit seems to > be at the end): snipped > Thank you very much in advance for any assistance, > James. Why are you trying to install yourself instead of using apt? On my debian etch box the psycopg packages have dependencies to the python- egenix-mx* packages and installing psycopg pulls in the others without problems. And I guess ubuntu should be similar. From duncan.booth at invalid.invalid Sat Nov 3 11:58:49 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 3 Nov 2007 15:58:49 GMT Subject: python newbie References: <472b2b84$0$13761$6e1ede2f@read.cnntp.org> <5p0s6vFp47k9U1@mid.individual.net> <472b5251$0$6238$426a34cc@news.free.fr> <13ioa6f6t797gce@corp.supernews.com> <7x4pg3wks5.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Duncan Booth writes: >> modules are not special in any way, except that you cannot subclass >> them. Oops, sorry I got that wrong. Modules are not special in any >> way, they can have methods as well as functions: > > I've felt for a long time that you should be able to define __call__ > on a module, but that doesn't seem to be allowed, at least if you > try it in the obvious way. This isn't perfect (global variables have to be set before hooking the module) but it sort of works: --------- callable.py --------------- """How to define a callable module""" import sys, new class CallableModule(new.module): def __call__(self, *args, **kw): self._call_(*args, **kw) def _call_(*args, **kw): """A call method""" print "Called with %r args, %r kw" % (args, kw) self = CallableModule(__name__, __doc__) self.__dict__.update(sys.modules[__name__].__dict__) sys.modules[__name__] = self ---------------------------------- >>> import callable >>> callable('test') Called with ('test',) args, {} kw >>> callable From limodou at gmail.com Fri Nov 23 03:10:21 2007 From: limodou at gmail.com (limodou) Date: Fri, 23 Nov 2007 16:10:21 +0800 Subject: python class methods identity? In-Reply-To: <7847e5160711230006i148ae5c0s3cfeec5904181bb5@mail.gmail.com> References: <7847e5160711222329t44e76c0yb819e9415b865d84@mail.gmail.com> <7847e5160711230006i148ae5c0s3cfeec5904181bb5@mail.gmail.com> Message-ID: <505f13c0711230010m4e72ecd1w59f879f45cc7acf6@mail.gmail.com> On Nov 23, 2007 4:06 PM, Roc Zhou wrote: > This is the result comes from the Linux. > > And the result from Windows is: > > >>> class Test: > var = 1 > def func(self): pass > >>> x = Test() > >>> y = Test() > >>> x.var is y.var > True > >>> x.func is y.func > False > >>> id(x.var) > 11228488 > >>> id(y.var) > 11228488 > >>> id(x.func) > 14430976 > >>> id(y.func) > 14433656 > ?????????????????????????????????????????? -- I like python! UliPad <>: http://code.google.com/p/ulipad/ meide <>: http://code.google.com/p/meide/ My Blog: http://www.donews.net/limodou From ricaraoz at gmail.com Mon Nov 26 12:07:09 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Mon, 26 Nov 2007 14:07:09 -0300 Subject: better way to write this function In-Reply-To: References: <4b4d9cc5-3759-421e-b3a2-3cb25bdaae7a@b40g2000prf.googlegroups.com> Message-ID: <474AFD3D.6020107@bigfoot.com> Peter Otten wrote: > Kelie wrote: > >> Hello, >> >> This function does I what I want. But I'm wondering if there is an >> easier/better way. To be honest, I don't have a good understanding of >> what "pythonic" means yet. >> >> def divide_list(lst, n): >> """Divide a list into a number of lists, each with n items. Extra >> items are >> ignored, if any.""" >> cnt = len(lst) / n >> rv = [[None for i in range(n)] for i in range(cnt)] >> for i in range(cnt): >> for j in range(n): >> rv[i][j] = lst[i * n + j] >> return rv > > You can use slicing: > >>>> def chunks(items, n): > ... return [items[start:start+n] for n in range(0, len(items)-n+1, n)] > ... >>>> for i in range(1,10): > ... print chunks(range(5), i) > ... > [[0], [1], [2], [3], [4]] > [[0, 1], [2, 3]] > [[0, 1, 2]] > [[0, 1, 2, 3]] > [[0, 1, 2, 3, 4]] > [] > [] > [] > [] This won't work(e.g. you don't define "start", you change the value of n through the loop). I guess you meant : def chunks(items, n) : return [items[i:i+n] for i in range(0, len(items)-n+1, n)] From steve at ferg.org Tue Nov 13 09:17:41 2007 From: steve at ferg.org (Steve) Date: Tue, 13 Nov 2007 06:17:41 -0800 Subject: AOP and pep 246 In-Reply-To: <1193935586.110516.105630@50g2000hsm.googlegroups.com> References: <1193935586.110516.105630@50g2000hsm.googlegroups.com> Message-ID: <1194963461.270262.90680@d55g2000hsg.googlegroups.com> > AOP was a research that gone nowhere - at least not in its orginal > AspectJ form ... I think it might be worth pointing out, though, that there is still significant interest in AOP in the Java community, in the form or interest in the Spring Framework. See, for instance: http://www.onjava.com/pub/a/onjava/2004/07/14/springaop.html This article was written in 2004. It has taken some time for awareness of Spring to penetrate the Java community, but it appears to be happening in a serious way. -- Thank-god-I-don't-have-to-learn-all-this-Java-superstructure-stuff- ly yours, Steve Ferg From bj_666 at gmx.net Fri Nov 2 06:47:13 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 2 Nov 2007 10:47:13 GMT Subject: Is pyparsing really a recursive descent parser? References: Message-ID: <5p0dhgFnj4rbU1@mid.uni-berlin.de> On Fri, 02 Nov 2007 06:05:13 +0000, Just Another Victim of the Ambient Morality wrote: > Is pyparsing really a recursive descent parser? I ask this because > there are grammars it can't parse that my recursive descent parser would > parse, should I have written one. For instance: > > > from pyparsing import * > > grammar = OneOrMore(Word(alphas)) + Literal('end') > grammar.parseString('First Second Third end') > > > Amazingly enough, this will fail to parse! > Now, maybe I have no idea what I'm talking about but shouldn't a > recursive descent parser recursively descend through all possible rule > combinations to discover one that works? Why does pyparsing fail to parse > this? Pyparsing is no recursive descent parser. It doesn't go back in the input stream. The ``OneOrMore(Word(alphas))`` part "eats" the 'end' and when it can't get more, the parser moves to the ``Literal('end')`` part which fails because the 'end' is already gone. > Is there a way to get pyparsing to parse a grammar like this? Negative lookahead maybe: grammar = (OneOrMore(NotAny(Literal('end')) + Word(alphas)) + Literal('end')) Ciao, Marc 'BlackJack' Rintsch From zionist.news at gmail.com Sat Nov 10 17:10:15 2007 From: zionist.news at gmail.com (zionist.news at gmail.com) Date: Sat, 10 Nov 2007 22:10:15 -0000 Subject: A JEW hacker in California admits distributing malware that let him steal usernames and passwords for Paypal accounts. Message-ID: <1194732615.277219.168670@o38g2000hse.googlegroups.com> A Jew hacker in California admits distributing malware that let him steal usernames and passwords for Paypal accounts. http://www.pcworld.com/article/id,139507-c,cybercrime/article.html The Jews and Israelis the top notch WHITE COLLAR CRIMINALS, YET, they are harassing MOSLEMS in CALIFORNIA. Do you know why ? BECAUSE ALL THE POLITICIANS ARE IN THEIR POCKET. Most senators and congressmen are the same ASHKENAZI KHAZAR JEWS. Tom Lantos and Diane Feinstein are two of the most crooked senators from CALIFORNIA and both Ashkenazi and khazar. LAPD to RACIALLY PROFILE MOSLEMS: http://www.latimes.com/news/local/la-me-lapd9nov09,0,1646403.story?page=2&coll=la-home-center LAPD to build data on Muslim areas Anti-terrorism unit wants to identify sites 'at risk' for extremism. By Richard Winton, Jean-Paul Renaud and Paul Pringle, Los Angeles Times Staff Writers November 9, 2007 An extensive mapping program launched by the LAPD's anti-terrorism bureau to identify Muslim enclaves across the city sparked outrage Thursday from some Islamic groups and civil libertarians, who denounced the effort as an exercise in racial and religious profiling. Los Angeles Police Department Deputy Chief Michael P. Downing, who heads the bureau, defended the undertaking as a way to help Muslim communities avoid the influence of those who would radicalize Islamic residents and advocate "violent, ideologically-based extremism." "We are seeking to identify at-risk communities," Downing said in an interview Thursday evening. "We are looking for communities and enclaves based on risk factors that are likely to become isolated. . . . We want to know where the Pakistanis, Iranians and Chechens are so we can reach out to those communities." Downing added that the Muslim Public Affairs Council has embraced the vaguely defined program "in concept." The group's executive director, Salam Al-Marayati, said Thursday that it wanted to know more about the plan and had a meeting set with the LAPD next week. "We will work with the LAPD and give them input, while at the same time making sure that people's civil liberties are protected," said Al- Marayati, who commended Downing for being "very forthright in his engagement with the Muslim community." Others condemned the project, however. "We certainly reject this idea completely," said Shakeel Syed, executive director of the Islamic Shura Council of Southern California. "This stems basically from this presumption that there is homogenized Muslim terrorism that exists among us." Syed said he is a member of Police Chief William J. Bratton's forum of religious advisors, but had not been told of the community mapping program. "This came as a jolt to me," Syed said. Hussam Ayloush, who leads the Los Angeles chapter of the Council on American-Islamic Relations, said the mapping "basically turns the LAPD officers into religious political analysts, while their role is to fight crime and enforce the laws." During Oct. 30 testimony before Congress, Downing described the program broadly as an attempt to "mitigate radicalization." At that time, he said law enforcement agencies nationwide faced "a vicious, amorphous and unfamiliar adversary on our land." Downing and other law enforcement officials said police agencies around the world are dealing with radical Muslim groups that are isolated from the larger community, making potential breeding groups for terrorism. He cited terror cells in Europe as well as the case of some Muslim extremists in New Jersey arrested in May for allegedly planning to bomb Ft. Dix. "We want to map the locations of these closed, vulnerable communities, and in partnership with these communities . . . help [weave] these enclaves into the fabric of the larger society," he said in his testimony. "To do this, we need to go into the community and get to know peoples' names," he said. "We need to walk into homes, neighborhoods, mosques and businesses." To assemble the mapping data, Downing said in an interview Thursday, the LAPD intends to enlist USC's Center for Risk and Economic Analysis of Terrorism Events, which was founded four years ago with $12 million in federal funds. In 2003, university officials said the center would focus on threats to power plants, telecommunications and transportation systems. It recently was tapped to strengthen security at Los Angeles International Airport. Downing said the effort would not involve spying on neighborhoods. He said it would identify groups, not individuals. "This has nothing to do with intelligence," he said, comparing it to market research. But in his congressional testimony, Downing said the LAPD hoped to identify communities that "may be susceptible to violent, ideologically-based extremism and then use a full-spectrum approach guided by an intelligence-led strategy." Downing told lawmakers the program would "take a deeper look at the history, demographics, language, culture, ethnic breakdown, socioeconomic status and social interactions." He added that the project was in its very early stages, and that its cost and full scope have not been determined. "Physically the work has not begun," Downing said. The American Civil Liberties Union and some community groups sent a letter Thursday to Downing expressing "grave concerns" about the program and asking for a meeting. "The mapping of Muslim communities . . . seems premised on the faulty notion that Muslims are more likely to commit violent acts than people of other faiths," the letter states. ACLU Executive Director Ramona Ripston compared the program to the Red Scare of the 1950s and said: "This is nothing short of racial profiling." But Al-Marayati said he believed that Downing was working in good faith. "He is well-known in the Muslim community," he said. "He's been in a number of mosques and been very forthright in his engagement with the Muslim community." richard.winton at latimes.com jp.renaud at latimes.com paul.pringle at latimes.com Times staff writers Francisco Vara-Orta, Andrew Blankstein and Stuart Silverstein contributed to this report. ========== 911 carried out by evil jews and mossad http://www.guba.com/watch/2000991770 911 truckload of Explosives on the George Washington Bridge http://www.youtube.com/watch?v=J520P-MD9a0 Benjamin Freedman's SEMINAL TESTIMONIAL SPEECH http://video.google.com/videoplay?docid=3552214685532803163 Benjamin Freedman speech with Slide Show (40 Minute Excerpt) http://video.google.com/videoplay?docid=3552214685532803163 Free pdf book: THE MANUFACTURE AND SALE of Saint Einstein @ http://jewishracism.com/SaintEinstein.htm Author interviews @ http://jewishracism.com/interviews.htm Rothschilds control half the world's wealth directly and indirectly using zionist proxies, and loyalty based on the zionist racist cult of hate and paranoia based on being caught for collective financial crimes and crimes of other categories History of the Rothschilds part 1 http://www.youtube.com/watch?v=o_u2MaNg-EQ History of the Rothschilds part 2 http://www.youtube.com/watch?v=o2cw-0N_Unk FBI, Where are the two Israelis with TRUCKLOAD of explosives at the George Washington Bridge ????? http://www.youtube.com/watch?v=JfVumKHkcIA <----- Shame stooopid americans Alex Jones Interviews David Mayer de Rothschild http://video.google.com/videoplay?docid=4891699310483983031 The rise of the Rothschild Money Masters http://www.youtube.com/watch?v=ZT3GyphxJv8 Rothschilds financed APARTHEID in South Africa. They corrupted Cecil Rhodes, the son of an anglican minister, by TEACHING him evil techniques of apartheid. Apartheid was taught to him by the father zionists themselves. Rothschilds control half the world's wealth directly and indirectly using zionist proxies, and loyalty based on the zionist racist cult http://www.youtube.com/watch?v=fXVJzXsraX4 Was Hitler's father a bastard son of Rothschilds? Did the Salomon Mayer von Rothschild perhaps rape Maria Anna Schicklgruber in dark so that she could not ever claim with certainty who the real father was? Look at his facial features, typical central asian khazar. What was the cause of Hitler's fanatical hatred for the Jews ? http://en.wikipedia.org/wiki/Alois_Hitler http://www.youtube.com/watch?v=TihCM_q59c8 On Nov 6, 9:53 am, zionist.n... at gmail.com wrote: From python-url at phaseit.net Tue Nov 27 20:40:38 2007 From: python-url at phaseit.net (Gabriel Genellina) Date: Wed, 28 Nov 2007 01:40:38 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Nov 28) Message-ID: QOTW: ""Given that C++ has pointers and typecasts, it's really hard to have a serious conversation about type safety with a C++ programmer and keep a straight face. It's kind of like having a guy who juggles chainsaws wearing body armor arguing with a guy who juggles rubber chickens wearing a T-shirt about who's in more danger." - Roy Smith, c.l.py, 2004.05.23 "[R]esumable functions are a honking great idea." - Alan Kennedy Making all equal instances the same (so "a==b" implies "a is b"): http://groups.google.com/group/comp.lang.python/browse_thread/thread/c82c7d1cfb49c1d4 A good way of organizing packages and project layout: http://groups.google.com/group/comp.lang.python/browse_thread/thread/8a064827f4d2afc7 Enumerating all the running processes (cross-platform): http://groups.google.com/group/comp.lang.python/browse_thread/thread/f9f0c6726f6e0211 Numerical tricks from number-crunching people: http://groups.google.com/group/comp.lang.python/browse_thread/thread/f67b7c777c0d6915 How to obtain the "next" floating point number: http://groups.google.com/group/comp.lang.python/browse_thread/thread/0d992d01db3bde1a Python "variables" and what they mean: http://groups.google.com/group/comp.lang.python/browse_thread/thread/26e4fe70c858e156 Catching a segfault in a third party library: http://groups.google.com/group/comp.lang.python/browse_thread/thread/d505960679df17d2 Why files don't have an EOF attribute - and an alternative method to process files in chunks http://groups.google.com/group/comp.lang.python/browse_thread/thread/4916ce38c3ca0e00 ======================================================================== 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. Just beginning with Python? This page is a great place to start: http://wiki.python.org/moin/BeginnersGuide/Programmers The Python Papers aims to publish "the efforts of Python enthusiats": http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the "Planet" sites: http://planetpython.org http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/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 continues the marvelous tradition early borne by Andrew Kuchling, Michael Hudson, Brett Cannon, Tony Meyer, and Tim Lesher 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 Many Python conferences around the world are in preparation. Watch this space for links to them. 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-- Phaseit, Inc. (http://phaseit.net) is pleased to participate in and sponsor the "Python-URL!" project. Watch this space for upcoming news about posting archives. From jiwon at stanford.edu Wed Nov 7 22:01:32 2007 From: jiwon at stanford.edu (Jiwon Seo) Date: Wed, 7 Nov 2007 19:01:32 -0800 Subject: Source insight support files Message-ID: Is there anyone who uses source insight for python source code editing/browsing? It seems like Tim used to use it ( http://mail.python.org/pipermail/python-list/2001-May/082137.html )..., but I'm not sure if he still uses it. Anyway, if there's anyone who uses it and has a customized support configuration/files, please let me use it, too. ;^) I'm currently using source insight with Python.clf file and it's not bad, but not satisfactory. -Jiwon From bdesth.quelquechose at free.quelquepart.fr Fri Nov 9 17:24:35 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 09 Nov 2007 23:24:35 +0100 Subject: Some "pythonic" suggestions for Python In-Reply-To: References: <5PGdnWmWZIdZ967anZ2dnUVZ_uuqnZ2d@cavtel.net> <47338e4c$0$30952$426a74cc@news.free.fr> <9qGdnadjs6a76ananZ2dnUVZ_q2hnZ2d@cavtel.net> Message-ID: <4734de48$0$26675$426a74cc@news.free.fr> Frank Samuelson a ?crit : (snip) >> Arbitrary changes to syntax are never going to fly. It's a lost cause. > > > The changes are not arbitrary. Which ones ? > They are logical, consistent, less > arbitrary and thus more productive. For who ? > If such > changes are a lost cause, that is too bad, because > it implies that Python will stagnate. Unfortunately that appears the case. This is totally ridiculous. Let's see : list comprehensions, a new, widely improved object system, with metaclasses, and the descriptor protocol which brings customisable computed attributes -, lexical closures, iterators, generator expressions, syntactic sugar for function decorators, contexts (the 'with' statement), and coroutines. Just to name a few, and only talking of production releases. Which other language grew so many new features in the last seven years ? Java ? C ? C++ ? Lisp ? VB (lol) ? (snip) >> If you can't handle Python without your pet changes, fork it and write >> your own version and let the marketplace of ideas decide if its >> useful. > > Apparently you missed my statement about loving Python. I love it > because it is the second most productive language I have ever used, > though I do believe it has the potential to be the greatest ever by > far. I don't think you'll gain that much productivity by fighting against the language trying to write in it. From mal at egenix.com Thu Nov 22 05:33:58 2007 From: mal at egenix.com (M.-A. Lemburg) Date: Thu, 22 Nov 2007 11:33:58 +0100 Subject: Formatting question. In-Reply-To: <13ka4hflvp77mf6@corp.supernews.com> References: <13k7jklks7fbm86@corp.supernews.com> <725f49c6-d0ab-48d6-8a7e-414c99a2b5e4@c29g2000hsa.googlegroups.com> <13ka4hflvp77mf6@corp.supernews.com> Message-ID: <47455B16.40500@egenix.com> Dennis Lee Bieber wrote: > On Wed, 21 Nov 2007 08:36:28 -0800 (PST), mike5160 > declaimed the following in comp.lang.python: > >> Thanks to you for your reply. I am a newbie to Python and appreciate >> you helping me. Now, I am importing data from an excel sheet and >> getting it ready for a derby database. I am to use netbeans, since our >> research team uses that. However, derby database uses sql entries to >> update the database. And I m trying to format all the excel data I >> have, which I got from using labview. I suggested that we use awk/perl/ >> python etc. and finally after looking at the documentation available I >> figured Python would be best. However, (see my reply above) I am >> looking for a sample book/document etc. somebody suggested we try >> Python Phrasebook. But that one covers a lot of different fields >> whereas for my purposes I need a book with examples on using Python in >> the above manner. If you or anybody knows about this kind of book >> please let me know. >> > Unfortunately, you probably won't find any single book... > > Parsing fixed format (if still variable line length) text files is > simplified by Python's string.split() and slicing, but those are just > built-in functions for simple algorithms that are language independent. > You might find it under the term "tokenizing" > > Formatting SQL statements is... SQL... a totally separate language, > hypothetically standardized but having lots of DBMS specific dialects. > > Also, you appear to be looking at it from the direction of > translating tab separated output file from Excel into a sequence of SQL > insert statements which will be written to another file, then "batched" > into some DBMS command line interpreter. That means that you will have > to be responsible for knowing how to escape special characters, properly > indicating nulls, etc. > > Presuming http://db.apache.org/derby/ is the DBMS you mention, I > wonder if you would not be better off converting the Excel data into an > XML file of the type wanted by > http://db.apache.org/derby/integrate/db_ddlutils.html > > Otherwise, I'm afraid to say, I'd suggest coding the Excel parser > /in/ Java, and use JDBC to directly insert the data... (If there were an > ODBC compatible driver, I'd suggest using a Python ODBC adapter and > doing it from Python). FYI: There is an Excel ODBC driver for Windows which is included in the Microsoft MDAC package. Using it, you can query Excel tables with SQL. mxODBC works great with it. OTOH, if you're on Windows anyway, you can also use the win32 Python package and then tap directly into Excel using COM. > If using the "ij" utility from a command line, please note that it > supports multiple record insert; instead of > > insert into values (a, ..., z); > insert into
values (a2, ..., z2); > ... > insert into
values (aX, ..., zX); > > you can use > > insert into
values > (a, ..., z), > (a2, ..., z2), > ... > (aX, ..., zX); > > though there may be a limit to how long the statement can be -- maybe > run in batches of 25-50 records at a time... > > > > > > >> Thank you very much for your help, >> Mike. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Nov 22 2007) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From nytrokiss at gmail.com Tue Nov 20 17:02:35 2007 From: nytrokiss at gmail.com (James Matthews) Date: Tue, 20 Nov 2007 23:02:35 +0100 Subject: Python too complex ?!?!?! In-Reply-To: <7hC%i.28332$mv3.17248@newsfe10.phx> References: <7hC%i.28332$mv3.17248@newsfe10.phx> Message-ID: <8a6b8e350711201402t5e45f1f9x467bc49727de0f57@mail.gmail.com> I think they need to change teachers in this school! On Nov 17, 2007 2:46 PM, Brian wrote: > Had a unsettling conversation with a CS instructor that > teaches at local high schools and the community > college. This person is a long-term Linux/C/Python > programmer, but he claims that the install, config, and > library models for C# have proved to be less > problematic than Python. So both his courses (intro, > data structs, algorithms) are taught in C#. > > I am a low-end (3-year) journeyman Pythonista, and I > was attracted to the language because of its > simplicity. And I have come to enjoy the richness of > available libraries. > > Many of the good people of this NG may be 'too close' > to answer, but has Python, as a general devel platform, > lost its simplicity ? Is library install too complex > and unreliable ? Will my dog go to heaven ? > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://search.goldwatches.com/ http://www.jewelerslounge.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From pydecker at gmail.com Wed Nov 28 19:54:27 2007 From: pydecker at gmail.com (Peter Decker) Date: Wed, 28 Nov 2007 19:54:27 -0500 Subject: Very basic, sorting a list ??? In-Reply-To: <474E064C.9040303@gmail.com> References: <474E064C.9040303@gmail.com> Message-ID: On Nov 28, 2007 7:22 PM, stef mientki wrote: > print 'xx3',ordered_list.sort() The sort() method returns None. It sorts the list in place; it doesn't return a copy of the sorted list. -- # p.d. From hniksic at xemacs.org Thu Nov 15 04:09:36 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Thu, 15 Nov 2007 10:09:36 +0100 Subject: no __len__ attribute in NodeList or the list base? References: <33c650ea-d250-4223-ab55-7f02476528bb@d50g2000hsf.googlegroups.com> Message-ID: <87hcjnswmn.fsf@mulj.homelinux.net> sndive at gmail.com writes: > i extract class object from an instance of NodeList (minicompat.py) > like so > PyObject *pclass = PyObject_GetAttrString( nodelistinsance, > "__class__"); > but > PyObject_GetAttrString(pclass, "__len__") > returns NULL. Are you sure about that? >>> import xml.dom.minicompat >>> xml.dom.minicompat.NodeList >>> xml.dom.minicompat.NodeList.__len__ >>> xml.dom.minicompat.NodeList() [] >>> _.__class__ >>> _.__len__ > to explain that endless loop i have to assume __len__ is defined > in the NodeList base(list that is) > but i don't see __len__ anywhere in listobject.c!!! The list object has __len__: >>> list.__len__ It just gets defined in a different way, through a C structure of function pointers defining sequence operations. (See where list_length is defined and used.) From bscrivener42 at gmail.com Wed Nov 7 19:09:36 2007 From: bscrivener42 at gmail.com (BartlebyScrivener) Date: Thu, 08 Nov 2007 00:09:36 -0000 Subject: regular expression syntax the same in Python, Perl and grep? In-Reply-To: <1194459115.764951.50440@y42g2000hsy.googlegroups.com> References: <1194459115.764951.50440@y42g2000hsy.googlegroups.com> Message-ID: <1194480576.941368.322120@o38g2000hse.googlegroups.com> On Nov 7, 12:11 pm, "seber... at spawar.navy.mil" wrote: > How similar is Python's re module (regular expressions) compared > to Perl's and grep's regular expression syntaxes? http://en.wikipedia.org/wiki/Comparison_of_regular_expression_engines rd From barronmo at gmail.com Wed Nov 7 08:27:22 2007 From: barronmo at gmail.com (barronmo) Date: Wed, 07 Nov 2007 05:27:22 -0800 Subject: global name is not defined In-Reply-To: References: <1194386232.498054.74520@d55g2000hsg.googlegroups.com> Message-ID: <1194442042.838626.292590@19g2000hsx.googlegroups.com> Thanks, seems to be fixed with importing MySQLdb, menus, EMR_main, etc in the Name_find module. Is there a better way to do things? I thought I was avoiding using global variables by putting the shared ones in their own module. Thanks for the help. Mike From grante at visi.com Thu Nov 29 21:40:56 2007 From: grante at visi.com (Grant Edwards) Date: Fri, 30 Nov 2007 02:40:56 -0000 Subject: Interfaces to high-volume discussion forums (was: Science list) References: <474ed805$0$239$e4fe514c@news.xs4all.nl> <13ku2jn7np6797c@corp.supernews.com> <87myswr2ip.fsf_-_@benfinney.id.au> Message-ID: <13kuu1op57u0841@corp.supernews.com> On 2007-11-30, Ben Finney wrote: > Most of the high-volume discussion lists I participate in are made > available as NNTP forums via news.gmane.org. I find that immeasurably > superior to any email interface, not least because I can use *any* > NNTP client to manage my interaction with those forums. Same here. I don't follow mailing lists unless they're available via gmane's NNTP server. Any other method wastes too much time. > The proliferation of "web forums", where the *only* way to participate > is to use an excreable web application that works differently to > everything else and has no connection to anything else I do on my > computer, is of course utterly antithesis to my needs. IMO, web forums suck the worst of any possible discussion medium. -- Grant From steve at REMOVE-THIS-cybersource.com.au Mon Nov 12 06:57:42 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Mon, 12 Nov 2007 11:57:42 -0000 Subject: Populating a dictionary, fast References: <818643.92017.qm@web915.biz.mail.mud.yahoo.com> Message-ID: <13jgftmrdca81cc@corp.supernews.com> On Sun, 11 Nov 2007 11:42:08 -0700, Arkanes wrote: > It takes about 20 seconds for me. It's possible it's related to int/long > unification - try using Python 2.5. If you can't switch to 2.5, try > using string keys instead of longs. I'm getting similar behaviour to the Original Poster, and I'm using Python 2.5 under Linux. Unlike him, my PC only has 1GB of RAM, and I've got a LOT of other apps running, so I'm not surprised it's taking about two minutes to build the dict. I put that down to low memory, and given the limitations of my system, I'm not worried about that. But taking 30+ minutes to delete the dict, even with garbage collection off, that can't be good. -- Steven. From gnewsg at gmail.com Fri Nov 30 17:48:58 2007 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Fri, 30 Nov 2007 14:48:58 -0800 (PST) Subject: Check if a symlink is broken or circular Message-ID: <45167a44-22e6-4e0a-b2a4-38fea0a7bab1@y43g2000hsy.googlegroups.com> Hi there, I would like to know if such function would be correct for verifying if a link is broken and/or circular. def isvalidlink(path): assert os.path.islink(path) try: os.stat(path) except os.error: return 1 return 0 From python.list at tim.thechases.com Thu Nov 29 09:33:10 2007 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 29 Nov 2007 08:33:10 -0600 Subject: Lib for audio? In-Reply-To: References: Message-ID: <474ECDA6.1030509@tim.thechases.com> >> I need to read microphone input and determine frequency. Is there a lib >> for that? Yet one more possibility includes the OpenAL Python bindings: http://home.gna.org/oomadness/en/pyopenal/index.html -tkc From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Nov 2 17:46:14 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 02 Nov 2007 22:46:14 +0100 Subject: python newbie References: <472b2b84$0$13761$6e1ede2f@read.cnntp.org> <5p0s6vFp47k9U1@mid.individual.net> <472b5251$0$6238$426a34cc@news.free.fr> Message-ID: <5p1k56Foq5j2U2@mid.individual.net> Bruno Desthuilliers wrote: > Bjoern Schliessmann a ?crit : >> You can't just declare in Python, you always define objects (and >> bind a name to them). > > def toto(): > global p > p = 42 > > Here I declared 'x' as global without defining it. Ah well, someone had to notice it ... BTW, where's x? :) >> Yes, globals need to be defined before you >> can access them using "global". > > For which definition of 'defined' ? to define a name: to bind an object to a name > >>> p > Traceback (most recent call last): > File "", line 1, in > NameError: name 'p' is not defined > >>> toto() > >>> p > 42 > >>> Easy, p = 42 is a definition. That's also true for translating to C/C++ nomenclature where "declare" means "tell the compiler a name and its type" and "define" means "declare and reserve memory for it". > Hem... I'm not sure you're really addressing the OP's question > here. Me too ... > But anyway: in Python, everything's an object, so the only > thing that makes functions a bit specials is that they are > callable - as are classes, methods, and every instance of a class > implementing __call__ FWIW. So saying 'variables holds data, > functions do stuff' is unapplyiable to Python. I don't think so. Even if everything is an object, there is still a concept behind the words "function" and "variable". >> They are. > > functions are *not* methods of their module. Yes, I used the term very sloppily. At least they are attributes. Regards, Bj?rn -- BOFH excuse #450: Terrorists crashed an airplane into the server room, have to remove /bin/laden. (rm -rf /bin/laden) From hpasanen at gmail.com Tue Nov 20 10:02:17 2007 From: hpasanen at gmail.com (harri) Date: Tue, 20 Nov 2007 07:02:17 -0800 (PST) Subject: Populating a dictionary, fast [SOLVED SOLVED] References: <818643.92017.qm@web915.biz.mail.mud.yahoo.com> <47374D00.7080500@gmail.com> <1195051438.889160.137120@50g2000hsm.googlegroups.com> <87fxz8kas6.fsf@mulj.homelinux.net> <13jn10p1r88u19f@corp.supernews.com> <65372cfb-7801-49c8-9363-259dca21adfa@w34g2000hsg.googlegroups.com> Message-ID: <1fda1025-6d0b-4ba9-a8fe-a4fb73c43ad1@n20g2000hsh.googlegroups.com> On Nov 15, 9:51 pm, "Michael Bacarella" wrote: > > Since some people missed the EUREKA!, here's the executive summary: > > Python2.3: about 45 minutes > Python2.4: about 45 minutes > Python2.5: about _30 seconds_ FYI, I tried on two 64 bit SMP machines (4 way and 2 way), running Mandriva 2007 and 2008 2.6.17-6mdv #1 SMP Wed Oct 25 12:17:57 MDT 2006 x86_64 AMD Opteron(tm) Processor 280 GNU/Linux Python 2.4.3 (#2, May 7 2007, 15:15:17) [GCC 4.1.1 20060724 (prerelease) (4.1.1-3mdk)] on linux2 2.6.23.1-1mdvsmp #1 SMP Sat Oct 20 18:04:52 EDT 2007 x86_64 Intel(R) Core(TM)2 CPU 6400 @ 2.13GHz GNU/Linux Python 2.5.1 (r251:54863, Sep 13 2007, 09:02:56) [GCC 4.2.1 20070828 (prerelease) (4.2.1-6mdv2008.0)] on linux2 I could not reproduce the problem with Steven's test file id2name.txt on either. sendspace seems to be over capacity, so I haven't been able download your keys.txt. I wonder if this might not be a glibc issue? If you own built python 2.5 linked with the same glibc version as the system python? What does ldd /usr/bin/python say vs. ldd /usr/local/bin/python ? Harri From gagsl-py2 at yahoo.com.ar Wed Nov 14 17:31:32 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 14 Nov 2007 19:31:32 -0300 Subject: private data stashed in local/global execution context of PyEval_EvalCode disappears down the execution stack References: <1194402317.678614.142450@y42g2000hsy.googlegroups.com> <1194988694.381313.202490@v65g2000hsc.googlegroups.com> <1194994796.459038.310970@v2g2000hsf.googlegroups.com> <1195063722.087861.149770@d55g2000hsg.googlegroups.com> Message-ID: En Wed, 14 Nov 2007 15:08:42 -0300, escribi?: > thank you. > result is the same however: > pyt: main.cpp:17: PyObject* pyNode_root(PyObject*, PyObject*): > Assertion `co' failed. Well, "is the same" in the sense that the code still doesn't do what you want... But the previous error is gone. (Now I regret having said the reason it didn't work before: you took my words too literally). I suggest you first try to write the program in pure Python, even with a dummy Node. From what I can understand of what you are doing, it appears you don't fully understand how import works, how modules work, and namespaces in Python. The C API exposes the same concepts so it's easier when one knows how to do things in pure Python first. Right now you have two problems: "what" to do, and "how" to write that using the API. First try to solve the "what", in Python, and only later move to the second stage. -- Gabriel Genellina From gert.cuykens at gmail.com Fri Nov 2 08:24:33 2007 From: gert.cuykens at gmail.com (gert) Date: Fri, 02 Nov 2007 12:24:33 -0000 Subject: MySQLdb.string_literal Message-ID: <1194006273.383109.97910@o80g2000hse.googlegroups.com> I want to escape binary data so i can insert data into a blob Using MySQLdb.string_literal(data) doesn't seem to escape everything ? From sndive at gmail.com Thu Nov 1 21:13:35 2007 From: sndive at gmail.com (sndive at gmail.com) Date: Fri, 02 Nov 2007 01:13:35 -0000 Subject: PyCheck for a classes defined in python and user data in PyObject_HEAD In-Reply-To: <1193955251.512135.152720@z9g2000hsf.googlegroups.com> References: <1193955251.512135.152720@z9g2000hsf.googlegroups.com> Message-ID: <1193966015.323437.65030@50g2000hsm.googlegroups.com> On Nov 1, 4:14 pm, snd... at gmail.com wrote: > q#1: > in C I want to check if a given PyObject is a xml.dom.minidom.Node (or > a derivative). > how do i extract a PyTypeObject for such a class? nevermind, i found an instance object that will work for me as long as i figure out where is the documentation beyond this: http://docs.python.org/api/instanceObjects.html on the data attrib access and extracting PyClassObject from it. > > issue #2 > I'm in a situation when i don't really need to extend python with any > classes of my own but > i do have extra luggage for the python data structures such as tuples, > lists, dictionaries, etc > on the c++ side. I see no place in PyObject_HEAD where i can stick a > void* to my extra data. > If i enter a feature request into bugzilla for python do you think it > will be well received? > #ifdefed of course like the prev/next extras. > I'm surprised noone else is using evil twin approach. > The reason i'm asking is because while for dictionaries i can stick > weak pointer back to my c++ > object in a key with an obscure name while in lists this would change > the list size and thus > is obviously not as easy to "hide" from the client code. > a placeholder in a pyobject would've been of help here From besturk at gmail.com Fri Nov 2 10:32:46 2007 From: besturk at gmail.com (Abandoned) Date: Fri, 02 Nov 2007 07:32:46 -0700 Subject: Copy database with python.. In-Reply-To: References: <1194011518.553434.278940@o3g2000hsb.googlegroups.com> Message-ID: <1194013966.385381.150060@o3g2000hsb.googlegroups.com> On Nov 2, 4:19 pm, Paul McNett wrote: > Abandoned wrote: > > Hi. > > I want to copy my database but python give me error when i use this > > command. > > cursor.execute("pg_dump mydata > old.dump") > > What is the problem ? And how can i copy the database with python ? > > You are just going to have to give us more to go on. Please post the > entire traceback of the error that you see (copy/paste it from your > terminal). > > You can't issue system commands using the cursor's execute() method and > expect that to work. execute() is for executing SQL, DML, or DDL, not > for doing shell stuff. > > Try: > > import os > os.system("pg_dump mydata > /tmp/old.dump") > > but I'm not versed in postgressql, so this probably won't work exactly > as written. You'd need to run that code from the server hosting the > postgresql database. > > > Note: The database's size is 200 GB > > Well, then you may want to make sure you have enough room on the target > volume before trying to dump the file! Note that the dump file could > conceivably be much larger (or much smaller) than the database itself. > > -- > pkm ~http://paulmcnett.com Are there any way to copy database without dump or any temp files ? (If there is a temp my harddisk not enough for this operation :( ) From bignose+hates-spam at benfinney.id.au Sun Nov 25 17:36:33 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 26 Nov 2007 09:36:33 +1100 Subject: How to Teach Python "Variables" References: <4749bb94$1@news.bezeqint.net> Message-ID: <873auut0jy.fsf@benfinney.id.au> none <""atavory\"@(none)"> writes: > IIRC, I once saw an explanation how Python doesn't have "variables" > in the sense that, say, C does, and instead has bindings from names > to objects. Does anyone have a link? In addition to the good answers you've had already, I highly recommend David Goodger's "Code like a Pythonista" page , which contains a very good "cardboard boxes versus paper tags" analogy of the topic you're asking about. -- \ "My roommate got a pet elephant. Then it got lost. It's in the | `\ apartment somewhere." -- Steven Wright | _o__) | Ben Finney From gregpinero at gmail.com Thu Nov 8 13:41:25 2007 From: gregpinero at gmail.com (gregpinero at gmail.com) Date: Thu, 08 Nov 2007 18:41:25 -0000 Subject: Using imaplib module with GMAIL's IMAP - hangs Message-ID: <1194547285.816141.110230@v29g2000prd.googlegroups.com> I'm trying to get a list of messages from GMAIL using it's new IMAP access. So far I've tried running this command but it just hangs. Any ideas? >>> import imaplib >>> M=imaplib.IMAP4('imap.gmail.com',993) I figured that's the first line to run from this example: http://docs.python.org/lib/imap4-example.html Here are the configuration settings GMAIL says to use: https://mail.google.com/support/bin/answer.py?answer=78799 Thanks for any help. -Greg From robert.kern at gmail.com Mon Nov 5 13:07:26 2007 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 05 Nov 2007 12:07:26 -0600 Subject: (MAC) CoreGraphics module??? In-Reply-To: References: <22uki39arp3a83topaimrka4s37uo1okm5@4ax.com> Message-ID: David C. Ullrich wrote: > On Sun, 04 Nov 2007 15:56:21 -0600, Robert Kern > wrote: > >> David C. Ullrich wrote: >>> On Fri, 02 Nov 2007 14:09:25 -0500, Robert Kern >>> wrote: >>> >>>> David C. Ullrich wrote: >>>>> [???] >>>> Okay, which version of OS X do you have? In 10.3 and 10.4 it used to be here: >>>> /System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/plat-mac/CoreGraphics.py >>>> >>>> I notice that in 10.5, it no longer exists, though. >>> Um, surely that doesn't mean that there's no CoreGraphics >>> available in 10.5? >> The CoreGraphics C library still exists, of course. The Python module they >> provided does not. > > Right - I was referring to the Python module. > > Why would they do such a thing? (Never mind, I don't > imagine you know.) Apple was using it in their fax software. I'm not sure they ever intended it to be used by people external to Apple, though. They certainly never documented it. I imagine they are no longer using it in their fax software. > Hmm, I saw somewhere the other day that PyObjC comes with 10.5. > Maybe that means there's no longer any point to a separate > CoreGraphics.py? No, they're different things. PyObjC does wrap a Cocoa drawing API, but that API does not cover nearly as much of the CoreGraphics API as CoreGraphics.py did. -- 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 liuwensui at gmail.com Sat Nov 17 00:28:13 2007 From: liuwensui at gmail.com (Wensui Liu) Date: Sat, 17 Nov 2007 00:28:13 -0500 Subject: OT: good code snippet manager Message-ID: <1115a2b00711162128g62674aaaxc02c4bc9cbb63f6e@mail.gmail.com> Might anyone recommend a good code snippet manager to me? Thank you so much! -- =============================== WenSui Liu (http://spaces.msn.com/statcompute/blog) =============================== From snewman18 at gmail.com Mon Nov 5 11:11:47 2007 From: snewman18 at gmail.com (snewman18 at gmail.com) Date: Mon, 05 Nov 2007 08:11:47 -0800 Subject: Adding GNU Readline after installation? In-Reply-To: <1193992039.339107.192140@50g2000hsm.googlegroups.com> References: <1193971069.380839.63080@o3g2000hsb.googlegroups.com> <1193992039.339107.192140@50g2000hsm.googlegroups.com> Message-ID: <1194279107.600410.274740@o3g2000hsb.googlegroups.com> > > I really just want to get my "up arrow" history working... > > Google for "rlwrap". Thanks for the rlwrap tip - much easier than reinstalling Python (for the short term). For anyone interested, I installed it and put this in my .bashrc file: alias python='rlwrap python' Now I have my up-arrow history functionality. Thanks! From klenwell at gmail.com Fri Nov 2 23:21:37 2007 From: klenwell at gmail.com (klenwell) Date: Sat, 03 Nov 2007 03:21:37 -0000 Subject: __file__ vs __FILE__ Message-ID: <1194060097.141059.196040@e34g2000pro.googlegroups.com> I apologize in advance for coming at this from this angle but... In PHP you have the __FILE__ constant which gives you the value of the absolute path of the file you're in (as opposed to the main script file.) With the function dirname, this makes it easy to get the parent dir of a particular file from within that file: $parent_dir = dirname(__FILE__); I'm looking for the best way to accomplish this in Python. This seems to work: parent_dir = os.path.normpath(os.path.join(os.path.abspath(__file__), '..')) Can anyone confirm the reliability of this method or suggest a better (one-line) method for accomplishing this? Thanks, Tom From duncan.booth at invalid.invalid Mon Nov 5 04:06:05 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 5 Nov 2007 09:06:05 GMT Subject: python newbie References: <472b2b84$0$13761$6e1ede2f@read.cnntp.org> <5p0s6vFp47k9U1@mid.individual.net> <472b5251$0$6238$426a34cc@news.free.fr> <13ioa6f6t797gce@corp.supernews.com> <7x4pg3wks5.fsf@ruckus.brouhaha.com> <7x8x5f83u5.fsf@ruckus.brouhaha.com> <1194126214.238480.254180@57g2000hsv.googlegroups.com> <7xabpvkn0n.fsf@ruckus.brouhaha.com> <472defc8$0$30484$426a74cc@news.free.fr> <7xr6j52acl.fsf@ruckus.brouhaha.com> <472e1a1f$0$24020$426a74cc@news.free.fr> <7xsl3lrd2o.fsf@ruckus.brouhaha.com> <13ishf1ama66dab@corp.supernews.com> Message-ID: Steven D'Aprano wrote: > As far as I know, all it would take to allow modules to be callable > would be a single change to the module type, the equivalent of: > > def __call__(self, *args, **kwargs): > try: > # Special methods are retrieved from the class, not > # from the instance, so we need to see if the > # instance has the right method. > callable = self.__dict__['__call__'] > except KeyError: > return None # or raise an exception? > return callable(self, *args, **kwargs) > The error should throw "TypeError: 'module' object is not callable" just as it does today. Also, it shouldn't pass self through to callable: modules have functions not methods. From gandalf at shopzeus.com Mon Nov 19 08:39:03 2007 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Mon, 19 Nov 2007 14:39:03 +0100 Subject: securing a python execution environment... In-Reply-To: <871wamv1vn.fsf@lizard.lizardnet> References: <47417093.2070800@simplistix.co.uk> <871wamv1vn.fsf@lizard.lizardnet> Message-ID: <474191F7.1010609@shopzeus.com> Alberto Berti wrote: > maybe using import hooks? > > http://www.python.org/dev/peps/pep-0302/ > > I don't think so. Anyone can hook the import statement. And this is just one reason. Some objects are built in. For example, file(). How can you restrict file creation? I believe that there is no safe restricted environment, implemented in pure python. Best, Laszlo From nick-news at net4u.hr Fri Nov 16 08:48:02 2007 From: nick-news at net4u.hr (Nikola Skoric) Date: Fri, 16 Nov 2007 13:48:02 +0000 (UTC) Subject: formated local time References: Message-ID: Dana Thu, 15 Nov 2007 10:12:11 -0600, Adam Pletcher kaze: >> -----Original Message----- >> From: python-list-bounces+adam=volition-inc.com at python.org >> [mailto:python-list-bounces+adam=volition-inc.com at python.org] On > Behalf >> Of attn.steven.kuo at gmail.com >> Sent: Thursday, November 15, 2007 9:56 AM >> To: python-list at python.org >> Subject: Re: formated local time >> If you want the formatted string, you can use strftime: >> >> >>> time.strftime("%Y-%m-%d %H:%M:%S") >> '2007-11-15 07:51:12' > > datetime also has the strftime method: > > import datetime > datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') Thanks everybody! -- "Now the storm has passed over me I'm left to drift on a dead calm sea And watch her forever through the cracks in the beams Nailed across the doorways of the bedrooms of my dreams" From bj_666 at gmx.net Mon Nov 19 03:57:54 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 19 Nov 2007 08:57:54 GMT Subject: Finding lowest value in dictionary of objects, how? References: <642d8c24-a6bf-488d-9416-5ad37cc91ea5@d4g2000prg.googlegroups.com> Message-ID: <5qd1giFveka0U1@mid.uni-berlin.de> On Mon, 19 Nov 2007 00:18:33 -0800, davenet wrote: > The objects are defined as follows: > > class Block: > def __init__(self,addr): > self.addr = addr > self.age = 0 > > My dictionary is defined as: > blocks = {} > > I have added 1000 (will hold more after I get this working) objects. I > need to find the lowest age in the dictionary. If there is more than > one age that is lowest (like if several of them are '1', etc), then I > can just pick randomly any that equal the lowest value. I don't care > which one I get. > > I saw the following code here but I don't know how to use this sample > to get at the values I need in the blocks object. > > def key_of_lowest(self,addr) > lowest = min(self.blocks.values()) > return [k for k in self.blocks if self.blocks[k]==val][0] > > This one returns the lowest value Object, but not the lowest value of > age in all the Objects of the table. In the example `min()` finds the object with the lowest `id()`. To change that you can implement the `__cmp__()` method on your `Block` objects. Ciao, Marc 'BlackJack' Rintsch From gagsl-py2 at yahoo.com.ar Fri Nov 2 21:45:26 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 02 Nov 2007 22:45:26 -0300 Subject: os.readlink returning value References: <1193968274.369843.167520@v3g2000hsg.googlegroups.com> <1194021877.535595.38340@19g2000hsx.googlegroups.com> Message-ID: En Fri, 02 Nov 2007 13:44:37 -0300, Giampaolo Rodola' escribi?: > On 2 Nov, 05:30, "Gabriel Genellina" wrote: >> En Thu, 01 Nov 2007 22:51:14 -0300, Giampaolo Rodola' >> escribi?: >> >> > readlink( path) >> >> > ...It's not clear to me when the returning result could be absolute >> > and when it could be relative. >> >> That depends on how the symlink was created. Assume the current > I'd only want to do the same as what ls does in such cases. > Imho, os.readlink() should have the same behaviour of ls, isn't it? Yes; os.readlink shows the same as ls -l -- Gabriel Genellina From bignose+hates-spam at benfinney.id.au Thu Nov 29 16:41:42 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 30 Nov 2007 08:41:42 +1100 Subject: Job posting on the site is broken References: <042303ed-d871-431b-b908-9ab9b755c507@s12g2000prg.googlegroups.com> Message-ID: <87r6i8rap5.fsf@benfinney.id.au> sjol writes: > To the webmaster of python.org, > > I have tried to have a job posted on the job board but! Alas, it > doesn't work and I cannot get a response from the webmaster. > > Shall I post here ? No. But, since you say webmaster is not responding, asking here (as you have done) seems the correct next action to find someone responsible for the website. -- \ "Experience is that marvelous thing that enables you to | `\ recognize a mistake when you make it again." -- Franklin P. | _o__) Jones | Ben Finney From kay.schluehr at gmx.net Fri Nov 23 17:29:37 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Fri, 23 Nov 2007 23:29:37 +0100 Subject: the annoying, verbose self In-Reply-To: <4746D20F.6060507@sympatico.ca> References: <3c954a31-9fb9-4c0f-b784-cef9ee057ca6@g30g2000hsb.googlegroups.com> <6f67fccf-fbec-4c75-baea-5d0277e07883@w40g2000hsb.googlegroups.com> <4745dc0b$0$3051$426a74cc@news.free.fr> <023aa14b-98b3-4e1c-8282-b3fece7e35d2@s19g2000prg.googlegroups.com> <4746D20F.6060507@sympatico.ca> Message-ID: <47475451.3050509@gmx.net> Colin J. Williams schrieb: > Kay Schluehr wrote: >> On Nov 22, 8:43 pm, Bruno Desthuilliers >> wrote: >>> Colin J. Williams a ?crit : >>> >>> >>> >>>> bearophileH... at lycos.com wrote: >>>>> Alexy: >>>>>> Sometimes I >>>>>> avoid OO just not to deal with its verbosity. In fact, I try to use >>>>>> Ruby anywhere speed is not crucial especially for @ prefix is >>>>>> better- >>>>>> looking than self. >>>>> Ruby speed will increase, don't worry, as more people will use it. >>>>> Bye, >>>>> bearophile >>>> I don't see this as a big deal, but suppose that the syntax were >>>> expanded so that, in a method, a dot ".", as a precursor to an >>>> identifier, >>>> was treated as "self." is currently treated? >>> >>> >>> Python's "methods" are thin wrapper around functions, created at lookup >>> time (by the __get__ method of the function type). What you define in a >>> class statement are plain functions, period. So there's just no way to >>> do what you're suggesting. >>> >>> >> >> The object model is irrelevant here. The substitution is purely >> syntactical and gets resolved at compile time: >> >> def foo(first, ...): >> .bar = ... >> >> is always equivalent with: >> >> def foo(first, ...): >> first.bar = ... >> >> and generates the same bytecode. >> >> Whether this is helpfull, beautifull or necessary is another issue. >> >> Kay > > I had never thought of trying the above, which is, essentially what I was > suggesting, as the syntax specifies: > > primary ::= > atom | attributeref > | subscription | slicing | call > > attributeref ::= > primary "." identifier > > I did try it and get: > > # tmp.py > class Z(): > def __init__(self): > a= 1 > self.b= 2 > #.c= 3 Marked as a syntax error by PyScripter > > def y(self): > self.a= 4 > #.b= 5 Marked as a syntax error by PyScripter > > It seems that some, probably simple, change in the parsing is needed. > > Colin W. Sure. Since you cite the grammar let me say that I find it somewhat confusing that the grammar in the Python documentation doesn't correspond to the grammar used by the CPython parser. For the following I will use the notations of the Grammar file used by the CPython parser. In order to adapt the syntax take a look at atom: ('(' [yield_expr|testlist_gexp] ')' | '[' [listmaker] ']' | '{' [dictmaker] '}' | '`' testlist1 '`' | NAME | NUMBER | STRING+) The last row must be changed to ['.'] NAME | NUMBER | STRING+) ~~~~~ But then you run into conflict with the definition of the ellipsis in rule subscript: '.' '.' '.' | test | [test] ':' [test] [sliceop] because you need two token of lookahead. Pythons LL(1) parser might not manage this. This problem vanishes with Python 3.0 which defines an own ellipsis literal: atom: ('(' [yield_expr|testlist_comp] ')' | '[' [testlist_comp] ']' | '{' [dictorsetmaker] '}' | NAME | NUMBER | STRING+ | '...' | 'None' | 'True' | 'False') Kay From kyosohma at gmail.com Mon Nov 19 10:07:56 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 19 Nov 2007 07:07:56 -0800 (PST) Subject: Book: Python Power!: The Comprehensive Guide References: <473fda2a$0$3113$c3e8da3@news.astraweb.com> Message-ID: On Nov 18, 12:17 am, John Salerno wrote: > Anyone know anything about this book? I've read a few intro Python books > already, but I'm always interested in reading more to reinforce the > language. No reviews on Amazon yet so I'm not sure if it's good or not. > > Thanks. It's a mostly good book. I found the author to be slightly arrogant as he would dismiss certain features of Python on occasion and there were a couple of "huh!?" moments where he contradicted what seems (to me) to be common Python idioms. But there's a lot to like too. There's a real app or two at the end and it covers using cgi in Python better than any of the other Python books I've read. Mike From dotancohen at gmail.com Fri Nov 30 03:21:45 2007 From: dotancohen at gmail.com (Dotan Cohen) Date: Fri, 30 Nov 2007 10:21:45 +0200 Subject: Interfaces to high-volume discussion forums (was: Science list) In-Reply-To: <87myswr2ip.fsf_-_@benfinney.id.au> References: <474ed805$0$239$e4fe514c@news.xs4all.nl> <13ku2jn7np6797c@corp.supernews.com> <87myswr2ip.fsf_-_@benfinney.id.au> Message-ID: <880dece00711300021p74c35379w40df702097d4b37f@mail.gmail.com> On 30/11/2007, Ben Finney wrote: > "Dotan Cohen" writes: > > > On 29/11/2007, Dennis Lee Bieber wrote: > > > Regardless of what Google/Yahoo/M$/AOL want you to think, > > > using a web-based mail client is typically the worst way to follow > > > mailing lists and/or news-groups; much better to use a decent > > > client program that can download posts in the background, then > > > sort/thread/filter them as desired. > > > > With the exception of Gmail. I really could not follow 20+ high > > volume lists (such as Python, PHP, Fedora, MySQL, OOo, and some > > other very high traffic lists) without Gmail. > > I'm not interested in learning some centralised web-application > interface, and far prefer the discussion forum to be available by a > standard *protocol*, that I can use my choice of *local client* > application with. > > Most of the high-volume discussion lists I participate in are made > available as NNTP forums via news.gmane.org. I find that immeasurably > superior to any email interface, not least because I can use *any* > NNTP client to manage my interaction with those forums. > > The metaphor of discussion-forum-as-NNTP-newsgroup is, for my > purposes, far superior to discussion-forum-as-mailing-list. For those > forums only available as mailing lists, I find them much more awkward > to manage. > > The proliferation of "web forums", where the *only* way to participate > is to use an excreable web application that works differently to > everything else and has no connection to anything else I do on my > computer, is of course utterly antithesis to my needs. > > I would, of course, welcome an increase in the number of discussion > forums made available as NNTP groups, whether via Gmane or any other > service ? including the same people who host the mailing list (or, > gods forbid, "web forum"). > Ben, I agree with you! VBforum, PHPBB, Inforum, and countless other interfaces to learn drive me nuts. Add to that every web based email client's "Betas" and random changes, and the situation is a mess. That said, I _still_ prefer Gmail to any other option. I can tag and star messages and threads for later retrieval. The search function is great. I could go on and on. Yes, there are bugs in Gmail but every app I've tried has bugs. I didn't care much for any of gmane's webbased interfaces, and although I prefer work email locally (Kmail||Tbird) I now prefer a web-based mailing list || forum interface. Gmail is perfect for that. Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? A: Because it messes up the order in which people normally read text. Q: Why is top-posting such a bad thing? From BjornSteinarFjeldPettersen at gmail.com Tue Nov 6 04:20:39 2007 From: BjornSteinarFjeldPettersen at gmail.com (thebjorn) Date: Tue, 06 Nov 2007 09:20:39 -0000 Subject: How can i find the form name without "nr=0" In-Reply-To: <1194303368.896613.284050@50g2000hsm.googlegroups.com> References: <1194277885.824920.216370@57g2000hsv.googlegroups.com> <5p8sifFq47k4U1@mid.uni-berlin.de> <1194282336.694320.77700@z9g2000hsf.googlegroups.com> <5p91dhFpais1U1@mid.uni-berlin.de> <1194303368.896613.284050@50g2000hsm.googlegroups.com> Message-ID: <1194340839.109520.104310@19g2000hsx.googlegroups.com> On Nov 5, 6:05 pm, scripteaze wrote: [...] > Well, i wasnt sure if you could have a form without a form name, i was > just thinking that it had one but maybe hidden and that i could > retrieve it I see you've got the answer you wanted already, but just for completeness: the following is a sufficiently(*) valid form in html
which will have a textbox, and a submit button with localized text saying "Submit Query". If you type something into the textbox and hit the button, a GET request is sent to the same "page" with ?q=something appended to the url. You can do the same with POSTed forms:
in this case only a button with the text "Erase?" is visible. I'm not expressing an opinion on whether this is good form or not... -- bjorn (*) the HTML spec says that the action attribute is required, so theoretically you must include it. From paul.hankin at gmail.com Thu Nov 1 19:47:09 2007 From: paul.hankin at gmail.com (Paul Hankin) Date: Thu, 01 Nov 2007 23:47:09 -0000 Subject: help on dictionary In-Reply-To: <1193959311.970991.122730@o3g2000hsb.googlegroups.com> References: <1193959311.970991.122730@o3g2000hsb.googlegroups.com> Message-ID: <1193960829.534760.130180@50g2000hsm.googlegroups.com> On Nov 1, 11:21 pm, cesco wrote: > Hi, > > I have a defaultdict which I have initialized as follows: > > def train(features): > model = collections.defaultdict(lambda: 1) > for f in features: > model[f] += 1 > return model > > def_dict = train(large_set_of_words) > > where large_set_of_words is the list of possible strings. > > I'd like to use such a default_dict as follows: > > return max(list_of_strings, key=lambda w: dic[w]) > > that is, among the strings in list_of_strings, I'd like to return the > one with the highest score in def_dict. > > The problem with such approach is that if the list_of_strings contains > a string that is not part of the def_dict, such a string gets added to > it while I'd like to keep the original def_dict unchanged/frozen. > > Do you have any suggestion on how to do that? Use .get instead of [], and use sensible variable names: return max(words, key=lambda word: model.get(word, 1)) -- Paul Hankin From bdesth.quelquechose at free.quelquepart.fr Sat Nov 24 12:19:26 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 24 Nov 2007 18:19:26 +0100 Subject: How do I convert escaped HTML into a string? In-Reply-To: <47484834.8030809@web.de> References: <47484834.8030809@web.de> Message-ID: <47485d3a$0$28505$426a34cc@news.free.fr> Stefan Behnel a ?crit : > leej at citymutual.com wrote: > >>On 24 Nov, 05:42, "Just Another Victim of the Ambient Morality" >> wrote: >> >> >>>I did find some people who complained about this and rolled their own >>>solution but I refuse to believe that Python doesn't have a built-in >>>solution to what must be a very common problem. >> >>Replace "python" with "c++" and would that seem a reasonable belief? > > > That's different, as Python comes with batteries included. Unfortunately, you still have to write a couple lines of code every once in a while !-) From Frank.Aune at broadpark.no Thu Nov 8 04:15:45 2007 From: Frank.Aune at broadpark.no (Frank Aune) Date: Thu, 8 Nov 2007 10:15:45 +0100 Subject: pyserial: loose connection after inactivity Message-ID: <200711081015.45477.Frank.Aune@broadpark.no> Hello, I configure the serial connection using: self.port = serial.Serial(baudrate=57600, timeout=0.06, parity=serial.PARITY_EVEN, stopbits=serial.STOPBITS_TWO, bytesize = serial.EIGHTBITS) After X hours of inactivity I loose connection to my serial device, with error message "Input/Output error" printed to stdout. The error happens both on Linux and Windows (although the error message is probably different on Windows, I've only been told the behaviour is the same). I cannot find an obvious reason for why this is happening, and since it happens after a long time of inactivite, debugging is awkward. So I though I'd run the question through the expert panel for ideas, before venturing down the path of pain and suffering myself :) Best regards, Frank From nospam at nospam.com Wed Nov 21 10:15:43 2007 From: nospam at nospam.com (Gilles Ganault) Date: Wed, 21 Nov 2007 16:15:43 +0100 Subject: Clean way to get one's network IP address? Message-ID: Hello I need to get the local computer's IP address, ie. what's displayed when running "ifconfig" in Linux: # ifconfig eth0 Link encap:Ethernet HWaddr 00:15:58:A1:D5:6F inet addr:192.168.0.79 Bcast:192.168.0.255 Mask:255.255.255.0 I know about socket.gethostbyname, but this relies on what's in /etc/hosts, and I'd rather have a more independent solution. What would be a good way to do this? Thank you. From steve at REMOVE-THIS-cybersource.com.au Fri Nov 23 18:19:20 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Fri, 23 Nov 2007 23:19:20 -0000 Subject: Recursive loading trouble for immutables References: Message-ID: <13kenvor2qgj4b0@corp.supernews.com> On Fri, 23 Nov 2007 16:43:28 -0600, rekkufa wrote: > I am currently building a system for serializing python objects to a > readable file-format, as well as creating python objects by parsing the > same format. You mean like pickle? (Pardon me for telling you something you may already know, but then you may not already know it...) >>> import pickle >>> >>> # Create a recursive tuple. ... alist = [1, 2, 3] >>> atuple = (4, 5, alist) >>> alist.append(atuple) >>> >>> atuple (4, 5, [1, 2, 3, (4, 5, [...])]) >>> pickle.dumps(atuple) '(I4\nI5\n(lp0\nI1\naI2\naI3\na(I4\nI5\ng0\ntp1\na0000g1\n.' pickle can dump to files, using either text or binary protocols, and load objects back from either files or strings. I won't pretend the text protocol is exactly human readable, but perhaps the way forward is to write a post-processor to convert the output of pickle to something more human-readable, rather than writing a completely new serializer. -- Steven. From donn.ingle at gmail.com Mon Nov 5 08:33:25 2007 From: donn.ingle at gmail.com (Donn Ingle) Date: Mon, 05 Nov 2007 15:33:25 +0200 Subject: pyparsing frames and tweens - take 2 References: <1194254785.718898.256060@o80g2000hse.googlegroups.com> Message-ID: Paul, > frame = Literal("#") > tween = Word("-") # that is, it is a "word" composed of 1 or more -'s > copy = Literal("=") > blank = Literal("_") > > animation = OneOrMore((frame + Optional( > (tween + FollowedBy(frame)) | > OneOrMore(copy | blank) ) ) ) I found that this form insists on having a # in char 0. How could it be changed to take a bunch of blanks before the first frame? ____# ? I have tried: animation = OneOrMore( Optional ( blank | frame ) + Optional( (tween + FollowedBy(frame) ) | OneOrMore(copy | blank) ) ) And permutations thereof, but it goes into a black hole. \d From gregpinero at gmail.com Thu Nov 8 14:10:41 2007 From: gregpinero at gmail.com (gregpinero at gmail.com) Date: Thu, 08 Nov 2007 19:10:41 -0000 Subject: Using imaplib module with GMAIL's IMAP - hangs In-Reply-To: <1194547974.193957.141650@e34g2000pro.googlegroups.com> References: <1194547285.816141.110230@v29g2000prd.googlegroups.com> <1194547974.193957.141650@e34g2000pro.googlegroups.com> Message-ID: <1194549041.421128.284420@q5g2000prf.googlegroups.com> On Nov 8, 1:52 pm, Jason wrote: > On Nov 8, 11:41 am, "gregpin... at gmail.com" > wrote: > > > I'm trying to get a list of messages from GMAIL using it's new IMAP > > access. > > > So far I've tried running this command but it just hangs. Any ideas? > > > >>> import imaplib > > >>> M=imaplib.IMAP4('imap.gmail.com',993) > > > I figured that's the first line to run from this example:http://docs.python.org/lib/imap4-example.html > > > Here are the configuration settings GMAIL says to use:https://mail.google.com/support/bin/answer.py?answer=78799 > > > Thanks for any help. > > > -Greg > > Well, Google states that it's using SSL. You're not using the SSL > with your example code. Take a look in the imaplib module. At least > under Python 2.5, there's also an IMAP4_SSL class: > > >>> import imaplib > >>> mail = imaplib.IMAP4_SSL('imap.gmail.com', 993) > > That worked for me. I could then use the login method to log into the > mail server. > > --Jason Thanks! That worked. You're a gem. -Greg From roger.miller at nova-sol.com Thu Nov 29 14:46:48 2007 From: roger.miller at nova-sol.com (Roger Miller) Date: Thu, 29 Nov 2007 11:46:48 -0800 (PST) Subject: Determine whether program was started by clicking icon or command line References: <5r7cs0F136db0U1@mid.individual.net> Message-ID: <2ee58d13-1ff4-4882-bbef-8ba2b9e48337@a35g2000prf.googlegroups.com> On Nov 28, 10:51 pm, Benjamin Hell wrote: > Hi! > > I wonder whether there might be a way to find out how a Python > program was started (in my case in Windows): By double clicking the > file or by calling it on the "DOS" command line prompt. > > Background: I would like to have the program run in an "interactive > mode" if double clicked, and silently in a "batch mode" when started > otherwise. I'm not sure whether this applies to your situation, but often programs started by clicking an icon are run by pythonw, but when started from the command line are run by python. If this is the case sys.stdin.fileno() will return -1 in the former case and 0 in the latter. From steve at REMOVE-THIS-cybersource.com.au Sat Nov 3 03:34:47 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 03 Nov 2007 07:34:47 -0000 Subject: Can local function access local variables in main program? References: <1194074297.822435.92380@o3g2000hsb.googlegroups.com> Message-ID: <13io94nmf8ln2b9@corp.supernews.com> On Sat, 03 Nov 2007 07:18:17 +0000, Sullivan WxPyQtKinter wrote: > def f(): > print x > x=0 > > x=12345 > f() > > result is: > Traceback (most recent call last): > File "...\test.py", line 5, in ? > f() > File "...\test.py", line 2, in f > print x > UnboundLocalError: local variable 'x' referenced before assignment When Python compiles your function f(), it sees that you have assigned to x, and that there is no line "global x", so it knows that x is a local variable. But when you call f(), you try to print x before the local x has a value assigned to it. Hence the (accurate but hardly user-friendly) error message. You can also do this: >>> help(UnboundLocalError) Help on class UnboundLocalError in module exceptions: class UnboundLocalError(NameError) | Local name referenced but not bound to a value. As far as I know, there is no way to read the value of global x if and only if local x doesn't exist. -- Steven From nytrokiss at gmail.com Mon Nov 26 20:08:19 2007 From: nytrokiss at gmail.com (James Matthews) Date: Tue, 27 Nov 2007 02:08:19 +0100 Subject: Rss Feed Creator In-Reply-To: <474B6CDF.1070304@ncee.net> References: <8a6b8e350711261645p1b41b0e0rda70204462e1a8b9@mail.gmail.com> <474B6B79.8010208@ncee.net> <8a6b8e350711261701p70f84075g35ca7b517cb2cab9@mail.gmail.com> <474B6CDF.1070304@ncee.net> Message-ID: <8a6b8e350711261708oe4ad16ch38ae603bc7b32a46@mail.gmail.com> Is there any where you do not have us tidy? On Nov 27, 2007 2:03 AM, Shane Geiger wrote: > I think this is what you need to make the output readable: > > tidy -asxml output.xml > > > > > > James Matthews wrote: > > Thank You Shane, > > > > However that is using PyRss2Gen which doesn't put newlines in the XML. > > So it's a little out of the picture! > > On Nov 27, 2007 1:57 AM, Shane Geiger < sgeiger at ncee.net > > > wrote: > > > > http://www.bigbold.com/snippets/tag/beautifulsoup > > > > > > > > James Matthews wrote: > > > Hi, > > > > > > I am looking for a library that will create Rss/Atom feeds in > > python. > > > It needs to format the XML in a readable format! Does anyone > > have any > > > suggestions? > > > > > > Thanks James > > > > > > > > > -- > > > http://search.goldwatches.com/?Search=Movado+Watches > > > http://www.goldwatches.com/coupons > > > http://www.jewelerslounge.com > > > > > > -- > > Shane Geiger > > IT Director > > National Council on Economic Education > > sgeiger at ncee.net | 402-438-8958 | > > http://www.ncee.net > > > > Leading the Campaign for Economic and Financial Literacy > > > > > > > > > > -- > > http://search.goldwatches.com/?Search=Movado+Watches > > http://www.goldwatches.com/coupons > > http://www.jewelerslounge.com > > > -- > Shane Geiger > IT Director > National Council on Economic Education > sgeiger at ncee.net | 402-438-8958 | http://www.ncee.net > > Leading the Campaign for Economic and Financial Literacy > > -- http://search.goldwatches.com/?Search=Movado+Watches http://www.jewelerslounge.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From matthieu.brucher at gmail.com Wed Nov 7 01:43:41 2007 From: matthieu.brucher at gmail.com (Matthieu Brucher) Date: Wed, 7 Nov 2007 07:43:41 +0100 Subject: How do I get the PC's Processor speed? In-Reply-To: <001a01c820bf$e6d525b0$b47f7110$@com> References: <1194376737.430731.60750@o80g2000hse.googlegroups.com> <1194383371.766037.117080@z9g2000hsf.googlegroups.com> <001a01c820bf$e6d525b0$b47f7110$@com> Message-ID: > > Executing the CPUID instruction may be helpful if you can figure out how > these guys are using it: > http://www.cpuid.com/cpuz.php > Numpy has an interface for this function. Matthieu -- French PhD student Website : http://miles.developpez.com/ Blogs : http://matt.eifelle.com and http://blog.developpez.com/?blog=92 LinkedIn : http://www.linkedin.com/in/matthieubrucher -------------- next part -------------- An HTML attachment was scrubbed... URL: From michele.simionato at gmail.com Tue Nov 6 22:47:19 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Wed, 07 Nov 2007 03:47:19 -0000 Subject: Confused about closures and scoping rules In-Reply-To: References: <20071107002343.8162.1155154160.divmod.quotient.32563@ohm> Message-ID: <1194407239.326216.297980@19g2000hsx.googlegroups.com> On Nov 6, 7:37 pm, "Chris Mellon" wrote: > On Nov 6, 2007 6:23 PM, Jean-Paul Calderone wrote: > > Lots of people ask about this. The behavior you observed is the expected > > (by the implementors, anyway) behavior. > > Are there languages where closures *don't* behave like this? A closure > that used a copy of the state rather than the actual state itself > doesn't seem as useful. For references sake, JavaScript (the only > language that a) has closures and b) I have a handy way to test with) > does the same thing. Closures in Haskell's list comprehensions work as Fernando (and many others would expect). See for instance this post: http://groups.google.com/group/comp.lang.python/browse_frm/thread/d691240a5cfebcdf/63234494ebbca54e?hl=en&lnk=gst&q=simionato+haskell#63234494ebbca54e Michele Simionato From enleverlesX.XmcX at XmclaveauX.com Fri Nov 30 04:48:36 2007 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Fri, 30 Nov 2007 10:48:36 +0100 Subject: PIL + show() + Vista In-Reply-To: <474f5197$0$27369$ba4acef3@news.orange.fr> References: <474f5197$0$27369$ba4acef3@news.orange.fr> Message-ID: <474fdf54$0$27367$ba4acef3@news.orange.fr> Re! I have found the problem. On Vista, the Windows-Photo-Galery (soft default displayer) don't wait. Even with START /WAIT (in Image.py & _showxv), it don't wait. Then, like the preview don't wait, the (next) "DEL" run prior the end of the launch of the software ; and Windows-Photo-Galery don't found the file... I don't have a good solution. For force view of image, it's possible to delete the "DEL /F %s" part ; but that will involve many BMP/temporary files. @+ & sorry for my bad english Michel Claveau From zhushenli at gmail.com Thu Nov 22 21:33:03 2007 From: zhushenli at gmail.com (Davy) Date: Thu, 22 Nov 2007 18:33:03 -0800 (PST) Subject: Is there pointer * in Python? Message-ID: Hi all, When I read "programming python", I found there is a code like def parse(self, *text): while text is a string. What's "*" mean?(Does it mean pointer like in C?) And I recall there is "**args" in Python, what's "**" mean? Best regards, Davy From gagsl-py2 at yahoo.com.ar Tue Nov 6 17:20:38 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 06 Nov 2007 19:20:38 -0300 Subject: global name is not defined References: <1194386232.498054.74520@d55g2000hsg.googlegroups.com> Message-ID: En Tue, 06 Nov 2007 18:57:12 -0300, barronmo escribi?: > I'm getting an error msg I don't understand, "global name EMR_globals > is not defined", and could use some help. > > I've separated the application I'm building into several modules. One > of the modules holds variables I need to pass from one module to > another and is called 'EMR_globals'. Several other modules hold > functions or user menus and then 'EMR_main' controls the initial user > interaction. I'm using MySQL to hold the data. Global variables usually are not a good design decision, but that's not your current problem. > The initial connection to the database is done by 'EMR_main'. > Functions then define and close a cursor for various queries. The > connection variable, 'conn', is defined 'conn = "" ' in EMR_globals > and then used in EMR_main. Unfortunately when a module.function > attempts to use it I get the error msg. In Python, "global" means "global to the module". If conn is defined in EMR_globals, when you want to use it elsewhere, you can: a) from EMR_globals import conn ... cursor = conn.cursor(...) b) import EMR_globals ... cursor = EMR_globals.conn.cursor(...) Usually those import statements are placed at the top of the module. > cursor.execute("SELECT * FROM demographics WHERE patient_ID = %s" > % (a,)) > selected_pt = cursor.fetchall() > # if this query returns more than one record the following code will > fail I think > print menus.menu_demographics(selected_pt['firstname'], > selected_pt['lastname'], ... I think it will fail even with one record, because fetchall() returns a list of rows. Try using fetchone(). Anyway, if patient_ID is the primary key, you should always get a single row. -- Gabriel Genellina From horpner at yahoo.com Fri Nov 16 12:02:22 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Fri, 16 Nov 2007 17:02:22 GMT Subject: Python Design Patterns - composition vs. inheritance References: <13jqadr38lcml31@corp.supernews.com> Message-ID: On 2007-11-16, Dennis Lee Bieber wrote: > On Thu, 15 Nov 2007 12:28:28 -0800 (PST), "snewman18 at gmail.com" > declaimed the following in comp.lang.python: > >> >> As a very simplified example, if I had two classes, Pet and Owner, it >> seems that I would not have Pet inherit from Owner, since a pet 'has >> an' owner, but not 'is an' owner. If this is correct, does my code >> below reflect this? I passed the owner object into the pet object's >> constructor - is this the right way to do it? >> > Well, other than the facet that I'd say "Owner" has-a "Pet", but > this example is a bit too disjoint for the association (IE, it goes both > ways) > > A common example is something like: > > class Vehicle(object): > #which has attributes for speed, direction, cargo capacity, > passenger capacity > > class RoadVehicle(Vehicle): > #inherits (RoadVehicle IS-A Vehicle with Axles) > > class Auto(RoadVehicle) > # HAS-A Front-Axle, Rear-Axle > # and Axle HAS-A Left-Tire, Right-Tire (unless a Dual -- with > inner left, outer left, inner right, outer right, those those would > appear on Bus(RoadVehicle) and Truck(RoadVehicle) classes) > > Look up "Law of Demeter" (I believe that is the name). The idea > is that a "user" of, say, Auto, should NOT need to know that it > has tires (may know it has axles, so it may have a > "listAxles()" method, which returns a list/tuple of the axles > that the Auto has. You could then use that list to access the > tires on each axle { for tire in aRoadVehicle.listAxles(): > print tire.specification() } The Law of Demeter constrains the attributes that the methods of Auto may invoke. Given the above containment hierarchy, the Law says that no method of Auto may depend on any attribute or method of Tire. So if you needed to compute, in an Auto method, something that depends on an attribute of Tire, you must make that information available directly through the Axle interface. The benefit is that this lowers the coupling between classes. The Tire interface can change completely without affecting the Auto class. > BUT... Just look at the Python library... sys.stdout.write(), > if following Law of Demeter would turn into: > > myStdout = sys.getStdout() > myStdout.write() The Law of Demeter doesn't apply to that example. -- Neil Cerutti From paul at subsignal.org Sun Nov 25 08:06:04 2007 From: paul at subsignal.org (paul) Date: Sun, 25 Nov 2007 14:06:04 +0100 Subject: How to display unicode with the CGI module? In-Reply-To: <5qsknfF11nhdfU1@mid.uni-berlin.de> References: <5qsknfF11nhdfU1@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch schrieb: > On Sat, 24 Nov 2007 15:58:56 -0800, coldpizza wrote: > >> The problem I am having is that I get an error while trying to display >> Unicode UTF-8 characters via a Python CGI script. >> >> The error goes like this: "UnicodeEncodeError: 'ascii' codec can't >> encode character u'\u026a' in position 12: ordinal not in range(128)". > > Unicode != UTF-8. You are not trying to send an UTF-8 encoded byte string > but an *unicode string*. Just to expand on this... It helps thinking of "unicode objects" and "strings" as seperate types (which they are). So there is no such thing like "unicode string" and you always need to think about when to encode() your unicode objects. However, this will change in py3k..., what's the new rule of thumb? cheers Paul From arkanes at gmail.com Tue Nov 6 14:35:25 2007 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 6 Nov 2007 13:35:25 -0600 Subject: How do I get the PC's Processor speed? In-Reply-To: <1194376737.430731.60750@o80g2000hse.googlegroups.com> References: <1194376737.430731.60750@o80g2000hse.googlegroups.com> Message-ID: <4866bea60711061135i33f07262l20f2f95b1b6d3a05@mail.gmail.com> On Nov 6, 2007 1:18 PM, wrote: > Hi, > > We use a script here at work that runs whenever someone logs into > their machine that logs various bits of information to a database. One > of those bits is the CPU's model and speed. While this works in 95% of > the time, we have some fringe cases where the only thing returned is > the processor name. We use this data to help us decide which PCs need > to be updated, so it would be nice to have the processor speed in all > cases. > > Currently, this script is run on Windows boxes only, most of which > have Windows XP on them. Right now I am having Python check the > following registry key for the CPU info: HKEY_LOCAL_MACHINE\HARDWARE\ > \DESCRIPTION\\System\\CentralProcessor\\0 > > I've also used Tim Golden's WMI module like so: > > > > import wmi > c = wmi.WMI() > for i in c.Win32_Processor (): > cputype = i.Name > > > > On the problem PCs, both of these methods give me the same information > (i.e. only the processor name). However, if I go to "System > Properties" and look at the "General" tab, it lists the CPU name and > processor speed. Does anyone else know of another way to get at this > information? > You'd want the MaxClockSpeed property. There's a few other clock speed properties as well, see http://msdn2.microsoft.com/en-us/library/aa394373.aspx. MSDN should always be your first stop with WMI questions, by the way. From kyosohma at gmail.com Tue Nov 20 16:41:39 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 20 Nov 2007 13:41:39 -0800 (PST) Subject: simple question on persisting variable values in a list References: <2e46934e-385a-413c-b1fc-fee64a2e3640@c29g2000hsa.googlegroups.com> Message-ID: <1e5f8ccc-6f7c-4a9c-9b9a-18c8d4d0d965@f13g2000hsa.googlegroups.com> On Nov 20, 3:25 pm, dgris... at gmail.com wrote: > Hi, > > I am an unabashed noob. > > I am trying to build a list to store values that are generated through > a loop. However, every time I append the variable to the list, I'd > like to reset the variable, but have the value persist in the loop. I > understand why this doesn't work because it's a reference not a > literal value but have been unsuccessful at using copy.copy() or > anything else to accomplish this: > > for char in splitlines[r]: > > if char == "\n": > temp = copy.deepcopy(templine) > individline.append(temp) > templine = "" > else: > templine += char > > results.append(individline) > > This just gives me the last element in splitlines[r] - what i want is > to persist each line that is parsed from splitlines[] into the results > list. > > Appreciate any help,,, Not sure if this is what you want, but here's what I did: >>> x = 'blah\nblah\n' >>> lst = [] >>> templine = '' >>> for char in x: if char == '\n': temp = templine lst.append(temp) templine = '' else: templine += char >>> lst ['blah', 'blah'] Mike From amutharr at gmail.com Tue Nov 27 03:56:18 2007 From: amutharr at gmail.com (amutharr at gmail.com) Date: Tue, 27 Nov 2007 00:56:18 -0800 (PST) Subject: FREE AIR TICKET Message-ID: AIR TICKET FOR SWIZ ANSWER SIMPLE QUESTIONhttp://rexmier.blogspot.com/ From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Nov 23 12:06:11 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 23 Nov 2007 18:06:11 +0100 Subject: may be a bug in string.rstrip In-Reply-To: References: Message-ID: <4747086a$0$14454$426a34cc@news.free.fr> Scott SA a ?crit : > On 11/23/07, kyo guan (kyoguan at gmail.com) wrote: > >> Please look at this code: >> >>>>> 'exe.torrent'.rstrip('.torrent') >> 'ex' <----- it should be 'exe', why? >> >> but this is a right answer: >> >>>>> '120.exe'.rstrip('.exe') >> '120' <------ this is a right value. >> >> there is a bug in the rstrip, lstrip there isn't this problem. > > Since your error has been addressed, I'd like to offer a point not expressed by others (that I've seen yet). > > To perform this task, there are a couple of options i.e. string.replace: > > >>> string.replace('120.exe','.exe','') > '120' > > ... but it has a side-effect of mid-string replacements: > > >>> string.replace('123.exe.more','.exe','') > '123.more' > > or maybe: > > >>> if x[-4:] == '.exe': > ... x[:-4] > '123' > > ... is functional, but not elegant i.e. quick 'n dirty esp. as one line. > > The better option, IMO, is probably to use regex. You forgot at least the simplest solution: import os.path os.path.splitext('132.ext')[0] HTH From gnewsg at gmail.com Tue Nov 27 12:17:42 2007 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Tue, 27 Nov 2007 09:17:42 -0800 (PST) Subject: os.path.islink documentation error? Message-ID: <39860dba-58b3-4b6c-8700-bd6c1b3d4f60@s36g2000prg.googlegroups.com> os.path.islink documentation says: "Return True if path refers to a directory entry that is a symbolic link. Always False if symbolic links are not supported." It's not clear to me why it is mentioned the DIRECTORY term. Shouldn't os.path.islink be used to just check if the *path* passed as argument is a symlink? In such case I would change it in: "Return True if path refers to a symbolic link" From bj_666 at gmx.net Tue Nov 6 05:55:51 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 6 Nov 2007 10:55:51 GMT Subject: how to filter files by creation date References: <1194334396.714190.225780@22g2000hsm.googlegroups.com> <5pal98Fq52s0U1@mid.uni-berlin.de> <1194342302.752133.235560@57g2000hsv.googlegroups.com> <5patt5Fq52s0U2@mid.uni-berlin.de> <1194345346.452344.52500@19g2000hsx.googlegroups.com> Message-ID: <5pavhnFq52s0U3@mid.uni-berlin.de> On Tue, 06 Nov 2007 02:35:46 -0800, awel wrote: >> >> In [438]: !touch test.py >> >> >> In [439]: datetime.date.fromtimestamp(os.stat('/home/bj/test.py').st_ctime) >> >> Out[439]: datetime.date(2007, 11, 6) >> >> > Could you explain a little more because I am new in scripting? >> >> Not really. I showed you the call I made and the result I got. How can I >> be more clear and precise!? > > Ok but I run in Windows and I cannot understand your '!touch test.py' Ah, sorry this was just to create and/or make sure that the file exists and has today's date. Ciao, Marc 'BlackJack' Rintsch From bjourne at gmail.com Fri Nov 23 18:38:24 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Fri, 23 Nov 2007 23:38:24 +0000 Subject: the annoying, verbose self In-Reply-To: <47458D4E.5030302@sympatico.ca> References: <3c954a31-9fb9-4c0f-b784-cef9ee057ca6@g30g2000hsb.googlegroups.com> <6f67fccf-fbec-4c75-baea-5d0277e07883@w40g2000hsb.googlegroups.com> <47458D4E.5030302@sympatico.ca> Message-ID: <740c3aec0711231538p34761b46qfbe2905adbd833f6@mail.gmail.com> On Nov 22, 2007 2:08 PM, Colin J. Williams wrote: > bearophileHUGS at lycos.com wrote: > > Alexy: > >> Sometimes I > >> avoid OO just not to deal with its verbosity. In fact, I try to use > >> Ruby anywhere speed is not crucial especially for @ prefix is better- > >> looking than self. > > > > Ruby speed will increase, don't worry, as more people will use it. > > > > Bye, > > bearophile > > I don't see this as a big deal, but The big deal is that "self." occupies important horizontal screen real estate. That is, it is usually not self in itself that is problematic, but the overflowing lines is. Take this silly vector class for example: 1 class Vector: 2 def __init__(self, x, y, z): 3 self.x = x 4 self.y = y 5 self.z = z 6 def abs(self): 7 return math.sqrt(self.x * self.x + self.y * self.y + self.z * self.z) Line 7 is 82 characters long which is, if you care about the readability of your code, a very real problem because the line is to long. So you break it: 7 return math.sqrt(self.x * self.x + self.y * self.y + self.z * self.z) Better, but definitely not as nice as it would have been with a shorter self prefix like you propose. And in my eyes, having to break lines like this instantly makes the code much less attractive. There is probably not a single language in existance in which wrapping lines doesn't make the code uglier. I also notice that the lines in your mail are nicely broken at about column 45, probably because you are typing on a PDA or similar? In those situations, where you require much shorter lines than the standard 78 characters, for example when typesetting code examples for a book, the problem with line breaks is even worse. > suppose that the syntax were > expanded so that, in a method, a dot > ".", as a precursor to an identifier, > was treated as "self." is currently treated? I like that a lot. This saves 12 characters for the original example and removes the need to wrap it. 7 return math.sqrt(.x * .x + .y * .y + .z * .z) +1 Readability counts, even on small screens. -- mvh Bj?rn From lew at lewscanon.com Wed Nov 14 15:12:23 2007 From: lew at lewscanon.com (Lew) Date: Wed, 14 Nov 2007 15:12:23 -0500 Subject: SPAM In-Reply-To: <473b4fdf$0$79951$742ec2ed@news.sonic.net> References: <1195065929.848318.25100@i13g2000prf.googlegroups.com> <473b46c3$0$79945$742ec2ed@news.sonic.net> <473b4fdf$0$79951$742ec2ed@news.sonic.net> Message-ID: just bob wrote: > "John Bean" wrote in message > news:uajmj398b7bscocruik918hlc0khvfn3st at 4ax.com... >> On Wed, 14 Nov 2007 11:04:35 -0800, "just bob" >> wrote: >> >> Your SPAM appears to be non-existent. Vapourware. Not real. >> >> Shame, I fancied a Spam fritter. >> > > The guy gets Google dollars when people view the site or click on links, me > thinks. It's spam. Yes, but it's not SPAM. SPAM is a registered trademark of Hormel Foods Corporation for a canned pork product. Spam is unwanted messages or email. -- Lew From ptmcg at austin.rr.com Fri Nov 16 12:10:31 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Fri, 16 Nov 2007 09:10:31 -0800 (PST) Subject: overriding methods - two questions References: Message-ID: <2ef27f6d-836a-487d-b854-f5e082f35e32@e4g2000hsg.googlegroups.com> On Nov 16, 11:03 am, Donn Ingle wrote: > Hi, > Here's a framework for the questions: > > --- In a module, part of an API --- > class Basis ( object ): > def foo ( self, arg ): > pass > > --- In user's own code --- > class Child ( Basis ): > def foo ( self, not, sure ): > ... > > Question 1: > > Given that the user of the API can choose to override foo() or not, how can > I control the signature that they use? In the example the user has chosen > bad arguments and Python will complain, but it's describing the sig of the > *overridden* method and not the one in the parent class. Actually, Python is complaining about your user's poor choice of argument names. 'not' is a reserved keyword. Change it to 'naught' or 'knot' or 'not_' and Python will accept this just fine. Whether this is a good idea or not is a separate question. But given Python's philosophy of "you are the human, so you must know what you are doing" (which is both an assumption and a directive), I don't think you will find much language machinery to prevent it. -- Paul -- Paul From sjmachin at lexicon.net Mon Nov 12 06:09:36 2007 From: sjmachin at lexicon.net (John Machin) Date: Mon, 12 Nov 2007 03:09:36 -0800 Subject: Extended date and time In-Reply-To: References: <1194823374.273619.79930@s15g2000prm.googlegroups.com> Message-ID: <1194865776.788990.279360@v23g2000prn.googlegroups.com> On Nov 12, 8:46 pm, Jeremy Sanders wrote: > John Machin wrote: > > What does "dates in the past" mean?? Please be more specific about the > > earliest date that you want to be able to handle. Python's datetime > > starts at 0001-01-01. Somebody mentioned the time module, which is > > implementation-dependent but typically starts at 1970-01-01 . > > > What functionality do you need, other than two-way conversion between > > days_since_epoch and (proleptic Gregorian) date/time? > > I want to convert between seconds from the epoch (let's say 1970 in floating > point) and date and time. I also want it to work across all platforms. > > Is there any way to convert a datetime into seconds from a certain date? Is > the most robust way of doing it just to subtract two datetime objects and > turn the timedelta into a floating point number? > That seems to be robust enough: C:\junk>type epoch.py import datetime now = datetime.datetime(2007, 11, 12, 21, 20, 39, 859123) for epoch_year in (1, 1970, 2070): EPOCH = datetime.datetime(epoch_year, 1, 1) print "\nepoch", repr(EPOCH) diff = now - EPOCH print "diff", repr(diff) sdiff = diff.microseconds / 1000000. \ + diff.seconds + diff.days * 24. * 3600. print "sdiff", repr(sdiff) roundtrip = EPOCH + datetime.timedelta(seconds=sdiff) print "roundtrip", repr(roundtrip) C:\junk>epoch.py epoch datetime.datetime(1, 1, 1, 0, 0) diff datetime.timedelta(732991, 76839, 859123) sdiff 63330499239.859123 roundtrip datetime.datetime(2007, 11, 12, 21, 20, 39, 859123) epoch datetime.datetime(1970, 1, 1, 0, 0) diff datetime.timedelta(13829, 76839, 859123) sdiff 1194902439.859123 roundtrip datetime.datetime(2007, 11, 12, 21, 20, 39, 859123) epoch datetime.datetime(2070, 1, 1, 0, 0) diff datetime.timedelta(-22696, 76839, 859123) sdiff -1960857560.140877 roundtrip datetime.datetime(2007, 11, 12, 21, 20, 39, 859123) C:\junk> Cheers, John From kyosohma at gmail.com Wed Nov 28 14:13:31 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Wed, 28 Nov 2007 11:13:31 -0800 (PST) Subject: wxPython problem References: Message-ID: <4382bb28-0d12-4734-8de5-75524750445e@d27g2000prf.googlegroups.com> On Nov 28, 1:06 pm, SMALLp wrote: > Hy. I'm new in linux (Ubuntu 7.10) as well as in python. I installed > IDLE, and i installed package python-wxgtkX. I start IDLE and when i > want co compile my aplication all windows close. Also when i vrite > smoethin lik thile in IDLE: > > import wx > app = wx.App() > wx.Frmae(none, -1) > > same thing, Please help! Thanks! I'm not sure, but I don't think you downloaded the package correctly. Go here for complete instructions: http://wxpython.org/download.php I think you need to replace the "X" in "python-wxgtkX" with the release number. Something like "python-wxgtk2.8" or some such. Then try to import wx and see if that works. If none of that works, post to the wxPython user's group which can be found at the link above. Mike From deets at nospam.web.de Thu Nov 29 13:06:49 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 29 Nov 2007 19:06:49 +0100 Subject: Tkinter, wxPython, PyGtk, or PyQt... In-Reply-To: References: <6be45504-8f27-47c2-9ba1-38f0d6a0d6f4@e6g2000prf.googlegroups.com> Message-ID: <5r8ddvF137u41U1@mid.uni-berlin.de> gsal schrieb: > is PyQt related to Qt? I presume so. > > is Qt needed for PyQt? Sure. > is PyQt usable in all platforms Python is available and is it GPLed, > too? Yes. Diez From ptmcg at austin.rr.com Wed Nov 28 14:37:27 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Wed, 28 Nov 2007 11:37:27 -0800 (PST) Subject: Control mouse position and clicking References: <4f209559-4454-4f8a-8ba3-18cbb50db094@b40g2000prf.googlegroups.com> Message-ID: <0b474190-7527-4946-884b-b8c8d4ed246e@i12g2000prf.googlegroups.com> On Nov 28, 1:29 pm, Glich wrote: > hi, how can I, control mouse position and clicking from python? > > I want to interact with a flash application inside firefox. thanks. > > ps: I am not using windows. Ooof, I was about to suggest using pywinauto, because I was able to interact with a flash app with that module, until I saw your p.s. So even though you are not using windows and can't use this technique directly, I am just posting to give you some encouragement that, at least theoretically, such a thing can be done. -- Paul From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Nov 19 07:41:46 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 19 Nov 2007 13:41:46 +0100 Subject: overriding methods - two questions In-Reply-To: <13js4tebjlucv16@corp.supernews.com> References: <473dd35a$0$7999$426a34cc@news.free.fr> <13js4tebjlucv16@corp.supernews.com> Message-ID: <4741848a$0$20133$426a34cc@news.free.fr> Steven D'Aprano a ?crit : > On Fri, 16 Nov 2007 18:28:59 +0100, Bruno Desthuilliers wrote: > >>> Question 1: >>> >>> Given that the user of the API can choose to override foo() or not, how >>> can I control the signature that they use? >> While technically possible (using inspect.getargspec), trying to make >> your code idiot-proof is a lost fight and a pure waste of time. > > > Worse: it's actually counter-productive! > > The whole idea of being able to subclass a class means that the user > should be able to override foo() *including* the signature. If you see subclassing as subtyping, the signatures should always stay fully compatibles. From loveu1life at gmail.com Wed Nov 28 09:30:41 2007 From: loveu1life at gmail.com (loveu1life at gmail.com) Date: Wed, 28 Nov 2007 06:30:41 -0800 (PST) Subject: You can very happy Message-ID: <6479659f-63e3-4076-be1c-88fc01c16107@a35g2000prf.googlegroups.com> Dear Sir/Madam We are one of the largest wholesalers in China who mainly sell stylish electronic product and equipment such as Digital Cameras, Mobile Phone, Laptops, Mp4, GPS, Digital Video and bulk products such as LCD TV, Motorcycles, Binoculars and Musical Instruments and so on with various international famous brands. We offer our customer good valuable product with very competitive price because we have advanced goods circulating solution and supporter. We have our own warehouse and stores, our clients all over the world. When you choose our products you will also enjoy our fast delivery. We appreciate all of customers' comments and will continue to improve our service in order to satisfy our old and new customer. During Christmas and New Year Holiday we have a various promotion plan. It will be out soon. Please welcome to visit our website www.elec-bc.com to check your voucher. Thanks. MSN & E-mail:elec-bc at hotmail.com From donn.ingle at gmail.com Fri Nov 23 07:39:14 2007 From: donn.ingle at gmail.com (Donn Ingle) Date: Fri, 23 Nov 2007 14:39:14 +0200 Subject: Is there pointer * in Python? References: <4746c51e$0$5067$ba4acef3@news.orange.fr> Message-ID: > think inside Python... Assuming you *can* think while being slowly crushed and digested :D \d From http Tue Nov 6 17:14:04 2007 From: http (Paul Rubin) Date: 06 Nov 2007 14:14:04 -0800 Subject: Populating huge data structures from disk References: <000001c820a1$78750ea0$695f2be0$@com> <4866bea60711061104i514838fcld9bbba1382a764a6@mail.gmail.com> Message-ID: <7xsl3jggyb.fsf@ruckus.brouhaha.com> "Michael Bacarella" writes: > Very sure. If we hit the disk at all performance drops > unacceptably. The application has low locality of reference so > on-demand caching isn't an option. We get the behavior we want when > we pre-cache; the issue is simply that it takes so long to build > this cache. The way I do it is run a separate process that mmaps the file and reads one byte from each page every half hour or so. You are right that it makes a huge difference. From hat at se-162.se.wtb.tue.nl Mon Nov 26 02:21:14 2007 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Mon, 26 Nov 2007 08:21:14 +0100 Subject: Code Management References: <7d81e2cc-b243-4d63-a20a-d10709241eaf@e4g2000hsg.googlegroups.com> <9ebda8f9-361b-40df-9c3a-fc180cab5e6b@l1g2000hsa.googlegroups.com> <87bq9otdxg.fsf@benfinney.id.au> <2ccb31d2-9458-44c9-bfa5-3af0e1ea5616@d27g2000prf.googlegroups.com> Message-ID: On 2007-11-24, BlueBird wrote: > On Nov 21, 7:05 am, "Sergio Correia" wrote: > And then you do your development in python-dev. But how do you manage > multiple development branches of the same program ? If you are using SVN, you may want to check out 'combinator' by Divmod (divmod.org). That tool manages SVN branches, and also switches Python when you switch branches. Very handy. Albert From adam at volition-inc.com Wed Nov 14 12:29:11 2007 From: adam at volition-inc.com (Adam Pletcher) Date: Wed, 14 Nov 2007 11:29:11 -0600 Subject: current script path via execfile? In-Reply-To: References: <893A44FF792E904A97B7515CE341914601C3EAD2@volimxs01.thqinc.com> Message-ID: <893A44FF792E904A97B7515CE341914601C3ED2C@volimxs01.thqinc.com> That works well, thank you! - Adam > -----Original Message----- > From: python-list-bounces+adam=volition-inc.com at python.org > [mailto:python-list-bounces+adam=volition-inc.com at python.org] On Behalf > Of Gabriel Genellina > Sent: Wednesday, November 14, 2007 12:34 AM > To: python-list at python.org > Subject: Re: current script path via execfile? > > En Tue, 13 Nov 2007 13:42:04 -0300, Adam Pletcher inc.com> > escribi?: > > > I have an app with an embedded Python interpreter. In that > interpreter, > > I want to use "execfile" (or something similar) to execute a script > from > > disk. The script needs to somehow acquire the full path to itself, > but > > I can't work out how to do this. > > > > > > Since it's run with execfile in the embedded interpreter, there's no > > sys.argv to look at. Is there another way to get the current > script's > > full pathname? > > Set a __file__ variable in the globals that you pass to execfile: > > fullpath = os.path.abspath(your script file) > g = globals().copy() > g['__file__'] = fullpath > execfile(fullpath, g) > > From inside the executed script, just inspect __file__ > > -- > Gabriel Genellina > From sjmachin at lexicon.net Sun Nov 25 05:55:38 2007 From: sjmachin at lexicon.net (John Machin) Date: Sun, 25 Nov 2007 02:55:38 -0800 (PST) Subject: Trouble getting loop to break References: <48f9c4a1-ae3a-4fdf-97f3-4c76e12d5aeb@b15g2000hsa.googlegroups.com> <20071120210132.BF3D11E499A@bag.python.org> <3d0cebfb0711201332r71f1621bue29a8ec19f7f65d8@mail.gmail.com> Message-ID: <37506a5f-c676-49e6-9bf6-c7c85b37f851@d4g2000prg.googlegroups.com> On Nov 25, 7:00 pm, Dick Moores wrote: > At 01:32 PM 11/20/2007, Fredrik Johansson wrote: > > > > > > > > >On Nov 20, 2007 10:00 PM, Dick Moores wrote: > > > And also with the amazing Chudnovsky algorithm for pi. See > > > > > >Nice! I'd like to suggest two improvements for speed. > > >First, the Chudnovsky algorithm uses lots of factorials, and it's > >rather inefficient to call mpmath's factorial function from scratch > >each time. You could instead write a custom factorial function that > >only uses multiplications and caches results, something like this: > > >cached_factorials = [mpf(1)] > > >def f(n): > > n = int(n) > > if n < len(cached_factorials): > > return cached_factorials[n] > > p = cached_factorials[-1] > > for i in range(len(cached_factorials), n+1): > > p *= i > > cached_factorials.append(p) > > return p > > >(In some future version of mpmath, the factorial function might be > >optimized so that you won't have to do this.) > > >Second, to avoid unnecessary work, factor out the fractional power of > >640320 that occurs in each term. That is, change the "denom =" line to > > > denom = (f(3*k) * ((f(k))**3) * (640320**(3*k))) > > >and then multiply it back in at the end: > > > print 1/(12*sum/640320**(mpf(3)/2)) > > >With these changes, the time to compute 1,000 digits drops to only > >0.05 seconds! > > >Further improvements are possible. > > >Fredrik > > Fredrik, > > I'm afraid I'm just too dumb to see how to use your first suggestion > of cached_factorials. Where do I put it and def()? Could you show me, > even on-line, what to do? (1) Replace line 8 (from mpmath import factorial as f) with Fredrik's code. (2) Test it to see that it gave the same answers as before ... [time passes] Wow! [w/o psyco] Pi to 1000 decimal places takes 13 seconds with original code and 0.2 seconds with Fredrik's suggestion. 2000: 99 seconds -> 0.5 seconds. From cwitts at gmail.com Mon Nov 26 03:36:54 2007 From: cwitts at gmail.com (Chris) Date: Mon, 26 Nov 2007 00:36:54 -0800 (PST) Subject: better way to write this function References: <4b4d9cc5-3759-421e-b3a2-3cb25bdaae7a@b40g2000prf.googlegroups.com> Message-ID: <42f62547-3cc7-46dd-95e0-52d1885d7e09@d61g2000hsa.googlegroups.com> On Nov 26, 9:42 am, Kelie wrote: > Hello, > > This function does I what I want. But I'm wondering if there is an > easier/better way. To be honest, I don't have a good understanding of > what "pythonic" means yet. > > def divide_list(lst, n): > """Divide a list into a number of lists, each with n items. Extra > items are > ignored, if any.""" > cnt = len(lst) / n > rv = [[None for i in range(n)] for i in range(cnt)] > for i in range(cnt): > for j in range(n): > rv[i][j] = lst[i * n + j] > return rv > > Thanks! x = ['1', '2', '3', '4', '5', '6', '7', '8'] def divide_list(lst, n): rv = [] for i in range(int(round((len(lst)/n),0))): rv.append(lst[i*n:(i+1)*n]) return rv tmp = divide_list(x, 3) tmp [['1', '2', '3'], ['4', '5', '6']] One way to do it. From tjreedy at udel.edu Mon Nov 19 17:17:47 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 19 Nov 2007 17:17:47 -0500 Subject: Is python.org blocking traffic from the ibm.com domain? References: <9ab13c4c-558a-442e-826f-03d8534c50eb@y43g2000hsy.googlegroups.com> Message-ID: | Can someone responsible for maintaining the website please check what | is happening and help me (and the rest of the IBM community) get back | into the python website ? forwarded to webmaster at python.org From dfabrizio51 at gmail.com Tue Nov 13 18:09:36 2007 From: dfabrizio51 at gmail.com (chewie54) Date: Tue, 13 Nov 2007 15:09:36 -0800 Subject: eclipse for developing and debugging python C or C++ extensions Message-ID: <1194995376.674972.27740@22g2000hsm.googlegroups.com> Hi All, Has anyone used eclipse to develop and debug c or c++ extensions for python? Is it possible to you PyDev and CDT with eclipes to get an integrated environment in which I could debug both Python and C using the debuggers in each plugin respectively? If not, how do others develop and debug c or c++ python extensions? I use a Mac for development but would switch to Windows or Linux if needed to get a better development environment. Thanks in advance, From davidtweet at gmail.com Fri Nov 30 03:54:59 2007 From: davidtweet at gmail.com (David Tweet) Date: Fri, 30 Nov 2007 00:54:59 -0800 Subject: Crackly sound in pygame In-Reply-To: <9fe4d7a6-bf02-4db7-be90-4f75378a78ca@e10g2000prf.googlegroups.com> References: <9fe4d7a6-bf02-4db7-be90-4f75378a78ca@e10g2000prf.googlegroups.com> Message-ID: <3fd0162e0711300054h259f4ef4r161a58b0378c68b@mail.gmail.com> Before calling pygame.init(), you can call pygame.mixer.pre_init. Make sure the sample rate and sample size matches your audio file. But most likely the issue is that the default audio buffer size of 1024 doesn't cut it for some sound cards; try increasing to the next power of two. Ex. pygame.mixer.pre_init(44100, -16, 2, 2048) On Nov 29, 2007 7:33 PM, Woot4Moo at gmail.com wrote: > Hey guys I am running Windows XP and am having an issue with a game > that my team has created. Whenever an audio file is played it creates > a very distorted, crackly sound. Any ideas what could be the issue? > > Thanks > -- > http://mail.python.org/mailman/listinfo/python-list > -- -David From ptmcg at austin.rr.com Fri Nov 2 08:47:38 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Fri, 02 Nov 2007 05:47:38 -0700 Subject: Is pyparsing really a recursive descent parser? In-Reply-To: <5p0dhgFnj4rbU1@mid.uni-berlin.de> References: <5p0dhgFnj4rbU1@mid.uni-berlin.de> Message-ID: <1194007658.200713.178210@57g2000hsv.googlegroups.com> On Nov 2, 5:47 am, Marc 'BlackJack' Rintsch wrote: > > Pyparsing is no recursive descent parser. It doesn't go back in the input > stream. The ``OneOrMore(Word(alphas))`` part "eats" the 'end' and when it > can't get more, the parser moves to the ``Literal('end')`` part which > fails because the 'end' is already gone. > > > Is there a way to get pyparsing to parse a grammar like this? > > Negative lookahead maybe: > > grammar = (OneOrMore(NotAny(Literal('end')) + Word(alphas)) > + Literal('end')) > > Ciao, > Marc 'BlackJack' Rintsch- Hide quoted text - > > - Show quoted text - Well I'll be darned! All this time, I thought "recursive descent" described the recursive behavior of the parser, which pyparsing definitely has. I never knew that backing up in the face of parse mismatches was a required part of the picture. In pyparsing, each construction gets composed from more fine-grained constructions, and they are called recursively to match or not match against the input string. For example, taking your working parser example: grammar = (OneOrMore(NotAny(Literal('end')) + Word(alphas)) + Literal('end')) This creates the following data structure: - And - OneOrMore - And - NotAny - Literal('end') - Word(alphas) - Literal('end') Every instance in this structure derives from the base class ParserElement, which defines a method parse(). parse() in turn calls preParse(), parseImpl(), and postParse(). If parseImpl succeeds, it returns a ParseResults object and the next location within the input string to continue parsing. The parseImpl methods are most often overridden in the subclasses (a few override postParse as well), such as: - And.parseImpl invokes parse() (note the recursion) on each of the expressions in its list. All must succeed or And.parseImpl throws an exception. - OneOrMore.parseImpl invokes parse() on its contained expression, which must succeed at least once; if not, the exception is rethrown. If the contained expression succeeds once, then its parse() method is called again and again until it fails, but no exceptions are rethrown, since only one match was actually required. - NotAny inverts the success/failure of its contained expression. If the expression's parse() method succeeds, NotAny.parseImpl throws an exception. If the contained expression's parse() method throws an exception, NotAny returns successfully. (NotAny does not advance the parse location, nor does it return any tokens.) - Literal and Word are terminals, in that they do not invoke any other expression's parse() method. Literal.parseImpl tests whether its string exists at the current parse location, and throws an exception if it doesn't. Word.parseImpl tests whether the current parse location contains a letter in the Word instance's set of valid initial characters - if so success; if not, throws an exception. It then advances through the input string, matching characters in the Word instance's set of valid body characters. The entire matched string is then returned, along with an updated string index at which to continue parsing. In my concept of "recursive descent" parsing, I was under the impression that pyparsing's use of this data structure, and *recursive* calls of parse() as it *descends* through the data structure, constituted a recursive descent parser. What the OP requested was a more regular expression-ish matcher, with backup (or backtracking). Your example did not include either of the alternation classes, MatchFirst or Or. These classes implement a form of backtracking on the stack, that if we descend into an expression on the list of alternatives, and that expression fails, then MatchFirst or Or will back up to the same starting location and try the next alternative. (MatchFirst is an "eager" matcher, in that it will pick the first matching expression in its list - Or is an "exhaustive" matcher, in that it will evaluate all of the alternatives, and select the longest match.) The Wikipedia entry for "Recursive Descent Parser" describes this parser model as a "predictive parser", and later goes on to say that some (uncited) authors equate "predictive parser" with "recursive descent parsers". The article makes a special distinction for a "recursive parser with backup", which is what I believe the OP was asking for. Yes, pyparsing is definitely *not* a "recursive descent parser with backup." The solution, as you correctly posted, is to add a negative lookahead. NotAny is also represented using the '~' operator. By the way, there are a couple of other places where pyparsing diverges from the standard model: - implicit whitespace skipping - user-definable comment skipping - attachment of parse actions to expressions These features, while atypical, provide some added capability and ease- of-use in creating quick and simple parsers. So I will take my stance with the uncited authors who lump predictive parsers in with recursive descent parsers. -- Paul From steve at REMOVE-THIS-cybersource.com.au Thu Nov 8 18:25:02 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 08 Nov 2007 23:25:02 -0000 Subject: Some "pythonic" suggestions for Python References: <5PGdnWmWZIdZ967anZ2dnUVZ_uuqnZ2d@cavtel.net> Message-ID: <13j76merr3an4d0@corp.supernews.com> On Thu, 08 Nov 2007 15:00:03 -0500, Frank Samuelson wrote: > 1. Currently in Python > def foo(x,y): ... > assigns the name foo to a function object. Is this pythonic? > > Why not use the = operator like most other assignments? Why? What benefit do you gain? > Define function objects as "function"s, let users put them where they > want to. Get rid of lambda, get rid of def, only use = for assignments. So you remove two keywords. That's a plus. But then you have to create a WHOLE lot more syntax to support it, and that's about a thousand minuses. Python has very little syntax, and the designers are (rightly) very resistant to adding more. > foo = function(x,y) x+y*2 # Example S language code This would currently be a syntax error, hence the need for new syntax. Also, function() couldn't be a normal type, or even a built-in function, because it has to have special syntax: name = function(*argument_list) expression It's also not clear how you expect this to work with anything more complex than a single expression. How do you handle statements and multiple returns? def foo(x, y): L = [] try: if x[y] % 2: print x, y return y return x[y] except: return None > bar = foo But you can still do this with Python: def foo(x, y): return x+y*2 bar = foo > 2. Allow sequences to be indices: > >>> s=["hello", 6, 33, "none"] > >>> x= [1,3] > >>> [ s[y] for y in x] # Current verbose version > [6, 'none'] I don't especially call it verbose. > >>> s[x] # Simpler, clearer, more productive It's certainly smaller. But the fatal objection to this is that it is a special case for a very limited benefit: saving half a dozen characters. List comprehensions are very flexible: [float(s[3*i % 2]) for i in x if 3 <= i < 12] # for example... Your proposal doesn't have anywhere near that flexibility. It simply duplicates perhaps the most trivial list comp [s[y] for y in x], just to save a dozen or so characters. Python doesn't treat terseness as that big a virtue. Besides, if you want this behaviour, you can add it yourself: class mylist(list): # Untested! def __getitem__(self, index): if type(index) is list: return [self[i] for i in index] return super(mylist, self).__getitem__(index) list = mylist The only difference is you have to write: s = list([1,2,3]) instead of s = [1,2,3]. > To quote a poster at http://www.thescripts.com/forum/thread22741.html, > "While we are at it, I also don't understand why sequences can't be used > as indices. Why not, say, l[[2,3]] or l[(2, 3)]? Why a special slice > concept? " Isn't that unpythonic? But can't you see that the suggestion to use sequences as replacements for slices is completely incompatible with your suggestion above? seq = range(10) Would you expect seq[[2,6]] to do an index lookup, as you suggested originally, or a slice? In the first case, it would return [2, 6], but in the second, it would return [2, 3, 4, 5]. If sequence indices are slices, what does an index of [1, 2, 3, 4] mean? > 3. When I first > started using python, I frequently used map, because I didn't want to > have to learn the additional syntax of list comprehensions, which > appeared very nonstructured. It is a slightly more verbose form of standard mathematical set notation. In case it comes out wrong, the symbol ? is supposed to be the symbol for "element". "the set of 3x+1 such that x is in (1, 2, 3) if x is odd" { 3x+1 : x ? (1, 2, 3) if x%2 } becomes the list comprehension: [ 3*x+1 for x in (1, 2, 3) if x%2 ] > # Is this readable? > b= [x+y for x in vec1 if x>0 for y in vec2 if y>x ] It is probably pushing the boundaries of how readable a list comp can get before it should be refactored, but it hasn't crossed over into unreadability. > Perhaps a list comprehension syntax more like the rest of python. I think the great majority Python folks find the list comprehension syntax to be one of the MOST Pythonic features, not the least. -- Steven. From hniksic at xemacs.org Fri Nov 9 06:24:05 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 09 Nov 2007 12:24:05 +0100 Subject: defaultdict and dict? References: <1194606107.406260.54650@k35g2000prh.googlegroups.com> Message-ID: <874pfvy84q.fsf@mulj.homelinux.net> Davy writes: > In Python 2.5 document, defaultdict is called high performance > container. From document, we can know defaultdict is subclass of dict. > So, why defaultdict have higher performance than dict? I don't think the "high performance" attribute is supposed to mean that it has higher performanec than dict, only that it is not a simple-minded hack on top of dict, but code carefully written in C with performance in mind -- like dict itself. > That is, when use defaultdict and when use dict? Any suggestions are > welcome! Use defaultdict when you need the dict to handle missing keys automatically, dict in all other cases. If in doubt, simply use dict. From steven.bethard at gmail.com Wed Nov 21 12:27:03 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 21 Nov 2007 10:27:03 -0700 Subject: Python web frameworks In-Reply-To: <4bc5e86c-0e95-4ea6-b406-a83131e355f0@d50g2000hsf.googlegroups.com> References: <226020ef-3955-43e8-b1f6-2ba9ba43d45e@c29g2000hsa.googlegroups.com> <5qga2mFvuljgU1@mid.uni-berlin.de> <160f8bbc-70be-4dcb-8874-de72588c1d10@d61g2000hsa.googlegroups.com> <1b343163-e755-44f8-b5c3-4af56c61e817@c29g2000hsa.googlegroups.com> <93a92a82-cf3c-4ebb-a93f-180374e5f75a@e4g2000hsg.googlegroups.com> <4744159b$0$24310$426a74cc@news.free.fr> <4bc5e86c-0e95-4ea6-b406-a83131e355f0@d50g2000hsf.googlegroups.com> Message-ID: Jeff wrote: > On Nov 21, 6:25 am, Bruno Desthuilliers 42.desthuilli... at wtf.websiteburo.oops.com> wrote: >> joe jacob a ?crit : >> (snip) >> >>> Thanks everyone for the response. From the posts I understand that >>> Django and pylons are the best. By searching the net earlier I got the >>> same information that Django is best among the frameworks so I >>> downloaded it and I found it very difficult to configure. >> ??? >> >> It's been a couple of years since I last used Django, but I don't >> remember any specific complexity wrt/ configuration. > > The only difficulties I have had have been with serving static media. > Specifically, in the differences in setup between the development > environment and production, and setting it up so that I don't have to > make any changes to the code in order to roll out upgrades to a > product. I ran into this same problem. I wish it was simply a matter of starting the django project on another server, but a bunch of paths and URLs always seem to need to be changed. (I end up having to modify my urls.py files because I go from being at the URL root on the development server to being in a subdirectory on the actual server.) Other that those issues though, I've really enjoyed working in Django. STeVe From mpelzsherman at yahoo.com Tue Nov 13 14:09:32 2007 From: mpelzsherman at yahoo.com (Michael Pelz Sherman) Date: Tue, 13 Nov 2007 11:09:32 -0800 (PST) Subject: why no automatic conversion in string concatenation? In-Reply-To: <20071113174412.GC23052@sdf.lonestar.org> Message-ID: <941931.1355.qm@web55315.mail.re4.yahoo.com> Thanks Cliff. Not to belabor this point - clearly it's just something I'll have to get used to - but isn't the choice of the "+" as the concatenation operator part of the problem here? A more "explicit" choice would have been an "append()" function, would it not? Or at least a non-ambiguous character. Obviously python *does* know that I'm concatenating, not adding, due to the type of the LH object, and it would save me a lot of time if I didn't have to explicitly convert my objects to strings. Any rule can be abused... - Michael "J. Clifford Dyer" wrote: On Tue, Nov 13, 2007 at 07:15:06AM -0800, Michael Pelz Sherman wrote regarding why no automatic conversion in string concatenation?: > > As a Java & PHP developer, I find it kind of annoying that I have to > explicitly convert non-string variables to strings when concatenating > them, especially when python is quite capable of doing the conversion > automatically. > i.e.: > >>> myBool = True > >>> print myBool > True > >>> print "myBool is " + myBool > Traceback (most recent call last): > File "", line 1, in > TypeError: cannot concatenate 'str' and 'bool' objects > >>> print "myBool is " + str(myBool) > myBool is True > Can anyone explain why this is so? Because python doesn't know if '1' + 1 should equal 2 or '11' and would rather you mad that decision. Should it be different than 1 + '1'? or to put it more succinctly, because "explicit is better than implicit." In fact, I think it's more often the case that I have string data that I need to treat as integers than the other way around (input from stdin and textfiles for example). > Are there any plans to change this > in python 3000? I hope not, and I don't think so. > Thanks, > - Michael No problem. Cheers, Cliff -------------- next part -------------- An HTML attachment was scrubbed... URL: From arkanes at gmail.com Tue Nov 20 12:02:54 2007 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 20 Nov 2007 11:02:54 -0600 Subject: mmap disk performance In-Reply-To: <33540d51-3039-4046-80e6-2b1ddf92a26d@a28g2000hsc.googlegroups.com> References: <33540d51-3039-4046-80e6-2b1ddf92a26d@a28g2000hsc.googlegroups.com> Message-ID: <4866bea60711200902n43163b92q1a85e33e4cf67e9d@mail.gmail.com> On Nov 20, 2007 10:31 AM, koara wrote: > Hello all, > > i am using the mmap module (python2.4) to access contents of a file. > > My question regards the relative performance of mmap.seek() vs > mmap.tell(). I have a generator that returns stuff from the file, > piece by piece. Since other things may happen to the mmap object in > between consecutive next() calls (such as another iterator's next()), > i have to store the file position before yield and restore it > afterwards by means of tell() and seek(). Is this correct? > > When restoring, is there a penalty for mmap.seek(pos) where the file > position is already at pos (i.e., nothing happened to the file > position in between, a common scenario)? If there is, is it worth > doing > > if mmap.tell() != pos: > mmap.seek(pos) > > or such? > Measure it and see. I suspect that the cost of the check in Python will outweigh any extra work the C code might do, but you should never guess - just measure it. This is also pretty unlikely to be any sort of hotspot in your application - again, measure and see. Unless your profiler says you spend a lot of time in mmap.seek calls, don't worry about it. From paddy3118 at googlemail.com Tue Nov 6 02:54:04 2007 From: paddy3118 at googlemail.com (Paddy) Date: Tue, 06 Nov 2007 07:54:04 -0000 Subject: permuting over nested dicts? In-Reply-To: References: <1193908332.223564.3040@z24g2000prh.googlegroups.com> Message-ID: <1194335644.739355.78380@o3g2000hsb.googlegroups.com> On Nov 1, 10:51 am, Christian Meesters wrote: > Thanks everyone, > > I knew there must be a snippet somewhere, just couldn't find one! (Just for > the sake of completeness: Order doesn't matter and I hope that with my data > I won't reach the recursion depth limit.) > > Christian My solution using comb2 is recursive so there is no problem with recursion depth. - Paddy. From wlwoon at gmail.com Thu Nov 1 16:01:36 2007 From: wlwoon at gmail.com (Wei Lee Woon) Date: Thu, 1 Nov 2007 16:01:36 -0400 Subject: Strange problem when using re module with threads Message-ID: <35c9b1fd0711011301l7be7c736yce75734856be8093@mail.gmail.com> Dear all I've been getting a rather strange problem with the following multithreaded code (reduced to the minimum which still results in the problem): import threading import re class hey(threading.Thread): def run(self): print re.compile("\d+").search("hey95you").group(); thlist=[] for tech in range(2): thlist.append(hey()) thlist[-1].start() for th in thlist: th.join() After saving this to a file (say "test.py"), if I try to run this from the console using "python test.py", it seems to work fine, but when i try to run it from the python interactive shell using "import test", it freezes up (if i don't issue the join() it is fine, though). Any ideas why this is so? Thanks Wei Lee -------------- next part -------------- An HTML attachment was scrubbed... URL: From bscrivener42 at gmail.com Wed Nov 21 11:56:46 2007 From: bscrivener42 at gmail.com (BartlebyScrivener) Date: Wed, 21 Nov 2007 08:56:46 -0800 (PST) Subject: Python web frameworks References: <226020ef-3955-43e8-b1f6-2ba9ba43d45e@c29g2000hsa.googlegroups.com> <5qga2mFvuljgU1@mid.uni-berlin.de> <160f8bbc-70be-4dcb-8874-de72588c1d10@d61g2000hsa.googlegroups.com> <1b343163-e755-44f8-b5c3-4af56c61e817@c29g2000hsa.googlegroups.com> <93a92a82-cf3c-4ebb-a93f-180374e5f75a@e4g2000hsg.googlegroups.com> Message-ID: <8b339374-9890-4a3f-ac18-3a9e120c9fe7@f3g2000hsg.googlegroups.com> On Nov 21, 4:42 am, joe jacob wrote: > Django is best among the frameworks so I > downloaded it and I found it very difficult to configure. I referred > the djangobook. It's not a turnkey type thing like WordPress or Joomla. It's a webframework. Also watch versions. The book examples work only in . 96. It's easy in the tutorial to stray into docs for .95 or SVN. I think that's part of the confusion. rd From martin at v.loewis.de Fri Nov 30 18:10:03 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 01 Dec 2007 00:10:03 +0100 Subject: Check if a symlink is broken or circular In-Reply-To: <45167a44-22e6-4e0a-b2a4-38fea0a7bab1@y43g2000hsy.googlegroups.com> References: <45167a44-22e6-4e0a-b2a4-38fea0a7bab1@y43g2000hsy.googlegroups.com> Message-ID: <4750984B.7060803@v.loewis.de> > I would like to know if such function would be correct for verifying > if a link is broken and/or circular. > > def isvalidlink(path): > assert os.path.islink(path) > try: > os.stat(path) > except os.error: > return 1 > return 0 You meant to flip the result values, right? 1 should mean that the link is value, and 0 that it is not. Mostly. If the link is correct, but you don't have permission to stat the target file, you get 0. OTOH, in that case, you have no way of finding out whether the link *is* correct. Still, you could try to detect the errnos that indicate a problem with the link itself, and pass all other errors through. Regards, Martin From horpner at yahoo.com Mon Nov 5 06:04:18 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Mon, 05 Nov 2007 11:04:18 GMT Subject: Is pyparsing really a recursive descent parser? References: <5p0dhgFnj4rbU1@mid.uni-berlin.de> <1194007658.200713.178210@57g2000hsv.googlegroups.com> <1194104971.263256.66640@d55g2000hsg.googlegroups.com> <43rXi.397547$6L.130044@fe03.news.easynews.com> <1194223837.104424.242360@o3g2000hsb.googlegroups.com> <6xvXi.39855$G23.18679@newsreading01.news.tds.net> Message-ID: On 2007-11-05, Just Another Victim of the Ambient Morality wrote: > "Neil Cerutti" wrote in message > news:6xvXi.39855$G23.18679 at newsreading01.news.tds.net... >> There are different kinds of recursion. Compare: > > While interesting, none of this actually addresses the > point I was making. I wasn't saying that there was no > recursion (at least, not in this paragraph), I was saying that > it wasn't recursing through what I thought it should be > recursing through. It recurses through a set of rules without > any regard to how these rules interact with each other. That's > why it fails to parse valid strings. In my opinion, it should > recurse through appropriate combinations of rules to determine > validity, rather than by arbitrary > categorization... OK. I thought you were saying that, without backtracking there's no recursion. Never mind! > I guess that all the And and Or class in pyparsing call > methods of each other from each other, even if they are doing > so from different instantiations. I still say they're not > recursing through the right things... Backtracking seems orthoganal to recursion, to me. >>>> I'm not sure one needs to start again with a naive approach just to >>>> avoid any parser theory. For a user of a parser it is quite important >>>> whether she has to wait 50 seconds for a parse to run or 50 >>>> milliseconds. I don't like to compromise speed for implementation >>>> simplicity here. >>> >>> Finally, I can't believe you complain about potential speed >>> problems. First, depending on the size of the string, it's >>> likely to be the difference between 2ms and 200ms. Secondly, >>> if speed were an issue, you wouldn't go with a recursive >>> descent parser. You'd go with LALR or the many other parsing >>> techniques available. Recursive descent parsing is for those >>> situations where you need correctness, regardless of execution >>> time. These situations happen... >> >> RDP is plenty fast; speed has never been one of it's >> disadvantages, as far as I know. Today there are many >> excellent parser generators and compiler builders that compose an >> RDP under the hood, e.g., Antlr and Gentle. > > I think I read somewhere that LALR was O(n) while RDP was > O(e^n). Most people would consider that, at least, slower... To my knowledge, most RDPs are LL(1), which is O(n). As you increase the amount of lookahead (a backtracking RDP is, I suppose, be a brute-force way of getting infinite lookahead), the complexity increases. > I think your examples may exemplify how little speed > matters rather than how fast RDPs are... > > Also, it should probably be noted that bubble sort is very > fast for nearly sorted lists; much faster than quicksort. So, > while it shouldn't be the default sorting algorithm, you could > have it somewhere in the library... Yes, bubble-sort runs fast in certain circumstances; you wouldn't want to be bereft of it completely. Backtracking parsers do probably have their place in the pantheon. I don't want PyParsing to do backtracking by default, though it might be a useful option. -- Neil Cerutti From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun Nov 4 06:45:49 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sun, 04 Nov 2007 12:45:49 +0100 Subject: Low-overhead GUI toolkit for Linux w/o X11? References: <13ipjvic6aj8c69@corp.supernews.com> <13ipvnvoqoh735f@corp.supernews.com> <5p4jqmFog9g5U1@mid.individual.net> <13iqa3rbns0c975@corp.supernews.com> Message-ID: <5p5pndFpm1piU1@mid.individual.net> Grant Edwards wrote: > On 2007-11-04, Bjoern Schliessmann >> Erm, wxWidgets is implemented in C++ > > Are you saying C++ software can't be large and slow? No, but wxWidgets is quite mature and my experience is that it's faster than Qt (partly, I think, because it always uses the native widgets). >> and wxPython is just a wrapper. > > Yes, I know. If we though Python was the problem, I wouldn't > be asking about other toolkits that had Python bindings. Ah, you know more than you wrote? If you've done measurements, I'd find them quite interesting to see. Regards, Bj?rn -- BOFH excuse #295: The Token fell out of the ring. Call us when you find it. From kyosohma at gmail.com Thu Nov 15 12:18:31 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 15 Nov 2007 09:18:31 -0800 (PST) Subject: Printing user input? References: <46e7af01-5cf6-4f7a-926f-73a3ecc0db47@v4g2000hsf.googlegroups.com> Message-ID: <29d7cdf4-fc68-4413-993b-ace630999a00@b15g2000hsa.googlegroups.com> On Nov 15, 11:03 am, Mohammed_M wrote: > Hi, > I'm v.new to Python, so please don't be too harsh :) > I get a NameError with the code below - All I want to do is store some > input taken from the user in a variable called name, & then print name > > # START CODE ========================================== > # Print name demo > > def PersonsDetails(): > name = input("What's your name?") > PersonsDetails() > > print(name) > > # END CODE ========================================== > > Thanks for reading & any help on this It's a scope issue. You have the variable, "name", inside a function and then you try to reference it outside the function, where it is not defined. Thus, Python gives an error. To fix this, put the print statement in the function itself...and when you use print, you don't usually put the object to be printed in parentheses. def PersonsDetails(): name = input("What's your name?") print name PersonsDetails() See also this article on scopes and namespaces: http://www.network-theory.co.uk/docs/pytut/PythonScopesandNameSpaces.html or http://www.diveintopython.org/html_processing/locals_and_globals.html Hope that helps some. Mike From vania.smirk at gmail.com Mon Nov 12 11:48:03 2007 From: vania.smirk at gmail.com (VSmirk) Date: Mon, 12 Nov 2007 16:48:03 -0000 Subject: Looking for a good Python environment In-Reply-To: <7xtznslax6.fsf@ruckus.brouhaha.com> References: <1194389774.159051.55580@19g2000hsx.googlegroups.com> <1194434140.836932.10670@k79g2000hse.googlegroups.com> <7xbqa6f192.fsf@ruckus.brouhaha.com> <1194816672.311766.80070@v3g2000hsg.googlegroups.com> <7xtznslax6.fsf@ruckus.brouhaha.com> Message-ID: <1194886083.939689.86130@v65g2000hsc.googlegroups.com> On Nov 11, 4:39 pm, Paul Rubin wrote: > Russell Warren writes: > > Wing now has multi-threaded debugging. > > Cool, is it windows-only? I'm using Linux. > > > A quick look at the current state of SPE shows that it now has multi- > > threaded debugging via WinPDB (what I used to use for debugging thread > > issues). Interesting. Worth a look to see if it is integrated well. > > Same issue: this also sounds windows-specific. Thanks though. Wing is actually not windows-specific. They are Linux based as well, and I believe a number of users are also MacOSX users. The multi-threading debugging is a new feature with it's latest release, but I have heard of no platform-specific issues related to it. From adam at volition-inc.com Wed Nov 14 11:45:15 2007 From: adam at volition-inc.com (Adam Pletcher) Date: Wed, 14 Nov 2007 10:45:15 -0600 Subject: Creating Installer or Executable in Python In-Reply-To: <1195055620.779127.69760@v2g2000hsf.googlegroups.com> References: <1195050579.054554.145120@22g2000hsm.googlegroups.com><1195052952.190158.311220@22g2000hsm.googlegroups.com><1195053450.776273.206040@v2g2000hsf.googlegroups.com> <1195055620.779127.69760@v2g2000hsf.googlegroups.com> Message-ID: <893A44FF792E904A97B7515CE341914601C3ECE3@volimxs01.thqinc.com> I'd second InnoSetup for Windows installers, it's easy and powerful (and free). However, I don't think it can create actual .MSI files, only .EXE installers. I wish it would create .MSIs, since those are easier to automatically deploy for large user groups. I'm not aware of any free tools for building MSIs, but I'd love to find one. - Adam > -----Original Message----- > From: python-list-bounces+adam=volition-inc.com at python.org > [mailto:python-list-bounces+adam=volition-inc.com at python.org] On Behalf > Of sturlamolden > Sent: Wednesday, November 14, 2007 9:54 AM > To: python-list at python.org > Subject: Re: Creating Installer or Executable in Python > > On 14 Nov, 16:17, DanielJohnson wrote: > > > Thanks for telling about py2exe. > > Also note that you should build an MSI installer e.g. using InnoSetup > after applying py2exe. > > You could skip the py2exe part and only use InnoSetup to create an > MSI. Most likely your client will not care if the executable file is > called .py/.pyw/.pyc or .exe. Windows users are generally ignorant to > the contents of the Program Files folder. They will not understand > what is there and certainly not care what is there. Therefore, the > only thing that really matters is to make it easy to install and run > the program. > > That is: > > 1. Create an MSI that makes it easy to install the software (including > runtime and dependencies). > > 2. Use autorun if you ship a DVD or CD-ROM. The installer should start > automatically when the disc is placed in the player. > > 3. Make sure an icon on the "Start Menu" launches the program. > > > If you have done that, 99.9% of all clients will be happy. The latter > 0.01% is stupid enough to think it matters if the suffix of the > executable is called .exe or not. Never mind these morons, just ship > an .exe that does nothing except to spawn your Python program and > exit. > > > > Is there any utility that will help to make it as a .deb or .rpm file > > (for Linux)? > > There is a tool called cx_Freeze which is similar to py2exe, except > that it works on several platforms, including Linux. You will have to > build the .deb or .rpm using other tools afterwards. > > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list From arkanes at gmail.com Mon Nov 12 11:54:39 2007 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 12 Nov 2007 10:54:39 -0600 Subject: PyGilState_Ensure interrupts python critical sections In-Reply-To: <1194872182.400646.234820@d55g2000hsg.googlegroups.com> References: <1194872182.400646.234820@d55g2000hsg.googlegroups.com> Message-ID: <4866bea60711120854s721fde93p3000cb1a66c7ad2d@mail.gmail.com> On Nov 12, 2007 6:56 AM, wrote: > Hi, > > I have a native windows thread in a c python module which calls into > python code and adds an item to a data structure (a home-grown > circular buffer). At the same time my main python application is > removing items from this data structure. > > Unlike native python containers adding and removing items from the > circular buffer is not atomic. So I need to put access to it in a > critical section. Using threading.Lock will work for native python > threads competing for access. But when access is from a windows thread > this will not work. That is because my call to PyGilState_ensure will > preempt my native python thread ***even when it is inside the critical > section***. > > What is going on looks something like this (I think). > > > Py Python Windows Py threading.Lock > resource > Sched Thread Thread Code | | > | | | | | > |Go (GIL)# | | | | > | # | | | | > | # | | | | > | #...Doit.....|...........>| | | > | # | |. acquire...>| | > |<-PyGILState_Ensure--| | | | > | ... ... ... ... > |Stop # > |-------`| > | > |----Ensure rtns-----># PyObject_ | | > | : |CallMethod | | | > | : |.(Doit)...> |. acquire...>| DEADLOCK | > : > : > :.how does python thread tell > PyScheduler not to give away > Gil until we are done with > critical section?? > > So my question is how in python do I tell the scheduler not to prempt > the current python thread. Especially how to tell it not to give the > GIL to any calls to PyGILState_ensure until further notice (i.e. until > I am outside my critical section?? It sounds like a reasonable request > - surely this exists already but I can't find it. > It took me some time to understand the problem you were describing because you've got some terms backward - there's no Python scheduler, and calling PyGILState_ensure doesn't preempt anything. The Python interpreter *releases* the GIL every so often to allow other threads looking for it to run, but calling the python GIL functions has no effect on preemption. The problem is that the GIL is being released while your object lock is held, a second thread (started from C) acquires the GIL and then blocks on the object lock. What you seem to be seeing is that it blocking on the object lock is preventing it from releasing the GIL, which prevents the python thread from running and releasing the lock. This shouldn't happen - blocking on a lock releases the GIL, so the python thread should run, release the GIL, and eventually your C thread should be able to acquire both locks at the same time. Are you sure that you're correctly acquiring the GIL in your C code? The data flow you *should* be seeing should look something like this: GIL object lock (P=Python, C=C, *=released) ------------------- P P Python holds both locks * P Python releases the GIL, inside critical section C P C thread acquires the GIL and starts executing Python code * P C thread tries to acquire object lock and blocks, releasing the GIL P P Python thread re-acquires the GIL P * Python thread exits critical section and releases the object lock * * Python thread releases the GIL (can be in any order with next state) * C The C thread acquires the object lock and blocks on the GIL C C C thread acquires the GIL and continues execution. > One thing that may work (though the documentation does not > specifically say so) is using setcheckinterval() to set the check > interval to a very large value, acessing my shared structure and then > setting the check interval back to the previous value. Provided my > access to the shared structure takes less byte codes than what I set > checkinterval to I should be okay. However that would be very > dependant on the exact fine detail of how the check interval works and > may not be compatible with other Python releases > > Maybe someone familiar with the python source code would know for > sure? > > I am using Python 2.4.3 on windows XP. > > Thanks for any help/suggestions offered! > BR, > Billy. > > -- > http://mail.python.org/mailman/listinfo/python-list > From gagsl-py2 at yahoo.com.ar Wed Nov 14 03:10:16 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 14 Nov 2007 05:10:16 -0300 Subject: function call problem in class? References: <1195026717.343184.33900@i38g2000prf.googlegroups.com> Message-ID: En Wed, 14 Nov 2007 04:51:57 -0300, Davy escribi?: > I have write a simple class, I want the function two() to call private > function __one(), but there is an error : > NameError: global name '_simple__one' is not defined, how to work > around it > > class simple: > def __one(self): > print "Hello" > def two(self): > __one() > print "world" > > if __name__ == '__main__': > s = simple() > s.two() Note that your problem is not related to mangled names: replacing __one by one raises a similar exception. Remember that "self" is not implicit: you must use self.__one() "private" methods (and atributes in general) use a single underscore: _one. Double underscores __one are reserved for the (rare) cases when you want to ensure unique names (or name clashes are expected). -- Gabriel Genellina From horpner at yahoo.com Fri Nov 9 16:28:05 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Fri, 09 Nov 2007 21:28:05 GMT Subject: Binary search tree References: <1194642369.914779.152960@57g2000hsv.googlegroups.com> Message-ID: On 2007-11-09, Larry Bates wrote: > maxim.novak at gmail.com wrote: >> I have to get list of URLs one by one and to find the URLs >> that I have more than one time(can't be more than twice). >> >> I thought to put them into binary search tree, this way >> they'll be sorted and I'll be able to check if the URL already >> exist. >> >> Couldn't find any python library that implements trees. Is >> there some library of this kind in python? Or can I find it >> somewhere else? > > Put them into a set. You can check for existence (very fast) > and at the end it is easy to sort. The set is likely the way to go. Python's library support for binary search trees consists of the bisect module. -- Neil Cerutti Ask about our plans for owning your home --sign at mortgage company From bedouglas at earthlink.net Mon Nov 12 12:15:52 2007 From: bedouglas at earthlink.net (bruce) Date: Mon, 12 Nov 2007 09:15:52 -0800 Subject: python - an eggs... In-Reply-To: <5pqnfnFshiqkU1@mid.uni-berlin.de> Message-ID: <1c3601c8254f$ae8205e0$0301a8c0@tmesa.com> diez... i was being polite in thanking you for your input/thoughts... i actually had read what you'd posted, as i stated. in act, i did manage to get things working, thanks to you. but your comment about "ignoring pointers" indicates that you are a jerk, so... i now find your emails/tone offensive, and insulting. so, do me a favor (and yourself). if you see any msgs from me, please just add me to your spam folder/application. but again, i thank you for your help! thanks peace -----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 Diez B. Roggisch Sent: Monday, November 12, 2007 2:16 AM To: python-list at python.org Subject: RE: python - an eggs... bruce wrote: > Hi Diez... > > I've never used setuptools, (it's not on the box) and i don't have > easy_install tools installed... > > But in looking at your output, I have some questions... > -The 1st, I'm assuming that easy_install works with python2.4.3? > -The 2nd, In the output, is see the durus egg... with the "durus" path > being relative to the egg... are the actual durus files in that dir?? > -3rd question.. in searching the 'net, it appears that i have to download > setuptools in order to get easy_install. Am I missing something here, or > is this correct? > > Thanks for your pointers on this!! So far, you deliberately ignored the pointers. Otherwise, you wouldn't need to ask above questions. Diez -- http://mail.python.org/mailman/listinfo/python-list From steve at REMOVE-THIS-cybersource.com.au Sat Nov 10 23:32:44 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 11 Nov 2007 04:32:44 -0000 Subject: Populating a dictionary, fast References: Message-ID: <13jd1fc3u7co1db@corp.supernews.com> On Sat, 10 Nov 2007 17:18:37 -0800, Michael Bacarella wrote: > So, you think the Python's dict implementation degrades towards O(N) > performance when it's fed millions of 64-bit pseudo-random longs? No. Here's my sample file: $ wc -l id2name.txt 8191180 id2name.txt $ ls -lh id2name.txt -rw-rw-r-- 1 steve steve 371M 2007-11-11 14:00 id2name.txt And the results of reading it into a dict (code follows below): $ time ./slurp_dict.py Starting at Sun Nov 11 14:26:51 2007 Line 0 Line 1000000 Line 2000000 Line 3000000 Line 4000000 Line 5000000 Line 6000000 Line 7000000 Line 8000000 Items in dict: 8191180 Completed import at Sun Nov 11 14:29:31 2007 Starting to delete dict... Traceback (most recent call last): File "./slurp_dict.py", line 20, in del id2name KeyboardInterrupt real 35m52.334s user 1m17.663s sys 0m16.758s Notice that the dict is completely read into memory in just two and a half minutes. The script then tries to delete the dict, and 32 minutes later is still struggling. That's the point I got sick of waiting and interrupted the script. Conclusion: it's a memory issue, or maybe a garbage collection issue, not a problem with dicts. Here's my code for creating the key:value file in the first place: #!/usr/bin/python """Make a big file of 64-bit integer keys plus random values.""" bits64 = 2**64 import random template = '%d:This is a bunch of text...\n' fp = open('id2name.txt', 'w') for i in xrange(8191180): fp.write(template % random.randint(0, bits64)) fp.close() ### And here's my code for slurping it in to a dict: #!/usr/bin/python """Read a big file into a dict.""" import gc import time print "Starting at %s" % time.asctime() flag = gc.isenabled() gc.disable() id2name = {} for n, line in enumerate(open('id2name.txt', 'r')): if n % 1000000 == 0: # Give feedback. print "Line %d" % n id,name = line.strip().split(':', 1) id = long(id) id2name[id] = name print "Items in dict:", len(id2name) print "Completed import at %s" % time.asctime() print "Starting to delete dict..." del id2name print "Completed deletion at %s" % time.asctime() if flag: gc.enable() print "Finishing at %s" % time.asctime() ### So, what can you do? Given that I'm not willing to do any more unpaid experimentation for you, here are my suggestions, in no particular order: (1) Presumably you don't want to run your app with the garbage collector turned off. You might still want to play around with the gc module to see what you can learn. (2) More memory will help avoid paging. If you can't get more memory, try more virtual memory. It will still be slow, but at least the operating system doesn't have to try moving blocks around as much. (3) Are you sure you need all eight-million-plus items in the cache all at once? (4) There are lots of algorithms out there for dealing with data too big to fit into main memory. Do some research. (5) There is a data structure designed for dealing with tens of millions of records at once. It is called "a database". If you can't find a better algorithm, and refuse to use an existing RDBMS, I suspect you're going to end up inventing a primitive, inefficient, buggy database which is no faster than existing systems out there. -- Steven. From bdesth.quelquechose at free.quelquepart.fr Thu Nov 8 17:30:57 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 08 Nov 2007 23:30:57 +0100 Subject: Some "pythonic" suggestions for Python In-Reply-To: <5PGdnWmWZIdZ967anZ2dnUVZ_uuqnZ2d@cavtel.net> References: <5PGdnWmWZIdZ967anZ2dnUVZ_uuqnZ2d@cavtel.net> Message-ID: <47338e4c$0$30952$426a74cc@news.free.fr> Frank Samuelson a ?crit : > I love Python, and it is one of my 2 favorite > languages. I would suggest that Python steal some > aspects of the S language. > > ------------------------------------------------------- > 1. Currently in Python > def foo(x,y): ... > assigns the name foo to a function object. Is this pythonic? Yes. Python deliberately choosed to be a statement-based language. > Why not use the = operator like most other assignments? This dead horse has been beaten to hell and back. Note that as far as I'm concerned, I may like an expression-based Python-inspired language. But this is another story. > > ------------------------------------------------------- > 2. Allow sequences to be indices: > >>> s=["hello", 6, 33, "none"] > >>> x= [1,3] > >>> [ s[y] for y in x] # Current verbose version Verbose ??? > [6, 'none'] > >>> s[x] # Simpler, clearer, more productive > > To quote a poster at http://www.thescripts.com/forum/thread22741.html, > "While we are at it, I also don't understand why sequences can't be > used as indices. Why not, say, l[[2,3]] or l[(2, 3)]? Why a special > slice concept? slices are very powerful. >" Isn't that unpythonic? Not IMHO. But extending slices to support might not be totally stupid. Do you volunteer to write the PEP and the patch ? > -------------------------------------------------------- > 3. When I first started using python, I frequently used > map, because I didn't want to have to learn the > additional syntax of list comprehensions, which > appeared very nonstructured. > > # Is this readable? > b= [x+y for x in vec1 if x>0 for y in vec2 if y>x ] Yes. > Perhaps a list comprehension syntax more like the rest > of python. "for" could return a list given by continue > arguments: > > b= for x in vec1 : > if (x>0): continue # "returns" nothing > continue for y in vec2: > if (x>y): continue(x+y) Now *this* is a mess. And FWIW, you inverted the second test... > Note that my code would actually return a list of lists > rather than a single list like the list comprehension. > More structured syntax opens the door to having much > more complicated, yet still comprehensible (thus more > pythonic), list comprehensions. The Pythonic way to write "more complicated yet still comprehensible list comprehensions" is to not use list comprehensions. b = [] for x in vec1: if x > 0: for y in vec2: if y > x: b.append(x + y) Or if you really want a more functional approach: def do_stuff(vec1, vec2): for x in vec1: if x > 0: for y in vec2: if y > x: yield x + y b = list(do_stuff(vec1, vec2)) From aaron.watters at gmail.com Thu Nov 15 09:40:14 2007 From: aaron.watters at gmail.com (Aaron Watters) Date: Thu, 15 Nov 2007 06:40:14 -0800 (PST) Subject: Populating a dictionary, fast [SOLVED SOLVED] References: <818643.92017.qm@web915.biz.mail.mud.yahoo.com> <47374D00.7080500@gmail.com> <1195051438.889160.137120@50g2000hsm.googlegroups.com> <87fxz8kas6.fsf@mulj.homelinux.net> <13jn10p1r88u19f@corp.supernews.com> Message-ID: On Nov 14, 6:26 pm, Steven D'Aprano wrote: > >> Someone please summarize. > > > Yes, that would be good. > > On systems with multiple CPUs or 64-bit systems, or both, creating and/or > deleting a multi-megabyte dictionary in recent versions of Python (2.3, > 2.4, 2.5 at least) takes a LONG time, of the order of 30+ minutes, > compared to seconds if the system only has a single CPU. Turning garbage > collection off doesn't help. > > -- > Steven. criminy... Any root cause? patch? btw, I think I've seen this, but I think you need to get into 10s of megs or more before it becomes critical. Note: I know someone will say "don't scare off the newbies" but in my experience most Python programmers are highly experienced professionals who need to know this sort of thing. The bulk of the newbies are either off in VB land or struggling with java. -- Aaron Watters === http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=silly+walk From kyosohma at gmail.com Fri Nov 16 15:29:07 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Fri, 16 Nov 2007 12:29:07 -0800 (PST) Subject: What is python????? References: <7ab5b781-3c6c-4fb5-9be1-703d5e7e73a6@s12g2000prg.googlegroups.com> Message-ID: <959349ce-34ad-4d8e-aea0-b7bcbbc6112f@f13g2000hsa.googlegroups.com> On Nov 16, 1:16 pm, "mensana... at aol.com" wrote: > On Nov 16, 8:14 am, Thorsten Kampe wrote: > > > * Cope (Fri, 16 Nov 2007 06:09:31 -0800 (PST)) > > > > please tell me what is python.This group is so crowded. > > > A Python is dangerous snake[1]. This group here mainly consists of > > misguided snake worshippers. You'd better run before they come to your > > place... > > > Thorsten > > [1]http://en.wikipedia.org/wiki/Pythonidae > > Don't listen to him, he was joking. > > "Python" is short for "Monty Python's Flying Circus", > a British television comedy originally from 1969-1971 > (although movies, records, books and Broadway shows > continue to the present). Read the documention, > you'll see numerous references to spam (used in one > of their famous routines) and other Pythonisms. > > Anyway, all the posting in this group is comedy. > If you aren't getting it, run out and buy and study > all the DVD's. When you've reached the point where > you have The Argument Clinic dialogue memorized, > come back here and all this will make sense. > > Just be careful, some of the Python routines aren't > SUPPOSED to make sense ("cabbage crates over the how's > your father"), that's the joke. I still don't get it and I've been haunting this group for months... Mike From mwilson at the-wire.com Sun Nov 25 07:21:41 2007 From: mwilson at the-wire.com (Mel) Date: Sun, 25 Nov 2007 07:21:41 -0500 Subject: Recursive loading trouble for immutables References: Message-ID: rekkufa wrote: > I am currently building a system for serializing python objects > to a readable file-format, as well as creating python objects by > parsing the same format. It is more or less complete except for > a single issue I just cannot figure out by myself: How to load > data that specifies immutables that recursively reference > themselves. > > There are only a few solutions I can think of. > > One: While loading recursive objects, I always create empty versions > of objects (lists, dicts, classes) etc, and fill them in afterwards. > This works fine for loading recursive lists and such, but as > immutables are, well, immutable, this gets me nowhere with important > datatypes like tuples. > [ ... ] I can imagine a C function that might do it. If it were a list, of course, a Python function would be easy: def IdioList (contents, marker): t = [] t[:] = [x if x is not marker else t for x in contents] return t With tuples, by the time we have the tuple's identity it's too late, but I suspect that in C we could bend the rules enough. The marker would be a caller-supplied object with the property that the caller would never want to put it in a self-referencing sequence. I'll have to check this out today to see. Mel. From mal at egenix.com Fri Nov 9 18:26:47 2007 From: mal at egenix.com (M.-A. Lemburg) Date: Sat, 10 Nov 2007 00:26:47 +0100 Subject: Python Extension Building Network In-Reply-To: <1194623343.121618.65350@v3g2000hsg.googlegroups.com> References: <1194617297.075298.238880@i13g2000prf.googlegroups.com> <1194623343.121618.65350@v3g2000hsg.googlegroups.com> Message-ID: <4734ECB7.2030800@egenix.com> kyosohma at gmail.com wrote: > On Nov 9, 8:36 am, Tim Golden wrote: >> kyoso... at gmail.com wrote: >>> Hi, >>> I am trying to get a small group of volunteers together to create >>> Windows binaries for any Python extension developer that needs them, >>> much like the package/extension builders who volunteer their time to >>> create Linux RPMs. Are you aware of the repository that ActiveState created for its version of Python (ActivePython) ? It comes with a set of pre-compiled Python extensions (PPMs) and an easy to use installer. Perhaps getting ActiveState to open up the repo would be good idea - something like Ubuntu does with the universe repo. >>> The main thing I need are people willing to test the binaries to make >>> sure the extension is stable. This would require installing the binary >>> and probably downloading the source too to get the developer's test >>> code. I've been able to get some of the tests to run great while >>> others are pretty finicky and some extensions don't come with tests. >>> It would be nice to know which extensions are most in need of this >>> too. >>> While I can create the binaries on my own for a while, if I get too >>> many requests, there will be a backlog, so it would be nice to have >>> help with that too. I'm also looking for knowledgeable people to be >>> sounding boards (i.e. give advice). >>> Developers: all I would require is a request, a link to the source, >>> and a well-written setup.py file for a cross-platform extension. >>> You can find the few that I've already done here:http:// >>> www.pythonlibrary.org/python_modules.htm >>> I have also posted a way to create the binaries using the MinGW >>> compiler. I have VS2003 installed on my PC and MinGW is installed in a >>> VM, so I can compile the extensions both ways. >> Mike, this is great news. Whenever I have time > means it sincerely> I'll try to run through some of the modules >> you've compiled. >> >> As a slight aside, the main problem I've found when I've tried >> to build extensions (and I've been doing it recently with AVBin and >> Pyglet) is that Windows just doesn't have the build environment, the >> directory structures, the env vars and all that that a ./configure or >> even a python setup.py install sometimes expects. eg if I were to >> offer to build a MySQL extension (as someone who doesn't use MySQL >> and wouldn't have the source libs installed if I did) there would >> be a fair bit of pain to go through. You've obviously gone through >> that pain barrier for at least some of the extensions on the modules >> page. Was it tough? > > The hardest part was finding accurate information. Most people on the > user groups have been unhelpful or sarcastic. I had better luck > contacting developers directly who had already created Windows > binaries. They didn't mind giving me some pointers. Interesting: Python seems to be "growing up" in all kinds of ways ... > The directions for MinGW were usually only partially correct. So I > went through the two sets of directions I found (links on the site) > and mixed and matched until I got it right. > > There are no directions on how to use Visual Studio 2003 that I've > found, just some old free edition. those directions were incompatible > with VS2003. I'll post VS2003's correct usage eventually, but it's > basically just installing it and then using distutils. Getting VS2003 ready to compile Python extensions is really easy: 1. open a command shell 2. run vcvars32.bat 3. make sure the Python version you are targetting is on the PATH 4. "python setup.py bdist_wininst" or "python setup.py bdist_msi" 5. pick up the installer in the build\ directory. Note: bdist_msi is only available in Python 2.5 and later. You need VC6 if you want to compile extensions for Python 1.5-2.3 and VC7.1 for Python 2.4 and later. >> TJG >> >> (PS SendKeys link on this page is dead:http://www.pythonlibrary.org/automation.htm) > > I've noticed some of the stuff I thought I uploaded seems to have gone > MIA. I'll get that fixed tonight. Thanks for the bug report and offer > of help. > > Mike > -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Nov 09 2007) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From goon12 at gmail.com Thu Nov 8 12:01:22 2007 From: goon12 at gmail.com (Joe Riopel) Date: Thu, 8 Nov 2007 12:01:22 -0500 Subject: http question In-Reply-To: References: Message-ID: <6a2ccd190711080901m4e6323c4rb073c5546b2f1788@mail.gmail.com> On Nov 8, 2007 11:02 AM, steven depret wrote: > I get a lot of stuff in my output, but simply NOT the a=xx and the b = yy. > What the heck am I doing wrong ? What kind of stuff are you getting? Are you getting all the contents of the HTTP response and/or HTML? From MonkeeSage at gmail.com Tue Nov 27 17:31:05 2007 From: MonkeeSage at gmail.com (MonkeeSage) Date: Tue, 27 Nov 2007 14:31:05 -0800 (PST) Subject: How to Teach Python "Variables" References: <4749bb94$1@news.bezeqint.net> <4749c888$0$14869$426a74cc@news.free.fr> <4749cc7c$1@news.bezeqint.net> <7bbc1e48-8f33-4891-9226-c74b190156d0@a39g2000pre.googlegroups.com> Message-ID: On Nov 27, 2:49 pm, Aaron Watters wrote: > In practice there is too much to understand all at > once and in the beginning you have to say "don't worry about that > right now, consider it magic..." Of course they should > eventually understand it. Of course. But then it really depends on the teaching methodology, doesn't it? There is no reason (well, barring the restraints of the curriculum vitea), that one should learn topics so complex as to require "off-putting" the *real* meaning until later, when one could just as easily learn the basic concepts first. I guess it's a matter of preference; whether you build from the top down (ala Berkley) or the other way 'round. Regards, Jordan From larry.bates at websafe.com Wed Nov 14 18:34:35 2007 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 14 Nov 2007 17:34:35 -0600 Subject: Feeding data into MySQLdb LOAD DATA from Python In-Reply-To: <473b47c9$0$14082$742ec2ed@news.sonic.net> References: <473b47c9$0$14082$742ec2ed@news.sonic.net> Message-ID: John Nagle wrote: > Is it possible to feed data into a LOAD DATA command in MySQL without > writing out the data to a file? It's possible to do this using the > MySQL command line and a UNIX FIFO, but that's kind of clunky. > I have to load a few gigabytes of data, and using INSERT takes > a whole day for each update. > > And can this be done portably across UNIX and Windows? Thanks. > > John Nagle Where is the data coming from? Two suggestions: 1) There is a MySQL option to not commit every insert, sorry I can't remember what it is, but it REALLY speeds things up (especially if you have lots of keys). Or drop all the keys load, the data, and recreate the keys. Sounds odd, but it is a recommended method. 2) If data is coming from a file now, use LOAD DATA directly, don't go through Python. You may even find writing to file and then loading it is very fast. I recommend tab delimited as that seems to work well. -Larry From arkanes at gmail.com Fri Nov 9 10:19:08 2007 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 9 Nov 2007 09:19:08 -0600 Subject: Some "pythonic" suggestions for Python In-Reply-To: <9qGdnadjs6a76ananZ2dnUVZ_q2hnZ2d@cavtel.net> References: <5PGdnWmWZIdZ967anZ2dnUVZ_uuqnZ2d@cavtel.net> <47338e4c$0$30952$426a74cc@news.free.fr> <9qGdnadjs6a76ananZ2dnUVZ_q2hnZ2d@cavtel.net> Message-ID: <4866bea60711090719s6ed82ba7o369b7ae37d96c555@mail.gmail.com> On Nov 9, 2007 8:52 AM, Frank Samuelson wrote: > Bruno Desthuilliers wrote: > > > Yes. Python deliberately choosed to be a statement-based language. > > > >> Why not use the = operator like most other assignments? > > > > This dead horse has been beaten to hell and back. > > > > Note that as far as I'm concerned, I may like an expression-based > > Python-inspired language. But this is another story. > > My bad! In my rush I forgot that python requires the return statements. > You people think I'm trying to push lisp, which I am not. (Apparently > many people do, because you are rather skittish.) > In S the value of the last executed statement of a function is the > returned value of the function by default, if there is no return() function. > It is very convenient for writing really small functions. But skip that for now. > > foo = function(x,y) { # S language > if (x>2) return(x+y*2) > x+y > } > > foo = func(x,y): # My suggested python syntax (Improved!) > if x>2: return x+y*2 > return x+y > > # put the function object in the code wherever you want it. > bb= bar( a,b, func(x,y): x=x*2 ; b=4 ; return x*b+y ) > > It still is a statement language. The statement is an explicit > assignment using the "=" like most other assignments. "Def" and "lambda" > are silly. Assign names to function objects names the same way > you assign them to any other object. Call a duck a duck. > > While I'm at it, classes are objects too. Assign names to them the > same way you assign names to _any_ other object: "=" > > MyClass= class(inhereted): > attributes > functions > whatever > > x=MyClass() # an object of the above class. > > > > > The Pythonic way to write "more complicated yet still comprehensible > > list comprehensions" is to not use list comprehensions. > > > > b = [] > > for x in vec1: > > if x > 0: > > for y in vec2: > > if y > x: > > b.append(x + y) > > > > You have just demonstrated that list comprehensions are not really > necessary at all. So given the "one clear way of doing things", > shouldn't they be removed? My point is that if you are going to > have them, why make some new unstructured syntax for them? > There are at least 2 posts a month by someone who decides that they want to re-wire Python syntax. Usually it's because of some particular idiom they're used to in another language, in other cases it's because they've got some particular issue with "consistency". The ideas are *never* fully thought out or materialized, and they invariably invite scorn from the user community. The poster is almost always a Python beginner (I don't know if thats true in your case or not). Arbitrary changes to syntax are never going to fly. It's a lost cause. If you can't handle Python without your pet changes, fork it and write your own version and let the marketplace of ideas decide if its useful. From hniksic at xemacs.org Mon Nov 12 05:37:42 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Mon, 12 Nov 2007 11:37:42 +0100 Subject: Populating a dictionary, fast References: <7xhcjt49o7.fsf@ruckus.brouhaha.com> Message-ID: <87zlxj21hl.fsf@mulj.homelinux.net> Paul Rubin writes: > Michael Bacarella writes: >> If only it were so easy. > > I think I know what's going on, the dictionary updates are sending the > GC into quadratic behavior. Try turning off the GC: > > import gc > gc.disable() This is becoming an FAQ on this newsgroup, having come up first with lists and now with dictionaries. It can also be considered a serious implementation problem, since code like Michael's is expected to perform in (close to) linear time and in fact did so in previous versions of Python, and still does in Perl and other popular scripting languages. Neither introductory nor intermediate Python learning materials don't cover the need to disable GC when building large data structures. Maybe the default GC strategy should be rethought. From Shawn at Milochik.com Fri Nov 16 11:57:17 2007 From: Shawn at Milochik.com (Shawn Milochik) Date: Fri, 16 Nov 2007 11:57:17 -0500 Subject: What is python????? In-Reply-To: References: <7ab5b781-3c6c-4fb5-9be1-703d5e7e73a6@s12g2000prg.googlegroups.com> Message-ID: <2dc0c81b0711160857w96d05c3k6f9a8fa3de80e479@mail.gmail.com> However, the python is not poisonous, so it is also edible if you can kill one before it squeezes you to death. Despite this fact, it is not a major food source for group members, due to our great respect for the mighty python. Shawn On Nov 16, 2007 9:14 AM, Thorsten Kampe wrote: > * Cope (Fri, 16 Nov 2007 06:09:31 -0800 (PST)) > > please tell me what is python.This group is so crowded. > > A Python is dangerous snake[1]. This group here mainly consists of > misguided snake worshippers. You'd better run before they come to your > place... > > Thorsten > [1] http://en.wikipedia.org/wiki/Pythonidae > -- > http://mail.python.org/mailman/listinfo/python-list > -- Please read: http://milocast.com/2007/07/31/this-i-believe/ A good reason not to say "I don't know -- what do you want to do?" http://xkcd.org/330/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From sknop at gmx.net Tue Nov 27 11:12:46 2007 From: sknop at gmx.net (Sven Erik Knop) Date: Tue, 27 Nov 2007 16:12:46 +0000 Subject: Keyword passing to superclass written in C In-Reply-To: <4866bea60711270758tee44095kf8242e99c52068ba@mail.gmail.com> References: <474C11D2.6090206@perforce.co.uk> <4866bea60711270758tee44095kf8242e99c52068ba@mail.gmail.com> Message-ID: <474C41FE.3060300@gmx.net> Duh of course. Not sure what I had done in Python/Python. Now it works. Thanks a lot. Sven Erik Chris Mellon wrote: > On Nov 27, 2007 6:47 AM, Sven Erik Knop wrote: > >> Hi >> >> I am getting slightly frustrated and wonder if you can help me. >> >> Consider a Python class Foo implemented in C++. I have declared an >> initialization method like this >> >> static int >> Foo_init(P4Adapter *self, PyObject *args, PyObject *kwds) >> { >> >> } >> >> and I am subclassing Foo in Python, which works fine in principle, >> except for passing keywords. >> >> Here is the subclass: >> >> class Bar(Foo): >> def __init__(self, *args, **kwlist): >> Foo.__init__(self, args, kwlist) >> >> > > This passes the args tuple and the kw dict as 2 regular arguments. You > need to expand them in the second call if you want them to be passed > as args and kwargs - > Foo.__init__(self, *args, **kwargs) > -------------------------------------------------------------------------------- This email and any files transmitted with it are confidential and intended solely for the use of the individual or entity to whom they are addressed. If you have received this email in error please notify the system manager. Please note that any views or opinions presented in this email are solely those of the author and do not necessarily represent those of Perforce Software. Finally, the recipient should check this email and any attachments for the presence of viruses. Perforce Software accepts no liability for any damage caused by any virus transmitted by this email. Perforce Software UK Ltd is registered in England and Wales as company no. 3816019 at the following address: West Forest Gate, Wellington Road, Wokingham, RG40 2AQ, UK -------------------------------------------------------------------------------- -------------- next part -------------- An HTML attachment was scrubbed... URL: From "atavory\" at (none) Sun Nov 25 15:20:46 2007 From: "atavory\" at (none) (none) Date: Sun, 25 Nov 2007 22:20:46 +0200 Subject: How to Teach Python "Variables" In-Reply-To: References: <4749bb94$1@news.bezeqint.net> Message-ID: <4749d7ee$1@news.bezeqint.net> Aahz wrote: > In article <4749bb94$1 at news.bezeqint.net>, none <""atavory\"@(none)"> wrote: >> IIRC, I once saw an explanation how Python doesn't have "variables" in >> the sense that, say, C does, and instead has bindings from names to >> objects. Does anyone have a link? > > http://starship.python.net/crew/mwh/hacks/objectthink.html Thanks! From jeffrey at fro.man Mon Nov 12 10:41:20 2007 From: jeffrey at fro.man (Jeffrey Froman) Date: Mon, 12 Nov 2007 07:41:20 -0800 Subject: Populating a dictionary, fast References: <873avb1tvr.fsf@mulj.homelinux.net> Message-ID: <13jgt11n7gj9r37@corp.supernews.com> Hrvoje Niksic wrote: > Note that both machines are x86_64. ?Please try your test on a 32-bit > machine and report the results. ?I suspect performance won't degrade > there. This theory seems to be supported by my findings. Running the test on a 32-bit machine took 45 seconds, while the same test on a 64-bit machine is taking ... 30 minutes SO FAR (I'm getting impatient ;-) Both machines are running Python2.3.4 under CentOS-4, and both have 1G of RAM. The 64-bit machine has 2 processors weighing in at 2792.097 Mhz each, while the 32-bit machine has only 1 1194.857 Mhz processor. Jeffrey From sndive at gmail.com Mon Nov 5 12:59:37 2007 From: sndive at gmail.com (sndive at gmail.com) Date: Mon, 05 Nov 2007 17:59:37 -0000 Subject: instance as a sequence In-Reply-To: <1194284424.362046.294570@k79g2000hse.googlegroups.com> References: <1194283930.922568.258040@k79g2000hse.googlegroups.com> <1194284424.362046.294570@k79g2000hse.googlegroups.com> Message-ID: <1194285577.259839.131240@o3g2000hsb.googlegroups.com> On Nov 5, 9:40 am, Paul McGuire wrote: > On Nov 5, 11:32 am, snd... at gmail.com wrote: > > > suppose i want to > > make foo.childNodes[bar] available as foo[bar] > > (while still providing access to the printxml/printprettyxml() > > functions > > and other functionality of dom/minidom instance). > > > What is a good way to accomplish that? > > define __getitem__(self, index) method on foo's class, and have the > method return foo.childNodes[index]. > > If you don't have access to foo's class, then just do this: > > foo.__getitem__ = delegatingGetItemMethod > > and define delegatingGetItemMethod as described above. > could i plug it into the (exiting) xml.dom.minidom class rather than the instance? From steve at REMOVE-THIS-cybersource.com.au Fri Nov 23 05:54:02 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Fri, 23 Nov 2007 10:54:02 -0000 Subject: foldr function in Python References: <9bf5a2bb-eac7-4859-a5de-b1e84573c77a@t47g2000hsc.googlegroups.com> <0d8c76de-3510-4711-959a-34aad4a33acd@r60g2000hsc.googlegroups.com> Message-ID: <13kdcaar4048329@corp.supernews.com> On Fri, 23 Nov 2007 00:50:30 -0800, Ant wrote: > On Nov 22, 7:14 pm, oj wrote: >> On Nov 22, 3:02 pm, Ant wrote: > ... >> It's basically just one line to implement: >> >> foldr = lambda f, i: lambda s: reduce(f, s, i) >> >> It's just reduce with currying, I'm not sure it adds that much to what >> python already offers. > > Yes it's easy to implement. I did it in two steps because I think it's > easier to read. That's not the point I'm trying to make though. sum, any > and all are trivial to implement, yet they made it into the builtin > methods. > > The point of those functions I believe to be to promote easier to > understand idioms. Without them people will continue to write ad hoc > reduce based versions (which are less readable and less efficient). With > sum, any and all in the standard library, it becomes easier to write > readable code, and so people will be more likely to do so. Alas and alack, I believe that Guido has a distaste for all but the simplest functional idioms, and an irrational belief that anything using reduce() must be too complex to bear. reduce() is going away, not just from the built-ins but (I believe) from the standard library as well. The recommendation is that everybody wanting to reduce a sequence to a single item should roll their own instead, using an accumulator and a for loop instead. To my mind, getting rid of a standard functional tool like reduce in favour of rolling your own is as irrational as getting rid of for loops and telling people to roll their own from a while loop. I hope to be proven wrong. > The other benefit is to promote ways of thinking about code that you may > not have come across or thought about before. This is a common situation > when learning new languages - before learning python I would never have > thought to use map or reduce functions, and these are trivially easy to > implement. Not quite so trivial to implement as fast as the built-in reduce though. A slow pure-Python reduce() would be a good way to disqualify reduce() as a serious tool, and condemn it to be used only in toy examples. > So my point really is that foldr (perhaps renamed to make_reducer or > something) could create idioms that are more readable than using reduce > directly. I believe that foldr() is a standard term in functional programming, and no more difficult to learn than other programming terms like zip, partition, map, iterator or curry. -- Steven. From tali.wang at gmail.com Wed Nov 14 07:41:53 2007 From: tali.wang at gmail.com (Linan) Date: Wed, 14 Nov 2007 12:41:53 -0000 Subject: pygobject replacement? Message-ID: <1195044113.127419.224180@o3g2000hsb.googlegroups.com> Hi, I have a python library which is written years ago and heavily using pygobject in binding signal/events (No GUI stuffs involve). Now I have to use it in a totally different environment which doesnot allow to install glib, gtk and gobject. Surely I don't want to change the whole structure of handling signals/events. Is there any pure python pygobject replacement that I can switch to, and change only functions like emit? Any suggestion is appreciated. From MonkeeSage at gmail.com Fri Nov 23 22:07:54 2007 From: MonkeeSage at gmail.com (MonkeeSage) Date: Fri, 23 Nov 2007 19:07:54 -0800 (PST) Subject: eof References: <92a2c0c9-e6a1-4344-aeac-830940200f20@t47g2000hsc.googlegroups.com> <79i9k35vs76cqgqnino7dj3ql623us3euq@4ax.com> <6c04c760-6cf1-4715-9ec9-30f43ebaa01f@d27g2000prf.googlegroups.com> <062a9497-7626-440a-93eb-b897e6dec01f@p69g2000hsa.googlegroups.com> <5qlkf3F10drl7U1@mid.uni-berlin.de> <877ikauwyw.fsf@mulj.homelinux.net> <7d28423c-5efa-415b-b727-f36c54d47f6f@d21g2000prf.googlegroups.com> <5qpbeiF10ogq3U1@mid.individual.net> Message-ID: <4ea698f2-9abf-4990-8ca2-ea02fbf7abac@e1g2000hsh.googlegroups.com> On Nov 23, 6:56 pm, greg wrote: > By not providing an eof() function, C -- and Python -- make > it clear that testing for eof is not a passive operation. > It's always obvious what's going on, and it's much harder to > make mistakes like the above. err...C has feof() in stdio (see "man 3 ferror"). Regards, Jordan From horpner at yahoo.com Tue Nov 6 16:43:26 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Tue, 06 Nov 2007 21:43:26 GMT Subject: Populating huge data structures from disk References: <000001c820a1$78750ea0$695f2be0$@com> <4866bea60711061104i514838fcld9bbba1382a764a6@mail.gmail.com> Message-ID: <2e5Yi.39922$G23.25713@newsreading01.news.tds.net> On 2007-11-06, Michael Bacarella wrote: > And there's no solace in lists either: > > $ time python eat800.py > > real 4m2.796s > user 3m57.865s > sys 0m3.638s > > $ cat eat800.py > #!/usr/bin/python > > import struct > > d = [] > f = open('/dev/zero') > for i in xrange(100000000): > d.append(struct.unpack('L',f.read(8))[0]) > > > cPickle with protocol 2 has some promise but is more complicated because > arrays can't be pickled. In a perfect world I could do something like this > somewhere in the backroom: > > x = lengthy_number_crunching() > magic.save_mmap("/important-data") > > and in the application do... > > x = magic.mmap("/important-data") > magic.mlock("/important-data") > > and once the mlock finishes bringing important-data into RAM, at > the speed of your disk I/O subsystem, all accesses to x will be > hits against RAM. > > > Any thoughts? Disable the garbage collector, use a while loop and manual index instead of an iterator, preallocate your list, e.g., [None]*100000000, and hope they don't have blasters! -- Neil Cerutti From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Nov 22 05:56:32 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 22 Nov 2007 11:56:32 +0100 Subject: Research-oriented Python mailing list? In-Reply-To: References: Message-ID: <4745604f$0$32733$426a34cc@news.free.fr> Albert-jan Roskam a ?crit : > Hi again, > > One more Q: I was wondering if there exists a more > research-oriented Python listserv. This one is good > (or so it seems, I'm just a newbie!), but the topics > are very broad. Suggestions, anyone? google search on comp.lang.py may be what you're looking for From theller at ctypes.org Fri Nov 16 15:57:29 2007 From: theller at ctypes.org (Thomas Heller) Date: Fri, 16 Nov 2007 21:57:29 +0100 Subject: PIL question Message-ID: I'm trying to read an image with PIL, crop several subimages out of it, and try to combine the subimages again into a combined new one. This is a test script, later I want to only several single images into a combined one. I have to work with 16-bit color windows bitmaps in BMP format. My input image (input.bmp) IS a 16-color bmp. The cropped images that the script saves are saved in 8-bit/256-color format; they look correct. The combined image is also saved in 8-bit/256-color format, but it is all black - maybe the palette is missing? Anyway, I cannot use 256-color images. How do I save the images in 4-bit/16-color format? Thanks, Thomas Here is the code; I'm using Python 2.4 and PIL 1.5: import Image img = Image.open("input.bmp") w, h = img.size print img.size, img.mode newimg = Image.new("P", (16*30, 15)) x = 0 i = 1 while x < w: this = img.crop((x, 0, x+16, 15)) this.save("%02d.bmp" % i) newimg.paste(this, (x, 0, x+16, 15)) x += 16 i += 1 newimg.save("output.bmp") From paulgeeleher at gmail.com Tue Nov 20 12:36:56 2007 From: paulgeeleher at gmail.com (sophie_newbie) Date: Tue, 20 Nov 2007 09:36:56 -0800 (PST) Subject: Create thumbnail image (jpg/png) of PDF file using Python Message-ID: <104837c4-898a-4f67-98ab-37df8ff76f0f@e25g2000prg.googlegroups.com> Is there any way to do this directly within python? If not is there any other good way to achieve it? Thanks in advance for any help! From paul at boddie.org.uk Tue Nov 20 06:37:38 2007 From: paul at boddie.org.uk (Paul Boddie) Date: Tue, 20 Nov 2007 03:37:38 -0800 (PST) Subject: Joining open source python projects References: <1c2794d5-1b27-4b93-bbbe-8b354fd23003@e1g2000hsh.googlegroups.com> Message-ID: <4ec0e40d-ff40-4fab-8079-b2ae1a457155@l1g2000hsa.googlegroups.com> On 20 Nov, 02:07, "Giampaolo Rodola'" wrote: > > It thought it would be very nice having a place where developers could > submit "help requests" for their projects and let the users view them > and eventually join them if they want to. > > Does someone knows if such a service already exist or not? There's a page on the Wiki which isn't particularly well known: http://wiki.python.org/moin/VolunteerOpportunities Paul From mail at microcorp.co.za Sat Nov 24 00:58:02 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 24 Nov 2007 07:58:02 +0200 Subject: Clean way to get one's network IP address? References: <13k9cj8f6055naa@corp.supernews.com><181f0caa-1fff-4d28-a52f-f18310d800f1@o42g2000hsc.googlegroups.com><13keml9gqg2pe70@corp.supernews.com><13keq8d7ughika0@corp.supernews.com><13keqlp97lf4p7d@corp.supernews.com> <13ker5kc0aail96@corp.supernews.com> Message-ID: <011d01c82e5e$fa5d9660$03000080@hendrik> "Steven D'Aprano" wrote: > On Sat, 24 Nov 2007 00:05:13 +0000, Steven D'Aprano wrote: > > > ... you're absolutely write ... > > Okay, I now officially have no more credibility left. Time for me to get > a Hotmail email address and open a MySpace page and spend all my time > writing "OMG LOL LOL LOL did u c teh thing on Ausrtalia Idle lastnight > lol lol lol it was soooooo much omg". That is not too bad - for real time typing by a male. Chat room parlance is not the same as what is supposed to be considered posting... homophones ruul, OK? rotflmfao - Hendrik From martin at v.loewis.de Wed Nov 14 14:40:11 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 14 Nov 2007 20:40:11 +0100 Subject: Building python packages for the correct architecture on OSX 10.5 In-Reply-To: <1195061700.315152.61070@22g2000hsm.googlegroups.com> References: <1195061700.315152.61070@22g2000hsm.googlegroups.com> Message-ID: <473b4f1b$0$17353$9b622d9e@news.freenet.de> > This means the modules need to be compiles for at least both i386 and > x86_64 in my case. Building Python in 64-bit mode as a universal (fat) binary is not supported in Python 2.5, period. So any solution you come necessarily has to be a work-around. The only solution I can see is to make a plain, non-fat installation of Python in 64-bit mode, and then use that installation to build 64-bit extension modules. > def Extension(*args, **kwargs): > extra_args = ['-arch', 'ppc', '-arch', 'ppc64', > '-arch', 'i386', '-arch', 'x86_64 '] This cannot really work, for two reasons: a) even if your extension module becomes x86_64 with that mechanism, the Python interpreter itself (i.e. the Python framework) will be purely 32-bit code. So it should not link correctly. b) During configure, Python generates a pyconfig.h which has the computed sizes of data types (such as int, long, size_t). It only has a single such file, and the file is generated only during configure. Therefore, the data in it cannot work both for 32-bit and 64-bit architectures. When you compile for a 64-bit target using the 32-bit pyconfig.h, the code may work incorrectly (provided it makes use of the computed values somewhere) (*) (*) It is surprising that pyconfig.h actually works for both big-endian (ppc) and little-endian (i386) systems, even though it computes the endianness during configure only once. This is due to an OSX-specific hack in pyconfig.h, which hides the definition of the computed endianness value, and uses the value that the compiler provides as a macro instead. Regards, Martin From brown at esteem.com Thu Nov 15 14:39:35 2007 From: brown at esteem.com (Tom Brown) Date: Thu, 15 Nov 2007 11:39:35 -0800 Subject: google earth / pythoncom In-Reply-To: References: Message-ID: <1195155575.17417.226.camel@brown.esteem.com> On Thu, 2007-11-15 at 18:09 +0000, John Walsh wrote: > Hi, > > I'd like to write a python script to control Google Earth, > and I've read that Google Earth provides a COM api, and that > Python has a COM module 'pythoncom'. > I think what you are looking for you can download from here: http://sourceforge.net/project/showfiles.php?group_id=78018 The main page is here: http://starship.python.net/crew/mhammond/win32/Downloads.html > The Python script I want to run to control Google Earth will be > on the PC (WinXP) - so maybe I should install the 'normal/full' > Python on the PC too - if that can be done ? Have 2 Pythons installed > on one PC ? You can have two python installations on one pc. You have to use the full path to the interpreter to get the one you want. Or, the first one it finds in your path will be used. HTH, Tom From george.sakkis at gmail.com Sun Nov 25 00:55:55 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Sat, 24 Nov 2007 21:55:55 -0800 (PST) Subject: How can I create customized classes that have similar properties as 'str'? References: <67954d23-9400-4ac9-ba45-bec04fab51a2@s6g2000prc.googlegroups.com> <8eebf8fb-74cc-452a-bbef-2fe93556491f@i29g2000prf.googlegroups.com> <5qqeroF11703eU2@mid.individual.net> <1f2e037f-3667-4070-97cd-f4f6486c9d79@i12g2000prf.googlegroups.com> <13kh7mmeksulu51@corp.supernews.com> <13khh86h0g4nm86@corp.supernews.com> Message-ID: On Nov 24, 7:42 pm, Steven D'Aprano > > To the OP: yes, your use case is quite valid; the keyword you are > > looking for is "memoize". You can find around a dozen of recipes in the > > Cookbook and posted in this list; here's one starting point: > >http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/413717. > > This has nothing, absolutely NOTHING, to do with memoization. Memoization > trades off memory for time, allowing slow functions to return results > faster at the cost of using more memory. The OP wants to save memory, not > use more of it. If you bothered to click on that link you would learn that memoization can be used to save space too and matches OP's case exactly; even the identity tests work. Self-importance is bad enough by itself, even without the ignorance, but you seem to do great in both. George From koara at atlas.cz Tue Nov 20 11:31:50 2007 From: koara at atlas.cz (koara) Date: Tue, 20 Nov 2007 08:31:50 -0800 (PST) Subject: mmap disk performance Message-ID: <33540d51-3039-4046-80e6-2b1ddf92a26d@a28g2000hsc.googlegroups.com> Hello all, i am using the mmap module (python2.4) to access contents of a file. My question regards the relative performance of mmap.seek() vs mmap.tell(). I have a generator that returns stuff from the file, piece by piece. Since other things may happen to the mmap object in between consecutive next() calls (such as another iterator's next()), i have to store the file position before yield and restore it afterwards by means of tell() and seek(). Is this correct? When restoring, is there a penalty for mmap.seek(pos) where the file position is already at pos (i.e., nothing happened to the file position in between, a common scenario)? If there is, is it worth doing if mmap.tell() != pos: mmap.seek(pos) or such? Cheers! From ianb at colorstudy.com Thu Nov 22 14:53:05 2007 From: ianb at colorstudy.com (Ian Bicking) Date: Thu, 22 Nov 2007 11:53:05 -0800 (PST) Subject: Python web frameworks References: <226020ef-3955-43e8-b1f6-2ba9ba43d45e@c29g2000hsa.googlegroups.com> Message-ID: <51637ce0-1515-4ff0-88c7-f5ebb7166ff8@s12g2000prg.googlegroups.com> On Nov 20, 7:55 am, "Joe Riopel" wrote: > On Nov 20, 2007 8:46 AM, BartlebyScrivener wrote: > > > Django comes with its own little server so that you don't have > > to set up Apache on your desktop to play with it. > > Pylons too, it's good for development but using the bundled web server > is not recommended for production. It's actually fine to use it for production. There's two servers that are used commonly with Pylons, the one in Paste and the CherryPy server (it's a one-line configuration change to switch). The generally recommended production deployment is using one of these, with another HTTP server in front proxying requests back. There's lots of side-benefits to that particular setup, like hosting the Pylons app alongside static files, PHP, etc. But there's quite a few people who serve directly from Python (probably more often using the CherryPy server, though I don't really know the differences in a production situation). Anyway, mostly an aside for choosing a framework. Ian From paul at boddie.org.uk Thu Nov 1 19:38:13 2007 From: paul at boddie.org.uk (Paul Boddie) Date: Thu, 01 Nov 2007 16:38:13 -0700 Subject: XML document causes pickle to go into infinite recursion In-Reply-To: <1193952322.928502.11820@o3g2000hsb.googlegroups.com> References: <1193884983.837420.67460@o3g2000hsb.googlegroups.com> <47299959.2090302@web.de> <1193952322.928502.11820@o3g2000hsb.googlegroups.com> Message-ID: <1193960293.186722.174640@o3g2000hsb.googlegroups.com> On 1 Nov, 22:25, Orest Kozyar wrote: > > > I'm working on a CGI script that pulls XML data from a public database > > > Ah, I missed that bit on first read. Consider using something different than > > CGI here if you want to do caching. FCGI would allow you to do in-memory > > caching, for example, as would mod_python and a lot of other solutions. > > What I'm aiming for is sort of a "permanent" disk cache/mirror that > adds records as needed. The main issue is that the database (PubMed) > requests that we limit requests to once every three seconds. Drifting off-topic slightly, it is possible to download archives of PubMed, but you'll need a lot of disk space; you probably know this already. Putting the data into something rapidly searchable can demand even more space, depending on what you use and what you want to be able to search for. I guess it depends on whether you're retrieving relatively few documents across the whole of PubMed or whether your searches are concentrated in particular sections of the whole archive. Paul From ivoras at __fer.hr__ Sat Nov 3 21:29:34 2007 From: ivoras at __fer.hr__ (Ivan Voras) Date: Sun, 04 Nov 2007 02:29:34 +0100 Subject: Poor python and/or Zope performance on Sparc In-Reply-To: <1194096917.333728.51570@22g2000hsm.googlegroups.com> References: <1194096917.333728.51570@22g2000hsm.googlegroups.com> Message-ID: joa2212 wrote: > We have a Sun T1000 with 8 cores and 8 GB of RAM. First, I installed > Solaris 10 because I know this OS better than Debian Linux. Result: > poor Performance. After that I decided to migrate to debian: Do you know the architecture of this machine? It's extremely streamlined for data throughput (IO) at the expense of computational ability. In particular: - it runs at a relatively small clock speed (1 GHz - 1.4 GHz) - it's terrible for floating-point calculations because there is only one FPU shared by all 32 logical processors While it will be screamingly fast for serving static content, and pretty decent for light database jobs, this not an optimal platform for dynamic web applications, especially for Python since the language's so dynamic and it doesn't support SMP. Since it's so optimized for a certain purpose, you can freely consider it a special-purpose machine, rather than a general-purpose one. Even if you manage to get Zope to spawn parallel request handlers (probably via something like fastcgi), if the web application is CPU-intensive you won't be happy with its performance (for CPU-intensive tasks you probably don't want to spawn more than 8 handlers, since that's the number of physical cores in the CPU). -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 258 bytes Desc: OpenPGP digital signature URL: From sheep.in.herd at green.meadow Fri Nov 2 02:45:09 2007 From: sheep.in.herd at green.meadow (Ton van Vliet) Date: Fri, 02 Nov 2007 07:45:09 +0100 Subject: python at command prompt References: <1193933820.086265.19100@57g2000hsv.googlegroups.com> Message-ID: On Thu, 01 Nov 2007 09:17:00 -0700, c3950ig at hotmail.com wrote: >Hi, >I am python newbie and the command prompt is having an issue with >python. I installed python 2.4.4 onto my windows machine, opened a >command prompt window, and typed python to start the interactive mode. >Got the following error. > >D:\>python >'python' is not recognized as an internal or external command, >operable program or batch file. > >The following programs work fine >IDLE (Python GUI) >Python (command line) >PythonWin > >For some strange reason, python is not recognized at the command >prompt. >Does anyone have any ideas as to why this is happening? >thanks, There's could also be an issue with entering 'python' at the command line, and not 'python.exe'. Once the PATH is setup correctly, try to enter 'python.exe', and check whether that works. IMHO, to get any 'program-name' (without the .exe extension) to work, one needs to: 1. register the executable with windows (doesn't work for python) or 2. make sure the the PATHEXT environment variable is set correctly, and includes the .EXE extension (on my w2k system it looks like: .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH) -- Ton From rich at worldsinfinite.com Mon Nov 5 09:25:06 2007 From: rich at worldsinfinite.com (Rich Harkins) Date: Mon, 05 Nov 2007 09:25:06 -0500 Subject: Descriptors and side effects In-Reply-To: <1194248333.382804.260390@y42g2000hsy.googlegroups.com> References: <1194248333.382804.260390@y42g2000hsy.googlegroups.com> Message-ID: <472F27C2.9060607@worldsinfinite.com> mrkafk at gmail.com wrote: > Hello everyone, > > I'm trying to do seemingly trivial thing with descriptors: have > another attribute updated on dot access in object defined using > descriptors. [snip] > A setter function should have updated self.l just like it updated > self.s: > > def __set__(self, obj, val): > self.s=val > self.l=len(val) > print "setting value:", self.s, "length:", self.l > > Yet it didn't happen. > [snip] I noticed that Python will block all attribute overrides (either via __dict__ through setattr) if the property has a __set__ method. The standard property has this method and there is no way that I can find to defeat it. So, here is what I use: class ConstProperty(object): """ Provides a property that keeps its return value. The function will only be called on the first access. After that the same value can be used over and over again with no function call penalty. If the cached value needs to be cleared, simply del the attribute. >>> class MyClass(object): ... def __init__(self, x): ... self.x = x ... @ConstProperty ... def y(self): ... print "HERE" ... return self.x ** 2 ... >>> obj = MyClass(5) >>> obj.y HERE 25 >>> obj.y 25 """ def __init__(self, fn): self.fn = fn def __get__(self, target, cls=None): if target is None: return self.fn # Helps pydoc else: obj = self.fn(target) setattr(target, self.fn.__name__, obj) return obj This is a little different than what you originally posted, but hopefully it is close enough to be helpful. Cheers! Rich From bborcic at gmail.com Thu Nov 22 08:22:54 2007 From: bborcic at gmail.com (Boris Borcic) Date: Thu, 22 Nov 2007 14:22:54 +0100 Subject: eof In-Reply-To: References: <92a2c0c9-e6a1-4344-aeac-830940200f20@t47g2000hsc.googlegroups.com> <79i9k35vs76cqgqnino7dj3ql623us3euq@4ax.com> <6c04c760-6cf1-4715-9ec9-30f43ebaa01f@d27g2000prf.googlegroups.com> Message-ID: > def chunked(chunksize,f) : > from itertools import count,groupby > counter=count(chunksize).next > return groupby(f,lambda _ : counter()/chunksize) And more to the point, no "yield" for Alexy to mock :) From keeftm at gmail.com Fri Nov 2 18:06:50 2007 From: keeftm at gmail.com (KeefTM) Date: Fri, 02 Nov 2007 22:06:50 -0000 Subject: Sub-sort after sort In-Reply-To: <1194039935.380959.254770@i13g2000prf.googlegroups.com> References: <1194039935.380959.254770@i13g2000prf.googlegroups.com> Message-ID: <1194041210.446273.188330@v23g2000prn.googlegroups.com> On Nov 2, 2:45 pm, kee... at gmail.com wrote: > Hello, I have been sorting a list of dicts using the following > function: > > result_rs = sorted(unsort_rs, key=itemgetter(orderby)) > > and this works fine. Now I am looking to perform a subsort as well. > For example, I have this: > > test = [{'name': 'John Smith', 'location': 'CA',},{'name': 'John > Smith', 'location': 'AZ',},] > > I would want to sort by name first, then sub sort by location. Any > ideas? Thanks! Well, I found a way to do it. Just create a new key and value that is a combination of two other values, like this: test = [{'name': 'John Smith', 'location': 'AZ','sort':'John SmithAZ'}, {'name': 'John > Smith', 'location': 'CA', 'sort':'John SmithCA'},] Not pretty in the slightest, but it works. From jcd at sdf.lonestar.org Tue Nov 20 15:08:55 2007 From: jcd at sdf.lonestar.org (J. Clifford Dyer) Date: Tue, 20 Nov 2007 15:08:55 -0500 Subject: Python strings question (vertical stack) In-Reply-To: <7LG0j.1782$yb2.750@newsfe14.phx> References: <1c156ae2-c7ff-45b4-839b-ac54e3d48426@v4g2000hsf.googlegroups.com> <7LG0j.1782$yb2.750@newsfe14.phx> Message-ID: <20071120200855.GG14956@sdf.lonestar.org> On Tue, Nov 20, 2007 at 11:40:59AM -0800, Farshid Lashkari wrote regarding Re: Python strings question (vertical stack): > > dmitrey wrote: > > Hi all, > > I have some strings, let it be string1, string2, string3. > > > > So how could String= > > """ > > string1 > > string2 > > string3 > > """ > > > > be obtained? > > > > Thank you in advance, D. > > If you just want the to add newlines between the strings then you can do > the following: > > String = '\\n'.join([string1,string2,string3]) > > -Farshid > -- > http://mail.python.org/mailman/listinfo/python-list I think you mean '\n'.join([string1,string2,string3]) You actually do want the \ to do its thing in this case. Cheers, Cliff From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sat Nov 3 07:29:58 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sat, 03 Nov 2007 12:29:58 +0100 Subject: py2exe (or other exe builder) on Vista system for Vista/XP install targets. References: <1193832521.937425.94860@o3g2000hsb.googlegroups.com> <5ordsfFo0djvU1@mid.individual.net> <1193854289.186421.100660@57g2000hsv.googlegroups.com> Message-ID: <5p34dnFp5d76U1@mid.individual.net> Michael wrote: > Bj?rn, what library files end up being in your dist directory for > that project? Would you mind posting a copy of the output of dir? Okay, sorry for the delay. Here the output of py2exe is, for directory contents see below. | The following modules appear to be missing | ['FCNTL', 'OpenSSL', 'email.Generator', 'email.Iterators', | 'email.Utils', 'pywintypes', 'resource', 'win32api', 'win32con', | 'win32event', 'win32file', 'win32pipe', 'win32process', | 'win32security', 'wx.Timer'] | | *** binary dependencies *** | Your executable(s) also depend on these dlls which are not | included, you may or may not need to distribute them. | | Make sure you have the license if you distribute any of them, and | make sure you don't distribute files belonging to the operating | system. | | OLEAUT32.dll - C:\windows\system32\OLEAUT32.dll | USER32.dll - C:\windows\system32\USER32.dll | SHELL32.dll - C:\windows\system32\SHELL32.dll | ole32.dll - C:\windows\system32\ole32.dll | comdlg32.dll - C:\windows\system32\comdlg32.dll | WSOCK32.dll - C:\windows\system32\WSOCK32.dll | COMCTL32.dll - C:\windows\system32\COMCTL32.dll | ADVAPI32.dll - C:\windows\system32\ADVAPI32.dll | GDI32.dll - C:\windows\system32\GDI32.dll | WS2_32.dll - C:\windows\system32\WS2_32.dll | MSVCP71.dll - C:\Program Files\Python25\lib\site-packages\ | wx-2.8-msw-unicode\wx\MSVCP71.dll | WINMM.dll - C:\windows\system32\WINMM.dll | KERNEL32.dll - C:\windows\system32\KERNEL32.dll | gdiplus.dll - C:\Program Files\Python25\lib\site-packages\ | wx-2.8-msw-unicode\wx\gdiplus.dll | RPCRT4.dll - C:\windows\system32\RPCRT4.dll Output of dir in the dist directory follows: | 01.11.2007 20:51 . | 01.11.2007 20:51 .. | 18.04.2007 07:51 77.824 bz2.pyd | 01.11.2007 20:51 4.874.503 library.zip | 29.06.2007 20:19 348.160 MSVCR71.dll | 18.04.2007 07:51 135.168 pyexpat.pyd | 18.04.2007 07:51 2.113.536 python25.dll | 18.04.2007 07:51 7.680 select.pyd | 18.04.2007 07:51 475.136 unicodedata.pyd | 18.04.2007 07:51 4.608 w9xpopen.exe | 07.08.2007 20:47 135.168 wxbase28uh_net_vc.dll | 07.08.2007 20:47 1.327.104 wxbase28uh_vc.dll | 07.08.2007 20:50 708.608 wxmsw28uh_adv_vc.dll | 07.08.2007 20:50 3.158.016 wxmsw28uh_core_vc.dll | 07.08.2007 20:51 479.232 wxmsw28uh_html_vc.dll | 07.08.2007 21:12 909.312 _controls_.pyd | 07.08.2007 21:09 950.272 _core_.pyd | 07.08.2007 21:11 716.800 _gdi_.pyd | 18.04.2007 07:52 323.584 _hashlib.pyd | 07.08.2007 21:14 659.456 _misc_.pyd | 18.04.2007 07:52 53.248 _socket.pyd | 18.04.2007 07:52 655.360 _ssl.pyd | 07.08.2007 21:11 647.168 _windows_.pyd | 08.01.2007 15:49 9.216 _zope_interface_ | coptimizations.pyd (my files, an exe and a data file, snipped) Regards & HTH, Bj?rn -- BOFH excuse #417: Computer room being moved. Our systems are down for the weekend. From donn.ingle at gmail.com Thu Nov 8 04:34:50 2007 From: donn.ingle at gmail.com (Donn Ingle) Date: Thu, 08 Nov 2007 11:34:50 +0200 Subject: easy 3D graphics for rendering geometry? References: <1194501211.730458.44000@o80g2000hse.googlegroups.com> <1194513397.915521.124900@57g2000hsv.googlegroups.com> Message-ID: > I recommend taking a look at Blender 3D: http://www.blender.org/ Oh yeah, Blender is THE way to go. It's fantastic. \d From mtobis at gmail.com Thu Nov 22 11:04:07 2007 From: mtobis at gmail.com (Michael Tobis) Date: Thu, 22 Nov 2007 08:04:07 -0800 (PST) Subject: Research-oriented Python mailing list? References: <14092.39489.qm@web32708.mail.mud.yahoo.com> Message-ID: <1367b065-0aa0-4bf1-a52d-98c0a984e9c6@e4g2000hsg.googlegroups.com> Perhaps what you are looking for is here: http://www.scipy.org/Mailing_Lists mt From eeskoe at northwestern.edu Mon Nov 5 16:10:47 2007 From: eeskoe at northwestern.edu (Erika Skoe) Date: Mon, 05 Nov 2007 15:10:47 -0600 Subject: dictionary viewer Message-ID: <472F86D7.70803@northwestern.edu> From kay.schluehr at gmx.net Tue Nov 13 12:38:56 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Tue, 13 Nov 2007 09:38:56 -0800 Subject: AOP and pep 246 In-Reply-To: <1194963461.270262.90680@d55g2000hsg.googlegroups.com> References: <1193935586.110516.105630@50g2000hsm.googlegroups.com> <1194963461.270262.90680@d55g2000hsg.googlegroups.com> Message-ID: <1194975536.386522.171920@57g2000hsv.googlegroups.com> On 13 Nov., 15:17, Steve wrote: > > AOP was a research that gone nowhere - at least not in its orginal > > AspectJ form ... > > I think it might be worth pointing out, though, that there is still > significant interest in AOP in the Java community, in the form or > interest in the Spring Framework. See, for instance:http://www.onjava.com/pub/a/onjava/2004/07/14/springaop.html > > This article was written in 2004. It has taken some time for > awareness of Spring to penetrate the Java community, but it appears to > be happening in a serious way. Yes, I knew about Spring AOP but didn't keep much attention. Is AOP used a lot in the Spring context or is it just a fancy, experimental feature which was just cool to implement at some time? > -- Thank-god-I-don't-have-to-learn-all-this-Java-superstructure-stuff- > ly yours, As I understand Spring it was part of a liberation wave from J2EE in the Java community: return to POJOs and dependency injection as the main composition technique. Spring is probably not that bad. > Steve Ferg From jarausch at skynet.be Wed Nov 21 15:34:42 2007 From: jarausch at skynet.be (Helmut Jarausch) Date: Wed, 21 Nov 2007 21:34:42 +0100 Subject: sendmail a long message Message-ID: <47449662$0$29249$ba620e4c@news.skynet.be> Hi, to send a possibly long email I have seen a solution which does os.popen to an external sendmail program and then writes the message into that pipe. I wonder if it possible to use smtplib.SMTP.sendmail but this requires building the complete body as one long string in memory before calling this. Is there an alternative solution, e.g. where smtplib.SMTP.sendmail calls a generator. Many thanks for a hint, Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From _n05pam_ at arcor.de Sun Nov 4 09:55:50 2007 From: _n05pam_ at arcor.de (tech user) Date: Mon, 5 Nov 2007 01:55:50 +1100 (EST) Subject: modify a file Message-ID: <466570.15141.qm@web15607.mail.cnb.yahoo.com> Hello, I have a file which is large about 3.5G. I need to modify some lines in it,but I don't like to create another file for the result. How can i do it? thanks. National Bingo Night. Play along for the chance to win $10,000 every week. Download your gamecard now at Yahoo!7 TV. http://au.blogs.yahoo.com/national-bingo-night/ From ptmcg at austin.rr.com Mon Nov 26 11:51:16 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 26 Nov 2007 08:51:16 -0800 (PST) Subject: How to write Regular Expression for recursive matching? References: Message-ID: On Nov 26, 10:40 am, lisong wrote: > Hi All, > > I have problem to split a string like this: > > 'abc.defg.hij.klmnop' > > and I want to get all substrings with only one '.' in mid. so the > output I expect is : > > 'abc.defg', 'defg.hij', 'hij.klmnop' > > a simple regular expression '\w+.\w' will only return: > 'abc.defg', 'hij.klmnop' > > is there a way to get 'defg.hij' using regular expression? > > Thanks, Why are you using regular expressions? Use the split method defined for strings: >>> 'abc.defg.hij.klmnop'.split('.') ['abc', 'defg', 'hij', 'klmnop'] -- Paul From bhell at spamfence.net Thu Nov 29 03:51:11 2007 From: bhell at spamfence.net (Benjamin Hell) Date: Thu, 29 Nov 2007 09:51:11 +0100 Subject: Determine whether program was started by clicking icon or command line Message-ID: <5r7cs0F136db0U1@mid.individual.net> Hi! I wonder whether there might be a way to find out how a Python program was started (in my case in Windows): By double clicking the file or by calling it on the "DOS" command line prompt. Background: I would like to have the program run in an "interactive mode" if double clicked, and silently in a "batch mode" when started otherwise. Any hints? Thank you! Ben From paul.nospam at rudin.co.uk Wed Nov 21 06:57:58 2007 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Wed, 21 Nov 2007 11:57:58 +0000 Subject: logging and propagation References: <7eef67e0-36a7-48b6-9137-0b10ea37ac3c@f3g2000hsg.googlegroups.com> <87zlx7om3k.fsf@rudin.co.uk> Message-ID: <87r6ijolo9.fsf@rudin.co.uk> oj writes: > On Nov 21, 11:48 am, Paul Rudin wrote: >> Loggers have a "propagate" attribute. If you set this to False in the >> child then you should get what you want I think. > > No, because I want message to propagate usually. There are only > specific instances when I don't want it to propagate. Can't you set propagate to False during those specific instances and 1 the rest of the time? From roy at panix.com Wed Nov 21 11:39:57 2007 From: roy at panix.com (Roy Smith) Date: Wed, 21 Nov 2007 11:39:57 -0500 Subject: Clean way to get one's network IP address? References: Message-ID: Gilles Ganault wrote: > I know about socket.gethostbyname, but this relies on what's in > /etc/hosts, and I'd rather have a more independent solution. The system I'm currently working on uses exactly this strategy -- we get the hostname then do a name lookup on it. We've gone around and around on this, and ended up with that being the best solution. For us, anyway. Your mileage may vary. As others have pointed out, it's entirely possible to have multiple IP addresses. In addition, your IP address(es) can change as connections come up and down, especially in a mobile environment (WiFi, VPN, cellular, etc). There is no single correct answer here. Oh, BTW, did you mean IPv4 or IPv6? From bj_666 at gmx.net Thu Nov 22 01:47:33 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 22 Nov 2007 06:47:33 GMT Subject: why it is invalid syntax? References: Message-ID: <5qkn05F10hq6fU1@mid.uni-berlin.de> On Thu, 22 Nov 2007 00:00:16 -0600, alf wrote: > I wonder why it is an invalid syntax: > > > >>> if 1: if 1: if 1: print 1 > File "", line 1 > if 1: if 1: if 1: print 1 > > or > > >>> if 1: for i in range(10): print i > File "", line 1 > if 1: for i in range(10): print i > > I would expect one could nest : It's quite unreadable and if this would be allowed you would have to introduce a special rule to forbid ``else``, ``except`` and ``finally`` because it can lead to ambiguities. To which ``if`` does the ``else`` belong to here? :: if 1: print 1 if: 1 print 1 else: print 1 Ciao, Marc 'BlackJack' Rintsch From bj_666 at gmx.net Sat Nov 24 11:50:39 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 24 Nov 2007 16:50:39 GMT Subject: the annoying, verbose self References: <3c954a31-9fb9-4c0f-b784-cef9ee057ca6@g30g2000hsb.googlegroups.com> <4068d518-cba9-4eac-bd91-11f676c17b3d@w34g2000hsg.googlegroups.com> <220d59b8-bcce-4496-beab-0976a5a83f80@g21g2000hsh.googlegroups.com> <5qqbf9F10jrh5U3@mid.uni-berlin.de> <3c561098-9229-4434-9e3b-c0aef8a4ddcd@n20g2000hsh.googlegroups.com> <5qqoguF10jrh5U5@mid.uni-berlin.de> Message-ID: <5qr32vF10jrh5U7@mid.uni-berlin.de> On Sat, 24 Nov 2007 08:27:56 -0800, samwyse wrote: > On Nov 24, 7:50 am, Marc 'BlackJack' Rintsch wrote: >> On Sat, 24 Nov 2007 02:54:27 -0800, samwyse wrote: >> > On Nov 24, 4:07 am, Marc 'BlackJack' Rintsch wrote: >> >> On Sat, 24 Nov 2007 01:55:38 -0800, samwyse wrote: >> >> > I've had the same thought, along with another. You see, on of my pet >> >> > peeves about all OO languages that that when creating new code, I >> >> > generally begin by writing something like this: >> >> >> > cat = 'felix' >> >> > dog = 'rover' >> >> > def example(): >> >> > global cat, dog # not always required, but frequently needed >> >> > return ', '.join((cat, dog)) >> >> >> Ouch that's bad design IMHO. The need to use ``global`` is a design >> >> smell, if needed *frequently* it starts to stink. >> >> > I'm not sure what you mean. In the example that I gave, the 'global' >> > statement isn't needed. However, here's a different example: >> >> I mean that global names that are (re)bound from within functions couple >> these functions in a non-obvious way and make the code and data flow harder >> to follow and understand. Also it makes refactoring and testing more >> difficult because of the dependencies. > > The whole point of this sub-thread is the difficulty of turning global > vars and functions into class vars and functions, and that is > something that is usually done precisely because the code and data > flow has become harder to follow and understand. Then don't use "global variables". If you don't put anything except constants, classes and functions in the module's namespace there's no problem "lifting" them into a class later. Ciao, Marc 'BlackJack' Rintsch From robert.kern at gmail.com Thu Nov 29 13:58:47 2007 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 29 Nov 2007 12:58:47 -0600 Subject: Control mouse position and clicking In-Reply-To: <4f209559-4454-4f8a-8ba3-18cbb50db094@b40g2000prf.googlegroups.com> References: <4f209559-4454-4f8a-8ba3-18cbb50db094@b40g2000prf.googlegroups.com> Message-ID: Glich wrote: > hi, how can I, control mouse position and clicking from python? > > I want to interact with a flash application inside firefox. thanks. > > ps: I am not using windows. I've use the external program xte with some success if you don't send it too many events too quickly. I start it using subprocess and feed it commands. On Ubuntu sudo apt-get install xautomation It uses the XTest extension for X11 to send mouse events to the system. One could probably easily wrap the xlib API for it using ctypes so you wouldn't have to bother with an external program. -- 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 tdp1001 at gmail.com Fri Nov 9 06:24:21 2007 From: tdp1001 at gmail.com (Tom Potter) Date: Fri, 09 Nov 2007 03:24:21 -0800 Subject: >>>> 911 operation by evil JEWS and Mossad <<<< In-Reply-To: <1194521283.443284.15070@k35g2000prh.googlegroups.com> References: <1194448081.967583.96940@k79g2000hse.googlegroups.com> <1194521283.443284.15070@k35g2000prh.googlegroups.com> Message-ID: <1194607461.539765.94220@y27g2000pre.googlegroups.com> On Nov 8, 7:28 pm, philipp neulist wrote: > On Nov 7, 4:08 pm, zionist.j... at gmail.com wrote:> 911 carried out by evil jews and mossadhttp://www.guba.com/watch/2000991770 > > >911 truckload of Explosives on the George WashingtonBridgehttp://www.youtube.com/watch?v=J520P-MD9a0 > > [...] > > I reported the first post in this thread (on Google groups) as abuse > as its content is "false and defamatory". In addition to that, it has > nothing to do with TeX. > > => Double reason to blaim the author! > > Please ignore threads like those in future and just report it! > > PN Thanks for calling my attention to this Web Site philipp, As my Pappy used to say: "A stuck pig squeals.", and when I see a post by a "squealing pig", I try to find out what made him squeal, as this saves me a lot of time in getting to the heart of issues. As one can view and easily download many interesting videos from the site that one cannot find elsewhere, I suggest that folks interested in interesting videos should visit the site. The following URL lists several interesting videos. http://www.guba.com/general/search?query=israel&set=5&x=17&y=9 Thanks again philipp! Your pal, -- Tom Potter http://home.earthlink.net/~tdp http://notsocrazyideas.blogspot.com/ From oruccim at gmail.com Sat Nov 10 16:51:48 2007 From: oruccim at gmail.com (oruccim at gmail.com) Date: Sat, 10 Nov 2007 21:51:48 -0000 Subject: security code whit python In-Reply-To: <1194731231.015260.58720@50g2000hsm.googlegroups.com> References: <1194710640.804970.28150@19g2000hsx.googlegroups.com> <1194731231.015260.58720@50g2000hsm.googlegroups.com> Message-ID: <1194731508.910573.262530@d55g2000hsg.googlegroups.com> have you got any example?pls :S From XX.XmcX at XX.XmclaveauX.com Thu Nov 22 06:46:07 2007 From: XX.XmcX at XX.XmclaveauX.com (MC) Date: Thu, 22 Nov 2007 12:46:07 +0100 Subject: Python Windows installation References: Message-ID: Hi! > 1.5.1 Sure? 1.5.1? For Python 2.5, look ActiveState. Their distrib have silent option. -- @-salutations Michel Claveau From jdillworth at gmail.com Mon Nov 19 23:14:56 2007 From: jdillworth at gmail.com (Jeremy Dillworth) Date: Mon, 19 Nov 2007 20:14:56 -0800 (PST) Subject: Is it possible to use sockets to login to a website that uses php? References: Message-ID: On Nov 19, 3:37 pm, "Gabriel Genellina" wrote: > En Mon, 19 Nov 2007 15:01:16 -0300, Lamonte Harris > escribi?: > > > I need to some how make a script that logs into a website from my desktop > > and I can do the rest and grab the information on my on hopefully. How > > would I login to a website using sockets with python? > > See the urllib2 module. > > -- > Gabriel Genellina You may also want to have a look at the Twill project: http://darcs.idyll.org/~t/projects/twill/doc/ Twill is a testing tool which can login to web apps as you describe. It also has a Python API here: http://darcs.idyll.org/~t/projects/twill/doc/python-api.html - Jeremy Dillworth From deets at nospam.web.de Tue Nov 13 11:01:52 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 13 Nov 2007 17:01:52 +0100 Subject: how can I interpret a file within the interactive interpreter References: Message-ID: <5pu03gFstmu8U1@mid.uni-berlin.de> Peter J. Bismuti wrote: > I want to interpret a file (or whatever you call it) and then keep the > interactive interpreter alive so I can then continue to issue commands. > > How can this be done? I saw online a -m flag but it does not seem to > work. Use the -i-flag. Diez From ptmcg at austin.rr.com Tue Nov 6 10:17:34 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 06 Nov 2007 07:17:34 -0800 Subject: Please explain collections.defaultdict(lambda: 1) In-Reply-To: <1194360878.021089.63120@z9g2000hsf.googlegroups.com> References: <1194360878.021089.63120@z9g2000hsf.googlegroups.com> Message-ID: <1194362254.612583.123610@o38g2000hse.googlegroups.com> On Nov 6, 8:54 am, "metaperl.com" wrote: > I'm readinghttp://norvig.com/spell-correct.html > > and do not understand the expression listed in the subject which is > part of this function: > > def train(features): > model = collections.defaultdict(lambda: 1) > for f in features: > model[f] += 1 > return model > > Perhttp://docs.python.org/lib/defaultdict-examples.html > > It seems that there is a default factory which initializes each key to > 1. So by the end of train(), each member of the dictionary model will > have value >= 1 > > But why wouldnt he set the value to zero and then increment it each > time a "feature" (actually a word) is encountered? It seems that each > model value would be 1 more than it should be. The explanation is a little further down on that same page, on the discussion of "novel" words and avoiding the probablity of them being 0 just because they have not yet been seen in the training text. -- Paul From bj_666 at gmx.net Mon Nov 12 05:51:36 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 12 Nov 2007 10:51:36 GMT Subject: Using python as primary language References: <1194508354.226023.232050@v3g2000hsg.googlegroups.com> <1194652106.191133.295200@e9g2000prf.googlegroups.com> Message-ID: <5pqphoFskt9cU1@mid.uni-berlin.de> On Mon, 12 Nov 2007 10:28:02 +0100, Martin Vilcans wrote: > Actually, I would prefer to do parallell programming at a higher > level. If Python can't do efficient threading at low level (such as in > Java or C), then so be it. Perhaps multiple processes with message > passing is the way to go. It just that it seems so... primitive. Well, to me threads seem to be more primitive. You have to be careful with shared memory accesses and they don't scale so well if you want to go from single machines to a cluster. Take a look at XML-RPC or Pyro for higher level communication between processes. Ciao, Marc 'BlackJack' Rintsch From dickinsm at gmail.com Wed Nov 14 17:13:00 2007 From: dickinsm at gmail.com (Mark Dickinson) Date: Wed, 14 Nov 2007 22:13:00 -0000 Subject: mpmath puzzle In-Reply-To: References: <1195068115.071870.198750@50g2000hsm.googlegroups.com> Message-ID: <1195078380.741801.29720@v3g2000hsg.googlegroups.com> On Nov 14, 2:45 pm, "Fredrik Johansson" wrote: > Unlike mpmath, the decimal module doesn't support non-integer powers > (except for square roots), and nor does gmpy (though you can do them > indirectly as mensanator showed earlier in the thread). And numpy / > scipy don't support arbitrary-precision floats. But in Python 2.6 (and in the current trunk), it will: Python 2.6a0 (trunk:58930, Nov 10 2007, 20:54:42) [GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from decimal import Decimal, getcontext >>> getcontext().prec = 32 >>> 1234**Decimal("10.9") Decimal("4.9583278648155041477415234438717E+33") >>> Mark From bbxx789_05ss at yahoo.com Sun Nov 18 12:40:10 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Sun, 18 Nov 2007 09:40:10 -0800 (PST) Subject: sockets: why doesn't my connect() block? References: Message-ID: <4314a0ae-d2b3-4276-9205-e7e660064533@e10g2000prf.googlegroups.com> On Nov 18, 8:18 am, Jean-Paul Calderone wrote: > On Sat, 17 Nov 2007 21:32:50 -0800 (PST), 7stud wrote: > >According to "Python in a Nutshell(2nd)", p. 523: > > >connect: s.connect((host, port)) > >... > >Blocks until the server accepts or rejects the connection attempt. > > >However, my client program ends immediately after the call to > >connect()--even though my server program does not call accept(): > > Your platform's TCP implementation acknowledges the connection attempt > before your application calls accept(). This is fairly usual. > > Jean-Paul Has my platform rejected or accepted the connection? If it accepted the connection, then why do I have to call accept()? Or is "Python in Nutshell" wrong? From jeremie at le-hen.org Wed Nov 14 19:21:02 2007 From: jeremie at le-hen.org (Jeremie Le Hen) Date: Thu, 15 Nov 2007 01:21:02 +0100 Subject: Unicode: matching a Message-ID: <20071115002102.GN21753@obiwan.tataz.chchile.org> Hi list, (Please Cc: me when replying, as I'm not subscribed to this list.) I'm working with Unicode strings to handle accented characters but I'm experiencing a few problem. The first one is with regular expression. If I want to match a word composed of characters only. One can easily use '[a-zA-Z]+' when working in ascii, but unfortunately there is no equivalent when working with unicode strings: the latter doesn't match accented characters. The only mean the re package provides is '\w' along with the re.UNICODE flag, but unfortunately it also matches digits and underscore. It appears there is no suitable solution for this currently. Am I right? Secondly, I need to translate accented characters to their unaccented form. I've written this function (sorry if the code isn't as efficient as possible, I'm not a long-time Python programmer, feel free to correct me, I' be glad to learn anything): % def unaccent(s): % """ % """ % % if not isinstance(s, types.UnicodeType): % return s % singleletter_re = re.compile(r'(?:^|\s)([A-Z])(?:$|\s)') % result = '' % for l in s: % desc = unicodedata.name(l) % m = singleletter_re.search(desc) % if m is None: % result += str(l) % continue % result += m.group(1).lower() % return result % But I don't feel confortable with it. It strongly depend on the UCD file format and names that don't contain a single letter cannot obvisouly all be converted to ascii. How would you implement this function? Thank you for your help. Regards, -- Jeremie Le Hen < jlehen at clesys dot fr > From gianmaria at hotmail.com Wed Nov 28 16:35:45 2007 From: gianmaria at hotmail.com (Gianmaria Iaculo - NVENTA) Date: Wed, 28 Nov 2007 22:35:45 +0100 Subject: Bit Operations References: <20071128211843.GB6625@sdf.lonestar.org> Message-ID: U are really nice guys... i'm really apreciating (sorry 4 my bad english) Chriss is right this are coordinates.... and i'm treating as strings naturally I dont really have floating points on my module.. it run a 1.5 python version from Telit. So i dont have zLib too... just have 1.5 Mb of Ram and 3Mb of Rom... not realy confortable..isn't it? I'm tring some experiments on the command line... i've tried this: My longitude is 42.237897 so as a first step... i created a X and done this job as your examples: a = 4 b = 2 x = (a<<4)|b x is 66 so i can do: aDecoded = x >> 4 and i have the 4 again...( a value) but i've some problems while i decode the b.... Where i go wrong? Gianmaria Firma Gianmaria Iaculo "Chris Mellon" ha scritto nel messaggio news:mailman.1677.1196285028.13605.python-list at python.org... > On Nov 28, 2007 3:18 PM, J. Clifford Dyer wrote: >> On Wed, Nov 28, 2007 at 10:05:40PM +0100, Gianmaria Iaculo - NVENTA wrote >> regarding Re: Bit Operations: >> > >> > Txs all, >> > i wont to respond to who asked why i needed it: >> > >> > I'm using python on GSM modules and the informations i have to move >> > goes >> > along GPRS/UMTS connections so it's beatiful for me to transfer more >> > informations with less space... >> > imagine i have to send this simple data.... >> > >> > 41.232323,12.345678 >> > >> > i can send it as it's or use the nibble trick and on the receiving >> > station >> > 'unlift" the data and rebuild the original information... >> > >> > isn'it??? >> > >> >> Um, no. It isn't. How exactly are you going to pack floating point >> numbers into a half a byte? >> >> Or are you sending it as strings? Also a waste of space, and >> unnecessarily complex. >> > > Assuming these are coordinates, not floats, using strings makes sense > but the zlib module is probably a much better choice than a > hand-written compression scheme. From jjl at pobox.com Tue Nov 27 15:39:25 2007 From: jjl at pobox.com (John J. Lee) Date: Tue, 27 Nov 2007 20:39:25 GMT Subject: Should proxy objects lie about their class name? References: <87lk8szlnm.fsf@pobox.com> <87d4txudv2.fsf@pobox.com> <5r0jfgF1219j2U1@mid.uni-berlin.de> Message-ID: <87lk8j5soy.fsf@pobox.com> "Diez B. Roggisch" writes: > John J. Lee schrieb: >> jjl at pobox.com (John J. Lee) writes: >> >>> Not much to add to the subject line. I mean something like this: >>> >>> ProxyClass.__name__ = ProxiedClass.__name__ >>> >>> >>> I've been told that this is common practice. Is it? Would this >>> surprise you if you ran into it in a debugging session? >> >> Does nobody have an opinion on this? Pull your socks up, c.l.py! >> >> > > I've written quite a few proxies, but none of them did that. IMHO this > is similar to using isinstance overeagerly: it works against the > duck-typing principle to guard code by requiring certain base-classes, > instead of just relying on protocol. The same applies here. Sure. The push here was the doctest issue. > There might be of course cases where you have code lying around that > does do some distinctions based on the class-name (I'm certainly I've > seen such stuff once or tiwce, but always regarded it a WTF). Then > doing as you do above might help in getting things work. Right. The actual case I'm talking about here involved an exception class (dynamically created by subclassing at runtime, eugh) -- and a common one at that -- so it's a pretty common thing in doctests and any workaround on the doctest level would be very ugly (of course, alternatives include working around it by wrapping the code that raises the exception, or changing the doctest files to use the new exception name). What worries me is the potential for confusion. Again, would it confuse you (not just Diez, everybody)? John From inq1ltd at inqvista.com Thu Nov 15 10:46:40 2007 From: inq1ltd at inqvista.com (jim-on-linux) Date: Thu, 15 Nov 2007 10:46:40 -0500 Subject: Custom Tkinter scrollbar In-Reply-To: <1195082524.398058.312030@50g2000hsm.googlegroups.com> References: <1195082524.398058.312030@50g2000hsm.googlegroups.com> Message-ID: <200711151046.40703.inq1ltd@inqvista.com> On Wednesday 14 November 2007 18:22, Hunter.lennon at gmail.com wrote: > I want to create a custom scrollbar using particular images, which > will then be placed on a canvas to control another window on the > canvas. Right now I am inheriting from scrollbar, but I do the > movement with custom functions. When I create it and put in into > the canvas with "canvas.create_window" a standard scrollbar shows > in the correct spot and my custom one is outside of the canvas. > > All I have right now is something that moves like a scrollbar but > has no effect on other objects. > > Can anyone give me some advice or point me to a guide for this? Is > it even possible? Can I create a widget that mimics a scrollbar, > or would that be more difficult? I have been unable to find > anything online and would appreciate any help. Sounds to me that you want a navigation window for a chosen image. Gimp imaging program has such a window. Check out how gimp works with multiple images. You might want to work with a toolbar that opens a navigation window for each image. For an explanation on how scrolling works check out a book by O'Reilly written by Mark Lutz, Programming Python, look up programming scrollbars. jim-on-linux http://www.inqvista.com From beema.shafreen at gmail.com Sat Nov 3 02:09:31 2007 From: beema.shafreen at gmail.com (Beema shafreen) Date: Sat, 3 Nov 2007 11:39:31 +0530 Subject: count increment... Message-ID: hi, evrybody.... I have file A_16_P21360207 304 A_14_P136880 783 A_16_P21360209 795 A_16_P21360210 173 A_16_P03641959 1177 A_16_P03641960 1944 A_16_P03641962 999 A_16_P41563648 -31 A_16_P03641963 3391 A_16_P41563649 3626 A_16_P03641964 180 A_16_P41563655 1216 A_16_P03641965 1170 A_16_P03641966 194 A_16_P21360229 290 A_16_P03641967 425 A_16_P21360231 1091 A_16_P03641968 1167 A_16_P03641969 421 A_16_P03641970 63 A_16_P21360234 290 A_16_P21360235 289 A_16_P03641971 398 A_16_P21360237 418 A_16_P03641972 122 A_16_P21360239 16 A_16_P03641973 2187 A_16_P41563669 2881 A_16_P03641974 1101 A_16_P03641975 451 A_16_P03641976 2203 A_16_P41563677 7927 A_16_P21360249 5749 A_16_P21360257 303 A_16_P03641977 2307 A_16_P21360259 2102 A_16_P03641980 270 my script: #!/usr/bin/env python fh = open('complete_span','r') line = fh.readline().split('#') old_probe = line[0].strip() old_value = line[1].strip() print old_probe, old_value count = 1 line = "" while line: line = fh.readline().strip() if line : current_probe, current_value = line.split('#')[0:2] probe =current_probe.strip() value = current_value.strip() if int(old_value) > int(value): res_value='%s\t%s'%(old_value, old_probe) print res_value if count >= 244000: break old_probe,old_value =probe, value fh.close() I need to increment the line........ until the line count is 244000..... i havescript but... it doesnot work... can anybody... chekc and let me know what was the problem... -------------- next part -------------- An HTML attachment was scrubbed... URL: From caren_balea at xemail.de Thu Nov 22 17:00:00 2007 From: caren_balea at xemail.de (Caren Balea) Date: Thu, 22 Nov 2007 14:00:00 -0800 (PST) Subject: How to import xplt, pylab? Message-ID: <8dbd9284-f4e5-41f6-b2b6-81616dd50be8@s19g2000prg.googlegroups.com> Hello, I'm newbie to python. So far, I'm a bit disappointed. It's awful to set Python up to work. It's not working!!! Ok, calm down. Here are my settings: I'm using Windows XP machine and have installed Python 2.5.1. Also, I have also installed something called "Cygwin" to type in my commands. Finally, I have installed scipy-0.6.0. After starting Cygin I type python import math import scipy ***************************************** Then I try import xplt and get the message Traceback (most recent call last): File "", line 1, in ImportError: No module named xplt ***************************************** Also I try import pylab and get the message Traceback (most recent call last): File "", line 1, in ImportError: No module named pylab ***************************************** So, how can I use xplt and pylab???!!!! Any help would be much appreciated!!! Thank you, Caren From arkanes at gmail.com Mon Nov 12 14:56:23 2007 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 12 Nov 2007 13:56:23 -0600 Subject: Override method name and original method access In-Reply-To: References: Message-ID: <4866bea60711121156p42e5da5cy4574db5d9eae79ce@mail.gmail.com> On Nov 12, 2007 1:41 PM, Donn Ingle wrote: > In an unusual twist of code I have a subclass which overrides a method but > it also needs to call the original method: > > class One: > def add (self, stuff): > self.stuff.append(stuff) > > class Two(One): > def __init__(self, otherstuff): > (otherstuff) #otherstuff must go into list within the parent. > #The override - totally different function in this context. > def add (self, data): > self.unrelated.append (data) > > For: > > I have tried: > self.One.add( otherstuff ) > No go. > super ( Two, self).add( otherstuff ) > Gives this error:TypeError: super() argument 1 must be type, not classobj > (Which reminds me, how the heck does super work? I always get that error!) > You need to be a new-style class (that is, you must inherit from object) for super() to work. Other than that, you are using it correctly here. > I could just change the method name to adddata() or something. I could pass > parent references around, but want to avoid that. > > I thought I'd ask about it here. > > \d > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From bdesth.quelquechose at free.quelquepart.fr Fri Nov 23 16:29:25 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 23 Nov 2007 22:29:25 +0100 Subject: python class methods identity? In-Reply-To: References: <7847e5160711222329t44e76c0yb819e9415b865d84@mail.gmail.com> Message-ID: <47474651$0$32731$426a34cc@news.free.fr> Chris Mellon a ?crit : > On Nov 23, 2007 1:29 AM, Roc Zhou wrote: (snip) >>Since both "var" and "func" are the variable of the class object, and > > "members", not variables. > "attributes", not members !-) From gc284 at vif.com Tue Nov 13 11:26:28 2007 From: gc284 at vif.com (Gordon C) Date: Tue, 13 Nov 2007 11:26:28 -0500 Subject: Arrays References: <1194917023.976618@www.vif.com> <1194918994.934367.28860@v3g2000hsg.googlegroups.com> <1194937100.432126.53690@k35g2000prh.googlegroups.com> Message-ID: <1194971181.168508@www.vif.com> OK, thanks to all. The key statement is "from array import array" which is not exactly intuitive! Gord "John Machin" wrote in message news:1194937100.432126.53690 at k35g2000prh.googlegroups.com... > > Bernard wrote: >> On 12 nov, 20:19, "Gordon C" wrote: >> > Absolute newbie here. In spite of the Python Software Foundation >> > tutorial's >> > (http://www.python.org/doc/current/tut/tut.html) use of the array >> > declaration >> > array(type[,initializer]), the Python interpreter does NOT accept the >> > word >> > array! It , presumably, needs to have an import included. >> > Could >> > some show me how to declare arrays with some basic examples? >> > Gord. >> >> hey Gordon, >> >> here's a good reading for you: http://effbot.org/zone/python-list.htm > > Hey Bernard, read Gordon's message carefully; he's asking about > arrays, not lists. > > Hey Gordon, You seem a little lost; here's the tutorial reference: > http://docs.python.org/tut/node13.html#SECTION0013700000000000000000 > which produces: > """ > The array module provides an array() object that is like a list that > stores only homogenous data and stores it more compactly. The > following example shows an array of numbers stored as two byte > unsigned binary numbers (typecode "H") rather than the usual 16 bytes > per entry for regular lists of python int objects: > > > >>> from array import array > >>> a = array('H', [4000, 10, 700, 22222]) > >>> sum(a) > 26932 > >>> a[1:3] > array('H', [10, 700]) > """ > > The 2nd word (array) is a link (http://docs.python.org/lib/module- > array.html) to the docs for the array module. > > Cheers, > John > From mike5160 at gmail.com Tue Nov 20 18:11:38 2007 From: mike5160 at gmail.com (mike5160) Date: Tue, 20 Nov 2007 15:11:38 -0800 (PST) Subject: Formatting question. Message-ID: Hi all, My input file looks like this : ( the data is separated by tabs ) 11/26/2007 56.366 898.90 -10.086 23.11 1212.3 11/26/2007 52.25 897.6 -12.5 12.6 13333.5 11/26/2007 52.25 897.6 -12.5 12.6 133.5 The output I'm trying to get is as follows : ( Insert NBUSER.Grochamber Values '11/26/2007','56.366','898.90','-10.086','23.11','1212.3', ) ( Insert NBUSER.Grochamber Values '11/26/2007','52.25','897.6','-12.5','12.6','13333.5', ) ( Insert NBUSER.Grochamber Values '11/26/2007','52.25','897.6','-12.5','12.6','133.5', ) The following is the program i have written so far : LoL = [] for line in open('mydata.txt'): LoL.append(line.split("\t")) print "read from a file: ", LoL, outfile = open("out.dat", "w") lilength = len(LoL) liwidelength = len(LoL[1]) print "length of list is " , lilength, "long" print "length of list is " , liwidelength, "long" for x in range(lilength): outfile.write(" ( ") outfile.write('Insert NBUSER.Grochamber Values ') for y in range(liwidelength): outfile.write( "'%s'," % (LoL[x][y])) outfile.write(" ) \n") outfile.close() I have 3 questions : 1. The formatting in the first line comes out wrong all the time. I m using windows python 2.5.1. The last part of the first line is always on the second line. 2. How do I avoid the "," symbol after the last entry in the line? (this are supposed to be sql-queries - importing excel based tabbed data to sql database) 3. What do I do when the data is missing? Like missing data? Thanks for all your help! Mike From erik at myemma.com Mon Nov 26 17:19:14 2007 From: erik at myemma.com (Erik Jones) Date: Mon, 26 Nov 2007 16:19:14 -0600 Subject: fork/exec with input redirection In-Reply-To: <5504f9ac0711261358p31c2b9f1ud24aec5829d8707e@mail.gmail.com> References: <5504f9ac0711261358p31c2b9f1ud24aec5829d8707e@mail.gmail.com> Message-ID: <9CD9ED66-3C6F-485E-A489-7B2253265184@myemma.com> On Nov 26, 2007, at 3:58 PM, Dan Upton wrote: > I have a Python script that does a fork/exec, so the parent process > can get the child's PID and monitor /proc/PID/stat (on a CentOS > system). Most of my processes' command lines are straightforward > enough to do this with, but I have a handful that use < on the command > line, eg > > ./gobmk_base.linux_x86 --quiet --mode gtp < 13x13.tst > > The only thing I could really think of to try was > > os.execv("./gobmk_base.linux_x86", ["./gobmk_base.linux_x86", > "--quiet", "--mode", "gtp", "<", "13x13.tst"]) > > but this apparently doesn't work. Is there some other way to > accomplish what I'm going for? Read up on the docs for the subprocess module. Erik Jones Software Developer | Emma? erik at myemma.com 800.595.4401 or 615.292.5888 615.292.0777 (fax) Emma helps organizations everywhere communicate & market in style. Visit us online at http://www.myemma.com From bborcic at gmail.com Tue Nov 6 02:05:08 2007 From: bborcic at gmail.com (Boris Borcic) Date: Tue, 06 Nov 2007 08:05:08 +0100 Subject: How to use list as key of dictionary? In-Reply-To: <1194332021.595511.67370@v29g2000prd.googlegroups.com> References: <1194332021.595511.67370@v29g2000prd.googlegroups.com> Message-ID: <4730125c$1_6@news.bluewin.ch> Davy wrote: > Hi all, > > We know that list cannot be used as key of dictionary. Yeah, but do we know why ? > So, how to work > around it? That's a subsidiary question. > > For example, there is random list like l=[1,323,54,67]. Don't use 1owercase L as a variab1e name, p1ease ! > > Any suggestions are welcome! >>> {tuple([1,323,54,67]):666} {(1, 323, 54, 67): 666} From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Nov 28 16:33:10 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Wed, 28 Nov 2007 22:33:10 +0100 Subject: Control mouse position and clicking References: <4f209559-4454-4f8a-8ba3-18cbb50db094@b40g2000prf.googlegroups.com> Message-ID: <5r654mF135t4eU1@mid.individual.net> Glich wrote: > hi, how can I, control mouse position and clicking from python? > > I want to interact with a flash application inside firefox. > thanks. > > ps: I am not using windows. On Mac, IIRC, you can't. Regards, Bj?rn -- BOFH excuse #394: Jupiter is aligned with Mars. From sndive at gmail.com Mon Nov 19 16:13:24 2007 From: sndive at gmail.com (sndive at gmail.com) Date: Mon, 19 Nov 2007 13:13:24 -0800 (PST) Subject: getElementsByTagName in ElementTree Message-ID: what's the equivalent of minidom's getElementsByTagName in ElementTree? From dave at poptech.coop Fri Nov 23 09:11:43 2007 From: dave at poptech.coop (Dave Kennedy) Date: Fri, 23 Nov 2007 14:11:43 -0000 Subject: Sockets not going away Message-ID: <43198B98F14D7A4B873265AFCB471618170279@exchange2003.poptech.coop> Hi, I'm getting to grips with sockets and http servers in Python. I have this bit of code which should be enough for a simple web demo import socket, os from BaseHTTPServer import HTTPServer from SimpleHTTPServer import SimpleHTTPRequestHandler def test(HandlerClass = SimpleHTTPRequestHandler, ServerClass = HTTPServer): server_address = ('', 8000) # (address, port) httpd = ServerClass(server_address, HandlerClass) sa = httpd.socket.getsockname() print "Serving HTTPS on", sa[0], "port", sa[1], "..." httpd.serve_forever() if __name__ == '__main__': test() I've noticed though that every time I connect to this server in Firefox/IE, it seems to leave a socket behind. If I view the output of netstat on the server, I can see a number of connections still seem to be there. Also, using the echo server and client programs from the O'Reilly Programming Python book, I find that while the server doesn't seem to leave connections behind, the client application does import sys from socket import * serverHost = '192.168.4.34' serverPort = 50007 message = ['Hello network world'] if len(sys.argv) > 1: serverHost = sys.argv[1] if len(sys.argv) > 2: message = sys.argv[2:] sockobj = socket(AF_INET, SOCK_STREAM) sockobj.connect((serverHost, serverPort)) for line in message: sockobj.send(line) data = sockobj.recv(1024) print 'Client received:', repr(data) sockobj.close() How do I make sure that all my sockets have been completely disposed of? I'm wanting to use Python to implement a client-server application, but experience so far seems to be that after a flurry of network activity, Python will use up all the available sockets. Thanks, Dave -------------- next part -------------- An HTML attachment was scrubbed... URL: From arkanes at gmail.com Tue Nov 6 16:00:44 2007 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 6 Nov 2007 15:00:44 -0600 Subject: Populating huge data structures from disk In-Reply-To: <000b01c820b5$44942cb0$cdbc8610$@com> References: <000001c820a1$78750ea0$695f2be0$@com> <4866bea60711061104i514838fcld9bbba1382a764a6@mail.gmail.com> <000b01c820b5$44942cb0$cdbc8610$@com> Message-ID: <4866bea60711061300r59d7f35eie183a0521d342930@mail.gmail.com> On Nov 6, 2007 2:40 PM, Michael Bacarella wrote: > > > > For various reasons I need to cache about 8GB of data from disk into > core on > > > application startup. > > > > Are you sure? On PC hardware, at least, doing this doesn't make any > > guarantee that accessing it actually going to be any faster. Is just > > mmap()ing the file a problem for some reason? > > > > I assume you're on a 64 bit machine. > > Very sure. If we hit the disk at all performance drops unacceptably. The > application > has low locality of reference so on-demand caching isn't an option. We get > the behavior > we want when we pre-cache; the issue is simply that it takes so long to > build this cache. > You're not going to avoid hitting disk just by reading into your memory space. If your performance needs are really so tight that you can't rely on the VM system to keep pages you're using in memory, you're going to need to do this at a much lower (and system specific) level. mmap() with a reasonable VM system shouldn't be any slower than reading it all into memory. > > > Building this cache takes nearly 2 hours on modern hardware. I am > surprised > > > to discover that the bottleneck here is CPU. > > > > > > The reason this is surprising is because I expect something like this to > be > > > very fast: > > > > > > #!python > > > import array > > > > > > a = array.array('L') > > > > > > f = open('/dev/zero','r') > > > > > > while True: > > > > > > a.fromstring(f.read(8)) > > > > This just creates the same array over and over, forever. Is this > > really the code you meant to write? I don't know why you'd expect an > > infinite loop to be "fast"... > > Not exactly. fromstring() appends to the array. It's growing the array > towards You're correct, I misread the results of my testing. > infinity. Since infinity never finishes it's hard to get an idea of how > slow > this looks. Let's do 800MB instead. > That makes this a useless benchmark, though... > Here's an example of loading 800MB in C: > > $ time ./eat800 > > real 0m44.939s > user 0m10.620s > sys 0m34.303s > > $ cat eat800.c > #include > #include > #include > > int main(void) > { > int f = open("/dev/zero",O_RDONLY); > int vlen = 8; > long *v = malloc((sizeof (long)) * vlen); > int i; > > for (i = 0; i < 100000000; i++) { > if (i >= vlen) { > vlen *= 2; > v = (long *)realloc(v,(sizeof (long)) * vlen); > } > read(f,v+i,sizeof (long)); > } > return 0; > } > > Here's the similar operation in Python: > $ time python eat800.py > > real 3m8.407s > user 2m40.189s > sys 0m27.934s > > $ cat eat800.py > #!/usr/bin/python > > import array > a = array.array('L') > > f = open('/dev/zero') > for i in xrange(100000000): > a.fromstring(f.read(8)) > > Note that you're not doing the same thing at all. You're pre-allocating the array in the C code, but not in Python (and I don't think you can). Is there some reason you're growing a 8 gig array 8 bytes at a time? > They spend about the same amount of time in system, but Python spends 4.7x > as much > CPU in userland as C does. > Python has to grow the array. It's possible that this is tripping a degenerate case in the gc behavior also (I don't know if array uses PyObjects for its internal buffer), and if it is you'll see an improvement by disabling GC. > And there's no solace in lists either: > > $ time python eat800.py > > real 4m2.796s > user 3m57.865s > sys 0m3.638s > > $ cat eat800.py > #!/usr/bin/python > > import struct > > d = [] > f = open('/dev/zero') > for i in xrange(100000000): > d.append(struct.unpack('L',f.read(8))[0]) > > > cPickle with protocol 2 has some promise but is more complicated because > arrays can't be pickled. In a perfect world I could do something like this > somewhere in the backroom: > > x = lengthy_number_crunching() > magic.save_mmap("/important-data") > > and in the application do... > > x = magic.mmap("/important-data") > magic.mlock("/important-data") > > and once the mlock finishes bringing important-data into RAM, at > the speed of your disk I/O subsystem, all accesses to x will be > hits against RAM. > You've basically described what mmap does, as far as I can tell. Have you tried just mmapping the file? > > Any thoughts? > > Did you try array.fromfile like I suggested? > -- > http://mail.python.org/mailman/listinfo/python-list > From nytrokiss at gmail.com Tue Nov 27 04:44:35 2007 From: nytrokiss at gmail.com (James Matthews) Date: Tue, 27 Nov 2007 10:44:35 +0100 Subject: Rss Feed Creator In-Reply-To: References: <8a6b8e350711261645p1b41b0e0rda70204462e1a8b9@mail.gmail.com> Message-ID: <8a6b8e350711270144y24507e76s415da8a703e67ff8@mail.gmail.com> Thank you everyone! On Nov 27, 2007 10:13 AM, Vladimir Rusinov wrote: > > > On 11/27/07, James Matthews wrote: > > > > I am looking for a library that will create Rss/Atom feeds in python. It > > needs to format the XML in a readable format! Does anyone have any > > suggestions? > > > You can also use some xml-based template engine (Kid or Genshi). > > -- > Vladimir Rusinov > GreenMice Solutions: IT-??????? ?? ???? Linux > http://greenmice.info/ -- http://search.goldwatches.com/?Search=Movado+Watches http://www.goldwatches.com/coupons http://www.jewelerslounge.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From antroy at gmail.com Thu Nov 22 10:02:23 2007 From: antroy at gmail.com (Ant) Date: Thu, 22 Nov 2007 07:02:23 -0800 (PST) Subject: foldr function in Python Message-ID: <9bf5a2bb-eac7-4859-a5de-b1e84573c77a@t47g2000hsc.googlegroups.com> Hi all, I've just been reading with interest this article: http://caos.di.uminho.pt/~ulisses/blog/2007/11/20/foldr-the-magic-function/ It's a useful function that (with a more intuitive name) could prove a compelling addition to the itertools module. In it's python form, it would be something like this: def reduce2 (fn, init, seq): return reduce(fn, seq, init) def foldr (function, initial): return partial(reduce2, function, initial) It's a bit different from the other itertools functions, in that rather than producing an iterator, it produces a function which reduces a iterator to a singe value. The advantages I see over reduce are that (a) it provides incentive to document the code and (b) it promotes reuse. For example: value = reduce(lambda x, y: "%s%s%s" % (x, "," if x else "", y), myList, "") vs. commaSeparate = foldr(lambda x, y: "%s%s%s" % (x, "," if x else "", y), "") commaSeparate(myList) Of course the lambda function in this case could be a named function, helping with both readability and reuse, but I think the latter is conceptually easier to grasp when reading the code. Discuss. -- Ant. From cyberco at gmail.com Sun Nov 18 16:48:59 2007 From: cyberco at gmail.com (Berco Beute) Date: Sun, 18 Nov 2007 13:48:59 -0800 (PST) Subject: Python too complex ?!?!?! References: <7hC%i.28332$mv3.17248@newsfe10.phx> Message-ID: <5caa68c2-85d5-4728-91dd-04b757a83f90@y5g2000hsf.googlegroups.com> On Nov 17, 3:21 pm, Tim Chase wrote: > > programmer, but he claims that the install, config, and > > library models for C# have proved to be less > > problematic than Python. So both his courses (intro, > > data structs, algorithms) are taught in C#. > > A little anecdotal comparison from some of my experience with two > web apps deployed at my current company: > > One web app, written in C#/ASP.net one written in Python. > > Moved each app to new servers (C#/ASP.net on a new Windows box, > Python app on a shiny new Debian box). > > C#/ASP.net app: had to find and install the right version of the > .net libraries. That's an afternoon of my life I won't get back. > > Python app: copied my app > > C#/ASP.net app: couldn't find VS2003 (in which the app had been > written) any more so had to upgrade to VS2005. > > Python app: Continued to use the same development environment. > > C#/ASP.net app: (ASP specific) generally requires following a > particular convention. Writing a RESTful web app is next to > impossible given the reliance on the postbacks; and the server > environment doesn't make it easy to make clean URLs > > Python app: Django makes web-app development easy and > clean/RESTful (other frameworks may as well...I speak from Django > experience) and push you to Do The Right Thing (tm) > > C#/ASP.net app: had to re-partition my server containers so that > it could deploy .Net 2.0 and .Net 3.0 apps side-by-side > > Python app: I've had Python 2.3, 2.4 and 2.5 running on the same > machine without a thought > > C#/ASP.net app: libraries are often written to a particular > framework version, so if any new functionality requires the new > version the whole app needs to be migrated. > > Python app: most of the libraries I use come built in, or they > work with 2.3 or later. > > C#/ASP.net app: Installing new libraries, same as upgrading > currently-used libraries. Usually requires paying for, then > manually installing various libraries, clearing distribution > rights, etc. > > Python app: There are an abundance libraries that are just an > apt-get away in terms of difficulty, and they are Free Software > so I can install them and deploy them without additional costs. > > C#/ASP.net app: 3rd party libraries usually come as source-less > DLLs that you can't peer into > > Python app: 3rd party libraries are usually pure python which > you can modify or step into as needed > > C#/ASP.net app: really only works well on Windows > > Python app: works well on Windows, Linux, BSD, Mac OS X... > > C#/ASP.net app: really requires Visual Studio > > Python app: works well with Eclipse, Vim, Emacs, Wing IDE, > Komodo, Idle, and piles of other development environments. Heck, > I've written the occasional python program using "ed" or "cat > > x.py". > > C#/ASP.net app: files are scattered all over. You've got source > apps, you've got templates, you've got resource files, you've got > GUID files. And VS hides the complexity so when (not "if") > something breaks you get a crash course in what goes on under the > covers. > > Python app: I've got .py files (and sometimes templates for my > Django code, and could have I18N files for translations). Very > easy to track down where everything is. > > C#/ASP.net app: Code/syntax is horridly opaque, requires braces > and lots of additional overhead code to get things done. Compare > the clutter of a basic C# script with a similarly function Python > script. How much is pure syntactic overhead? > > Python app: Code/syntax is rather easy to read (once you > understand list comprehensions and the __foo__ methods) > > Yeah, I'd take Python any day...for implementation *OR* for > teaching someone how to program. > > -tkc Thank you very much for this VERY useful summary. It gives me tons of ammunition in case the latest .Net zealot walks into my office :) From steve at REMOVE-THIS-cybersource.com.au Sat Nov 24 17:17:56 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 24 Nov 2007 22:17:56 -0000 Subject: How can I create customized classes that have similar properties as 'str'? References: <67954d23-9400-4ac9-ba45-bec04fab51a2@s6g2000prc.googlegroups.com> <8eebf8fb-74cc-452a-bbef-2fe93556491f@i29g2000prf.googlegroups.com> <5qqeroF11703eU2@mid.individual.net> <1f2e037f-3667-4070-97cd-f4f6486c9d79@i12g2000prf.googlegroups.com> <5a9a3a5b-2986-4dd4-9cfe-cdebe69c3514@l1g2000hsa.googlegroups.com> Message-ID: <13kh8ok6b7e0s44@corp.supernews.com> On Sat, 24 Nov 2007 04:54:43 -0800, samwyse wrote: > create a hash that maps your keys to themselves, then use the values of > that hash as your keys. > >>>> store = {} >>>> def atom(str): > global store > if str not in store: > store[str] = str > return store[str] Oh lordy, that's really made my day! That's the funniest piece of code I've seen for a long time! Worthy of being submitted to the DailyWTF. Samwyse, while I applaud your willingness to help, I think you actually need to get some programming skills before doing so. Here's a hint to get you started: can you think of a way to optimize that function so it does less work? -- Steven. From sindhu_jjcet at yahoo.co.in Mon Nov 5 23:52:45 2007 From: sindhu_jjcet at yahoo.co.in (sindhu_jjcet at yahoo.co.in) Date: Mon, 05 Nov 2007 20:52:45 -0800 Subject: hi friends Message-ID: <1194324765.944933.104460@e9g2000prf.googlegroups.com> to get preapred for the business see bird-flumanual.com log on to http://www.geocities.com/humnoses/ From yoram.hekma at aoes.com Mon Nov 12 09:44:09 2007 From: yoram.hekma at aoes.com (Yoram Hekma) Date: Mon, 12 Nov 2007 15:44:09 +0100 Subject: which tool to use? In-Reply-To: References: Message-ID: <20071112144409.GA6671@aoes.com> On Sun, Nov 11, 2007 at 01:06:35PM -0500, Brian Blais wrote: > Hello, > > I'm looking for a system for managing submissions of proposals, with > multiple parts, and possible updating of those parts by the user (so it > needs some basic version control). There has to be some sort of > permissions enforcement, to distinguish submitters from committee members > reading/commenting on proposals. I've looked at Plone, but am not sure if > it is the correct tool for this job: it's much more than I need. I could > try to roll my own, but it seems like I'd be reinventing the wheel. Is > there software out there already for this kind of thing, preferably > customizable in Python? I can be more specific about my requirements if > that would help. > > > thanks, > > Brian Blais Brian, Well, while it might be better to just try some systems and see which one you like best, maybe Trac (in combination with SVN for the vcs part) is something worth looking into. See http://trac.edgewall.org/ Regards, Yoram -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From mullen at tsuda.ac.jp Sat Nov 10 23:52:41 2007 From: mullen at tsuda.ac.jp (Tony Mullen) Date: Sun, 11 Nov 2007 13:52:41 +0900 Subject: System exit hanging in Leopard Message-ID: Hello, (I posted this once before, but haven't gotten a response. This is a pretty heavy traffic mailing list, so it's hardly surprising, but I'm going to bump the question in case anybody has seen or can replicate (or not replicate) this issue. Thx) I'm using Tkinter to create widgets in Python 2.5 on OS X 10.5. When I call root.quit or sys.exit in any way, the following traceback appears, after which the application stops responding and just gives the spinning rainbow cursor. The IDLE editor and the Python shell remain responsive, and I can kill the application from the command line, but not any other way. I don't see anything problematic in the traceback, but I don't think that the application should be hanging like this. Is this likely a Leopard-related issue? Thanks for any responses, Tony Traceback (most recent call last): File "/Users/tonymullen/Documents/ui", line 11, in widget.mainloop() File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-tk/Tkinter.py", line 1023, in mainloop self.tk.mainloop(n) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-tk/Tkinter.py", line 1405, in __call__ raise SystemExit, msg SystemExit -- Tony Mullen Department of Computer Science, Tsuda College 2-1-1 Tsudamachi, Kodairashi Tokyo 187-8577, Japan Tel: +81-42-342-5482 From lasses_weil at klapptsowieso.net Tue Nov 6 04:46:48 2007 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Tue, 06 Nov 2007 10:46:48 +0100 Subject: How to use list as key of dictionary? In-Reply-To: <1194339027.038844.22200@v23g2000prn.googlegroups.com> References: <1194332021.595511.67370@v29g2000prd.googlegroups.com> <1194332941.190425.21090@i38g2000prf.googlegroups.com> <1194339027.038844.22200@v23g2000prn.googlegroups.com> Message-ID: <47303809$0$16661$9b4e6d93@newsspool3.arcor-online.net> Davy wrote: > Hi Matimus and Boris, > > Thank you :) > > And a further question about vector above rank 1, how can I use it as > the key of dictionary? > > For example, if I have list like L=[[1,2,3],[4,5,6,7]], > Then I do L_tuple = tuple(L) >>>> L_tuple = ([1,2,3],[4,5,6,7]) > But {L_tuple:'hello'} cause an error? > Yes, because your key still contains mutable elements. That should not surprise you. If it does, please (re-)read and . maybe something like this could help: def tupleize(non_tuple): try: return tuple(tupleize(thing) for thing in non_tuple) except TypeError: # non_tuple is not iterable return non_tuple /W From pofuk at email.t-com.hr Thu Nov 15 15:38:03 2007 From: pofuk at email.t-com.hr (SMALLp) Date: Thu, 15 Nov 2007 21:38:03 +0100 Subject: Python beginner! Message-ID: Could someone please paste some program in wxPython that uses inharitance. I would be very thankfull. From James.w.Howard at gmail.com Mon Nov 12 14:41:40 2007 From: James.w.Howard at gmail.com (JamesHoward) Date: Mon, 12 Nov 2007 19:41:40 -0000 Subject: Transfer socket connection between programs Message-ID: <1194896500.733359.93510@50g2000hsm.googlegroups.com> Does anyone know any method to have one program, acting as a server transfer a socket connection to another program? I looked into transferring the connection via xml rpc to no avail. It seems to be a problem of getting access to a programs private memory space and giving another program access to that space. Thanks in advance, James Howard From alberto at metapensiero.it Thu Nov 15 09:38:14 2007 From: alberto at metapensiero.it (Alberto Berti) Date: Thu, 15 Nov 2007 15:38:14 +0100 Subject: why there is no pythonscript insine web browsers? References: <1194992388.373707.327500@o38g2000hse.googlegroups.com> Message-ID: <87ir43376x.fsf@lizard.lizardnet> >>>>> "Piet" == Piet van Oostrum writes: Piet> CGI is server-side. The OP was asking for client-side Piet> embedding of Python. FireFox 3 aka "Gran Paradiso" can be compiled to have python scripting but for security reasons it can be used only on crome:// urls, which load local content. there is an xpi package that can be installed on Gran Paradiso alphas: http://vamposdecampos.googlepages.com/pyxpcom From jcd at sdf.lonestar.org Tue Nov 13 12:44:12 2007 From: jcd at sdf.lonestar.org (J. Clifford Dyer) Date: Tue, 13 Nov 2007 12:44:12 -0500 Subject: why no automatic conversion in string concatenation? In-Reply-To: <627523.28675.qm@web55303.mail.re4.yahoo.com> References: <627523.28675.qm@web55303.mail.re4.yahoo.com> Message-ID: <20071113174412.GC23052@sdf.lonestar.org> On Tue, Nov 13, 2007 at 07:15:06AM -0800, Michael Pelz Sherman wrote regarding why no automatic conversion in string concatenation?: > > As a Java & PHP developer, I find it kind of annoying that I have to > explicitly convert non-string variables to strings when concatenating > them, especially when python is quite capable of doing the conversion > automatically. > i.e.: > >>> myBool = True > >>> print myBool > True > >>> print "myBool is " + myBool > Traceback (most recent call last): > File "", line 1, in > TypeError: cannot concatenate 'str' and 'bool' objects > >>> print "myBool is " + str(myBool) > myBool is True > Can anyone explain why this is so? Because python doesn't know if '1' + 1 should equal 2 or '11' and would rather you mad that decision. Should it be different than 1 + '1'? or to put it more succinctly, because "explicit is better than implicit." In fact, I think it's more often the case that I have string data that I need to treat as integers than the other way around (input from stdin and textfiles for example). > Are there any plans to change this > in python 3000? I hope not, and I don't think so. > Thanks, > - Michael No problem. Cheers, Cliff From zionist.news2 at gmail.com Tue Nov 13 11:01:06 2007 From: zionist.news2 at gmail.com (zionist.news2 at gmail.com) Date: Tue, 13 Nov 2007 08:01:06 -0800 Subject: FALSE FLAG TACTIC TO SCARE CHRISTIANS AND THOSE WHO HAVE LITTLE KNOWLEDGE Re: Concept of God in Islam In-Reply-To: <1194939934.370229.105470@22g2000hsm.googlegroups.com> References: <1194939934.370229.105470@22g2000hsm.googlegroups.com> Message-ID: <1194969666.726194.35520@v65g2000hsc.googlegroups.com> Here, a jew subterfuge false-flag posing as an Islamic spams the newsgroup with CUT AND PASTE job from some Islamic webpage TO SCARE THE CHRISTIAN FUNDAMENTALISTS and EUROPEANS (like those French) in an attempt to destroy 911 truth discussion by making them think that 911 truth victory = something like islamic victory and confuse the readership. 911 truthers never get into this kind of thing. 911 truthers never get into this kind of thing. 911 truthers never get into this kind of thing. We will reply to EXPOSE this tactic coz we know that there are vulnerable XENOPHOBIC people or just those who dont understand the nature of these tactics. Such posts have often piggy-backed the posts by 911 truthers. It is important to explain the nature of these posts appearing after 911 truth posts which are truly science related and educational and meant to protect our constitution and democracy from the criminals. We (911 truthers) must protect our unity. On Nov 13, 7:45 am, abdo911 wrote: > WAMY Series: On Islam No.9.Introduction > God's Attributes > The Oneness of God > The Believer's Attitude > Introduction > It is a known fact that every language has one or more terms that are > used in reference to God and sometimes to lesser deities. This is not > the case with Allah. Allah is the personal name of the One true God. > Nothing else can be called Allah. The term has no plural or gender. > This shows its uniqueness when compared with the word "god," which can > be made plural, as in "gods," or made feminine, as in "goddess." It is > interesting to notice that Allah is the personal name of God in > Aramaic, the language of Jesus and a sister language of Arabic.The One > true God is a reflection of the unique concept that Islam associates > with God. To a Muslim, Allah is the Almighty Creator and Sustainer of > the universe, Who is similar to nothing, and nothing is comparable to > Him. The Prophet Muhammad was asked by his contemporaries about Allah; > the answer came directly from God Himself in the form of a short > chapter of the Qur'an, which is considered to be the essence of the > unity or the motto of monotheism. This is chapter 112, which reads:" > In the name of Allah, the Merciful, the Compassionate. Say (O > Muhammad), He is God, the One God, the Everlasting Refuge, who has not > begotten, nor has been begotten, and equal to Him is not anyone".Some > non-Muslims allege that God in Islam is a stern and cruel God who > demands to be obeyed fully and is not loving and kind. Nothing could > be farther from the truth than this allegation. It is enough to know > that, with the exception of one, each of the 114 chapters of the > Qur'an begins with the verse " In the name of God, the Merciful, the > Compassionate". In one of the sayings of Prophet Muhammad (PBUH), we > are told that " God is more loving and kind than a mother to her dear > child".On the other hand, God is also Just. Hence, evildoers and > sinners must have their share of punishment, and the virtuous must > have God's bounties and favors. Actually, God's attribute of Mercy has > full manifestation in His attribute of Justice. People suffering > throughout their lives for His sake should not receive similar > treatment from their Lord as people who oppress and exploit others > their whole lives. Expecting similar treatment for them would amount > to negating the very belief in the accountability of man in the > Hereafter and thereby negate all the incentives for a moral and > virtuous life in this world. The following Qur'anic verses are very > clear and straightforward in this respect. > Verily, for the Righteous are gardens of Delight, in the Presence of > their Lord. Shall We then treat the people of Faith like the people of > Sin? What is the matter with you? How judge you? > Islam rejects characterizing God in any human form or depicting Him as > favoring certain individuals or nations on the basis of wealth, power > or race. He created the human-beings as equals. They may distinguish > themselves and get His favor through virtue and piety only. > The concepts that God rested on the seventh day of creation, that God > wrestled with one of His soldiers, that God is an envious plotter > against mankind, and that God is incarnate in any human being are > considered blasphemy from the Islamic point of view. > The unique usage of Allah as a personal name of God is a reflection of > Islam's emphasis on the purity of the belief in God that is the > essence of the message of all God's messengers. Because of this, Islam > considers associating any deity or personality with God as a deadly > sin that God will never forgive, despite the fact that He may forgive > all other sins. > The Creator must be of a different nature from the things created > because if He is of the same nature as they are, He will be temporal > and will therefore need a maker. It follows that nothing is like Him. > If the maker is not temporal, then he must be eternal. But if he is > eternal, he cannot be caused, and if nothing caused Him to come into > existence, nothing outside Him causes Him to continue to exist, which > means that he must be self-sufficient. And if He does not depend on > anything for the continuance of His own existence, then this existence > can have no end. The Creator is therefore eternal and everlasting: "He > is the First and the Last". > He is Self-sufficient or Self-subsistent, or, to use a Qur'anic term, > Al-Qayyum The Creator does not create only in the sense of bringing > things into being, He. also preserves them and takes them out of > existence and is the ultimate cause of whatever happens to them. > " God is the Creator of everything. He is the guardian over > everything. Unto Him belong the keys of the heavens and the > earth" (39:62-63). > " No creature is there crawling on the earth, but its provision rests > on God. He knows its lodging place and its repository" (11:16). > God's Attributes > If the Creator is Eternal and Everlasting, then His attributes must > also be eternal and everlasting. He should not lose any of His > attributes nor acquire new ones. If this is so, then his attributes > are absolute. Can there be more than one Creator with such absolute > attributes? Can there be, for example, two absolutely powerful > Creators? A moment's thought shows that this is not feasible. > The Qur'an summarizes this argument in the following verses:" God has > not taken to Himself any son, nor is there any god with Him: for then > each god would have taken of that which he created and some of them > would have risen up over others" (23:91). > " And why, were there gods in earth and heaven other than God, they > (heaven and earth) would surely go to ruin" (21:22). > The Oneness of God > The Qur'an reminds us of the falsity of all alleged gods. To the > worshippers of man-made objects it asks:" Do you worship what you have > carved yourself" (37:95). " Or have you taken unto yourself others > beside Him to be your protectors, even such as have no power either > for good or for harm to themselves" (13:16). > To the worshippers of heavenly bodies it cites the story of Abraham:" > When night outspread over him, he saw a star and said: This is my > Lord. But when it set, he said: I love not the setters. When he saw > the moon rising, he said: This is my Lord. But when it set, he said: > If my Lord does not guide me, I shall surely be of the people gone > astray. When he saw the sun rising, he said: This is my Lord; this is > greater. But when it set, he said: O my people, surely I quit that > which you associate, I have turned my face to Him who originated the > heavens and the earth; a man of pure faith, I am not one of the > idolators" (6:76-79). > The Believer's Attitude > In order to be a Muslim, that is, to surrender oneself to God, it is > necessary to believe in the oneness of God, in the sense of His being > the only Creator, Preserver, Nourisher, etc. But this belief, later > called Tawhid Ar-Rububiyyah, is not enough. Many of the idolators knew > and believed that only the Supreme God could do all this. But this was > not enough to make them Muslims. To tawhid ar-rububiyyah, one must add > tawhid al-'uluhiyyah. That is, one acknowledges the fact that it is > God alone who deserves to be worshipped, and thus abstains from > worshipping any other thing or being. > Having achieved this knowledge of the one true God, man should > constantly have faith in Him, and should allow nothing to induce him > to deny truth. > When faith enters a person's heart, it causes certain mental states > that result in certain actions. Taken together, these mental states > and actions are the proof for the true faith. The Prophet said:" Faith > is that which resides firmly in the heart and which is proved by > deeds". > Foremost among those mental stated is the feeling of gratitude towards > God, which could be said to be the essence of ibada (worship). > The feeling of gratitude is so important that a non-believer is called > 'kafir', which means 'one who denies a truth' and also 'one who is > ungrateful'. > A believer loves, and is grateful to God for the bounties He bestowed > upon him, but being aware of the fact that his good deeds, whether > mental or physical, are far from being commensurate with Divine > favors, he is always anxious lest God should punish him, here or in > the Hereafter. He, therefore, fears Him, surrenders himself to Him and > serves Him with great humility. One cannot be in such a mental state > without being almost all the time mindful of God. Remembering God is > thus the life force of faith, without which it fades and withers > away. > The Qur'an tries to promote this feeling of gratitude by repeating the > attributes of God very frequently. We find most of these attributes > mentioned together in the following verses of the Qur'an:" He is God; > there is no god but He. He is the Knower of the unseen and the > visible; He is the All-Merciful, the All-Compassionate. He is God; > there is no god but He. He is the King, the All-Holy, the All-Peace, > the Guardian of the Faith, the All-Preserver, the All-Mighty, the All- > Compeller, the All-Sublime. Glory be to God, above that they > associate! He is God, the Creator, the Maker, the Shaper. To Him > belong the Names Most Beautiful. All that is in the heavens and the > earth magnifies Him; He is the Almighty, the All-Wise" (59:22-24). > " There is no god but He, the Living, the Everlasting. Slumber seizes > Him not, nor sleep. To Him belongs all that is in the heavens and the > earth. Who is there that shall intercede with Him save by His leave? > He knows what lies before them, and what is after them, and they > comprehend not anything of His knowledge save such as He wills. His > throne comprises the heavens and earth. The preserving of them > oppresses Him not; He is the All-High, the All-Glorious" (2:255). > People of the Book, go not beyond the bounds in your religion, and say > not as to God but the truth. > " The Messiah, Jesus, son of Mary, was only the Messenger of God, and > His Word that He committed to Mary, and a Spirit from Him. So believe > in God and His Messengers, and say not "Three". Refrain; better it is > for you. God is only one God. Glory be to Him - (He is) above having a > son" (4:171). From diffuser78 at gmail.com Wed Nov 14 09:29:39 2007 From: diffuser78 at gmail.com (DanielJohnson) Date: Wed, 14 Nov 2007 14:29:39 -0000 Subject: Creating Installer or Executable in Python Message-ID: <1195050579.054554.145120@22g2000hsm.googlegroups.com> I have a small project which has around 10 .py files and I run this project using command line arguments. I have to distribute this project to somebody. I was wondering how can I make an executable or some kind of installer, so that end user doesn't need to compile and worry if he/ she has Python installed or not ? Every help is greatly appreciated. Thanks, From nicola.larosa at gmail.com Wed Nov 28 05:06:02 2007 From: nicola.larosa at gmail.com (Nicola Larosa (tekNico)) Date: Wed, 28 Nov 2007 02:06:02 -0800 (PST) Subject: Is Ruby 1.9 going to be faster than CPython? Message-ID: <300b0599-082a-42aa-97e7-e95930ad2691@j44g2000hsj.googlegroups.com> Holy Shmoly, Ruby 1.9 smokes Python away! http://antoniocangiano.com/2007/11/28/holy-shmoly-ruby-19-smokes-python-away/ The post is less flaming than the title, fortunately. :-) -- Nicola Larosa - http://www.tekNico.net/ If you have multiple CPUs and you want to use them all, fork off as many processes as you have CPUs. [...] If you really want "true" multi- threading for Python, use Jython or IronPython; the JVM and the CLR do support multi-CPU threads. Of course, be prepared for deadlocks, live-locks, race conditions, and all the other nuisances that come with multi-threaded code. -- Guido van Rossum, July 2007 From urbangabo at gmail.com Thu Nov 15 11:05:17 2007 From: urbangabo at gmail.com (Gabor Urban) Date: Thu, 15 Nov 2007 17:05:17 +0100 Subject: Volume id In-Reply-To: <473C2B2E.8060705@shopzeus.com> References: <473C2B2E.8060705@shopzeus.com> Message-ID: OK, you are right... Problem was not precise enough. I need to process CDs to create a list. Does it ring a bell for you? Thanks 2007/11/15, Laszlo Nagy : > > Gabor Urban wrote: > > Hi, > > > > I have a problem, which may be trivial, but I could not find an answer. > > > > I have to write a Python script, which does a directory tree walking > > on given mounted disk. But I do need to extract the volume id, > > somehow. And that's the problem. An additional issue, the script will > > be used on unix type systems, and on MS XP or Vista, too.... > > > > Any ideas are wellcome. > I believe (although not 100% sure) that "volume id" always belongs to a > FAT partition (maybe an NTFS partition?). When you format a partition, > it will give you a - hopefully unique - volume identifier. I don't think > that unix partitions (like reiserfs, ext2, ext3, ufs2 etc.) has that > identifier. I may be wrong, others will probably correct me. > > Do you want to know the identifier (serial number?) of the disk device > instead? E.g. not the partition but the hard disk? > > Can you list the platforms/operating systems where you want to use your > program? It might help to look at the documentation/source code or the > various hardware diagnostic utilities. > > Best, > > Laszlo > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From paul at subsignal.org Sun Nov 4 13:05:50 2007 From: paul at subsignal.org (paul) Date: Sun, 04 Nov 2007 19:05:50 +0100 Subject: Python good for data mining? In-Reply-To: <1194141739.683498.206780@k79g2000hse.googlegroups.com> References: <1194141739.683498.206780@k79g2000hse.googlegroups.com> Message-ID: Jens schrieb: > What about user interfaces? How easy is it to use Tkinter for > developing a user interface without an IDE? And with an IDE? (which > IDE?) Tkinter is easy but looks ugly (yeah folks, I know it doesn't matter in you mission critical flight control system). Apart from ActiveStates Komodo I'm not aware of any GUI builders. Very likely you don't need one. > > What if I were to use my Python libraries with a web site written in > PHP, Perl or Java - how do I intergrate with Python? How do you "integrate" Perl and PHP? The usual methods are calling external programs (slow) or using some IPC method (socket, xmlrpc, corba). > > I really like Python for a number of reasons, and would like to avoid > Java. Have you looked at jython? cheers Paul From hniksic at xemacs.org Fri Nov 2 05:45:23 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 02 Nov 2007 10:45:23 +0100 Subject: PyCheck for a classes defined in python and user data in PyObject_HEAD References: <1193955251.512135.152720@z9g2000hsf.googlegroups.com> Message-ID: <87y7dhgevg.fsf@mulj.homelinux.net> Note that there is a mailing list dedicated to the Python/C API, http://mail.python.org/mailman/listinfo/capi-sig sndive at gmail.com writes: > issue #2 I'm in a situation when i don't really need to extend > python with any classes of my own but i do have extra luggage for > the python data structures such as tuples, lists, dictionaries, etc > on the c++ side. I see no place in PyObject_HEAD where i can stick a > void* to my extra data. Adding additional luggage is a valid definition of extending. :-) Simply inherit from the desired data structure, and add the pointers you need to the extended structure. If you must add extra data to existing Python objects created by someone else, then you can use a weak dictionary: import weakref _map = {} # can't use WeakKeyDictionary because we need # mapping by identity def set_extra_data(obj, data): # use id(obj) as key to map by object identity ident = id(obj) ref = weakref.ref(obj, lambda x: _map.pop(ident)) _map[ident] = ref, data def extra_data(obj): if id(obj) not in _map: raise TypeError("object has no extra data") ref, data = _map[id(obj)] assert ref() is obj return data From mauriceling at acm.org Sun Nov 18 09:17:42 2007 From: mauriceling at acm.org (Maurice LING) Date: Sun, 18 Nov 2007 14:17:42 GMT Subject: SOAPpy port reuse In-Reply-To: <5qatthFujh89U1@mid.uni-berlin.de> References: <473fa41e$1@news.unimelb.edu.au> <5qatthFujh89U1@mid.uni-berlin.de> Message-ID: <47404983$1@news.unimelb.edu.au> Diez B. Roggisch wrote: > Maurice LING schrieb: >> Hi, >> >> I have a problem: >> >> 1. Assuming that my application is a SOAP server that uses SOAPpy, >> 2. I am given port 35021 for use. >> >> What I normally do (simply) is: >> >> functionlist = [] >> import SOAPpy >> server = SOAPpy.SOAPServer((, 35021)) >> for func in functionlist: server.registerFunction(func) >> server.serve_forever() >> >> My question is: How can I shutdown this server and reuse port 35021 >> when my functionlist changes? >> >> Currently, after killing the python process which runs this SOAP >> server, the port (35021 in this case) cannot be re-used, as though it >> is still phantom-ly bounded to some process (which should have been >> killed). > > It shouldn't be that way. Either you still have some process lying > around hogging the port. Or the OS needs a while to re-enable the port > for allocation. That happened to me quite a few times. > > Shutting down gracefully might speed up things I guess. > I am under the impression that SOAPpy.SOAPServer.serve_forever() is an "endless" loop. I had been suggested to see if there is a method of SOAPpy.SOAPServer (which I can call through a wrapper function in functionlist) that can enable me to gracefully shutdown the server. Any advice? Thanks Maurice From exarkun at divmod.com Fri Nov 9 19:44:32 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Fri, 9 Nov 2007 19:44:32 -0500 Subject: Valgrind and Python In-Reply-To: <86psl3fhr32.fsf@ruuvi.it.helsinki.fi> Message-ID: <20071110004432.8162.173709598.divmod.quotient.33971@ohm> On 10 Nov 2007 02:38:57 +0200, Esa A E Peuha wrote: >Running Python 2.5.1 under Valgrind is interesting; just starting it and >then pressing Ctrl-D produces this: > >==27082== ERROR SUMMARY: 713 errors from 56 contexts (suppressed: 10 from 1) >==27082== malloc/free: in use at exit: 1,243,153 bytes in 508 blocks. >==27082== malloc/free: 3,002 allocs, 2,494 frees, 2,748,487 bytes allocated. >==27082== For counts of detected errors, rerun with: -v >==27082== searching for pointers to 508 not-freed blocks. >==27082== checked 1,399,984 bytes. >==27082== >==27082== LEAK SUMMARY: >==27082== definitely lost: 0 bytes in 0 blocks. >==27082== possibly lost: 17,072 bytes in 58 blocks. >==27082== still reachable: 1,226,081 bytes in 450 blocks. >==27082== suppressed: 0 bytes in 0 blocks. >==27082== Reachable blocks (those to which a pointer was found) are not shown. >==27082== To see them, rerun with: --show-reachable=yes > >A lot of those 713 errors occur in the various deallocation functions. > Did you use the suppression file? Jean-Paul From jura.grozni at gmail.com Sun Nov 4 08:19:25 2007 From: jura.grozni at gmail.com (azrael) Date: Sun, 04 Nov 2007 13:19:25 -0000 Subject: how to keep order key in a dictionary Message-ID: <1194182365.022620.34770@k79g2000hse.googlegroups.com> I 'm currenty working on a project for which it would be great to use a dictionary. At the begining I have a list of strings that should represent the keys in the dictionary. When I try to create a dictionary it rearanges the keys. For this dictionary it is realy important to keep the right order. Is it possible to arange them in a specific order? From gagsl-py2 at yahoo.com.ar Mon Nov 5 02:33:23 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 05 Nov 2007 04:33:23 -0300 Subject: opinion - file.readlines blemish References: <472CB74E.5000708@seehart.com> Message-ID: En Sat, 03 Nov 2007 15:00:46 -0300, Ken Seehart escribi?: > *newlines* > > If Python was built with the *---with-universal-newlines* option to > *configure* (the default) this read-only attribute exists, and for > files opened in universal newline read mode it keeps track of the > types of newlines encountered while reading the file. The values it > can take are |'\r'|, |'\n'|, |'\r\n'|, *None* > (unknown, no newlines read yet) > or a tuple containing all the newline types seen, to indicate that > multiple newline conventions were encountered. For files not opened > in universal newline read mode the value of this attribute will be > *None* . > > > It seems immediately obvious to me that the return value should always > be a tuple, consisting of zero or more strings. If built with universal > newlines, it should return ('\n',) if a newline was found. > > Perhaps there was some blurry contemplation that the None return value > could identify that *universal-newlines* is enabled, but this is blurry > because None could also just mean that no newlines have been read. > Besides, it's not a good idea to stuff extra semantics like that. > Better would be a separate way to identify *universal-newlines *mode. I don't fully understand your concerns. If Python was compiled with universal newlines support, the "newline" attribute exists; if not, it doesn't exist. If it exists, and certain particular file was open with universal newline mode ("rU" by example), None means "no end of line read yet", any other values represent the end-of-line markers already seen. If the file was not opened in universal newline mode, that attribute will always be None. You usually know whether the file was opened in universal newline mode or not, but in any case, you can always look at the "mode" file attribute. As why is not always a tuple, even with 0 or 1 element: I can guess that it's some kind of optimization. Most programs don't even care about this attribute, and most files will contain only one kind of end-of-line markers, so None and a single string would be the most common values. Why build a tuple (it's not free) when it's not needed most of the time? -- Gabriel Genellina From rdm at rcblue.com Sun Nov 18 20:03:35 2007 From: rdm at rcblue.com (Dick Moores) Date: Sun, 18 Nov 2007 17:03:35 -0800 Subject: Help with sympy, please In-Reply-To: <3d0cebfb0711181626u432dbdd3je049093f5343b716@mail.gmail.co m> References: <13k1jg03l3cgdef@corp.supernews.com> <20071119001219.5B7111E4021@bag.python.org> <3d0cebfb0711181626u432dbdd3je049093f5343b716@mail.gmail.com> Message-ID: <20071119010335.D6EE41E43CF@bag.python.org> At 04:26 PM 11/18/2007, Fredrik Johansson wrote: >On Nov 19, 2007 1:05 AM, Dick Moores wrote: >Hi Dick, I recognize you from python-list, where you had a question >about mpmath. > >Your code still won't work if you convert the numbers to Floats >because the Float type in sympy.numerics does not implement ** for >fractional numbers. You could use the exp function in >sympy.numerics.functions instead to compute e**x. Thanks, Fredrik, but I get the same error using either exp or power: ============================ from __future__ import division from sympy import * from sympy import Rational as R from sympy.numerics import * from sympy.numerics.functions import power, exp prec = 50 Float.setdps(prec) e = evalf(E) n = 1 m = n + 1 k = 0 n = evalf(R(n,1)) m = evalf(R(m,1)) prod = evalf(R(1,1)) prec = 50 Float.setdps(prec) e = evalf(E) n = 1 k = 0 prod = evalf(R(1,1)) while k < 1000: k += 1 n = evalf(R(n,1)) term = (exp(1/n))/(exp(1/(n+1))) prod *= term n += 2 print prod, term ============================= term = (exp(1/n))/(exp(1/(n+1))) TypeError: unsupported operand type(s) for /: 'int' and 'Float' And also if I use sympy.numerics.functions.power in that line, as term = power(e,(1/n))/power(e,(1/(n+1))) I get: term = power(e,(1/n))/power(e,(1/(n+1))) TypeError: unsupported operand type(s) for /: 'int' and 'Float' Dick From dannox at gmail.com Thu Nov 29 05:50:37 2007 From: dannox at gmail.com (whatazor) Date: Thu, 29 Nov 2007 02:50:37 -0800 (PST) Subject: wxPython and Tkinter Message-ID: <0be0b410-c53b-4b1a-9a30-1c9e76faae61@g30g2000hsb.googlegroups.com> Hi all, I migrate some code from tkinter to wxpython. I need the equivalent Tkinter method Tkinter.Tk.after in wxPython, but I'm not able to find it. It exist or there are other trick to emulate it? thank you w From greg at cosc.canterbury.ac.nz Mon Nov 26 03:37:19 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Mon, 26 Nov 2007 21:37:19 +1300 Subject: How to Teach Python "Variables" In-Reply-To: <4749bb94$1@news.bezeqint.net> References: <4749bb94$1@news.bezeqint.net> Message-ID: <5qvf6pF122r3mU1@mid.individual.net> none wrote: > IIRC, I once saw an explanation how Python doesn't have "variables" > in the sense that, say, C does, and instead has bindings from names to > objects. If you're talking to C programmers, just tell them that Python variables always contain pointers. That should give them the right mental model to build on. -- Greg From grante at visi.com Thu Nov 29 16:11:02 2007 From: grante at visi.com (Grant Edwards) Date: Thu, 29 Nov 2007 21:11:02 -0000 Subject: How to Split a String References: <0b724d25-24ea-41ba-b084-a8d59a9558b8@w40g2000hsb.googlegroups.com> <5iF3j.187077$U01.1250481@twister1.libero.it> <13kuaflbo02dg8d@corp.supernews.com> Message-ID: <13kuan6ah7g1n4d@corp.supernews.com> On 2007-11-29, Grant Edwards wrote: >> One solution: >> >> >>> s = '(a, b, "c", d, "e")' >> >>> print [x.strip('" ') for x in s.strip('()').split(',')] >> ['a', 'b', 'c', 'd', 'e'] > > That fails when a quoted string contains commas: > >>>> s = '(a, b, "c", d, "e,f,g")' >>>> print [x.strip('" ') for x in s.strip('()').split(',')] > ['a', 'b', 'c', 'd', 'e', 'f', 'g'] > > I presume the correct result would be > > ['a', 'b', 'c', 'd', 'e,f,g'] You can get that result easily with the csv module: >>> repr(ss) '\'a,b,"c",d,"e,f,g"\'' >>> for row in csv.reader([ss],skipinitialspace=True): ... print row ... ['a', 'b', 'c', 'd', 'e,f,g'] -- Grant Edwards grante Yow! I'm not available at for comment.. visi.com From hall.jeff at gmail.com Tue Nov 27 13:37:19 2007 From: hall.jeff at gmail.com (hall.jeff at gmail.com) Date: Tue, 27 Nov 2007 10:37:19 -0800 (PST) Subject: Pulling data from a .asps site Message-ID: There's a government website which shows public data for banks. We'd like to pull the data down programmatically but the data is "hidden" behind .aspx... Is there anyway in Python to hook in directly to a browser (firefox or IE) to do the following... 1) Fill the search criteria 2) Press the "Search" button 3) Press another button (the CSV button) on the resulting page 4) Then grab the data out of the notepad file that pops up If this is a wild good chase, let me know... (or if there's a better way besides Python... I may have to explore writing a firefox plug-in or something)... From kyosohma at gmail.com Tue Nov 27 16:45:42 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 27 Nov 2007 13:45:42 -0800 (PST) Subject: string conversion latin2 to ascii References: Message-ID: <882b8d30-84d7-4ba0-ab8a-699a40a6ab40@y43g2000hsy.googlegroups.com> On Nov 27, 3:35 pm, Martin Landa wrote: > Hi all, > > sorry for a newbie question. I have unicode string (or better say > latin2 encoding) containing non-ascii characters, e.g. > > s = "Uk?zka_mo?nosti_vyu?it?_programu_OpenJUMP_v_SOA" > > I would like to convert this string to plain ascii (using some lookup > table for latin2) > > to get > > -> Ukazka_moznosti_vyuziti_programu_OpenJUMP_v_SOA > > Thanks for any hits! Regards, Martin Landa With a little googling, I found this: http://www.peterbe.com/plog/unicode-to-ascii You might also find this article useful: http://www.reportlab.com/i18n/python_unicode_tutorial.html Mike From vladimir at greenmice.info Tue Nov 27 04:13:48 2007 From: vladimir at greenmice.info (Vladimir Rusinov) Date: Tue, 27 Nov 2007 12:13:48 +0300 Subject: Rss Feed Creator In-Reply-To: <8a6b8e350711261645p1b41b0e0rda70204462e1a8b9@mail.gmail.com> References: <8a6b8e350711261645p1b41b0e0rda70204462e1a8b9@mail.gmail.com> Message-ID: On 11/27/07, James Matthews wrote: > > I am looking for a library that will create Rss/Atom feeds in python. It > needs to format the XML in a readable format! Does anyone have any > suggestions? You can also use some xml-based template engine (Kid or Genshi). -- Vladimir Rusinov GreenMice Solutions: IT-??????? ?? ???? Linux http://greenmice.info/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From kyosuke at kimagure.cz Wed Nov 7 04:13:14 2007 From: kyosuke at kimagure.cz (Jakub Hegenbart) Date: Wed, 07 Nov 2007 10:13:14 +0100 Subject: Strange behavior of __get__ in a descriptor in IPython Message-ID: Hi, I'm studying the descriptor protocol and its usage from the following document: http://users.rcn.com/python/download/Descriptor.htm There is some sample code: http://users.rcn.com/python/download/Descriptor.htm#descriptor-example that behaves in a different way on my machine than the example suggests: In [2]: a=MyClass() In [3]: a.x Retrieving var "x" Retrieving var "x" Out[3]: 1 On the other hand, in the 'plain' Python shell, it's invoked only once as expected: >>> a=desc.MyClass() >>> a.x Retrieving var "x" 10 >>> Should I take as granted that IPython might in some cases access an attribute of an object more than once even in face of side effects, or is this a bug? Regards, Jakub Hegenbart From paddy3118 at googlemail.com Mon Nov 26 02:33:16 2007 From: paddy3118 at googlemail.com (Paddy) Date: Sun, 25 Nov 2007 23:33:16 -0800 (PST) Subject: basic if stuff- testing ranges References: Message-ID: On Nov 25, 6:49 pm, Donn Ingle wrote: > Sheesh, I've been going spare trying to find how to do this short-hand: > if 0 > x < 20: print "within" > > So that x must be > 0 and < 20. > > I usually do: > if x > 0 and x < 20: print "within" > > What's the rule? Does it even exist? > I read something like it recently on the list but can't find it, that's > where I got the urge to try it from. I can't find anything in the docs, but > then again (imho) the Python docs are like a tangled jungle... > > \d The output of the following program might help: # chained_comparisons.py complist = '< <= == != >= >'.split() for lhs in complist: for rhs in complist: print "\n1 %2s x %2s 3:" % (lhs, rhs) for x in range(5): chain = " 1 %2s %i %2s 3" % (lhs, x, rhs) print chain," is ", eval(chain) - Paddy. From sarup26 at gmail.com Thu Nov 1 02:54:28 2007 From: sarup26 at gmail.com (sarup26 at gmail.com) Date: Wed, 31 Oct 2007 23:54:28 -0700 Subject: What is Jython? Message-ID: <1193900068.263686.174020@v23g2000prn.googlegroups.com> Hello .. I would like to know more about Python and Jython? What is the difference between both of them? What is the future for Jython and which are the areas where it is used? Swot From sipickles at hotmail.com Sat Nov 3 10:11:05 2007 From: sipickles at hotmail.com (Simon Pickles) Date: Sat, 03 Nov 2007 14:11:05 +0000 Subject: Python IDE Message-ID: <472C8179.3020506@hotmail.com> Hi, I have recently moved from Windows XP to Ubuntu Gutsy. I need a Python IDE and debugger, but have yet to find one as good as Pyscripter for Windows. Can anyone recommend anything? What are you all using? Coming from a Visual Studio background, editing text files and using the terminal to execute them offends my sensibilities :) Thanks Si From vinay_sajip at yahoo.co.uk Thu Nov 22 09:44:27 2007 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Thu, 22 Nov 2007 06:44:27 -0800 (PST) Subject: logging and propagation References: <7eef67e0-36a7-48b6-9137-0b10ea37ac3c@f3g2000hsg.googlegroups.com> <78583738-b488-4a24-a48e-1e0eab84ae6b@e6g2000prf.googlegroups.com> <59d17954-0af8-4a4c-b007-ff892d9b0181@o42g2000hsc.googlegroups.com> Message-ID: <8b077b42-fb1d-414f-afce-d236f46cfe1e@e6g2000prf.googlegroups.com> On Nov 22, 2:34 pm, Vinay Sajip wrote: > On Nov 22, 9:18 am, oj wrote: > > Why not apply the same filter to the parent loggers? Of course, you can apply filters at the loggers or the handlers. The filters at the logger are checked first. If they pass, then the event is handled - and filters at the handlers get to participate. From tjreedy at udel.edu Sat Nov 10 01:09:09 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 10 Nov 2007 01:09:09 -0500 Subject: Valgrind and Python References: <86psl3fhr32.fsf@ruuvi.it.helsinki.fi> Message-ID: | | does that mean that python's interpretor is a memory beast? No. The developers have occasionally run Valgrind on Python (or seen the results of so doing). I believe they have determined that it gives spurious messages due to some particular features of its coding style or standards. See JPC's message. From davisn90210 at gmail.com Thu Nov 8 14:07:35 2007 From: davisn90210 at gmail.com (davisn90210 at gmail.com) Date: Thu, 08 Nov 2007 19:07:35 -0000 Subject: spawn background process and detach it w/o problems In-Reply-To: References: Message-ID: <1194548855.128422.163120@i13g2000prf.googlegroups.com> On Nov 8, 8:09 am, "Dmitry Teslenko" wrote: > Hello! > How to write portable (win32, unix) script that launches another > program and continues its execution? > > I've looked at spawn*() but it doesn't look in PATH dirs on windows so > it's totally unusable when you don't know where exactly program is. > > I've looked at fork() way but there's no fork for windows. > > My current solution is > thread.start_new(os.system, (,)) > > It's ugly and there's one big unpleasant pecularity: > in case there were any os.chdir()-s between beginning of script > execution and that thread.start_new() then new thread starts in > original directory. Not in current directory at moment of > thread.start_new() Take a look at the subprocess module. From martin at v.loewis.de Fri Nov 30 01:58:53 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 30 Nov 2007 07:58:53 +0100 Subject: Using marshal to manually "import" a python module In-Reply-To: References: Message-ID: <474fb4ad$0$13138$9b622d9e@news.freenet.de> > The strange thing is, it worked fine locally on my two machines (32bit > running python 2.3.5 and 64bit running python 2.4.1), but when run by a > 64bit machine on the network, it would fail every time in the following > manner: It may not that much be an issue of 32-bit vs. 64-bit, but of Python 2.3 vs. Python 2.4. The marshal format changes across versions, and files created in one version might not be understood correctly by another version. Now, you don't give enough details on resolving this completely: what specific microprocessors, and what specific operating systems are you using? What is the specific code of the module that fails to load (e.g. minimal example), and what is the resulting byte code? Off-hand, I can't see why a 2.3-generated file shouldn't be loadable by a 2.4 interpreter, but you say "it" fails without saying what "it" is (i.e. running the 64-bit machine to generate a marshal file over the net that is then read by the 32-bit machine, or vice versa). > I can't figure out why this would work locally, but not when the module > is loaded across a network. In fact, I have no idea what would ever > cause it not to see A as a function. I'm stumped, and this is over my > head as far as intimate knowledge of the direct loading of python > bytecode via marshal is concerned...so I'm not clear on the best way to > debug it. I would trace through the loading, either in a debugger, or by adding printf statements into marshal. Regards, Martin From deets at nospam.web.de Thu Nov 15 17:25:07 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 15 Nov 2007 23:25:07 +0100 Subject: Python Design Patterns - composition vs. inheritance In-Reply-To: <63c98d5d-b65f-4a9c-a17c-d25e20afec49@w28g2000hsf.googlegroups.com> References: <5q3p0uFu0notU1@mid.uni-berlin.de> <63c98d5d-b65f-4a9c-a17c-d25e20afec49@w28g2000hsf.googlegroups.com> Message-ID: <5q3vb4Fu6fovU1@mid.uni-berlin.de> > I think my main concern while getting my toes wet on this was to not > reference the owner object out of "thin air" but to pass it in when > pet is instantiated. I'm not sure what 'actor-passed' is yet, but it > gives me something to search for and learn about. I meant ctor, short-hand for constructor. > I'd love to see other/better/different implementations if anyone wants > to enlighten me. What would a non-unidirectional (bidirectional?) look > like or accomplish? Does that mean that in the example I provided, you > could make the owner aware of their pets? That's something that is not > available using inheritance, if I understand correctly. Its simple. class Owner(object): def __init__(self): self.pets = [] class Pet(object): def __init__(self, owner): self.owner = owner owner.pets.append(self) >> No, that's certainly not a good idea. And I'm under the impression you >> misunderstood something there in the original lecture/explanation. > > That wouldn't surprise me if I misunderstood it :) I've watched Alex > Martelli's Google Tech talk a half-dozen times and it's only now > starting to make sense. It's hard to apply some of the available > material's examples to Python since a lot of the documentation I find > is specific to implementations in lower-level languages and don't > apply to Python. (such as the Strategy pattern?) > > My understanding was that using __getattr__ was either called > delegation or a Command pattern, and this was hiding/encapsulating the > specifics of the implementation. I'd like to be corrected if I'm > wrong, or if I'm two blocks off Main Street with this. I don't know that talk. Maybe you can give us the link, so we can see for ourselves? There is no doubt about Alex' being a profound teacher of software design. But yet I think your example doesn't capture what you think he wanted to present. Delegation of course is a well-known pattern. It applies at circumstances that are manyfold, e.g. wehn you try create a proxy for purposes of tracking or filtering calls. Diez From __peter__ at web.de Tue Nov 20 04:10:53 2007 From: __peter__ at web.de (Peter Otten) Date: Tue, 20 Nov 2007 10:10:53 +0100 Subject: Tkinter Problem? References: <5qffeiFvh912U2@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch wrote: > On Mon, 19 Nov 2007 18:13:03 -0800, Davy wrote: > >> ##---------------------- >> from Tkinter import * >> >> class MyApp: >> def __init__(self,parent): >> self.myContainer1 = Frame(parent) >> self.myContainer1.pack() >> self.canv = Canvas(relief=SUNKEN) >> self.canv.config(width = 300,height=300) >> self.canv.pack() >> self.canv.create_rectangle(100,100,150,150,tags="rect") >> self.canv.bind('',self._onUpKey) >> self.canv.bind('', self._onReturnKey) >> def _onUpKey(self,event): >> self.canv.move(tagOrId,xAmount=0,yAmount=10) > > Where's `tagOrId` coming from? That's a `NameError` here. Also, the arguments of Canvas.move() are positional. self.canv.move("rect", 0, 10) should work though the direction of the move might surprise you. Peter From devnew at gmail.com Thu Nov 1 14:24:08 2007 From: devnew at gmail.com (devnew at gmail.com) Date: 1 Nov 2007 11:24:08 -0700 Subject: setting and getting column in numpymatrix Message-ID: <1193900514.375423.129150@q5g2000prf.googlegroups.com> hi i am looking for an efficient way to get a specific column of a numpy.matrix .. also i want to set a column of the matrix with a given set of values ..i couldn't find any methods for this in matrix doc..do i have to write the functions from scratch? TIA dn From martin at v.loewis.de Mon Nov 26 17:18:55 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 26 Nov 2007 23:18:55 +0100 Subject: Installing Python 3000 In-Reply-To: <4a065db6-fb65-4862-9a2a-8afe77f76fe8@d21g2000prf.googlegroups.com> References: <4a065db6-fb65-4862-9a2a-8afe77f76fe8@d21g2000prf.googlegroups.com> Message-ID: <474B464F.1090002@v.loewis.de> > I'd like to install Python 3000 on my computers (Mac, and possibly > Windows), without messing up the existing versions. So far, I've > always relied on using ".msi" on Windows and ".dmg" on the Mac. > > From the Python site, I read (different version, but still...): > ---- > Unpack the archive with tar -zxvf Python-2.4.4.tgz ... Change to the > Python-2.4.4 directory and run the "./configure", "make", "make > install" commands to compile and install Python. > ---- > The step that gets me worried is the "make install" one... I don't > want it to take over as default. I would like to be able to invoke it > by typing "python3k ..." from anywhere and have it work - while still > having "python" invoke the default 2.5 version. I recommend that you then do use the prebuilt binaries, at least where available, i.e. http://www.python.org/download/releases/3.0/ For OSX, I recommend to use a different --prefix for installing, e.g. /usr/local/py3k. All files then go into that directory, and nothing else lives in it. To invoke it, you give /usr/local/py3k/bin/python; if you want to make a python3k link someone in your path - that would be your choice. HTH, Martin From steven at REMOVE.THIS.cybersource.com.au Tue Nov 27 04:12:28 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Tue, 27 Nov 2007 09:12:28 -0000 Subject: Why are class methods not classmethods? Message-ID: There's some subtle behaviour going on here that I don't really follow. Class methods apparently aren't classmethods. >>> class Parrot(object): ... def method(self, *args): ... return self, args ... @classmethod ... def cmethod(cls, *args): ... return cls, args ... >>> type(parrot.method) # as expected >>> type(parrot.cmethod) # I don't expect this result >>> type(classmethod(parrot.method)) >>> >>> parrot.cm = classmethod(parrot.method) >>> type(parrot.cm) # I expect this >>> >>> Parrot.CM = classmethod(parrot.method) >>> type(Parrot.CM) # but not this Can anyone explain why class methods bound to a class are instancemethods rather than classmethods? -- Steven. From mbac at gpshopper.com Sun Nov 11 11:25:15 2007 From: mbac at gpshopper.com (Michael Bacarella) Date: Sun, 11 Nov 2007 08:25:15 -0800 (PST) Subject: Populating a dictionary, fast Message-ID: <75007.96469.qm@web901.biz.mail.mud.yahoo.com> Firstly, thank you for all of your help so far, I really appreciate it. > > So, you think the Python's dict implementation degrades towards O(N) > > performance when it's fed millions of 64-bit pseudo-random longs? > > No. Yes. I tried your code (with one change, time on feedback lines) and got the same terrible performance against my data set. $ cat stevescode.py #!/usr/bin/python """Read a big file into a dict.""" import gc import time print "Starting at %s" % time.asctime() flag = gc.isenabled() gc.disable() id2name = {} for n, line in enumerate(open('id2name.txt', 'r')): if n % 1000000 == 0: # Give feedback. print "Line %d" % n,time.asctime() id,name = line.strip().split(':', 1) id = long(id) id2name[id] = name print "Items in dict:", len(id2name) print "Completed import at %s" % time.asctime() print "Starting to delete dict..." del id2name print "Completed deletion at %s" % time.asctime() if flag: gc.enable() print "Finishing at %s" % time.asctime() $ ./stevescode.py Starting at Sun Nov 11 10:46:37 2007 Line 0 Sun Nov 11 10:46:37 2007 Line 1000000 Sun Nov 11 10:48:22 2007 Line 2000000 Sun Nov 11 10:51:08 2007 Line 3000000 Sun Nov 11 10:56:16 2007 Line 4000000 Sun Nov 11 10:58:41 2007 Line 5000000 Sun Nov 11 11:03:26 2007 ^C To prove that my machine is sane, I ran the same against your generated sample file and got _excellent_ performance. Start to finish in under a minute. $ cat steves-makedict.py #!/usr/bin/python """Make a big file of 64-bit integer keys plus random values.""" bits64 = 2**64 import random template = '%d:This is a bunch of text...\n' fp = open('id2name.txt', 'w') for i in xrange(8191180): fp.write(template % random.randint(0, bits64)) fp.close() $ ./steves-makedict.py $ ./stevescode.py Starting at Sun Nov 11 11:15:31 2007 Line 0 Sun Nov 11 11:15:31 2007 Line 1000000 Sun Nov 11 11:15:37 2007 Line 2000000 Sun Nov 11 11:15:43 2007 Line 3000000 Sun Nov 11 11:15:49 2007 Line 4000000 Sun Nov 11 11:15:54 2007 Line 5000000 Sun Nov 11 11:16:00 2007 Line 6000000 Sun Nov 11 11:16:07 2007 Line 7000000 Sun Nov 11 11:16:12 2007 Line 8000000 Sun Nov 11 11:16:18 2007 Items in dict: 8191180 Completed import at Sun Nov 11 11:16:19 2007 Starting to delete dict... Completed deletion at Sun Nov 11 11:16:23 2007 Finishing at Sun Nov 11 11:16:23 2007 > Notice that the dict is completely read into memory in just two and a > half minutes. The script then tries to delete the dict, and 32 minutes > later is still struggling. That's the point I got sick of waiting and > interrupted the script. > > Conclusion: it's a memory issue, or maybe a garbage collection issue, not > a problem with dicts. As you can see, not the case at all against my data set. > (1) Presumably you don't want to run your app with the garbage collector > turned off. You might still want to play around with the gc module to see > what you can learn. As you can see, your version did no better. :( > (2) More memory will help avoid paging. If you can't get more memory, try > more virtual memory. It will still be slow, but at least the operating > system doesn't have to try moving blocks around as much. The machine has 8GB, and is not doing anything else when I run this. > (3) Are you sure you need all eight-million-plus items in the cache all > at once? Yes. > (4) There are lots of algorithms out there for dealing with data too big > to fit into main memory. Do some research. It DOES fit into main memory and a dictionary is exactly the right way to do this. > (5) There is a data structure designed for dealing with tens of millions > of records at once. It is called "a database". If you can't find a better > algorithm, and refuse to use an existing RDBMS, I suspect you're going to > end up inventing a primitive, inefficient, buggy database which is no > faster than existing systems out there. I've tried three disk-based implementations already (BerkeleyDB, cdb, and an RDBMS) Performance is terrible because they end up doing too many random disk seeks. Pre-caching all of the data ahead of time has offered us the best performance so far, but is still slower than it ought to be. Creating a HEAP TABLE in the RDBMS is an idea, but moving all of this really easy code into the RDBMS just to find a hashing algorithm that doesn't choke on my keys sounds pretty lame. A cached in main memory hash is the right way to do this. The Perl version runs *very* fast, after all. From tarundevnani at gmail.com Thu Nov 22 01:45:05 2007 From: tarundevnani at gmail.com (tarun) Date: Thu, 22 Nov 2007 12:15:05 +0530 Subject: Issue with reading and writing into .ini files using python Message-ID: Hello, I am using config approach as mentioned in the below link to read and write into setup (.ini) files: http://www.voidspace.org.uk/python/configobj.html I've a key named 'SELECTED' in my .ini file. Sometimes I get the following error on trying to read the .ini file: val = dict.__getitem__(self, key) KeyError: 'SELECTED' Can anyone help. Thanks in advance Regards, Tarun -------------- next part -------------- An HTML attachment was scrubbed... URL: From mhearne808 at gmail.com Fri Nov 9 18:56:16 2007 From: mhearne808 at gmail.com (mhearne808[insert-at-sign-here]gmail[insert-dot-here]com) Date: Fri, 09 Nov 2007 23:56:16 -0000 Subject: Creating installer with external extension modules Message-ID: <1194652576.266935.134910@v2g2000hsf.googlegroups.com> I'm creating a piece of software which will be used by in-house users. My code will all be written in pure Python; however, it depends heavily on a number of third-party Python modules, many of which have C/C++ dependencies (numpy, scipy, etc.) Installing these packages on my machine involved a morning of several serial "./ configure;make;sudo make install" steps. I'd prefer to automate all of this for my users, but I'm not clear how to do this - I'm in an environment of mixed Mac (desktops) and Linux (servers) and I'll need to install on both platforms, and would prefer not to run around to each computer making sure the dependencies are met. I've looked through the documentation for distutils and setuptools, and it's not obvious to me that there are hooks in either one for passing in configure and make calls. The fallback, I suppose, presuming that the correct version of Python is already installed, is to write a custom Python script that "knows" about each dependency, and takes the appropriate action. I should be able to depend on everyone having gcc and make installed, I think. Does anyone have any suggestions on the best way to approach this? Thanks, Mike From python.list at tim.thechases.com Mon Nov 12 10:51:20 2007 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 12 Nov 2007 09:51:20 -0600 Subject: regex that is equivalent to perl's syntax In-Reply-To: <1194881937.166971.228390@19g2000hsx.googlegroups.com> References: <1194881937.166971.228390@19g2000hsx.googlegroups.com> Message-ID: <47387678.40808@tim.thechases.com> > does python's re library have a similar capability of the perls > regular expression to > search for pattern that appears a variable number of times within the > lower and upper bounds given? For example, what is the python's > equivalent to the following perl's search string? > m/^\S{1,8}\.\S{0,3}/ > which seeks to find all strings with 8 characters followed by a dot > and then three more characters as in filename.txt > > Actually, i need to find a pattern such as ABCDXLMNO with the > character X > repeated 5 to 8 times. You're interested in the "re" library, documented here[1] which, astonishingly, is the first result when I google for python re library In your particular case, the syntax is identical to perl regexps[2] (the 2nd hit Google returns with the above query) import re r1 = re.compile(r'\S{1,8}\.\S{0,3}') r2 = re.compile(r'ABCDX{5,8}LMNO') # use r1/r2 for matching, substitution, taking over the world Note the use of "raw" strings (doesn't matter so much in the 2nd version, as there's nothing escaped), as suggested in the docs. -tkc [1] http://docs.python.org/lib/module-re.html [2] http://docs.python.org/lib/re-syntax.html From jeffober at gmail.com Mon Nov 5 08:14:12 2007 From: jeffober at gmail.com (Jeff) Date: Mon, 05 Nov 2007 05:14:12 -0800 Subject: how does google search in phrase In-Reply-To: <1194267563.593888.109930@o80g2000hse.googlegroups.com> References: <1194178870.569742.181240@z9g2000hsf.googlegroups.com> <1194267563.593888.109930@o80g2000hse.googlegroups.com> Message-ID: <1194268452.805537.298900@k79g2000hse.googlegroups.com> Here is a detailed explanation: http://www.google.com/technology/pigeonrank.html From miked at xtalwind.net Sun Nov 11 11:54:01 2007 From: miked at xtalwind.net (miked) Date: Sun, 11 Nov 2007 11:54:01 -0500 Subject: "No backend servers available" using httplib Message-ID: <000301c82483$77b2ee70$46f2a0cd@pavilion> i am trying to access printing templates from avery.com and i get a message from the nsapi plugin:no backend server available.can you help me? From daniel.haus at gmail.com Fri Nov 30 05:53:59 2007 From: daniel.haus at gmail.com (Daniel Haus) Date: Fri, 30 Nov 2007 02:53:59 -0800 (PST) Subject: Announcing Apydia Message-ID: <7d161b4a-eb20-417a-a446-9bf285aaa3d3@t47g2000hsc.googlegroups.com> Today, I am very excited to announce the first release of the Apydia API reference documentation generator for Python. It's designed as an instantly serviceable replacement for Pudge's API documentation generator. It won't generate complete websites from reST etc. like Pudge does, though - Apydia is only about the API. Features include: - Basic Pudge compatibility and a short and easy migration path - Rudimentary Trac-integration, that is links into Trac's sourcecode browser - Some fair amount of usability - Setuptools integration - Flexible, Genshi/XInclude-based themeability with theme inheritance - Support for various text formats like Markdown, Textile and reST - Other parsers can easily be plugged in on demand - Syntax highlighting thanks to Pygments For more information visit Apydia's web site at http://apydia.ematia.de and the Apydia Google Group at http://groups.google.com/group/apydia. -- Daniel Haus http://ematia.de From bj_666 at gmx.net Fri Nov 16 09:55:58 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 16 Nov 2007 14:55:58 GMT Subject: list of class initiations ? References: Message-ID: <5q5pbuFu5fr3U1@mid.uni-berlin.de> On Fri, 16 Nov 2007 13:20:59 +0100, stef mientki wrote: > Is there a way to create a hierarchical list of class headers, including > the parameters. > What I mean (I'm not a programmer) is something like this: > > > class Block ( t_BaseShape ): (self, Pos = [10,10] ): > class t_BaseShape(Shape): (self, x=20, y=20, x2=90, y2=90, > type='rect' ): > class Shape(ShapeEvtHandler): (self, x=[], y=[]): > class ShapeEvtHandler: () Take a look at the `inspect` module. Should be possible to build something with those functions. Ciao, Marc 'BlackJack' Rintsch From russandheather at gmail.com Sun Nov 11 16:31:12 2007 From: russandheather at gmail.com (Russell Warren) Date: Sun, 11 Nov 2007 13:31:12 -0800 Subject: Looking for a good Python environment In-Reply-To: <7xbqa6f192.fsf@ruckus.brouhaha.com> References: <1194389774.159051.55580@19g2000hsx.googlegroups.com> <1194434140.836932.10670@k79g2000hse.googlegroups.com> <7xbqa6f192.fsf@ruckus.brouhaha.com> Message-ID: <1194816672.311766.80070@v3g2000hsg.googlegroups.com> > While we're at it, do any of these debuggers implement a good way to > debug multi-threaded Python programs? Wing now has multi-threaded debugging. I'm a big Wing (pro) fan. To be fair, when I undertook my huge IDE evaluation undertaking it was approx 2 years ago... at the time as far as what I would consider to be a full featured professional IDE it was IMO really only Wing and Komodo who could compete. The others were left in the dust. Unfortunately both cost money, but it became clear that at least in this instance you get what you pay for. Not a big deal for me because as far as professional development costs the cost is ridiculously low and I use it professionally, but I could see balking at the cost if strictly a hobbiest... although I would pay as I'd be lost without my Wing I think. At the time, I much preferred Wing to Komodo, but haven't tried Komodo more than sparingly since then. My bet is that the situation would still be similar since Wing has done nothing but get better over time. The support crew at Wing are great, too... the mailing list is excellent and the Wing developers typically respond very quickly to any support requests, and even feature requests (I've had a few things added due to the mailing list). The biggest missing feature in Wing at the moment is integrating GUI development. If you are into that, you may want to look elsewhere. Any GUI stuff I do I use wxPython and after starting with a template builder I just manually code the GUIs... painful at times, especially when you just want to whip up something small, but I've gotten used to it. Now that I type this, though, I think I'll go looking for what's new! Maybe Boa is less buggy now? Hmm. Prior to taking on my "find the ultimate IDE" quest I was using SPE and it was free and quite decent, just not comparable to Wing. http://pythonide.stani.be/ A quick look at the current state of SPE shows that it now has multi- threaded debugging via WinPDB (what I used to use for debugging thread issues). Interesting. Worth a look to see if it is integrated well. From supercooper at gmail.com Thu Nov 29 11:24:52 2007 From: supercooper at gmail.com (supercooper) Date: Thu, 29 Nov 2007 08:24:52 -0800 (PST) Subject: looking for ocbc example References: <1190371280.070392.55700@22g2000hsm.googlegroups.com> Message-ID: <2ae1f78b-f474-4023-ae90-ad73bf3b76e0@s36g2000prg.googlegroups.com> On Nov 28, 2:43 am, Tim Golden wrote: > Carl K wrote: > > jay graves wrote: > >> On Sep 21, 2:43 am, Tim Golden wrote: > >>> Carl K wrote: > >>>> It seems there are 2 odbc modules - pyOdbc and mxOdbc - anyone know the difference? > >>> In short, pyodbc is open source; mxOdbc requires a commercial license. > >>> pyodbc is a newcomer, but appears to work for everything I've thrown > >>> at it (which is not much). mxOdbc has been around longer, and is sure > >>> to be a more mature product. It may offer more features & functionality. > >> There is also a brand new module 'ceODBC'. > >>http://ceodbc.sourceforge.net/ > > >> I haven't used it yet but I want to give it a try. > > > I tried it, and it worked better than pyodbc. (better is not exactly right. > > there was some weird bug in the ctree odbc driver, and the author of ceODBC gave > > me a workaround.) > > All right, I'm a little perplexed as to whether "better" here > refers to the admirable response of the ceOBDC author or to > some other factors which demonstrate ceODBC's superiority. > > I've not really got the opportunity to pit them against each > other so to speak, but I'd love to hear from someone who had. > > TJ Just tried ceODBC the other day (on XP), and it worked like a charm connecting SqlServer and DB2. Here's SqlServer: >>> import ceODBC >>> db=ceODBC.connect('DSN=Wells') >>> c=db.cursor() >>> c.execute('select wellname, latitudedecimal, longitudedecimal from dbo.wells where wellid in (11587,11194,11157)') >>> for each in c.fetchall(): ... print each ... ('GILL #1-18', 33.095599, -92.38563) ('HOW #2-7', 35.10155, -91.48824) ('JKK #11-13', 34.09130, -93.45256) Simple! Very similar syntax to mxODBC. From arkanes at gmail.com Mon Nov 26 14:43:50 2007 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 26 Nov 2007 13:43:50 -0600 Subject: How to Teach Python "Variables" In-Reply-To: <7c2eaf31-9549-4f13-83c6-5f41149b5005@j44g2000hsj.googlegroups.com> References: <4749bb94$1@news.bezeqint.net> <5qvf6pF122r3mU1@mid.individual.net> <87abp1qqth.fsf@mulj.homelinux.net> <7c2eaf31-9549-4f13-83c6-5f41149b5005@j44g2000hsj.googlegroups.com> Message-ID: <4866bea60711261143j67ae758fna6f9f809d6515e6d@mail.gmail.com> On Nov 26, 2007 1:21 PM, davisn90210 at gmail.com wrote: > Hrvoje Niksic wrote: > > greg writes: > > > > > none wrote: > > >> IIRC, I once saw an explanation how Python doesn't have > > >> "variables" in the sense that, say, C does, and instead has bindings > > >> from names to objects. > > > > > IMHO, this is nonsense. All that variables are (in any language) are > "bindings" for names. Pretending python does anything novel with > regard to "variables" is confusing and, ultimately, simply results in > a redefinition of terms programmers are already familiar with. I > mean, it's kind of like saying my computer is not a computer but is > actually a device that follows input directions. Of course that > description may be true (and I may even use it to explain to students > *what* a computer is), but it is no less a computer for it. > Long real-life experience that people with previous programming experience, especially C programmers, have a great deal of trouble with this concept. Python "variables" do not work the way they do in other languages, where variables are compile-time bindings for memory locations. Even Java references aren't the same (there's no such thing as a null reference in Python, for example). > > > If you're talking to C programmers, just tell them that Python > > > variables always contain pointers. That should give them the right > > > mental model to build on. > > > > That is a convenient shortcut when it works, but in my experience it > > tends to confuse the issue. The reason is that one of the main uses > > of pointers in C is implementing pass-by-reference. A C programmer > > told that Python variables internally hold pointers expects this code: > > > > I think most C programmers are smart enough to figure out the supposed > differences, with only a little additional explanation on the part of > the instructor. Python's "variable model" is practically identical to > that of Java, after all, and I don't recall any discussion of > cataclysmic proportions over the differences between C "pointers" and > Java "references". There are "differences" (or more accurately > "points of emphasis"), but of the sort that take a paragraph or two of > explanation/clarification -- not a completely new model. > C programmers, when told that Python works like this almost *always* get this wrong, because they want to pretend that Python is C-like pass by reference and it isn't. The very first thing they want to do is to get at "the pointer" underneath the object so they can simulate C style pass by reference with ints. It takes a lot of bandwidth (both mental and electronic) before they get that there is no underlying pointer and they can't do this. The second thing they want to do is to intercept rebinding actions, like you might do in C++ with operator overloads. If you explain it to them in these terms, it is not clear (and will not be, until you use other terms) that rebinding a name (assignment) and mutating an object are fundamentally different operations. I see these questions on a daily basis in #python and somewhat less frequently in c.l.p. Your assertion that C programmers will "just get it" if it's explained in those terms is simply not borne out by real world results. One thing that C programmers *do* get, at least the smarter ones, is explaining it in terms of the actual implementation - that there are PyObject structs that are not exposed, that they are refcounted, and that name/object bindings are entries in various hash tables. Saying "it's just like a pointer" isn't generally sufficient, because it's not like a pointer, and it gives them totally the wrong model to work with. > > def func(a): > > a = 10 > > ... > > func(x) > > > > to change the value of x. > > Depends on how you implement the C "equivalent". The most direct > translation, IMHO, is the following: > > void func(int *a){ > a = 10; //Of course this is nonsense, but it illustrates the > point. Just because "a" is a pointer > //does not mean that "a" is not rebound when it is > assigned to. Oh wait! Did I use > //the word "rebound" when talking about a *C* > variable? ;-) > //*a = 10; //I'm guessing this is what *you* had in mind, but it > is very different > } > The very first thing a C programmer will want to do when seeing this snippet is ask how to do the later operation in Python. If you tell them they can't, they will then think of python variables as "like pointers, except for special cases" which is wrong. If you use Python semantics to explain it, in terms of names and bindings, they'll see that it's not at all like pointers, that assignment operations are totally consistent (assignment is name binding, not mutation) and that immutable objects are immutable by virtue of not having mutating methods, not because of compiler magic. The only "special cases" which then need to be explained are augmented assignment and object attribute assignment, which are easily (and correctly) explained as being syntactic sugar for mutate + rebind and a mutating method respectively. From benruza at gmail.com Fri Nov 16 01:42:22 2007 From: benruza at gmail.com (Bruza) Date: Thu, 15 Nov 2007 22:42:22 -0800 (PST) Subject: implement random selection in Python References: <663086c8-96f0-4350-afe0-c587b3dfe5e9@a28g2000hsc.googlegroups.com> Message-ID: On Nov 15, 9:32 pm, "mensana... at aol.com" wrote: > On Nov 15, 10:40?pm, Bruza wrote: > > > > > I need to implement a "random selection" algorithm which takes a list > > of [(obj, prob),...] as input. Each of the (obj, prob) represents how > > likely an object, "obj", should be selected based on its probability > > of > > "prob".To simplify the problem, assuming "prob" are integers, and the > > sum of all "prob" equals 100. For example, > > > ? ?items = [('Mary',30), ('John', 10), ('Tom', 45), ('Jane', 15)] > > > The algorithm will take a number "N", and a [(obj, prob),...] list as > > inputs, and randomly pick "N" objects based on the probabilities of > > the > > objects in the list. > > > For N=1 this is pretty simply; the following code is sufficient to do > > the job. > > > def foo(items): > > ? ? index = random.randint(0, 99) > > ? ? currentP = 0 > > ? ? for (obj, p) in items: > > ? ? ? ?currentP += w > > ? ? ? ?if currentP > index: > > ? ? ? ? ? return obj > > > But how about the general case, for N > 1 and N < len(items)? Is there > > some clever algorithm using Python standard "random" package to do > > the trick? > > > Thanks, > > > Ben > > What do you think of this? > > import random > N = 100 > items = [('Mary',30), ('John', 10), ('Tom', 45), ('Jane', 15)] > the_items = [] > for i,j in items: > the_items.extend([i]*j) > histogram = {} > for i in xrange(N): > chosen = random.choice(the_items) > print chosen, > if chosen in histogram: > histogram[chosen] += 1 > else: > histogram[chosen] = 1 > print > print > for i in histogram: > print '%4s: %d' % (i,histogram[i]) > > ## John Mary Jane Tom Tom Mary Mary Tom John John Tom John Tom > ## John Mary Mary Mary John Tom Tom John Mary Mary Tom Mary > ## Mary John Tom Jane Jane Jane John Tom Jane Tom Tom John Tom > ## Tom Mary Tom Tom Mary Tom Mary Tom Tom Tom Tom Mary Mary Tom > ## Mary Tom Mary Tom Tom Jane Tom Mary Tom Jane Tom Tom Tom Tom > ## Tom Mary Tom Jane Tom Mary Mary Jane Mary John Mary Mary Tom > ## Mary Mary Tom Mary John Tom Tom Tom Tom Mary Jane Mary Tom > ## Mary Tom Tom Jane Tom Mary Mary Tom > ## > ## Jane: 11 > ## John: 12 > ## Mary: 32 > ## Tom: 45 No. That does not solve the problem. What I want is a function def randomPick(n, the_items): which will return n DISTINCT items from "the_items" such that the n items returned are according to their probabilities specified in the (item, pro) elements inside "the_items". If I understand correctly, both of the previous replies will output one item at a time independently, instead of returning n DISTINCT items at a time. From deliverable at gmail.com Thu Nov 8 06:13:21 2007 From: deliverable at gmail.com (braver) Date: Thu, 08 Nov 2007 11:13:21 -0000 Subject: Showing native 8-bit strings in Python interpreter Message-ID: <1194520401.910631.18910@z24g2000prh.googlegroups.com> I'm storing 8-bit characters from the 128-256 range in Python strings. They are Windows CP1251 Russian characters. When looking at those strings in the Python interpreter, they come up as codes inside the string. How can I teach Python to show those 8-bit characters in the native encoding of the terminal -- in the current locale -- where the interpreter was started? Cheers, Alexy From sheep.in.herd at green.meadow Sat Nov 24 08:09:04 2007 From: sheep.in.herd at green.meadow (Ton van Vliet) Date: Sat, 24 Nov 2007 14:09:04 +0100 Subject: the annoying, verbose self References: <3c954a31-9fb9-4c0f-b784-cef9ee057ca6@g30g2000hsb.googlegroups.com> <4068d518-cba9-4eac-bd91-11f676c17b3d@w34g2000hsg.googlegroups.com> <5qq6quF10jrh5U2@mid.uni-berlin.de> Message-ID: On 24 Nov 2007 08:48:30 GMT, Marc 'BlackJack' Rintsch wrote: >On Sat, 24 Nov 2007 09:12:34 +0100, Ton van Vliet wrote: > >> Just bringing up something I sometimes miss from good-old Turbo-Pascal >> here, which has the WITH statement to reduce the typing overhead with >> (long) record/struct prefixes, used like: >> >> with do begin >> a = ... >> b = ... >> end; >> >> where all variables would be automatically prefixed with the >> (if present in the already available record definition!) > >And here lies the problem: The compiler decides at compile time which >names are local to a function and there is no equivalent of a record >definition to make that decision. > The whole clause following 'using self:' could be seen as the record definition: all attribute assignments/bindings in there should be prefixed with 'self' (if not already existing in the self namespace?) and thereby become instance attributes, which outside the 'using self' clause still need 'self.' as the (namespace?) prefix. It would not bring an 'implicit' self, but could possibly improve readability in some areas (btw, personally, I don't have anything against the 'explicit' self in general) Even in Pascal the 'with' statement was not meant to improve speed, but merely for readability, especially with complex records. Please, bear with me, I am relatively new to Python (reading books, scanning newsgroups, etc) and feel in no way capable of giving 'educated' or 'well overthought' advise, just my 2 cents ;-) -- Ton From steven at REMOVE.THIS.cybersource.com.au Tue Nov 27 03:17:22 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Tue, 27 Nov 2007 08:17:22 -0000 Subject: the annoying, verbose self References: <3c954a31-9fb9-4c0f-b784-cef9ee057ca6@g30g2000hsb.googlegroups.com> <4068d518-cba9-4eac-bd91-11f676c17b3d@w34g2000hsg.googlegroups.com> <5qq6quF10jrh5U2@mid.uni-berlin.de> <5qqoslF10jrh5U6@mid.uni-berlin.de> <474b1b44$0$20133$426a74cc@news.free.fr> Message-ID: On Mon, 26 Nov 2007 21:48:36 +0100, Ton van Vliet wrote: > On Mon, 26 Nov 2007 20:14:50 +0100, Bruno Desthuilliers > wrote: > >>> However, I was more thinking in terms of attributes only >> >>Too bad : in Python, everything's an object, so 'methods' are attributes >>too. > > Right, but I'm sure *you* know a way to distinguish between them (I'm > just a beginner ;-) All methods are attributes. Not all attributes are methods. The usual way to see if something is a method is to try calling it and see what happens, but if you want a less informal test, try type(): >>> type(''.join) >>> type(Foo().foo) # with the obvious definition of Foo -- Steven From Russ.Paielli at gmail.com Wed Nov 7 07:27:50 2007 From: Russ.Paielli at gmail.com (Russ P.) Date: 7 Nov 2007 04:27:50 -0800 Subject: command-line arguments in IDLE Message-ID: <1194397079.632843.16240@t8g2000prg.googlegroups.com> Is it possible to pass command-line arguments when running a program in IDLE? The "Run" menu does not seem to provide that option. Thanks. From info at egenix.com Mon Nov 19 07:43:50 2007 From: info at egenix.com (eGenix Team: M.-A. Lemburg) Date: Mon, 19 Nov 2007 13:43:50 +0100 Subject: ANN: eGenix mxODBC and mxODBC Zope DA on AIX 5.3 (and later) Message-ID: <47418506.5090205@egenix.com> ________________________________________________________________________ ANNOUNCING eGenix.com mxODBC Database Interface eGenix.com mxODBC Zope Database Adapter for AIX 5.3 and later This announcement is also available on our web-site for online reading: http://www.egenix.com/company/news/eGenix-mxODBC-on-AIX53-POWER5-GA.html ________________________________________________________________________ eGenix mxODBC Distribution The eGenix mxODBC Distribution is a Python database interface add-on distribution for our eGenix mx Base Distribution. It comes with mxODBC, our universal ODBC database interface for Python. Customers who have purchased licenses for other platforms and wish to move their installation to AIX 5.3 (or later), can do so without having to buy a new license. The licenses will continue to work on the AIX platform. Users of mxODBC 2.0 will have to purchase new licenses from our online shop in order to upgrade to mxODBC 3.0. You can request 30-day evaluation licenses on the product page. Downloads --------- Please visit the eGenix mxODBC Distribution page for downloads, instructions on installation and documentation of the packages. http://www.egenix.com/products/python/mxODBC/ Note that in order to use the eGenix mxODBC Distribution you need to install the eGenix mx Base Distribution first. ________________________________________________________________________ eGenix mxODBC Zope DA eGenix mxODBC Zope DA is our database interface for Zope and Plone. It is based on the mxODBC interface. Customers who have purchased licenses for other platforms and wish to move their installation to AIX 5.3 (or later), can do so without having to buy a new license. The licenses will continue to work on the AIX platform. You can request 30-day evaluation licenses on the product page. Downloads --------- Please visit the eGenix mxODBC Zope DA product page for downloads, instructions on installation and documentation of the packages. http://www.egenix.com/products/zope/mxODBCZopeDA/ ________________________________________________________________________ More Information For more information on our products, licensing and download instructions, please write to sales at egenix.com. Enjoy, -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Nov 19 2007) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From jcd at sdf.lonestar.org Sat Nov 17 10:23:58 2007 From: jcd at sdf.lonestar.org (J. Clifford Dyer) Date: Sat, 17 Nov 2007 10:23:58 -0500 Subject: implement random selection in Python Message-ID: <20071117152358.GA18686@sdf.lonestar.org> On Fri, 2007-11-16 at 16:47 -0800, Bruza wrote: I think I need to explain on the probability part: the "prob" is a > relative likelihood that the object will be included in the output > list. So, in my example input of > > items = [('Mary',30), ('John', 10), ('Tom', 45), ('Jane', 15)] > > So, for any size of N, 'Tom' (with prob of 45) will be more likely to > be included in the output list of N distinct member than 'Mary' (prob > of 30) and much more likely than that of 'John' (with prob of 10). > > I know "prob" is not exactly the "probability" in the context of > returning a multiple member list. But what I want is a way to "favor" > some member in a selection process. > My understanding of what you are looking for is that on each individual selection, the probability of picking a given name is that name's prob value, divided by the sum of all prob values. That is, in the following case: items = [('Mary',96),('Shimon',1),('Aisha',1),('Toshiro',2)] N = 3 On the first pass Mary has a 96% chance of getting selected, Shimon a 1% Chance, Aisha a 1% chance and Toshiro a 2% chance. If Mary gets selected, then on the second round Shimon and Aisha should each have a 25% chance of getting selected, and Toshiro a 50% chance. If Shimon gets selected, then on round three, Aisha will have a ~33% chance, and Toshiro a little less than 67%. If that is correct, then the following might meet your needs: from random import choice def select(weighted_list, n=1): selected = set() for iteration in xrange(n): print iteration selection_list = [] for item in weighted_list: if item[0] not in selected: selection_list.extend([item[0]] * item[1]) #print selection_list this_choice = choice(selection_list) #print this_choice selected.add(this_choice) return selected if __name__ == '__main__': items = [('Mary',96),('Shimon',1),('Aisha',1),('Toshiro',2)] N = 3 print select(items, 3) It creates a new selection list at every pass, but it should be a marked improvement over solutions that have to flail against already chosen values, especially in unbalanced cases like the one I've shown above. I have not run tests to establish this for certain. Exercise left to the reader. If you care who was chosen first or last (like, say, if this is for selecting members of a kick ball team), you may want to replace the selected set with a list. Or you may want to keep both the set and a list. Depends on your needs. Cheers, Cliff From kf9150 at gmail.com Wed Nov 21 13:42:00 2007 From: kf9150 at gmail.com (Kelie) Date: Wed, 21 Nov 2007 10:42:00 -0800 (PST) Subject: having problem using xlrd Message-ID: <6e4ee601-6a21-48f4-9d3a-1b121280d6ea@v4g2000hsf.googlegroups.com> Hello, I tried using xlrd to read an Excel file and kept getting this error: AttributeError: 'Book' object has no attribute 'mem' >>> import xlrd >>> p = r'C:\2.xls' >>> wb = xlrd.open_workbook(p) >>> wb.get_sheets() AttributeError: 'Book' object has no attribute 'mem' >>> wb.get_record_parts() AttributeError: 'Book' object has no attribute 'mem' Any hint? Thanks! p.s. i tried posting the question at the python-excel mailing list. but it seems failed. if it shows up later, sorry for crossposting. From bscrivener42 at gmail.com Tue Nov 27 22:27:29 2007 From: bscrivener42 at gmail.com (BartlebyScrivener) Date: Tue, 27 Nov 2007 19:27:29 -0800 (PST) Subject: Books on Python References: Message-ID: <17796751-2450-4783-b624-14b3ce09072d@i12g2000prf.googlegroups.com> On Nov 27, 9:05 pm, "barcaroller" wrote: > Can someone kindly recommend some good books on the following: > > Python for beginners > Python for advanced users > http://wiki.python.org/moin/PythonBooks From lawry_jim at yahoo.com Wed Nov 21 14:14:59 2007 From: lawry_jim at yahoo.com (lawry_jim at yahoo.com) Date: Wed, 21 Nov 2007 11:14:59 -0800 (PST) Subject: computer programming Message-ID: <2cbcbc61-0c59-4b56-b56a-3b673f10eeef@l1g2000hsa.googlegroups.com> http://computer-programmings.blogspot.com From davidh at ilm.com Thu Nov 29 17:19:44 2007 From: davidh at ilm.com (David Hirschfield) Date: Thu, 29 Nov 2007 14:19:44 -0800 Subject: Using marshal to manually "import" a python module Message-ID: <474F3B00.2040100@ilm.com> I had a situation recently that required I manually load python bytecode from a .pyc file on disk. So, for the most part, I took code from imputil.py which loads the .pyc data via the marshal module and then exec's it into a newly created module object (created by imp.new_module()). The relevant pieces of code are in imputil.py_suffix_importer and imputil.Importer._process_result (where it exec's the code into the module's __dict__) The strange thing is, it worked fine locally on my two machines (32bit running python 2.3.5 and 64bit running python 2.4.1), but when run by a 64bit machine on the network, it would fail every time in the following manner: My marshal/exec-based loader would load the module from the pyc apparently without problems, but if I then pulled a specific function attr out of the resulting module object, and that function called another function defined within the same module, it would raise a "TypeError: 'NoneType' object is not callable" exception when attempting to call that second function. So the setup is: module blah: def A(): ... def B(): x = A() compiled to bytecode: blah.pyc then, in my program: m = my_marshal_loader("blah.pyc") f = getattr(m,"B") x = f() raises "TypeError: 'NoneType' object is not callable" inside that call to f(), on the line x = A(), as though A is a None and not the function object defined in the module. I can't figure out why this would work locally, but not when the module is loaded across a network. In fact, I have no idea what would ever cause it not to see A as a function. I'm stumped, and this is over my head as far as intimate knowledge of the direct loading of python bytecode via marshal is concerned...so I'm not clear on the best way to debug it. If anyone has an inkling of what might be going on, I'd love to hear it. Thanks in advance, -Dave -- Presenting: mediocre nebula. From Frank.Aune at broadpark.no Thu Nov 29 07:41:19 2007 From: Frank.Aune at broadpark.no (Frank Aune) Date: Thu, 29 Nov 2007 13:41:19 +0100 Subject: PyPubSub module version 3 usage Message-ID: <200711291341.19248.Frank.Aune@broadpark.no> Hello, I just recently found out that wx.lib.pubsub has finally moved away from wx, and now lives at: http://pubsub.wiki.sourceforge.net I'm trying to use pubsub3, which is the third version and now the default one, but I'm having a hard time creating topics and messages for sending: class Topic: __init__(self, _name, _description, _parent=None, **kwargs) | Specify the name, description, and parent of | this Topic, and the list of kwargs allowed on listeners | of this topic. The non-kwargs all start with a '_' to | minimize the chance of conflict with a kwargs key. from pubsub import pub class Test(pub.Topic): def __init__(self): pub.Topic.__init__(self, 'Topic.Test', 'This is a test topic') class Msg(pub.Message): pass pub.sendMessage(Test()) Traceback (most recent call last): File "topics.py", line 80, in pub.sendMessage(Test()) File "build/bdist.linux-i686/egg/pubsub/pubsub3.py", line 421, in sendMessage File "build/bdist.linux-i686/egg/pubsub/pubsub3.py", line 195, in sendMessage File "/home/frank/test/topics.py", line 155, in getTopic File "/home/frank/test/topics.py", line 162, in __getTopic TypeError: iteration over non-sequence. pub.sendMessage(Msg()) Traceback (most recent call last): File "topics.py", line 80, in pub.sendMessage(Test()) File "build/bdist.linux-i686/egg/pubsub/pubsub3.py", line 421, in sendMessage File "build/bdist.linux-i686/egg/pubsub/pubsub3.py", line 195, in sendMessage File "/home/frank/test/topics.py", line 155, in getTopic File "/home/frank/test/topics.py", line 162, in __getTopic TypeError: iteration over non-sequence. The variable in question for class Test() contains: Topic 'T.o.p.i.c...T.e.s.t': This is a test topic. Listeners that have 'topic=pub.AUTO_PASS_TOPIC' as a kwarg will get the topic name as value of topic (ie 'T.o.p.i.c...T.e.s.t'). Listeners must otherwise be callable with no args. No listeners are currently subscribed. There are currently no subtopics. which of course is non-iterable. Same for class Msg(), So obviously my Topic and Message class constructors are wrong. The code on the wiki is for pubsub2, and seems to be outdated compared to pubsub3 API. pubsub1 is the same as wx.lib.pubsub btw. Basically I'm looking for example code to get me kickstarted using pubsub3. Best regards, Frank From fabiofz at gmail.com Fri Nov 9 10:56:05 2007 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Fri, 9 Nov 2007 12:56:05 -0300 Subject: Looking for a good Python environment In-Reply-To: <7xbqa6f192.fsf@ruckus.brouhaha.com> References: <1194389774.159051.55580@19g2000hsx.googlegroups.com> <1194434140.836932.10670@k79g2000hse.googlegroups.com> <7xbqa6f192.fsf@ruckus.brouhaha.com> Message-ID: On 07 Nov 2007 08:50:49 -0800, Paul Rubin <"http://phr.cx"@nospam.invalid> wrote: > "Colin J. Williams" writes: > > Could you elaborate on "lightweight" please? I find PyScripter to be a > > powerful editor/debugger combination. > > > > What functionality does Eclipse have that PyScripter does not? > > While we're at it, do any of these debuggers implement a good way to > debug multi-threaded Python programs? > Pydev handles multi-threaded debugging. Cheers, Fabio -------------- next part -------------- An HTML attachment was scrubbed... URL: From alainpoint at yahoo.fr Fri Nov 30 03:54:57 2007 From: alainpoint at yahoo.fr (alain) Date: Fri, 30 Nov 2007 00:54:57 -0800 (PST) Subject: Crackly sound in pygame References: <9fe4d7a6-bf02-4db7-be90-4f75378a78ca@e10g2000prf.googlegroups.com> Message-ID: <144e62a0-2e6f-4636-bd9c-3de22502e435@p69g2000hsa.googlegroups.com> On Nov 30, 4:33 am, "Woot4... at gmail.com" wrote: > Hey guys I am running Windows XP and am having an issue with a game > that my team has created. Whenever an audio file is played it creates > a very distorted, crackly sound. Any ideas what could be the issue? > > Thanks No, and the more i look at your post, the more i can't see why. Sorry for not being able to help. Alain From phil at freehackers.org Wed Nov 21 09:04:10 2007 From: phil at freehackers.org (BlueBird) Date: Wed, 21 Nov 2007 06:04:10 -0800 (PST) Subject: Python too complex ?!?!?! References: <7hC%i.28332$mv3.17248@newsfe10.phx> <7bde7627-adf1-4bc6-a936-2159370485a1@e1g2000hsh.googlegroups.com> <672dfa43-bd56-44fa-b85d-15eca7682c84@s36g2000prg.googlegroups.com> <46601afd-9c1d-48d1-8d1c-9330b726211e@a39g2000pre.googlegroups.com> Message-ID: On Nov 20, 9:36 pm, "sjdevn... at yahoo.com" wrote: > FWIW it's trivial to run pyflakes on your code (automatically behind > the scenes) to get syntax checking; in vim, my syntax errors get > underlined immediately for python code. Can you describe your setup a bit more precisely ? I'm interested in this kind of development help. I had a quick look at pyflakes but I haven't found any signs of vim integration. > I also get function prototypes on the status line I'm interested in that as well ! regards, Philippe From ppetrick at gmail.com Tue Nov 20 18:40:09 2007 From: ppetrick at gmail.com (p.) Date: Tue, 20 Nov 2007 15:40:09 -0800 (PST) Subject: mimicking a file in memory References: <3ea3babb-29f1-4950-9d5b-c31f67d4e54a@i29g2000prf.googlegroups.com> <13k6mjapuemsre6@corp.supernews.com> <13k6qie8ah5qh64@corp.supernews.com> Message-ID: <9a770545-d44a-4c9e-ba6b-5863fafe5455@s6g2000prc.googlegroups.com> On Nov 20, 3:14 pm, Grant Edwards wrote: > On 2007-11-20, p. wrote: > > > > >> By "memory" I presume you mean virtual memory? RAM with > >> disk-blocks as backing store? On any real OS, tempfiles are > >> just RAM with disk-blocks as backing store. > > >> Sound similar? The only difference is the API used to access > >> the bytes. You want a file-I/O API, so you can either use the > >> extensively tested and and highly optimized filesystem code in > >> the OS to make disk-backed-RAM look like a file, or you can try > >> to write Python code that does the same thing. > > >> Which do you think is going to work faster/better? > > >> [The kernel is generally better at knowing what needs to be in > >> RAM than you are -- let it do its job.] > > >> IOW: just use a temp file. Life will be simple. The bytes > >> probably won't ever hit the platters (if they do, then that > >> means they would have the other way too). > > > Grant, are temp files automatically put into ram for all linux > > distros? > > All files are put into ram for all linux distros that use > virtual memory. (You'll know if you're not using virtual.) > > > at any rate, i could set up ram disk. much better solution > > than using python...except that i've never done a ram disk > > before. more reading to do... > > You don't have set up a ram disk. You already have one. All > your disks are ram disks. It's just that some of them have > magnetic platters as backing store so they get preserved during > a reboot. On some Linux distros, the /tmp directory is a > filesystem without prmanent magnetic backing-store. On others > it does have a permanent backing store. If you do a "mount" > command, you'll probably see a "filesystem" who's type is > "tmpfs". That's a filesystem with no permanent magnetic > backing-store[1]. > > Seehttp://en.wikipedia.org/wiki/TMPFS > > /tmp might or might not be in a tmpfs filesystem (depends on > the distro). In any case, you probably don't need to worry > about it. > > Just call tempfile.NamedTemporaryFile() and tell it you want an > unbuffered file (that way you don't have to remember to flush > the file after writing to it). It will return a file object: > > f = tempfile.NamedTemporaryFile(bufsize=0) > > Write the data to that file object and flush it: > > f.write(mydata) > > Pass the file's name to whatever broken library it is that > insists on a file name instead of a file-like object: > > brokenLib.brokenModule(f.name). > > When you're done, delete the file object: > > del f > > NB: This particular approach won't work on Windows. On Windows > you'll have to use tempfile.mktemp(), which can have race > conditions. It returns a name, so you'll have to create > the file, write to it, and then pass the name to the broken > module. > > [1] Tmpfs pages use the swap partition for temporary backing > store the same as for all other memory pages. If you're > using tmpfs for big stuff, make sure your swap partition is > large enough to hold whatever you're doing in tmpfs plus > whatever normal swapping capacity you need. > > ------------------------------demo.py------------------------------ > def brokenModule(filename): > f = file(filename) > d = f.read() > print d > f.close() > > import tempfile,os > > f = tempfile.NamedTemporaryFile(bufsize=0) > n = f.name > print f,":",n > os.system("ls -l %s\n" % n) > > f.write("hello world") > brokenModule(n) > > del f > os.system("ls -l %s\n" % n) > ------------------------------demo.py------------------------------ > > If you run this you'll see something like this: > > $ python demo.py > ', mode 'w+b' at 0xb7c37728> : /tmp/tmpgqSj8p > -rw------- 1 grante users 0 2007-11-20 17:11 /tmp/tmpgqSj8p > hello world > ls: cannot access /tmp/tmpgqSj8p: No such file or directory > > -- > Grant Edwards grante Yow! I want to mail a > at bronzed artichoke to > visi.com Nicaragua! excellent. didn't know tempfile was a module. thanks so much. From ladynikon at gmail.com Fri Nov 2 09:48:26 2007 From: ladynikon at gmail.com (Danyelle Gragsone) Date: Fri, 2 Nov 2007 09:48:26 -0400 Subject: ((((((((((((((FREE)()((((SEX STIL FUCKING STILL FREE((((((((((()()()()()(WORLD SEX STILL FREE SEX(((((((((((((( In-Reply-To: <1193990737.915887.194770@i13g2000prf.googlegroups.com> References: <1193990737.915887.194770@i13g2000prf.googlegroups.com> Message-ID: <59f9c5160711020648l6e7bb2b9t9618731db2c71532@mail.gmail.com> if only one could zap people over the internetz.. From inq1ltd at inqvista.com Tue Nov 27 10:17:03 2007 From: inq1ltd at inqvista.com (jim-on-linux) Date: Tue, 27 Nov 2007 10:17:03 -0500 Subject: It works! Was: Installing Python 3000 In-Reply-To: <8110866b-41a6-4ff6-a9a7-9f7e3a56540b@e1g2000hsh.googlegroups.com> References: <8110866b-41a6-4ff6-a9a7-9f7e3a56540b@e1g2000hsh.googlegroups.com> Message-ID: <200711271017.03557.inq1ltd@inqvista.com> On Tuesday 27 November 2007 07:20, Andr? wrote: > On Nov 26, 9:59 pm, "Andr?" wrote: > > While I made some progress in trying to install Py3k from source > > (for the first time), it has failed... > > > > Here are the steps I went through (not necessarily in that order > > - except for those that matter). > > > > 1. After installing Leopard, install Xcode tools from the dvd - > > even if you had done so with a previous version (they need to be > > updated - trust me :-) > > > > 2. Download Python 3.0a1 > > > > 3. Unpack the archive. > > > > 4. Go to /usr/local and make a directory "sudo mkdir py3k" > > (This is probably not needed, but that's what I did). > > > > 5. From the directory where the Python 3.0a1 was unpacked run > > ./configure --prefix=/usr/local/py3k > > > > 6. run "make" > > > > This last step failed with the following error message: > > > > gcc -fno-strict-aliasing -Wno-long-double -no-cpp-precomp > > -mno-fused- madd -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. > > -I./Include - DPy_BUILD_CORE -c ./Modules/posixmodule.c -o > > Modules/posixmodule.o ./Modules/posixmodule.c: In function > > 'posix_setpgrp': > > ./Modules/posixmodule.c:3769: error: too few arguments to > > function 'setpgrp' > > make: *** [Modules/posixmodule.o] Error 1 > > > > Any suggestions? > > > > Andr? > > Following Martin v L?wis's suggestion, I looked at > > http://bugs.python.org/issue1358 > > and added the line > #define SETPGRP_HAVE_ARG > by hand to pyconfig.h (after it was created by configure). Then > 6. run "make" > 7. run "make test" (one test failed; this step likely unnecessary) > 8. sudo make altinstall > 9. sudo ln /usr/local/bin/py3k/python3.0 /usr/bin/python3.0 > > 10. type "python" > 11. print("Hello world!") > 12. Be happy! > > Andr?, hoping this report might help some other newbie. Bug fix excluded, After unpacking the compressed version of Python, look for a file named "README". Open "README" and look for Installing. Make install and Make altinstall is explained. I don't like to read instructions but in the long run, it saves time. jim-on-linux http://www.inqvista.com From glenboucher at googlemail.com Wed Nov 28 11:52:07 2007 From: glenboucher at googlemail.com (glenboucher) Date: Wed, 28 Nov 2007 08:52:07 -0800 (PST) Subject: ****** The ULTIMATE FREE INTERNET BUSINESS!!! No Cost!****** Message-ID: <14fa17c3-e76e-4f7f-8816-6a5ed61ac2b1@a39g2000pre.googlegroups.com> @@@@@ @@@@@ Are you looking for an easy work at home? Are you looking for a way to earn extra? Then look no further!! It's not only the easiest business but it's also FREE to join!!! For More Details Check the Links Below: http://solutionformakingmoneyonline.blogspot.com/ http://accessmoneyonline.blogspot.com/ P.S - The Key To Making Money Online Is Knowing How And Where To Start. @@@@@ @@@@@ From tjreedy at udel.edu Thu Nov 29 19:11:25 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 29 Nov 2007 19:11:25 -0500 Subject: Embedding Python - Passing by Reference References: <6ef0cabb-5a41-4095-9654-c82cc39bdbe1@e23g2000prf.googlegroups.com> Message-ID: wrote in message news:6ef0cabb-5a41-4095-9654-c82cc39bdbe1 at e23g2000prf.googlegroups.com... |I understand the parameters to Python functions are passed by reference: Nope. Python's name-object model is so far different from the named memory block model of Fortran/C/etc that terms invented for the latter are misleading when applied to Python. Argument objects (or the contents thereof, or lists or dicts constructed therefrom) are bound to parameter names. (See the archives for endless discussion of what to call this.) | def foo(a): | a = a + 1 | | Will change the value of a in the calling function. Nope. Try it with the interactive interpreter (or IDLE, etc, equivalent). Only takes a minute to test whatever you meant by that.tjr | From bborcic at gmail.com Fri Nov 2 11:04:16 2007 From: bborcic at gmail.com (Boris Borcic) Date: Fri, 02 Nov 2007 16:04:16 +0100 Subject: new style class In-Reply-To: <1194004712.691884.249570@v3g2000hsg.googlegroups.com> References: <1194002609.296417.111050@v3g2000hsg.googlegroups.com> <1194004712.691884.249570@v3g2000hsg.googlegroups.com> Message-ID: <472b3caa$1_3@news.bluewin.ch> gert wrote: > Could not one of you just say "@staticmethod" for once damnit :) > I did, did I not ? From phil at freehackers.org Fri Nov 2 07:21:06 2007 From: phil at freehackers.org (BlueBird) Date: Fri, 02 Nov 2007 04:21:06 -0700 Subject: PyQt with embedded python in Qt App In-Reply-To: References: <1193924163.660753.179140@o38g2000hse.googlegroups.com> <5ov81oFof171U1@mid.uni-berlin.de> Message-ID: <1194002466.539726.267780@k79g2000hse.googlegroups.com> On Nov 2, 8:03 am, "Bart." wrote: > Friday 02 of November 2007 01:06:58 Diez B. Roggisch napisa (a): > > > > So how to pass this object into embeded python interpreter (executed > > > script)? Anyone know any example? > > > You don't pass it, you _retrieve_ it in the embedded interpreter by > > invoking the code given to you. > > Know any example, please? > For better understand this :) I wan't add scripting to one application wrotten > with Qt. So, you have Qt/C++ application which you want to script through python. But why do you need PyQt for ? If you design a script api in python and bind it using whatever binding technology (manually, boost, sip, pyrex, ...), you should not need to use PyQt. Or do you mean to use PyQt as the binding technology ? Philippe From simon at brunningonline.net Sat Nov 17 14:59:30 2007 From: simon at brunningonline.net (Simon Brunning) Date: Sat, 17 Nov 2007 19:59:30 +0000 Subject: Excellent sci-fi novel featuring Python In-Reply-To: References: <45ae31dd-0aaf-4065-ba9e-b1e5cf78b105@c30g2000hsa.googlegroups.com> Message-ID: <8c7f10c60711171159o1319a789pcdc5f3c6deefdd3d@mail.gmail.com> On Nov 17, 2007 4:25 PM, Paul McGuire wrote: > On Nov 17, 9:37 am, Wade Leftwich wrote: > > I'm about halfway through Charles Stross' excellent new novel, > > "Halting State". It's set in Edinburgh in the year 2018, and one of > > the main characters is a game programmer whose primary language is > > something called "Python 3000". > > I should hope that by 2018, Python 4000 would be more cutting-edge. > Or is the protagonist struggling with backward-compatibility with a > Python version that would be nearly 10 years old already? If the whole 3.n series is called "Python 3000", then it's very plausible. I can see Python 3.7 or 3.8 being the latest version in 2018. -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues From bj_666 at gmx.net Sat Nov 24 05:07:37 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 24 Nov 2007 10:07:37 GMT Subject: the annoying, verbose self References: <3c954a31-9fb9-4c0f-b784-cef9ee057ca6@g30g2000hsb.googlegroups.com> <4068d518-cba9-4eac-bd91-11f676c17b3d@w34g2000hsg.googlegroups.com> <220d59b8-bcce-4496-beab-0976a5a83f80@g21g2000hsh.googlegroups.com> Message-ID: <5qqbf9F10jrh5U3@mid.uni-berlin.de> On Sat, 24 Nov 2007 01:55:38 -0800, samwyse wrote: > I've had the same thought, along with another. You see, on of my pet > peeves about all OO languages that that when creating new code, I > generally begin by writing something like this: > > cat = 'felix' > dog = 'rover' > def example(): > global cat, dog # not always required, but frequently needed > return ', '.join((cat, dog)) Ouch that's bad design IMHO. The need to use ``global`` is a design smell, if needed *frequently* it starts to stink. Ciao, Marc 'BlackJack' Rintsch From pavlovevidence at gmail.com Fri Nov 30 05:51:35 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 30 Nov 2007 02:51:35 -0800 (PST) Subject: Witch editor to use! References: <2b6a7153-d9ad-4ac0-acf0-4b5a39318d74@e10g2000prf.googlegroups.com> Message-ID: <16b8f26b-f780-4eaf-a295-8c27de1965fc@d4g2000prg.googlegroups.com> On Nov 30, 4:40 am, Ant wrote: > On Nov 30, 9:10 am, SMALLp wrote: > > > Hello! > > > I'm new in wxPython and before i start doing anything I have one qustion. > > > Shoul I use some of editors like boa, spe or shoud i use my favorite > > text editor! > > > i used IDLE on windows and it seamd nice. Now i have linux installed on > > my mashine and boa works, spe wont start, IDLE crashes when compailinfg! > > > And if editor is bether choice witch one to use! > > One with a spell checker would be a good start. Punny. Carl Banks From salvatore.randazzo at gmail.com Wed Nov 21 02:45:39 2007 From: salvatore.randazzo at gmail.com (salrandazzo) Date: Tue, 20 Nov 2007 23:45:39 -0800 (PST) Subject: pyserial doesn't recognize virtual serial port References: <1192168211.911755.71940@z24g2000prh.googlegroups.com> Message-ID: <32a3a61d-080c-413f-99bb-8a5c227ca0e3@d50g2000hsf.googlegroups.com> Try reading the sourceforge.net help forum about com0com: http://sourceforge.net/forum/forum.php?thread_id=1395157&forum_id=440109 Maybe you can find the solution. I think you should prefix the port name with "\\.\" Something like "\\.\CNCA0" Did you ever try to use the com2tcp utility? I'm trying to use it, but there are so little information. I posted a request on the forum, and still waiting for answer. Salvatore On 12 Ott, 06:50, naveen.sabapa... at gmail.com wrote: > Hi, > I am trying to use virtual serial ports to develop/test my serial > communication program. Running in to trouble... > > I am using com0com to create the virtual ports. The virtual ports > seem to be working fine when I test it with Hyperterminal . > > I am using the example program that comes with pyserial, as below. > --------------- > import serial > ser = serial.Serial('CNCA0') #open virtual serial port > print ser.portstr #check which port was realy used > ser.write("Hello") #write a string > ser.close() #close port > ----------------- > > The following is the error message: > > -------------- > Traceback (most recent call last): > File "C:\Python25\Naveen Files\TestSerial", line 2, in > ser = serial.Serial('CNCA0') #open first serial port > File "c:\Python25\Lib\site-packages\serial\serialutil.py", line 156, > in __init__ > self.open() > File "c:\Python25\Lib\site-packages\serial\serialwin32.py", line 55, > in open > raise SerialException("could not open port: %s" % msg) > SerialException: could not open port: (2, 'CreateFile', 'The system > cannot find the file specified.') > -------------- > > When I try with 'COM3', which comes inbuilt in my laptop, COM3 is > recognized. Few other posts on the web seem to indicate pyserial > should work fine with virtual serial ports. What am I missing? Please > help. > > --Thanks > --NS From DouhetSukd at gmail.com Tue Nov 13 03:42:52 2007 From: DouhetSukd at gmail.com (DouhetSukd) Date: 13 Nov 2007 00:42:52 -0800 Subject: How to get a set of keys with largest values? In-Reply-To: <1194858457.677637.90530@i13g2000prf.googlegroups.com> References: <1194858457.677637.90530@i13g2000prf.googlegroups.com> Message-ID: <1194941665.185787.116010@y27g2000pre.googlegroups.com> On Nov 12, 1:07 am, Davy wrote: > Hi all, > > I have a dictionary with n elements, and I want to get the m(m<=n) > keys with the largest values. > > For example, I have dic that includes n=4 elements, I want m=2 keys > have the largest values) > dic = {0:4,3:1,5:2,7:8} > So, the the largest values are [8,4], so the keys are [7,0]. > > Is there any fast way to implement this algorithm? > Any suggestions are welcome! > > Best regards, > Davy #get a list of tuples, with value in 1st position, key second li = [(value,key) for key, value in dic.items()] #sort the list li.sort() m = 2 #grab the m highest values, from the end of the list li_high_keys = [k for v, k in li[-m:]] From DustanGroups at gmail.com Mon Nov 5 07:59:23 2007 From: DustanGroups at gmail.com (Dustan) Date: Mon, 05 Nov 2007 12:59:23 -0000 Subject: how does google search in phrase In-Reply-To: <1194178870.569742.181240@z9g2000hsf.googlegroups.com> References: <1194178870.569742.181240@z9g2000hsf.googlegroups.com> Message-ID: <1194267563.593888.109930@o80g2000hse.googlegroups.com> On Nov 4, 6:21 am, "oruc... at gmail.com" wrote: > hi my friends; > google can searching in phrase but it is imposible. it have a lot of > page in data base and quadrillions sentence it can't search in > fulltxt all of them .it need a super algorithm. ? need the algorithm > now. if you have a idea ,pls share to me Ummm... What? Do you want to use Google or create another Google? > thanks > (sorry for my bad english :( ) From iclark at mail.ewu.edu Fri Nov 2 13:13:45 2007 From: iclark at mail.ewu.edu (Ian Clark) Date: Fri, 02 Nov 2007 10:13:45 -0700 Subject: Iterable Flattener with Depth. In-Reply-To: <1193997410.835980.36250@22g2000hsm.googlegroups.com> References: <1193918613.831666.305230@k79g2000hse.googlegroups.com> <1193981554.692209.226450@o3g2000hsb.googlegroups.com> <1193997410.835980.36250@22g2000hsm.googlegroups.com> Message-ID: thebjorn wrote: > On Nov 2, 6:32 am, praddy wrote: >> On Nov 1, 5:03 pm, bearophileH... at lycos.com wrote: >> >>> Pradeep Jindal: >>>> Any comments? >>> Something with similar functionality (plus another 20 utility >>> functions/classes or so) has probably to go into the std lib... :-) >>> Bye, >>> bearophile >> Same Here! >> >> - Pradeep > > Yeah, everyone has to write a flatten sooner or later :-) My version > is at: > > http://blog.tkbe.org/archive/python-flatten/ > > -- bjorn > And here is mine. Note that it is very similar to Michael Spencer's implementation[1]. The only difference is that this adds a depth counter. def iflat(itr, depth=0): itr = iter(itr) stack = [] cur_depth = 0 while True: try: elem = itr.next() if hasattr(elem, "__iter__") and cur_depth < depth: stack.append(itr) itr = iter(elem) cur_depth += 1 else: yield elem except StopIteration: if not stack: raise StopIteration cur_depth -= 1 itr = stack.pop() if __name__ == "__main__": test1 = ((0, 1, 2), ((3, 4), 5), (((6, 7), 8), 9)) test2 = [1,[2,[3,4,5],'bash'],6,[7,[8,[9,10,['hi', 'hello']]]], 11, 12] for x in (test1, test2): print print list(iflat(x)) print print list(iflat(x, 1)) print list(iflat(x, 2)) print list(iflat(x, 3)) print list(iflat(x, 4)) print iflat(x, 10) Ian [1] http://mail.python.org/pipermail/python-list/2005-March/312022.html From carl at personnelware.com Tue Nov 27 20:51:28 2007 From: carl at personnelware.com (Carl K) Date: Tue, 27 Nov 2007 19:51:28 -0600 Subject: looking for ocbc example In-Reply-To: <1190371280.070392.55700@22g2000hsm.googlegroups.com> References: <1190371280.070392.55700@22g2000hsm.googlegroups.com> Message-ID: jay graves wrote: > On Sep 21, 2:43 am, Tim Golden wrote: >> Carl K wrote: >>> It seems there are 2 odbc modules - pyOdbc and mxOdbc - anyone know the difference? >> In short, pyodbc is open source; mxOdbc requires a commercial license. >> pyodbc is a newcomer, but appears to work for everything I've thrown >> at it (which is not much). mxOdbc has been around longer, and is sure >> to be a more mature product. It may offer more features & functionality. > > There is also a brand new module 'ceODBC'. > http://ceodbc.sourceforge.net/ > > I haven't used it yet but I want to give it a try. I tried it, and it worked better than pyodbc. (better is not exactly right. there was some weird bug in the ctree odbc driver, and the author of ceODBC gave me a workaround.) Carl K Carl K From mccredie at gmail.com Mon Nov 5 13:50:29 2007 From: mccredie at gmail.com (Matimus) Date: Mon, 05 Nov 2007 18:50:29 -0000 Subject: __file__ vs __FILE__ In-Reply-To: <1194253637.588512.14820@e34g2000pro.googlegroups.com> References: <1194060097.141059.196040@e34g2000pro.googlegroups.com> <1194095230.217067.147090@y42g2000hsy.googlegroups.com> <1194221360.542208.79950@19g2000hsx.googlegroups.com> <1194253637.588512.14820@e34g2000pro.googlegroups.com> Message-ID: <1194288629.186414.210310@q3g2000prf.googlegroups.com> On Nov 5, 1:07 am, sandipm wrote: > interestingly... > I wanted to reuse this code so i wrote function in a file > > def getParentDir(): > import os > return os.path.dirname(os.path.abspath(__file__)) > > and called this function, in another file, its giving me parent > directory of file where this function is defined.? This is true. __file__ is defined at the module level where the function is defined. > how to reuse this piece of code then? or am i doing something wrong? > You have a few choices. You could implement it wherever you need it which might actually be nice from a OO point of view. You could modify the function above to accept a parameter and operate on the __file__ attribute of that parameter. Or, you could use the inspect module to look at the stack and operate on the __file__ attribute of the caller. The first one is obvious to implement, although it will only apply to modules you have implemented. The second one I think someone has already posted a solution to. Here is how to implement the third one (this is also usable with a parameter). [code] import inspect import os def getpardir(obj=None): if obj is None: obj = inspect.stack()[1][0] return os.path.dirname(inspect.getfile(obj)) [/code] Some may choose to stay away from this sort of thing though, since inspecting the stack can tend to feel a bit like voo-doo. Passing a parameter is probably your best bet IMHO. Matt From dieterv at optionexplicit.be Fri Nov 16 08:52:12 2007 From: dieterv at optionexplicit.be (Dieter Verfaillie) Date: Fri, 16 Nov 2007 14:52:12 +0100 Subject: Volume id In-Reply-To: References: <473C2B2E.8060705@shopzeus.com> Message-ID: <1195221132.27061.6.camel@PO001> On Thu, 2007-11-15 at 17:05 +0100, Gabor Urban wrote: > OK, you are right... Problem was not precise enough. I need to process > CDs to create a list. Does it ring a bell for you? > > Thanks Hello, The method below will work on linux systems (it uses dbus to communicate with HAL). You'll maybe have to expand the filter on line 37, but I'm not sure... hth, Dieter #!/usr/bin/env python import dbus def discover(): disks = [] volumes = [] # get a connection to the system bus bus = dbus.SystemBus () # get a HAL object and an interface to HAL to make function calls hal_obj = bus.get_object ('org.freedesktop.Hal', '/org/freedesktop/Hal/Manager') hal = dbus.Interface (hal_obj, 'org.freedesktop.Hal.Manager') # find all devices that have the capability 'volume' udis = hal.FindDeviceByCapability('volume') for udi in udis: # get volume info dev_obj = bus.get_object('org.freedesktop.Hal', udi) dev = dbus.Interface(dev_obj, 'org.freedesktop.Hal.Device') volume = str(dev.GetProperty('block.device')) volume_label = str(dev.GetProperty('volume.label')) volume_mount_point = str(dev.GetProperty('volume.mount_point')) volume_fstype = str(dev.GetProperty('volume.fstype')) # get storage info parent_udi = dev.GetProperty('info.parent') dev_obj = bus.get_object('org.freedesktop.Hal', parent_udi) dev = dbus.Interface(dev_obj, 'org.freedesktop.Hal.Device') storage = str(dev.GetProperty('block.device')) storage_product = str(dev.GetProperty('info.product')) # filter out hard disks if dev.GetProperty('storage.drive_type') == 'disk': continue # store disk if not storage in disks: disks.append(storage) # store volume volumes.append((storage, volume, volume_label, volume_mount_point, volume_fstype)) return disks, volumes if __name__ == '__main__': disks, volumes = discover() for disk in disks: print 'found disk', disk for volume in volumes: if volume[0] == disk: print ' with volume', volume[1] print ' label', volume[2] print ' mount point is', volume[3] print ' fstype is', volume[4] -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: This is a digitally signed message part URL: From mnations at gmail.com Thu Nov 29 15:22:34 2007 From: mnations at gmail.com (Mudcat) Date: Thu, 29 Nov 2007 12:22:34 -0800 (PST) Subject: Outbound HTML Authentication Message-ID: Hi, I was trying to do a simple web scraping tool, but the network they use at work does some type of internal authentication before it lets the request out of the network. As a result I'm getting the '401 - Authentication Error' from the application. I know when I use a web browser or other application that it uses the information from my Windows AD to validate my user before it accesses a website. I'm constantly getting asked to enter in this info before I use Firefox, and I assume that IE picks it up automatically. However I'm not sure how to tell the request that I'm building in my python script to either use the info in my AD account or enter in my user/pass automatically. Anyone know how to do this? Thanks From steven.bethard at gmail.com Mon Nov 19 12:03:17 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 19 Nov 2007 10:03:17 -0700 Subject: Finding lowest value in dictionary of objects, how? In-Reply-To: References: <642d8c24-a6bf-488d-9416-5ad37cc91ea5@d4g2000prg.googlegroups.com> Message-ID: Boris Borcic wrote: > davenet wrote: >> Hi, >> >> I'm new to Python and working on a school assignment. >> >> I have setup a dictionary where the keys point to an object. Each >> object has two member variables. I need to find the smallest value >> contained in this group of objects. >> >> The objects are defined as follows: >> >> class Block: >> def __init__(self,addr): >> self.addr = addr >> self.age = 0 >> >> My dictionary is defined as: >> blocks = {} >> >> I have added 1000 (will hold more after I get this working) objects. I >> need to find the lowest age in the dictionary. If there is more than >> one age that is lowest (like if several of them are '1', etc), then I >> can just pick randomly any that equal the lowest value. > > >>> help(min) > Help on built-in function min in module __builtin__: > > min(...) > min(iterable[, key=func]) -> value > min(a, b, c, ...[, key=func]) -> value > > With a single iterable argument, return its smallest item. > With two or more arguments, return the smallest argument. > > >>> def f(x) : return 3*x**2+10*x-4 > > >>> min(f(x) for x in range(-100,100)) > -12 > >>> min(range(-100,100), key=f) > -2 > >>> f(-2) > -12 I'd like to second this one just so it doesn't get lost among all the other responses. You definitely want to look into the key= argument of min(). Your key function should look something like:: def key(block): # return whatever attribute of block you care about Then just modify this code:: lowest = min(self.blocks.values()) to use the key= argument as well. I don't think you need the list comprehension at all. STeVe From kyosohma at gmail.com Wed Nov 28 17:26:56 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Wed, 28 Nov 2007 14:26:56 -0800 (PST) Subject: Books on Python References: Message-ID: <5329b3e7-5f1e-4ec5-ae02-09969a30f0e5@e4g2000hsg.googlegroups.com> On Nov 27, 9:05 pm, "barcaroller" wrote: > Can someone kindly recommend some good books on the following: > > Python for beginners > Python for advanced users > > Is there a bible like Larry Wall's Programming Perl or Bjarne Stroustrup's > The C++ Programming Language? For good techniques and advanced knowledge, it's hard to beat Lutz's tome: "Programming Python 3rd Ed." or Chun's "Core Python Programming". Both are huge. Lutz's is a little bit more approachable and had more extensive code examples, but I learned a lot about Python's insides from Chun. The cookbooks are handy too, but if you troll ActiveState already, you may not need those. Mike From davisn90210 at gmail.com Mon Nov 12 12:19:58 2007 From: davisn90210 at gmail.com (davisn90210 at gmail.com) Date: Mon, 12 Nov 2007 17:19:58 -0000 Subject: how to know if folder contents have changed In-Reply-To: <1194843813.901372.246490@k35g2000prh.googlegroups.com> References: <1194843813.901372.246490@k35g2000prh.googlegroups.com> Message-ID: <1194887998.593094.67480@y27g2000pre.googlegroups.com> On Nov 11, 11:03 pm, "dev... at gmail.com" wrote: > hi > i am trying to create a cache of digitized values of around 100 > image files in a folder..In my program i would like to know from time > to time if a new image has been added or removed from the folder.. > Why not use the file creation/modification timestamps? From gandalf at shopzeus.com Tue Nov 20 14:04:28 2007 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Tue, 20 Nov 2007 20:04:28 +0100 Subject: How to add a Decorator to a Class Method In-Reply-To: References: <8026df56-e953-4e17-a439-39ef23be5259@w28g2000hsf.googlegroups.com> <5qff8tFvh912U1@mid.uni-berlin.de> <2dc98b97-84e9-4042-82d6-c31ec8dcd363@b15g2000hsa.googlegroups.com> Message-ID: <47432FBC.7010309@shopzeus.com> >> Can new_func reference self? Would self just be one of the args? >> >> -Greg >> > > For methods, self is always "just one of the args". When the > decorator is applied to a method, self will be args[0] in new_func. > If you want to use the name "self" instead of args[0] you can: def pre(fn): def new_func(self,*args,**kwargs): print "hi",self return fn(self,*args,**kwargs) return new_func Best, Laszlo From bedouglas at earthlink.net Tue Nov 6 16:40:37 2007 From: bedouglas at earthlink.net (bruce) Date: Tue, 6 Nov 2007 13:40:37 -0800 Subject: Parallel Python environments.. In-Reply-To: <1194366351.337684.309200@50g2000hsm.googlegroups.com> Message-ID: <113101c820bd$abce4930$0301a8c0@tmesa.com> i'm running rhel... so there isn't a python-config script as far as i know.. -----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 psihodelia at googlemail.com Sent: Tuesday, November 06, 2007 8:26 AM To: python-list at python.org Subject: Re: Parallel Python environments.. In Gentoo Linux you can select between installed python version using python-config script. -- http://mail.python.org/mailman/listinfo/python-list From larry.bates at websafe.com Mon Nov 19 15:49:33 2007 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 19 Nov 2007 14:49:33 -0600 Subject: python application dll In-Reply-To: <855444a7-988a-488b-b75b-dfe3ff672077@y5g2000hsf.googlegroups.com> References: <855444a7-988a-488b-b75b-dfe3ff672077@y5g2000hsf.googlegroups.com> Message-ID: dongarbage at hotmail.com wrote: > Hi, > > Is there a way to create a .dll from a python program which includes > the python runtime? > > I'm building a Windows application (C# VisualStudio2005) and I'd like > to utilize some of the functionality available in a Python module. For > my users who install my Windows application, I'd prefer that they not > have to install the entirety of Python on their machines. > > Thanks much, > D Turn the Python program into a COM object instead. Then it can be dispatched by any programming language and distributed after bundling with py2exe. -Larry From hniksic at xemacs.org Mon Nov 12 05:01:23 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Mon, 12 Nov 2007 11:01:23 +0100 Subject: Using python as primary language References: <1194508354.226023.232050@v3g2000hsg.googlegroups.com> <1194561005.427982.263160@s15g2000prm.googlegroups.com> <004801c8225e$49843350$dc8c99f0$@com> <4866bea60711081538m2b24ab48v3d223adca8b4bd7c@mail.gmail.com> <004901c82264$3b10f460$b132dd20$@com> <878x57yd2s.fsf@mulj.homelinux.net> Message-ID: <877ikn3hqk.fsf@mulj.homelinux.net> "Martin Vilcans" writes: > But if Python gets slow when you add fine-grained locks, then most > certainly it wouldn't get so slow if the locks were very fast, > right? Given the sheer number of increfs and decrefs happening, they should be impossibly fast (meaning: nonexistent). Even adding an additional test to those macros slows down Python, let alone adding a lock. > But that's not what my question was about. It was about whether it > would make sense to, on the same python installation, select between > the GIL and fine-grained locks at startup. Because even if the locks > slows down the interpreter, if they let you utilize a 32 core CPU, > it may not be so bad anymore. Unfortunately the selection must be done at compile time, not at run-time. Even taking into account the possibility of selection, so far no one has come up with a set of patches that remove the GIL that would come close to being accepted. This is a recent discussion about GIL removal that provides good reading: http://mail.python.org/pipermail/python-dev/2007-September/thread.html#74545 From robert.kern at gmail.com Thu Nov 29 13:51:18 2007 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 29 Nov 2007 12:51:18 -0600 Subject: Control mouse position and clicking In-Reply-To: <5r80m4F11ssjvU2@mid.individual.net> References: <4f209559-4454-4f8a-8ba3-18cbb50db094@b40g2000prf.googlegroups.com> <5r654mF135t4eU1@mid.individual.net> <5r80m4F11ssjvU2@mid.individual.net> Message-ID: Bjoern Schliessmann wrote: > Tony wrote: > > [place mouse programmatically] >> well, you can do it from Java, > > Are you absolutely positive? IIRC the Mac UI guidelines forbid such > things, and there's no API function for it; so Java wouldn't have > any chance. There is an API for it. Not all programs have GUIs so the HIG doesn't restrict the scope of the OS's APIs. Otherwise, one couldn't write assistive software or userland drivers for new hardware. How do you think ControllerMate does what it does? http://www.orderedbytes.com/controllermate/ In 10.4 and up, the recommended API is to use CGEventCreateMouseEvent and CGEventPost. Before that, there was CGPostMouseEvent back to 10.0, but there are situations where that can lock things up, so it is deprecated and not recommended for use. http://developer.apple.com/documentation/Carbon/Reference/QuartzEventServicesRef/Reference/reference.html -- 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 ggpolo at gmail.com Tue Nov 6 12:31:13 2007 From: ggpolo at gmail.com (Guilherme Polo) Date: Tue, 6 Nov 2007 15:31:13 -0200 Subject: Insane crazy question - printing commands In-Reply-To: References: Message-ID: 2007/11/6, Donn Ingle : > Hi, > I'm doing something odd with pycairo and friends and I want to see what > commands are coming out of my objects. > > Here's some code: > > class Box: > def draw() > self.context.set_source_rgb(1, 0, 0) > self.context.rectangle(0, 00, 50, 50) > self.context.fill() > > Box.draw() draws a red box, all fine. But, I *also* want it to output the > actual commands within the draw def to the console (or a file). > > At the moment I am doing this: > class Box: > def draw() > self.context.set_source_rgb(1, 0, 0) > self.context.rectangle(0, 00, 50, 50) > self.context.fill() > print """ > self.context.set_source_rgb(1, 0, 0) > self.context.rectangle(0, 00, 50, 50) > self.context.fill() > """ > Do you see the form? Is there some python introspection way I > can perform that automagically without having to use the print statement? > > Something like: > class Box: > def draw() > self.context.set_source_rgb(1, 0, 0) > self.context.rectangle(0, 00, 50, 50) > self.context.fill() > def dump(): > You could use inspect, something like this: import inspect class Box: def draw(self): print "hi" return 3 x = Box() print inspect.getsource(x.draw) -- -- Guilherme H. Polo Goncalves From donn.ingle at gmail.com Tue Nov 13 12:35:33 2007 From: donn.ingle at gmail.com (Donn Ingle) Date: Tue, 13 Nov 2007 19:35:33 +0200 Subject: Override method name and original method access References: <4866bea60711121156p42e5da5cy4574db5d9eae79ce@mail.gmail.com> Message-ID: > One.add(self, otherstuff) Ah! Thanks - that makes more sense. Much appreciated. /d From gc284 at vif.com Tue Nov 13 20:25:07 2007 From: gc284 at vif.com (Gordon C) Date: Tue, 13 Nov 2007 20:25:07 -0500 Subject: Arrays References: <1194917023.976618@www.vif.com><1194918994.934367.28860@v3g2000hsg.googlegroups.com><1194937100.432126.53690@k35g2000prh.googlegroups.com><1194971181.168508@www.vif.com> <13jk6af1vs5g89@corp.supernews.com> Message-ID: <1195004202.383567@www.vif.com> OK Steve, But why do we say "from array import array" and NOT "from math import math"? Why the difference in syntax? Gord "Steven D'Aprano" wrote in message news:13jk6af1vs5g89 at corp.supernews.com... > On Tue, 13 Nov 2007 11:26:28 -0500, Gordon C wrote: > >> OK, thanks to all. The key statement is "from array import array" which >> is not exactly intuitive! > > > "The only intuitive interface is the nipple. After that, it's all > learned." -- Bruce Ediger on user interfaces. > > Once you've been using Python for a while, using import becomes as > intuitive as a spoon. The only tricky part is knowing *which* module to > import. But, honestly, are you surprised to learn that the array type is > held in in the array module? > > > > -- > Steven. From kyosohma at gmail.com Fri Nov 9 19:44:43 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Sat, 10 Nov 2007 00:44:43 -0000 Subject: Python Extension Building Network In-Reply-To: References: <1194617297.075298.238880@i13g2000prf.googlegroups.com> <1194623343.121618.65350@v3g2000hsg.googlegroups.com> Message-ID: <1194655483.880861.120570@o38g2000hse.googlegroups.com> On Nov 9, 5:26 pm, "M.-A. Lemburg" wrote: > kyoso... at gmail.com wrote: > > On Nov 9, 8:36 am, Tim Golden wrote: > >> kyoso... at gmail.com wrote: > >>> Hi, > >>> I am trying to get a small group of volunteers together to create > >>> Windows binaries for any Python extension developer that needs them, > >>> much like the package/extension builders who volunteer their time to > >>> create Linux RPMs. > > Are you aware of the repository that ActiveState created for > its version of Python (ActivePython) ? It comes with a > set of pre-compiled Python extensions (PPMs) and an easy > to use installer. > > Perhaps getting ActiveState to open up the repo would be good > idea - something like Ubuntu does with the universe repo. > > > > >>> The main thing I need are people willing to test the binaries to make > >>> sure the extension is stable. This would require installing the binary > >>> and probably downloading the source too to get the developer's test > >>> code. I've been able to get some of the tests to run great while > >>> others are pretty finicky and some extensions don't come with tests. > >>> It would be nice to know which extensions are most in need of this > >>> too. > >>> While I can create the binaries on my own for a while, if I get too > >>> many requests, there will be a backlog, so it would be nice to have > >>> help with that too. I'm also looking for knowledgeable people to be > >>> sounding boards (i.e. give advice). > >>> Developers: all I would require is a request, a link to the source, > >>> and a well-written setup.py file for a cross-platform extension. > >>> You can find the few that I've already done here:http:// > >>>www.pythonlibrary.org/python_modules.htm > >>> I have also posted a way to create the binaries using the MinGW > >>> compiler. I have VS2003 installed on my PC and MinGW is installed in a > >>> VM, so I can compile the extensions both ways. > >> Mike, this is great news. Whenever I have time >> means it sincerely> I'll try to run through some of the modules > >> you've compiled. > > >> As a slight aside, the main problem I've found when I've tried > >> to build extensions (and I've been doing it recently with AVBin and > >> Pyglet) is that Windows just doesn't have the build environment, the > >> directory structures, the env vars and all that that a ./configure or > >> even a python setup.py install sometimes expects. eg if I were to > >> offer to build a MySQL extension (as someone who doesn't use MySQL > >> and wouldn't have the source libs installed if I did) there would > >> be a fair bit of pain to go through. You've obviously gone through > >> that pain barrier for at least some of the extensions on the modules > >> page. Was it tough? > > > The hardest part was finding accurate information. Most people on the > > user groups have been unhelpful or sarcastic. I had better luck > > contacting developers directly who had already created Windows > > binaries. They didn't mind giving me some pointers. > > Interesting: Python seems to be "growing up" in all kinds of > ways ... > > > The directions for MinGW were usually only partially correct. So I > > went through the two sets of directions I found (links on the site) > > and mixed and matched until I got it right. > > > There are no directions on how to use Visual Studio 2003 that I've > > found, just some old free edition. those directions were incompatible > > with VS2003. I'll post VS2003's correct usage eventually, but it's > > basically just installing it and then using distutils. > > Getting VS2003 ready to compile Python extensions is really easy: > > 1. open a command shell > 2. run vcvars32.bat > 3. make sure the Python version you are targetting is on the > PATH > 4. "python setup.py bdist_wininst" or "python setup.py bdist_msi" > 5. pick up the installer in the build\ directory. > I didn't need to run vcvars32.bat to make mine work. But that's good to know...I think. > Note: bdist_msi is only available in Python 2.5 and later. > > You need VC6 if you want to compile extensions for Python 1.5-2.3 > and VC7.1 for Python 2.4 and later. > I was aware of that you needed VC6 for 2.3, but I didn't realize it went that far back. And I knew you needed 7.1 for 2.4 and 2.5, but I've heard that they're moving to VS2005 soon. Thanks for the feedback, Marc-Andre! Mike > > -- > Marc-Andre Lemburg > eGenix.com > From fredrik.johansson at gmail.com Wed Nov 14 04:20:26 2007 From: fredrik.johansson at gmail.com (Fredrik Johansson) Date: Wed, 14 Nov 2007 10:20:26 +0100 Subject: mpmath puzzle Message-ID: <3d0cebfb0711140120g11aa2096x9172015f84984ad9@mail.gmail.com> Dick Moores wrote: > For 1234 ** 10.9, why the wrong result from mpmath.power()? > > ======================================== > #!/usr/bin/env python > #coding=utf-8 > from mpmath import * > > mpf.dps = 32 > > x = mpf(1234) > y = mpf(10.9) > > print power(x,y) > print "4.9583278648155041477415234438717e+33" # from Windows calculator > > """ > output: > 4.9583278648155166864966558721921e+33 > 4.9583278648155041477415234438717e+33 > """ > ======================================== > (Code is also at ) > > Thanks, > > Dick Moores Hi, When you create y, you first create an inexact Python float whose value is actually 10.900000000000000355... and then pass it to mpf, which just copies that value along with the error. To create an accurate representation of a fractional number (integers are safe), pass a string instead: >>> from mpmath import * >>> >>> mpf.dps = 32 >>> x = mpf(1234) >>> y = mpf('10.9') >>> print power(x,y) 4.9583278648155041477415234438719e+33 The last printed digit is wrong, which is to be expected in binary arithmetic since 10.9 still cannot be represented exactly (with mpf.dps = 32, the error is about 5e-033); computing a power amplifies that error. You can temporarily increase the precision by a couple of digits during calculations and then reduce it before printing the final value if you want all digits to be right. I should update the mpmath documentation to be much clearer about all this. Fredrik From donn.ingle at gmail.com Fri Nov 30 08:55:16 2007 From: donn.ingle at gmail.com (Donn Ingle) Date: Fri, 30 Nov 2007 15:55:16 +0200 Subject: Gnu/Linux dialogue boxes in python Message-ID: Hi, Okay, so I am in the mood to try this: Inform the user about what modules the app requires in a graphical dialogue that can vary depending on what the system already has installed. (It will fail-to output on cli) I am running Kubuntu and I seem to have 'kdialog' installed by default (not sure if it came as stock.) What other 'stock' systems are there out there in the wild? Ubuntu? Suse? Fedora? Others? I would take a stab at wrapping them in python so that I can use the first dialogue system found to popup messages for the user. (Hoping, natch, that this has already been done ... ? ) \d From george.sakkis at gmail.com Mon Nov 19 10:08:57 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 19 Nov 2007 07:08:57 -0800 (PST) Subject: overriding methods - two questions References: <473dd35a$0$7999$426a34cc@news.free.fr> <13js4tebjlucv16@corp.supernews.com> <1b944969-1157-4f9f-86cb-153c176e7027@b40g2000prf.googlegroups.com> <47418533$0$20133$426a34cc@news.free.fr> Message-ID: <1600e5df-71b1-4dbc-bad0-378fcfcfe9b0@s19g2000prg.googlegroups.com> On Nov 19, 7:44 am, Bruno Desthuilliers wrote: > George Sakkis a ?crit : > > > > > On Nov 16, 5:03 pm, Steven D'Aprano > cybersource.com.au> wrote: > > >> On Fri, 16 Nov 2007 18:28:59 +0100, Bruno Desthuilliers wrote: > >>>> Question 1: > >>>> Given that the user of the API can choose to override foo() or not, how > >>>> can I control the signature that they use? > >>> While technically possible (using inspect.getargspec), trying to make > >>> your code idiot-proof is a lost fight and a pure waste of time. > >> Worse: it's actually counter-productive! > > >> The whole idea of being able to subclass a class means that the user > >> should be able to override foo() *including* the signature. Why do you > >> want to stop them? > > > Primarily because of this:http://en.wikipedia.org/wiki/Liskov_substitution_principle. > > >> Let me give a practical example: > > >> (snip misleading example involving __init__) > > > Constructors are in general different from other regular methods > > because you refer explicitly to the class name when creating an > > instance; > > Not necessarily. There are (quite a few) cases where you don't know > which "concrete" class you're instanciating... > > > that is, the client writes "f = ContinuedFraction(...)" or > > "f = RegularCF(...)" so it's not necessary to have the same signature > > in __init__. > > import platform > cls = platform.get_the_class() > obj = cls('yadda', 42) That's why I qualified my statement with "in general" ;-) Besides, this emphasizes even further the need for consistent (though not necessarily identical) signatures in all (public) methods, which was my point anyway. George From martin at v.loewis.de Thu Nov 8 15:24:25 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 08 Nov 2007 21:24:25 +0100 Subject: Old version of sqlite3 In-Reply-To: References: Message-ID: <47337079$0$18065$9b622d9e@news.freenet.de> > Any suggestions for a workaround? You could silence the warning, using the warnings module. Alternatively, I think you should be able to replace sqlite3.dll with a newer version. Regards, Martin From gagsl-py2 at yahoo.com.ar Sat Nov 3 10:42:13 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 03 Nov 2007 11:42:13 -0300 Subject: python newbie References: <472b2b84$0$13761$6e1ede2f@read.cnntp.org> <5p0s6vFp47k9U1@mid.individual.net> <472b5251$0$6238$426a34cc@news.free.fr> <13ioa6f6t797gce@corp.supernews.com> <7x4pg3wks5.fsf@ruckus.brouhaha.com> Message-ID: En Sat, 03 Nov 2007 09:55:38 -0300, Paul Rubin <"http://phr.cx"@NOSPAM.invalid> escribi?: > Duncan Booth writes: >> modules are not special in any way, except that you cannot subclass >> them. >> Oops, sorry I got that wrong. Modules are not special in any way, they >> can >> have methods as well as functions: > > I've felt for a long time that you should be able to define __call__ > on a module, but that doesn't seem to be allowed, at least if you > try it in the obvious way. Notice that you usually define __call__ for a *type*, not for specific object instances. All special methods, like __call__, are searched on the type - not on the instance. And all modules are instances of the same type. For something like that to work, each module should be a *subclass* of moduletype, not an instance. -- Gabriel Genellina From zaz600 at gmail.com Wed Nov 21 22:58:04 2007 From: zaz600 at gmail.com (NoName) Date: Wed, 21 Nov 2007 19:58:04 -0800 (PST) Subject: how terminate console(not Ctrl-C) Message-ID: Is it possible to interrupt loop (program) by pressing Q key like Ctrl- C? how can i hook user's keypress while program running? thnx From atuc at gmx.de Sun Nov 25 12:29:58 2007 From: atuc at gmx.de (Alexander Tuchacek) Date: Sun, 25 Nov 2007 18:29:58 +0100 Subject: PyQt, Cannot send events to objects owned by a different thread? References: Message-ID: <4749b116$0$27128$9b4e6d93@newsspool1.arcor-online.net> David Boddie wrote: > You can either construct some sort of event handling mechanism or use > signals and slots. Personally, I'd use signals and slots for this, if > possible. > > The idea would be to set up a connection between your callback code and > the status bar's showMessage() slot. Then you would only have to emit that > signal to update the status bar. hallo david, great, the signal an slot mechanism works over threads, thanks alex From jcd at sdf.lonestar.org Sun Nov 25 17:33:54 2007 From: jcd at sdf.lonestar.org (J. Clifford Dyer) Date: Sun, 25 Nov 2007 17:33:54 -0500 Subject: basic if stuff- testing ranges In-Reply-To: References: Message-ID: <1196030034.6057.20.camel@jcd-desktop> On Sun, 2007-11-25 at 20:49 +0200, Donn Ingle wrote: > Sheesh, I've been going spare trying to find how to do this short-hand: > if 0 > x < 20: print "within" > if 0 > x: print "within" From jstroud at mbi.ucla.edu Sat Nov 17 23:36:29 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 17 Nov 2007 20:36:29 -0800 Subject: Mac os x 10.4.11: Error installing Python 2.5.1 In-Reply-To: References: <5aded601-3773-4cc4-a68d-d84f561aea88@e10g2000prf.googlegroups.com> Message-ID: David wrote: > On Nov 17, 7:27 pm, James Stroud wrote: >> David wrote: >>> Running OS X 10.4.11 PPC. No Intel. >>> I downloaded: >>> http://www.python.org/ftp/python/2.5.1/python-2.5.1-macosx.dmg >>> I started the install, accepted the license, selected easy install, >>> then upgrade, entered my password for the mac, but the installation >>> process finished with: >>> There were errors installing the software. Please try installing >>> again. >> Usually this happens when you are not an administrator. If you aren't >> log out and log in again as one. If that doesn't do it, what does your >> /Applications/Utilities/Console say? > Rebooted. I am admin. Tried installing again. Same result. console.log > has this: > > Mac OS X Version 10.4.11 (Build 8S165) > 2007-11-17 19:59:32 -0800 > 2007-11-17 19:59:40.718 SystemUIServer[334] lang is:en > Nov 17 19:59:45 darnold diskarbitrationd[44]: SystemUIServer [334]: > 27139 not responding. My best guess is that you have a problem with your account. Try creating a new administrative user and log in as that user, then try the install. Also, some external storage devices can cause this problem. If you have this problem after you create the new user and log in as that user, then log out and remove all external storage devices and log in again as the new user. It will not be sufficient simply to authenticate as said user from your preexisting account. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com From giles_brown at hotmail.com Thu Nov 1 09:31:31 2007 From: giles_brown at hotmail.com (Giles Brown) Date: Thu, 01 Nov 2007 06:31:31 -0700 Subject: Which persistence is for me? In-Reply-To: References: Message-ID: <1193923891.451429.205200@o80g2000hse.googlegroups.com> On 1 Nov, 11:47, Neal Becker wrote: > I need to organize the results of some experiments. Seems some sort of > database is in order. > > I just took a look at DBAPI and the new sqlite interface in python2.5. I > have no experience with sql. I am repulsed by e.g.: > c.execute("""insert into stocks > values ('2006-01-05','BUY','RHAT',100,35.14)""") > > ewww. How unpythonic. I don't want to use a string to specify what > function to execute. I want to call a function (c.insert?). > > Is there some other interface/database that I might like better? http://wiki.python.org/moin/HigherLevelDatabaseProgramming From horpner at yahoo.com Thu Nov 1 17:23:37 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Thu, 01 Nov 2007 21:23:37 GMT Subject: Syntax coloring in Python interpreter References: <1193939152.721480.140500@22g2000hsm.googlegroups.com> Message-ID: On 2007-11-01, Chris Mellon wrote: > On Nov 1, 2007 3:01 PM, Neil Cerutti wrote: >> On 2007-11-01, Lee Capps wrote: >> > >> > On Nov 1, 2007, at 1:45 PM, braver wrote: >> >> Greetings -- as a long time user of both Python and Ruby >> >> interpreters, I got used to the latter's syntax-coloring gem, >> >> wirble, which colorizes Ruby syntax on the fly. Is there >> >> anything similar for Python? >> >> >> > >> > I believe IPython can do this: >> > >> > http://ipython.scipy.org/moin/ >> >> IPython's syntax coloring doesn't work with Windows 2000 and >> up, since (last I checked) it relies on a readline.py file, >> which relies on ANSI.SYS, which is not supported by the >> Windows console. > > If you scroll down about half a page in the above link you'll > find a link to a readline implementation for Windows. That pyreadline.py appears to be an improvement on the Windows support when I last looked (6 months or so ago). Thanks for the heads up. -- Neil Cerutti From Russ.Paielli at gmail.com Tue Nov 6 19:56:24 2007 From: Russ.Paielli at gmail.com (Russ P.) Date: Wed, 07 Nov 2007 00:56:24 -0000 Subject: command-line arguments in IDLE Message-ID: <1194396984.553516.158420@e34g2000pro.googlegroups.com> Is it possible to pass command-line arguments when running a program in IDLE? The "Run" menu does not seem to provide that option. Thanks. From martin at v.loewis.de Wed Nov 14 16:31:39 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 14 Nov 2007 22:31:39 +0100 Subject: Building python packages for the correct architecture on OSX 10.5 In-Reply-To: <1195069840.338560.74320@o3g2000hsb.googlegroups.com> References: <1195061700.315152.61070@22g2000hsm.googlegroups.com> <473b4f1b$0$17353$9b622d9e@news.freenet.de> <1195069840.338560.74320@o3g2000hsb.googlegroups.com> Message-ID: <473B693B.4000007@v.loewis.de> >> a) even if your extension module becomes x86_64 with that mechanism, >> the Python interpreter itself (i.e. the Python framework) will be >> purely 32-bit code. So it should not link correctly. > > My machine disagrees: I see. I guess Apple has implemented that somehow; the official Python release does not support such an operation. Regards, Martin From jcd at sdf.lonestar.org Fri Nov 16 09:17:11 2007 From: jcd at sdf.lonestar.org (J. Clifford Dyer) Date: Fri, 16 Nov 2007 09:17:11 -0500 Subject: sorting contacts alphabetically, sorted by surname In-Reply-To: References: Message-ID: <20071116141711.GB16174@sdf.lonestar.org> On Fri, Nov 16, 2007 at 12:31:19PM +0000, Marie Hughes wrote regarding sorting contacts alphabetically, sorted by surname: > > HI > > I have to write a program that contains a text file in the following > format: > > Academic Position Room Ext. Email > Prof Marie Maguire Head of > School M9002 0000 [1]lp.muire at ulioooor.ac.uk > > And produce a output file where conatcts are sorted alphabetically- > sorted by surname. > > Has anyone any ideas. Well, the first thing you need to do is develop a workable understanding of how your data file is formatted. What separates one field from another? Is it tab-delimited? Does the field always start at a given column number? Then you need to read each line of the file, and split the lines up according to the format. Save to a data structure, sort by last name (you'll have to further parse the name to isolate this information), and reprint the results. Depending on the details you uncover about the precise format of your data file, you will find it helpful to read the documentation on string methods, particularly s.split(), and sequence slicing: s[4:14]. Best of luck with it. Cheers, Cliff From sgeiger at ncee.net Mon Nov 26 08:26:07 2007 From: sgeiger at ncee.net (Shane Geiger) Date: Mon, 26 Nov 2007 07:26:07 -0600 Subject: Add speller to Python application In-Reply-To: References: Message-ID: <474AC96F.6080506@ncee.net> http://pyenchant.sourceforge.net/ helzer wrote: > I need to add spell checking to my Python application (for Windows). > Any ideas on where to start? > > Thanks, > Helzer > -- Shane Geiger IT Director National Council on Economic Education sgeiger at ncee.net | 402-438-8958 | http://www.ncee.net Leading the Campaign for Economic and Financial Literacy From grzesiof at gmail.com Tue Nov 13 01:03:36 2007 From: grzesiof at gmail.com (gz) Date: Tue, 13 Nov 2007 06:03:36 -0000 Subject: pyopenglcontext binaries for 2.5 on win32 Message-ID: <1194933816.838109.45470@v3g2000hsg.googlegroups.com> no, I don't have them... I need them :) I'd like to thank Giovanni Bajo for providing binaries for the various package dependencies, and geting me going with pyopengl. Unfortunately I only menaged to run a basic example, where there's no animation. The glwindow only get's redrawn when it's resized, moved... well generally redrawed as a window. I would greatly appreciate some hints, about how to process the gui events in the gl portion, and how to run a continous animation in wx + pyopengl? I suspect the whole thing would be way easier with pyopenglcontext, but I can't seem to find a binary for python 2.5 I can't get it to install with mingw and don't have vc currently installed. If someone has successfully built it, plesase share. Although, I think, an example of a running opengl spinning cube, embedded in some wx menu + buttons, capable of handling, say, mouse clicks in the glwindow, would work best for me. I'm not even that keen on wx. I choose it, purely, on the basis that wx is generaly brought up here frequenter than qt. (Didn't qt have some licensing change in the last few months that could potentially change that?) From ramamoorthy003 at gmail.com Sat Nov 24 05:25:23 2007 From: ramamoorthy003 at gmail.com (roja) Date: Sat, 24 Nov 2007 02:25:23 -0800 (PST) Subject: see the jop Message-ID: <198f0b69-05a7-4c5d-a344-3e6ac687b7e0@d4g2000prg.googlegroups.com> see the jop http://earnmac.blogspot.com From anthonybaxter at gmail.com Thu Nov 29 19:38:51 2007 From: anthonybaxter at gmail.com (Anthony Baxter) Date: Fri, 30 Nov 2007 11:38:51 +1100 Subject: Lib for audio? In-Reply-To: References: Message-ID: On Nov 29, 2007 11:04 PM, Dave wrote: > I need to read microphone input and determine frequency. Is there a lib > for that? There's a bunch of code in shtoom for both reading from the mike on different platforms, and doing a bit of frequency analysis (for inline DTMF detection). From bborcic at gmail.com Tue Nov 6 07:54:14 2007 From: bborcic at gmail.com (Boris Borcic) Date: Tue, 06 Nov 2007 13:54:14 +0100 Subject: Trouble with for loop In-Reply-To: <1194344347.943085.306080@q5g2000prf.googlegroups.com> References: <1194343197.272342.16130@t8g2000prg.googlegroups.com> <1194343786.700768.191040@d55g2000hsg.googlegroups.com> <1194344347.943085.306080@q5g2000prf.googlegroups.com> Message-ID: <4730642f$1_1@news.bluewin.ch> Shriphani wrote: > On Nov 6, 3:09 pm, Ant wrote: >> On Nov 6, 9:59 am, Shriphani wrote: >> ... >> >>> My main intention is to state that each of the variables namely a, b, >>> c, ## can take value from 1 to 9. >>> How do I go about this ? >> It sounds like you are after something like: >> >> for var in (a, b, c, d, e, f): >> assert var in [1, 2, 3, 4, 5, 6, 7, 8, 9] >> >> but it's hard to tell without some more information from you on >> exactly what you are trying to achieve. > > I want to obtain a number whose first digit "a" is divisible by 1, > 10*b +a is divisible by 2, 10^2*c + 10b + a is divisible by 3 and so > on. And so on ? up to how many digits ? 10^3 is divisible by 4 and 10^4 is divisible by 5 so that the conditions on the fourth and fifth digits boil down to 10^2*c+10b+a being divisible by 4 and 5 in supplement to 3, iow divisible by 60. This implies a==0 but you seem to say that a must be in [1, 2, 3, 4, 5, 6, 7, 8, 9]. > I hope my question is a bit clearer now. Not really :) > Thanks, > Shriphani Palakodety > From brian.p.hunter at gmail.com Tue Nov 27 13:58:37 2007 From: brian.p.hunter at gmail.com (bhunter) Date: Tue, 27 Nov 2007 10:58:37 -0800 (PST) Subject: spawning a process with subprocess References: <8b45ae31-a3e2-470f-93d0-ad31d8717176@s36g2000prg.googlegroups.com> <9gk5o4knd5.fsf@overberg.got.jeppesensystems.com> Message-ID: <243adf48-3041-4653-aa4b-964990fd751a@s36g2000prg.googlegroups.com> Wow, everyone. Great comments. Thanks so much! A few points on all of the above, just so I don't look too stupid: * The problem with the testcase, I believe, was the size of the file and the output pipe filling up, as Nick suggested. When run on a smaller file, with Jordan's suggestions, it works fine. With a larger file, it's necessary to do as Nick says. If the size of the file is unknown, its best to use this case as the default. This seems unfortunate to me, because it's quite a bit of code to do something that should be fairly straightforward--at least, that's what I think. * Using poll() and checking for None and not non-zero: Yes, I had both of those originally in my testcase, but when I re-wrote and re- wrote it after it initially didn't work those initial concepts got dropped. Thanks for reminding me. * Yes, I should use proc instead of thread as a variable. Good point, Ove. But your solution works on small files but chokes on larger files, too. Thanks again...and just to reiterate, I really think this could be more straightforward for the rest of us if Popen could do all of this on its own. Brian On Nov 27, 5:13 am, Ove Svensson wrote: > bhunter writes: > > Hi, > > > I've used subprocess with 2.4 several times to execute a process, wait > > for it to finish, and then look at its output. Now I want to spawn > > the process separately, later check to see if it's finished, and if it > > is look at its output. I may want to send a signal at some point to > > kill the process. This seems straightforward, but it doesn't seem to > > be working. > > > Here's my test case: > > > import subprocess, time > > > cmd = "cat somefile" > > thread = subprocess.Popen(args=cmd.split(), shell=True, > > stdout=subprocess.PIPE, stdin=subprocess.PIPE, > > stderr=subprocess.STDOUT, close_fds=True) > > > while(1): > > time.sleep(1) > > if(thread.returncode): > > break > > else: > > print thread.returncode > > > print "returncode = ", thread.returncode > > for line in thread.stdout: > > print "stdout:\t",line > > > This will just print the returncode of None forever until I Ctrl-C it. > > > Of course, the program works fine if I call thread.communicate(), but > > since this waits for the process to finish, that's not what I want. > > > Any help would be appreciated. > > Reading documentation for subprocess, it mentions that > > On UNIX, with shell=False (default): In this case, the Popen class > uses os.execvp() to execute the child program. args should normally > be a sequence. A string will be treated as a sequence with the string > as the only item (the program to execute). > > On UNIX, with shell=True: If args is a string, it specifies the > command string to execute through the shell. If args is a sequence, > the first item specifies the command string, and any additional items > will be treated as additional shell arguments. > > Since you have specified shell = True, and since you pass a sequence as > args, you will efficiently invoke the cat process through the shell and > then pass somefile as an extra argument to she shell (not the cat command) > That is probably not what you intended. > > This can be solved by either > - Not splitting the cmd, in which case you will pass the whole cmd > string to the shell for execution > - Or setting shell to False. This is what I would have done, since > I can't see any reason for going via the shell. Please note that > if setting shell to False, you must then split the cmd. > > Please also note that your test for the returncode might not work > since a normal returncode is 0. Your code will only detect non-0 > values. > > Also, it is good practice to call wait() on the subprocess in order > to avoid zombie-processes. > > Finally, I find it somewhat misleading to use the name thread for > the variable used to represent a sub-process. Threads and processes > are not exactly the same > > Hence, the following code should works as expected > > cmd = "cat somefile" > proc = subprocess.Popen( > args = cmd.split(), > shell = False, > stdin = None, > stdout = subprocess.PIPE, > stderr = subprocess.STDOUT, > close_fds = True) > > while True: > rc = proc.poll() > if rc != None: break > print rc > time.sleep(1) > > lno = 1 > for lin in proc.stdout: > print '%i: %s' % (lno,lin.rstrip('\n')) > lno += 1 > > rc = proc.wait() > print "rc = %i" % rc > > /Ove From kyosohma at gmail.com Mon Nov 26 11:50:23 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 26 Nov 2007 08:50:23 -0800 (PST) Subject: win32serviceutil won't start References: <3e7ed25b-4289-4b19-b216-b8459a110c29@e25g2000prg.googlegroups.com> Message-ID: <8a487ea6-94c4-4d52-a754-618caeaa5dae@o6g2000hsd.googlegroups.com> On Nov 25, 5:11 pm, Nikola Skoric wrote: > Dana Sun, 25 Nov 2007 13:52:35 -0800 (PST), > kyoso... at gmail.com kaze: > > > Looks like Microsoft thinks you mis-spelled it. > > >http://www.microsoft.com/technet/prodtechnol/windows2000serv/reskit/w... > > > I would check and see if that service is installed on your PC. You can > > go to Start --> Run and type services.msc > > > Scroll through there and see if your service is listed. You might > > check to see if you can enable/disable it via that console as well. > > Seems like I misunderstood Windows services (I'm porting UNIX daemon > to Windows so I'm thinking in UNIX terms). I didn't know I have to > _install_ a service before I _start_ it. How do I install a service? > > -- > "Now the storm has passed over me > I'm left to drift on a dead calm sea > And watch her forever through the cracks in the beams > Nailed across the doorways of the bedrooms of my dreams" Sorry I didn't reply sooner. If you're creating a service based on a Python file, check out the following links in addition to the book Wolfgang mentioned: http://agiletesting.blogspot.com/2005/09/running-python-script-as-windows.html http://www.thescripts.com/forum/thread595660.html http://essiene.blogspot.com/2005/04/python-windows-services.html That should get you started. Hope it helps! Mike From dominiquevalentine at gmail.com Wed Nov 14 17:23:44 2007 From: dominiquevalentine at gmail.com (dominiquevalentine at gmail.com) Date: Wed, 14 Nov 2007 22:23:44 -0000 Subject: Using Python To Change The World :) In-Reply-To: References: <1195040866.173845.173360@v65g2000hsc.googlegroups.com> Message-ID: <1195079024.444810.270230@s15g2000prm.googlegroups.com> On Nov 14, 5:38 am, "Sells, Fred" wrote: > It sounds as if this project is a major task based on your current level of experience. That being said, all we "pythonistas" encourage and support anyone who is trying to learn/apply python. > > Break the problem into 2 parts: > --simulation math of what you're trying to do > --cool visual display (2D is sufficient) to make it interesting and so others can grasp what you did > > Then the math drives the display, but you can build and test the math using text output. > > pygame and pysim are good candidates. There is alsowww.vpython.org. Make sure you find some tutorial on object oriented programming "OOP" because that's the way to build this critter. > > I'm assuming you have a fairly powerful PC, if so you need a decent development environment. google for python IDE or check at python.org. I use Eclipse + PyDev (both free) although there is a wide difference of opinion on IDE's. > > Remember to eat the elephant one byte at a time. i.e. small steps. > > > -----Original Message----- > > From: python-list-bounces+frsells=adventistcare.... at python.org > > [mailto:python-list-bounces+frsells=adventistcare.... at python.org]On > > Behalf Of Ant > > Sent: Wednesday, November 14, 2007 6:48 AM > > To: python-l... at python.org > > Subject: Re: Using Python To Change The World :) > > > On Nov 14, 3:09 am, dominiquevalent... at gmail.com wrote: > > ... > > > so here is MY question: > > > how would you replicate a street intersection in python? and > > > furthermore, how would you do you have the cars move up and > > down those > > > "streets". > > > I've never used it, but I'd have thought that pygame would satisfy the > > graphical side of things. > > > -- > > Ant > > > -- > >http://mail.python.org/mailman/listinfo/python-list ah, great advice. thanks very much. thank you to everyone for helping :) From bscrivener42 at gmail.com Tue Nov 27 10:13:09 2007 From: bscrivener42 at gmail.com (BartlebyScrivener) Date: Tue, 27 Nov 2007 07:13:09 -0800 (PST) Subject: reading/writing files References: <1d4cb97a-847b-45d6-b9a6-2ba51dfedbaa@b40g2000prf.googlegroups.com> <9726f81b-3497-47b3-91f3-ffa9a2b61a3e@a35g2000prf.googlegroups.com> Message-ID: On Nov 27, 7:14 am, sandipm wrote: > f1= open("file1.pdf", "rb") > x = f1.read() > open("file2.pdf", "wb").write(x) > > works... > > thanks > sandip You might also like: http://pybrary.net/pyPdf/ From aaron.watters at gmail.com Fri Nov 30 17:18:04 2007 From: aaron.watters at gmail.com (Aaron Watters) Date: Fri, 30 Nov 2007 14:18:04 -0800 (PST) Subject: "Python" is not a good name, should rename to "Athon" References: Message-ID: <9c5782f7-f3f6-4efe-b953-579280d61eee@p69g2000hsa.googlegroups.com> On Nov 30, 9:58 am, ureuffyrtu... at gmail.com wrote: > Now, python3000 is coming. It's the best time to rename! Yes, but "Thong" would be a better name, due to the minimalist syntax and the attraction/repulsion/catatonic revulsion effect it has with different people from different cultural backgrounds. -- Aaron Watters === http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=nasty+reasons From bedouglas at earthlink.net Tue Nov 6 10:13:43 2007 From: bedouglas at earthlink.net (bruce) Date: Tue, 6 Nov 2007 07:13:43 -0800 Subject: Parallel Python environments.. Message-ID: <104f01c82087$9fa566b0$0301a8c0@tmesa.com> Hi.. If I wanted to be able to build/test/use parallel python versions, what would I need to do/set (paths/libs/etc...) and where would I need to place the 2nd python version, so as not to screw up my initial python dev env. I'd like to be able to switch back/forth between the different versions if possible. I know it should be, but I haven't been able to find what I'm looking for via the 'net... Any sites/pointers describing the process would be helpuful. In particular, any changfes to the bashrc/profile/etc... files to allow me to accomplish this would be helpful. thanks From steve at REMOVE-THIS-cybersource.com.au Thu Nov 1 10:24:38 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Thu, 01 Nov 2007 14:24:38 -0000 Subject: A Python 3000 Question References: <1193761000.248965.139690@y42g2000hsy.googlegroups.com> <1193842798.085242.22690@t8g2000prg.googlegroups.com> <13ii0dpq86mhhfc@corp.supernews.com> <1193896092.501853.92470@50g2000hsm.googlegroups.com> Message-ID: <13ijod6b3viulcb@corp.supernews.com> On Wed, 31 Oct 2007 22:48:12 -0700, Carl Banks wrote: >> I hope you're not serious that $# would make a good operator. > > If you happen to know where I borrowed it from, it would be pretty > evident that I wasn't being serious. Ooh, now I'm curious. -- Steven. From http Mon Nov 19 11:41:15 2007 From: http (Paul Rubin) Date: 19 Nov 2007 08:41:15 -0800 Subject: Efficient (HUGE) prime modulus References: <144c4524-fb8d-4a11-8851-ea6761dad9e7@l1g2000hsa.googlegroups.com> Message-ID: <7x8x4urxw4.fsf@ruckus.brouhaha.com> blaine writes: > A = (G ** a) % P # G^a mod P Think of how large the intermediate result G**a will be. That should explain why it's taking so long. So figure out what Java's modPow function must be doing, and write something similar. Or, see the docs for python's built-in pow function. From ggpolo at gmail.com Tue Nov 13 22:21:51 2007 From: ggpolo at gmail.com (Guilherme Polo) Date: Wed, 14 Nov 2007 01:21:51 -0200 Subject: Using Python To Change The World :) In-Reply-To: <1195009751.327435.182540@i13g2000prf.googlegroups.com> References: <1195009751.327435.182540@i13g2000prf.googlegroups.com> Message-ID: 2007/11/14, dominiquevalentine at gmail.com : > Hello, I'm a teen trying to do my part in improving the world, and me > and my pal came up with some concepts to improve the transportation > system. > > I have googled up and down for examples of using python to create a > city street but I can not find any. > > my objective is to replicate a section of los angeles using python, > and program the street lights and cars and whatnot. Should I be > looking towards 3D to do this? > > so here is MY question: > how would you replicate a street intersection in python? and > furthermore, how would you do you have the cars move up and down those > "streets". > > my question to YOU is: > can you point me in the right direction? I will search on my own, but > I would greatly appreciate any help :) > > and if anyone is interested in learning more about this project (we've > got some nifty things planned), or if you wanna help, give a shout ;] > > -- > http://mail.python.org/mailman/listinfo/python-list > It seems you are looking something to build an user interface. You could do such thing in tkinter, for example. You would "move" cars by redrawing them in other positions after time. But besides doing these drawings, you will be doing a lot of math to improve the transportation system. The drawings will be just a representation of what you calculate, I dont see why it would be important to do it in 3d right now. -- -- Guilherme H. Polo Goncalves From kf9150 at gmail.com Mon Nov 26 11:36:13 2007 From: kf9150 at gmail.com (Kelie) Date: Mon, 26 Nov 2007 08:36:13 -0800 (PST) Subject: better way to write this function References: <4b4d9cc5-3759-421e-b3a2-3cb25bdaae7a@b40g2000prf.googlegroups.com> <87y7clpdep.fsf@rudin.co.uk> Message-ID: <66e0aab3-e91c-49f4-b605-a84bfca2ccf1@s36g2000prg.googlegroups.com> On Nov 25, 11:24 pm, Paul Rudin wrote: > See the last recipe from:http://docs.python.org/lib/itertools-recipes.html. It's not doing > quite the same thing, but gives an illustration of one way to approach > this sort of thing. Thanks for the link! From maarten.sneep at knmi.nl Mon Nov 5 10:29:42 2007 From: maarten.sneep at knmi.nl (Maarten) Date: Mon, 05 Nov 2007 07:29:42 -0800 Subject: Python good for data mining? In-Reply-To: <1194270693.957593.55250@19g2000hsx.googlegroups.com> References: <1194141739.683498.206780@k79g2000hse.googlegroups.com> <1194234136.556841.246740@v3g2000hsg.googlegroups.com> <1194270693.957593.55250@19g2000hsx.googlegroups.com> Message-ID: <1194276582.961527.101890@57g2000hsv.googlegroups.com> On Nov 5, 1:51 pm, Jens wrote: > On 5 Nov., 04:42, "D.Hering" wrote: > > > On Nov 3, 9:02 pm, Jens wrote: > > > I then leaned C and then C++. I am now coming home to Python realizing > > after my self-eduction, that programming in Python is truly a pleasure > > and the performance is not the concern I first considered to be. > > Here's why: > > > Python is very easily extended to near C speed. The Idea that FINALLY > > sunk in, was that I should first program my ideas in Python WITHOUT > > CONCERN FOR PERFOMANCE. Then, profile the application to find the > > "bottlenecks" and extend those blocks of code to C or C++. Cython/ > > Pyrex/Sip are my preferences for python extension frameworks. > > > Numpy/Scipy are excellent libraries for optimized mathematical > > operations. Pytables is my preferential python database because of > > it's excellent API to the acclaimed HDF5 database (used by very many > > scientists and government organizations). > > So what you're saying is, don't worry about performance when you start > coding, but use profiling and optimization in C/C++. Sounds > reasonable. It's been 10 years ago since I've done any programming in C > ++, so I have to pick up on that soon I guess. "Premature optimization is the root of all evil", to quote a famous person. And he's right, as most people working larger codes will confirm. As for pytables: it is the most elegant programming interface for HDF on any platform that I've encountered so far. Most other platforms stay close the HDF5 library C-interface, which is low-level, and quite complex. PyTables was written with the end-user in mind, and it shows. One correction though: PyTables is not a database: it is a storage for (large) arrays, datablocks that you don't want in a database. Use a database for the metadata to find the right file and field within that file. Keep in mind though that I mostly work with externally created HDF-5 files, not with files created in pytables. PyTables Pro has an indexing feature which may be helpful for datamining (if you write the hdf-5 files from python). Maarten From sbix at ensynch.com Wed Nov 14 23:45:59 2007 From: sbix at ensynch.com (sbix at ensynch.com) Date: Wed, 14 Nov 2007 20:45:59 -0800 (PST) Subject: Seeking Python Developer Message-ID: Hi, I work for an IT company in Phoenix, AZ and am trying to find an experienced python developer in the area. Can anyone help? From gnewsg at gmail.com Thu Nov 29 16:59:31 2007 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Thu, 29 Nov 2007 13:59:31 -0800 (PST) Subject: Is os.lstat available on all platforms? References: <7eea5c47-cf1d-4bc5-8dca-aa0d137cbf66@a35g2000prf.googlegroups.com> Message-ID: <6445aff7-1ffe-4c73-bf10-cc89849ca0df@w40g2000hsb.googlegroups.com> I'd just want to be sure that even on a strange python implementation I won't ever get an AttributeError exception because os.lstat is not defined. From fredrik.johansson at gmail.com Sun Nov 18 20:24:34 2007 From: fredrik.johansson at gmail.com (Fredrik Johansson) Date: Mon, 19 Nov 2007 02:24:34 +0100 Subject: Help with sympy, please In-Reply-To: <20071119010335.D6EE41E43CF@bag.python.org> References: <13k1jg03l3cgdef@corp.supernews.com> <20071119001219.5B7111E4021@bag.python.org> <3d0cebfb0711181626u432dbdd3je049093f5343b716@mail.gmail.com> <20071119010335.D6EE41E43CF@bag.python.org> Message-ID: <3d0cebfb0711181724w1a674da2sd4cb070f67d844c9@mail.gmail.com> On Nov 19, 2007 2:03 AM, Dick Moores wrote: > At 04:26 PM 11/18/2007, Fredrik Johansson wrote: > >On Nov 19, 2007 1:05 AM, Dick Moores wrote: > >Hi Dick, I recognize you from python-list, where you had a question > >about mpmath. > > > >Your code still won't work if you convert the numbers to Floats > >because the Float type in sympy.numerics does not implement ** for > >fractional numbers. You could use the exp function in > >sympy.numerics.functions instead to compute e**x. > > Thanks, Fredrik, but I get the same error using either exp or power: > ============================ > from __future__ import division > from sympy import * > from sympy import Rational as R > from sympy.numerics import * > from sympy.numerics.functions import power, exp > > prec = 50 > Float.setdps(prec) > e = evalf(E) > n = 1 > m = n + 1 > k = 0 > n = evalf(R(n,1)) > m = evalf(R(m,1)) > prod = evalf(R(1,1)) > prec = 50 > Float.setdps(prec) > e = evalf(E) > n = 1 > k = 0 > prod = evalf(R(1,1)) > while k < 1000: > k += 1 > n = evalf(R(n,1)) > term = (exp(1/n))/(exp(1/(n+1))) > prod *= term > n += 2 > print prod, term > ============================= > term = (exp(1/n))/(exp(1/(n+1))) > TypeError: unsupported operand type(s) for /: 'int' and 'Float' > > And also if I use sympy.numerics.functions.power in that line, as > term = power(e,(1/n))/power(e,(1/(n+1))) > > I get: > > term = power(e,(1/n))/power(e,(1/(n+1))) > TypeError: unsupported operand type(s) for /: 'int' and 'Float' Try not using "from __future__ import division". Also, n = evalf(R(n,1)) won't work, because the arguments to Rational must be ints. Fredrik From steveshaw89 at hotmail.com Fri Nov 23 13:48:26 2007 From: steveshaw89 at hotmail.com (Steve S) Date: Fri, 23 Nov 2007 10:48:26 -0800 (PST) Subject: Refreshing GridBagSizer Message-ID: <13917194.post@talk.nabble.com> Hey guys, I'm stuck with using a GridBagSizer (wxPython) in a GUI Dialog and am having a frustrating time with refreshing it properly. Essentially, I've got to refresh the contents of the GridBagSizer on occasion with new values. The way I'm doing it works 4 times out of 5 but on the 5th, *all* of the grid objects that are set to various positions in the GBS are set to (0,0) :| So, the way I refresh it is that I keep a record of all grid objects inserted into the GridBagSizer and on refresh, I first iterate through that list and destroy everything in it. I then call Clear() and then Layout() and start adding new grid objects. i.e. I do this: for obj in self.gridObjects: obj.Destroy() self.gridObjects = [] self.gbs.Clear() self.gbs.Layout // Add all new gridObjects, recording them in self.gridObjects Again, this works most all the time *except* that sometimes all newly added grid objects will end up at (0,0) in the GBS :| Am I refreshing it correctly? Has anybody experienced a similar issue? I appreciate any help :) Steve -- View this message in context: http://www.nabble.com/Refreshing-GridBagSizer-tf4863314.html#a13917194 Sent from the Python - python-list mailing list archive at Nabble.com. From martin at marcher.name Mon Nov 5 18:25:10 2007 From: martin at marcher.name (Martin Marcher) Date: Tue, 6 Nov 2007 00:25:10 +0100 Subject: dictionary viewer In-Reply-To: <1194303369.723030.144000@d55g2000hsg.googlegroups.com> References: <1194303369.723030.144000@d55g2000hsg.googlegroups.com> Message-ID: <5fa6c12e0711051525x5a8a399lc293cad52af53a9e@mail.gmail.com> 2007/11/5, mensanator at aol.com : > On Nov 5, 3:10 pm, Erika Skoe wrote: > > > > That's funny, I can't see anything. Of course, it's an empty dict! tzz, *shaking head* martin -- http://noneisyours.marcher.name http://feeds.feedburner.com/NoneIsYours From gandalf at shopzeus.com Tue Nov 13 02:44:26 2007 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Tue, 13 Nov 2007 08:44:26 +0100 Subject: Issue with wxPython GUI In-Reply-To: References: Message-ID: <473955DA.9040709@shopzeus.com> > > *New Problem: *I am opening and executing a script from the GUI. The > script has a many log messages, > which it posts on some shared memory. The GUI reads the messages from > the shared memory, > in the Idle loop. But the script is huge and so the logging is not > run-time. > Rather this happens only after the script has executed. Moreover, the > GUI becomes > un-responsive till the script has completely executed. > This is (probably) because you are running your script in your main thread. While the main thread of the application is running, your windowing system cannot process message queues. Since the updating of a text control uses window messages, it has no chance to process them. I recommend that you run your script in a separate (terminateable?) thread, send your messages into a Queue instance, and load messages from that queue in your main thread. > > Do you have any suggestions for this? Well, if you do not want to create more threads, it migth work if you call this periodically from your main thread (but I did not try this): wxApp::Dispatch *virtual void* *Dispatch*() Dispatches the next event in the windowing system event queue. This can be used for programming event loops, e.g. while (app.Pending()) Dispatch(); From dteslenko at gmail.com Fri Nov 9 04:18:10 2007 From: dteslenko at gmail.com (Dmitry Teslenko) Date: Fri, 9 Nov 2007 12:18:10 +0300 Subject: spawn background process and detach it w/o problems In-Reply-To: <1194548855.128422.163120@i13g2000prf.googlegroups.com> References: <1194548855.128422.163120@i13g2000prf.googlegroups.com> Message-ID: <91325fec0711090118r3803d6d1k719ad3d1b3b9af7c@mail.gmail.com> Hello! On 08/11/2007, davisn90210 at gmail.com wrote: > Take a look at the subprocess module. Big thanks! It's interesting what's happening with subprocess.Popen instance after it has been instatiated and script's main thread exits leaving Popen'ed application open. From xah at xahlee.org Fri Nov 30 18:14:46 2007 From: xah at xahlee.org (Xah Lee) Date: Fri, 30 Nov 2007 15:14:46 -0800 (PST) Subject: Python's doc problems Message-ID: <8edcb4fa-f17d-4e76-aee1-a40f656b6d92@i12g2000prf.googlegroups.com> Every few months, i receive a hearty letter about how well people agree with my criticism of Python's docs. (see http://xahlee.org/perl-python/python_doc_index.html ) Here's one received this week: ---------------------------------- Hello, I landed on your website's comments about the Python documentation. I could not agree more. I could scream about it! The documentation's discussion of character encodings is a disgrace. It's so bad I would not be able to improve it much, because I dont understand it. The end result being that I never understood the topic correctly. I was a technical writer and would not have been able to get away with that level of quality. yours truly <> ---------------------------------- Xah xah at xahlee.org $B-t(B http://xahlee.org/ From deets at nospam.web.de Tue Nov 27 16:04:29 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 27 Nov 2007 22:04:29 +0100 Subject: Passing arguments to subclasses of unittest.TestCase In-Reply-To: References: Message-ID: <5r3f32F12j2tqU2@mid.uni-berlin.de> Tom Harris schrieb: > Hi, > > Is there a way to pass arguments to TestCases when running tests? I have > a test suite that need to be configured slightly differently for 3 > different products, and rather than do a hack I wondered if there was a > canonical way to do it. > > I _know_ that py.test can do it trivially. I am rather stuck with > unittest, as I have 84 testcases, and I have to make it work tomorrow. How about writing one test that takes arguments, and three test-methods that invoke it with different arguments? Or need there be commandline arguments or such stuff involved? Diez From shoplife0001 at gmail.com Tue Nov 27 09:47:19 2007 From: shoplife0001 at gmail.com (shoplife0001 at gmail.com) Date: Tue, 27 Nov 2007 06:47:19 -0800 (PST) Subject: you want? Message-ID: <8a733e2d-84dc-4d5f-8e51-850033f852c7@a39g2000pre.googlegroups.com> Dear Friends The Shoplifes.com belongs to Shoplife Limited Company who mainly sell personal stylish electronic consumable products such as Mobile phones, Laptops, Digital Cameras, Digital Videos,Mp3,Mp4 and bulk products such as LCD TV, Motorcycles and so on. The specific item please visit our company website www.shoplifes.com. As a larger wholesaler we pursue a goal which offer our customer competitive price, highly efficient delivery and perfect customer service. In China we have own warehouse and stores, and our clients all over the world. The best foundation and long-term business relation lead to our company gain highly reputation. We expect to please our honest customer through our product and service. If you have any comments about our products or service please contact us we are appreciated and will improve our service. Hope we can have cooperate with great pleasure and establish long-term business relationship. Website: www.shoplifes.com E-mail: shoplifes at hotmail.com MSN: shoplifes at hotmail.com From gagsl-py2 at yahoo.com.ar Sat Nov 17 03:08:10 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 17 Nov 2007 05:08:10 -0300 Subject: overriding methods - two questions References: <21fcb053-1c95-4b76-909e-1c5d23d47b8b@d50g2000hsf.googlegroups.com> <2718aa24-acad-48b9-a960-89015f7acc2e@i37g2000hsd.googlegroups.com> Message-ID: En Sat, 17 Nov 2007 01:56:22 -0300, Donn Ingle escribi?: > for obj in list: > if 'foo' in obj.__class__.__dict__: > etc. > > Although I am concerned that it's a loop ('in') and so may be slower than > some other way to detect foo(). 'in' for dictionaries is fast and runs in constant time. You may be thinking about 'in' for lists, that runs in time proportional to the number of elements. -- Gabriel Genellina From rndblnch at gmail.com Wed Nov 14 20:33:00 2007 From: rndblnch at gmail.com (rndblnch at gmail.com) Date: Wed, 14 Nov 2007 17:33:00 -0800 (PST) Subject: Unicode: matching a word and unaccenting characters References: Message-ID: <951de902-29b7-48af-8b90-b4effb48c560@d50g2000hsf.googlegroups.com> On Nov 15, 1:21 am, Jeremie Le Hen wrote: > (Mail resent with the proper subject. > > Hi list, > > (Please Cc: me when replying, as I'm not subscribed to this list.) Don't know your mail, hope you will come back to look at the list archive... > I'm working with Unicode strings to handle accented characters but I'm > experiencing a few problem. [skipped first question] > Secondly, I need to translate accented characters to their unaccented > form. I've written this function (sorry if the code isn't as efficient > as possible, I'm not a long-time Python programmer, feel free to correct > me, I' be glad to learn anything): > > % def unaccent(s): > % """ > % """ > % > % if not isinstance(s, types.UnicodeType): > % return s > % singleletter_re = re.compile(r'(?:^|\s)([A-Z])(?:$|\s)') > % result = '' > % for l in s: > % desc = unicodedata.name(l) > % m = singleletter_re.search(desc) > % if m is None: > % result += str(l) > % continue > % result += m.group(1).lower() > % return result > % > > But I don't feel confortable with it. It strongly depend on the UCD > file format and names that don't contain a single letter cannot > obvisouly all be converted to ascii. How would you implement this > function? my 2 cents: # -*- coding: utf-8 -*- import unicodedata def unaccent(s): u""" >>> unaccent(u"?a cr?e d?j? l'?v?nement") "Ca cree deja l'evenement" """ s = unicodedata.normalize('NFD', unicode(s.encode("utf-8"), encoding="utf-8")) return "".join(b for b in s.encode("utf-8") if ord(b) < 128) def _test(): import doctest doctest.testmod() if __name__ == "__main__": import sys sys.exit(_test()) > Thank you for your help. you are welcome. (left to the reader: - why does it work? - why does doctest work?) renaud > Regards, > -- > Jeremie Le Hen > < jlehen at clesys dot fr > > > ----- End forwarded message ----- > > -- > Jeremie Le Hen > < jlehen at clesys dot fr > From antroy at gmail.com Fri Nov 23 05:11:34 2007 From: antroy at gmail.com (Ant) Date: Fri, 23 Nov 2007 02:11:34 -0800 (PST) Subject: may be a bug in string.rstrip References: Message-ID: <83039f21-0ca5-4147-9796-99129dd1fd3b@n20g2000hsh.googlegroups.com> On Nov 23, 4:09 am, "kyo guan" wrote: ... > >>> '120.exe'.rstrip('.exe') Another approach since you seem to be working with filenames is using the os.path module: >>> import os.path as path >>> s = "test.torrent" >>> t = "test.exe" >>> u = "test" >>> path.splitext(s)[0] 'test' >>> path.splitext(t)[0] 'test' >>> path.splitext(u)[0] 'test' From gagsl-py2 at yahoo.com.ar Thu Nov 1 01:14:17 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 01 Nov 2007 02:14:17 -0300 Subject: PyDict_*() refcount assumptions References: <1193878913.364157.91440@57g2000hsv.googlegroups.com> Message-ID: En Wed, 31 Oct 2007 22:01:53 -0300, escribi?: > i checked this: > http://svn.python.org/projects/python/trunk/Doc/data/refcounts.dat > and it seems that > PyDict_SetItem incref the value being added and the key > and PyDict_DelItem does not decrement any refcounts > so i have to do so manually for the key and for the data( by calling > PyDict_GetItem first). Looking at the implementation, PyDict_DelItem decrements both the previous key *and* its associated value. The stored key might not be the same as the parameter; consider this example: d = {} d[1] = 'a' del d[1.0] assert d == {} I think the refcounts.dat file is more intended for automatic tools than for humans. It cannot express the fact that PyDict_DelItem decrements both the stored key and its associated value, by example. This is a limitation of the chosen format. PyDict_Clear decrements a lot of references but there is no way to express that in the refcounts.dat file. > Did i decipher the dat file correctly and is there a wrapper for > DelItem that reverses > the refcounts to what they were before the SetItem or do i have have > to do 2 calls for > deletion? You don't need any wrapper: PyDict_SetItem and PyDict_DelItem do "the right thing" with their reference counts, so there is no need of additional increments/decrements. -- Gabriel Genellina From george.sakkis at gmail.com Sat Nov 17 10:13:03 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Sat, 17 Nov 2007 07:13:03 -0800 (PST) Subject: class='something' as kwarg References: Message-ID: <2ae0d95f-039f-410d-9e24-aaac3b9604cb@d50g2000hsf.googlegroups.com> On Nov 17, 3:45 am, "Vladimir Rusinov" wrote: > Hello! > > I'm using beautiful soup html parser, and I need to get all '
class=g>...
' tags. > It can be done by: > > import BeautifulSoup as BSoup > > ... > > soup = BSoup(page) > for div in soup.findAll('div', class='g'): > > > But how can I use `class` as kwarg name? """ You could search by CSS class with soup.find("tagName", { "class" : "cssClass" }), but that's a lot of code for such a common operation. Instead, you can pass a string for attrs instead of a dictionary. The string will be used to restrict the CSS class. """ http://www.crummy.com/software/BeautifulSoup/documentation.html#Searching%20by%20CSS%20class George From paul.hankin at gmail.com Tue Nov 6 12:04:38 2007 From: paul.hankin at gmail.com (Paul Hankin) Date: Tue, 06 Nov 2007 17:04:38 -0000 Subject: regular expressions In-Reply-To: <1194367773.329640.202340@i13g2000prf.googlegroups.com> References: <1194367773.329640.202340@i13g2000prf.googlegroups.com> Message-ID: <1194368678.996938.150380@50g2000hsm.googlegroups.com> On Nov 6, 4:49 pm, krishnamanenia... at gmail.com wrote: > hi i am looking for pattern in regular expreesion that replaces > anything starting with and betweeen http:// until / > likehttp://www.start.com/startservice/yellow/fdhttp://helo/abcdwill > be replaced as > p/startservice/yellow/ fdp/abcd What have you come up with so far? Have you looked at the 're' module? -- Paul Hankin From ureuffyrtu955 at gmail.com Fri Nov 30 09:58:28 2007 From: ureuffyrtu955 at gmail.com (ureuffyrtu955 at gmail.com) Date: Fri, 30 Nov 2007 06:58:28 -0800 (PST) Subject: "Python" is not a good name, should rename to "Athon" Message-ID: Python is a good programming language, but "Python" is not a good name. First, python also means snake, Monty Python. If we search "python" in google, emule, many results are not programming resource. If we search PHP, all results are programming resource. Second, python also means snake, snake is not a good thing in western culture. Many people dislike any things relevant to snake. We must have high regard for the custom. Now, python3000 is coming. It's the best time to rename! Athon is a good candidate, you could provide better names. In Athon, the first letter "A" could pronounce as [ e ] . From jr244 at kent.ac.uk Wed Nov 14 11:21:53 2007 From: jr244 at kent.ac.uk (J. Robertson) Date: Wed, 14 Nov 2007 16:21:53 +0000 Subject: Problem using os.environ.get In-Reply-To: <1195056743.978655.125270@z24g2000prh.googlegroups.com> References: <1195056743.978655.125270@z24g2000prh.googlegroups.com> Message-ID: paragon.john at gmail.com wrote: > > > # echo $HOSTTYPE > x86_64 > # python >>>> import os >>>> print os.environ.get('HOSTTYPE') > None > > If I do the same thing with a different variable (XILINX, in this > case), it works fine. bash documentation indicates that HOSTTYPE (and a few others: OSTYPE, MACHTYPE, etc.) are variables set by the shell - not quite part of the environment, as such, and they're don't seem to be available to any subprocess: if you launch ksh from bash and check the variable, you'll get none too (on netbsd at least). So, that's a bash problem - not that it helps I guess :-) but bash docs may have some more info about this issue. j. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sat Nov 24 06:00:25 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sat, 24 Nov 2007 12:00:25 +0100 Subject: How can I create customized classes that have similar properties as 'str'? References: <67954d23-9400-4ac9-ba45-bec04fab51a2@s6g2000prc.googlegroups.com> Message-ID: <5qqei9F11703eU1@mid.individual.net> Licheng Fang wrote: > I mean, all the class instances that equal to each other should be > reduced into only one instance, which means for instances of this > class there's no difference between a is b and a==b. If you only want that if "a == b" is True also "a is b" is True, overload the is_ attribute of your class. Personally, I don't see any advantage in this. Regards, Bj?rn -- BOFH excuse #352: The cables are not the same length. From sndive at gmail.com Thu Nov 15 22:27:42 2007 From: sndive at gmail.com (sndive at gmail.com) Date: Thu, 15 Nov 2007 19:27:42 -0800 (PST) Subject: PyCheck for a classes defined in python and user data in PyObject_HEAD References: <1193955251.512135.152720@z9g2000hsf.googlegroups.com> <1193966015.323437.65030@50g2000hsm.googlegroups.com> Message-ID: On Nov 1, 11:04 pm, "Gabriel Genellina" wrote: > En Thu, 01 Nov 2007 22:13:35 -0300, escribi?: > > > On Nov 1, 4:14 pm, snd... at gmail.com wrote: > >> q#1: > >> in C I want to check if a given PyObject is a xml.dom.minidom.Node (or > >> a derivative). > >> how do i extract a PyTypeObject for such a class? > > > nevermind, i found an instance object that will work for me > > as long as i figure out where is the documentation > > beyond this: > >http://docs.python.org/api/instanceObjects.html > > on the data attrib access and extracting PyClassObject from it. > > classic_class = PyObject_GetAttrString( your_classic_instance, "__class__") > > >> issue #2 > >> I'm in a situation when i don't really need to extend python with any > >> classes of my own but > >> i do have extra luggage for the python data structures such as tuples, > >> lists, dictionaries, etc > >> on the c++ side. I see no place in PyObject_HEAD where i can stick a > >> void* to my extra data. > > Assuming you can recompile all the extensions you use, you could insert > your void* into _PyObject_HEAD_EXTRA and _PyObject_EXTRA_INIT i added two void pointers to head_extra and 0,0, to the extra_init. For some reason i get garbage in them from PyEval_EvalCode :-( (that's after i blew the build dir and rebuilt 2.4.4 from scratch so i don't think i have a bad build) From nytrokiss at gmail.com Tue Nov 6 19:14:43 2007 From: nytrokiss at gmail.com (James Matthews) Date: Wed, 7 Nov 2007 01:14:43 +0100 Subject: Wanted: Software Engineers in San Jose, CA In-Reply-To: <22E9DC658696E640A074D8B363795BE6076600BA60@mail1.ABACA.local> References: <22E9DC658696E640A074D8B363795BE6076600BA60@mail1.ABACA.local> Message-ID: <8a6b8e350711061614u78317133u7a58ed32699b6956@mail.gmail.com> Please use monster.com! or linkedin On Nov 6, 2007 10:49 PM, Peter Hsu wrote: > I hope job posting is appropriate on this mailing list. I couldn't find > anything indicating otherwise. > > > > I'm looking for software engineers of all levels to help create a > next-generation spam filtering solution for Abaca Technology. Abaca is > located in San Jose, CA. > > > > The job posting for the senior position follows. If you have any > questions, please feel free to email me. > > > > Peter Hsu > > Engineering Manager > > Abaca Technology Corporation > > phsu at abaca.com > > > > ===== > > > > Abaca is looking for a Senior Software Engineer. In addition to being a > python guru, you will be required to provide technical leadership. You will > design and implement software using the latest technologies and development > process. Set engineering priorities in support of company goals to deliver > quality, high-performance products in a fast-paced startup environment. You > will also be expected to: > > > > * Lead the full software development lifecycle from prototyping and > design to release > > * Provide realistic scoping of projects > > * Create extensible designs and implement products with high quality, and > performance > > * Insure quality development processes are used and that code is designed > to facilitate testability and support > > * Support Sales and Marketing efforts > > * Mentor technical team members in a collaborative > > team-oriented environment > > > > JOB REQUIREMENTS: > > * 7-10 years software development experience > > * Proven track record of meeting tight deadlines > > * Positive, team-oriented attitude > > * Excellent oral and written communication skills > > * Excellent analytic and troubleshooting skills > > * Demonstrated ability to complete highly detailed tasks with strict > attention to quality, completeness and timeliness > > * Strong organizational and self-management skills > > * Must be a self-motivated learner > > * Must be able to work individually and with others with little > supervision in fast-paced, constantly changing start-up environment > > * Will likely have customer contact and/or need to provide customer-level > documentation > > > > TECHNICAL SKILLS REQUIREMENTS: > > * Application development experience on Linux platform > > * Strong knowledge of Python > > * Strong background of OO, MVC-based, web-focused analysis and design > > * Knowledge of Internet protocols such as SMTP, LDAP, HTTP, POP3, IMAP, > FTP, SNMP, etc. > > * Knowledge of Java, C++ or other object-oriented language is a plus. > > * Experience with Postgres stored procedures a plus. > > * Prior experience with AJAX a plus > > * Experience designing areas of security, performance, capacity and > maintainability > > * SQL and schema design experience > > * Must understand the general software development release cycle, source > management and defect management methodologies in a mixed Microsoft Windows > > and Linux environment. > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://search.goldwatches.com/ http://www.jewelerslounge.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From ricaraoz at gmail.com Fri Nov 23 07:28:30 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Fri, 23 Nov 2007 09:28:30 -0300 Subject: Problems with if/elif statement syntax In-Reply-To: <3bc076d3-9164-473f-859e-5f0daea83c56@d27g2000prf.googlegroups.com> References: <4d58211e-ebe8-40fe-80ae-cf8b4a56f9ec@d21g2000prf.googlegroups.com> <3bc076d3-9164-473f-859e-5f0daea83c56@d27g2000prf.googlegroups.com> Message-ID: <4746C76E.7060607@bigfoot.com> cokofreedom at gmail.com wrote: > On Nov 22, 12:33 pm, "riqu... at gmail.com" wrote: >> On 22 Nov, 12:09, Neil Webster wrote: >> >> >> >>> Hi all, >>> I'm sure I'm doing something wrong but after lots of searching and >>> reading I can't work it out and was wondering if anybody can help? >>> I've got the following block of code: >>> if a >= 20 and a < 100: >>> if c == "c": >>> radius = 500 >>> else: >>> radius = 250 >>> elif (a >= 100) and (a < 500): >>> radius = 500 >>> elif (a >= 500) and (a < 1000): >>> radius = 1000 >>> elif (a >= 1000) and (a < 3000): >>> radius = 1500 >>> elif (a >= 3000) and (a < 5000): >>> radius = 2000 >>> else: >>> radius = 4000 >>> No matter what value goes in for 'a' the radius always comes out as >>> 4000. >>> What am I doing wrong? >>> Cheers >>> Neil >> as Oliver pointed out, check if you're not compairing "a" as a string >> >> I wanted to let you know that you can write the above conditions in a >> more natural way, using the a> >> e.g. >> >> x=int(raw_input("write a number")) >> if 5<=x<30: >> print 'x is between 5 and 30' > > Argh, I really dislike raw_input. Though it helps to remind me to use > Try:Except blocks a lot. Hasn't anyone TRIED the code? I did, with a = 30 and c = 'x' radius comes out as 250. So it seems the problem is somewhere else and not in this bit of code. From kyosohma at gmail.com Fri Nov 16 09:09:21 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Fri, 16 Nov 2007 06:09:21 -0800 (PST) Subject: PDF library References: Message-ID: <592a8140-4daf-4f18-822f-fad397ee69cc@o6g2000hsd.googlegroups.com> On Nov 15, 7:17 pm, james_027 wrote: > hi, > > I am looking for a python PDF library that starts with 'Q' ... I just > found them somewhere in the internet but I can't find them now that I > need it. Does someone knows this? > > Thanks I'm not sure what you're referring to. The best known one is ReportLabs for generating PDFs in Python code. There's also pyPdf for merging PDFs and/or extracting information from them, among other things. http://pybrary.net/pyPdf/ www.reportlab.org Maybe if one of these was listed on a foreign site, it was spelled with a 'Q'? Mike From greg at cosc.canterbury.ac.nz Mon Nov 26 03:21:20 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Mon, 26 Nov 2007 21:21:20 +1300 Subject: How to display unicode with the CGI module? In-Reply-To: <9673bd8e-fcf7-4ddd-bd27-ba0c7954db29@p69g2000hsa.googlegroups.com> References: <5qsknfF11nhdfU1@mid.uni-berlin.de> <9673bd8e-fcf7-4ddd-bd27-ba0c7954db29@p69g2000hsa.googlegroups.com> Message-ID: <5qve8tF127s1kU1@mid.individual.net> coldpizza wrote: > I am always confused as to which one to use: encode() or decode(); In unicode land, an "encoding" is a method of representing unicode data in an external format. So you encode unicode data in order to send it into the outside world, and you decode it in order to turn it back into unicode data. It'll be easier to get right in py3k, because bytes will only have a decode() method and str will only have an encode() method. > It is funny that encode() and decode() omit the name of the other > encoding (Unicode ucs2?), Unicode objects don't *have* an encoding. UCS2 is not an encoding, it's an internal storage format. You're not supposed to need to know or care about it, and it could be different between different Python builds. > Another wierd thing is that by default Python converts internal > Unicode to ascii. It's the safest assumption. Python is refusing the temptation to guess the encoding of anything outside the range 0-127 if you don't tell it. -- Greg From harald.naumann at roundsolutions.com Tue Nov 20 23:49:24 2007 From: harald.naumann at roundsolutions.com (Meff) Date: Tue, 20 Nov 2007 20:49:24 -0800 (PST) Subject: google earth / pythoncom References: Message-ID: <75cb0010-112a-4571-93aa-00f4de9be1d3@w34g2000hsg.googlegroups.com> > > I'd like to write a python script to control Google Earth, > > and I've read that Google Earth provides a COM api, and that > > Python has a COM module 'pythoncom'. > Io ho fatto prima ad acquistarne uno d'importazione molto ben fatto e > professionale, costo 250euro What about Euro 108,90 for an AarLogic C05/03? GE863-GPS-LP on PCB Easy integration into your tracking solution includes: - Combinde GPRS / GPS modules GE863-GPS-LP - SIM card holder - Power supply (6-40V) - 2x UF.L antenna connector for GPS+GSM - License free Python interpreter: Price list here http://www.roundsolutions.com/pdf/Round%20Price-GSM%2BAcc-Euros.pdf Further details on Aarlogic are mentioned here: http://roundsolutions.com/pdf/Designing-mobile-devices.pdf Free of charger test server for tracking http://www.track4free.com The Python binary file is for free as well. If you upload it to AarLogic C05/03, then you will have a PCB that starts with transmitting of postion to Track4free. http://www.roundsolutions.com/uk_track4free.htm Innovative positioning package from Round Solutions: Website and starter kit for tracking applications Dreieich, March 15th 2007 - Round Solutions, a specialist and value- added distributor for M2M applications, is now offering its customers an attractive developer package. This includes the access to the www.track4free.com website and a starter kit based on what is currently the world's smallest GPRS GPS module. The package assists system integrators in the development of compact and inexpensive tracking solutions. The latest positioning package from Round Solutions is based in the customer's access to the www.track4free.com website. This track4free server relies on Google Maps and offers free global GPS positioning. To use the online platform, a function-enabled GPS device is needed that can transmit geographical data via HDCSD, GPRS, EDGE or UMTS. Following registration with track4free, the user is shown examples of a map that illustrates his or her positional data along with a range of other information. This is enhanced by extensive documentation about the movements made by the user's device. Users can register up to two applications per account. Starter kit promotes development System integrators also have the option of using the Round Solutions starter kit when developing their tracking application. The Basic Board S3 is based on what is currently the world's smallest combined GPRS-GPS module, equipped with extremely small embedded antennas. The starter kit's core component is a licence-free Phython interpreter with a free-of-charge Phython code. This transmits the device's GPS position to the track4free server. The HTTP protocol is provided free of charge. The starter kit has been developed completely as a BGA design. It assists developers in their mission to create very small and inexpensive positioning devices for various fields of application. Extensive additional services Round Solutions supports system integrators with design-in services and bespoke adaptations for integrated antennas. If developers have any queries, they can access 24-hour support from the world's biggest GSM / GPRS / UMTS / GPS user community, which has more than 3,000 members from all over the globe. Premium customers can also have their designs and devices checked and tested free of charge by Round Solutions. The package is supplemented by a free marketing service, which establishes contact with several thousand companies. "Our services make it significantly easier for our customers to sell their products," explains Ben Hoelke, CEO of Round Solutions. About Round Solutions Round Solutions is a leading, internationally active supplier of products, services and concepts for industrial users of electronic components. The focus lies on wireless technologies such as GSM, UMTS, GPS, Bluetooth, ZigBee, WIFI, UWB and ISM. The product portfolio ranges from starter kits to components for mass production. Round Solutions offers a wide range of electronic components such as radio modules, HF cables and ultra-sensitive antennas. Round Solutions currently has the world's largest range of quad-band and penta-band antennas. Unlike its competitors, integrated antennas are already available in small quantities at Round Solutions. Its stock also includes lithium polymer, lithium-ion and nickel-metal hydride batteries. Moreover, Round Solutions offers a global express delivery service. With the compact and innovative components from Round Solutions, system integrators can develop their solutions quickly, easily and inexpensively. They thus enjoy greater efficiency and a shorter time to market for their applications. The company has branches in Germany and the United Kingdom. With AarLogic you get it up and running easy, cheap and fast. Regards Meff From gagsl-py2 at yahoo.com.ar Mon Nov 5 15:07:54 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 05 Nov 2007 17:07:54 -0300 Subject: Python thinks file is empty References: <1194275982.617384.57430@57g2000hsv.googlegroups.com> <472F3D5B.1000007@tim.thechases.com> Message-ID: En Mon, 05 Nov 2007 12:57:15 -0300, Tim Chase escribi?: > To confuse matters, it happens to work in your example, because a > string is an iterable that returns each character in that string > as the result, so code like this > > f.writelines('hello\n') > > is effectively doing something like this > > f.write('h') > f.write('e') > f.write('l') > f.write('l') > f.write('o') > f.write('\n') > > (unless writelines is optimized to smarten up the code here) As of 2.5.1, it's not :( writelines is perhaps one of the worst used functions in Python. It'b been there for ages (since 1.5.2 at least) but a lot of people does not know it even exists (and roll their own, *always* slower; map(f.write, lines) appears to be the favorite spelling...) or, if they are aware of it, use it wrongly as you pointed out above. Perhaps some of them come from Delphi/Pascal, looking for something similar to writeln, and writelines is the closest match... -- Gabriel Genellina From greg at cosc.canterbury.ac.nz Tue Nov 27 02:29:08 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Tue, 27 Nov 2007 20:29:08 +1300 Subject: How to Teach Python "Variables" In-Reply-To: <87abp1qqth.fsf@mulj.homelinux.net> References: <4749bb94$1@news.bezeqint.net> <5qvf6pF122r3mU1@mid.individual.net> <87abp1qqth.fsf@mulj.homelinux.net> Message-ID: <5r1vj0F120hd7U1@mid.individual.net> Hrvoje Niksic wrote: > A C programmer > told that Python variables internally hold pointers expects this code: > > def func(a): > a = 10 > ... > func(x) > > to change the value of x. He shouldn't expect that, because that's not what the equivalent code would do in C. To get that effect in C, you would (among other things) have to write the call as func(&x) which you can't do, because there is no & operator in Python. I would probably use the term "reference", and explain it by saying that a reference is a pointer to an object. Also that Python variables always hold references, never objects; a reference always refers to an entire object, never a part of an object or another variable; and that assignment is always reference assignment and never copies objects. And illustrate everything with lots of drawings of boxes and arrows. It's much easier to explain all these things unambiguously with diagrams than with words that may not mean the same thing to the listener that they mean to you. -- Greg From mindmaster32 at gmail.com Thu Nov 15 14:05:30 2007 From: mindmaster32 at gmail.com (mindmaster32 at gmail.com) Date: Thu, 15 Nov 2007 11:05:30 -0800 (PST) Subject: Movement recognition in video file References: <97c875c2-bf92-4327-97b5-de3c0724393d@e23g2000prf.googlegroups.com> Message-ID: <38bf0cee-3459-415c-ac41-a7f7ae7b40af@d61g2000hsa.googlegroups.com> Thanks guys, I will give those solutions a try! davisn90210 at gmail.com escreveu: > On Nov 15, 8:29 am, mindmaste... at gmail.com wrote: > > Hi, > > > > I am looking for a python tool or module that helps me build a script > > that can perceive object moves in a video file captured by a (web) > > camera. My main goal is to be able to count people entering a store > > using the store's surveillance camera. > > > > I know of some packages like Eyesweb (gestural recognition package) or > > Pure Data's module called GEM, but I don't know any written in python. > > > > Thanks > > You could use something like PyMedia to iterate the frames in the > video, then process the image using something like PIL or numpy. > Other possibilities might include gstreamer, or any other multimedia > library that has python bindings. Depending on your exact needs, > python may be too slow for the "guts" of the algorithm, but certainly > could be used for prototyping and/or glue code. > > I've used PyMedia with both PIL and numpy to do some video processing > in the past. If you need help getting started, just ask. > > --Nathan Davis From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun Nov 25 10:04:27 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sun, 25 Nov 2007 16:04:27 +0100 Subject: PyQt, Cannot send events to objects owned by a different thread? References: <47498520$0$13104$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <5qth7rF11o4fpU1@mid.individual.net> Alexander Tuchacek wrote: > i try to adress an qt object > > self.statusbar.showMessage("rtt %s...." % (n.rtt)) > > in an callback function, comming from a shared lib importet by > ctypes, on osx this works wonderfull > > when i run the same code on linux (ubuntu gutsy), i get this core > dump, ok, i understand that the problem is, that i cant speak to > the qt thread, but why does it work on osx? Luck. If something works reproducibly in some conditions, that neither means it will work elsewhere nor that it is wise to do so at all. (I will spare the group far-fetched road traffic similes for now ;) ) > shall i recompile python? pyqt or sip? without threads? > > could somebody give me a hint what to do best? Just use Qt as recommended in its docs; that's how you do the best you can against future portability or other issues. Regards, Bj?rn -- BOFH excuse #99: SIMM crosstalk. From ra21vi at gmail.com Thu Nov 29 08:18:10 2007 From: ra21vi at gmail.com (Ravi Kumar) Date: Thu, 29 Nov 2007 18:48:10 +0530 Subject: any Templating system help Message-ID: <9a63e8920711290518x1339d58bp6b0ee83d5a90308d@mail.gmail.com> Hi, I am stuck a little. I am working on a demo site to propose for the my company. Using mod_python and several python technologies. But the website is simply using publisher handler, i dont want to use any framework such as DJango etc. so the main idea is, i made many python files which has several defs inside, such as index, getList, submitForm etc now everything is working nice, means calling them in url. I need a templating system now. But not slow and complex. The only things in templating system i need is: fetching all the names of variables/placeholder in template. (i can then call the suitable defs from files and apply the wrapper on it and return to main caller) setting the values Please suggest some ideas. -- -=Ravi=- -------------- next part -------------- An HTML attachment was scrubbed... URL: From ojeeves at gmail.com Wed Nov 21 06:38:32 2007 From: ojeeves at gmail.com (oj) Date: Wed, 21 Nov 2007 03:38:32 -0800 (PST) Subject: logging and propagation Message-ID: <7eef67e0-36a7-48b6-9137-0b10ea37ac3c@f3g2000hsg.googlegroups.com> Hi, I want to setup logging with two loggers: The child logger is used when something different needs to be done with the log record, and the log record will propagate and be logged by the root logger as usual. However, there are certain times when I don't want a log record to propagate from the child to the parent. I don't really want to add a filter to the root logger, as it should be up to the child whether the record propagates or not. I've tried setting the child to a lower level then the parent, but if a record is dealt with by the child, the parent deals with it anyway regardless of its own log level. Also, filters only apply particular handlers and do not affect propagation. Can anyone suggest a simple way to achieve this? Currently, the only thing I can think of, is overriding the callHandlers method in a custom Logger class. From dickinsm at gmail.com Thu Nov 22 17:41:01 2007 From: dickinsm at gmail.com (Mark Dickinson) Date: Thu, 22 Nov 2007 14:41:01 -0800 (PST) Subject: Next float? References: Message-ID: On Nov 21, 11:48 pm, "Mark T" wrote: > Here's some functions to get the binary representation of a float. Then > just manipulate the bits (an exercise for the reader): > > import struct > > def f2b(f): > return struct.unpack('I',struct.pack('f',f))[0] > > def b2f(b): > return struct.unpack('f',struct.pack('I',b))[0] > > >>> f2b(1.0) > 1065353216 > >>> hex(f2b(1.0)) > '0x3f800000' > >>> b2f(0x3f800000) > 1.0 > >>> b2f(0x3f800001) > 1.0000001192092896 > >>> b2f(0x3f7fffff) > > 0.99999994039535522 And it's worth noting that thanks to the way the floating-point format is designed, the 'bit-twiddling' is actually just a matter of adding or subtracting one from the integer representation above. This works all the way from zero, through subnormals, up to and including infinities. Mark (but not the same Mark) From loic.mahe at nospam.fr Mon Nov 12 09:37:33 2007 From: loic.mahe at nospam.fr (Loic Mahe) Date: Mon, 12 Nov 2007 15:37:33 +0100 Subject: Some "pythonic" suggestions for Python In-Reply-To: <1194623991.801386.163970@50g2000hsm.googlegroups.com> References: <5PGdnWmWZIdZ967anZ2dnUVZ_uuqnZ2d@cavtel.net> <473482a9$0$5096$ba4acef3@news.orange.fr> <1194623991.801386.163970@50g2000hsm.googlegroups.com> Message-ID: <4738652b$0$27394$ba4acef3@news.orange.fr> Chris M write : > Multi-return value lambda? Just so you know, there is no concept of > returning more than one value from a function. I wrote: > * multi return value lambda I meant: multiple return statement, not return multiple values pseudo code here: lambda x: if A return B, if C return D, if E return F ... it could be nice if ou could write normal functions ... as lambda ones and not being limited to a subset of the kewords ... at least it would fit Frank Samuleson needs/wishes better... From garlictrompet at gmail.com Wed Nov 7 04:36:49 2007 From: garlictrompet at gmail.com (Ajay Deshpande) Date: Wed, 7 Nov 2007 15:06:49 +0530 Subject: Retrieving all open applications ... In-Reply-To: <3b10c2060711031152r46159f96x8d1bdd9ee7c2a2d5@mail.gmail.com> References: <3b10c2060710300220g16373e41i6d4290563c15776@mail.gmail.com> <3b10c2060711031152r46159f96x8d1bdd9ee7c2a2d5@mail.gmail.com> Message-ID: <3b10c2060711070136v72032102t63f57b707fb7f8db@mail.gmail.com> hi guys: well i still havent found a solution to this ... since i am using ubuntu 7.10, i cannot use the hammond modules ... -Ajay On 11/4/07, Ajay Deshpande wrote: > > applications ... i need to retrieve all currently open applications ... > > thx for your help ... > > -Ajay > > On 10/31/07, Gabriel Genellina < gagsl-py2 at yahoo.com.ar> wrote: > > > > En Tue, 30 Oct 2007 06:20:10 -0300, Ajay Deshpande > > escribi?: > > > > > I need to retrieve all currently open applications using a python > > > program. > > > So my output should be a list of window handles. Is there a module > > which > > > I > > > can use? > > > > "applications" or "windows"? You can use the EnumWindows function, from > > the Windows API, to enumerate all top level windows. See this article > > from the Microsoft Knowledge Base < > > http://support.microsoft.com/kb/183009> > > (the example is in VB but I hope you get the idea) > > > > Install the pywin32 extensions from Mark Hammond > > http://pywin32.sourceforge.net and you'll have the EnumWindows function > > available. > > > > -- > > Gabriel Genellina > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jim at bizcomputinginc.com Fri Nov 2 12:09:58 2007 From: jim at bizcomputinginc.com (Jim Hendricks) Date: Fri, 02 Nov 2007 12:09:58 -0400 Subject: python newbie In-Reply-To: References: <472b2b84$0$13761$6e1ede2f@read.cnntp.org> <1194014916.893875.188770@19g2000hsx.googlegroups.com> <472b3e97$0$13759$6e1ede2f@read.cnntp.org> Message-ID: <472b4bf7$0$13762$6e1ede2f@read.cnntp.org> J. Clifford Dyer wrote: >> before calling my_function, x does not exist in my program. So, my >> question is in my_function, the combination of using the global >> statement, then implicitly creating x via assignment to the result of >> the open function, is x created in the global namespace? > > Yes. > >>>> y > > Traceback (most recent call last): > File "", line 1, in > y > NameError: name 'y' is not defined >>>> def f(): > global y > y = 123 >>>> f() >>>> y > 123 tks, and tks also for the example. > > Remember, the interactive interpreter is your friend. Just type 'python' at the command line and hammer away. (It's even better through a decent IDE). yes, you are correct, last time I had the advantage of a console was when I was working in Forth. Working with Java & PHP for a living makes one forget that Python has the console. > > Oh yeah, you have to actually call f before y will get defined. > > Cheers, > Cliff From pavlovevidence at gmail.com Thu Nov 29 17:43:42 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 29 Nov 2007 14:43:42 -0800 (PST) Subject: A context manager for temporary memoization. References: Message-ID: <6975fa21-2fb2-4cfa-9d34-733452e436f4@e4g2000hsg.googlegroups.com> On Nov 29, 3:20 pm, "Michael Speer" wrote: > I posted this to my blog athttp://michaelspeer.blogspot.com/2007/11/context-manager-for-temporar.... > > I decided to forward it onto the list for comments. I thought someone > might find it interesting. > > *** > > This is very much a fragile hack at the moment. It's an interesting > idea I think. I was disappointed when I initially found that the > with_statement syntax does not restore the value of the `as var` upon > completion. > > This made doing something along the lines of > > with temporarily_memoized( func ) : > for datum in data : > func( datum ) > > unattainable. > > Well, just a lot hackier actually. > > Thus temporarily_memoized( ... ) was born : > > #!/usr/bin/python > > # a context manager for temporarily turning any function into > # a memoized version of itself. > > from __future__ import with_statement > import contextlib , sys , types > > def memoize ( func ) : > """ In haskell mutability must be handled explicitly. > Only fair that Python do the same to transparent functionality > """ > remembered = {} > def memoized ( *args ) : > """ memoized version of function """ > if args in remembered : > return remembered[ args ] > else : > new = func( *args ) > remembered[ args ] = new > return new > return memoized > > @contextlib.contextmanager > def temporarily_memoized ( func ) : > """ memoize the given function for the duration of this block > save anything in the local variables that gets in the way of > using this so that it can be restored afterward , the memoized > version is found in the locals. use on actual functions only. > no members. """ > > # this is being called, there has to be a frame above it > frame = sys._getframe().f_back.f_back > > if func.func_name in frame.f_locals : > f = frame.f_locals[ func.func_name ] > frame.f_locals[ func.func_name ] = memoize( func ) > try : > # this hack replaces whatever in the local scope > # has the name of the variable. if you try to use > # the 'as whatever' portion of the syntax , you > # are doing it wrong > yield None > finally : > frame.f_locals[ f.func_name ] = f > else : > frame.f_locals[ func.func_name ] = memoize( func ) > try : > yield None > finally : > del frame.f_locals[ func.func_name ] > > def fib(n): > """ biggus fibbus """ > if n == 0 or n == 1: > return n > else: > return fib(n-1) + fib(n-2) > > if __name__ == '__main__' : > print fib.__doc__ > with temporarily_memoized( fib ) : > print fib.__doc__ > for i in xrange( 36 ) : > print "n=%d => %d" % (i, fib(i)) > print fib.__doc__ > print fib.__doc__ > > outputs : > > biggus fibbus > memoized version of function > n=0 => 0 > ..... > n=35 => 9227465 > memoized version of function > biggus fibbus Did you try to use temporarily_itemized inside a function? It might not work as you think. BTW, the name temporarily_memoized is superfluous. By definition, whatever a context manager does is temporary, so using "temporarily" in the name just adds a lot of letters and tells us nothing we didn't already know. Just call it memoized. Carl Banks From steven at REMOVE.THIS.cybersource.com.au Mon Nov 26 21:45:51 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Tue, 27 Nov 2007 02:45:51 -0000 Subject: How can I create customized classes that have similar properties as 'str'? References: <67954d23-9400-4ac9-ba45-bec04fab51a2@s6g2000prc.googlegroups.com> <8eebf8fb-74cc-452a-bbef-2fe93556491f@i29g2000prf.googlegroups.com> <5qqeroF11703eU2@mid.individual.net> <1f2e037f-3667-4070-97cd-f4f6486c9d79@i12g2000prf.googlegroups.com> <13kh7mmeksulu51@corp.supernews.com> <03bf25a0-0195-4cc4-b304-b56c9125b5bd@e6g2000prf.googlegroups.com> Message-ID: On Sun, 25 Nov 2007 02:42:36 -0800, Licheng Fang wrote: > I mentioned trigram counting as an illustrative case. In fact, you'll > often need to define patterns more complex than that, and tens of > megabytes of text may generate millions of them, and I've observed they > quickly ate up the 8G memory of a workstation in a few minutes. > Manipulating these patterns can be tricky, you can easily waste a lot of > memory without taking extra care. I just thought if I define my pattern > class with this 'atom' property, coding efforts could be easier later. I'm just not getting the same results as you when I try this. I'm finding that with no extra effort at all, it just works. The size of your corpus is not important. Neither is the complexity of how you generate the patterns. What's important is the number of patterns you produce, and "millions" isn't that huge a number, even without interning the strings. Obviously I'm not running your code, but I can build a dict with millions of patterns, from hundreds of megabytes of text, on a PC with just 1GB of memory and not run into any serious problems. I've just processed roughly 240MB of random emails, generating n-grams up to length 5. The emails include binary attachments and HTML etc., so I'm getting lots of patterns that don't normally exist in natural languages (e.g. 71 occurrences of 'qqq', and 5 of 'qqqq'). As I said, my PC has only 1GB, and that's being shared with about a dozen other apps (including such memory hogs as Firefox). Results? 64939962 patterns found, of which 17031467 are unique. There's paging, yes, and my PC runs a little slow when I try to switch from one running application to another, but nothing unusable. Opening a dozen YouTube videos at once impacts performance worse. I can't think what you're doing to use up 8GB of RAM for merely "millions" of strings, even if you are keeping two, three, ten redundant copies. Assuming an average length of twenty bytes per pattern (you said trigrams, but I'd rather over-estimate than under), and even assuming that only half the 8GB are available to Python, you should be able to store something of the order of one hundred million patterns easily: 4 bytes for a pointer plus 20 bytes for the string = 24 bytes 4*1024**3 / 24 = 178,956,970 (This is a ballpark figure. Real Python strings will have additional overhead.) If you're running into problems with merely millions of patterns, then you're doing worse by probably two orders of magnitude. I don't think that the problem lies where you think it does. If you have a dict with millions of keys, it doesn't matter how many times each pattern exists in the corpus because the key only exists *once* in the dict. Duplicate the dict, or generate it from scratch even, and at worse you double the memory used by the keys. And probably not even that. The only thing I can think of that might explain why you're using so much memory is if you are generating *all* the patterns up front, say in a list, before adding them to the dict: # Generate one massive list of patterns containing many duplicates patterns = make_patterns(text) # returns a massive list like ['fre', 'req', 'equ', 'que' ...] d = {} for pattern in patterns: d[pattern] = d.get(pattern, 0) + 1 Notice that the real killer in the above algorithm is that you need enough storage, not just for the unique patterns, but for EVERY separate occurrence of each pattern. Nothing to do with how dicts operate, and everything to do with the algorithm you (hypothetically) are using. If that's what you're doing, then no wonder you're running out of memory. With 200MB of text, you have 209715198 trigrams in your list. The pointers alone will take almost a gigabyte, assuming 32-bit pointers. If this is your approach, interning the strings won't save you. You almost certainly should change to a lazy approach, and use a generator to make each pattern as needed, then thrown away: def make_patterns(s, n=3): """Yield n-grams.""" if len(s) <= n: yield s else: for i in range(len(s)-n+1): yield s[i:i+n] d = {} fp = open('corpus', 'r') for line in fp: for word in line.split(): for pattern in make_patterns(word.strip()): d[pattern] = d.get(pattern, 0) + 1 Obviously I haven't seen your code and don't actually know what you are doing. If my 1GB machine can deal with a dict of 17 million unique keys from a corpus of 240MB with no special memory management, your 8GB machine should too. -- Steven. From paddy3118 at googlemail.com Fri Nov 16 01:45:18 2007 From: paddy3118 at googlemail.com (Paddy) Date: Thu, 15 Nov 2007 22:45:18 -0800 (PST) Subject: Interfaces. References: <1ecf1cca-f05f-44b5-8128-a93208815f15@y5g2000hsf.googlegroups.com> Message-ID: <8d96529a-e184-4a6e-a955-4c19aaff9318@v4g2000hsf.googlegroups.com> On Nov 16, 1:55 am, "PeterBrad... at googlemail.com" wrote: > Hi, > ... > I also had a new idea - when specifying the functionality of a module, > it would be nice to combine examples of valid behaviour / some sort of > testing. > ... Try the 'Pythonic' doctest module: http://en.wikipedia.org/wiki/Doctest > (new to python so be nice :) Welcome to Python! - Paddy. From rokkamraja at gmail.com Mon Nov 12 21:33:33 2007 From: rokkamraja at gmail.com (Raja) Date: Mon, 12 Nov 2007 18:33:33 -0800 Subject: Multithreaded Python Mysql MAC Problems Message-ID: <1194921213.640148.254780@o38g2000hse.googlegroups.com> Hi All, I wrote a multithreaded crawler program in Python 2.4 using Mysql 5.045 and MySqldb version as MySql-Python 1.2.2 on MAC OS 10.4.10 . The program strangely segfaults while it is running perfectly in Ubuntu and Windows as well. The gdb stack trace of program is below: LuLu:~/tempdownloads/crawl tspencer$ gdb python GNU gdb 6.1-20040303 (Apple version gdb-434) (Wed Nov 2 17:23:33 GMT 2005) 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-apple-darwin"...Reading symbols for shared libraries .. done (gdb) run FinalCrawler.py Starting program: /Library/Frameworks/Python.framework/Versions/2.4/ bin/python FinalCrawler.py Reading symbols for shared libraries . done Program received signal SIGTRAP, Trace/breakpoint trap. 0x8fe01010 in __dyld__dyld_start () (gdb) bt #0 0x8fe01010 in __dyld__dyld_start () (gdb) info threads * 1 process 19802 local thread 0xf03 0x8fe01010 in __dyld__dyld_start () (gdb) continue Continuing. Reading symbols for shared libraries ... done Reading symbols for shared libraries . done Reading symbols for shared libraries . done Reading symbols for shared libraries .. done Reading symbols for shared libraries . done Reading symbols for shared libraries . done Reading symbols for shared libraries .. done Reading symbols for shared libraries . done Reading symbols for shared libraries . done Reading symbols for shared libraries . done Reading symbols for shared libraries . done Reading symbols for shared libraries ... done Reading symbols for shared libraries . done Reading symbols for shared libraries . done Reading symbols for shared libraries . done Reading symbols for shared libraries . done Reading symbols for shared libraries . done Reading symbols for shared libraries . done Reading symbols for shared libraries . done Reading symbols for shared libraries . done Reading symbols for shared libraries . done putting starting threads now !!!! putting putting putting putting putting putting putting putting putting 3 Now after Lock acquired 3 Now releasing lock Program received signal EXC_BAD_ACCESS, Could not access memory. Reason: KERN_PROTECTION_FAILURE at address: 0x00000090 [Switching to process 19802 thread 0x1703] _db_return_ (_line_=95, _sfunc_=0xb0283f3c, _sfile_=0xb0283f38, _slevel_=0xb0283f34) at dbug.c:828 828 state->framep = (char **) *state->framep; (gdb) The "putting" and number 3 are program's print statements. Can anyone please provide me with a insight into this problem and solution to it ? What might be the cause of this problem or how to go about further debugging it ? Thanks, Raja. From ganesh.borse at credit-suisse.com Thu Nov 15 04:15:39 2007 From: ganesh.borse at credit-suisse.com (Borse, Ganesh) Date: Thu, 15 Nov 2007 17:15:39 +0800 Subject: What is the function to evaluate code object returned by PyParser _SimpleParseString function? Message-ID: Hi, Thanks for this information Py_CompileString takes the source code from file, isn't it? As can be seen from the syntax of this function: "PyObject* Py_CompileString(char *str, char *filename, int start)" I want to parse the code which is in memory - loaded from database. In that case, may I know, how to use the Py_CompileString? Is it mandatory to read from file for this function? Reading from file increases startup time of my application. So, I was thinking of using PyParser_SimpleParseString, which takes the code to be parsed in the "char*" format. Quit suitable to my need. Can I use the output of the function PyParser_SimpleParseString as input to PyEval_EvalCode? Please guide. Thanks in advance for your time & guidance. Warm Regards, Ganesh -----Original Message----- From: Gabriel Genellina [mailto:gagsl-py2 at yahoo.com.ar] Sent: 15 November 2007 07:51 To: python-list at python.org Subject: Re: How to use the evaluate the code object returned by PyParser_Simp leParseString function? En Wed, 14 Nov 2007 06:48:41 -0300, Borse, Ganesh escribi?: > `struct _node* PyParser_SimpleParseString(char *str, int start)' > Parse Python source code from STR using the start token START. > The result can be used to create a code object which can be evaluated > efficiently. > This is useful if a code fragment must be evaluated many times. > I have exactly same requirement. I have dynamic expressions loaded > from database at startup in my C++ application. > I want to parse these expressions at startup & keep the parsed > (compiled) code in memory of this application. > Then at runtime, I want to evaluate all this parsed code. This has to > be very efficient. parsed != compiled. Use Py_CompileString instead. The resulting code object may be executed with PyEval_EvalCode. BTW, instead of looking at some random web site, it's better to read the official documentation at http://docs.python.org. You should have a copy of it in the Doc subdirectory inside your Python installation. -- Gabriel Genellina ============================================================================== Please access the attached hyperlink for an important electronic communications disclaimer: http://www.credit-suisse.com/legal/en/disclaimer_email_ib.html ============================================================================== From deets at nospam.web.de Mon Nov 12 14:41:34 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 12 Nov 2007 20:41:34 +0100 Subject: python - an eggs... In-Reply-To: References: Message-ID: <5prokdFskv4hU1@mid.uni-berlin.de> bruce schrieb: > hey dietz... > > if you give me your email i'll correspond with you directly.. > but yeah, you are a jerk. in that you make assumptions that may/may not be > correct, but you appear to have a holier than thou mentality... > > i did download the setuptools tar file.... i read through the txt files that > came with it... i couldn't fing anything that stated exactly how to get the > easy_install app... > You mean you read the link I gave you and didn't find this: http://peak.telecommunity.com/DevCenter/setuptools#installing-setuptools Conveniently linked as second point in the table of contents? > i'm fully aware of what the site states, as i read it. you ignorant slut > assume that i didn't. Well, it appears that we have different definitions of reading. > > in my mind, the docs on the installation could use a little more > clarification, especially for those who aren't quite sure of how python > might work, and so don't want to risk screwing up a system. You think that http://peak.telecommunity.com/DevCenter/EasyInstall#installation-instructions """ Download ez_setup.py, and run it; this will download and install the appropriate setuptools egg for your Python version. (You will need at least Python 2.3.5, or if you are on a 64-bit platform, Python 2.4.) An easy_install script will be installed in the normal location for Python scripts on your platform. (Windows users, don't put ez_setup.py inside your Python installation; please put it in some other directory before running it.) """ isn't clear? And the following paragraphs that detail some specific problems that _might_ occur, but most probably won't as you didn't have a setuptools installed already? > but, as far as the setuptools site goes, can you point to the section that > states, to install (setuptools/easy_install), you do x: > -download this file > -run this command... I just did. > i found the files to download... i couldn't find the command to run, (at > least is wasn't apparent to me.) I'm not sure how much more apparent things can be that are titled Installing "setuptools" Installing "Easy Install" Bruce, you can give me whatever names you like - slut, jerk, dietz - but the fact remains that you did NOT carefully read my posts nor the links I pointed you to. Which I showed in the last post already, that you conveniently ignored to comment on. For me, it's EOD here. Diez From mike5160 at gmail.com Wed Nov 21 12:40:17 2007 From: mike5160 at gmail.com (mike5160) Date: Wed, 21 Nov 2007 09:40:17 -0800 (PST) Subject: Formatting question. References: <13k7jklks7fbm86@corp.supernews.com> <725f49c6-d0ab-48d6-8a7e-414c99a2b5e4@c29g2000hsa.googlegroups.com> Message-ID: <31893501-8d5f-495a-976b-129708f9204a@l1g2000hsa.googlegroups.com> On Nov 21, 11:36 am, mike5160 wrote: > On Nov 21, 1:22 am, Dennis Lee Bieber wrote: > > > > > On Tue, 20 Nov 2007 15:11:38 -0800 (PST), mike5160 > > declaimed the following in comp.lang.python: > > > > Hi all, > > > > My input file looks like this : ( the data is separated by tabs ) > > > > 11/26/2007 56.366 898.90 -10.086 23.11 1212.3 > > > 11/26/2007 52.25 897.6 -12.5 12.6 13333.5 > > > 11/26/2007 52.25 897.6 -12.5 12.6 133.5 > > > > The output I'm trying to get is as follows : > > > > ( Insert NBUSER.Grochamber Values > > > '11/26/2007','56.366','898.90','-10.086','23.11','1212.3', ) > > > ( Insert NBUSER.Grochamber Values > > > '11/26/2007','52.25','897.6','-12.5','12.6','13333.5', ) > > > ( Insert NBUSER.Grochamber Values > > > '11/26/2007','52.25','897.6','-12.5','12.6','133.5', ) > > > > > > > 2. How do I avoid the "," symbol after the last entry in the line? > > > (this are supposed to be sql-queries - importing excel based tabbed > > > data to sql database) > > > If those are SQL inserts, the ( is in the wrong place... > > > insert into NBUSER.Grochamber values (v1, v2, ... , vx) > > > > 3. What do I do when the data is missing? Like missing data? > > > First, for reading the file, recommend you look at the CSV module, > > which can be configured to use TABS rather than COMMAS. > > > For SQL -- if you are going to be writing raw text strings to an > > output file for later batching, YOU are going to have to supply some > > means to properly escape the data. The better way is to have the program > > connect to the database, using the applicable database adapter: MySQLdb > > for MySQL, pysqlite2 (or some variant) for SQLite3, some generic ODBC > > adapter if going that route... Let IT do the escaping. > > > Now, since MySQLdb just happens to expose the escaping function, AND > > just uses %s formatting of the results, one could easily get stuff to > > write to a file. > > > >>> import MySQLdb > > >>> con = MySQLdb.connect(host="localhost", user="test", passwd="test", db="test") > > >>> data = [ "11/26/2007 56.366 898.90 -10.086 23.11 1212.3", > > > ... "11/26/2007 897.6 O'Reilly 12.6 13333.5", > > ... "11/26/2007 52.25 897.6 -12.5 12.6 133.5" ] > > > Note how I left out a field (two tabs, nothing between), and how I > > put in a data item with a ' in it. > > > >>> for ln in data: > > > ... flds = ln.split("\t") > > ... placeholders = ", ".join(["%s"] * len(flds)) > > ... sql = BASE % placeholders > > ... sql = sql % con.literal(flds) > > ... print sql > > ... > > insert into NBUSER.Grochamber values ('11/26/2007', '56.366', '898.90', > > '-10.086', '23.11', '1212.3') > > insert into NBUSER.Grochamber values ('11/26/2007', '', '897.6', > > 'O\'Reilly', '12.6', '13333.5') > > insert into NBUSER.Grochamber values ('11/26/2007', '52.25', '897.6', > > '-12.5', '12.6', '133.5') > > > Note how the empty field is just '' (If you really need a NULL, > > you'll have to do some games to put a Python None entity into that empty > > string field). Also note how the single quote string value has been > > escaped. > > > Something like this for NULL in STRING DATA -- if a field were > > numeric 0 it would get substituted with a NULL too... > > > >>> for ln in data: > > > ... flds = ln.split("\t") > > ... placeholders = ", ".join(["%s"] * len(flds)) > > ... sql = BASE % placeholders > > ... flds = [(fld or None) for fld in flds] > > ... sql = sql % con.literal(flds) > > ... print sql > > ... > > insert into NBUSER.Grochamber values ('11/26/2007', '56.366', '898.90', > > '-10.086', '23.11', '1212.3') > > insert into NBUSER.Grochamber values ('11/26/2007', NULL, '897.6', > > 'O\'Reilly', '12.6', '13333.5') > > insert into NBUSER.Grochamber values ('11/26/2007', '52.25', '897.6', > > '-12.5', '12.6', '133.5') > > > -- > > Wulfraed Dennis Lee Bieber KD6MOG > > wlfr.....140 at ix.netcom.com wulfr.....141 at bestiaria.com > > HTTP://wlfraed.home.netcom.com/ > > (Bestiaria Support Staff: web-a.....142 at bestiaria.com) > > HTTP://www.bestiaria.com/98143 > > Hi Dennis, > > Thanks to you for your reply. I am a newbie to Python and appreciate > you helping me. Now, I am importing data from an excel sheet and > getting it ready for a derby database. I am to use netbeans, since our > research team uses that. However, derby database uses sql entries to > update the database. And I m trying to format all the excel data I > have, which I got from using labview. I suggested that we use awk/perl/ > python etc. and finally after looking at the documentation available I > figured Python would be best. However, (see my reply above) I am > looking for a sample book/document etc. somebody suggested we try > Python Phrasebook. But that one covers a lot of different fields > whereas for my purposes I need a book with examples on using Python in > the above manner. If you or anybody knows about this kind of book > please let me know. > > Thank you very much for your help, > Mike. Oops! Sorry I did not know what I did , but I just noticed that I changed the subject of the Discussion twice. I just want every body to know that it was unintentional. Thanks, Mike. From cokofreedom at gmail.com Tue Nov 13 05:17:09 2007 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Tue, 13 Nov 2007 10:17:09 -0000 Subject: Looking for a good Python environment In-Reply-To: <1194947762.178169.318430@57g2000hsv.googlegroups.com> References: <1194389774.159051.55580@19g2000hsx.googlegroups.com> <1194434140.836932.10670@k79g2000hse.googlegroups.com> <1194686473.581666.203870@k79g2000hse.googlegroups.com> <87d4uimnwk.fsf@rudin.co.uk> <1194947762.178169.318430@57g2000hsv.googlegroups.com> Message-ID: <1194949029.856998.306670@22g2000hsm.googlegroups.com> On Nov 13, 10:56 am, bramble wrote: > On Nov 10, 4:48 am, Paul Rudin wrote: > > > jwelby writes: > > > > The main reason I have used Eclipse for larger, team based, projects > > > is for the source control plug-ins. Eclipse has plug-in support for > > > cvs and svn. PyScripter may have this too - perhaps I've missed it. > > > (I'm away from my Windows box at the moment, otherwise I would check). > > > Of course, there are other ways to implement source control without it > > > needing to be integrated in the IDE, so even this need not put off > > > anyone who wants to use PyScripter with source control. > > > > [snip] > > > I'm not sure if you count emacs as "lightweight" but it's certainly > > less resource hungry than eclipse/pydev, and does have integrated > > cvs/svn functionality. > > I've never understood the desire for using your version control > software via your IDE. Why not just Alt-Tab over to your terminal > window and run the svn/bzr/hg/git/whatever commands yourself right > from there? Because it saves you from having to do this. Some people prefer all their commands in one place. And GUI wise it is often easier to click the button showing all previouis versions, or comparing two of them visually. I use Eclipse with ClearCase and it saves me a great deal of trouble when dealing with 100+ files... From ihatespam at hotmail.com Wed Nov 7 18:15:40 2007 From: ihatespam at hotmail.com (Just Another Victim of the Ambient Morality) Date: Wed, 07 Nov 2007 23:15:40 GMT Subject: Is pyparsing really a recursive descent parser? References: <43rXi.397547$6L.130044@fe03.news.easynews.com><1194223837.104424.242360@o3g2000hsb.googlegroups.com><9HoYi.50838$m72.33706@fe06.news.easynews.com><9WpYi.124193$g82.92783@fe07.news.easynews.com> Message-ID: "Chris Mellon" wrote in message news:mailman.945.1194471797.13605.python-list at python.org... > On Nov 7, 2007 3:15 PM, Just Another Victim of the Ambient Morality > wrote: > >> > In short, it hasn't really evovled into a user-friendly package >> > yet. >> >> Thank you. >> How is it that I seem to be the only one in the market for a correct >> parser? Earley has a runtine of O(n^3) in the worst case and O(n^2) >> typically. I have trouble believing that everyone else in the world has >> such intense run-time requirements that they're willing to forego >> correctness. Why can't I find a pyparsing-esque library with this >> implementation? I'm tempted to roll my own except that it's a fairly >> complicated algorithm and I don't really understand how it's any more >> efficient than the naive approach... > > You have an unusual definition of correctness. Many people would say > that an ambiguous grammar is a bug, not something to support. I don't think I do. Besides, you assume too much... First off, we've already established that there are unambiguous grammars for which pyparsing will fail to parse. One might consider that a bug in pyparsing... Secondly, I get the impression you want to consider ambiguous grammars, in some sense, "wrong." They are not. Even if they were, if you are parsing something for which you are not the creator and that something employs an ambiguous grammar, what choice do you have? Furthermore, given a set of possible parsings, you might be able to decide which one you favour given the context of what was parsed! There's a plethora of applications for parsing ambiguous grammars yet there are no tools for doing so? > In fact, I often use pyparsing precisely in order to disambiguate > (according to specific rules, which are embodied by the parser) > ambiguous input, like bizarre hand-entered datetime value. What do you mean? How do you use pyparsing to disambiguate: 01-01-08 ...? From meesters at uni-mainz.de Thu Nov 1 06:51:16 2007 From: meesters at uni-mainz.de (Christian Meesters) Date: Thu, 01 Nov 2007 11:51:16 +0100 Subject: permuting over nested dicts? References: <1193908332.223564.3040@z24g2000prh.googlegroups.com> Message-ID: Thanks everyone, I knew there must be a snippet somewhere, just couldn't find one! (Just for the sake of completeness: Order doesn't matter and I hope that with my data I won't reach the recursion depth limit.) Christian From rishiyoor at gmail.com Sat Nov 10 15:37:48 2007 From: rishiyoor at gmail.com (rishiyoor at gmail.com) Date: Sat, 10 Nov 2007 12:37:48 -0800 Subject: Coding Help In-Reply-To: References: <1194716747.634041.204620@k79g2000hse.googlegroups.com> <5pmbulFri447U4@mid.uni-berlin.de> <1194724489.417628.313430@19g2000hsx.googlegroups.com> Message-ID: <1194727068.352431.120250@50g2000hsm.googlegroups.com> On Nov 10, 3:20 pm, Carsten Haese wrote: > > Maybe it would help you if you added an S6 that does nothing underneath > the "C2 is true" branch of your flow chart. > > -- > Carsten Haesehttp://informixdb.sourceforge.net Think I found a sequence of statements that would work if C1 if C2 else if C4 S2 else S3 else if C3 S1 if C5 # This should be C5. There is an error in the chart. S4 From sndive at gmail.com Tue Nov 6 17:14:57 2007 From: sndive at gmail.com (sndive at gmail.com) Date: Tue, 06 Nov 2007 22:14:57 -0000 Subject: PyObject sanitizer (CPython 2.4.4) Message-ID: <1194387297.257028.172740@50g2000hsm.googlegroups.com> I get this from valgrind (no suppression file but thgis probably is not covered by the suppressor anyway): ==6108== Invalid read of size 4 ==6108== at 0x48D19F4: lookdict_string (dictobject.c:359) ==6108== by 0x48D1B59: PyDict_GetItem (dictobject.c:554) ==6108== by 0x48B1657: instance_getattr2 (classobject.c:741) ==6108== by 0x48B701D: instance_getattr1 (classobject.c:725) ==6108== by 0x48B2670: instance_getattr (classobject.c:764) ==6108== by 0x48D6500: PyObject_GetAttr (object.c:1088) ==6108== by 0x48D6355: PyObject_GetAttrString (object.c:1031) so i wonder if the PyObject i gave to PyObject_GetAttrString to gnaw on is in good shape. is assert(obj->ob_refcnt>0); a good way to check if i'm dealing with a valid PyObject or there is a helper that can do this for me? From Xue.Huichao at gmail.com Fri Nov 9 23:33:17 2007 From: Xue.Huichao at gmail.com (Bighead) Date: Sat, 10 Nov 2007 04:33:17 -0000 Subject: Writing a CGI to query DB Message-ID: <1194669197.429480.65820@s15g2000prm.googlegroups.com> Hi, I am currently working on a CGI deployed on an Apache server, which, given an arbitrary SQL, fetches raw data from a remote DB server and return them in a HTML page. This CGI works fine on quick SQLs. But when I try to run a slow SQL on this CGI, through a Squid Proxy, I always get the Error message from Squid: Zero Sized Reply, after 5 minutes. The SQL itself is correct, since I have tried it directly on the DB server. So what do you think might cause the problem? Thank you. From http Sat Nov 3 08:55:38 2007 From: http (Paul Rubin) Date: 03 Nov 2007 05:55:38 -0700 Subject: python newbie References: <472b2b84$0$13761$6e1ede2f@read.cnntp.org> <5p0s6vFp47k9U1@mid.individual.net> <472b5251$0$6238$426a34cc@news.free.fr> <13ioa6f6t797gce@corp.supernews.com> Message-ID: <7x4pg3wks5.fsf@ruckus.brouhaha.com> Duncan Booth writes: > modules are not special in any way, except that you cannot subclass them. > Oops, sorry I got that wrong. Modules are not special in any way, they can > have methods as well as functions: I've felt for a long time that you should be able to define __call__ on a module, but that doesn't seem to be allowed, at least if you try it in the obvious way. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Nov 27 04:11:48 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 27 Nov 2007 10:11:48 +0100 Subject: the annoying, verbose self In-Reply-To: References: <3c954a31-9fb9-4c0f-b784-cef9ee057ca6@g30g2000hsb.googlegroups.com> <4068d518-cba9-4eac-bd91-11f676c17b3d@w34g2000hsg.googlegroups.com> <5qq6quF10jrh5U2@mid.uni-berlin.de> <5qqoslF10jrh5U6@mid.uni-berlin.de> <474b1b44$0$20133$426a74cc@news.free.fr> Message-ID: <474bdf4f$0$19226$426a74cc@news.free.fr> Steven D'Aprano a ?crit : > On Mon, 26 Nov 2007 21:48:36 +0100, Ton van Vliet wrote: > >> On Mon, 26 Nov 2007 20:14:50 +0100, Bruno Desthuilliers >> wrote: >> >>>> However, I was more thinking in terms of attributes only >>> Too bad : in Python, everything's an object, so 'methods' are attributes >>> too. >> Right, but I'm sure *you* know a way to distinguish between them Yes : reading the doc. But that's something the compiler will have hard time doing. >> (I'm >> just a beginner ;-) > > All methods are attributes. Not all attributes are methods. The usual way > to see if something is a method is to try calling it and see what > happens, but if you want a less informal test, try type(): > > >>>> type(''.join) > >>>> type(Foo().foo) # with the obvious definition of Foo > > Fine. Now since Python let you define your own callable types and your own descriptors, you can as well have an attribute that behave just like a method without being an instance of any of the method types - so the above test defeats duck typing. And since you can have callable attributes that are definitively not methods, you can't rely on the fact that an attribute is callable neither. From joemystery123 at gmail.com Mon Nov 5 17:56:51 2007 From: joemystery123 at gmail.com (crybaby) Date: Mon, 05 Nov 2007 22:56:51 -0000 Subject: Eclipse3.3 with Pydev 1.3.10 Mylar problem, have Mylyn Message-ID: <1194303411.186722.156140@o80g2000hse.googlegroups.com> Right now I am trying to install pydev 1.3.10 on Eclipse 3.3. I am getting an Mylar error org.eclipse.mylar (2.0.0.v20070403-1300) or something needed. Mylyn is mylar, now. How do you disable the mylar dependency, so that Mylyn is used by PyDev? From fred.sells at adventistcare.org Mon Nov 19 16:06:36 2007 From: fred.sells at adventistcare.org (Sells, Fred) Date: Mon, 19 Nov 2007 16:06:36 -0500 Subject: newbie Q: sequence membership In-Reply-To: <8a934485-efd4-4e89-ac1b-d7c277978686@l22g2000hsc.googlegroups.com> Message-ID: <0A53725C4A497848A7B3A0874B2598313D3990@acesxch01.ADVENTISTCORP.NET> > >>> a, b = [], [] > >>> a.append(b) > >>> b.append(a) did you perhaps mean a.append('b'); b.append('a'); otherwise this seems pretty advanced for a newbie > >>> b in a > True > >>> a in a > Traceback (most recent call last): > File "", line 1, in > RuntimeError: maximum recursion depth exceeded in cmp > >>> > >>> a is a[0] > False > >>> a == a[0] > Traceback (most recent call last): > File "", line 1, in > RuntimeError: maximum recursion depth exceeded in cmp > > ---------- > > I'm a little new to this language so my mental model on whats going on > may need to be refined. > > I expect "a in a" to evaluate to "False". Since it does not it may be > that while checking equality it uses "==" and not "is". If that is the > reason then the question becomes why doesn't "a == a[0]" evaluate to > "False"? As a side, and if that is the reason, is there a version of > "in" that uses "is"? "a is in a" does not work. > > Thankx, > Trivik > -- > http://mail.python.org/mailman/listinfo/python-list > From kumar.mcmillan at gmail.com Tue Nov 27 09:19:00 2007 From: kumar.mcmillan at gmail.com (Kumar McMillan) Date: Tue, 27 Nov 2007 08:19:00 -0600 Subject: Best ways of managing text encodings in source/regexes? In-Reply-To: <474B4858.50905@v.loewis.de> References: <474B4858.50905@v.loewis.de> Message-ID: On Nov 26, 2007 4:27 PM, "Martin v. L?wis" wrote: > > myASCIIRegex = re.compile('[A-Z]') > > myUniRegex = re.compile(u'\u2013') # en-dash > > > > then read the source file into a unicode string with codecs.read(), > > then expect re to match against the unicode string using either of > > those regexes if the string contains the relevant chars? Or do I need > > to do make all my regex patterns unicode strings, with u""? > > It will work fine if the regular expression restricts itself to ASCII, > and doesn't rely on any of the locale-specific character classes (such > as \w). If it's beyond ASCII, or does use such escapes, you better make > it a Unicode expression. yes, you have to be careful when writing unicode-senstive regular expressions: http://effbot.org/zone/unicode-objects.htm "You can apply the same pattern to either 8-bit (encoded) or Unicode strings. To create a regular expression pattern that uses Unicode character classes for \w (and \s, and \b), use the "(?u)" flag prefix, or the re.UNICODE flag: pattern = re.compile("(?u)pattern") pattern = re.compile("pattern", re.UNICODE) " > > I'm not actually sure what precisely the semantics is when you match > an expression compiled from a byte string against a Unicode string, > or vice versa. I believe it operates on the internal representation, > so \xf6 in a byte string expression matches with \u00f6 in a Unicode > string; it won't try to convert one into the other. > > Regards, > Martin > > -- > http://mail.python.org/mailman/listinfo/python-list > From arnodel at googlemail.com Tue Nov 27 14:14:42 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 27 Nov 2007 11:14:42 -0800 (PST) Subject: Looking for a Python tutor References: <5644ac82-29c2-4e5a-86a3-7c7c11fc2152@r60g2000hsc.googlegroups.com> Message-ID: <5dd6753e-f355-44e8-89e5-8f9695ff263e@i12g2000prf.googlegroups.com> On Nov 27, 5:46 pm, hong2221 wrote: > I'm looking for a Python programmar that is willing write simple ^^^^^^^^^^ > functions, prices can be talked over. Contact me asap. You should start with a prospelling :) -- Arnaud From martin at v.loewis.de Mon Nov 26 17:27:36 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 26 Nov 2007 23:27:36 +0100 Subject: Best ways of managing text encodings in source/regexes? In-Reply-To: References: Message-ID: <474B4858.50905@v.loewis.de> > * When I say "# -*- coding: utf-8 -*-" and confirm my IDE is saving > the source file as UTF-8, do I still need to prefix all the strings > constructed in the source with u as in myStr = u"blah", even when > those strings contain only ASCII or ISO-8859-1 chars? (It would be a > bother for me to do this for the complete source I'm working on, where > I rarely need chars outside the ISO-8859-1 range.) Depends on what you want to achieve. If you don't prefix your strings with u, they will stay byte string objects, and won't become Unicode strings. That should be fine for strings that are pure ASCII; for ISO-8859-1 strings, I recommend it is safer to only use Unicode objects to represent such strings. In Py3k, that will change - string literals will automatically be Unicode objects. > * Will python figure it out if I use different encodings in different > modules -- say a main source file which is "# -*- coding: utf-8 -*-" > and an imported module which doesn't say this (for which python will > presumably use a default encoding)? Yes, it will. The encoding declaration is per-module. > * If I want to use a Unicode char in a regex -- say an en-dash, U+2013 > -- in an ASCII- or ISO-8859-1-encoded source file, can I say > > myASCIIRegex = re.compile('[A-Z]') > myUniRegex = re.compile(u'\u2013') # en-dash > > then read the source file into a unicode string with codecs.read(), > then expect re to match against the unicode string using either of > those regexes if the string contains the relevant chars? Or do I need > to do make all my regex patterns unicode strings, with u""? It will work fine if the regular expression restricts itself to ASCII, and doesn't rely on any of the locale-specific character classes (such as \w). If it's beyond ASCII, or does use such escapes, you better make it a Unicode expression. I'm not actually sure what precisely the semantics is when you match an expression compiled from a byte string against a Unicode string, or vice versa. I believe it operates on the internal representation, so \xf6 in a byte string expression matches with \u00f6 in a Unicode string; it won't try to convert one into the other. Regards, Martin From martin at v.loewis.de Tue Nov 6 16:02:06 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 06 Nov 2007 22:02:06 +0100 Subject: How do I get the PC's Processor speed? In-Reply-To: <1194376737.430731.60750@o80g2000hse.googlegroups.com> References: <1194376737.430731.60750@o80g2000hse.googlegroups.com> Message-ID: <4730D64E.2090401@v.loewis.de> > On the problem PCs, both of these methods give me the same information > (i.e. only the processor name). However, if I go to "System > Properties" and look at the "General" tab, it lists the CPU name and > processor speed. Does anyone else know of another way to get at this > information? I'm not sure whether it is *this* information, but you can use NtQuerySystemInformation, with a class parameter of SystemProcessorPowerInformation, and passing SYSTEM_PROCESSOR_POWER_INFORMATION as the buffer. That gives, among others, a value CurrentFrequency (along with LastBusyFrequency, LastC3Frequency, and ThermalLimitFrequency). This usage of NtQuerySystemInformation is undocumented. Regards, Martn From bj_666 at gmx.net Sun Nov 25 01:57:51 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 25 Nov 2007 06:57:51 GMT Subject: How to display unicode with the CGI module? References: Message-ID: <5qsknfF11nhdfU1@mid.uni-berlin.de> On Sat, 24 Nov 2007 15:58:56 -0800, coldpizza wrote: > The problem I am having is that I get an error while trying to display > Unicode UTF-8 characters via a Python CGI script. > > The error goes like this: "UnicodeEncodeError: 'ascii' codec can't > encode character u'\u026a' in position 12: ordinal not in range(128)". Unicode != UTF-8. You are not trying to send an UTF-8 encoded byte string but an *unicode string*. That's not possible. If unicode strings should "leave" your program they must be encoded into byte strings. If you don't do this explicitly Python tries to encode as ASCII and fails if there's anything non-ASCII in the string. The `encode()` method is your friend. Ciao, Marc 'BlackJack' Rintsch From aaron.watters at gmail.com Mon Nov 5 14:08:59 2007 From: aaron.watters at gmail.com (Aaron Watters) Date: Mon, 05 Nov 2007 11:08:59 -0800 Subject: Python good for data mining? In-Reply-To: <472e3b8d$0$3128$426a74cc@news.free.fr> References: <1194141739.683498.206780@k79g2000hse.googlegroups.com> <472e3b8d$0$3128$426a74cc@news.free.fr> Message-ID: <1194289739.271421.48660@k79g2000hse.googlegroups.com> On Nov 4, 4:36 pm, Bruno Desthuilliers wrote: > > > How good is the integration with MySQL in Python? > > Pretty good - but I wouldn't call MySQL a serious RDBMS. I would disagree with this, for this particular case. I think it's probably better than most other rdbms's for apps like data mining where you don't need transactional support, especially if you use the table implementations that don't support ACID transactions. -- Aaron Watters === http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=segmentation%20fault From s.jolicoeur at gmail.com Thu Nov 29 15:20:49 2007 From: s.jolicoeur at gmail.com (sjol) Date: Thu, 29 Nov 2007 12:20:49 -0800 (PST) Subject: Job posting on the site is broken Message-ID: <042303ed-d871-431b-b908-9ab9b755c507@s12g2000prg.googlegroups.com> To the webmaster of python.org, I have tried to have a job posted on the job board but! Alas, it doesn't work and I cannot get a response from the webmaster. Shall I post here ? Stephane From mike5160 at gmail.com Wed Nov 21 11:36:28 2007 From: mike5160 at gmail.com (mike5160) Date: Wed, 21 Nov 2007 08:36:28 -0800 (PST) Subject: Formatting question. References: <13k7jklks7fbm86@corp.supernews.com> Message-ID: <725f49c6-d0ab-48d6-8a7e-414c99a2b5e4@c29g2000hsa.googlegroups.com> On Nov 21, 1:22 am, Dennis Lee Bieber wrote: > On Tue, 20 Nov 2007 15:11:38 -0800 (PST), mike5160 > declaimed the following in comp.lang.python: > > > > > Hi all, > > > My input file looks like this : ( the data is separated by tabs ) > > > 11/26/2007 56.366 898.90 -10.086 23.11 1212.3 > > 11/26/2007 52.25 897.6 -12.5 12.6 13333.5 > > 11/26/2007 52.25 897.6 -12.5 12.6 133.5 > > > The output I'm trying to get is as follows : > > > ( Insert NBUSER.Grochamber Values > > '11/26/2007','56.366','898.90','-10.086','23.11','1212.3', ) > > ( Insert NBUSER.Grochamber Values > > '11/26/2007','52.25','897.6','-12.5','12.6','13333.5', ) > > ( Insert NBUSER.Grochamber Values > > '11/26/2007','52.25','897.6','-12.5','12.6','133.5', ) > > > > > 2. How do I avoid the "," symbol after the last entry in the line? > > (this are supposed to be sql-queries - importing excel based tabbed > > data to sql database) > > If those are SQL inserts, the ( is in the wrong place... > > insert into NBUSER.Grochamber values (v1, v2, ... , vx) > > > 3. What do I do when the data is missing? Like missing data? > > First, for reading the file, recommend you look at the CSV module, > which can be configured to use TABS rather than COMMAS. > > For SQL -- if you are going to be writing raw text strings to an > output file for later batching, YOU are going to have to supply some > means to properly escape the data. The better way is to have the program > connect to the database, using the applicable database adapter: MySQLdb > for MySQL, pysqlite2 (or some variant) for SQLite3, some generic ODBC > adapter if going that route... Let IT do the escaping. > > Now, since MySQLdb just happens to expose the escaping function, AND > just uses %s formatting of the results, one could easily get stuff to > write to a file. > > >>> import MySQLdb > >>> con = MySQLdb.connect(host="localhost", user="test", passwd="test", db="test") > >>> data = [ "11/26/2007 56.366 898.90 -10.086 23.11 1212.3", > > ... "11/26/2007 897.6 O'Reilly 12.6 13333.5", > ... "11/26/2007 52.25 897.6 -12.5 12.6 133.5" ] > > Note how I left out a field (two tabs, nothing between), and how I > put in a data item with a ' in it. > > >>> for ln in data: > > ... flds = ln.split("\t") > ... placeholders = ", ".join(["%s"] * len(flds)) > ... sql = BASE % placeholders > ... sql = sql % con.literal(flds) > ... print sql > ... > insert into NBUSER.Grochamber values ('11/26/2007', '56.366', '898.90', > '-10.086', '23.11', '1212.3') > insert into NBUSER.Grochamber values ('11/26/2007', '', '897.6', > 'O\'Reilly', '12.6', '13333.5') > insert into NBUSER.Grochamber values ('11/26/2007', '52.25', '897.6', > '-12.5', '12.6', '133.5') > > > > Note how the empty field is just '' (If you really need a NULL, > you'll have to do some games to put a Python None entity into that empty > string field). Also note how the single quote string value has been > escaped. > > Something like this for NULL in STRING DATA -- if a field were > numeric 0 it would get substituted with a NULL too... > > >>> for ln in data: > > ... flds = ln.split("\t") > ... placeholders = ", ".join(["%s"] * len(flds)) > ... sql = BASE % placeholders > ... flds = [(fld or None) for fld in flds] > ... sql = sql % con.literal(flds) > ... print sql > ... > insert into NBUSER.Grochamber values ('11/26/2007', '56.366', '898.90', > '-10.086', '23.11', '1212.3') > insert into NBUSER.Grochamber values ('11/26/2007', NULL, '897.6', > 'O\'Reilly', '12.6', '13333.5') > insert into NBUSER.Grochamber values ('11/26/2007', '52.25', '897.6', > '-12.5', '12.6', '133.5') > > > > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfr...95 at ix.netcom.com wulfr...96 at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-a...97 at bestiaria.com) > HTTP://www.bestiaria.com/98 Hi Dennis, Thanks to you for your reply. I am a newbie to Python and appreciate you helping me. Now, I am importing data from an excel sheet and getting it ready for a derby database. I am to use netbeans, since our research team uses that. However, derby database uses sql entries to update the database. And I m trying to format all the excel data I have, which I got from using labview. I suggested that we use awk/perl/ python etc. and finally after looking at the documentation available I figured Python would be best. However, (see my reply above) I am looking for a sample book/document etc. somebody suggested we try Python Phrasebook. But that one covers a lot of different fields whereas for my purposes I need a book with examples on using Python in the above manner. If you or anybody knows about this kind of book please let me know. Thank you very much for your help, Mike. From rustompmody at gmail.com Sat Nov 3 00:17:34 2007 From: rustompmody at gmail.com (Rustom Mody) Date: Sat, 3 Nov 2007 09:47:34 +0530 Subject: AOP and pep 246 In-Reply-To: References: <1193937488.399694.235180@o80g2000hse.googlegroups.com> <7x1wb9z3qv.fsf@ruckus.brouhaha.com> <1193992351.035997.237890@o80g2000hse.googlegroups.com> Message-ID: I find these viewpoints interesting in their divergence. At the risk of being simplistic: Kay: AOP == AspectJ or thereabouts. A failure in itself and uninteresting to pythonistas Michele: AOP not very interesting though does good work himself in decorators, metaclasses and other such AOPish stuff Carl: Aspect == something (anything?) cognitively coherent. AOP (rather AAP) means: When a language feature supports an aspect use it, when not wriggle round it. Python requires less wriggling than java. A powerful conceptual viewpoint but unhelpful to the developer... My own feeling: Python is more AOP ready than java. So lighter-weight techniques like Michele's decorator should go further. But methodology not yet formulated. From gagsl-py2 at yahoo.com.ar Tue Nov 6 15:48:57 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 06 Nov 2007 17:48:57 -0300 Subject: subprocess chokes on spaces in path References: <1194381153.973107.132570@19g2000hsx.googlegroups.com> Message-ID: En Tue, 06 Nov 2007 17:32:33 -0300, BartlebyScrivener escribi?: > Using bash on Debian Etch. > > If word_doc = sys.argv[1] and it's a file name like My\ Word.doc this > function reads My and Word as two separate files unless the second > '%s' is quoted. Took me a lot of trial and error to discover. Is this > the most elegant way to do it? I was using popen originally, then saw > some threads suggesting subprocess cured the spaces in path problem. Use a list of arguments [antiword, word_doc] and let subprocess handle the spaces the right way. -- Gabriel Genellina From hdante at gmail.com Wed Nov 28 11:57:43 2007 From: hdante at gmail.com (hdante) Date: Wed, 28 Nov 2007 08:57:43 -0800 (PST) Subject: How to Teach Python "Variables" References: <4749bb94$1@news.bezeqint.net> <5qvf6pF122r3mU1@mid.individual.net> <87abp1qqth.fsf@mulj.homelinux.net> <2d7c881d-e5c0-43ec-a8eb-b7c81a118c21@w40g2000hsb.googlegroups.com> Message-ID: <8cca3871-2bb1-4eeb-96bc-f9dacc20c0a4@o6g2000hsd.googlegroups.com> On Nov 28, 2:12 pm, "Chris Mellon" wrote: > > Right. Python variables are pointers, except for all the ways that > they are different. By the same criteria, they are also puppies. Give > it a rest. I'm sorry if your notion of pointer is incorrect. A pointer (or, more formally, a reference) is an object that points to some value. A python variable isn't different than that in any way. From besturk at gmail.com Sun Nov 18 01:46:20 2007 From: besturk at gmail.com (Abandoned) Date: Sat, 17 Nov 2007 22:46:20 -0800 (PST) Subject: how can i return a image in mod python ? Message-ID: Hi.. I want to show the pictures with mod python directly. def showimage(req): some process... open /var/www/a.jpg and print for example if i open: domain.com/a.py/showimage It must show me image directly (no redirect or html) How can i do it ? I'm sorry for my bad english. Kind Regards.... From ptmcg at austin.rr.com Thu Nov 1 10:10:21 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Thu, 01 Nov 2007 07:10:21 -0700 Subject: ANN: O'Reilly e-book, "Getting Started with Pyparsing" In-Reply-To: References: Message-ID: <1193926221.267047.75510@o3g2000hsb.googlegroups.com> On Nov 1, 1:25 am, Paul McGuire wrote: > Several chapter excerpts are available online, including this > chapter on the Zen of Pyparsing:http://preview.tinyurl.com/yp4v48 > Here is a better link: http://my.safaribooksonline.com/9780596514235/what_makes_pyparsing_so_special -- Paul From stevendepret at hotmail.com Thu Nov 8 11:02:59 2007 From: stevendepret at hotmail.com (steven depret) Date: Thu, 8 Nov 2007 17:02:59 +0100 Subject: http question Message-ID: hello there, a question that keeps me puzzled for some time now: basically i want to fetch the output from an http page. The page exists out of an input field and a button to calculate my data. The problem is that I simply cannot get my hands on the output, but only on the page itself. Image that the following URL ( http://10.10.10.10:8765/?command=foo&inputfield=bar ) gives as result : a = xx b = yy My intention is to fetch the output so that I can play with it. this is what I do : import httplib connection = httplib.HTTPConnection('10.10.10.10:8765') connection.request('POST', 'command=foo', 'inputfield=bar') response = connection.getresponse() output = response.read() print output I get a lot of stuff in my output, but simply NOT the a=xx and the b = yy. What the heck am I doing wrong ? _________________________________________________________________ Deel je gedachten direct met je vrienden http://messenger.live.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From pecora at anvil.nrl.navy.mil Wed Nov 28 17:08:50 2007 From: pecora at anvil.nrl.navy.mil (Lou Pecora) Date: Wed, 28 Nov 2007 17:08:50 -0500 Subject: Books on Python References: <3ef06e6a-329c-47d6-8860-55b760e8e6a2@e4g2000hsg.googlegroups.com> Message-ID: In article <3ef06e6a-329c-47d6-8860-55b760e8e6a2 at e4g2000hsg.googlegroups.com>, shadowsithe at gmail.com wrote: > On Nov 27, 10:05 pm, "barcaroller" wrote: > > Can someone kindly recommend some good books on the following: > > > > Python for beginners > > Python for advanced users > > > > Is there a bible like Larry Wall's Programming Perl or Bjarne Stroustrup's > > The C++ Programming Language? > > Python in a Nutshell is a very good reference. I second that. I also found Learning Python (Lutz & Ascher, O'Reilly pub.) to be helpful when I first started, but Nutshell is what I keep going back to. Very good book. -- -- Lou Pecora From bellman at lysator.liu.se Thu Nov 22 09:36:53 2007 From: bellman at lysator.liu.se (Thomas Bellman) Date: Thu, 22 Nov 2007 14:36:53 +0000 (UTC) Subject: eof References: <92a2c0c9-e6a1-4344-aeac-830940200f20@t47g2000hsc.googlegroups.com> <79i9k35vs76cqgqnino7dj3ql623us3euq@4ax.com> <6c04c760-6cf1-4715-9ec9-30f43ebaa01f@d27g2000prf.googlegroups.com> <062a9497-7626-440a-93eb-b897e6dec01f@p69g2000hsa.googlegroups.com> <5qlkf3F10drl7U1@mid.uni-berlin.de> <877ikauwyw.fsf@mulj.homelinux.net> Message-ID: Hrvoje Niksic wrote: > I don't get it, Python's files are implemented on top of stdio FILE > objects, which do buffering and provide EOF checking (of the sort > where you can check if a previous read hit the EOF, but still). Why > not export that functionality? Alexy wants to check if a file is about to hit EOF, not if it has already hit EOF. Stdio does not support that. Nor does Unix. The only way to check if the file is about to hit EOF, is to actually perform a read and see if it returns zero bytes. That is usually OK to do on plain files, but on pipes, sockets or terminals, you would have major problems, since suddenly calling the eof() method would block the process. Probably not what you were expecting. -- Thomas Bellman, Lysator Computer Club, Link?ping University, Sweden "Life IS pain, highness. Anyone who tells ! bellman @ lysator.liu.se differently is selling something." ! Make Love -- Nicht Wahr! From bellman at lysator.liu.se Tue Nov 27 13:07:19 2007 From: bellman at lysator.liu.se (Thomas Bellman) Date: Tue, 27 Nov 2007 18:07:19 +0000 (UTC) Subject: spawning a process with subprocess References: <8b45ae31-a3e2-470f-93d0-ad31d8717176@s36g2000prg.googlegroups.com> <9gk5o4knd5.fsf@overberg.got.jeppesensystems.com> <243adf48-3041-4653-aa4b-964990fd751a@s36g2000prg.googlegroups.com> Message-ID: bhunter wrote: > * The problem with the testcase, I believe, was the size of the file > and the output pipe filling up, as Nick suggested. When run on a > smaller file, with Jordan's suggestions, it works fine. With a larger > file, it's necessary to do as Nick says. If the size of the file is > unknown, its best to use this case as the default. This seems > unfortunate to me, because it's quite a bit of code to do something > that should be fairly straightforward--at least, that's what I think. You may be interrested in the module 'asyncproc', which I wrote a couple of years ago to make it easier working with processes that would otherwise block on output. You can download it at . It probably only works on Unix, but considering your use of "cat" as a test program, I suppose that isn't a problem for you. -- Thomas Bellman, Lysator Computer Club, Link?ping University, Sweden "God is real, but Jesus is an integer." ! bellman @ lysator.liu.se ! Make Love -- Nicht Wahr! From arkanes at gmail.com Sun Nov 11 13:42:08 2007 From: arkanes at gmail.com (Arkanes) Date: Sun, 11 Nov 2007 11:42:08 -0700 Subject: Populating a dictionary, fast In-Reply-To: <818643.92017.qm@web915.biz.mail.mud.yahoo.com> References: <818643.92017.qm@web915.biz.mail.mud.yahoo.com> Message-ID: <47374D00.7080500@gmail.com> Michael Bacarella wrote: > You can download the list of keys from here, it's 43M gzipped: > http://www.sendspace.com/file/9530i7 > > and see it take about 45 minutes with this: > > $ cat cache-keys.py > #!/usr/bin/python > v = {} > for line in open('keys.txt'): > v[long(line.strip())] = True > > It takes about 20 seconds for me. It's possible it's related to int/long unification - try using Python 2.5. If you can't switch to 2.5, try using string keys instead of longs. From fabiofz at gmail.com Mon Nov 5 14:53:39 2007 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Mon, 5 Nov 2007 17:53:39 -0200 Subject: Pydev 1.3.10 Released Message-ID: Hi All, Pydev and Pydev Extensions 1.3.10 have been released Details on Pydev Extensions: http://www.fabioz.com/pydev Details on Pydev: http://pydev.sf.net Details on its development: http://pydev.blogspot.com Release Highlights in Pydev Extensions: ----------------------------------------------------------------- * Code-analysis: Doesn't report 'statement without effect' within list comprehension. * Context insensitive code completion: Shows contents of zips/eggs/jars * Go to definition: Working with zips/eggs/jars. Release Highlights in Pydev: ---------------------------------------------- * Symlinks supported in the system pythonpath configuration. * Egg/zip files are now supported. * The creation of a project in a non-default location is now allowed within the workspace * JDT used to get completions from jars (but referencing other java projects is still not supported). * Configuration of pythonpath allows multiple selection for removal. * Configuration of pythonpath allows multiple jars/zips to be added at once. * When configuring the pythonpath, the paths are sorted for selection. * The file extensions that pydev recognizes for python can now be customized. * Patch by Carl Robinson: Code-folding for elements such as for, try, while, etc. * Removed the go to next/previous problem annotation (Eclipse 3.3 already provides a default implementation for it). What is PyDev? --------------------------- PyDev is a plugin that enables users to use Eclipse for Python and Jython development -- making Eclipse a first class Python IDE -- It comes with many goodies such as code completion, syntax highlighting, syntax analysis, refactor, debug and many others. Cheers, -- Fabio Zadrozny ------------------------------------------------------ Software Developer ESSS - Engineering Simulation and Scientific Software http://www.esss.com.br Pydev Extensions http://www.fabioz.com/pydev Pydev - Python Development Enviroment for Eclipse http://pydev.sf.net http://pydev.blogspot.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From j3nsby at gmail.com Wed Nov 7 20:46:36 2007 From: j3nsby at gmail.com (Jens) Date: Wed, 07 Nov 2007 17:46:36 -0800 Subject: pydoc - how to generate documentation for an entire package? Message-ID: <1194486396.222749.302390@22g2000hsm.googlegroups.com> I have a project/package for which I want to generate documentation using pydoc. My problem is that when I type "pydoc.py -w MyPackage" it only generates documentation for the package - no modules, classes or methods or sub-packages. Just a single HTML file called "MyPackage.html" That's strange - is there something here I'm missing. How do you generate documentation for a whole package? From ron.l.johnson at cox.net Fri Nov 23 21:34:04 2007 From: ron.l.johnson at cox.net (Ron Johnson) Date: Fri, 23 Nov 2007 20:34:04 -0600 Subject: md5 wrongness? Message-ID: Why do Python's md5 and GNU md5sum produce differing results? $ md5sum --version md5sum (GNU coreutils) 5.97 $ echo snagglefrob | md5sum f842244d79af85b457811091319d85ff - $ echo 'snagglefrob' | md5sum f842244d79af85b457811091319d85ff - $ echo "snagglefrob" | md5sum f842244d79af85b457811091319d85ff - $ python Python 2.4.4 (#2, Aug 16 2007, 02:03:40) [GCC 4.1.3 20070812 (prerelease) (Debian 4.1.2-15)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import md5 >>> s = md5.new() >>> s.update('snagglefrob') >>> s.hexdigest() '9eb2459fcdd9f9b8a9fef7348bcac933' -- Ron Johnson, Jr. Jefferson LA USA %SYSTEM-F-FISH, my hovercraft is full of eels From nytrokiss at gmail.com Fri Nov 30 06:44:55 2007 From: nytrokiss at gmail.com (James Matthews) Date: Fri, 30 Nov 2007 12:44:55 +0100 Subject: Benchmark... In-Reply-To: <990f56470711300039k6aa625aexedec9c55dc4b0692@mail.gmail.com> References: <990f56470711300039k6aa625aexedec9c55dc4b0692@mail.gmail.com> Message-ID: <8a6b8e350711300344v5e32d19fn5f4a19d38133a234@mail.gmail.com> Google and wikipedia! On Nov 30, 2007 9:39 AM, ArShAm Shirvani wrote: > Hi > I need a benchmark for speed , comparing with other languages > > Regards > Arsham > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://search.goldwatches.com/?Search=Movado+Watches http://www.goldwatches.com http://www.jewelerslounge.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From fetchinson at googlemail.com Mon Nov 12 14:48:50 2007 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Mon, 12 Nov 2007 11:48:50 -0800 Subject: why there is no pythonscript insine web browsers? In-Reply-To: <4738966A.4070607@savaskarsitlari.org> References: <4738966A.4070607@savaskarsitlari.org> Message-ID: > I'm an old programmer coming from a cobol background and started to > learn python. I'm using javasript for web based applications but after I > started to learn python, the javascript language started to seem ugly to > me. Now I'm wondering why there is java support on web browsers but no > python support? there is even a vbscript support inside MS-IE but there > is no python support. it would be really nice and easy for me to use > python instead of javascript to write those ajax scripts. > > Please tell me, is there a python substitude for JRE ? Java has nothing to do with javascript. I guess you are really asking about javascript so let's forget about java. Having a full python runtime in a browser would be a really bad idea because imagine a website telling your browser to "import os ; os.unlink( 'your_secret_very_important_file' )". If you want to write your browser client code nevertheless in python you can use pypy [1] to translate it into javascript. This is also what I do and it works pretty well in conjunction with MochiKit [2]. HTH, Daniel [1] http://codespeak.net/pypy/dist/pypy/doc/news.html [2] http://mochikit.com From pavlovevidence at gmail.com Thu Nov 15 19:57:57 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 15 Nov 2007 16:57:57 -0800 (PST) Subject: Python Design Patterns - composition vs. inheritance References: Message-ID: <87600e6e-2409-4369-9ba2-bd231b010b46@n20g2000hsh.googlegroups.com> On Nov 15, 3:28 pm, "snewma... at gmail.com" wrote: > My response ended up being pretty long and heavy for a beginner, but you sound pretty smart. > In learning about design patterns, I've seen discussion about using > inheritance when an object's relationship to another object is 'is-a' > and composition when the relationship is 'has-a'. I've never been a big fan of this rule, for two reasons. First of all, "is a" and "has a" aren't always used in the sense intended by this rule's inventor. To illustrate the confusion, take your Pet-Owner example. When you say "A Pet has an Owner", the verb "to have" has the sense of "to possess". But possession alone is *not* the right sense of "to have" to suggest using containment. (Note: I'm using containment to mean "object X owns object Y". Referencing the object without owning it is not containment; it's just referencing.) The reciprocal relationship to "has a" is "is a part of", and I rather prefer that way of putting it. The Pet has an Owner, but the Owner is not part of the Pet, so "has a" is being used in the wrong sense. OTOH, a Car has an Engine, and an Engine is part of a Car, so "has a" is being used in the right sense there. This is not to say containment is not the appropriate way to implement Pet-Owner in any case. If this program is Pet-centric, and the Owner exists only insofar as it is perceived by the Pet, containment might be right way. That's another point: sometimes external circumstances play a part in whether inheritance or containment or something else should be used. FWIW, my first stab at a Pet-Owner relationship would probably look something like this: class Family: def __init__(self,humans,pets): self.humans = humans self.pets = pets Note that a Family has Pets, and Pets are part of the Family, so containment would be a good idea for Family-Pet relationship. (The Pets and Humans would have a field referring back to the Family, and the pet could determine its owners that way.) A source of confusion with "is a" is that it doesn't necessarily imply a good inheritance relationship (aka Liskov substitutability). Consider a Rectangle class that has methods set_width() and set_height(). Should Square class inherit from Rectangle? A Square is a Rectangle, but it's not suitable as a subclass of Rectangle, because the width and height can't be set independently. You can't substitute a Square for a Rectangle and get reasonable behavior. Second reason I don't like "is a" and "has a": They are misleading enough for concrete objects like Pets, Owners, Rectangles, and so on. But real programming is often done with abstract objects like SimulationContexts, EncryptedHTTPConnections, ItemSequencers, and FingerProtocols. "Is-a" and "has-a" relationships are not always clear for classes such as these. > Also, I've seen talk that ideally you shouldn't have too many "dots" > in your method calls, instead using delegates to the methods and > attributes. Can anyone elaborate on this? Ideally, should I be writing > getattr() methods so I can do pet.address instead of > pet.owner.address? Should I be doing the same with owner's methods > like I did with get_foo()? I wouldn't worry about minimizing dots. If you find yourself often using a certain long expressions like self.owner.house.yard.grass_length you might want to delegate them on a case-by-case basis by writing methods like this: def get_home_grass_length(self): return self.owner.house.yard.grass_length But using getattr to do it automatically is tricky, error prone, and defeats the purpose of keeping seperate namespaces. OTOH, if you find yourself delving several dots deep a lot, it suggests that you need to refactor you code. Move some of the code from the shallower classes into the deeper classes, closer to the data it needs. Hope this helped and didn't confuse you even more. :) Good luck learning. Carl Banks From horpner at yahoo.com Fri Nov 2 11:06:17 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Fri, 02 Nov 2007 15:06:17 GMT Subject: python newbie References: <472b2b84$0$13761$6e1ede2f@read.cnntp.org> Message-ID: On 2007-11-02, Jim Hendricks wrote: > New to python, programming in 15 or so langs for 24 years. > > Couple of questions the tuts I've looked at don't explain: > > 1) global vars - python sets scope to the block a var is > declared (1st set), I see the global keyword that allows access > to global vars in a function, what I'm not clear on is does > that global need to be declared in the global scope, or, when > 1st set in a function where it is listed as a global, does that > then declare the necessary global. Names that are assigned in an assignment statement are assumed to be defined in the current scope. Names that are assigned to in a function are considered local variables to that function. This allows them to be faster to access than other attributes or global variables (which are just attributes of a module). def foo(): x = 7 In function foo x is a local variable. This is true even if there is an x defined in foo's enclosing scope. x = 5 def foo(): x = 7 x is a local variable, which shadows the module scope (global) x. x = 5 If x is referenced, but not assigned to, then Python does not create a local variable for it, and normal lookup rules will cause x to be found in the enclosing scope of the bar function, below: def bar(): print x In bar, the x name refers to the global x. In order to inform Python that you would like to make modifications to a global variable in a function, you use the global statement to declare your intation. This overrides Python's assumption that that name is a local variable. x = 5 def foo2(): global x x = 7 > 2) Everything is an object. So then, why the distinction between > functions/variables and fields/methods. If a module is an object, would > not every function be a method of that module and every variable be a > field of that module? You are almost correct. Every identifier/name in Python is conceptually an attribute of an object. But identifiers in Python are not typed. It is the objects that they refer to that are typed. -- Neil Cerutti From R.Brodie at rl.ac.uk Thu Nov 1 13:21:02 2007 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Thu, 1 Nov 2007 17:21:02 -0000 Subject: serving html from a python script in IE References: <1193928739.157628.291110@50g2000hsm.googlegroups.com> <1193932276.785913.229010@v3g2000hsg.googlegroups.com> <1193936177.555739.168270@k35g2000prh.googlegroups.com> Message-ID: "bluegray" wrote in message news:1193936177.555739.168270 at k35g2000prh.googlegroups.com... > print "Content-Type: application/xhtml+xml That's your problem. You can't use that Mime type because IE doesn't support XHMTL. No "appendix C" hair splitting comments, please. From mail at microcorp.co.za Thu Nov 22 03:18:38 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 22 Nov 2007 10:18:38 +0200 Subject: eof References: <92a2c0c9-e6a1-4344-aeac-830940200f20@t47g2000hsc.googlegroups.com><79i9k35vs76cqgqnino7dj3ql623us3euq@4ax.com> <6c04c760-6cf1-4715-9ec9-30f43ebaa01f@d27g2000prf.googlegroups.com> Message-ID: <011001c82ce0$497722a0$03000080@hendrik> "braver" wrote: > Well folks compare scripting languages all the time, and surely Ruby > is closer to Python than C++. Since Ruby can do f.eof, which is > easily found in its references, and Python can't, or its EOF can't > easily be found -- the one *equivalent* to a semantically clear > Ruby's, or Pascal's IIRC, f.eof -- something's missing here... > > Why do I have to count sizes of lines read and compare it to some > filesize or do other weird tricks just to see, in a way not changing > my input stream, whether it's at the, well, EOF? The man has a valid point - In general, Python allows you, for an object f, to write: f.SomethingNew = 'Whatever the hell you like' However, when f is a builtin file object, it barfs on an AttributeError. So he can't even help himself by setting his own EOF attribute to False initially, and to True when he sees an empty string. Is there a reason for this Bondage style? - Hendrik From kyoguan at gmail.com Thu Nov 22 23:09:50 2007 From: kyoguan at gmail.com (kyo guan) Date: Fri, 23 Nov 2007 12:09:50 +0800 Subject: may be a bug in string.rstrip Message-ID: <004d01c82d86$b3c0e550$811ba8c0@kyom> Hi : Please look at this code: >>> 'exe.torrent'.rstrip('.torrent') 'ex' <----- it should be 'exe', why? but this is a right answer: >>> '120.exe'.rstrip('.exe') '120' <------ this is a right value. there is a bug in the rstrip, lstrip there isn't this problem. Kyo. From exarkun at divmod.com Tue Nov 6 12:41:21 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 6 Nov 2007 12:41:21 -0500 Subject: Insane crazy question - printing commands In-Reply-To: Message-ID: <20071106174121.8162.413817976.divmod.quotient.32421@ohm> On Tue, 06 Nov 2007 19:09:21 +0200, Donn Ingle wrote: >Hi, >I'm doing something odd with pycairo and friends and I want to see what >commands are coming out of my objects. > >Here's some code: > >class Box: > def draw() > self.context.set_source_rgb(1, 0, 0) > self.context.rectangle(0, 00, 50, 50) > self.context.fill() > >Box.draw() draws a red box, all fine. But, I *also* want it to output the >actual commands within the draw def to the console (or a file). See inspect.getsource(). Jean-Paul From mail at microcorp.co.za Sat Nov 3 02:36:24 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 3 Nov 2007 08:36:24 +0200 Subject: python newbie References: <472b2b84$0$13761$6e1ede2f@read.cnntp.org><5p0s6vFp47k9U1@mid.individual.net> <472b5251$0$6238$426a34cc@news.free.fr> Message-ID: <00b301c81de3$dafdb1a0$03000080@hendrik> "Bruno Desthuilliers" wrote: >functions are *not* methods of their module. Now I am confused - if I write: result = foo.bar(param) Then if foo is a class, we probably all agree that bar is a method of foo. But the same syntax would work if I had imported some module as foo. So what's the difference ? Why can't bar be called a method of foo, or is it merely a convention that classes have methods and modules have functions? Note that I am purposely refraining from mentioning a module that has a class that has a method. - Hendrik From tommy.nordgren at comhem.se Fri Nov 2 08:14:16 2007 From: tommy.nordgren at comhem.se (Tommy Nordgren) Date: Fri, 2 Nov 2007 13:14:16 +0100 Subject: (MAC) CoreGraphics module??? In-Reply-To: <22uki39arp3a83topaimrka4s37uo1okm5@4ax.com> References: <22uki39arp3a83topaimrka4s37uo1okm5@4ax.com> Message-ID: <1C9468D5-5077-4525-986A-5520FA0285FC@comhem.se> On 2 nov 2007, at 02.10, David C. Ullrich wrote: > Running OS X 10.4 "Tiger". Various references > by Apple and others say that there exists a > module that gives Quartz bindings, allowing > all sort of graphics things in Python. > > Sure enough, after installing Xcode I have > some sample scripts. They all start with > > from CoreGraphics import * > > (as do all the examples in two books, both > of which say they're talking about Tiger.) > > I get an ImportError trying to import CoreGraphics. > I found a CoreGraphics.py in a folder named Carbon; > when I change the script to read > > import Carbon > from Carbon.CoreGraphics import * > > there's no import error, but all of the Quartz > things are NameErrors. I look at CoreGraphics.py, > it's just about twenty lines long, defining a few > constants with Quartz-sounding names. > > What gives? I'm supposed to do something else? > Someone accidentally deleted all the code from > my CoreGraphics.py? (Is there a working > CoreGraphics.py around somewhere? I found a > file somewhere on the net that was the same > as mine except it ended with > > from CG import * > > Adding that doesn't change anything.) > > (Yes, the XCode installation seems to be working > fine.) > > ??? > > ************************ > > David C. Ullrich > -- > http://mail.python.org/mailman/listinfo/python-list There are Python wrappers for the Cocoa API. These can be used with binaries from Python.org. The name of the module is PyObjC, and can be downloaded from sourceforge. There are binary builds for Python up to version 2.4.1. For Python 2.5.1, it is necessary to build it yourself, which I've found out requires modifying setup.py. (The problem is that setup.py tries to use two modules that's not installed by default on Tiger) ------ What is a woman that you forsake her, and the hearth fire and the home acre, to go with the old grey Widow Maker. --Kipling, harp song of the Dane women Tommy Nordgren tommy.nordgren at comhem.se From ihatespam at hotmail.com Tue Nov 27 10:48:42 2007 From: ihatespam at hotmail.com (Just Another Victim of the Ambient Morality) Date: Tue, 27 Nov 2007 15:48:42 GMT Subject: A bug in Python's regular expression engine? Message-ID: This won't compile for me: regex = re.compile('(.*\\).*') I get the error: sre_constants.error: unbalanced parenthesis I'm running Python 2.5 on WinXP. I've tried this expression with another RE engine in another language and it works just fine which leads me to believe the problem is Python. Can anyone confirm or deny this bug? Thank you... From koutoo at hotmail.com Mon Nov 19 13:48:00 2007 From: koutoo at hotmail.com (koutoo at hotmail.com) Date: Mon, 19 Nov 2007 10:48:00 -0800 (PST) Subject: display messages in python shell Message-ID: Is it possible to display messages in the python shell? I want to display error messages based on parameters in my scripts to the users. Is there another way to display messages other than log files? Thanks. Kou From brenNOSPAMbarn at NObrenSPAMbarn.net Tue Nov 20 02:22:46 2007 From: brenNOSPAMbarn at NObrenSPAMbarn.net (OKB (not okblacke)) Date: Tue, 20 Nov 2007 07:22:46 GMT Subject: Variable-width lookbehind References: Message-ID: Tim Roberts wrote: > "OKB (not okblacke)" wrote: >> >> For years now Python has not supported variable-length >> lookbehinds. >>I'm just curious whether there are any plans to change this in >>Python 3.0, or before, or after. It seems that Perl 6 will allow >>variable- width lookbehinds (see >>http://dev.perl.org/perl6/doc/design/apo/A05.html and >>http://dev.perl.org/perl6/rfc/72.html ). > > If I may be just a bit catty, your last sentence may actually be > the best reason NOT to include it in Python 3.0. Perl 6 has become > a worthy successor to ALGOL 68 and PL/I. They are attempting to > pack in every feature that has ever been requested by every person > in the known universe. That's as may be, but if I may be a bit redundant with myself, I'd like to reiterate that I don't see this is as a new "feature". Regular expressions already exist in Python. Lookbehinds already exist in Python regular expressions. The only thing that doesn't exist is the ability to use arbitrary regular expressions in lookbehinds, and my understanding is that this is just because regular expression engines have typically been implemented in a way that makes this hard to add on. In other words, what I'm describing isn't an extension of what regular expressions are, it's just the lifting of a bothersome implementation- based restriction on one aspect of their use. -- --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 exarkun at divmod.com Fri Nov 16 13:09:10 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Fri, 16 Nov 2007 13:09:10 -0500 Subject: Using python as primary language In-Reply-To: <1195061104.922452.11560@22g2000hsm.googlegroups.com> Message-ID: <20071116180910.8162.861660763.divmod.quotient.36631@ohm> On Wed, 14 Nov 2007 09:25:04 -0800, sturlamolden wrote: > [snip] >I think the need for these "eventloop unifications" stems from Visual >Basic. VB programmers never learned to use more than one thread, and >they are still struggling to unlearn the bad habits they aquired. > +1 QOTW Jean-Paul From steven.bethard at gmail.com Thu Nov 8 11:51:29 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 08 Nov 2007 09:51:29 -0700 Subject: How to output newline or carriage return with optparse In-Reply-To: References: <1194538920.777563.156260@v23g2000prn.googlegroups.com> Message-ID: Tim Chase wrote: > ASIDE: I've started refactoring this bit out in my local source...how > would I go about contributing it back to the Python code-base? I didn't > get any feedback from posting to the Optik site. You can post a patch to bugs.python.org, but it will probably just get forwarded to the optik site because the optparse module is supposed to be automatically generated from the current optik release. My impression is that optik is mostly unmaintained, which makes getting patches applied to optik difficult... STeVe P.S. FWIW, I think it would be great to get your patch in -- this feature is requested all the time. From cai.haibin at gmail.com Tue Nov 20 20:42:08 2007 From: cai.haibin at gmail.com (james_027) Date: Tue, 20 Nov 2007 17:42:08 -0800 (PST) Subject: sorting a list of list Message-ID: <1d1d0685-08d2-45ec-b721-e73c1dfea2f4@e25g2000prg.googlegroups.com> hi, are there available library or pythonic algorithm for sorting a list of list depending on the index of the list inside the list of my choice? d_list = [ ['a', 1, 9], ['b', 2, 8], ['c', 3, 7], ['d', 4, 6], ['e', 5, 5], ] Thanks james From gagsl-py2 at yahoo.com.ar Fri Nov 9 20:36:35 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 09 Nov 2007 22:36:35 -0300 Subject: private data stashed in local/global execution context of PyEval_EvalCode disappears down the execution stack References: <1194402317.678614.142450@y42g2000hsy.googlegroups.com> Message-ID: En Tue, 06 Nov 2007 23:25:17 -0300, escribi?: > i naively created execution context: > PyObject *execcontext = PyDict_New(); > stuffed a handle in it: > PyObject *ih = PyCObject_FromVoidPtr(handle, NULL); > int st= PyDict_SetItemString(res, "interp", ih); What's `res`? One should make a lot of assumptions about your code because it's not complete. Please post a minimal complete example showing your problem. -- Gabriel Genellina From pablo.yabo at gmail.com Sat Nov 3 17:58:06 2007 From: pablo.yabo at gmail.com (Pablo Yabo) Date: Sat, 3 Nov 2007 18:58:06 -0300 Subject: Thread structures BUG? Message-ID: Hello, I create lots of threads that run a script and I have a problem when a thread is created with the same threadId that existed before. When a new thread is started I use this code to enter the interpreter: // create a thread state object for this thread PyEval_AcquireLock(); threadState = PyThreadState_New(mainInterpreterState); PyThreadState_Swap(threadState); and when the thread finishes: PyThreadState_Swap(NULL); PyThreadState_Clear(info); // delete my thread state object PyThreadState_Delete(info); PyEval_ReleaseLock(); Everything works smoothly until a thread id is re-used. I've been testing what is happening and the problem is that PyGILState_GetThisThreadState() returns a PyThreadState for the reused thread id. I changed my code to call PyGILState_GetThisThreadState() before creating the PyThreadState. But if I try to use the returned PyThreadState (that shouldn't exist because I've already deleted) I got an error when trying to access the interpreter dictionary. The workaround that I found is to keep all PyThreadState structures without calling PyThreadState_Clear / PyThreadState_Delete. When a new thread is created I call PyGILState_GetThisThreadState(). If it returns something I reuse the structure. In this way, my code works. Thanks, Pablo Yabo -- http://www.nektra.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Fri Nov 23 09:20:38 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 23 Nov 2007 15:20:38 +0100 Subject: foldr function in Python References: <9bf5a2bb-eac7-4859-a5de-b1e84573c77a@t47g2000hsc.googlegroups.com> <0d8c76de-3510-4711-959a-34aad4a33acd@r60g2000hsc.googlegroups.com> <13kdcaar4048329@corp.supernews.com> <1b539321-8112-4e94-9fee-5be922660065@n20g2000hsh.googlegroups.com> Message-ID: Ant wrote: > On Nov 23, 10:54 am, Steven D'Aprano cybersource.com.au> wrote: > ... >> Alas and alack, I believe that Guido has a distaste for all but the >> simplest functional idioms, and an irrational belief that anything using >> reduce() must be too complex to bear. reduce() is going away, not just >> from the built-ins but (I believe) from the standard library as well. I believe I've spotted an irrational belief in an irrational belief of the BDFL here ;) > I thought that at the last count it was merely being moved out into > functools (or somewhere similar). reduce() is indeed in the functools -- added by Guido van Rossum himself. Peter From mobiledreamers at gmail.com Sun Nov 25 19:08:16 2007 From: mobiledreamers at gmail.com (mobiledreamers at gmail.com) Date: Sun, 25 Nov 2007 16:08:16 -0800 Subject: image rendering in python Message-ID: http://cdnll.i.imagechef.com/ic/templimg2/Shaved%20Head.jpg Do u know how to make such images using PIL or other tools in python thanks a lot for your kind help -------------- next part -------------- An HTML attachment was scrubbed... URL: From brenNOSPAMbarn at NObrenSPAMbarn.net Sat Nov 17 20:39:39 2007 From: brenNOSPAMbarn at NObrenSPAMbarn.net (OKB (not okblacke)) Date: Sun, 18 Nov 2007 01:39:39 GMT Subject: Variable-width lookbehind References: <7xve8031ya.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > "OKB (not okblacke)" writes: >> For years now Python has not supported variable-length >> lookbehinds. > > I'm not sure what that is and the perl links you gave don't work, > but it sounds evil. The links work fine for me. . . You're not sure what "variable-length lookbehinds" means? Lookbehind is something that Python regexps already have. You can do "(?<=one)two" to match "two" only if it's preceded by "one", and you can do "(? QOTW: "I think the need for these 'eventloop unifications' stems from Visual Basic. VB programmers never learned to use more than one thread, and they are still struggling to unlearn the bad habits they aquired." - sturlamolden http://groups.google.com/group/comp.lang.python/msg/41d29242b2a825de "XML. Almost as good as plain text for grepping." - Joe Mason Tips for loading data into MySQL efficiently: http://groups.google.com/group/comp.lang.python/browse_thread/thread/2afd4dbd7cc5ce/ A misunderstanding on how Python threads and the GIL work leads to a good explanation by Chris Mellon: http://groups.google.com/group/comp.lang.python/browse_thread/thread/80f6e2e33b633c50/ Thoughts about composition / inheritance and when to use them in Python: http://groups.google.com/group/comp.lang.python/browse_thread/thread/1b0fe5e45ea6a636/ Comparison: the effort of migrating two web apps to a new server, Python/Django vs. C#/ASP.net: http://groups.google.com/group/comp.lang.python/browse_thread/thread/ffb00f1a5837fec5/ There appears to be an issue with dictionaries being extremely slow on 64bits multiprocessor systems only: http://groups.google.com/group/comp.lang.python/browse_thread/thread/77e5d747c4a727cb/ Python 3000 featured on a futuristic novel ("Halting State", by Charles Stross): http://groups.google.com/group/comp.lang.python/browse_thread/thread/b97233c2a33b2e28/ ======================================================================== 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. Just beginning with Python? This page is a great place to start: http://wiki.python.org/moin/BeginnersGuide/Programmers The Python Papers aims to publish "the efforts of Python enthusiats": http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the "Planet" sites: http://planetpython.org http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/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 continues the marvelous tradition early borne by Andrew Kuchling, Michael Hudson, Brett Cannon, Tony Meyer, and Tim Lesher 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 Many Python conferences around the world are in preparation. Watch this space for links to them. 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-- Phaseit, Inc. (http://phaseit.net) is pleased to participate in and sponsor the "Python-URL!" project. Watch this space for upcoming news about posting archives. From Scott.Daniels at Acm.Org Tue Nov 13 22:25:06 2007 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 13 Nov 2007 19:25:06 -0800 Subject: referencing a subhash for generalized ngram counting In-Reply-To: <1194969728.877025.255860@v23g2000prn.googlegroups.com> References: <1194969728.877025.255860@v23g2000prn.googlegroups.com> Message-ID: <13jkqevf9f68hc1@corp.supernews.com> braver wrote: > ... > The real-life motivation for this is n-gram counting. Say you want to > maintain a hash for bigrams. For each two subsequent words a, b in a > text, you do > bigram_count[a][b] += 1 This application is easily handed with tuples as keys. bigrams = {} src = iter(source) lag = src.next() for current in src: bigrams[lag, current] = bigrams.get((lag, current), 0) + 1 lag = current But if you really want nested: bigrams = {} src = iter(source) lag = src.next() for current in src: count = bigrams.setdefault(lag, {}).get(current, 0) bigrams[lag][current] = count + 1 lag = current -Scott David Daniels Scott.Daniels at Acm.Org From bedouglas at earthlink.net Tue Nov 6 16:43:10 2007 From: bedouglas at earthlink.net (bruce) Date: Tue, 6 Nov 2007 13:43:10 -0800 Subject: Parallel Python environments.. In-Reply-To: Message-ID: <113201c820be$070aea10$0301a8c0@tmesa.com> thorsten... if i have python 2.4.3 installed, it gets placed in the python2.4 dir.. if i don't do anything different, and install python 2.4.2, it too will get placed in the python2.4 tree... which is not what i want. i'm running rhel4/5... so.. i still need to know what to do/change in order to be able to run multiple versions of python, and to switch back/forth between the versions. 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 Thorsten Kampe Sent: Tuesday, November 06, 2007 8:19 AM To: python-list at python.org Subject: Re: Parallel Python environments.. * bruce (Tue, 6 Nov 2007 07:13:43 -0800) > If I wanted to be able to build/test/use parallel python versions, what > would I need to do/set (paths/libs/etc...) nothing > and where would I need to place the 2nd python version, so as not to > screw up my initial python dev env. Anywhere you like (probably ~/bin would be best) > Any sites/pointers describing the process would be helpuful. In particular, > any changfes to the bashrc/profile/etc... files to allow me to accomplish > this would be helpful. Nothing like that. Just change the shebang. Thorsten -- http://mail.python.org/mailman/listinfo/python-list From python.list at tim.thechases.com Thu Nov 8 12:15:41 2007 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 08 Nov 2007 11:15:41 -0600 Subject: How to output newline or carriage return with optparse In-Reply-To: References: <1194538920.777563.156260@v23g2000prn.googlegroups.com> Message-ID: <4733443D.7030403@tim.thechases.com> >> ASIDE: I've started refactoring this bit out in my local >> source...how would I go about contributing it back to the >> Python code-base? I didn't get any feedback from posting to >> the Optik site. > > You can post a patch to bugs.python.org, but it will probably > just get forwarded to the optik site because the optparse > module is supposed to be automatically generated from the > current optik release. My impression is that optik is mostly > unmaintained, which makes getting patches applied to optik > difficult... What sorts of things are required? Just a patch? Or do I also need to include some sort of collection of doctest/unittests or documentation patches (and if so, against which documentation source)? -tkc From hniksic at xemacs.org Mon Nov 26 04:49:46 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Mon, 26 Nov 2007 10:49:46 +0100 Subject: How to Teach Python "Variables" References: <4749bb94$1@news.bezeqint.net> <5qvf6pF122r3mU1@mid.individual.net> Message-ID: <87abp1qqth.fsf@mulj.homelinux.net> greg writes: > none wrote: >> IIRC, I once saw an explanation how Python doesn't have >> "variables" in the sense that, say, C does, and instead has bindings >> from names to objects. > > If you're talking to C programmers, just tell them that Python > variables always contain pointers. That should give them the right > mental model to build on. That is a convenient shortcut when it works, but in my experience it tends to confuse the issue. The reason is that one of the main uses of pointers in C is implementing pass-by-reference. A C programmer told that Python variables internally hold pointers expects this code: def func(a): a = 10 ... func(x) to change the value of x. From http Fri Nov 9 06:02:34 2007 From: http (Paul Rubin) Date: 09 Nov 2007 03:02:34 -0800 Subject: parallel csv-file processing References: <1194605470.380185.111520@19g2000hsx.googlegroups.com> Message-ID: <7xve8b65rp.fsf@ruckus.brouhaha.com> Michel Albert writes: > buffer = [] > for line in reader: > buffer.append(line) > if len(buffer) == 1000: > f = job_server.submit(calc_scores, buffer) > buffer = [] > > f = job_server.submit(calc_scores, buffer) > buffer = [] > > but would this not kill my memory if I start loading bigger slices > into the "buffer" variable? Why not pass the disk offsets to the job server (untested): n = 1000 for i,_ in enumerate(reader): if i % n == 0: job_server.submit(calc_scores, reader.tell(), n) the remote process seeks to the appropriate place and processes n lines starting from there. From timr at probo.com Mon Nov 5 23:20:17 2007 From: timr at probo.com (Tim Roberts) Date: Tue, 06 Nov 2007 04:20:17 GMT Subject: python at command prompt References: <1193933820.086265.19100@57g2000hsv.googlegroups.com> <9nupi3lula431c9ee9svvtkib5igjfvalf@4ax.com> <98jti39b8uv4cs3ghct5l5jareoerhcphd@4ax.com> Message-ID: Ton van Vliet wrote: > >There are executables (.exe) that have a 'registering' option builtin, >and need to be registered to have their capabilities made available >using the /regserver switch (possibly related to OLE/COM services, but >I'm not an expert here ;-) Yes, that's strictly for COM. And the "App Paths" registry key you mentioned is only for Explorer things, like the Start menu's "Run" box. It doesn't apply to the command line. Try typing "wordpad" in a cmd shell, then try it in Start -> Run. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From landa.martin at gmail.com Tue Nov 27 16:35:42 2007 From: landa.martin at gmail.com (Martin Landa) Date: Tue, 27 Nov 2007 13:35:42 -0800 (PST) Subject: string conversion latin2 to ascii Message-ID: Hi all, sorry for a newbie question. I have unicode string (or better say latin2 encoding) containing non-ascii characters, e.g. s = "Uk?zka_mo?nosti_vyu?it?_programu_OpenJUMP_v_SOA" I would like to convert this string to plain ascii (using some lookup table for latin2) to get -> Ukazka_moznosti_vyuziti_programu_OpenJUMP_v_SOA Thanks for any hits! Regards, Martin Landa From zhushenli at gmail.com Mon Nov 12 04:07:37 2007 From: zhushenli at gmail.com (Davy) Date: Mon, 12 Nov 2007 09:07:37 -0000 Subject: How to get a set of keys with largest values? Message-ID: <1194858457.677637.90530@i13g2000prf.googlegroups.com> Hi all, I have a dictionary with n elements, and I want to get the m(m<=n) keys with the largest values. For example, I have dic that includes n=4 elements, I want m=2 keys have the largest values) dic = {0:4,3:1,5:2,7:8} So, the the largest values are [8,4], so the keys are [7,0]. Is there any fast way to implement this algorithm? Any suggestions are welcome! Best regards, Davy From tasjaevan at gmail.com Fri Nov 2 12:50:27 2007 From: tasjaevan at gmail.com (tasjaevan at gmail.com) Date: Fri, 02 Nov 2007 09:50:27 -0700 Subject: python newbie In-Reply-To: <472b43f8$0$13761$6e1ede2f@read.cnntp.org> References: <472b2b84$0$13761$6e1ede2f@read.cnntp.org> <5p0s6vFp47k9U1@mid.individual.net> <472b43f8$0$13761$6e1ede2f@read.cnntp.org> Message-ID: <1194022227.306650.188570@o38g2000hse.googlegroups.com> On Nov 2, 3:35 pm, Jim Hendricks wrote: > > This sounds like an issue of terminology. I understand that I don't > declare variables like I would in C or Java, but that they are > implicitly declared via the first assignment. And the define objects > and bind a name to them makes no sense to me. I can only assume that if > I say: my_file = open( ... the "techy" explaination is that the open > function defines a file object and binds the name my_file to it. To me, > it's easier to say that the open function creates a file object and > assigns a reference to the my_file variable. If my_file does not exist, > it is created, if my_file does exist, prior to the assignment, the type > of my_file is checked to ensure type safety. > Objects have types, names (what you're calling variables) don't. my_file = open ... binds the name 'my_file' to a file object. A subsequent my_file = 7 will bind the name 'my_file' to an int object. No type-checking involved (but neither is there any loss of type safety). James From martin at v.loewis.de Mon Nov 19 22:22:02 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 20 Nov 2007 04:22:02 +0100 Subject: compiling python 2.5, missing zlib In-Reply-To: <693e08b5-2911-4c9c-a00f-f7b6ceae66a3@e4g2000hsg.googlegroups.com> References: <4741FDDF.8070505@v.loewis.de> <693e08b5-2911-4c9c-a00f-f7b6ceae66a3@e4g2000hsg.googlegroups.com> Message-ID: <474252DA.1040308@v.loewis.de> > Those headers are already installed, according to "up2date". Is there > a way to specify the header files used? It will automatically use them if they are good. What's the value of ZLIB_VERSION in /usr/include/zlib.h? Regards, Martin From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Nov 15 08:42:52 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 15 Nov 2007 14:42:52 +0100 Subject: how to figure out if python was used as a cgi script References: <8bb2fd14-38c5-46c6-94fe-40174a734ebc@e23g2000prf.googlegroups.com> Message-ID: <5q30msFtcpkkU1@mid.individual.net> ce wrote: > is there a way to figure out which scripting language was used in > a cgi. I used to watch extensions (i.e. py, pl, asp or php) I'd say that ASP and PHP are rather rarely used for CGI scripts. Also, extensions are essentially meaningless. > nowadays i hardly see any extensions and really it is hard to find > out anything from the generated HTML or even the HTML being sent > out through the FORM tag .. is there another way to find out which > scripting language was used in website!!! Since this is a Python NG I suspect you have something you'd like to achieve using Python regarding this topic. What is it? > -------------------------------- > Sorry I couldn't resist > -------------------------------- ? Regards, Bj?rn -- BOFH excuse #413: Cow-tippers tipped a cow onto the server. From pieter.cogghe at gmail.com Thu Nov 29 11:10:26 2007 From: pieter.cogghe at gmail.com (pieter.cogghe at gmail.com) Date: Thu, 29 Nov 2007 08:10:26 -0800 (PST) Subject: PIL image.filter -> boundaries Message-ID: <867bc66b-d106-4493-8642-9eaaa78a12f2@s19g2000prg.googlegroups.com> Hi, I'm filtering an image with a custom kernel. It works fine, except for the boundaries. image.filter() seems to add a 1px zero-border to the image to process the pixels at the boundaries of the image.I'd rather have it replicate the values of the boundary pixels. Is this an option and where can I set it? thanks, Pieter ps, the code: img = Image.open('cell.tif') kernelX = ImageFilter.Kernel(size=(3,3),kernel=[1,0,-1,2,0,-2,1,0,-1],scale=8) gradientX = im.filter(kernelX) From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Nov 2 10:57:34 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 02 Nov 2007 15:57:34 +0100 Subject: python newbie References: <472b2b84$0$13761$6e1ede2f@read.cnntp.org> Message-ID: <5p0s6vFp47k9U1@mid.individual.net> Please use a more informative subject next time. Jim Hendricks wrote: > 1) global vars - python sets scope to the block a var is declared > (1st set), http://docs.python.org/ref/global.html I'm afraid not. Python only interprets the listed name(s) as globals. > I see the global keyword that allows access to global vars in a > function, what I'm not clear on is does that global need to be > declared in the global scope, You can't just declare in Python, you always define objects (and bind a name to them). Yes, globals need to be defined before you can access them using "global". > 2) Everything is an object. So then, why the distinction between > functions/variables and fields/methods. Because they are different things to achieve different goals. One holds data, the other does stuff. But nonetheless, both a function and a string literal have their own set of methods. You can look at them using "dir", a function to show attributes (the pythonic word for fields/methods) of objects. >>> def test(): ... print "test" ... >>> dir(test) ['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__get__', '__getattribute__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name'] >>> dir("honk") ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__str__', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] >>> > If a module is an object, would not every function be a method of > that module and every variable be a field of that module? They are. BTW, don't confuse "class" and "object". Classes also are objects. >>> import os >>> dir (os) [[...], '__all__', '__builtins__', '__doc__', '__file__', '__name__', '_copy_reg', '_execvpe', '_exists', '_exit', '_get_exports_list', '_make_stat_result', '_make_statvfs_result', '_pickle_stat_result', '_pickle_statvfs_result', '_spawnvef', 'abort', 'access', 'altsep', 'chdir', 'chmod', 'chown', 'chroot', 'close', 'confstr', 'confstr_names', 'ctermid', 'curdir', 'defpath', 'devnull', 'dup', 'dup2', 'environ', 'error', 'execl', 'execle', 'execlp', 'execlpe', 'execv', 'execve', 'execvp', 'execvpe', 'extsep', 'fchdir', 'fdatasync', 'fdopen', 'fork', 'forkpty', 'fpathconf', 'fstat', 'fstatvfs', 'fsync', 'ftruncate', [...]] >>> Regards, Bj?rn -- BOFH excuse #205: Quantum dynamics are affecting the transistors From HWang at ciber.com Mon Nov 26 16:04:02 2007 From: HWang at ciber.com (Wang, Harry) Date: Mon, 26 Nov 2007 14:04:02 -0700 Subject: gnosis XML objectify Message-ID: <8FFDEE1FC17DFB4BAF050331C185449FD38006@srv-corp-exmb4.ciber.cbr.inc> Problem solved. I left out a right closing tag (">") in the XML, but I am having another problem. Harry C. Wang Sr. Test Engineer (Automation) AOL Mobile Phone 206 - 268 - 7502 temporary e-mail: hwang at ciber.com Personal e-mail: hcwang at comcast.net From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sat Nov 24 18:02:02 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sun, 25 Nov 2007 00:02:02 +0100 Subject: How can I create customized classes that have similar properties as 'str'? References: <67954d23-9400-4ac9-ba45-bec04fab51a2@s6g2000prc.googlegroups.com> <5qqei9F11703eU1@mid.individual.net> <13kh8rqfdca9j73@corp.supernews.com> Message-ID: <5qroraFtu9ueU1@mid.individual.net> Steven D'Aprano wrote: > No advantage? That's for sure. There is no is_ attribute of > generic classes, and even if there was, it would have no special > meaning. Argl, I confused the operator module's attributes with objects ;) Regards, Bj?rn -- BOFH excuse #378: Operators killed by year 2000 bug bite. From kay.schluehr at gmx.net Sat Nov 3 04:32:23 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sat, 03 Nov 2007 01:32:23 -0700 Subject: Is pyparsing really a recursive descent parser? In-Reply-To: References: <5p0dhgFnj4rbU1@mid.uni-berlin.de> <1194007658.200713.178210@57g2000hsv.googlegroups.com> Message-ID: <1194078743.125127.93410@v3g2000hsg.googlegroups.com> On Nov 3, 6:33 am, "Just Another Victim of the Ambient Morality" wrote: > "Paul McGuire" wrote in message > > news:1194007658.200713.178210 at 57g2000hsv.googlegroups.com... > > > > > On Nov 2, 5:47 am, Marc 'BlackJack' Rintsch wrote: > > >> Pyparsing is no recursive descent parser. It doesn't go back in the > >> input > >> stream. The ``OneOrMore(Word(alphas))`` part "eats" the 'end' and when > >> it > >> can't get more, the parser moves to the ``Literal('end')`` part which > >> fails because the 'end' is already gone. > > >> > Is there a way to get pyparsing to parse a grammar like this? > > >> Negative lookahead maybe: > > >> grammar = (OneOrMore(NotAny(Literal('end')) + Word(alphas)) > >> + Literal('end')) > > >> Ciao, > >> Marc 'BlackJack' Rintsch- Hide quoted text - > > >> - Show quoted text - > > > Well I'll be darned! All this time, I thought "recursive descent" > > described the recursive behavior of the parser, which pyparsing > > definitely has. I never knew that backing up in the face of parse > > mismatches was a required part of the picture. > > It has recursion in it but that's not sufficient to call it a recursive > descent parser any more than having a recursive implementation of the > factorial function. The important part is what it recurses through... > > > > > In pyparsing, each construction gets composed from more fine-grained > > constructions, and they are called recursively to match or not match > > against the input string. > > > For example, taking your working parser example: > > > grammar = (OneOrMore(NotAny(Literal('end')) + Word(alphas)) > > + Literal('end')) > > > This creates the following data structure: > > > - And > > - OneOrMore > > - And > > - NotAny > > - Literal('end') > > - Word(alphas) > > - Literal('end') > > > Every instance in this structure derives from the base class > > ParserElement, which defines a method parse(). parse() in turn calls > > preParse(), parseImpl(), and postParse(). If parseImpl succeeds, it > > returns a ParseResults object and the next location within the input > > string to continue parsing. > > > The parseImpl methods are most often overridden in the subclasses (a > > few override postParse as well), such as: > > - And.parseImpl invokes parse() (note the recursion) on each of the > > expressions in its list. All must succeed or And.parseImpl throws an > > exception. > > - OneOrMore.parseImpl invokes parse() on its contained expression, > > which must succeed at least once; if not, the exception is rethrown. > > If the contained expression succeeds once, then its parse() method is > > called again and again until it fails, but no exceptions are rethrown, > > since only one match was actually required. > > - NotAny inverts the success/failure of its contained expression. If > > the expression's parse() method succeeds, NotAny.parseImpl throws an > > exception. If the contained expression's parse() method throws an > > exception, NotAny returns successfully. (NotAny does not advance the > > parse location, nor does it return any tokens.) > > - Literal and Word are terminals, in that they do not invoke any other > > expression's parse() method. Literal.parseImpl tests whether its > > string exists at the current parse location, and throws an exception > > if it doesn't. Word.parseImpl tests whether the current parse > > location contains a letter in the Word instance's set of valid initial > > characters - if so success; if not, throws an exception. It then > > advances through the input string, matching characters in the Word > > instance's set of valid body characters. The entire matched string is > > then returned, along with an updated string index at which to continue > > parsing. > > Thank you for the detailed description of pyparsing's implementation. > > > In my concept of "recursive descent" parsing, I was under the > > impression that pyparsing's use of this data structure, and > > *recursive* calls of parse() as it *descends* through the data > > structure, constituted a recursive descent parser. What the OP > > requested was a more regular expression-ish matcher, with backup (or > > backtracking). > > In my concept of "recursive descent" parsing, I was under the impression > that one should recurse through all rule combinations to ensure that the > grammar is fully applied. As I have mentioned before, merely having > recursion in your algorithm is insufficient. What you recurse through is > key. pyparsing recurses through rules but what's important is to recurse > through rule combinations. I think the confusing aspect of pyparsing for someone like me coming from an (E)BNF and formal language background is that scanning and parsing are merged into one. pyparsing is scannerless and where a tokenizer such as Pythons performs a longest match tokenization but interprets CFGs correctly ( in the bounds of the parsers power ) one has to disambiguate grammars in pyparsing where you expect a CFG to be established. Note that I don't like pyparsings approach and it is clearly not for everyone. I rather tend to make the experience that token definitions can be reused across different languages. I count 65 token for Python and I added 10 token for an experimental C++ parser and deactivated some others. The distance between both languages on a lexical level is not that huge. What pyparsing has been established in the Python community is something different IMO: readable and verbose pattern matching syntax which is not regexp line noise. Around 8 years ago when I started using Python I found a little module called reverb.py. It was actually nothing but a front end for regular expressions. It didn't make any career but I think it is the only one survived the anagrammatical release hopping from 1.5.2 to 2.5.1 in my own case: from reverb import* >>> p = required(required(alphanum)+whitespace)+text("end") >>> p >>> RE(p).pattern '(?:\\w+\\s)+end' From steve at REMOVE-THIS-cybersource.com.au Tue Nov 6 11:00:15 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Tue, 06 Nov 2007 16:00:15 -0000 Subject: How to use list as key of dictionary? References: <1194332021.595511.67370@v29g2000prd.googlegroups.com> <1194332941.190425.21090@i38g2000prf.googlegroups.com> <1194339027.038844.22200@v23g2000prn.googlegroups.com> <47303809$0$16661$9b4e6d93@newsspool3.arcor-online.net> <13j0hvbrnnt5ed1@corp.supernews.com> Message-ID: <13j13sfc0jfdf2b@corp.supernews.com> On Tue, 06 Nov 2007 11:25:29 +0000, Duncan Booth wrote: > Steven D'Aprano wrote: > > > >> Not quite, because that will also convert strings to tuples, which may >> not be what you want for a general solution. > > I take it you didn't actually try the original code then. No I didn't. > Converting strings to tuples is not something it did. Ah yes, you're right. The old "single characters are sequences too" gotcha bites again. >> That works for all data types I've tried, and it insures that the keys >> it makes from different types are distinguishable: >> >> e.g. >> >> make_dict_key([(1, 2), (3, 4)]) != make_dict_key({1: 2, 3: 4}) > > Really? It seems to me to be quite easy to get a clash: > >>>> make_dict_key([]) > (,) >>>> make_dict_key((list,)) > (,) I should have said "tries to insure". It isn't strictly possible to avoid all clashes, even in principle. For any mutable object M, if make_dict_key (M) returns a key K, then make_dict_key(K) will also return K. However, the clashes are for unusual containers with a type as the first element, instead of "usual" containers containing lists, tuples, strings, etc. Unless you deal with tuples with the first item being a type, you shouldn't come across any clashes. Also: nice work on supporting recursive data structures, thanks. -- Steven. From siasookhteh at gmail.com Thu Nov 29 16:18:02 2007 From: siasookhteh at gmail.com (Siah) Date: Thu, 29 Nov 2007 13:18:02 -0800 (PST) Subject: How to Split a String References: <0b724d25-24ea-41ba-b084-a8d59a9558b8@w40g2000hsb.googlegroups.com> <5iF3j.187077$U01.1250481@twister1.libero.it> <13kuaflbo02dg8d@corp.supernews.com> <13kuan6ah7g1n4d@corp.supernews.com> Message-ID: <86759b1b-4539-421a-a3d1-f2d226927ab3@j20g2000hsi.googlegroups.com> Thanks Mr. Edwards, I went ahead and started using the csv reader. Sia From MonkeeSage at gmail.com Fri Nov 23 22:17:35 2007 From: MonkeeSage at gmail.com (MonkeeSage) Date: Fri, 23 Nov 2007 19:17:35 -0800 (PST) Subject: foldr function in Python References: <9bf5a2bb-eac7-4859-a5de-b1e84573c77a@t47g2000hsc.googlegroups.com> <0d8c76de-3510-4711-959a-34aad4a33acd@r60g2000hsc.googlegroups.com> <5qnkuqF10t5hgU2@mid.uni-berlin.de> <5qpbv9F10sforU1@mid.individual.net> <3f197da0-67db-4b30-bf02-4703234fd3b2@g30g2000hsb.googlegroups.com> Message-ID: On Nov 23, 8:56 pm, MonkeeSage wrote: > This doesn't matter for non-associative functions > like "+", but it does for associative functions like "-". Err...that's backwards...should have been: This doesn't matter for associative functions like "+", but it does for non-associative functions like "-". From vinay_sajip at yahoo.co.uk Thu Nov 22 00:44:36 2007 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Wed, 21 Nov 2007 21:44:36 -0800 (PST) Subject: logging and propagation References: <7eef67e0-36a7-48b6-9137-0b10ea37ac3c@f3g2000hsg.googlegroups.com> Message-ID: <78583738-b488-4a24-a48e-1e0eab84ae6b@e6g2000prf.googlegroups.com> On Nov 21, 11:38 am, oj wrote: > Hi, > > I want to setuploggingwith two loggers: > > The child logger is used when something different needs to be done > with the log record, and the log record will propagate and be logged > by the root logger as usual. > > However, there are certain times when I don't want a log record to > propagate from the child to the parent. > > I don't really want to add a filter to the root logger, as it should > be up to the child whether the record propagates or not. > > I've tried setting the child to a lower level then the parent, but if > a record is dealt with by the child, the parent deals with it anyway > regardless of its own log level. > > Also, filters only apply particular handlers and do not affect > propagation. > > Can anyone suggest a simple way to achieve this? > > Currently, the only thing I can think of, is overriding the > callHandlers method in a custom Logger class. Do you already have a Logger subclass? Where and when is the decision being made about whether to propagate or not? From dominiquevalentine at gmail.com Tue Nov 13 22:09:11 2007 From: dominiquevalentine at gmail.com (dominiquevalentine at gmail.com) Date: Wed, 14 Nov 2007 03:09:11 -0000 Subject: Using Python To Change The World :) Message-ID: <1195009751.327435.182540@i13g2000prf.googlegroups.com> Hello, I'm a teen trying to do my part in improving the world, and me and my pal came up with some concepts to improve the transportation system. I have googled up and down for examples of using python to create a city street but I can not find any. my objective is to replicate a section of los angeles using python, and program the street lights and cars and whatnot. Should I be looking towards 3D to do this? so here is MY question: how would you replicate a street intersection in python? and furthermore, how would you do you have the cars move up and down those "streets". my question to YOU is: can you point me in the right direction? I will search on my own, but I would greatly appreciate any help :) and if anyone is interested in learning more about this project (we've got some nifty things planned), or if you wanna help, give a shout ;] From ojeeves at gmail.com Tue Nov 20 08:47:24 2007 From: ojeeves at gmail.com (oj) Date: Tue, 20 Nov 2007 05:47:24 -0800 (PST) Subject: logging.SocketHandler connections References: <23cfe277-7ece-4bef-a16f-1e64b1847f1c@a28g2000hsc.googlegroups.com> <7dfca907-f2e6-45b6-84f1-e60772c24c3d@w34g2000hsg.googlegroups.com> <5a39cd02-1f21-417d-8dd2-f96f10a2ac8f@v4g2000hsf.googlegroups.com> <4623a151-3246-4405-a770-23c70b4b45f1@w34g2000hsg.googlegroups.com> <58ef16cc-f2e4-4447-8939-30897e0bb35a@w28g2000hsf.googlegroups.com> Message-ID: <533a9736-d268-4d0f-add8-cd48a1211f8d@e4g2000hsg.googlegroups.com> On Nov 20, 12:26 pm, Vinay Sajip wrote: > > Can you confirm that if you add the while loop back in, all messages > are seen by the server? It worked for me. Yes, it works in that case. This was meant to be implied by my earlier messages, but on reflection, isn't obvious. As I said previously, the point is sorta moot, but if you do have an explanation as to why it behaves that way, or how I'm causing it, I would be interested. -Oliver From atuc at gmx.de Sun Nov 25 09:22:24 2007 From: atuc at gmx.de (Alexander Tuchacek) Date: Sun, 25 Nov 2007 15:22:24 +0100 Subject: PyQt, Cannot send events to objects owned by a different thread? Message-ID: <47498520$0$13104$9b4e6d93@newsspool2.arcor-online.net> hallo, i try to adress an qt object self.statusbar.showMessage("rtt %s...." % (n.rtt)) in an callback function, comming from a shared lib importet by ctypes, on osx this works wonderfull when i run the same code on linux (ubuntu gutsy), i get this core dump, ok, i understand that the problem is, that i cant speak to the qt thread, but why does it work on osx? shall i recompile python? pyqt or sip? without threads? could somebody give me a hint what to do best? how can i call a qt object in an c-lib callback? thanks for any help, alex ASSERT failure in QCoreApplication::sendEvent: "Cannot send events to objects owned by a different thread. Current thread 82c31e8. Receiver 'MainWindow' (of type 'MainWindow') was created in thread 81f5060", file kernel/qcoreapplication.cpp, line 269 Aborted (core dumped) From gagsl-py2 at yahoo.com.ar Sat Nov 10 00:32:13 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 10 Nov 2007 02:32:13 -0300 Subject: Python Extension Building Network References: <1194617297.075298.238880@i13g2000prf.googlegroups.com> <1194623343.121618.65350@v3g2000hsg.googlegroups.com> <1194625803.672229.299390@50g2000hsm.googlegroups.com> Message-ID: En Fri, 09 Nov 2007 13:30:03 -0300, escribi?: > On Nov 9, 10:02 am, Tim Golden wrote: >> kyoso... at gmail.com wrote: >> > The hardest part was finding accurate information. Most people on the >> > user groups have been unhelpful or sarcastic. >> >> That's a shame to hear. Because you were building on Windows? >> Or for some other reason? (I ask because, even here on the >> Python lists, reactions like "Get a working O/S" are not unknown >> in answer to questions like "How do I... on Windows?") > > I don't think it was because of Windows, but because I was asking > about how to use Visual Studio. I've had classes in it, but intro > classes in Comp Sci don't teach you how to compile. One of the people > on this list told me to go read Microsoft's docs. Was that me? In this message? (Note that you were asking "how do I use VS to compile an exe?", not "how do I build a Python extension?") I'm sorry if you feel the response was somewhat rude, I apologize in that case. It was not intended at all. -- Gabriel Genellina From donn.ingle at gmail.com Fri Nov 23 23:53:24 2007 From: donn.ingle at gmail.com (Donn Ingle) Date: Sat, 24 Nov 2007 06:53:24 +0200 Subject: Catching a segfault in a Python library References: <7x1wagp8vu.fsf@ruckus.brouhaha.com> Message-ID: > Run your app under a debugger and figure out what is making it crash. Already done, the code within PIL is causing the crash. It gets ugly and out of my remit. It's a freetype/Pil thing and I simply want to a way to catch it when it happens. Since a segfault ends the process, I am asking about "wrappers" around code to catch a segfault. \d From samrobertsmith at gmail.com Sun Nov 25 21:38:17 2007 From: samrobertsmith at gmail.com (linda.s) Date: Sun, 25 Nov 2007 18:38:17 -0800 Subject: multiple selection of cells Message-ID: <1d987df30711251838o851ceb0i9a025f329564ecbf@mail.gmail.com> Hi, I wonder how to hold the ctrl key and left button (button-1) to do multiple selection of the following items? Thanks, Linda import Tkinter s = Tkinter.Scrollbar() L = Tkinter.Listbox() s.pack(side=Tkinter.RIGHT, fill=Tkinter.Y) L.pack(side=Tkinter.LEFT, fill=Tkinter.Y) s.config(command=L.yview) L.config(yscrollcommand=s.set) for i in range(30): L.insert(Tkinter.END, str(i)*3) Tkinter.mainloop() From horpner at yahoo.com Sat Nov 17 10:57:14 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Sat, 17 Nov 2007 15:57:14 GMT Subject: Python Design Patterns - composition vs. inheritance References: <87600e6e-2409-4369-9ba2-bd231b010b46@n20g2000hsh.googlegroups.com> <13jqadr992huk32@corp.supernews.com> <473dc281$0$4990$4c368faf@roadrunner.com> Message-ID: On 2007-11-17, Odalrick wrote: >> But that breaks expectations: a user doesn't expect >> set_width() to affect the height. > > I can't speak for everyone but I certainly expect setting the > width of a Square to change it's height. In fact, that would > probably be the reason I used a Square rather than a Rectangle > in the first place. Some of the dissonance is from assuming that rectangles can mutate themselves. I've never seen one do that! ;) The rest of the dissonance is caused by strong typing. A rectangle with equal width and height is still a rectangle, in a strongly typed language. -- Neil cerutti From nick at craig-wood.com Thu Nov 15 13:30:04 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Thu, 15 Nov 2007 12:30:04 -0600 Subject: Creating Installer or Executable in Python References: <1195050579.054554.145120@22g2000hsm.googlegroups.com> Message-ID: Shane Geiger wrote: > DanielJohnson wrote: > > I have a small project which has around 10 .py files and I run this > > project using command line arguments. I have to distribute this > > project to somebody. > > > > I was wondering how can I make an executable or some kind of > > installer, so that end user doesn't need to compile and worry if he/ > > she has Python installed or not ? > > A few candidate solutions: > > http://nsis.sourceforge.net/Main_Page > http://www.jrsoftware.org/isinfo.php I've used py2exe and nsis quite a few times - works well. Note that py2exe can bundle your app into a single exe which you can just run which may be good enough (no need for an installer). -- Nick Craig-Wood -- http://www.craig-wood.com/nick From asterix at lagaule.org Mon Nov 26 05:53:46 2007 From: asterix at lagaule.org (Yann Le Boulanger) Date: Mon, 26 Nov 2007 11:53:46 +0100 Subject: regex and IGNORECASE Message-ID: <474aa5ba$0$8147$426a34cc@news.free.fr> Hi all, I have a problem with regex , utf-8 chars and IGNORECASE >>> re.search(u'?', u'qw?rt', re.IGNORECASE) <_sre.SRE_Match object at 0x2aaaaed0c100> Here everything is ok. >>> re.search(u'?', u'qw?rt', re.IGNORECASE) Here that doesn't work. but: >>> print u'?'.upper() ? is it a bug in IGNORECASE option? Thanks for your help -- Yann From bborcic at gmail.com Fri Nov 9 09:54:37 2007 From: bborcic at gmail.com (Boris Borcic) Date: Fri, 09 Nov 2007 15:54:37 +0100 Subject: Closure/binding problem or misunderstanding In-Reply-To: <1194618728.985169.15880@t8g2000prg.googlegroups.com> References: <1194618728.985169.15880@t8g2000prg.googlegroups.com> Message-ID: <473474e7$1_1@news.bluewin.ch> Bob.Sidebotham at gmail.com wrote: > If I run the following code: > > class path(object): > def __init__(self, **subdirs): > for name, path in subdirs.iteritems(): > def getpath(): > return path > setattr(self, name, getpath) > > export = path( > one = 'this is one', > two = 'this is two', > ) > > print "invoking", export.one, export.one() > print "invoking", export.two, export.two() > > I get this output: > > invoking this is one > invoking this is one > > So there apparently are two definitions of the function "getpath" (the > addresses are different, anyway), but they seem to have the same value > for the binding of "path". It's not clear to me, after reading what I > can find about python name binding, whether this is the expected > behavior, or not (although I was surprised). > > Can anyone enlighten me? Yes this is the expected behavior. Both your getpath() functions return the current value of the single path variable at the time of invocation. Perhaps this would be the slightest bit clearer if subdir.iteritems() did not provide your items in swapped order (so that the returned values would be "this is two"). To create distinct bindings to distinct values of path at the distinct executions of "def getpath() :...", you should write "def getpath(path=path) :..." HTH, BB > > Thanks, > Bob Sidebotham > From kyosohma at gmail.com Thu Nov 8 09:18:59 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 08 Nov 2007 06:18:59 -0800 Subject: wxPython ListCtrl image configuring In-Reply-To: <1194522304.427000.32120@q5g2000prf.googlegroups.com> References: <1194522304.427000.32120@q5g2000prf.googlegroups.com> Message-ID: <1194531539.598589.5370@i13g2000prf.googlegroups.com> On Nov 8, 5:45 am, vedrandeko... at v-programs.com wrote: > Hello, > > Here is example of my ListCtrl items with image: > > ( filebox1 is ListCtrl ) > > il = wx.ImageList(16,16) > images=["file1.png","folder.png"] > for i in images: > il.Add(wx.Bitmap(i)) > img_list=filebox1.SetImageList(il, wx.IMAGE_LIST_SMALL) > j=1 > unos1p=unos1.GetValue() > unos2p=unos2.GetValue() > unos3p=unos3.GetValue() > newftp=FTPHost(unos1p,unos2p,unos3p) > for item in newftp._dir('/'): > if item.split()[2]=="": > index=filebox1.InsertStringItem(j,item) > filebox1.SetItemImage(index,2) > > else: > index=filebox1.InsertStringItem(j,item) > filebox1.SetItemImage(index,1) > > ......Then my program show all items and images with them, but the > problem is when I click on item > image of item disappere .Any idea? > > Regards, > Vedran I'm not seeing anything, but then again I don't use images in my listctrls. I would recommend posting your on-click event handler. You may find the wxPython demo's code helpful. You can also see more examples on the wxPython wiki: http://wiki.wxpython.org/ListControls http://wiki.wxpython.org/Refillable_List_Control You should also post to the wxPython user's group: http://www.wxpython.org/maillist.php Mike From waldemar.osuch at gmail.com Fri Nov 9 18:02:03 2007 From: waldemar.osuch at gmail.com (Waldemar Osuch) Date: Fri, 09 Nov 2007 15:02:03 -0800 Subject: Codec lookup fails for bad codec name, blowing up BeautifulSoup In-Reply-To: <4734C6CC.7090204@animats.com> References: <4734C6CC.7090204@animats.com> Message-ID: <1194649323.666365.192100@y27g2000pre.googlegroups.com> > > This is a known bug. It's in the old tracker on SourceForge: > [ python-Bugs-960874 ] codecs.lookup can raise exceptions other > than LookupError > but not in the new tracker. The new tracker has it too. http://bugs.python.org/issue960874 > > The "resolution" back in 2004 was "Won't Fix", without a change > to the documentation. Grrr. > From Afro.Systems at gmail.com Thu Nov 22 10:44:23 2007 From: Afro.Systems at gmail.com (Tzury Bar Yochay) Date: Thu, 22 Nov 2007 07:44:23 -0800 (PST) Subject: 100% CPU Usage when a tcp client is disconnected References: <2aae621c-35e7-48a5-9121-ca2446a0ee04@y43g2000hsy.googlegroups.com> <360c78fb-0d13-4f51-9ae6-f0cdef5951be@s8g2000prg.googlegroups.com> Message-ID: <662972b9-db0f-4fd9-9814-7e2a1e343003@d21g2000prf.googlegroups.com> > data = "dummy" > while data: > ... Thanks Alot From edreamleo at charter.net Fri Nov 16 08:38:47 2007 From: edreamleo at charter.net (Edward K Ream) Date: Fri, 16 Nov 2007 07:38:47 -0600 Subject: Leo 4.4.5 beta 1 released Message-ID: Leo 4.4.5 beta 1 is available at: http://sourceforge.net/project/showfiles.php?group_id=3458&package_id=29106 Leo is a text editor, data organizer, project manager and much more. See: http://webpages.charter.net/edreamleo/intro.html Leo 4.4.5 fixes several long-delayed bug fixes and adds several new features. The highlights of Leo 4.4.5: ---------------------------- - Fixes all known bugs. - Adds 3 new sort-lines commands. - Adds commands to insert and delete icons from headlines. - Adds all the Tango 16x16 icons to Leo's icon library. - Adds support for @rst-preformat nodes to the rst3 plugin. Links: ------ Leo: http://webpages.charter.net/edreamleo/front.html Home: http://sourceforge.net/projects/leo/ Download: http://sourceforge.net/project/showfiles.php?group_id=3458 CVS: http://leo.tigris.org/source/browse/leo/ Quotes: http://webpages.charter.net/edreamleo/testimonials.html -------------------------------------------------------------------- Edward K. Ream email: edreamleo at yahoo.com Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From soundmaker at optonline.net Wed Nov 28 16:15:17 2007 From: soundmaker at optonline.net (Wally Lepore) Date: Wed, 28 Nov 2007 16:15:17 -0500 Subject: Tuning question Message-ID: <000501c83203$c67312a0$6501a8c0@iwilldualp3> Hi Graham Is this email still good? Its been awhile since we spoke last on the tuning list. Are you still on Yahoo messenger? Also, what is your email address please. You told me to email you when I had questions that seemed too basic for the tuning list. Thanks Graham. My email is soundmaker at optonline.net Stay well Walter (Wally) Lepore From jcd at sdf.lonestar.org Tue Nov 20 21:57:43 2007 From: jcd at sdf.lonestar.org (J. Clifford Dyer) Date: Tue, 20 Nov 2007 21:57:43 -0500 Subject: [regex] Basic rewriting In-Reply-To: References: Message-ID: <1195613863.7838.2.camel@jcd-desktop> On Wed, 2007-11-21 at 03:24 +0100, Gilles Ganault wrote: > Hello > > I've been reading tutorials on regexes in Python, but I still > don't get it: > > ======== > #!/usr/bin/python > > #myscript.py 0123456789 > > import sys,re > > #Turn 0123456789 into 01.23.45.67.89 > p = re.compile('(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)') > phone = p.sub('\1.\2.\3.\4.\5',sys.argv[1]) > print phone > ======== > > => Python displays "...." instead. Any idea what I'm doing wrong? > > Thank you. Use raw strings for re expressions. r'this is a raw string' 'this is not' p = re.compile(r'(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)') phone = p.sub(r'\1.\2.\3.\4.\5',sys.argv[1]) Should clear up your problem. From steven at REMOVE.THIS.cybersource.com.au Tue Nov 27 22:09:32 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Wed, 28 Nov 2007 03:09:32 -0000 Subject: How to Teach Python "Variables" References: <4749bb94$1@news.bezeqint.net> <5qvf6pF122r3mU1@mid.individual.net> <87abp1qqth.fsf@mulj.homelinux.net> Message-ID: On Tue, 27 Nov 2007 10:21:36 -0800, hdante wrote: > Python variables are pointers and that's it. How do I increment a Python variable so that it points to the next address, like I can do with pointers in C, Pascal, and other languages? -- Steven. From kyosohma at gmail.com Wed Nov 7 13:35:51 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Wed, 07 Nov 2007 18:35:51 -0000 Subject: os.popen does not seem to catch stdout In-Reply-To: <1194459474.813737.27540@k79g2000hse.googlegroups.com> References: <1194443892.026237.67480@e9g2000prf.googlegroups.com> <1194453068.928713.117600@o38g2000hse.googlegroups.com> <1194459474.813737.27540@k79g2000hse.googlegroups.com> Message-ID: <1194460551.058503.298510@d55g2000hsg.googlegroups.com> On Nov 7, 12:17 pm, "gregpin... at gmail.com" wrote: > On Nov 7, 11:31 am, kyoso... at gmail.com wrote: > > > > > On Nov 7, 7:58 am, zane.selv... at gmail.com wrote: > > > > Hi there, > > > > I've been banging my head against this for a day, and I can't take it > > > anymore. It's probably a stupid error, but I don't see where. > > > > I'm trying to use Python to call an external program, and then catch > > > and process the output of that program. Seems simple enough. The > > > command I'm trying to run, in the test, is: > > > > "/Users/zane/svn/stress/satstress/satstress -r1.561e+06 -a5 -s45000 - > > > e0 -R6.709e+08 -g1.31472 -m1.8987e+27 -Q57100.1 -n0.333355 -Y9.29881e > > > +09 -k1e+22 -Z1.19173 -z-6.293e-05 -V0.309434 -v-2.903e-05 -W1.81305 - > > > w-0.00418645 -U0.474847 -u-0.00276624 -C /tmp/18_tmp.gen -b 60" > > > > When I run it at my zsh prompt, I get the expected output. > > > > If I let ss_cmd equal the above string within ipython (or the standard > > > python interactive interpreter): > > > > ss_outlines = os.popen(ss_cmd).readlines() > > > > ss_outlines contains the same output I saw when I ran the command at > > > my zsh prompt, one line per list element, as expected. > > > > However, when I try doing the same thing from within a program, it > > > fails. ss_outlines is an empty list. > > > > I've tried using subprocess.Popen(), and subprocess.call(), and > > > subprocess.check_call(), and all have yielded similar results. I did > > > find, however, that the return value python is getting from the > > > program I'm calling is different from what I get at the command line > > > (I get 0, python gets -11). > > > > Does this ring a bell for anyone? > > > > I'm using Python 2.5.1 on a Mac running OS X 10.5. > > > I think when you use subprocess.Popen, you need to do something set > > the shell to True to get it to behave like running from a command > > prompt: > > > subprocess.Popen('some command', shell=True) > > > Seehttp://docs.python.org/lib/node529.htmlformore details. > > > You'll also find a fairly interesting thread on this topic here: > > >http://mail.python.org/pipermail/chicago/2005-November/000141.htmlhtt... > > > This seems to be a recipe on it: > > >http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440554 > > > Mike > > That's right, and I think you also want to put the whole command in a > list or tuple, one item for each arg. I don't know why though. > > -Greg I've never had to put the command into a list or tuple...but you're welcome to try it that way. Mike From nick at craig-wood.com Sun Nov 25 16:30:04 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Sun, 25 Nov 2007 15:30:04 -0600 Subject: import pysqlite2 or import sqlite3? References: <19355218-e15b-4403-91af-c8c9c33f08cb@e1g2000hsh.googlegroups.com> Message-ID: MonkeeSage wrote: > I use the following for a progam I wrote using sqlite, to ensure > maximum compatibility (since the API is the same, importing them both > as 'sqlite' should be fine): > > try: > from sqlite3 import dbapi2 as sqlite # python 2.5 I've been using import sqlite3 as sqlite here sqlite3 and sqlite3.dbapi2 seem to be the same thing Python 2.5.1 (r251:54863, Aug 17 2007, 00:51:07) [GCC 4.1.3 20070812 (prerelease) (Debian 4.1.2-15)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from sqlite3 import dbapi2 >>> import sqlite3 >>> set(dir(sqlite3)) ^ set(dir(dbapi2)) set(['__path__', 'dbapi2']) >>> -- Nick Craig-Wood -- http://www.craig-wood.com/nick From psihodelia at googlemail.com Tue Nov 6 11:25:51 2007 From: psihodelia at googlemail.com (psihodelia at googlemail.com) Date: Tue, 06 Nov 2007 16:25:51 -0000 Subject: Parallel Python environments.. In-Reply-To: References: Message-ID: <1194366351.337684.309200@50g2000hsm.googlegroups.com> In Gentoo Linux you can select between installed python version using python-config script. From hdante at gmail.com Fri Nov 23 20:02:14 2007 From: hdante at gmail.com (hdante at gmail.com) Date: Fri, 23 Nov 2007 17:02:14 -0800 (PST) Subject: How to import xplt, pylab? References: <8dbd9284-f4e5-41f6-b2b6-81616dd50be8@s19g2000prg.googlegroups.com> <0bde7684-3215-436a-9848-c21292ca5456@i29g2000prf.googlegroups.com> Message-ID: <74e50ce4-aa6b-4519-b3f6-9b11a0807eb1@a39g2000pre.googlegroups.com> On Nov 23, 8:03 pm, Robert Kern wrote: > > In any case, xplt has been deprecated for a long time. It probably doesn't work. > I don't recommend using it unless if you want to take on the responsibility of > maintaining it. > > -- BTW, does she need help with importing a module or with plotting some graph ? :-) From wleftwich at gmail.com Sat Nov 17 10:37:11 2007 From: wleftwich at gmail.com (Wade Leftwich) Date: Sat, 17 Nov 2007 07:37:11 -0800 (PST) Subject: Excellent sci-fi novel featuring Python Message-ID: <45ae31dd-0aaf-4065-ba9e-b1e5cf78b105@c30g2000hsa.googlegroups.com> I'm about halfway through Charles Stross' excellent new novel, "Halting State". It's set in Edinburgh in the year 2018, and one of the main characters is a game programmer whose primary language is something called "Python 3000". The cover features blurbs from William Gibson, Vernor Vinge, John Carnack, and Bruce Scheier. What, they couldn't pop for an advance copy for Guido? -- Wade Leftwich Ithaca, NY From steve at REMOVE-THIS-cybersource.com.au Sat Nov 10 17:46:47 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sat, 10 Nov 2007 22:46:47 -0000 Subject: Populating a dictionary, fast References: Message-ID: <13jcd6noulpvg1c@corp.supernews.com> On Sat, 10 Nov 2007 13:56:35 -0800, Michael Bacarella wrote: > The id2name.txt file is an index of primary keys to strings. They look > like this: > > 11293102971459182412:Descriptive unique name for this record\n > 950918240981208142:Another name for another record\n > > The file's properties are: > > # wc -l id2name.txt > > 8191180 id2name.txt > # du -h id2name.txt > 517M id2name.txt > > I'm loading the file into memory with code like this: > > id2name = {} > for line in iter(open('id2name.txt').readline,''): > id,name = line.strip().split(':') > id = long(id) > id2name[id] = name That's an awfully complicated way to iterate over a file. Try this instead: id2name = {} for line in open('id2name.txt'): id,name = line.strip().split(':') id = long(id) id2name[id] = name On my system, it takes about a minute and a half to produce a dictionary with 8191180 entries. > This takes about 45 *minutes* > > If I comment out the last line in the loop body it takes only about 30 > _seconds_ to run. This would seem to implicate the line id2name[id] = > name as being excruciatingly slow. No, dictionary access is one of the most highly-optimized, fastest, most efficient parts of Python. What it indicates to me is that your system is running low on memory, and is struggling to find room for 517MB worth of data. > Is there a fast, functionally equivalent way of doing this? > > (Yes, I really do need this cached. No, an RDBMS or disk-based hash is > not fast enough.) You'll pardon me if I'm skeptical. Considering the convoluted, weird way you had to iterate over a file, I wonder what other less-than-efficient parts of your code you are struggling under. Nine times out of ten, if a program runs too slowly, it's because you're using the wrong algorithm. -- Steven. From arkanes at gmail.com Thu Nov 8 10:11:13 2007 From: arkanes at gmail.com (Arkanes) Date: Thu, 08 Nov 2007 08:11:13 -0700 Subject: pyparsing and svg In-Reply-To: <1194516523.132716.168340@i13g2000prf.googlegroups.com> References: <1194516523.132716.168340@i13g2000prf.googlegroups.com> Message-ID: <47332711.2020902@gmail.com> Paul McGuire wrote: > On Nov 8, 3:14 am, Donn Ingle wrote: > > >> float = nums + dot + nums >> > > Should be: > > float = Combine(Word(nums) + dot + Word(nums)) > > nums is a string that defines the set of numeric digits for composing > Word instances. nums is not an expression by itself. > > For that matter, I see in your later tests that some values have a > leading minus sign, so you should really go with: > > float = Combine(Optional("-") + Word(nums) + dot + Word(nums)) > > > I have a working path data parser (in pyparsing) at http://code.google.com/p/wxpsvg. Parsing the numeric values initially gave me a lot of trouble - I translated the BNF in the spec literally and there was a *ton* of backtracking going on with every numeric value. I ended up using a more generous grammar, and letting pythons float() reject invalid values. I couldn't get repeating path elements (like M 100 100 200 200, which is the same as M 100 100 M 200 200) working right in the grammar, so I expand those with post-processing. The parser itself can be seen at http://wxpsvg.googlecode.com/svn/trunk/svg/pathdata.py > Some other comments: > > 1. Read up on the Word class, you are not using it quite right. > > command = Word("MLCZ") > > will work with your test set, but it is not the form I would choose. > Word(characterstring) will match any "word" made up of the characters > in the input string. So Word("MLCZ") will match > M > L > C > Z > MM > LC > MCZL > MMLCLLZCZLLM > > I would suggest instead using: > > command = Literal("M") | "L" | "C" | "Z" > > or > > command = oneOf("M L C Z") > > 2. Change comma to > > comma = Literal(",").suppress() > > The comma is important to the parsing process, but the ',' token is > not much use in the returned set of matched tokens, get rid of it (by > using suppress). > > 3. Group your expressions, such as > > couple = Group(float + comma + float) > > It will really simplify getting at the resulting parsed tokens. > > > 4. What is the purpose of (couple + couple)? This is sufficient: > > phrase = OneOrMore(command + Group(OneOrMore(couple)) ) > > (Note use of Group to return the coord pairs as a sublist.) > > > 5. Results names! > > phrase = OneOrMore(command("command") + Group(OneOrMore(couple)) > ("coords") ) > > will allow you to access these fields by name instead of by index. > This will make your parser code *way* more readable. > > > -- Paul > > From steve at REMOVE-THIS-cybersource.com.au Sun Nov 4 17:21:21 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 04 Nov 2007 22:21:21 -0000 Subject: python newbie References: <472b2b84$0$13761$6e1ede2f@read.cnntp.org> <5p0s6vFp47k9U1@mid.individual.net> <472b5251$0$6238$426a34cc@news.free.fr> <13ioa6f6t797gce@corp.supernews.com> <7x4pg3wks5.fsf@ruckus.brouhaha.com> <7x8x5f83u5.fsf@ruckus.brouhaha.com> <1194126214.238480.254180@57g2000hsv.googlegroups.com> <7xabpvkn0n.fsf@ruckus.brouhaha.com> <472defc8$0$30484$426a74cc@news.free.fr> <7xr6j52acl.fsf@ruckus.brouhaha.com> <472e1a1f$0$24020$426a74cc@news.free.fr> <7xsl3lrd2o.fsf@ruckus.brouhaha.com> Message-ID: <13ishf1ama66dab@corp.supernews.com> On Sun, 04 Nov 2007 12:05:35 -0800, Paul Rubin wrote: > Bruno Desthuilliers writes: >> > from random import random >> > x = random() >> > y = random.choice((1,2,3)) # oops >> >> from random import random, choice >> >> x = random() >> y = choice((1, 2, 3)) > > Really, a lot of these modules exist primarily to export a single class > or function, but have other classes or functions of secondary interest. > I'd like to be able to get to the primary function without needing to > use a qualifier, and be able to get to the secondary ones by using a > qualifier instead of having to import explicitly and clutter up the > importing module's name space like that. It just seems natural. +1 on Paul's suggestion. It's a style thing: it is so much more elegant and obvious than the alternatives. A module is a single conceptual unit. It might very well have a rich internal API, but many modules also have a single main function. It might be a function or class with the same name as the module, or it might literally be called "main". It might be designed to be called from the shell, as a shell script, but it need not be. A good clue that you're dealing with such a module is if you find yourself usually calling the same object from the module, or if the module has a main class or function with the same name as the module. The module is, in effect, a single functional unit. Possible candidates, in no particular order: StringIO, random, glob, fnmatch, bisect, doctest, filecmp, ... Note that they're not *quite* black boxes: at times it is useful to crack that functional unit open to access the internals: the module's "not main" functions. But *much of the time*, you should be able to use a module as a black box, without ever caring about anything inside it: import module module(data) # do something with the module The model I have in mind is that of shell-scripting languages, like Bash. For the purpose of syntax, Bash doesn't distinguish between built-in commands and other Bash scripts, but Python does. When you call a script (module) in Bash, you don't need to qualify it to use it: ls > myscript --options instead of ls > myscript.myscript --options If you think of modules (at least sometimes) as being the equivalent of scripts, only richer and more powerful, then the ugliness of the current behaviour is simply obvious. This model of modules as scripts isn't appropriate for all modules, but it is backwards compatible with the current way of doing things (except for code that assumes that calling a module will raise an exception). For those modules that don't have a single main function, simply don't define __call__. The "natural" way to treat a module as a functional whole *and* still be able to crack it open to access the parts currently is some variation of: from module import main import module That's inelegant for at least six reasons: (1) There's no standard interface for module authors. Should the main function of the module be called "main" or "__main__" or "__call__" or something derived from the name of the module? The same as the module name? (2) Namespace pollution. There are two names added to the namespace just to deal with a single conceptual unit. (3) The conceptual link between the module and it's main function is now broken. There is no longer any obvious connection between main() and the module. The two are meant to be joined at the hip, and we're treating them as independent things. (4) What happens if you have two modules you want to treat this way, both with a main function with the same name? You shouldn't have to say "from module import main as main2" or similar. (5) You can't use the module as a black box. You *must* care about the internals, if only to find out the name of the main function you wish to import. (6) The obvious idiom uses two imports (although there is an almost as obvious idiom only using one). Python caches imports, and the second is presumably much faster than the first, but it would be nice to avoid the redundant import. As far as I know, all it would take to allow modules to be callable would be a single change to the module type, the equivalent of: def __call__(self, *args, **kwargs): try: # Special methods are retrieved from the class, not # from the instance, so we need to see if the # instance has the right method. callable = self.__dict__['__call__'] except KeyError: return None # or raise an exception? return callable(self, *args, **kwargs) -- Steven From ptmcg at austin.rr.com Wed Nov 21 10:20:45 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Wed, 21 Nov 2007 07:20:45 -0800 (PST) Subject: Clean way to get one's network IP address? References: Message-ID: <32088557-2978-49d2-aa4c-0cce87c12291@y5g2000hsf.googlegroups.com> On Nov 21, 9:15 am, Gilles Ganault wrote: > Hello > > I need to get the local computer's IP address, ie. what's displayed > when running "ifconfig" in Linux: > > # ifconfig > eth0 Link encap:Ethernet HWaddr 00:15:58:A1:D5:6F > inet addr:192.168.0.79 Bcast:192.168.0.255 > Mask:255.255.255.0 > > I know about socket.gethostbyname, but this relies on what's in > /etc/hosts, and I'd rather have a more independent solution. > > What would be a good way to do this? > > Thank you. Be aware that it is very possible to have multiple IP addresses from which to choose (systems have multiple network adapters, VPNs, wireless, etc.), so the question might not be how to get THE IP address, but how to get THE RIGHT IP address. Selecting the right IP address from among several is not always clear cut. -- Paul From kyosohma at gmail.com Fri Nov 9 11:24:15 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Fri, 09 Nov 2007 16:24:15 -0000 Subject: Expanding the size of wx Frame In-Reply-To: <1194584529.374997.281890@d55g2000hsg.googlegroups.com> References: <1194584529.374997.281890@d55g2000hsg.googlegroups.com> Message-ID: <1194625455.233762.225010@19g2000hsx.googlegroups.com> On Nov 8, 11:02 pm, sundarvenkata wrote: > hello all, is there a way to make wxpython frame to expand itself > as we add controls to it Yes. I recommend using sizers. Then you can have the frame fit the widgets it holds using the Fit() command. I think this only applies when you first create the frame. After that the usual way is to call Layout() or Refresh() on the parent of the widgets (the frame in this case). I've done something like this before when I've changed elements in my panel: self.SetClientSize(self.panel.GetBestSize()) You might also find the wx.CollapsiblePane valuable. Mike From davisn90210 at gmail.com Mon Nov 12 16:03:47 2007 From: davisn90210 at gmail.com (davisn90210 at gmail.com) Date: Mon, 12 Nov 2007 21:03:47 -0000 Subject: Transfer socket connection between programs In-Reply-To: <1194896500.733359.93510@50g2000hsm.googlegroups.com> References: <1194896500.733359.93510@50g2000hsm.googlegroups.com> Message-ID: <1194901427.812895.309490@v29g2000prd.googlegroups.com> On Nov 12, 1:41 pm, JamesHoward wrote: > Does anyone know any method to have one program, acting as a server > transfer a socket connection to another program? I looked into > transferring the connection via xml rpc to no avail. It seems to be a > problem of getting access to a programs private memory space and > giving another program access to that space. > > Thanks in advance, > James Howard On Unix, you can use Unix Domain Sockets to pass file descriptors between processes. You need to create a Unix Socket, then use sendmsg and recvmsg to pass the file descriptor between processes. Linux Application Development includes an example of how to do this in section 16.4.6. The book is available through Amazon.com at http://www.amazon.com/Linux-Application-Development-Michael-Johnson/dp/0321219147 I'm sure you can find other examples on the internet to follow. Hope this points you in the right direction, --Nathan Davis From fer7msb02 at sneakemail.com Wed Nov 14 18:24:29 2007 From: fer7msb02 at sneakemail.com (Yang) Date: Wed, 14 Nov 2007 18:24:29 -0500 Subject: os.system() not returning Message-ID: <31178-43445@sneakemail.com> I have a Python program that does the following (pseudo-code): while True: is_downloading = True use ftplib to download any new files from a server is_downloading = False os.system('make') sleep(60) To deal with intermittent connectivity/failures (this is running on a mobile device), /etc/ppp/ip-up.local (a program that is run whenever Internet connectivity is established) issues SIGUSR1 to the python process, which handles it as such: def handle_sigusr1(sig, bt): global is_downloading, debug if debug: print 'got SIGUSR1'; sys.stdout.flush() if is_downloading: args = ['python'] + sys.argv if debug: print 'spawning', args; sys.stdout.flush() pid = os.spawnvp(os.P_NOWAIT, 'python', args) if debug: print 'pid', pid; sys.stdout.flush() os.kill(os.getpid(), SIGTERM) signal(SIGUSR1, handle_sigusr1) (I start a new process since I didn't want to get into the business of killing threads.) However, os.system() occasionally does not return. It's just: ... os.system('make -C ' + localpath + ' -f ' + makefiles[-1]) if debug: print 'sleeping' ... and the stdout log always ends in "make: Leaving directory `/dldir'" (make finishes). The python process is still running, but doesn't respond to SIGUSR1, so perhaps it's still in the syscall. (SIGTERM kills it, though; no SIGKILL needed.) I separately tested that (a) python can be interrupted by SIGUSR1 while in blocking socket IO, and (b) SIGUSR1 doesn't screw up python while in a os.system('make') (the signal gets handled after the call returns). Has anybody seen this kind of behavior, or might know what's going on? Thanks in advance for any help. FWIW, here is other info: root at soekris4801:~$ uname -a Linux soekris4801 2.6.20-soekris #2 Sun Nov 4 19:07:00 EST 2007 i586 unknown root at soekris4801:~$ python -V Python 2.5.1 Here are the commands the Makefile executes (repeatedly) - all standard bash/command-line tools: make: Entering directory `/dldir' ls -1 /dldir/setup*.bash | tail -1 | xargs bash -x + set -o errexit + set -o nounset + mkdir -p /tftproot/ ++ ls -1 /dldir/iii-03.tgz ++ sed 's/.*iii-\([0-9]*\)\.tgz.*/\1/' ++ tail -1 + avail=03 ++ cat /tftproot/iii-version + installed=03 + '[' -z 03 ']' + (( installed < avail )) make: Leaving directory `/dldir' From garywlee at gmail.com Thu Nov 1 02:15:05 2007 From: garywlee at gmail.com (GaryLee) Date: Wed, 31 Oct 2007 23:15:05 -0700 Subject: py2exe (or other exe builder) on Vista system for Vista/XP install targets. In-Reply-To: <1193832521.937425.94860@o3g2000hsb.googlegroups.com> References: <1193832521.937425.94860@o3g2000hsb.googlegroups.com> Message-ID: <1193897705.338785.133640@q5g2000prf.googlegroups.com> On 10 31 , 8 08 , Michael wrote: > I'm trying to build a exe on a vista system using py2exe. It will > deploy to vista and XP systems. If it matters, the application uses > pyserial, as well. I have VS Studio 2005 installed on this laptop as > well. I've found this so far that seems to be identical to what I'm > seeing (for non-python programs):http://www.thescripts.com/forum/thread611031.html > > When I attempt to run, I get "The procedure entry point > _except_handler4_common could not be located in the dynamic link > library mscvrt.dll." Apparently vista has one more > _except_handler#_common function than XP does. > I use pyinstaller to create the single execution file. However, if you have some DLLs which built from VC2005. You may need to include the VC2005 redistribution files in your execution file. Here are the files which I get from VC2005's redistributed package and include in my execution file. Microsoft.VC80.CRT.manifest msvcm80.dll msvcp80.dll msvcr80.dll From yuxi at ece.gatech.edu Sun Nov 11 00:06:38 2007 From: yuxi at ece.gatech.edu (Yu-Xi Lim) Date: Sun, 11 Nov 2007 00:06:38 -0500 Subject: Populating a dictionary, fast In-Reply-To: <13jd1fc3u7co1db@corp.supernews.com> References: <13jd1fc3u7co1db@corp.supernews.com> Message-ID: Steven D'Aprano wrote: > (2) More memory will help avoid paging. If you can't get more memory, try > more virtual memory. It will still be slow, but at least the operating > system doesn't have to try moving blocks around as much. > Based on his previous post, it would seem he has 7GB of RAM (with about 5GB free) and 2GB of swap. I don't think RAM is the issue. Maybe there's something wrong with his specific Python installation. What version is it and was it compiled by him? From chris.monsanto at gmail.com Thu Nov 15 21:38:33 2007 From: chris.monsanto at gmail.com (Chris M) Date: Thu, 15 Nov 2007 18:38:33 -0800 (PST) Subject: Interfaces. References: <1ecf1cca-f05f-44b5-8128-a93208815f15@y5g2000hsf.googlegroups.com> Message-ID: On Nov 15, 8:55 pm, "PeterBrad... at googlemail.com" wrote: > Hi, > > Does anyone know what the state of progress with interfaces for python > (last I can see ishttp://www.python.org/dev/peps/pep-0245/) > > I would argue that interfaces/(similar feature) are necessary in any > modern language because they provide a way of separating the > specification from the implementation of a module. > > I also had a new idea - when specifying the functionality of a module, > it would be nice to combine examples of valid behaviour / some sort of > testing. > > It might therefore be possible to combine unit testing with > interfaces. > > What do you all think? > > Peter > (new to python so be nice :) Status: Rejected If you really want an "interface", make a class with methods that raise NotImplementedError. From mail at microcorp.co.za Sun Nov 18 01:19:50 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 18 Nov 2007 08:19:50 +0200 Subject: Troubleshooting garbage collection issues References: Message-ID: <00a801c829ab$07627aa0$03000080@hendrik> (Dave) wrote: 8<--------- description of horrible problem -------------- Faced with this, I would: 1 - identify the modules that import gc to separate the sheep from the goats. 2 - do my best to change gc importing goats back to sheep. 3 - amongst the remaining goats, identify the ones that also use threads, (supergoats) and take a long hard look at them. 4 - hope I get lucky. 5 - If no luck, I would change the most complex of the supergoats to use more processes and messaging, to make sheep out of a supergoat, or failing that, a goat and some sheep. 6 - Repeat from 2 until luck strikes. Now the trouble with a simple minded algorithm such as the above is that a sheep could be at the bottom of the trouble if it uses threads. So a module is only a lamb if it uses neither threads nor makes calls into gc... HTH - Hendrik From paul.nospam at rudin.co.uk Wed Nov 28 03:18:43 2007 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Wed, 28 Nov 2007 08:18:43 +0000 Subject: How to Teach Python "Variables" References: <4749bb94$1@news.bezeqint.net> Message-ID: <87aboyhjfg.fsf@rudin.co.uk> none <""atavory\"@(none)"> writes: > IIRC, I once saw an explanation how Python doesn't have > "variables" in the sense that, say, C does, and instead has bindings > from names to objects. Does anyone have a link? "Variable" is an abstract concept, and it's a slightly different concept for every programming language. So you're correct to say that they're not like C variables. But putting it that way is no more valid than saying that C doesn't have variables like Python's. If you're teaching it from first principles then I wouldn't start by saying what they're not, if people don't know what C variables are then it doesn't help to say "these Python variables are not like C variables". If they do know about variables in other languages, it might help to say "forget your preconceptions about what a variable is". As you say, in Python variables are essentially names in some kind of lookup table for objects... this is a perfectly reasonable way to try and explain the idea (and is essentially the way it's implemented). Then you have to get into scoping, and the odd gotcha (e.g. contrast assigning to a global variable in local scope with referencing one - with and without a "global" statement). From brzrkr0 at gmail.com Thu Nov 8 11:26:00 2007 From: brzrkr0 at gmail.com (brzrkr0 at gmail.com) Date: Thu, 08 Nov 2007 16:26:00 -0000 Subject: Linking debug C++ DLL with python dlls In-Reply-To: <1194523667.585997.199590@e9g2000prf.googlegroups.com> References: <1194523667.585997.199590@e9g2000prf.googlegroups.com> Message-ID: <1194539160.899504.68040@t8g2000prg.googlegroups.com> On Nov 8, 4:07 am, mosheha... at gmail.com wrote: > I tried to change the code above (just for fun) so in both cases i'll > use python25.lib and in debug compilation I got linker errors on > unresolved externals. seems like the debug version exports more > methods than the release version. I usually just build my extensions in release mode and avoid using the debugger. Getting a copy of python24_d.lib (in my case) and building a debug version of my extension isn't a big deal, but afaik all my other extensions (wxPython, numpy, etc) have to be built in debug mode as well in order for things to work. If you find a good solution, please post it to the group because I'd like to know how to do this as well. -Casey From nswebster at gmail.com Thu Nov 22 06:09:38 2007 From: nswebster at gmail.com (Neil Webster) Date: Thu, 22 Nov 2007 03:09:38 -0800 (PST) Subject: Problems with if/elif statement syntax Message-ID: <4d58211e-ebe8-40fe-80ae-cf8b4a56f9ec@d21g2000prf.googlegroups.com> Hi all, I'm sure I'm doing something wrong but after lots of searching and reading I can't work it out and was wondering if anybody can help? I've got the following block of code: if a >= 20 and a < 100: if c == "c": radius = 500 else: radius = 250 elif (a >= 100) and (a < 500): radius = 500 elif (a >= 500) and (a < 1000): radius = 1000 elif (a >= 1000) and (a < 3000): radius = 1500 elif (a >= 3000) and (a < 5000): radius = 2000 else: radius = 4000 No matter what value goes in for 'a' the radius always comes out as 4000. What am I doing wrong? Cheers Neil From stefan.behnel-n05pAM at web.de Tue Nov 20 01:29:50 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 20 Nov 2007 07:29:50 +0100 Subject: getElementsByTagName in ElementTree In-Reply-To: References: Message-ID: <47427EDE.8080708@web.de> sndive at gmail.com wrote: > what's the equivalent of minidom's getElementsByTagName in ElementTree? element.findall("//{namespace}tagname") Stefan From seungchan.oh at gmail.com Mon Nov 5 02:32:24 2007 From: seungchan.oh at gmail.com (flyfree) Date: Mon, 05 Nov 2007 07:32:24 -0000 Subject: PyObjC with Xcode 3.0 Leopard Message-ID: <1194247944.398414.262030@z24g2000prh.googlegroups.com> I got an error during making a python application with xcode 3.0 in OS X Leopard. (KeyError: 'NSUnknownKeyException - [ valueForUndefinedKey:]: this class is not key value coding-compliant for the key calculatedMean.') The application is a simple example of how to use the PyObjC with xcode 2.0. http://developer.apple.com/cocoa/pyobjc.html Could you give any hint to start to dig into it? From lepto.python at gmail.com Sun Nov 11 06:21:25 2007 From: lepto.python at gmail.com (oyster) Date: Sun, 11 Nov 2007 19:21:25 +0800 Subject: why ctypes+dll gives a strange result Message-ID: <6a4f17690711110321i19a37d7bm5fd16a40b9fbc037@mail.gmail.com> you can download the files at http://www.newsmth.net/att.php?s.284.38015.655.zip the dll and exe are created by freebasic import ctypes mydll=ctypes.windll.LoadLibrary("mydll.dll") _TwoTimes=getattr(mydll,'TWOTIMES at 8') _TwoTimes.argtypes=[ctypes.c_double] def TwoTimes(i): return _TwoTimes(i) in fact, twotimes function return double*2, but when I use print TwoTimes(10) in python, I get 2226880 thanx -------------- next part -------------- An HTML attachment was scrubbed... URL: From msc at es.aau.dk Fri Nov 2 10:34:23 2007 From: msc at es.aau.dk (Martin Sand Christensen) Date: Fri, 02 Nov 2007 15:34:23 +0100 Subject: Copy database with python.. References: <1194011518.553434.278940@o3g2000hsb.googlegroups.com> <1194013753.923866.131570@o3g2000hsb.googlegroups.com> Message-ID: >>>>> "Abandoned" == Abandoned writes: Abandoned> Yes i understand thank you. Now i find that maybe help the Abandoned> other users. Abandoned> import os Abandoned> os.system("su postgres") Abandoned> ... I get the distinct impression that you're trying to replace simple shell scripting with Python. While it's possible, you're probably making things much more complicated than they need to be. Unless you're actually doing something with all that data of yours, don't use Python where a simple shell script will be much smaller and cleaner. Martin From deliverable at gmail.com Thu Nov 8 10:30:03 2007 From: deliverable at gmail.com (braver) Date: Thu, 08 Nov 2007 15:30:03 -0000 Subject: optional arguments with compact reporting in optparse Message-ID: <1194535803.845082.171590@q5g2000prf.googlegroups.com> Posted to the Optik list, but it seems defunct. Optik is now Python's optparse. I wonder how do you implement optional arguments to Optik. I.e., you can have an option -P [file] -- the filename is optional, with a default "data,pikl". It works as follows: -- if no -P is given, no pickle is written -- if -P is given without the filename following, a pickle file is written with the default name data.pikl -- if -P filename is given, the pickle is written to filename How do we do optional values in Optik, with nargs <= 1? Another question I have it how can I output a docstring right from the parser.add_option() block? I prefer to define all option-related things in the same block once. I'd like to output the help value from the block, or append it to a report. Here's example from my Ruby wrapper for Ruby's optparse: name = :divisor help = "show divisor" short = "-m" opt.on(short, "--#{name} [STR]", help) do |val| hash[:show_divisor] = true hash[:divisor] = val if val end report << [name,short,help] -- notice that my report list is built with the exact values of all options, regardless of whether they're encountered or not. The I simply walk through the report list to print a report for this run: report.each do |name,short,help| val = opts.name || "----" STDERR.printf "--%s (%s)\t\%s\t%s\n", o, short, val, help end if verbose How can I group such reporting together with add_option in Optik? Cheers, Alexy From a.harrowell at gmail.com Fri Nov 23 06:15:36 2007 From: a.harrowell at gmail.com (TYR) Date: Fri, 23 Nov 2007 03:15:36 -0800 (PST) Subject: Python web frameworks References: <226020ef-3955-43e8-b1f6-2ba9ba43d45e@c29g2000hsa.googlegroups.com> <5qga2mFvuljgU1@mid.uni-berlin.de> <160f8bbc-70be-4dcb-8874-de72588c1d10@d61g2000hsa.googlegroups.com> <1b343163-e755-44f8-b5c3-4af56c61e817@c29g2000hsa.googlegroups.com> <93a92a82-cf3c-4ebb-a93f-180374e5f75a@e4g2000hsg.googlegroups.com> <00c0167e-3b4c-4476-b473-1f938a54db63@e1g2000hsh.googlegroups.com> <2672de28-2c94-4967-83f5-18f2823492ee@b15g2000hsa.googlegroups.com> <8adb0024-e74b-4ea9-a819-9da9f64a460a@j20g2000hsi.googlegroups.com> Message-ID: <3fdcc219-71fc-4b00-9f69-823624af5ee9@i29g2000prf.googlegroups.com> On Nov 23, 4:22 am, SamFeltus wrote: > """Perhaps we need a pythonic FRONTEND. """ > > Should have happened years ago. Python Internet Environment: PIE. From paddy3118 at googlemail.com Sat Nov 10 13:05:05 2007 From: paddy3118 at googlemail.com (Paddy) Date: Sat, 10 Nov 2007 10:05:05 -0800 Subject: Returning actual argument expression to a function call? In-Reply-To: References: <1194674580.142801.244840@57g2000hsv.googlegroups.com> Message-ID: <1194717905.581509.73100@22g2000hsm.googlegroups.com> On Nov 10, 3:44 pm, Piet van Oostrum wrote: > With Python this can't be done without either quoting the expression (make > a string out of it) or using a lambda. Lisp and C# can do this kind of thing. I'd like to propose we add '() to Python. Pronounced tick- brackets, it surrounds an expression which is compiled into an anonymous function. I have not thought this through apart from knowing that this is one more step towards Lisp heaven and submit no code as the implementation will be trivial ;-) Of course if my suggestion is not welcomed with open arms then this is Pythons last chance to escape terminal decline.... From arkanes at gmail.com Tue Nov 27 10:53:12 2007 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 27 Nov 2007 09:53:12 -0600 Subject: Why are class methods not classmethods? In-Reply-To: References: Message-ID: <4866bea60711270753l629a85dbhb5e024e5e47ef0ee@mail.gmail.com> On Nov 27, 2007 3:12 AM, Steven D'Aprano wrote: > There's some subtle behaviour going on here that I don't really follow. > Class methods apparently aren't classmethods. > > > >>> class Parrot(object): > ... def method(self, *args): > ... return self, args > ... @classmethod > ... def cmethod(cls, *args): > ... return cls, args > ... > >>> type(parrot.method) # as expected > > >>> type(parrot.cmethod) # I don't expect this result > > >>> type(classmethod(parrot.method)) > > >>> > >>> parrot.cm = classmethod(parrot.method) > >>> type(parrot.cm) # I expect this > > >>> > >>> Parrot.CM = classmethod(parrot.method) > >>> type(Parrot.CM) # but not this > > > > Can anyone explain why class methods bound to a class are instancemethods > rather than classmethods? > > They're instancemethods bound to the type instance, rather than to an instance of the type: >>> c = C() >>> c.method > >>> c.cmethod > >>> So rather than inventing special machinery for classmethods, Python uses the existing instancemethod machinery and just changes the object the instancemethod is bound to. From mwilson at the-wire.com Sun Nov 25 13:54:16 2007 From: mwilson at the-wire.com (Mel) Date: Sun, 25 Nov 2007 13:54:16 -0500 Subject: basic if stuff- testing ranges References: Message-ID: Donn Ingle wrote: > Sheesh, I've been going spare trying to find how to do this short-hand: > if 0 > x < 20: print "within" > > So that x must be > 0 and < 20. > > I usually do: > if x > 0 and x < 20: print "within" > > What's the rule? Does it even exist? if 0 < x < 20: ? Mel. From bignose+hates-spam at benfinney.id.au Tue Nov 13 17:03:51 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 14 Nov 2007 09:03:51 +1100 Subject: [OT] The Jew Spam on this list: Blocking the IP address of spammers References: <5fa6c12e0711130426y2c625e66kdaba332272bc4794@mail.gmail.com> <8a6b8e350711131210w1011a87u23742cf6c6828fc8@mail.gmail.com> Message-ID: <87tznp6bw8.fsf@benfinney.id.au> "Peter J. Bismuti" writes: > Why aren't these spammers having their IP addresses blocked (or > something like that)? People making these posts should not be > allowed to post ever again. Is there not someone administering this > mailing list? "This mailing list" is actually a mail gateway of the Usenet newsgroup, . The spammer you seem to be referring to is posting via Google Groups; please see the header of their messages to find the email address in the 'Complaints-To' field. Their messages are an abuse of Google Groups's terms of service, and Google will likely act on complaints that include a *full* copy of the offending message. -- \ "I was once walking through the forest alone and a tree fell | `\ right in front of me, and I didn't hear it." -- Steven Wright | _o__) | Ben Finney From deliverable at gmail.com Thu Nov 22 08:40:27 2007 From: deliverable at gmail.com (braver) Date: Thu, 22 Nov 2007 05:40:27 -0800 (PST) Subject: the annoying, verbose self References: <3c954a31-9fb9-4c0f-b784-cef9ee057ca6@g30g2000hsb.googlegroups.com> <6332c20d-4b6a-48c5-8151-d3eabaa20b9e@d21g2000prf.googlegroups.com> Message-ID: <1b708206-1d29-4ad1-8eb8-94f4f1bc0526@s12g2000prg.googlegroups.com> On Nov 22, 4:34 pm, Kay Schluehr wrote: > On 22 Nov., 00:51, braver wrote: > > But things grow -- is there any metaprogramming tricks or whatnot we > > can throw on the self? > > http://docs.python.org/lib/compiler.html Indeed. Well, my current solution is to bow to the collective wisdom and retain the self, but type it with just one symbol .-> ... in TextMate, with the Python bundle! (If only TextMate Python bundle woulldn't indent everything it pastes.... And that's how Ruby helps Python -- at the code's very inception TextMate!) Cheers, Alexy From rdm at rcblue.com Sun Nov 18 20:37:42 2007 From: rdm at rcblue.com (Dick Moores) Date: Sun, 18 Nov 2007 17:37:42 -0800 Subject: Help with sympy, please In-Reply-To: <3d0cebfb0711181724w1a674da2sd4cb070f67d844c9@mail.gmail.co m> References: <13k1jg03l3cgdef@corp.supernews.com> <20071119001219.5B7111E4021@bag.python.org> <3d0cebfb0711181626u432dbdd3je049093f5343b716@mail.gmail.com> <20071119010335.D6EE41E43CF@bag.python.org> <3d0cebfb0711181724w1a674da2sd4cb070f67d844c9@mail.gmail.com> Message-ID: <20071119013742.7D6971E4005@bag.python.org> At 05:24 PM 11/18/2007, Fredrik Johansson wrote: >On Nov 19, 2007 2:03 AM, Dick Moores wrote: > > At 04:26 PM 11/18/2007, Fredrik Johansson wrote: > > >On Nov 19, 2007 1:05 AM, Dick Moores wrote: > > >Hi Dick, I recognize you from python-list, where you had a question > > >about mpmath. > > > > > >Your code still won't work if you convert the numbers to Floats > > >because the Float type in sympy.numerics does not implement ** for > > >fractional numbers. You could use the exp function in > > >sympy.numerics.functions instead to compute e**x. > > > > Thanks, Fredrik, but I get the same error using either exp or power: > > ============================ > > from __future__ import division > > from sympy import * > > from sympy import Rational as R > > from sympy.numerics import * > > from sympy.numerics.functions import power, exp > > > > prec = 50 > > Float.setdps(prec) > > e = evalf(E) > > n = 1 > > m = n + 1 > > k = 0 > > n = evalf(R(n,1)) > > m = evalf(R(m,1)) > > prod = evalf(R(1,1)) > > prec = 50 > > Float.setdps(prec) > > e = evalf(E) > > n = 1 > > k = 0 > > prod = evalf(R(1,1)) > > while k < 1000: > > k += 1 > > n = evalf(R(n,1)) > > term = (exp(1/n))/(exp(1/(n+1))) > > prod *= term > > n += 2 > > print prod, term > > ============================= > > term = (exp(1/n))/(exp(1/(n+1))) > > TypeError: unsupported operand type(s) for /: 'int' and 'Float' > > > > And also if I use sympy.numerics.functions.power in that line, as > > term = power(e,(1/n))/power(e,(1/(n+1))) > > > > I get: > > > > term = power(e,(1/n))/power(e,(1/(n+1))) > > TypeError: unsupported operand type(s) for /: 'int' and 'Float' > >Try not using "from __future__ import division". Didn't help. >Also, > > n = evalf(R(n,1)) > >won't work, because the arguments to Rational must be ints. But both n and 1 are ints, aren't they? Anyway, you've by now seen my new success with mpmath. I'll abandon syspy for the time being. Dick From cokofreedom at gmail.com Tue Nov 13 05:58:56 2007 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Tue, 13 Nov 2007 10:58:56 -0000 Subject: Loop three lists at the same time? In-Reply-To: <1194950769.587384.177590@v23g2000prn.googlegroups.com> References: <1194950769.587384.177590@v23g2000prn.googlegroups.com> Message-ID: <1194951536.475479.17090@19g2000hsx.googlegroups.com> On Nov 13, 11:46 am, Davy wrote: > Hi all, > > I have three lists with the same length. Is there any method to loop > the three lists without a loop counter? > > Best regards, > Davy What exactly do you mean? Are you trying to loop them together with the same ?count?. "for loop in zip(1,2,3) kind of thing or something else. Please either post a more descriptive question, or your current code. Coko From hniksic at xemacs.org Fri Nov 30 08:36:17 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 30 Nov 2007 14:36:17 +0100 Subject: Oh no, my code is being published ... help! References: <49adb113-bbaa-4d9f-b3f6-9300d563f2f8@d4g2000prg.googlegroups.com> <89avk3tfjhqoppagt0mi4njolvpbe9lu6m@4ax.com> Message-ID: <87fxyn26um.fsf@mulj.homelinux.net> "Eduardo O. Padoan" writes: > No, writing this way will confound the 2to3 tool. Why? print("foo") is a perfectly valid Python 2 statement. Maybe it's simply a matter of fixing the tool. From ptmcg at austin.rr.com Tue Nov 6 05:30:57 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 06 Nov 2007 02:30:57 -0800 Subject: How to use list as key of dictionary? In-Reply-To: <1194343729.484495.201400@v29g2000prd.googlegroups.com> References: <1194332021.595511.67370@v29g2000prd.googlegroups.com> <1194332941.190425.21090@i38g2000prf.googlegroups.com> <1194339027.038844.22200@v23g2000prn.googlegroups.com> <47303809$0$16661$9b4e6d93@newsspool3.arcor-online.net> <1194343729.484495.201400@v29g2000prd.googlegroups.com> Message-ID: <1194345057.884918.174220@z9g2000hsf.googlegroups.com> On Nov 6, 4:08 am, Dustan wrote: > On Nov 6, 3:58 am, Duncan Booth wrote: > > > Wildemar Wildenburger wrote: > > > maybe something like this could help: > > > > def tupleize(non_tuple): > > > try: > > > return tuple(tupleize(thing) for thing in non_tuple) > > > except TypeError: > > > # non_tuple is not iterable > > > return non_tuple > > > Just don't try passing that a string or anything containing a string. > > Untested > > def tupleize(non_tuple): > if isinstance(non_tuple, str): > return non_tuple > try: > return tuple(tupleize(thing) for thing in non_tuple) > except TypeError: > # non_tuple is not iterable > return non_tuple isinstance(x,basestring) is preferred over isinstance(x,str) in case x is a unicode. -- Paul From nagle at animats.com Thu Nov 22 15:07:53 2007 From: nagle at animats.com (John Nagle) Date: Thu, 22 Nov 2007 12:07:53 -0800 Subject: How to read gzipped utf8 file in Python? Message-ID: <4745e153$0$14127$742ec2ed@news.sonic.net> I have a large (gigabytes) file which is encoded in UTF-8 and then compressed with gzip. I'd like to read it with the "gzip" module and "utf8" decoding. The obvious approach is fd = gzip.open(fname, 'rb',encoding='utf8') But "gzip.open" doesn't support an "encoding" parameter. (It probably should, for consistency.) Is there some way to do this? Is it possible to express "unzip, then decode utf8" via "codecs.open"? John Nagle From tjreedy at udel.edu Sat Nov 10 01:19:08 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 10 Nov 2007 01:19:08 -0500 Subject: How to link different site-packages to different Python? References: <1194603553.861256.56380@i13g2000prf.googlegroups.com> <47344c58$1_7@news.bluewin.ch> Message-ID: "Boris Borcic" wrote in message news:47344c58$1_7 at news.bluewin.ch... | If your lazyness isn't caused by your impatience, From robert.kern at gmail.com Tue Nov 13 17:36:30 2007 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 13 Nov 2007 16:36:30 -0600 Subject: NumPy Question - numpy.put in multi-dimensional array In-Reply-To: <1194981752.080834.255380@19g2000hsx.googlegroups.com> References: <1194981752.080834.255380@19g2000hsx.googlegroups.com> Message-ID: Bryan.Fodness at gmail.com wrote: > from numpy import * > > a = zeros((2,40), int) > > fields = {} > field = 10 > fields[field] = '30A', 5 > > iy = int(fields[field][1]) > ix = int(fields[field][0].rstrip('AB')) > > for i in range(2): > for j in range(iy): > # put(a,[39 - j],[1]) #1d > > Can someone help me figure out how I would do it for multiple rows? numpy questions are best asked on the numpy mailing list. http://www.scipy.org/Mailing_Lists > I thought, > > put(a,[i][39-j],[1]) > > but, > > Traceback (most recent call last): > put(a,[i][39 - j],[1]) > IndexError: list index out of range In this case, you don't really want put(). Just use indexing: for i in range(2): for j in range(iy): a[i,39-j] = 1 -- 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 kay.schluehr at gmx.net Tue Nov 13 04:54:06 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Tue, 13 Nov 2007 01:54:06 -0800 Subject: 2007.comp.lang.python In-Reply-To: <1194932118.165518.316270@t8g2000prg.googlegroups.com> References: <1194932118.165518.316270@t8g2000prg.googlegroups.com> Message-ID: <1194947646.161158.233200@v65g2000hsc.googlegroups.com> Is this headline a demand for Ruby style DSLs in Python? From duncan.booth at invalid.invalid Fri Nov 9 04:17:18 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 9 Nov 2007 09:17:18 GMT Subject: Some "pythonic" suggestions for Python References: <5PGdnWmWZIdZ967anZ2dnUVZ_uuqnZ2d@cavtel.net> <13j76merr3an4d0@corp.supernews.com> Message-ID: Steven D'Aprano wrote: > Besides, if you want this behaviour, you can add it yourself: > > class mylist(list): > # Untested! > def __getitem__(self, index): > if type(index) is list: > return [self[i] for i in index] > return super(mylist, self).__getitem__(index) > > list = mylist It works very nicely, just don't try passing it a recursive list. :) From __peter__ at web.de Mon Nov 26 14:26:27 2007 From: __peter__ at web.de (Peter Otten) Date: Mon, 26 Nov 2007 20:26:27 +0100 Subject: better way to write this function References: <4b4d9cc5-3759-421e-b3a2-3cb25bdaae7a@b40g2000prf.googlegroups.com> Message-ID: Peter Otten wrote: >>>> def chunks(items, n): > ... return [items[start:start+n] for n in range(0, len(items)-n+1, n)] Ouch, this should be def chunks(items, n): return [items[start:start+n] for start in range(0, len(items)-n+1, n)] Peter From kyosohma at gmail.com Tue Nov 6 15:36:02 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 06 Nov 2007 20:36:02 -0000 Subject: How do I get the PC's Processor speed? In-Reply-To: References: <1194376737.430731.60750@o80g2000hse.googlegroups.com> <1194379931.259532.198930@z9g2000hsf.googlegroups.com> Message-ID: <1194381362.828736.230960@o38g2000hse.googlegroups.com> On Nov 6, 2:27 pm, "Chris Mellon" wrote: > On Nov 6, 2007 2:12 PM, wrote: > > > > > On Nov 6, 1:35 pm, "Chris Mellon" wrote: > > > > On Nov 6, 2007 1:18 PM, wrote: > > > > > Hi, > > > > > We use a script here at work that runs whenever someone logs into > > > > their machine that logs various bits of information to a database. One > > > > of those bits is the CPU's model and speed. While this works in 95% of > > > > the time, we have some fringe cases where the only thing returned is > > > > the processor name. We use this data to help us decide which PCs need > > > > to be updated, so it would be nice to have the processor speed in all > > > > cases. > > > > > Currently, this script is run on Windows boxes only, most of which > > > > have Windows XP on them. Right now I am having Python check the > > > > following registry key for the CPU info: HKEY_LOCAL_MACHINE\HARDWARE\ > > > > \DESCRIPTION\\System\\CentralProcessor\\0 > > > > > I've also used Tim Golden's WMI module like so: > > > > > > > > > > import wmi > > > > c = wmi.WMI() > > > > for i in c.Win32_Processor (): > > > > cputype = i.Name > > > > > > > > > > On the problem PCs, both of these methods give me the same information > > > > (i.e. only the processor name). However, if I go to "System > > > > Properties" and look at the "General" tab, it lists the CPU name and > > > > processor speed. Does anyone else know of another way to get at this > > > > information? > > > > You'd want the MaxClockSpeed property. There's a few other clock speed > > > properties as well, seehttp://msdn2.microsoft.com/en-us/library/aa394373.aspx. > > > > MSDN should always be your first stop with WMI questions, by the way. > > > That's true, but I didn't just use WMI to try to get this information. > > I also looked in the registry...although I forgot to mention that I > > used the _winreg module to do so. > > > I did see that when I looked at Microsoft's Python scripts here: > >http://www.microsoft.com/technet/scriptcenter/scripts/python/pyindex.... > > > MaxClockSpeed doesn't report the speed the same way MS does in the > > System Properties, but I suppose I can work around that. Although this > > will make AMD 3800+ procs look much slower (i.e. 2.4 Ghz in this > > case). > > System Properties probably uses current clock speed, which will > usually be lower than max clock speed on modern processors, which > scale their speed with load. I don't think so. For example, my PC has an "AMD Athlon(tm) 64 Processor 3800+", which is what's reported in System Properties. On one of the problem PCs, System Properties lists it as "AMD Athlon(tm) 1.73 Ghz". The 3800+ on my machine is reflected in the registry key I mentioned and WMI also finds that somewhere. But the 1.73 Ghz is in neither of these places. However, using MaxClockSpeed and dividing by 1000 along with some string manipulation gets me closer...although I think this may cause potential problems. Thanks for the feedback. Mike From kyosohma at gmail.com Mon Nov 5 12:16:17 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 05 Nov 2007 17:16:17 -0000 Subject: wxPython ListCtrl In-Reply-To: <1194282029.133610.137730@d55g2000hsg.googlegroups.com> References: <1194282029.133610.137730@d55g2000hsg.googlegroups.com> Message-ID: <1194282977.200567.128010@z9g2000hsf.googlegroups.com> On Nov 5, 11:00 am, vedrandeko... at v-programs.com wrote: > Hello, > > How can I Insert image with string in ListCtrl with this example: > > # Import ftputil module - like ftplib > from ftputil import FTPHost > # Create connection > ftp=FTPHost("ftp.someserver.com","user","password") > > # LIST ALL FILES/FOLDERS ON SERVER > for item in ftp._dir("/"): > # Now check if item is file /folder > if item is file insert this image: wx.ART_NORMAL_FILE and if > the item is folder insert this image > wx.ART_FOLDER > > .......how can I do the same on server with GenericDirCtrl? > > Regards, > Vedran I would recommend looking at the wxPython demo as it shows how to add pictures to the listctrl there. You'll probably need to look at wx.ArtProvider to get the correct syntax for using its images: http://wxpython.org/docs/api/wx.ArtProvider-class.html You might also find the wiki's entry on listctrls helpful: http://wiki.wxpython.org/ListControls Of course, it sounds like you're making your own FTP client, so I would use one of the treectrl variants rather than a listctrl. See the TreeListCtrl, the TreeMixin or the CustomTreeCtrl. The demo also shows code for the GenericDirCtrl. See http://www.wxpython.org/download.php You may also find the wxPython user's group more helpful for wxPython specific inquiries: http://www.wxpython.org/maillist.php Mike From gagsl-py2 at yahoo.com.ar Fri Nov 9 22:21:10 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 10 Nov 2007 00:21:10 -0300 Subject: python - stealth window References: <33e619fa0711072223s3aebf56bt92b49aa54647116d@mail.gmail.com> Message-ID: En Thu, 08 Nov 2007 03:23:27 -0300, Adam escribi?: > I want create Windows console window in stealth with Python script. I > tried > search on internet but I do not find anything. I want something like this > just it is in C++: > > HWND stealth; /*creating stealth (window is not visible)*/ > AllocConsole(); > stealth=FindWindowA("ConsoleWindowClass",NULL); > ShowWindow(stealth,0); > > So I start my script and that is will be run in the background and I can > trick with "hotkeys" in WINAMP. I do not worry for a new one window. :-) > I > hope you understand me because my english is not perfect. Using the pywin32 packages from Mark Hammond, this is a direct translation of the above: import win32console, win32gui win32console.AllocConsole() stealth = win32gui.FindWindow("ConsoleWindowClass", None) win32gui.ShowWindow(stealth, 0) import time time.sleep(5) win32gui.ShowWindow(stealth, 1) You must either run it using pythonw.exe, or remove the AllocConsole call -- Gabriel Genellina From horpner at yahoo.com Sun Nov 4 21:49:38 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Mon, 05 Nov 2007 02:49:38 GMT Subject: Is pyparsing really a recursive descent parser? References: <5p0dhgFnj4rbU1@mid.uni-berlin.de> <1194007658.200713.178210@57g2000hsv.googlegroups.com> <1194104971.263256.66640@d55g2000hsg.googlegroups.com> <43rXi.397547$6L.130044@fe03.news.easynews.com> <1194223837.104424.242360@o3g2000hsb.googlegroups.com> Message-ID: <6xvXi.39855$G23.18679@newsreading01.news.tds.net> On 2007-11-05, Just Another Victim of the Ambient Morality wrote: > > "Kay Schluehr" wrote in message > news:1194223837.104424.242360 at o3g2000hsb.googlegroups.com... >> On Nov 4, 10:44 pm, "Just Another Victim of the Ambient Morality" >> >> >>> I believe there is a cure and it's called recursive descent parsing. >>> It's slow, obviously, but it's correct and, sometimes (arguably, often), >>> that's more important the execution speed. >> >> Recursive decendent parsing is not necessarily slow but from your >> remarks above I infer you want a general RD parser with backtracking: >> when one rule doesn't match, try another one to derive the current >> symbol in the input stream. > > I think I've just discovered a major hurdle in my understand of the > problem. > You keep saying "with backtracking." Why? Isn't "backtracking" > inherent in recursion? So, why can't these alleged "recursive descent > parsers" find valid parsings? How are they not already backtracking? What > was the point of being recursive if not to take advantage of the inherent > backtracking in it? > Obviously, these parsers aren't recursing through what I think they > should be recursing. The question is "why not?" There are different kinds of recursion. Compare: def fac1(x, y=1): """ Compute factorials with a recursive function (it calls itself), but the stack is not actually used for storing anything important, i.e., it is tail-recursive. """ if x < 0: raise ValueError('non-negative integer') elif x == 0: return y else: return fac1(x-1, y*x) to def fac2(x): """ Computes factorials with a recursive process, keeping the state of the calculation on the stack. """ if x < 0: raise ValueError('non-negative integer') if x == 0: return 1 else: return fac2(x-1) * x to def Ack(x, y): """ The Ackermann function. Creates a humongous mess even with quite tiny numbers. """ if x < 0 or y < 0: raise ValueError('non-negative integer') elif x == 0: return y + 1 elif y == 0: return foo3(x-1, 1) else: return foo3(x-1, foo3(x, y-1)) There's probably a word for the type of recursive process built by fac2; the RDP's I'm most familiar with create a fac2 sort of process, which stores valuable info on the stack. And even though fac1 defines an iterative process, the code itself is recursive, and you can call it a recursive function if you wish (and in Python you might as well). > Correct me if I'm wrong but I'm beginning to think that > pyparsing doesn't typically use recursion, at all. It only > employs it if you create one, using the Forward class. > Otherwise, it does everything iteratively, hence the lack of > "backtracking." It's recursive because each production rule calls other production rules to define itself. A rule regularly ends up calling itself. Consider the Parser class I built earlier. list_tail keeps calling itself to continue consuming characters in an ab_list. The stack is used to keep track of where we are in the grammar; at any time you can look up the stack and see how you got where you are--you 'descend' down from the topmost productions to the most primitive productions, and then back up once everything has been sorted out. Take another look at the exception raised in my Parsing class example for an illustrative traceback. >> I'm not sure one needs to start again with a naive approach just to >> avoid any parser theory. For a user of a parser it is quite important >> whether she has to wait 50 seconds for a parse to run or 50 >> milliseconds. I don't like to compromise speed for implementation >> simplicity here. > > Finally, I can't believe you complain about potential speed > problems. First, depending on the size of the string, it's > likely to be the difference between 2ms and 200ms. Secondly, > if speed were an issue, you wouldn't go with a recursive > descent parser. You'd go with LALR or the many other parsing > techniques available. Recursive descent parsing is for those > situations where you need correctness, regardless of execution > time. These situations happen... RDP is plenty fast; speed has never been one of it's disadvantages, as far as I know. Today there are many excellent parser generators and compiler builders that compose an RDP under the hood, e.g., Antlr and Gentle. > I've said this before, albeit for a different language, but > it applies to Python just as well. I don't use Python to write > fast code, I use it to write code fast. > If _you_ "don't like to compromise speed for implementation > simplicity" then you have a plethora choices available to you. > What about the guy who needs to parse correctly and is > unconcerned about speed? You have to be concerned about speed when something runs so slowly in common circumstances compared to other well-known algotithms that you can't practically wait for an answer. Would you consider bubble-sort a suitable general-purpose sorting algorithm for Python? -- Neil Cerutti From hat at se-162.se.wtb.tue.nl Thu Nov 29 11:16:51 2007 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Thu, 29 Nov 2007 17:16:51 +0100 Subject: How to suggest a new Python list? Was: Science list References: Message-ID: On 2007-11-29, J. Robertson wrote: > Francesco Pietra wrote: >> I was trying to suggest a more specific mail-list in order not to be floaded. I >> am the opinion that python-list at python.org is very informative and useful, >> though it is hard to find the time for so many mails. >> f. >> > > I agree with Francesco: Python is increasingly used in sciences (or, at > least, I use it increasingly :-) and it would be of some use to have a > communication channel focused on this: there are a few mailing lists for > specific niche topics (CAD, XML) already, so sciences could be one more. So what is the focus in the list? I think 'science' is both too broad and in many cases not at all relevant for the problem at hand. For example, Should I be a scientist before I can post there? (If yes, what about: I work as supporting staff, am a PhD student, am a regular student, have a home work question, think of going to college, just learning Python that I may need at school). Any particular brand of science (CS, Math, Physics, Bio, Chemistry, other)? Should I use Python for programming a science problem? Should I have a problem in science and want to use Python for solving it? How are science problems any different from 'normal' problems? I am writing a parser for a language used in science, can I put it there? (and if yes, how is that different from writing a language for a non-science problem?) I am trying to run program XYZ as a sub-shell, or in a thread, or distributed. Does it make any difference whether XYZ solves a science problem or not? I don't see a clear useful line called 'science', but YMMV. > Some folks that do not want to be flooded by 200 posts/day are going to > pop up there and explain how they replaced 60,000 lines of FORTRAN by > 100 lines of Python in one afternoon (before the tea break), surely that > can't hurt. If the sheer number of posts is a problem, skip subjects that you don't like, just like everybody else. If your mailinglist idea fails you have a nicely quiet corner (but is otherwise useless). That is however more easily achieved by not reading c.l.p. If it succeeds, you may easily get the same amount of traffic as you have now here. So how is 'science' here a good criterium? > Anyway, I do not see how to suggest a new mailing list on > http://www.python.org/community/lists/ - does anyone know? Ask at c.l.p. ? :) Albert From tjreedy at udel.edu Thu Nov 29 18:36:39 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 29 Nov 2007 18:36:39 -0500 Subject: Variables and their domain References: <007b01c8327c$9fcffa40$2000a8c0@depid.local> Message-ID: "Jose Ignacio Gisbert" wrote in message news:007b01c8327c$9fcffa40$2000a8c0 at depid.local... | I have one doubt, in my applciation I have a method (Method1) which has | other method (Method2) inside of it. You have a function inside a function. In Python, methods are functions bound to classes. | Method1 | Lista=a,b,c,d. That makes a tuple, not a list. Do lista = [a,b,c,d] to make a list that you can modify inside an inner function using item or slice assignment or modify-in-place methods | Lb=listbox | Method2 | Lista=e,f,g.. -->error! lista[:] = [e,f,g] will replace the contents of lista Good luck. tjr From namesagame-usenet at yahoo.com Tue Nov 13 18:00:35 2007 From: namesagame-usenet at yahoo.com (gamename) Date: Tue, 13 Nov 2007 23:00:35 -0000 Subject: Equivalent of TCL's "subst" ? Message-ID: <1194994835.078939.112210@k79g2000hse.googlegroups.com> Hi, In TCL, you can do things like: set foobar "HI!" set x foo set y bar subst $$x$y HI! Is there a way to do this type of evaluation in python? TIA, -T From mensanator at aol.com Sat Nov 17 02:14:26 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Fri, 16 Nov 2007 23:14:26 -0800 (PST) Subject: What is python????? References: <7ab5b781-3c6c-4fb5-9be1-703d5e7e73a6@s12g2000prg.googlegroups.com> <959349ce-34ad-4d8e-aea0-b7bcbbc6112f@f13g2000hsa.googlegroups.com> <4a92044d-ef1b-47b0-82e0-45946e08a794@n20g2000hsh.googlegroups.com> Message-ID: <828cecd6-40b9-4aaf-bb07-8386b6c7518e@f3g2000hsg.googlegroups.com> On Nov 16, 3:10?pm, Alan wrote: > On Nov 16, 8:29 pm, kyoso... at gmail.com wrote: > > > I still don't get it and I've been haunting this group for months... > > > Mike > > Go on then ?... > > What ? > > The punchline, do the punchline Punchline? I don't think there's a punchline scheduled, is there? Where are we? A week 39.4 ...no, it's Friday, isn't it - 39.7. Oh...here we are. Oh! Ha, ha, ha, very good. Ha, ha, ha, very good. What a good punchline. Pity we missed that. > > -- > Alan From arkanes at gmail.com Tue Nov 13 16:31:17 2007 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 13 Nov 2007 15:31:17 -0600 Subject: private data stashed in local/global execution context of PyEval_EvalCode disappears down the execution stack In-Reply-To: <1194988694.381313.202490@v65g2000hsc.googlegroups.com> References: <1194402317.678614.142450@y42g2000hsy.googlegroups.com> <1194988694.381313.202490@v65g2000hsc.googlegroups.com> Message-ID: <4866bea60711131331x39a05a93v12b6c77903101ef@mail.gmail.com> On Nov 13, 2007 3:18 PM, wrote: > On Nov 9, 5:36 pm, "Gabriel Genellina" wrote: > > En Tue, 06 Nov 2007 23:25:17 -0300, escribi?: > > > One should make a lot of assumptions about your code because it's not > > complete. Please post a minimal complete example showing your problem. > > > It's a rather large program. My assumption was that just posting the > snippet around the call site and the callee pathetic attempt > to extract interp would be sufficient :( > The creation of a minimal runnable sample is a fantastic way to find any bugs in your code, and has the benefit of (if the bug is not in your code) giving other people a simple way to recreate the bug. If I were to check this (and I'm not, but I would if you'd posted runnable code) I'll have to write the code myself from your textual description. Then, if the code works, I'll have to post the code that I wrote as well as my negative response, and go through several back and forths trying to isolate any differences between what I wrote and what you wrote but didn't show. That's way more work than I'm willing to do to solve someone else's problem. In my experience, creating a minimal sample that demonstrates the bug will lead you to the actual bug more than half the time. That's a lot of time (yours and other peoples) that can be saved if you do it. From kw at codebykevin.com Mon Nov 5 09:34:09 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Mon, 05 Nov 2007 09:34:09 -0500 Subject: PyObjC with Xcode 3.0 Leopard In-Reply-To: <1194247944.398414.262030@z24g2000prh.googlegroups.com> References: <1194247944.398414.262030@z24g2000prh.googlegroups.com> Message-ID: <472F29E1.5090900@codebykevin.com> flyfree wrote: > I got an error during making a python application with xcode 3.0 in OS > X Leopard. > > (KeyError: 'NSUnknownKeyException - [ > valueForUndefinedKey:]: this class is not key value coding-compliant > for the key calculatedMean.') > > The application is a simple example of how to use the PyObjC with > xcode 2.0. > http://developer.apple.com/cocoa/pyobjc.html > > Could you give any hint to start to dig into it? > The PythonMac or PyObjc lists are probably a better place to ask this kind of question. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From ark at acm.org Sun Nov 25 14:51:08 2007 From: ark at acm.org (Andrew Koenig) Date: Sun, 25 Nov 2007 19:51:08 GMT Subject: How to Teach Python "Variables" References: <4749bb94$1@news.bezeqint.net> <4749c888$0$14869$426a74cc@news.free.fr> Message-ID: "Aur?lien Camp?as" wrote in message news:4749c888$0$14869$426a74cc at news.free.fr... > I mean : aren't C variables also bindings from names to objects ? Or what > ? No, they're not. In C, when you execute x = y; you cause x to become a copy of y. In Python, when you execute x = y you cause x and y to be two different names for the same object. It is difficult to distinguish these cases unless the objects in question are mutable, so consider this C example: struct {int a, b;} x = {3, 4}, y = x; x.a = 42 printf ("%d, %d\n", y.a, y.b); and the following apparently analogous Python example: x = [3, 4] y = x x[0] = 42 print y Try them both and see how they behave. From software at ginstrom.com Fri Nov 2 03:04:50 2007 From: software at ginstrom.com (Ryan Ginstrom) Date: Fri, 2 Nov 2007 16:04:50 +0900 Subject: posting to a form with no form name In-Reply-To: <1193985868.984883.44990@d55g2000hsg.googlegroups.com> References: <1193985868.984883.44990@d55g2000hsg.googlegroups.com> Message-ID: <021301c81d1e$a9b8e3f0$0203a8c0@MOUSE> > On Behalf Of scripteaze at gmail.com > posting to a form with no form name or it's just that i cant > find the form name. > can anyone explain how to either post to a form with no name > or, find the name of the form..here my current output, but i > dont see a form name, also, there is only 1 form on the page I believe you want Browser.select_form(nr=0) # Using mechanize # http://wwwsearch.sourceforge.net/mechanize/ from mechanize import Browser browser = Browser() browser.open("http://example.com") browser.select_form(nr=0) browser['username'] = "me" browser['password'] = "secret" browser.submit() Regards, Ryan Ginstrom From Moh989 at gmail.com Thu Nov 15 18:45:02 2007 From: Moh989 at gmail.com (Mohammed_M) Date: Thu, 15 Nov 2007 15:45:02 -0800 (PST) Subject: Printing user input? References: <46e7af01-5cf6-4f7a-926f-73a3ecc0db47@v4g2000hsf.googlegroups.com> Message-ID: <6e512ef9-48d6-4202-8338-4980d45c194b@l22g2000hsc.googlegroups.com> Thanks Mike, Lorenzo & Cliff for your replies. I definately will be reading up on namespaces & scopes. Thanks again guys :) From odonnems at yahoo.com Mon Nov 19 16:07:28 2007 From: odonnems at yahoo.com (Michael ODonnell) Date: Mon, 19 Nov 2007 13:07:28 -0800 (PST) Subject: weave and compiler install help Message-ID: <50207.86115.qm@web58002.mail.re3.yahoo.com> I am trying to compile some inline c++ code inside python using weave. I always get a similar problem where the compiled file cannot be found (see below). I am not sure if the problem is with the compiler or something else. I am a new user of scipy and a novice with python so I would appreciate any direction someone can give me because I have not been able to figure out a work around. PS. I have also posted this on scipy list and have not received any feedback. Thank you, Michael +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ I have the following related applications installed: +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Python: 2.4.1 (I am using an older version because this is what ESRI GIS application supports) Scipy: scipy-0.6.0.win32-py2.4.exe MinGW: MinGW-5.1.3.exe gcc-4.1.2-mingw-setup.exe cygwin: 3.2.25 OS: Windows XP SP2 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ When I test the installation of Weave I get the following output: +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ >>> weave.test() Found 1 tests for scipy.weave.ast_tools Found 2 tests for scipy.weave.blitz_tools Found 9 tests for scipy.weave.build_tools Found 0 tests for scipy.weave.c_spec Found 26 tests for scipy.weave.catalog building extensions here: c:\docume~1\michael\locals~1\temp\Michael\python24_compiled\m3 Found 1 tests for scipy.weave.ext_tools Found 0 tests for scipy.weave.inline_tools Found 74 tests for scipy.weave.size_check Found 16 tests for scipy.weave.slice_handler Found 3 tests for scipy.weave.standard_array_spec Found 0 tests for __main__ ...warning: specified build_dir '_bad_path_' does not exist or is not writable. Trying default locations .....warning: specified build_dir '_bad_path_' does not exist or is not writable. Trying default locations ............................removing 'c:\docume~1\michael\locals~1\temp\tmpdqudhmcat_test' (and everything under it) error removing c:\docume~1\michael\locals~1\temp\tmpdqudhmcat_test: c:\docume~1\michael\locals~1\temp\tmpdqudhmcat_test\win3224compiled_catalog: Permission denied error removing c:\docume~1\michael\locals~1\temp\tmpdqudhmcat_test: c:\docume~1\michael\locals~1\temp\tmpdqudhmcat_test: Directory not empty .removing 'c:\docume~1\michael\locals~1\temp\tmpw144aycat_test' (and everything under it) ............................................................................................... ---------------------------------------------------------------------- Ran 132 tests in 2.625s OK +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ When I try to test the following script or any other script I get the following message: +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ def prod(m, v): #C++ version nrows, ncolumns = m.shape res = numpy.zeros((nrows, ncolumns), float) code = r""" for (int i=0; i running build_ext running build_src building extension "sc_045cfaf40ef1a0738b1066aaa886a55d7" sources customize Mingw32CCompiler customize Mingw32CCompiler using build_ext customize Mingw32CCompiler customize Mingw32CCompiler using build_ext building 'sc_045cfaf40ef1a0738b1066aaa886a55d7' extension compiling C++ sources C compiler: g++ -mno-cygwin -O2 -Wall compile options: '-IC:\Python24\lib\site-packages\scipy\weave -IC:\Python24\lib\site-packages\scipy\weave\scxx -IC:\Python24\lib\site-packages\numpy\core\include -IC:\Python24\include -IC:\Python24\PC -c' g++ -mno-cygwin -O2 -Wall -IC:\Python24\lib\site-packages\scipy\weave -IC:\Python24\lib\site-packages\scipy\weave\scxx -IC:\Python24\lib\site-packages\numpy\core\include -IC:\Python24\include -IC:\Python24\PC -c c:\docume~1\michael\locals~1\temp\Michael\python24_compiled\sc_045cfaf40ef1a0738b1066aaa886a55d7.cpp -o c:\docume~1\michael\locals~1\temp\Michael\python24_intermediate\compiler_c8350d870e6c54e8f29dd7094c2bfb45\Release\docume~1\michael\locals~1\temp\michael\python24_compiled\sc_045cfaf40ef1a0738b1066aaa886a55d7.o Traceback (most recent call last): File "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "C:\Documents and Settings\Michael\Application Data\ESRI\ArcToolbox\scripts\test_weave.py", line 179, in ? main() File "C:\Documents and Settings\Michael\Application Data\ESRI\ArcToolbox\scripts\test_weave.py", line 170, in main prod(m, v) File "C:\Documents and Settings\Michael\Application Data\ESRI\ArcToolbox\scripts\test_weave.py", line 44, in prod err = weave.inline(code,['nrows', 'ncolumns', 'res', 'm', 'v'], verbose=2) File "C:\Python24\Lib\site-packages\scipy\weave\inline_tools.py", line 338, in inline auto_downcast = auto_downcast, File "C:\Python24\Lib\site-packages\scipy\weave\inline_tools.py", line 447, in compile_function verbose=verbose, **kw) File "C:\Python24\Lib\site-packages\scipy\weave\ext_tools.py", line 365, in compile verbose = verbose, **kw) File "C:\Python24\Lib\site-packages\scipy\weave\build_tools.py", line 269, in build_extension setup(name = module_name, ext_modules = [ext],verbose=verb) File "C:\Python24\lib\site-packages\numpy\distutils\core.py", line 173, in setup return old_setup(**new_attr) File "C:\Python24\lib\distutils\core.py", line 159, in setup raise SystemExit, error CompileError: error: c:\docume~1\michael\locals~1\temp\tmp2dwbkp: No such file or directory This file is created and automatically opens in python: import os import sys sys.path.insert(0,'C:\\Python24\\lib\\site-packages\\numpy\\distutils') from exec_command import exec_command del sys.path[0] cmd = ['g++', '-mno-cygwin', '-O2', '-Wall', '-IC:\\Python24\\lib\\site-packages\\scipy\\weave', '-IC:\\Python24\\lib\\site-packages\\scipy\\weave\\scxx', '-IC:\\Python24\\lib\\site-packages\\scipy\\weave\\blitz', '-IC:\\Python24\\lib\\site-packages\\numpy\\core\\include', '-IC:\\Python24\\include', '-IC:\\Python24\\PC', '-c', 'c:\\docume~1\\michael\\locals~1\\temp\\Michael\\python24_compiled\\sc_e6928d48a5ee12fb55c3b29ed6bf49ef4.cpp', '-o', 'c:\\docume~1\\michael\\locals~1\\temp\\Michael\\python24_intermediate\\compiler_921933e1c4e3c013306c4ed6f4c15144\\Release\\docume~1\\michael\\locals~1\\temp\\michael\\python24_compiled\\sc_e6928d48a5ee12fb55c3b29ed6bf49ef4.o'] os.environ = {'TMP': 'C:\\WINDOWS\\TEMP', 'COMPUTERNAME': 'ALDER', 'USERDOMAIN': 'ALDER', 'ARCHOME': 'C:\\arcgis\\arcexe9x', 'COMMONPROGRAMFILES': 'C:\\Program Files\\Common Files', 'PROCESSOR_IDENTIFIER': 'x86 Family 6 Model 13 Stepping 8, GenuineIntel', 'PROGRAMFILES': 'C:\\Program Files', 'PROCESSOR_REVISION': '0d08', 'PATH': 'c:\\mingw\\bin;C:\\Program Files\\Common Files\\Roxio Shared\\DLLShared;C:\\arcgis\\arcexe9x\\bin;C:\\Program Files\\FWTools1.2.2\\pymod;C:\\Program Files\\R\\R-2.5.1\\bin;C:\\Documents and Settings\\Michael\\My Documents\\mod_web\\ems_web\\web-content\\mapserver-4.8.1bin;C:\\cygwin\\bin;C:\\program files\\imagemagick-6.3.6-q16;C:\\Python24;C:\\Program Files\\gs\\gs8.51\\lib;C:\\Program Files\\gnuplot\\bin;C:\\ModisTools\\MRT\\bin;C:\\ModisTools\\LDOPE\\LDOPE_Win_bin\\ANCILLARY;C:\\Documents and Settings\\Michael\\My Documents\\my_home\\py_scripting\\src\\tools;C:\\Program Files\\HEG\\HEG_Win\\bin;C:\\Perl\\site\\bin;C:\\Perl\\bin;C:\\WINDOWS\\system32;C:\\WINDOWS;C:\\WINDOWS\\System32\\Wbem;C:\\Program Files\\Microsoft SQL Server\\80\\Tools\\Binn\\;C:\\Program Files\\MySQL\\MySQL Server 5.0\\bin;C:\\Program Files\\QuickTime\\QTSystem;C:\\WINDOWS\\system32\\config\\systemprofile\\Local Settings\\Temp;C:\\ModisTools\\MRT\\bin; C:\\ModisTools\\LDOPE\\LDOPE_Win_bin\\ANCILLARY;C:\\Program Files\\R\\R-2.5.1\\bin;;c:\\Program Files\\HEG\\HEG_Win\\bin;c:\\Program Files\\HEG\\HEG_Win\\bin;c:\\Program Files\\HEG\\HEG_Win\\bin', 'SYSTEMROOT': 'C:\\WINDOWS', 'ATHOME': 'C:\\arcgis\\arcexe9x\\arctools', 'SCRIPTING': 'C:\\Documents and Settings\\Michael\\My Documents\\my_home\\py_scripting', 'ARCHOME_USER': 'C:\\arcgis\\arcexe9x', 'TEMP': 'C:\\DOCUME~1\\Michael\\LOCALS~1\\Temp', 'PROCESSOR_ARCHITECTURE': 'x86', 'ANCPATH': 'C:\\ModisTools\\LDOPE\\LDOPE_Win_bin\\ANCILLARY', 'ALLUSERSPROFILE': 'C:\\Documents and Settings\\All Users', 'SESSIONNAME': 'Console', 'ARCINFOFONTSIZE': '8', 'HOMEPATH': '\\Documents and Settings\\Michael', 'USERNAME': 'Michael', 'LOGONSERVER': '\\\\ALDER', 'COMSPEC': 'C:\\WINDOWS\\system32\\cmd.exe', 'QTJAVA': 'C:\\Program Files\\Java\\jre1.6.0_01\\lib\\ext\\QTJava.zip', 'PYTHONPATH': 'C:\\Program Files\\ArcGIS\\bin;C:\\Python24\\Lib\\site-packages\\gdal;C:\\Program Files\\R\\R-2.5.1\\bin;C:\\Documents and Settings\\Michael\\My Documents\\my_home\\py_scripting\\src\\tools;C:\\Documents and Settings\\Michael\\My Documents\\my_home\\py_scripting\\lib;C:\\WINDOWS\\system32\\config\\systemprofile\\Local Settings\\Temp;C:\\cygwin\\bin;C:\\mingw\\bin;c:\\mingw\\bin;C:\\Program Files\\Common Files\\Roxio Shared\\DLLShared;C:\\arcgis\\arcexe9x\\bin;C:\\Program Files\\FWTools1.2.2\\pymod;C:\\Program Files\\R\\R-2.5.1\\bin;C:\\Documents and Settings\\Michael\\My Documents\\mod_web\\ems_web\\web-content\\mapserver-4.8.1bin;C:\\cygwin\\bin;C:\\program files\\imagemagick-6.3.6-q16;C:\\Python24;C:\\Program Files\\gs\\gs8.51\\lib;C:\\Program Files\\gnuplot\\bin;C:\\ModisTools\\MRT\\bin;C:\\ModisTools\\LDOPE\\LDOPE_Win_bin\\ANCILLARY;C:\\Documents and Settings\\Michael\\My Documents\\my_home\\py_scripting\\src\\tools;C:\\Program Files\\HEG\\HEG_Win\\bin;C:\\Perl\\site\\bin;C:\\Perl\\bin;C:\\WINDOWS\\system32;C:\\WINDOWS;C:\\WINDOWS\\System32\\Wbem;C:\\Program Files\\Microsoft SQL Server\\80\\Tools\\Binn\\;C:\\Program Files\\MySQL\\MySQL Server 5.0\\bin;C:\\Program Files\\QuickTime\\QTSystem;%USERPROFILE%\\Local Settings\\Temp;', 'CLASSPATH': '.;C:\\Program Files\\Java\\jre1.6.0_01\\lib\\ext\\QTJava.zip', 'PLAT': 'win32', 'PYTHONSRC': 'C:\\Python24', 'PGSHOME': 'c:\\Program Files\\HEG\\HEG_Win\\TOOLKIT_MTD', 'PATHEXT': '.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.py;.pdf', 'CLIENTNAME': 'Console', 'FP_NO_HOST_CHECK': 'NO', 'WINDIR': 'C:\\WINDOWS', 'APPDATA': 'C:\\Documents and Settings\\Michael\\Application Data', 'HOMEDRIVE': 'C:', 'ARCINFOFONTNAME': 'Courier New', 'SYSTEMDRIVE': 'C:', 'NUMBER_OF_PROCESSORS': '1', 'ARCGISHOME': 'C:\\Program Files\\ArcGIS\\', 'MRTBINDIR': 'c:\\Program Files\\HEG\\HEG_Win\\bin', 'PROCESSOR_LEVEL': '6', 'MRTDATADIR': 'C:\\ModisTools\\MRT\\data', 'OS': 'Windows_NT', '__COMPAT_LAYER': 'EnableNXShowUI ', 'USERPROFILE': 'C:\\Documents and Settings\\Michael'} s,o = exec_command(cmd, _with_python=0, **{}) f=open('c:\\docume~1\\michael\\locals~1\\temp\\tmp0gk0g_',"w") f.write(str(s)) f.close() f=open('c:\\docume~1\\michael\\locals~1\\temp\\tmpadrrdg',"w") f.write(o) f.close() ____________________________________________________________________________________ Be a better sports nut! Let your teams follow you with Yahoo Mobile. Try it now. http://mobile.yahoo.com/sports;_ylt=At9_qDKvtAbMuh1G1SQtBI7ntAcJ -------------- next part -------------- An HTML attachment was scrubbed... URL: From duncan.booth at invalid.invalid Fri Nov 16 08:31:03 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 16 Nov 2007 13:31:03 GMT Subject: Looking for docs References: Message-ID: Donn Ingle wrote: > Hi, > I have seen strange looking things in various Python code like: > staticmethod and also lines starting with an @ sign, just before > method defs - I can't find an example right now. > I have Python 2.5 installed with it's docs, but I can't find any > discussion > of 'new style' classes and other info. > > I'm not even sure what subject that @ sign stuff falls under. > > Anyone have a link? > http://www.python.org/doc/2.4.4/whatsnew/node6.html http://www.python.org/dev/peps/pep-0318/ From python.list at tim.thechases.com Sun Nov 18 07:40:30 2007 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 18 Nov 2007 06:40:30 -0600 Subject: keyword parameter order In-Reply-To: References: Message-ID: <474032BE.2040009@tim.thechases.com> > I am looking for a way to determine the order of keyword parameters > passed on to a class method. I'm fairly certain it's not possible, as how would code like this behave: def my_func(**kwd): kwd = OrderedDict(kwd) #magic happens here? return do_something(kwd) my_dict = {'hello':42, 'world':3.14159} print my_func(**my_dict) This is regularly used in lots of code. The ordering of the contents of my_dict is already lost before the my_func() ever gets a chance to see it. And in case one suggests trying to sniff the source-code for the ordering, it's easy to break with things like my_dict = read_dict_from_file(get_filename_from_user()) where the dict and its source are completely outside the scope of the code. The only way around it I see is to force the user to pass in an ordered dict explicitly: def my_func(ordered_dict_of_kwdargs): return do_something(ordered_dict_of_kwdargs) my_dict = OrderedDict() my_dict['hello'] = 42 my_dict['world'] = 3.14159 print my_func(my_dict) -tkc From f.braennstroem at gmx.de Wed Nov 21 16:05:16 2007 From: f.braennstroem at gmx.de (Fabian Braennstroem) Date: Wed, 21 Nov 2007 21:05:16 +0000 Subject: regex problem with re and fnmatch In-Reply-To: References: Message-ID: Hi John, John Machin schrieb am 11/20/2007 09:40 PM: > On Nov 21, 8:05 am, Fabian Braennstroem wrote: >> Hi, >> >> I would like to use re to search for lines in a files with >> the word "README_x.org", where x is any number. >> E.g. the structure would look like this: >> [[file:~/pfm_v99/README_1.org]] >> >> I tried to use these kind of matchings: >> # org_files='.*README\_1.org]]' >> org_files='.*README\_*.org]]' >> if re.match(org_files,line): > > First tip is to drop the leading '.*' and use search() instead of > match(). The second tip is to use raw strings always for your > patterns. > >> Unfortunately, it matches all entries with "README.org", but >> not the wanted number!? > > \_* matches 0 or more occurrences of _ (the \ is redundant). You need > to specify one or more digits -- use \d+ or [0-9]+ > > The . in .org matches ANY character except a newline. You need to > escape it with a \. > >>>> pat = r'README_\d+\.org' >>>> re.search(pat, 'xxxxREADME.org') >>>> re.search(pat, 'xxxxREADME_.org') >>>> re.search(pat, 'xxxxREADME_1.org') > <_sre.SRE_Match object at 0x00B899C0> >>>> re.search(pat, 'xxxxREADME_9999.org') > <_sre.SRE_Match object at 0x00B899F8> >>>> re.search(pat, 'xxxxREADME_9999Zorg') >>>> Thanks a lot, works really nice! >> After some splitting and replacing I am able to check, if >> the above file exists. If it does not, I start to search for >> it using the 'walk' procedure: > > I presume that you mean something like: """.. check if the above file > exists in some directory. If it does not, I start to search for it > somewhere else ...""" > >> for root, dirs, files in >> os.walk("/home/fab/org"): > >> for name in dirs: >> dirs=os.path.join(root, name) + '/' > > The above looks rather suspicious ... > for thing in container: > container = something_else > ???? > What are you trying to do? > > >> for name in files: >> files=os.path.join(root, name) > > and again .... > >> if fnmatch.fnmatch(str(files), "README*"): > > Why str(name) ? > >> print "File Found" >> print str(files) >> break > > > fnmatch is not as capable as re; in particular it can't express "one > or more digits". To search a directory tree for the first file whose > name matches a pattern, you need something like this: > def find_one(top, pat): > for root, dirs, files in os.walk(top): > for fname in files: > if re.match(pat + '$', fname): > return os.path.join(root, fname) > > >> As soon as it finds the file, > > "the" file or "a" file??? > > Ummm ... aren't you trying to locate a file whose EXACT name you found > in the first exercise?? > > def find_it(top, required): > for root, dirs, files in os.walk(top): > if required in files: > return os.path.join(root, required) Great :-) Thanks a lot for your help... it can be so easy :-) Fabian From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Tue Nov 20 10:05:12 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Tue, 20 Nov 2007 16:05:12 +0100 Subject: Web update library in python? References: <5qfu1mFv5oirU1@mid.uni-berlin.de> Message-ID: <5qgbd8FvsvaaU1@mid.individual.net> Jorgen Bodde wrote: > There are two roles: > > Repository maintainer: > ----- > - Developer of the 'repository' creates a snapshot > - This archive is uploaded on his private site > - A file that accompanies the archive containing the list of > updates is sent last > > Repository updater: > ----- > - Downloads the accompanying file > - If the accompanying file is valid (I agree upon uploading this > small file can be downloaded, but since it is a small text file I > would not consider this a huge risk) > - Downloads the archive that was put there earlier Still, subversion would let you accomplish this. Also I wonder where you'd like to save state information in downloaded copies -- that's what subversion does in .svn directories. You have to save the state to update economically. > It might not be a 100% secure methodology, but I won't claim I get > thousands of hits per hour to begin with, Do you mean "security" or "reliability"? > But I guess I am defending my way of solving the issue while the > main question was if there was anything remotely similar to what I > would need, besides using SVN that is ;-) I don't really understand this. Regards, Bj?rn -- BOFH excuse #150: Arcserve crashed the server again. From gianmaria at hotmail.com Wed Nov 28 16:05:40 2007 From: gianmaria at hotmail.com (Gianmaria Iaculo - NVENTA) Date: Wed, 28 Nov 2007 22:05:40 +0100 Subject: Bit Operations References: Message-ID: Txs all, i wont to respond to who asked why i needed it: I'm using python on GSM modules and the informations i have to move goes along GPRS/UMTS connections so it's beatiful for me to transfer more informations with less space... imagine i have to send this simple data.... 41.232323,12.345678 i can send it as it's or use the nibble trick and on the receiving station 'unlift" the data and rebuild the original information... isn'it??? cheers + TXS, Gianmaria ps: now i'm gonna read all your answers in details... txs again Firma Gianmaria Iaculo "Gianmaria Iaculo - NVENTA" ha scritto nel messaggio news:fikhra$dmc$1 at aioe.org... > Hi there, > I'm so new to python (coming from .net so excuse me for the stupid > question) and i'm tring to do a very simple thing,with bytes. > > My problem is this: > > i've a byte that naturally is composed from 2 nibbles hi&low, and two > chars.. like A nd B. What i wonna do is to write A to the High nibble and > B to the the lower nibble. > Or an other example can be i've 2 numbers.. like 7 and 8 and whant to do > the same as for chars. > > I'm really confused on how t do it, maybe cause python is type-less > (dynamic typed) > > > Any Help? > > Cheers, > Gianmaria > ITALY > > From DustanGroups at gmail.com Tue Nov 6 05:08:49 2007 From: DustanGroups at gmail.com (Dustan) Date: Tue, 06 Nov 2007 10:08:49 -0000 Subject: How to use list as key of dictionary? In-Reply-To: References: <1194332021.595511.67370@v29g2000prd.googlegroups.com> <1194332941.190425.21090@i38g2000prf.googlegroups.com> <1194339027.038844.22200@v23g2000prn.googlegroups.com> <47303809$0$16661$9b4e6d93@newsspool3.arcor-online.net> Message-ID: <1194343729.484495.201400@v29g2000prd.googlegroups.com> On Nov 6, 3:58 am, Duncan Booth wrote: > Wildemar Wildenburger wrote: > > maybe something like this could help: > > > def tupleize(non_tuple): > > try: > > return tuple(tupleize(thing) for thing in non_tuple) > > except TypeError: > > # non_tuple is not iterable > > return non_tuple > > Just don't try passing that a string or anything containing a string. Untested def tupleize(non_tuple): if isinstance(non_tuple, str): return non_tuple try: return tuple(tupleize(thing) for thing in non_tuple) except TypeError: # non_tuple is not iterable return non_tuple From patrick.waldo at gmail.com Fri Nov 16 14:13:42 2007 From: patrick.waldo at gmail.com (patrick.waldo at gmail.com) Date: Fri, 16 Nov 2007 11:13:42 -0800 (PST) Subject: Sorting Countries by Region Message-ID: <4375355d-b23e-4a1c-8f4b-183156a163c5@f13g2000hsa.googlegroups.com> Hi all, I'm analyzing some data that has a lot of country data. What I need to do is sort through this data and output it into an excel doc with summary information. The countries, though, need to be sorted by region, but the way I thought I could do it isn't quite working out. So far I can only successfully get the data alphabetically. Any ideas? import xlrd import pyExcelerator def get_countries_list(list): countries_list=[] for country in countries: if country not in countries_list: countries_list.append(country) EU = ["Austria","Belgium", "Cyprus","Czech Republic", "Denmark","Estonia", "Finland"] NA = ["Canada", "United States"] AP = ["Australia", "China", "Hong Kong", "India", "Indonesia", "Japan"] Regions_tot = {'European Union':EU, 'North America':NA, 'Asia Pacific':AP,} path_file = "c:\\1\country_data.xls" book = xlrd.open_workbook(path_file) Counts = book.sheet_by_index(1) countries= Counts.col_values(0,start_rowx=1, end_rowx=None) get_countries_list(countries) wb=pyExcelerator.Workbook() matrix = wb.add_sheet("matrix") n=1 for country in unique_countries: matrix.write(n,1, country) n = n+1 wb.save('c:\\1\\matrix.xls') From heikki at osafoundation.org Wed Nov 14 17:05:59 2007 From: heikki at osafoundation.org (Heikki Toivonen) Date: Wed, 14 Nov 2007 14:05:59 -0800 Subject: ANN: Chandler 0.7.2 Message-ID: <8q2dndyTPMHU7KbanZ2dnUVZ_uadnZ2d@comcast.com> The Chandler Project is pleased to announce the 0.7.2 release of Chandler Desktop! Download links, information on mailing lists, and how to get the sources are available from the homepage[1]. The 0.7.2 release is the second in a series of quick, time-based releases since Chandler Preview 0.7.0.1 intended to respond to the feedback we received from 0.7.0.1 and continue to receive from these quick releases. 0.7.2 fixes over 80 bugs and includes some major improvements: * Dashboard: Following up on users logged bugs and remarks, we improved the Dashboard display of the Who column and made it work more in sync with the other columns. We also changed how the triage status cycles. * Support for Ubuntu Gutsy Gibbon: We?re now using wxPython 2.8.6.0 which fixes crashes reported by several users of Ubuntu Gutsy Gibbon. This fixes Bug #10906. * New version of PyLucene: Chandler?s PyLucene is not using gcj anymore, but rather our own home brew jcc. This fixes Bug #10803 among others. * Auto fill for common email providers: Account settings now fill automatically for the most common email providers. Just type your email address and if the provider is recognized, most of the settings will be filled out automatically. * Chandler-on-a-stick, a.k.a. ?Portable Chandler?: Though not built automatically and available for download, it is now possible to build a relocatable distribution of Chandler that can be stored on, and run from a removable device such as a USB memory stick or an iPod. * Getting ready for l10n (localization): Chandler Desktop 0.7.2 is not completely ready for localizers yet (still a handful of bugs to fix; this will happen in 0.7.3) but we solved a significant set of issues that will make the localization process much easier. For a more complete list of bug fixes and known issues, please visit our Release Notes[2]. Thanks for your interest in Chandler Desktop! [1] http://chandlerproject.org/ [2] http://chandlerproject.org/Projects/ReleaseNotes From cedb816 at yahoo.com Fri Nov 16 10:24:56 2007 From: cedb816 at yahoo.com (ce) Date: Fri, 16 Nov 2007 07:24:56 -0800 (PST) Subject: Any pythonists in guangzhou china!!! Message-ID: Hi, wondering if there is any python community in guangzhou/china I need ppl to talk to! I am dieing here From gnewsg at gmail.com Mon Nov 19 20:07:19 2007 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Mon, 19 Nov 2007 17:07:19 -0800 (PST) Subject: Joining open source python projects Message-ID: <1c2794d5-1b27-4b93-bbbe-8b354fd23003@e1g2000hsh.googlegroups.com> Hi there, I don't know if such a thing has been already discussed, in which case I'm sorry. I was wondering if there's a place for python open source projects that need help. It thought it would be very nice having a place where developers could submit "help requests" for their projects and let the users view them and eventually join them if they want to. Does someone knows if such a service already exist or not? From hniksic at xemacs.org Tue Nov 13 09:43:06 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 13 Nov 2007 15:43:06 +0100 Subject: Iterator for circulating a list References: Message-ID: <87hcjqcikl.fsf@mulj.homelinux.net> "BJ?rn Lindqvist" writes: > L = somelist > > idx = 0 > while True: > item = L[idx] > # Do something with item > idx = (idx + 1) % len(L) > > wouldn't it be cool if there was an itertool like this: > > def circulate(L, begin = 0, step = 1): > idx = begin > while True: > yield L[idx] > idx = (idx + step) % len(L) > > for x in circulate(range(10)): > print 'at', x,'!' How about itertools.cycle? From shanesclark at hotmail.com Fri Nov 16 14:16:25 2007 From: shanesclark at hotmail.com (Shane Clark) Date: Fri, 16 Nov 2007 14:16:25 -0500 Subject: Getting name of control under mouse in Windows? Message-ID: Hi, I am trying to get my python app to output the name of the control under the mouse each time it is clicked. Currently, I am trying to do this with a combination of pyhook and pyAA, but pyAA gives me "pyAA.Error: -2147417843" for almost any control in Microsoft Office apps, for example. If it matters, I am trying to retrieve the control's name based on the mouse position coordinates. Any ideas what is going wrong here? I looked into switching to comtypes briefly, but it is still undocumented and I cannot find useful examples for it thus far. I apologize if this was the wrong place to ask for help, but I did not find a more pertinent mailing list. Thanks, -Shane _________________________________________________________________ Climb to the top of the charts!? Play Star Shuffle:? the word scramble challenge with star power. http://club.live.com/star_shuffle.aspx?icid=starshuffle_wlmailtextlink_oct -------------- next part -------------- An HTML attachment was scrubbed... URL: From bearophileHUGS at lycos.com Thu Nov 22 05:05:39 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 22 Nov 2007 02:05:39 -0800 (PST) Subject: the annoying, verbose self References: <3c954a31-9fb9-4c0f-b784-cef9ee057ca6@g30g2000hsb.googlegroups.com> Message-ID: <6f67fccf-fbec-4c75-baea-5d0277e07883@w40g2000hsb.googlegroups.com> Alexy: > Sometimes I > avoid OO just not to deal with its verbosity. In fact, I try to use > Ruby anywhere speed is not crucial especially for @ prefix is better- > looking than self. Ruby speed will increase, don't worry, as more people will use it. Bye, bearophile From ihatespam at hotmail.com Thu Nov 29 03:26:26 2007 From: ihatespam at hotmail.com (Just Another Victim of the Ambient Morality) Date: Thu, 29 Nov 2007 08:26:26 GMT Subject: How do I not make a list? Message-ID: It may sound like a strange question but that's probably only because I don't know the proper terminology. I have an iterable object, like a list, and I want to perform a transform on it (do an operation on each of the elements) and then pass it onto something else that expects and iterable. I'm pretty sure this something else doesn't need a list, either, and just wants to iterate over elements. Now, I could just make a list, using a list comprehension, performing my operation on each element, and then pass that list on, knowing that it is iterable. However, I was wondering if there was a way I can do virtually this without having to actually allocate the memory for a list. Creating a stock iterator or generator or whatever it's called, with a passed in operation? I hope I've described this adequately. Thank you... From james.b.looney at lmco.com Wed Nov 28 15:59:34 2007 From: james.b.looney at lmco.com (Looney, James B) Date: Wed, 28 Nov 2007 13:59:34 -0700 Subject: Optimized Python bytecode Message-ID: I'm using SCons to build all kinds of things, and part of our build process involves creating a "release" version of our software. In the case of Python, that means compiling the .py into a .pyc or .pyo. Because I'm placing the compiled script into a different location from the .py, I have to figure out myself whether to name the file a .pyc or a .pyo. So, how do I programatically (within Python) figure out if someone used the -O or -OO flags, without having access to the argv list? How about programatically (still within Python) setting those flags? -James -------------- next part -------------- An HTML attachment was scrubbed... URL: From theller at ctypes.org Fri Nov 16 16:07:18 2007 From: theller at ctypes.org (Thomas Heller) Date: Fri, 16 Nov 2007 22:07:18 +0100 Subject: PIL question In-Reply-To: References: Message-ID: Thomas Heller schrieb: > I'm trying to read an image with PIL, crop several subimages out of it, > and try to combine the subimages again into a combined new one. This is > a test script, later I want to only several single images into a combined one. [...] > Here is the code; I'm using Python 2.4 and PIL 1.5: PIL 1.1.5, of course; sorry for the confusion. From matthiasblankenhaus at yahoo.com Fri Nov 2 14:14:07 2007 From: matthiasblankenhaus at yahoo.com (matthias) Date: Fri, 02 Nov 2007 11:14:07 -0700 Subject: Assertion for python scripts Message-ID: <1194027247.325466.14300@o80g2000hse.googlegroups.com> Howdy ! I started using the assert() stmt and found it quite useful :-) I have only one problem: I don't know how to turn them off again. I know that "-O" turns off assertions in general. However, how do I pass thus parameter to python to an executable script ? I have tried the following: 1. !#/usr/bin/env python -O -> Fails with this msg: /usr/bin/env: python -O: No such file or directory Also, putting it in quotes won't do it. 2. Passing the "-O" to the runnable script won't work either. Here is my question: How do I maintain debug / release builds that allow me to switch debug stmts, like assert, on / off ? Thanx, Matthias From http Thu Nov 1 23:42:06 2007 From: http (Paul Rubin) Date: 01 Nov 2007 20:42:06 -0700 Subject: marshal vs pickle References: <1193949315.556471.72530@o80g2000hse.googlegroups.com> <1193951706.592622.49260@o38g2000hse.googlegroups.com> Message-ID: <7xlk9htisx.fsf@ruckus.brouhaha.com> Aaron Watters writes: > > >>> marshal.loads('RKp,U\xf7`\xef\xe77\xc1\xea\xd8\xec\xbe\\') > > Segmentation fault > >... > I'll grant you the above as a denial of service attack. ... > Can you give me an example > where someone can erase the filesystem using marshal.load? You should always assume that if an attacker can induce a memory fault (typically through a buffer overflow) then s/he can inject and run arbitrary machine code and take over the process. It's not even worth looking for a specific exploit--this type of thing MUST be fixed if the function can be exposed to untrusted data. Yes it should be possible to fix the segfault in marshal--but in principle pickle could be locked down as well, at least from these code injection attacks. It's just something the python stdlib doesn't currently address, for whatever reason. BTW, if denial of service counts, I think that you also have to check for algorithmic complexity attacks against Python dictionary objects. I.e. by constructing a serialized dictionary whose keys all hash to the same number, you can possibly make the deserializer use quadratic runtime, bringing the remote process to its knees with a dictionary of a few million elements, a not-unreasonable size for applications like database dumps. (I haven't checked yet what actually happens in practice if you try this, given that the already-known problems with pickle and marshal are even worse). This can't really be fixed in the serialization format. Either the deserializer should run in a controlled environment (enforced resource bounds) or (preferably) the underlying dict implementation should change to resist this attack. For more info, see: http://www.cs.rice.edu/~scrosby/hash/ From deets at nospam.web.de Fri Nov 2 12:49:52 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 02 Nov 2007 17:49:52 +0100 Subject: Copy database with python.. References: <1194011518.553434.278940@o3g2000hsb.googlegroups.com> <1194013966.385381.150060@o3g2000hsb.googlegroups.com> Message-ID: <5p12pgFoqsksU1@mid.uni-berlin.de> Abandoned wrote: > On Nov 2, 4:19 pm, Paul McNett wrote: >> Abandoned wrote: >> > Hi. >> > I want to copy my database but python give me error when i use this >> > command. >> > cursor.execute("pg_dump mydata > old.dump") >> > What is the problem ? And how can i copy the database with python ? >> >> You are just going to have to give us more to go on. Please post the >> entire traceback of the error that you see (copy/paste it from your >> terminal). >> >> You can't issue system commands using the cursor's execute() method and >> expect that to work. execute() is for executing SQL, DML, or DDL, not >> for doing shell stuff. >> >> Try: >> >> import os >> os.system("pg_dump mydata > /tmp/old.dump") >> >> but I'm not versed in postgressql, so this probably won't work exactly >> as written. You'd need to run that code from the server hosting the >> postgresql database. >> >> > Note: The database's size is 200 GB >> >> Well, then you may want to make sure you have enough room on the target >> volume before trying to dump the file! Note that the dump file could >> conceivably be much larger (or much smaller) than the database itself. >> >> -- >> pkm ~http://paulmcnett.com > > Are there any way to copy database without dump or any temp files ? > (If there is a temp my harddisk not enough for this operation :( ) You can invoke the pg_dump on the remote machine. Diez From rhamph at gmail.com Wed Nov 7 15:53:41 2007 From: rhamph at gmail.com (Rhamphoryncus) Date: Wed, 07 Nov 2007 20:53:41 -0000 Subject: Confused about closures and scoping rules In-Reply-To: References: <20071107002343.8162.1155154160.divmod.quotient.32563@ohm> Message-ID: <1194468821.972784.131100@v29g2000prd.googlegroups.com> On Nov 6, 5:37 pm, "Chris Mellon" wrote: > On Nov 6, 2007 6:23 PM, Jean-Paul Calderone wrote: > > > On Tue, 06 Nov 2007 17:07:47 -0700, Fernando Perez wrote: > > > [snip] > > > >This struck me as counterintuitive, but I couldn't find anything in the > > >official docs indicating what the expected behavior should be. Any > > >feedback/enlightenment would be welcome. This problem appeared deep inside a > > >complicated code and it took me almost two days to track down what was going > > >on... > > > Lots of people ask about this. The behavior you observed is the expected > > (by the implementors, anyway) behavior. > > Are there languages where closures *don't* behave like this? A closure > that used a copy of the state rather than the actual state itself > doesn't seem as useful. For references sake, JavaScript (the only > language that a) has closures and b) I have a handy way to test with) > does the same thing. I've never needed to repeatedly modify closure variables. However, I may not set them until after the function is defined. A simple example is that of a recursive function: def foo(): def bar(): bar() # useful work omitted return bar Obviously, bar can't be set until after the function object is created. Showing changes also matches the behaviour of globals, which is a good thing IMO. -- Adam Olsen, aka Rhamphoryncus From zhushenli at gmail.com Wed Nov 14 03:48:16 2007 From: zhushenli at gmail.com (Davy) Date: Wed, 14 Nov 2007 00:48:16 -0800 Subject: function call problem in class? In-Reply-To: References: <1195026717.343184.33900@i38g2000prf.googlegroups.com> Message-ID: <1195030096.950732.109180@v29g2000prd.googlegroups.com> On Nov 14, 4:10 pm, "Gabriel Genellina" wrote: > En Wed, 14 Nov 2007 04:51:57 -0300, Davy escribi?: > > > I have write a simple class, I want the function two() to call private > > function __one(), but there is an error : > > NameError: global name '_simple__one' is not defined, how to work > > around it > > > class simple: > > def __one(self): > > print "Hello" > > def two(self): > > __one() > > print "world" > > > if __name__ == '__main__': > > s = simple() > > s.two() > > Note that your problem is not related to mangled names: replacing __one by > one raises a similar exception. > Remember that "self" is not implicit: you must use self.__one() Hi Gabriel, Thank you. now my code work well ) Davy > > "private" methods (and atributes in general) use a single underscore: > _one. Double underscores __one are reserved for the (rare) cases when you > want to ensure unique names (or name clashes are expected). > > -- > Gabriel Genellina From ptmcg at austin.rr.com Thu Nov 1 02:25:44 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Wed, 31 Oct 2007 23:25:44 -0700 Subject: ANN: O'Reilly e-book, "Getting Started with Pyparsing" Message-ID: I'm happy to report the release of the O'Reilly ShortCut, "Getting Started With Pyparsing." This 65-page e-book goes into detail on Pyparsing's design rationale, basic features, and a succession of applications. "Getting Started With Pyparsing" covers a range of samples, from an extended version of "Hello, World!" to a 100-line search engine. An index helps you quickly find descriptions and sample uses of the most common Pyparsing classes and methods. Several chapter excerpts are available online, including this chapter on the Zen of Pyparsing: http://preview.tinyurl.com/yp4v48 For more details, see O'Reilly's web page: http://www.oreilly.com/catalog/9780596514235/ Thanks, -- Paul McGuire (For those who have downloaded it, please add a review to the book download page.) From andre.roberge at gmail.com Thu Nov 29 13:10:34 2007 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Thu, 29 Nov 2007 10:10:34 -0800 (PST) Subject: Any Pythonista knowing Estonian on this list? References: <2f7be902-7929-46ec-9924-a82366e2f221@r60g2000hsc.googlegroups.com> Message-ID: <02a5ab87-d84d-4dfd-900d-056297fd4891@s36g2000prg.googlegroups.com> Two nice Python fans (Pearu and Raul) have contacted me about this. Thanks! On Nov 28, 10:39 pm, "Andr?" wrote: > Some of the tasks that are part of Google's H.O.P. involved > translation (i18n) of some well-known ... and some lesser known > projects. I have received a translation in Estonian for Crunchy - > probably of the order of a 100 phrases. I just want to make sure that > no practical joke has been played in doing the translations ... my > Estonian is None. > > Anyone with basic reading knowledge of Estonian is more than welcome > to contact me. > > Andr? From fperez.net at gmail.com Wed Nov 7 13:16:00 2007 From: fperez.net at gmail.com (Fernando Perez) Date: Wed, 07 Nov 2007 11:16:00 -0700 Subject: Strange behavior of __get__ in a descriptor in IPython References: Message-ID: Jakub Hegenbart wrote: > Hi, > > I'm studying the descriptor protocol and its usage from the following > document: > > http://users.rcn.com/python/download/Descriptor.htm > > There is some sample code: > > http://users.rcn.com/python/download/Descriptor.htm#descriptor-example > > that behaves in a different way on my machine than the example suggests: > > In [2]: a=MyClass() > > In [3]: a.x > Retrieving var "x" > Retrieving var "x" > Out[3]: 1 > > On the other hand, in the 'plain' Python shell, it's invoked only once as > expected: > >>>> a=desc.MyClass() >>>> a.x > Retrieving var "x" > 10 >>>> > > Should I take as granted that IPython might in some cases access an > attribute > of an object more than once even in face of side effects, or is this a bug? Yup, IPython does access attributes more than once in an attempt to determine if things can be called as functions. This behavior, however, only exists if 'autocall' is active. Here's an example: In [1]: run desc In [2]: m.x Retrieving var "x" Retrieving var "x" Out[2]: 10 In [3]: m.x Retrieving var "x" Retrieving var "x" Out[3]: 10 In [4]: autocall 0 Automatic calling is: OFF In [5]: m.x Retrieving var "x" Out[5]: 10 As you can see, once autocall is disabled, the double access goes away. There really is no way to provide the autocall feature without any side effects whatsoever, so if you need to avoid them at all costs, disable this feature. You can do it permanently by editing your ipythonrc file. Cheers, f From duncan.booth at invalid.invalid Thu Nov 1 10:30:59 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 1 Nov 2007 14:30:59 GMT Subject: urllib.getproxies and PAC References: <1193926723.847326.147690@19g2000hsx.googlegroups.com> Message-ID: gooli wrote: > Hi, > > I'm using urllib to get html pages from the web but my computer is > behind a proxy. > > The proxy is automatically configured in Internet Explorer via a > proxy.pac file (http://en.wikipedia.org/wiki/Proxy_auto-config). > >>From what I can see in the urllib source it only handles proxies that > are manually configured in IE and doesn't concern itself with > automatic configuration. > > Does anybody know of some code that can handle all the proxy > configuration variants? > Automatic proxy configuration involves retrieving a javascript file from a server and calling the javascript for each URL to find out which proxy to use. There really isn't any easy way to implement that in Python. Your best bet may be to drive Internet Explorer through COM automation. From deets at nospam.web.de Thu Nov 8 16:15:00 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 08 Nov 2007 22:15:00 +0100 Subject: Some "pythonic" suggestions for Python In-Reply-To: <5PGdnWmWZIdZ967anZ2dnUVZ_uuqnZ2d@cavtel.net> References: <5PGdnWmWZIdZ967anZ2dnUVZ_uuqnZ2d@cavtel.net> Message-ID: <5phcjgFri0fuU1@mid.uni-berlin.de> Frank Samuelson schrieb: > I love Python, and it is one of my 2 favorite > languages. I would suggest that Python steal some > aspects of the S language. > > ------------------------------------------------------- > 1. Currently in Python > def foo(x,y): ... > assigns the name foo to a function object. Is this pythonic? > > Why not use the = operator like most other assignments? > Define function objects as "function"s, let users put them where > they want to. Get rid of lambda, get rid of def, only use = > for assignments. > > foo = function(x,y) x+y*2 # Example S language code > bar = foo > bar(3,4) > m = lapply( s, foo ) > bb = lapply(s, function(t) t[3]*4 ) > > foo = func(x,y): x+y*2 # Possible python code > bar = foo > bar(3,4) > m = barf( s, foo ) > bb = barf(s, func(t): t[3]*4 ) The whole purpose being that you have statements in lambdas - something that has been proposed and rejected about a bazillion times. Read the archives. > ------------------------------------------------------- > 2. Allow sequences to be indices: > >>> s=["hello", 6, 33, "none"] > >>> x= [1,3] > >>> [ s[y] for y in x] # Current verbose version > [6, 'none'] > >>> s[x] # Simpler, clearer, more productive > > To quote a poster at http://www.thescripts.com/forum/thread22741.html, > "While we are at it, I also don't understand why sequences can't be > used as indices. Why not, say, l[[2,3]] or l[(2, 3)]? Why a special > slice concept? " Isn't that unpythonic? What has the one to do with the other? Slices are use- and powerful. I'm not against this, but then what you call "verbose" is very concise in my book - and concise enough to be used when the need arises, which is seldom enough. > -------------------------------------------------------- > 3. When I first started using python, I frequently used > map, because I didn't want to have to learn the > additional syntax of list comprehensions, which > appeared very nonstructured. > > # Is this readable? > b= [x+y for x in vec1 if x>0 for y in vec2 if y>x ] Yes, I think it is readable. You could ask the same for the parenthesis-overload in lisp - after all, it's just what you are accustomed to. > Perhaps a list comprehension syntax more like the rest > of python. "for" could return a list given by continue > arguments: > > b= for x in vec1 : > if (x>0): continue # "returns" nothing > continue for y in vec2: > if (x>y): continue(x+y) > > Note that my code would actually return a list of lists > rather than a single list like the list comprehension. > More structured syntax opens the door to having much > more complicated, yet still comprehensible (thus more > pythonic), list comprehensions. So it is _not_ a list comprehension, but all it does is to create implicit lists? I prefer list-comps. They allow for nested as well as flattened structures: b= [x+y for x in vec1 if x>0 for y in vec2 if y>x ] b= [[x+y for y in vec2 if y>x ] for x in vec1 if x>0] Overall, I'd say you don't stand a chance that your proposals will be adopted. They are minor variations of things that have been proposed & rejected too often to count - and to be honest: it get's tiresome beating the same old horses again and again... Diez From meyousikmann at yahoo.com Tue Nov 13 10:28:49 2007 From: meyousikmann at yahoo.com (meyousikmann at yahoo.com) Date: Tue, 13 Nov 2007 07:28:49 -0800 Subject: Convert some Python code to C++ Message-ID: <1194967729.175135.39830@22g2000hsm.googlegroups.com> I am working on an implementation of the Longest Common Subsequence problem (as I understand it, this problem can be used in spell checking type activities) and have used this site to understand the problem and its solution: http://en.wikibooks.org/wiki/Algorithm_implementation/Strings/Longest_common_subsequence For those that understand algorithms and can talk Python, I want to convert the Python code in the section "Reading out all LCSs" into C++ code but I don't understand some of the syntax. Can anyone give me a hand? Here is the code from that section, but is probably of little use without understanding the entire problem setup given at the site above: def backTrackAll(C, X, Y, i, j): if i == 0 or j == 0: return set([""]) elif X[i-1] == Y[j-1]: return set([Z + X[i-1] for Z in backTrackAll(C, X, Y, i-1, j-1)]) else: R = set() if C[i][j-1] >= C[i-1][j]: R.update(backTrackAll(C, X, Y, i, j-1)) if C[i-1][j] >= C[i][j-1]: R.update(backTrackAll(C, X, Y, i-1, j)) return R Thanks! From espie at lain.home Mon Nov 12 19:36:15 2007 From: espie at lain.home (Marc Espie) Date: Tue, 13 Nov 2007 00:36:15 +0000 (UTC) Subject: Distributed RVS, Darcs, tech love References: <1192850894.310464.89070@e9g2000prf.googlegroups.com> <1192980705.698811.128060@i38g2000prf.googlegroups.com> <1192998506.251127.172530@v29g2000prd.googlegroups.com> Message-ID: In article <1192998506.251127.172530 at v29g2000prd.googlegroups.com>, llothar wrote: >On 21 Okt., 22:45, Lew wrote: > >> Evidence is that TeX development is dead. > >Exactly and Knuths only contribution to software development was the >theory of >"literate" programming. As i said for me algorithms are not software >development, >this is programming in the small (something left for coding apes), not >programming >in the large. There are no problems anymore with programming the >small, sure you >can try to develop Judy Arrays or another more optimized sorting >algorithm, but >this has no real world effect. It is theoretical computer science - >well a few >people seem to like this. Boy, you really have to get a clue. Apart from the fact that Knuth wrote a book series that is still THE definitive series on computer algorithms (and that most people who need these algorithms know those books... they document a fairly large set of interesting facts about floating point arithmetic, and the designers of cpu would do well to read them and not cut to many corners for IEEE754. They also a document a large set of useful algorithms, some of them fairly commonplace as soon as you need some efficiency), no, he hasn't done anything smart. No real world effect ? Ah! have a look inside your computer at some point. You'll be surprised where you find those algorithms (your kernel is likely to use some of them, for instance). And perl is probably better for Knuth's study of hash algorithms... As far as TeX being `dead' goes, it's just finished, from Knuth's point of view. It doesn't prevent TeX-based distributions from thriving (TeXlive being the latest fad), and TeX-derived projects from going forward... From carllemp at gmail.com Thu Nov 29 22:22:35 2007 From: carllemp at gmail.com (carllemp at gmail.com) Date: Thu, 29 Nov 2007 19:22:35 -0800 (PST) Subject: Yet Another Tabular Data Question References: <3989e27a-76ee-40d6-a0ca-f8231dc8c98e@n20g2000hsh.googlegroups.com> Message-ID: <112a4059-fbfe-43ef-96c2-f8e87f720f35@f3g2000hsg.googlegroups.com> On Nov 29, 5:46 pm, patrick.wa... at gmail.com wrote: > Hi all, > > Fairly new Python guy here. I am having a lot of trouble trying to > figure this out. I have some data on some regulations in Excel and I > need to basically add up the total regulations for each country--a > statistical analysis thing that I'll copy to another Excel file. > Writing with pyExcelerator has been easier than reading with xlrd for > me...So that's what I did first, but now I'd like to learn how to > crunch some data. > > The input looks like this: > > Country Module > Topic # of Docs > Argentina Food and Consumer Products Cosmetics 1 > Argentina Food and Consumer Products Cosmetics 8 > Argentina Food and Consumer Products Food Additives 1 > Argentina Food and Consumer Products Food Additives 1 > Australia Food and Consumer Products Drinking Water 7 > Australia Food and Consumer Products Food Additives 3 > Australia Food and Consumer Products Food Additives 1 > etc... > > So I need to add up all the docs for Argentina, Australia, etc...and > add up the total amount for each Topic for each country so, Argentina > has 9 Cosmetics laws and 2 Food Additives Laws, etc... > > So, here is the reduced code that can't add anything...Any thoughts > would be really helpful. > > import xlrd > import pyExcelerator > from pyExcelerator import * > > #Open Excel files for reading and writing > path_file = "c:\\1\\data.xls" > book = xlrd.open_workbook(path_file) > Counts = book.sheet_by_index(1) > wb=pyExcelerator.Workbook() > matrix = wb.add_sheet("matrix") > > #Get all Excel data > n=1 > data = [] > while n data.append(Counts.row_values(n, start_colx=0, end_colx=None)) > n=n+1 > > COUNTRY, MODULE, TOPIC,DOCS = range(4) > COUNTRY_TOT = [] > n=0 > while n x=n > while data[n][COUNTRY]==data[n+1][COUNTRY]: > n=n+1 > print sum(data[x:n][FT_DOCS]) > > wb.save('c:\\1\\matrix.xls') Considering the topic of the usenet group, I know this is heresy but I'd suggest using the Pivot Table feature in Excel. The whole thing will be done if 5 clicks and no code. Simple is better than complex. From demarcheb at gmail.com Tue Nov 6 03:53:36 2007 From: demarcheb at gmail.com (Palindrom) Date: Tue, 06 Nov 2007 08:53:36 -0000 Subject: achieving performance using C/C++ In-Reply-To: <1194269273.308062.9810@z9g2000hsf.googlegroups.com> References: <1194244802.345519.264810@q5g2000prf.googlegroups.com> <1194263492.756770.192190@19g2000hsx.googlegroups.com> <1194269273.308062.9810@z9g2000hsf.googlegroups.com> Message-ID: <1194339216.007895.14820@50g2000hsm.googlegroups.com> Thanks to everybody ! From mostro713 at gmail.com Sat Nov 24 15:20:04 2007 From: mostro713 at gmail.com (mostro713 at gmail.com) Date: Sat, 24 Nov 2007 12:20:04 -0800 (PST) Subject: Disk Space Script References: <363cd9c7-095f-45c7-b92e-f097e93d1a85@s36g2000prg.googlegroups.com> Message-ID: On Nov 24, 2:11 pm, kyoso... at gmail.com wrote: > On Nov 24, 11:46 am, "mostro... at gmail.com" > wrote: > > > > > Hello all, > > > I would like to write a script in Python to email me when disk space > > gets below a certain value. > > > My first question (I'm sure of many) is how do get this output into a > > dictionary or list to index the values? > > > import os > > os.system("df -x cifs -x iso9660 | grep -E ^/dev | awk '{ print > > $1,$4 }'") > > > [What the output looks like] > > > /dev/sda3 15866012 > > /dev/sda4 26126712 > > > I would like to write code that compares /dev/sda* to a number (ex. > > 2000000 -> "2GB") and sends an alert if the indexed value is below it. > > > I'm a noob so keep it simple. > > > Thanks in advance. > > I don't know the Unix command for this, but I would just redirect the > output to a file on your system. See the following for more info: > > http://www.faqs.org/docs/diveintopython/kgp_stdio.html > > You could send the output to a variable and create a file-like stream > too. Either way, read the file (or stream) and then for each line, > split it on the space. > > Then you can do the compare and use the email module to email you the > result should it go over your specified amount. > > By the by, if you're using Python 2.4 or above, you should switch to > using the subprocess module rather than using os.system since the > latter is being deprecated. > > For more on file objects, see the docs: > > http://docs.python.org/lib/bltin-file-objects.html > > or there's this good article: > > http://www.devshed.com/c/a/Python/File-Management-in-Python/ > > And the email module is explained quite well in the docs too: > > http://docs.python.org/lib/module-email.html > > Mike Thanks for the info... I will do some reading... From jgardner.jonathangardner.net at gmail.com Thu Nov 1 16:41:13 2007 From: jgardner.jonathangardner.net at gmail.com (Jonathan Gardner) Date: Thu, 01 Nov 2007 20:41:13 -0000 Subject: shelve.open() and error 22: invalid argument In-Reply-To: <1193947698.151702.20860@o3g2000hsb.googlegroups.com> References: <1193947698.151702.20860@o3g2000hsb.googlegroups.com> Message-ID: <1193949673.854193.257420@e34g2000pro.googlegroups.com> On Nov 1, 1:08 pm, max.agin... at gmail.com wrote: > Hi everyone > > I've come across the following problem: on two different linux > machines, both running python 2.5 (r25:51908), I have the same file > 'd.dat'. The md5 checksums are the same. > > Now, on one machine the following code works > > >>> import shelve > >>> d=shelve.open('d.dat') > > while on the other... > > Traceback (most recent call last): > File "", line 1, in > File "local/lib/python2.5/shelve.py", line 225, in open > return DbfilenameShelf(filename, flag, protocol, writeback) > File "local/lib/python2.5/shelve.py", line 209, in __init__ > Shelf.__init__(self, anydbm.open(filename, flag), protocol, > writeback) > File "local/lib/python2.5/anydbm.py", line 83, in open > return mod.open(file, flag, mode) > File "local/lib/python2.5/dbhash.py", line 16, in open > return bsddb.hashopen(file, flag, mode) > File "local/lib/python2.5/bsddb/__init__.py", line 299, in hashopen > e = _openDBEnv(cachesize) > File "local/lib/python2.5/bsddb/__init__.py", line 355, in > _openDBEnv > e.set_lk_detect(db.DB_LOCK_DEFAULT) > bsddb.db.DBInvalidArgError: (22, 'Invalid argument') > > What is happening? I am running the same Python interpreter on the > same file! Why different results? (To make things weirder, this > actually fails on the machine in which I created the d.dat file using > the shelve module!) > This comes up outside of Python as well. Look into your BDB setup. I bet you that the two machines have different versions of BDB libraries. From python at rcn.com Wed Nov 14 16:16:54 2007 From: python at rcn.com (Raymond Hettinger) Date: Wed, 14 Nov 2007 13:16:54 -0800 Subject: cmp and sorting non-symmetric types In-Reply-To: <1194988703.973800.312070@k79g2000hse.googlegroups.com> References: <1194988703.973800.312070@k79g2000hse.googlegroups.com> Message-ID: <1195075014.653458.55710@v23g2000prn.googlegroups.com> On Nov 13, 1:18 pm, Carl Banks wrote: > The right solution is to use comparison operators > only for ordered comparisons, not for subset and superset testing. The whole point of the rich comparisons PEP was to be able to override the operators for other purposes. Raymond From istvan.albert at gmail.com Sun Nov 11 22:40:42 2007 From: istvan.albert at gmail.com (Istvan Albert) Date: Mon, 12 Nov 2007 03:40:42 -0000 Subject: Populating a dictionary, fast In-Reply-To: References: Message-ID: <1194838842.968952.33650@v2g2000hsf.googlegroups.com> On Nov 11, 11:51 am, Michael Bacarella wrote: > and see it take about 45 minutes with this: > > $ cat cache-keys.py > #!/usr/bin/python > v = {} > for line in open('keys.txt'): > v[long(line.strip())] = True On my system (windows vista) your code (using your data) runs in: 36 seconds with python 2.4 25 seconds with python 2.5 39 seconds with python 3000 i. From lisong.1979 at gmail.com Mon Nov 26 13:30:30 2007 From: lisong.1979 at gmail.com (lisong) Date: Mon, 26 Nov 2007 10:30:30 -0800 (PST) Subject: How to write Regular Expression for recursive matching? References: <5r0clmF1251rpU1@mid.uni-berlin.de> Message-ID: On Nov 26, 12:34 pm, "J. Clifford Dyer" wrote: > On Mon, Nov 26, 2007 at 06:04:54PM +0100, Diez B. Roggisch wrote regarding Re: How to write Regular Expression for recursive matching?: > > > > > > > lisong wrote: > > > > Hi All, > > > > I have problem to split a string like this: > > > > 'abc.defg.hij.klmnop' > > > > and I want to get all substrings with only one '.' in mid. so the > > > output I expect is : > > > > 'abc.defg', 'defg.hij', 'hij.klmnop' > > > > a simple regular expression '\w+.\w' will only return: > > > 'abc.defg', 'hij.klmnop' > > > > is there a way to get 'defg.hij' using regular expression? > > > Nope. Regular expressions can't get back in their input-stream, at least not > > for such stuff. > > > The problem at hand is easily solved using > > > s = 'abc.defg.hij.klmnop' > > > pairs = [".".join(v) for v in zip(s.split(".")[:-1], s.split(".")[1:])] > > which is veritably perlesque in its elegance and simplicity! > > A slightly more verbose version. > > l = s.split('.') > pairs = [] > for x in xrange(len(l)-1): > pairs.append('.'.join(l[x:x+2])) > > Cheers, > Cliff Thank u all for your kindly reply, I agree, RE is not necessary here. Song From arkanes at gmail.com Wed Nov 28 11:12:47 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 28 Nov 2007 10:12:47 -0600 Subject: How to Teach Python "Variables" In-Reply-To: References: <4749bb94$1@news.bezeqint.net> <5qvf6pF122r3mU1@mid.individual.net> <87abp1qqth.fsf@mulj.homelinux.net> <2d7c881d-e5c0-43ec-a8eb-b7c81a118c21@w40g2000hsb.googlegroups.com> Message-ID: <4866bea60711280812v3be1e070k4366d6492e10d47b@mail.gmail.com> On Nov 28, 2007 9:51 AM, hdante wrote: > On Nov 28, 1:42 pm, Neil Cerutti wrote: > > On 2007-11-28, hdante wrote: > > > > > > > > > On Nov 28, 1:09 am, Steven D'Aprano > > > wrote: > > >> On Tue, 27 Nov 2007 10:21:36 -0800, hdante wrote: > > >> > Python variables are pointers and that's it. > > > > >> How do I increment a Python variable so that it points to the > > >> next address, like I can do with pointers in C, Pascal, and > > >> other languages? > > > > >> -- > > >> Steven. > > > > > You can't. Python variables still are pointers. Hint: > > > > > int * const x = &y; > > > > > How do I increment x ? > > > > Not only that, you can't point x at any other object at all. > > That's not a Python variable either. > > > > -- > > Neil Cerutti > > That's right. Languages may have arbitrary sets of operations defined > for their variables. There's nothing wrong with that. > Right. Python variables are pointers, except for all the ways that they are different. By the same criteria, they are also puppies. Give it a rest. From Afro.Systems at gmail.com Thu Nov 8 00:29:18 2007 From: Afro.Systems at gmail.com (Tzury Bar Yochay) Date: Thu, 08 Nov 2007 05:29:18 -0000 Subject: a simple tcp server sample In-Reply-To: References: <1194461679.059865.209530@k79g2000hse.googlegroups.com> Message-ID: <1194499758.871554.236410@d55g2000hsg.googlegroups.com> > Even simpler, use Twisted: I am afraid Twisted is not the right choice in my case. I am looking for smaller, simpler and minimal server sample. From mbac at gpshopper.com Mon Nov 12 12:46:32 2007 From: mbac at gpshopper.com (Michael Bacarella) Date: Mon, 12 Nov 2007 12:46:32 -0500 Subject: Populating a dictionary, fast [SOLVED SOLVED] In-Reply-To: <47374D00.7080500@gmail.com> References: <818643.92017.qm@web915.biz.mail.mud.yahoo.com> <47374D00.7080500@gmail.com> Message-ID: <009701c82553$f67c6580$e3753080$@com> > > You can download the list of keys from here, it's 43M gzipped: > > http://www.sendspace.com/file/9530i7 > > > > and see it take about 45 minutes with this: > > > > $ cat cache-keys.py > > #!/usr/bin/python > > v = {} > > for line in open('keys.txt'): > > v[long(line.strip())] = True > > > > > It takes about 20 seconds for me. It's possible it's related to > int/long > unification - try using Python 2.5. If you can't switch to 2.5, try > using string keys instead of longs. Yes, this was it. It ran *very* fast on Python v2.5. Terribly on v2.4, v2.3. (I thought I had already evaluated v2.5 but I see now that the server With 2.5 on it invokes 2.3 for 'python'.) Thanks! From aaron.watters at gmail.com Tue Nov 6 07:10:05 2007 From: aaron.watters at gmail.com (Aaron Watters) Date: Tue, 06 Nov 2007 04:10:05 -0800 Subject: Python good for data mining? In-Reply-To: References: <1194141739.683498.206780@k79g2000hse.googlegroups.com> <1194314950.490427.210210@v3g2000hsg.googlegroups.com> Message-ID: <1194351005.291502.50170@v3g2000hsg.googlegroups.com> On Nov 6, 4:19 am, "Hendrik van Rooyen" wrote: > "D.Hering" wrote: > > > [1] Anything/everything that is physical/virtual, or can be conceived > > is hierarchical... if the system itself is not random/chaotic. Thats a > > lovely revelation I've had... EVERYTHING is hierarchical. If it has > > context it has hierarchy. > > Do I hear Echoes of What Was Said by a chappie > who rejoiced in the name of Aristotle? The 20th century perspective found it more flexible to base everything on set theory (or category theory or similar) which is fundamentally relational. Historically hierarchical/network databases preceded rdbms's because they are fundamentally more efficient. Unfortunately, they are also fundamentally more inflexible (it is generally agreed). -- Aaron Watters === http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=ascii+christmas From robin at reportlab.com Fri Nov 23 13:14:26 2007 From: robin at reportlab.com (Robin Becker) Date: Fri, 23 Nov 2007 18:14:26 +0000 Subject: png transparency with PIL Message-ID: <47471882.6020807@chamonix.reportlab.co.uk> I'm trying to determine the transparency information for a png image. With gif images I can determine the colour that is used for transparent areas using im.info['transparency']. For the png images of interest there is no such entry in the info dict. I assume that's because of the way png does transparency. I'm guessing I need the alpha channel, but is there a way to get hold of it? -- Robin Becker From uzi18 at o2.pl Fri Nov 2 07:59:48 2007 From: uzi18 at o2.pl (Bart.) Date: Fri, 2 Nov 2007 12:59:48 +0100 Subject: PyQt with embedded python in Qt App In-Reply-To: <1194002466.539726.267780@k79g2000hse.googlegroups.com> References: <1193924163.660753.179140@o38g2000hse.googlegroups.com> <1194002466.539726.267780@k79g2000hse.googlegroups.com> Message-ID: <200711021259.49130.uzi18@o2.pl> Friday 02 of November 2007 12:21:06 BlueBird napisa?(a): > On Nov 2, 8:03 am, "Bart." wrote: > > Friday 02 of November 2007 01:06:58 Diez B. Roggisch napisa (a): > > > > So how to pass this object into embeded python interpreter (executed > > > > script)? Anyone know any example? > > > > > > You don't pass it, you _retrieve_ it in the embedded interpreter by > > > invoking the code given to you. > > > > Know any example, please? > > For better understand this :) I wan't add scripting to one application > > wrotten with Qt. > > So, you have Qt/C++ application which you want to script through > python. > > But why do you need PyQt for ? If you design a script api in python > and bind it using whatever binding technology (manually, boost, sip, > pyrex, ...), you should not need to use PyQt. > > Or do you mean to use PyQt as the binding technology ? Or I want to use PyQt in scripts to have similar gui for plugins written in python Or I want to extend application by scripts with PyQt. Or better question: How to easy add python scripting in Qt application and have almast all objects of app accesible in scripts? Kross could be good solution? I realy need some examples :( I'm looking for solutions. You are proffesional programmers so that is why write on this list :) Thanks for Your answars. Bart. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Nov 2 17:45:36 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 02 Nov 2007 22:45:36 +0100 Subject: python newbie References: <472b2b84$0$13761$6e1ede2f@read.cnntp.org> <5p0s6vFp47k9U1@mid.individual.net> Message-ID: <5p1k40Foq5j2U1@mid.individual.net> Duncan Booth wrote: > Why not try it out for yourself (both of you). Globals do not need > to be defined in the global scope so long as the first 'access' is > to bind a value to the variable: Well, I did. I (mis)understood the OP to mean "read" by "access". I didn't consider rebinding another object to that name. > A function is an attribute of the module which contains it, not a > method. It is just like when you do: Yes, I agree, not a method in Python terms. Regards, Bj?rn -- BOFH excuse #196: Me no internet, only janitor, me just wax floors. From fgmoyles at nospam.com Thu Nov 22 04:50:42 2007 From: fgmoyles at nospam.com (Frank Moyles) Date: Thu, 22 Nov 2007 09:50:42 +0000 Subject: scipy-0.6.0.win32-py2.5.exe does not install Message-ID: Hi, I want to use SciPy library. I am using W2k, and ActiveState Python 2.5. I have succesfully numpy, but when I run the scipy-0.6.0.win32-py2.5.exe (from the downloads section on the SciPy page), nothing happens - i.e. no information is printed on the console, and the setup application simply quits with no warning/error message. has anyone managed to succesfully install SciPy using scipy-0.6.0.win32-py2.5.exe & ActiveState Python on W2k? Am I missing a step? From waldemar.osuch at gmail.com Fri Nov 9 21:55:45 2007 From: waldemar.osuch at gmail.com (Waldemar Osuch) Date: Fri, 09 Nov 2007 18:55:45 -0800 Subject: Codec lookup fails for bad codec name, blowing up BeautifulSoup In-Reply-To: <4734e9e3$0$14119$742ec2ed@news.sonic.net> References: <4734C6CC.7090204@animats.com> <1194649323.666365.192100@y27g2000pre.googlegroups.com> <4734e9e3$0$14119$742ec2ed@news.sonic.net> Message-ID: <1194663345.732540.193980@v23g2000prn.googlegroups.com> On Nov 9, 4:15 pm, John Nagle wrote: > Waldemar Osuch wrote: > >> This is a known bug. It's in the old tracker on SourceForge: > >> [ python-Bugs-960874 ] codecs.lookup can raise exceptions other > >> than LookupError > >> but not in the new tracker. > > > The new tracker has it too. > >http://bugs.python.org/issue960874 > > How did you find that? I put "codecs.lookup" into the tracker's > search box, and it returned five hits, but not that one. > > John Nagle I have seen this explained on this list once: http://bugs.python.org/issues + points to the converted ticket. And yes the search could be better. From antroy at gmail.com Fri Nov 23 07:58:27 2007 From: antroy at gmail.com (Ant) Date: Fri, 23 Nov 2007 04:58:27 -0800 (PST) Subject: foldr function in Python References: <9bf5a2bb-eac7-4859-a5de-b1e84573c77a@t47g2000hsc.googlegroups.com> <0d8c76de-3510-4711-959a-34aad4a33acd@r60g2000hsc.googlegroups.com> <13kdcaar4048329@corp.supernews.com> Message-ID: <1b539321-8112-4e94-9fee-5be922660065@n20g2000hsh.googlegroups.com> On Nov 23, 10:54 am, Steven D'Aprano wrote: ... > Alas and alack, I believe that Guido has a distaste for all but the > simplest functional idioms, and an irrational belief that anything using > reduce() must be too complex to bear. reduce() is going away, not just > from the built-ins but (I believe) from the standard library as well. I thought that at the last count it was merely being moved out into functools (or somewhere similar). -- Ant. From kyosohma at gmail.com Fri Nov 9 09:08:17 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Fri, 09 Nov 2007 14:08:17 -0000 Subject: Python Extension Building Network Message-ID: <1194617297.075298.238880@i13g2000prf.googlegroups.com> Hi, I am trying to get a small group of volunteers together to create Windows binaries for any Python extension developer that needs them, much like the package/extension builders who volunteer their time to create Linux RPMs. The main thing I need are people willing to test the binaries to make sure the extension is stable. This would require installing the binary and probably downloading the source too to get the developer's test code. I've been able to get some of the tests to run great while others are pretty finicky and some extensions don't come with tests. It would be nice to know which extensions are most in need of this too. While I can create the binaries on my own for a while, if I get too many requests, there will be a backlog, so it would be nice to have help with that too. I'm also looking for knowledgeable people to be sounding boards (i.e. give advice). Developers: all I would require is a request, a link to the source, and a well-written setup.py file for a cross-platform extension. You can find the few that I've already done here:http:// www.pythonlibrary.org/python_modules.htm I have also posted a way to create the binaries using the MinGW compiler. I have VS2003 installed on my PC and MinGW is installed in a VM, so I can compile the extensions both ways. Thanks in advance for any feedback. Mike From pofuk at email.t-com.hr Mon Nov 12 18:16:52 2007 From: pofuk at email.t-com.hr (SMALLp) Date: Tue, 13 Nov 2007 00:16:52 +0100 Subject: Help needed! References: Message-ID: I forgot, I'm using wxPython "SMALLp" wrote in message news:fhamq8$84u$1 at ss408.t-com.hr... > I'm new in python and i got lost. > > Ima building an aplication that add's 2 panels and menu bar to the window. > So i made base class that makes window, menuBarClass that inherits > mainWindowClass. > > Problem is with PanelClass that would need to inherit MainWindowClass to > add panels. So if someone has time to write simple example it would be > realy helpfull. > > > > From mail at timgolden.me.uk Fri Nov 30 11:22:00 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 30 Nov 2007 16:22:00 +0000 Subject: "Python" is not a good name, should rename to "Athon" In-Reply-To: <47503626.4060405@scivisum.co.uk> References: <47502B0C.3040504@fmed.uba.ar> <47503626.4060405@scivisum.co.uk> Message-ID: <475038A8.8060106@timgolden.me.uk> Tim Couper wrote: > but it would mean that a version for large duration projects would be > "MarAthon" ... Can't decide whether you were deliberately avoiding "long-running" there, Tim, or just missed the opportunity :) TJG From pclinch at gmail.com Sat Nov 10 17:02:09 2007 From: pclinch at gmail.com (paulC) Date: Sat, 10 Nov 2007 14:02:09 -0800 Subject: Bitmap editor and File-saving In-Reply-To: References: Message-ID: <1194732129.123857.113090@50g2000hsm.googlegroups.com> On 10 Nov, 15:44, Johnston Jiaa wrote: > In my Python program (using Tkinter), I would like to have a window > where the user will be able to draw a simple picture. I don't know > where to begin.. can somehow give me a general idea how to do > something like this? > > Also, I'd like for the program to save that picture along with some > text. What would be the best way to go about doing this? Is > pickling a viable option? > > Thanks in advance, > Johnston The Canvas widget provides structured graphics facilities for Tkinter. At http://infohost.nmt.edu/tcc/help/pubs/tkinter.pdf is a useful manual. Regards, Paul Clinch From Russ.Paielli at gmail.com Sun Nov 4 22:01:57 2007 From: Russ.Paielli at gmail.com (Russ P.) Date: Mon, 05 Nov 2007 03:01:57 -0000 Subject: IDLE In-Reply-To: <1194082626.957066.200570@k79g2000hse.googlegroups.com> References: <1194043445.147572.126100@k35g2000prh.googlegroups.com> <1194082626.957066.200570@k79g2000hse.googlegroups.com> Message-ID: <1194231717.737240.165560@t8g2000prg.googlegroups.com> Thanks for the information on IDLE. > As for your question, I couldn't quite understand what you're trying > to do. In general, you can have the script use os.chdir() to go to the > relevant directory and then open() the file, or you can use open() > directly with a relative/full path to it. (This question isn't IDLE > specific in any way, unless I misunderstood...) I should have been clearer about what I'm trying to do. I have approximately 100 directories, each corresponding to an "incident" (I won't say what type of "incident" here). Each directory has many data files on the incident, and the structure of all the directories is the same (i.e., each has files of the same name). One of those files in an input file that I wish to "replay" through my program, then the results are recorded in an output data file. To replay one incident, I would normally go to the directory for that case and execute my program. I can specify the input and output files explicitly, but I virtually never need to do so because they default to the same file name in each directory. I also have a script that can replay all 100 cases automatically. I would like to do the same sort of thing with IDLE. I don't want to have to specify the input and output files explicitly using absolute pathnames from outside the directory for the incident. That would be horrendously cumbersome after a few times. I want to just cd to a directory and execute my program. But in my first few tries, it seems that I need to be in the directory that contains the source code -- not the directory that contains the data. Am I missing something? Thanks. From martin at v.loewis.de Fri Nov 30 02:26:52 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 30 Nov 2007 08:26:52 +0100 Subject: Dynamically adding a runtime generated method to a class. In-Reply-To: References: Message-ID: <474FBB3C.4000605@v.loewis.de> > This would work and not be too terribly inefficient but I was thinking > it would be much better generate the getLine method at runtime and > dynamically add it to the class so I wouldn't have to pass the columns > around and loop through them every time; I would advise against that. Generating methods on the fly is fairly involved (although possible); but I see no gain. If you don't want to pass the cols around (which I can see as desirable), I recommend to make them an instance variable: def getLine(self, per): vals = [self.desc] for col in self.cols: vals.append(col(self, per)) return vals line1 = lineClass1('Some Description', [1,2,3,4,5,6,7,8,9,10,11,12]) line1.cols = [lineClass1.Ptd, lineClass1.Ytd] print line1.getLine(5) HTH, Martin From hong2221 at gmail.com Tue Nov 27 12:46:13 2007 From: hong2221 at gmail.com (hong2221) Date: Tue, 27 Nov 2007 09:46:13 -0800 (PST) Subject: Looking for a Python tutor Message-ID: <5644ac82-29c2-4e5a-86a3-7c7c11fc2152@r60g2000hsc.googlegroups.com> I'm looking for a Python programmar that is willing write simple functions, prices can be talked over. Contact me asap. From arkanes at gmail.com Mon Nov 19 14:54:13 2007 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 19 Nov 2007 13:54:13 -0600 Subject: Some clauses cases BeautifulSoup to choke? In-Reply-To: References: Message-ID: <4866bea60711191154k4f1b99b3l8dc7523db6531b9b@mail.gmail.com> On Nov 19, 2007 1:36 PM, Frank Stutzman wrote: > I've got a simple script that looks like (watch the wrap): > --------------------------------------------------- > import BeautifulSoup,urllib > > ifile = urllib.urlopen("http://www.naco.faa.gov/digital_tpp_search.asp?fldId > ent=klax&fld_ident_type=ICAO&ver=0711&bnSubmit=Complete+Search").read() > > soup=BeautifulSoup.BeautifulSoup(ifile) > print soup.prettify() > ---------------------------------------------------- > > and all I get out of it is garbage. Other simular urls from the same site > work fine (use http://www.naco.faa.gov/digital_tpp_search.asp?fldId > ent=klax&fld_ident_type=ICAO&ver=0711&bnSubmit=Complete+Search as one example). > > I did some poking and proding and it seems that there is something in the > clause that is causing the problem. Heck if I can see what it is. > > I'm new to BeautifulSoup (heck, I'm new to python). If I'm doing something > dumb, you don't need to be gentle. > You have the same URL as both your good and bad example. From meithamj at gmail.com Thu Nov 1 17:15:46 2007 From: meithamj at gmail.com (Meitham) Date: Thu, 01 Nov 2007 21:15:46 +0000 Subject: How python writes text into another windows application In-Reply-To: <38djv4-kp9.ln1@darkstargames.dnsalias.net> References: <38djv4-kp9.ln1@darkstargames.dnsalias.net> Message-ID: <472A4202.3090708@gmail.com> Thank you all for your kind answers. I was going to use just shell.SendKeys("fu bar"), but as your answers suggested pywinauto is a ready framework that covers all I need. I wanted to play some politics with TNT, but I'm new in the company and my manager won't listen :). Meitham Wolfgang Draxinger wrote: > Meitham wrote: > >> My question is, how do I write the data into another >> application fields. My target application is the TNT >> consignment manager. I asked TNT for their API to make my life >> easier but they refused to release it :(. > > You know what the word "market" means? Just tell TNT, that it > seems they don't need you as a customer and so you will change > to another parcel service. > > I had the very same situation with a regional parcel service a > few years ago, you won't believe how quick they were in > providing me with API information, in the prospect of loosing a > valuable customer (the fact that you want to automatize the > process suggests, that you have a lot of stuff to be delivered). > > If they still don't bite, just show them a calculation, that it's > cheaper for you, to choose another parcel service that might > cost more, but you can save that money with the automatized data > entry. > > Of course it's possible to send keypresses, mouse moves/clicks > and other messages to another application, but then you _MUST_ > make sure, that no other application or a user interferes in the > process, and if an update of the software changes the interface > you have to reimplement the stuff from grounds up. > > Wolfgang Draxinger From vito.detullio at gmail.com Mon Nov 26 11:14:08 2007 From: vito.detullio at gmail.com (ZeD) Date: Mon, 26 Nov 2007 16:14:08 GMT Subject: eof References: <92a2c0c9-e6a1-4344-aeac-830940200f20@t47g2000hsc.googlegroups.com> <79i9k35vs76cqgqnino7dj3ql623us3euq@4ax.com> <6c04c760-6cf1-4715-9ec9-30f43ebaa01f@d27g2000prf.googlegroups.com> <062a9497-7626-440a-93eb-b897e6dec01f@p69g2000hsa.googlegroups.com> <9e25e813-f4a7-48c6-9f0e-ef04223e29a0@e23g2000prf.googlegroups.com> <3cb8cff4-4c1d-4ca2-8d21-c012a109351b@w34g2000hsg.googlegroups.com> <13klrcmdds31o5a@corp.supernews.com> Message-ID: Grant Edwards wrote: > The user-defined xor is operates on "logical" boolean values. > The one in the operator module is a bitwise operator. def xor(a, b): return bool(a) ^ bool(b) seems more explicit to me. maybe, to make "more" explicit (too much, onestly...) from operator import xor as bitwise_xor def logical_xor(a, b): return bitwise_xor(bool(a), bool(b)) -- Under construction From not_here at no_where.com Sat Nov 17 08:46:45 2007 From: not_here at no_where.com (Brian) Date: Sat, 17 Nov 2007 05:46:45 -0800 Subject: Python too complex ?!?!?! Message-ID: <7hC%i.28332$mv3.17248@newsfe10.phx> Had a unsettling conversation with a CS instructor that teaches at local high schools and the community college. This person is a long-term Linux/C/Python programmer, but he claims that the install, config, and library models for C# have proved to be less problematic than Python. So both his courses (intro, data structs, algorithms) are taught in C#. I am a low-end (3-year) journeyman Pythonista, and I was attracted to the language because of its simplicity. And I have come to enjoy the richness of available libraries. Many of the good people of this NG may be 'too close' to answer, but has Python, as a general devel platform, lost its simplicity ? Is library install too complex and unreliable ? Will my dog go to heaven ? From arkanes at gmail.com Wed Nov 21 11:55:39 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 21 Nov 2007 10:55:39 -0600 Subject: Python too complex ?!?!?! In-Reply-To: <87pry4zlyx.fsf@pobox.com> References: <7hC%i.28332$mv3.17248@newsfe10.phx> <87pry4zlyx.fsf@pobox.com> Message-ID: <4866bea60711210855r50e63efcta9d89cee44266572@mail.gmail.com> On Nov 20, 2007 2:43 PM, John J. Lee wrote: > "Chris Mellon" writes: > [...] > > These modules exist, but aren't that common. Certainly anything you're > > likely to be using in an introductory compsci course is well packaged. > > And even if it's not, it's really not that hard to create packages or > > installers - a days work of course prep would take care of the > > potential problem. > > "A day's worth of course prep" for beginners would let them debug all > the crap that building MySQLdb on Windows might throw at them, for > example? I think not! (MySQLdb, last time I looked, was one of the > not-so-obscure modules that don't have a Windows installer available > and kept up to date. Maybe it does now, but that's not really the > point.) > A days worth of course prep would allow the professor (or his TA, more likely) to produce a set of installers that's suitable for use with the course. This is a comp sci course, not a "how to sysadmin a Python installation" course. For the record, it took me less than 3 minutes to install MySqldb, the first time I've ever needed to do it - I don't like or approve of MySql. Steps required: Google for "mysql python" and click through 3 or 4 links to the SF download page. Download the binary installer, from March 2007. Not exactly rocket science. On a similar note, I have or create executable installers for all the third party modules I use, because I need to provide them to the people who do our deployments. This has never been much of a burden. > I certainly don't recognise what some people have been saying, though. > It's a rare thing that I have any real pain installing a Python module > on Linux. That's not to say you don't need some background knowledge > about distributions and Python if doing it "by hand", of course > (rather than with a packaging tool like apt-get). Occasionally you'll > want the newest version of something, which will in turn occasionally > get you into some grim automake issue or similar. But all of this can > be entirely avoided in an introductory course -- simply restrict > yourself to what can be installed with apt-get (if the instructor > feels they *must* make some new library available, they can always > package it themselves). > > The obstacles as presented in the OP seem pretty bogus to me. Of course, it's third hand anecdotal evidence, so there's not much of a reason to believe that the original statement really preserves the essence of the problem. I'd be pretty interested if the OP could ask his associate to chime in with some of the actual issues he encountered From luismgz at gmail.com Mon Nov 5 08:27:40 2007 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M=2E_Gonz=E1lez?=) Date: Mon, 05 Nov 2007 13:27:40 -0000 Subject: achieving performance using C/C++ In-Reply-To: <1194263492.756770.192190@19g2000hsx.googlegroups.com> References: <1194244802.345519.264810@q5g2000prf.googlegroups.com> <1194263492.756770.192190@19g2000hsx.googlegroups.com> Message-ID: <1194269260.735322.86990@o3g2000hsb.googlegroups.com> On Nov 5, 8:51 am, Filip Wasilewski wrote: > On Nov 5, 7:40 am, sandipm wrote:> I did fair amount of programming in python but never used c/c++ as > > mentioned below. > > any good tutorials for using C/C++ to optimize python codebase for > > performance? > > how widely do they use such kind of mixed coding practices? > > [...] > > Since you are fluent in Python I also suggest you to start with > Pyrex[1]/Cython[2]. This will let you to express your ideas more > naturally (in a Python-based language) and interface with C code base > without delving much into reference counting, manual parameters > conversion and low-level exception handling. > > You will find some tutorials and links to resources and mailing lists > on the projects websites, and if you specify your problem a bit more > then probably someone will be able to give you more precise > references. > > For alternatives take a look at [3] and [4]. Try also scanning the > Python Package Index[5] for 'binding', 'wrapper', 'lib' or 'pyrex' > keywords or browse for C/C++ Programming Language category as this > will return some examples of Python extensions. > > [1]http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/ > [2]http://www.cython.org/ > [3]http://www.python.org/doc/faq/extending/#writing-c-is-hard-are-there-... > [4]http://docs.python.org/lib/module-ctypes.html > [5]http://pypi.python.org > > fw You might be interested also in ShedSkin. It is a python to c++ compiler, and it lets you write extension modules in a restricted subset of python that get automatically translated to c++. It's still a work in progress although very usable in its current state (and extremely easy to use). Its main advantage, compared to Pyrex, is that you don't need to know c or c++ at all to use it. Pyrex requires some knowledge about c and its data types in order to take advantage of its capabilities. On the other hand, with shedskin you just code in python (getting rid of its most dynamic features), and this code gets automatically compiled to a c++ extension module, directly usable from cpython. Check it out: http://mark.dufour.googlepages.com/ Luis From deets at nospam.web.de Thu Nov 15 07:39:12 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 15 Nov 2007 13:39:12 +0100 Subject: how to figure out if python was used as a cgi script References: <8bb2fd14-38c5-46c6-94fe-40174a734ebc@e23g2000prf.googlegroups.com> Message-ID: <5q2svgFsd74lU1@mid.uni-berlin.de> ce wrote: > hi, > > is there a way to figure out which scripting language was used in a > cgi. I used to watch extensions (i.e. py, pl, asp or php) nowadays i > hardly see any extensions and really it is hard to find out anything > from the generated HTML or even the HTML being sent out through the > FORM tag .. is there another way to find out which scripting language > was used in website!!! No. Diez From sndive at gmail.com Tue Nov 13 16:18:14 2007 From: sndive at gmail.com (sndive at gmail.com) Date: Tue, 13 Nov 2007 21:18:14 -0000 Subject: private data stashed in local/global execution context of PyEval_EvalCode disappears down the execution stack In-Reply-To: References: <1194402317.678614.142450@y42g2000hsy.googlegroups.com> Message-ID: <1194988694.381313.202490@v65g2000hsc.googlegroups.com> On Nov 9, 5:36 pm, "Gabriel Genellina" wrote: > En Tue, 06 Nov 2007 23:25:17 -0300, escribi?: > > > i naively created execution context: > > PyObject *execcontext = PyDict_New(); > > stuffed a handle in it: > > PyObject *ih = PyCObject_FromVoidPtr(handle, NULL); > > int st= PyDict_SetItemString(res, "interp", ih); > > What's `res`? duh! it should be execcontext: int st= PyDict_SetItemString(execcontext, "interp", ih); then i'd PyEval_EvalCode(somecallable, execcontext, g_maindict); where g_maindict is a dictionary from __main__ module ... later as part of PyEval_EvalCode a method in a module extending python is executed by python runtime and i want to get "interp" assuming it would be in the global context: PyObject *dict = PyEval_GetGlobals(); PyObject *co = PyDict_GetItemString(dict, "interp"); but apparently PyEval_GetGlobals(); returns the dictionary that has nothing to do with the execcontext passed into PyEval_EvalCode higher up on the call stack and i do not know how to get to the execcontext dictionary that i passed in PyEval_EvalCode. If each module has its own globals what the point of passing global and local namespace into PyEval_EvalCode? > One should make a lot of assumptions about your code because it's not > complete. Please post a minimal complete example showing your problem. > It's a rather large program. My assumption was that just posting the snippet around the call site and the callee pathetic attempt to extract interp would be sufficient :( From sipickles at hotmail.com Sat Nov 10 11:25:11 2007 From: sipickles at hotmail.com (Simon Pickles) Date: Sat, 10 Nov 2007 16:25:11 +0000 Subject: Looking for a good Python environment In-Reply-To: <87d4uimnwk.fsf@rudin.co.uk> References: <1194389774.159051.55580@19g2000hsx.googlegroups.com> <1194434140.836932.10670@k79g2000hse.googlegroups.com> <1194686473.581666.203870@k79g2000hse.googlegroups.com> <87d4uimnwk.fsf@rudin.co.uk> Message-ID: Well, I am recent Windows escapee, and was dismayed by lack of Pyscripter for Linux. Hold on... there is hope! Pyscripter works great using WINE. search http://groups.google.com/group/PyScripter?hl=en for "Linux" Enjoy! Paul Rudin wrote: > jwelby writes: > > > >> This is a fair question. I didn't phrase my post too well. >> >> I find PyScripter does pretty much everything I need in terms of doing >> actual development for Python. My use of 'lightweight' is by no means >> a criticism of PyScripter - it's more of a compliment, as it refers to >> the relatively modest demands that it makes on my system compared with >> Eclipse, which can be hog. >> >> The main reason I have used Eclipse for larger, team based, projects >> is for the source control plug-ins. Eclipse has plug-in support for >> cvs and svn. PyScripter may have this too - perhaps I've missed it. >> (I'm away from my Windows box at the moment, otherwise I would check). >> Of course, there are other ways to implement source control without it >> needing to be integrated in the IDE, so even this need not put off >> anyone who wants to use PyScripter with source control. >> >> Summary - unless you need the added flexibility offered by Eclipse >> plug-ins, PyScripter is a great tool for developing with Python on >> Windows. >> > > I'm not sure if you count emacs as "lightweight" but it's certainly > less resource hungry than eclipse/pydev, and does have integrated > cvs/svn functionality. > From deets at nospam.web.de Mon Nov 5 08:29:24 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 05 Nov 2007 14:29:24 +0100 Subject: Downloading file from cgi application References: <1194264683.908009.237000@o80g2000hse.googlegroups.com> Message-ID: <5p8k5kFq00fdU1@mid.uni-berlin.de> sophie_newbie wrote: > Hi, > > I'm writing a cgi application in Python that generates a PDF file for > the user and then allows them to download that file. Currently I'm > just writing the PDF file to the 'htdocs' directory and giving the > user a link to this file to download it. But the problem is that > another user could simply come along and download a file that isn't > their file by typing the address into the address bar. I don't want to > delete the file after it is downloaded either because I'd like the > user to be able to download it again if necessary. Is there any way > around this problem? If the user needs to be authenticated, yes. Just encode the username in the pdf-name (on the FS that is, what name you give the downloaded file is unrelated). Then just allow to download the pdf by a user with the right name. Diez From jr244 at kent.ac.uk Tue Nov 13 05:53:12 2007 From: jr244 at kent.ac.uk (J. Robertson) Date: Tue, 13 Nov 2007 10:53:12 +0000 Subject: Loop three lists at the same time? In-Reply-To: <1194950769.587384.177590@v23g2000prn.googlegroups.com> References: <1194950769.587384.177590@v23g2000prn.googlegroups.com> Message-ID: Davy wrote: > Hi all, > > I have three lists with the same length. Is there any method to loop > the three lists without a loop counter? > > Best regards, > Davy > Hello, the zip function? >>> list1 = [1,2,3] >>> list2 = [4,5,6] >>> list3 = [7,8,9] >>> for a,b,c in zip(list1,list2,list3): ... print a, b, c ... 1 4 7 2 5 8 3 6 9 hth j. From grante at visi.com Sun Nov 25 10:46:25 2007 From: grante at visi.com (Grant Edwards) Date: Sun, 25 Nov 2007 15:46:25 -0000 Subject: OPLC purchase period extended References: <13kgrdbf8eb7l34@corp.supernews.com> <13khho3mb3pp27e@corp.supernews.com> Message-ID: <13kj66hg7jbaa27@corp.supernews.com> On 2007-11-25, Aahz wrote: > In article <13khho3mb3pp27e at corp.supernews.com>, > Grant Edwards wrote: >> >>The most imporant thing is that the "control" key is to the left of the >>"A" keay where god intened. Not too surprising when you realized the >>design was headed by folks from the media lab at MIT. MIT requires >>everybody to use Emacs, right? > > What the fuck does that have to do with emacs? Emacs requires almost constant use of the control key, and in my experience Emacs users are the most cranky about having the control key in the "right playce" > I use vi; my ctrl key is immediately left of the "A" key as > intended by the Flying Spaghetti Monster. -- Grant From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Nov 30 11:51:15 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 30 Nov 2007 17:51:15 +0100 Subject: Yet another database question, please In-Reply-To: <47503cfa$0$228$e4fe514c@news.xs4all.nl> References: <47500ee6$0$228$e4fe514c@news.xs4all.nl> <47501469$0$3125$426a74cc@news.free.fr> <47501cd0$0$228$e4fe514c@news.xs4all.nl> <475034bc$0$26771$426a74cc@news.free.fr> <47503cfa$0$228$e4fe514c@news.xs4all.nl> Message-ID: <47503f6a$0$14714$426a74cc@news.free.fr> nmp a ?crit : > Bruno Desthuilliers wrote: > > [..] > >> About DB access, there are two major APIs : the official (low-level - >> that is,relatively to the other one...) db-api, and the higher-level >> SQLAlchemy package. Note that while having an ORM part, SQLAlchemy is >> first an higher-level SQL/Python integration layer, so you can still >> think "relational" - but with something much more powerful than strings >> to build your queries. >> >> Tying the model (wether relational or not) with the UI is quite a >> different problem. I assume you know what MVC mean, and from then I'm >> afraid I can't help more. > > MVC is one of those vague abbreviations that describe the architecture of > three-tier client/server applications, right? :) Nope. It's one of those vague abbreviations that describes the architecture of GUI applications !-) More seriously, the original MVC concept (which comes from Smalltalk) is still worth studying. > Anyway, I think I have found some study material. I don't know whether > these are really good examples, but I will be studying the source code of > and . > These seem to be two programs in the same style that I want to create, > using both SQLAlchemy and PyGTK. > > I have also found (looks trustworthy) and > (website offline at the moment?) > which could be alternatives for SQLAlchemy. I am not sure at this point > if I want to go that course. > Well, having used SQLAlchemy, I can tell you it's really worth it's weight in gold. From robin at reportlab.com Mon Nov 19 07:42:38 2007 From: robin at reportlab.com (Robin Becker) Date: Mon, 19 Nov 2007 12:42:38 +0000 Subject: struct,long on 64-bit machine In-Reply-To: References: Message-ID: <474184BE.2050804@chamonix.reportlab.co.uk> Neal Becker wrote: > What's wrong with this? > type(struct.unpack('l','\00'*8)[0]) > > > Why I am getting 'int' when I asked for 'long'? > > This is on python-2.5.1-15.fc8.x86_64 > On my AMD 64 I think int is 64 bits $ python -c "import sys; print sys.maxint" 9223372036854775807 -- Robin Becker From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Nov 23 13:24:37 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 23 Nov 2007 19:24:37 +0100 Subject: png transparency with PIL References: Message-ID: <5qok75F10ste0U1@mid.individual.net> Robin Becker wrote: > I'm trying to determine the transparency information for a png > image. With gif images I can determine the colour that is used for > transparent areas using im.info['transparency']. For the png > images of interest there is no such entry in the info dict. I > assume that's because of the way png does transparency. I'm > guessing I need the alpha channel, but is there a way to get hold > of it? For accessing the alpha channel, there is an RGBA mode for PNG files: http://www.pythonware.com/library/pil/handbook/format-png.htm Regards, Bj?rn -- BOFH excuse #58: high pressure system failure From James.w.Howard at gmail.com Mon Nov 5 14:41:39 2007 From: James.w.Howard at gmail.com (JamesHoward) Date: Mon, 05 Nov 2007 19:41:39 -0000 Subject: IDLE won't color code! In-Reply-To: <1194291203.040543.98970@v29g2000prd.googlegroups.com> References: <1194291203.040543.98970@v29g2000prd.googlegroups.com> Message-ID: <1194291699.616313.53230@o38g2000hse.googlegroups.com> On Nov 5, 12:33 pm, "ram.rac... at gmail.com" wrote: > Please help! > IDLE color codes only the shell, not the open files! How can I solve > this? My first guess is that idle is opening files without the .py extension. If that isn't it, what operating system are you using? What version of python and idle are you using? James Howard From malaclypse2 at gmail.com Wed Nov 28 11:28:53 2007 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 28 Nov 2007 11:28:53 -0500 Subject: WindowsError: [Error 5] Access is denied With _winreg.enum In-Reply-To: References: Message-ID: <16651e80711280828p544650e6t6183d4395e0513c7@mail.gmail.com> On Nov 28, 2007 11:04 AM, black_13 wrote: > I have included a small script the reproduces the error I am having in > larger script. The line 'hkey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,name)' > seems to be causing the error but im not sure why. ... > WindowsError: [Error 5] Access is denied Your user does not have permission to open the registry key you requested. On my local machine, HKEY_LOCAL_MACHINE/SECURITY is only accessible by the SYSTEM account. Even Administrative users do not have Read rights to that key by default. If you want to skip keys you don't have permission to access, you could do something like this: import _winreg for index in xrange(_winreg.QueryInfoKey(_winreg.HKEY_LOCAL_MACHINE)[0]): try: name = _winreg.EnumKey(_winreg.HKEY_LOCAL_MACHINE,index) hkey = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,name) except WindowsError: print "Could not access registry key", name else: print name, hkey -- Jerry From david at nospam.spam Sun Nov 4 19:03:36 2007 From: david at nospam.spam (david) Date: Mon, 05 Nov 2007 11:03:36 +1100 Subject: python at command prompt In-Reply-To: <9nupi3lula431c9ee9svvtkib5igjfvalf@4ax.com> References: <1193933820.086265.19100@57g2000hsv.googlegroups.com> <9nupi3lula431c9ee9svvtkib5igjfvalf@4ax.com> Message-ID: <13isneo214ebn33@corp.supernews.com> Tim Roberts wrote: > Ton van Vliet wrote: >> There's could also be an issue with entering 'python' at the command >> line, and not 'python.exe'. Once the PATH is setup correctly, try to >> enter 'python.exe', and check whether that works. >> >> IMHO, to get any 'program-name' (without the .exe extension) to work, >> one needs to: >> 1. register the executable with windows (doesn't work for python) or >> 2. make sure the the PATHEXT environment variable is set correctly, >> and includes the .EXE extension (on my w2k system it looks like: >> .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH) > > You're confusing two things here. Executables (.exe) are always available, > and do not need to be registered to be run without the extension. > > It is possible to have Windows execute "abc.py" when you type "abc", and > that DOES require registering the .py extension and adding .py to the > PATHEXT environment variable. > > A very useful thing to do, by the way. I have many command line tools for > which I have forgotten whether they are batch files, small executables, or > Python scripts. And that's how it should be. That is, "Executables (.exe) are always available," ... provided that the PATHEXT environment variable has not been set incorrectly... and "Executables ... do not need to be registered" [david] From daftspaniel at gmail.com Wed Nov 28 16:15:33 2007 From: daftspaniel at gmail.com (daftspaniel at gmail.com) Date: Wed, 28 Nov 2007 13:15:33 -0800 (PST) Subject: Python Network Graph Library Message-ID: Hi Folks, I am looking for a network Graph Library with Python bindings (Iron or C!). Just need a simple relationship visualisation - seen a few via google but many seem to be unmaintained. Any suggestions? Thanks, Davy Mitchell -- Davy Mitchell Blog - http://daftspaniel.blogspot.com Twitter - http://twitter.com/daftspaniel Skype - daftspaniel needgod.com From tal.no.no.spam at gmail.com Wed Nov 7 17:32:26 2007 From: tal.no.no.spam at gmail.com (Tal Einat) Date: Wed, 07 Nov 2007 14:32:26 -0800 Subject: command-line arguments in IDLE In-Reply-To: <1194397079.632843.16240@t8g2000prg.googlegroups.com> References: <1194397079.632843.16240@t8g2000prg.googlegroups.com> Message-ID: <1194474746.735689.17770@o80g2000hse.googlegroups.com> Russ P. wrote: > Is it possible to pass command-line arguments when running a program > in IDLE? The "Run" menu does not seem to provide that option. Thanks. thunderfoot's workaround should work well, but requires changing the script. If you want IDLE environment, but don't mind running IDLE from the command line, you can do the following: idle.py -r scriptname.py this is a test The script will run inside IDLE's shell with sys.argv set as you would expect. The output will go to IDLE's shell, and once the script is done running the shell will become interactive. (idle.py is usually found in your Python installation under Lib/ idlelib/) - 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 Graham.Dumpleton at gmail.com Thu Nov 22 16:49:35 2007 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Thu, 22 Nov 2007 13:49:35 -0800 (PST) Subject: Python web frameworks References: <226020ef-3955-43e8-b1f6-2ba9ba43d45e@c29g2000hsa.googlegroups.com> <5qga2mFvuljgU1@mid.uni-berlin.de> <160f8bbc-70be-4dcb-8874-de72588c1d10@d61g2000hsa.googlegroups.com> <1b343163-e755-44f8-b5c3-4af56c61e817@c29g2000hsa.googlegroups.com> <93a92a82-cf3c-4ebb-a93f-180374e5f75a@e4g2000hsg.googlegroups.com> <00c0167e-3b4c-4476-b473-1f938a54db63@e1g2000hsh.googlegroups.com> Message-ID: On Nov 23, 4:00 am, Istvan Albert wrote: > On Nov 21, 12:15 am, Graham Dumpleton > wrote: > > > I would say that that is now debatable. Overall mod_wsgi is probably a > > better package in terms of what it has to offer. Only thing against > > mod_wsgi at this point is peoples willingness to accept something that > > is new in conjunction with Linux distributions and web hosting > > companies being slow to adopt new packages. > > Yes that is to be expected, many people want someone else to pay the > early adopter's costs. Nonetheless mod_wsgi seems like the right > direction to move the python world. > > One confounding factor that may slow its adoption could be the need of > running plain old CGI in an efficient way. I'm not sure how that fits > into the WSGI picture. Do note that using mod_wsgi doesn't preclude you still running plain old CGI scripts using mod_cgi or mod_cgid. As to making it more efficient, one can go two paths on this. The preferred path would be to put in the effort to convert the Python CGI application to WSGI. If one still needs to run it as CGI with other hosting solutions, then use a CGI-WSGI adapter. Second, albeit a bit of a kludge, just like mod_python.cgihandler is a kludge, is to emulate the CGI environment on top of WSGI. This would work if using single threaded Apache prefork MPM, or using mod_wsgi daemon mode with multiple processes but where each is single threaded. It wouldn't be practical though to do it for multithread Apache worker MPM, or multithreaded daemon processes with mod_wsgi daemon mode. Because of how Python leaks environment variables between sub interpreters, you would also only want to be running one sub interpreter within a process. This would be fine if using mod_wsgi daemon mode as different CGI scripts could be delegated to run in different daemon processes as necessary to keep them separate, but may not be practical if using embedded mode if hosting a range of other WSGI applications at the same time in embedded mode. So, it is doable, but effort would be better off expended at least converting the Python CGI script to WSGI instead. It would save a lot of trouble in the long run, especially with CGI scripts which weren't designed to be run multiple times in same memory context, ie., where they don't clean up after themselves. If someone really wanted to host an existing CGI script under WSGI where the same process was used over and over, and had good reasons for doing so, it wouldn't be hard for me to come up with a workable adapter that allowed it. Graham From mhearne808 at gmail.com Mon Nov 19 17:12:36 2007 From: mhearne808 at gmail.com (mhearne808[insert-at-sign-here]gmail[insert-dot-here]com) Date: Mon, 19 Nov 2007 14:12:36 -0800 (PST) Subject: compiling python 2.5, missing zlib References: <4741FDDF.8070505@v.loewis.de> Message-ID: <693e08b5-2911-4c9c-a00f-f7b6ceae66a3@e4g2000hsg.googlegroups.com> On Nov 19, 2:19 pm, "Martin v. L?wis" wrote: > > Neither seems to work. What am I missing here? > > You forgot to install the zlib header files, which come in > an RPM provided by Redhat (probably called zlib-dev or some > such). > > Regards, > Martin Those headers are already installed, according to "up2date". Is there a way to specify the header files used? --Mike From gnewsg at gmail.com Fri Nov 9 19:44:27 2007 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Fri, 09 Nov 2007 16:44:27 -0800 Subject: ftplib ssl/tls support? Message-ID: <1194655467.564042.119940@o38g2000hse.googlegroups.com> I noticed that poplib, smtplib, httplib, imaplib and probably others include support for ssl connections. Are there future plans for ftplib ssl/tls support? From python.list at tim.thechases.com Thu Nov 8 09:11:27 2007 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 08 Nov 2007 08:11:27 -0600 Subject: Python iPod challenge In-Reply-To: <1194530006.878927.274830@t8g2000prg.googlegroups.com> References: <1194513690.380607.86460@d55g2000hsg.googlegroups.com> <1194530006.878927.274830@t8g2000prg.googlegroups.com> Message-ID: <4733190F.8070802@tim.thechases.com> >> if you are interested please be so kind to visit: >> >> http://test-iq.web.cern.ch/test-iq/step1.php?lang=en > > Well, just out of curosity, i started the test, however, it seems a > little bugy. My answer to the first question one was: [snipped] > getting the following error: > > SYNTAX ERROR Check line 3 text = 'In principio creavit Deus caelum et > terram. Terra autem erat' ^ > > Im not sure but i think you are looking for only one method of getting > the answer, however, there are several ways to achieve it, so, im > done..lol, no offense, but if im going to fail the test, i want to > fail because i did it wrong and not because i did it different.. I had similar problems. Additionally, that's pretty unpythonic code, as the "correct" answer would be something like print text.count("a") which obviates the whole looping/testing/counting aspect, letting Python just do its thing instead. The whole thing also seemed to fail if JavaScript/Cookies were turned off (I don't know which was the culprit...two strikes was enough to ). -tkc From bdesth.quelquechose at free.quelquepart.fr Fri Nov 30 14:15:35 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 30 Nov 2007 20:15:35 +0100 Subject: Need to call functions/class_methods etc using string ref :How In-Reply-To: References: <9a63e8920711260237u223abc66x1cb6d6cee3492bfa@mail.gmail.com> <20071126155840.GA5180@sdf.lonestar.org> <474b18e2$0$20133$426a74cc@news.free.fr> Message-ID: <4750616d$0$12468$426a74cc@news.free.fr> George Sakkis a ?crit : > On Nov 26, 2:04 pm, Bruno Desthuilliers > > wrote: > >>Donn Ingle a ?crit : >> >> >>>>I see someone already showed you eval. Eval is evil. Don't use it. >>>>Especially if the functions are coming to you from a public URL! >> >>>Yes, I suggested to him (by email) this: >> >>>thisinstance = SomeObject.__class__.__dict__ >>> >> >>This will only get attributes defined in SomeObject.__class__ - not the >>one defined in the parent classes. Nor methods dynamically bound to a >>specific instance. >> >> >> >> >>>for f in yourlist: >>> if f in thisinstance: eval(f)(params) >> >>>Which would vet the functions too. >> >>You *still* don't need eval here. >> >>target = >>for funcname in funclist: >> func = getattr(target, funcname, None) >> if callable(func): >> func(*args, **kwargs) >> >>I've almost never had a real use case for eval (or exec) in 7 years. > > > That's not to say there aren't any. Indeed. But most of the time, I found that Python provides a more appropriate solution. > In one project I'm using exec to > parse user provided function bodies from a web interface into real > python functions (the function signatures are auto generated). A problem I've never had to solve so far, so you're the expert here - but what about compiling the source with compile, then instanciating a function object from it ? (snip) From deets at nospam.web.de Mon Nov 12 05:16:23 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 12 Nov 2007 11:16:23 +0100 Subject: python - an eggs... References: Message-ID: <5pqnfnFshiqkU1@mid.uni-berlin.de> bruce wrote: > Hi Diez... > > I've never used setuptools, (it's not on the box) and i don't have > easy_install tools installed... > > But in looking at your output, I have some questions... > -The 1st, I'm assuming that easy_install works with python2.4.3? > -The 2nd, In the output, is see the durus egg... with the "durus" path > being relative to the egg... are the actual durus files in that dir?? > -3rd question.. in searching the 'net, it appears that i have to download > setuptools in order to get easy_install. Am I missing something here, or > is this correct? > > Thanks for your pointers on this!! So far, you deliberately ignored the pointers. Otherwise, you wouldn't need to ask above questions. Diez From z80vsvic20 at hotmail.com Sun Nov 18 12:22:49 2007 From: z80vsvic20 at hotmail.com (Eric von Horst) Date: Sun, 18 Nov 2007 09:22:49 -0800 (PST) Subject: Looking for a event-message-qeue framework Message-ID: <95f5ce6a-4342-4f69-9566-650ce75ee8f4@w34g2000hsg.googlegroups.com> Hi, I am looking for a kind of framework that let's me send events between systems. What I had in mind is common event bus that can be spread over multiple systems. On each system, there should be sort of an 'agent' that listens to the events on the bus and acts upon them if they are destined for the agent. The agent should also be able to send events. Some queue mechanism would also be nice. Is there something like this in Python? (I really want to avoid Java or MQ series) Eric From nospam at invalid.com Wed Nov 28 14:16:58 2007 From: nospam at invalid.com (Jack) Date: Wed, 28 Nov 2007 11:16:58 -0800 Subject: Trying to build cjson on Widnows, getting errors Message-ID: Since I don't have VS2003, I'm trying to build cjson with MingW and Cygwin but I'm getting lots of errors like these: build\temp.win32-2.5\Release\cjson.o(.text+0x8e):cjson.c: undefined reference to `_imp___Py_NoneStruct' build\temp.win32-2.5\Release\cjson.o(.text+0x95):cjson.c: undefined reference to `_imp___Py_NoneStruct' build\temp.win32-2.5\Release\cjson.o(.text+0x122):cjson.c: undefined reference t o `_imp___Py_TrueStruct' build\temp.win32-2.5\Release\cjson.o(.text+0x129):cjson.c: undefined reference t o `_imp___Py_TrueStruct' build\temp.win32-2.5\Release\cjson.o(.text+0x15d):cjson.c: undefined reference t o `_imp___Py_ZeroStruct' Any idea what I'm missing? Thanks. From benruza at gmail.com Fri Nov 16 19:47:16 2007 From: benruza at gmail.com (Bruza) Date: Fri, 16 Nov 2007 16:47:16 -0800 (PST) Subject: implement random selection in Python References: Message-ID: On Nov 16, 6:58 am, duncan smith wrote: > Bruza wrote: > > I need to implement a "random selection" algorithm which takes a list > > of [(obj, prob),...] as input. Each of the (obj, prob) represents how > > likely an object, "obj", should be selected based on its probability > > of > > "prob".To simplify the problem, assuming "prob" are integers, and the > > sum of all "prob" equals 100. For example, > > > items = [('Mary',30), ('John', 10), ('Tom', 45), ('Jane', 15)] > > > The algorithm will take a number "N", and a [(obj, prob),...] list as > > inputs, and randomly pick "N" objects based on the probabilities of > > the > > objects in the list. > > > For N=1 this is pretty simply; the following code is sufficient to do > > the job. > > > def foo(items): > > index = random.randint(0, 99) > > currentP = 0 > > for (obj, p) in items: > > currentP += w > > if currentP > index: > > return obj > > > But how about the general case, for N > 1 and N < len(items)? Is there > > some clever algorithm using Python standard "random" package to do > > the trick? > > I think you need to clarify what you want to do. The "probs" are > clearly not probabilities. Are they counts of items? Are you then > sampling without replacement? When you say N < len(items) do you mean N > <= sum of the "probs"? > > Duncabn I think I need to explain on the probability part: the "prob" is a relative likelihood that the object will be included in the output list. So, in my example input of items = [('Mary',30), ('John', 10), ('Tom', 45), ('Jane', 15)] So, for any size of N, 'Tom' (with prob of 45) will be more likely to be included in the output list of N distinct member than 'Mary' (prob of 30) and much more likely than that of 'John' (with prob of 10). I know "prob" is not exactly the "probability" in the context of returning a multiple member list. But what I want is a way to "favor" some member in a selection process. So far, only Boris's solution is closest (but not quite) to what I need, which returns a list of N distinct object from the input "items". However, I tried with input of items = [('Mary',1), ('John', 1), ('Tom', 1), ('Jane', 97)] and have a repeated calling of Ben From bborcic at gmail.com Fri Nov 2 07:27:31 2007 From: bborcic at gmail.com (Boris Borcic) Date: Fri, 02 Nov 2007 12:27:31 +0100 Subject: new style class In-Reply-To: <1194002609.296417.111050@v3g2000hsg.googlegroups.com> References: <1194002609.296417.111050@v3g2000hsg.googlegroups.com> Message-ID: <472b09dd$1_7@news.bluewin.ch> gert wrote: > class Test(object): > > def execute(self,v): > return v > > def escape(v): > return v > > if __name__ == '__main__': > gert = Test() > print gert.m1('1') > print Test.m2('2') > > Why doesn't this new style class work in python 2.5.1 ? > why should it ? From j3nsby at gmail.com Tue Nov 6 20:43:39 2007 From: j3nsby at gmail.com (Jens) Date: Wed, 07 Nov 2007 01:43:39 -0000 Subject: Python good for data mining? In-Reply-To: <1194359176.070030.40770@o80g2000hse.googlegroups.com> References: <1194141739.683498.206780@k79g2000hse.googlegroups.com> <1194314950.490427.210210@v3g2000hsg.googlegroups.com> <1194351005.291502.50170@v3g2000hsg.googlegroups.com> <1194359176.070030.40770@o80g2000hse.googlegroups.com> Message-ID: <1194399819.226243.310250@d55g2000hsg.googlegroups.com> > > Jens, > > You might be interested in this bookhttp://www.oreilly.com/catalog/9780596529321/index.html > which is new, I just ordered my copy. From the contents shown online, > it has lot of applicability to data mining, using Python, although it > its primary topic is data mining the web, it also covers analyzing the > data etc. > > Ron Stephens > I'm a big fan of O'Reilly's books. This one looks very promising, and I have just added it to my wishlist. Thanks for the tip Ron! As for databases - I think its a good idea to support a good selection of data sources. Just now, one of my main concerns, is to make a structure that is flexible enough, as well as being easy to use. Flexibility and usability! From chris at simplistix.co.uk Mon Nov 19 07:09:24 2007 From: chris at simplistix.co.uk (Chris Withers) Date: Mon, 19 Nov 2007 12:09:24 +0000 Subject: What is python????? In-Reply-To: <5qda3kFv123mU1@mid.uni-berlin.de> References: <7ab5b781-3c6c-4fb5-9be1-703d5e7e73a6@s12g2000prg.googlegroups.com> <5qda3kFv123mU1@mid.uni-berlin.de> Message-ID: <47417CF4.7060000@simplistix.co.uk> Diez B. Roggisch wrote: > It's amazing that recently so many spam is written by some guys actually > _reading_ this group. I presume they somehow want to create credibility in > their postings by provoking real threads that then at some point contain > the actual information. I wonder why this group/list isn't moderated in such a way that posts by new members are moderated at first until they're seen to be human. (and non-spamming humans to boot ;-) ) I admin a few low volume lists and it's proved very close to 100% successful in killing off the spam problem :-) cheers, Chris -- Simplistix - Content Management, Zope & Python Consulting - http://www.simplistix.co.uk From djangodev at rscorp.ab.ca Sat Nov 17 11:27:20 2007 From: djangodev at rscorp.ab.ca (Scott SA) Date: Sat, 17 Nov 2007 09:27:20 -0700 Subject: Interfaces. In-Reply-To: Message-ID: On 11/17/07, Duncan Booth (duncan.booth at invalid.invalid) wrote: >Bjoern Schliessmann wrote: > >> Benjamin wrote: >>> Python is has duck typing. "If it quacks like a duke, it's duck." >> >> How do dukes quack, exactly? :) > >They quack with a North-eastern Scottish accent of course. > >The following excerpt from "Scots: Practical Approaches" should make it >clear: > >> A. From Scotland the What?, by Buff Hardie, Stephen Robertson and >> George Donald (Gordon Wright, 1987) >> >> In this comic monologue from 1982, the owner of a toy shop in >> Ballater, near Aberdeen telephones the Princess of Wales to ask what >> her son would like for Christmas. >> >> Noo, fit wid he like for his Christmas, the loon? Fit aboot a pair o? >> fitba beets? Beets. Beets. B-O-O-T-S, beets. Weel, I ken that, but ../snip/... >> D-U-C-K, duke. A quack quack duke. Like Donald Duke. Donald Duke. He?s >> a freen? o? Mickey Moose...Moose...M-O-U-S-E, Moose! God, div ye nae >> understan? English, lassie? I think me sister wah bit be onae eese. Is ears nae long enuff ta be a rrhabbitt, an ah latter nae care fer cheese. From gregpinero at gmail.com Thu Nov 8 14:22:59 2007 From: gregpinero at gmail.com (gregpinero at gmail.com) Date: Thu, 08 Nov 2007 19:22:59 -0000 Subject: Using imaplib module with GMAIL's IMAP - hangs In-Reply-To: <1194547974.193957.141650@e34g2000pro.googlegroups.com> References: <1194547285.816141.110230@v29g2000prd.googlegroups.com> <1194547974.193957.141650@e34g2000pro.googlegroups.com> Message-ID: <1194549779.482298.141530@v23g2000prn.googlegroups.com> On Nov 8, 1:52 pm, Jason wrote: > On Nov 8, 11:41 am, "gregpin... at gmail.com" > wrote: > > > I'm trying to get a list of messages from GMAIL using it's new IMAP > > access. > > > So far I've tried running this command but it just hangs. Any ideas? > > > >>> import imaplib > > >>> M=imaplib.IMAP4('imap.gmail.com',993) > > > I figured that's the first line to run from this example:http://docs.python.org/lib/imap4-example.html > > > Here are the configuration settings GMAIL says to use:https://mail.google.com/support/bin/answer.py?answer=78799 > > > Thanks for any help. > > > -Greg > > Well, Google states that it's using SSL. You're not using the SSL > with your example code. Take a look in the imaplib module. At least > under Python 2.5, there's also an IMAP4_SSL class: > > >>> import imaplib > >>> mail = imaplib.IMAP4_SSL('imap.gmail.com', 993) > > That worked for me. I could then use the login method to log into the > mail server. > > --Jason Followup question. My ultimate goal is to get all messages with a certain GMAIL label. I'm going under the assumption labels will appear as folders over IMAP. Any idea how to access folders with IMAP? -Greg From ramamoorthy003 at gmail.com Sat Nov 24 05:24:33 2007 From: ramamoorthy003 at gmail.com (roja) Date: Sat, 24 Nov 2007 02:24:33 -0800 (PST) Subject: see the jop Message-ID: see the jop http://earnmac.blogspot.com From deets at nospam.web.de Sun Nov 18 16:54:21 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 18 Nov 2007 22:54:21 +0100 Subject: regular expression In-Reply-To: <4740ad46$0$21929$157c6196@dreader1.cybercity.dk> References: <4740ad46$0$21929$157c6196@dreader1.cybercity.dk> Message-ID: <5qbqkdFv8380U1@mid.uni-berlin.de> gardsted schrieb: > I just can't seem to get it: > I was having some trouble with finding the first following with this regex: > > Should these two approaches behave similarly? > I used hours before I found the second one, > but then again, I'm not so smart...: > > kind retards > jorgen / de mente > using python 2.5.1 > ------------------------------------------- > import re > > TESTTXT=""" SAMPLES "" "" > > > MAINSEND 1 > ACT 1 > > > ACT 1 > > > > > > > """ > print "The First approach - flags in finditer" > rex = re.compile(r'^<(?P[a-zA-Z0-9_]*)') > for i in rex.finditer(TESTTXT,re.MULTILINE): > print i,i.groups() > > print "The Second approach - flags in pattern " > rex = re.compile(r'(?m)^<(?P[a-zA-Z0-9_]*)') > for i in rex.finditer(TESTTXT): > print i,i.groups() What the heck is that format? XML's retarded cousin living in the attic? Ok, back to the problem then... This works for me: rex = re.compile(r'^<(?P[a-zA-Z0-9_]+)',re.MULTILINE) for i in rex.finditer(TESTTXT): print i,i.groups() However, you might think of getting rid of the ^ beceause otherwise you _only_ get the first tag beginning at a line. And making the * a + in the TAGNAME might also be better. Diez From timr at probo.com Fri Nov 2 01:56:41 2007 From: timr at probo.com (Tim Roberts) Date: Fri, 02 Nov 2007 05:56:41 GMT Subject: os.readlink returning value References: <1193968274.369843.167520@v3g2000hsg.googlegroups.com> Message-ID: <2ueli3t3tsrrkn9fbnpfb9p3n2j30tjcqj@4ax.com> Giampaolo Rodola' wrote: > >I was reading os.readlink doc which says: > >readlink( path) > >Return a string representing the path to which the symbolic link >points. The result may be either an absolute or relative pathname; if >it is relative, it may be converted to an absolute pathname using >os.path.join(os.path.dirname(path), result). Availability: Macintosh, >Unix. > >...It's not clear to me when the returning result could be absolute >and when it could be relative. >Could someone clarify this point? It will be relative if the symbolic link is relative, and absolute if the symbolic link is absolute. ln -s ../../over/there here1 ln -s /home/timr/spot here2 "here1" is a relative link. "here2" is an absolute link. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From gagsl-py2 at yahoo.com.ar Sat Nov 17 06:47:51 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 17 Nov 2007 08:47:51 -0300 Subject: Fwd: Sorting Countries by Region References: <4375355d-b23e-4a1c-8f4b-183156a163c5@f13g2000hsa.googlegroups.com> <0ed483f8-da41-479f-bd39-6b8155d7a7a3@e4g2000hsg.googlegroups.com> Message-ID: En Sat, 17 Nov 2007 08:34:43 -0300, escribi?: > for i, country in countries_list: > if country in REGIONS_COUNTRIES['European Union']: > matrix.write(i+2, 1, country) > but I got "ValueError: too many values to unpack" Remove the i, and try again... -- Gabriel Genellina From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Nov 29 09:25:53 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 29 Nov 2007 15:25:53 +0100 Subject: Science list References: Message-ID: <5r80fhF11ssjvU1@mid.individual.net> Francesco Pietra wrote: > Nonetheless, this extremely useful list is so crowded that if > checking email is not carried out every few hours, it is difficult > to detect other messages in the plethora of pythons and spams > arrived. Why don't you use a newsreader to access comp.lang.python? It's suited much better for tracking long and many threads. Regards, Bj?rn -- BOFH excuse #357: I'd love to help you -- it's just that the Boss won't let me near the computer. From deets at nospam.web.de Tue Nov 20 06:28:16 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 20 Nov 2007 12:28:16 +0100 Subject: VB6 frontend GUI with Python References: <5qforcFvoi0oU1@mid.uni-berlin.de> Message-ID: <5qfumgFv5oirU3@mid.uni-berlin.de> > Simple. its because my main application (the GUI that is), is written in > VB6. I have a MDI application (i.e. many child windows in the same > application), and I want to use one of these windows as a console to > inteactively type Python commands. If I were to use wxPython, I would > not be able to treat the console 'the same' as the other child windows > in the application (i.e. minimize, close all etc). Maybe a simpler way > to think of this is to imagine that I am writing a PythonWin clone in > VB6. What I am asking here, is how can I create the 'Interactive Window' ? Your asking for more. Your asking for the interactive window (which shouldn't be too hard, just using subprocess and somehow attaching stdin/stdout - there should be code that does that) AND you are asking for integration of GUI. Which is much more complicated. I'm not a windows guru, but at least you need a way to communicate a window-handle to some background thread or so of the python interpreter, which will be used to render the plot. But that of course implies that the various plotting libs are somehow capable of doing so. I know that for example under X-windwow, you can "capture" one window and display it as part of another. If there exists something like that in Windwos, a way to shell various applications, that would help you. Apart from that the only thing that comes to my mind is an ActiveX-control, but even there I'm ont sure how event-loops and stuff behave. All in all - an integration hell.... Diez From mauriceling at acm.org Fri Nov 23 07:56:18 2007 From: mauriceling at acm.org (Maurice LING) Date: Fri, 23 Nov 2007 12:56:18 GMT Subject: The Python Papers is looking for additional Associate Editors Message-ID: <4746cdee$1@news.unimelb.edu.au> "The Python Papers" (http://pythonpapers.org), ISSN 1834-3147, is an online e-journal, covering articles on Python in the community, industry and academia. We were established in the second half of 2006 and launched our first issue in November 2006. Since then, we have released 3 more issues. Recently, we have also initiated a monograph series, which will be known as "The Python Papers Monograph Series" (http://pythonpapers.org/monograph.html) with its own ISSN, but managed by "The Python Papers" Editorial Committee. Due to this new initiative, we are looking for an additional member to join the team as an Associate Editor from February 2008. The main roles of an Associate Editor includes: 1. Organizing and chairing reviews for submissions 2. Reviewing submissions 3. Answering queries regarding the periodicals 4. Assisting the Editor-in-Chief in tasks as required The current workload is estimated to be about 3 hours per week. We invite committed individuals with a good knowledge of Python programming to join our team. Please send in your CV, a statement of intention, and answer the following questions to us at editor at pythonpapers.org before December 20, 2007. 1. An account of your programming experiences using your projects for illustrations 2. An account of your publication record and experiences with peer-review process 3. A brief description of your expertise in computer science 4. A brief account of your understanding about The Python Papers 5. How will you propose to improve The Python Papers Please direct any queries to editor at pythonpapers.org Thank you Maurice Ling Associate Editor, The Python Papers From salgerman at gmail.com Fri Nov 9 23:43:57 2007 From: salgerman at gmail.com (gsal) Date: Fri, 09 Nov 2007 20:43:57 -0800 Subject: easy 3D graphics for rendering geometry? In-Reply-To: <1194651348.799290.39100@v3g2000hsg.googlegroups.com> References: <1194501211.730458.44000@o80g2000hse.googlegroups.com> <13j7ls18d9dn5f5@corp.supernews.com> <1194651348.799290.39100@v3g2000hsg.googlegroups.com> Message-ID: <1194669837.381577.107750@o80g2000hse.googlegroups.com> By the way, VPython crashes my computer rather easily: - launch the editor - open python file - press F5 to run - when the graphical windows first appears, it will be accompanied by a cursor AND a sand watch to indicate that python is busy doing somethin...if before the watch goes away, I attempt to manipulate (drag or resize) the window... - ...the computer looses it! At the end, sometimes, the computer looks like is trying to take care of things but simply takes forever; other times, I end up with a blank screen and an unresponsive computer and have to press the power button for about 10 seconds to get it to power off. gsal From ladynikon at gmail.com Mon Nov 12 21:42:41 2007 From: ladynikon at gmail.com (Danyelle Gragsone) Date: Mon, 12 Nov 2007 21:42:41 -0500 Subject: A JEW hacker in California admits distributing malware that let him steal usernames and passwords for Paypal accounts. In-Reply-To: References: <1194732615.277219.168670@o38g2000hse.googlegroups.com> <1194890656.529348.85610@v65g2000hsc.googlegroups.com> <4738a9a5$0$27051$ecde5a14@news.coretel.net> <1194905259.017086.194100@19g2000hsx.googlegroups.com> Message-ID: <59f9c5160711121842q188e5ccckeb0f0c1edef1e55a@mail.gmail.com> Please 2 stop feeding the trolls.. From stef.mientki at gmail.com Thu Nov 1 16:55:32 2007 From: stef.mientki at gmail.com (stef mientki) Date: Thu, 01 Nov 2007 21:55:32 +0100 Subject: Is it possible to use a instance property as a default value ? In-Reply-To: <4866bea60711011320y7c748adbucb2b48afc7043e3b@mail.gmail.com> References: <472A3482.9030803@gmail.com> <4866bea60711011320y7c748adbucb2b48afc7043e3b@mail.gmail.com> Message-ID: <472A3D44.7090302@gmail.com> Chris Mellon wrote: > On Nov 1, 2007 3:18 PM, stef mientki wrote: > >> hello, >> >> I would like to use instance parameters as a default value, like this: >> >> class PlotCanvas(wx.Window): >> def __init__(self) >> self.Buf_rp = 0 >> self.Buf_wp = 0 >> >> def Draw ( self, x1 = self.Buf_rp, x2 = self.Buf_wp ) : >> >> is something like this possible ? >> >> > > No, because self is not in scope at the time that default arguments > are evaluated. The traditional workaround is to use x1=None, and if x1 > is None: x1 = self.Buf_rp. > > thanks Chris, I was afraid of that ;-) cheers, Stef From lasses_weil at klapptsowieso.net Sat Nov 10 16:57:30 2007 From: lasses_weil at klapptsowieso.net (Wildemar Wildenburger) Date: Sat, 10 Nov 2007 22:57:30 +0100 Subject: security code whit python In-Reply-To: <1194710640.804970.28150@19g2000hsx.googlegroups.com> References: <1194710640.804970.28150@19g2000hsx.googlegroups.com> Message-ID: <4736294d$0$16656$9b4e6d93@newsspool3.arcor-online.net> oruccim at gmail.com wrote: > I want to create picture of security code.can i do it ? I don't know what you mean by "security code". I take it you want to create technical diagrams, from a sort of algorithmic description? PIL might help you, as paulC pointed out. It works on raster images (bitmaps). pYx is a tool library for vector graphics and scientific plots. Maybe that can help. I've produced nice looking graphics of search-trees within about 60 minutes of installing it. This example is copied right from the pyx site: from pyx import * c = canvas.canvas() c.text(0, 0, "Hello, world!") # Put oruccim here, if you want c.stroke(path.line(0, 0, 2, 0)) c.writeEPSfile("hello") c.writePDFfile("hello") /W From nytrokiss at gmail.com Thu Nov 8 06:44:40 2007 From: nytrokiss at gmail.com (James Matthews) Date: Thu, 8 Nov 2007 12:44:40 +0100 Subject: >>>> 911 operation by evil JEWS and Mossad <<<< In-Reply-To: <1194521283.443284.15070@k35g2000prh.googlegroups.com> References: <1194448081.967583.96940@k79g2000hse.googlegroups.com> <1194521283.443284.15070@k35g2000prh.googlegroups.com> Message-ID: <8a6b8e350711080344l7f11435agdcdb2596efe271b5@mail.gmail.com> Thank You! Maybe we can get rid of this guy now... This is a python group... On Nov 8, 2007 12:28 PM, philipp neulist wrote: > On Nov 7, 4:08 pm, zionist.j... at gmail.com wrote: > > 911 carried out by evil jews and > mossadhttp://www.guba.com/watch/2000991770 > > > > 911 truckload of Explosives on the George Washington > Bridgehttp://www.youtube.com/watch?v=J520P-MD9a0 > > > [...] > > I reported the first post in this thread (on Google groups) as abuse > as its content is "false and defamatory". In addition to that, it has > nothing to do with TeX. > > => Double reason to blaim the author! > > Please ignore threads like those in future and just report it! > > PN > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://search.goldwatches.com/ http://www.jewelerslounge.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From abarun22 at gmail.com Thu Nov 29 00:43:01 2007 From: abarun22 at gmail.com (abarun22 at gmail.com) Date: Wed, 28 Nov 2007 21:43:01 -0800 (PST) Subject: How to access nested structural members from python Message-ID: <083cd4aa-eb99-4b95-b225-676d4dfcd65e@d21g2000prf.googlegroups.com> Hi I would like to know if there are any ways to access the members of a nested structure inside python. I use SWIG as interface for C. My structure comes as follows. struct SA{ int nb_dep, max_dep SB *b } struct SB{ int id[10], node, kg; double dep[3]; } I have written a C helper function like this to access the internal members of the structure SB. SB get_sb(SB *b, int index){ return(b[index]); } >From python i call like this for example: >>modname.get_sb(sb, i).node where i=1,2....N What i would like to know is that any other way to access the internal pieces of nested structure. Any ideas in this regard are most welcome. From unews at onlinehome.de Fri Nov 2 04:19:51 2007 From: unews at onlinehome.de (Uwe Grauer) Date: Fri, 02 Nov 2007 09:19:51 +0100 Subject: Adding GNU Readline after installation? In-Reply-To: <1193971069.380839.63080@o3g2000hsb.googlegroups.com> References: <1193971069.380839.63080@o3g2000hsb.googlegroups.com> Message-ID: snewman18 at gmail.com wrote: > I compiled Python from source on a bunch of my development machines > without enabling the readline modules. Is it possible to add readline > support after installation? > > I really just want to get my "up arrow" history working... > No. You have to uncomment readline support in Modules/Setup, call make again and do a reinstall. Uwe From pydev at rscorp.ab.ca Sat Nov 17 13:51:50 2007 From: pydev at rscorp.ab.ca (Scott SA) Date: Sat, 17 Nov 2007 11:51:50 -0700 Subject: which Python ? asks beginner In-Reply-To: <2fbuj3p0cnf8uv1cn41j2retpqsuuc63qt@4ax.com> Message-ID: On 11/17/07, WB3DWE at bag.python.org (Dave at bag.python.org) wrote: >Have given up Java. Want to switch to Python. But _which_ ? >There is ver : > 2.5 out now > 2.6 in beta , final expected Apr 2008 > 3.0 ? in alpha or beta > 3.0 final expected Sep 2008 ? >Will the real python please stand up. In the early stages of learning, the core of 2.5 compared to earlier versions will be functionally similar if not identical. I have books on version 2.2, for example, that are still quite relevent today for a majority of things. "Go big or go home" can be a precarious philosophy to live by, so why live on the edge, when you don't know where the edge is? (let alone how sharp, steep or deap it is once you get there). 0.02 Scott From horpner at yahoo.com Tue Nov 13 13:51:11 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Tue, 13 Nov 2007 18:51:11 GMT Subject: Convert some Python code to C++ References: <1194967729.175135.39830@22g2000hsm.googlegroups.com> <1194974326.377387.191400@k79g2000hse.googlegroups.com> Message-ID: On 2007-11-13, kyosohma at gmail.com wrote: > On Nov 13, 9:28 am, meyousikm... at yahoo.com wrote: >> I am working on an implementation of the Longest Common >> Subsequence problem (as I understand it, this problem can be >> used in spell checking type activities) and have used this >> site to understand the problem and its solution: >> >> http://en.wikibooks.org/wiki/Algorithm_implementation/Strings/Longest... >> >> For those that understand algorithms and can talk Python, I >> want to convert the Python code in the section "Reading out >> all LCSs" into C++ code but I don't understand some of the >> syntax. Can anyone give me a hand? >> >> Here is the code from that section, but is probably of little >> use without understanding the entire problem setup given at >> the site above: >> >> def backTrackAll(C, X, Y, i, j): >> if i == 0 or j == 0: >> return set([""]) >> elif X[i-1] == Y[j-1]: >> return set([Z + X[i-1] for Z in backTrackAll(C, X, Y, i-1, >> j-1)]) >> else: >> R = set() >> if C[i][j-1] >= C[i-1][j]: >> R.update(backTrackAll(C, X, Y, i, j-1)) >> if C[i-1][j] >= C[i][j-1]: >> R.update(backTrackAll(C, X, Y, i-1, j)) >> return R >> >> Thanks! > > You might try Shed Skin: > > http://sourceforge.net/projects/shedskin/ > > It's been a while since I did C++. I would recommend going > through a basic C++ tutorial. I'm pretty sure the equivalence > operators are almost the same. You'll likely need to declare > the types for the arguments passed into the function as well. > > I think lists are called arrays in C++. I don't know what the > "set" equivalent is though. It is called set, oddly enough. ;) There's an overload of the set::insert function that takes a couple of iterators that will serve for Python's update method. -- Neil Cerutti From http Sun Nov 4 01:39:16 2007 From: http (Paul Rubin) Date: 03 Nov 2007 23:39:16 -0700 Subject: Low-overhead GUI toolkit for Linux w/o X11? References: <13ipjvic6aj8c69@corp.supernews.com> <13ipvnvoqoh735f@corp.supernews.com> Message-ID: <7xtzo2pl9n.fsf@ruckus.brouhaha.com> Grant Edwards writes: > There is no mouse. I'm not sure how many "widgets" are > required. Probably not very many. Back in the old days there were some lightweight toolkits for doing text mode GUI's using ANSI graphic characters for MS-DOS. I did a few of them. You could do quite usable and attractive gui's that way, as long as you didn't require too much bling. From vel.accel at gmail.com Mon Nov 5 23:50:59 2007 From: vel.accel at gmail.com (D.Hering) Date: Tue, 06 Nov 2007 04:50:59 -0000 Subject: SIP won't compile on OSX 10.3 In-Reply-To: <1194320477.278726.306810@k79g2000hse.googlegroups.com> References: <1194320477.278726.306810@k79g2000hse.googlegroups.com> Message-ID: <1194324659.164551.320900@50g2000hsm.googlegroups.com> On Nov 5, 10:41 pm, Benjamin wrote: > Hi! I'm trying to install SIP on my Mac with the eventual aim of > installing PyQt. The "python configure.py" stage works fine, but when > I type make this is what I see: > cc -c -pipe -Os -w -I. -o main.o main.c > cc -c -pipe -Os -w -I. -o transform.o transform.c > cc -c -pipe -Os -w -I. -o gencode.o gencode.c > cc -c -pipe -Os -w -I. -o export.o export.c > cc -c -pipe -Os -w -I. -o heap.o heap.c > cc -c -pipe -Os -w -I. -o parser.o parser.c > cc -c -pipe -Os -w -I. -o lexer.o lexer.c > c++ -headerpad_max_install_names -o sip main.o transform.o gencode.o > export.o heap.o parser.o lexer.o > cc -c -pipe -fPIC -Os -w -I. -I/Library/Frameworks/Python.framework/ > Versions/2.5/include/python2.5 -o siplib.o siplib.c > cc -c -pipe -fPIC -Os -w -I. -I/Library/Frameworks/Python.framework/ > Versions/2.5/include/python2.5 -o qtlib.o qtlib.c > cc -c -pipe -fPIC -Os -w -I. -I/Library/Frameworks/Python.framework/ > Versions/2.5/include/python2.5 -o threads.o threads.c > cc -c -pipe -fPIC -Os -w -I. -I/Library/Frameworks/Python.framework/ > Versions/2.5/include/python2.5 -o objmap.o objmap.c > c++ -c -pipe -fPIC -Os -w -I. -I/Library/Frameworks/Python.framework/ > Versions/2.5/include/python2.5 -o bool.o bool.cpp > c++ -headerpad_max_install_names -bundle -F/Library/Frameworks - > framework Python -o sip.so siplib.o qtlib.o threads.o objmap.o bool.o > ld: Undefined symbols: > _fstatvfs referenced from Python expected to be defined in libSystem > _lchown referenced from Python expected to be defined in libSystem > _statvfs referenced from Python expected to be defined in libSystem > make[1]: *** [sip.so] Error 1 > make: *** [all] Error 2 > > I'm not an expert at linking, but it looks like the Python lib was > built incorrectly. Or is this a SIP problem? Thanks. Do a google search for _fstatvfs, _lchown, _statvfs. I don't use mac but I'd guess your missing a needed library. From bluegatesltd at gmail.com Wed Nov 14 04:29:52 2007 From: bluegatesltd at gmail.com (bluegatesltd at gmail.com) Date: Wed, 14 Nov 2007 09:29:52 -0000 Subject: e Message-ID: <1195032592.866214.276720@i38g2000prf.googlegroups.com> END OF YEAR JUMBO SALES OFFER AND GET 2 APPLE IPHONE 8GB FREE We are offering Wholesale Prices for our all our products + FREE SHIPPING NOTE - YOU GET 2 FREE Apple iPhone 8GB And 1 Nokia 8800 Sirocco... FOR ANY 10 UNITS ORDER IN OUR JUMBO SALES OFFER OUR PRODUCTS ON OFFER : Nokia N95 --$250 Nokia N95 8GB--$300 Nokia N93i --$230 Nokia N76 --$200 Nokia N73 Music --$200 Nokia N91 --$210 Nokia 8800 Sirocco --$300 Nokia 8800 Sirocco 18K Gold--$400 Nokia 8600 Luna --$250 Nokia E90--$350 Nokia E65--$210 Nokia N800 --$220 Nokia 6300--$180 Nokia 5300--$120 Nokia 5500--$180 Apple iPhone 8GB Unlocked --$300 Apple iPhone 4GB Unlocked --$200 O2 XDA Atom --$200 O2 XDA STEALTH--$210 Treo 750--$220 Treo 700p--$200 Nextel i880 --$150 Nextel i960 --$180 Sidekick 3-- $180 Imate Jasjar-- $220 Imate K-Jam-- $200 BenQ PL51--$250 HTC Universal 3G--$200 HTC Advantage X7500 --$270 HTC Touch --$250 Blackberry 8300 Curve--$220 Blackberry 8800--$230 Blackberry 8100 Pearl--$210 Blackberry 8700 --$200 LG KE850 Prada --$190 LG Chocolate KG800 --$180 LG Shine KU970---$200 Sony Ericsson W950i --$250 Sony Ericsson W810i --$200 Sony Ericsson W880i --$210 Sony Ericsson P990 --$250 Moto V3i (D&G) --$150 Motorola A1010 PDA SmartPhone --$160 A1200--$180 Moto Z8--$160 Moto Q--$160 KRZR K1--$150 RIZR --$130 Samsung U600 slim --$200 SGH BlackJack--$180 SGH-X830 --$195 SGH-P310 --$200 Ultra Smart F700--$210 SGH-D800--$180 SGH-D900--$220 LAPTOPS/NOTEBOOKS: Acer Ferrari 5006 Laptop--$650 Acer Ferrari 1000 Laptop--$600 Dell XPS M1710 Laptop--$650 Dell XPS M2010 Laptop--$750 Apple MacBook Pro Laptop--$500 Sony VAIO VGN-AR190G Core duo--$620 GAME CONSOLES: Playstation 3 60gb --$250 Nintendo Wii--$180 Xbox 360 Premium--$160 Microsoft Xbox 360 Halo 3 Special Edition--$180 Sony Mylo--$200 iPod Video 80gb--$180 GPS : TomTom Go 910--$200 TomTom One--$150 Garmin Nuvi 660...$350 Pioneer Avic...$400 DIGITAL CAMERAS: Nikon D200 Digital Camera --$320 Nikon D80 Digital Camera --$280 Sony Cyber-Shot DSCT33- 5.1 MegaPixels ...$300 Sony CyberShot 8.1 Megapixel ...$310 Canon PowerShot 8.1Megapixel--$300 These are absolute bargains ! All GSM Phones,Brand New, Unlocked - And Video Games are also Brand new with Complete Accessories plus Int'l Warranty . Payment Term : T/T - Western union. Shipment : FedEx / DHL / UPS Courier Service Delivery Leadtime : 48hrs - 36hrs delivery We also give 20% discount for bulk purchase above 20 units Other model of cell phones are also available in stock. NOTE: ALL ENQUIRES SHOULD BE DIRECTED VIA EMAIL EMAIL: bluegatesltd at gmail.com EMAIL: bluegateltd at yahoo.com Warm Regards, Manuel Russell From hniksic at xemacs.org Mon Nov 12 10:42:27 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Mon, 12 Nov 2007 16:42:27 +0100 Subject: Moving from java to python. References: <1194881119.674022.326040@22g2000hsm.googlegroups.com> Message-ID: <87bq9zwjvg.fsf@mulj.homelinux.net> "PeterBraden1 at googlemail.com" writes: > def __init__(self, connections = None, uid = None): You can use connections=(), so you don't need the "if" below. In fact, you can further write: for node, weight in connections: self._connected.append(node) self._weight.append(weight) > def getConnected(self): > return self._connected I'd drop the getters and simply use self.connected, self.weights, etc. It's not such a big deal in Python if someone can view the innards of your objects; they can do so even if their name starts with _. Also note that Python doesn't really use the camel-case naming convention. If you must have multi-word method/variable/property names, use lower-case with underscores for separation. For example: > def getConnections(self): Why not simply def connections(self) or, if you must, def get_connections(self). > connections = [] > for i in range(len(connected)): > connections.append((self._connected[i],self._weight[i])) Use xrange(len(...)) when iterating over the sequence; range unnecessarily allocates the whole list. Some will probably recommend enumerate() or even itertools.izip(), but those are overkill for this usage. From ganesh.borse at credit-suisse.com Wed Nov 14 21:20:14 2007 From: ganesh.borse at credit-suisse.com (Borse, Ganesh) Date: Thu, 15 Nov 2007 10:20:14 +0800 Subject: How to evaluate the code object returned by PyParser_SimplePa rseString function? Message-ID: Hi, Thanks for this information. I would like to know few more things. Py_CompileString takes the source code from file, isn't it? As can be seen from the syntax of this function: PyObject* Py_CompileString(char *str, char *filename, int start) I want to parse the code which is in memory - loaded from database. In that case, may I know, how to use the Py_CompileString? If it is mandatory to read from file for this function? Reading from file increases startup time of my application. So, I was thinking of using PyParser_SimpleParseString, which takes the code to be parsed in the "char*" format. Quit suitable to my need. Can I use the output of the function PyParser_SimpleParseString as input to PyEval_EvalCode? Please guide. Thanks in advance for your time & guidance. Warm Regards, Ganesh -----Original Message----- From: Gabriel Genellina [mailto:gagsl-py2 at yahoo.com.ar] Sent: 15 November 2007 07:51 To: python-list at python.org Subject: Re: How to use the evaluate the code object returned by PyParser_Simp leParseString function? En Wed, 14 Nov 2007 06:48:41 -0300, Borse, Ganesh escribi?: > `struct _node* PyParser_SimpleParseString(char *str, int start)' > Parse Python source code from STR using the start token START. > The result can be used to create a code object which can be evaluated > efficiently. > This is useful if a code fragment must be evaluated many times. > I have exactly same requirement. I have dynamic expressions loaded > from database at startup in my C++ application. > I want to parse these expressions at startup & keep the parsed > (compiled) code in memory of this application. > Then at runtime, I want to evaluate all this parsed code. This has to > be very efficient. parsed != compiled. Use Py_CompileString instead. The resulting code object may be executed with PyEval_EvalCode. BTW, instead of looking at some random web site, it's better to read the official documentation at http://docs.python.org. You should have a copy of it in the Doc subdirectory inside your Python installation. -- Gabriel Genellina ============================================================================== Please access the attached hyperlink for an important electronic communications disclaimer: http://www.credit-suisse.com/legal/en/disclaimer_email_ib.html ============================================================================== From bignose+hates-spam at benfinney.id.au Tue Nov 20 23:34:03 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 21 Nov 2007 15:34:03 +1100 Subject: Code Management References: <7d81e2cc-b243-4d63-a20a-d10709241eaf@e4g2000hsg.googlegroups.com> <9ebda8f9-361b-40df-9c3a-fc180cab5e6b@l1g2000hsa.googlegroups.com> Message-ID: <87bq9otdxg.fsf@benfinney.id.au> Jens writes: > On 21 Nov., 04:16, Jens wrote: > > On 21 Nov., 01:46, brzr... at gmail.com wrote: > > dummy/ > > dummy_package/ > > __init__.py > > moduleA.py > > tests/ > > __init__.py > > test.py To avoid confusion, the directory that is the package should be named as you want the imports to appear; e.g. if you want to 'import foo.module_a', then name the directory containing 'module_a.py' as 'foo/'. This often results in:: foo/ setup.py foo/ __init__.py module_a.py test/ __init__.py test_module_a.py That is, the *project* directory (containing all the files) is named 'foo/'; the *package* directory (where all the implementation code is found) is named 'foo/foo/', and the unit tests are found in the directory 'foo/test/'. That's normal, though if it confuses you you might want to rename the project directory. I'm often doing development on multiple version-control branches, so each project directory is named for the branch it contains; within each of those, the same 'foo/' name is used for the package directory. > > I'm using Python 2.5.1. When I'm trying to call a function in > > 'moduleA' from 'test' it won't work unless I make the 'dummy' > > folder a package as well. That's pretty weird. Does > > 'dummy_package' have to be in my pythonpath or something? How do I > > reference moduleA from test? You should install the package into a place where Python's import path will find it. Read up on using the standard library 'distutils' mechanism for this; it involves writing a 'setup.py' file to define the parameters for installation of your package. > > I would like to avoid making 'dummy' into a package as well. Yes. The top-level directory is used for containing a number of files, including 'setup.py', that should not be part of the installed package. > Problem solved. I added 'dummy' to the PYTHONPATH. (Do I really have > to do that for every project I create?) Anyway, it works the way I'd > like it to now. I hope the above makes it clearer what I prefer for this situation. -- \ "True greatness is measured by how much freedom you give to | `\ others, not by how much you can coerce others to do what you | _o__) want." --Larry Wall | Ben Finney From pavlovevidence at gmail.com Thu Nov 15 16:49:10 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 15 Nov 2007 13:49:10 -0800 (PST) Subject: Python Design Patterns - composition vs. inheritance References: <5q3p0uFu0notU1@mid.uni-berlin.de> Message-ID: <96a54eb3-f487-4153-92b8-27d372408d33@n20g2000hsh.googlegroups.com> On Nov 15, 3:37 pm, "Diez B. Roggisch" wrote: > > Also, I've seen talk that ideally you shouldn't have too many "dots" > > in your method calls, instead using delegates to the methods and > > attributes. Can anyone elaborate on this? Ideally, should I be writing > > getattr() methods so I can do pet.address instead of > > pet.owner.address? Should I be doing the same with owner's methods > > like I did with get_foo()? > > No, that's certainly not a good idea. And I'm under the impression you > misunderstood something there in the original lecture/explanation. Having read lots of "perspectives" on OO style, it wouldn't surprise me if the OP understood the point perfectly. I.e., there probably are people out there who suggest that when you have something like this: mypet.owner.get_attributes() you should reverse-refactor it into something like this: mypet.get_owner_attributes() I would agree that the former is preferable, especially in cases like this one where the classes aren't really closely related. Carl Banks From afriere at yahoo.co.uk Mon Nov 19 00:15:31 2007 From: afriere at yahoo.co.uk (Asun Friere) Date: Sun, 18 Nov 2007 21:15:31 -0800 (PST) Subject: Python beginner! References: <473cb2a4$0$27124$9b4e6d93@newsspool1.arcor-online.net> <473d9ded$0$13117$9b4e6d93@newsspool2.arcor-online.net> Message-ID: On Nov 17, 12:41 am, Wildemar Wildenburger wrote: > It is true that I could have been way more polite. I don't see how. You said "please" read it. You didn't make fun of the poor spelling and said nothing rude. I can't agree that the response "reeks of arrogance." I've seen the same thing said far more agressively. You have to teach students as you find them. Clearly the querent first needs to be taught how to ask questions. If (s)he took the time to read the link you supplied (s)he will be rewarded by getting better responses not only on this group but on usenet groups generally (and probably IRL as well). From paul at boddie.org.uk Thu Nov 22 17:15:43 2007 From: paul at boddie.org.uk (Paul Boddie) Date: Thu, 22 Nov 2007 14:15:43 -0800 (PST) Subject: the annoying, verbose self References: <3c954a31-9fb9-4c0f-b784-cef9ee057ca6@g30g2000hsb.googlegroups.com> <4745d762$0$90264$14726298@news.sunsite.dk> Message-ID: On 22 Nov, 20:24, Ayaz Ahmed Khan wrote: > > I've never really understood why some people find that annoying to do. I > make it a point to use, for example, the `this` operator when writing C++ > code to avoid implicilty calling/accessing attributes of objects as much > as possible. Precisely. One wonders whether the people complaining so vehemently about self have ever encountered coding style guides. Paul From mbac at gpshopper.com Thu Nov 8 14:09:54 2007 From: mbac at gpshopper.com (Michael Bacarella) Date: Thu, 8 Nov 2007 14:09:54 -0500 Subject: Using python as primary language In-Reply-To: <1194508354.226023.232050@v3g2000hsg.googlegroups.com> References: <1194508354.226023.232050@v3g2000hsg.googlegroups.com> Message-ID: <003b01c8223a$f24c3fb0$d6e4bf10$@com> > In our company we are looking for one language to be used as default > language. So far Python looks like a good choice (slacking behind > Java). A few requirements that the language should be able cope with > are: How do you feel about multithreading support? A multithreaded application in Python will only use a single CPU on multi-CPU machines due to big interpreter lock, whereas the "right thing" happens in Java. This can be worked around with fork() and shared memory but it certainly surprised us to learn this. From george.sakkis at gmail.com Fri Nov 16 21:30:28 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 16 Nov 2007 18:30:28 -0800 (PST) Subject: overriding methods - two questions References: <473dd35a$0$7999$426a34cc@news.free.fr> <13js4tebjlucv16@corp.supernews.com> Message-ID: <1b944969-1157-4f9f-86cb-153c176e7027@b40g2000prf.googlegroups.com> On Nov 16, 5:03 pm, Steven D'Aprano wrote: > On Fri, 16 Nov 2007 18:28:59 +0100, Bruno Desthuilliers wrote: > >> Question 1: > > >> Given that the user of the API can choose to override foo() or not, how > >> can I control the signature that they use? > > > While technically possible (using inspect.getargspec), trying to make > > your code idiot-proof is a lost fight and a pure waste of time. > > Worse: it's actually counter-productive! > > The whole idea of being able to subclass a class means that the user > should be able to override foo() *including* the signature. Why do you > want to stop them? Primarily because of this: http://en.wikipedia.org/wiki/Liskov_substitution_principle. > Let me give a practical example: > > (snip misleading example involving __init__) Constructors are in general different from other regular methods because you refer explicitly to the class name when creating an instance; that is, the client writes "f = ContinuedFraction(...)" or "f = RegularCF(...)" so it's not necessary to have the same signature in __init__. For all other methods though, given that you have an instance x so that isinstance(x, ContinuedFraction), the client should be able to say x.foo(arg, kwd=v) without having to know whether x.__class__ is ContinuedFraction. If not, you have a leaky abstraction [1], i.e. in your example, a RegularCF is not really a ContinuedFraction. George [1] http://www.joelonsoftware.com/articles/LeakyAbstractions.html From grante at visi.com Mon Nov 12 15:23:49 2007 From: grante at visi.com (Grant Edwards) Date: Mon, 12 Nov 2007 20:23:49 -0000 Subject: Transfer socket connection between programs References: <1194896500.733359.93510@50g2000hsm.googlegroups.com> <13jhbl370uidu0c@corp.supernews.com> <1194897743.427660.115340@o80g2000hse.googlegroups.com> Message-ID: <13jhdilifpugpc4@corp.supernews.com> On 2007-11-12, JamesHoward wrote: >> Private memory has nothing to do with it. The connection is a >> data structure that lives in kernel space, not in user space. >> Even if you could grant another process access to your "private >> memory space", it wouldn't help you "transfer a socket >> connection", since that connection is something the OSes >> manages. > Does this mean that there is some way to transfer a pointer to that > kernel memory space from one program to another and have it be valid, No. > or is that kernel memory space protected and unusable from other > processes? On Linux (I'm not sure how it works on Windows), there is a table of file descriptors that the kernel keeps for each process. A table entry can be an open file on disk, a serial port, a network connection, etc. A file descriptor is just an index into that table. That table can't be accessed by any other processes. When you fork a process the new process inherits a copy of that table (and therefore inherits any open network connections). -- Grant Edwards grante Yow! I'm having an at EMOTIONAL OUTBURST!! But, visi.com uh, WHY is there a WAFFLE in my PAJAMA POCKET?? From zzbbaadd at aol.com Sat Nov 10 06:18:13 2007 From: zzbbaadd at aol.com (TheFlyingDutchman) Date: Sat, 10 Nov 2007 03:18:13 -0800 Subject: Writing a CGI to query DB In-Reply-To: <1194669197.429480.65820@s15g2000prm.googlegroups.com> References: <1194669197.429480.65820@s15g2000prm.googlegroups.com> Message-ID: <1194693493.820438.59360@o38g2000hse.googlegroups.com> On Nov 9, 8:33 pm, Bighead wrote: > Hi, > > I am currently working on a CGI deployed on an Apache server, which, > given an arbitrary SQL, fetches raw data from a remote DB server and > return them in a HTML page. This CGI works fine on quick SQLs. > > But when I try to run a slow SQL on this CGI, through a Squid Proxy, I > always get the Error message from Squid: Zero Sized Reply, after 5 > minutes. > > The SQL itself is correct, since I have tried it directly on the DB > server. So what do you think might cause the problem? Thank you. Slow SQL = query that takes a long time? How long does the query take if you run it on the same machine as the DB server without a Squid Proxy? From paul at boddie.org.uk Wed Nov 7 17:25:06 2007 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 07 Nov 2007 14:25:06 -0800 Subject: Retrieving all open applications ... In-Reply-To: References: <3b10c2060710300220g16373e41i6d4290563c15776@mail.gmail.com> <3b10c2060711031152r46159f96x8d1bdd9ee7c2a2d5@mail.gmail.com> <3b10c2060711070136v72032102t63f57b707fb7f8db@mail.gmail.com> Message-ID: <1194474306.835675.157890@y42g2000hsy.googlegroups.com> On 7 Nov, 21:33, "Gabriel Genellina" wrote: > En Wed, 07 Nov 2007 06:36:49 -0300, Ajay Deshpande > escribi?: > > > well i still havent found a solution to this ... since i am using ubuntu > > 7.10, i cannot use the hammond modules ... > > As you said "list of window handles" I thought you were working on Windows. > Try with: man ps > Use the subprocess module to call ps with your desired options. Something like xlsclients might do the job. For more information on each window, try xwininfo with the -name option; something like this: xwininfo -name 'Mail - Kontact' The xprop program can provide plenty more detail, and both programs accept a -root option to refer to the root window instead of a named window. Paul From michael.poeltl at univie.ac.at Fri Nov 23 01:33:02 2007 From: michael.poeltl at univie.ac.at (michael poeltl) Date: Fri, 23 Nov 2007 07:33:02 +0100 Subject: may be a bug in string.rstrip In-Reply-To: <004d01c82d86$b3c0e550$811ba8c0@kyom> References: <004d01c82d86$b3c0e550$811ba8c0@kyom> Message-ID: <200711230733.02160.michael.poeltl@univie.ac.at> hi, what about this >>> 'exe.torrent'.split('.')[0] 'exe' >>> 'exe.torrent'.rstrip('toren').rstrip('.') 'exe' >>> that's what you need, isn't it? On Friday 23 November 2007 05:09:50 am kyo guan wrote: > Hi : > > Please look at this code: > >>> 'exe.torrent'.rstrip('.torrent') > > 'ex' <----- it should be 'exe', why? > > but this is a right answer: > >>> '120.exe'.rstrip('.exe') > > '120' <------ this is a right value. > > there is a bug in the rstrip, lstrip there isn't this problem. > > > > Kyo. michael From kyosohma at gmail.com Tue Nov 13 17:19:48 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 13 Nov 2007 22:19:48 -0000 Subject: why there is no pythonscript insine web browsers? In-Reply-To: References: Message-ID: <1194992388.373707.327500@o38g2000hse.googlegroups.com> On Nov 12, 12:07 pm, Timu?in K z lay wrote: > I'm an old programmer coming from a cobol background and started to > learn python. I'm using javasript for web based applications but after I > started to learn python, the javascript language started to seem ugly to > me. Now I'm wondering why there is java support on web browsers but no > python support? there is even a vbscript support inside MS-IE but there > is no python support. it would be really nice and easy for me to use > python instead of javascript to write those ajax scripts. > > Please tell me, is there a python substitude for JRE ? You can also use Python's cgi module. It's pretty cool, from what I've read: http://docs.python.org/lib/module-cgi.html http://www.cs.virginia.edu/~lab2q/ http://www.python.org/doc/essays/ppt/sd99east/index.htm Of course, there's also the many Python web frameworks to choose from too. There are more ways to implement Python in the browser than just trying to replace javascript with Python. Admittedly, they may be too big a hammer for your needs. Mike From mccredie at gmail.com Thu Nov 15 16:45:21 2007 From: mccredie at gmail.com (Matimus) Date: Thu, 15 Nov 2007 13:45:21 -0800 (PST) Subject: Insert image to a List box References: Message-ID: <39e5b06b-4435-4761-a0a1-f4fc1e39cb46@e25g2000prg.googlegroups.com> On Nov 15, 12:45 pm, linda.s wrote: > I run the following code and got the error (I put a .gif file on the desktop) > Traceback (most recent call last): > File "11.py", line 25, in > for gifname in os.listdir(dirpath): > OSError: [Errno 2] No such file or directory: '.\\Desktop\\' > > import os > import Tkinter > > root = Tkinter.Tk() > L = Tkinter.Listbox(selectmode=Tkinter.SINGLE) > gifsdict = {} > > dirpath = '.\\Desktop\\' > for gifname in os.listdir(dirpath): > if not gifname[0].isdigit(): > continue > gifpath = os.path.join(dirpath, gifname) > gif = Tkinter.PhotoImage(file=gifpath) > gifsdict[gifname] = gif > L.insert(Tkinter.END, gifname) > > L.pack() > img = Tkinter.Label() > img.pack() > def list_entry_clicked(*ignore): > imgname = L.get(L.curselection()[0]) > img.config(image=gifsdict[imgname]) > L.bind('', list_entry_clicked) > root.mainloop() The exception points to this line as being the issue: > for gifname in os.listdir(dirpath): and the error says `No such file or directory: '.\\Desktop\\'' So, there must be no directory named '.\\Desktop\\' in your current working directory. To find out your current working directory use `os.getcwd()'. Make sure that `os.getcwd()' returns the path to a directory with a Desktop folder in it. This is usually something like 'C:\\Documents and Settings\\username'. Matt Matt From paul.hankin at gmail.com Mon Nov 26 14:08:46 2007 From: paul.hankin at gmail.com (Paul Hankin) Date: Mon, 26 Nov 2007 11:08:46 -0800 (PST) Subject: better way to write this function References: <4b4d9cc5-3759-421e-b3a2-3cb25bdaae7a@b40g2000prf.googlegroups.com> Message-ID: On Nov 26, 7:42 am, Kelie wrote: > Hello, > > This function does I what I want. But I'm wondering if there is an > easier/better way. To be honest, I don't have a good understanding of > what "pythonic" means yet. > > def divide_list(lst, n): > """Divide a list into a number of lists, each with n items. Extra > items are > ignored, if any.""" > cnt = len(lst) / n > rv = [[None for i in range(n)] for i in range(cnt)] > for i in range(cnt): > for j in range(n): > rv[i][j] = lst[i * n + j] > return rv > > Thanks! Here's a terrible way to do it: def divide_list(lst, n): return zip(*[lst[i::n] for i in range(n)]) [It produces a list of tuples rather than a list of lists, but it usually won't matter]. -- Paul Hankin From donn.ingle at gmail.com Sat Nov 24 01:41:15 2007 From: donn.ingle at gmail.com (Donn Ingle) Date: Sat, 24 Nov 2007 08:41:15 +0200 Subject: Catching a segfault in a Python library References: <7x1wagp8vu.fsf@ruckus.brouhaha.com> <7xbq9k1be4.fsf@ruckus.brouhaha.com> <7xwss817l4.fsf@ruckus.brouhaha.com> Message-ID: > You may have to roll your own fork/exec to start the wxpython, instead > of using popen or the subprocess module. ?I'm not terribly conversant > in those modules but they may start a shell which would isolate your > program from the wxpython exit code. Hrmm... Neither am I, that's why I asked here :) But I'll skin that Python when I get to it. Thanks. \d From mightybastion at gmail.com Tue Nov 13 20:24:40 2007 From: mightybastion at gmail.com (Joe Blow) Date: Tue, 13 Nov 2007 17:24:40 -0800 Subject: Pythonic tee for subprocess module. Message-ID: I'd like to use the subprocess module to create a pipeline with a fork. For example, what if I wanted a "cat" process to send a file to both an "md5sum" process and a "gzip" process. In bash, I'd do something like this: > cat source_file | tee >(md5sum > source_file.md5sum) | gzip -c > source_file.gz What is the best way to "tee" a Python file object so that I can send it to two different subprocess.Popen instances? I tried creating a Tee class with read and write methods that send duplicate data to a number of file objects, but the Popen class won't accept my class as an argument to the stdin parameter. subprocess.Popen seems to require _real_ file objects with file descriptors, etc., not just any class with a read() and write() method. Suggestions anyone? Thanks for your help. --Ethan From Anaryin at gmail.com Fri Nov 2 08:05:02 2007 From: Anaryin at gmail.com (=?iso-8859-1?q?Jo=E3o_Rodrigues?=) Date: Fri, 02 Nov 2007 12:05:02 -0000 Subject: Webservices, SOAP and Python Message-ID: <1194005102.209237.126900@19g2000hsx.googlegroups.com> Hello all, I'm trying to build a webserver client and I'm having quite the trouble. I ended up using ZSI (since it's the only one that I could actually install on my Linux system) but I wonder: is there any other software for this purpose? I read about SOAPpy and PyXML but since both are discontinued, what do you use? By the way, I'm having trouble connecting ZSI-using scripts to the internet. Every other script works. Why could this be happening? How can I prevent this? (I'm behind a proxy) Cheers! From arkanes at gmail.com Tue Nov 27 13:00:46 2007 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 27 Nov 2007 12:00:46 -0600 Subject: Unsupported operator for Decimal: + (or -) In-Reply-To: <904774730711270945j1dc88698m2c6e4f806f8acbec@mail.gmail.com> References: <904774730711270945j1dc88698m2c6e4f806f8acbec@mail.gmail.com> Message-ID: <4866bea60711271000t2ab1751do807137c191912598@mail.gmail.com> On Nov 27, 2007 11:45 AM, Todd O'Bryan wrote: > This seems to have come up earlier... > > http://mail.python.org/pipermail/python-list/2007-July/451187.html > > but no resolution. > > We're seeing the same thing. We're using Django's DecimalField type > and when we try to add or subtract values--which should be > decimal.Decimal objects--we occasionally get an error about the > operator not being supported. It doesn't always happen and we can't > seem to reproduce it when we try to. > > Has anybody else seen this or is it just the original poster and me? > If __sub__ (or __add__, or whatever) returns NotImplemented that can raise this error. This should never happen between two Decimal instances, and the traceback should show you which two classes were used. The most likely cause is that something is getting passed into the comparison that's not a Decimal, an int, or a long. From james.b.looney at lmco.com Tue Nov 20 16:15:12 2007 From: james.b.looney at lmco.com (Looney, James B) Date: Tue, 20 Nov 2007 14:15:12 -0700 Subject: Writing Error in program In-Reply-To: References: Message-ID: There could be any number of issues in your code that could cause that problem. Can you post some of the code in question? > -----Original Message----- > From: python-list-bounces+james.b.looney=lmco.com at python.org > [mailto:python-list-bounces+james.b.looney=lmco.com at python.org > ] On Behalf Of koutoo at hotmail.com > Sent: Tuesday, November 20, 2007 2:03 PM > To: python-list at python.org > Subject: Writing Error in program > > I have a code that writes to 2 seperate files. I keep getting a "list > index out of range" error. The strange part is that when checking the > files that I'm writing too, the script has already iterated through > and finished writing, yet the error stated implies that it hasn't? So > how can it be, that my script has written to the files, yet the error > is stating that it hasn't made it through the script? I'll have 15 > files that I have written to and the script will bog out at number > 10? Is python doing something I'm not seeing? I printed everything > that was written on the shell and it shows that it went through the > script, so how can it still say there are a few files left to iterate > through? > -- > http://mail.python.org/mailman/listinfo/python-list > From tbabula at gmail.com Sun Nov 4 01:58:16 2007 From: tbabula at gmail.com (Tom_chicollegeboy) Date: Sun, 04 Nov 2007 05:58:16 -0000 Subject: how to iterate through each set In-Reply-To: <13iqn7piblqqb20@corp.supernews.com> References: <1194150610.798025.282330@y42g2000hsy.googlegroups.com> <13iqn7piblqqb20@corp.supernews.com> Message-ID: <1194155896.243516.171220@o38g2000hse.googlegroups.com> On Nov 4, 12:47 am, Dennis Lee Bieber wrote: > On Sat, 03 Nov 2007 21:30:10 -0700, Tom_chicollegeboy > declaimed the following in comp.lang.python: > > > > > It works only for first set. How should I implement another solution > > that would move program to read next set? I think I should implement > > nested while look, with first that reads until -1 and under it another > > while loop that reads n times sets. But I have no idea how. Can you > > help me? > > Homework, huh? So I need to avoid a working solution... > > Personally, based upon the nature of the data file, I'd base the > entire algorithm on a control break which is signified by a line with a > single "term", and ignore the "count" value of that term. > > I'd have to ignore the first "control break" as there is no output > at that time. That can be done by initially setting the total mileage to > None (not to 0). > > On a control break (len(input.split()) == 1): if total mileage is > NOT None, output results; set total mileage and elapsed time to 0. > > On a data line (len(input.split()) == 2): total mileage = total > mileage + speed * (current time - elapsed time); elapsed time = current > time. > > Exit on EOF. > > This algorithm will function even with erroneous input: > > 4 <== only three actual values follow > 20 2 > 30 6 > 10 7 > 2 > 60 1 > 30 5 > -1 > > Calling the function "speed" is misleading too -- the /input/ is > speed and time, but the output wanted is mileage. > > With the following data: > -=-=-=-=-=-=-=- > 4 > 20 2 > 30 6 > 10 7 > 2 > 60 1 > 30 5 > -1 > 10 1 > 25 1 > 5 10 > -=-=-=-=-=-=-=-=- > > A quick program produces the following output (NOTE: I added a LOT > of ouput statements so you can see the logic -- but I won't show the > actual code). > > initialize total None, elapsed 0, trip count 0 > open data file > loop over lines in input file, exit on null line > input line is: [4] > number of values in the line: 1 > one value, control break > no trip data read before this control break > resetting total mileage 0, elapsed 0, incrementing trip count 1 > input line is: [20, 2] > number of values in the line: 2 > elapsed miles: 40 > input line is: [30, 6] > number of values in the line: 2 > elapsed miles: 160 > input line is: [10, 7] > number of values in the line: 2 > elapsed miles: 170 > input line is: [2] > number of values in the line: 1 > one value, control break > trip 1: 170 miles > resetting total mileage 0, elapsed 0, incrementing trip count 2 > input line is: [60, 1] > number of values in the line: 2 > elapsed miles: 60 > input line is: [30, 5] > number of values in the line: 2 > elapsed miles: 180 > input line is: [-1] > number of values in the line: 1 > one value, control break > trip 2: 180 miles > resetting total mileage 0, elapsed 0, incrementing trip count 3 > input line is: [10, 1] > number of values in the line: 2 > elapsed miles: 10 > input line is: [25, 1] > number of values in the line: 2 > elapsed miles: 10 > input line is: [5, 10] > number of values in the line: 2 > elapsed miles: 55 > No terminating control break found > Unfinished trip is: > trip 3: 55 miles > > By the way -- YOUR sample input data has ONLY TWO TRIPS -- so how > can the correct output be THREE trips? > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfr... at ix.netcom.com wulfr... at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-a... at bestiaria.com) > HTTP://www.bestiaria.com/ very helpful hints. thank you very much From http Sun Nov 4 15:05:35 2007 From: http (Paul Rubin) Date: 04 Nov 2007 12:05:35 -0800 Subject: python newbie References: <472b2b84$0$13761$6e1ede2f@read.cnntp.org> <5p0s6vFp47k9U1@mid.individual.net> <472b5251$0$6238$426a34cc@news.free.fr> <13ioa6f6t797gce@corp.supernews.com> <7x4pg3wks5.fsf@ruckus.brouhaha.com> <7x8x5f83u5.fsf@ruckus.brouhaha.com> <1194126214.238480.254180@57g2000hsv.googlegroups.com> <7xabpvkn0n.fsf@ruckus.brouhaha.com> <472defc8$0$30484$426a74cc@news.free.fr> <7xr6j52acl.fsf@ruckus.brouhaha.com> <472e1a1f$0$24020$426a74cc@news.free.fr> Message-ID: <7xsl3lrd2o.fsf@ruckus.brouhaha.com> Bruno Desthuilliers writes: > > from random import random > > x = random() > > y = random.choice((1,2,3)) # oops > > from random import random, choice > > x = random() > y = choice((1, 2, 3)) Really, a lot of these modules exist primarily to export a single class or function, but have other classes or functions of secondary interest. I'd like to be able to get to the primary function without needing to use a qualifier, and be able to get to the secondary ones by using a qualifier instead of having to import explicitly and clutter up the importing module's name space like that. It just seems natural. From kyosohma at gmail.com Tue Nov 13 11:14:50 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 13 Nov 2007 16:14:50 -0000 Subject: best open source sample In-Reply-To: <1194967205.108745.231030@i38g2000prf.googlegroups.com> References: <1194967205.108745.231030@i38g2000prf.googlegroups.com> Message-ID: <1194970490.169888.228650@k79g2000hse.googlegroups.com> On Nov 13, 9:20 am, Johnny wrote: > Hi, I'm new to Python and am looking for a really good/complete open > source project to learn from. I'd like it to take input from the > browser and query mysql. Suggestions? Zope / Plone, Django, or Turbogears are all web frameworks that are Python based. You could check those out. Dabo is created on top of wxPython and is made for accessing databases. You might also find these links helpful: http://wiki.python.org/moin/SummerOfCode http://freshmeat.net/articles/view/334/ www.python.org Mike From phil at riverbankcomputing.co.uk Thu Nov 1 18:32:02 2007 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Thu, 1 Nov 2007 23:32:02 +0100 Subject: PyQt with embedded python in Qt App In-Reply-To: <200711012324.42322.uzi18@o2.pl> References: <1193924163.660753.179140@o38g2000hse.googlegroups.com> <200711011413.56006.phil@riverbankcomputing.co.uk> <200711012324.42322.uzi18@o2.pl> Message-ID: <200711012232.02979.phil@riverbankcomputing.co.uk> On Thursday 01 November 2007, Bart. wrote: > Thursday 01 of November 2007 15:13:55 Phil Thompson napisa?(a): > > On Thursday 01 November 2007, cgrebeld wrote: > > > Is it possible for a Qt C++ application, which embeds the python > > > interpreter, to import and use PyQt? There can be only one > > > QApplication, which is created in the C++ side, so how would I use > > > that from the python side? > > > > QtGui.QApplication.instance() > > What I can do with this pointer? It's not a pointer, it's a Python object that wraps the C++ pointer. > It is possible to add window to application ? Yes. > It is possible to connect to application signals? Yes. Phil From paul at boddie.org.uk Thu Nov 22 06:47:39 2007 From: paul at boddie.org.uk (Paul Boddie) Date: Thu, 22 Nov 2007 03:47:39 -0800 (PST) Subject: Research-oriented Python mailing list? References: <14092.39489.qm@web32708.mail.mud.yahoo.com> Message-ID: On 22 Nov, 12:05, Robin Becker wrote: > Albert-jan Roskam wrote: > > > One more Q: I was wondering if there exists a more > > research-oriented Python listserv. This one is good > > (or so it seems, I'm just a newbie!), but the topics > > are very broad. Suggestions, anyone? [...] > I guess that depends on what you want to research. If you're into developing > python I'd start lurking on the python dev list; if you're into compilers and > basic blocks then the pypy list is just the thing etc etc etc Take your pick from the list here, perhaps: http://mail.python.org/ Or take a look at the short guide here: http://wiki.python.org/moin/MailingListsAndNewsgroups Paul From jcd at sdf.lonestar.org Tue Nov 6 12:07:04 2007 From: jcd at sdf.lonestar.org (J. Clifford Dyer) Date: Tue, 6 Nov 2007 12:07:04 -0500 Subject: regular expressions In-Reply-To: <1194367773.329640.202340@i13g2000prf.googlegroups.com> References: <1194367773.329640.202340@i13g2000prf.googlegroups.com> Message-ID: <20071106170704.GG1077@sdf.lonestar.org> On Tue, Nov 06, 2007 at 08:49:33AM -0800, krishnamanenianil at gmail.com wrote regarding regular expressions: > > hi i am looking for pattern in regular expreesion that replaces > anything starting with and betweeen http:// until / > like http://www.start.com/startservice/yellow/ fdhttp://helo/abcd will > be replaced as > p/startservice/yellow/ fdp/abcd > You don't need regular expressions to do that. Look into the methods that strings have. Look at slicing. Look at len. Keep your code readable for future generations. Py>>> help(str) Py>>> dir(str) Py>>> help(str.startswith) Cheers, Cliff From mbac at gpshopper.com Tue Nov 6 17:36:50 2007 From: mbac at gpshopper.com (Michael Bacarella) Date: Tue, 6 Nov 2007 17:36:50 -0500 Subject: Populating huge data structures from disk In-Reply-To: <7xsl3jggyb.fsf@ruckus.brouhaha.com> References: <000001c820a1$78750ea0$695f2be0$@com> <4866bea60711061104i514838fcld9bbba1382a764a6@mail.gmail.com> <7xsl3jggyb.fsf@ruckus.brouhaha.com> Message-ID: <002201c820c5$873039f0$9590add0$@com> > > Very sure. If we hit the disk at all performance drops > > unacceptably. The application has low locality of reference so > > on-demand caching isn't an option. We get the behavior we want when > > we pre-cache; the issue is simply that it takes so long to build > > this cache. > > The way I do it is run a separate process that mmaps the file and > reads one byte from each page every half hour or so. You are right > that it makes a huge difference. Why not just disable swap? From http Wed Nov 7 11:50:49 2007 From: http (Paul Rubin) Date: 07 Nov 2007 08:50:49 -0800 Subject: Looking for a good Python environment References: <1194389774.159051.55580@19g2000hsx.googlegroups.com> <1194434140.836932.10670@k79g2000hse.googlegroups.com> Message-ID: <7xbqa6f192.fsf@ruckus.brouhaha.com> "Colin J. Williams" writes: > Could you elaborate on "lightweight" please? I find PyScripter to be a > powerful editor/debugger combination. > > What functionality does Eclipse have that PyScripter does not? While we're at it, do any of these debuggers implement a good way to debug multi-threaded Python programs? From aahz at pythoncraft.com Fri Nov 2 13:54:59 2007 From: aahz at pythoncraft.com (Aahz) Date: 2 Nov 2007 10:54:59 -0700 Subject: new style class References: <1194002609.296417.111050@v3g2000hsg.googlegroups.com> <472b09dd$1_7@news.bluewin.ch> <1194003093.338406.300870@y42g2000hsy.googlegroups.com> Message-ID: In article , Nigel Rantor wrote: > >I think what Boris was being exceedingly unhelpful in saying was "why >should it work when you're calling methods that do not exist" http://www.catb.org/~esr/faqs/smart-questions.html -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Typing is cheap. Thinking is expensive." --Roy Smith From goon12 at gmail.com Sat Nov 10 12:12:22 2007 From: goon12 at gmail.com (Joe Riopel) Date: Sat, 10 Nov 2007 12:12:22 -0500 Subject: Python IDE In-Reply-To: <1194103732.450284.300420@o3g2000hsb.googlegroups.com> References: <1194103732.450284.300420@o3g2000hsb.googlegroups.com> Message-ID: <6a2ccd190711100912r550f80f8xf0ed2449f300be51@mail.gmail.com> On Nov 3, 2007 10:28 AM, BartlebyScrivener wrote: > Try the free trial of Komodo > > http://www.activestate.com/Products/komodo_ide/ Komodo Edit is free http://www.activestate.com/Products/komodo_edit/ Open Komodo is free and open source: http://www.openkomodo.com/ From ptmcg at austin.rr.com Fri Nov 30 18:45:02 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Fri, 30 Nov 2007 15:45:02 -0800 (PST) Subject: Is __import__ known to be slow in windows? References: Message-ID: On Nov 30, 5:08 pm, Joshua Kugler wrote: > [I tried googling for this, didn't find anything relevant.] > > We've recently been doing some profiling on a project of ours. It runs > quite fast on Linux but *really* bogs down on Windows 2003. We initially > thought it was the simplejson libraries (we don't use the C extensions) but > profiling proved otherwise. > > We have a function that does some runtime imports via calls to __import__. > We ran 1000 iterations (we used cProfile) of the application (web app). > There were eight calls to __import__ per iteration, so 8000 calls total. > Identical hardware, by the way. > > On Linux (Debian Etch, Python 2.5.1) > Total time was 2.793 CPU seconds, with __import__ using 1.059 seconds of > that. So, 37% of the time was spent in import. Not great, but not a show > stopper. > > On Windows 2003 (R2, Python 2.5.1) > Total time was 18.532 CPU seconds, with __import__ using 16.330 seconds > (88%) of that. > > So, Linux spends 1.734 seconds on non-import activities, and Windows spends > 2.202 seconds on non-import activities. Pretty close. But 16.3 seconds on > import!? > > Is this a known deficiency in Windows' Python import calls, or is there > something deeper going on here? > > Pointers, suggestions, and URLs welcome. > > j Imagine you have two laundry baskets, one is green, one is purple. Both contain 10 pairs of pants, but the pockets of the pants in the purple basket are filled with rocks. You pick up the green basket - kind of heavy, but not terrible. Then you pick up the purple basked - wow! Really heavy! Who would have had any idea that the color of the laundry basket would make such a difference in the weight? :) Of course, to clear up this question, you empty both baskets, try to lift each one, and then find out that they both weigh about the same. (Or one does weigh more than the other, but now you have ruled out the possibility that the baskets' contents were a factor in the comparison.) Ok, back to your question. __import__ doesn't just load up a module. At import time, all of the top-level code in the module is executed also. So if you want to really assess the impact of *just* __import__ on different platforms, then you should try importing: - empty .py modules - .py modules containing no top-level executable statements, but some class or method definitions - modules that have already been imported It's possible that your imported module imports additional modules which have significant platform-dependent logic, or import modules which are compiled builtins on one platform, but written in Python on the other. As it stands, your experiment still has too many unknowns to draw any decent conclusion, and it certainly is too early to jump to "wow! __import__ on Windows is sure slower than __import__ on Linux!" -- Paul From marcus at sbh.eng.br Wed Nov 14 09:30:42 2007 From: marcus at sbh.eng.br (Marcus Alves Grando) Date: Wed, 14 Nov 2007 12:30:42 -0200 Subject: [SOLVED] Re: os walk() and threads problems (os.walk are thread safe?) In-Reply-To: <473A0F43.1010908@sbh.eng.br> References: <5ptsjjFsvk9kU1@mid.uni-berlin.de> <5pu2otFsm96nU1@mid.uni-berlin.de> <4739F5AC.10003@sbh.eng.br> <4866bea60711131146k553de85ds2dc0d71be890dd8b@mail.gmail.com> <473A0F43.1010908@sbh.eng.br> Message-ID: <473B0692.3040306@sbh.eng.br> Ok. I found the problem. That's because in for i test "if EXIT" and break loop if it's true. In main part i'm wait Queue to be empty and set EXIT after that, with this subdirectories in for loop does not process and program exit. Because that output are not same. Removing "if EXIT" all works fine again. Thanks all Regards Marcus Alves Grando wrote: > I make one new version more equally to original version: > > --code-- > #!/usr/bin/python > > import os, sys, time > import glob, random, Queue > import threading > > EXIT = False > BRANDS = {} > LOCK=threading.Lock() > EV=threading.Event() > POOL=Queue.Queue(0) > NRO_THREADS=20 > > def walkerr(err): > print err > > class Worker(threading.Thread): > def run(self): > EV.wait() > while True: > try: > mydir=POOL.get(timeout=1) > if mydir == None: > continue > > for root, dirs, files in os.walk(mydir, onerror=walkerr): > if EXIT: > break > > terra_user = 'test' > terra_brand = 'test' > user_du = '0 a' > user_total_files = 0 > > LOCK.acquire() > if not BRANDS.has_key(terra_brand): > BRANDS[terra_brand] = {} > BRANDS[terra_brand]['COUNT'] = 1 > BRANDS[terra_brand]['SIZE'] = int(user_du.split()[0]) > BRANDS[terra_brand]['FILES'] = user_total_files > else: > BRANDS[terra_brand]['COUNT'] = BRANDS[terra_brand]['COUNT'] + 1 > BRANDS[terra_brand]['SIZE'] = BRANDS[terra_brand]['SIZE'] + > int(user_du.split()[0]) > BRANDS[terra_brand]['FILES'] = BRANDS[terra_brand]['FILES'] + > user_total_files > LOCK.release() > > except Queue.Empty: > if EXIT: > break > else: > continue > except KeyboardInterrupt: > break > except Exception: > print mydir > raise > > if len(sys.argv) < 2: > print 'Usage: %s dir...' % sys.argv[0] > sys.exit(1) > > glob_dirs = [] > for i in sys.argv[1:]: > glob_dirs = glob_dirs + glob.glob(i+'/[a-z_]*') > random.shuffle(glob_dirs) > > for x in xrange(NRO_THREADS): > Worker().start() > > try: > for i in glob_dirs: > POOL.put(i) > > EV.set() > while not POOL.empty(): > time.sleep(1) > EXIT = True > > while (threading.activeCount() > 1): > time.sleep(1) > except KeyboardInterrupt: > EXIT=True > > for b in BRANDS: > print '%s:%i:%i:%i' % (b, BRANDS[b]['SIZE'], BRANDS[b]['COUNT'], > BRANDS[b]['FILES']) > --code-- > > And run in make servers: > > # uname -r > 2.6.18-8.1.15.el5 > # python test.py /usr > test:0:2267:0 > # python test.py /usr > test:0:2224:0 > # python test.py /usr > test:0:2380:0 > # python -V > Python 2.4.3 > > # uname -r > 7.0-BETA2 > # python test.py /usr > test:0:1706:0 > # python test.py /usr > test:0:1492:0 > # python test.py /usr > test:0:1524:0 > # python -V > Python 2.5.1 > > # uname -r > 2.6.9-42.0.8.ELsmp > # python test.py /usr > test:0:1311:0 > # python test.py /usr > test:0:1486:0 > # python test.py /usr > test:0:1520:0 > # python -V > Python 2.3.4 > > I really don't know what's happen. > > Another ideia? > > Regards > > Chris Mellon wrote: >> On Nov 13, 2007 1:06 PM, Marcus Alves Grando wrote: >>> Diez B. Roggisch wrote: >>>> Marcus Alves Grando wrote: >>>> >>>>> Diez B. Roggisch wrote: >>>>>> Marcus Alves Grando wrote: >>>>>> >>>>>>> Hello list, >>>>>>> >>>>>>> I have a strange problem with os.walk and threads in python script. I >>>>>>> have one script that create some threads and consume Queue. For every >>>>>>> value in Queue this script run os.walk() and printing root dir. But if i >>>>>>> increase number of threads the result are inconsistent compared with one >>>>>>> thread. >>>>>>> >>>>>>> For example, run this code plus sort with one thread and after run again >>>>>>> with ten threads and see diff(1). >>>>>> I don't see any difference. I ran it with 1 and 10 workers + sorted the >>>>>> output. No diff whatsoever. >>>>> Do you test in one dir with many subdirs? like /usr or /usr/ports (in >>>>> freebsd) for example? >>>> Yes, over 1000 subdirs/files. >>> Strange, because to me accurs every time. >>> >>>>>> And I don't know what you mean by diff(1) - was that supposed to be some >>>>>> output? >>>>> No. One thread produce one result and ten threads produce another result >>>>> with less lines. >>>>> >>>>> Se example below: >>>>> >>>>> @@ -13774,8 +13782,6 @@ >>>>> /usr/compat/linux/proc/44 >>>>> /usr/compat/linux/proc/45 >>>>> /usr/compat/linux/proc/45318 >>>>> -/usr/compat/linux/proc/45484 >>>>> -/usr/compat/linux/proc/45532 >>>>> /usr/compat/linux/proc/45857 >>>>> /usr/compat/linux/proc/45903 >>>>> /usr/compat/linux/proc/46 >>>> I'm not sure what that directory is, but to me that looks like the >>>> linux /proc dir, containing process ids. Which incidentially changes >>>> between the two runs, as more threads will have process id aliases. >>> My example are not good enough. I run this script in ports directory of >>> freebsd and imap folders in my linux server, same thing. >>> >>> @@ -182,7 +220,6 @@ >>> /usr/ports/archivers/p5-POE-Filter-Bzip2 >>> /usr/ports/archivers/p5-POE-Filter-LZF >>> /usr/ports/archivers/p5-POE-Filter-LZO >>> -/usr/ports/archivers/p5-POE-Filter-LZW >>> /usr/ports/archivers/p5-POE-Filter-Zlib >>> /usr/ports/archivers/p5-PerlIO-gzip >>> /usr/ports/archivers/p5-PerlIO-via-Bzip2 >>> @@ -234,7 +271,6 @@ >>> /usr/ports/archivers/star-devel >>> /usr/ports/archivers/star-devel/files >>> /usr/ports/archivers/star/files >>> -/usr/ports/archivers/stuffit >>> /usr/ports/archivers/szip >>> /usr/ports/archivers/tardy >>> /usr/ports/archivers/tardy/files >>> >>> >> Are you just diffing the output? There's no guarantee that >> os.path.walk() will always have the same order, or that your different >> working threads will produce the same output in the same order. On my >> system, for example, I get a different order of subdirectory output >> when I run with 10 threads than with 1. >> >> walk() requires that stat() works for the next directory that will be >> walked. It might be remotely possible that stat() is failing for some >> reason and some directories are being lost (this is probably not going >> to be reproducible). If you can reproduce it, trying using pdb to see >> what's going on inside walk(). > -- Marcus Alves Grando marcus(at)sbh.eng.br | Personal mnag(at)FreeBSD.org | FreeBSD.org From __peter__ at web.de Mon Nov 26 17:02:56 2007 From: __peter__ at web.de (Peter Otten) Date: Mon, 26 Nov 2007 23:02:56 +0100 Subject: Installing Python 3000 References: <4a065db6-fb65-4862-9a2a-8afe77f76fe8@d21g2000prf.googlegroups.com> Message-ID: Andr? wrote: > The step that gets me worried is the "make install" one... I don't want it > to take over as default. I would like to be able to invoke it by typing > "python3k ..." from anywhere and have it work - while still having > "python" invoke the default 2.5 version. You want make altinstall Peter From donn.ingle at gmail.com Thu Nov 8 04:14:58 2007 From: donn.ingle at gmail.com (Donn Ingle) Date: Thu, 08 Nov 2007 11:14:58 +0200 Subject: pyparsing and svg Message-ID: Hi - I have been trying, but I need some help: Here's my test code to parse an SVG path element, can anyone steer me right? d1=""" M 209.12237 , 172.2415 L 286.76739 , 153.51369 L 286.76739 , 275.88534 L 209.12237 , 294.45058 L 209.12237 , 172.2415 z """ #Try it with no enters d1="""M 209.12237,172.2415 L 286.76739,153.51369 L 286.76739,275.88534 L 209.12237,294.45058 L 209.12237,172.2415 z """ #Try it with no spaces d1="""M209.12237,172.2415L286.76739,153.51369L286.76739,275.88534L209.12237,294.45058L209.12237,172.2415z""" #For later, has more commands d2=""" M 269.78326 , 381.27104 C 368.52151 , 424.27023 90.593578 , -18.581883 90.027729 , 129.28708 C 89.461878 , 277.15604 171.04501 , 338.27184 269.78326 , 381.27104 z """ ## word :: M, L, C, Z ## number :: group of numbers ## dot :: "." ## comma :: "," ## couple :: number dot number comma number dot number ## command :: word ## ## phrase :: command couple from pyparsing import Word, Literal, alphas, nums, Optional, OneOrMore command = Word("MLCZ") comma = Literal(",") dot = Literal(".") float = nums + dot + nums couple = float + comma + float phrase = OneOrMore(command + OneOrMore(couple | ( couple + couple ) ) ) print phrase print phrase.parseString(d1.upper()) Thanks \d From tarundevnani at gmail.com Thu Nov 29 06:38:01 2007 From: tarundevnani at gmail.com (tarun) Date: Thu, 29 Nov 2007 17:08:01 +0530 Subject: GUI builder tool Message-ID: Hi All, Please help me in selecting the best tool for developing wxPython GUIs. I'm preparing a tool that has explorer,editor and log window using wxPython.. I've heard some namely wxGlade,Boa,etc.. Which one would be the best. Thanks in Advance Regards, Tarun -------------- next part -------------- An HTML attachment was scrubbed... URL: From ra21vi at gmail.com Mon Nov 26 05:37:03 2007 From: ra21vi at gmail.com (Ravi Kumar) Date: Mon, 26 Nov 2007 16:07:03 +0530 Subject: Need to call functions/class_methods etc using string ref :How Message-ID: <9a63e8920711260237u223abc66x1cb6d6cee3492bfa@mail.gmail.com> Hi, First of all, since this is my first mail to Python-List, I want to say "Hello world!" After that; I am stuck in a project. Actually I am writing a module (for testing now), which takes URL, parses it, finds which modules and then which method to call or which class to initiate and which string to load. So far, I have done some basic URL manipulation and validation and extracted the name of modules in a dict { 'ModuleName-1': None, 'ModuleName-2': None --ETC-- } Now I want your help about how to call the function i.e _render() in the module. I have to iterate it calling all modules/also Class.methods and assinging the values in dict for each key as modulename. Means, just take that moduleName is a string which contains the name of module to load. FuncName is the string which contains the name of def to call clName is the string which contains the name of the Class, which is to init and get returned object. means everything in string. ALso, if there are multiple methods to do it, if you provide a little pros/cons and comments, it would really be very nice of you. Before I came here, I have searched Google, and found a way hasattr()/getattr(), but that confused me a little and didnt worked for me. I am missing something I know, so please ENLIGHTEN Me :) Thanks in advance EVen you read this mail :P -- -=Ravi=- -------------- next part -------------- An HTML attachment was scrubbed... URL: From Hunter.lennon at gmail.com Wed Nov 14 18:22:04 2007 From: Hunter.lennon at gmail.com (Hunter.lennon at gmail.com) Date: Wed, 14 Nov 2007 15:22:04 -0800 Subject: Custom Tkinter scrollbar Message-ID: <1195082524.398058.312030@50g2000hsm.googlegroups.com> I want to create a custom scrollbar using particular images, which will then be placed on a canvas to control another window on the canvas. Right now I am inheriting from scrollbar, but I do the movement with custom functions. When I create it and put in into the canvas with "canvas.create_window" a standard scrollbar shows in the correct spot and my custom one is outside of the canvas. All I have right now is something that moves like a scrollbar but has no effect on other objects. Can anyone give me some advice or point me to a guide for this? Is it even possible? Can I create a widget that mimics a scrollbar, or would that be more difficult? I have been unable to find anything online and would appreciate any help. From exarkun at divmod.com Thu Nov 1 07:57:39 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 1 Nov 2007 06:57:39 -0500 Subject: Which persistence is for me? In-Reply-To: Message-ID: <20071101115739.8162.1068421314.divmod.quotient.30461@ohm> On Thu, 01 Nov 2007 07:47:25 -0400, Neal Becker wrote: >I need to organize the results of some experiments. Seems some sort of >database is in order. > >I just took a look at DBAPI and the new sqlite interface in python2.5. I >have no experience with sql. I am repulsed by e.g.: >c.execute("""insert into stocks > values ('2006-01-05','BUY','RHAT',100,35.14)""") > >ewww. How unpythonic. I don't want to use a string to specify what >function to execute. I want to call a function (c.insert?). > >Is there some other interface/database that I might like better? > There are a lot of choices. Take a look, for example, at storm: https://storm.canonical.com/ Jean-Paul From deliverable at gmail.com Tue Nov 13 11:02:08 2007 From: deliverable at gmail.com (braver) Date: Tue, 13 Nov 2007 08:02:08 -0800 Subject: referencing a subhash for generalized ngram counting Message-ID: <1194969728.877025.255860@v23g2000prn.googlegroups.com> Greetings: I wonder how does one uses single-name variables to refer to nested sunhashes (subdictionaries). Here's an example: In [41]: orig = { 'abra':{'foo':7, 'bar':9}, 'ca':{}, 'dabra':{'baz': 4} } In [42]: orig Out[42]: {'abra': {'bar': 9, 'foo': 7}, 'ca': {}, 'dabra': {'baz': 4}} In [43]: h = orig['ca'] In [44]: h = { 'adanac':69 } In [45]: h Out[45]: {'adanac': 69} In [46]: orig Out[46]: {'abra': {'bar': 9, 'foo': 7}, 'ca': {}, 'dabra': {'baz': 4}} I want to change orig['ca'], which is determined somewhere else in a program's logic, where subhashes are referred to as h -- e.g., for x in orig: ... . But assigning to h doesn't change orig. The real-life motivation for this is n-gram counting. Say you want to maintain a hash for bigrams. For each two subsequent words a, b in a text, you do bigram_count[a][b] += 1 -- notice you do want to have nested subhashes as it decreases memory usage dramatically. In order to generalize this to N-grammity, you want to do something like, h = bigram_count # iterating over i, not word, to notice the last i for i in range(len(ngram): word = ngram[i] if word not in h: if i < N: h[word] = {} else: h[word] = 0 h = h[word] h += 1 -- doesn't work and is just a sketch; also, if at any level we get an empty subhash, we can short-circuit vivify all remaining levels and add 1 in the lowest, count, level. Yet since names are not exactly references, something else is needed for generalized ngram multi-level counting hash -- what? Cheers, Alexy From steve at REMOVE-THIS-cybersource.com.au Fri Nov 23 17:18:52 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Fri, 23 Nov 2007 22:18:52 -0000 Subject: foldr function in Python References: <9bf5a2bb-eac7-4859-a5de-b1e84573c77a@t47g2000hsc.googlegroups.com> <0d8c76de-3510-4711-959a-34aad4a33acd@r60g2000hsc.googlegroups.com> <13kdcaar4048329@corp.supernews.com> <1b539321-8112-4e94-9fee-5be922660065@n20g2000hsh.googlegroups.com> Message-ID: <13kekechm4v8va1@corp.supernews.com> On Fri, 23 Nov 2007 15:20:38 +0100, Peter Otten wrote: > reduce() is indeed in the functools -- added by Guido van Rossum > himself. I am extremely glad to be wrong, you've cheered me up no end :-D -- Steven. From anbilnambi007 at gmail.com Tue Nov 27 04:58:59 2007 From: anbilnambi007 at gmail.com (abi) Date: Tue, 27 Nov 2007 01:58:59 -0800 (PST) Subject: vanga machan vanga Message-ID: http://goast.50webs.com/ http://bigchurch.com/go/g912753-pmem http://indianfriendfinder.com/go/g912753-pmem From mnordhoff at mattnordhoff.com Fri Nov 30 11:17:04 2007 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Fri, 30 Nov 2007 11:17:04 -0500 Subject: "Python" is not a good name, should rename to "Athon" In-Reply-To: <475031EE.2020600@tim.thechases.com> References: <13l0bhjkh4noi0e@corp.supernews.com> <475031EE.2020600@tim.thechases.com> Message-ID: <47503780.5030500@mattnordhoff.com> Tim Chase wrote: > (You'd think this was the Lisp ML, not Python... ) Atsp? :-) -- From horpner at yahoo.com Fri Nov 16 14:18:10 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Fri, 16 Nov 2007 19:18:10 GMT Subject: timing puzzle References: Message-ID: On 2007-11-16, Robin Becker wrote: > I'm trying to get my head round a timing puzzle I find whilst > optimizing A Kuchling's version of the Knuth line splitting > algorithm from the oedipus project. The puzzle is as follows in > highly abstract form (here active_nodes is a list of objects > kept in a sorted order, but there are no special methods on the > objects for comparison etc) > > for i in xrange(m): > ....... > for A in active_nodes[:]: > ...... > if cond: > active_nodes.remove(A) > ...... > ..... > > is slow my test takes 2.7 seconds; profiling reveals we're > calling A.remove thousands of times and it's taking a lot of > time. There appear to be no other usages of active_nodes in the > for A loop. > > On a hunch I changed the above to > > removed = [] > aremoved = removed.append > for i in xrange(m): > ....... > for iA,A in enumerate(active_nodes): > ...... > if cond: > aremoved(iA) > ...... > if removed: 'if removed' is reduntant, as the loop body below will not be executed if removed is empty. > for iA in reversed(removed): > del active_nodes[iA] > del removed[:] > ...... > > this latter is 5 times faster, but I can't really see why. You are no longer making m copies of active_nodes. > My only guess is that appending to the removed list is > relatively easy compared with deletes and the reverse order > delete is somehow moving less data about. I think in the > original Knuth the deletion would have been from some real kind > of list and O(1) whereas here deletions are O(n/2) on average. > On the other hand we have to keep this list in sorted order. > What data structure should I be using? When you have to make many deletions from the middle of a sequence, you would normally choose a linked list. Python doesn't provide much support for linked lists, unfortunately. Instead, filter your list. It looks like you can't use filter directly, so just do it manually. for i in xrange(m): ....... saved_nodes = [] for A in active_nodes[:]: ...... if not cond: saved_nodes.append(A) ...... active_nodes = saved_nodes ..... -- Neil Cerutti Sermon Outline: I. Delineate your fear II. Disown your fear III. Displace your rear --Church Bulletin Blooper From cliff at develix.com Fri Nov 9 15:46:02 2007 From: cliff at develix.com (Cliff Wells) Date: Fri, 09 Nov 2007 12:46:02 -0800 Subject: Some "pythonic" suggestions for Python In-Reply-To: <5PGdnWmWZIdZ967anZ2dnUVZ_uuqnZ2d@cavtel.net> References: <5PGdnWmWZIdZ967anZ2dnUVZ_uuqnZ2d@cavtel.net> Message-ID: <1194641163.28060.26.camel@portable-evil> On Thu, 2007-11-08 at 15:00 -0500, Frank Samuelson wrote: > I love Python, and it is one of my 2 favorite > languages. I would suggest that Python steal some > aspects of the S language. In general, I agree that Python has some antiquated concepts at its core (statements being a major one) and that some of these things make the language inconsistent and introduce additional syntax. However, despite the apparent close-mindedness of some of the respondents (it doesn't look like current Python syntax, hence it's "ugly"), I also agree with them to a degree: changing Python at this level would mean it would no longer be Python, it would be some other language. What you are basically asking is that GvR abandon Python (like ABC before it) and start on a "next generation" language. That's quite a request. I'm not saying it's a bad request, simply that you should recognize the scale of request you are making. On a more practical level, you might take a look at Boo. It's intentionally Python-like in appearance, yet lifts several key limitations (and is probably far more open to suggestions at this early stage in its life). Unfortunately it's nowhere near Python in completeness (notably documentation, size of community and overall maturity) and, for better or worse, it runs on .NET/Mono. Regards, Cliff From gdamjan at gmail.com Tue Nov 6 12:07:08 2007 From: gdamjan at gmail.com (Damjan) Date: Tue, 06 Nov 2007 18:07:08 +0100 Subject: Low-overhead GUI toolkit for Linux w/o X11? References: <13ipjvic6aj8c69@corp.supernews.com> <13ipvnvoqoh735f@corp.supernews.com> <5p4jqmFog9g5U1@mid.individual.net> <13iqa3rbns0c975@corp.supernews.com> Message-ID: <47309f3b$0$90267$14726298@news.sunsite.dk> >> PyQt and PySDL are AFAIK not much "less weight". > > They don't use X11. That's a _lot_ "less weight". Do you mean the X11 server or the libraries? The kdrive server should be fairly small (depending on features). I think it builds from the main xorg source today?? Isn't that what maemo uses. I don't know about the X11 libraries, but the xcb libraries are pretty much small too (126kb on i386 here) - there are additional libraries depending on which features you want: render, shape, screensaver, shm, randr, dri etc.. Shame the toolkits still don't use it directly. -- damjan From jehugaleahsa at gmail.com Sat Nov 17 16:51:16 2007 From: jehugaleahsa at gmail.com (jehugaleahsa at gmail.com) Date: Sat, 17 Nov 2007 13:51:16 -0800 (PST) Subject: implement random selection in Python References: <663086c8-96f0-4350-afe0-c587b3dfe5e9@a28g2000hsc.googlegroups.com> Message-ID: <0e95324f-9bcb-440b-9500-47dc04e41846@a28g2000hsc.googlegroups.com> Knuth says to pick N distinct records from a collection where the probability is equal you should: first fill up N records by chosing the first seen. if less than N were in the collection, quit. otherwise, t = (the number of items looked at) or N to start. while your not at the end of the collection: increment t generate a random number between 0 and t => K if K < N: add it to your collection at position K (replacing the previous item). Now, to incorporate probability is another question . . . Find the largest probability. Assume it has 100% probability. Calculate the probability of each item accordingly. Take the randomly generated number and multiply it by the probability. Take the random number minus the (random number times to probability). If it falls in range, then you replace like usual. You should find that the max probability will always appear in the zeroth position if it is not replaced by another value. Now, this does not guarantee that the highest probability value will show up first in the list, since that is the same as sorting by the probability. It is just a way of increasing the probability of making the value fall in the range as the probability varies. I am not guaranteeing this even works. I am seeing that there is some collision among the numbers, but it will work for the most part. From jorgen.maillist at gmail.com Tue Nov 20 03:39:08 2007 From: jorgen.maillist at gmail.com (Jorgen Bodde) Date: Tue, 20 Nov 2007 09:39:08 +0100 Subject: Web update library in python? Message-ID: <11e49df10711200039r72c10b73o6b49a517162fa7f4@mail.gmail.com> Hi all, I want to provide my users the ability to download a repository from the web, and after that check for updates. I thought of a mechanism that could do that, but since there is patch and diff readily available I wondered if there is a python solution that allows me to download a file, and let the patch be applied locally. In the patch there are binaries and sources I am not sure if patch can handle them both though. So here are the situations; Downloading 1. User enters URL and local path where to store 2. Updated downloads the file 3. Either creates a new repository or patches an existing one Check for updates 1. A web check is done if there is a newer version 2. File is downloaded, patch is applied Plain zip file extraction is possible, but I will miss out on files that might be deleted in future versions, but not yet on the client side. Also local changes might need to be preserved although it is not a show stopper if it doesn't. I want to have a solution that is very easy for the user, so point and click kind of work. Is there a tool / library around that can provide me a base for this problem? Thanks in advance! - Jorgen From bedouglas at earthlink.net Sat Nov 17 11:25:20 2007 From: bedouglas at earthlink.net (bruce) Date: Sat, 17 Nov 2007 08:25:20 -0800 Subject: python debugging... Message-ID: <09a101c82936$7351c290$0301a8c0@tmesa.com> Hi... new to python, trying to debug an app.... i have : >>> lib]# cat foo #!/usr/bin/python2.4 -OO # -*- coding: ascii -*- # vim:ts=4:sw=4:softtabstop=0:smarttab # import sys import slstorageserver slstorageserver.storaged(sys.argv) ============================================== i do a >> python -m pdb foo <<< which gets me into the dbg mode i then do a >> br slstorageserver.storaged <<< which states that it's setting the break... my issue now is how to run the app, so that the debugger stops at the break... i've looked at various sites, and the docs, etc... it appears that i should be able to do >> continue << and the debugger should stop at the break. it doesn't, it goes to the end.. this whole process is supposed to create a daemon process that's running in the background... any thoughts/steps/etc.. would be helpful!! thanks... From arkanes at gmail.com Wed Nov 7 14:22:32 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 7 Nov 2007 13:22:32 -0600 Subject: regular expression syntax the same in Python, Perl and grep? In-Reply-To: <1194459115.764951.50440@y42g2000hsy.googlegroups.com> References: <1194459115.764951.50440@y42g2000hsy.googlegroups.com> Message-ID: <4866bea60711071122l71ed18a4qfb6448f5861d283a@mail.gmail.com> On Nov 7, 2007 12:11 PM, seberino at spawar.navy.mil wrote: > How similar is Python's re module (regular expressions) compared > to Perl's and grep's regular expression syntaxes? > Somewhat. > I really hope regular expression syntax is sufficiently standardized > that > we don't have to learn new dialects everytime we move from one > language or shell command to another. > It isn't, at least for non-trivial use of regexps. From cokofreedom at gmail.com Thu Nov 22 11:59:53 2007 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Thu, 22 Nov 2007 08:59:53 -0800 (PST) Subject: why it is invalid syntax? References: <2d3a2$47454917$83aef404$6351@news1.tudelft.nl> <1476cd2e-7750-4fd6-bc81-8cee29aa9a12@d27g2000prf.googlegroups.com> <4745b259$0$5431$9b622d9e@news.freenet.de> Message-ID: On Nov 22, 5:46 pm, Stargaming wrote: > On Thu, 22 Nov 2007 03:24:48 -0800, cokofreedom wrote: > > On Nov 22, 10:58 am, "Guilherme Polo" wrote: > >> 2007/11/22, Stef Mientki : > > >> > alf wrote: > >> > > Hi, > > >> > > I wonder why it is an invalid syntax: > > >> > > >>> if 1: if 1: if 1: print 1 > >> > > File "", line 1 > >> > > if 1: if 1: if 1: print 1 > > >> > > or > > >> > > >>> if 1: for i in range(10): print i > >> > > File "", line 1 > >> > > if 1: for i in range(10): print i > > >> > > I would expect one could nest : > > >> > Although I agree it might be quit unreadable for normal programmers, > >> > people who are used to writing math formula, (i.e. MatLab), this is > >> > not true. > > >> > Here another interesting one, that is accepted: > > >> > self.nodes.extend ( [ ONode(shape,n,self) \ > >> > for n in range(shape.Parent.N_Outputs) > >> > \ if shape.Type_Outputs[n] == type ] ) > > >> That is a list comprehension > > >> > cheers, > >> > Stef > >> > -- > >> >http://mail.python.org/mailman/listinfo/python-list > > >> -- > >> -- Guilherme H. Polo Goncalves > > > So acceptable usage (though disgusting :P) would be > > > while 1: print 'hello'; print 'goodbye'; exec(rm -rf *) > > Nope:: > > exec(rm -rf *) > ^ > SyntaxError: invalid syntax > > Even the syntactically correct ``exec("rm -rf *")`` would make your > computer explode. Should we introduce this as a shortcut to `break`? ;-) > > SCNR, > stargaming Haha, you are correct. I was tempted to actually trial and error the code too much... I feel it is an important thing to present to a new user however, much like the infinite "alert message" because of their infinite loop. From HWang at ciber.com Fri Nov 30 18:07:42 2007 From: HWang at ciber.com (Wang, Harry) Date: Fri, 30 Nov 2007 16:07:42 -0700 Subject: Error: UnboundLocalError: local variable 'PfFlag' referenced before assignment Message-ID: <8FFDEE1FC17DFB4BAF050331C185449FD38040@srv-corp-exmb4.ciber.cbr.inc> $$ TestCase ID : 001 Step : deleteDvc,206268 Result Eval type : XmlChk Step : deleteDvc,206269 Result Eval type : XmlChk Traceback (most recent call last): File "C:\UDR2\UDRxmlGateway.py", line 388, in ParseAll() File "C:\UDR2\UDRxmlGateway.py", line 371, in ParseAll if (PfFlag == 1): UnboundLocalError: local variable 'PfFlag' referenced before assignment PfFlag gets assigned in a for loop in line 365 for i in range(PfFlagArrSize): if (PfFlagArr[i] == 1): ---> PfFlag = int(1) break else: PfFlag = int(-1) No idea what is going on here Harry C. Wang Sr. Test Engineer (Automation) Phone 206 - 268 - 7502 temporary e-mail: hwang at ciber.com Personal e-mail: hcwang at comcast.net Ciber EmpID # 36219 From aaron.watters at gmail.com Tue Nov 27 13:37:02 2007 From: aaron.watters at gmail.com (Aaron Watters) Date: Tue, 27 Nov 2007 10:37:02 -0800 (PST) Subject: How to Teach Python "Variables" References: <4749bb94$1@news.bezeqint.net> <4749c888$0$14869$426a74cc@news.free.fr> <4749cc7c$1@news.bezeqint.net> Message-ID: <13563193-c47c-42a3-aaf7-58fb72fc322b@b40g2000prf.googlegroups.com> On Nov 27, 11:52 am, "Chris Mellon" wrote: > > I would try to avoid talking > > in generalities about python variables versus C or > > lisp or whatever, unless I was teaching an upper division > > college programming languages survey class. > > I disagree, although it's not really on topic for the thread. There's > no reason why low level details need to be relegated to "upper > division" college classes. It shouldn't be in Programming Languages > 101, but it's something that I would expect a first year student who's > planning to pursue a programming career or a comp sci degree to be > exposed to. It's not out of place even in high school - that's where I > first learned C. Well I learned PDP11 assembly and FORTRAN IV in high school and I'm still recovering (taking it day by day). Offline I would discuss anything the students wanted to talk about, but during lecture or in reading, etcetera I would try to stick to the "pythonic" way of looking at things without worrying about the underlying implementation, except in side references. Yes, some boxes and arrows would be very useful to explain shared side effects, but I'd keep the diagrams limited. I think thinking too much like "C" can lead to bad practices -- for example I've seen people use the global module name space more or less like any other hash table -- adding, deleting, changing freely -- and I think this was motivated by the "C" level understanding that it really is just another hash table. From a pythonic perspective you would never think of behaving this way except under extreme duress. -- Aaron Watters === http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=revolting+delicate From horpner at yahoo.com Wed Nov 21 08:23:18 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Wed, 21 Nov 2007 13:23:18 GMT Subject: s[i:j:t] = t stipulation References: Message-ID: On 2007-11-20, Terry Reedy wrote: > "Neil Cerutti" wrote in message > news:slrnfk65hp.1mk.horpner at FIAD06.norwich.edu... >| s[i:j:t] = t (1) t must have the same length as the slice it is > replacing. > > This is essentially the same rule as requiring a proper length > of t for > > a,b,c = t # for whatever number of targets > > And people have made similar suggestions as below for that case > also. > >| Why? > > A mismatch could be intentional or accidental. In most cases > of this sort, Python assumes 'accident', especially when intent > can easily be indicated otherwise. Thanks. Assignment to slices are a convenient way to insert, assign, and delete elements, but extended slices are only good for assignment. Perhaps I was searching for consistency in the wrong place, though. >| >>> def foo(): >| ... while True: >| ... yield 'a' >| ... >| >>> foo() >| >>> x = range(10) >| >>> x[::2] = foo() >| >| This is infinite loop due to Python building a sequence out of >| the iterator to check its length. >| >| I think it might be more useful for >| >| x[::2] = foo() >| >| to result in an x of >| >| ['a', 1, 'a', 3, 'a', 5, 'a', 7, 'a', 9] >| >| In other words, take (j-i)//k elements from t for abs(k) != 1. > > Use the appropriate itertools function to take the proper > number of elements. And anyway my math was quite wrong. :( >| A problem, though, arises when t is too short--the sequence >| could be corrupted before an exception is thrown if you omit the >| length check. >| >| So you'd also have to define >| >| x[::2] = 'aaa' >| >| as resulting in >| >| ['a', 1, 'a', 2, 'a', 3, 5, 7, 9] > > No, it should be defined as resulting in > > ['a', 1, 'a', 2, 'a', 3, None, 5, None, 7, None, 9] # ;-) I thought deletion of elements would be more similar to slice assignment, e.g.: x[5:] = [] --> [0, 1, 2, 3, 4] -/ /-> [0, 1, 2, 3, 4, None, None, None, None, None] > Or better yet, require the programmer to specify by modifying > either the target or source spec, as is done now. It seems a shame to accept iterators but to build a sequence out of them, if it can be avoided. But if there's too much confusion about what it should mean, I guess that kills the idea. -- Neil Cerutti From ingoogni at gmail.com Wed Nov 14 05:57:08 2007 From: ingoogni at gmail.com (ingoogni at gmail.com) Date: Wed, 14 Nov 2007 02:57:08 -0800 Subject: Using Python To Change The World :) In-Reply-To: <1195009751.327435.182540@i13g2000prf.googlegroups.com> References: <1195009751.327435.182540@i13g2000prf.googlegroups.com> Message-ID: <1195037828.467479.234120@57g2000hsv.googlegroups.com> On Nov 14, 4:09 am, dominiquevalent... at gmail.com wrote: > my question to YOU is: > can you point me in the right direction? I will search on my own, but > I would greatly appreciate any help :) have a look at http://simpy.sourceforge.net/ for the simulation part From fomcl at yahoo.com Thu Nov 22 05:06:02 2007 From: fomcl at yahoo.com (Albert-jan Roskam) Date: Thu, 22 Nov 2007 02:06:02 -0800 (PST) Subject: Research-oriented Python mailing list? Message-ID: <14092.39489.qm@web32708.mail.mud.yahoo.com> Hi again, One more Q: I was wondering if there exists a more research-oriented Python listserv. This one is good (or so it seems, I'm just a newbie!), but the topics are very broad. Suggestions, anyone? Thanks in advance! Cheers!!! Albert-Jan Cheers! Albert-Jan ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Did you know that 87.166253% of all statistics claim a precision of results that is not justified by the method employed? [HELMUT RICHTER] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ____________________________________________________________________________________ Be a better pen pal. Text or chat with friends inside Yahoo! Mail. See how. http://overview.mail.yahoo.com/ From mnordhoff at mattnordhoff.com Fri Nov 30 10:12:32 2007 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Fri, 30 Nov 2007 10:12:32 -0500 Subject: "Python" is not a good name, should rename to "Athon" In-Reply-To: References: Message-ID: <47502860.70303@mattnordhoff.com> ureuffyrtu955 at gmail.com wrote: > Python is a good programming language, but "Python" is not a good > name. > > First, python also means snake, Monty Python. If we search "python" in > google, emule, many results are not programming resource. If we search > PHP, all results are programming resource. > > Second, python also means snake, snake is not a good thing in western > culture. Many people dislike any things relevant to snake. We must > have high regard for the custom. > > Now, python3000 is coming. It's the best time to rename! > > Athon is a good candidate, you could provide better names. > > In Athon, the first letter "A" could pronounce as [ e ] . Great, now the Google results will just be filled with AMD typoes. :-P One downside of Athon is that "Python" makes for a good two-letter abbreviation: py. It sounds nice (hey, pie), and since it ends in a vowel, is good for project names: PyGTK or pytz or whatever. AtGTK and attz don't have quite the ring. -- From deets at nospam.web.de Thu Nov 1 04:30:41 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 01 Nov 2007 09:30:41 +0100 Subject: What is Jython? In-Reply-To: <1193900068.263686.174020@v23g2000prn.googlegroups.com> References: <1193900068.263686.174020@v23g2000prn.googlegroups.com> Message-ID: <5oth67Fo507sU1@mid.uni-berlin.de> sarup26 at gmail.com schrieb: > Hello .. > > I would like to know more about Python and Jython? > What is the difference between both of them? > What is the future for Jython and which are the areas where it is > used? Bad google day? http://www.jython.org/ """ What is Jython? Jython, lest you do not know of it, is the most compelling weapon the Java platform has for its survival into the 21st century:-) ?Sean McGrath, CTO, Propylon Jython is an implementation of the high-level, dynamic, object-oriented language Python seamlessly integrated with the Java platform. The predecessor to Jython, JPython, is certified as 100% Pure Java. Jython is freely available for both commercial and non-commercial use and is distributed with source code. Jython is complementary to Java and is especially suited for the following tasks: * Embedded scripting - Java programmers can add the Jython libraries to their system to allow end users to write simple or complicated scripts that add functionality to the application. * Interactive experimentation - Jython provides an interactive interpreter that can be used to interact with Java packages or with running Java applications. This allows programmers to experiment and debug any Java system using Jython. * Rapid application development - Python programs are typically 2-10X shorter than the equivalent Java program. This translates directly to increased programmer productivity. The seamless interaction between Python and Java allows developers to freely mix the two languages both during development and in shipping products. There are numerous alternative languages implemented for the Java VM. The following features help to separate Jython from the rest: * Dynamic compilation to Java bytecodes - leads to highest possible performance without sacrificing interactivity. * Ability to extend existing Java classes in Jython - allows effective use of abstract classes. * Optional static compilation - allows creation of applets, servlets, beans, ... * Bean Properties - make use of Java packages much easier. * Python Language - combines remarkable power with very clear syntax. It also supports a full object-oriented programming model which makes it a natural fit for Java's OO design. """ Diez From execrable at gmail.com Thu Nov 29 05:11:53 2007 From: execrable at gmail.com (execrable at gmail.com) Date: Thu, 29 Nov 2007 02:11:53 -0800 (PST) Subject: Does changing a Tkinter Variable bound to a widget invoke its 'command' callback function? Message-ID: <3a709385-05e3-4c9a-98e4-02149c7437cf@b40g2000prf.googlegroups.com> I am writing a simple (maybe a bit conveluded, but I just started learning Tkinter) program that uses a 'notebook' code snippet from a python cookbook. It creates a customizable frame and radio button for each 'tab' and uses .forget to hide the frames that aren't 'current'. I modified it to use a Scale slider bar instead of radio buttons. What my program does is create a parent notebook object, and in each notebook frame, child notebooks are created. All the sliders are created with: command=lambda x: self.display(int(x)) Which displays the contents of the associated notebook frame (via forget/pack). All of this also works fine, but I wanted it to be a little more user-friendly by linking all the sliders on the child notebooks using a control IntVar so that each child notebook can be on the same page while scrolling through them. The problem is that when the currently displayed slider is moved, it updates the current child notebook, but not the notebooks of the hidden frames. Their sliders are moved when they are next displayed, but the associated frames are not updated, so there is a mismatch between slider and frame until that specific slider is moved. I can't find much information on control variables with respect to Scale widgets, so any insight, hints, or suggestions would be greatly appreciated. Some snippets of the involved routines: def __init__(self, master, size, start=0, side=LEFT, choice=None): self.active_fr = start self.size = size if(choice): self.choice = choice else: self.choice = IntVar(value=start) ... # create slider self.slide = Scale(self.rb_fr, variable=self.choice, orient=self.orient, from_=start, to=(size-start+1), length=200, command=lambda x: self.display(int(x))) ... def display(self, fr): self.frames[self.active_fr].forget() self.frames[fr].pack(fill=BOTH, expand=1) self.active_fr = fr From pavlovevidence at gmail.com Mon Nov 12 14:09:57 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 12 Nov 2007 11:09:57 -0800 Subject: OT: concatenating targets for python with (eg.) Gnu make In-Reply-To: <13jh6ecggrst1d1@corp.supernews.com> References: <13jh6ecggrst1d1@corp.supernews.com> Message-ID: <1194894597.167208.178760@i13g2000prf.googlegroups.com> On Nov 12, 1:22 pm, Jon Nicoll wrote: > My question is, how can I specify a makefile rule so that *all* of the > changed .A files are invoked on the AtoB command line - ie if 1.A, 2.A > and 3.A are newer than 1.B, 2.B, 3.B, I want make to invoke > > AtoB.py 1.A 2.A 3.A 4.A > > rather than > > AtoB.py 1.A > AtoB.py 2.A > AtoB.py 3.A > > Thanks for your thoughts. The typical idiom is to do something like this (where .Bstamp is an empty file that timestamps the latest time AtoB was run): AFILES = 1.A 2.A 3.A .Bstamp: $(AFILES) AtoB.py $(AFILES) touch .Bstamp It's a little bit harder if you want to run AtoB on just the files that changed, but all the ones that changed in one command. Now, since you asked an off-topic question here, I am forced to bring the thread somewhat back on topic by suggesting Scons, which is written in Python. I find it to be more robust and versatile than GNU Make for complex builds, though it's a little bit to learn at first. Carl Banks From rustompmody at gmail.com Sat Nov 3 05:43:50 2007 From: rustompmody at gmail.com (rustompmody at gmail.com) Date: Sat, 03 Nov 2007 09:43:50 -0000 Subject: IDLE In-Reply-To: References: <1194043445.147572.126100@k35g2000prh.googlegroups.com> Message-ID: <1194083030.802919.176650@z24g2000prh.googlegroups.com> Just curious: What makes you wish to move from emacs to idle? Admission: I used to be a dyed-in-the-wool emacs guy but Ive been having trouble with it lately. eg Yesterday when editing a largish file (I think it was setup.py) it kept going to sleep and when I killed emacs it said LALR parsing..... and made me wait for nearly a minute! So just wondering what trouble others are having with emacs and python. From zionist.news2 at gmail.com Tue Nov 6 19:10:10 2007 From: zionist.news2 at gmail.com (zionist.news2 at gmail.com) Date: Wed, 07 Nov 2007 00:10:10 -0000 Subject: LaTeX tutorial updated In-Reply-To: <1194381028.587292.174790@k79g2000hse.googlegroups.com> References: <1194381028.587292.174790@k79g2000hse.googlegroups.com> Message-ID: <1194394210.959622.83910@o3g2000hsb.googlegroups.com> On Nov 6, 12:30 pm, Nicola Talbot wrote: > Hi, > > I've updated my "Using LaTeX to write a PhD thesis" tutorial. Both PDF > and HTML versions can be reached viahttp://theoval.cmp.uea.ac.uk/~nlct/latex/ > > I have added/deleted sections, so if you have any links to document > nodes (i.e. files that are of the form node*.html) you may have to > update your links. > > Regards > Nicola Talbot very nice. 911 truckload of Explosives on the George Washington Bridge http://www.youtube.com/watch?v=J520P-MD9a0 http://video.google.com/videoplay?docid=3552214685532803163 From tartifola at gmail.com Fri Nov 30 09:42:26 2007 From: tartifola at gmail.com (Tartifola) Date: Fri, 30 Nov 2007 15:42:26 +0100 Subject: Sorting array Message-ID: <20071130154226.c17a34ec.tartifola@gmail.com> Hi, I'm working with numerical array and I'm a little lost on a particular sorting of one of them. In particular I have an array like a = array([[8,4,1],[2,0,9]]) and I need to sort it using only the first column as reference but keeping the lines together so to obtain array([[2, 0, 9], [8, 4, 1]]) Any help? Thanks From dbowey at comcast.net Tue Nov 13 23:27:19 2007 From: dbowey at comcast.net (Don Bowey) Date: Tue, 13 Nov 2007 20:27:19 -0800 Subject: A JEW hacker in California admits distributing malware that let him steal usernames and passwords for Paypal accounts. References: <1194732615.277219.168670@o38g2000hse.googlegroups.com> <1194890656.529348.85610@v65g2000hsc.googlegroups.com> <4738a9a5$0$27051$ecde5a14@news.coretel.net> Message-ID: On 11/13/07 8:03 PM, in article spskj3ds79bfqg693pt0fsd3723o8asihf at 4ax.com, "ChairmanOfTheBored" wrote: > On Tue, 13 Nov 2007 17:40:30 -0800, Don Bowey wrote: > >> On 11/13/07 5:03 PM, in article q9ikj35p2u3b5c9dhlo8c5tkapivt0qvn5 at 4ax.com, >> "ChairmanOfTheBored" wrote: >> >>> On Tue, 13 Nov 2007 13:37:13 +0100, Hendrik Maryns >>> wrote: >>> >>>> ||__|| | Please do | >>>> / O O\__ NOT >>> >>> Do NOT tell folks what to do in Usenet, dipshit. >> >> >> Notice the "please do not......" That means it is a request, not a demand. >> >> A demand is if I said to you "Quit making such absolutely stupid posts," >> which by the way, is a good idea. >> >> Or I might say "Try to understand a post before you post comments, dipship." >> >> See the difference, dipshit? > > Dipship? > > Bowey boy... You are out of your league. So fuck off. Wrong again. I'm way out of *your* pitiful league. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sat Nov 17 04:39:31 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sat, 17 Nov 2007 10:39:31 +0100 Subject: Interfaces. References: <1ecf1cca-f05f-44b5-8128-a93208815f15@y5g2000hsf.googlegroups.com> Message-ID: <5q7r6jFulqooU2@mid.individual.net> PeterBraden1 at googlemail.com wrote: > I would argue that interfaces/(similar feature) are necessary in > any modern language I wouldn't, but have a look at the Zope interfaces module. It seems to work similar to Java's interfaces. Regards, Bj?rn -- BOFH excuse #104: backup tape overwritten with copy of system manager's favourite CD From pyth0nc0d3r at gmail.com Mon Nov 19 13:01:16 2007 From: pyth0nc0d3r at gmail.com (Lamonte Harris) Date: Mon, 19 Nov 2007 12:01:16 -0600 Subject: Is it possible to use sockets to login to a website that uses php? Message-ID: I need to some how make a script that logs into a website from my desktop and I can do the rest and grab the information on my on hopefully. How would I login to a website using sockets with python? -------------- next part -------------- An HTML attachment was scrubbed... URL: From ptmcg at austin.rr.com Mon Nov 26 12:19:52 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 26 Nov 2007 09:19:52 -0800 (PST) Subject: How to write Regular Expression for recursive matching? References: Message-ID: On Nov 26, 10:51 am, Paul McGuire wrote: > On Nov 26, 10:40 am, lisong wrote: > > > > > > > Hi All, > > > I have problem to split a string like this: > > > 'abc.defg.hij.klmnop' > > > and I want to get all substrings with only one '.' in mid. so the > > output I expect is : > > > 'abc.defg', 'defg.hij', 'hij.klmnop' > > > a simple regular expression '\w+.\w' will only return: > > 'abc.defg', 'hij.klmnop' > > > is there a way to get 'defg.hij' using regular expression? > > > Thanks, > > Why are you using regular expressions? Use the split method defined > for strings: > > >>> 'abc.defg.hij.klmnop'.split('.') > > ['abc', 'defg', 'hij', 'klmnop'] > > -- Paul- Hide quoted text - > > - Show quoted text - Sorry, misread your post - Diez Roggisch has the right answer. -- Paul From m_tayseer82 at yahoo.com Wed Nov 21 11:20:15 2007 From: m_tayseer82 at yahoo.com (Mohammad Tayseer) Date: Wed, 21 Nov 2007 08:20:15 -0800 (PST) Subject: [regex] Basic rewriting Message-ID: <554276.75862.qm@web31101.mail.mud.yahoo.com> It's also preferred if you use \d{2} instead of repeating \d Mohammad Tayseer http://spellcoder.com/blogs/tayseer ____________________________________________________________________________________ Be a better pen pal. Text or chat with friends inside Yahoo! Mail. See how. http://overview.mail.yahoo.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Tue Nov 20 09:42:27 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 20 Nov 2007 15:42:27 +0100 Subject: Python web frameworks References: <226020ef-3955-43e8-b1f6-2ba9ba43d45e@c29g2000hsa.googlegroups.com> Message-ID: <5qga2mFvuljgU1@mid.uni-berlin.de> > 12/7. Django comes with its own little server so that you don't have > to set up Apache on your desktop to play with it. I was rather shocked to learn that django only has this tiny server and does not come with a stand-alone server and is supposed to run as mod_python/cgi-driven app through apache. Which reaps you of all the benefits of standalone servers like connection pooling & caching data and so forth. Including sessions - I presume they always go into the db/filesystem as PHP does. Diez From MonkeeSage at gmail.com Sun Nov 25 08:08:36 2007 From: MonkeeSage at gmail.com (MonkeeSage) Date: Sun, 25 Nov 2007 05:08:36 -0800 (PST) Subject: How can I create customized classes that have similar properties as 'str'? References: <67954d23-9400-4ac9-ba45-bec04fab51a2@s6g2000prc.googlegroups.com> <8eebf8fb-74cc-452a-bbef-2fe93556491f@i29g2000prf.googlegroups.com> <5qqeroF11703eU2@mid.individual.net> <1f2e037f-3667-4070-97cd-f4f6486c9d79@i12g2000prf.googlegroups.com> <13kh7mmeksulu51@corp.supernews.com> <13khh86h0g4nm86@corp.supernews.com> Message-ID: On Nov 24, 6:42 pm, Steven D'Aprano wrote: > This has nothing, absolutely NOTHING, to do with memoization. Memoization > trades off memory for time, allowing slow functions to return results > faster at the cost of using more memory. The OP wants to save memory, not > use more of it. Not to beat a dead horse, but memoization can significantly minimize memory usage, given a large data set with redundant elements (as the OP seems to suggest [e.g., calculating the deltas of trigrams in a natural language]). For example, if the data set has 1/3 redundant elements, then the un-memoized version requires 1/3 more memory, because it needs to store 1/3 more unique copies of the element, whereas the memoized version has only to store unique elements once. Every instance of an element which is already in the cache requires only the cache lookup (speed), rather than the creation of a new object (memory). So the trade-off is actually speed for memory rather than the other way around. Of course, it all depends on the nature of the data; but for large, redundant data sets, memoization is definitely a win when it comes to memory optimization. Regards, Jordan From http Sun Nov 11 16:39:01 2007 From: http (Paul Rubin) Date: 11 Nov 2007 13:39:01 -0800 Subject: Looking for a good Python environment References: <1194389774.159051.55580@19g2000hsx.googlegroups.com> <1194434140.836932.10670@k79g2000hse.googlegroups.com> <7xbqa6f192.fsf@ruckus.brouhaha.com> <1194816672.311766.80070@v3g2000hsg.googlegroups.com> Message-ID: <7xtznslax6.fsf@ruckus.brouhaha.com> Russell Warren writes: > Wing now has multi-threaded debugging. Cool, is it windows-only? I'm using Linux. > A quick look at the current state of SPE shows that it now has multi- > threaded debugging via WinPDB (what I used to use for debugging thread > issues). Interesting. Worth a look to see if it is integrated well. Same issue: this also sounds windows-specific. Thanks though. From cokofreedom at gmail.com Wed Nov 14 04:56:17 2007 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Wed, 14 Nov 2007 09:56:17 -0000 Subject: Arrays In-Reply-To: <1195008669.562425.66420@22g2000hsm.googlegroups.com> References: <1194917023.976618@www.vif.com><1195004202.383567@www.vif.com> <1195008669.562425.66420@22g2000hsm.googlegroups.com> Message-ID: <1195034177.421853.81710@o38g2000hse.googlegroups.com> On Nov 14, 3:51 am, "davisn90... at gmail.com" wrote: > Modules contain objects. When you want to import a specific set of > objects contained in a module into the local namespace, you use: > from import > For example: > from math import sqrt > from math import sin, cos > > If you want to import everything from a module, use: > from import * > For example: > from math import * > > If you want to import a module as an entity itself, use: > import > For example: > import math #Use, for example, math.sqrt to call the sqrt function > > You can also use import ... as ... to "rename" an imported object: > import math as m #Now use m.sqrt instead of math.sqrt > from math import sqrt as square_root #sqrt is now bound to > square_root in the local module > > In the array module, there is an object named array. You could access > using: > import array > array.array > or > from array import array > array > or > from array import array as foobar > foobar > or ... > The way you choose to actually do this is up to you. Most people just > decide what they like/makes the most sense. > > In the math module, there is no object called math. That is why we do > not use > >>> from math import math > Traceback (most recent call last): > File "", line 1, in > ImportError: cannot import name math > > --Nathan Davis > > On Nov 13, 7:25 pm, "Gordon C" wrote: > > > OK Steve, But why do we say "from array import array" and NOT "from math > > import math"? Why the difference in syntax? > > Gord > > > "Steven D'Aprano" wrote in message > > >news:13jk6af1vs5g89 at corp.supernews.com... > > > > On Tue, 13 Nov 2007 11:26:28 -0500, Gordon C wrote: > > > >> OK, thanks to all. The key statement is "from array import array" which > > >> is not exactly intuitive! > > > > "The only intuitive interface is the nipple. After that, it's all > > > learned." -- Bruce Ediger on user interfaces. > > > > Once you've been using Python for a while, using import becomes as > > > intuitive as a spoon. The only tricky part is knowing *which* module to > > > import. But, honestly, are you surprised to learn that the array type is > > > held in in the array module? > > > > -- > > > Steven. Let me just say, that is a perfect reply! From jcd at sdf.lonestar.org Mon Nov 19 09:05:43 2007 From: jcd at sdf.lonestar.org (J. Clifford Dyer) Date: Mon, 19 Nov 2007 09:05:43 -0500 Subject: overriding methods - two questions In-Reply-To: <4741848a$0$20133$426a34cc@news.free.fr> References: <473dd35a$0$7999$426a34cc@news.free.fr> <13js4tebjlucv16@corp.supernews.com> <4741848a$0$20133$426a34cc@news.free.fr> Message-ID: <20071119140543.GD2175@sdf.lonestar.org> On Mon, Nov 19, 2007 at 01:41:46PM +0100, Bruno Desthuilliers wrote regarding Re: overriding methods - two questions: > > Steven D'Aprano a ?crit : > > On Fri, 16 Nov 2007 18:28:59 +0100, Bruno Desthuilliers wrote: > > > >>> Question 1: > >>> > >>> Given that the user of the API can choose to override foo() or not, how > >>> can I control the signature that they use? > >> While technically possible (using inspect.getargspec), trying to make > >> your code idiot-proof is a lost fight and a pure waste of time. > > > > > > Worse: it's actually counter-productive! > > > > The whole idea of being able to subclass a class means that the user > > should be able to override foo() *including* the signature. > > If you see subclassing as subtyping, the signatures should always stay > fully compatibles. > Isn't that more what Zope-type interfaces are for than inheritance? I'm uncertain here, but I'm not persuaded that changing signature is bad. From piet at cs.uu.nl Tue Nov 13 07:52:57 2007 From: piet at cs.uu.nl (Piet van Oostrum) Date: Tue, 13 Nov 2007 13:52:57 +0100 Subject: Distributed RVS, Darcs, tech love References: <1192850894.310464.89070@e9g2000prf.googlegroups.com> <1192914246.208743.94870@y27g2000pre.googlegroups.com> <471afd4c.179297746@news.readfreenews.net> <1192972158.250126.203980@v23g2000prn.googlegroups.com> <471b64b2$0$90272$14726298@news.sunsite.dk> <1192980705.698811.128060@i38g2000prf.googlegroups.com> Message-ID: >>>>> Lew (L) wrote: >L> Evidence is that TeX development is dead. There is not yet firm evidence >L> that Tex is a "dead end" (or even what that means), and there has been none >L> (nor, I expect, is there any) that any of that reflects on Knuth's skill as >L> a programmer. According to Knuth's definition the name 'TeX' is reserved for a program that passes the trip test. Under this assumption TeX is dead by definition. However in a broader sense TeX is still actively developed, but it may not be called just 'TeX' because these new versions contain extensions. So they get new names with 'tex' being part of their name. PdfTeX and LuaTeX are new versions that are being developed right now. -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From hat at se-162.se.wtb.tue.nl Fri Nov 16 07:49:37 2007 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Fri, 16 Nov 2007 13:49:37 +0100 Subject: Python Design Patterns - composition vs. inheritance References: Message-ID: On 2007-11-15, snewman18 at gmail.com wrote: > inheritance when an object's relationship to another object is 'is-a' > and composition when the relationship is 'has-a'. > > Since this is all new and I'm still learning, I was hoping someone can > give me some pointers on best practices on applying these ideas. If my > logic is incorrect on anything, please don't hesitate to tell me where > I'm wrong - I'm completely open to any help offered. > > As a very simplified example, if I had two classes, Pet and Owner, it > seems that I would not have Pet inherit from Owner, since a pet 'has > an' owner, but not 'is an' owner. If this is correct, does my code > below reflect this? I passed the owner object into the pet object's > constructor - is this the right way to do it? This is indeed one way. One of the things you enforce in this way that there is no Pet object without an owner. > Also, I've seen talk that ideally you shouldn't have too many "dots" > in your method calls, instead using delegates to the methods and > attributes. Can anyone elaborate on this? Ideally, should I be writing As with most design stuff, they are right and they are also wrong. It's a trade-off. They are right in the sense that if you change the structure of your links, you will break potentionally a lot of code. Imagine you have to ask a data base for the owner rather than having a direct link. All "pet.owner" references will need to be changed then. If you hide the connection inside your Pet, there is only one place that needs to be changed. They are wrong in the sense that it is not always appropiate for a Pet object to perform such a function. By hiding "self.owner.address" inside Pet, you are designing a smart pet that knows how to find the address of its owner. Unfortunately, smarter also means more complex, and at some point you will defeat the advantage of OO, namely spreading responsibilities, and having several simple objects that work together to realize your application. So there is a trade-off. There is no universal rule, it highly depends on your application, your future plans, and the lifetime of the app (to name a few). > getattr() methods so I can do pet.address instead of > pet.owner.address? Should I be doing the same with owner's methods > like I did with get_foo()? I'd say no. One of the 'rules' (guide lines) of Python is "Be explicit rather than implicit" [1]. You may save a few dots, on the other hand, you obfuscate how the link is realized (that is "pet.address" doesn't say it uses owner to make the connection, unlike "pet.owner.address"). In the long run, the latter may be more important. In general, I think you shouldn't need advanced trickery like __getattr__() for your design. If you do, your design is most likely wrong. [1]: The Zen of Python: http://www.python.org/dev/peps/pep-0020/ Sincerely, Albert From paul at boddie.org.uk Fri Nov 9 07:48:42 2007 From: paul at boddie.org.uk (Paul Boddie) Date: Fri, 09 Nov 2007 04:48:42 -0800 Subject: parallel csv-file processing In-Reply-To: <7xve8b65rp.fsf@ruckus.brouhaha.com> References: <1194605470.380185.111520@19g2000hsx.googlegroups.com> <7xve8b65rp.fsf@ruckus.brouhaha.com> Message-ID: <1194612522.204966.67020@z24g2000prh.googlegroups.com> On 9 Nov, 12:02, Paul Rubin wrote: > > Why not pass the disk offsets to the job server (untested): > > n = 1000 > for i,_ in enumerate(reader): > if i % n == 0: > job_server.submit(calc_scores, reader.tell(), n) > > the remote process seeks to the appropriate place and processes n lines > starting from there. This is similar to a lot of the smarter solutions for Tim Bray's "Wide Finder" - a problem apparently in the same domain. See here for more details: http://www.tbray.org/ongoing/When/200x/2007/09/20/Wide-Finder Lots of discussion about more than just parallel processing/ programming, too. Paul From joemystery123 at gmail.com Thu Nov 1 21:18:25 2007 From: joemystery123 at gmail.com (crybaby) Date: Thu, 01 Nov 2007 18:18:25 -0700 Subject: ValueError: invalid \x escape Message-ID: <1193966305.529136.149110@z9g2000hsf.googlegroups.com> I wrote a python code in linux text pad and copied to thumb drive and try to ran the file by changing the path to windows: sys.path = sys.path + ['D:\Python24\Lib\site-packages\mycode] I get the following error: ValueError: invalid \x escape I am pretty sure this problem is due some kind of linux end of line markers or escape characters that windows os doesn't understand. Is there a way to fix this? From ullrich at math.okstate.edu Sat Nov 3 07:59:58 2007 From: ullrich at math.okstate.edu (David C. Ullrich) Date: Sat, 03 Nov 2007 05:59:58 -0600 Subject: (MAC) CoreGraphics module??? References: <22uki39arp3a83topaimrka4s37uo1okm5@4ax.com> Message-ID: On Fri, 2 Nov 2007 13:14:16 +0100, Tommy Nordgren wrote: > >On 2 nov 2007, at 02.10, David C. Ullrich wrote: > >> [Why doesn't CoreGraphics work?] >> -- >> http://mail.python.org/mailman/listinfo/python-list > There are Python wrappers for the Cocoa API. These can be used with >binaries from Python.org. >The name of the module is PyObjC, and can be downloaded from >sourceforge. Ah. I'd read about this in the context of using Python in Xcode applications, which seems like something I definitely want to learn how to do, but it was scheduled for "later"... PyObjC will also allow a person to access Cocoa things from an ordinary Python script? If so, keen. Thanks. >There are binary builds for Python up to version 2.4.1. > For Python 2.5.1, it is necessary to build it yourself, which I've >found out requires modifying setup.py. >(The problem is that setup.py tries to use two modules that's not >installed by default on Tiger) >------ >What is a woman that you forsake her, and the hearth fire and the >home acre, >to go with the old grey Widow Maker. --Kipling, harp song of the >Dane women >Tommy Nordgren >tommy.nordgren at comhem.se > > ************************ David C. Ullrich From kyosohma at gmail.com Mon Nov 19 09:52:10 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 19 Nov 2007 06:52:10 -0800 (PST) Subject: Python too complex ?!?!?! References: <7hC%i.28332$mv3.17248@newsfe10.phx> Message-ID: On Nov 17, 7:46 am, Brian wrote: > Had a unsettling conversation with a CS instructor that > teaches at local high schools and the community > college. This person is a long-term Linux/C/Python > programmer, but he claims that the install, config, and > library models for C# have proved to be less > problematic than Python. So both his courses (intro, > data structs, algorithms) are taught in C#. > > I am a low-end (3-year) journeyman Pythonista, and I > was attracted to the language because of its > simplicity. And I have come to enjoy the richness of > available libraries. > > Many of the good people of this NG may be 'too close' > to answer, but has Python, as a general devel platform, > lost its simplicity ? Is library install too complex > and unreliable ? Will my dog go to heaven ? If this professor was only using Windows for his environment, then I might be able to understand his argument better. There are many more external modules for Python that don't have Windows installers than there are with binaries. And I've had more than my fair share of broken setup.py files. On the other hand, if all that is needed are the standard libraries, than it's a breeze to install Python since they're all included. Mike From buyonline.eworld at gmail.com Sat Nov 17 07:32:52 2007 From: buyonline.eworld at gmail.com (Cope) Date: Sat, 17 Nov 2007 04:32:52 -0800 (PST) Subject: What is python????? References: <7ab5b781-3c6c-4fb5-9be1-703d5e7e73a6@s12g2000prg.googlegroups.com> <959349ce-34ad-4d8e-aea0-b7bcbbc6112f@f13g2000hsa.googlegroups.com> <4a92044d-ef1b-47b0-82e0-45946e08a794@n20g2000hsh.googlegroups.com> <828cecd6-40b9-4aaf-bb07-8386b6c7518e@f3g2000hsg.googlegroups.com> Message-ID: <1e0f997d-f51d-416e-b272-39ced467073b@e10g2000prf.googlegroups.com> On Nov 17, 5:00 pm, "Amit Khemka" wrote: > On 11/17/07, Cope wrote: > > > > > In our place we eat pythons for curry. Its delicious. > > And how about your python? > > > Cope > > Not much of the difference here, it is just a bit more flexible. My > python goes and brings me whatever I wish to eat. > > Cheers, > -- > -- > Amit Khemka You must be Python Charmer From duncan.booth at invalid.invalid Thu Nov 1 05:26:21 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 1 Nov 2007 09:26:21 GMT Subject: setting variables in outer functions References: <87myu1k4rm.fsf@mulj.homelinux.net> <1193830119.542006.137750@o38g2000hse.googlegroups.com> <1193870968.747606.281180@50g2000hsm.googlegroups.com> <87ir4mj24t.fsf@mulj.homelinux.net> Message-ID: Hrvoje Niksic wrote: > In real-life code, closures are used to implement callbacks with > automatic access to their lexical environment without the need for the > bogus additional "void *" argument one so often sees in C callbacks, > and without communication through global variables. If the callbacks > can access variables in the outer scope, it's only logical (and > useful) for them to be able to change them. Prohibiting modification > reduces the usefulness of closures and causes ugly workarounds such as > the avar[0] pattern. > In real life code methods are used to implement callbacks with automatic access to their environment without the need for any C type hacks. What is your point here? Python isn't C (or Javascript). If you have a function which takes a callback in Python you just pass it a bound method and you have all the context you want without resorting to ugly workrounds. From bearophileHUGS at lycos.com Fri Nov 16 05:19:09 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 16 Nov 2007 02:19:09 -0800 (PST) Subject: implement random selection in Python References: Message-ID: This recipe of mine may help: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/498229 Bye, bearophile From gagsl-py2 at yahoo.com.ar Sat Nov 3 01:42:15 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 03 Nov 2007 02:42:15 -0300 Subject: difference between IDLE and command line References: <472b5294$0$13762$6e1ede2f@read.cnntp.org> Message-ID: En Fri, 02 Nov 2007 13:38:07 -0300, Jim Hendricks escribi?: > New to Python, and just had something strange happen. > > I've been running my new code in IDLE running in windows. My IDLE > version shows as 1.2.1, Python version displaying in IDLE is 2.5.1. > > I have been editing my code in UltraEdit then testing in IDLE by > choosing open, then F5. I didn't see an easy way to refresh in IDLE, so > each edit I've been closing the file (not IDLE itself), then opening > again. Since IDLE does not keep track of what directory I last opened > from, this gets tedious, so I decided to run my code from the command > line. > > Here's where it got interesting for me. From the command line, I'm in > the directory containing my source, I execute via "python mycode.py", I > receive an error in my code. Specifically, it's erroring because I have > a copyright character in a string that I am outputting via the > file.write method. The error has to do with no encoding declared. > > What surprised me is that this code runs with no problems in IDLE. Since version 2.4, Python *requires* an explicit encoding declaration at the start of the file, when it contains a string literal outside the ASCII range (0 to 127). See That IDLE doesn't require an encoding (and assumes something, perhaps latin-1, I don't know) is an unfortunate bug (already reported, I think). -- Gabriel Genellina From stefan.behnel-n05pAM at web.de Thu Nov 1 04:57:01 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Thu, 01 Nov 2007 09:57:01 +0100 Subject: XML document causes pickle to go into infinite recursion In-Reply-To: <1193884983.837420.67460@o3g2000hsb.googlegroups.com> References: <1193884983.837420.67460@o3g2000hsb.googlegroups.com> Message-ID: <472994DD.7000401@web.de> Orest Kozyar wrote: > I'm working on a CGI script that pulls XML data from a public database > (Medline) and caches this data using shelveleto minimize load on the > database. In general, the script works quite well, but keeps crashing > every time I try to pickle a particular XML document. Below is a > script that illustrates the problem, followed by the stack trace that > is generated (thanks to Kent Johnson who helped me refine the > script). I'd appreciate any advice for solving this particular > problem. Someone on Python-Tutor suggested that the XML document has > a circular reference, but I'm not sure exactly what this means, or why > the document would have a reference to itself. minidom creates a pretty complete tree data structure, with loads of backlinks to parent elements etc. That's where your circular references come from. I don't know why you want to use pickle here (and not serialised XML or the plain in-memory tree), but if memory consumption is an issue, try cElementTree, which comes with Python 2.5 (or as an external module for older versions). It's faster, more memory friendly and easier to use than minidom. There's also lxml.objectify, in case you can't live without pickeling. http://effbot.org/zone/celementtree.htm http://codespeak.net/lxml Stefan From bedouglas at earthlink.net Thu Nov 22 20:23:29 2007 From: bedouglas at earthlink.net (bruce) Date: Thu, 22 Nov 2007 17:23:29 -0800 Subject: python question!! Message-ID: <13a601c82d6f$76587eb0$0301a8c0@tmesa.com> hi... new to python, and can't seem to find an answer to this via google.. of course i'm not even sure what to callit.. so i might be searching in the wrong places... a python script foo.py, can have an import.. foo.py import dog import cat where dog, and cat, might have other "import" statements, and so on.. is there a function/feature/etc.. that i can run on "foo.py" that would walk through the entire list of files that make up foo.py, so i could see the list of *.py files that are required to run "foo.py". this kind of list could then be used to compare my local version of files, with the files that my group are changing, so i can tell which (if any) files have been changed for the foo.py app... thanks From gkreddybh at gmail.com Sun Nov 25 23:48:11 2007 From: gkreddybh at gmail.com (nani) Date: Sun, 25 Nov 2007 20:48:11 -0800 (PST) Subject: i want to know what is the problem in this code Message-ID: <861f006c-0568-487a-a0ec-fc081cdb9487@d21g2000prf.googlegroups.com> i am getting the following error for below code Python 2.5.1: C:\Python25\python.exe Mon Nov 26 10:13:17 2007 A problem occurred in a Python script. Here is the sequence of function calls leading up to the error, in the order they occurred. C:\Program Files\Apache Group\Apache2\cgi-bin\hello.py in () 7 8 val = cgi.FieldStorage() 9 name = val["name"].value 10 time_from = val["time_from"].value 11 time_to = val["time_to"].value name undefined, val = FieldStorage(None, None, []), ].value = [] C:\Python25\lib\cgi.py in __getitem__(self=FieldStorage(None, None, []), key='name') 565 if item.name == key: found.append(item) 566 if not found: 567 raise KeyError, key 568 if len(found) == 1: 569 return found[0] builtin KeyError = , key = 'name' : 'name' #!C:/Python25/python.exe import cgi import cgitb; cgitb.enable() print "Content-Type: text/html" print val = cgi.FieldStorage() name = val["name"].value time_from = val["time_from"].value time_to = val["time_to"].value html = """

Hello %s from %s to %s

""" print html%(name, time_from, time_to) html page is.......................................
Enter your name:
Time from:
Time to:
From python at hope.cz Wed Nov 7 10:19:41 2007 From: python at hope.cz (Johny) Date: Wed, 07 Nov 2007 07:19:41 -0800 Subject: What colour model does the image use in PIL In-Reply-To: <87zlxqb1rv.fsf@mulj.homelinux.net> References: <1194442641.095444.17690@z9g2000hsf.googlegroups.com> <87zlxqb1rv.fsf@mulj.homelinux.net> Message-ID: <1194448781.660254.36120@22g2000hsm.googlegroups.com> On Nov 7, 2:53 pm, Hrvoje Niksic wrote: > Johny writes: > > I use PIL and with it im.getpixel((x,y)) to find out the colour of a > > pixel. But how can I find out in which color model the the return > > value is? > > im.mode gives you a string such as 'RGBA' or 'CMYK'. im.getbands() > returns a tuple such as ('R', 'G', 'B', 'A'). Thank you for your help. Can you please help me once more? Now I would need to apply a threshold value to the image, where everything above a certain brightness level becomes white, and everything below the level becomes black. How can I do that with PIL? Thank you L From klenwell at gmail.com Sat Nov 3 14:51:56 2007 From: klenwell at gmail.com (klenwell) Date: Sat, 03 Nov 2007 18:51:56 -0000 Subject: __file__ vs __FILE__ In-Reply-To: <5p33o0Fp4918U2@mid.individual.net> References: <1194060097.141059.196040@e34g2000pro.googlegroups.com> <5p33o0Fp4918U2@mid.individual.net> Message-ID: <1194115916.533465.264940@z24g2000prh.googlegroups.com> On Nov 3, 4:18 am, Bjoern Schliessmann wrote: > Jeff McNeil wrote: > > I've used the 'os.path.realpath(os.path.pardir)' construct in a > > couple of scripts myself. > > In Windows? Using Linux, this gives me "..". > > I use os.path.dirname(os.path.abspath(__file__)) > > > That ought to work within the interactive interpreter. > > Why do you also enter that code in the interpreter? If it is in a > module, you should always be able to use __file__. > > Regards, > > Bj?rn > > -- > BOFH excuse #238: > > You did wha... oh _dear_.... > I use os.path.dirname(os.path.abspath(__file__)) That makes sense, as it is almost a literal translation of what I'm used to using in PHP. Thanks for pointing this out. From j3nsby at gmail.com Mon Nov 5 13:42:49 2007 From: j3nsby at gmail.com (Jens) Date: Mon, 05 Nov 2007 10:42:49 -0800 Subject: Python good for data mining? In-Reply-To: <1194276582.961527.101890@57g2000hsv.googlegroups.com> References: <1194141739.683498.206780@k79g2000hse.googlegroups.com> <1194234136.556841.246740@v3g2000hsg.googlegroups.com> <1194270693.957593.55250@19g2000hsx.googlegroups.com> <1194276582.961527.101890@57g2000hsv.googlegroups.com> Message-ID: <1194288169.309122.24330@57g2000hsv.googlegroups.com> On 5 Nov., 16:29, Maarten wrote: > As for pytables: it is the most elegant programming interface for HDF > on any platform that I've encountered so far. Most other platforms > stay close the HDF5 library C-interface, which is low-level, and quite > complex. PyTables was written with the end-user in mind, and it shows. > One correction though: PyTables is not a database: it is a storage for > (large) arrays, datablocks that you don't want in a database. Use a > database for the metadata to find the right file and field within that > file. Keep in mind though that I mostly work with externally created > HDF-5 files, not with files created in pytables. PyTables Pro has an > indexing feature which may be helpful for datamining (if you write the > hdf-5 files from python). > PyTables? Wow! Looks amazing - I'll have to try that out soon. Thanks! From snewman18 at gmail.com Thu Nov 15 17:10:26 2007 From: snewman18 at gmail.com (snewman18 at gmail.com) Date: Thu, 15 Nov 2007 14:10:26 -0800 (PST) Subject: Python Design Patterns - composition vs. inheritance References: <5q3p0uFu0notU1@mid.uni-berlin.de> Message-ID: <63c98d5d-b65f-4a9c-a17c-d25e20afec49@w28g2000hsf.googlegroups.com> > Yes. Of course there are other ways, establishing the connection later, > and of course making the Owner know her pets. But your unidirectional, > ctor-passed implementation is sensible. I think my main concern while getting my toes wet on this was to not reference the owner object out of "thin air" but to pass it in when pet is instantiated. I'm not sure what 'actor-passed' is yet, but it gives me something to search for and learn about. I'd love to see other/better/different implementations if anyone wants to enlighten me. What would a non-unidirectional (bidirectional?) look like or accomplish? Does that mean that in the example I provided, you could make the owner aware of their pets? That's something that is not available using inheritance, if I understand correctly. > No, that's certainly not a good idea. And I'm under the impression you > misunderstood something there in the original lecture/explanation. That wouldn't surprise me if I misunderstood it :) I've watched Alex Martelli's Google Tech talk a half-dozen times and it's only now starting to make sense. It's hard to apply some of the available material's examples to Python since a lot of the documentation I find is specific to implementations in lower-level languages and don't apply to Python. (such as the Strategy pattern?) My understanding was that using __getattr__ was either called delegation or a Command pattern, and this was hiding/encapsulating the specifics of the implementation. I'd like to be corrected if I'm wrong, or if I'm two blocks off Main Street with this. > The reason is simple: by adding these methods, you essentially extend > Pet's knowledge as a class to what only its owner has to know. Which > makes no sense. Why should pets know about addresses? Or cars? Or > anything else that belongs to the owner only. > Of course there are just reasons to create such delegation methods - if > for example the property/method is of general interest to the Pet, but > implemented by means of the owner. But I've got difficulties even to > imagine such thing, at least in your actual example. Yeah, I was struggling to come up with a decent example - a pet's address was about the best example of a delegated property I could think of. If someone has a better set of objects that make sense, let me know and I'll probably feel less foolish asking. Thanks for your help! It's truly appreciated. Scott From tarundevnani at gmail.com Tue Nov 13 02:35:29 2007 From: tarundevnani at gmail.com (tarun) Date: Tue, 13 Nov 2007 13:05:29 +0530 Subject: Issue with wxPython GUI Message-ID: Hi All, I've a probelm and solution for it to build the preface. Below it is the new problem I'm facing. Can someone help me out? *Problem:* I've have created a GUI (using wxPython widgets) where in I've a message log window (A TextCtrl window). I've a router.dll that helps me putting in message onto a channel. In my script that generates the GUI, I want to continuously poll the channel and populate the messages from the channel to the message log window. For this I've to put a while (1) loop, but when I do this, the GUI doesn't come up. I see the GUI coming when while(1) is removed. Is there any issue with usage of app.mainloop and while(1) together. *Solution: *I used: self.Bind (wx. EVT_IDLE, self.OnIdle) And in the OnIdle function, I check if the data is available on the channel. Referred: http://wiki.wxpython.org/LongRunningTasks *New Problem: *I am opening and executing a script from the GUI. The script has a many log messages, which it posts on some shared memory. The GUI reads the messages from the shared memory, in the Idle loop. But the script is huge and so the logging is not run-time. Rather this happens only after the script has executed. Moreover, the GUI becomes un-responsive till the script has completely executed. Do you have any suggestions for this? Thanks & Regards, Tarun -------------- next part -------------- An HTML attachment was scrubbed... URL: From exarkun at divmod.com Thu Nov 1 17:34:47 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 1 Nov 2007 16:34:47 -0500 Subject: marshal vs pickle In-Reply-To: <1193951706.592622.49260@o38g2000hse.googlegroups.com> Message-ID: <20071101213447.8162.1938857708.divmod.quotient.30585@ohm> On Thu, 01 Nov 2007 21:15:06 -0000, Aaron Watters wrote: >On Nov 1, 4:59 pm, Jean-Paul Calderone wrote: >> On Thu, 01 Nov 2007 20:35:15 -0000, Aaron Watters wrote: >> >On Nov 1, 2:15 pm, Raymond Hettinger wrote: >> >> On Nov 1, 4:45 am, Aaron Watters wrote: >> >> >> > Marshal is more secure than pickle >> >> >> "More" or "less" make little sense in a security context which >> >> typically is an all or nothing affair. Neither module is designed for >> >> security. From the docs for marshal: >> >> >> ''' >> >> Warning: The marshal module is not intended to be secure against >> >> erroneous or maliciously constructed data. Never unmarshal data >> >> received from an untrusted or unauthenticated source. >> >> ''' >> >> >> If security is a focus, then use xmlrpc or some other tool that >> >> doesn't construct arbitrary code objects. >> >> >I disagree. Xmlrpc is insecure if you compile >> >and execute one of the strings >> >you get from it. Marshal is similarly insecure if you evaluate a code >> >object it hands you. If you aren't that dumb, then neither one >> >is a problem. As far as I'm concerned marshal.load is not any >> >more insecure than file.read. >> >> You're mistaken. >> >> $ python >> Python 2.4.3 (#2, Oct 6 2006, 07:52:30) >> [GCC 4.0.3 (Ubuntu 4.0.3-1ubuntu5)] on linux2 >> Type "help", "copyright", "credits" or "license" for more information. >> >>> import marshal >> >>> marshal.loads('RKp,U\xf7`\xef\xe77\xc1\xea\xd8\xec\xbe\\') >> Segmentation fault >> >> Plenty of other nasty stuff can happen when you call marshal.loads, too. > >I'll grant you the above as a denial of service attack. You are right >that I was mistaken in that sense. (btw, it doesn't core dump for >2.5.1) > >That is/was a bug in marshal. Someone should fix it. Properly >implemented, >marshal is not fundamentally insecure. One can then ask the question of whether or not marshal is properly implemented in any extant version of CPython. ;) It isn't much comfort to know that marshal is ideologically sound after someone uses it to exploit your service. >Can you give me an example >where someone can erase the filesystem using marshal.load? I saw one >for pickle.load once. > Many bugs which lead to a segfault can also be exploited to execute arbitrary code. Not all such bugs can be. I haven't looked closely at the marshal source code to determine if it can be or not in this case. My observations agree with yours, for what it's worth. A cursory investigation doesn't reveal any inputs which cause segfaults in trunk at HEAD with marshal.loads(), although there are still many which will cause it to allocate huge amounts of memory, another effective DoS attack. Jean-Paul From donn.ingle at gmail.com Sat Nov 17 05:19:07 2007 From: donn.ingle at gmail.com (Donn Ingle) Date: Sat, 17 Nov 2007 12:19:07 +0200 Subject: overriding methods - two questions References: <473dd35a$0$7999$426a34cc@news.free.fr> <13js4tebjlucv16@corp.supernews.com> <13jt8u2r3l8in30@corp.supernews.com> Message-ID: > *not* being called by the user but *by* my API (in a timeout loop). > > You don't know that. How can you possibly guarantee that the user won't > find some other use for the draw() method Well, as per your good examples, I would answer that as the parameters passed to draw() grow in number, so the API is actually growing and so the draw() call will be updated. Or, other calls can be introduced like drawPreview() etc. (Better cos it won't break old code.) The way it is now, in heavy alpha :), is that the draw() is *only* called outwards and does not return or call parentClass.draw( self, ...) back in any way. It's a pure source of context.cairo_ commands. > BTW, it is a convention for method names to be lower case, and classes to > be Title case. Seeing something like obj.Draw, most(?) Python developers > will expect that the Draw attribute of obj is itself a class: Thanks, I'm pretty damn unorganized in that way. Is it convention to do: class BigLetterAndCamels(): def smallLetterAndCamels() or def smallletterandnocamels() ? /d From usenet-mail at markshroyer.com Sun Nov 11 08:21:22 2007 From: usenet-mail at markshroyer.com (Mark Shroyer) Date: Sun, 11 Nov 2007 13:21:22 GMT Subject: Portrait of a "real life" __metaclass__ References: <1194680507.652797.111620@v23g2000prn.googlegroups.com> <1194767329.076870.274710@e34g2000pro.googlegroups.com> Message-ID: On 2007-11-11, Jonathan Gardner wrote: >> There isn't much difference between >> >> match_calendar_month(2007, 11, message) >> >> and >> >> m = CalendarMonthMatcher(2007, 11) >> m.match(message) > > Yes, there isn't a world of difference between the two. But there > is a world of difference between those and: > > match(message, before=date(2007, 12, 1), after=date(2007, 11, 1)) > > And you can add parameters as needed. In the end, you may have a > lot of parameters, but only one match function and only one > interface. No, that would be an absolutely, positively bad decision. Heck, suppose I wanted to match messages from "@ufl.edu" that are at least seven days old, OR all other messages from the previous month or earlier -- but only if we're at least four days into the current month. (This isn't a fanciful invention for the sake of argument, it's an actual rule I'm using right now.) Then, at best, we'd have something like: (match(message, domain="ufl.edu") and match(message, before=date(2007, 11, 4)) or (match(message, before=date(2007, 11, 1)), \ butMatchThePreviousMonthInsteadIfDaysIntoCurrentMonthIsLessThan=4)) Or you could go the other way and try to solve it by adding even more arguments to the function, but then you're even worse off for complexity. Either way, you're left without an abstract way to say "this month" or "previous week" without implementing the logic to do so separately from the data. In my experience, that kind of design ends up making things a lot more complicated than they need to be, once the application is put to use and once you (or worse, somebody else) starts wanting to extend it. Compare that to the actual implementation of this rule in my program: rule= Or( And( SenderPattern(re.compile("@ufl\.edu")), DaysOld(7) ), CalendarMonthOld(match_delay_days=4) ) rule.match(message) (The current implementation of CalendarMonthOld takes the current month if not otherwise specified.) > Or it could be that you are confusing two things with each other. > > [...] > > How do you avoid complexity? You take a step back, identify patterns, > or pull different things apart from each other (like rows and > columns), and try to find the most basic principles to guide the > entire system. If I could just break everything down into date ranges, I would. But that doesn't give me the kind of behavior I want. > The very fact that you are talking about months (and thus days and > weeks and years and centuries, etc...) and not generic dates means you > have some more simplifying to do in your design elsewhere as well. No, it truly does not. Sometimes I want to match a message that is N days old; sometimes I want to match a message from the previous *calendar month* or earlier, which can not be readily specified as a number of days; the same goes for calendar year, calendar week, etc. Some small amount of calculation has to be performed to convert a given number of calendar weeks into a datetime range. And in order for the user -- that is, primarily, me, but hopefully others too once I get around to polishing up this thing -- to be able to generically say, "match all the messages from the last quarter", bundling such behavior with the data it operates on makes the system easier to implement and *much* easier to extend. If I used a monolithic match() function, as you suggest, then any user who wanted to implement a new message handling action or a new matching rule would need to alter the core application. With my approach, all that user needs to do is toss a module containing his or her custom Matcher and Action implementations into a certain directory, and he's good to go. > Rewrite the SaveAttachmentsByMonth so that it calls a more generic > SaveAttachmentsByDateRange function. Or better yet, have it > FilterEmailsByDateRange and ExtractAttachment and SaveAttachment. Or > even better, have it FilterEmailsBySpecification(date_from=X, > date_to=Y) and SaveAttachmentl. Yeah, actually the class I have defined for this action *is* a more generic "save attachments by date range" action type, as I used for an example later in that post when I described passing it a CalendarWeek date range instead of a CalendarMonth. The confusion on this point is my fault, though, as I also referred to this action as SaveAttachmentsByMonth in a misguided attempt at clarifying my point. > Do you see the point? Your big function SaveAttachmentsByMonth is kind > of like point number 735. It's easier to describe it as the point at > (7,35) than as a single number. It's better to talk about the most > basic functionality --- saving emails and filter emails -- rather than > talking about big concepts. > > [...] > > Your users will appreciate it as well. While it may be nice to have a > shiny button that saves attachments by months, they'd rather they > could specify the date ranges theyd like to use (hours? Days? Weeks? > Quarters?) and what they'd like to save (the attachments, the entire > email, etc...) (Better yet, what they'd like to *do*.) That's the point precisely! How does one specify "last quarter," in a configuration file, in terms of a raw range of dates, such that it retains the meaning of "last quarter" as we progress from one month to the next? He doesn't. He needs the application to understand the concept of a "quarter" first. With my approach, all he'd need to do to get the app thinking in terms of quarters for him, is to add to the app's extensions/ subdirectory a module containing the following: class QuarterAgeSpec(AgeSpec): def __init__(self, relative_quarter=0): now = datetime.utcnow() year, quarter = now.year, (now.month-1)/3 (self.year, self.quarter) \ = self._relative(year, quarter, relative_quarter) def _relative(self, year, quarter, delta): quarter += delta if quarter/4 != 0: year += quarter/4 quarter %= 4 return (year, quarter) def match(self, timestamp): (n_year, n_quarter) = self._relative(self.year, self.quarter, 1) return timestamp >= datetime(self.year, self.quarter*3+1, 1) \ and timestamp < datetime(n_year, n_quarter*3+1, 1) Then my program calls Matcher.__subclasses__() and finds the new implementation, so he can immediately use this new Matcher from his configuration file as: actions = ( ( mailbox => ( ... ), match => ( type => Quarter, relative_quarter => -1, ), action => ( ... ), ), ) That's all there is to it. He doesn't have to go about mucking with the program's internals, he just needs to extend one specific class with a well-defined interface. How would you propose to accomplish this following your monolithic match-function approach, on the other hand? > Except we don't have different kinds of re expressions for different > kinds of matching. One spec to handle everything is good enough, and > it's much simpler. If you have the time, try to see what people did > before regex took over the world. In fact, try writing a text parser > that doesn't use one general regex function. You'll quickly discover > why one method with one very general interface is the best way to > handle things. Sure, if you're dealing with a known, fixed set of types of inputs. But semantically -- in terms of how they're entered into the configuration file, in terms of the logic needed to match them -- a CalendarMonth and a DaysOld are *not* the same thing. Slightly different code is required to initialize / define either one; and in my experience, when you have many differing behaviors and inputs floating around together as such, it's often more productive to group them together behind a class hierarchy. > See, you are thinking in general terms, but you are writing a specific > implementation. In other words, you're talking about the problem the > right way, but you're trying to write the code in a different way. > Coming from a C, perl, or Java background, this is to be expected. > Those languages are a strait-jacket that impose themselves on your > very thoughts. But in Python, the code should read like pseudo-code. > Python *is* pseudo-code that compiles, after all. > > You don't need many classes because the branching logic--the bits or > the program that say, "I'm filtering by days and not months"--can be > contained in one bigger function that calls a very general sub- > function. There's no need to abstract that bit out into a class. No > one is going to use it but the match routine. Just write the code that > does it and be done with it. > > In fact, by writing classes for all these branches in the program > logic, you are doing yourself a disservice. When you return to this > code 3 weeks from now, you'll find all the class declarations and > metaclass and syntactic sugar is getting in your way of seeing what is > really happening. That is always bad and should be avoided, just like > flowery language and useless decorum should be avoided. As for the metaclass -- yeah, quite possibly; that was more of a "just for fun" experiment than anything else. Hence the Don Quixote reference; attacking imaginary enemies and all that ;). But as for the rest of this statement, I thoroughly disagree. This object-oriented "syntactic sugar" is, in this case, a means of organizing my application's behavior into meaningful, simply understood, and easily adapted units. A monolithic "match" function with an ever-increasing number of arguments as I cram in more and more classes of matching logic? *That* is what's bound to become incomprehensible. > No, you're arguing about the thing I wanted to argue about, so you see > the point I am trying to make. > > It's painful to realize that all those years learning OO design and > design patterns just to make Java usable are wasted in the world of > Python. I understand that because I've invested years mastering C++ > and perl before discovering Python. Your solace comes when you embrace > that and see how much simpler life really is when the language gets > out of your way. It's just as harmful as to ignore the occasional usefulness of object-oriented patterns as it is to abuse them left and right. My approach on this project feels right, it produces legible and easily extensible code, it's been a breeze to test and maintain so far... if implementing different types of matching logic as classes here is "wrong" by Python convention (and that would come as a rather big surprise to me), then I don't want to be right. -- Mark Shroyer http://markshroyer.com/ From kyosohma at gmail.com Mon Nov 26 15:19:58 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 26 Nov 2007 12:19:58 -0800 (PST) Subject: gnosis XML objectify References: Message-ID: <21051b4a-9690-4f48-a6bd-8ae467987261@r31g2000hsg.googlegroups.com> On Nov 26, 1:46 pm, "Wang, Harry" wrote: > The gnosis xml libs should not be version specific, but when I try to use Python 2.5, I am getting "not well formed (invalid token)" errors. > > Harry When does this happen? When you import the module? When you pass it some xml? Do you have a full traceback? Mike From bborcic at gmail.com Mon Nov 26 10:15:25 2007 From: bborcic at gmail.com (Boris Borcic) Date: Mon, 26 Nov 2007 16:15:25 +0100 Subject: eof In-Reply-To: <3cb8cff4-4c1d-4ca2-8d21-c012a109351b@w34g2000hsg.googlegroups.com> References: <92a2c0c9-e6a1-4344-aeac-830940200f20@t47g2000hsc.googlegroups.com> <79i9k35vs76cqgqnino7dj3ql623us3euq@4ax.com> <6c04c760-6cf1-4715-9ec9-30f43ebaa01f@d27g2000prf.googlegroups.com> <062a9497-7626-440a-93eb-b897e6dec01f@p69g2000hsa.googlegroups.com> <9e25e813-f4a7-48c6-9f0e-ef04223e29a0@e23g2000prf.googlegroups.com> <3cb8cff4-4c1d-4ca2-8d21-c012a109351b@w34g2000hsg.googlegroups.com> Message-ID: hdante at gmail.com wrote: > def xor(a, b): > return a and not b or b and not a >>> from operator import xor >>> help(xor) Help on built-in function xor in module operator: xor(...) xor(a, b) -- Same as a ^ b. From gagsl-py2 at yahoo.com.ar Sat Nov 10 02:02:08 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 10 Nov 2007 04:02:08 -0300 Subject: Returning actual argument expression to a function call? References: <1194674580.142801.244840@57g2000hsv.googlegroups.com> Message-ID: En Sat, 10 Nov 2007 03:03:00 -0300, Paddy escribi?: > Hi, > # If I have a function definition > def f1(arg): > global capturecall > if capturecall: > ... > do_normal_stuff(arg) > > # and its later use: > def f2(): > ... > return f1(a and (b or c)) > > # But also to do: > capturecall = True > result = f2() > # And get the same result, but also save the actual > # calling arguments to f1 either as a string: > # "a and (b or c))" > # Or a code object computing a and(b or c) Would be enough to have the source line text? def extract_caller_info(): import sys, traceback return traceback.extract_stack(sys._getframe(2), limit=1) def f1(arg): if capturecall: print extract_caller_info() # do_normal_stuff(arg) def f2(): a,b,c = 1,0,3 return f1(a and (b or c)) capturecall = True result = f2() output is like this: [('test1.py', 12, 'f2', 'return f1(a and (b or c))')] source file name, line number, function name, source line text. > P.S. You might also have multiple calls where I > would need to capture each individual argument > expression of f1 e.g: > def f3(): > ... > return f1(a and b) or e or f1(c and d) Tell your users that they'll have better results if those two calls are split on different lines: def f3(): return (f1(a and b) or e or f1(c and d)) Output: [('test1.py', 18, 'f3', 'return (f1(a and b)')] [('test1.py', 20, 'f3', 'or f1(c and d))')] -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Tue Nov 13 04:00:29 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 13 Nov 2007 06:00:29 -0300 Subject: Override method name and original method access References: <4866bea60711121156p42e5da5cy4574db5d9eae79ce@mail.gmail.com> Message-ID: En Tue, 13 Nov 2007 01:45:31 -0300, Donn Ingle escribi?: >> You need to be a new-style class (that is, you must inherit from >> object) for super() to work. > Problem is that my classes inherit already, from others I wrote. So, > should > I explicitly put (object) into the ones at the top? Changing from old-style to new-style classes may have some unintended side effects. You may prefer keeping your old-style classes and avoid using super, if you don't have multiple inheritance. Just call explicitely the base class. >> Other than that, you are using it >> correctly here. > Well, even with it seems to be calling to local > overridden > method. In a bit of a hurry, so can't test again right now. Remember that you must pass `self` explicitely. That is: class One: def __init__(self): self.stuff = [] def add (self, stuff): self.stuff.append(stuff) class Two(One): def __init__(self, otherstuff): One.__init__(self) One.add(self, otherstuff) self.unrelated = [] def add (self, data): self.unrelated.append(data) py> x = One() py> x.add(1) py> x.stuff [1] py> y = Two(2) py> y.add(3) py> y.stuff [2] py> y.unrelated [3] -- Gabriel Genellina From Anthon.van.der.Neut at googlemail.com Sun Nov 18 13:57:57 2007 From: Anthon.van.der.Neut at googlemail.com (Anthon) Date: Sun, 18 Nov 2007 10:57:57 -0800 (PST) Subject: keyword parameter order References: <47401d4c$0$9168$9b622d9e@news.freenet.de> Message-ID: <3a9a0c10-e494-4381-ac9f-9bd8489ace75@w73g2000hsf.googlegroups.com> Martin, Thanks for pointing this out. I might have found that code eventualy but it would have taken me quite sometime. There was a request from a user to make ordereddict more of drop-in replacement for dict. That can be already be done by specifying the relax keyword parameter (or defining a subclass that does so), but it made me revisit the idea of investigating the keyword parameter order.. I will just drop this idea Thanks Anthon On Nov 18, 12:08 pm, "Martin v. L?wis" wrote: > > I am not sure if this kind of info is available internally to the > > interpreter (ordereddict is in C, so I would even prefer that). Has > > anyone done this or anything like it? > > It's not available. See ceval.c:do_call; this fills the dictionary. > From then on, information about the order of keyword arguments is > lost. > > > I could probably compile the python interpreter to use ordereddict > > instead of dict and then the parser would insert the keyword > > parameters in specification order in the **kw ordereddict, after which > > iteration over parameters would be ordered. > > If you'ld do that literally, you'll find that the keyword arguments are > in reverse order. > > > As an aside: I think that allowing dict to be initialised from keyword > > parameters (introduced in Python 2.2 IIRC) was a mistake. This kind of > > use of keyword parameters prevents any real keyword parameters. E.g. > > with 'maxsize' that restricts the dictionary size or 'unique' that > > would throw an Exception if an existing key gets reassigned. > > For your own dictionary implementation, you are not required to follow > this interface - in particular if you believe it was a mistake. > > Regards, > Martin From jeff at jmcneil.net Mon Nov 5 08:50:05 2007 From: jeff at jmcneil.net (Jeff McNeil) Date: Mon, 5 Nov 2007 08:50:05 -0500 Subject: Downloading file from cgi application In-Reply-To: <1194269203.386164.157460@57g2000hsv.googlegroups.com> References: <1194264683.908009.237000@o80g2000hse.googlegroups.com> <1194269203.386164.157460@57g2000hsv.googlegroups.com> Message-ID: <7B81AF8F-0264-4D83-89BC-8B3B662BF6A9@jmcneil.net> You could also just store the files outside of the document root if you don't want to worry about a database. Then, as Jeff said, just print the proper Content-Type header and print the file out. On Nov 5, 2007, at 8:26 AM, Jeff wrote: > Store the file in a database. When an authorized user clicks the > link, send the proper headers ('Content-Type: application/pdf') and > then print the file. > > -- > http://mail.python.org/mailman/listinfo/python-list From kyosohma at gmail.com Thu Nov 29 09:09:56 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 29 Nov 2007 06:09:56 -0800 (PST) Subject: Lib for audio? References: Message-ID: <76d4597c-dd87-4c72-bcac-4e4fe04aa6b8@t47g2000hsc.googlegroups.com> On Nov 29, 6:04 am, Dave wrote: > I need to read microphone input and determine frequency. Is there a lib > for that? > > Thanks, > Dave You might take a look at the ossaudiodev module (note: it's #nix only): http://docs.python.org/lib/module-ossaudiodev.html http://docs.python.org/lib/mixer-device-objects.html If you're on Windows, looking at the source for the above module still might be enlightening. I also found the following which may or may not be helpful: http://py.vaults.ca/parnassus/apyllo.py/63131194 Mike From joejacob21 at gmail.com Tue Nov 20 07:19:44 2007 From: joejacob21 at gmail.com (joe jacob) Date: Tue, 20 Nov 2007 04:19:44 -0800 (PST) Subject: Python web frameworks Message-ID: There are a lot of web frameworks for python like django, mod_python, spyce, turbo gears, Zope, Cherrypy etc. Which one is the best in terms of performance and ease of study. From brian.p.hunter at gmail.com Mon Nov 26 14:30:14 2007 From: brian.p.hunter at gmail.com (bhunter) Date: Mon, 26 Nov 2007 11:30:14 -0800 (PST) Subject: spawning a process with subprocess References: <8b45ae31-a3e2-470f-93d0-ad31d8717176@s36g2000prg.googlegroups.com> <5r0iqtF11gmauU1@mid.uni-berlin.de> Message-ID: <078233a7-a296-4910-a544-786098e0cc46@d4g2000prg.googlegroups.com> On Nov 26, 1:50 pm, "Diez B. Roggisch" wrote: > bhunter schrieb: > > > > > Hi, > > > I've used subprocess with 2.4 several times to execute a process, wait > > for it to finish, and then look at its output. Now I want to spawn > > the process separately, later check to see if it's finished, and if it > > is look at its output. I may want to send a signal at some point to > > kill the process. This seems straightforward, but it doesn't seem to > > be working. > > > Here's my test case: > > > import subprocess, time > > > cmd = "cat somefile" > > thread = subprocess.Popen(args=cmd.split(), shell=True, > > stdout=subprocess.PIPE, stdin=subprocess.PIPE, > > stderr=subprocess.STDOUT, close_fds=True) > > > while(1): > > time.sleep(1) > > if(thread.returncode): > > break > > else: > > print thread.returncode > > > print "returncode = ", thread.returncode > > for line in thread.stdout: > > print "stdout:\t",line > > > This will just print the returncode of None forever until I Ctrl-C it. > > > Of course, the program works fine if I call thread.communicate(), but > > since this waits for the process to finish, that's not what I want. > > > Any help would be appreciated. > > I have difficulties understanding what you are after here. To me it > looks as if everything works as expected. I mean you periodically check > on the liveness of the "thread" - which is what you describe above. All > you are missing IMHO is the actual work in this program. > > So > > while True: > if do_work(): > if thread.returncode: > break > else: > thread.kill() > > This assumes that your do_work()-method communicates the wish to end the > sub-process using it's returnvalue. > > Diez If the subprocess had finished, I expect that the returncode will not be None, and the loop would break. The process hasn't actually started. I know this because while this simple testcase just cats a file, the real case submits a simulation job. This job never starts until after I ctrl-c the program. Brian From windspy at gmail.com Sun Nov 18 23:46:20 2007 From: windspy at gmail.com (windspy) Date: Sun, 18 Nov 2007 20:46:20 -0800 (PST) Subject: Learning Python : >>> import math doesn't work ? References: <8dt1k3hpjmlna23m13iuqglg0cnj6pkm2c@4ax.com> Message-ID: On Nov 19, 10:48 am, pdlem... at earthlink.net wrote: > Have carefully installed Python 2.5.1 under XP in dir E:\python25 . > ran set path = %path% ; E:\python25 > Python interactive mode works fine for simple arithmetic . > Then tried >>> import math > >>> x = sqrt(100) > Get error Name error : name 'sqrt' is not defined > Same thing with sin(x) . > I'm unable to find "math" , "sqrt" , or "sin" anywhere in lib , Libs > or include directories . > The Tutorial does not clear this up . > Please help. Thanks Dave pdlem... at earthlink.net use it like: x = math.sqrt (100) and math.sin(x) From steve at REMOVE-THIS-cybersource.com.au Sat Nov 24 19:42:46 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Sun, 25 Nov 2007 00:42:46 -0000 Subject: How can I create customized classes that have similar properties as 'str'? References: <67954d23-9400-4ac9-ba45-bec04fab51a2@s6g2000prc.googlegroups.com> <8eebf8fb-74cc-452a-bbef-2fe93556491f@i29g2000prf.googlegroups.com> <5qqeroF11703eU2@mid.individual.net> <1f2e037f-3667-4070-97cd-f4f6486c9d79@i12g2000prf.googlegroups.com> <13kh7mmeksulu51@corp.supernews.com> Message-ID: <13khh86h0g4nm86@corp.supernews.com> On Sat, 24 Nov 2007 14:58:50 -0800, George Sakkis wrote: > On Nov 24, 4:59 pm, Steven D'Aprano > > wrote: >> On Sat, 24 Nov 2007 03:44:59 -0800, Licheng Fang wrote: >> > On Nov 24, 7:05 pm, Bjoern Schliessmann > > mail-0306.20.chr0n... at spamgourmet.com> wrote: >> >> Licheng Fang wrote: >> >> > I find myself frequently in need of classes like this for two >> >> > reasons. First, it's efficient in memory. >> >> >> Are you using millions of objects, or MB size objects? Otherwise, >> >> this is no argument. >> >> > Yes, millions. >> >> Oh noes!!! Not millions of words!!!! That's like, oh, a few tens of >> megabytes!!!!1! How will a PC with one or two gigabytes of RAM >> cope????? >> >> > Comments like these make one wonder if your real life experience with > massive data matches even the one tenth of your self-importance and need > to be snarky in most of your posts. I cheerfully admit to never needing to deal with "massive data". However, I have often needed to deal with tens and hundreds of megabytes of data, which IS NOT MASSIVE amounts of data to deal with on modern systems. Which was my point. > To the OP: yes, your use case is quite valid; the keyword you are > looking for is "memoize". You can find around a dozen of recipes in the > Cookbook and posted in this list; here's one starting point: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/413717. This has nothing, absolutely NOTHING, to do with memoization. Memoization trades off memory for time, allowing slow functions to return results faster at the cost of using more memory. The OP wants to save memory, not use more of it. -- Steven. From johnjsal at NOSPAMgmail.com Sun Nov 18 13:17:54 2007 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sun, 18 Nov 2007 13:17:54 -0500 Subject: Book: Python Power!: The Comprehensive Guide In-Reply-To: <473ff64f@news.unimelb.edu.au> References: <473fda2a$0$3113$c3e8da3@news.astraweb.com> <473ff64f@news.unimelb.edu.au> Message-ID: <474081da$0$1675$c3e8da3@news.astraweb.com> Maurice LING wrote: > John Salerno wrote: >> Anyone know anything about this book? I've read a few intro Python books >> already, but I'm always interested in reading more to reinforce the >> language. No reviews on Amazon yet so I'm not sure if it's good or not. >> >> Thanks. > > > A cursory glance while standing in the bookshop suggest that I should > give it a closer read - there are some interesting stuffs that caught my > eyes but I only have time for a quick flip then. > > maurice Thanks. My nearest Barnes & Noble doesn't usually have stuff like this, but I'll see if they do and maybe I can get a better look myself. From pofuk at email.t-com.hr Wed Nov 28 14:06:27 2007 From: pofuk at email.t-com.hr (SMALLp) Date: Wed, 28 Nov 2007 20:06:27 +0100 Subject: wxPython problem Message-ID: Hy. I'm new in linux (Ubuntu 7.10) as well as in python. I installed IDLE, and i installed package python-wxgtkX. I start IDLE and when i want co compile my aplication all windows close. Also when i vrite smoethin lik thile in IDLE: import wx app = wx.App() wx.Frmae(none, -1) same thing, Please help! Thanks! From msc at es.aau.dk Fri Nov 2 10:11:06 2007 From: msc at es.aau.dk (Martin Sand Christensen) Date: Fri, 02 Nov 2007 15:11:06 +0100 Subject: Copy database with python.. References: <1194011518.553434.278940@o3g2000hsb.googlegroups.com> Message-ID: >>>>> "Abandoned" == Abandoned writes: Abandoned> I want to copy my database but python give me error when i Abandoned> use this command. cursor.execute("pg_dump mydata > old.dump") Abandoned> What is the problem ? cursor.execute() is for executing SQL commands, and this is not an SQL command, but rather a shell command. Abandoned> And how can i copy the database with python ? Note: The Abandoned> database's size is 200 GB If you want to do this from Python, run it as a separate process. Martin From gagsl-py2 at yahoo.com.ar Fri Nov 2 21:52:16 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 02 Nov 2007 22:52:16 -0300 Subject: python tutorial on a single html page? References: <1194043403.572130.203200@o38g2000hse.googlegroups.com> Message-ID: En Fri, 02 Nov 2007 19:43:23 -0300, BartlebyScrivener escribi?: > Is the main Python tutorial posted on single searchable page > somewhere? As opposed to browsing the index and clicking NEXT etc. The next release will use a different doc format (and different layout too), with far less pages. You can see it at Also, you can download the current documentation in many different formats, including PDF, at -- Gabriel Genellina From gherron at islandtraining.com Sun Nov 18 02:58:36 2007 From: gherron at islandtraining.com (Gary Herron) Date: Sat, 17 Nov 2007 23:58:36 -0800 Subject: Variable-width lookbehind In-Reply-To: References: <7xve8031ya.fsf@ruckus.brouhaha.com> Message-ID: <473FF0AC.6040806@islandtraining.com> OKB (not okblacke) wrote: > Paul Rubin wrote: > > >> "OKB (not okblacke)" writes: >> >>> For years now Python has not supported variable-length >>> lookbehinds. >>> >> I'm not sure what that is and the perl links you gave don't work, >> but it sounds evil. >> > > The links work fine for me. . . > > You're not sure what "variable-length lookbehinds" means? > Lookbehind is something that Python regexps already have. You can do > "(?<=one)two" to match "two" only if it's preceded by "one", and you can > do "(? What you can't do is "(?<=one|three)two", because Python requires that > the lookbehind contain only strings of a fixed length. What I'm asking > about is the possibility of lifting this limitation, to allow the > lookbehinds (positive and negative) to contain general regexps. I don't > see how this is in any way evil. > If not *evil*, then how about *unreadable*. Regular expressions are powerful, but nearly unreadable as they are. Allowing them to be even more complex just gets one step closer to *absolutely unreadable*. But that's not necessarily a reason to keep it out of the language. (Well actually, keeping Python's clarity-of-code goal in mind, it might be reason enough for some to want to keep it out.) But this is an all volunteer community. Your feature is not in the language because no one has cared enough to implement it. Or if some one has implemented it, no one has found it useful enough to lobby it into the language. Are you willing to implement it and lobby for it's inclusion? If so, good, we'll look at it. If not, then perhaps you understand perfectly why it's not yet included. Welcome to the world of Open Source! Gary Herron From hniksic at xemacs.org Mon Nov 12 08:22:00 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Mon, 12 Nov 2007 14:22:00 +0100 Subject: Populating a dictionary, fast References: Message-ID: <873avb1tvr.fsf@mulj.homelinux.net> Michael Bacarella writes: > $ uname -a > Linux xxx 2.6.9-22.ELsmp #1 SMP Sat Oct 8 21:32:36 BST 2005 x86_64 x86_64 x86_64 GNU/Linux > > We've also tried it on this version (on a different machine): > > $ uname -a > Linux yyy 2.6.18-8.el5 #1 SMP Thu Mar 15 19:46:53 EDT 2007 x86_64 x86_64 x86_64 GNU/Linux Note that both machines are x86_64. Please try your test on a 32-bit machine and report the results. I suspect performance won't degrade there. Most of the people who tried your test couldn't repeat your result (including me), but some did. It is quite possible that those who did were running on variants of x86_64, just like you. My guess is you've hit a bug that degrades performance of hashing of longs, or of large dicts, only affecting 64-bit architectures. As a workaround, you can try skipping the long() construction and simply hashing strings. (There should be no loss of information, and string objects are probably just as compact as Python longs in that range.) From horpner at yahoo.com Sun Nov 4 21:09:08 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Mon, 05 Nov 2007 02:09:08 GMT Subject: Is pyparsing really a recursive descent parser? References: <5p0dhgFnj4rbU1@mid.uni-berlin.de> <1194007658.200713.178210@57g2000hsv.googlegroups.com> <1194104971.263256.66640@d55g2000hsg.googlegroups.com> <43rXi.397547$6L.130044@fe03.news.easynews.com> <5CtXi.24942$m72.12315@fe06.news.easynews.com> Message-ID: <8XuXi.39854$G23.28548@newsreading01.news.tds.net> On 2007-11-05, Just Another Victim of the Ambient Morality wrote: > > "Neil Cerutti" wrote in message > news:qzsXi.39852$G23.9814 at newsreading01.news.tds.net... >> On 2007-11-04, Just Another Victim of the Ambient Morality >> wrote: >>> "Neil Cerutti" wrote in message >>> news:nPnXi.39845$G23.30920 at newsreading01.news.tds.net... >>>> I believe there's no cure for the confusion you're having except >>>> for implementing a parser for your proposed grammar. >>>> Alternatively, try implementing your grammar in one of your other >>>> favorite parser generators. >>> >>> I believe there is a cure and it's called recursive descent >>> parsing. It's slow, obviously, but it's correct and, sometimes >>> (arguably, often), that's more important the execution speed. >>> >>> I spent this morning whipping up a proof of concept parser >>> whose interface greatly resembles pyparsing but, baring unknown >>> bugs, works and works as I'd expect a recursive descent parser >>> to work. I don't know Python very well so the parser is pretty >>> simple. It only lexes single characters as tokens. It only >>> supports And, Or, Optional, OneOrMore and ZeroOrMore rules but >>> I already think this is a rich set of rules. I'm sure others >>> can be added. Finally, I'm not sure it's safely copying all >>> its parameter input the same way pyparsing does but surely >>> those bugs can be worked out. It's merely a proof of concept >>> to demonstrate a point. >>> Everyone, please look it over and tell me what you think. >>> Unfortunately, my news client is kind of poor, so I can't >>> simply cut and paste the code into here. All the tabs get >>> turned into single spacing, so I will post this link, instead: >>> >>> http://theorem.ca/~dlkong/new_pyparsing.zip >> >> Your program doesn't necessarily address the ambiguity in the >> grammar in question, since right now it is only a recognizer. >> Will it be hard to get it to return a parse tree? > > Hey, it's only a proof of concept. If you can parse the tree, surely > you can record what you parsed, right? > Did you notice that the parse() functions have the rather serious bug of > not returning how much of the string they could parse? Unfortunately I haven't had much time to play with it today; just barely enough to put it through a very few paces. > It just so happens that the contstructions that I made only > ever had to increment the matches by one, so they just happen > to work. That's an easy bug to fix but a pretty major one to > have overlooked. Hence, my enthusiasm for input... > >> The grammar in your implementation is: >> >>>>> goal = OneOrMore(RuleAnd('a') | RuleAnd('b')) + RuleAnd('b') >>>>> goal.parse(0, 'ab') >> True >>>>> goal.parse(0, 'ba') >> False >>>>> goal.parse(0, 'b') >> False >>>>> goal.parse(0, 'aaab') >> True >>>>> goal.parse(0, 'abc') >> True >> >> So far so good. :) > > Good! Keep hammering at it! > More importantly, study it to understand the idea I'm > trying to convey. This is what I thought a recursive descent > parser would do... Kay has pointed out how it works. Strangely enough, I've never studied a backtracking RDP before (trying to teach yourself a subject like parsing can be tricky--I've had to somehow avoid all the texts that overuse Greek letters--those incomprehensible symbols confuse the hell out of me). It does simplify the job of the grammar designer, but Kay's message makes it sound like it won't scale very well. It might, perhaps, be an interesting feature for PyParsing to entertain by setting a 'backtracking' option, for when you're writing a quick script and don't want to fuss too much with a non-conformant grammar. I'll have more time to look at it tomorrow. -- Neil Cerutti From steven at REMOVE.THIS.cybersource.com.au Mon Nov 19 04:20:42 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 19 Nov 2007 09:20:42 -0000 Subject: Simple eval References: <5qc77gFujovgU1@mid.individual.net> Message-ID: On Sun, 18 Nov 2007 21:46:49 -0800, MonkeeSage wrote: > As I see it, just as a matter of common sense, there will be no way to > match the performance of the backend eval() with any interpreted code. > At best, performance-wise, a preprocessor for the built-in eval() would > be in order, filtering out the "unsafe" cases and passing the rest > through. But what do I know, I could be dead wrong. :) In general, there are two approaches to security. The first is "Anything not explicitly permitted is forbidden". The second is "Anything not explicitly forbidden is permitted". The first is used when you actually want security. The second is when you are only pretending to care about security. Valuing convenience and ease of use over security is a reasonable thing to do, but only so long as you know that you are putting security second and are prepared to face the consequences. I for one don't surround myself with a team of crack British ex-SAS officers as body guards, but that's because I'm prepared to run the risk of Russian ex-KGB special forces attacking. On the other hand... I do lock my house. Rather than providing a list of people not allowed into the house, only those with a key are permitted. -- Steven. From listservs at mac.com Thu Nov 8 16:13:02 2007 From: listservs at mac.com (Chris) Date: Thu, 8 Nov 2007 21:13:02 +0000 (UTC) Subject: Python on Leopard issues Message-ID: Are others having fundamental issues on OSX 10.5 with python 2.5.1? I was excited that Python 2.5 was included, but this excitement was very short lived. Almost nothing works. Upon startup I get this message: 'import site' failed; use -v for traceback and sure enough, all of the built-in packages are non-existent. I'm not sure why Apple bothered including an improperly-configured version. Does anyone have an easy fix for this, or should I go to ActiveState and install a version that works? Thanks. From bj_666 at gmx.net Sat Nov 24 01:29:39 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 24 Nov 2007 06:29:39 GMT Subject: the annoying, verbose self References: <3c954a31-9fb9-4c0f-b784-cef9ee057ca6@g30g2000hsb.googlegroups.com> <6f67fccf-fbec-4c75-baea-5d0277e07883@w40g2000hsb.googlegroups.com> <47458D4E.5030302@sympatico.ca> <13keq168fnu9328@corp.supernews.com> Message-ID: <5qpumjF10jrh5U1@mid.uni-berlin.de> On Fri, 23 Nov 2007 20:48:06 -0800, Kay Schluehr wrote: > I like this pattern but less much I like the boilerplate. What about > an explicit unpacking protocol and appropriate syntax? > > def abs(self): > x, y, z by self > return math.sqrt(x**2 + y**2 + z**2) > > expands to > > def abs(self): > x, y, z = self.__unpack__("x","y","z") > return math.sqrt(x**2 + y**2 + z**2) What about ``from`` instead of ``by``? That's already a keyword so we don't have to add a new one. Ciao, Marc 'BlackJack' Rintsch From shriphanip at gmail.com Tue Nov 6 05:19:07 2007 From: shriphanip at gmail.com (Shriphani) Date: Tue, 06 Nov 2007 10:19:07 -0000 Subject: Trouble with for loop In-Reply-To: <1194343786.700768.191040@d55g2000hsg.googlegroups.com> References: <1194343197.272342.16130@t8g2000prg.googlegroups.com> <1194343786.700768.191040@d55g2000hsg.googlegroups.com> Message-ID: <1194344347.943085.306080@q5g2000prf.googlegroups.com> On Nov 6, 3:09 pm, Ant wrote: > On Nov 6, 9:59 am, Shriphani wrote: > ... > > > My main intention is to state that each of the variables namely a, b, > > c, ## can take value from 1 to 9. > > How do I go about this ? > > It sounds like you are after something like: > > for var in (a, b, c, d, e, f): > assert var in [1, 2, 3, 4, 5, 6, 7, 8, 9] > > but it's hard to tell without some more information from you on > exactly what you are trying to achieve. I want to obtain a number whose first digit "a" is divisible by 1, 10*b +a is divisible by 2, 10^2*c + 10b + a is divisible by 3 and so on. I hope my question is a bit clearer now. Thanks, Shriphani Palakodety From Anthon.van.der.Neut at googlemail.com Sun Nov 18 05:30:28 2007 From: Anthon.van.der.Neut at googlemail.com (Anthon) Date: Sun, 18 Nov 2007 02:30:28 -0800 (PST) Subject: keyword parameter order Message-ID: I am looking for a way to determine the order of keyword parameters passed on to a class method. In the source code the keyword parameters are ordered, an ordering that is lost by putting them into a dictionary and then accessing them by using **kw. If I had this order (either of the keyword+value pairs or just of the keywords) I could meaningfully initialise my ordereddict implemenation (which uses Key Insertion Order or KeyValue Insertion Order). I looked at traceback (which shows this info if all the keywords are on one source line), and tracing that I found that it displays the sourcecode line based on the code-object found in the frame stack. I could persue that but I find the idea of reparsing the sourcecode kind of ugly (although doable, as the keyword are never variables, and I would not have to reevaluate the variables). I am not sure if this kind of info is available internally to the interpreter (ordereddict is in C, so I would even prefer that). Has anyone done this or anything like it? I could probably compile the python interpreter to use ordereddict instead of dict and then the parser would insert the keyword parameters in specification order in the **kw ordereddict, after which iteration over parameters would be ordered. I am pretty sure though if the 10% speed overhead of the ordereddict implementation compared to dict is going to prevent people from using such an interpreter version. As an aside: I think that allowing dict to be initialised from keyword parameters (introduced in Python 2.2 IIRC) was a mistake. This kind of use of keyword parameters prevents any real keyword parameters. E.g. with 'maxsize' that restricts the dictionary size or 'unique' that would throw an Exception if an existing key gets reassigned. Anthon From hniksic at xemacs.org Wed Nov 7 10:33:31 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Wed, 07 Nov 2007 16:33:31 +0100 Subject: What colour model does the image use in PIL References: <1194442641.095444.17690@z9g2000hsf.googlegroups.com> <87zlxqb1rv.fsf@mulj.homelinux.net> <1194448781.660254.36120@22g2000hsm.googlegroups.com> Message-ID: <87mytqax4k.fsf@mulj.homelinux.net> Johny writes: > I would need to apply a threshold value to the image, where > everything above a certain brightness level becomes white, and > everything below the level becomes black. How can I do that with > PIL? I think you're supposed to use the "point" method, but I don't have an example ready. See http://mail.python.org/pipermail/image-sig/2004-November/003019.html for a hint. From robert.kern at gmail.com Thu Nov 22 22:50:30 2007 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 22 Nov 2007 21:50:30 -0600 Subject: scipy-0.6.0.win32-py2.5.exe does not install In-Reply-To: References: Message-ID: Frank Moyles wrote: > Hi, I want to use SciPy library. I am using W2k, and ActiveState Python > 2.5. I have succesfully numpy, but when I run the > scipy-0.6.0.win32-py2.5.exe (from the downloads section on the SciPy > page), nothing happens - i.e. no information is printed on the console, > and the setup application simply quits with no warning/error message. > > has anyone managed to succesfully install SciPy using > scipy-0.6.0.win32-py2.5.exe & ActiveState Python on W2k? > > Am I missing a step? You might get better luck asking on the scipy-user mailing list: http://www.scipy.org/Mailing_Lists -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From enleverlesX.XmcX at XmclaveauX.com Fri Nov 23 07:04:30 2007 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Fri, 23 Nov 2007 13:04:30 +0100 Subject: Writing event handler for dropdown list in python In-Reply-To: <19625a43-e809-467b-b974-e4fa17027b1c@s12g2000prg.googlegroups.com> References: <19625a43-e809-467b-b974-e4fa17027b1c@s12g2000prg.googlegroups.com> Message-ID: <4746c33a$0$27377$ba4acef3@news.orange.fr> Hi! Please, specify which way you chose, for Python (client-side): wxpython, active-scripting, qt, pluie, other... @-salutations Michel Claveau From andrei.avk at gmail.com Mon Nov 12 15:33:13 2007 From: andrei.avk at gmail.com (andrei.avk at gmail.com) Date: Mon, 12 Nov 2007 20:33:13 -0000 Subject: Information manager/organizer with tags question. In-Reply-To: <1194895492.850381.200220@19g2000hsx.googlegroups.com> References: <1194821054.161459.86240@o3g2000hsb.googlegroups.com> <1194895492.850381.200220@19g2000hsx.googlegroups.com> Message-ID: <1194899593.140934.294430@50g2000hsm.googlegroups.com> On Nov 12, 2:24 pm, Aaron Watters wrote: > On Nov 11, 5:44 pm, andrei.... at gmail.com wrote: > > > Hello, > > > I would like to write an information manager/organizer type of app but > > first I'd like to ask if there is something like that already... > > Your outline sounds like a killer app, and I don't know of anything > like > it (especially for free). However, I have to plug nucular as a > possible > back end data store that may make it easier for you to implement the > app you outlined. Please have a look: > > http://nucular.sourceforge.net > > See the "demos" for examples of what you can do with it very easily. > -- Aaron Watters > > ===http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=unsuspecting+v... Sounds interesting and thanks for reply but I need something that will work in windows also.. -andrei From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Tue Nov 27 14:33:23 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Tue, 27 Nov 2007 20:33:23 +0100 Subject: read/write to java socket in python References: Message-ID: <5r39o3F12lghnU1@mid.individual.net> madsornomads at gmail.com wrote: > I have a problem with reading from a Java server after I have > written to it - it just hangs. It works fine if I just write to > the server and not try to write. Excuse me? > I have read the HOWTO on sockets - and it states that there is a > problem (something about flushing), but not what the solutions is. > Nor do google. Can somebody please help? Spare yourself the trouble and do not use low level socket functions in Python directly. Try Twisted. http://twistedmatrix.com/projects/core/documentation/howto/clients.html As for that Java problem I recommend learning common debugging techniques: Use a protocol analyser (www.wireshark.org) and let your program(s) output a debug log. Regards, Bj?rn -- BOFH excuse #16: somebody was calculating pi on the server From buyonline.eworld at gmail.com Sat Nov 10 23:54:29 2007 From: buyonline.eworld at gmail.com (Cope) Date: Sat, 10 Nov 2007 20:54:29 -0800 Subject: Join DOWNLOAD CENTRE Message-ID: <1194756869.934320.196820@v23g2000prn.googlegroups.com> Post your softwares and other digital products here. Note that your post must be downloadable. Cope, Owner. http://groups.google.co.in/group/download-centre From goon12 at gmail.com Wed Nov 21 08:23:29 2007 From: goon12 at gmail.com (Joe Riopel) Date: Wed, 21 Nov 2007 08:23:29 -0500 Subject: Python web frameworks In-Reply-To: References: <226020ef-3955-43e8-b1f6-2ba9ba43d45e@c29g2000hsa.googlegroups.com> <5qga2mFvuljgU1@mid.uni-berlin.de> <160f8bbc-70be-4dcb-8874-de72588c1d10@d61g2000hsa.googlegroups.com> <1b343163-e755-44f8-b5c3-4af56c61e817@c29g2000hsa.googlegroups.com> <93a92a82-cf3c-4ebb-a93f-180374e5f75a@e4g2000hsg.googlegroups.com> Message-ID: <6a2ccd190711210523v6d2a098bob7b79db8dbd8c418@mail.gmail.com> On Nov 21, 2007 5:42 AM, joe jacob wrote: > Thanks everyone for the response. From the posts I understand that > Django and pylons are the best. By searching the net earlier I got the > same information that Django is best among the frameworks so I > downloaded it and I found it very difficult to configure. I referred > the djangobook. Is pylons better in terms of performance and ease of > study compared to Django. I have only used Pylons for the simplest of applications (Not because I don't think it can handle complex applications, but because I am trying to learn the framework) and find it very easy to configure. That said, I think it's definitely worth your time to to either give Pylons a try, or give Django more time. This thread has been going for only a few days now, and I wouldn't expect you'd have very intimate knowledge with any framework. From bdesth.quelquechose at free.quelquepart.fr Mon Nov 5 15:20:08 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 05 Nov 2007 21:20:08 +0100 Subject: Functions as Objects, and persisting values In-Reply-To: <1194291811.879837.161110@z24g2000prh.googlegroups.com> References: <1194291811.879837.161110@z24g2000prh.googlegroups.com> Message-ID: <472f7b34$0$3522$426a34cc@news.free.fr> Falcolas a ?crit : > Please help me understand the mechanics of the following behavior. > > >>>>def d(): > > header = 'I am in front of ' > def e(something): > print header + something > return e > > >>>>f = d() >>>>f('this') > > I am in front of this > >>>>del(d) >>>>f('this') > > I am in front of this > > The way I understand it, function d is an object, Right. > as is e. Right. > However I > don't quite grok the exact relationship between e and d. > > Is e > considered to be a subclass of 'd', Nope. > so that it has access to it's > parent's __dict__ object, in order to access the value of 'header'? Or > is this persistence managed in a different fashion? As Diez said, it's called a lexical closure. A lexical closure is a function that captures and carries the lexical scope it was defined in with it - it 'closes over' it's environnement. Each time you call d, it returns a new function object (using the same code object) with a different environnement. You'll find this environement in f.func_closure. From garrickp at gmail.com Mon Nov 5 14:43:31 2007 From: garrickp at gmail.com (Falcolas) Date: Mon, 05 Nov 2007 11:43:31 -0800 Subject: Functions as Objects, and persisting values Message-ID: <1194291811.879837.161110@z24g2000prh.googlegroups.com> Please help me understand the mechanics of the following behavior. >>> def d(): header = 'I am in front of ' def e(something): print header + something return e >>> f = d() >>> f('this') I am in front of this >>> del(d) >>> f('this') I am in front of this The way I understand it, function d is an object, as is e. However I don't quite grok the exact relationship between e and d. Is e considered to be a subclass of 'd', so that it has access to it's parent's __dict__ object, in order to access the value of 'header'? Or is this persistence managed in a different fashion? From cjw at sympatico.ca Wed Nov 7 07:42:10 2007 From: cjw at sympatico.ca (Colin J. Williams) Date: Wed, 07 Nov 2007 07:42:10 -0500 Subject: Looking for a good Python environment In-Reply-To: <1194434140.836932.10670@k79g2000hse.googlegroups.com> References: <1194389774.159051.55580@19g2000hsx.googlegroups.com> <1194434140.836932.10670@k79g2000hse.googlegroups.com> Message-ID: jwelby wrote: > On Nov 6, 10:56 pm, "ram.rac... at gmail.com" > wrote: >> Hey, I'm looking for a good Python environment. That is, at least an >> editor and a debugger, and it should run on Windows. Does anyone have >> any idea? > > I currently use Python Scripter as a lightweight editor for Windows. Could you elaborate on "lightweight" please? I find PyScripter to be a powerful editor/debugger combination. What functionality does Eclipse have that PyScripter does not? Colin W. > > For project work I use Eclipse, which can be installed with PyDev and > other useful plug-ins already included if you choose a suitable > distribution of Easy Eclipse (http://www.easyeclipse.org/). There is a > distribution specifically for Python development, and also one for > LAMP, which includes a number of other components which will be of use > if you are developing for the web. > From arkanes at gmail.com Fri Nov 16 10:59:16 2007 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 16 Nov 2007 09:59:16 -0600 Subject: gc penalty of 30-40% when manipulating large data structures? In-Reply-To: References: Message-ID: <4866bea60711160759le50a744k88858958c032320b@mail.gmail.com> On Nov 16, 2007 8:34 AM, Aaron Watters wrote: > Poking around I discovered somewhere someone saying that > Python gc adds a 4-7% speed penalty. > > So since I was pretty sure I was not creating > reference cycles in nucular I tried running the tests with garbage > collection disabled. > > To my delight I found that index builds run 30-40% faster without > gc. This is really nice because testing gc.collect() afterward > shows that gc was not actually doing anything. > > I haven't analyzed memory consumption but I suspect that should > be significantly improved also, since the index builds construct > some fairly large data structures with lots of references for a > garbage collector to keep track of. > > Somewhere someone should mention the possibility that disabling > gc can greatly improve performance with no down side if you > don't create reference cycles. I couldn't find anything like this > on the Python site or elsewhere. As Paul (I think) said, this should > be a FAQ. > > Further, maybe Python should include some sort of "backoff" > heuristic which might go like this: If gc didn't find anything and > memory size is stable, wait longer for the next gc cycle. It's > silly to have gc kicking in thousands of times in a multi-hour > run, finding nothing every time. > The GC has a heuristic where it kicks in when (allocations - deallocations) exceeds a certain threshold, which has (sometimes quite severe) implications for building large indexes. This doesn't seem to be very well known (it's come up at least 3-4 times on this list in the last 6 months) and the heuristic is probably not a very good one. If you have some ideas for improvements, you can read about the current GC in the gc module docs (as well as in the source) and can post them on python-ideas. From Scott.Daniels at Acm.Org Sat Nov 10 10:54:37 2007 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 10 Nov 2007 07:54:37 -0800 Subject: Image treshold In-Reply-To: <1194686591.983580.98040@v2g2000hsf.googlegroups.com> References: <1194686591.983580.98040@v2g2000hsf.googlegroups.com> Message-ID: <13jbkshqualqm8f@corp.supernews.com> Johny wrote: > Can anyone give me an example how to apply a threshold value to an > image? > (everything above a certain brightness level becomes white, and > everything below the level becomes black.) > I was told I should use 256-item mapping table and pass it to the > "point" method. > But how should the 256-item mapping table look like, if the threshold > is 18( found from the histogram) Sounds like homework. You have the tools, and are close to the answer. Experiment and look at the results. -Scott From bj_666 at gmx.net Sat Nov 10 12:10:57 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 10 Nov 2007 17:10:57 GMT Subject: String/Decimal issues References: Message-ID: <5pm711Fri447U2@mid.uni-berlin.de> On Sat, 10 Nov 2007 09:02:01 -0800, Mike Howarth wrote: > Basically I'm reducing an array of prices like so: >>> subtotal = reduce(operator.add, itemprices) Take a look at the built in `sum()` function. > This gives me a string of '86.00.00' which I am trying to use with decimal > objects. So what the heck is in `itemprices`!? > Being relatively new to python, I'm not sure how I could round the string or > similar. Anyone got any ideas? You can't round strings. Maybe that's the problem here: data types. Are you sure you have numbers that you are adding and not strings or something!? Ciao, Marc 'BlackJack' Rintsch From peter.j.bismuti at boeing.com Mon Nov 12 20:10:35 2007 From: peter.j.bismuti at boeing.com (Peter J. Bismuti) Date: Mon, 12 Nov 2007 17:10:35 -0800 Subject: Distributed RVS, Darcs, tech love In-Reply-To: References: <1192850894.310464.89070@e9g2000prf.googlegroups.com> <1192998506.251127.172530@v29g2000prd.googlegroups.com> Message-ID: <200711121710.35430.peter.j.bismuti@boeing.com> Be nice. > Boy, you really have to get a clue. From fenglinyushu at 163.com Mon Nov 12 08:03:36 2007 From: fenglinyushu at 163.com (Billows) Date: Mon, 12 Nov 2007 05:03:36 -0800 Subject: Coding Help In-Reply-To: <1194727068.352431.120250@50g2000hsm.googlegroups.com> References: <1194716747.634041.204620@k79g2000hse.googlegroups.com> <5pmbulFri447U4@mid.uni-berlin.de> <1194724489.417628.313430@19g2000hsx.googlegroups.com> <1194727068.352431.120250@50g2000hsm.googlegroups.com> Message-ID: <1194872616.559630.179220@v23g2000prn.googlegroups.com> Maybe AutoFlowchart can help you! AutoFlowchart is a excellent source code flowcharting tool to generate flowchart from source code. Its flowchart can expand and shrink. and you can pre-define the the width , height,Horizontal spacing and vertical spacing. Move and zoom is also very easy. It can export the flowchart as a Microsoft Word file or a bitmap file. It can help programmers understand, document and visualize source code. As a new product to replace AgFlowchart, it revised the bugs of AgFlowchart and add many features. It supports C,C++,VC++(Visual C++ .NET),Delphi(Object Pascal). Maybe it can help you! http://www.ezprog.com From ullrich at math.okstate.edu Fri Nov 2 08:19:19 2007 From: ullrich at math.okstate.edu (David C. Ullrich) Date: Fri, 02 Nov 2007 06:19:19 -0600 Subject: (MAC) CoreGraphics module??? References: <22uki39arp3a83topaimrka4s37uo1okm5@4ax.com> Message-ID: On Thu, 01 Nov 2007 19:39:20 -0500, Robert Kern wrote: >David C. Ullrich wrote: >> [why doesn't CoreGraphics work?] > >That's different than the one that is referenced. The one those articles >reference is only available in the Python that came with the system in >/System/Library/Frameworks/Python.framework, not one that you might have >installed from www.python.org into /Library/Frameworks/Python.framework. The >module was made by Apple, and they have not released the source code, so it >cannot be made to work with the www.python.org distribution. usenet is amazing - your reply appears to have been posted a half hour before my question! Thanks. So CoreGraphics is a builtin in Apple-Python, explaining why I didn't find the relevant CoreGraphics.py anywhere on the hard drive, eh? Fine. Now what? Please feel free to bear in mind that I have very little experience with the Mac and with Unix - I'm certain that if I knew what I was doing there I wouldn't need to ask the questions below, sorry. And sorry about the length of this post - there's a second issue that maybe you could explain, that I'd really love to have an explanation for before modifying things. Anyway: Since I didn't do anything special to remove it when I installed the Python-Python, the Apple-Python should still be there, yes? I'd appreciate any advice on how to get things set up the way I'd like. Below when I refer to the MacPython stuff I mean ApplicationLauncher (or however it's spelled, the Mac's at the office and I'm at home) and Idle; the stuff that gives convenient access to Python scripts in the GUI. Note that I don't have any particular reason to want to use the latest version of Python - I was actually getting along fine with 1.5 until very recently. I'd be perfectly happy to set things up so everything used the Apple-Python. (i) If I just uninstalled the Python-Python (how?) would everything (Terminal, the MacPython stuff) automagically find the Apple-Python instead? (ii) If not, what would I have to do to make things use the Apple-Python instead? (And if I have to do something to make that happen, would doing that still work if I just left the Python-Python sitting there?) OR: Is there something special I could do with CoreGraphics scripts and/or how I invoke them so that _they_ would use the Apple-Python while other scripts would just use the Python-Python as now? (A last choice would be a setup where most scripts work as they do now and I somehow make CoreGraphics work from Terminal but not in Finder...) (Hmm, a wild guess: something somewhere is an alias to Python-Python, and I just change that (how?) to an alias to Apple-Python?) I'm a little nervous about making any changes, because something very mysterious happened when I was setting things up the way they are now - since I have no idea what I did to make things work the way they are now I don't know that I could set things up the way they are now again if I had to. If you can explain the following that will be something (I've been meaning to ask about the following sometime, hasn't been important til now when I'm contemplating changing the setup): The history: I get a Mac. I discover that it includes Python, can't figure out how to execute .py files in Finder. I hear about MacPython. I install the "small" MacPython download, that's supposed to just add ApplicationLauncher(?), Idle, etc on top of the existing Python. Works fine _except_ that when I double-click a .py file in Finder it executes with the cwd equal to the root directory instead of the directory where the script is located. Trying to fix that I install the "full" MacPython, including Python itself. Doesn't help, scripts still execute in "/". A few weeks later I decide to try to fix that. The plan is to edit whatever.py, the script that's supposed to run before everything else allowing customizations (always takes me a while to find the magic name in the docs - probably you know the name I mean). The plan is to extract the directory I want from sys.argv and then chdir. And here's the mysterious part: The day I plan on modifying whatever.py I find the problem has fixed itself! When I double- click .py files they execute in the right directory. If you asked what I was smoking I wouldn't blame you. (Not that I really think that's it, but the _only_ thing I can imagine I did that could have led to the change was that perhaps I hadn't yet tried out Idle when things were executing in the wrong directory, and somehow the first time I ran Idle it fixed something for me.) Anyway. You have any idea what was going on there, and/or any idea about what to do to fix that problem if it appears again? Something somewhere changed - what, and how do I change it manually? "defaults write what.what.what what what"? Or what? I'd be much happier understanding what happened here before making any changes... Evidently you've read this far - thanks. Long posts are irritating. Of course so are posts that don't describe the problem - oh well. ************************ David C. Ullrich From python.list at tim.thechases.com Wed Nov 28 15:20:28 2007 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 28 Nov 2007 14:20:28 -0600 Subject: Bit Operations In-Reply-To: References: Message-ID: <474DCD8C.3000106@tim.thechases.com> > I'm really confused on how t do it, maybe cause python is > type-less (dynamic typed) Being duck-typed doesn't really have anything to do with it. Python supports logical shifting and combining > i've a byte that naturally is composed from 2 nibbles hi&low, > and two chars.. like A nd B. What i wonna do is to write A to > the High nibble and B to the the lower nibble. Or an other > example can be i've 2 numbers.. like 7 and 8 and whant to do > the same as for chars. >>> a = int('1001', 2) >>> b = int('0110', 2) >>> a 9 >>> b 6 >>> 0xff & (((0xff & a) << 4) | (0xff & b)) 150 or, if you're sloppy, >>> (a << 4) | b 150 And for verification: >>> int('10010110', 2) 150 Thus, that can be wrapped up as a function >>> nibbles2byte = lambda a,b: \ 0xff & (((0xff & a) << 4) | (0xff & b)) >>> nibbles2byte(a,b) 150 -tkc From Scott.Daniels at Acm.Org Mon Nov 19 22:25:27 2007 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 19 Nov 2007 19:25:27 -0800 Subject: implement random selection in Python In-Reply-To: References: Message-ID: <13k4kn98ijjhne4@corp.supernews.com> J. Clifford Dyer wrote: > My understanding of what you are looking for is that on each individual selection, > the probability of picking a given name is that name's prob value, divided by the > sum of all prob values. That is, in the following case: > items = [('Mary', 96),('Shimon', 1), ('Aisha', 1), ('Toshiro', 2)] > ... On the first pass Mary has a 96% chance of getting selected, .... > If that is correct, then the following might meet your needs: > > from random import choice > > def select(weighted_list, n=1): > selected = set() > for iteration in xrange(n): > print iteration > selection_list = [] > for item in weighted_list: > if item[0] not in selected: > selection_list.extend([item[0]] * item[1]) > #print selection_list > this_choice = choice(selection_list) > #print this_choice > selected.add(this_choice) > return selected or even: def picks(weighted_list, N): result = [] adict = dict(weighted_list) total = sum(adict.values()) for i in range(N): score = random.random() * total for choice, weight in cp.iteritems(): if weight < score: score -= weight else: result.append(choice) total -= cp.pop(choice) break else: raise ValueError('ran out of data') return result -Scott From malte.forkel at berlin.de Mon Nov 19 12:17:39 2007 From: malte.forkel at berlin.de (Malte Forkel) Date: Mon, 19 Nov 2007 18:17:39 +0100 Subject: Python for embedded devices? Message-ID: I would like to use Python on a router, an Edimax BR-6104K, running OpenWrt (http://www.openwrt.org). While I probably won't need most of the fancier stuff in Python, serial I/O and threads should be supported. The router is based on the ADM5120P, has 2MB of flash and 16MB of RAM, so the version of Python 2.5.1 that is part of OpenWrt is probably a litte to big. Any suggestions? Thanks in advance, Malte From usenet-mail at markshroyer.com Fri Nov 9 22:12:25 2007 From: usenet-mail at markshroyer.com (Mark Shroyer) Date: Sat, 10 Nov 2007 03:12:25 GMT Subject: Portrait of a "real life" __metaclass__ Message-ID: I guess this sort of falls under the "shameless plug" category, but here it is: Recently I used a custom metaclass in a Python program I've been working on, and I ended up doing a sort of write-up on it, as an example of what a "real life" __metaclass__ might do for those who may never have seen such a thing themselves. http://markshroyer.com/blog/2007/11/09/tilting-at-metaclass-windmills/ So what's the verdict? Incorrect? Missed the point completely? Needs to get his head checked? I'd love to hear what comp.lang.python has to (anthropomorphically) say about it. -- Mark Shroyer http://markshroyer.com/ From michele.simionato at gmail.com Wed Nov 21 04:34:18 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Wed, 21 Nov 2007 01:34:18 -0800 (PST) Subject: logging module: removing handlers References: <2c910cda-c9e4-4076-8b86-dc91b40b67a9@f3g2000hsg.googlegroups.com> <5qibpeFvrbo1U1@mid.uni-berlin.de> Message-ID: <5b21f759-fa77-440c-979f-30fb697f5804@w28g2000hsf.googlegroups.com> On Nov 21, 10:23 am, "Diez B. Roggisch" wrote: > I can only guess - but I'd say if you can do > > foo.removeHandler(h) > > you can do > > foo.removeHandler(h) > h.close() > > easily. But not > > foo.removeHandler(h) # implicit closing > bar.addHandler(h) > > It does kind of make sense if you decouple the life-cycles IMHO. > > Diez But what is the use case for removing an handler without closing it? Michele Simionato From ggpolo at gmail.com Tue Nov 6 12:44:28 2007 From: ggpolo at gmail.com (Guilherme Polo) Date: Tue, 6 Nov 2007 15:44:28 -0200 Subject: Insane crazy question - printing commands In-Reply-To: <200711061942.08741.donn.ingle@gmail.com> References: <200711061942.08741.donn.ingle@gmail.com> Message-ID: 2007/11/6, Donn : > > import inspect > > > > class Box: > > def draw(self): > > print "hi" > > return 3 > > > > x = Box() > > print inspect.getsource(x.draw) > > Tried that, but get this error. I did a dir(inspect) in the command env. and > getsource it definitely there... > > Traceback (most recent call last): > File "inspect.py", line 1, in ? > import inspect > > File "/home/donn/Projects/pythoning/fontyPython/extending/cairotests/containers/inspect.py", > line 9, in ? > print inspect.getsource(x.draw) > AttributeError: 'module' object has no attribute 'getsource' > By now you should know that you shouldn't be naming your modules like that. Rename your inspect.py to something else -- -- Guilherme H. Polo Goncalves From krishnamanenianil at gmail.com Tue Nov 6 11:49:33 2007 From: krishnamanenianil at gmail.com (krishnamanenianil at gmail.com) Date: Tue, 06 Nov 2007 08:49:33 -0800 Subject: regular expressions Message-ID: <1194367773.329640.202340@i13g2000prf.googlegroups.com> hi i am looking for pattern in regular expreesion that replaces anything starting with and betweeen http:// until / like http://www.start.com/startservice/yellow/ fdhttp://helo/abcd will be replaced as p/startservice/yellow/ fdp/abcd From robert.kern at gmail.com Fri Nov 30 15:50:19 2007 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 30 Nov 2007 14:50:19 -0600 Subject: Sorting array In-Reply-To: References: <20071130154226.c17a34ec.tartifola@gmail.com> Message-ID: Chris Hulan wrote: > the list.sort method seems to do exactly what you want? > > Unless your array() method is creating a custom array object with > different sort functionality than list? Presumably he is using numpy arrays. -- 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 arnodel at googlemail.com Wed Nov 14 14:50:40 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 14 Nov 2007 11:50:40 -0800 Subject: Building python packages for the correct architecture on OSX 10.5 In-Reply-To: <473b4f1b$0$17353$9b622d9e@news.freenet.de> References: <1195061700.315152.61070@22g2000hsm.googlegroups.com> <473b4f1b$0$17353$9b622d9e@news.freenet.de> Message-ID: <1195069840.338560.74320@o3g2000hsb.googlegroups.com> On Nov 14, 7:40 pm, "Martin v. L?wis" wrote: > > This means the modules need to be compiles for at least both i386 and > > x86_64 in my case. > > Building Python in 64-bit mode as a universal (fat) binary is not > supported in Python 2.5, period. So any solution you come necessarily > has to be a work-around. > > The only solution I can see is to make a plain, non-fat installation > of Python in 64-bit mode, and then use that installation to build > 64-bit extension modules. > > > def Extension(*args, **kwargs): > > extra_args = ['-arch', 'ppc', '-arch', 'ppc64', > > '-arch', 'i386', '-arch', 'x86_64 '] > > This cannot really work, for two reasons: > a) even if your extension module becomes x86_64 with that mechanism, > the Python interpreter itself (i.e. the Python framework) will be > purely 32-bit code. So it should not link correctly. My machine disagrees: marigold:~ arno$ file /System/Library/Frameworks/Python.framework/ Python /System/Library/Frameworks/Python.framework/Python: Mach-O universal binary with 4 architectures /System/Library/Frameworks/Python.framework/Python (for architecture ppc7400): Mach-O dynamically linked shared library ppc /System/Library/Frameworks/Python.framework/Python (for architecture ppc64): Mach-O 64-bit dynamically linked shared library ppc64 /System/Library/Frameworks/Python.framework/Python (for architecture i386): Mach-O dynamically linked shared library i386 /System/Library/Frameworks/Python.framework/Python (for architecture x86_64): Mach-O 64-bit dynamically linked shared library x86_64 > b) During configure, Python generates a pyconfig.h which has the > computed sizes of data types (such as int, long, size_t). It only > has a single such file, and the file is generated only during > configure. Therefore, the data in it cannot work both for 32-bit > and 64-bit architectures. When you compile for a 64-bit target > using the 32-bit pyconfig.h, the code may work incorrectly > (provided it makes use of the computed values somewhere) (*) > > (*) It is surprising that pyconfig.h actually works for both > big-endian (ppc) and little-endian (i386) systems, even though > it computes the endianness during configure only once. This is > due to an OSX-specific hack in pyconfig.h, which hides the > definition of the computed endianness value, and uses the > value that the compiler provides as a macro instead. Thanks for the details. I have had no problems with the modules I have compiled so far, they have been working in 32 and 64 bits. Maybe I was just lucky? I'll have to look into this more, then. Python on OSX 10.5 has been a challenge so far :( > Regards, > Martin Thanks -- Arnaud From martin at marcher.name Wed Nov 7 14:44:24 2007 From: martin at marcher.name (Martin Marcher) Date: Wed, 7 Nov 2007 20:44:24 +0100 Subject: regular expression syntax the same in Python, Perl and grep? In-Reply-To: <4866bea60711071122l71ed18a4qfb6448f5861d283a@mail.gmail.com> References: <1194459115.764951.50440@y42g2000hsy.googlegroups.com> <4866bea60711071122l71ed18a4qfb6448f5861d283a@mail.gmail.com> Message-ID: <5fa6c12e0711071144n3442d836o5ddfabe1421a335c@mail.gmail.com> 2007/11/7, Chris Mellon : > On Nov 7, 2007 12:11 PM, seberino at spawar.navy.mil > wrote: > > How similar is Python's re module (regular expressions) compared > > to Perl's and grep's regular expression syntaxes? > > > > Somewhat. > > > I really hope regular expression syntax is sufficiently standardized > > that > > we don't have to learn new dialects everytime we move from one > > language or shell command to another. I forgot where I read that so can't back it up but: "Unices are just a collection of different dialects of regex" I think the same is true for about every implementation of regex you can find. In theory it _should_ be same. Then again, so should SQL but I bet that it's actually quite hard to find a single statement that you can literally execute it on all DB servers (major ones). -- http://noneisyours.marcher.name http://feeds.feedburner.com/NoneIsYours From adam at volition-inc.com Thu Nov 15 11:12:11 2007 From: adam at volition-inc.com (Adam Pletcher) Date: Thu, 15 Nov 2007 10:12:11 -0600 Subject: formated local time In-Reply-To: References: Message-ID: <893A44FF792E904A97B7515CE341914601C3EEE7@volimxs01.thqinc.com> datetime also has the strftime method: import datetime datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') - Adam > -----Original Message----- > From: python-list-bounces+adam=volition-inc.com at python.org > [mailto:python-list-bounces+adam=volition-inc.com at python.org] On Behalf > Of attn.steven.kuo at gmail.com > Sent: Thursday, November 15, 2007 9:56 AM > To: python-list at python.org > Subject: Re: formated local time > > On Nov 15, 7:19 am, Nikola Skoric wrote: > > I have been trying to find appropriate way to do get local time in > > "yyyy-mm-dd hh:mm:ss" format, but the best I got is this: > > datetime.datetime.fromtimestamp(time.mktime(time.localtime())) > > It seems to me I'm missing a much simpler method, am I? > > > If you want the formatted string, you can use strftime: > > >>> time.strftime("%Y-%m-%d %H:%M:%S") > '2007-11-15 07:51:12' > > -- > Hope this helps, > Steven > -- > http://mail.python.org/mailman/listinfo/python-list From abarun22 at gmail.com Tue Nov 27 01:08:49 2007 From: abarun22 at gmail.com (abarun22 at gmail.com) Date: Mon, 26 Nov 2007 22:08:49 -0800 (PST) Subject: C pointer representation in python References: Message-ID: HI Thanks for the suggestion and i believe that seems a good idea. But because of some work related constraints i have to use SWIG for the moment. Regards Arun Terry Reedy wrote: > wrote in message > news:f58fb0de-9e3f-4a88-a0b4-211d2fd3fc97 at d4g2000prg.googlegroups.com... > | Hi > | I am new to SWIG and python. I have a problem while trying to call a C > | function from Python using SWIG as an interface. > > Did you consider using the ctypes module? > (It is new in the stdlib for 2.5, I believe.) > Some consider it easier to use than swig. From greg at cosc.canterbury.ac.nz Sun Nov 18 20:24:39 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Mon, 19 Nov 2007 14:24:39 +1300 Subject: Simple eval In-Reply-To: References: Message-ID: <5qc77gFujovgU1@mid.individual.net> Tor Erik S?nvisen wrote: > Comments, speedups, improvements in general, etc are appreciated. You're doing a lot of repeated indexing of token[0] and token[1] in your elif branches. You might gain some speed by fetching these into locals before entering the elif chain. Also you could try ordering the branches so that the most frequent cases come first. Probably strings and numbers first, then the various kinds of bracket. This would also give you a chance to avoid pulling out token[1] until you need it. token[1].startswith('u'): It's probably faster to use an index to get the first character, if you know that the string is not empty. Importing the names from tokenize that you use repeatedly should save some time, too. Putting all these together, it would look something like from tokenize import STRING, NUMBER def atom(next, token): token0 = token[0] if token0 == STRING ... elif token0 == NUMBER: ... elif token0[0] == 'u': ... else: token1 = token[1] if token1 in KEYWORDS: ... elif token1 == '(': ... elif token1 == '[': ... elif token1 == '{': ... If you were willing to indulge in some default-argument abuse, you could also do def atom(next, token, STRING = tokenize.STRING, NUMBER = tokenize.NUMBER): ... A more disciplined way would be to wrap it in a closure: def make_atom(): from tokenize import STRING, NUMBER def atom(next, token): ... return atom atom = make_atom() -- Greg From python at rcn.com Mon Nov 12 22:33:07 2007 From: python at rcn.com (Raymond Hettinger) Date: Mon, 12 Nov 2007 19:33:07 -0800 Subject: Define key in nlargest() of heapq? In-Reply-To: <1194922587.656458.228340@e34g2000pro.googlegroups.com> References: <1194922587.656458.228340@e34g2000pro.googlegroups.com> Message-ID: <1194924787.678372.129870@y27g2000pre.googlegroups.com> On Nov 12, 6:56 pm, Davy wrote: > I have a dictionary with n elements, and I want to get the m(m<=n) > keys with the largest values. > > For example, I have dic that includes n=4 elements, I want m=2 keys > have the largest values) > dic = {0:4,3:1,5:2,7:8} > So, the the largest values are [8,4], so the keys are [7,0]. > > How to do this by nlargest() of heapq? I have tried > nlargest(2,dic,key), Try this: >>> from heapq import nlargest >>> dic = {0:4,3:1,5:2,7:8} >>> from operator import itemgetter >>> nlargest(2, dic, dic.__getitem__) [7, 0] Raymond From paddy3118 at googlemail.com Sat Nov 10 06:34:34 2007 From: paddy3118 at googlemail.com (Paddy) Date: Sat, 10 Nov 2007 03:34:34 -0800 Subject: Returning actual argument expression to a function call? In-Reply-To: <13jaldkc4is505b@corp.supernews.com> References: <1194674580.142801.244840@57g2000hsv.googlegroups.com> <13jaldkc4is505b@corp.supernews.com> Message-ID: <1194694474.354294.294540@57g2000hsv.googlegroups.com> On Nov 10, 6:54 am, Steven D'Aprano wrote: > In the second example, if you are trying to capture the expression "0.4 > +1", I don't think that is possible. As far as I know, there is no way > for the called function to find out how its arguments were created. I > think if you need that, you need to create your own parser. > > -- > Steven. Unfortunately Steven, its exactly the expression that I want rather than the expression result. Thanks for your attempt, and I will try and make myself clearer in the future (allthough I did take time over my initial post). - Paddy. From hat at se-162.se.wtb.tue.nl Tue Nov 20 07:09:05 2007 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Tue, 20 Nov 2007 13:09:05 +0100 Subject: Web update library in python? References: Message-ID: On 2007-11-20, Jorgen Bodde wrote: > The 'repositories' can be created by anyone who likes to share their > code templates, and let the end user configure this template and > create a customized code base of it, on which they can code their > entire app. My tool supports incremental configuration which means if > there are updates to this repository, the user simply has to click > configure/generate again and merge the changes into their working > copy. SVN seems not useful in your situation, exactly because of the assumption of a single authorative repository that everybody uses, as you described. Instead, I think you should have a look at distributed SCM tools. Distributed SCMs do not have the concept of a central repo (that's why they are called 'distributed'), everybody can start their own repo (or copy one from elsewhere), hack away, and offer their changes to others. The system manages exchange of patches between the repositories. I have currently very limited experience with distributed SCMs. I just started experimenting locally with bzr. Please note that 'bzr repository' is comparable to a 'svn working copy'. There are no doubt subtle and not-so-subtle differences, but as I said, I have limited experience... The problem that I solved was that I wanted to have several personal sub-projects inside a SVN-based project (that I do not own and have no write access to). The changes of my sub-projects are then feed back into the main project and (hopefully) committed. Of course, these diffs should be against a recent SVN trunk of the project. I created a project_trunk directory with the anonymous SVN checkout. On top of svn, I added bzr management. (after 'svn update' I add/commit the changes also in bzr in the same directory). This directory now functions as an authorative source of bzr updates. Now, each personal sub-project is a copy of that bzr repo. I can do arbitrary code hacking, committing, running diff etc in each sub-project. I can also merge changes from the project_trunk directory with 'bzr merge' to pull in new updates from the SVN project. Although I haven't tried it, it should also be possible to copy/merge changes between my personal sub-projects. [hmm, while answering your post, I read some of the bzr website, and found that bzr has a standard tool for doing what I do... nice ] > I really thought about SVN but I would not like end-users to be > bothered with maintaining or installing SVN or a SVN server, and have > intermediate .svn local files inside every directory ;-) Now in your case, my 'project_trunk' would be your central web-site, and my personal sub-projects would be your users. Of course, the bandwidth between your website and users is a bit smaller than my local file system bandwidth, but given the fact that these SCMs are designed to work in a distributed way across the Internet, so I would expect them to handle this. Albert From cynshard at gmail.com Mon Nov 19 13:43:58 2007 From: cynshard at gmail.com (Jesse Jaggars) Date: Mon, 19 Nov 2007 12:43:58 -0600 Subject: Efficient: put Content of HTML file into mysql database In-Reply-To: <851acc320711191012q470f252biccf2e0bec86c8c08@mail.gmail.com> References: <851acc320711191012q470f252biccf2e0bec86c8c08@mail.gmail.com> Message-ID: <4741D96E.7010401@gmail.com> Fabian L?pez wrote: > Hi colegues, > do you know the most efficient way to put the content of an html file > into a mySQL database?Could it be this one?: > 1.- I have the html document in my hard disk. > 2.- Then I Open the file (maybe with fopen??) > 3.- Read the content (fread or similar) > 4.- Write all the content it in a SQL sentence. > > What happens if the html file is very big? > > > Thanks! > FAbian > > I don't understand why you would want to store an entire static html page in the database. All that accomplishes is adding the overhead of calling MySQL too. If you want to serve HTML do just let your webserver serve HTML. Is there more to the situation that would help myself and others understand why you want to do this? From tjreedy at udel.edu Thu Nov 15 18:23:39 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 15 Nov 2007 18:23:39 -0500 Subject: Populating a dictionary, fast [SOLVED SOLVED] References: <818643.92017.qm@web915.biz.mail.mud.yahoo.com><47374D00.7080500@gmail.com><1195051438.889160.137120@50g2000hsm.googlegroups.com><87fxz8kas6.fsf@mulj.homelinux.net><13jn10p1r88u19f@corp.supernews.com><876403jkqe.fsf@mulj.homelinux.net> <13jpgtq22a9lhc5@corp.supernews.com> Message-ID: "Steven D'Aprano" wrote in message news:13jpgtq22a9lhc5 at corp.supernews.com... | (7) It occurs in Python 2.3, 2.4 and 2.5, but not 2.5.1. | | Do we treat this as a solved problem and move on? If the problem was fixed accidentally as an undocumented by product of a patch aimed at something else, it might get similarly unfixed without triggering a test failure. So if someone pins down the problem source well enough to warn future maintainers in a comment or commit note, all the better. Otherwise, wait until a reversion happens, if ever. From david at boddie.org.uk Sun Nov 25 11:24:02 2007 From: david at boddie.org.uk (David Boddie) Date: Sun, 25 Nov 2007 17:24:02 +0100 Subject: PyQt, Cannot send events to objects owned by a different thread? Message-ID: <200711251724.03545.david@boddie.org.uk> On Sun Nov 25 15:22:24 CET 2007, Alexander Tuchacek wrote: > i try to adress an qt object > > self.statusbar.showMessage("rtt %s...." % (n.rtt)) > > in an callback function, comming from a shared lib importet by ctypes, on > osx this works wonderfull > > when i run the same code on linux (ubuntu gutsy), i get this core dump, ok, > i understand that the problem is, that i cant speak to the qt thread, but > why does it work on osx? Maybe the implementation of the library is different on OS X. You need to give us more enough information to work with. > shall i recompile python? pyqt or sip? without threads? > > could somebody give me a hint what to do best? how can i call a qt object in > an c-lib callback? You can either construct some sort of event handling mechanism or use signals and slots. Personally, I'd use signals and slots for this, if possible. The idea would be to set up a connection between your callback code and the status bar's showMessage() slot. Then you would only have to emit that signal to update the status bar. David From kay.schluehr at gmx.net Fri Nov 2 01:29:02 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Thu, 01 Nov 2007 22:29:02 -0700 Subject: AOP and pep 246 In-Reply-To: References: <1193937488.399694.235180@o80g2000hse.googlegroups.com> Message-ID: <1193981342.258351.153660@d55g2000hsg.googlegroups.com> On Nov 2, 5:00 am, "Rustom Mody" wrote: > On 11/1/07, Kay Schluehr wrote: > > > AOP was a research that gone nowhere - at least not in its orginal AspectJ form: > > declaring aspect code that targets business code, weaving the aspect code into the > > business app using a code generator. There was much excitement about it around 2001 > > that faded away > > Maybe so but five years maybe too short to decide this. > > Consider that the core ideas of LISP -- interpretation, > garbage-collection, s-exps-as-universal data-structure (now XML) have > taken 50 years to get into the mainstream. > > Of course its also true that the number of dead-end ideas exceeds the successes. > My own guess is that AOP via higher order functions and metaclasses > will be more successful than via aspectj and code-generation. > > In short python will do better than java. And so.. thanks for the link Yes. The methodological apparatus and terminology of AOP was invented for Java or another language that fits cleanly into the OO paradigm of "classes first". Aspects were a complementary modularization mechanism for crosscutting features that did not fit into the "classes first" ideology but were nevertheless modelled after classes. When you look at AspectJ code you will find all kinds of lexical dependencies since aspect code had to determine its join points using code pattern. Very brittle! Now compare this to decorators which do not have to declare where they are applied. You just decorate an appropriate function / method. Since higher order functions give you all this for free there isn't a real need to continue the semiotic legacy of AOP. Note that I actually do believe that code generation will increase in importance but not as an ordinary software engineering technique that provides better modularization of application code. I consider this as a failed idea. From jim at bizcomputinginc.com Fri Nov 2 11:13:00 2007 From: jim at bizcomputinginc.com (Jim Hendricks) Date: Fri, 02 Nov 2007 11:13:00 -0400 Subject: python newbie In-Reply-To: <1194014916.893875.188770@19g2000hsx.googlegroups.com> References: <472b2b84$0$13761$6e1ede2f@read.cnntp.org> <1194014916.893875.188770@19g2000hsx.googlegroups.com> Message-ID: <472b3e97$0$13759$6e1ede2f@read.cnntp.org> BartlebyScrivener wrote: > On Nov 2, 8:51 am, Jim Hendricks wrote: >> New to python, programming in 15 or so langs for 24 years. >> >> Couple of questions the tuts I've looked at don't explain: > > Did you look at THE tut? You would seem to be the perfect reader for > it, because you are already a programmer. > > http://docs.python.org/tut/node6.html#SECTION006600000000000000000 > > rd > I initially looked at THE tut, and it came across so techy that it's such a slow read. Therefore, I looked to other tuts that were very easy reads and could give me the basic lowdown of the language. Problem of course is the easy read tuts don't get into the details. That said, I looked at the section of the tutorial you provided (thanks) and I am still confused. It specifies a global var cannot be assigned unless it's specified in the global statement. Here's an example of what I am asking: def my_function(): global x x = open( .... before calling my_function, x does not exist in my program. So, my question is in my_function, the combination of using the global statement, then implicitly creating x via assignment to the result of the open function, is x created in the global namespace? From martin at marcher.name Mon Nov 12 12:27:31 2007 From: martin at marcher.name (Martin Marcher) Date: Mon, 12 Nov 2007 18:27:31 +0100 Subject: how to know if folder contents have changed In-Reply-To: <1194887998.593094.67480@y27g2000pre.googlegroups.com> References: <1194843813.901372.246490@k35g2000prh.googlegroups.com> <1194887998.593094.67480@y27g2000pre.googlegroups.com> Message-ID: <5fa6c12e0711120927i34088493q92677ac2a3dafeb2@mail.gmail.com> 2007/11/12, davisn90210 at gmail.com : > Why not use the file creation/modification timestamps? because you'd have to a) create a thread that pulls all the time for changes or b) test everytime for changes fam informs in a notification like way. Personally I'd create a "hidden" cache file parsable by configparser and have filename = $favorite_checksum_algo - key value pairs in it if it's not a long running process. Otherwise I'd probably go with fam (or hal i think that's the other thing that does that) hth martin -- http://noneisyours.marcher.name http://feeds.feedburner.com/NoneIsYours From r.grimm at science-computing.de Fri Nov 9 01:53:16 2007 From: r.grimm at science-computing.de (r.grimm at science-computing.de) Date: Thu, 08 Nov 2007 22:53:16 -0800 Subject: operator overloading on built-ins Message-ID: <1194591196.143682.70590@z9g2000hsf.googlegroups.com> Hallo, could you explaint me the difference between the two following statements. Python 2.5 (r25:51908, Oct 7 2006, 23:45:05) [GCC 3.3.5 20050117 (prerelease) (SUSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> (1).__cmp__(10) -1 >>> 1.__cmp__(10) File "", line 1 1.__cmp__(10) ^ SyntaxError: invalid syntax The first works as expect, but the second. Regards Rainer From donn.ingle at gmail.com Sat Nov 17 14:23:25 2007 From: donn.ingle at gmail.com (Donn Ingle) Date: Sat, 17 Nov 2007 21:23:25 +0200 Subject: Python too complex ?!?!?! References: <7hC%i.28332$mv3.17248@newsfe10.phx> Message-ID: > Interesting idea, although it's not something I'd want included and > turned on by default. Should certainly be possible, though, with a > little __import__ magic. Well, since we're shooting the sh*t :), I tried in my one and only released app (Fonty Python) to wrap the imports in try clauses and then print helpful strings to the console to guide the user. I'm really not too clued-up on the __deep__ magic of Python, so I can't say what tricks there are, but a simple "catch a fail and then start a solution" process is a general approach. >> If you are online and the app runs, it can check the "freshness" of your >> modules (those called from the app and recursively) and offer to fetch >> the latest stable versions. > Something similar to Java's webstart? Implement an __import__ hook > that downloads and caches the latest (stable) versions of libraries as > needed. I have also never touched Java, so I can't say, but something like that. The main problem with having modules coming from the web is time. How long is the life of a URL? The Cheese Shop seems pretty well established and could serve the role. Perhaps there are already ways of making sure that a hard-coded link in an app can reach a variable URL online. > You wouldn't really *need* a GUI, although it probably should be a > configurable option ... I'd agree, but then I grew up with commands lines. I can say with total confidence that the command-line scares a lot of people and if there are any questions that need answering during the automated process (and there's always *something* that crops up ) then a gui is the natural way to reach the user. > No reason why it couldn't be totally > automated. easy_install already provides for automated installation > of python apps/libraries, so you could build off that. Totally automated would be the goal. I'd say a throbber or progress animation of some kind would be needed. Just thought of a wrinkle - say a new module is available and is installed and then proves to be broken. How can the app recover? There'd have to be a system of flags in a db that mark the situation and on re-run can roll back to the last working module. Then we get feedback to the author of the module.... And let's not forget all the joy that can be spread by having to compile modules (on various platforms) from C/C++ and then worry about *their* dependant libraries! Oh fun times :p (I think I can see why this has never been approached.) > Merely using decorators is, IMHO, much easier > to understand (but still requires a slight brain-warp). I'm still stuck with those things. I can't really find an example that I want to use. My brain keeps saying "yeah, but that's so smoke and mirrors and I could do it this way ... which seems much plainer." > I think some > people try to understand decorators too completely too quickly, and > end up labeling them one of those complex/unintuitive/"way out" > things. I have put them in the bag along with Design Patterns and Threads as "things that I don't have to worry about because liff is too short. And like the Spanish Inquisition, they're welcome to surprise me when I least expect it, but I'm not going to lose my mind waiting :D /d From donn.ingle at gmail.com Fri Nov 9 18:06:28 2007 From: donn.ingle at gmail.com (Donn Ingle) Date: Sat, 10 Nov 2007 01:06:28 +0200 Subject: Global variables within classes. References: <4734b3d4$0$5462$426a34cc@news.free.fr> <4734e2a9$0$12488$426a74cc@news.free.fr> Message-ID: > I guess you mean "instances", not "classes". Yes. > Err...Perhaps a dumb question, but what about passing the "common > objects" to initializers ? > s = Stack() > c = Canvas(s) > t = Thing(s) Okay, I see where you're going. It's better than what I have at the moment. Thanks. \d From samuel.progin at gmail.com Wed Nov 21 02:35:21 2007 From: samuel.progin at gmail.com (samuel.progin at gmail.com) Date: Tue, 20 Nov 2007 23:35:21 -0800 (PST) Subject: How to make a standalone Python/Tk program? References: <5feebbea-6569-4567-95e0-4c466f9f46f0@c29g2000hsa.googlegroups.com> Message-ID: <62aae223-3a5e-4a5d-a3b3-6cb40f4249fc@w34g2000hsg.googlegroups.com> > How to make a standalone Python/Tk program(e.g. exe file on Windows)? > Any suggestions are welcome! Hello! Here are a few pointers, try to google: - pyinstaller - python freeze - py2exe or more generally "python to exe" You may have a search on this mailing list, in my mind this topic was discussed recently. Best regards. Sam From donn.ingle at gmail.com Sun Nov 25 22:49:58 2007 From: donn.ingle at gmail.com (Donn Ingle) Date: Mon, 26 Nov 2007 05:49:58 +0200 Subject: basic if stuff- testing ranges References: <2f4afd60-295d-44ef-94c6-163591d33dc1@d21g2000prf.googlegroups.com> Message-ID: >> if 0 > x < 20: print "within" > That means "if x LESS THAN 0 and x < 20". Oh, bugger. It's tricky. > So try > if 0 < x < 20: Thanks. I was flipping signs in my tests, but I guess I flipped both and got myself all confused. > Likely manuals: Tutorial & Reference > Tutorial: check contents, "if statement" looks possible, but no luck Yes, I got that far. > Reference: check contents, "comparisons" looks possible, and Thanks again. I find the reference is laid-out in a way that I don't find intuitive and every time I look for something I fail. I even grep through the folder to get a clue, which shows how poor the index is (to me)! Many thanks for the help! \d From beldin79 at yahoo.com Thu Nov 22 18:17:36 2007 From: beldin79 at yahoo.com (maurice ling) Date: Thu, 22 Nov 2007 15:17:36 -0800 (PST) Subject: The Python Papers is looking for additional Associate Editors Message-ID: <594560.25511.qm@web51803.mail.re2.yahoo.com> "The Python Papers" (http://pythonpapers.org), ISSN 1834-3147, is an online e-journal, covering articles on Python in the community, industry and academia. We were established in the second half of 2006 and launched our first issue in November 2006. Since then, we have released 3 more issues. Recently, we have also initiated a monograph series, which will be known as "The Python Papers Monograph Series" (http://pythonpapers.org/monograph.html) with its own ISSN, but managed by "The Python Papers" Editorial Committee. Due to this new initiative, we are looking for an additional member to join the team as an Associate Editor from February 2008. The main roles of an Associate Editor includes: 1. Organizing and chairing reviews for submissions 2. Reviewing submissions 3. Answering queries regarding the periodicals 4. Assisting the Editor-in-Chief in tasks as required The current workload is estimated to be about 3 hours per week. We invite committed individuals with a good knowledge of Python programming to join our team. Please send in your CV and a statement of intention to us at editor at pythonpapers.org before December 20, 2007. Please direct any queries to editor at pythonpapers.org Thank you Maurice Ling Associate Editor, The Python Papers From mfriedeman at gmail.com Thu Nov 8 17:55:55 2007 From: mfriedeman at gmail.com (Hans Moleman) Date: 9 Nov 2007 11:55:55 +1300 Subject: Version 0.6.0 of CodeInvestigator Message-ID: <473393fb$1@clear.net.nz> CodeInvestigator version 0.6.0 was released on November 8. This version adds support for input() and raw_input() functions. The main changes: * The 'Details' button on the file selection screen gives access to statistics, stdin and stdout for the running program. Control Z and control D keys in stdin are honored. * Keyword values are now recorded just like variable values. * Bug fixes. An expression that evaluates to a function call was not handled correctly. CodeInvestigator is a tracing tool for Python programs. Running a program trough CodeInvestigator creates a recording. Program flow, function calls, variable values and conditions are all stored for every line the program executes. The recording is then viewed with an interface consisting of the code. The code can be clicked: A clicked variable displays its value, a clicked loop displays its iterations. You read code, and have at your disposal all the run time details of that code. A computerized desk check tool and another way to learn about your program. http://sourceforge.net/project/showfiles.php?group_id=183942 From zhushenli at gmail.com Wed Nov 21 21:55:21 2007 From: zhushenli at gmail.com (Davy) Date: Wed, 21 Nov 2007 18:55:21 -0800 (PST) Subject: Introspect the class name of object? Message-ID: Hi all, How to get the class name of an object from an introspect way? For example, Class cls:pass obj = cls() I want to get function(obj) = 'cls' Best regards, Davy From dfabrizio51 at gmail.com Mon Nov 19 14:23:54 2007 From: dfabrizio51 at gmail.com (chewie54) Date: Mon, 19 Nov 2007 11:23:54 -0800 (PST) Subject: embed ipython in wxPython app References: <8f8fbbed-6cae-42ac-8efa-d1c34739c4cb@w34g2000hsg.googlegroups.com> <5506d1e2-530f-4ef7-9109-e98ba3354e4b@f3g2000hsg.googlegroups.com> <0ebab410-126e-4312-83ea-3d9f5a9308ed@f3g2000hsg.googlegroups.com> Message-ID: On Nov 19, 1:44 pm, "Chris Mellon" wrote: > On Nov 19, 2007 12:21 PM, chewie54 wrote: > > > > > On Nov 19, 1:07 pm, "Chris Mellon" wrote: > > > > On Nov 19, 2007 11:51 AM, chewie54 wrote: > > > > > On Nov 18, 8:39 pm, chewie54 wrote: > > > > > Hi All, > > > > > > I'm evaluting IPython to see if I can it use like Tcl and Tk. If I > > > > > start wish8.4, I get a command line > > > > > interpreter in xterm, then I can source tcl progams that draw tk > > > > > graphics on a canvas in another window. > > > > > > Is there a way to embed IPython in a wxPython app to do that? > > > > > When I do as shown in the example below the GUI window does not show > > > > > until I exit IPython. > > > > > > Thanks in advance for any help with this, > > > > > > import wx > > > > > from IPython.Shell import IPShellEmbed > > > > > > class MyFrame(wx.Frame): > > > > > def __init__(self,parent=None, id=-1, title=' '): > > > > > wx.Frame.__init__(self,parent,id,title,size=(200,140)) > > > > > top = wx.Panel(self) > > > > > sizer = wx.BoxSizer(wx.VERTICAL) > > > > > lb = wx.StaticText(top,-1,'Animals(in pairs; min,pair, > > > > > max,dozen)') > > > > > sizer.Add(lb) > > > > > > top.SetSizer(sizer) > > > > > self.Layout() > > > > > > class MyApp(wx.App): > > > > > def OnInit(self): > > > > > frame = MyFrame(title="wxWidgets") > > > > > frame.Show(True) > > > > > self.SetTopWindow(frame) > > > > > return True > > > > > > def main(): > > > > > ipshell = IPShellEmbed() > > > > > ipshell() > > > > > app = MyApp() > > > > > app.MainLoop() > > > > > > if __name__ == '__main__': > > > > > main() > > > > > I forgot to mention. > > > > > I did see an example of embedding IPython in a PyGTK app on > > > >http://ipython.scipy.org/moin/Cookbook > > > > > It would be nice to see an example that shows how to embed > > > > IPython in a wxPython or Tkinter GUI app. > > > > IPython has a custom event loop. You'll need to look at it's sources > > > and figure out how to drive it externally. There's some plugins for > > > IPython that may help (or may even work out of the box), they're used > > > to let you run wx or gtk or other libraries that have their own event > > > loop within IPython. > > > > Are you aware that wx already has a Python shell implementation? It's > > > different than IPython, of course, but it has graphical inspection of > > > objects which is the main reason people tend to use IPython. > > > Yes, I have seen the wxPython demo and PyShell example but was > > looking > > to use IPython since the user can navigate directories like other > > unix > > shells. > > > What are these plugins you mentioned? > > http://ipython.scipy.org/moin/Cookbook/InterruptingThreads > > I'm not sure how these work (the wiki page implies they just run the > external event loop in a thread, so they're not suitable for embedding > IPython in such a tool kit). I'm sure there's a way to pump IPython > though (there must be, since it's embeddable in gtk) so that's where > you'll want to look. This was helpful. ipython -wxthread run test1_python.py and the GUI window was displayed and I can see my object definitions. I'm getting closer, now I need to imbed ipython -wxthread shell in the app somehow. Thanks, From aassime1 at hotmail.fr Fri Nov 30 14:03:37 2007 From: aassime1 at hotmail.fr (aassime abdellatif) Date: Fri, 30 Nov 2007 11:03:37 -0800 (PST) Subject: 25 MOST FREQUENTLY ASKED QUESTIONS ABOUT ISLAM Message-ID: <4457a36c-e371-4fc8-8caf-c7828010f8ce@d21g2000prf.googlegroups.com> 1. What is Islam? The word "Islam" means peace and submission. Peace means to be at peace with yourself and your surroundings and submission means submission to the will of God. A broader meaning of the word "Islam" is to achieve peace by submitting to the will of God. This is a unique religion with a name which signifies a moral attitude and a way of life. Judaism takes its name from the tribe of Juda, Christianity from Jesus Christ, Buddhism from Goutam Buddha and Hinduism from Indus River. However, Muslims derive their identity from the message of Islam, rather than the person of Muhammed (P), thus should not be called "Muhammadans". 2. Who is Allah? Allah is the Arabic word for "one God". Allah is not God of Muslims only. He is God of all creations, because He is their Creator and Sustainer. 3. Who is a Muslim? The word "Muslim" means one who submits to the will of God. This is done by declaring that "there is no god except one God and Muhammad is the messenger of God." In a broader sense, anyone who willingly submits to the will of God is a Muslim. Thus, all the prophets preceding the prophet Muhammad are considered Muslims. The Quran specifically mentions Abraham who lived long before Moses and Christ that, "he was not a Jew or a Christian but a Muslim," because, he had submitted to the will of God. Thus there are Muslims who are not submitting at all to the will of God and there are Muslims who are doing their best to live an Islamic life. One cannot judge Islam by looking at those individuals who have a Muslim name but in their actions, they are not living or behaving as Muslims. The extent of being a Muslim can be according to the degree to which one is submitting to the will of God, in his beliefs and his actions. 4. Who was Muhammad? (P) In brief, Muhammad (Peace be upon him) was born in a noble tribe of Mecca in Arabia in the year 570 AD. His ancestry goes back to Prophet Ishmael (P), son of Prophet Abraham (P). His father died before his birth and his mother died when he was six. He did not attend a formal school since he was raised first by a nurse as it was the custom those days, and then by his grandfather and uncle. As a young man, he was known as a righteous person who used to meditate in a cave. At age 40, he was given the prophethood when the angel, Gabriel, appeared in the cave. Subsequently, the revelations came over 23 years and were compiled in the form of a book called the Quran which Muslims consider as the final and the last word of God. The Quran has been preserved, unchanged, in its original form and confirms the truth in the Torah, the psalms and the Gospel. 5. Do Muslims worship Muhammad? (P) No. Muslims do not worship Muhammad (P) or any other prophets. Muslims believe in all prophets including Adam, Noah, Abraham, David, Solomon, Moses and Jesus. Muslims believe that Muhammad (P) was the last of the prophets. They believe that God alone is to be worshiped, not any human being. 6. What do Muslims think of Jesus? (P) Muslims think highly of Jesus (P) and his worthy mother, Mary. The Quran tells us that Jesus was born of a miraculous birth without a father. "Lo! The likeness of Jesus with Allah is the likeness of Adam. He created him of dust, and then He said unto him: Be and he is" (Quran 3.59). He was given many miracles as a prophet. These include speaking soon after his birth in defense of his mother's piety. God's other gifts to him included healing the blind and the sick, reviving the dead, making a bird out of clay and most importantly, the message he was carrying. These miracles were given to him by God to establish him as a prophet. According to the Quran, he was not crucified but was raised into Heaven. (Quran, Chapter Maryam) 7. Do Muslims have many sects? Muslims have no sects. In Islam, there are two major schools of thought, the Shia and the Sunni. Both have many things in common. They follow the same book - Quran. They follow the same prophet Muhammad (P). Both offer their prayers five time a day. Both fast in the month of Ramadan. They both go for hajj, pilgrimage to Mecca. Those who follow Prophet Muhammad (P), in accordance with his sayings and actions, are called Sunni and those who in addition follow the sayings and views of Ali (Muhammad's son-in- law), as the rightful successor to Prophet Muhammad (P), are called Shia. Shia means a partisan (party of Ali) and it started more as a political party to help Ali in his conflict with his political adversaries. Most Shias live in Iran and Iraq while the rest of the Muslim world is mostly Sunni. Shias comprise about 16-percent of the Muslim population. 8. What are the pillars of Islam? There are five major pillars of Islam which are the articles of faith. These pillars are 1) the belief (Iman) in one God and that Muhammad (P) is His messenger, 2) prayer (Salat) which are prescribed five times a day, 3) fasting (Siyam) which is required in the month of Ramadan, 4) charity (Zakat) which is the poor-due on the wealth of the rich and 5) hajj which is the pilgrimage to Mecca once in a lifetime if one can afford it physically and financially. All the pillars should be of equal height and strength in a building in order to give the building its due shape and proportions. It is not possible that one would do hajj without observing fasting or without practicing regular prayers. Now think of a building which has pillars only. It would not be called a building. In order to make it a building, it has to have a roof, it has to have walls, it has to have doors and windows. These things in Islam are the moral codes of Islam such as honesty, truthfulness, steadfastness and many other human moral qualities. Thus in order to be a Muslim, one should not only be practicing the pillars of Islam but should also have the highest possible attribute for being a good human being. Only then the building is completed and looks beautiful. 9. What is the purpose of worship in Islam? The purpose of worship in Islam is to be God conscious. Thus the worship, whether it is prayer, fasting, or charity, is a means to achieve God consciousness so that when one becomes conscious of God, in thought and in action, he is in a better position to receive His bounties both in this world and the hereafter. 10. Do Muslims believe in the hereafter? God is Just and manifest His justice, He established the system of accountability. Those who do good will be rewarded and those who do wrong will be punished accordingly. Thus, He created Heaven and Hell and there are admission criteria for both. Muslims believe that the present life is a temporary one. It is a test and if we pass the test, we will be given a life of permanent pleasure in the company of good people in Heaven. 11. Will the good actions of the non-believers be wasted? No. The Quran clearly says that, "anyone who has an atom's worth of goodness will see it and anyone who has done an atom's worth of evil will also see it" (Quran 99:7-8). By that it is meant that those who are non- believers but have done good will be rewarded in this world for their good deed. On the other hand, those who do good if they are Muslims, they will be rewarded not only in this world but also in the world hereafter. However, the final Judgment is up to God himself. (Quran 2:62) 12. What is the dress code for Muslims? Islam emphasizes modesty. No person should be perceived as a sex object. There are certain guidelines both for men and women that their dress should neither be too thin nor too tight to reveal body forms. For men, they must at least cover the area from the knee to navel and for women, their dress should cover all areas except the hands and face. The veil is not essential. 13. What are the dietary prohibitions in Islam? Muslims are told in the Quran not to eat pork or pork products, meat of the animals who died before being slaughtered or the carnivorous animals (as they eat dead animals), nor drink blood or intoxicants such as wine or use any illicit drugs. 14. What is Jihad? The word "Jihad" means struggle, or to be specific, striving in the cause of God. Any struggle done in day-to-day life to please God can be considered Jihad. One of the highest levels of Jihad is to stand up to a tyrant and speak a word of truth. Control of the self from wrong doings is also a great Jihad. One of the forms of Jihad is to take up arms in defense of Islam or a Muslim country when Islam is attacked. This kind of Jihad has to be declared by the religious leadership or by a Muslim head of state who is following the Quran and Sunnah. 15. What is the Islamic Year? The Islamic year started from the migration (Hijra) of Prophet Muhammad (P) from Mecca to Medina in 622 AD. It is a lunar year of 354 days. The first month is called Muharram. 1996 AD is in Islamic year 1416 AH. 16. What are the major Islamic festivals? Idul Fitre, marks the end of fasting in the month of Ramadan and is celebrated with public prayers, feasts and exchange of gifts. Idul Adha marks the end of the Hajj or the annual pilgrimage to Mecca. After the public prayers, those who can afford, sacrifice a lamb or a goat to signify Prophet Abraham's obedience to God, shown by his readiness to sacrifice his son Ishmael. 17. What is Sharia? Sharia is the comprehensive Muslim law derived form two sources, a) the Quran b) the Sunnah or traditions of Prophet Muhammad (P). It covers every aspect of daily individual and collective living. The purpose of Islamic laws are protection of individuals' basic human rights to include right to life, property, political and religious freedom and safeguarding the rights of women and minorities. The low crime rate in Muslim societies is due to the application of the Islamic laws. 18. Was Islam spread by the sword? According to the Quran, "There is no compulsion in religion" (2:256), thus, no one can be forced to become a Muslim. While it is true that in many places where Muslim armies went to liberate people or the land, they did carry the sword as that was the weapon used at that time. However, Islam did not spread by the sword because in many places where there are Muslims now, in the Far East like Indonesia, in China, and many parts of Africa, there are no records of any Muslim armies going there. To say that Islam was spread by the sword would be to say that Christianity was spread by guns, F-16's and atomic bombs, etc., which is not true. Christianity spread by the missionary works of Christians. Ten-percent of all Arabs are Christians. The "Sword of Islam" could not convert all the non-Muslim minorities in Muslim countries. In India, where Muslims ruled for 700 years, they are still a minority. In the U.S.A., Islam is the fastest growing religion and has 6 million followers without any sword around. 19. Does Islam promote violence and terrorism? No. Islam is religion of peace and submission and stresses on the sanctity of human life. A verse in the Quran says, [Chapter 5, verse 32], that "anyone who saves one life, it is as if he has saved the whole of mankind and anyone who has killed another person (except in lieu of murder or mischief on earth) it is as if he has killed the whole of mankind." Islam condemns all the violence which happened in the Crusades, in Spain, in WW II, or by acts of people like the Rev. Jim Jones, David Koresh, Dr. Baruch Goldstein, or the atrocities committed in Bosniaby the Christian Serbs. Anyone who is doing violence is not practicing his religion at that time. However, sometimes violence is a human response of oppressed people as it happens in Palestine. Although this is wrong, they think of this as a way to get attention. There is a lot of terrorism and violence in areas where there is no Muslim presence. For example, in Ireland, South Africa, Latin America, and Sri Lanka. Sometimes the violence is due to a struggle between those who have with those who do not have, or between those who are oppressed with those who are oppressors. We need to find out why people become terrorists. Unfortunately, the Palestinians who are doing violence are called terrorists, but not the armed Israeli settlers when they do the same sometimes even against their own people. As it turned out to be in the Oklahoma City bombing, sometime Muslims are prematurely blamed even if the terrorism is committed by non-Muslims. Sometimes those who want Peace and those who oppose Peace can be of the same religion. 20. What is "Islamic Fundamentalism"? There is no concept of "Fundamentalism" in Islam. The western media has coined this term to brand those Muslims who wish to return to the basic fundamental principles of Islam and mould their lives accordingly. Islam is a religion of moderation and a practicing God fearing Muslim can neither be a fanatic nor an extremist. 21. Does Islam promote polygamy? No, polygamy in Islam is a permission not an injunction. Historically, all the prophets except Jesus, who was not married, had more than one wife. For Muslim men to have more than one wife is a permission which is given to them in the Quran, not to satisfy lust, but for the welfare of the widows and the orphans of the wars. In the pre-Islamic period, men used to have many wives. One person had 11 wives and when he became Muslim, he asked the Prophet Muhammad (P), "What should I do with so many wives?" and he said, "Divorce all except the four." The Quran says, "you can marry 2 or 3 and up to 4 women if you can be equally just with each of them" (4:3). Since it is very difficult to be equally just with all wives, in practice, most of the Muslim men do not have more than one wife. Prophet Muhammad (P) himself from age 24 to 50 was married to only one woman, Khadija. In the western society, some men who have one wife have many extramarital affairs. Thus, a survey was published in "U.S.A. Today" (April 4, 1988 Section D) which asked 4,700 mistresses what they would like their status to be. They said that "they preferred being a second wife rather than the 'other woman' because they did not have the legal rights, nor did they have the financial equality of the legally married wives, and it appeared that they were being used by these men." 22. Does Islam oppress women? No. On the contrary, Islam elevated the status of women 1,400 years ago by giving them the right to divorce, the right to have financial independence and support and the right to be identified as dignified women (Hijab) when in the rest of the world, including Europe, women had no such rights. Women are equal to men in all acts of piety (Quran 33:32). Islam allows women to keep their maiden name after marriage, their earned money and spend it as they wish, and ask men to be their protector as women on the street can be molested. Prophet Muhammad (P) told Muslim men, "the best among you is the one who is best to his family." Not Islam, but some Muslim men, do oppress women today. This is because of their cultural habits or their ignorance about their religion. Female Genital Mutilations has nothing to do with Islam. It is a pre Islamic African Custom, practiced by non Muslims including coptic Christians as well. 23. Is Islam intolerant of other religious minorities? Islam recognizes the rights of the minority. To ensure their welfare and safety, Muslim rulers initiated a tax (Jazia) on them. Prophet Muhammad (P) forbade Muslim armies to destroy churches and synagogues. Caliph Umer did not even allow them to pray inside a church. Jews were welcomed and flourished in Muslim Spain even when they were persecuted in the rest of Europe. They consider that part of their history as the Golden Era. In Muslim countries, Christians live in prosperity, hold government positions and attend their church. Christian missionaries are allowed to establish and operate their schools and hospitals. However, the same religious tolerance is not always available to Muslim minorities as seen in the past during Spanish inquisition and the crusades, or as seen now by the events in Bosnia, Israel and India. Muslims do recognize that sometimes the actions of a ruler does not reflect the teachings of his religion. 24. What is the Islamic view on- a. Dating and Premarital sex: Islam does not approve of intimate mixing of the sexes, and forbids premarital or extramarital sex. Islam encourages marriage as a shield to such temptations and as a means of having mutual love, mercy and peace. b. Abortion: Islam considers abortion as murder and does not permit it except to save the mother's life (Quran 17:23-31, 6:15 1). c. Homosexuality and AIDS: Islam categorically opposes homosexuality and considers it a sin. However, Muslim physicians are advised to care for AIDS patients with compassion just as they would for other patients. d. Euthanasia and Suicide: Islam is opposed to both suicide and euthanasia. Muslims do not believe in heroic measures to prolong the misery in a terminally ill patient. e. Organ transplantation: Islam stresses upon saving lives (Quran 5:32); thus, transplantation in general would be considered permissible provided a donor consent is available. The sale of the organ is not allowed. 25. How should Muslims treat Jews and Christians? The Quran calls them "People of the Book", i.e., those who received Divine scriptures before Muhammad (P). Muslims are told to treat them with respect and justice and do not fight with them unless they initiate hostilities or ridicule their faith. The Muslims ultimate hope is that they all will join them in worshipping one God and submit to His will. "Say (O Muhammad): O people of the Book (Jews and Christians) come to an agreement between us and you, that we shall worship none but Allah, and that we shall take no partners with Him, and none of us shall take others for Lords beside Allah. And if they turn away, then say: Bear witness that we are those who have surrendered (unto Him)." (Quran 3:64) What about Hindus, Bahai, Buddhists and members of other religions? They should also be treated with love, respect, and understanding to make them recipients of Invitations to Islam. From Moh989 at gmail.com Thu Nov 15 12:03:26 2007 From: Moh989 at gmail.com (Mohammed_M) Date: Thu, 15 Nov 2007 09:03:26 -0800 (PST) Subject: Printing user input? Message-ID: <46e7af01-5cf6-4f7a-926f-73a3ecc0db47@v4g2000hsf.googlegroups.com> Hi, I'm v.new to Python, so please don't be too harsh :) I get a NameError with the code below - All I want to do is store some input taken from the user in a variable called name, & then print name # START CODE ========================================== # Print name demo def PersonsDetails(): name = input("What's your name?") PersonsDetails() print(name) # END CODE ========================================== Thanks for reading & any help on this From paddy3118 at googlemail.com Sat Nov 17 08:53:57 2007 From: paddy3118 at googlemail.com (Paddy) Date: Sat, 17 Nov 2007 05:53:57 -0800 (PST) Subject: Python too complex ?!?!?! References: <7hC%i.28332$mv3.17248@newsfe10.phx> Message-ID: <060441c4-9943-4514-bbff-e919ceb06d92@w28g2000hsf.googlegroups.com> On Nov 17, 1:46 pm, Brian wrote: > Had a unsettling conversation with a CS instructor that > teaches at local high schools and the community > college. This person is a long-term Linux/C/Python > programmer, but he claims that the install, config, and > library models for C# have proved to be less > problematic than Python. So both his courses (intro, > data structs, algorithms) are taught in C#. > > I am a low-end (3-year) journeyman Pythonista, and I > was attracted to the language because of its > simplicity. And I have come to enjoy the richness of > available libraries. > > Many of the good people of this NG may be 'too close' > to answer, but has Python, as a general devel platform, > lost its simplicity ? Is library install too complex > and unreliable ? Will my dog go to heaven ? It would be nice to have more info on his specific problems. Me, I find both Activestates and the official Python wiundows installers just work. - Paddy. From kay.schluehr at gmx.net Fri Nov 23 23:48:06 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Fri, 23 Nov 2007 20:48:06 -0800 (PST) Subject: the annoying, verbose self References: <3c954a31-9fb9-4c0f-b784-cef9ee057ca6@g30g2000hsb.googlegroups.com> <6f67fccf-fbec-4c75-baea-5d0277e07883@w40g2000hsb.googlegroups.com> <47458D4E.5030302@sympatico.ca> <13keq168fnu9328@corp.supernews.com> Message-ID: On Nov 24, 12:54 am, Steven D'Aprano wrote: > The correct solution to your example is to get rid of the attribute > lookups from the expression completely: > > def abs(self): > x, y, z = self.x, self.y, self.z > return math.sqrt(x**2 + y**2 + z**2) > > It's probably also faster, because it looks up the attributes only once > each, instead of twice. > > -- > Steven. I like this pattern but less much I like the boilerplate. What about an explicit unpacking protocol and appropriate syntax? def abs(self): x, y, z by self return math.sqrt(x**2 + y**2 + z**2) expands to def abs(self): x, y, z = self.__unpack__("x","y","z") return math.sqrt(x**2 + y**2 + z**2) This would have another nice effect on expression oriented programming where people use to create small "domain specific languages" using operator overloading: x,y,z by Expr class Expr(object): def __init__(self, name): self.name = name self._sexpr = () def __unpack__(self, *names): if len(names)>1: return [Expr(name) for name in names] elif len(names) == 1: return Expr(names[0]) else: raise ValueError("Nothing to unpack") def __add__(self, other): e = Expr("") e._sub = ('+',(self, other)) return e def __repr__(self): if self._sexpr: return self._sexpr[0].join(str(x) for x in self._sexpr[1]) return self.name >>> x,y by Expr >>> x+y x+y >>> 4+x 4+x From andy at britishideas.com Thu Nov 15 18:09:52 2007 From: andy at britishideas.com (andy at britishideas.com) Date: Thu, 15 Nov 2007 15:09:52 -0800 (PST) Subject: Redirecting sys.stdin Message-ID: <06e53808-2212-4cc7-8fe2-1fdb86434790@e10g2000prf.googlegroups.com> Can anyone tell me what I am doing wrong with the following code? When python 2.4 is embedded it crashes because of the assignment to stdin. import sys; class RedirectB: def readline(self): return "bar"; sys.stdin = RedirectB(); Thanks! Andy From grante at visi.com Wed Nov 28 15:42:45 2007 From: grante at visi.com (Grant Edwards) Date: Wed, 28 Nov 2007 20:42:45 -0000 Subject: Bit Operations References: Message-ID: <13krkm5t07u1o9b@corp.supernews.com> On 2007-11-28, Chris Mellon wrote: > On Nov 28, 2007 2:07 PM, Gianmaria Iaculo - NVENTA > wrote: >> Hi there, >> I'm so new to python (coming from .net so excuse me for the stupid question) >> and i'm tring to do a very simple thing,with bytes. >> >> My problem is this: >> >> i've a byte that naturally is composed from 2 nibbles hi&low, and two >> chars.. like A nd B. What i wonna do is to write A to the High nibble and B >> to the the lower nibble. > > A string in python is a sequence of bytes, so what you're describing > here is the string "AB". No, he's describing something that consists of 2 nibbles (1 byte). The string "AB" is two bytes. >> Or an other example can be i've 2 numbers.. like 7 and 8 and whant to do the >> same as for chars. >> > > "\x07\x08" Again, he wants a single byte and that's two bytes. >> I'm really confused on how t do it, maybe cause python is >> type-less (dynamic typed) > > You can use the struct module to convert back and forth between byte > sequences and numerical values. For example, to get an integer with > the value of the nibble you mentioned before: > > struct.unpack("h", "AB") -> (16961,) No, he wants to do this: (0x0A<<4) | 0x0B (7<<4) | 8 > Exactly what you'll want to use and what format you want will depend > on why you're doing this. -- Grant Edwards grante Yow! My vaseline is at RUNNING... visi.com From steven.bethard at gmail.com Thu Nov 8 11:44:56 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 08 Nov 2007 09:44:56 -0700 Subject: optional arguments with compact reporting in optparse In-Reply-To: <1194535803.845082.171590@q5g2000prf.googlegroups.com> References: <1194535803.845082.171590@q5g2000prf.googlegroups.com> Message-ID: braver wrote: > Posted to the Optik list, but it seems defunct. Optik is now Python's > optparse. > > I wonder how do you implement optional arguments to Optik. You may want to check out argparse: http://argparse.python-hosting.com/ It supports optional arguments like this:: parser = argparse.ArgumentParser() parser.add_argument('-P', metavar='file', nargs='?', const='data') args = parser.parse_args() if args.file is not None: # -P was supplied, so do something with the file # if no argument to -P was given, it will be 'data' > Another question I have it how can I output a docstring right from the > parser.add_option() block? I prefer to define all option-related > things in the same block once. I'd like to output the help value from > the block, or append it to a report. > > Here's example from my Ruby wrapper for Ruby's optparse: I don't understand what you want here (and I don't understand the Ruby code). Can you try explaining what you're trying to do here a different way? STeVe From davisn90210 at gmail.com Tue Nov 13 21:51:09 2007 From: davisn90210 at gmail.com (davisn90210 at gmail.com) Date: Wed, 14 Nov 2007 02:51:09 -0000 Subject: Arrays In-Reply-To: <1195004202.383567@www.vif.com> References: <1194917023.976618@www.vif.com><13jk6af1vs5g89@corp.supernews.com> <1195004202.383567@www.vif.com> Message-ID: <1195008669.562425.66420@22g2000hsm.googlegroups.com> Modules contain objects. When you want to import a specific set of objects contained in a module into the local namespace, you use: from import For example: from math import sqrt from math import sin, cos If you want to import everything from a module, use: from import * For example: from math import * If you want to import a module as an entity itself, use: import For example: import math #Use, for example, math.sqrt to call the sqrt function You can also use import ... as ... to "rename" an imported object: import math as m #Now use m.sqrt instead of math.sqrt from math import sqrt as square_root #sqrt is now bound to square_root in the local module In the array module, there is an object named array. You could access using: import array array.array or from array import array array or from array import array as foobar foobar or ... The way you choose to actually do this is up to you. Most people just decide what they like/makes the most sense. In the math module, there is no object called math. That is why we do not use >>> from math import math Traceback (most recent call last): File "", line 1, in ImportError: cannot import name math --Nathan Davis On Nov 13, 7:25 pm, "Gordon C" wrote: > OK Steve, But why do we say "from array import array" and NOT "from math > import math"? Why the difference in syntax? > Gord > > "Steven D'Aprano" wrote in message > > news:13jk6af1vs5g89 at corp.supernews.com... > > > On Tue, 13 Nov 2007 11:26:28 -0500, Gordon C wrote: > > >> OK, thanks to all. The key statement is "from array import array" which > >> is not exactly intuitive! > > > "The only intuitive interface is the nipple. After that, it's all > > learned." -- Bruce Ediger on user interfaces. > > > Once you've been using Python for a while, using import becomes as > > intuitive as a spoon. The only tricky part is knowing *which* module to > > import. But, honestly, are you surprised to learn that the array type is > > held in in the array module? > > > -- > > Steven. From maxim.novak at gmail.com Fri Nov 9 16:06:09 2007 From: maxim.novak at gmail.com (maxim.novak at gmail.com) Date: Fri, 09 Nov 2007 21:06:09 -0000 Subject: Binary search tree Message-ID: <1194642369.914779.152960@57g2000hsv.googlegroups.com> Hi, I have to get list of URLs one by one and to find the URLs that I have more than one time(can't be more than twice). I thought to put them into binary search tree, this way they'll be sorted and I'll be able to check if the URL already exist. Couldn't find any python library that implements trees. Is there some library of this kind in python? Or can I find it somewhere else? From davisn90210 at gmail.com Tue Nov 20 13:04:22 2007 From: davisn90210 at gmail.com (davisn90210 at gmail.com) Date: Tue, 20 Nov 2007 10:04:22 -0800 (PST) Subject: Web update library in python? References: Message-ID: <0314ba1e-5d03-4bcc-8e23-6bb7b1d2e711@d50g2000hsf.googlegroups.com> On Nov 20, 8:48 am, "Jorgen Bodde" wrote: > Hi Paul, > > Like I said, I do not want to limit my end users into installing > something in Apache or some other solution in order to get my tool > working. On the end user side (which also are the people who are > creating the repositories for others) there must be no burden > whatsoever. Your thoughts are interesting though, I will have to look > into that. > Bazaar does not require Apache or anything particular server-side. In other words, you can distribute repositories from any plain-old web- server. It is also written in python, so there is no reason you couldn't bundle it with your client-side app (with hacks, if necessary). And it has pretty good support for merging, etc. It even has a GUI. See http://bazaar-vcs.org/ for more details. --Nathan Davis From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Nov 30 06:26:48 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 30 Nov 2007 12:26:48 +0100 Subject: Witch editor to use! In-Reply-To: <16b8f26b-f780-4eaf-a295-8c27de1965fc@d4g2000prg.googlegroups.com> References: <2b6a7153-d9ad-4ac0-acf0-4b5a39318d74@e10g2000prf.googlegroups.com> <16b8f26b-f780-4eaf-a295-8c27de1965fc@d4g2000prg.googlegroups.com> Message-ID: <474ff35f$0$31345$426a34cc@news.free.fr> Carl Banks a ?crit : > On Nov 30, 4:40 am, Ant wrote: >> On Nov 30, 9:10 am, SMALLp wrote: (snip) >>> And if editor is bether choice witch one to use! >> One with a spell checker would be a good start. > > Punny. indeed !-) From timr at probo.com Sat Nov 3 18:51:05 2007 From: timr at probo.com (Tim Roberts) Date: Sat, 03 Nov 2007 22:51:05 GMT Subject: python at command prompt References: <1193933820.086265.19100@57g2000hsv.googlegroups.com> Message-ID: <9nupi3lula431c9ee9svvtkib5igjfvalf@4ax.com> Ton van Vliet wrote: > >There's could also be an issue with entering 'python' at the command >line, and not 'python.exe'. Once the PATH is setup correctly, try to >enter 'python.exe', and check whether that works. > >IMHO, to get any 'program-name' (without the .exe extension) to work, >one needs to: >1. register the executable with windows (doesn't work for python) or >2. make sure the the PATHEXT environment variable is set correctly, >and includes the .EXE extension (on my w2k system it looks like: >.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH) You're confusing two things here. Executables (.exe) are always available, and do not need to be registered to be run without the extension. It is possible to have Windows execute "abc.py" when you type "abc", and that DOES require registering the .py extension and adding .py to the PATHEXT environment variable. A very useful thing to do, by the way. I have many command line tools for which I have forgotten whether they are batch files, small executables, or Python scripts. And that's how it should be. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From antroy at gmail.com Thu Nov 1 09:42:34 2007 From: antroy at gmail.com (Ant) Date: Thu, 01 Nov 2007 06:42:34 -0700 Subject: What is Jython? In-Reply-To: <1193923400.063743.233670@50g2000hsm.googlegroups.com> References: <1193900068.263686.174020@v23g2000prn.googlegroups.com> <1193906235.560348.226380@v3g2000hsg.googlegroups.com> <1193917020.873344.252710@y42g2000hsy.googlegroups.com> <1193923400.063743.233670@50g2000hsm.googlegroups.com> Message-ID: <1193924554.461034.286950@57g2000hsv.googlegroups.com> On Nov 1, 1:23 pm, Ant wrote: > On Nov 1, 11:37 am, Ze'ev wrote: > ... > > > ...> Jython is currently significantly slower than Python. > > > ... > > Not according to this :http://blogs.warwick.ac.uk/dwatkins/entry/benchmarking_parallel_pytho... >... > So that's parallel processing and mathematical processing that seems > faster in Jython. It's be interesting to see a proper comparison of > how different types of program run. Simple rexex processing of a large log file on the other hand was 10x faster in Python than Jython, so I guess it depends on what you want to achieve. -- Ant From kw at codebykevin.com Wed Nov 14 14:16:11 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Wed, 14 Nov 2007 14:16:11 -0500 Subject: Building python packages for the correct architecture on OSX 10.5 In-Reply-To: <1195061700.315152.61070@22g2000hsm.googlegroups.com> References: <1195061700.315152.61070@22g2000hsm.googlegroups.com> Message-ID: <473B497B.3030402@codebykevin.com> Arnaud Delobelle wrote: > Hi fellow python enthusiasts. > > Having recently acquired a MacBook Pro (Intel Core 2 Duo) which comes > with python2.5, I have been installing some modules that I need (PIL, > psycopg2, PyXML ...). > > The problem is that [$python setup.py build] compiles all the binaries > to universal files for i386 and ppc32, but not x86_64 or ppc64. It > does not appear to be a problem when running scripts from the shell > (as python seems to run as a 32 bits problems), but it is a problem > from apache2/mod_python as the included apache2 runs as 64 bits > processes. > > This means the modules need to be compiles for at least both i386 and > x86_64 in my case. I have been looking at the setup.py files of > various modules but I cannot see a suitable way to indicate what > architectures I want them compiled for. So far, I have managed by > adding the following lines in setup.py just after the Extension class > is imported: > > OrigExtension = Extension > def Extension(*args, **kwargs): > extra_args = ['-arch', 'ppc', '-arch', 'ppc64', > '-arch', 'i386', '-arch', 'x86_64 '] > kwargs['extra_compile_args'] = extra_args + > kwargs.get('extra_compile_args', []) > kwargs['extra_link_args'] = extra_args + > kwargs.get('extra_link_args', []) > return OrigExtension(*args, **kwargs) > > > Obviously this is a dirty hack, and I would like to know how to do > this the right way. How can this be done better? > > -- > Arnaud > You may want to post this on the MacPython list--there are plenty of experts there on building Python mudles for OS X. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From steve at REMOVE-THIS-cybersource.com.au Wed Nov 21 17:34:16 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Wed, 21 Nov 2007 22:34:16 -0000 Subject: Clean way to get one's network IP address? References: Message-ID: <13k9cj8f6055naa@corp.supernews.com> On Wed, 21 Nov 2007 12:00:52 -0500, Joe Riopel wrote: > On Nov 21, 2007 10:15 AM, Gilles Ganault wrote: >> I know about socket.gethostbyname, but this relies on what's in >> /etc/hosts, and I'd rather have a more independent solution. > > I might be missing something in your question, but on a Windows XP > machine, I can get the IP address of my machine using: >>>> from socket import gethostname, gethostbyname >>>> gethostbyname(gethostname()) > '192.168.0.11' >>>> Just out of curiosity, what part of the Original Poster's comment that he already knew about socket.gethostbyname did you not understand? -- Steven who seems to be making a lot of snarky comments lately. From nick-news at net4u.hr Sun Nov 25 15:40:57 2007 From: nick-news at net4u.hr (Nikola Skoric) Date: Sun, 25 Nov 2007 20:40:57 +0000 (UTC) Subject: win32serviceutil won't start Message-ID: I have a very simple win32serviceutil script: import win32serviceutil, time win32serviceutil.StartService("burek", "localhost") time.sleep(10) exit() It successfuly imports win32serviceutil, and chokes on StartService: Traceback (most recent call last): File "foobar.py", line 3, in ? win32serviceutil.StartService("burek", "localhost") File "C:\Python24\Lib\site-packages\win32\lib\win32serviceutil.py", line 399, in StartService hs = SmartOpenService(hscm, serviceName, win32service.SERVICE_ALL_ACCESS) File "C:\Python24\Lib\site-packages\win32\lib\win32serviceutil.py", line 76, in SmartOpenService return win32service.OpenService(hscm, name, access) pywintypes.error: (1060, 'OpenService', 'The specified service does not exist as an installed service.') What does that mean? -- "Now the storm has passed over me I'm left to drift on a dead calm sea And watch her forever through the cracks in the beams Nailed across the doorways of the bedrooms of my dreams" From kyosohma at gmail.com Fri Nov 23 09:52:03 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Fri, 23 Nov 2007 06:52:03 -0800 (PST) Subject: /usr/local/lib/python25.zip References: Message-ID: <76b30295-dc24-4e04-9e14-6ad26c6e46b7@y43g2000hsy.googlegroups.com> On Nov 23, 12:05 am, ebzzry wrote: > I'm trying to run an application and I got this: > > % meld > Traceback (most recent call last): > File "/usr/local/bin/meld", line 73, in > pygtk.require("2.0") > File "/usr/local/lib/python2.5/site-packages/pygtk.py", line 47, in > require > versions = _get_available_versions() > File "/usr/local/lib/python2.5/site-packages/pygtk.py", line 34, in > _get_available_versions > for filename in os.listdir(dir): > OSError: [Errno 2] No such file or directory: '/usr/local/lib/ > python25.zip' > > What went wrong? How can I fix this? > > Thanks in advance. > > P.S. By the way, how can I make my name appear instead of "ebzzry" at > the top? It sounds like you it's looking for Python in the wrong place or you need to upgrade your pygtk package. Alas...I don't know how to make my name appear either. I have a feeling it requires using a real newsgroup reader rather than Google Groups though. Mike From gslindstrom at gmail.com Fri Nov 9 11:52:38 2007 From: gslindstrom at gmail.com (Greg Lindstrom) Date: Fri, 9 Nov 2007 10:52:38 -0600 Subject: PyCon 2008 - Call for Tutorials Message-ID: Still thinking of presenting a tutorial at PyCon 2008 in Chicago? "Tutorial Day" is March 13th offering 1/2 day classes on just about any topic Python. It's a great way to help others in the community learn more about Python and you get paid ($1000.00 cash money + conference registration; not a bad gig!). We have a number of proposals already but want more ideas. The more topics we can offer the better the conference will be for everyone. - Testing - "Intermediate" Python - Working with Databases - Documentation - Object Oriented Python - Web Development - Anything Else (just about) Anything is up for consideration. Pop on over to http://us.pycon.org/2008/tutorials/proposals/ for more information or submit your idea to pycon-tutorials at python.org. Thanks! Greg Lindstrom Tutorial Coordinator, PyCon 2008 (Chicago) -------------- next part -------------- An HTML attachment was scrubbed... URL: From jjl at pobox.com Thu Nov 22 16:31:09 2007 From: jjl at pobox.com (John J. Lee) Date: Thu, 22 Nov 2007 21:31:09 GMT Subject: trace module and doctest References: Message-ID: <87ve7unf1e.fsf@pobox.com> skip at pobox.com writes: > I am trying to use the trace module with the --count flag to test for > statement coverage in my doctests. The trace coverage listing is very > weird, marking many statements as unexecuted which were clearly executed > during the run (I can see their output on the screen). Is this some known > interaction between the trace and doctest modules? Yes: http://python-nose.googlecode.com/svn/trunk/nose/plugins/doctests.py http://svn.zope.org/Zope3/trunk/src/zope/testing/doctest.py?rev=28679&r1=28703&r2=28705 John From bdesth.quelquechose at free.quelquepart.fr Mon Nov 26 15:42:34 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 26 Nov 2007 21:42:34 +0100 Subject: Need to call functions/class_methods etc using string ref :How In-Reply-To: References: <9a63e8920711260237u223abc66x1cb6d6cee3492bfa@mail.gmail.com> <20071126155840.GA5180@sdf.lonestar.org> <474b18e2$0$20133$426a74cc@news.free.fr> Message-ID: <474b2fd4$0$30685$426a74cc@news.free.fr> Donn Ingle a ?crit : >>target = >>for funcname in funclist: >>func = getattr(target, funcname, None) >>if callable(func): >>func(*args, **kwargs) > > Nice. 'callable' is new to me. What about getattr, then ?-) And FWIW, callable will disappear in py3k... (anyway, you can just test if the object has a __call__ method). From pydecker at gmail.com Fri Nov 30 08:18:21 2007 From: pydecker at gmail.com (Peter Decker) Date: Fri, 30 Nov 2007 08:18:21 -0500 Subject: Oh no, my code is being published ... help! In-Reply-To: <89avk3tfjhqoppagt0mi4njolvpbe9lu6m@4ax.com> References: <49adb113-bbaa-4d9f-b3f6-9300d563f2f8@d4g2000prg.googlegroups.com> <89avk3tfjhqoppagt0mi4njolvpbe9lu6m@4ax.com> Message-ID: On Nov 30, 2007 1:19 AM, Tim Roberts wrote: > You also have a couple of instances of: > print("Error Squeezing %s...") > > The parentheses serve no purpose here, and are unidiomatic. I thought that with the eventual dropping of 'print' as a statement in Python 3, that writing it this way (as if it were a print function) is preferred, since that will be one fewer thing to convert. -- # p.d. From trivik at gmail.com Mon Nov 19 01:32:12 2007 From: trivik at gmail.com (saccade) Date: Sun, 18 Nov 2007 22:32:12 -0800 (PST) Subject: newbie Q: sequence membership References: <8a934485-efd4-4e89-ac1b-d7c277978686@l22g2000hsc.googlegroups.com> Message-ID: <17880eed-b3c1-4d77-854a-cf8e24a56746@w73g2000hsf.googlegroups.com> On Nov 17, 3:40 am, "Gabriel Genellina" wrote: > > You can write your own membership test based on identity ('is'): > Thank you for the practical (usable) advice and explanation of the '==' operator. On Nov 17, 4:35 am, John Machin wrote: > > And that can be done by reading the fine manual, specifically > This is true. I was being lazy by posting but have been pleasantly surprised by the detailed responses. For the most, Python's beautiful syntax has thus far required minimal thought of me. Programs feel more like pseudo code than code and I may have gotten carried away. On Nov 17, 4:35 am, John Machin wrote: > > Worse: Consider z = ['A1', 'Z9']. It's highly likely that when x == > 'A1', "x is_in z" is True -- because an unguaranteed implementation- > dependent caper caches or "interns" some values, so that x and z[0] > are the same object. Try explaining that to the novices!! > I am not a programmer so I feel odd commenting about language design decisions. When my Prof. introduced python the first question that popped into mind was that since "x=9; y=9; print x is y and x == y" prints "True" is there a way to change the value of 9? He said that was silly but after class showed me that statements "True = []" work but suggested it was harmless and not quite a bug. So if I am permitted to think of integers as immutable objects with predefined labels (i.e. the integers used in the text of the program code) that cannot de or re referenced then what a similar treatment of characters will look like seams to be an arbitary (a design) decition. In this vein it seams reasonable to expect 'a'[0] and 'ba'[1] to refer to the same object. If one follows the convention used with integers (9 and 9 refer to the same object) then 'ab' and 'ab' would be the same. An equally reasonable assumption would be that 'ab' and 'ab' are two different sequences and so not equal (I do not see the problem here). Actually this is what you said is left up to the implementation. '==' seams to add a lot of power but I am not sure where or how (except as a shortcut in the very special case of strings). Pardon the babble. On Nov 17, 4:35 am, John Machin wrote: > > Do you have a use case for that? > I have a list of lists and want to see if another list is a member of it. The content of the lists and the way they are related to each other changes from program to program. From deliverable at gmail.com Thu Nov 22 08:09:55 2007 From: deliverable at gmail.com (braver) Date: Thu, 22 Nov 2007 05:09:55 -0800 (PST) Subject: eof References: <92a2c0c9-e6a1-4344-aeac-830940200f20@t47g2000hsc.googlegroups.com> <79i9k35vs76cqgqnino7dj3ql623us3euq@4ax.com> <6c04c760-6cf1-4715-9ec9-30f43ebaa01f@d27g2000prf.googlegroups.com> Message-ID: On Nov 22, 3:26 pm, Duncan Booth wrote: > This sounds like a case for writing a generator. Try this one: [...] Thanks, Duncan! Really cool & useful. And yield is the Ruby way, too! (Wayne -- :P). Cheers, Alexy From gert.cuykens at gmail.com Fri Nov 2 09:18:32 2007 From: gert.cuykens at gmail.com (gert) Date: Fri, 02 Nov 2007 13:18:32 -0000 Subject: MySQLdb.string_literal In-Reply-To: References: <1194006273.383109.97910@o80g2000hse.googlegroups.com> Message-ID: <1194009512.412427.240500@v3g2000hsg.googlegroups.com> On Nov 2, 1:48 pm, Carsten Haese wrote: > On Fri, 2007-11-02 at 12:24 +0000, gert wrote: > > I want to escape binary data so i can insert data into a blob > > No, you don't want to escape binary data. You want to bind it to a > parametrized query: > > http://informixdb.blogspot.com/2007/07/filling-in-blanks.html > > Keep in mind, though, that MySQLdb uses %s as parameter markers instead > of the SQL standard question mark. ok thx, this is one of those questions i wished i asked way sooner. From kilbyfan at aoldotcom Wed Nov 14 14:43:27 2007 From: kilbyfan at aoldotcom (just bob) Date: Wed, 14 Nov 2007 11:43:27 -0800 Subject: SPAM References: <1195065929.848318.25100@i13g2000prf.googlegroups.com> <473b46c3$0$79945$742ec2ed@news.sonic.net> Message-ID: <473b4fdf$0$79951$742ec2ed@news.sonic.net> "John Bean" wrote in message news:uajmj398b7bscocruik918hlc0khvfn3st at 4ax.com... > On Wed, 14 Nov 2007 11:04:35 -0800, "just bob" > wrote: > >> > > Your SPAM appears to be non-existent. Vapourware. Not real. > > Shame, I fancied a Spam fritter. > The guy gets Google dollars when people view the site or click on links, me thinks. It's spam. From bborcic at gmail.com Thu Nov 22 08:12:52 2007 From: bborcic at gmail.com (Boris Borcic) Date: Thu, 22 Nov 2007 14:12:52 +0100 Subject: eof In-Reply-To: References: <92a2c0c9-e6a1-4344-aeac-830940200f20@t47g2000hsc.googlegroups.com> <79i9k35vs76cqgqnino7dj3ql623us3euq@4ax.com> <6c04c760-6cf1-4715-9ec9-30f43ebaa01f@d27g2000prf.googlegroups.com> Message-ID: Duncan Booth wrote: > import itertools > def chunks(f, size): > iterator = iter(f) > def onechunk(line): > yield line > for line in itertools.islice(iterator, size-1): > yield line > for line in iterator: > yield onechunk(line) Quite simpler, and provides chunk# as well :) def chunked(chunksize,f) : from itertools import count,groupby counter=count(chunksize).next return groupby(f,lambda _ : counter()/chunksize) > > for chunk in chunks(open('chunks.py'), 3): > for n, line in enumerate(chunk): > print "%d:%s" % (n,line.rstrip()) > print "---------------" > print "done" > #eof > ------ end chunks.py -------- > > Ths output when you run this is: > > C:\Temp>chunks.py > 0:import itertools > 1:def chunks(f, size): > 2: iterator = iter(f) > --------------- > 0: def onechunk(line): > 1: yield line > 2: for line in itertools.islice(iterator, size-1): > --------------- > 0: yield line > 1: for line in iterator: > 2: yield onechunk(line) > --------------- > 0: > 1:for chunk in chunks(open('chunks.py'), 3): > 2: for n, line in enumerate(chunk): > --------------- > 0: print "%d:%s" % (n,line.rstrip()) > 1: print "---------------" > 2:print "done" > --------------- > 0:#eof > --------------- > done > > Or change it to do: > > for chunk in chunks(enumerate(open('chunks.py')), 3): > for n, line in chunk: > > and you get all lines numbered from 0 to 15 instead of resetting the > count each chunk. From python.list at tim.thechases.com Thu Nov 1 14:23:53 2007 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 01 Nov 2007 13:23:53 -0500 Subject: python at command prompt In-Reply-To: <1193936330.775959.155720@d55g2000hsg.googlegroups.com> References: <1193933820.086265.19100@57g2000hsv.googlegroups.com> <1193936330.775959.155720@d55g2000hsg.googlegroups.com> Message-ID: <472A19B9.1000504@tim.thechases.com> >> [1]http://www.imladris.com/Scripts/PythonForWindows.html > > I set the pythonpath to where the python interpreter is located C: > \Python24 > However I still get the same error message. Is there something else > that must be configured? Make sure you're setting your PATH, not your PYTHONPATH variable. From your command-prompt, issue c:\test\> path to see what your current path is. You _should_ see your python2.x\bin folder in there. If not, are you re-using the same command-prompt window? I vaguely remember that it requires you to close the cmd window and open a new one to pick up the new environment-variable changes. Alternatively, if you don't want to lose history in that particular window, you can update your path for that particular window using c:\test\> set path=%PATH%;c:\progra~1\python2.4\bin or whatever your path is. -tkc From upton at virginia.edu Fri Nov 30 11:27:45 2007 From: upton at virginia.edu (Dan Upton) Date: Fri, 30 Nov 2007 11:27:45 -0500 Subject: "Python" is not a good name, should rename to "Athon" In-Reply-To: <47503780.5030500@mattnordhoff.com> References: <13l0bhjkh4noi0e@corp.supernews.com> <475031EE.2020600@tim.thechases.com> <47503780.5030500@mattnordhoff.com> Message-ID: <5504f9ac0711300827l29a1714h7230606f5a02cd7e@mail.gmail.com> On Nov 30, 2007 11:17 AM, Matt Nordhoff wrote: > Tim Chase wrote: > > (You'd think this was the Lisp ML, not Python... ) > > Atsp? :-) > -- Athp? Wait, no, Microsoft already claimed that one... From riquito at gmail.com Thu Nov 22 06:33:40 2007 From: riquito at gmail.com (riquito at gmail.com) Date: Thu, 22 Nov 2007 03:33:40 -0800 (PST) Subject: Problems with if/elif statement syntax References: <4d58211e-ebe8-40fe-80ae-cf8b4a56f9ec@d21g2000prf.googlegroups.com> Message-ID: On 22 Nov, 12:09, Neil Webster wrote: > Hi all, > > I'm sure I'm doing something wrong but after lots of searching and > reading I can't work it out and was wondering if anybody can help? > > I've got the following block of code: > if a >= 20 and a < 100: > if c == "c": > radius = 500 > else: > radius = 250 > elif (a >= 100) and (a < 500): > radius = 500 > elif (a >= 500) and (a < 1000): > radius = 1000 > elif (a >= 1000) and (a < 3000): > radius = 1500 > elif (a >= 3000) and (a < 5000): > radius = 2000 > else: > radius = 4000 > > No matter what value goes in for 'a' the radius always comes out as > 4000. > > What am I doing wrong? > > Cheers > > Neil as Oliver pointed out, check if you're not compairing "a" as a string I wanted to let you know that you can write the above conditions in a more natural way, using the a Message-ID: On Nov 18, 6:46 am, Abandoned wrote: > Hi.. > I want to show the pictures with mod python directly. > > def showimage(req): > some process... > open /var/www/a.jpg and print > > for example if i open: > domain.com/a.py/showimage > It must show me image directly (no redirect or html) > > How can i do it ? > I'm sorry for my bad english. > Kind Regards.... How about: def showimage(req): req.content_type="image/jpeg" # Change to you image type req.sendfile("/path/to/image.jpg") return apache.OK HTH BTW mod_python has its own list :) -- Arnaud From Afro.Systems at gmail.com Thu Nov 22 11:11:18 2007 From: Afro.Systems at gmail.com (Tzury Bar Yochay) Date: Thu, 22 Nov 2007 08:11:18 -0800 (PST) Subject: 100% CPU Usage when a tcp client is disconnected References: <2aae621c-35e7-48a5-9121-ca2446a0ee04@y43g2000hsy.googlegroups.com> <87y7cqthkt.fsf@mulj.homelinux.net> Message-ID: Thank Hrvoje as well From horpner at yahoo.com Fri Nov 30 10:01:19 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Fri, 30 Nov 2007 15:01:19 GMT Subject: Oh no, my code is being published ... help! References: <49adb113-bbaa-4d9f-b3f6-9300d563f2f8@d4g2000prg.googlegroups.com> <89avk3tfjhqoppagt0mi4njolvpbe9lu6m@4ax.com> Message-ID: On 2007-11-30, Eduardo O. Padoan wrote: > On Nov 30, 2007 11:18 AM, Peter Decker wrote: >> On Nov 30, 2007 1:19 AM, Tim Roberts wrote: >> >> > You also have a couple of instances of: >> > print("Error Squeezing %s...") >> > >> > The parentheses serve no purpose here, and are unidiomatic. >> >> I thought that with the eventual dropping of 'print' as a >> statement in Python 3, that writing it this way (as if it were >> a print function) is preferred, since that will be one fewer >> thing to convert. > > No, writing this way will confound the 2to3 tool. Just try for > yourself. You would have to write print(something) all the time > and disable the fix_print convertion. It is easier and safer to > write the common 2.Xish way and let 2to3 do the work. Output ought be centralized to support maintenance, solving the 3.0 compatibility problem as a side-effect. So the above would be something like: my_print("Error Squeezing %s..." % the_thingy) With my_print defined appropriately for the time and place. Moreover, publishing code today with print(...) will, at best, require a needless digression. -- Neil Cerutti From z.darkmere at gmail.com Thu Nov 22 13:47:20 2007 From: z.darkmere at gmail.com (Federico Ceccatto) Date: Thu, 22 Nov 2007 15:47:20 -0300 Subject: Subprocess and 16-bit FORTRAN Message-ID: Hello, For the past year I've been building an XP Python/wxPython shell of sorts for several dozen command line FORTRAN tools developed for various material science problems. Given how the methods and how-to's have been lost to everyone but the original creators for these 80's to 90's pieces of code and the fact I am no physicist, I've relied on the subprocess module in order to feed info according to their output. I/O in general has worked wonders up to a handful of applications that act in the strangest of ways. I strongly believe it's a bug in the original programs/compiler, but that gets me nowhere. There's also the fact the error shows up in two tools compiled with different FORTRAN versions and made by different authors. I'll probably go cry for help in a FORTRAN forum too. Can't quite paste code due to its size and threaded nature, but basically I have the output PIPE rigged to a class that parses text into a tidy list (for easier analyzing), and a function that returns input characters to the stdin method of the subprocess object according to wether there has been any new data from stdout and certain conditions (specific to the executable) are met. I've got prints and repr()s everywhere to check nothing is ignored, written multiple times or the child process is reporting errors. As I mentioned, it works wonders for several other executables. None of the obvious errors seem to be the case. As far as I can tell, the input/output is ideal until the misbehaviour described below rears its ugly head. This is the kind of 'bugs' i've run into, perhaps someone could shed some light onto them? - Sometimes execution of child process (in this case, NTVDM.exe and its children) stops and the object is destroyed for no reason whatsoever. Very silent, no errors. - Sometimes '\x03' as input is ignored, working simply as a '\n' of sorts, while most of the time it simply kills the program as expected. - Sometimes specific points in the code where the user is asked for input and execution should be temporarily halted are ignored, as if somehow it got a newline character. None of these bugs are reproducible by running the same child processess via NTVDM.exe through say, cmd.exe and such. This has been driving me nuts for the last three weeks... Thanks for your time. - F. From pavlovevidence at gmail.com Mon Nov 26 18:56:16 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 26 Nov 2007 15:56:16 -0800 (PST) Subject: Should proxy objects lie about their class name? References: <87lk8szlnm.fsf@pobox.com> Message-ID: On Nov 20, 3:50 pm, j... at pobox.com (John J. Lee) wrote: > Not much to add to the subject line. I mean something like this: > > ProxyClass.__name__ = ProxiedClass.__name__ > > I've been told that this is common practice. Is it? Would this > surprise you if you ran into it in a debugging session? > > One very real advantage that I can see is avoiding breaking existing > doctests. > > Thanks in advance for your views Python 3.0 has a proposal, accepted I believe, to allow classes to control the behavior of issubclass and ininstance, so there appears to be tacit support from the language for mimicking the proxied classes in such ways. I guess for me it would be a judgment call on based how tight I wanted the proxy class to be--is it being the class, or is it just standing in? Carl Banks From exarkun at divmod.com Thu Nov 29 18:17:03 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 29 Nov 2007 18:17:03 -0500 Subject: Embedding Python - Passing by Reference In-Reply-To: <6ef0cabb-5a41-4095-9654-c82cc39bdbe1@e23g2000prf.googlegroups.com> Message-ID: <20071129231703.8162.731403674.divmod.quotient.41352@ohm> On Thu, 29 Nov 2007 14:39:52 -0800 (PST), andy at britishideas.com wrote: >I understand the parameters to Python functions are passed by >reference: > >def foo(a): > a = a + 1 > >Will change the value of a in the calling function. How do I implement >the equivalent in C when extending Python? You misunderstand how parameters are passed in Python: >>> x = 10 >>> def foo(y): ... y = y + 1 ... >>> foo(x) >>> x 10 >>> So there's no behavior here to attempt to emulate when embedding or extending. Jean-Paul From khemkaamit at gmail.com Thu Nov 1 08:11:38 2007 From: khemkaamit at gmail.com (Amit Khemka) Date: Thu, 1 Nov 2007 17:41:38 +0530 Subject: Which persistence is for me? In-Reply-To: References: Message-ID: <1360b7230711010511i1f481048ta6a8c49c752dd5bf@mail.gmail.com> On 11/1/07, Neal Becker wrote: > I need to organize the results of some experiments. Seems some sort of > database is in order. > > I just took a look at DBAPI and the new sqlite interface in python2.5. I > have no experience with sql. I am repulsed by e.g.: > c.execute("""insert into stocks > values ('2006-01-05','BUY','RHAT',100,35.14)""") > > ewww. How unpythonic. I don't want to use a string to specify what > function to execute. I want to call a function (c.insert?). > > Is there some other interface/database that I might like better? Why you can always look at some "pure" database solutions. If persistence is all you require, have a look at "anydbm" and or "shelve" modules . Cheers, -- -- Amit Khemka From nick-news at net4u.hr Fri Nov 2 10:52:41 2007 From: nick-news at net4u.hr (Nikola Skoric) Date: Fri, 2 Nov 2007 14:52:41 +0000 (UTC) Subject: http client using ssh -D Message-ID: Is there a python library which supports using SOCKS proxy which I create by "ssh -D port remote-host"? I was trying to use that socket by SocksiPy, but I get "channel 3: open failed: administratively prohibited: open failed" on the server side. And I can use that channel freely with firefox. Any other library I might use? -- "Now the storm has passed over me I'm left to drift on a dead calm sea And watch her forever through the cracks in the beams Nailed across the doorways of the bedrooms of my dreams" From arnodel at googlemail.com Sun Nov 18 07:42:13 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 18 Nov 2007 04:42:13 -0800 (PST) Subject: A proposal for attribute lookup failures References: <0eb5426d-3eea-4b8a-93d5-a3b22ff8032a@f3g2000hsg.googlegroups.com> Message-ID: <46b6a6e8-d88c-49f9-ac62-f938a1275172@f3g2000hsg.googlegroups.com> On Nov 18, 4:07 am, MonkeeSage wrote: > Proposal: > > When an attribute lookup fails for an object, check the top-level > (and local scope?) for a corresponding function or attribute and apply > it as the called attribute if found, drop through to the exception > otherwise. This is just syntactic sugar. [...] > Benefits: [...] > - Backwards compatible; one can use the top-level functions when > desired. No change to existing code required. It changes how the following code executes: -------------------------- def foo(x): return x.foo() foo(1) -------------------------- * currently this raises AttributeError * under your proposal this code would fill the stack and raise a RuntimeError I guess. > - Seemingly trivial to implement (though I don't know much C). On > attribute lookup failure, simply iterate the symbol table looking for > a match, otherwise raise the exception (like current implementation). This is not a benefit! -- Arnaud From kay.schluehr at gmx.net Sun Nov 18 18:59:49 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sun, 18 Nov 2007 15:59:49 -0800 (PST) Subject: A proposal for attribute lookup failures References: <0eb5426d-3eea-4b8a-93d5-a3b22ff8032a@f3g2000hsg.googlegroups.com> <46b6a6e8-d88c-49f9-ac62-f938a1275172@f3g2000hsg.googlegroups.com> <2e1247b4-8cd2-4004-8efc-6fbe797985ae@f3g2000hsg.googlegroups.com> Message-ID: <57ddf35c-b22a-40ea-88ab-be2ee9e32572@c30g2000hsa.googlegroups.com> On 19 Nov., 00:02, MonkeeSage wrote: > Ps. Just for kicks, here is a simple ruby 1.8 mock-up of the proposal > (sorry for using ruby, but I don't know enough C to start hacking the > CPython backend; I think that a higher-level example is conceptually > clearer anyhow). No need to excuse. I think Ruby provides a nice context for discussing the semantics of top level "open classes". But I think those are entirely different than your contextual bindings. Note I find your proposal somewhat confusing since I expect that an attribute is "owned" by an object and is not an arbitrary contextual property. Regarding open classes in Python, what about "extension classes"? class +object: def len(self): return self.__len__() This either adds the len method to the namespace of object or it creates a new namespace which is associated with the namespace of object s.t. each object can lookup attributes in this namespace when default lookup fails. I'm not entirely sure about scope. I think the lifetime of an extension class shall be determined by the lifetime of the extended class and not by the scope in which the extension class is defined. What do you think? Kay PS. you can use EasyExtend when you want to provide a language extension without hacking the CPython runtime. EE was made for such kinds of experiments. From BjornSteinarFjeldPettersen at gmail.com Mon Nov 12 03:28:12 2007 From: BjornSteinarFjeldPettersen at gmail.com (thebjorn) Date: Mon, 12 Nov 2007 08:28:12 -0000 Subject: python - an eggs... In-Reply-To: References: <5ppfp0Frv6obU1@mid.uni-berlin.de> Message-ID: <1194856092.721358.175430@o38g2000hse.googlegroups.com> On Nov 12, 1:12 am, "bruce" wrote: > Hi Diez... > > I've never used setuptools, (it's not on the box) and i don't have > easy_install tools installed... In the link you were given there is a section titled "Installing setuptools". I'm reading it aloud for you now... -- bjorn From paul.nospam at rudin.co.uk Wed Nov 21 06:48:47 2007 From: paul.nospam at rudin.co.uk (Paul Rudin) Date: Wed, 21 Nov 2007 11:48:47 +0000 Subject: logging and propagation References: <7eef67e0-36a7-48b6-9137-0b10ea37ac3c@f3g2000hsg.googlegroups.com> Message-ID: <87zlx7om3k.fsf@rudin.co.uk> oj writes: > Hi, > > I want to setup logging with two loggers: > > The child logger is used when something different needs to be done > with the log record, and the log record will propagate and be logged > by the root logger as usual. > > However, there are certain times when I don't want a log record to > propagate from the child to the parent. > > I don't really want to add a filter to the root logger, as it should > be up to the child whether the record propagates or not. > > I've tried setting the child to a lower level then the parent, but if > a record is dealt with by the child, the parent deals with it anyway > regardless of its own log level. > > Also, filters only apply particular handlers and do not affect > propagation. > > Can anyone suggest a simple way to achieve this? > > Currently, the only thing I can think of, is overriding the > callHandlers method in a custom Logger class. Loggers have a "propagate" attribute. If you set this to False in the child then you should get what you want I think. From devraj at gmail.com Fri Nov 2 06:15:25 2007 From: devraj at gmail.com (Devraj) Date: Fri, 02 Nov 2007 10:15:25 -0000 Subject: Writing GTK UI for Python apps in XUL Message-ID: <1193998525.923252.48490@i38g2000prf.googlegroups.com> Hi everyone, Is it possible to write UI code in XUL for a GTK Python application? I found NuFox, which does the reverse (lets me write Python to generate XUL) Thanks. From ullrich at math.okstate.edu Sun Nov 4 08:27:10 2007 From: ullrich at math.okstate.edu (David C. Ullrich) Date: Sun, 04 Nov 2007 07:27:10 -0600 Subject: (MAC) CoreGraphics module??? References: <22uki39arp3a83topaimrka4s37uo1okm5@4ax.com> Message-ID: On Fri, 02 Nov 2007 14:09:25 -0500, Robert Kern wrote: >David C. Ullrich wrote: >> [???] > >Okay, which version of OS X do you have? In 10.3 and 10.4 it used to be here: >/System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/plat-mac/CoreGraphics.py > >I notice that in 10.5, it no longer exists, though. Um, surely that doesn't mean that there's no CoreGraphics available in 10.5? >>[...] > >For scripts executed from the terminal, you could start them with a hash-bang line: > > #!/usr/bin/python > >Use "chmod u+x" on the script, and then you can execute it like any other >program from the terminal. Sure enough: As I suspected yesterday morning, the reason that didn't work the first time I tried it is that I'd already "corrected" the import statement to Carbon.CoreGraphics. When I put it back the way it's supposed to be everything's great. Such a happy camper - I now have a pdf consisting of a blank white page with one red circle in the middle! Something I've always wanted - thanks. ************************ David C. Ullrich From nulla.epistola at web.de Wed Nov 21 15:11:59 2007 From: nulla.epistola at web.de (Hertha Steck) Date: Wed, 21 Nov 2007 21:11:59 +0100 Subject: import pysqlite2 or import sqlite3? References: Message-ID: Hertha Steck wrote: > Hello, > > I'm using Python 2.5.1, Pysqlite 2.3.5 and SQLite 3.4.1 on Gentoo Linux. > I've always imported pysqlite using > > from pysqlite2 import dbapi2 > > and that works. If I try > > import sqlite3 > > I get > > Traceback (most recent call last): > File "", line 1, in > File "/usr/lib/python2.5/sqlite3/__init__.py", line 24, in > from dbapi2 import * > File "/usr/lib/python2.5/sqlite3/dbapi2.py", line 27, in > from _sqlite3 import * > ImportError: No module named _sqlite3 > > And I thought that's normal, there is no Python module called sqlite3. > After a second look at the error message: when I installed Gentoo, Python 2.4 was installed, I got the new version a little later. And I think I installed Pysqlite 2.3.5 separately. Python 2.5 comes with pysqlite - should I uninstall my version? From bdesth.quelquechose at free.quelquepart.fr Sun Nov 4 11:13:18 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 04 Nov 2007 17:13:18 +0100 Subject: python newbie In-Reply-To: <7xabpvkn0n.fsf@ruckus.brouhaha.com> References: <472b2b84$0$13761$6e1ede2f@read.cnntp.org> <5p0s6vFp47k9U1@mid.individual.net> <472b5251$0$6238$426a34cc@news.free.fr> <13ioa6f6t797gce@corp.supernews.com> <7x4pg3wks5.fsf@ruckus.brouhaha.com> <7x8x5f83u5.fsf@ruckus.brouhaha.com> <1194126214.238480.254180@57g2000hsv.googlegroups.com> <7xabpvkn0n.fsf@ruckus.brouhaha.com> Message-ID: <472defc8$0$30484$426a74cc@news.free.fr> Paul Rubin a ?crit : > Paul Hankin writes: > >>I'm intrigued - when would you want a callable module? > > > I think it would be nice to be able to say > > import StringIO > buf = StringIO('hello') > > instead of > > import StringIO > buf = StringIO.StringIO('hello') What's wrong with: from StringIO import StringIO buf = StringIO('hello') ??? From tjreedy at udel.edu Thu Nov 22 14:42:29 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 22 Nov 2007 14:42:29 -0500 Subject: Research-oriented Python mailing list? References: <14092.39489.qm@web32708.mail.mud.yahoo.com> Message-ID: "Albert-jan Roskam" wrote in message news:14092.39489.qm at web32708.mail.mud.yahoo.com... | Hi again, | | One more Q: I was wondering if there exists a more | research-oriented Python listserv. This one is good | (or so it seems, I'm just a newbie!), but the topics | are very broad. Suggestions, anyone? gmane.org presents technical mailing lists in newsgroup format. gmane.comp.python.* has over 200 entries. From steve at REMOVE-THIS-cybersource.com.au Fri Nov 16 15:51:11 2007 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Fri, 16 Nov 2007 20:51:11 -0000 Subject: Resolving declaring class of a method at runtime References: <13jpd9ek4ss4qc2@corp.supernews.com> Message-ID: <13js0lvf64v719b@corp.supernews.com> On Fri, 16 Nov 2007 19:02:25 +0200, Janne H?rk?nen wrote: >> X is an "old style" class. Most people probably shouldn't use old style >> classes, for various reasons. To use new style classes, you inherit >> from object: > > I am also aware of old and new style classes, this was the fastest way > to type it in console Ah, an optimization huh? So, by saving 1/2 a second by not typing "(object)" in your example code, the consequences are that I wasted my time explaining that you should use new style classes, and you wasted your time reading and responding to my explanation, and now I'm wasting my time *again* telling you off for wasting my time in the first place. There should be a term for "optimization" techniques that actually slow things down instead of speeding them up. -- Steven. From aaron.watters at gmail.com Fri Nov 2 09:04:04 2007 From: aaron.watters at gmail.com (Aaron Watters) Date: Fri, 02 Nov 2007 13:04:04 -0000 Subject: marshal vs pickle In-Reply-To: <7xlk9htisx.fsf@ruckus.brouhaha.com> References: <1193949315.556471.72530@o80g2000hse.googlegroups.com> <1193951706.592622.49260@o38g2000hse.googlegroups.com> <7xlk9htisx.fsf@ruckus.brouhaha.com> Message-ID: <1194008644.451840.101790@z9g2000hsf.googlegroups.com> On Nov 1, 11:42 pm, Paul Rubin wrote: > Aaron Watters writes: > > > >>> marshal.loads('RKp,U\xf7`\xef\xe77\xc1\xea\xd8\xec\xbe\\') > > > Segmentation fault > > >... > > I'll grant you the above as a denial of service attack. ... > > Can you give me an example > > where someone can erase the filesystem using marshal.load? > > You should always assume that if an attacker can induce a memory fault > (typically through a buffer overflow) then s/he can inject and run > arbitrary machine code ... Yes yes yes, but this takes an extraordinary amount of skill and criminal malice. With pickle an innocent person on another continent could potentially delete all the files on your computer by accident. In summary my view is this. - pickle is way too complicated and not worth the extra overhead and danger in most cases. - marshal is an excellent tool for getting large amounts of data in and out of Python that can be much faster than pickle and is always much less dangerous than pickle. I think it's safe enough for most RPC uses, for example. - It's a damn shame that the Python developers can't be bothered to make marshal portable across platforms and versions. It's a silly mistake. Sorry for all the fuss. -- Aaron Watters === http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=limiting+perl From duncan.booth at invalid.invalid Fri Nov 9 09:34:48 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 9 Nov 2007 14:34:48 GMT Subject: Some "pythonic" suggestions for Python References: <5PGdnWmWZIdZ967anZ2dnUVZ_uuqnZ2d@cavtel.net> <13j76merr3an4d0@corp.supernews.com> Message-ID: Frank Samuelson wrote: >> It's also not clear how you expect this to work with anything more >> complex than a single expression. How do you handle statements and >> multiple returns? > > >> def foo(x, y): >> L = [] >> try: >> if x[y] % 2: >> print x, y >> return y >> return x[y] >> except: >> return None > > Huh? This is trivial. I don't see why this is so hard to grasp. > > foo= function(x, y): > L = [] > try: > if x[y] % 2: > print x, y > return y > return x[y] > except: > return None > It is hard to grasp because you said you wanted: name = function(*argument_list) expression There is no colon in your proposed syntax, and you only asked for a single expression in the function rather than a suite. Your 'this is trivial' response seems to be proposing another syntax entirely. Unfortunately my crystal ball is away being cleaned, so I am unable to guess whether you meant for a function definition to be an expression (opening up a whole host of questions about how you nest it inside other expressions) or a special case of an assignment to a single name and wanted to disallow such things as: foo = l[3] = function(): pass or if you didn't mean to disallow them, what name should that function have. If you are going to make syntax proposals you must be precise. From bborcic at gmail.com Thu Nov 1 10:33:03 2007 From: bborcic at gmail.com (Boris Borcic) Date: Thu, 01 Nov 2007 15:33:03 +0100 Subject: permuting over nested dicts? In-Reply-To: References: Message-ID: <4729e3d5$1_1@news.bluewin.ch> Christian Meesters wrote: > Hoi, > > I have the following data structure (of variable size actually, to make > things simple, just that one): > d = {'a': {'x':[1,2,3], 'y':[4,5,6]}, > 'b': {'x':[7,8,9], 'y':[10,11,12]}} > This can be read as a dict of possibilities: The entities 'a' and 'b' have > the parameters 'x' and 'y', each. And d['a']['x'] can be either 1 or 2 or > 3. Does anybody know a convenient (and fast) way to permute over all > possible nested dicts like > {'a': {'x':1, 'y':4}, > 'b': {'x':7, 'y':10}} > and > {'a': {'x':2, 'y':4}, > 'b': {'x':7, 'y':10}} > and so forth? > > Any link or snippet is appreciated. > > TIA > Christian def cases(d) : import re bits = re.split('(\[.*?\])',repr(d)) vv = [('_%s' % k, ' for _%s in %s' % (k,v)) for k,v in enumerate(bits[1::2])] expr = [p+v for p,(v,_) in zip(bits[::2],vv)]+bits[-1:]+[v for _,v in vv] return eval('(%s)' % ''.join(expr)) for t in cases({'a': {'x':[1,2,3], 'y':[4,5,6]}, 'b': {'x':[7,8,9], 'y':[10,11,12]}}) : print t {'a': {'y': 4, 'x': 1}, 'b': {'y': 10, 'x': 7}} {'a': {'y': 4, 'x': 1}, 'b': {'y': 10, 'x': 8}} {'a': {'y': 4, 'x': 1}, 'b': {'y': 10, 'x': 9}} {'a': {'y': 4, 'x': 1}, 'b': {'y': 11, 'x': 7}} {'a': {'y': 4, 'x': 1}, 'b': {'y': 11, 'x': 8}} {'a': {'y': 4, 'x': 1}, 'b': {'y': 11, 'x': 9}} {'a': {'y': 4, 'x': 1}, 'b': {'y': 12, 'x': 7}} {'a': {'y': 4, 'x': 1}, 'b': {'y': 12, 'x': 8}} {'a': {'y': 4, 'x': 1}, 'b': {'y': 12, 'x': 9}} {'a': {'y': 4, 'x': 2}, 'b': {'y': 10, 'x': 7}} Caveats : (1) assert eval(repr(d))==d (2) no square bracket in either keys or values From deliverable at gmail.com Thu Nov 22 04:22:39 2007 From: deliverable at gmail.com (braver) Date: Thu, 22 Nov 2007 01:22:39 -0800 (PST) Subject: eof References: <92a2c0c9-e6a1-4344-aeac-830940200f20@t47g2000hsc.googlegroups.com> <79i9k35vs76cqgqnino7dj3ql623us3euq@4ax.com> <6c04c760-6cf1-4715-9ec9-30f43ebaa01f@d27g2000prf.googlegroups.com> Message-ID: <062a9497-7626-440a-93eb-b897e6dec01f@p69g2000hsa.googlegroups.com> On Nov 22, 10:37 am, Wayne Brehaut wrote: > As others have already pointed out, "because it's seldom necessary in Python". You know what? I've read this many times, and it's a lot of self- congratulation. There's lot of things which can be useful in Python. This lack of EOF is inconvenient, there's nothing "Python way" about it, as a simple search on "EOF" or "eof" in this group demonstrates. Just a few threads: http://groups.google.com/group/comp.lang.python/browse_thread/thread/ed25388487b3ac7b Here folks fight the same problem in one way uglier than another. Iterators and whatnot are thrown at a poor li'l EOF: http://groups.google.com/group/comp.lang.python/browse_thread/thread/b09d612e99f67561 The recurrence of the question simply shows Python lacks an f.eof() method. That's all! Why do we may need it? The last thread shows clearly -- because the last line processing is often a special case. After I couldn't find the f.eof() in Python docs, I've quickly changed the logic to this (extracts): filesize = os.stat(filename)[6] cur_size = 0 def eof(): return cur_size == filesize def add_line(line): self.cur_size += len(line) ... if eof(): print >>sys.stderr, "* * * eof * * *" Basically, it allows me to write what I want, and it's natural to ask for eof() in this case -- and for a language to provide it. Ruby has all iterators-schmiterators you want and a kitchen sink, yet provides the said eof() without much fuss and 100 threads on c.l.*. :) > "Python is not Ruby." Both Python and Ruby happily agree here: >> "Python" == "Ruby" => false In [11]: "Python" == "Ruby" Out[11]: False There's nothing special about Python except indentation, which gets screwed up between editors all the time. (It's much easier to flip- flop between TextMate and Emacs with Ruby than with Python, without setting your tabs and spaces pedantically.) It's faster than Ruby, otherwise they're similar. When Ruby X.Y gets faster, it'll be a tough call to between 'em. I use Python to accomplish things I know how, with algorithms which work and proven control logic, so this is reasonable to ask about certain control flow equivalents. And comparisons will always be good. :) Cheers, Alexy From deets at nospam.web.de Wed Nov 7 05:11:05 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 07 Nov 2007 11:11:05 +0100 Subject: Strange behavior of __get__ in a descriptor in IPython References: Message-ID: <5pdh9pFqqdk9U1@mid.uni-berlin.de> Jakub Hegenbart wrote: > Hi, > > I'm studying the descriptor protocol and its usage from the following > document: > > http://users.rcn.com/python/download/Descriptor.htm > > There is some sample code: > > http://users.rcn.com/python/download/Descriptor.htm#descriptor-example > > that behaves in a different way on my machine than the example suggests: > > In [2]: a=MyClass() > > In [3]: a.x > Retrieving var "x" > Retrieving var "x" > Out[3]: 1 > > On the other hand, in the 'plain' Python shell, it's invoked only once as > expected: > >>>> a=desc.MyClass() >>>> a.x > Retrieving var "x" > 10 >>>> > > Should I take as granted that IPython might in some cases access an > attribute > of an object more than once even in face of side effects, or is this a > bug? I'm not sure, but you could try and set up a counter that counts the number of accesses. But to be honest: I don't think it's a bug - this is one hell of an essential part of python, not working here would cause all kinds of troubles. Instead, I presume the printing/shell-part of IPython is responsible. Diez From ganesh.borse at credit-suisse.com Wed Nov 14 04:48:41 2007 From: ganesh.borse at credit-suisse.com (Borse, Ganesh) Date: Wed, 14 Nov 2007 17:48:41 +0800 Subject: How to use the evaluate the code object returned by PyParser_Simp leParseString function? Message-ID: Hi, Can someone please help me in the following question? On the web page http://olympus.het.brown.edu/cgi-bin/info2www?(python2.3-api)Very+High+Level+Layer, I got the following information: `struct _node* PyParser_SimpleParseString(char *str, int start)' Parse Python source code from STR using the start token START. The result can be used to create a code object which can be evaluated efficiently. This is useful if a code fragment must be evaluated many times. I have exactly same requirement. I have dynamic expressions loaded from database at startup in my C++ application. I want to parse these expressions at startup & keep the parsed (compiled) code in memory of this application. Then at runtime, I want to evaluate all this parsed code. This has to be very efficient. So, which function should be used for evaluating the parsed code generated by PyParser_SimpleParseString? Do I need to use the "struct _node*" returned by PyParser_SimpleParseString? Any example of this use would be more helpful? Thanks in advance for guidance & help. Warm Regards, Ganesh ============================================================================== Please access the attached hyperlink for an important electronic communications disclaimer: http://www.credit-suisse.com/legal/en/disclaimer_email_ib.html ============================================================================== From davisn90210 at gmail.com Mon Nov 12 23:30:56 2007 From: davisn90210 at gmail.com (davisn90210 at gmail.com) Date: Tue, 13 Nov 2007 04:30:56 -0000 Subject: persisting data within a module In-Reply-To: References: Message-ID: <1194928256.144154.231650@o38g2000hse.googlegroups.com> On Nov 12, 5:30 pm, "Peter J. Bismuti" wrote: > I'm having trouble understanding how namespaces work in modules. I want to > execute a module within the interpreter and then have values that are > calculated persist so that other modules that get executed can retrieve them. > Modules retain state their state across all imports in the same interpreter instance. Module state is not shared among different instances of the interpreter. > For example, consider the two simple modules below. The first method fails > and I'm not sure exactly why. (Note: assume one instance of an interpreter. > In my case a 3rd party software tool that starts an interpreter when it > launches). > > Two alternate ways of running it: > > 1. (FAILS: RESULTS A = 0) Use the module "test" itself as the driver using > the conditional statement if (__name__=="__main__"): > > test.py > run2.py > Ok, what do you mean by this? Do you mean run test.py and then run run2.py? In so, then you will have *two* instances -- one for each file being executed. You can only have one main module per interpreter instance. I suspect this is the source of your confusion. > or, > > 2. (SUCCES: RESULTS A = 10) Use "run.py" as the driver. > > run.py > > _________test.py__________________ > > import sys,os > > A = 0 > > def getA(): > global A > return A > > def run(): > global A > A = 10 > > if (__name__=="__main__"): > run() > Here, A is only initialized when the module is loaded iff it is the main module. If it's not the main module, then it will have A set to 0 until some other code calls run(). > _________run.py__________________ > > import test > > test.run() > print "A = " + str(test.getA()) > This code calls test.run(), which is necessary for A to be 10. > _________run2.py__________________ > > import test > > print "A = " + str(test.getA()) > > -- > This code gets the value of test.A without calling test.run(). Since test.run() was not called, A is the value it was initialized when the test module was loaded -- namely, 0. Hope this helps, --Nathan Davis From python.list at tim.thechases.com Mon Nov 5 10:57:15 2007 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 05 Nov 2007 09:57:15 -0600 Subject: Python thinks file is empty In-Reply-To: <1194275982.617384.57430@57g2000hsv.googlegroups.com> References: <1194275982.617384.57430@57g2000hsv.googlegroups.com> Message-ID: <472F3D5B.1000007@tim.thechases.com> loial wrote: > I am writing a file in python with writelines > > f = open('/home/john/myfile',"w") > f.writelines("line1\n") > f.writelines("line2\n") > f.close() > > But whenever I try to do anything with the file in python it finds no > data. I am trying ftp, copying the file...the resultant file is always > 0 bytes, although if I look at the original file on the unix command > line, its fine > > e.g. > > shutil.copyfile('/home/john/myfile', '/home/john/myfile2') > > Any ideas what the problem is? A failure to copy/paste the lines as you had them? Or perhaps accessing the file before it's been closed/flushed? Or perhaps you're opening it in write-mode after you've closed the file (thus overwriting your content with a blank file)? As shown in the below session, it works for me: #################################### tchase at agix2:~/tmp$ python Python 2.4.4 (#2, Apr 5 2007, 20:11:18) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> f = open('test.txt', 'w') >>> f.writelines('hello\n') >>> f.writelines('world\n') >>> f.close() >>> import shutil >>> shutil.copyfile('test.txt', 'test2.txt') >>> tchase at agix2:~/tmp$ cat test.txt hello world tchase at agix2:~/tmp$ cat test2.txt hello world ##################################### You may also want to use f.write() rather than f.writelines() which seems to be your usage. f.writelines() is used for writing an iterable of strings. Thus, it would be used something like this trivial example: f.writelines(['hello\n', 'world\n']) To confuse matters, it happens to work in your example, because a string is an iterable that returns each character in that string as the result, so code like this f.writelines('hello\n') is effectively doing something like this f.write('h') f.write('e') f.write('l') f.write('l') f.write('o') f.write('\n') (unless writelines is optimized to smarten up the code here) -tkc From mail at timgolden.me.uk Fri Nov 23 08:58:29 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 23 Nov 2007 13:58:29 +0000 Subject: Finding out what other tasks are running In-Reply-To: <4746D7A4.6070902@timgolden.me.uk> References: <4746D7A4.6070902@timgolden.me.uk> Message-ID: <4746DC85.1080106@timgolden.me.uk> Tim Golden wrote: > Jeremy C B Nicoll wrote: >> Is there a cross-platform of determining what other processes (or in Windows >> terms, other applications) are running? >> >> Is it possible in a cross-platform way to ask some other application to shut >> down, wait a while, and then test to see if it did shut? >> >> Failing that are there separate Windows, Mac and Linux/Unix ways of doing >> this? > > Sorry, thought I'd part-answered this a while back; doesn't seem > to have shown up. In short, I don't believe there's anything > truly x-platform... ... or I could eat my words and point you towards Christian Heimes enumprocess package: http://cheeseshop.python.org/pypi/enumprocess TJG From ojeeves at gmail.com Thu Nov 22 14:28:56 2007 From: ojeeves at gmail.com (oj) Date: Thu, 22 Nov 2007 11:28:56 -0800 (PST) Subject: how terminate console(not Ctrl-C) References: Message-ID: On Nov 22, 3:58 am, NoName wrote: > Is it possible to interrupt loop (program) by pressing Q key like Ctrl- > C? > how can i hook user's keypress while program running? > > thnx There's a quite complicated example here: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/203830 But it seems to just boil down to fiddling around with tty, and then using select to read from sys.stdin to detect a keypress, and then taking the appropriate action. This will be different on Windows. If you really need this, it might be worth looking for a library that will make key press detection trivial. For example, this sort of thing is easy with pygame. From python at hope.cz Wed Nov 7 08:37:21 2007 From: python at hope.cz (Johny) Date: Wed, 07 Nov 2007 05:37:21 -0800 Subject: What colour model does the image use in PIL Message-ID: <1194442641.095444.17690@z9g2000hsf.googlegroups.com> I use PIL and with it im.getpixel((x,y)) to find out the colour of a pixel. But how can I find out in which color model the the return value is? For example for png picture format im.getpixel((20,50)) gives the result 60. What does the value mean? Is it possible to find out the RGB model values? Thank you for help. L. From hdante at gmail.com Fri Nov 23 23:43:56 2007 From: hdante at gmail.com (hdante at gmail.com) Date: Fri, 23 Nov 2007 20:43:56 -0800 (PST) Subject: eof References: <92a2c0c9-e6a1-4344-aeac-830940200f20@t47g2000hsc.googlegroups.com> <79i9k35vs76cqgqnino7dj3ql623us3euq@4ax.com> <6c04c760-6cf1-4715-9ec9-30f43ebaa01f@d27g2000prf.googlegroups.com> <062a9497-7626-440a-93eb-b897e6dec01f@p69g2000hsa.googlegroups.com> <9e25e813-f4a7-48c6-9f0e-ef04223e29a0@e23g2000prf.googlegroups.com> <3cb8cff4-4c1d-4ca2-8d21-c012a109351b@w34g2000hsg.googlegroups.com> <80978b7f-da78-4b1b-9400-66efa1421c4d@n20g2000hsh.googlegroups.com> Message-ID: <94db0532-981a-45b6-9af9-ab5eef054fb7@s19g2000prg.googlegroups.com> On Nov 24, 2:24 am, MonkeeSage wrote: > > Actually, to be a bit more technical, IO#eof acts like standard C eof > for File objects, it only blocks / requires a previous read() on > character devices and pipes and such. For files, it's the same as > checking the absolute position of the file stream: f.tell == > File.size(f.path). This is not the same as ISO C. f.tell could be equal to File.size(f.path) and eof could be false. An extra read() is required. > > Regards, > Jordan From gagsl-py2 at yahoo.com.ar Fri Nov 2 00:30:15 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 02 Nov 2007 01:30:15 -0300 Subject: os.readlink returning value References: <1193968274.369843.167520@v3g2000hsg.googlegroups.com> Message-ID: En Thu, 01 Nov 2007 22:51:14 -0300, Giampaolo Rodola' escribi?: > I was reading os.readlink doc which says: > > readlink( path) > > Return a string representing the path to which the symbolic link > points. The result may be either an absolute or relative pathname; if > it is relative, it may be converted to an absolute pathname using > os.path.join(os.path.dirname(path), result). Availability: Macintosh, > Unix. > > > > ...It's not clear to me when the returning result could be absolute > and when it could be relative. > Could someone clarify this point? That depends on how the symlink was created. Assume the current directory is /usr/home/giampaolo/any/dir > ln -s ../foo/bar creates a symbolic link at /usr/home/giampaolo/any/dir/bar pointing to ../foo/bar (relative to where the link resides). That is, actually pointing to /usr/home/giampaolo/any/foo/bar (but this absolute path is NOT stored on the link itself - only ../foo/bar) Now, a program whose current directory is /usr/home/giampaolo executes this: readlink("any/dir/bar") It will return the string "../foo/bar". One must resolve the .. reference relative to where the link resides, NOT relative to the current directory. That is, relative to any/dir. os.path.dirname("any/dir/bar") returns exactly that. Then, the suggested expression in the docs evaluates to "any/dir/../foo/bar" - it's not an absolute pathname yet, one should use abspath() on it. Or instead os.path.join(os.path.abspath(os.path.dirname(path)), result) -- Gabriel Genellina From aaron.watters at gmail.com Tue Nov 27 15:49:35 2007 From: aaron.watters at gmail.com (Aaron Watters) Date: Tue, 27 Nov 2007 12:49:35 -0800 (PST) Subject: How to Teach Python "Variables" References: <4749bb94$1@news.bezeqint.net> <4749c888$0$14869$426a74cc@news.free.fr> <4749cc7c$1@news.bezeqint.net> Message-ID: <7bbc1e48-8f33-4891-9226-c74b190156d0@a39g2000pre.googlegroups.com> On Nov 27, 2:20 pm, MonkeeSage wrote: > On Nov 27, 11:50 am, Donn Cave wrote: .... > I agree with your point, but I think the distinction is this: > pedagogical analogies should be truly *analogous* -- they should not > be "analogies" that are only vaguely similar and require you to > constantly say "...but ignore this difference and that > difference...oh, and that one...you'll learn that later." I personally > think the "ignore this for now" approach is detrimental..... Yes, in theory. And in theory, theory is the same as practice. In practice there is too much to understand all at once and in the beginning you have to say "don't worry about that right now, consider it magic..." Of course they should eventually understand it. Again, this is another place where Python shines, because the front end scary magic is limited -- you can start out with simple and useful imperative straight line scripts and then move into higher levels from there -- in contrast to C# and java which require you to declare a class with static methods even if you have no intention of writing any OO code. Beginners find this incredibly confusing and scary. Magic should never be permanent, however. In the case of Struts or Spring there is magic that no one is ever intended to truly understand. Danger Will Robinson! Danger! This is my problem also with most web application frameworks, even in Python -- too much strange magic floats around in the air -- usually in order to make things "easy" that I never thought were hard in the first place. -- Aaron Watters === http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=lame+hack+wink From aclarke11 at yahoo.co.uk Wed Nov 28 17:45:32 2007 From: aclarke11 at yahoo.co.uk (Tony) Date: Wed, 28 Nov 2007 14:45:32 -0800 (PST) Subject: Control mouse position and clicking References: <4f209559-4454-4f8a-8ba3-18cbb50db094@b40g2000prf.googlegroups.com> <5r654mF135t4eU1@mid.individual.net> Message-ID: On Nov 28, 9:33 pm, Bjoern Schliessmann wrote: snip > > On Mac, IIRC, you can't. > > Regards, well, you can do it from Java, (the Robot class, as I recall), so you should be able to do it in Jython, which is a Python implementation, so.... Tony From dmurray777 at cox.net Thu Nov 29 07:04:34 2007 From: dmurray777 at cox.net (Dave) Date: Thu, 29 Nov 2007 05:04:34 -0700 Subject: Lib for audio? Message-ID: I need to read microphone input and determine frequency. Is there a lib for that? Thanks, Dave From miller.paul.w at gmail.com Tue Nov 27 23:39:56 2007 From: miller.paul.w at gmail.com (miller.paul.w at gmail.com) Date: Tue, 27 Nov 2007 20:39:56 -0800 (PST) Subject: PyMultimethods References: Message-ID: On Nov 27, 7:14 pm, "davisn90... at gmail.com" wrote: > I've written a small project that implements multimethods for python. Interesting. Were you aware of the article Guido wrote on multimethods in python? ( www.artima.com/weblogs/viewpost.jsp?thread=101605 ) Although I'm a decent python programmer and could surely figure it out from the source, a file of example code showing how to use the module is always a good thing. Also, you should consider submitting to pypi if you haven't already ( www.python.org/pypi ). From bernard.chhun at gmail.com Mon Nov 12 20:56:34 2007 From: bernard.chhun at gmail.com (Bernard) Date: Tue, 13 Nov 2007 01:56:34 -0000 Subject: Arrays In-Reply-To: <1194917023.976618@www.vif.com> References: <1194917023.976618@www.vif.com> Message-ID: <1194918994.934367.28860@v3g2000hsg.googlegroups.com> On 12 nov, 20:19, "Gordon C" wrote: > Absolute newbie here. In spite of the Python Software Foundation tutorial's > (http://www.python.org/doc/current/tut/tut.html) use of the array > declaration > array(type[,initializer]), the Python interpreter does NOT accept the word > array! It , presumably, needs to have an import included. Could > some show me how to declare arrays with some basic examples? > Gord. hey Gordon, here's a good reading for you: http://effbot.org/zone/python-list.htm From barronmo at gmail.com Tue Nov 6 16:57:12 2007 From: barronmo at gmail.com (barronmo) Date: Tue, 06 Nov 2007 13:57:12 -0800 Subject: global name is not defined Message-ID: <1194386232.498054.74520@d55g2000hsg.googlegroups.com> I'm getting an error msg I don't understand, "global name EMR_globals is not defined", and could use some help. I've separated the application I'm building into several modules. One of the modules holds variables I need to pass from one module to another and is called 'EMR_globals'. Several other modules hold functions or user menus and then 'EMR_main' controls the initial user interaction. I'm using MySQL to hold the data. The initial connection to the database is done by 'EMR_main'. Functions then define and close a cursor for various queries. The connection variable, 'conn', is defined 'conn = "" ' in EMR_globals and then used in EMR_main. Unfortunately when a module.function attempts to use it I get the error msg. Here is the source of the error, module 'name_lookup': def name_find(namefrag): cursor = EMR_globals.conn.cursor(MySQLdb.cursors.DictCursor) cursor.execute("SELECT patient_ID, firstname, lastname FROM demographics WHERE lastname LIKE '%s%%'" % (namefrag)) results = cursor.fetchall() for index, row in enumerate(results): print "%d %s %s %s" % (index, row["patient_ID"], row["firstname"], row["lastname"]) indx = int(raw_input("Select the record you want: ")) results_list = list(results) a = str(results_list[indx]['patient_ID']) print 'You have chosen patient ID # ' + a cursor.execute("SELECT * FROM demographics WHERE patient_ID = %s" % (a,)) selected_pt = cursor.fetchall() # if this query returns more than one record the following code will fail I think print menus.menu_demographics(selected_pt['firstname'], selected_pt['lastname'], selected_pt['address'], selected_pt['city'], selected_pt['state'], selected_pt['zipcode'], selected_pt['phonenumber']) print menus.menu_pt_record cursor.close() Thanks for any help. Mike From arkanes at gmail.com Thu Nov 1 16:15:34 2007 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 1 Nov 2007 15:15:34 -0500 Subject: Syntax coloring in Python interpreter In-Reply-To: References: <1193939152.721480.140500@22g2000hsm.googlegroups.com> Message-ID: <4866bea60711011315j320cd223la6db0742fbc4ba64@mail.gmail.com> On Nov 1, 2007 3:01 PM, Neil Cerutti wrote: > On 2007-11-01, Lee Capps wrote: > > > > On Nov 1, 2007, at 1:45 PM, braver wrote: > >> Greetings -- as a long time user of both Python and Ruby > >> interpreters, I got used to the latter's syntax-coloring gem, > >> wirble, which colorizes Ruby syntax on the fly. Is there > >> anything similar for Python? > >> > > > > I believe IPython can do this: > > > > http://ipython.scipy.org/moin/ > > IPython's syntax coloring doesn't work with Windows 2000 and up, > since (last I checked) it relies on a readline.py file, which > relies on ANSI.SYS, which is not supported by the Windows > console. > If you scroll down about half a page in the above link you'll find a link to a readline implementation for Windows. > -- > Neil Cerutti > > -- > http://mail.python.org/mailman/listinfo/python-list > From DustanGroups at gmail.com Thu Nov 29 06:49:57 2007 From: DustanGroups at gmail.com (Dustan) Date: Thu, 29 Nov 2007 03:49:57 -0800 (PST) Subject: Tuning question References: Message-ID: <7406fb0e-9dbe-4467-af5b-7dc99755b2d5@p69g2000hsa.googlegroups.com> On Nov 28, 3:15 pm, Wally Lepore wrote: > Hi Graham > > Is this email still good? Not anymore. You just gave it out to millions of spammers on Usenet. > Its been awhile since we spoke last on the tuning list. Are you still on > Yahoo messenger? > Also, what is your email address please. You told me to email you when I had > questions that seemed too basic for the tuning list. Thanks Graham. My > email is soundma... at optonline.net > > Stay well > Walter (Wally) Lepore From godson.g at gmail.com Fri Nov 2 02:15:00 2007 From: godson.g at gmail.com (Godson Gera) Date: Fri, 2 Nov 2007 11:45:00 +0530 Subject: Use of while(1) with app.mainLoop of wxpython In-Reply-To: References: Message-ID: On 11/2/07, tarun wrote: > > Dear All, > > I've have created a GUI (using wxPython widgets) where in I've a message > log window (A TextCtrl window). I've a router.dll that helps me putting in > message onto a channel. In my script that generates the GUI, I want to > continuously poll the channel and populate the messages from the channel to > the message log window. > > For this I've to put a while (1) loop, but when I do this, the GUI > doesn't come up. I see the GUI coming when while(1) is removed. Is there any > issue with usage of app.mainloop and while(1) together. > > Quick help would be really appreciated. > > > Hi Tarun, The best practice to poll things in any GUI application is to use timers provided by the GUI frameworks. All of the GUI frameworks does provide timers, so does wxPython. Look for wx.Timer (also look for wx.CallAfter ) and use it to poll what ever the things you want http://www.wxpython.org/docs/api/wx.Timer-class.html When you use a while(1) loop, the python interpreter enters into an infinite local loop thus GUI events never gets processed. So your case seems be that, the while loop is getting executed before GUI is drawn on screen, it will never show up till the loop exits. And if while(1) is executed after GUI is drawn on screen, it will hangup and will not get updated till the loop exits. So avoid using while loops in your GUI for polling long running tasks . -- Godson Gera, http://godson.auroinfo.com http://godson.in -- Godson Gera, http://godson.auroinfo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From jgardner.jonathangardner.net at gmail.com Thu Nov 1 16:53:39 2007 From: jgardner.jonathangardner.net at gmail.com (Jonathan Gardner) Date: Thu, 01 Nov 2007 20:53:39 -0000 Subject: just a crazy question In-Reply-To: References: Message-ID: <1193950419.202861.5950@y27g2000pre.googlegroups.com> On Nov 1, 7:16 am, Robert LaMarca wrote: > So.. how is Python for memory management? ... > Terrible. If you have a memory-intensive application, use ASM (perhaps C), not Python (or any other high-level language for that matter.) > My plan is to try measuring the memory usage of my python code elements and take a guess as to how it might perform on a cell-system.. . naturally a good idea in any event.. But.. Just thought maybe someone out in Python world would have an idea? > This probably won't work at all as expected. If you wanted to get Python processes to run on the cells, you'd probably need a special interpreter written with that in mind. My memory of how the cell technology works is that there is really a tiny amount of memory in each cell and you need to think at a fundamentally low level to get anything useful done. I'm extremely interested in what you discover, and I'm sure others are well. I'd love to be proven wrong in my assumptions. So keep us posted when you find something interesting or useful. From tim at savaskarsitlari.org Mon Nov 12 13:07:38 2007 From: tim at savaskarsitlari.org (=?UTF-8?B?VGltdcOnaW4gS8SxesSxbGF5?=) Date: Mon, 12 Nov 2007 20:07:38 +0200 Subject: why there is no pythonscript insine web browsers? Message-ID: <4738966A.4070607@savaskarsitlari.org> I'm an old programmer coming from a cobol background and started to learn python. I'm using javasript for web based applications but after I started to learn python, the javascript language started to seem ugly to me. Now I'm wondering why there is java support on web browsers but no python support? there is even a vbscript support inside MS-IE but there is no python support. it would be really nice and easy for me to use python instead of javascript to write those ajax scripts. Please tell me, is there a python substitude for JRE ? From mbac at gpshopper.com Thu Nov 15 16:36:17 2007 From: mbac at gpshopper.com (Michael Bacarella) Date: Thu, 15 Nov 2007 16:36:17 -0500 Subject: Populating a dictionary, fast [SOLVED SOLVED] In-Reply-To: <13jpe355qvtb825@corp.supernews.com> References: <818643.92017.qm@web915.biz.mail.mud.yahoo.com> <47374D00.7080500@gmail.com> <1195051438.889160.137120@50g2000hsm.googlegroups.com> <87fxz8kas6.fsf@mulj.homelinux.net> <13jn10p1r88u19f@corp.supernews.com> <65372cfb-7801-49c8-9363-259dca21adfa@w34g2000hsg.googlegroups.com> <13jpe355qvtb825@corp.supernews.com> Message-ID: <004601c827cf$8e437c00$aaca7400$@com> > On Thu, 15 Nov 2007 15:51:25 -0500, Michael Bacarella wrote: > > > Since some people missed the EUREKA!, here's the executive summary: > > > > Python2.3: about 45 minutes > > Python2.4: about 45 minutes > > Python2.5: about _30 seconds_ > > I'm really happy that upgrading to 2.5 solved the issue for you, but I > get similar behaviour and I'm running 2.5, so it isn't as simple as > that. Maybe some more details about my environment will help. Our fast Python is 2.5, built from source. Our slow Python is 2.3, default installed with the OS, from rpm. # python Python 2.5.1 (r251:54863, May 11 2007, 14:17:21) [GCC 3.4.4 20050721 (Red Hat 3.4.4-2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. # which python /usr/local/bin/python # ls -la /usr/local/bin/python -rwxr-xr-x 2 root root 5312572 Nov 12 12:54 /usr/local/bin/python # md5sum /usr/local/bin/python 5c24e54a6cf5a556e9371325d18bc1fb /usr/local/bin/python # ls -la /usr/bin/python* lrwxrwxrwx 1 root root 9 Nov 12 12:57 /usr/bin/python -> python2 lrwxrwxrwx 1 root root 6 Nov 12 12:57 /usr/bin/python2 -> python2.5 -rwxr-xr-x 1 root root 8344 May 2 2007 /usr/bin/python2.3 lrwxrwxrwx 1 root root 21 Nov 12 12:57 /usr/bin/python2.5 -> /usr/local/bin/python # ls -la /usr/local/src/ | grep Python drwxr-xr-x 19 1000 1000 4096 Nov 12 12:54 Python-2.5.1 -rw-r--r-- 1 root root 9383651 Nov 12 12:51 Python-2.5.1.tar.bz2 # gcc -v Reading specs from /usr/lib/gcc/x86_64-redhat-linux/3.4.4/specs Configured with: ../configure --prefix=/usr --mandir=/usr/share/man --infodir=/usr/share/info --enable-shared --enable-threads=posix --disable-checking --with-system-zlib --enable-__cxa_atexit --disable-libunwind-exceptions --enable-java-awt=gtk --host=x86_64-redhat-linux Thread model: posix gcc version 3.4.4 20050721 (Red Hat 3.4.4-2) # cat /etc/redhat-release CentOS release 4.2 (Final) # uname -a Linux xxx 2.6.9-22.ELsmp #1 SMP Sat Oct 8 21:32:36 BST 2005 x86_64 x86_64 x86_64 GNU/Linux # free total used free shared buffers cached Mem: 7390244 6961440 428804 0 15520 2549732 -/+ buffers/cache: 4396188 2994056 Swap: 2096472 10280 2086192 # cat /proc/cpuinfo processor : 0 vendor_id : AuthenticAMD cpu family : 15 model : 5 model name : AMD Opteron(tm) Processor 246 stepping : 10 cpu MHz : 2009.305 cache size : 1024 KB fpu : yes fpu_exception : yes cpuid level : 1 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 syscall nx mmxext lm 3dnowext 3dnow bogomips : 3981.31 TLB size : 1088 4K pages clflush size : 64 cache_alignment : 64 address sizes : 40 bits physical, 48 bits virtual power management: ts fid vid ttp processor : 1 vendor_id : AuthenticAMD cpu family : 15 model : 5 model name : AMD Opteron(tm) Processor 246 stepping : 10 cpu MHz : 2009.305 cache size : 1024 KB fpu : yes fpu_exception : yes cpuid level : 1 wp : yes flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 syscall nx mmxext lm 3dnowext 3dnow bogomips : 4014.08 TLB size : 1088 4K pages clflush size : 64 cache_alignment : 64 address sizes : 40 bits physical, 48 bits virtual power management: ts fid vid ttp ***** information about Python 2.3 ***** # rpm -qi python Name : python Relocations: (not relocatable) Version : 2.3.4 Vendor: CentOS Release : 14.4 Build Date: Wed 02 May 2007 07:20:29 PM EDT Install Date: Mon 04 Jun 2007 05:48:29 PM EDT Build Host: builder6 Group : Development/Languages Source RPM: python-2.3.4-14.4.src.rpm Size : 21137194 License: PSF - see LICENSE Signature : DSA/SHA1, Sat 05 May 2007 09:33:49 AM EDT, Key ID a53d0bab443e1821 URL : http://www.python.org/ Summary : An interpreted, interactive, object-oriented programming language. Description : Python is an interpreted, interactive, object-oriented programming language often compared to Tcl, Perl, Scheme or Java. Python includes modules, classes, exceptions, very high level dynamic data types and dynamic typing. Python supports interfaces to many system calls and libraries, as well as to various windowing systems (X11, Motif, Tk, Mac and MFC). Programmers can write new built-in modules for Python in C or C++. Python can be used as an extension language for applications that need a programmable interface. This package contains most of the standard Python modules, as well as modules for interfacing to the Tix widget set for Tk and RPM. Note that documentation for Python is provided in the python-docs package. From jzgoda at o2.usun.pl Thu Nov 8 16:09:12 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Thu, 08 Nov 2007 22:09:12 +0100 Subject: Some "pythonic" suggestions for Python In-Reply-To: <5PGdnWmWZIdZ967anZ2dnUVZ_uuqnZ2d@cavtel.net> References: <5PGdnWmWZIdZ967anZ2dnUVZ_uuqnZ2d@cavtel.net> Message-ID: Frank Samuelson pisze: > foo = function(x,y) x+y*2 # Example S language code Ugly. -- Jarek Zgoda http://zgodowie.org/ From paulgeeleher at gmail.com Wed Nov 21 13:16:55 2007 From: paulgeeleher at gmail.com (sophie_newbie) Date: Wed, 21 Nov 2007 10:16:55 -0800 (PST) Subject: Create thumbnail image (jpg/png) of PDF file using Python References: <104837c4-898a-4f67-98ab-37df8ff76f0f@e25g2000prg.googlegroups.com> Message-ID: <9c15c8a2-2250-43d4-9084-e8d3bdab2107@c30g2000hsa.googlegroups.com> On Nov 20, 5:36 pm, sophie_newbie wrote: > Is there any way to do this directly within python? > > If not is there any other good way to achieve it? > > Thanks in advance for any help! I think I've solved this problem using a piece of software called imageMagick. Good stuff so it is. From algotrhythm at gmail.com Fri Nov 16 16:06:31 2007 From: algotrhythm at gmail.com (Alan) Date: Fri, 16 Nov 2007 13:06:31 -0800 (PST) Subject: Resolving declaring class of a method at runtime References: <13jpd9ek4ss4qc2@corp.supernews.com> <13js0lvf64v719b@corp.supernews.com> Message-ID: <09b0219b-1671-46e8-bdca-2cfd68d2fdc7@e1g2000hsh.googlegroups.com> On Nov 16, 8:51 pm, Steven D'Aprano wrote: > There should be a term for "optimization" techniques that actually slow > things down instead of speeding them up. > I belive those are the ones known as "premature optimizations", which sit at the root of all evil -- Alan From amir.helzer at gmail.com Mon Nov 26 19:43:10 2007 From: amir.helzer at gmail.com (helzer) Date: Mon, 26 Nov 2007 16:43:10 -0800 (PST) Subject: Add speller to Python application References: Message-ID: Hi Jarek and Shane, This is just what I need. Thanks, Helzer From jcd at sdf.lonestar.org Fri Nov 30 09:57:41 2007 From: jcd at sdf.lonestar.org (J. Clifford Dyer) Date: Fri, 30 Nov 2007 09:57:41 -0500 Subject: Oh no, my code is being published ... help! In-Reply-To: References: <49adb113-bbaa-4d9f-b3f6-9300d563f2f8@d4g2000prg.googlegroups.com> <89avk3tfjhqoppagt0mi4njolvpbe9lu6m@4ax.com> <87fxyn26um.fsf@mulj.homelinux.net> Message-ID: <20071130145741.GB12755@sdf.lonestar.org> On Fri, Nov 30, 2007 at 12:25:25PM -0200, Eduardo O. Padoan wrote regarding Re: Oh no, my code is being published ... help!: > > On Nov 30, 2007 11:36 AM, Hrvoje Niksic wrote: > > "Eduardo O. Padoan" writes: > > > > > No, writing this way will confound the 2to3 tool. > > > > Why? print("foo") is a perfectly valid Python 2 statement. Maybe > > it's simply a matter of fixing the tool. > > > > print("foo") -> print(("foo")) > And more to the point (2.5) print(foo, bar) != (3.0) print(foo, bar) From robin at alldunn.com Fri Nov 30 18:26:40 2007 From: robin at alldunn.com (Robin Dunn) Date: Fri, 30 Nov 2007 15:26:40 -0800 Subject: ANN: wxPython 2.8.7.1 Message-ID: <47509C30.9000005@alldunn.com> Announcing ---------- The 2.8.7.1 release of wxPython is now available for download at http://wxpython.org/download.php. This release has had some bugs fixed, some minor patches applied, and also incorporates the Google Summer of Code 2007 version of XRCed, and adds the Editra source code editor. Source code is available, as well as binaries for Python 2.3, 2.4 and 2.5, for Windows and Mac, as well some packages for various Linux distributions. A summary of changes is listed below and also at http://wxpython.org/recentchanges.php. NOTE: On Mac OS X 10.5 (Leopard) the Python 2.5 binaries of wxPython expect to be used with the user-installed version of MacPython, not the Apple installed version. A fix for this issue is being worked on for the next release. In the meantime you can either install MacPython 2.5.1 and adjust your paths so that that Python is used, or you can stick with Apple's Python and the wxPython 2.8.4.0 that comes with Leopard. What is wxPython? ----------------- wxPython is a GUI toolkit for the Python programming language. It allows Python programmers to create programs with a robust, highly functional graphical user interface, simply and easily. It is implemented as a Python extension module that wraps the GUI components of the popular wxWidgets cross platform library, which is written in C++. wxPython is a cross-platform toolkit. This means that the same program will usually run on multiple platforms without modifications. Currently supported platforms are 32-bit Microsoft Windows, most Linux or other Unix-like systems using GTK2, and Mac OS X 10.3+, in most cases the native widgets are used on each platform to provide a 100% native look and feel for the application. Changes in 2.8.7.1 ------------------ Applied Patch [ 1783958 ] to use the native renderer for drawing the checkboxes in CheckListCtrlMixin. Incorporated the new version of XRCed. This is the result of a Google Summer of Code 2007 project by Roman Rolinsky, and includes a number of UI enhancements, as well as a mechanism for adding support for new components without needing changes to XRCed itself. These new components can be those supported at the C++ layer of XRC, as well as custom XRC handlers written in Python. See http://wiki.wxpython.org/XRCed_Refactoring_Project wxMac: Fixed wx.BusyInfo so it doesn't steal the activated status from the parent window. (This actually applies to all frames with the wx.FRAME_TOOL_WINDOW style and no decorations.) wxMac: Fixed the lack of painting the area between scrollbars on Leopard. wxMac: Fixed assertion errors dealing with toolbars on Leopard. wxMac: Multiline textcontrols now support attributes for margins and alignement; only a single tab distance can be set though. Added the wx.Image.AdjustChannels method. This function muliplies all 4 channels (red, green, blue, alpha) with a factor (around 1.0). Useful for gamma correction, colour correction and to add a certain amount of transparency to a image. Added Editra to the distribution, to give us a simple yet powerful programmer's code editor to replace the never finished PyAlaMode editor and related tools. Many thanks to Cody Precord for the work he has done on this tool and for allowing us to make it part of wxPython. Editra has syntax highlighting and other support for over 40 programming languages, excellent OS X integration, is extendable via plugins, and for those that are on the VI side of the fence there is a VI emulation mode. For more information see the Editra website at http://editra.org/ wxGTK: wx.Frame.ShowFullScreen now preserves the menubar's accelerators. wxGTK: wx.GetClientDisplayRect fixed. Applied patch [1838043], which adds a demo of the wx.RendererNative class functionality. Applied patch [1837449], which uses wx.RenderNative for drawing the combo button in the PopupControl. Added GetDirItemData to wx.GenericDirCtrl, which returns a reference to the data object associated with an item in the control. (Patch #1836326) -- Robin Dunn Software Craftsman http://wxPython.org Java give you jitters? Relax with wxPython! From samwyse at gmail.com Sun Nov 25 08:28:20 2007 From: samwyse at gmail.com (samwyse) Date: Sun, 25 Nov 2007 05:28:20 -0800 (PST) Subject: the annoying, verbose self References: <3c954a31-9fb9-4c0f-b784-cef9ee057ca6@g30g2000hsb.googlegroups.com> <4068d518-cba9-4eac-bd91-11f676c17b3d@w34g2000hsg.googlegroups.com> <5qq6quF10jrh5U2@mid.uni-berlin.de> <5qqoslF10jrh5U6@mid.uni-berlin.de> Message-ID: On Nov 24, 1:10 pm, "Patrick Mullen" wrote: > If there were a "using" or if the with statement would handle > something like this, I wouldn't use it. "s." is only 2 characters. I > saw chained dots mentioned. Chained dots are 2 characters. Why are > we still discussing this? "s." is the answer, or pulling the > attributes into local vars if you are going to use them many times, to > save lookup. This is not a band-aid, this is an actual valid > programming technique. There is more to programming than typing... Actually, the chained dots are solving a completely different problem, that of refactoring a collection of functions that use global vars into a class. Although I'm now wondering if I could jigger something together using globals() to make a top-level self-like object. Hmmm, maybe someting like this: >>> class GlobalSelf(object): def __init__(self): self.__dict__ = globals() >>> x = 42 >>> def myfunc(*args): "something that I may want to refactor later" s = GlobalSelf() s.x += 1 >>> x 42 >>> myfunc() >>> x 43 From donn.ingle at gmail.com Mon Nov 26 05:52:23 2007 From: donn.ingle at gmail.com (Donn Ingle) Date: Mon, 26 Nov 2007 12:52:23 +0200 Subject: Need to call functions/class_methods etc using string ref :How References: <9a63e8920711260237u223abc66x1cb6d6cee3492bfa@mail.gmail.com> Message-ID: Well, I don't know all the answers, but you can start here: def boobs(): print "Oohh little birds!" b="boobs" >>>eval(b)() Ohhh little birds! Naturally, eval is going to run anything... Even code to format your drive. HTH \d From sergio.correia at gmail.com Fri Nov 16 19:12:01 2007 From: sergio.correia at gmail.com (Sergio Correia) Date: Fri, 16 Nov 2007 19:12:01 -0500 Subject: Fwd: Sorting Countries by Region In-Reply-To: <0ed483f8-da41-479f-bd39-6b8155d7a7a3@e4g2000hsg.googlegroups.com> References: <4375355d-b23e-4a1c-8f4b-183156a163c5@f13g2000hsa.googlegroups.com> <0ed483f8-da41-479f-bd39-6b8155d7a7a3@e4g2000hsg.googlegroups.com> Message-ID: About the sort: Check this (also on http://pastebin.com/f12b5b6ca ) def make_regions(): # Values you provided EU = ["Austria","Belgium", "Cyprus","Czech Republic", "Denmark","Estonia", "Finland"] NA = ["Canada", "United States"] AP = ["Australia", "China", "Hong Kong", "India", "Indonesia", "Japan"] regions = {'European Union':EU, 'North America':NA, 'Asia Pacific':AP} ans = {} for reg_name, reg in regions.items(): for cou in reg: ans[cou] = reg_name return ans def cmp_region(cou1, cou2): ans = cmp(regions[cou1], regions[cou2]) if ans: # If the region is the same, sort by country return cmp(cou1, cou2) else: return ans regions = make_regions() some_countries = ['Austria', 'Canada', 'China', 'India'] print 'Old:', some_countries some_countries.sort(cmp_region) print 'New:', some_countries Why that code? Because the first thing I want is a dictionary where the key is the name of the country and the value is the region. Then, I just make a quick function that compares considering the region and country. Finally, I sort. Btw, the code is just a quick hack, as it can be improved -a lot-. About the rest of your code: - martyw's example is much more useful than you think. Why? because you can just iterate across your document, adding the values you get to the adequate object property. That is, instead of using size or pop, use the variables you are interested in. Best, and good luck with python, Sergio On Nov 16, 2007 5:15 PM, wrote: > Great, this is very helpful. I'm new to Python, so hence the > inefficient or nonsensical code! > > > > > 2) I would suggest using countries.sort(...) or sorted(countries,...), > > specifying cmp or key options too sort by region instead. > > > > I don't understand how to do this. The countries.sort() lists > alphabetically and I tried to do a lambda x,y: cmp() type function, > but it doesn't sort correctly. Help with that? > > For martyw's example, I don't need to get any sort of population > info. I'm actually getting the number of various types of documents. > So the entry is like this: > > Argentina Food and Consumer Products Food Additives Color > Additives 1 > Argentina Food and Consumer Products Food Additives Flavors 1 > Argentina Food and Consumer Products Food Additives > General 6 > Argentina Food and Consumer Products Food Additives labeling 1 > Argentina Food and Consumer Products Food Additives Prohibited > Additives 1 > Argentina Food and Consumer Products Food Contact Cellulose 1 > Argentina Food and Consumer Products Food Contact Food > Packaging 1 > Argentina Food and Consumer Products Food Contact Plastics 4 > Argentina Food and Consumer Products Food Contact > Waxes 1 > Belize > etc... > > So I'll need to add up all the entries for Food Additives and Food > contacts, the other info like Color Additives isn't important. > > So I will have an output like this > Food Additives Food Contact > Argentina 10 7 > Belize > etc... > > Thanks so much for the help! > -- > > http://mail.python.org/mailman/listinfo/python-list > From khemkaamit at gmail.com Wed Nov 7 01:37:27 2007 From: khemkaamit at gmail.com (Amit Khemka) Date: Wed, 7 Nov 2007 12:07:27 +0530 Subject: manually cutting a picture In-Reply-To: References: Message-ID: <1360b7230711062237q2d0b39ap6bc5109bfcadffd3@mail.gmail.com> On 11/6/07, Joseph king wrote: > I have a kinda hard question.... i am trying to build a jigsaw game with > python, i would like to give the option for people to create there own > puzzle piece.... does anyone know how to accomplish this it is becoming > increasingly difficult for me Disclaimer: I don't know how helpful I am being here. I have no experience with jigsaw puzzles programming, but the problem seemed interesting enough to give it a thought. I think given an image (may be user provided) you want to cut it in N (user input) pieces. Here is an idea: Cut image by "m X m" grid (bigger the m, the more varied shapes you would be able to generate), this will give you m*m square pieces. With each piece store a vector which represents the polygon (say by storing co-ordinates of the corners). Now visualize this set of pieces as a graph with an edge between adjacent pieces. Now depending on the final number of pieces that you want to generate (N), you traverse the graph and for each node: 1. "Merge" a node with a randomly selected neighbor Repeat step 1 until you have N pieces left Notes: 1. ''merge" operations can be optimized calculating a factor "m*m/N" and doing all merges together. 2. You can also maintain a 'size' attribute with each piece, so that all the pieces generated are of approximately same size. Please let me know if you have other ideas. Cheers, -- -- Amit Khemka From arkanes at gmail.com Mon Nov 19 10:57:58 2007 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 19 Nov 2007 09:57:58 -0600 Subject: Python too complex ?!?!?! In-Reply-To: References: <7hC%i.28332$mv3.17248@newsfe10.phx> Message-ID: <4866bea60711190757l584ae13ke2e6ac5257ef75e0@mail.gmail.com> On Nov 19, 2007 8:52 AM, wrote: > > On Nov 17, 7:46 am, Brian wrote: > > Had a unsettling conversation with a CS instructor that > > teaches at local high schools and the community > > college. This person is a long-term Linux/C/Python > > programmer, but he claims that the install, config, and > > library models for C# have proved to be less > > problematic than Python. So both his courses (intro, > > data structs, algorithms) are taught in C#. > > > > I am a low-end (3-year) journeyman Pythonista, and I > > was attracted to the language because of its > > simplicity. And I have come to enjoy the richness of > > available libraries. > > > > Many of the good people of this NG may be 'too close' > > to answer, but has Python, as a general devel platform, > > lost its simplicity ? Is library install too complex > > and unreliable ? Will my dog go to heaven ? > > If this professor was only using Windows for his environment, then I > might be able to understand his argument better. There are many more > external modules for Python that don't have Windows installers than > there are with binaries. And I've had more than my fair share of > broken setup.py files. > > On the other hand, if all that is needed are the standard libraries, > than it's a breeze to install Python since they're all included. > > Mike > These modules exist, but aren't that common. Certainly anything you're likely to be using in an introductory compsci course is well packaged. And even if it's not, it's really not that hard to create packages or installers - a days work of course prep would take care of the potential problem. From bj_666 at gmx.net Wed Nov 14 06:28:22 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 14 Nov 2007 11:28:22 GMT Subject: Using Python To Change The World :) References: <1195009751.327435.182540@i13g2000prf.googlegroups.com> <5pvvc4FtkgvgU1@mid.uni-berlin.de> Message-ID: <5q04elFsvfksU2@mid.uni-berlin.de> On Wed, 14 Nov 2007 11:01:40 +0100, Diez B. Roggisch wrote: > dominiquevalentine at gmail.com wrote: > >> Hello, I'm a teen trying to do my part in improving the world, and me >> and my pal came up with some concepts to improve the transportation >> system. > > [?] > > Of course if you want to have more or less realistic imaging for whatever > purpose, 3D is the way to go. If you are after traffic-simulations, it's > unneeded complexity. Not if their solution includes flying buses and taxis. Or this pneumatic delivery system for people from `Futurama`. ;-) Ciao, Marc 'BlackJack' Rintsch From cjw at sympatico.ca Sun Nov 25 09:16:01 2007 From: cjw at sympatico.ca (Colin J. Williams) Date: Sun, 25 Nov 2007 09:16:01 -0500 Subject: the annoying, verbose self In-Reply-To: References: <3c954a31-9fb9-4c0f-b784-cef9ee057ca6@g30g2000hsb.googlegroups.com> <6f67fccf-fbec-4c75-baea-5d0277e07883@w40g2000hsb.googlegroups.com> <47458D4E.5030302@sympatico.ca> <13keq168fnu9328@corp.supernews.com> Message-ID: <474983A1.4000102@sympatico.ca> Andrew Koenig wrote: > "Colin J. Williams" wrote in message > news:mailman.1557.1195995738.13605.python-list at python.org... > >> Alternatively, as someone else suggested, an analogue of the Pascal "with" >> could be used: >> >> def abs(self): >> with self: >> return math.sqrt(x**2 + y**2 + z**2) > > How does your suggested "with" statement know to transform x into self.x but > not transform math.sqrt into self.math.sqrt? > > I am not advocating this, but this could be: def abs(self): with self: with math: return sqrt(x**2 + y**2 + z**2) The idea being that "with self" use creates a new namespace: newGlobal= oldGlobal + oldLocal newLocal= names from self Similarly, "with math" creates a newer namespace: newerGlobal= newGlobal + newLocal newerLocal= names from math My guess is that there would be little use for nesting the "with". Colin W. From Goodimage126 at gmail.com Tue Nov 6 04:31:41 2007 From: Goodimage126 at gmail.com (Goodimage126 at gmail.com) Date: Tue, 06 Nov 2007 01:31:41 -0800 Subject: ********Hi Dear******** Message-ID: <1194341501.860031.280390@t8g2000prg.googlegroups.com> ********Hi Dear******** http://www.geocities.com/godshowm/ http://indianfriendfinder.com/go/g908533-pmem http://bigchurch.com/go/g908534-pmem From sjmachin at lexicon.net Tue Nov 27 18:08:25 2007 From: sjmachin at lexicon.net (John Machin) Date: Tue, 27 Nov 2007 15:08:25 -0800 (PST) Subject: string conversion latin2 to ascii References: <882b8d30-84d7-4ba0-ab8a-699a40a6ab40@y43g2000hsy.googlegroups.com> Message-ID: <83af6dfa-dee0-45af-9a84-fe17bd9b900c@s8g2000prg.googlegroups.com> On Nov 28, 8:45 am, kyoso... at gmail.com wrote: > On Nov 27, 3:35 pm, Martin Landa wrote: > > > Hi all, > > > sorry for a newbie question. I have unicode string (or better say > > latin2 encoding) containing non-ascii characters, e.g. > > > s = "Uk?zka_mo?nosti_vyu?it?_programu_OpenJUMP_v_SOA" > > > I would like to convert this string to plain ascii (using some lookup > > table for latin2) > > > to get > > > -> Ukazka_moznosti_vyuziti_programu_OpenJUMP_v_SOA > > > Thanks for any hits! Regards, Martin Landa > > With a little googling, I found this: > > http://www.peterbe.com/plog/unicode-to-ascii and if the OP has the patience to read *ALL* the comments on that blog entry, he will find that comment[-2] points to http://effbot.python-hosting.com/file/stuff/sandbox/text/unaccent.py and comment[-1] (from the blog owner) is "Brilliant! Thank you." The bottom line is that there is no universal easy solution; you need to handcraft a translation table suited to your particular purpose (e.g. do you want u-with-umlaut to become u or ue?). The unicodedata.normalize function is useful for off-line preparation of a set of candidate mappings for that table; it should not be applied either on-line or blindly. Cheers, John From arnodel at googlemail.com Tue Nov 20 01:57:24 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 19 Nov 2007 22:57:24 -0800 (PST) Subject: How to add a Decorator to a Class Method References: <8026df56-e953-4e17-a439-39ef23be5259@w28g2000hsf.googlegroups.com> Message-ID: <2ee4a805-dd38-4e99-9229-80fcc9172c59@e4g2000hsg.googlegroups.com> On Nov 20, 4:59 am, "gregpin... at gmail.com" wrote: > How do I add a decorator to a class method? Here's what I want to do, > but I guess my syntax isn't right. Any advice? > > class A: > def pre(self,fn): > def new_func(*args,**kwargs): > print 'hi' > fn(*args,**kwargs) > return new_func > @self.pre > def func(self,a,b): > print a+b 'self' is not bound during class creation so self.pre does not exist. Your decorator should be a regular function: def pre(fn): ... class A: @pre def func(self, x, y): .... HTH -- Arnaud From wbrehaut at mcsnet.ca Wed Nov 21 19:41:16 2007 From: wbrehaut at mcsnet.ca (Wayne Brehaut) Date: Wed, 21 Nov 2007 17:41:16 -0700 Subject: eof References: <92a2c0c9-e6a1-4344-aeac-830940200f20@t47g2000hsc.googlegroups.com> Message-ID: <79i9k35vs76cqgqnino7dj3ql623us3euq@4ax.com> Hi braver, On Wed, 21 Nov 2007 15:17:14 -0800 (PST), braver wrote: >I'd like to check, for a filehandle f, that EOF has been reached on >it. What's the way to do it? I don't want to try/except on EOF, I >want to check, after I read a line, that now we're in the EOF state. It would be nicer to check the reference manual than ask here. If you have PythonWin 2.5.1 (r251:54863, May 1 2007, 17:47:05) [MSC v.1310 32 bit (Intel)] on win32.for example, using Help, Index, eof gives: eof Token used to determine end of file. This will be set to the empty string (''), in non-POSIX mode, and to None in POSIX mode. New in version 2.3. If you don't use Active State Python--and even of you do--it helps to have these three "official" references handy: === http://docs.python.org/ref/ref.html Python Reference Manual Guido van Rossum Python Software Foundation Email: docs at python.org Fred L. Drake, Jr., editor Release 2.5 19th September, 2006 === http://docs.python.org/lib/lib.html Python Library Reference Guido van Rossum Python Software Foundation Email: docs at python.org Fred L. Drake, Jr., editor Release 2.5 19th September, 2006 === http://docs.python.org/tut/tut.html Python Tutorial Guido van Rossum Python Software Foundation Email: docs at python.org Fred L. Drake, Jr., editor Release 2.5 19th September, 2006 === The tutorial gives simpler explanations and examples, including: 7. Input and Output 7.2.1 Methods of File Objects >>> f.read() 'This is the entire file.\n' >>> f.read() '' === If the end of the file has been reached, f.read() will return an empty string (""). By browsing the index or TOC, or searching, or guessing, you should conclude that you want 3.9 File Objects There, and checking for "EOF" you'll note that both read( [size]) and readline( [size]) include: "An empty string is returned only when EOF is encountered immediately." HTH? >In Ruby it's f.eof: It also is not nice to talk Ruby here--nor Perl. Refer to C/C++ if necessary. wwwayne > >In Ruby: >>> f = File.open("jopa") >=> # >>> f.read() >=> "jopa\n" >>> f.eof >=> true > >Is there a Python analog? > >Cheers, >Alexy From arkanes at gmail.com Fri Nov 23 11:00:26 2007 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 23 Nov 2007 10:00:26 -0600 Subject: Python too complex ?!?!?! In-Reply-To: <4745EEEA.80709@no_where.com> References: <7hC%i.28332$mv3.17248@newsfe10.phx> <87pry4zlyx.fsf@pobox.com> <4745EEEA.80709@no_where.com> Message-ID: <4866bea60711230800j218954dfn636979cb13709c7f@mail.gmail.com> On Nov 22, 2007 3:04 PM, Brian wrote: > / Chime Mode > I have, in fact, sent this thread to my friend. > His limiting factors are > > - money-control people favor MS platforms > - C# and VS have minimal cost impact for academia > - sys admins have everything locked down (probably > essential for high school and community college) > - both Python 2.4.2, then 2.5.1, on XP and Win2k > crashed approx 10% of lab cptrs, so lab techs refused > to allow further install of any 'third-party' s/w. > (side note - I have installed Python and all the > supporting stuff for PyVISA on 14 work-site (11 XP, 3 > Debian) cptrs with no problem, so I do not understand). > - no such thing as TAs in JC or HS. > - CS instructors, for the effected schools, are not > allowed to config machines or admin the network. > - money-control people want students to learn skills > that are on the IT buzz-word list. > - my friend is no longer allowed to use me as an > 'unofficial' assistant in these classes (not considered > qualified because I only have a B.S. degree), so he > only uses stuff that existing staff are (supposedly) > familiar with... > / Chime Mode > > I told my friend, the wannabe Python instructor, to > walk away from any more volunteer work, and stick to > the paid stuff. American education, what a mess... > Pretty unfortunate stuff, especially that he doesn't have any permission to configure the machines for his course. These are all (mostly?) political problems in his specific situation, though, not issues with Python per se - except in the general sense that Python doesn't get much respect. Except possibly the crashes, although honestly public school computer labs tend to be incredibly hostile environments (admin lockdowns notwithstanding). Support for even mildly off the beaten track thinking is in short supply in most schools, I'm sad to hear of your friends problems. From http Sun Nov 25 15:49:10 2007 From: http (Paul Rubin) Date: 25 Nov 2007 12:49:10 -0800 Subject: OPLC purchase period extended References: <13kgrdbf8eb7l34@corp.supernews.com> <13khho3mb3pp27e@corp.supernews.com> <7xejeeaxo1.fsf@ruckus.brouhaha.com> <13kjn9dcdg5rgb3@corp.supernews.com> Message-ID: <7xir3qnj95.fsf@ruckus.brouhaha.com> Grant Edwards writes: > It's not going to be a full-time computer. It's mostly going > to be something to play with -- though using it in tablet mode > as an e-book reader sounds like it might work. It is fairly nice for that. It's especially cool that the screen works outdoors (reflective). I don't know why regular laptops don't do that any more. From antroy at gmail.com Fri Nov 30 04:56:57 2007 From: antroy at gmail.com (Ant) Date: Fri, 30 Nov 2007 01:56:57 -0800 (PST) Subject: python vs pythonw References: Message-ID: On Nov 30, 3:30 am, John Velman wrote: > New to mac. I have leopard. What's the difference between python and > pythonw? So far (which isn't very far) I can't tell the difference. > > I have a small application using TKinter that I was working on under > Linux. Both python and pythonw run it, but on both it "stops > responding" (pinwheel of death) when I touch the vertical scrollbar. On Windows, python runs in console mode (and pops up a console window if you're not executing the script from a console already), pythonw runs the script as a background process. I'd imagine that it is the same for the Mac, and I shouldn't think it has anything to do with your problem here. -- Ant. From nagle at animats.com Fri Nov 9 18:15:06 2007 From: nagle at animats.com (John Nagle) Date: Fri, 09 Nov 2007 15:15:06 -0800 Subject: Codec lookup fails for bad codec name, blowing up BeautifulSoup In-Reply-To: <1194649323.666365.192100@y27g2000pre.googlegroups.com> References: <4734C6CC.7090204@animats.com> <1194649323.666365.192100@y27g2000pre.googlegroups.com> Message-ID: <4734e9e3$0$14119$742ec2ed@news.sonic.net> Waldemar Osuch wrote: >> This is a known bug. It's in the old tracker on SourceForge: >> [ python-Bugs-960874 ] codecs.lookup can raise exceptions other >> than LookupError >> but not in the new tracker. > > The new tracker has it too. > http://bugs.python.org/issue960874 How did you find that? I put "codecs.lookup" into the tracker's search box, and it returned five hits, but not that one. John Nagle From thorsten at thorstenkampe.de Wed Nov 7 03:53:12 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Wed, 7 Nov 2007 08:53:12 -0000 Subject: Parallel Python environments.. References: Message-ID: * bruce (Tue, 6 Nov 2007 13:43:10 -0800) > if i have python 2.4.3 installed, it gets placed in the python2.4 dir.. if i > don't do anything different, and install python 2.4.2, it too will get > placed in the python2.4 tree... which is not what i want. > > i'm running rhel4/5... So you're using rpm as a packet manager. I suggest you RTFM to see if there are options for slots or dual installations. > so.. i still need to know what to do/change in order to be able to run > multiple versions of python, and to switch back/forth between the versions. Unpack the Python rpm to ~/bin or compile Python yourself. And be more specific about what you mean with "switching back/forth". On the other hand - as Gabriel pointed out: there is almost a 100% certainty that the problem you want to solve by having Python 2.4.2 *and* 2.4.3 simultaneously exists only in your head or cannot be solved this way. Thorsten From grante at visi.com Sat Nov 3 19:06:39 2007 From: grante at visi.com (Grant Edwards) Date: Sat, 03 Nov 2007 23:06:39 -0000 Subject: Low-overhead GUI toolkit for Linux w/o X11? References: <13ipjvic6aj8c69@corp.supernews.com> Message-ID: <13ipvnvoqoh735f@corp.supernews.com> On 2007-11-03, David Bolen wrote: > Grant Edwards writes: > >> I'm looking for GUI toolkits that work with directly with the >> Linux frambuffer (no X11). It's an embedded device with >> limited resources, and getting X out of the picture would be a >> big plus. > > Sounds like a reasonably modern "embedded" system since traditionally > neither X (nor Python) would likely have even been plausible in such > environments. Yes, it's "modern" enough to run Linux/X11 -- horsepower-wise it's sort of in the PDA class of devices. wxWidgets has been tried, but it's pretty sluggish. Hence the search for something a littler lighter weight. Using Python is probably going to be a little bit of a stretch, but using open-source libraries and something like Python for the application langauge seems to be an important part of the business model. > Depending on the higher level GUI functionality you require That's still a bit up in the air. Routines to render text would be nice, as would sprite graphics. I don't think text entry or much in the way of windowing is required. > and how tight the resources really are, you might want to > consider investigating pure drawing libraries and then > implement any missing GUI elements (widgets and mouse > handling) you need yourself. There is no mouse. I'm not sure how many "widgets" are required. Probably not very many. > When I was looking for an embedded graphics library for a prior > platform (ELAN 486, 2MB flash, 6MB RAM) under DOS, we took a look at > these: > > * GRX (http://grx.gnu.de/index.html) > * Allegro (http://alleg.sourceforge.net/) > > We ended up using GRX, primarily because it was the simplest > to develop a custom video driver for to match our platform, > along with having a simpler core. We were under DOS but also > used it with a later generation of the platform under Linux. > Both libraries support operation over the framebuffer in > Linux. Our app was in C++ (Python wasn't an option), and we > implemented our own buttons and text widgets (in our case we > never needed any scrolling widgets). > > There aren't any Python wrappers for GRX, but the library is > straight C which should be easy to wrap (manually or with > something like SWIG). No built-in widget support at all (some > sample button processing code in a demo module), but easy > enough to implement your own if your needs are modest. > > Although we didn't end up using it, Allegro is more fully > featured (actually with some non-GUI cruft too since it > targets games), and also appears to have two work-in-progress > Python bindings. Some basic widget support in dialog > processing routines. Thanks for the pointers. -- Grant From vedrandekovic at v-programs.com Mon Nov 5 12:00:29 2007 From: vedrandekovic at v-programs.com (vedrandekovic at v-programs.com) Date: Mon, 05 Nov 2007 09:00:29 -0800 Subject: wxPython ListCtrl Message-ID: <1194282029.133610.137730@d55g2000hsg.googlegroups.com> Hello, How can I Insert image with string in ListCtrl with this example: # Import ftputil module - like ftplib from ftputil import FTPHost # Create connection ftp=FTPHost("ftp.someserver.com","user","password") # LIST ALL FILES/FOLDERS ON SERVER for item in ftp._dir("/"): # Now check if item is file /folder if item is file insert this image: wx.ART_NORMAL_FILE and if the item is folder insert this image wx.ART_FOLDER .......how can I do the same on server with GenericDirCtrl? Regards, Vedran From nytrokiss at gmail.com Tue Nov 27 13:36:41 2007 From: nytrokiss at gmail.com (James Matthews) Date: Tue, 27 Nov 2007 19:36:41 +0100 Subject: Looking for a Python tutor In-Reply-To: <5644ac82-29c2-4e5a-86a3-7c7c11fc2152@r60g2000hsc.googlegroups.com> References: <5644ac82-29c2-4e5a-86a3-7c7c11fc2152@r60g2000hsc.googlegroups.com> Message-ID: <8a6b8e350711271036x596ea0e4x97d7002d846efc9@mail.gmail.com> Please post on the job section! On Nov 27, 2007 6:46 PM, hong2221 wrote: > I'm looking for a Python programmar that is willing write simple > functions, prices can be talked over. Contact me asap. > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://search.goldwatches.com/?Search=Movado+Watches http://www.goldwatches.com/coupons http://www.jewelerslounge.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From timr at probo.com Tue Nov 20 01:50:34 2007 From: timr at probo.com (Tim Roberts) Date: Tue, 20 Nov 2007 06:50:34 GMT Subject: Variable-width lookbehind References: Message-ID: "OKB (not okblacke)" wrote: > > For years now Python has not supported variable-length lookbehinds. >I'm just curious whether there are any plans to change this in Python >3.0, or before, or after. It seems that Perl 6 will allow variable- >width lookbehinds (see http://dev.perl.org/perl6/doc/design/apo/A05.html >and http://dev.perl.org/perl6/rfc/72.html ). If I may be just a bit catty, your last sentence may actually be the best reason NOT to include it in Python 3.0. Perl 6 has become a worthy successor to ALGOL 68 and PL/I. They are attempting to pack in every feature that has ever been requested by every person in the known universe. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From MonkeeSage at gmail.com Sat Nov 24 00:03:33 2007 From: MonkeeSage at gmail.com (MonkeeSage) Date: Fri, 23 Nov 2007 21:03:33 -0800 (PST) Subject: eof References: <92a2c0c9-e6a1-4344-aeac-830940200f20@t47g2000hsc.googlegroups.com> <79i9k35vs76cqgqnino7dj3ql623us3euq@4ax.com> <6c04c760-6cf1-4715-9ec9-30f43ebaa01f@d27g2000prf.googlegroups.com> <062a9497-7626-440a-93eb-b897e6dec01f@p69g2000hsa.googlegroups.com> <9e25e813-f4a7-48c6-9f0e-ef04223e29a0@e23g2000prf.googlegroups.com> <3cb8cff4-4c1d-4ca2-8d21-c012a109351b@w34g2000hsg.googlegroups.com> <80978b7f-da78-4b1b-9400-66efa1421c4d@n20g2000hsh.googlegroups.com> <94db0532-981a-45b6-9af9-ab5eef054fb7@s19g2000prg.googlegroups.com> Message-ID: <8c5243c7-9457-4333-a539-1a52e3835f5b@y5g2000hsf.googlegroups.com> On Nov 23, 10:43 pm, "hda... at gmail.com" wrote: > This is not the same as ISO C. f.tell could be equal to > File.size(f.path) and eof could be false. An extra read() is required. My bad. As you might have surmised, I'm not a genius when it comes to C. I thought that the eof flag was set when the pointer into the stream was the same as the length of the stream, but I guess it makes since that as an error flag, it would only be set after an attempted read past the end of the stream (in which case, I guess you'd get a NULL from the read, equivalent to python's empty string?). Ps. braver, if you really want a ruby-like eof method on file objects in python, how about overriding the open() alias with a file subclass including eof? import os class open(file): def __init__(self, name): self.size = os.stat(name).st_size file.__init__(self, name) def eof(self): return self.tell() == self.size f = open('tmp.py') print f.eof() # False f.read() print f.eof() # True Regards, Jordan From gagsl-py2 at yahoo.com.ar Wed Nov 7 15:33:41 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 07 Nov 2007 17:33:41 -0300 Subject: Retrieving all open applications ... References: <3b10c2060710300220g16373e41i6d4290563c15776@mail.gmail.com> <3b10c2060711031152r46159f96x8d1bdd9ee7c2a2d5@mail.gmail.com> <3b10c2060711070136v72032102t63f57b707fb7f8db@mail.gmail.com> Message-ID: En Wed, 07 Nov 2007 06:36:49 -0300, Ajay Deshpande escribi?: > well i still havent found a solution to this ... since i am using ubuntu > 7.10, i cannot use the hammond modules ... As you said "list of window handles" I thought you were working on Windows. Try with: man ps Use the subprocess module to call ps with your desired options. -- Gabriel Genellina From arnodel at googlemail.com Wed Nov 14 12:35:00 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 14 Nov 2007 09:35:00 -0800 Subject: Building python packages for the correct architecture on OSX 10.5 Message-ID: <1195061700.315152.61070@22g2000hsm.googlegroups.com> Hi fellow python enthusiasts. Having recently acquired a MacBook Pro (Intel Core 2 Duo) which comes with python2.5, I have been installing some modules that I need (PIL, psycopg2, PyXML ...). The problem is that [$python setup.py build] compiles all the binaries to universal files for i386 and ppc32, but not x86_64 or ppc64. It does not appear to be a problem when running scripts from the shell (as python seems to run as a 32 bits problems), but it is a problem from apache2/mod_python as the included apache2 runs as 64 bits processes. This means the modules need to be compiles for at least both i386 and x86_64 in my case. I have been looking at the setup.py files of various modules but I cannot see a suitable way to indicate what architectures I want them compiled for. So far, I have managed by adding the following lines in setup.py just after the Extension class is imported: OrigExtension = Extension def Extension(*args, **kwargs): extra_args = ['-arch', 'ppc', '-arch', 'ppc64', '-arch', 'i386', '-arch', 'x86_64 '] kwargs['extra_compile_args'] = extra_args + kwargs.get('extra_compile_args', []) kwargs['extra_link_args'] = extra_args + kwargs.get('extra_link_args', []) return OrigExtension(*args, **kwargs) Obviously this is a dirty hack, and I would like to know how to do this the right way. How can this be done better? -- Arnaud From __peter__ at web.de Sat Nov 17 08:43:24 2007 From: __peter__ at web.de (Peter Otten) Date: Sat, 17 Nov 2007 14:43:24 +0100 Subject: class='something' as kwarg References: Message-ID: Vladimir Rusinov wrote: > I'm using beautiful soup html parser, and I need to get all '
class=g>...
' tags. > It can be done by: > > import BeautifulSoup as BSoup > > ... > > soup = BSoup(page) > for div in soup.findAll('div', class='g'): > > > But how can I use `class` as kwarg name? # hack findAll("div", **{"class": "g"}) # official workaround findAll("div", attrs={"class": "g"}) Peter From rickyclarke9 at gmail.com Fri Nov 2 01:24:57 2007 From: rickyclarke9 at gmail.com (rickyclarke9 at gmail.com) Date: Fri, 02 Nov 2007 05:24:57 -0000 Subject: Configuration Management Message-ID: <1193981097.106575.150400@o38g2000hse.googlegroups.com> I have found an excellent resource on understanding Windows Application concepts and exam 070-306. http://technical-talk.com/mc/mcsd/mcsd306.asp From hat at se-162.se.wtb.tue.nl Tue Nov 20 05:01:30 2007 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Tue, 20 Nov 2007 11:01:30 +0100 Subject: Web update library in python? References: Message-ID: On 2007-11-20, Jorgen Bodde wrote: > Hi all, > > I want to provide my users the ability to download a repository from > the web, and after that check for updates. I thought of a mechanism > that could do that, but since there is patch and diff readily > available I wondered if there is a python solution that allows me to > download a file, and let the patch be applied locally. In the patch > there are binaries and sources I am not sure if patch can handle them > both though. there is difflib > I want to have a solution that is very easy for the user, so point and > click kind of work. Is there a tool / library around that can provide > me a base for this problem? However, from your description, it looks like you are trying to achieve what many modern SCM tools do already out-of-the-box, so why are you trying to re-invent the wheel? For example, SVN handles anonymous download of working copies with HTTP, distributed SCM tools (bzr, git, mercurial, to name a few) allow you to copy complete repositories over the internet, and merge/update them (as well as sending patches back by eg email). Such a solution reduces your problem mostly to a one line script like 'svn update'. You may want to add a nice GUI front-end around it (although given the fact you are offering them a repository with sources (which, presumably is more advanced than point-and-click), I don't really see the need for a point-and-click solution). Albert From dannox at gmail.com Fri Nov 30 15:09:05 2007 From: dannox at gmail.com (whatazor) Date: Fri, 30 Nov 2007 12:09:05 -0800 (PST) Subject: pythonw.exe and python.exe Message-ID: <6ea272f8-679b-4548-b431-74ded26c58d0@e1g2000hsh.googlegroups.com> Hi all, I made a little application with multithreading in winxp with python2.5. An event generated from a third part software is the trigger for the creation of progress bar in a wxPython app. This python app is launched via wxExecute. I've noticed a different behaviour if the script is launched with python.exe and pythonw.exe (i.e. without dos shell), in fact in the first case it's all ok, while in the other case only the first, the third , the fifth ... progress bar is setted correctly and update its value. Now, before control again the code , what can be the origin of the problem? why python and pythonw give a result so different? thank you w From exarkun at divmod.com Wed Nov 7 14:59:43 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Wed, 7 Nov 2007 14:59:43 -0500 Subject: a simple tcp server sample In-Reply-To: <1194461679.059865.209530@k79g2000hse.googlegroups.com> Message-ID: <20071107195943.8162.1885568223.divmod.quotient.33078@ohm> On Wed, 07 Nov 2007 18:54:39 -0000, Tzury Bar Yochay wrote: >hi, the following sample (from docs.python.org) is a server that can >actually serve only single client at a time. > >In my case I need a simple server that can serve more than one client. >I couldn't find an example on how to do that and be glad to get a >hint. > >Thanks in advance > >import socket > >HOST = '127.0.0.1' # Symbolic name meaning the local host >PORT = 50007 # Arbitrary non-privileged port > >s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) >s.bind((HOST, PORT)) >s.listen(1) >conn, addr = s.accept() > >print 'Connected by', addr > >while 1: > data = conn.recv(1024) > if not data: > break > conn.send(data) > >conn.close() Even simpler, use Twisted: from twisted.internet.protocol import ServerFactory, Protocol from twisted.internet import reactor HOST = '127.0.0.1' # Symbolic name meaning the local host PORT = 50007 # Arbitrary non-privileged port class Echo(Protocol): def connectionMade(self): print 'Connection from', self.transport.getPeer() def dataReceived(self, bytes): self.transport.write(bytes) factory = ServerFactory() factory.protocol = Echo reactor.listenTCP(HOST, PORT, factory) reactor.run() This doesn't have the bug your version has (where it randomly drops some data on the floor) and handles multiple clients. Check it out: http://twistedmatrix.com/ Jean-Paul From donn.ingle at gmail.com Tue Nov 6 13:03:04 2007 From: donn.ingle at gmail.com (Donn Ingle) Date: Tue, 06 Nov 2007 20:03:04 +0200 Subject: Insane crazy question - printing commands References: Message-ID: Thanks for the replies -- Python, is there anything it can't do? :D \d From chiendarret at yahoo.com Thu Nov 29 15:17:04 2007 From: chiendarret at yahoo.com (Francesco Pietra) Date: Thu, 29 Nov 2007 12:17:04 -0800 (PST) Subject: Donloadin mail on the background Message-ID: <99582.42261.qm@web57611.mail.re1.yahoo.com> Dennis: Why am I using web-based email? As I work on several machines scp linked. I find often useful to see the same mail on different machines around, without downloading anything, just to set up the files on-the-fly for local trial computation before sending a calculation to the mainframe. That I found easy with web-based email. I do not maintain locally on any machine any mail for longer than working on. I am sure you have, or can devise, a better strategy to the same purpose. I am not an expert in software. Regards francesco pietra ____________________________________________________________________________________ Be a better sports nut! Let your teams follow you with Yahoo Mobile. Try it now. http://mobile.yahoo.com/sports;_ylt=At9_qDKvtAbMuh1G1SQtBI7ntAcJ From deets at nospam.web.de Thu Nov 29 03:34:30 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 29 Nov 2007 09:34:30 +0100 Subject: Bundling Python on Mac In-Reply-To: References: Message-ID: <5r7bstF135rvoU1@mid.uni-berlin.de> Benjamin schrieb: > Hello, I'm writing a Python/PyQt application. For my Mac distribution. > I would like to include all the needed libraries in the Mac bundle. > How should I go about doing this? The py2app distutils extension should do that for you. It works flawless for PyObjc-apps for me - it _should_ do so for Qt as well, but I have to admit that it sometimes had errors related to Qt when creating bundles - so maybe you need to tweak the support a bit. Diez From bdesth.quelquechose at free.quelquepart.fr Thu Nov 22 18:45:55 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 23 Nov 2007 00:45:55 +0100 Subject: the annoying, verbose self In-Reply-To: <023aa14b-98b3-4e1c-8282-b3fece7e35d2@s19g2000prg.googlegroups.com> References: <3c954a31-9fb9-4c0f-b784-cef9ee057ca6@g30g2000hsb.googlegroups.com> <6f67fccf-fbec-4c75-baea-5d0277e07883@w40g2000hsb.googlegroups.com> <4745dc0b$0$3051$426a74cc@news.free.fr> <023aa14b-98b3-4e1c-8282-b3fece7e35d2@s19g2000prg.googlegroups.com> Message-ID: <474614d0$0$31237$426a74cc@news.free.fr> Kay Schluehr a ?crit : (snip) > The object model is irrelevant here. The substitution is purely > syntactical and gets resolved at compile time: > > def foo(first, ...): > .bar = ... > > is always equivalent with: > > def foo(first, ...): > first.bar = ... > > and generates the same bytecode. Point taken. But: > Whether this is helpfull, beautifull or necessary is another issue. indeed. From waldemar.osuch at gmail.com Fri Nov 9 22:15:51 2007 From: waldemar.osuch at gmail.com (Waldemar Osuch) Date: Fri, 09 Nov 2007 19:15:51 -0800 Subject: Using python as primary language In-Reply-To: <1194508354.226023.232050@v3g2000hsg.googlegroups.com> References: <1194508354.226023.232050@v3g2000hsg.googlegroups.com> Message-ID: <1194664551.954488.174620@t8g2000prg.googlegroups.com> On Nov 8, 12:52 am, Michel Albert wrote: > In our company we are looking for one language to be used as default > language. So far Python looks like a good choice (slacking behind > Java). A few requirements that the language should be able cope with > are: > > * Database access to Sybase. > This seems to be available for python, but the windows-binaries for > the library > are not available. Self-Compiling them proved to be non-trivial (As > always > on windows). Consider using ODBC. "mxODBC" as well as "pyodbc" and "ceODBC" could be good alternatives. > * Easy GUI creation. > Solved using PyQt. > * Cross Platform (Linux + Windows). > Again, PyQt, solves this > * Easy deployment. > Solved using py2exe + innosetup > * Charting (Histograms, Line charts, bar charts, pie charts, ...) > I am currently looking into PyQwt, which looks promising. > * Report generation with GUI support > reportlab + rml? > > So far, nearly all point seems to be manageable. But I was not yet > able to find a solution for the report generation. What we would like > to have is a sort of GUI interface to prepare the reports without > having to "code" the positioning. I found reportlab, and it looks like > it can do all that is needed in terms of output. But you still have to > code the report. And this is a no go. In context, I found RML and saw > links to graphical RML editors. But I have not yet found a concrete > example code, or documentation. What am I missing? Is RML a reportlab > creation or is it a recognised open standard? If not, is there an open > standard, that is easily to process with python? I still have to try it but pisa looks very promising: http://pisa.spirito.de/content/501/pisa3.html PDF generation using HTML+CSS for layout. I hope your boss considers HTML acceptable "coding". > > Any pointers? I would prefer coding Python to coding Java or > worse..... VB ;) which is another contender in our roundup. You mean VB before .Net? You know that Microsoft ended support for it. Thanks to that brilliant decision Python is an "official" language at my place of work. From MonkeeSage at gmail.com Sun Nov 25 08:22:56 2007 From: MonkeeSage at gmail.com (MonkeeSage) Date: Sun, 25 Nov 2007 05:22:56 -0800 (PST) Subject: the annoying, verbose self References: <3c954a31-9fb9-4c0f-b784-cef9ee057ca6@g30g2000hsb.googlegroups.com> <6f67fccf-fbec-4c75-baea-5d0277e07883@w40g2000hsb.googlegroups.com> <47458D4E.5030302@sympatico.ca> <13keq168fnu9328@corp.supernews.com> Message-ID: I like the explicit "self", personally. It helps distinguish class methods from functions. When I see a "self" I think "A-ha, a class method". Of course, I could tell that from just the indentation and following that back to the class declaration, but as a quick reference I find it helpful. Besides, none of the proposals have sufficinetly dealt with lexical scope without introducing a lot of costly checks which would also hide the complexity of the process (and thereby, most likely, lead to abuse and bad practices). Regards, Jordan From greg at cosc.canterbury.ac.nz Fri Nov 23 19:56:23 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Sat, 24 Nov 2007 13:56:23 +1300 Subject: eof In-Reply-To: <7d28423c-5efa-415b-b727-f36c54d47f6f@d21g2000prf.googlegroups.com> References: <92a2c0c9-e6a1-4344-aeac-830940200f20@t47g2000hsc.googlegroups.com> <79i9k35vs76cqgqnino7dj3ql623us3euq@4ax.com> <6c04c760-6cf1-4715-9ec9-30f43ebaa01f@d27g2000prf.googlegroups.com> <062a9497-7626-440a-93eb-b897e6dec01f@p69g2000hsa.googlegroups.com> <5qlkf3F10drl7U1@mid.uni-berlin.de> <877ikauwyw.fsf@mulj.homelinux.net> <7d28423c-5efa-415b-b727-f36c54d47f6f@d21g2000prf.googlegroups.com> Message-ID: <5qpbeiF10ogq3U1@mid.individual.net> braver wrote: > Historically, is it possible to trace the eof-related design decision > in stdlib? You seem to be assuming that someone started out with a design that included an eof() of the kind you want, and then decided to remove it. But I doubt that such a method was ever considered in the first place. Someone used to programming with the C stdlib doesn't think in terms of testing for EOF separately from reading, because the C stdlib doesn't work that way. Pascal started out with an eof() function because the earliest implementations only worked with disk files. Later, when people tried to make Pascal programs work interactively, they found out that it was a mistake, as it provides opportunities such as the following classic wrong way to read interactive input in Pascal: while not eof(input) do begin write('Enter some data: '); readln(input, line); end which stops and waits for input before printing the first prompt. By not providing an eof() function, C -- and Python -- make it clear that testing for eof is not a passive operation. It's always obvious what's going on, and it's much harder to make mistakes like the above. > when Python was > codified, there should gave been some decisions made. Some decisions were made when the C stdlib was designed, and I think they were the right ones. Python wisely followed them. > for line lin file: > # look at a line > # we can tell eof occurs right here after the last line > No, if the line you just read ends in "\n", you don't know whether eof has been reached until the for-loop tries to read another line. -- Greg From gagsl-py2 at yahoo.com.ar Mon Nov 5 19:37:03 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 05 Nov 2007 21:37:03 -0300 Subject: Library package import question References: <200711051434.26910.Frank.Aune@broadpark.no> Message-ID: En Mon, 05 Nov 2007 10:34:26 -0300, Frank Aune escribi?: > I have a python library package 'Foo', which contains alot of submodules: > > Foo/: > __init__.py > module1.py: > class Bar() > class Hmm() > module2.py > class Bee() > class Wax() > module3.py > etc etc > > To prevent namespace pollution, I want to import and use this library in > the > following way: > > import Foo > (...) > t = Foo.module2.Bee() > > To accomplish this, I put explicit imports in __init__.py: > > import module1 > import module2 > import module3 > > what Im wondering about, is if its a more refined way of doing this, as > the > explicit imports now need to be manually maintained if the library grows. > I've tried to use __all__, but this only seems to work with "from Foo > import > *" and it causes modules to be imported directly into the namespace of > course. If I understand your question right, you want some way to automatically enumerate and import all *.py files inside your package. Try this inside Foo/__init__.py: def import_all_modules(): "Import all modules in this directory" import os.path pkgdir = os.path.dirname(__file__) for filename in os.listdir(pkgdir): modname, ext = os.path.splitext(filename) if ext=='.py' and modname!='__init__': __import__(modname, globals()) import_all_modules() del import_all_modules -- Gabriel Genellina From horpner at yahoo.com Wed Nov 21 21:06:58 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Thu, 22 Nov 2007 02:06:58 GMT Subject: eof References: <92a2c0c9-e6a1-4344-aeac-830940200f20@t47g2000hsc.googlegroups.com> Message-ID: <6v51j.40414$G23.22012@newsreading01.news.tds.net> On 2007-11-21, braver wrote: > I'd like to check, for a filehandle f, that EOF has been reached on > it. What's the way to do it? I don't want to try/except on EOF, I > want to check, after I read a line, that now we're in the EOF state. > In Ruby it's f.eof: > > In Ruby: >>> f = File.open("jopa") >=> # >>> f.read() >=> "jopa\n" >>> f.eof >=> true > > Is there a Python analog? Yes. >>> f = file('jopa') >>> f.read() 'jopa\n' ...and in both Ruby and Python you are at EOF by definition. There's no need to check. -- Neil Cerutti From hniksic at xemacs.org Fri Nov 9 04:37:15 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 09 Nov 2007 10:37:15 +0100 Subject: Using python as primary language References: <1194508354.226023.232050@v3g2000hsg.googlegroups.com> <1194561005.427982.263160@s15g2000prm.googlegroups.com> <004801c8225e$49843350$dc8c99f0$@com> <4866bea60711081538m2b24ab48v3d223adca8b4bd7c@mail.gmail.com> <004901c82264$3b10f460$b132dd20$@com> Message-ID: <878x57yd2s.fsf@mulj.homelinux.net> "Martin Vilcans" writes: >> If by 'this' you mean the global interpreter lock, yes, there are good >> technical reasons. All attempts so far to remove it have resulted in an >> interpeter that is substantially slower on a single processor. > > Is there any good technical reason that CPython doesn't use the GIL > on single CPU systems and other locking mechanisms on multi-CPU > systems? It's not the locking mechanism itself that is slow, what's slow is the Python you get when you remove it. By removing the GIL you grant different threads concurrent access to a number of shared resources. Removing the global lock requires protecting those shared resources with a large number of smaller locks. Suddenly each incref and decref (at the C level) must acquire a lock, every dict operation must be locked (dicts are used to implement namespaces and in many other places), every access to a global (module) variable must be locked, a number of optimizations that involve using global objects must be removed, and so on. Each of those changes would slow down Python; combined, they grind it to a halt. From thorsten at thorstenkampe.de Fri Nov 16 09:14:55 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Fri, 16 Nov 2007 14:14:55 -0000 Subject: What is python????? References: <7ab5b781-3c6c-4fb5-9be1-703d5e7e73a6@s12g2000prg.googlegroups.com> Message-ID: * Cope (Fri, 16 Nov 2007 06:09:31 -0800 (PST)) > please tell me what is python.This group is so crowded. A Python is dangerous snake[1]. This group here mainly consists of misguided snake worshippers. You'd better run before they come to your place... Thorsten [1] http://en.wikipedia.org/wiki/Pythonidae From arturklis2 at gmail.com Wed Nov 14 14:01:21 2007 From: arturklis2 at gmail.com (arturklis2 at gmail.com) Date: 14 Nov 2007 11:01:21 -0800 Subject: Fender Guitars Message-ID: <1195065929.848318.25100@i13g2000prf.googlegroups.com> Best off http://fender-guitars-review.blogspot.com/ From scripteaze at gmail.com Tue Nov 6 00:23:15 2007 From: scripteaze at gmail.com (scripteaze) Date: Tue, 06 Nov 2007 05:23:15 -0000 Subject: How can i find the form name without "nr=0" In-Reply-To: <1194312811.272500.283150@q5g2000prf.googlegroups.com> References: <1194277885.824920.216370@57g2000hsv.googlegroups.com> <5p8sifFq47k4U1@mid.uni-berlin.de> <1194282336.694320.77700@z9g2000hsf.googlegroups.com> <5p91dhFpais1U1@mid.uni-berlin.de> <1194303368.896613.284050@50g2000hsm.googlegroups.com> <1194312811.272500.283150@q5g2000prf.googlegroups.com> Message-ID: <1194326595.329760.26520@o80g2000hse.googlegroups.com> On Nov 5, 6:33 pm, alex23 wrote: > On Nov 6, 8:56 am, scripteaze wrote: > > > Is it possible then to have a form with no name and if so, how can i > > access this form > > Hey scripteaze, > > I'm not sure about mechanize, but you might have more success using > another one of the author's modules, ClientForm:http://wwwsearch.sourceforge.net/ClientForm/ > > from urllib2 import urlopen > from ClientForm import ParseResponse > > response = urlopen("http://wwwsearch.sourceforge.net/ClientForm/ > example.html") > forms = ParseResponse(response, backwards_compat=False) > form = forms[0] > > As it returns a list of forms, you don't need to have a name to access > it. > > Hope this helps. > > -alex23 Thank you very much for your reply. Ill check it out. From pavlovevidence at gmail.com Tue Nov 13 16:18:23 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 13 Nov 2007 13:18:23 -0800 Subject: cmp and sorting non-symmetric types In-Reply-To: References: Message-ID: <1194988703.973800.312070@k79g2000hse.googlegroups.com> On Nov 13, 1:51 pm, "Adam Olsen" wrote: > (I've had trouble getting response for collaboration on a PEP. > Perhaps I'm the only interested party?) > > Although py3k raises an exception for completely unsortable types, it > continues to silently do the wrong thing for non-symmetric types that > overload comparison operator with special meanings. > > >>> a = set([1]) > >>> b = set([2, 5]) > >>> c = set([1, 2]) > >>> sorted([a, c, b]) > > [{1}, {1, 2}, {2, 5}]>>> sorted([a, b, c]) > > [{1}, {2, 5}, {1, 2}] > > To solve this I propose a revived cmp (as per the previous thread[1]), > which is the preferred path for orderings. The rich comparison > operators will be simple wrappers for cmp() (ensuring an exception is > raised if they're not merely comparing for equality.) > > Thus, set would need 7 methods defined (6 rich comparisons plus > __cmp__, although it could skip __eq__ and __ne__), whereas nearly all > other types (int, list, etc) need only __cmp__. > > Code which uses <= to compare sets would be assumed to want subset > operations. Generic containers should use cmp() exclusively. I second Raymond Hettinger's strong -1 on this. I would further suggest that it's the wrong solution even insofar as it's a problem. The right solution is to use comparison operators only for ordered comparisons, not for subset and superset testing. Unfortunately, the rogue operators are already there and in use, so the right solution would probably cause more trouble than it would save at this point. But it'd still cause less trouble than resurrecting the __cmp__ operator. Carl Banks From ptmcg at austin.rr.com Sat Nov 17 11:25:07 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sat, 17 Nov 2007 08:25:07 -0800 (PST) Subject: Excellent sci-fi novel featuring Python References: <45ae31dd-0aaf-4065-ba9e-b1e5cf78b105@c30g2000hsa.googlegroups.com> Message-ID: On Nov 17, 9:37 am, Wade Leftwich wrote: > I'm about halfway through Charles Stross' excellent new novel, > "Halting State". It's set in Edinburgh in the year 2018, and one of > the main characters is a game programmer whose primary language is > something called "Python 3000". I should hope that by 2018, Python 4000 would be more cutting-edge. Or is the protagonist struggling with backward-compatibility with a Python version that would be nearly 10 years old already? -- Paul From greg at cosc.canterbury.ac.nz Sat Nov 24 18:29:33 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Sun, 25 Nov 2007 12:29:33 +1300 Subject: the annoying, verbose self In-Reply-To: References: <3c954a31-9fb9-4c0f-b784-cef9ee057ca6@g30g2000hsb.googlegroups.com> <4068d518-cba9-4eac-bd91-11f676c17b3d@w34g2000hsg.googlegroups.com> <5qq6quF10jrh5U2@mid.uni-berlin.de> <5qqoslF10jrh5U6@mid.uni-berlin.de> Message-ID: <5qrqnoF10vprtU1@mid.individual.net> Patrick Mullen wrote: > Sometimes I actually use a dictionary, but typing all of the quotes > for the keys gets old. If the keys are all identifiers, you can use keyword args to the dict constructor. So you could write self.__dict__.update(dict(var1 = 5, var2 = "a value", var3 = stuff)) if you really wanted to. (Don't be surprised if everyone else refuses to maintain your code, though!) -- Greg From mbac at gpshopper.com Tue Nov 6 15:40:26 2007 From: mbac at gpshopper.com (Michael Bacarella) Date: Tue, 6 Nov 2007 15:40:26 -0500 Subject: Populating huge data structures from disk In-Reply-To: <4866bea60711061104i514838fcld9bbba1382a764a6@mail.gmail.com> References: <000001c820a1$78750ea0$695f2be0$@com> <4866bea60711061104i514838fcld9bbba1382a764a6@mail.gmail.com> Message-ID: <000b01c820b5$44942cb0$cdbc8610$@com> > > For various reasons I need to cache about 8GB of data from disk into core on > > application startup. > > Are you sure? On PC hardware, at least, doing this doesn't make any > guarantee that accessing it actually going to be any faster. Is just > mmap()ing the file a problem for some reason? > > I assume you're on a 64 bit machine. Very sure. If we hit the disk at all performance drops unacceptably. The application has low locality of reference so on-demand caching isn't an option. We get the behavior we want when we pre-cache; the issue is simply that it takes so long to build this cache. > > Building this cache takes nearly 2 hours on modern hardware. I am surprised > > to discover that the bottleneck here is CPU. > > > > The reason this is surprising is because I expect something like this to be > > very fast: > > > > #!python > > import array > > > > a = array.array('L') > > > > f = open('/dev/zero','r') > > > > while True: > > > > a.fromstring(f.read(8)) > > This just creates the same array over and over, forever. Is this > really the code you meant to write? I don't know why you'd expect an > infinite loop to be "fast"... Not exactly. fromstring() appends to the array. It's growing the array towards infinity. Since infinity never finishes it's hard to get an idea of how slow this looks. Let's do 800MB instead. Here's an example of loading 800MB in C: $ time ./eat800 real 0m44.939s user 0m10.620s sys 0m34.303s $ cat eat800.c #include #include #include int main(void) { int f = open("/dev/zero",O_RDONLY); int vlen = 8; long *v = malloc((sizeof (long)) * vlen); int i; for (i = 0; i < 100000000; i++) { if (i >= vlen) { vlen *= 2; v = (long *)realloc(v,(sizeof (long)) * vlen); } read(f,v+i,sizeof (long)); } return 0; } Here's the similar operation in Python: $ time python eat800.py real 3m8.407s user 2m40.189s sys 0m27.934s $ cat eat800.py #!/usr/bin/python import array a = array.array('L') f = open('/dev/zero') for i in xrange(100000000): a.fromstring(f.read(8)) They spend about the same amount of time in system, but Python spends 4.7x as much CPU in userland as C does. And there's no solace in lists either: $ time python eat800.py real 4m2.796s user 3m57.865s sys 0m3.638s $ cat eat800.py #!/usr/bin/python import struct d = [] f = open('/dev/zero') for i in xrange(100000000): d.append(struct.unpack('L',f.read(8))[0]) cPickle with protocol 2 has some promise but is more complicated because arrays can't be pickled. In a perfect world I could do something like this somewhere in the backroom: x = lengthy_number_crunching() magic.save_mmap("/important-data") and in the application do... x = magic.mmap("/important-data") magic.mlock("/important-data") and once the mlock finishes bringing important-data into RAM, at the speed of your disk I/O subsystem, all accesses to x will be hits against RAM. Any thoughts? From gagsl-py2 at yahoo.com.ar Fri Nov 2 02:09:13 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 02 Nov 2007 03:09:13 -0300 Subject: looping References: Message-ID: En Fri, 02 Nov 2007 02:03:09 -0300, Beema shafreen escribi?: > hi everbody, > i have a file , > A_16_P41851056 1730 > A_16_P03796992 165 > A_16_P21640222 360 > A_16_P21640223 240 > A_16_P03796998 205 > column 2 of my file has values.... 1730, 165,360.... > if i need to put a condition checking that if the first values is greater > than the next i have to print the column coresponding to that..... > say for example 1730 is greater than 165 so i print column1 value > =A_16_P41851056 , but 165 is lesser that both the 1730 and 360 so i omit > the > value....from column1, and i have to continue the loop till the end of > file > checking which values is greater the both tom and bottom how do i do > it..... An easy way would be to use the csv module to read your data; then compare rows [i] and [i+1] -- Gabriel Genellina From deets at nospam.web.de Thu Nov 8 06:19:09 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 08 Nov 2007 12:19:09 +0100 Subject: Showing native 8-bit strings in Python interpreter References: <1194520401.910631.18910@z24g2000prh.googlegroups.com> Message-ID: <5pg9ldFrarh2U1@mid.uni-berlin.de> braver wrote: > I'm storing 8-bit characters from the 128-256 range in Python > strings. They are Windows CP1251 Russian characters. When looking at > those strings in the Python interpreter, they come up as codes inside > the string. How can I teach Python to show those 8-bit characters in > the native encoding of the terminal -- in the current locale -- where > the interpreter was started? The python-interpreter will print them out using hex because it calls repr(string) - to prevent any encoding-related troubles. But printing them will meet your expectations. See below: Python 2.5.1 (r251:54863, May 2 2007, 16:56:35) >>> s = '??????' >>> s '\xc3\xa4\xc3\xb6\xc3\xbc\xc3\x9f\xc3\x84\xc3\x9c' >>> print s ?????? >>> Diez From michele.simionato at gmail.com Wed Nov 21 06:10:26 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Wed, 21 Nov 2007 03:10:26 -0800 (PST) Subject: logging module: removing handlers References: <2c910cda-c9e4-4076-8b86-dc91b40b67a9@f3g2000hsg.googlegroups.com> <5qibpeFvrbo1U1@mid.uni-berlin.de> <5b21f759-fa77-440c-979f-30fb697f5804@w28g2000hsf.googlegroups.com> <5qieceFtp5rqU1@mid.uni-berlin.de> Message-ID: <6b40b598-5fc2-4d75-9306-95cc45e03e5e@p69g2000hsa.googlegroups.com> On Nov 21, 11:08 am, "Diez B. Roggisch" wrote: > Having thought more about this, it _has_ to be that way - think of one > handler attached to several loggers. Removing AND closing it from one would > render it useless for others. You can't want that to happen. You have a point. From hniksic at xemacs.org Fri Nov 16 05:24:24 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 16 Nov 2007 11:24:24 +0100 Subject: Populating a dictionary, fast [SOLVED SOLVED] References: <818643.92017.qm@web915.biz.mail.mud.yahoo.com> <47374D00.7080500@gmail.com> <1195051438.889160.137120@50g2000hsm.googlegroups.com> <87fxz8kas6.fsf@mulj.homelinux.net> <13jn10p1r88u19f@corp.supernews.com> <876403jkqe.fsf@mulj.homelinux.net> <13jpgtq22a9lhc5@corp.supernews.com> Message-ID: <871waqwkrr.fsf@mulj.homelinux.net> Steven D'Aprano writes: >> Can you post minimal code that exhibits this behavior on Python 2.5.1? >> The OP posted a lot of different versions, most of which worked just >> fine for most people. > > Who were testing it on single-CPU, 32 bit systems. Still, I'd like to see a test case that fails (works slowly) for you, so that I (and others) can try it on different machines. As I said, the OP posted several versions of his code, and tended to depend on a specific dataset. A minimal test case would help more people debug it. From pyscripter at gmail.com Thu Nov 8 14:15:55 2007 From: pyscripter at gmail.com (PyScripter) Date: 8 Nov 2007 11:15:55 -0800 Subject: Looking for a good Python environment In-Reply-To: <7xbqa6f192.fsf@ruckus.brouhaha.com> References: <1194389774.159051.55580@19g2000hsx.googlegroups.com> <1194434140.836932.10670@k79g2000hse.googlegroups.com> <7xbqa6f192.fsf@ruckus.brouhaha.com> Message-ID: <1194524925.330645.222230@s15g2000prm.googlegroups.com> On Nov 7, 6:50 pm, Paul Rubin wrote: > "Colin J. Williams" writes: > > > Could you elaborate on "lightweight" please? I findPyScripterto be a > > powerful editor/debugger combination. > > > What functionality does Eclipse have thatPyScripterdoes not? > > While we're at it, do any of these debuggers implement a good way to > debug multi-threaded Python programs? PyScripter (http://pyscripter.googlepages.com) debugging is based on the standard Python debugger bdb.py which does not currently support multi-threaded debugging (only the main thread can be debugged). One debugger with such support is Winpdb. PyScripter may integrate Winpdb in the future. However PyScripter does support debugging of GUI (e.g. Tkinter, WxPython) applications with remote debugging. From haraldarminmassa at gmail.com Sun Nov 25 09:10:59 2007 From: haraldarminmassa at gmail.com (GHUM) Date: Sun, 25 Nov 2007 06:10:59 -0800 (PST) Subject: OPLC purchase period extended References: Message-ID: <646867bc-43d5-4739-b812-9a4a6650e7a0@o42g2000hsc.googlegroups.com> > > [http://laptopgiving.org/en/terms-and-conditions.php] > > I'm sure that some people would be willing to serve as middleware... So, which US-Pythoneer is willing to serve as middleware for my buying of the XO? Please contact me. Harald -- GHUM Harald Massa persuadere et programmare Harald Armin Massa Spielberger Stra?e 49 70435 Stuttgart 0173/9409607 fx 01212-5-13695179 - EuroPython 2008 will take place in Vilnius, Lithuania - Stay tuned! From paul at boddie.org.uk Tue Nov 20 10:13:52 2007 From: paul at boddie.org.uk (Paul Boddie) Date: Tue, 20 Nov 2007 07:13:52 -0800 (PST) Subject: Python web frameworks References: <226020ef-3955-43e8-b1f6-2ba9ba43d45e@c29g2000hsa.googlegroups.com> <5qga2mFvuljgU1@mid.uni-berlin.de> Message-ID: On 20 Nov, 15:42, "Diez B. Roggisch" wrote: > > 12/7. Django comes with its own little server so that you don't have > > to set up Apache on your desktop to play with it. > > I was rather shocked to learn that django only has this tiny server and does > not come with a stand-alone server and is supposed to run as > mod_python/cgi-driven app through apache. The standalone server aspect of a large number of Python Web frameworks typically involves BaseHTTPServer from the standard library, as far as I've seen, excluding things like Twisted which aspire to offer production quality server solutions themselves. This was common back in the old days of Webware, in contrast to Zope which used Medusa at the time, if I remember correctly. > Which reaps you of all the benefits of standalone servers like connection > pooling & caching data and so forth. Including sessions - I presume they > always go into the db/filesystem as PHP does. I guess it's a compromise between deployment complexity and benefits in the above areas, although mod_python should offer some relief in some of the above areas. What people didn't like about Webware so much was that run in the recommended way - with a standalone server which communicated with Web server processes - people had to have separate long-running processes, which various hosting providers didn't like. What's most important is that you should be able to switch out one server technology with another when you reach the limits of the original, all without having to rewrite your application or do some major re-plumbing. It does surprise me that mod_python is recommended for use with Django in the various quick start guides I've read, but I suppose that lets the developer avoid the issue of migrating up from a simple server to something more scalable. Not that this should be a problem, of course. Paul From kris.vorwerk at gmail.com Thu Nov 8 10:03:47 2007 From: kris.vorwerk at gmail.com (Kryvor) Date: Thu, 08 Nov 2007 15:03:47 -0000 Subject: why did these companies choose Tcl over Python In-Reply-To: <1193779506.643321.216030@z9g2000hsf.googlegroups.com> References: <1193779506.643321.216030@z9g2000hsf.googlegroups.com> Message-ID: <1194534227.372505.300160@t8g2000prg.googlegroups.com> > As an electronics engineer I use some very expensive EDA CAD tool > programs that are scriptable using Tcl. I was wondering why these > companies have choose to use Tcl instead of Python. Some of these > are: > > Mentor Graphics ModelTech VHDL and Verilog simulator > Synopsys Design Compiler and Primetime Static Timing Analyzer > ActelFPGA tools. I suspect that it's due to historical reasons. TCL first appeared in 1988, whereas Python appeared in 1991. Some of these tools have been around for a very long time, and I suspect that, at first, it was mostly a question of picking the most popular scripting language; decisions made in recent years are probably more for convenience & backward-compatibility reasons than anything else. (That said, I'm not a huge fan of Python's lack of braces ... :) K. From paulgeeleher at gmail.com Mon Nov 5 07:11:23 2007 From: paulgeeleher at gmail.com (sophie_newbie) Date: Mon, 05 Nov 2007 04:11:23 -0800 Subject: Downloading file from cgi application Message-ID: <1194264683.908009.237000@o80g2000hse.googlegroups.com> Hi, I'm writing a cgi application in Python that generates a PDF file for the user and then allows them to download that file. Currently I'm just writing the PDF file to the 'htdocs' directory and giving the user a link to this file to download it. But the problem is that another user could simply come along and download a file that isn't their file by typing the address into the address bar. I don't want to delete the file after it is downloaded either because I'd like the user to be able to download it again if necessary. Is there any way around this problem? Thanks. From http Mon Nov 26 03:51:23 2007 From: http (Paul Rubin) Date: 26 Nov 2007 00:51:23 -0800 Subject: better way to write this function References: <4b4d9cc5-3759-421e-b3a2-3cb25bdaae7a@b40g2000prf.googlegroups.com> <42f62547-3cc7-46dd-95e0-52d1885d7e09@d61g2000hsa.googlegroups.com> Message-ID: <7xlk8lgzjo.fsf@ruckus.brouhaha.com> Chris writes: > for i in range(int(round((len(lst)/n),0))): ... Ugh!!! Not even correct (under future division), besides being ugly. I think you mean: for i in xrange(len(lst) // n): ... Really though, this grouping function gets reimplemented so often that it should be built into the stdlib, maybe in itertools. From simon at removethis.simifilm.ch Mon Nov 12 13:20:15 2007 From: simon at removethis.simifilm.ch (Simon Spiegel) Date: Mon, 12 Nov 2007 19:20:15 +0100 Subject: Rothschilds own half the worlds wealth directly and indirectly thru zionist proxies Re: Bill Gates was never the Richest man on earth References: <1194371581.828680.303910@v3g2000hsg.googlegroups.com> <1194890227.891778.15570@d55g2000hsg.googlegroups.com> Message-ID: <5prjqvFso1rgU1@mid.individual.net> On 2007-11-12 18:57:07 +0100, zionist.news at gmail.com said: > On Nov 11, 5:48 am, "GOH, Kheng-Swee" > wrote: >> On Tue, 06 Nov 2007 17:53:01 -0000, zionist.n... at gmail.com wrote: >> >> ... >> >>> Using an innovative system of pigeons >>> for communication and encoded letters, ... >> >> I didn't believe you until I read that part. It all makes sense now! >> <-------- > > You would learn a lot MORE if you listened to the videos whose links > are provided. Ah, good, we don't have to actually *watch* them ... simon From jorgen.maillist at gmail.com Tue Nov 20 06:41:33 2007 From: jorgen.maillist at gmail.com (Jorgen Bodde) Date: Tue, 20 Nov 2007 12:41:33 +0100 Subject: Web update library in python? In-Reply-To: <5qfu1mFv5oirU1@mid.uni-berlin.de> References: <5qfu1mFv5oirU1@mid.uni-berlin.de> Message-ID: <11e49df10711200341t5f2b7bbfnd8a1df643cdea042@mail.gmail.com> Hi Diez , I fail to see that. If I am the one that can only put new "archive files" on my server by FTP or HTTP upload or whatever, and I update the file which contains the information about what updates are present on my site as last, there is no data corruption or loss of data. There are two roles: Repository maintainer: ----- - Developer of the 'repository' creates a snapshot - This archive is uploaded on his private site - A file that accompanies the archive containing the list of updates is sent last Repository updater: ----- - Downloads the accompanying file - If the accompanying file is valid (I agree upon uploading this small file can be downloaded, but since it is a small text file I would not consider this a huge risk) - Downloads the archive that was put there earlier It might not be a 100% secure methodology, but I won't claim I get thousands of hits per hour to begin with, I am lucky if someone is willing to try my tool to begin with ;-) If all fails I can temporarily rename the directory on the server side, upload the files, and rename it back so that no corrupted files are downloaded. But even it the small 'dictionary' file is corrupted, the install process can abort and the user is asked to try again later. But I guess I am defending my way of solving the issue while the main question was if there was anything remotely similar to what I would need, besides using SVN that is ;-) Thank you for your input! - Jorgen From no at no.no Tue Nov 27 14:47:39 2007 From: no at no.no (Zepo Len) Date: Tue, 27 Nov 2007 21:47:39 +0200 Subject: Pulling data from a .asps site References: Message-ID: On Tue, 27 Nov 2007 20:37:19 +0200, wrote: > > There's a government website which shows public data for banks. We'd > like to pull the data down programmatically but the data is "hidden" > behind .aspx... > > Is there anyway in Python to hook in directly to a browser (firefox or > IE) to do the following... > > 1) Fill the search criteria > 2) Press the "Search" button > 3) Press another button (the CSV button) on the resulting page > 4) Then grab the data out of the notepad file that pops up > > If this is a wild good chase, let me know... (or if there's a better > way besides Python... I may have to explore writing a firefox plug-in > or something)... Well, Python supports moving the mouse pointer so it's should be quite simple to write such a program. From arkanes at gmail.com Sat Nov 3 15:47:56 2007 From: arkanes at gmail.com (Chris Mellon) Date: Sat, 03 Nov 2007 13:47:56 -0600 Subject: Bizarre additional calling overhead. In-Reply-To: References: <1194048439.395384.119980@i38g2000prf.googlegroups.com> Message-ID: <1194119276.12702.1.camel@balamos> On Sat, 2007-11-03 at 01:08 -0300, Gabriel Genellina wrote: > En Fri, 02 Nov 2007 21:07:19 -0300, Matimus escribi?: > > > On Nov 2, 3:08 pm, "Chris Mellon" wrote: > >> >>> def test_func(): > >> > >> ... pass > >> ...>>> import new > >> >>> test_func2 = new.function(test_func.func_code, {}, "test_func2") > >> >>> test_func2 > >> > >> >>> test_func > >> > >> >>> import timeit > >> >>> tf = timeit.Timer("test_func()", "from __main__ import test_func") > >> >>> tf.repeat() > >> > >> [0.2183461704377247, 0.18068215314489791, 0.17978585841498085]>>> tf2 = > >> timeit.Timer("test_func2()", "from __main__ import test_func2") > >> >>> tf2.repeat() > >> > >> [0.40015390239890891, 0.35893452879396648, 0.36034628133737456] > >> > >> Why almost twice the calling overhead for a dynamic function? > > > > So, I don't have an official explanation for why it takes twice as > > long, but the only difference between the two functions I could find > > was that test_func.func_globals was set to globals() and > > test_func2.func_globals was an empty dict. When I re-created > > test_func2 with globals set to globals() it ran just as fast as > > test_func. > > Yes - and that's a very important difference. Not because it's empty, nor > because it's not the same as globals(), but because the builtins as seen > by the function are not from the original __builtin__ module. > > From the Python Reference Manual, section 4.1: > The built-in namespace associated with the execution of a code block is > actually found by looking up the name __builtins__ in its global > namespace; [...] __builtins__ can be set to a user-created dictionary to > create a weak form of restricted execution. > > From the Library Reference, section 28, Restricted Execution: > The Python run-time determines whether a particular code block is > executing in restricted execution mode based on the identity of the > __builtins__ object in its global variables: if this is (the dictionary > of) the standard __builtin__ module, the code is deemed to be > unrestricted, else it is deemed to be restricted. > > Section 3.2, when describing frame objects: > f_restricted is a flag indicating whether the function is executing in > restricted execution mode > > Let's try to see if this is the case. Getting the f_restricted flag is a > bit hard with an empty globals(), so let's pass sys as an argument: > > py> def test_func(sys): > ... print "restricted", sys._getframe().f_restricted > ... > py> import sys, new > py> test_func2 = new.function(test_func.func_code, {}, "test_fun > c2") > py> test_func(sys) > restricted False > py> test_func2(sys) > restricted True > > So test_func2 is running in restricted mode. That't the reason it is so > slow. Even if the restricted mode implementation is now considered unsafe > -because new style classes provide many holes to "escape" from the "jail"- > the checks are still being done. > > Ok, now let's try to avoid entering restricted mode: > > py> import __builtin__ > py> test_func3 = new.function(test_func.func_code, {'__builtins_ > _':__builtin__}, "test_func3") > py> test_func3(sys) > restricted False > > And now, repeating the timings when __builtins__ is correctly set to the > builtin module __builtin__ (!), shows no difference with the original > function. So this was the cause of the slow down. > > The rule is: unless you *actually* want to execute code in restricted > mode, pass globals() when building a new function object, or at least, set > '__builtins__' to the __builtin__ module Thanks for the very informative and detailed information. After posting I, like the other responders, figured out that it was related to the empty globals dict but I had no idea how that could be happening. From wiggly at wiggly.org Fri Nov 2 07:40:11 2007 From: wiggly at wiggly.org (Nigel Rantor) Date: Fri, 02 Nov 2007 11:40:11 +0000 Subject: new style class In-Reply-To: <1194003093.338406.300870@y42g2000hsy.googlegroups.com> References: <1194002609.296417.111050@v3g2000hsg.googlegroups.com> <472b09dd$1_7@news.bluewin.ch> <1194003093.338406.300870@y42g2000hsy.googlegroups.com> Message-ID: <472B0C9B.1040901@wiggly.org> gert wrote: > On Nov 2, 12:27 pm, Boris Borcic wrote: >> gert wrote: >>> class Test(object): >>> def execute(self,v): >>> return v >>> def escape(v): >>> return v >>> if __name__ == '__main__': >>> gert = Test() >>> print gert.m1('1') >>> print Test.m2('2') >>> Why doesn't this new style class work in python 2.5.1 ? >> why should it ? > > I don't know I thought it was supported from 2.2? > I think what Boris was being exceedingly unhelpful in saying was "why should it work when you're calling methods that do not exist" I don't see 'm1' or 'm2' defined for the class 'Test'. n From barberomarcelo at gmail.com Fri Nov 30 15:41:01 2007 From: barberomarcelo at gmail.com (barberomarcelo at gmail.com) Date: Fri, 30 Nov 2007 12:41:01 -0800 (PST) Subject: Witch editor to use! References: Message-ID: <212fa742-46ca-418b-9377-d615fe2f96d2@e6g2000prf.googlegroups.com> On 30 nov, 06:10, SMALLp wrote: > Hello! > > I'm new in wxPython and before i start doing anything I have one qustion. > > Shoul I use some of editors like boa, spe or shoud i use my favorite > text editor! > > i used IDLE on windows and it seamd nice. Now i have linux installed on > my mashine and boa works, spe wont start, IDLE crashes when compailinfg! > > And if editor is bether choice witch one to use! I have spe installed and working in Ubuntu 7.10. See some feedback here: http://pythonide.blogspot.com/2007/02/spe-now-works-on-wxpython28-and-how-to.html When I installed spe, it didn't start, but there was a previous fix (editing a file that I can't remember now). It was a wx version problem. HTH Marcelo From j3nsby at gmail.com Sat Nov 3 22:02:19 2007 From: j3nsby at gmail.com (Jens) Date: Sun, 04 Nov 2007 02:02:19 -0000 Subject: Python good for data mining? Message-ID: <1194141739.683498.206780@k79g2000hse.googlegroups.com> I'm starting a project in data mining, and I'm considering Python and Java as possible platforms. I'm conserned by performance. Most benchmarks report that Java is about 10-15 times faster than Python, and my own experiments confirms this. I could imagine this to become a problem for very large datasets. How good is the integration with MySQL in Python? What about user interfaces? How easy is it to use Tkinter for developing a user interface without an IDE? And with an IDE? (which IDE?) What if I were to use my Python libraries with a web site written in PHP, Perl or Java - how do I intergrate with Python? I really like Python for a number of reasons, and would like to avoid Java. Sorry - lot of questions here - but I look forward to your replies! From bedouglas at earthlink.net Sun Nov 11 11:50:19 2007 From: bedouglas at earthlink.net (bruce) Date: Sun, 11 Nov 2007 08:50:19 -0800 Subject: python - an eggs... In-Reply-To: <5pobb2FsfvckU1@mid.uni-berlin.de> Message-ID: <1b0f01c82482$f3292ed0$0301a8c0@tmesa.com> Hi Diez... In my case, I do a "python setup.py install" and i get a Durus...egg installed in the /usr/lib/python2.4/site-packages/ dir... As I understand it, this egg/file contains compressed pythonic files. When I run the app which uses the durus stuff... the app crashes, and displays the durus python script with a path. However, when I simply cut/copy the path, and attempt to view that file, the path doesn't exist on the drive. I'm assuming that there is some sort of relative offset action going on, but that the file actually doesn't exist, except within the egg itself. I've also tried to simply modify the original source file, without rebuilding the egg, which obviously doesn't affect the egg file. So, for now, the only way I can see to modify the src, is to go back to the src files, modify, and rebuild the durus app. I don't see any "setuptools" neither setuptools, nor "man setuptools" returns anything on my system. when i run "python setup.py develop" and I then run my app, it crashes, complaining of a persisten object not being found.... So I don't think that's the immediate solution. 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 Diez B. Roggisch Sent: Sunday, November 11, 2007 4:36 AM To: python-list at python.org Subject: Re: python - an eggs... bruce schrieb: > Hi... > > I have a python script/app that i'm dealing with. It uses Durus, which > installs as an egg. > > I'm trying to figure out how to modify any of the underlying source files or > the egg, short of modifying the original source file, and then having to > reinstall the egg via "python setup.py install"... > > I'm relatively new to python/egg(s), but I can't seem to find a way to > accomplish this via the 'net. > > I've looked in the Install file, as well as the setup.py thinking that I > migt be able to find a way to simply build the app, and to have the required > scripts installed under the "/usr/lib/python2.4/site-packages" tree as the > other pyhon apps/scripts are.... > > The app I'm working with is Durus 3.7. I've got the tar.gz uncompressed, but > the only thing I get is an egg file, which gets installed/placed under the > "site-packages" dir. > > Any help/pointers/etc.. would be helpful!! Usually, eggs are created using setuptools [1]. The documentation there is comparably good. So I'm wondering where your troubles come from. Your usecase should be solved by a simple # python setup.py develop Then in the site-packages there will be created an egg-link that points to your durus-dir. You can then modify the source. Diez -- http://mail.python.org/mailman/listinfo/python-list From ayaz at dev.null Sat Nov 24 03:27:11 2007 From: ayaz at dev.null (Ayaz Ahmed Khan) Date: 24 Nov 2007 08:27:11 GMT Subject: md5 wrongness? References: <01cd53c7-085e-4fef-a5c2-8e61e89fea5b@s12g2000prg.googlegroups.com> Message-ID: <4747e05f$0$90271$14726298@news.sunsite.dk> John Machin wrote: > On Nov 24, 1:34 pm, Ron Johnson wrote: >> Why do Python's md5 and GNU md5sum produce differing results? > > They don't differ. Try feeding them the same input: > >>>> import md5 >>>> md5.new('snagglefrob').hexdigest() > '9eb2459fcdd9f9b8a9fef7348bcac933' >>>> md5.new('snagglefrob\n').hexdigest() > 'f842244d79af85b457811091319d85ff' >>>> Or, alternatively: $ echo -n snagglefrob | md5sum 9eb2459fcdd9f9b8a9fef7348bcac933 - -- Ayaz Ahmed Khan From http Sat Nov 17 12:10:32 2007 From: http (Paul Rubin) Date: 17 Nov 2007 09:10:32 -0800 Subject: python debugging... References: <09a101c82936$7351c290$0301a8c0@tmesa.com> Message-ID: <7xr6iovlvb.fsf@ruckus.brouhaha.com> Donn Ingle writes: > I don't know if this will help you, but if you can, install "Eric". It's an > IDE that I often use and you can do point and click debugging with > breakpoints and nice displays of all vars and whatnot as you go. Much > easier than fiddling with the debugger manually. I've just started fooling with winpdb (google for it). Despite its name it is not windows specific and I'm using it on linux. It's a debugger and not a full IDE, but it's very nice so far. I'm especially interested in its multi-thread debugging capabilities. From zionist.news at gmail.com Mon Nov 5 20:40:19 2007 From: zionist.news at gmail.com (zionist.news at gmail.com) Date: Tue, 06 Nov 2007 01:40:19 -0000 Subject: >>> CIA Squashes Democracy in Pakistan <<< In-Reply-To: References: <1194298989.746423.199810@o3g2000hsb.googlegroups.com> Message-ID: <1194313219.536008.263420@22g2000hsm.googlegroups.com> On Nov 5, 4:55 pm, Ivar Rosquist wrote: > On Mon, 05 Nov 2007 21:43:09 +0000, zionist.news wrote: > >http://www.youtube.com/watch?v=BdB2r1ss5Wk > > >http://www.jewwatch.com/ <----- excellent source for well researched > > news on world events and the big movers of history > > What democracy? Pakistan will be either a military dictatorship > or theocratic one. A country with such a high proportion of moslem > fundamentalists is not likely to develop into a democracy any time soon. Your understanding is rather shallow. However, my knowledge of history is good enough to see the facts and put them in their proper perspective. The fundamentalist Islam is democratic by nature. (The Coran itself gives rights to the non-moslem people and can be held up by non-moslems to demand their rights.) We see that in Iran. There, a commoner, Ahmadinejad has risen to be the leader by democratic voting. The women are quite educated and as aggressive as the iranian males. The videos and testimonials by the Rabbis of Neturei Karta who visited Iran shows that the jews there live quite well. On the other hand, here, the corporations decide who will get into the white house. The wahhabi puppets in Saudi Arabia and the little estates on the peninsula are dictators imposed by the Anglo-American forces. 911 was staged to prevent a democratic revolution in Saudi Arabia as one of its key objectives, and Osama was scapegoated to pre-empt a democratic revolution like in Iran. If you still insist on Iran as a theocracy, you might compare it with Israel and think about how either treats its minority. Go to youtube and google for neturei karta and find their videos about Iran. From aaron.watters at gmail.com Tue Nov 20 10:20:37 2007 From: aaron.watters at gmail.com (Aaron Watters) Date: Tue, 20 Nov 2007 07:20:37 -0800 (PST) Subject: Python too complex ?!?!?! References: <7hC%i.28332$mv3.17248@newsfe10.phx> <7bde7627-adf1-4bc6-a936-2159370485a1@e1g2000hsh.googlegroups.com> Message-ID: <672dfa43-bd56-44fa-b85d-15eca7682c84@s36g2000prg.googlegroups.com> On Nov 19, 1:41 am, MonkeeSage wrote: > On the other hand, C# and .NET seems like a lot of baggage to bring to > the table. First off, you have to introduce the CLR and how it relates > to C#, then you have to deal with all the public, private, etc, > syntaxis for constructors/destructors. I don't see how anyone could > claim that C# is simpler to teach than python. I mean, (non-PC > statement follows), it's easier to teach retarded, blind children to > recite the lord's prayer backwards, in sign language, than it is to > get a working .net environment set up for actual use w/o installing > the latest visual studio. And not everyone had five-million dollars > (or a corporate license) to get the latest and greatest VS. You've got some good points that are not necessarily the case any more. The free version of Visual Studio from MSFT installs with no problems as far as I can tell, especially on recent Windows OS's. The extra complexity of "static public void Main()..." &c is scary and confusing, but you can just tell the students to "ignore that stuff for now." You don't have to talk about the CLR at all; the students naturally take it for granted. In VS when you start typing something, VS makes a pretty good guess what you are trying to do and offers to complete it for you -- which would be really nice to have in Python (and unavailable afaik, at least at that level of sophistication). When you make a syntax or type error you get a red squiggly underline, and so forth. On the other hand I still think that the Python interactive interpreter is the coolest thing about Python for beginners. It's the only language I know where you could seriously start introducing basic concepts of strings, hash tables, and arrays (lists/tuples) in the first hour or so to students below MIT level of preparation. This is primarily because the interactive interpreter and Python's nice syntax make everything so accessible. In C# you might get into arrays or strings in week 3+ and hash tables and other scary things would probably wait for the second course. IronPython anyone? (btw, what's up with IronPython?) -- Aaron Watters === http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=crash+many+ways&FocusId=1593 From kyosohma at gmail.com Tue Nov 6 16:09:31 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 06 Nov 2007 21:09:31 -0000 Subject: How do I get the PC's Processor speed? In-Reply-To: References: <1194376737.430731.60750@o80g2000hse.googlegroups.com> Message-ID: <1194383371.766037.117080@z9g2000hsf.googlegroups.com> On Nov 6, 2:51 pm, "Michael Bacarella" wrote: > > On the problem PCs, both of these methods give me the same information > > (i.e. only the processor name). However, if I go to "System > > Properties" and look at the "General" tab, it lists the CPU name and > > processor speed. Does anyone else know of another way to get at this > > information? > > This information is hardware dependent and probably unreliable. > > Why not run a benchmark and report the results instead? > Like bogomips? That's an interesting idea, but this is in a login script, so I can't exactly run benchmarks while logging in as the users will get impatient quite quickly. They already think the scripts take too long as it is. While this information may be unreliable, it is desired by my boss for the express purpose of budgeting upgrades in our organization. Thanks! Mike From tyler.smith at mail.mcgill.ca Sun Nov 4 18:08:20 2007 From: tyler.smith at mail.mcgill.ca (Tyler Smith) Date: 04 Nov 2007 23:08:20 GMT Subject: cgi undefined? References: <13isguorbi6m155@corp.supernews.com> Message-ID: On 2007-11-04, Dennis Lee Bieber wrote: > > '/home/tyler/public_html/cgi-bin/cgi.py' > ^^^^^^ > > Very simple -- you named YOUR handler "cgi". So when it does "import > cgi" it is importing itself... > Of course. I knew it must be something dumb. Thanks! Tyler From danfike at gmail.com Wed Nov 14 13:41:44 2007 From: danfike at gmail.com (danfike at gmail.com) Date: Wed, 14 Nov 2007 18:41:44 -0000 Subject: Trouble building pywin32 with Visual Studio 2005 Message-ID: <1195065704.281487.52130@o38g2000hse.googlegroups.com> Hi everybody... I'm hoping one of you reading this can help me out here. I'm having trouble getting pywin32 to build with Visual Studio 2005. But first, some background. I'm embedding Python in an MFC application. I've manually built Python .lib and .dll files using Visual Studio 2005 from the solution/ project files in the PCBuild8 folder. I've got a totally happy, working Python interpreter in my MFC application. When I use pre-built pywin32 packages, some strange crashes occur. Specifically, if I import win32com.server.register and call the RegisterClasses function, I get a complaint regarding an attempt to free unallocated memory. Now, my theory on this issue is that DLLs like win32api.pyd, which I acquired pre-built, were built with Visual Studio 2003, and they depend on msvcr71.dll. My Python/MFC application, on the other hand, was built with Visual Studio 2005, and is linking with msvcr80.dll. If memory gets allocated through one DLL, and an attempt is made at freeing it in the other DLL, bad things can happen, since the freeing DLL doesn't have any header information on the allocated memory. In order to test this theory (and potentially fix it), I want to re- build the pywin32 stuff using Visual Studio 2005. Now I've never built pywin32, so please excuse any "noobness" from here on out. I downloaded the pywin32-210.zip source from sourceforge. I tried running "setup.py build" per the Readme, and I received the following message. Warning - can't find an installed platform SDK error: Python was built with Visual Studio 2003; extensions must be built with a compiler that can generate compatible binaries. Visual Studio 2003 was not found on this system. if you have Cygwin installed, you can try compiling with MingW32, by passing "-c mingw32" to setup.py. (Note that I don't have the Platform SDK - This is a Vista machine, so I've got what they now are calling the Windows SDK. If it ends up being a problem, I'll tackle it when it shows up) The logical conclusion to jump to from this error message is that pywin32 is trying to build with VS2005, but it thinks that Python was built with VS2003. Well, in a manner of speaking, that is true. I did have a regular Python installation in C:\Python25, straight from one of the MSI installers. That regular Python installation was undoubtedly compiled with VS2003. I guess what I need to do is find a way to replace the default installation, or certain files within it, with stuff I compiled myself using VS2005. I tried replacing all of the python25[_d].dll and python[w][_d].exe files with those that I built, and that isn't helping. I considered creating a Python installer with the msi.py that is included in the Python Source, but that requires pywin32 (according to the README), and that's what I'm trying to build. I tried going through the setup.py code to find out where it is acquiring this "Python was built with Visual Studio 2003" information, but I keep getting lost in the code, so I can't figure out which, if any, file(s) to change/replace. From gh at ghaering.de Sun Nov 25 14:24:24 2007 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Sun, 25 Nov 2007 20:24:24 +0100 Subject: [ANN] pysqlite 2.4.0 released Message-ID: <4749CBE8.5090309@ghaering.de> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 pysqlite 2.4.0 released ======================= I'm pleased to announce the availability of pysqlite 2.4.0. This is a release with major new features. Go to http://pysqlite.org/ for downloads, online documentation and reporting bugs. What is pysqlite? pysqlite is a DB-API 2.0-compliant database interface for SQLite. SQLite is a in-process library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine. pysqlite makes this powerful embedded SQL engine available to Python programmers. It stays compatible with the Python database API specification 2.0 as much as possible, but also exposes most of SQLite's native API, so that it is for example possible to create user-defined SQL functions and aggregates in Python. If you need a relational database for your applications, or even small tools or helper scripts, pysqlite is often a good fit. It's easy to use, easy to deploy, and does not depend on any other Python libraries or platform libraries, except SQLite. SQLite itself is ported to most platforms you'd ever care about. It's often a good alternative to MySQL, the Microsoft JET engine or the MSDE, without having any of their license and deployment issues. pysqlite can be downloaded from http://pysqlite.org/ - Sources and Windows binaries for Python 2.5, 2.4 and Python 2.3 are available. ======= CHANGES ======= - - Implemented context managers. pysqlite's connections can now be used as context managers with Python 2.5 or later: from __future__ import with_statement from pysqlite2 import dbapi2 as sqlite con = sqlite.connect(":memory:") con.execute("create table person (id integer primary key, firstname varchar unique)") # Successful, con.commit() is called automatically afterwards with con: con.execute("insert into person(firstname) values (?)", ("Joe",)) # con.rollback() is called after the with block finishes with an exception, the # exception is still raised and must be catched try: with con: con.execute("insert into person(firstname) values (?)", ("Joe",)) except sqlite.IntegrityError: print "couldn't add Joe twice" - - pysqlite connections can now be created from APSW connections. This enables users to use APSW functionality in applications using the DB-API from pysqlite: from pysqlite2 import dbapi2 as sqlite import apsw apsw_con = apsw.Connection(":memory:") apsw_con.createscalarfunction("times_two", lambda x: 2*x, 1) # Create pysqlite connection from APSW connection con = sqlite.connect(apsw_con) result = con.execute("select times_two(15)").fetchone()[0] assert result == 30 con.close() Caveat: This will only work if both pysqlite and APSW are dynamically linked against the same SQLite shared library. Otherwise you will experience a segfault. - - Fixed shuffled docstrings for fetchXXX methods. - - Workaround for SQLite 3.5.x versions which apparently return NULL for "no-operation" statements. - - Disable the test for rollback detection on old SQLite versions. This prevents test failures on systems that ship outdated SQLite libraries like MacOS X. - - Implemented set_progress_handler for progress callbacks from SQLite. This is particularly useful to update GUIs during long-running queries. Thanks to exarkun for the original patch. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.6 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFHScvodIO4ozGCH14RAoFkAJ4uQc5hW83jhD9D30FbjeYvMRjvKwCdEq/y MmWmjLU7eFpLprVQRZpp2OQ= =caM6 -----END PGP SIGNATURE----- From bearophileHUGS at lycos.com Fri Nov 16 12:22:51 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Fri, 16 Nov 2007 09:22:51 -0800 (PST) Subject: overriding methods - two questions References: Message-ID: <21fcb053-1c95-4b76-909e-1c5d23d47b8b@d50g2000hsf.googlegroups.com> Donn Ingle: > Say I am in class Basis, doing a loop and I have a list of Child objects. I > want to run the foo() method for each one that *has* a foo() method. This may help (on an old Python version): >>> class Sam: pass ... >>> class Judy: ... def foo(self): pass ... >>> children = [Sam(), Judy(), Sam()] >>> for child in children: hasattr(child, "foo") ... False True False Bye, bearophile From rekkufa at footard.com Fri Nov 23 17:43:28 2007 From: rekkufa at footard.com (rekkufa) Date: Fri, 23 Nov 2007 16:43:28 -0600 Subject: Recursive loading trouble for immutables Message-ID: I am currently building a system for serializing python objects to a readable file-format, as well as creating python objects by parsing the same format. It is more or less complete except for a single issue I just cannot figure out by myself: How to load data that specifies immutables that recursively reference themselves. There are only a few solutions I can think of. One: While loading recursive objects, I always create empty versions of objects (lists, dicts, classes) etc, and fill them in afterwards. This works fine for loading recursive lists and such, but as immutables are, well, immutable, this gets me nowhere with important datatypes like tuples. Two: Global replacement. If I dont remember incorrectly, PyPy has a function for simply globally replacing all references to a given object with another. This would make the loading code a piece of cake, although I assume this functionality doesn't exist in CPython? This is the second time I've had good use for it. Three: Create transparent proxies everywhere. Just kidding. Four: Disallow immutable recursiveness. This is bad for two reasons. Firstly, it requires me to greatly increase the complexity of the loading code as I have to topsort all references to avoid recursiveness in immutables while at the SAME TIME allow mutables to be recursive. I can't imagine how unelegant the code will be. Secondly, there is nothing wrong with recursive tuples. To disallow them and work miles around them just because they can't be properly expressed in Python In any case I am stumped. It's the last piece of a module I am otherwise very pleased with. There must be a way. I certainly know most people on this list can get around python much better than I do, so, any ideas? ---------------------------------------------------------------- Brought to you by Footard: http://www.footard.com Please report abuse/spam/scams to reportabuse at footard dot com From exarkun at divmod.com Fri Nov 23 18:21:50 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Fri, 23 Nov 2007 18:21:50 -0500 Subject: Looking to learn python willing to clean up code In-Reply-To: Message-ID: <20071123232150.8162.581858181.divmod.quotient.39169@ohm> On Fri, 23 Nov 2007 01:36:10 GMT, Nathan McSween wrote: >Hi I would like to learn python I have background in php, pawn, bash. I was >wondering if anyone would like to show me the ropes or even just throw me >some code that needs work and seeing what I come up with. Twisted python >seems to have very bright people behind it using newer programming ideas >which would tie in nicely with what I want to know. I have read programming >python: novice to professional. > You could take a look through the open tickets for Twisted: http://twistedmatrix.com/trac/report And drop by #twisted on irc.freenode.net to chat about some tasks you might be able to tackle. Twisted development involves code review for all changes, so this would be a guaranteed way to get feedback on your work. Jean-Paul From kf9150 at gmail.com Thu Nov 22 02:33:44 2007 From: kf9150 at gmail.com (Kelie) Date: Wed, 21 Nov 2007 23:33:44 -0800 (PST) Subject: having problem using xlrd References: <6e4ee601-6a21-48f4-9d3a-1b121280d6ea@v4g2000hsf.googlegroups.com> Message-ID: <27298639-0145-426a-9ba9-328f9f2c188a@e23g2000prf.googlegroups.com> FYI, this question has been answered in python-excel group. Thanks. From kyosohma at gmail.com Tue Nov 13 12:18:46 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 13 Nov 2007 17:18:46 -0000 Subject: Convert some Python code to C++ In-Reply-To: <1194967729.175135.39830@22g2000hsm.googlegroups.com> References: <1194967729.175135.39830@22g2000hsm.googlegroups.com> Message-ID: <1194974326.377387.191400@k79g2000hse.googlegroups.com> On Nov 13, 9:28 am, meyousikm... at yahoo.com wrote: > I am working on an implementation of the Longest Common Subsequence > problem (as I understand it, this problem can be used in spell > checking type activities) and have used this site to understand the > problem and its solution: > > http://en.wikibooks.org/wiki/Algorithm_implementation/Strings/Longest... > > For those that understand algorithms and can talk Python, I want to > convert the Python code in the section "Reading out all LCSs" into C++ > code but I don't understand some of the syntax. Can anyone give me a > hand? > > Here is the code from that section, but is probably of little use > without understanding the entire problem setup given at the site > above: > > def backTrackAll(C, X, Y, i, j): > if i == 0 or j == 0: > return set([""]) > elif X[i-1] == Y[j-1]: > return set([Z + X[i-1] for Z in backTrackAll(C, X, Y, i-1, > j-1)]) > else: > R = set() > if C[i][j-1] >= C[i-1][j]: > R.update(backTrackAll(C, X, Y, i, j-1)) > if C[i-1][j] >= C[i][j-1]: > R.update(backTrackAll(C, X, Y, i-1, j)) > return R > > Thanks! You might try Shed Skin: http://sourceforge.net/projects/shedskin/ It's been a while since I did C++. I would recommend going through a basic C++ tutorial. I'm pretty sure the equivalence operators are almost the same. You'll likely need to declare the types for the arguments passed into the function as well. I think lists are called arrays in C++. I don't know what the "set" equivalent is though. Mike From michele.simionato at gmail.com Wed Nov 21 04:06:13 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Wed, 21 Nov 2007 01:06:13 -0800 (PST) Subject: logging module: removing handlers Message-ID: <2c910cda-c9e4-4076-8b86-dc91b40b67a9@f3g2000hsg.googlegroups.com> I have just discovered a bug in my code using the logging module, due to handlers not being closed properly. The issue was that I called the function removeHandler and I assumed that it took care of closing the handler, but it did not. Looking at the source code of logging/__init__.py I discovered that it is implemented as follows: def removeHandler(self, hdlr): """ Remove the specified handler from this logger. """ if hdlr in self.handlers: #hdlr.close() hdlr.acquire() try: self.handlers.remove(hdlr) finally: hdlr.release() The question is: why in the hell the "hdlr.close()" line is commented?? I discovered this because we had locks in our production database (we were logging on the DB) and it was not easy to spot the source of the problem, so I would like to know the rationale for not closing the handler in removeHandler. Michele Simionato From nagle at animats.com Wed Nov 14 14:09:15 2007 From: nagle at animats.com (John Nagle) Date: Wed, 14 Nov 2007 11:09:15 -0800 Subject: Feeding data into MySQLdb LOAD DATA from Python Message-ID: <473b47c9$0$14082$742ec2ed@news.sonic.net> Is it possible to feed data into a LOAD DATA command in MySQL without writing out the data to a file? It's possible to do this using the MySQL command line and a UNIX FIFO, but that's kind of clunky. I have to load a few gigabytes of data, and using INSERT takes a whole day for each update. And can this be done portably across UNIX and Windows? Thanks. John Nagle From __peter__ at web.de Sun Nov 25 04:39:38 2007 From: __peter__ at web.de (Peter Otten) Date: Sun, 25 Nov 2007 10:39:38 +0100 Subject: How can I create customized classes that have similar properties as 'str'? References: <67954d23-9400-4ac9-ba45-bec04fab51a2@s6g2000prc.googlegroups.com> <8eebf8fb-74cc-452a-bbef-2fe93556491f@i29g2000prf.googlegroups.com> <5qqeroF11703eU2@mid.individual.net> <1f2e037f-3667-4070-97cd-f4f6486c9d79@i12g2000prf.googlegroups.com> <5a9a3a5b-2986-4dd4-9cfe-cdebe69c3514@l1g2000hsa.googlegroups.com> <13kh8ok6b7e0s44@corp.supernews.com> Message-ID: Steven D'Aprano wrote: >>>>> store = {} >>>>> def atom(str): >> global store >> if str not in store: >> store[str] = str >> return store[str] > > Oh lordy, that's really made my day! That's the funniest piece of code > I've seen for a long time! Worthy of being submitted to the DailyWTF. Here's a script to show atom()'s effect on memory footprint: $ cat atom.py import sys data = [1]*1000 items = [] cache = {} if "-a" in sys.argv: def atom(obj): try: return cache[obj] except KeyError: cache[obj] = obj return obj else: def atom(obj): return obj try: while 1: items.append(atom(tuple(data))) except MemoryError: print len(items) $ ulimit -v 5000 $ python atom.py 226 $ python atom.py -a 185742 So if you are going to submit Sam's function make sure to bundle it with this little demo... Peter From mhearne808 at gmail.com Wed Nov 21 10:30:33 2007 From: mhearne808 at gmail.com (mhearne808[insert-at-sign-here]gmail[insert-dot-here]com) Date: Wed, 21 Nov 2007 07:30:33 -0800 (PST) Subject: compiling python 2.5, missing zlib References: <4741FDDF.8070505@v.loewis.de> <693e08b5-2911-4c9c-a00f-f7b6ceae66a3@e4g2000hsg.googlegroups.com> <474252DA.1040308@v.loewis.de> Message-ID: <153a8523-8fcf-4b1e-91ea-b4460c54f7a7@w34g2000hsg.googlegroups.com> On Nov 19, 8:22 pm, "Martin v. L?wis" wrote: > > Those headers are already installed, according to "up2date". Is there > > a way to specify the header files used? > > It will automatically use them if they are good. What's the value of > ZLIB_VERSION in /usr/include/zlib.h? > > Regards, > Martin I got my Python compile to work, by setting recompiling the zlib source I downloaded with a --shared configure option. Now I'm having trouble getting the Python MySQL module to install. That'll be a separate post! --Mike From mrmakent at cox.net Thu Nov 22 20:33:42 2007 From: mrmakent at cox.net (Mike Kent) Date: Thu, 22 Nov 2007 17:33:42 -0800 (PST) Subject: python question!! References: Message-ID: <7e630535-bceb-4402-b87f-b51c9aeff28e@b40g2000prf.googlegroups.com> On Nov 22, 8:23 pm, "bruce" wrote: > is there a function/feature/etc.. that i can run on "foo.py" that would walk > through the entire list of files that make up foo.py, so i could see the > list of *.py files that are required to run "foo.py". There's this: http://www.tarind.com/depgraph.html It generates a nice chart showing the 'tree' of imports for your program. I found it valuable for helping me resolve a circular import problem. From nytrokiss at gmail.com Tue Nov 13 15:10:21 2007 From: nytrokiss at gmail.com (James Matthews) Date: Tue, 13 Nov 2007 21:10:21 +0100 Subject: [OT] The Jew Spam on this list In-Reply-To: <5fa6c12e0711130426y2c625e66kdaba332272bc4794@mail.gmail.com> References: <5fa6c12e0711130426y2c625e66kdaba332272bc4794@mail.gmail.com> Message-ID: <8a6b8e350711131210w1011a87u23742cf6c6828fc8@mail.gmail.com> I agree! On Nov 13, 2007 1:26 PM, Martin Marcher wrote: > Hello, > > please do not respond to the "political" spam on this list anymore. > Rather report it as spam to your provider/anti-spam-measures or report > it to the listmasters (if you have the feeling that it helps, I guess > they're already on this issue). > > I understand that this might be a heated topic but people please it's > "just spam" and every message regarding this topic is spam too (funny > enough, so is this message) please just add this stuff to your > killfile or whatever you use. > > thanks > martin > > PS: if you must discuss this opinion with me answer to me off list as > I guess most people just aren't interested... > > -- > http://noneisyours.marcher.name > http://feeds.feedburner.com/NoneIsYours > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.goldwatches.com/movado--watches.html http://www.jewelerslounge.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From cjw at sympatico.ca Sun Nov 25 08:24:23 2007 From: cjw at sympatico.ca (Colin J. Williams) Date: Sun, 25 Nov 2007 08:24:23 -0500 Subject: the annoying, verbose self In-Reply-To: <47475451.3050509@gmx.net> References: <3c954a31-9fb9-4c0f-b784-cef9ee057ca6@g30g2000hsb.googlegroups.com> <6f67fccf-fbec-4c75-baea-5d0277e07883@w40g2000hsb.googlegroups.com> <4745dc0b$0$3051$426a74cc@news.free.fr> <023aa14b-98b3-4e1c-8282-b3fece7e35d2@s19g2000prg.googlegroups.com> <4746D20F.6060507@sympatico.ca> <47475451.3050509@gmx.net> Message-ID: Kay Schluehr wrote: > Colin J. Williams schrieb: >> Kay Schluehr wrote: >>> On Nov 22, 8:43 pm, Bruno Desthuilliers >>> wrote: >>>> Colin J. Williams a ?crit : >>>> >>>> >>>> >>>>> bearophileH... at lycos.com wrote: >>>>>> Alexy: >>>>>>> Sometimes I >>>>>>> avoid OO just not to deal with its verbosity. In fact, I try to use >>>>>>> Ruby anywhere speed is not crucial especially for @ prefix is >>>>>>> better- >>>>>>> looking than self. >>>>>> Ruby speed will increase, don't worry, as more people will use it. >>>>>> Bye, >>>>>> bearophile >>>>> I don't see this as a big deal, but suppose that the syntax were >>>>> expanded so that, in a method, a dot ".", as a precursor to an >>>>> identifier, >>>>> was treated as "self." is currently treated? >>>> >>>> >>>> Python's "methods" are thin wrapper around functions, created at lookup >>>> time (by the __get__ method of the function type). What you define in a >>>> class statement are plain functions, period. So there's just no way to >>>> do what you're suggesting. >>>> >>>> >>> The object model is irrelevant here. The substitution is purely >>> syntactical and gets resolved at compile time: >>> >>> def foo(first, ...): >>> .bar = ... >>> >>> is always equivalent with: >>> >>> def foo(first, ...): >>> first.bar = ... >>> >>> and generates the same bytecode. >>> >>> Whether this is helpfull, beautifull or necessary is another issue. >>> >>> Kay >> I had never thought of trying the above, which is, essentially what I was >> suggesting, as the syntax specifies: >> >> primary ::= >> atom | attributeref >> | subscription | slicing | call >> >> attributeref ::= >> primary "." identifier >> >> I did try it and get: >> >> # tmp.py >> class Z(): >> def __init__(self): >> a= 1 >> self.b= 2 >> #.c= 3 Marked as a syntax error by PyScripter >> >> def y(self): >> self.a= 4 >> #.b= 5 Marked as a syntax error by PyScripter >> >> It seems that some, probably simple, change in the parsing is needed. >> >> Colin W. > > Sure. Since you cite the grammar let me say that I find it somewhat > confusing that the grammar in the Python documentation doesn't > correspond to the grammar used by the CPython parser. For the following > I will use the notations of the Grammar file used by the CPython parser. > > In order to adapt the syntax take a look at > > atom: ('(' [yield_expr|testlist_gexp] ')' | > '[' [listmaker] ']' | > '{' [dictmaker] '}' | > '`' testlist1 '`' | > NAME | NUMBER | STRING+) > > The last row must be changed to > > ['.'] NAME | NUMBER | STRING+) > ~~~~~ > > But then you run into conflict with the definition of the ellipsis in rule > > subscript: '.' '.' '.' | test | [test] ':' [test] [sliceop] > > because you need two token of lookahead. Pythons LL(1) parser might not > manage this. > > This problem vanishes with Python 3.0 which defines an own ellipsis literal: > > atom: ('(' [yield_expr|testlist_comp] ')' | > '[' [testlist_comp] ']' | > '{' [dictorsetmaker] '}' | > NAME | NUMBER | STRING+ | '...' | 'None' | 'True' | 'False') > > Kay > Kay, Could you please elaborate "This problem vanishes with Python 3.0 which defines an own ellipsis literal"? It seems that ellipsis remains "..." - I've never found a use for it. See http://docs.python.org/dev/3.0/library/constants.html#Ellipsis Colin W. From arkanes at gmail.com Tue Nov 6 14:04:57 2007 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 6 Nov 2007 13:04:57 -0600 Subject: Populating huge data structures from disk In-Reply-To: <000001c820a1$78750ea0$695f2be0$@com> References: <000001c820a1$78750ea0$695f2be0$@com> Message-ID: <4866bea60711061104i514838fcld9bbba1382a764a6@mail.gmail.com> On Nov 6, 2007 12:18 PM, Michael Bacarella wrote: > > > > > For various reasons I need to cache about 8GB of data from disk into core on > application startup. > Are you sure? On PC hardware, at least, doing this doesn't make any guarantee that accessing it actually going to be any faster. Is just mmap()ing the file a problem for some reason? I assume you're on a 64 bit machine. > Building this cache takes nearly 2 hours on modern hardware. I am surprised > to discover that the bottleneck here is CPU. > > > > The reason this is surprising is because I expect something like this to be > very fast: > > > > #!python > > > > import array > > a = array.array('L') > > f = open('/dev/zero','r') > > while True: > > a.fromstring(f.read(8)) > > This just creates the same array over and over, forever. Is this really the code you meant to write? I don't know why you'd expect an infinite loop to be "fast"... > > > > Profiling this application shows all of the time is spent inside > a.fromstring. > Obviously, because that's all that's inside your while True loop. There's nothing else that it could spend time on. > Little difference if I use list instead of array. > > > > Is there anything I could tell the Python runtime to help it run this > pathologically slanted case faster? > This code executes in a couple seconds for me (size reduced to fit in my 32 bit memory space): Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import array >>> s = '\x00' * ((1024 **3)/2) >>> len(s) 536870912 >>> a = array.array('L') >>> a.fromstring(s) >>> You might also want to look at array.fromfile() From robin at NOSPAMreportlab.com Fri Nov 16 14:55:09 2007 From: robin at NOSPAMreportlab.com (Robin Becker) Date: Fri, 16 Nov 2007 19:55:09 +0000 Subject: timing puzzle In-Reply-To: References: <473DE4A6.4010208@chamonix.reportlab.co.uk> Message-ID: <473DF59D.6070200@jessikat.plus.net> Chris Mellon wrote: ........ > > remove() does a linear search to find the item to remove, so it's O(n) > + the actual deletion. Append() is amortized O(1) (overcommit). If you > delete by index instead: > for idx, node in active_nodes: > if cond: > del active_nodes[idx] > > that's what I was missing; my indexed deletes avoid the linear search. I was looking only at the data movements > You should see performance comparable to your second option. If you > can trade memory for performance, discarding the old active_nodes > might be even faster: > active_nodes = [node for node in active_nodes if node not in > deleted_nodes], where deleted_nodes is a set. > > > Normal micro-optimization techniques apply here too, like looking up > the remove() method ahead of time and so on. >..... yes indeed and they'll start to count if I can eliminate the main problem areas. -- Robin Becker From gagsl-py2 at yahoo.com.ar Mon Nov 19 14:55:45 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 19 Nov 2007 16:55:45 -0300 Subject: newbie Q: sequence membership References: <8a934485-efd4-4e89-ac1b-d7c277978686@l22g2000hsc.googlegroups.com> <17880eed-b3c1-4d77-854a-cf8e24a56746@w73g2000hsf.googlegroups.com> Message-ID: En Mon, 19 Nov 2007 03:32:12 -0300, saccade escribi?: > So if I am permitted to think of integers as immutable objects with > predefined labels (i.e. the integers used in the text of the program > code) that cannot de or re referenced then what a similar treatment of > characters will look like seams to be an arbitary (a design) decition. > > In this vein it seams reasonable to expect 'a'[0] and 'ba'[1] to refer > to the same object. If one follows the convention used with integers > (9 and 9 refer to the same object) then 'ab' and 'ab' would be the > same. An equally reasonable assumption would be that 'ab' and 'ab' are > two different sequences and so not equal (I do not see the problem > here). Note that the fact that integers are immutable means that Python *could* share the same integer object any time that integer appears on the program. For mutable objects --lists by example-- this is not possible because different instances of the "same" list may be changed independently. In the following example, both x and y *could* refer to the same object, but they don't: py> x=1000 py> y=1000 py> x is y False In contrast, small integers are shared: py> x=10 py> y=10 py> x is y True So immutability is a *necessary* condition for literals to be shared (in the Python object model), but it's not *sufficient*. -- Gabriel Genellina From beacybooks at bigpond.com Tue Nov 27 05:45:45 2007 From: beacybooks at bigpond.com (Tom Harris) Date: Tue, 27 Nov 2007 21:45:45 +1100 Subject: Passing arguments to subclasses of unittest.TestCase Message-ID: <474BF559.70803@bigpond.com> Hi, Is there a way to pass arguments to TestCases when running tests? I have a test suite that need to be configured slightly differently for 3 different products, and rather than do a hack I wondered if there was a canonical way to do it. I _know_ that py.test can do it trivially. I am rather stuck with unittest, as I have 84 testcases, and I have to make it work tomorrow. -- Tom Harris BeacyBooks bigpondcom> From bluegraydragon at gmail.com Thu Nov 1 10:52:19 2007 From: bluegraydragon at gmail.com (bluegray) Date: Thu, 01 Nov 2007 14:52:19 -0000 Subject: serving html from a python script in IE Message-ID: <1193928739.157628.291110@50g2000hsm.googlegroups.com> I'm writing a script that outputs html. It works fine in Firefox, however, IE wants to download the file instead of displaying the output. I keep getting the file download dialog instead of the html page. I am doing something like this: print 'Content-Type: text/html ; charset=utf-8\nCache-Control: no-cache \n' print 'some text and html' I also tried various things in .htaccess which has the following line: AddHandler cgi-script .py Any help will be appreciated. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Nov 16 12:52:14 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 16 Nov 2007 18:52:14 +0100 Subject: Python Design Patterns - composition vs. inheritance In-Reply-To: References: Message-ID: <473dd8cc$0$15766$426a74cc@news.free.fr> snewman18 at gmail.com a ?crit : > In learning about design patterns, I've seen discussion about using > inheritance when an object's relationship to another object is 'is-a' > and composition when the relationship is 'has-a'. wrt/ inheritance, it only makes sens with declarative static type systems where polymorphic dispatch depends on subclassing (so inheritance is used for both implementation and subtyping). In the context of a dynamic type system, inheritance is only for implementation reuse, ie given the following class definitions : class Foo(object): def bar(self): return 42 class Baaz(object): def bar(self): return 84 Baaz actually 'is a' (proper subtype of) Foo (and vice-versa). > > Since this is all new and I'm still learning, I was hoping someone can > give me some pointers on best practices on applying these ideas. If my > logic is incorrect on anything, please don't hesitate to tell me where > I'm wrong - I'm completely open to any help offered. > > As a very simplified example, if I had two classes, Pet and Owner, it > seems that I would not have Pet inherit from Owner, since a pet 'has > an' owner, but not 'is an' owner. Both (I mean 'has a' and 'is a') are not necessary exclusive. > If this is correct, does my code > below reflect this? I passed the owner object into the pet object's > constructor - is this the right way to do it? Here again, it depends on the lifetime cycles of both objects. Look for the difference between composition and aggregation. And it of course depends on the problem you're trying to solve - there's no such thing as an 'absolute' model. > Also, I've seen talk that ideally you shouldn't have too many "dots" > in your method calls, instead using delegates to the methods and > attributes. Can anyone elaborate on this? "should", "should not", laws and golden rules... Indeed, it's usually better to respect encapsulation. > Ideally, should I be writing > getattr() methods so I can do pet.address instead of > pet.owner.address? What's the use of pet.address ? Is really 'adress' a responsability of 'Pet' ? > Should I be doing the same with owner's methods > like I did with get_foo()? Python's methods actually are attributes, so you don't (technically) need a distinct scheme for methods - __getattr__ will work as well. __getattr__ is fine when you really have a generic delegation (look for the Proxy pattern for an example). Else (ie, you decide that, for this given problem, 'address' is really a responsability of Pet), you might be better defining an explicit 'address' attribute in Pet - preferably using a computed attribute (either a property object or a custom descriptor). Anyway, the simplest your design and implementation, the better. My 2 cents... From fredrik.johansson at gmail.com Sun Nov 25 13:32:34 2007 From: fredrik.johansson at gmail.com (Fredrik Johansson) Date: Sun, 25 Nov 2007 19:32:34 +0100 Subject: Trouble getting loop to break In-Reply-To: <20071125134710.052861E4003@bag.python.org> References: <48f9c4a1-ae3a-4fdf-97f3-4c76e12d5aeb@b15g2000hsa.googlegroups.com> <20071120210132.BF3D11E499A@bag.python.org> <3d0cebfb0711201332r71f1621bue29a8ec19f7f65d8@mail.gmail.com> <20071125080046.874391E4002@bag.python.org> <3d0cebfb0711250326k2e7654f4r9effbb4431156dbc@mail.gmail.com> <20071125134710.052861E4003@bag.python.org> Message-ID: <3d0cebfb0711251032j45babaf3gc01ef32ff930f865@mail.gmail.com> On Nov 25, 2007 2:47 PM, Dick Moores wrote: > Wow. your f() is ingenious, Frederik. Thanks very much. > > Any more tricks up your sleeve? You did say a post or so ago, > "Further improvements are possible." The next improvement would be to find a recurrence formula for the terms instead of computing them directly. So for example, if summing over c[n] = x**n / n!, instead of computing c[n] = x**n / factorial(n) for each n, you'd compute c[0] and then just do c[n] = c[n-1] * x / n for each of the remaining terms. Fredrik From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Nov 2 12:27:26 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 02 Nov 2007 17:27:26 +0100 Subject: python newbie In-Reply-To: <472b2b84$0$13761$6e1ede2f@read.cnntp.org> References: <472b2b84$0$13761$6e1ede2f@read.cnntp.org> Message-ID: <472b4fe0$0$9223$426a34cc@news.free.fr> Jim Hendricks a ?crit : > New to python, programming in 15 or so langs for 24 years. > > Couple of questions the tuts I've looked at don't explain: > > 1) global vars - python sets scope to the block a var is declared (1st > set), I see the global keyword that allows access to global vars in a > function, what I'm not clear on is does that global need to be declared > in the global scope, or, when 1st set in a function where it is listed > as a global, does that then declare the necessary global. Didn't you try by yourself ? Would have been faster than writing down your question... Python 2.5.1 (r251:54863, May 2 2007, 16:56:35) [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> def toto(): ... global p ... p = 42 ... >>> p Traceback (most recent call last): File "", line 1, in NameError: name 'p' is not defined >>> toto() >>> p 42 >>> Anyway, remember that in Python, 'global' really means 'module level'. > 2) Everything is an object. So then, why the distinction between > functions/variables and fields/methods. If a module is an object, would > not every function be a method of that module functions are *instance* attributes of the modules (obviously, since each module is a distinct instance of class 'module'...), and when functions are instance attributes of an object, the lookup mechanism doesn't turn them into methods. > and every variable be a > field of that module? There's nothing like a 'field' in Python - only attributes. And module-level (so-called 'global') vars *are* attributes of the module. So from 'the outside' (ie: from the importing code), a module is just an instance of class module, with it's own set of attributes - some of them callables (functions and classes), some other not. HTH From S.Mientki-nospam at mailbox.kun.nl Thu Nov 29 04:40:38 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Thu, 29 Nov 2007 10:40:38 +0100 Subject: Very basic, sorting a list ??? In-Reply-To: References: <474E064C.9040303@gmail.com> Message-ID: <29080$474e8916$83aef404$7726@news1.tudelft.nl> Peter Decker wrote: > On Nov 28, 2007 7:22 PM, stef mientki wrote: >> print 'xx3',ordered_list.sort() > > The sort() method returns None. It sorts the list in place; it doesn't > return a copy of the sorted list. > Thank you all for the answers, I do understand now, although I find it rather non-intuitive. I didn't expect a copy, but a reference to itself wouldn't be asked too much ? Why does it return None, instead of the sorted object itself ? I guess it would cost almost exactly the same processing power. cheers, Stef Mientki From rolf.wester at ilt.fraunhofer.de Thu Nov 15 05:47:58 2007 From: rolf.wester at ilt.fraunhofer.de (Rolf Wester) Date: Thu, 15 Nov 2007 11:47:58 +0100 Subject: Memory problem In-Reply-To: <5q2lf4Ftr3plU1@mid.uni-berlin.de> References: <473c1d40$1@news.fhg.de> <5q2lf4Ftr3plU1@mid.uni-berlin.de> Message-ID: <473c23e1$1@news.fhg.de> Sorry, of course your are wright. I'm running Python2.5 on Linux, my program imports numpy, matplotlib, sys and a python module of my own. This module uses numpy and scipy.weave for imbedded C-code but no extension modules. I though the code to be to large to show, I hoped you could give me hint on what I could try. Thank you in advance Rolf Diez B. Roggisch wrote: > Rolf Wester wrote: > >> Hi, >> >> I have a strange (for me) memory problem. When running a loop in a >> Python program memory usage increases from about 4% up to 100%. I do a >> gc.collect() every loop cycle but this doesn't help. There are about >> 67000 objects that are tracked by the garbage collector. This number >> does vary a little bit but does not increase on average whereas the >> memory usage does. The number of garbage objects (len(gc.garbage()) is >> zero. This is a very severe problem for my application, so I would be >> very appreciative for any help. > > well, it might be that the relative moon humidity resonates with the > loop-cycle, creating quantum-flux in the main memory banks. > > Or not. > > Seriously - what help do you expect without showing us _any_ code or at > least getting into details like usage of libs, python-version, possible > C-extensions, platform, .... > > Diez From mail at timgolden.me.uk Tue Nov 27 11:51:12 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 27 Nov 2007 16:51:12 +0000 Subject: count pages in a pdf In-Reply-To: <08f76ce6-0484-4b0e-ad4f-610b6877acdc@a35g2000prf.googlegroups.com> References: <08f76ce6-0484-4b0e-ad4f-610b6877acdc@a35g2000prf.googlegroups.com> Message-ID: <474C4B00.1050409@timgolden.me.uk> belred at gmail.com wrote: > is it possible to parse a pdf file in python? for starters, i would > like to count the number of pages in a pdf file. i see there is a > project called ReportLab, but it seems to be a pdf generator... i > can't tell if i would be able to parse a pdf file programmically. Well the simple expedient of putting "python count pages pdf" into Google turned up the following link: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496837 and no few others. Might be worth a look? TJG From jcd at sdf.lonestar.org Wed Nov 7 07:35:27 2007 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Wed, 07 Nov 2007 07:35:27 -0500 Subject: regular expressions In-Reply-To: <1194372017.649776.109750@19g2000hsx.googlegroups.com> References: <1194367773.329640.202340@i13g2000prf.googlegroups.com> <1194372017.649776.109750@19g2000hsx.googlegroups.com> Message-ID: <4731B10F.8030200@sdf.lonestar.org> Paul McGuire wrote: > On Nov 6, 11:07 am, "J. Clifford Dyer" wrote: > >> On Tue, Nov 06, 2007 at 08:49:33AM -0800, krishnamanenia... at gmail.com wrote regarding regular expressions: >> >> >> >> >>> hi i am looking for pattern in regular expreesion that replaces >>> anything starting with and betweeen http:// until / >>> likehttp://www.start.com/startservice/yellow/fdhttp://helo/abcdwill >>> be replaced as >>> p/startservice/yellow/ fdp/abcd >>> >> You don't need regular expressions to do that. Look into the methods that strings have. Look at slicing. Look at len. Keep your code readable for future generations. >> >> Py>>> help(str) >> Py>>> dir(str) >> Py>>> help(str.startswith) >> >> Cheers, >> Cliff >> > > Look again at the sample input. Some of the OP's replacement targets > are not at the beginning of a word, so str.startswith wont be much > help. > > Here are 2 solutions, one using re, one using pyparsing. > > -- Paul > > > instr = """ > anything starting with and betweeen "http://" until "/" > like http://www.start.com/startservice/yellow/ fdhttp://helo/abcd > will > be replaced as > """ > > REPLACE_STRING = "p" > > # an re solution > import re > print re.sub("http://[^/]*", REPLACE_STRING, instr) > > > # a pyparsing solution - with handling of target strings inside quotes > from pyparsing import SkipTo, replaceWith, quotedString > > replPattern = "http://" + SkipTo("/") > replPattern.setParseAction( replaceWith(REPLACE_STRING) ) > replPattern.ignore(quotedString) > > print replPattern.transformString(instr) > > > Prints: > > anything starting with and betweeen "p/" > like p/startservice/yellow/ fdp/abcd will > be replaced as > > > anything starting with and betweeen "http://" until "/" > like p/startservice/yellow/ fdp/abcd will > be replaced as > > Interesting. In my email clients, they do show up at the beginning of words (thunderbird and mutt), but in your reply they aren't. I wonder if there's some funky unicode space that your computer isn't rendering.... Or something on my end. There were definitely spaces in his email as it appears on my computer. But if there aren't, s.startswith() is clearly not the way to go. -------------- next part -------------- An HTML attachment was scrubbed... URL: From samckain at southslope.net Thu Nov 1 01:35:10 2007 From: samckain at southslope.net (Steve) Date: Thu, 1 Nov 2007 05:35:10 +0000 (UTC) Subject: Dictionary help References: Message-ID: On Wed, 31 Oct 2007 17:02:49 -0500, Larry Bates wrote: > Steve wrote: >> I'm currently working on a little database type program is which I'm >> using a dictionary to store the information. The key is a component a >> and the definition is a list of parts that make up the component. My >> problem is I need to list out several components, but not all, and >> there associated parts to a printer. Not having any luck. I can list >> them to the screen but not the printer. Any help/ideas would be >> appreciated. >> >> Steve > > Windows or Linux or Mac. Printers are handled differently on different > platforms. On Windows you can simply open LPT1, LPT2 or LPT3 as a file > and write to it (for simple printing). For more complex "Windows" > printing you must use Win32 extensions or something like wxWindows. > > -Larry I'm currently using Linux. I give it some more thought and research and see what I can come up with. Thank you for the reply. Steve From vel.accel at gmail.com Sun Nov 11 17:23:58 2007 From: vel.accel at gmail.com (D.Hering) Date: Sun, 11 Nov 2007 22:23:58 -0000 Subject: Extended date and time In-Reply-To: <1194817612.504392.213690@o3g2000hsb.googlegroups.com> References: <1194817612.504392.213690@o3g2000hsb.googlegroups.com> Message-ID: <1194819838.527806.18850@o3g2000hsb.googlegroups.com> On Nov 11, 4:46 pm, "D.Hering" wrote: > On Nov 10, 10:37 am, Jeremy Sanders > I also have trouble with date/times with whats available. Off the top > of my head... converting a numpy array of epochs to some datetime > object and back. > > If I had the time I'd contribute additional functionality to Pierre's > and Matt's TimeSeries module (the one in scipy). > > -dieter I made a request for this to Pierre and Matt on the scipy-user list. From ricaraoz at gmail.com Fri Nov 2 06:24:35 2007 From: ricaraoz at gmail.com (=?ISO-8859-15?Q?Ricardo_Ar=E1oz?=) Date: Fri, 02 Nov 2007 07:24:35 -0300 Subject: Need some help... In-Reply-To: References: <1193560272.637389.315680@e34g2000pro.googlegroups.com> <47271907$1_6@news.bluewin.ch> <4729e9a8$1_4@news.bluewin.ch> <472A5D74.1050603@bigfoot.com> Message-ID: <472AFAE3.4030202@bigfoot.com> Gabriel Genellina wrote: > En Thu, 01 Nov 2007 20:12:52 -0300, Ricardo Ar?oz > escribi?: > >>>>>>> def sumToOneDigit(num) : >>>> if num < 10 : >>>> return num >>>> else : >>>> return sumToOneDigit(sum(int(i) for i in str(num))) >>>> > > def sumToOneDigit(num): > return num % 9 or 9 > > Valid when num>=1, which is guaranteed by the OP context. > Beautiful. Much better than mine. From BjornSteinarFjeldPettersen at gmail.com Fri Nov 2 05:56:50 2007 From: BjornSteinarFjeldPettersen at gmail.com (thebjorn) Date: Fri, 02 Nov 2007 09:56:50 -0000 Subject: Iterable Flattener with Depth. In-Reply-To: <1193981554.692209.226450@o3g2000hsb.googlegroups.com> References: <1193918613.831666.305230@k79g2000hse.googlegroups.com> <1193981554.692209.226450@o3g2000hsb.googlegroups.com> Message-ID: <1193997410.835980.36250@22g2000hsm.googlegroups.com> On Nov 2, 6:32 am, praddy wrote: > On Nov 1, 5:03 pm, bearophileH... at lycos.com wrote: > > > Pradeep Jindal: > > > > Any comments? > > > Something with similar functionality (plus another 20 utility > > functions/classes or so) has probably to go into the std lib... :-) > > > Bye, > > bearophile > > Same Here! > > - Pradeep Yeah, everyone has to write a flatten sooner or later :-) My version is at: http://blog.tkbe.org/archive/python-flatten/ -- bjorn From Alex.Holkner at gmail.com Fri Nov 9 09:55:58 2007 From: Alex.Holkner at gmail.com (Alex Holkner) Date: Sat, 10 Nov 2007 01:55:58 +1100 Subject: ANN: pyglet 1.0beta1 Message-ID: <473474FE.7060607@gmail.com> Greetings I am pleased to announce the first public beta of pyglet, a cross-platform windowing and multimedia package useful for developing games and other visually-rich applications. http://www.pyglet.org pyglet is written entirely in Python, with no external requirements needed to develop applications for Windows XP, Mac OS X or Linux. pyglet allows applications to open any number of top-level windows and draw into them using the OpenGL API. Multiple-monitor setups are well-supported. Applications using pyglet can also play sound and music samples in surround-sound, taking advantage of hardware acceleration where available. With the addition of a single DLL based on FFmpeg, applications can read compressed sound and video in many formats. pyglet is provided under the BSD open-source license, allowing you to use it for both commercial and other open-source projects with very little restriction. Cheers, Alex. From horpner at yahoo.com Fri Nov 2 09:01:34 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Fri, 02 Nov 2007 13:01:34 GMT Subject: Syntax coloring in Python interpreter References: <1193939152.721480.140500@22g2000hsm.googlegroups.com> Message-ID: On 2007-11-02, Tim Golden wrote: > Neil Cerutti wrote: >> On 2007-11-01, Chris Mellon wrote: >>> On Nov 1, 2007 3:01 PM, Neil Cerutti wrote: >>>> On 2007-11-01, Lee Capps wrote: >>>>> On Nov 1, 2007, at 1:45 PM, braver wrote: >>>>>> Greetings -- as a long time user of both Python and Ruby >>>>>> interpreters, I got used to the latter's syntax-coloring gem, >>>>>> wirble, which colorizes Ruby syntax on the fly. Is there >>>>>> anything similar for Python? >>>>>> >>>>> I believe IPython can do this: >>>>> >>>>> http://ipython.scipy.org/moin/ >>>> IPython's syntax coloring doesn't work with Windows 2000 and >>>> up, since (last I checked) it relies on a readline.py file, >>>> which relies on ANSI.SYS, which is not supported by the >>>> Windows console. >>> If you scroll down about half a page in the above link you'll >>> find a link to a readline implementation for Windows. >> >> That pyreadline.py appears to be an improvement on the Windows >> support when I last looked (6 months or so ago). Thanks for the >> heads up. >> > > And it's worth looking at ipykit[1] which is a standalone > bundle of ipython py2exe-ed for Windows users. > > TJG > > [1] http://ipython.scipy.org/moin/IpyKit I installed the new version and the coloring works out of the box on Windows 2000 with Gary's PyReadline 1.4.4. -- Neil Cerutti If you throw at someone's head, it's very dangerous, because in the head is the brain. --Pudge Rodriguez From mc.pandey at gmail.com Fri Nov 23 06:43:31 2007 From: mc.pandey at gmail.com (mc.pandey at gmail.com) Date: Fri, 23 Nov 2007 03:43:31 -0800 (PST) Subject: how to write event handler for dropdown list Message-ID: <3fb04cf6-01ef-4f94-bb34-e86cf8f24949@e6g2000prf.googlegroups.com> Hi, I am new to python, Can someone help me with writing event handler for a dropdown list in python. i have one function to create dropdown list in a file def dropdown_options(self,title,options,name,value = None): ret = "\n"+ title.title() + " \n" if (options != []): ret += "" else: ret += "No options available for this item" return ret and i am calling this from another file ret += ui.dropdown_options("Project",db.getprojects(user),"proj") + ui.linebreak() Now i want to do some activity when i select diffrent options from the dropdown list. Any help is appreciated !! From cokofreedom at gmail.com Thu Nov 22 06:39:23 2007 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Thu, 22 Nov 2007 03:39:23 -0800 (PST) Subject: Problems with if/elif statement syntax References: <4d58211e-ebe8-40fe-80ae-cf8b4a56f9ec@d21g2000prf.googlegroups.com> Message-ID: <3bc076d3-9164-473f-859e-5f0daea83c56@d27g2000prf.googlegroups.com> On Nov 22, 12:33 pm, "riqu... at gmail.com" wrote: > On 22 Nov, 12:09, Neil Webster wrote: > > > > > Hi all, > > > I'm sure I'm doing something wrong but after lots of searching and > > reading I can't work it out and was wondering if anybody can help? > > > I've got the following block of code: > > if a >= 20 and a < 100: > > if c == "c": > > radius = 500 > > else: > > radius = 250 > > elif (a >= 100) and (a < 500): > > radius = 500 > > elif (a >= 500) and (a < 1000): > > radius = 1000 > > elif (a >= 1000) and (a < 3000): > > radius = 1500 > > elif (a >= 3000) and (a < 5000): > > radius = 2000 > > else: > > radius = 4000 > > > No matter what value goes in for 'a' the radius always comes out as > > 4000. > > > What am I doing wrong? > > > Cheers > > > Neil > > as Oliver pointed out, check if you're not compairing "a" as a string > > I wanted to let you know that you can write the above conditions in a > more natural way, using the a > e.g. > > x=int(raw_input("write a number")) > if 5<=x<30: > print 'x is between 5 and 30' Argh, I really dislike raw_input. Though it helps to remind me to use Try:Except blocks a lot. From davisn90210 at gmail.com Sat Nov 17 13:44:32 2007 From: davisn90210 at gmail.com (davisn90210 at gmail.com) Date: Sat, 17 Nov 2007 10:44:32 -0800 (PST) Subject: Python too complex ?!?!?! References: <7hC%i.28332$mv3.17248@newsfe10.phx> Message-ID: On Nov 17, 8:25 am, Donn Ingle wrote: > I dunno about your dog :) but Python libs are not too demanding. From a > Gnu/Linux pov with package managers things are quite simple. > > My wish is to find a way to make that even easier because the packaged > modules are not always up to date. > > If the Cheese Shop could supply downloads of modules and we could stick on a > gui interface that wraps around import statements to guide the installation > of any missing packages -- that would be progress. > Interesting idea, although it's not something I'd want included and turned on by default. Should certainly be possible, though, with a little __import__ magic. > If you are online and the app runs, it can check the "freshness" of your > modules (those called from the app and recursively) and offer to fetch the > latest stable versions. > Something similar to Java's webstart? Implement an __import__ hook that downloads and caches the latest (stable) versions of libraries as needed. > The gui is an issue. Does one TK or rely on some fall-back system of > gnome/kde/x11/windows dialogue boxes (ending in abject failure by way of > raw_input on the command line)? Or (perhaps) have it fetch a standard > dialogue library which would fetch and install what is needed for future > occasions. > You wouldn't really *need* a GUI, although it probably should be a configurable option ... so the user can keep tabs on, and more control over, what's going on. No reason why it couldn't be totally automated. easy_install already provides for automated installation of python apps/libraries, so you could build off that. > Anyway, this is a bit of a hijack and I have not touched C# in any way, but > I don't think Python has anything to be ashamed of.* > > /d > > * Okay, maybe decorators but that's just because I am far too thick to grok > them :D It seems there are a number of people who don't grok decorators. While getting to know how they work underneath does require some careful reading and out-of-the-box thinking, it's only really necessary to understand them at this level if you want to actually implement a decorator. Merely using decorators is, IMHO, much easier to understand (but still requires a slight brain-warp). I think some people try to understand decorators too completely too quickly, and end up labeling them one of those complex/unintuitive/"way out" things. --Nathan Davis From gnewsg at gmail.com Fri Nov 2 12:44:37 2007 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Fri, 02 Nov 2007 09:44:37 -0700 Subject: os.readlink returning value In-Reply-To: References: <1193968274.369843.167520@v3g2000hsg.googlegroups.com> Message-ID: <1194021877.535595.38340@19g2000hsx.googlegroups.com> On 2 Nov, 05:30, "Gabriel Genellina" wrote: > En Thu, 01 Nov 2007 22:51:14 -0300, Giampaolo Rodola' > escribi?: > > > I was reading os.readlink doc which says: > > > readlink( path) > > > Return a string representing the path to which the symbolic link > > points. The result may be either an absolute or relative pathname; if > > it is relative, it may be converted to an absolute pathname using > > os.path.join(os.path.dirname(path), result). Availability: Macintosh, > > Unix. > > > ...It's not clear to me when the returning result could be absolute > > and when it could be relative. > > Could someone clarify this point? > > That depends on how the symlink was created. Assume the current directory > is /usr/home/giampaolo/any/dir> ln -s ../foo/bar > > creates a symbolic link at /usr/home/giampaolo/any/dir/bar pointing to > ../foo/bar (relative to where the link resides). That is, actually > pointing to /usr/home/giampaolo/any/foo/bar (but this absolute path is NOT > stored on the link itself - only ../foo/bar) > > Now, a program whose current directory is /usr/home/giampaolo executes > this: > readlink("any/dir/bar") > It will return the string "../foo/bar". One must resolve the .. reference > relative to where the link resides, NOT relative to the current directory. > That is, relative to any/dir. os.path.dirname("any/dir/bar") returns > exactly that. Then, the suggested expression in the docs evaluates to > "any/dir/../foo/bar" - it's not an absolute pathname yet, one should use > abspath() on it. Or instead > os.path.join(os.path.abspath(os.path.dirname(path)), result) > > -- > Gabriel Genellina Thanks for the examplanation. I'd only want to do the same as what ls does in such cases. Imho, os.readlink() should have the same behaviour of ls, isn't it? From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Nov 2 08:51:43 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 02 Nov 2007 13:51:43 +0100 Subject: new style class References: <1194002609.296417.111050@v3g2000hsg.googlegroups.com> <1194004712.691884.249570@v3g2000hsg.googlegroups.com> Message-ID: <5p0kqvFopmkaU1@mid.individual.net> gert wrote: > Could not one of you just say "@staticmethod" for once damnit :) No, since everyone's crystal balls are in repair. Regards, Bj?rn -- BOFH excuse #256: You need to install an RTFM interface. From bj_666 at gmx.net Wed Nov 7 14:42:04 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 7 Nov 2007 19:42:04 GMT Subject: os.popen does not seem to catch stdout References: <1194443892.026237.67480@e9g2000prf.googlegroups.com> <1194453068.928713.117600@o38g2000hse.googlegroups.com> <1194459474.813737.27540@k79g2000hse.googlegroups.com> <1194460551.058503.298510@d55g2000hsg.googlegroups.com> Message-ID: <5peiocFqub38U3@mid.uni-berlin.de> On Wed, 07 Nov 2007 18:35:51 +0000, kyosohma wrote: > I've never had to put the command into a list or tuple...but you're > welcome to try it that way. You don't *have* to but if you do the module takes care of quoting the arguments if necessary. Ciao, Marc 'BlackJack' Rintsch From Russ.Paielli at gmail.com Sun Nov 4 21:40:23 2007 From: Russ.Paielli at gmail.com (Russ P.) Date: Mon, 05 Nov 2007 02:40:23 -0000 Subject: IDLE In-Reply-To: <1194083030.802919.176650@z24g2000prh.googlegroups.com> References: <1194043445.147572.126100@k35g2000prh.googlegroups.com> <1194083030.802919.176650@z24g2000prh.googlegroups.com> Message-ID: <1194230423.898270.15500@v23g2000prn.googlegroups.com> On Nov 3, 1:43 am, rustompm... at gmail.com wrote: > Just curious: What makes you wish to move from emacs to idle? I don't necessarily want to move from xemacs to idle. I'm just getting tired of using print statements to debug, and I figure I'm well past the stage where I should still be doing that. If I can use xemacs *with* idle, I'll try that. Then again, if gdb works with python, maybe I should be using that with xemacs. The local Python interest group had a meeting to discuss these development environments, but unfortunately I missed it. I hope they do another one soon. From bignose+hates-spam at benfinney.id.au Wed Nov 28 18:08:40 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 29 Nov 2007 10:08:40 +1100 Subject: How to Teach Python "Variables" References: <4749bb94$1@news.bezeqint.net> Message-ID: <87ve7mrmrr.fsf@benfinney.id.au> "Chris Mellon" writes: > Whether you like it or not, the term "pointer" has a specific common > meanings. They do not mean "any means by which you may reference a > value". "variable" is certainly less clear and is used much more > loosely, but in the specific context of comparison to C, python > name/object bindings are not the same as C variables. Yes. Further, "in the specific context of comparison to C" was all this thread was *ever* about at the beginning: none <""atavory\"@(none)"> writes: > Hello, > > IIRC, I once saw an explanation how Python doesn't have > "variables" in the sense that, say, C does, and instead has bindings > from names to objects. Does anyone have a link? So please, let's stop trying to brinng up "pointer" and "variable" with some pure language-independent meaning that is the only one we should consider. The *specific context* here is the existing preconceptions programmers bring from other languages like C. -- \ "Anytime I see something screech across a room and latch onto | `\ someone's neck, and the guy screams and tries to get it off, I | _o__) have to laugh, because what is that thing?" -- Jack Handey | Ben Finney From enleverlesX.XmcX at XmclaveauX.com Fri Nov 23 07:13:35 2007 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI (MVP)) Date: Fri, 23 Nov 2007 13:13:35 +0100 Subject: Is there pointer * in Python? In-Reply-To: References: Message-ID: <4746c51e$0$5067$ba4acef3@news.orange.fr> Hi! > like in C Why think to C? Why not Cobol? APL? Intercal? For think right in Python, forget C, forget others languages, think inside Python... Michel Claveau From nytrokiss at gmail.com Mon Nov 26 19:45:00 2007 From: nytrokiss at gmail.com (James Matthews) Date: Tue, 27 Nov 2007 01:45:00 +0100 Subject: Rss Feed Creator Message-ID: <8a6b8e350711261645p1b41b0e0rda70204462e1a8b9@mail.gmail.com> Hi, I am looking for a library that will create Rss/Atom feeds in python. It needs to format the XML in a readable format! Does anyone have any suggestions? Thanks James -- http://search.goldwatches.com/?Search=Movado+Watches http://www.goldwatches.com/coupons http://www.jewelerslounge.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From tal.no.no.spam at gmail.com Sat Nov 3 11:00:45 2007 From: tal.no.no.spam at gmail.com (Tal Einat) Date: Sat, 03 Nov 2007 08:00:45 -0700 Subject: difference between IDLE and command line In-Reply-To: <472b5294$0$13762$6e1ede2f@read.cnntp.org> References: <472b5294$0$13762$6e1ede2f@read.cnntp.org> Message-ID: <1194102045.657085.133020@57g2000hsv.googlegroups.com> Jim Hendricks wrote: > I have been editing my code in UltraEdit then testing in IDLE by > choosing open, then F5. I didn't see an easy way to refresh in IDLE, so > each edit I've been closing the file (not IDLE itself), then opening > again. Since IDLE does not keep track of what directory I last opened > from, this gets tedious, so I decided to run my code from the command line. Tip: IDLE has a recent files list, under the File menu. Use Alt-f Alt- r to access it quickly. Tip #2: You can run a script in IDLE from the command line: IDLE -r