Re: Regular Expression Syntax Help
Oh! yes you can use re for that. You just need to change the pattern a bit I did not understand where the "title" will be so I have ignored it, but I got something below which will be helpful for you >>> value = """name:asasasasas\nrequest: play\ntitle""" >>> reg = re.compile('Name:.*\\nrequest:.', re.IGNORECASE) >>> re.findall(reg, value) ['name:asasasasas\nrequest: play'] >>> value2 = """name:asasasasas\nrequest: next\ntitle""" >>> reg = re.compile('Name:.*\\nrequest:.', re.IGNORECASE) >>> re.findall(reg, value2) ['name:asasasasas\nrequest: next'] >>> -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 2.4.2 using msvcrt71.dll on Win and compatibility issues
Martin v. Löwis wrote: > Christoph Zwerschke wrote: >> I understand what you mean. But the Postgres dll provides no means to >> fdopen a new stream. > > Right. So you must do so in the pygresql module. That means you have > to get hold of msvcrt.dll's (sic) fdopen implementation. > > One way to do so would be through linking pygresql to msvcrt.dll, > instead of linking it to msvcr71.dll. I think this would only shift the problem. Because then I would have to convert the msvcr71 stream I get from Python to a msvcrt stream. Using fileno() (of msvcrt) to get the file descriptor will probably not work. > The other option is to use GetProcAddress to obtain the address of > fdopen. That would be an option. However, I would need to know the handle of the PostgreSQL dll module. Is there an easy way to get it (without having to hard-code the explicit name of the dll)? In any way, it seems I have to insert a lot of platform-dependent, ugly code. In my case, it is probably easier to simply mimic the Postgres PQprint() function provided by the dll in PyGreSQL. It is not such a complicated thing. Plus it is only called with fixed parameters, so I don't need the complete functionality. PQprint() is considered obsolete anyway and may vanish one day. But thanks a lot for your help. Sometimes you don't know whether you're doing something terribly wrong or missing a very easy solution if you don't discuss with others. -- Christoph -- http://mail.python.org/mailman/listinfo/python-list
only a simple xml reader value
H!, Is it possible to get a value value ? When I do this: - theXML = """ The Fascist Menace """ import xml.dom.minidom as dom doc = dom.parseString(theXML) print doc.getElementsByTagName('title')[0].toxml() I get : The Fascist Menace thats oke for me - But the xmlfile I must read have other tags: theXML = """ The Fascist Menace bla la etc """ how to get that values ? I try things like: print doc.getElementsByTagName('title:id')[0].toxml() <--error Thanks, GC-Martijn -- http://mail.python.org/mailman/listinfo/python-list
Re: tricky regular expressions
I had a somewhat similar problem that got solved with a line-based state machine parser. Cheers, Elezar = Wiki Dictionary - Bosnian/Croatian/Serbian http://izraz.com/%C4%8Cengi%C4%87_vila -- http://mail.python.org/mailman/listinfo/python-list
Re: Detecting line endings
Alex Martelli wrote: > Fuzzyman <[EMAIL PROTECTED]> wrote: >... > > I can't open with a codec unless an encoding is explicitly supplied. I > > still want to detect UTF16 even if the encoding isn't specified. > > > > As I said, I ought to test this... Without metadata I wonder how Python > > determines it ? > > It doesn't. Python doesn't even try to guess: nor would any other > sensible programming language. > Right, so opening in "rU" mode and testing the 'newline' attribute *won't* work for UTF16 encoded files. (Which was what I was asking.) I'll have to read, determine encoding, decode, then *either* use my code to determine line endings *or* use ``splitlines(True)``. All the best, Fuzzyman http://www.voidspace.org.uk/python/index.shtml > > Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: apostrophe or double quote?
Steve Holden wrote: > It's just easier to have two permitted string quotes. That way, if your > string has an apostrophe in it you can say > > s = "it's" It's particularly handy if you are building strings of a language that already has its own quotes, e.g. SQL or XML: sql_snippet = " where name='Max'" html_snippet = ' align="left"' -- Christoph -- http://mail.python.org/mailman/listinfo/python-list
Re: Too Many if Statements?
Bryan Olson wrote: > Alan Morgan wrote: > >> slogging_away wrote: >> >>> Hi - I'm running Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 >>> 32 bit (Intel)] on win32, and have a script that makes numerous checks >>> on text files, (configuration files), so discrepancies can be reported. >>> The script works fine but it appears that I may have hit a wall with >>> 'if' statements. >>> >>> Due to the number of checks perfromed by the script on the text files, >>> (over 500), there are quite a few 'if' statements in the script, (over >>> 1150). It seems that it is at the point that when I add any additional >>> 'if' statements the script will not run. No error is produced - it >>> just returns to the python prompt much the same as when a successful >>> 'Check Module' command is selected. If I delete some other 'if' >>> statements the new ones work so it appears that it has hit a limit on >>> the number of 'if' statements. This has stunted any further checks for >>> the script to make on the text files. >>> >>> Hs anyone ever run into this sort of thing? >> >> >> >> I generated files with 1, 25000, and 5 simple if statements >> and ran >> them. 1 was okay, 25000 gave a bizarre internal error, and 5 >> segfaulted >> and died. My system has plenty of memory and it isn't obvious to me >> why python >> should be so bothered about this. I'm not sure why I can have 10x the >> number of >> if statements that cause you trouble. There might be some overall >> limitation >> on the number of statements in a file. > > > I made a script with 100,000 if's, (code below) and it appears > to work on a couple systems, including Python 2.4.2 on Win32-XP. > So at first cut, it doesn't seem to be just the if-count that > triggers the bug. I tried that code. It runs fine. However, the following gives a SystemError with only 2500 elif's. #!/usr/bin/env python lines = [ 'n = -1','m = 0','if n < 0:',' m = 2*n',] for i in range(2500): lines.append('elif n == %i:' % i) lines.append('m = 2*n') prog = '\n'.join(lines) progfile = file('if.py','w') progfile.writelines(prog) progfile.close() exec prog Traceback (most recent call last): File "iftest.py", line 10, in ? exec prog SystemError: com_backpatch: offset too large I tried this with Python 2.3.3 and 2.3.4 (Linux) and both fail. -- http://mail.python.org/mailman/listinfo/python-list
Re: The problem of anonymity with decorators
Alex, Michele and Skip, Many thanks for your help, I should find my way by putting all these information together. Best regards, Franck -- http://mail.python.org/mailman/listinfo/python-list
Re: Too Many if Statements?
Pierre Quentel wrote: > This is because Python has a hidden mechanism to detect programs > generated by Perl scripts, and make them crash with no explanation > KEYBOARD ! -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list
Re: Python Class use
S Borg wrote: > Hello, > > I am running Python on Mac OS X. The interpreter has been great for > learning the basics, but I would now like to be able to reuse code. > How do I write reusable code? I have done it "The Java way": write > the class, and save it to my home directory, then call it from the > interpreter, here is an example. > > my saved file## > class MyClass: > def f(self): > return 'calling f from MyClass' > > ###interpreter# > x = MyClass() (unhelpful error mesages) This message - that is called a 'traceback' - may seem unhelpful to you, but as a general rule, please post it : it may be *very* helpful to those trying to help you (well, in this case the problem is pretty obvious, but most of the time it is not...) NB: see other answers in this thread about your actual problem - and please take time to read the Fine Manual, specially: http://docs.python.org/tut/node8.html -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about idioms for clearing a list
Ed Singleton wrote: > I'm a fairly average programmer (better than average compared to my > immediate colleagues). I've read every tutorial I can get my hands > on, but I have no _memory_ of ever coming across the del keyword, let > alone that it is fundamental to Python, and I have no idea what > collections school is. I doubtless have read of it at some point, but > as no importance has ever been attached to it, I have probably not > remembered it. > > Similarly, I remember slices simply because they are handy, not > because I have ever heard of them being fundamental before. Ok, I can understand that, but I think that you really understand that the strength of a programming language such as Python is that it's like lego bricks. You have some basic pieces, and you can combine them to into something unique that does what you want. There are plenty of statements, operators, functions, types, modules and other things in Python already. I can well imagine that you had forgotten about del, and that you don't immediately think about slices when you wonder how to empty a list. It's like when I build lego with my son. I guess he has around 2000 pieces, and it's not always easy to spot what you need. It was difficult enough when I was a kid. Now there are so many different kinds of pieces, shaped to fulfil some niche usecase. One thing that I'm sure of is this: Making more kinds of odd-shaped "pieces", especially prepared to solve the specific problem I'm facing right now, won't make it easier to understand or use Python in the long run. I've used Python for almost 10 years now, and I still learn new things, and I sometimes come across things that I once new but had forgotten. It might work for a while to add a new convenience function as soon as someone finds that they don't immediately now how to solve a certain problem. It's my impression that that's pretty much the idea with PHP. It's not Python though. PHP is only successful in a fairly narrow (if important) niche, it has failed in getting used outside its niche, and I assume we'll see a decline in its use one the web pretty soon, just as it happened with Perl. (Whether RoR, something Python based or something entirely new will replace it is beyond my radar screen though.) -- http://mail.python.org/mailman/listinfo/python-list
Re: Best way of finding terminal width/height?
> sys.stdin.read() will return when ... the > underyling read() call is aborted by a signal. Not "return", really? Won't it just pass an exception? I thought that was what I was catching with the "except IOError" part there? I assumed that sys.stdin.read() would only return a value properly at EOF? It looks to me as if sys.stderr.read() really gets an EOF at the final linebreak fed into the terminal prior to window size change, because the final unterminated line shows up on my shell prompt. Like so: $ python winch.py moo moo cow cowmoo moo $ cow cow In this example I type moo moo[ENTER]cow cow on my keyboard and then resize the window. Now that EOF has to come from somewhere (since there's no IOError or other exception, or the program wouldn't terminate nicely with nothing on stderr) and I'd like to point the blame at the terminal. Or is there something really fishy inside sys.stdin.read() or signal that puts EOFs into streams? But anyway, as long as this behavior only shows up on interactive operation, the user will likely spot it anyway and can react to it. So I think this code would be pretty safe to use. What do you think? > Resign the terminal will abort pending I/O operations on > that terminal. It won't terminal I/O operations pending on > other devices/files. What do you mean by "abort"? I can accept that "aborting" may lead to raising of IOError (which we can catch and retry), but not to arbitrary insertion of EOFs into streams (which we cannot distinguish from the real deal coming from the user). Also: try your example and enter moo moo[ENTER]cow cow[RESIZE][ENTER][RESIZE] Thanks again for your help. /Joel > > >>but it does return as soon as I enter more than one >>line of text and then resize the window (one unterminated line >>is ok). >> >>Example text to type in: >>moo moo >>cow cow >> >>As soon as I have typed in something that includes a newline >>charater through the keyboard and try to resize the terminal, >>sys.stdin.read() will return whatever I put in no far and no >>exception raised. > > > Yup. That does indeed appear to be the way it works. :) > > >>Weird. Could it in fact my terminal that's screwing things up >>for me? > > > No. > > Try this out: > > -- > #!/usr/bin/python > import signal, os, sys > > _bTerminalSizeChanged = False > > def report_terminal_size_change(signum, frame): > global _bTerminalSizeChanged > _bTerminalSizeChanged = True > > signal.signal(signal.SIGWINCH, report_terminal_size_change) > > while True: > try: > s = sys.stdin.read() > if not s: > break > sys.stdout.write(s) > except IOError: > sys.stderr.write("IOError\n") > if _bTerminalSizeChanged: > sys.stderr.write("SIGWINCH recevied\n") > _bTerminalSizeChanged = False > -- > > In that example, I handle IOError on write with the same > exception handler as the one for read. That may not be exactly > what you want to do, but it does demonstrate what > window-resizing does. > > When the window is resized, the SIGWINCH handler will be > called. A pending read() may abort with an IOError, or it may > just return some buffered data. > -- http://mail.python.org/mailman/listinfo/python-list
RE: module with __call__ defined is not callable?
On Wed, 08 Feb 2006 13:58:13 +1100, Delaney, Timothy (Tim) wrote: > adam johnson wrote: > >> Hi All. >> I was wondering why defining a __call__ attribute for a module >> doesn't make it actually callable. > > For the same reason that the following doesn't work [snip example] > The __call__ attribute must be defined on the class (or type) - not on > the instance. A module is an instance of . That's not a _reason_, it is just a (re-)statement of fact. We know that defining a __call__ method on a module doesn't make it callable. Why not? The answer isn't "because defining a __call__ method on a module or an instance doesn't make it callable", that's just avoiding the question. Someone had to code Python so that it raised an error when you try to call a module object. Is there a reason why module() should not execute module.__call__()? I would have thought that by the duck typing principle, it shouldn't matter whether the object was a class, a module or an int, if it has a __call__ method it should be callable. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: module with __call__ defined is not callable?
Steven D'Aprano wrote: > On Wed, 08 Feb 2006 13:58:13 +1100, Delaney, Timothy (Tim) wrote: > > > adam johnson wrote: > > > >> Hi All. > >> I was wondering why defining a __call__ attribute for a module > >> doesn't make it actually callable. > > > > For the same reason that the following doesn't work > [snip example] > > The __call__ attribute must be defined on the class (or type) - not on > > the instance. A module is an instance of . > > That's not a _reason_, it is just a (re-)statement of fact. We know that > defining a __call__ method on a module doesn't make it callable. Why not? > The answer isn't "because defining a __call__ method on a module or an > instance doesn't make it callable", that's just avoiding the question. > > Someone had to code Python so that it raised an error when you try to call > a module object. Is there a reason why module() should not execute > module.__call__()? I would have thought that by the duck typing principle, > it shouldn't matter whether the object was a class, a module or an int, if > it has a __call__ method it should be callable. > It would nice if you could make modules callable. All the best, Fuzzyman http://www.voidspace.org.uk/python/index.shtml > > -- > Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: Strange behavior with os call in cgi script
Vinay Sajip: >Rene Pijlman: >> It struck me as somewhat complicated as well. >You should look at later versions of Python - your points above about >easier configuration have already been addressed: here's a link from >the current (2.4) docs: > >http://docs.python.org/lib/minimal-example.html Yes, that looks good. Thanks for pointing that out. So... my advice to OP (if still alive) is: Add logging to your program: http://docs.python.org/lib/minimal-example.html And log the environment: http://www.python.org/dev/doc/newstyle/lib/os-procinfo.html :-) -- René Pijlman -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about idioms for clearing a list
Ed Singleton wrote: > Is it obvious to a newbie what the difference between mappings and > "not-mappings", and is it obvious exactly what is and isn't a mapping? > > Should it be necessary to "know" python before it becomes easy to use? QOTW! (You are joking, aren't you? :) I can undestand how people can turn a bit defensive when some people who are more skilled in programming than in diplomacy basically tells the confused that they are ignorant and should just learn the language. On the other hand, I think that Art Siegel said it very well: "My ability to grok Python to any extent, from that starting point, was based on an understanding that it was my responsibility to come to Python, not it to me." (Actually, that's a much better QOTW! It gives me flashbacks from a book I once read, http://www.amazon.com/gp/product/0060958324 ) There are just a few statements in Python. Some of them should really have been functions (print and exec) but anyway, they are still few enough to learn. There are also a few ways to get inside composite objects, x.y, x[y], x[y:z]. These things are among the most fundamental in Python. If luminaries like Fredrik Lundh and Raymond Hettiger tells you that things should be done in a certain way, it's really just silly to argue further. I've programmed Python since 1996, but if these guys tell me I'm wrong, I won't bother to argue. If I don't understand their position, I'll try to study the subject further, and I might ask them to clarify, but I'll assume that they are right. That assumption has worked so far for me. There are warts and quirks in Python, everybody will agree to that, but Python is *not* Perl. A basic motto has always been to avoid synonyms, to try to provide as few ways to do one thing, rather than to provide as many ways, as possible. This has proven very successful in making Python easy to learn and use. The opposite approach has made Perl into the favourite programimng language among people who think that "if the program was difficult to write, it should be difficult to read as well!" When you can't transfer one approach from one type to another, there is a reason for that. A few times it might be due to some obscure practical aspect of the implementation, but most of the time, it's completely intentional, and finding these aspects of Python, learning why they are the way they are, and embracing the language rather than trying to fight it, is actually very rewarding. Tuples aren't just immutable lists--they have different purposes beyond that. Ordereded and unordered collections are conceptually different. Neither call-by-referece nor call-by-value describes parameter passing in Python well, the clue lies in understanding how assignments and objects work, and you need to understand the difference between mutable and immutable objects etc. There are a number of fundamental concepts that you need to understand to really use Python well. Python works very smoothly, and you can do a lot of productive work with it even if you don't know these things, but in time you'll trip over them, and as you do, you need to grok these concepts to get further. Asking for some syntactic change or some convenience method so that you can get a little further without understanding the fundamental concept isn't the way to get beyond these little stumbling blocks. It's a bit as if you call the design department of your car manufacturer and tell them how they should redesign the suspension since it was so bumpy when you drove around with flat tires. Saying that it's too much to ask that you keep the tires filled with the right amount of air won't meet much sympathy. -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with curses and UTF-8
"Martin v. Löwis" <[EMAIL PROTECTED]> wrote: > Ian Ward wrote: >> Any Ideas? > I think there is one or more ncurses bugs somewhere. indeed. It might be nice to report them rather than jawing about it. > The ncurses documentation suggests that you should link with > ncurses_w instead of linking with ncurses - you might try > that as well. If it helps, please do report back. ncursesw > Ultimately, somebody will need to debug ncurses to find out > what precisely happens, and why. no need for debugging - it's a well-known problem. UTF-8 uses more than one byte per cell, normal curses uses one byte per cell. To handle UTF-8, you need ncursesw. -- Thomas E. Dickey http://invisible-island.net ftp://invisible-island.net -- http://mail.python.org/mailman/listinfo/python-list
Re: Replacing curses
Ian Ward <[EMAIL PROTECTED]> wrote: > I've had to work around many curses issues while developing Urwid (a hmm - I've read Urwid, and most of the comments I've read in that regard reflect problems in Urwid. Perhaps it's time for you to do a little analysis. (looking forward to bug reports, rather than line noise) -- Thomas E. Dickey http://invisible-island.net ftp://invisible-island.net -- http://mail.python.org/mailman/listinfo/python-list
Re: Detecting line endings
Alex Martelli wrote: > Fuzzyman <[EMAIL PROTECTED]> wrote: >... > > > Open the file with 'rU' mode, and check the file object's newline > > > attribute. > > Just to confirm, for a UTF16 encoded file, the newlines attribute is ``None``. All the best, Fuzzyman http://www.voidspace.org.uk/python/index.shtml -- http://mail.python.org/mailman/listinfo/python-list
get output of cmd-line command under MS windows
Hi all, unfotunately, 'commands.getstatusoutput(command)' does not work under windows. Would there be any alternative? os.system also just provides the exit number I think. thanks a lot, and cheers marco -- calmar (o_ It rocks: LINUX + Command-Line-Interface //\ V_/_ http://www.calmar.ws -- http://mail.python.org/mailman/listinfo/python-list
Re: Is Python good for web crawlers?
Tempo wrote: > I was wondering if python is a good language to build a web crawler > with? For example, to construct a program that will routinely search x > amount of sites to check the availability of a product. Or to search > for news articles containing the word 'XYZ'. These are just random > ideas to try to explain my question a bit further. Well if you have an > opinion about this please let me know becasue I am very interested to > hear what you have to say. Thanks. I dunno, but there are these two guys, Sergey Brin and Lawrence Page, who wrote a web crawler in Python. As far as I understood, they were fairly successful with it. I think they called their system Koogle, Bugle, or Gobble or something like that. Goo...can't remember. See http://www-db.stanford.edu/~backrub/google.html They've also employed some clever Python programmers, such as Greg Stein, Alex Martelli (isn't he a bot?) and some obscure dutch mathematician called Guido van something. It seems they still like Python. -- http://mail.python.org/mailman/listinfo/python-list
Re: module with __call__ defined is not callable?
Fuzzyman wrote: > Steven D'Aprano wrote: > >>On Wed, 08 Feb 2006 13:58:13 +1100, Delaney, Timothy (Tim) wrote: >> >> >>>adam johnson wrote: >>> >>> Hi All. I was wondering why defining a __call__ attribute for a module doesn't make it actually callable. >>> >>>For the same reason that the following doesn't work >> >>[snip example] >> >>>The __call__ attribute must be defined on the class (or type) - not on >>>the instance. A module is an instance of . >> >>That's not a _reason_, it is just a (re-)statement of fact. We know that >>defining a __call__ method on a module doesn't make it callable. Why not? >>The answer isn't "because defining a __call__ method on a module or an >>instance doesn't make it callable", that's just avoiding the question. >> >>Someone had to code Python so that it raised an error when you try to call >>a module object. Is there a reason why module() should not execute >>module.__call__()? I would have thought that by the duck typing principle, >>it shouldn't matter whether the object was a class, a module or an int, if >>it has a __call__ method it should be callable. >> > > > It would nice if you could make modules callable. > Right. While we're at it, why don't we make strings callable. Calling a string could call the function whose name (in some namespace or other) was in the string. And we can make integers callable too - that could just assume that the integer was the address of a function to be called. In case you think I'm joking, I am. Why should a module be callable? What's the advantage? Should we be able to add two modules together, yielding a module that contains all the code of both modules? What happens if I multiply a module by two - presumably the result should be the same as adding a module to itself? Perhaps we should be able to divide a module by a function? The pursuit of orthogonality, while admirable, can lead to insanity if pushed too far. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Detecting line endings
Fuzzyman wrote: > Alex Martelli wrote: > > Fuzzyman <[EMAIL PROTECTED]> wrote: > >... > > > > Open the file with 'rU' mode, and check the file object's newline > > > > attribute. > > > > > Just to confirm, for a UTF16 encoded file, the newlines attribute is > ``None``. > Hmmm... having read the documentation, the newlines attribute remains None until some newlines are encountered. :oops: I don't think it's technique is any better than mine though. ;-) Fuzzy http://www.voidspace.org.uk/python/index.shtml > All the best, > > Fuzzyman > http://www.voidspace.org.uk/python/index.shtml -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about idioms for clearing a list
On 2/8/06, Fredrik Lundh <[EMAIL PROTECTED]> wrote: > you seem to be missing that we're talking about a programming language > here. nothing is obvious if you don't know anything about the language; > a lot of things are obvious once you've learned a little about it. a little > is > all it takes. why is that so hard to understand ? "The only 'intuitive' user interface is the nipple. After that, it's all learned." - Bruce Ediger -- Cheers, Simon B, [EMAIL PROTECTED], http://www.brunningonline.net/simon/blog/ -- http://mail.python.org/mailman/listinfo/python-list
Re: module with __call__ defined is not callable?
Steve Holden wrote: > Fuzzyman wrote: > > Steven D'Aprano wrote: > > > >>On Wed, 08 Feb 2006 13:58:13 +1100, Delaney, Timothy (Tim) wrote: > >> > >> > >>>adam johnson wrote: > >>> > >>> > Hi All. > I was wondering why defining a __call__ attribute for a module > doesn't make it actually callable. > >>> > >>>For the same reason that the following doesn't work > >> > >>[snip example] > >> > >>>The __call__ attribute must be defined on the class (or type) - not on > >>>the instance. A module is an instance of . > >> > >>That's not a _reason_, it is just a (re-)statement of fact. We know that > >>defining a __call__ method on a module doesn't make it callable. Why not? > >>The answer isn't "because defining a __call__ method on a module or an > >>instance doesn't make it callable", that's just avoiding the question. > >> > >>Someone had to code Python so that it raised an error when you try to call > >>a module object. Is there a reason why module() should not execute > >>module.__call__()? I would have thought that by the duck typing principle, > >>it shouldn't matter whether the object was a class, a module or an int, if > >>it has a __call__ method it should be callable. > >> > > > > > > It would nice if you could make modules callable. > > > Right. While we're at it, why don't we make strings callable. Calling a > string could call the function whose name (in some namespace or other) > was in the string. And we can make integers callable too - that could > just assume that the integer was the address of a function to be called. > > In case you think I'm joking, I am. > > Why should a module be callable? What's the advantage? Should we be able > to add two modules together, yielding a module that contains all the > code of both modules? What happens if I multiply a module by two - > presumably the result should be the same as adding a module to itself? > Perhaps we should be able to divide a module by a function? > > The pursuit of orthogonality, while admirable, can lead to insanity if > pushed too far. > Sure - feel free to venture as far down the road of insanity as you like :-) To pursue your analogy, why don't we answer all usenet posts by pushing suggestions to ridiculous levels ? ;-) What would actually be the problem with allowing modules to define a __call__ though ? This would allow for nice clean namespaces at the module level. Ok, so there are other ways of doing it - but it's not at all illogical. Fuzzyman http://www.voidspace.org.uk/python/index.shtml > regards > Steve > -- > Steve Holden +44 150 684 7255 +1 800 494 3119 > Holden Web LLC www.holdenweb.com > PyCon TX 2006 www.python.org/pycon/ -- http://mail.python.org/mailman/listinfo/python-list
Re: module with __call__ defined is not callable?
Fuzzyman wrote: > Steve Holden wrote: [...] >> >>The pursuit of orthogonality, while admirable, can lead to insanity if >>pushed too far. >> > > > Sure - feel free to venture as far down the road of insanity as you > like :-) To pursue your analogy, why don't we answer all usenet posts > by pushing suggestions to ridiculous levels ? ;-) > Right, and publish cartoons of Larry Wall where his hat is a bomb. Then the perlmongers will burn the Googleplex down? > What would actually be the problem with allowing modules to define a > __call__ though ? This would allow for nice clean namespaces at the > module level. > What's clean about defining __call__() and calling the module name rather than defining functions and calling them? Why should one specific function in a module be promoted to this special status? How many modules have precisely one function? > Ok, so there are other ways of doing it - but it's not at all > illogical. > I was merely trying to suggest that just because something *can* be done doesn't mean it *should* be done. Perhaps I went a little over the top. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ -- http://mail.python.org/mailman/listinfo/python-list
Re: critique my code, please
"Brian Blais" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Hello, > > I am including at the end of this document (is it better as an attachment?) some code > for a small gui dialog. Since I am quite new to this, if anyone has any suggestions > for improvements to the code, bad coding practices, poor gui design, etc... I'd love > to hear it. The GUI is "welded" to the application. I much prefer to see a program split into a command-ling "engine" application and a (or more) "GUI", "CLI" e.t.c. interface applications that can connect to the engine and drive it. That way it is possible to script the application. -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about idioms for clearing a list
On 08/02/06, Magnus Lycka <[EMAIL PROTECTED]> wrote: > Ed Singleton wrote: > > I'm a fairly average programmer (better than average compared to my > > immediate colleagues). I've read every tutorial I can get my hands > > on, but I have no _memory_ of ever coming across the del keyword, let > > alone that it is fundamental to Python, and I have no idea what > > collections school is. I doubtless have read of it at some point, but > > as no importance has ever been attached to it, I have probably not > > remembered it. > > > > Similarly, I remember slices simply because they are handy, not > > because I have ever heard of them being fundamental before. > > Ok, I can understand that, but I think that you really understand > that the strength of a programming language such as Python is that > it's like lego bricks. You have some basic pieces, and you can > combine them to into something unique that does what you want. > > There are plenty of statements, operators, functions, types, modules > and other things in Python already. I can well imagine that you had > forgotten about del, and that you don't immediately think about slices > when you wonder how to empty a list. It's like when I build lego with > my son. I guess he has around 2000 pieces, and it's not always easy > to spot what you need. It was difficult enough when I was a kid. Now > there are so many different kinds of pieces, shaped to fulfil some > niche usecase. > > One thing that I'm sure of is this: Making more kinds of odd-shaped > "pieces", especially prepared to solve the specific problem I'm facing > right now, won't make it easier to understand or use Python in the > long run. I agree utterly with this, particularly the general philosophy of having simple bricks that work in as many different places as possible. The point is that having to use del to clear a list appears to the inexperienced as being an odd shaped brick when they've already used the .clear() brick in other places. Having bricks that work in lots of places makes the language 'guessable'. "I've never cleared a list before, but I've cleared dictionaries and I guess the same way would work here". The problem is you have to be very careful when talking about this, not to use the C-word, because that's the hobgoblin of little minds, whereas in almost every other field it is considered an important part of usability. > I've used Python for almost 10 years now, and I still learn new > things, and I sometimes come across things that I once new but > had forgotten. > > It might work for a while to add a new convenience function as soon > as someone finds that they don't immediately now how to solve a > certain problem. It's my impression that that's pretty much the idea > with PHP. It's not Python though. PHP is only successful in a fairly > narrow (if important) niche, it has failed in getting used outside > its niche, and I assume we'll see a decline in its use one the web > pretty soon, just as it happened with Perl. (Whether RoR, something > Python based or something entirely new will replace it is beyond my > radar screen though.) > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: 450 Pound Library Program
just a few style notes... > def checkOutBook(self, readerName): > "'Remove book from the front of the list, block if no books are > available'" I don't understand what "' is supposed to imply. If you meant to use triple quoting, you need to use ''' or """. Then the string can contain line breaks. (Perhaps you have a really stupid email client/news client/editor/whatever that replaces ''' with "'? Please loose that or use """.) Also, please use lines that are short enough not to wrap around. Line wrapping makes the code very ugly. Do like this: def checkOutBook(self, readerName): """Remove book from the front of the list, block if no books are available.""" [...] > for line in theBookFile.readlines(): In modern Python you simply write: for line in theBookFile: > L = line.split (",") # a comma-delimited list > author = L[0] > bookName = L[1] Why bother with L? The follwing is as clear I think, and solves the problem of commas in the title. Also, don't put a space between the callable and the parenthesis please. See the Python style guide, PEP 008. author, bookName = line.split(",", 2) [...] > totalBooks = input("How many books would you like in the > Library?[1-" + str(len(stacks)) + "]") Again, don't make the lines so long. You don't have to do that. You can break lines freely inside (), {} and [], and adjacent string literals are automatically concatenated. totalBooks = input("How many books would you like in " "the Library?[1-%d]" % len(stacks)) -- http://mail.python.org/mailman/listinfo/python-list
Re: Another try at Python's selfishness
<[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Having read previous discussions on python-dev I think I'm not the only > Python programmer who doesn't particularly like python's "self" > parameter: Ok, there might be five programmers and one imam. The imam does not like anything more recent than 700 A.D ... > What do you think? > Troll! -- http://mail.python.org/mailman/listinfo/python-list
Python threading, and processes
Hey there I'm doing some threading in python with Python 2.3 and 2.4 on Ubuntu and Debian machines, and I've noticed that if I open a lot of threads (say, 50), I get lots of python processes with individual PIDs, which consume a disproportionate amount of CPU. Does this mean that Python is using the dummy_thread module by accident? And is there a realistic limitation to the number of threads I can do? Cheers -Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about idioms for clearing a list
Ed Singleton wrote: > Having bricks that work in lots of places makes the language > 'guessable'. "I've never cleared a list before, but I've cleared > dictionaries and I guess the same way would work here". f = open("foo") f.clear() sys.stdout.clear() os.getcwd().clear() shelve.clear() s = "sky" s.clear() -- http://mail.python.org/mailman/listinfo/python-list
Re: Python threading, and processes
Robin Haswell wrote: > Hey there > > I'm doing some threading in python with Python 2.3 and 2.4 on Ubuntu and > Debian machines, and I've noticed that if I open a lot of threads (say, > 50), I get lots of python processes with individual PIDs, which consume a > disproportionate amount of CPU. Does this mean that Python is using the > dummy_thread module by accident? And is there a realistic limitation to > the number of threads I can do? Both system-depend. The way threads are shwon depends on the systenm. And a thread that runs, runs - so it consumes cpu-cycles. Try calling time.sleep() to see how the consumption decreases. And the limitation of allowed threads per process and/or system is also a OS-dependend thing. """ Under Linux, threads are counted as processes, so any limits to the number of processes also applies to threads. In a heavily threaded app like a threaded TCP engine, or a java server, you can quickly run out of threads. """ from http://people.redhat.com/alikins/system_tuning.html#threads Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: 450 Pound Library Program
mwt wrote: > So in a further attempt to learn some Python, I've taken the little > Library program > (http://groups.google.com/group/comp.lang.python/browse_thread/thread/f6a9ccf1bc136f84) > I wrote and added several features to it. Readers now quit when they've > read all the books in the Library. Books know how many times they've > been read. Best of all, you can now create your own list of books to > read! > > Again, the point of all this is to get used to programming in Python. > So although the program is trivial, any feedback on style, structure, > etc. would be much appreciated. I'm a convert from Java, Welcome !-) > so I've > probably got some unconscious Javanese in there somewhere. Help me get > rid of it! Well, apart from namingConventions (vs naming_conventions), I did not spot too much javaism in your code. > Here's the new, improved program: > [code] > #!/usr/bin/python > # Filename: Library.py > # author: mwt > # Feb, 2006 > > import thread > import time > import threading > import random > > > > class Library2: Old-style classes are deprecated, use new-style classes instead: class Library2(object): > def __init__(self, listOfBooks, totalBooks): > self.stacks = listOfBooks If its a collection of books, why not call it 'books' ? > self.cv = threading.Condition() > self.totalBooks = totalBooks What is 'totalBooks' ? > def checkOutBook(self, readerName): > "'Remove book from the front of the list, block if no books are > available'" Why not using triple-quoted strings ? > self.cv.acquire() > while len(self.stacks) == 0: > self.cv.wait() > print "%s waiting for a book..." %readerName > book = self.stacks.pop(0) This last line will crash (IndexError) on an empty list, and then the resource may not be released... A first step would be to enclose this in a try/finally block. > self.cv.release() > return book > > def returnBook(self, returnedBook): > "'put book at the end of the list, notify that a book is > available'" > returnedBook.wasRead() > self.cv.acquire() > self.stacks.append(returnedBook) > self.cv.notify() > self.cv.release() You have a recurring pattern in the last 2 methods: aquire/do something/release. You could factor this out in a method decorator (don't forget that functions and methods are objects too, so you can do a *lot* of things with them). > class Reader(threading.Thread): > > def __init__(self, library, name, readingSpeed, timeBetweenBooks): > threading.Thread.__init__(self) or : super(Reader, self).__init__() but this wouldn't make a big difference here > self.library = library > self.name = name > self.readingSpeed = readingSpeed > self.timeBetweenBooks = timeBetweenBooks > self.book = "" You later user Reader.book to hold a reference to a Book object, so it would be wiser to initialize it with None. > self.numberOfBooksRead = 0 > > def run(self): > "'Keep checking out and reading books until you've read all in > the Library'" > while self.numberOfBooksRead < self.library.totalBooks: > self.book = self.library.checkOutBook(self.name) > print "%s reading %s" %(self.name, self.book.title), > time.sleep(self.readingSpeed) > self.numberOfBooksRead += 1 > self.library.returnBook(self.book) > print "%s done reading %s" %(self.name, self.book.title), > print"Number of books %s has read: %d" %(self.name, > self.numberOfBooksRead) > self.bookName = "" > time.sleep(self.timeBetweenBooks) > print "%s done reading." %self.name > > class Book: > def __init__(self, author, title): > self.author = author > self.title = title > self.numberOfTimesRead = 0 > #print "%s,%s" % (self.author, self.title),#print as books are > loaded in > > def wasRead(self): > self.numberOfTimesRead += 1 > print "Number of times %s has been read: %d" %(self.title, > self.numberOfTimesRead) > > if __name__=="__main__": > You should define a main() function and call it from here. > print "\nWELCOME TO THE THURMOND STREET PUBLIC LIBRARY" > print "Checking which books are avialable...\n" s/avialable/available/ !-) > try: > theBookFile = open("books.txt", "r")#Create your own list of > books! Filenames should not be hardcoded. (Ok, you probably know this already, but I thought it would be better to point this out for newbie programmers) > stacks = []#a place to put the books > for line in theBookFile.readlines(): > L = line.split (",") # a comma-delimited list Mmm... may not be the best format. What if there are commas in the book title ? Hint : there's a CSV module in the standard lib. Also, by convention, UPPERCASE
Re: 450 Pound Library Program
Magnus Lycka wrote: > just a few style notes... > (snip) > > Why bother with L? The follwing is as clear I think, and solves > the problem of commas in the title. Also, don't put a space between > the callable and the parenthesis please. See the Python style guide, > PEP 008. > > author, bookName = line.split(",", 2) >>> "toto, tata, tutu".split(",", 2) ['toto', ' tata', ' tutu'] >>> You want line.split(',', 1) here. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list
Re: module with __call__ defined is not callable?
Steve Holden wrote: (snip) > The pursuit of orthogonality, while admirable, can lead to insanity if > pushed too far. > +1 QOTW -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in '[EMAIL PROTECTED]'.split('@')])" -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about idioms for clearing a list
On 08/02/06, Magnus Lycka <[EMAIL PROTECTED]> wrote: > Ed Singleton wrote: > > Is it obvious to a newbie what the difference between mappings and > > "not-mappings", and is it obvious exactly what is and isn't a mapping? > > > > Should it be necessary to "know" python before it becomes easy to use? > > QOTW! (You are joking, aren't you? :) It was a genuine question. Judging from one of your other responses, that you are still learning new things and remembering forgotten ones after 10 years, I assume the answer is "no, it is not necessary". (I'm also assuming you find Python easy to use). The thing that first attracted me to Python was that I only had to read a page or two of the tutorial before I could get started on doing little things with Python and find it easy. > I can undestand how people can turn a bit defensive when some > people who are more skilled in programming than in diplomacy > basically tells the confused that they are ignorant and should > just learn the language. > > On the other hand, I think that Art Siegel said it very well: > "My ability to grok Python to any extent, from that starting point, > was based on an understanding that it was my responsibility to come > to Python, not it to me." > (Actually, that's a much better QOTW! It gives me flashbacks from > a book I once read, http://www.amazon.com/gp/product/0060958324 ) > > There are just a few statements in Python. Some of them should > really have been functions (print and exec) but anyway, they are > still few enough to learn. There are also a few ways to get inside > composite objects, x.y, x[y], x[y:z]. These things are among the > most fundamental in Python. > > If luminaries like Fredrik Lundh and Raymond Hettiger tells you > that things should be done in a certain way, it's really just > silly to argue further. I've programmed Python since 1996, but if > these guys tell me I'm wrong, I won't bother to argue. If I don't > understand their position, I'll try to study the subject further, > and I might ask them to clarify, but I'll assume that they are > right. That assumption has worked so far for me. I didn't know they were luminaries. I apologise. I've never heard of any of the people on the list before I came to Python and the only people I've learned to trust are Kent Johnson and Alan Gauld. I guess if I start to see those guys say things that turn out to be right I might start assuming they are right as well. Maybe there should be a list of luminaries on the website so we know who not to argue with? > There are warts and quirks in Python, everybody will agree to that, > but Python is *not* Perl. A basic motto has always been to avoid > synonyms, to try to provide as few ways to do one thing, rather > than to provide as many ways, as possible. This has proven very > successful in making Python easy to learn and use. The opposite > approach has made Perl into the favourite programimng language > among people who think that "if the program was difficult to write, > it should be difficult to read as well!" I think people concentrate on the total number of ways to do something, when the obviousness or consistency of one one of those ways is more important. For example one of the few things Microsoft does okay at, is in having a pretty consistent interface across their applications. There's a menu bar that (theoretically) has all the commands you can perform in a structured format. But you can also use reasonably consistent keyboard shortcuts to do something, or context menus for things that you do a lot. Having several different ways means that everyone can use the way they prefer. Beginners tend to use the menu bar a lot as they can always find what they want there, but can start using the keyboard shortcuts as they start to perform the action a lot and start to become more experienced. I know this isn't entirely applicable but hopefully you see the analogy. > When you can't transfer one approach from one type to another, > there is a reason for that. A few times it might be due to some > obscure practical aspect of the implementation, but most of the > time, it's completely intentional, and finding these aspects of > Python, learning why they are the way they are, and embracing the > language rather than trying to fight it, is actually very rewarding. No, it's rewarding for a certain type of person. It's not a rewarding activity for every type of person. I find it deeply frustrating when I have to constantly look things up to see what is the way of doing things for this type. I'd rather spend my time writing code then looking things up to see which way I have to do it now. > Tuples aren't just immutable lists--they have different purposes > beyond that. Ordereded and unordered collections are conceptually > different. Neither call-by-referece nor call-by-value describes > parameter passing in Python well, the clue lies in understanding > how assignments and objects work, and you need to understand th
Re: Another try at Python's selfishness
"But the point is, the current situation is not newbie-friendly (I can tell, I am a newbie)" I will agree to that, as I consider myself still new. _But_, it's a stumbling stone only briefly. Get enough nagging error messages, and you learn and move on. I agree with the grandparent poster that it is a perfect self-documenting thing, as the use of 'self' is pretty obvious. For a language that one can learn in a short time, this is a tempest in a teacup. I'm just trying to disown my several years of Perl. I like PHP too much and have no experience with Python in a CGI environment. So, I'm a little bit confused linguistically. ;-) -- http://mail.python.org/mailman/listinfo/python-list
os.walk() dirs and files
Hello, When working with file and dir info recursively on Windows XP. I'm going about it like this: for root, dirs, files in os.walk(path): for f in files: ADD F to dictionary for d in dirs: ADD D to dictionary Is it possible to do something such as this: for root, dirs, files in os.walk(path): for f,d in files, dirs: ADD F|D to dictionary Just trying to save some lines of code and thought it wise to ask the gurus before trying it :) Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: Another try at Python's selfishness
Frithiof Andreas Jensen wrote: > <[EMAIL PROTECTED]> wrote in message > news:[EMAIL PROTECTED] >> Having read previous discussions on python-dev I think I'm not the only >> Python programmer who doesn't particularly like python's "self" >> parameter: > > Ok, there might be five programmers and one imam. The imam does not like > anything more recent than 700 A.D ... > You Danes and your Muslim jokes :) -- http://mail.python.org/mailman/listinfo/python-list
Re: Python threading, and processes
On Wed, 08 Feb 2006 14:24:38 +0100, Diez B. Roggisch wrote: > Robin Haswell wrote: > >> Hey there >> >> I'm doing some threading in python with Python 2.3 and 2.4 on Ubuntu and >> Debian machines, and I've noticed that if I open a lot of threads (say, >> 50), I get lots of python processes with individual PIDs, which consume a >> disproportionate amount of CPU. Does this mean that Python is using the >> dummy_thread module by accident? And is there a realistic limitation to >> the number of threads I can do? > > Both system-depend. The way threads are shwon depends on the systenm. And a > thread that runs, runs - so it consumes cpu-cycles. Try calling > time.sleep() to see how the consumption decreases. Cheers for that info. The thread's main tasks are getting webpages (spidering), the actual amount of processing done in each thread is minimal - that's why I'm confused by the CPU usage. Cheers -Rob > > Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: os.walk() dirs and files
Duncan Booth wrote: > How about just concatentating the two lists: > >>for root, dirs, files in os.walk(path): >for fs_object in files + dirs: >> ADD fs_object to dictionary Thank you Duncan! that solves the problem perfectly! -- http://mail.python.org/mailman/listinfo/python-list
Re: a question regarding call-by-reference
Thank you everyone for your helpful replies! I think the problems that arise with nested and overly large lists and dictionaries, and difficulties of handling other mutable datatypes will make my little assignment just too difficult. I'll just specify that call-by-reference isn't supported and leave it at that. Between floors. Going down. Enjoying the view. -- http://mail.python.org/mailman/listinfo/python-list
Re: apostrophe or double quote?
Steve Holden <[EMAIL PROTECTED]> wrote: >Huy wrote: >> I've been unable to find information clarifying this but. What is the >> difference between 'somestring' and "somestring"? >It's just easier to have two permitted string quotes. That way, if your >string has an apostrophe in it you can say > > s = "it's" > >and if it has a double quote in it you can say > > s = 'The double quote (") rules' > >So there's really no difference at all. You can also use escaping to >achieve the same end: > > s = "The double quote (\") rules" > >if you prefer. Or triple quoting: s = """The double quote (") rules""" I've seen someone around here use 'somestring' for internal values (dict keys and the like) and "somestring" for values being shown to the user, so it's easy(ish) to tell what may need translating or can otherwise safely be changed. I like this convention (provided it remains a convention). -- \S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ |-- Arthur C. Clarke her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump -- http://mail.python.org/mailman/listinfo/python-list
Re: Python and Flash
Thanks for the help so far. There are two Python applications involved, one runs on a remote PC (server) and another on the users PC (client). The server at present merely receives and sends out messages via an instant messaging platform. Based on the information it receives via the IM platform it then updates the Flash application. I guess it could do it in a number of ways, one method being to send messages to the Flash application to update the display, or another to update the visualisation on the server then get the web browser (on the client PC) to reload it. Thanks, rod -- http://mail.python.org/mailman/listinfo/python-list
Re: os.walk() dirs and files
rtilley wrote: > Hello, > > When working with file and dir info recursively on Windows XP. I'm going > about it like this: > > for root, dirs, files in os.walk(path): > for f in files: > ADD F to dictionary > for d in dirs: > ADD D to dictionary > > Is it possible to do something such as this: > > for root, dirs, files in os.walk(path): > for f,d in files, dirs: > ADD F|D to dictionary Just to clarify. In this particular case, I do not need to differentiate between files and dirs... so would it be possible to do something such as this: for root, dirs, files in os.walk(path): for fs_object in files, dirs: ADD fs_object to dictionary -- http://mail.python.org/mailman/listinfo/python-list
Re: os.walk() dirs and files
rtilley wrote: > Just to clarify. In this particular case, I do not need to differentiate > between files and dirs... so would it be possible to do something such > as this: > How about just concatentating the two lists: > for root, dirs, files in os.walk(path): > for fs_object in files, dirs: for fs_object in files + dirs: > ADD fs_object to dictionary -- http://mail.python.org/mailman/listinfo/python-list
Re: Too Many if Statements?
bruno at modulix wrote: [...] > Suppose you have to match a line against a list of regexp and log if it > doesn't match. You could of course repeat the whole code for each > regexp, ie: > > if not re.match(r'a/regexp/here', line): > log('a first message') > > if not re.match(r'another/regexp/here', line): > log('another message') > > (... 150 regexps later ...) > > if not re.match(r'150/regexps/later', line): > log('pfww, getting tired of copy/pasting') > > etc... > > But you could also factor much of it: > > def checkMatch(line, regexp, msg): > if not re.match(regexp, line): > log(msg) > > then have a list of regexps/messages pairs and: > for exp, msg in regexps: > checkMatch(line, exp, msg) > > And now, you can add as many thousands regexps you want, you still have > one (and only one) if in the code (well, in this snippet at least...). If your checks are this complicated, I think you should consider writing a parser for your configuration file. If you use a parser generator it's not that difficult. Moreover a lexical analyzer could be enough if your syntax is simple. I found Dave Beazley's PLY reasonably easy to use: http://www.dabeaz.com/ply/ Cheers, Nicola Musatti -- http://mail.python.org/mailman/listinfo/python-list
Re: UnboundMethodType and MethodType
Kirk McDonald wrote: > I think it's perfectly consistent: > > >>> class B(object): > ... def bar(self): pass > ... > >>> B.bar > > >>> type(B.bar) > > >>> b = B() > >>> b.bar > > > >>> type(b.bar) > > >>> id(B.bar) > -1211888788 > >>> id(b.bar) > -1211888788 > > It's the same function, whether it's bound or not. Thus, it should > always have the same type. No, it's not the same function. You got the same id because you didn't bind B.bar and b.bar to anything so the id was reused. >>> class B(object): ... def bar(self): pass ... >>> Bbar = B.bar >>> bbar = B().bar >>> Bbar >>> bbar > >>> id(Bbar) 10751312 >>> id(bbar) 10736624 >>> Bbar is bbar False Kent -- http://mail.python.org/mailman/listinfo/python-list
Re: module with __call__ defined is not callable?
Op 2006-02-08, Steve Holden schreef <[EMAIL PROTECTED]>: > Fuzzyman wrote: >> Steve Holden wrote: > [...] >>> >>>The pursuit of orthogonality, while admirable, can lead to insanity if >>>pushed too far. >>> >> >> >> Sure - feel free to venture as far down the road of insanity as you >> like :-) To pursue your analogy, why don't we answer all usenet posts >> by pushing suggestions to ridiculous levels ? ;-) >> > Right, and publish cartoons of Larry Wall where his hat is a bomb. Then > the perlmongers will burn the Googleplex down? > >> What would actually be the problem with allowing modules to define a >> __call__ though ? This would allow for nice clean namespaces at the >> module level. >> > What's clean about defining __call__() and calling the module name > rather than defining functions and calling them? The same question can be asked about classes? What's clean about defining a __call__() method and calling the instance name rather than defining methods and calling them? > Why should one specific > function in a module be promoted to this special status? How many > modules have precisely one function? For the same reason they are already promoted special status in classes. Python promotes duck typing so why shouldn't special functions of modules be treated the same as special methods? -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: only a simple xml reader value
[EMAIL PROTECTED] wrote: > H!, > > Is it possible to get a value value ? > > When I do this: > - > theXML = """ > The Fascist Menace > """ > import xml.dom.minidom as dom > doc = dom.parseString(theXML) > print doc.getElementsByTagName('title')[0].toxml() > > I get : The Fascist Menace thats oke for me > - > > But the xmlfile I must read have other tags: > theXML = """ > The Fascist Menace > bla la etc > """ > > how to get that values ? > I try things like: > print doc.getElementsByTagName('title:id')[0].toxml() <--error Addressing your general question, unfortunately you're a bit stuck. Minidom is rather confused about whether or not it's a namespace aware library. Addressing your specific example, I strongly advise you not to use documents that are not well-formed according to Namespaces 1.0. Your second example is a well-formed XML 1.0 external parsed entity, but not a well-formed XML 1.0 document entity, because it has multiple elements at document level. It's also not well-formed according to XMLNS 1.0 unless you declare the "title" prefix. You will not be able to use a non XMLNS 1.0 document with most XML technologies, including XSLT, WXS, RELAX NG, etc. If you have indeed declared a namespace and are just giving us a very bad example, use: print doc.getElementsByTagNameNS(title_namespace, 'id') -- Uche Ogbuji Fourthought, Inc. http://uche.ogbuji.nethttp://fourthought.com http://copia.ogbuji.net http://4Suite.org Articles: http://uche.ogbuji.net/tech/publications/ -- http://mail.python.org/mailman/listinfo/python-list
how to...python with winmodem...
Hello, i wanna know how to communicate my python program with my winmodem on PC...thanks!!! -- http://mail.python.org/mailman/listinfo/python-list
Re: module with __call__ defined is not callable?
Op 2006-02-08, Steve Holden schreef <[EMAIL PROTECTED]>: > > Why should a module be callable? What's the advantage? Should we be able > to add two modules together, yielding a module that contains all the > code of both modules? What happens if I multiply a module by two - > presumably the result should be the same as adding a module to itself? > Perhaps we should be able to divide a module by a function? > > The pursuit of orthogonality, while admirable, can lead to insanity if > pushed too far. This is not an argument. This doesn't give a clue about where to stop this pursuit en when to go on. Whether it is usefull to call modules add them or multiply them by two is up to the person producing the code. That is no different than when he decides it is usefull to call certain objects, add them or multiply them by two. I can understand there are implemenation details that make it not worth while to implement this. But otherwise I would think it a bad reason to give up orthogonality just because one can't imagine what it could be usefull for. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: only a simple xml reader value
I'm newbie with that xml stuff. The only thing I must read is the response I get from a EPP server. A response like this: http://www.eurid.eu/xml/epp/epp-1.0"; xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"; xmlns:contact="http://www.eurid.eu/xml/epp/contact-1.0"; xmlns:domain="http://www.eurid.eu/xml/epp/domain-1.0"; xmlns:eurid="http://www.eurid.eu/xml/epp/eurid-1.0"; xmlns:nsgroup="http://www.eurid.eu/xml/epp/nsgroup-1.0"; xsi:schemaLocation="http://www.eurid.eu/xml/epp/epp-1.0 epp-1.0.xsd http://www.eurid.eu/xml/epp/contact-1.0 contact-1.0.xsd http://www.eurid.eu/xml/epp/domain-1.0 domain-1.0.xsd http://www.eurid.eu/xml/epp/eurid-1.0 eurid-1.0.xsd http://www.eurid.eu/xml/epp/nsgroup-1.0 nsgroup-1.0.xsd"> Command completed successfully; ending session c-and-a.eu c-and-a_1 25651602 2005-11-08T14:51:08.929Z OK clientref-12310026 eurid-1589 // //Command completed successfully; ending session what is the official/best way to handle/parse such xml response ? Thats maybe a better question -- http://mail.python.org/mailman/listinfo/python-list
What editor shall I use?
What editor shall I use if my Python script must contain utf-8 characters? I use XP Thank you for reply l.b. -- http://mail.python.org/mailman/listinfo/python-list
Re: 450 Pound Library Program
mwt <[EMAIL PROTECTED]> wrote: >while len(self.stacks) == 0: To (kind of) repeat myself, the idiomatic Python would be: while not self.stacks: An empty list is considered to be false, hence testing the list itself is the same as testing len(l) > 0 . As someone else has noticed, you're using len() an awful lot when you don't need to. -- \S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ |-- Arthur C. Clarke her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump -- http://mail.python.org/mailman/listinfo/python-list
Undergraduate project :: python ToDo list
Hi. I would like to know if there's any todo list on python project. My interest in doing a undergraduate project. It could be anything in the python core interpreter. I program C/C++. Thanks in advance. Regards. Joao Macaiba (wavefunction) -- http://mail.python.org/mailman/listinfo/python-list
Re: What editor shall I use?
> What editor shall I use if my Python script must contain utf-8 > characters? > I use XP vim :-) > Thank you for reply > l.b. not for all :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: What editor shall I use?
is vim for XP? -- http://mail.python.org/mailman/listinfo/python-list
Re: get output of cmd-line command under MS windows
You should give a go to os.popen( ). Article 6.1.2 and 6.1.3 in the Python Library doc. I recently wrote a program that would create a pipe using the popen() method, and would enter a while loop. At each iteration, it would read one line of the pipe output, and the loop would break when it gets an empty line (indicating the running application is not running in this case). Example: import os oPipe = os.popen( "run C:/program files/my app/executable.exe" ) while 1: sLine = oPipe.read() print sLine if sLine == '': print 'No more line from pipe, exit.' break Cheers Bernard On 2/8/06, calmar <[EMAIL PROTECTED]> wrote: > Hi all, > > unfotunately, 'commands.getstatusoutput(command)' does not work under > windows. > > Would there be any alternative? > > os.system also just provides the exit number I think. > > thanks a lot, > and cheers > marco > > > -- > calmar > > (o_ It rocks: LINUX + Command-Line-Interface > //\ > V_/_ http://www.calmar.ws > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: 450 Pound Library Program
Ok, I give up. DRY = Don't Repeat Yourself (google Pragmatic Programmers) but SPOT? Google is little help here, SPOT is too common a word. Thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: UnboundMethodType and MethodType
Kent Johnson wrote: > Kirk McDonald wrote: ... >> >>> id(B.bar) >> -1211888788 >> >>> id(b.bar) >> -1211888788 >> >> It's the same function, whether it's bound or not > > No, it's not the same function. You got the same id because you didn't > bind B.bar and b.bar to anything so the id was reused. > > >>> class B(object): > ... def bar(self): pass > ... > >>> Bbar = B.bar > >>> bbar = B().bar > >>> Bbar > > >>> bbar > > > >>> id(Bbar) > 10751312 > >>> id(bbar) > 10736624 > >>> Bbar is bbar > False > > Kent To elaborate on this, once 'id' is called, you drop the reference. This allows quite surprising things like: >>> id(7**8) == id(8**7) True >>> a, b = 7**8, 8**7 >>> id(a) == id(b) # this time there are other references to a and b False If you wanted to test the original code for identity match: >>> B.bar is B().bar False is the appropriate test (the 'is' test holds the identities through the comparison). By the by, this is tricky stuff, nobody should expect to understand it thoroughly without both study and testing. --Scott David Daniels [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: What editor shall I use?
I did not find where I can set encoding type in vim -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about idioms for clearing a list
Magnus Lycka wrote: >... I sometimes come across things that I once new but had forgotten. I'm sorry, and I mean no offense, _but_ I think _new_ there is a lovely typo. :-) I stopped, corrected it in my head, proceeded, and then I backed up, put it back and laughed out loud. --Scott David Daniels [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: module with __call__ defined is not callable?
Steven D'Aprano wrote: > On Wed, 08 Feb 2006 13:58:13 +1100, Delaney, Timothy (Tim) wrote: > >> adam johnson wrote: >> >>> Hi All. >>> I was wondering why defining a __call__ attribute for a module >>> doesn't make it actually callable. >> For the same reason that the following doesn't work > [snip example] >> The __call__ attribute must be defined on the class (or type) - not on >> the instance. A module is an instance of . > > That's not a _reason_, it is just a (re-)statement of fact. We know that > defining a __call__ method on a module doesn't make it callable. Why not? > The answer isn't "because defining a __call__ method on a module or an > instance doesn't make it callable", that's just avoiding the question. You missed it. Steven D'Aprano was telling you why, and all you heard was the no. He stated a more general principal which controls why modules in particular are not callable. It is not a design decision about modules; it is a design decision about classes and instances. class SomeClass(object): def __call__(self): return 'Text' class AnotherClass(object): def __repr__(self): return 'Missive' name = SomeClass()() # this works name = AnotherClass()() # this doesn't obj = AnotherClass() # build an instance def fun(*args): return 'more text' # *args so nearly any call works obj.__call__ = fun# tack a function onto an instance obj() # note this doesn't call the function. Now, if you think the last _should_ do the call, then let's step back to classes. class SomeClass(object): def __call__(self): return 'Text' Now the SomeClass object (which is a subclass of object) has an attribute named "__call__". Should that define how the expression SomeClass() is evaluated? Should that return the string 'Text' or create a new instance of SomeClass? --Scott David Daniels [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: apostrophe or double quote?
Thank you for all your help; it makes perfect sense now. -- http://mail.python.org/mailman/listinfo/python-list
PyGTK
Hi, I'm new to Python, and GUI development, but am no novice to backend programming. Aside from mastering the standard language, I will eventually be developing applications dealing with images and controls. Thus forth I have been testing out PyGTK & it appears to be quite robust (that and I like the fact of cross-platform compatibility). What I am curious to know is whether anyone has come across any noteworthy gui development platforms. Cross compatibility is not a must, but a bonus. Good documentation and clarity is essential for me. Also, I imagine I can use modules for image manipulation in tandem with the GUI interface? Any comments or speculations are looked forward to. Just thought I'd see if there's anything out there the community knows I may not be currently aware of. -- http://mail.python.org/mailman/listinfo/python-list
Re: Undergraduate project :: python ToDo list
Joao Macaiba <[EMAIL PROTECTED]> wrote: > Hi. > > I would like to know if there's any todo list on python project. > > My interest in doing a undergraduate project. > > It could be anything in the python core interpreter. I program C/C++. The PEP index shows several PEPs approved but not implemented for Python 2.5; take a look and write the development mailing list, python-dev@python.org, to volunteer to implement one of them. Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: What editor shall I use?
http://www.pspad.com/en/ Petr Jakes -- http://mail.python.org/mailman/listinfo/python-list
Re: Python threading, and processes
Robin Haswell <[EMAIL PROTECTED]> wrote: ... > Cheers for that info. The thread's main tasks are getting webpages > (spidering), the actual amount of processing done in each thread is > minimal - that's why I'm confused by the CPU usage. BTW, spidering is a great use case for async (even-driven) programming; use Twisted (or even build on top of asyncore) and you'll easily saturate your network bandwidth with modest CPU demands. Alex -- http://mail.python.org/mailman/listinfo/python-list
Re: Jython inherit from Java class
[Mark Fink] > I wrote a Jython class that inherits from a Java class and (thats the > plan) overrides one method. Everything should stay the same. > > If I run this nothing happens whereas if I run the Java class it says: > usage: java fit.FitServer [-v] host port socketTicket > -v verbose > > I think this is because I do not understand the jython mechanism for > inheritance (yet). 1. Are you running jythonc? If yes, I think your class and file should have the same name, i.e. Class FitServer should be in a file called "FitServer.py". I recommend calling your class something different from the base class, e.g. MyJythonFitServer, to prevent namespace clashes. 2. If your main function in jython? If yes, please post the code so we can see how you're instantiating your objects? 3. How are you running this? I.e. show us a command line session which uses your class. > JyFitServer.py: > === > class FitServer(fit.FitServer): > # call constructor of superclass > def __init__(self, host, port, verbose): > FitServer.__init__(self, host, port, verbose) ^ Shouldn't this be: > fit.FitServer.__init__(self, host, port, verbose) I'm not sure the latter is cause of your problems, but it might be. HTH, -- alan kennedy -- email alan: http://xhaus.com/contact/alan -- http://mail.python.org/mailman/listinfo/python-list
Re: Replacing curses (Was: Re: Problem with curses and UTF-8)
On 2006-02-08, Ian Ward <[EMAIL PROTECTED]> wrote: > I think there are enough escape sequences common to all modern terminals > so that I can build a generic curses-replacement for my library. Why not use termcap/terminfo? -- Grant Edwards grante Yow! Where does it go when at you flush? visi.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Is Python good for web crawlers?
On 2/8/06, Alex Martelli <[EMAIL PROTECTED]> wrote: > > Bot? me? did I fail a Turing test again without even noticing?! If you'd noticed the test, you'd have passed. ;-) -- Cheers, Simon B, [EMAIL PROTECTED], http://www.brunningonline.net/simon/blog/ -- http://mail.python.org/mailman/listinfo/python-list
RE: What editor shall I use?
I use it on XPvisit http://www.vim.org/download.php , and scroll down to the Windows section. --Brian > -Original Message- > From: [EMAIL PROTECTED] > [mailto:[EMAIL PROTECTED] > On Behalf Of Lad > Sent: Wednesday, February 08, 2006 10:08 > To: python-list@python.org > Subject: Re: What editor shall I use? > > is vim for XP? > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- http://mail.python.org/mailman/listinfo/python-list
Re: RPy / R
Thanks for your response. I'll try to install all the same versions that you have. I have removed my version of Python and installed ActivePython (ActivePython-2.4.2.10-win32-x86.msi). Could you please tell me which versions of the following you have installed: NumPy SciPy RPy R I have not installed Numeric. Is that different from NumPy? If so, which version do you have? Thanks. "Eddie" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > Hi Jason > > I had more success, being able to run a few test programs. > Not sure why yours would be crashing - I have a similar setup (Win XP SP2 > with all updates) - my version of Python is the Activestate download > (ActivePython-2.4.2.10-win32-x86.msi). Have you installed Numeric? > If all else fails might be worth trying to unistall Python and installing > the Activestate version (which includes the Win32 extensions). > > Good luck > > Eddie > > jason wrote: >> Hello: >> >> I installed the following: >> >> python-2.4.2.msi >> pywin32-207.win32-py2.4.exe >> R-2.2.1-win32.exe >> rpy-0.4.6-R-2.0.0-to-2.2.1-py24.win32.exe >> >> on a Windows XP (SP2) box. >> >> [SNIP] >> >> Is this a setup issue? Thanks for your help. >> -- http://mail.python.org/mailman/listinfo/python-list
Re: UnboundMethodType and MethodType
[...] >> It's the same function, whether it's bound or not. Thus, it should >> always have the same type. > > > No, it's not the same function. You got the same id because you didn't > bind B.bar and b.bar to anything so the id was reused. thank you for the explanation it's indeed tricky with reusing the id are there some pages on the net to read more about it? >>> class Q: ... def __init__(self,val): ... self.val = val ... def bar(self): ... print self.val ... >>> x = Q.bar >>> y = Q("test").bar >>> x >>> y > >>> y() test >>> id(x) 1078081812 >>> id(y) 1078082492 >>> the same id-value would enforce two objects to be of the same type (trivial case) the reverse is not necessarily true in this case x.bar and y.bar are of the same type UnboundMethodType is still not very suitable name for Q().bar :-/ Regards, Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about idioms for clearing a list
A slim lady in a brown overcoat appears and says with a silly French accent: "Lizten very carefully, I vill zay ziz only onze." BTW, I happen to reply to Ed's post now, but I'm really responding to a fairly common attitude which I find somewhat counterproductive. I hope people are openminded and able to see the point I'm trying to make. Ed Singleton wrote: > The point is that having to use del to clear a list appears to the > inexperienced as being an odd shaped brick when they've already used > the .clear() brick in other places. Agreed. The smart way to go from this stage of surprise is not to assume that Python is broken, but to try to understand how lists are different from e.g. dicts, and why the so-much- smarter-than-me Python designers made it like this. Hubris is considered a virtue in the Perl community. While not mentioned so much, I'd say that humility is considered a virtue here. Not that Python is perfect, but when you don't get a "sorry, this change would break existing code, won't happen until Python 3.0"-resonse, but a "study this more"-response, the smart thing is to open your mind and try to fully grok this. There is a very strong ambition among the Python developers to avoid duplication of features. This is one of the keys to Python's ease of use and readability. Don't bother suggesting synonyms. While there are thousands of situations where adding just another method would make life easier in the short run, life would be much harder if there were thousands of extra methods in the Python core! It isn't always possible to use one approch to a problem in all cases. If two approaches are used, they don't usually overlap. The "extra" approach is only used where the normal approach doesn't work. > Having bricks that work in lots of places makes the language > 'guessable'. "I've never cleared a list before, but I've cleared > dictionaries and I guess the same way would work here". I think we both agree that Python is very useful in this regard. It's more consistent than other languages I've worked with, and when things seems inconsistent, that's probably deliberate, and the appearent lack of consistency is a hint that we need to grok how these cases are different. You really happen to arrive at this from the wrong direction. :) The .clear() methods in dicts and sets are there because there is no other convenient way to empty these containers. There is no support in these kinds of containers to refer to the whole contents without copying. There is no which lets you do "del aDict[]" to clean a dict. You can do "for key in aDict: del aDict[key]", but since this is a fairly common thing to do, there is a shortcut for that called .clear(). I'm pretty sure the reason to implement it was speed rather than convenience. As you know, "There should be one-- and preferably only one --obvious way to do it." "Although practicality beats purity." In other words, moving a very common loop from Python to C was more important than a minimal interface. Don't forget to "import this" and ponder a bit... Statements and operators are really fundamental in Python. We don't support n = 1.add(2), since we have the '+' operator. You can't do x.clear() to remove arbitrary variables x from a namespace, but del x works for every x, whether it's a dict, a module or an int etc. Python basically just use methods when the statements and operators aren't enough. To really understand more about this, it might be useful to ask why we can't use del to somehow empty dicts instead. In the best case, that might possibly lead to the removal or at least deprecation of the .clear() method in Python 3.0, but I doubt that people would find some way that had the required beauty. > The problem is you have to be very careful when talking about this, > not to use the C-word, because that's the hobgoblin of little minds, > whereas in almost every other field it is considered an important part > of usability. That hobgoblin-phrase isn't very helpful. First of all, not all who respond to questions at comp.lang.python know what they are talking about. This is the internet. Take everything you read with a grain of salt. But another thing I've learnt in my years as a consultant, is that when experienced people directly and strongly reject an idea, they usually do that based on intuition and experience, and even if they are arguing poorly for their case, it's in your best interest to try to understand why they react like they do, or you'll fall down in that tar pit they were trying to warn you about. It's like being in a foreign country and meeting someone who is waving his arms and shouting incomprehensibly to you. Just because you don't understand what he's saying, you shouldn't assume that he's just talking jibberish and can be safely ignored. The smart approach is neither to stubbornly repeat your already rejected idea, nor to try to crush the arguments of those who oppose you, but rather to openly and humbly try your best to see
Re: Is Python good for web crawlers?
Magnus Lycka <[EMAIL PROTECTED]> wrote: ... > I dunno, but there are these two guys, Sergey Brin and Lawrence Page, > who wrote a web crawler in Python. As far as I understood, they were > fairly successful with it. I think they called their system Koogle, > Bugle, or Gobble or something like that. Goo...can't remember. > > See http://www-db.stanford.edu/~backrub/google.html Yeah, I've heard of them, too. > They've also employed some clever Python programmers, such as Greg > Stein, Alex Martelli (isn't he a bot?) and some obscure dutch > mathematician called Guido van something. It seems they still like > Python. Bot? me? did I fail a Turing test again without even noticing?! Alex -- http://mail.python.org/mailman/listinfo/python-list
encoding during elementtree serialization
ElementTree's XML serialization routine implied by tree._write(file, node, encoding, namespaces looks like this (elided): def _write(self, file, node, encoding, namespaces): # write XML to file tag = node.tag if tag is Comment: file.write("" % _escape_cdata(node.text, encoding)) elif tag is ProcessingInstruction: file.write("" % _escape_cdata(node.text, encoding)) else: ... file.write("<" + _encode(tag, encoding)) if items or xmlns_items: items.sort() # lexical order Note that "_escape_cdata" (which also performs encoding) and "_encode" are called for pcdata (and attribute values) only, but not for the tag literals like "<" and "". In some profiling I've done, I believe encoding during recursion makes serialization slightly slower than it could be if we could get away with not encoding any pcdata or attribute values during recursion. Instead, we might be able to get away with encoding everything just once at the end. But I don't know if this is kosher. Is there any reason to not also encode tag literals and quotation marks that are attribute containers, just once, at the end of serialization? Even if that's not acceptable in general because tag literals cannot be encoded, would it be acceptable for "ascii-compatible" encodings like utf-8, latin-1, and friends? Something like: def _escape_cdata(text, encoding=None, replace=string.replace): # doesn't do any encoding text = replace(text, "&", "&") text = replace(text, "<", "<") text = replace(text, ">", ">") return text class _ElementInterface: ... def write(self, file, encoding="us-ascii"): assert self._root is not None if not hasattr(file, "write"): file = open(file, "wb") if not encoding: encoding = "us-ascii" elif encoding != "utf-8" and encoding != "us-ascii": file.write("\n" % encoding) tmp = StringIO() self._write(tmp, self._root, encoding, {}) file.write(tmp.getvalue().encode(encoding)) def _write(self, file, node, encoding, namespaces): # write XML to file tag = node.tag if tag is Comment: file.write("" % _escape_cdata(node.text, encoding)) elif tag is ProcessingInstruction: file.write("" % _escape_cdata(node.text, encoding)) else: items = node.items() xmlns_items = [] # new namespaces in this scope try: if isinstance(tag, QName) or tag[:1] == "{": tag, xmlns = fixtag(tag, namespaces) if xmlns: xmlns_items.append(xmlns) except TypeError: _raise_serialization_error(tag) file.write("<" + tag) I smell the mention of a Byte Order Mark coming on. ;-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Best way of finding terminal width/height?
On 2006-02-08, Joel Hedlund <[EMAIL PROTECTED]> wrote: >> sys.stdin.read() will return when ... the >> underyling read() call is aborted by a signal. > > Not "return", really? Yes, really. On a SIGWINCH, the read() will _either_ return currently buffered data or thrown an IOError exception. You need to handle either one. > Won't it just pass an exception? That seems to be the behavior if there is no buffered data to return. > I thought that was what I was catching with the "except > IOError" part there? I assumed that sys.stdin.read() would > only return a value properly at EOF? That assumption seems to be wrong. sys.stdin.read() also returns w/o an exception if there's buffered data and a SIGWINCH occurs. Whether that is "proper" or not, I don't know, but that's what it does. Hmm, here's what the library reference says about file object's read() method: read([size]) Read at most size bytes from the file (less if the read hits EOF before obtaining size bytes). If the size argument is negative or omitted, read all data until EOF is reached. The bytes are returned as a string object. An empty string is returned when EOF is encountered immediately. (For certain files, like ttys, it makes sense to continue reading after an EOF is hit.) Note that this method may call the underlying C function fread() more than once in an effort to acquire as close to size bytes as possible. Also note that when in non-blocking mode, less data than what was requested may be returned, even if no size parameter was given. There appear to be a couple problems with this description: 1) It says that read() in blocking mode without a size parameter it will read until EOF. This is not what happens when reading a terminal that receives SIGWINCH, so you're right: read() it isn't working as described. 2) It also says that it makes sense to continue to read a tty after you get an EOF. That's not true. Once you get an EOF on a tty, there's no point in reading it any more: you'll continue to get an EOF forever. > It looks to me as if sys.stderr.read() really gets an EOF at > the final linebreak fed into the terminal prior to window size > change, because the final unterminated line shows up on my > shell prompt. Python's read() (which seems to call fread()) didn't get an EOF from fread(), it got an error from fread() because the C read() call that was made by fread() returned an error because it was interrupted by a signal. In Python, EOF is when read() returns '' (the empty string). > Like so: > > $ python winch.py > moo moo > cow cowmoo moo > $ cow cow > > In this example I type moo moo[ENTER]cow cow on my keyboard > and then resize the window. > > Now that EOF has to come from somewhere There was no EOF. read() returned because of the signal, not because of an EOF. > (since there's no > IOError or other exception, or the program wouldn't terminate > nicely with nothing on stderr) and I'd like to point the blame > at the terminal. Or is there something really fishy inside > sys.stdin.read() or signal that puts EOFs into streams? > > But anyway, as long as this behavior only shows up on > interactive operation, the user will likely spot it anyway and > can react to it. So I think this code would be pretty safe to > use. What do you think? > >> Resign the terminal will abort pending I/O operations on >> that terminal. It won't terminal I/O operations pending on >> other devices/files. > > What do you mean by "abort"? I can accept that "aborting" may > lead to raising of IOError (which we can catch and retry), but > not to arbitrary insertion of EOFs into streams (which we > cannot distinguish from the real deal coming from the user). It didn't insert an EOF, it just caused read() to return "prematurely". You should call read() again until it receives a _real_ EOF and returns ''. Take another look at my example: #!/usr/bin/python import signal, os, sys _bTerminalSizeChanged = False def report_terminal_size_change(signum, frame): global _bTerminalSizeChanged _bTerminalSizeChanged = True signal.signal(signal.SIGWINCH, report_terminal_size_change) while True: try: s = sys.stdin.read() if not s: sys.stderr.write("EOF\n") break sys.stdout.write(s) except IOError: sys.stderr.write("IOError\n") if _bTerminalSizeChanged: sys.stderr.write("SIGWINCH\n") _bTerminalSizeChanged = False -- Grant Edwards grante Yow! Yow! It's a hole at all the way to downtown visi.comBurbank! -- http://mail.python.org/mailman/listinfo/python-list
Re: Python threading, and processes
Robin Haswell wrote: > Hey there > > I'm doing some threading in python with Python 2.3 and 2.4 on Ubuntu and > Debian machines, and I've noticed that if I open a lot of threads (say, > 50), I get lots of python processes with individual PIDs, which consume a > disproportionate amount of CPU. Does this mean that Python is using the > dummy_thread module by accident? And is there a realistic limitation to > the number of threads I can do? Though I can not answer your question, I have however a similar situation here, on debian sarge. I have a simple daemon that runs one thread, and I noticed that on our sarges with kernel 2.4 my daemon creates 4 processes, on the ones with kernel 2.6, only one process. btw, I use the thread module. best regards, Yves > Cheers > > -Rob -- http://mail.python.org/mailman/listinfo/python-list
breadth first search
I am new in using Python Anyone know how to implement breadth first search using Python? Can Python create list dynamically, I want to implement a program which will read data from a file and store each line into a list, is this possible? Please send mail to me at [EMAIL PROTECTED] or reply this mail Thanks a lot! -- http://mail.python.org/mailman/listinfo/python-list
Re: What editor shall I use?
Lad wrote: > I did not find where I can set encoding type in vim Google is your friend. http://vim.sourceforge.net/scripts/script.php?script_id=789 http://www.vim.org/tips/tip.php?tip_id=246 http://www.vim.org/htmldoc/mbyte.html -- http://mail.python.org/mailman/listinfo/python-list
Re: 450 Pound Library Program
[EMAIL PROTECTED] wrote: > Ok, > > I give up. DRY = Don't Repeat Yourself (google Pragmatic Programmers) > but SPOT? Google is little help here, SPOT is too common a word. The only SPOT I worked with (as I know of) was SPOT4 (Le Systeme Pour 'l Observation de la Terre) but that's probably not it... Single Point Of Truth? It seems some claim that DRY and SPOT are the same things. http://www.artima.com/cppsource/reducepnp3.html -- http://mail.python.org/mailman/listinfo/python-list
Re: breadth first search
News wrote: > I am new in using Python > > Anyone know how to implement breadth first search using Python? Breadth-first search of what? It depends what kind of tree you're searching, but here's a page with a few implementations: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/231503 Can Python > create list dynamically, I want to implement a program which will read data > from a file and store each line into a list, is this possible? L = [] [L.append(line) for line in (open('filename.txt')] - C -- http://mail.python.org/mailman/listinfo/python-list
Re: Replacing curses
Thomas Dickey wrote: > hmm - I've read Urwid, and most of the comments I've read in that regard > reflect problems in Urwid. Perhaps it's time for you to do a little analysis. > > (looking forward to bug reports, rather than line noise) A fair request. My appologies for the inflammatory subject :-) When trying to check for user input without waiting I use code like: window_object.nodelay(1) curses.cbreak() input = window_object.getch() Occasionally (hard to reproduce reliably) the cbreak() call will raise an exception, but if I call it a second time before calling getch the code will work properly. This problem might be related to a signal interrupting the function call, I'm not sure. Also, screen resizing only seems to be reported once by getch() even if the user continues to resize the window. I have worked around this by calling curses.doupdate() between calls to getch(). Maybe this is by design? Finally, the curses escape sequence detection could be broadened. The top part of the curses_display module in Urwid defines many escape sequences I've run into that curses doesn't detect. Ian Ward -- http://mail.python.org/mailman/listinfo/python-list
Mixing custom __setattr__ method and properties in new style classes
Can custom __setattr__ methods and properties be mixed in new style classes? I experimented with a new style class with both a custom __setattr__ method and a property. Attributes controlled by the __setattr__ method work fine. When I attempt to set or get the property it raises the error: "TypeError: _settext() takes exactly two arguments (1 given)". This suggests that the __setattr__ may be conflicting with assignment to the property since it doesn't seem the class name is being passed to the property when it's created. This is the code for the property at the end of the class definition: def _settext(self, txt): self._tree.text = txt def _gettext(self, txt): return self._tree.text def _deltext(self, txt): self._tree.text = '' text = property(_settext, _gettext, _deltext) -- http://mail.python.org/mailman/listinfo/python-list
Number Format function
I'm am relatively new to Python but use it daily. Today, I went looking for a function, like PHP's number_function, that will take a number and return a string with number formatted with grouped thousands and the decimal portion rounded to a given number of places. This is certainly needed when you want to take a floating-point value from a database and display it as currency, for instance. I could not find what I was looking for so I wrote the following function. I hope either (a) I've provided something useful or (b) someone can tell me what I *should* have done! Thanks. import math def number_format(num, places=0): """Format a number with grouped thousands and given decimal places""" #is_negative = (num < 0) #if is_negative: #num = -num places = max(0,places) tmp = "%.*f" % (places, num) point = tmp.find(".") integer = (point == -1) and tmp or tmp[:point] decimal = (point != -1) and tmp[point:] or "" count = commas = 0 formatted = [] for i in range(len(integer) - 1, 0, -1): count += 1 formatted.append(integer[i]) if count % 3 == 0: formatted.append(",") integer = "".join(formatted[::-1]) return integer+decimal begin:vcard fn:Edward Hartfield n:Hartfield;Edward org:BungeeCraft Technologies adr;dom:;;4824 W Medford Avenue;Milwaukee;Wisconsin;53216 email;internet:[EMAIL PROTECTED] title:President tel;work:414 839-2387 tel;fax:414 449-9105 note:Milwaukee-based BungeeCraft Technologies provides cost-effective technology solutions for small and mid-sized businesses. From aligning our clients' business and IT strategies to improving business processes and deploying and supporting solutions that accelerate business results, we are able and ready to provide YOU with comprehensive information technology solutions and services. x-mozilla-html:FALSE url:http://www.bungeecraft.com version:2.1 end:vcard -- http://mail.python.org/mailman/listinfo/python-list
Re: breadth first search
> Anyone know how to implement breadth first search using Python? Yes. Granted, for more details, you'd have to describe the data structure you're trying to navigate breadth-first. > Can Python create list dynamically Is Perl write-only? Does Lisp use too many parens? Of course! :) Not only can Python create lists dynamically, but it's one of Python's strong points. x = [] x.append(42) x.append("hello") h = x.pop() ft = x.pop() > I want to implement a program which will read data > from a file and store each line into a list, is this possible? x = [line[:-1] for line in open("file.txt", "r").readlines()] will assign the contents of the file "file.txt" to the list "x", making x[0] the first line in the file and x[-1] is the last line in the file. If you want to make other use of the file, you can open a file object first: fileObject = open("file.txt", "r") x = [line[:-1] for line in fileObject.readlines()] # use fileObject elsehow here fileObject.close() The convention of using the "line[:-1]" strips off the newline at the end of each line. Otherwise, you can just use "line" instead of "line[:-1]" -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: Mixing custom __setattr__ method and properties in new style classes
I see the error: the get and set properties are inverted. Now it works. -- http://mail.python.org/mailman/listinfo/python-list
Re: breadth first search
Chris McDonough wrote: >> Can Python >> create list dynamically, I want to implement a program which will read >> data from a file and store each line into a list, is this possible? > > L = [] > [L.append(line) for line in (open('filename.txt')] Why would you create two lists, one filled only with None entries just to throw it away immediately? Don't use list comprehensions just because you can. Here are two sane approaches: lines = open(filename).readlines() lines = list(open(filename)) # a bit more generic Finally, if you want to strip off the trailing newlines, a list comprehension is in order: lines = [line[:-1] for line in open(filename, "U")] Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: breadth first search
Chris McDonough wrote: > L = [] > [L.append(line) for line in (open('filename.txt')] Ouch. Did you perhaps mean: L = [ line for line in open('filename.txt') ] Or, with better error handling: try: f = open('filename.txt') except IOError: # handle error here else: L = [ line for line in f ] -- http://mail.python.org/mailman/listinfo/python-list
Re: Omniorb event channel question
Diez B. Roggisch <[EMAIL PROTECTED]> wrote: >> channel = orb.getRootInterface(channelname) >> chadmin = channel.for_consumers() >> supplier = chadmin.obtain_push_supplier() >> listener = EventListener() >> supplier.connect_push_consumer(listener) > > Not sure, but I guess you want a > > listener._this() > > here. That worked, thanks. However, the event receiving doesn't seem to work. I've started the ORB with corba.orb.run() but the push() method of the EventListener object doesn't get called (or at least the print() calls in the method are not executed) and the event sender program is blocked in the push() call. Do I need something else to set up? Bye,NAR -- http://mail.python.org/mailman/listinfo/python-list
Re: breadth first search
Chris McDonough wrote: > News wrote: >... Can Python >> create list dynamically, I want to implement a program which will read >> data >> from a file and store each line into a list, is this possible? > > L = [] > [L.append(line) for line in (open('filename.txt')] > > - C Woops, crossed wires there: after: somefile = open('filename.txt') You can do: L = somefile.readlines() or L = [line for line in somefile] or L = [] for line for line in somefile: L.append(line) to put all lines of somefile into L, but L = [] K = [L.append(line) for line in somefile] builds a list K that has a None for each line in somefile, while filling up L with the lines as a side-effect. It is a style to avoid. Dropping the "K = " part simply says "build the list of Nones and then discard it." -- not good style. Also, it is good style to then call somefile.close() after you are done with the file. --Scott David Daniels [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: sys.path and unicode folder names
>> Nir Aides wrote: >>> Is there a solution or a work around for the sys.path problem with >>> unicode folder names on Windows XP? >>> >>> I need to be able to import modules from a folder with a non-ascii name. > Martin v. Löwis wrote: >> If the name is restricted to the CP_ACP code page (i.e. more than >> ASCII, less then full Unicode), using the "mbcs" encoding should work >> fine. Regards, Martin Nir Aides: > I can not restrict the name to CP_ACP. > I am interested in the general case of Unicode. > Windows XP is a native Unicode OS. Python internally converts unicode entries on sys.path to strings before using them. Changing that would require a large rewrite of the import machinery. I once started to work on a patch, but got ZERO feedback, so I gave up. Thomas -- http://mail.python.org/mailman/listinfo/python-list
Re: Mixing custom __setattr__ method and properties in new style classes
"L.C. Rees" wrote: > This is the code for the property at the end of the class definition: > > def _settext(self, txt): > self._tree.text = txt > > def _gettext(self, txt): > return self._tree.text > > def _deltext(self, txt): > self._tree.text = '' > > text = property(_settext, _gettext, _deltext) hint: >>> help(property) class property(object) | property(fget=None, fset=None, fdel=None, doc=None) -> property attribute | | fget is a function to be used for getting an attribute value, and likewise | fset is a function for setting, and fdel a function for del'ing, an | attribute. Typical use is to define a managed attribute x: | class C(object): | def getx(self): return self.__x | def setx(self, value): self.__x = value | def delx(self): del self.__x | x = property(getx, setx, delx, "I'm the 'x' property.") -- http://mail.python.org/mailman/listinfo/python-list
email questions
I'm looking for a way to send a simple, plain text email message using Python. My initial attempts are failing with the following error: socket.error: (61, 'Connection refused') Does this imply that I do not have the machine's smtp server running? (I don't; and I'd like to avoid setting it up.) I'm following example code in the lib ref docs: >>> s = smtplib.SMTP() >>> s.connect() Traceback (most recent call last): File "", line 1, in ? File "/Library/Frameworks/Python.framework/Versions/2.4/lib/ python2.4/smtplib.py", line 303, in connect raise socket.error, msg socket.error: (61, 'Connection refused') Python 2.4.1 MacOSX 10.4.3 Is there a better/easier way to send a plain text message? Thanks in advance! Scott -- http://mail.python.org/mailman/listinfo/python-list
Re: Mixing custom __setattr__ method and properties in new style classes
L.C. Rees wrote: > Can custom __setattr__ methods and properties be mixed in new style > classes? > > I experimented with a new style class with both a custom __setattr__ > method and a property. Attributes controlled by the __setattr__ method > work fine. When I attempt to set or get the property it raises the > error: "TypeError: _settext() takes exactly two arguments (1 given)". > This suggests that the __setattr__ may be conflicting with assignment > to the property since it doesn't seem the class name is being passed to > the property when it's created. This is the code for the property at > the end of the class definition: > > def _settext(self, txt): > self._tree.text = txt > > def _gettext(self, txt): > return self._tree.text > > def _deltext(self, txt): > self._tree.text = '' > > text = property(_settext, _gettext, _deltext) > The order to call property is get, set, del, doc You need to take a _lot_ more care before asking for help. neither get not del take any arg besides self. When you are trying to debug an interaction, make sure your tests work stand- alone. class Holder(object): pass # to allow attributes stuck on class Demo(object): def __init__(self): self._tree = Holder() def _settext(self, txt): self._tree.text = txt def _gettext(self): return self._tree.text def _deltext(self): self._tree.text = '' text = property(_gettext, _settext, _deltext, 'text property') d = Demo() d.text = 'my text' print repr(d.text) del d.text print repr(d.text) --Scott David Daniels [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: breadth first search
Peter Otten wrote: > Chris McDonough wrote: > >>> Can Python >>> create list dynamically, I want to implement a program which will read >>> data from a file and store each line into a list, is this possible? >> L = [] >> [L.append(line) for line in (open('filename.txt')] > > Why would you create two lists, one filled only with None entries just to > throw it away immediately? Don't use list comprehensions just because you > can. Yes, of course. Thank you. I didn't mean to offend your sensibilities. I'm not retarded *every* day, just today. ;-) - C -- http://mail.python.org/mailman/listinfo/python-list
Re: how to...python with winmodem...
pdt wrote: > Hello, i wanna know how to communicate my python program with my > winmodem on PC...thanks!!! Use pyserial. Diez -- http://mail.python.org/mailman/listinfo/python-list