[Python-Announce] cfgparse v01_01 released
I'm pleased to announce the V01_01 release of cfgparse. Whats New - 1) Exception argument added to the Configuration parser initializer so that exceptions may be raised when user errors are encountered instead of the default call to sys.exit() that doesn't provide traceback. 2) Error messages were enhanced giving more detailed information. Background - cfgparse is a more convenient, flexible, and powerful module for parsing configuration files than the standard library ConfigParser module. cfgparse uses a more declarative style modelled after the popular optparse standard library module. cfgparse can optionally cooperate with the optparse module to provide coordination between command line and configuration file options. In addition, the cooperation can be used to allow the user to control features of the parser from the command line. URLs - Documentation: http://cfgparse.sourceforge.net/ Download: http://sourceforge.net/projects/cfgparse/ Feature Summary - + Simple ini style configuration syntax. + Type checking with error handling and help messages. + Help summary modelled after that in optparse. + Round trip - read, modify, write configuration files with comment retention. + Cooperates with optparse so options may be overridden from command line. + Supports heirarchically organized option settings. * User may store multiple option settings in a arbitrarily deep keyed dictionary. * Application uses a key list to walk into the dictionary to obtain a setting. * User controls key list with setting in configuration file. * Keys may be added to the list using command line or environment variables. + Supports allowing user control of configuration files used. * Environment variables may be used to specify a default configuration file. * Command line may be used to specify additional configuration files. * Configuration files may include other configuration files. + Configuration files may alternatively be written in Python. * Full power and flexibility of Python available for creation of option settings. * Allows options settings to be real Python objects. * This feature is NOT enabled by default. + May be extended to support syntax such as XML. Enjoy, Dan Gass -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Re: Python limericks (was Re: Text-to-speech)
Michael Spencer wrote: How about a category for executable limericks? That was my thought too... for programmer in search_of(elegance): if programmer.needs(an experience): print whitespace counts much if Van_Rossum is Dutch: print Dictators are made by benevolence And an attempt at a self-replicating one that uses far too many syllables in the last line: rhymes = 'for line in [rhymes, fines]:\n ' fines = 'print line, =, `eval(line)`\n' for line in [rhymes, fines]: print line, =, `eval(line)` whine='whine=%s;print rhymes, fines, whine%%`whine`';print rhymes, fines, whine%`whine` This can actually be pronounced as a proper limerick as follows: always pronounce = as is and ; as so, don't pronounce any other punctuation, and cheat by pronouncing the first string in the last line as junk :-) rhymes is for line in rhymes fines fines is print line is eval line for line in rhymes fines print line is eval line whine is junk so print rhymes fines whine whine David -- http://mail.python.org/mailman/listinfo/python-list
Re: MinGW building with Python 2.4
mrstephengross wrote: Ok, I know there are already a million posts on this group about getting Python to build with MinGW. I've been through many of them, and have still not found a good comprehensive way to accomplish this. I've got Cygwin 5.1 with GCC 3.3.3 on it. I'm using Python 2.4. Note: You invoke the mingwin compiler *indirectly*, by running gcc with the -mno-cygwin option. So first of all, I tried exporting CC='gcc -mno-cygwin', configuring, and making. You end up getting file-not-found errors, because some of the include files aren't present for mingw. Next: I tried pymingw: didn't work :( Any ideas? Since the only official way to do this is pymingw, you should at least give feedback of the steps you followed, and what didn't work David -- http://mail.python.org/mailman/listinfo/python-list
Re: Regular Expressions: large amount of or's
: Done. 'startpos' and other bug fixes are in Release 0.7: : http://hkn.eecs.berkeley.edu/~dyoo/python/ahocorasick/ahocorasick-0.7.tar.gz Ok, I stopped working on the Aho-Corasick module for a while, so I've just bumped the version number to 0.8 and posted it up on PyPI. I did add some preliminary code to use graphviz to emit DOT files, but it's very untested code. I also added an undocumented api for inspecting the states and their transitions. I hope that the original poster finds it useful, even though it's probably a bit late. Hope this helps! -- http://mail.python.org/mailman/listinfo/python-list
Re: Regular Expressions
escape chars are always a pain when making regex's. There is a section on it the Regex HOWTO http://www.amk.ca/python/howto/regex/regex.html#SECTION00042 -- http://mail.python.org/mailman/listinfo/python-list
Re: Anonymus functions revisited
Op 2005-03-22, Diez B. Roggisch schreef [EMAIL PROTECTED]: Not exactly in fact - unless I messed something. There are 2 problems here: a more flexible tuple unpacking, *and* a lambda in disguise. Actually, I'd go + 1 for the first, -1 for the second The proposed syntax from Kay is lambda in disguise. To make it work like George want it is modifying the unpacking behaviour. Actually while Kay proposed his syntax as result of the discussion started by George it won't work for that case. The reason is simply that the lambda form returns a tuple, but does not make any revelations about the variable names that tuple shall be unpacked to. So they are in fact unrelated - at least if introduced as declared. An augmentation to fulfill George's wishes could look like this: [a,b,c for a,b,c: (x,y,z=0)- x,y,z) in values] Yes, one can live without... troll ...and without list comprehensions, __call__ and other special methods, descriptors, metaclasses, first class functions, builtin datatypes like lists and dicts, exceptions, dynamic typing, garbage collection, etc too. Hurray, let's all happily program in assembly !-) /troll You are right, but for lambda in its current limited form short, named functions are a good replacement. I don't want to get rid of lambda - but since listcomps got introduced, 95% of my usages of them disappeared. I don't understand why people always say short named functions are a good replacement. IMO list comprehensions and generator expressions use lambda's in disguise. When we write something like [x * x for x in some_iterator], nobody seems to have problems that we just write an expression here and nobody is argueing that we should define a short function. However when people need the same kind of semantics in their function, being an expression that is being reevaluated with different values, for which lambda is the natural candidate, suddenly we should use short named functions. Can someone who thinks this way, please explain why this is acceptable [ x * x for x in some_iterator ] But this is not map(lambda x: x * x, some_iteraror) and should be replaced with def sqr(x): return x * x map(sqr , some_iterator) -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: Please help for Python programming
Thanks for your advice.^^ I find out something special (because i don't know). I would like to retrieve data from source file into array. The data will be omited if the value is duplicated. For example, there is 3 values - 1,2,1. It will only display 1,2 after i ran the script. value = (1,2,1) while 1: users = {} byteDict = {} byteDict = users[value] users[value] = byteDict print users I think the above code cannot run properly. Any ppl knows why the value omited when it was duplicated. Many of thanks for all!!! -- http://mail.python.org/mailman/listinfo/python-list
Re: I'm just an idiot when it comes logging
olsongt at verizon.net writes: I'm trying to be a good boy and use the logging module but it's behaving rather counter-intuitively. I've posted a simplified test script below. To summarize, I've set the basic config to only log root level messages with = ERROR level. I've created another named logger that logs on info level. I've set it up so it just shows the message text without INFO:: logger: boilerplate. The way I see things, when I call otherLogger.info, it should propogate the message to the root logger, but the root logger should discard it since it is at ERROR level. Could someone explain what I'm not getting? -Grant The way it works is: when you log to a logger, the event level is checked against the logger. If the event should be logged (event level = logger level) then the event is passed to the handlers configured for that logger, and (while the logger's propagate attribute is true - the default - passed to handlers configured for loggers higher up the hierarchy. In your case, this inlcudes the root logger's handlers. Note that if you don't set a level on a logger, then the hierarchy is searched until a level is found. That becomes the effective level for the logger. Handlers normally process all events passed to them, but you can set a level on a handler to get it to drop events below a certain threshold. Since you haven't done this, you will see an INFO message appear even though the root logger's level is set to ERROR. (This would only affect logging calls to the root logger). Rule of thumb: Set levels on handlers only when you need them, not as common practice. If you don't want to see info messages from otherLogger, set its level to INFO. Vinay Sajip -- http://mail.python.org/mailman/listinfo/python-list
Re: Please help for Python programming
[EMAIL PROTECTED] wrote: Thanks for your advice.^^ It would be more useful to follow them than to thank me. I find out something special (because i don't know). I would like to retrieve data from source file into array. The data will be omited if the value is duplicated. For example, there is 3 values - 1,2,1. It will only display 1,2 after i ran the script. value = (1,2,1) while 1: users = {} byteDict = {} byteDict = users[value] users[value] = byteDict print users I think the above code cannot run properly. Don't think. Be sure. Verify. Try to find out why it cannot run at all[1]. Fix this problem first. *Then* we'll happily read your next posts and try to help you fix the other problems if there are... [1] It's pretty obvious for anyone having read any python beginner tutorial, I already explained you why, and gave you a working example. If you don't read answers, don't post questions :-/ -- 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: Anonymus functions revisited
Ron wrote: On Tue, 22 Mar 2005 21:56:57 GMT, Ron [EMAIL PROTECTED] wrote: Why should a function not create a local varable of an argument if the varable doesn't exist and a default value is given? ok... thought it out better. :) Getting a default into a function isn't the problem. Returning the value to a varable that doesn't exist is. So then the question is ... is there a way for a function to create a varable in it's parents namespace that persists after the function is done? yes, that'w called a global, and it's UGLY(tm) def yuck(): ... global G ... G = 42 ... G Traceback (most recent call last): File stdin, line 1, in ? NameError: name 'G' is not defined yuck() G 42 Anyone doing such a thing in my team would be shoot down at once !-) -- 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: Anonymus functions revisited
George Sakkis wrote: Ron [EMAIL PROTECTED] wrote: On Tue, 22 Mar 2005 21:56:57 GMT, Ron [EMAIL PROTECTED] wrote: Why should a function not create a local varable of an argument if the varable doesn't exist and a default value is given? ok... thought it out better. :) Getting a default into a function isn't the problem. Returning the value to a varable that doesn't exist is. So then the question is ... is there a way for a function to create a varable in it's parents namespace that persists after the function is done? Yeap.. a simple one-liner can do the trick: def makeVars(**nameVals): sys._getframe(1).f_locals.update(nameVals) try: b except NameError: print Before makeVars: NameError else: print Before makeVars: Not NameError makeVars(b=2) try: b except NameError: print After makeVars: NameError else: print After makeVars: Not NameError Interesting. I'll keep a copy of this one in my cookbook for further exploration. But I think I would use such a thing in production code. b = 25 makeVars(b=88) b 88 -- 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: Anonymus functions revisited
Ron wrote: On Tue, 22 Mar 2005 21:45:42 +0100, Bruno Desthuilliers [EMAIL PROTECTED] wrote: Ron a écrit : On 21 Mar 2005 22:37:42 -0800, Kay Schluehr [EMAIL PROTECTED] wrote: Mappings like that: ((x,y),z) - x+y-z ((x,y=0),z) - None should be valid actions too. What is the audience thinking about that? I think that there's too much implied, and that in the long run it, if we keep addding in special shortcuts, it will lead to very dificult to read code. Don't like Perl ?-) I tried it.. Wrote a html reformatter in it a long time ago. Wasn't tempted to do anything else with it. It was good for that, but I went a month later and had trouble figuring out how it worked. :) This was kind of rethorical question !-) The problem here is that Kay's proposition mixes two points: flexible tuple unpacking and a new syntax for anonymous functions. Yes, two different problems. I don't think anything needs to be done to tuples myself. I tend to use lists more anyway. They are two different beasts. Note that you don't have anything like list unpacking, now tuple unpacking is pretty common in Python (swap, multiple return values, formatted strings and outputs, ...). As far as anonymous functions go... (snip prospective code) Yes, there are probably loads of stuff wrong with this. ;-) Err... Isn't it a bit more complicated than our actual lambdas ?-) -- bruno desthuilliers ruby -e print '[EMAIL PROTECTED]'.split('@').collect{|p| p.split('.').collect{|w| w.reverse}.join('.')}.join('@') -- http://mail.python.org/mailman/listinfo/python-list
Re: missing? dictionary methods
Op 2005-03-22, Bengt Richter schreef [EMAIL PROTECTED]: On 22 Mar 2005 07:40:50 GMT, Antoon Pardon [EMAIL PROTECTED] wrote: [...] I also was under the impression that a particular part of my program almost doubled in execution time once I replaced the naive dictionary assignment with these self implemented methods. A rather heavy burden IMO for something that would require almost no extra burden when implemented as a built-in. I think I see a conflict of concerns between language design and optimization. I call it arms-length assembler programming when I see language features being proposed to achieve assembler-level code improvements. For example, what if subclassing could be optimized to have virtually zero cost, with some kind of sticky-mro hint etc to the compiler/optimizer? How many language features would be dismissed with just do a sticky subclass? I'm sorry you have lost me here. What do you mean with stick-mro My feeling about this is the following. A[key] = value, A.reset(key, value) and A.make(key, value) would do almost identical things, so identical that it would probably easy to unite them into something like A.assign(key, value, flag) where flag would indicate which of the three options is wanted. Also a lot of this code is identical to searching for a key. Now because the implemantation doesn't provide some of the possibilities I have to duplicate some of the work. One could argue that hashes are fast enough so that this doesn't matter, but dictionaries are the template for all mappings in python. What it you are using a tree and you have to go through it twice or what if you are working with slower mediums like with one of the dbm modules where you have to go through your structure on disk twice. You can see it as assembler-level code improvements, but you also can see it as an imcomplete interface to your structure. IMO it would be like only providing '' and if people wanted '==' they would have to implement that like 'not (b a or a b)' and in this case too, this would increase the cost compared with a directly implemented '=='. But you are right that there doesn't seem to be much support for this. So I won't press the matter. I think I would rather see efficient general composition mechanisms such as subclassing, decoration, and metaclassing etc. for program elements, if possible, than incremental aggregation of efficient elements into the built-in core. Also, because optimization risks using more computation to optimize than the expression being optimized, I think this would hardly be the case here. The dictionary code already has to find out if the key is already in the hash or not. Instead of just continuing the branch it decided on as is now the case, the code would test if the branch is appropiate for the demanded action and raise an exception if not. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: Anonymus functions revisited : tuple actions
Kay Schluehr wrote: Hi all, thanks for Your attention ! I think my proposal was more in mind of Rons modified exec than Pythons lambda. When George proposed his unpacking behavoir for list-comps as a pack of suggar: 1. [x*y-z for (x,y,z=0) in (1,2,3), (4,5), (6,7,8)] I interpreted it in a subsequent posting in lambda fashion: 2. [(lambda x,y,z=0:x*y-z)(*v) for v in (1,2,3), (4,5), (6,7,8)] Argh! Stupid me ! I never thought of using the star operator for this :( Thanks Kay. (snip) -- 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: Anonymus functions revisited
George Sakkis wrote: So then the question is ... is there a way for a function to create a varable in it's parents namespace that persists after the function is done? Yeap.. a simple one-liner can do the trick: def makeVars(**nameVals): sys._getframe(1).f_locals.update(nameVals) try: b except NameError: print Before makeVars: NameError else: print Before makeVars: Not NameError makeVars(b=2) try: b except NameError: print After makeVars: NameError else: print After makeVars: Not NameError Do I really need to mention that the whole concept here is broken. This only works if you call it from global scope. If you call it from inside a function it [usually] won't work: def makeVars(**nameVals): sys._getframe(1).f_locals.update(nameVals) def test(): try: b except NameError: print Before makeVars: NameError else: print Before makeVars: Not NameError makeVars(b=2) try: b except NameError: print After makeVars: NameError else: print After makeVars: Not NameError import sys test() Before makeVars: NameError After makeVars: NameError -- http://mail.python.org/mailman/listinfo/python-list
Python to c++ conversion problem
I have a code in python like if eval('player.moveRoom(SeLinuxMud.Direction.' + x + ')'): # moveRoom function takes Direction enum as a parameter When I am trying to write this code in c++ if (player-moveRoom(s[1])) //s[1] is a string so it outputs an error because of not taking enum as a parameter How can I change string to enum in c++? Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: cross platform use of set locale
Timothy Smith wrote: thats ok, but how do i get it to group thousands with a , ? and thats would mean i'd have to run everything through a formatter before i displayed it :/ it'd be nicer if i could just select a proper locale I think you're misusing locale. There is no guarantee that any specific locale will have properties (like grouping) set to a known value. Are you trying to format money? Then you need a special class so that you can say: d = Dollars(100.01) print You have %s in your account % d and get You have $1,000,000.01 in your account. Serge. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python to c++ conversion problem
Hi, Convert the string to int then cast the int to enum with static_cast. Ahmed Akdes Serin [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] I have a code in python like if eval('player.moveRoom(SeLinuxMud.Direction.' + x + ')'): # moveRoom function takes Direction enum as a parameter When I am trying to write this code in c++ if (player-moveRoom(s[1])) //s[1] is a string so it outputs an error because of not taking enum as a parameter How can I change string to enum in c++? Thanks. -- http://mail.python.org/mailman/listinfo/python-list
setattr inside a module
I'm trying to use setattr inside a module. From outside a module it's easy: import spam name=hello value=1 setattr(spam, name, value) But if I want to do this inside the module spam itself, what I've to pass to setattr as first argument? Thanks a lot for your time. Marco. -- http://mail.python.org/mailman/listinfo/python-list
Re: cross platform use of set locale
Serge Orlov wrote: Timothy Smith wrote: thats ok, but how do i get it to group thousands with a , ? and thats would mean i'd have to run everything through a formatter before i displayed it :/ it'd be nicer if i could just select a proper locale I think you're misusing locale. There is no guarantee that any specific locale will have properties (like grouping) set to a known value. Are you trying to format money? Then you need a special class so that you can say: d = Dollars(100.01) print You have %s in your account % d and get You have $1,000,000.01 in your account. Serge. thats exactly what i'm trying to do, only having to do that for all my outputs is more work then i'd like :/ why is this a misuse of locale? it's exactly what locale is meant for isn't it? -- http://mail.python.org/mailman/listinfo/python-list
Re: Regular Expressions
Ron wrote: This is probably a repeated question, but try as I might I was unable to find something similar in the archives. I'm trying to develop a regular expression for recognizing a simplified C-Style string syntax. I need it to be able to handle escape sequences of the form \x where x is any character including . Here's what I'm trying: \([^\\]|(\\.))*\ When I try to get it to recognize something like: I said, \Hello!\ It stops at the first quote after the \. Works for me: print re.search(r'\([^\\]|(\\.))*\', ... r'I said \Hello!\').group(0) I said \Hello!\ You can leave out the backslashes in fron of the first and last quotes in the regex, by the way, at least if you use ' instead of to delimite it: print re.search(r'([^\\]|(\\.))*', ... r'I said \Hello!\').group(0) I said \Hello!\ -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven -- http://mail.python.org/mailman/listinfo/python-list
Re: setattr inside a module
On Wed, 23 Mar 2005 11:35:34 +0100 kramb64 wrote: K I'm trying to use setattr inside a module. K From outside a module it's easy: K K import spam K name=hello K value=1 K setattr(spam, name, value) K K But if I want to do this inside the module spam itself, what I've to K pass to setattr as first argument? globals()[name] = value or setattr(__import__(__name__), name, value) # note, circular import here -- Denis S. Otkidach http://www.python.ru/ [ru] -- http://mail.python.org/mailman/listinfo/python-list
PyGTK Button Size Question
How does one set the width of a gtk.Button explicitly? and height for that matter as well... thanks, Harlin Seritt -- http://mail.python.org/mailman/listinfo/python-list
Re: Python-list Digest, Vol 18, Issue 366
I have a doubt in python curses how to get the current screen size using python curses... glad if neone cud help thankz Sagar On Wed, 23 Mar 2005 12:00:17 +0100 (CET), [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Send Python-list mailing list submissions to python-list@python.org To subscribe or unsubscribe via the World Wide Web, visit http://mail.python.org/mailman/listinfo/python-list or, via email, send a message with subject or body 'help' to [EMAIL PROTECTED] You can reach the person managing the list at [EMAIL PROTECTED] When replying, please edit your Subject line so it is more specific than Re: Contents of Python-list digest... Today's Topics: 1. Re: cross platform use of set locale (Serge Orlov) 2. Re: Python to c++ conversion problem (Ahmed MOHAMED ALI) 3. setattr inside a module (kramb64) 4. Re: cross platform use of set locale (Timothy Smith) 5. Re: Regular Expressions (Roel Schroeven) -- Forwarded message -- From: Serge Orlov [EMAIL PROTECTED] To: python-list@python.org Date: 23 Mar 2005 02:34:06 -0800 Subject: Re: cross platform use of set locale Timothy Smith wrote: thats ok, but how do i get it to group thousands with a , ? and thats would mean i'd have to run everything through a formatter before i displayed it :/ it'd be nicer if i could just select a proper locale I think you're misusing locale. There is no guarantee that any specific locale will have properties (like grouping) set to a known value. Are you trying to format money? Then you need a special class so that you can say: d = Dollars(100.01) print You have %s in your account % d and get You have $1,000,000.01 in your account. Serge. -- Forwarded message -- From: Ahmed MOHAMED ALI [EMAIL PROTECTED] To: python-list@python.org Date: Wed, 23 Mar 2005 11:54:24 +0100 Subject: Re: Python to c++ conversion problem Hi, Convert the string to int then cast the int to enum with static_cast. Ahmed Akdes Serin [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] I have a code in python like if eval('player.moveRoom(SeLinuxMud.Direction.' + x + ')'): # moveRoom function takes Direction enum as a parameter When I am trying to write this code in c++ if (player-moveRoom(s[1])) //s[1] is a string so it outputs an error because of not taking enum as a parameter How can I change string to enum in c++? Thanks. -- Forwarded message -- From: kramb64 [EMAIL PROTECTED] To: python-list@python.org Date: Wed, 23 Mar 2005 11:35:34 +0100 Subject: setattr inside a module I'm trying to use setattr inside a module. From outside a module it's easy: import spam name=hello value=1 setattr(spam, name, value) But if I want to do this inside the module spam itself, what I've to pass to setattr as first argument? Thanks a lot for your time. Marco. -- Forwarded message -- From: Timothy Smith [EMAIL PROTECTED] To: Serge Orlov [EMAIL PROTECTED], python-list@python.org Date: Wed, 23 Mar 2005 20:52:06 +1000 Subject: Re: cross platform use of set locale Serge Orlov wrote: Timothy Smith wrote: thats ok, but how do i get it to group thousands with a , ? and thats would mean i'd have to run everything through a formatter before i displayed it :/ it'd be nicer if i could just select a proper locale I think you're misusing locale. There is no guarantee that any specific locale will have properties (like grouping) set to a known value. Are you trying to format money? Then you need a special class so that you can say: d = Dollars(100.01) print You have %s in your account % d and get You have $1,000,000.01 in your account. Serge. thats exactly what i'm trying to do, only having to do that for all my outputs is more work then i'd like :/ why is this a misuse of locale? it's exactly what locale is meant for isn't it? -- Forwarded message -- From: Roel Schroeven [EMAIL PROTECTED] To: python-list@python.org Date: Wed, 23 Mar 2005 10:51:41 GMT Subject: Re: Regular Expressions Ron wrote: This is probably a repeated question, but try as I might I was unable to find something similar in the archives. I'm trying to develop a regular expression for recognizing a simplified C-Style string syntax. I need it to be able to handle escape sequences of the form \x where x is any character including . Here's what I'm trying: \([^\\]|(\\.))*\ When I try to get it to recognize something like: I said, \Hello!\ It stops at the first quote after the \. Works for me: print re.search(r'\([^\\]|(\\.))*\', ... r'I said \Hello!\').group(0) I said \Hello!\ You can leave out the backslashes in fron of the first and last quotes in the regex, by the way, at least if you use ' instead of to
Re: Anonymus functions revisited
Can someone who thinks this way, please explain why this is acceptable [ x * x for x in some_iterator ] But this is not map(lambda x: x * x, some_iteraror) and should be replaced with def sqr(x): return x * x map(sqr , some_iterator) It shouldn't, it should be replaced with the listcomp. And IMHO it results in better readable code. AFAIK the reason people say you should use named functions is _not_ because of these single expression replacements. The reason is that frequently people complain about lambda being so restrictive so that you can't write lambda x,y: if x 100: x else: y and want to _extend_ lambda beyond its current capabilities and make it full featured but anonymous functions. And these requests are rebuked with the argument that having to give a more complex function a name instead of declaring it anonymously doesn't cost you much - especially since you can declare them inside other functions so the global namespace isn't cluttered. I have to admit that rereading my statement You are right, but for lambda in its current limited form short, named functions are a good replacement is not really what I wanted to say. I should have written: for lambda in its current limited form, listcomprehensions often are a good replacement. But as I've said various times before: I personally don't mind lambdas and for example the reduce function has been useful for me quite a few times, can't be replaced by listcomps, and frequently needs a callable consisting of only a single expression. So I'll continue to use lambdas there. -- Regards, Diez B. Roggisch -- http://mail.python.org/mailman/listinfo/python-list
Re: setattr inside a module
On Wed, 23 Mar 2005 11:35:34 +0100, kramb64 [EMAIL PROTECTED] wrote: I'm trying to use setattr inside a module. From outside a module it's easy: import spam name=hello value=1 setattr(spam, name, value) But if I want to do this inside the module spam itself, what I've to pass to setattr as first argument? Thanks a lot for your time. Marco. I found this: setattr(__import__(__name__), name, value) But too much underscores Nothing better? Marco. -- http://mail.python.org/mailman/listinfo/python-list
Python to C++ conversion substituting vectors for lists in a recursive function
I'm new to C++, coming from a Python background. I wrote the following code in C++ based on the Python code found here: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/302478 //beginning #include vector #include iostream.h using namespace std; void looper(vector vectorint nseq, vectorint comb); vector vectorint master; int main() { int n, C; vector vectorint seq; vectorint holder; cout Enter constant: ; cin C; cout Enter n: ; cin n; for(i=0; i=n; i++) { vector int tmp; for(int j=0; j=C; j++) { tmp.push_back(j); } seq.push_back(tmp); } looper(seq, holder); return 0; } void looper(vector vectorint nseq, vectorint comb) { if(nseq.size()0) { vectorint tseq = nseq.at(0); for(int i=0; itseq.size(); i++) { vector vectorint gseq = nseq; vectorint tcomb = comb; gseq.erase(0); tcomb.push_back(tseq[i]); looper(gseq, tcomb); } } else { master.push_back(comb); } } // end The program dies on the line: tcomb.push_back(tseq[i]); in the recursive function. Is my C++ translation accurate from the original Python? -- http://mail.python.org/mailman/listinfo/python-list
Re: scrollbar dependencies
Thanks a lot, Eric Brunel. Harlin, if it's still actual (don't think so, but whoever...) here is a simple code that works. --- from Tkinter import * ## Main window root = Tk() root.grid_rowconfigure(0, weight=1) root.grid_rowconfigure(1, weight=1) root.grid_columnconfigure(0, weight=1) ## First canvas c1 = Canvas(root, width=200, height=100, bd=2, relief=SUNKEN, scrollregion=(0, 0, 500, 500)) c1.grid(row=0, column=0, sticky='nswe') ## Second canvas c2 = Canvas(root, width=200, height=100, bd=2, relief=SUNKEN, scrollregion=(0, 0, 500, 500)) c2.grid(row=1, column=0, sticky='nswe') ## Special function scroll both canvases horizontally def xscrollboth(self,*args): c1.xview(self,*args) c2.xview(self,*args) ## Horizontal scrollbar for both canvases hScroll = Scrollbar(root, orient=HORIZONTAL, command=xscrollboth) hScroll.grid(row=2, column=0, sticky='we') ## Vertical scrollbars vScroll1 = Scrollbar(orient=VERTICAL, command=c1.yview) vScroll1.grid(row=0, column=1, sticky='ns') c1.config(yscrollcommand=vScroll1.set,xscrollcommand=hScroll.set) vScroll2 = Scrollbar(orient=VERTICAL, command=c2.yview) vScroll2.grid(row=1, column=1, sticky='ns') c2.config(yscrollcommand=vScroll2.set,xscrollcommand=hScroll.set) root.mainloop() --- Eric Brunel [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED]... On 3 Mar 2005 02:38:59 -0800, Harlin Seritt [EMAIL PROTECTED] wrote: Pardon a question I should already know the answer to, but what are the *args in the: def xscrollboth(*args): c1.xview(*args) c2.xview(*args) Thanks, Harlin If your question is about the syntax, it's just the way of passing any number of arguments to a function as explained in: http://docs.python.org/tut/node6.html#SECTION00673 If your question is about what will actually be passed in these arguments, the answer is simply: I don't know, and I don't care. That's why I used a *args: I just want to pass to the c1.xview and c2.xview methods exactly what was passed to my xscrollboth function. Since Python allows me to just pass the list of arguments unchanged, I happily do it. -- http://mail.python.org/mailman/listinfo/python-list
Re: Python to c++ conversion problem
Akdes Serin [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] I have a code in python like if eval('player.moveRoom(SeLinuxMud.Direction.' + x + ')'): # moveRoom function takes Direction enum as a parameter When I am trying to write this code in c++ if (player-moveRoom(s[1])) //s[1] is a string so it outputs an error because of not taking enum as a parameter How can I change string to enum in c++? Obviously C++ has no eval equivalent, but it also has limited introspection at run-time. That is, the executing code has no way to know the compile-time name associated with the enum values. One way to do this mapping manually would be: #include map #include string enum ERoom { roomEntrance = 0 , roomLobby = 1 , roomCave = 2 }; typedef std::mapstd::string,ERoom RoomLookup; typedef RoomLookup::value_type RoomLookupEntry; RoomLookupEntry roomLookupData[3] = { RoomLookupEntry(Entrance, roomEntrance ) , RoomLookupEntry(Lobby,roomLobby ) , RoomLookupEntry(Entrance, roomCave ) }; RoomLookup sRoomLookup(roomLookupData,roomLookupData+3); Then in your code: if (player-moveRoom(sRoomLookup[ s[1] ])) An annoyance with this approach is that your are writing everything twice. There are tricks to avoid that, using the preprocessor, but it has its own drawbacks (see the thread associated with http://groups.google.ca/groups?selm=QJGdnT8LXIMFEGLcRVn-1A%40comcast.com ) But for a game, most typically, the code would load room descriptions from a data file at run-time, and dynamically generate the equivalent of sRoomLookup. I hope this helps, Ivan -- http://ivan.vecerina.com/contact/?subject=NG_POST - email contact form Brainbench MVP for C++ http://www.brainbench.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Python to C++ conversion substituting vectors for lists in a recursive function
I didn't look at the original code but i you should know that passing vectors directly (i.e by value) to functions is not a good idea (results in big copy), its better to use `const vector ` or `vector ` (i.e. by reference). In general you should try to reduce the number of vector coping to a minimum. As for the error in the code, it would be better to see the example of the error, be it compiler or other wise. I have a question about this line `vectorint tseq = nseq.at(0);` as i have never seen the at() member of vector. And its not referenced on the sgi site http://www.sgi.com/tech/stl/Vector.html what version of the STL are you using? -- http://mail.python.org/mailman/listinfo/python-list
Re: Anonymus functions revisited
Duncan Booth wrote: Do I really need to mention that the whole concept here is broken. This only works if you call it from global scope. If you call it from inside a function it [usually] won't work: def makeVars(**nameVals): sys._getframe(1).f_locals.update(nameVals) def test(): try: b except NameError: print Before makeVars: NameError else: print Before makeVars: Not NameError makeVars(b=2) try: b except NameError: print After makeVars: NameError else: print After makeVars: Not NameError import sys test() Before makeVars: NameError After makeVars: NameError Yes. To put it short: def makeVars(**nameVals): print prev,sys._getframe(1).f_locals[z] sys._getframe(1).f_locals.update(nameVals) print post,sys._getframe(1).f_locals[z] def test(): z = 0 makeVars(z=2) z = 0 makeVars(z=3) prev 0 post 3 test() prev 0 post 0 The Python runtime uses the opcodes STORE_FAST and LOAD_FAST to store/access local variables of a function. Take a closer look at the code: case STORE_FAST: v = POP(); SETLOCAL(oparg, v); goto fast_next_opcode; with register PyObject **fastlocals and macros #define GETLOCAL(i) (fastlocals[i]) #define SETLOCAL(i, value) do { PyObject *tmp = GETLOCAL(i); \ GETLOCAL(i) = value; \ Py_XDECREF(tmp); } while (0) The local variables will be stored in the pointer array fastlocals not within a Python dict. If a variable is created as a global it will be stored using the STORE_NAME opcode instead: case STORE_NAME: w = GETITEM(names, oparg); v = POP(); if ((x = f-f_locals) != NULL) { if (PyDict_CheckExact(x)) err = PyDict_SetItem(x, w, v); else err = PyObject_SetItem(x, w, v); Py_DECREF(v); if (err == 0) continue; break; } which clearly accesses a Python dict for storage. Regards Kay -- http://mail.python.org/mailman/listinfo/python-list
Re: How to use subprocess
Nicolas Fleury [EMAIL PROTECTED] writes: Hi, I want to use the subprocess module (or any standard Python module) to run a process: - which stdout and stderr can each be redirected to any file-like object (no fileno function). - can be cancelled with a threading.Event. My problem is that the subprocess.Popen constructor doesn't seem to support file-like objects (only file objects with fileno()). If I use subprocess.PIPE, I have the problem that the read functions of of the subprocess objects stdout and stderr are blocking (and I want to redirect them to different file-like objects, so I definitely need non-blocking access). How am I supposed to do it? You might take a look at my asyncproc module, available at http://www.lysator.liu.se/~bellman/download/asyncproc.py Specifically the Process class. It doesn't do exactly what you want, but maybe you can use it as inspiration for doing it yourself. It requires the subprocess module, but I have successfully used it under Python 2.3.2 with subprocess installed locally. -- Thomas Bellman, Lysator Computer Club, Linköping University, Sweden Adde parvum parvo magnus acervus erit ! bellman @ lysator.liu.se (From The Mythical Man-Month) ! Make Love -- Nicht Wahr! -- http://mail.python.org/mailman/listinfo/python-list
Re: setattr inside a module
kramb64 wrote: I'm trying to use setattr inside a module. From outside a module it's easy: import spam name=hello value=1 setattr(spam, name, value) But if I want to do this inside the module spam itself, what I've to pass to setattr as first argument? Thanks a lot for your time. Marco. ??? Why don't You create 'name' and 'value' as module scoped variables just by defining them? If You want to introspect the module within the module, just define # defined within spam def introspect(): import spam print dir(spam) introspect() Regards Kay -- http://mail.python.org/mailman/listinfo/python-list
Re: Python limericks (was Re: Text-to-speech)
[Michael] from itertools import repeat for feet in [3,3,2,2,3]: print .join(DA-DA-DUM for dummy in [None] for foot in repeat(metric, feet)) Spectacular! +1 QOTW -- Richie Hindle [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Anonymus functions revisited
Op 2005-03-23, Diez B. Roggisch schreef [EMAIL PROTECTED]: Can someone who thinks this way, please explain why this is acceptable [ x * x for x in some_iterator ] But this is not map(lambda x: x * x, some_iteraror) and should be replaced with def sqr(x): return x * x map(sqr , some_iterator) It shouldn't, it should be replaced with the listcomp. And IMHO it results in better readable code. This misses the point. The fact that map and the listcomprehension do the same stuff is just a detail. It is about giving a function an expression as argument that is to be evaluated multiple times. AFAIK the reason people say you should use named functions is _not_ because of these single expression replacements. The reason is that frequently people complain about lambda being so restrictive so that you can't write lambda x,y: if x 100: x else: y and want to _extend_ lambda beyond its current capabilities and make it full featured but anonymous functions. This is one kind of people. An other kind of people seems to want to get rid of lamda's altogether and asks whether it is so difficult to make a named function each time you would otherwise use a lambda. But as I've said various times before: I personally don't mind lambdas and for example the reduce function has been useful for me quite a few times, can't be replaced by listcomps, and frequently needs a callable consisting of only a single expression. So I'll continue to use lambdas there. Then my question was not meant for you. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: Submission for Python Limmerick Contest
[EMAIL PROTECTED] wrote: My submission for P.L.C. A mathematican named van Rossum went hunting for opossum he could not find one all eaten by Python to her his language he named as a blossum wish me luck Harald At the prompt, when I type import this, it Invites me to be more excplicit: But in five lines of verse One's obliged to be terse, So the limerick form is illicit! :) -- Website: www DOT jarmania FULLSTOP com -- http://mail.python.org/mailman/listinfo/python-list
Re: setattr inside a module
I found this: setattr(__import__(__name__), name, value) But too much underscores Nothing better? Marco. setattr(sys.modules[__name__], name, value) -- Regards, Diez B. Roggisch -- http://mail.python.org/mailman/listinfo/python-list
Re: cross platform use of set locale
Timothy Smith wrote: Serge Orlov wrote: Timothy Smith wrote: thats ok, but how do i get it to group thousands with a , ? and thats would mean i'd have to run everything through a formatter before i displayed it :/ it'd be nicer if i could just select a proper locale I think you're misusing locale. There is no guarantee that any specific locale will have properties (like grouping) set to a known value. Are you trying to format money? Then you need a special class so that you can say: d = Dollars(100.01) print You have %s in your account % d and get You have $1,000,000.01 in your account. Serge. thats exactly what i'm trying to do, only having to do that for all my outputs is more work then i'd like :/ SUS has added numeric grouping For some numeric conversions a radix character (`decimal point') or thousands' grouping character is used. The actual character used depends on the LC_NUMERIC part of the locale. The POSIX locale uses `.' as radix character, and does not have a grouping character. Thus, printf(%'.2f, 1234567.89); results in `1234567.89' in the POSIX locale, in `1234567,89' in the nl_NL locale, and in `1.234.567,89' in the da_DK locale. but they hasn't added monetary grouping. I don't think you'll get monetary grouping anytime soon. Besides as far as I understood your question, you *always* want grouping, right? Actually I don't think a cryptic flag is better than an explicit formatter. What do you think is more clear for a maintainer of your code? print %'.2f % amount or print %s % dollars(amount) why is this a misuse of locale? it's exactly what locale is meant for isn't it? I just reacted to your words select a proper locale and how do i get it to group thousands with a ,. It's just not a good idea to select a locale and expect the grouping character to be , or expect grouping, see nl_NL locale example above. Serge. -- http://mail.python.org/mailman/listinfo/python-list
How to pickling VT_DATE values?
Hi all this is my first go at pickling and I'm having trouble with variables of type VT_DATE returned from a COM application. I don't seem to be successfully pickling/depickling to the the same value. I think this may be due to a strange return value. The VT_DATE seems to be a floating point number 'days.(hours, seconds) since midnight 30 December 1899'. in some cases I get a value (probably 0.0?) which is printed as '12/30/0/ 00:00:00' and I wonder if this strange value is causing the depickling to fail. Haven't yet followed this to ground... Anyway, I'm sure someone out there has successfully pickled such values and wondered how it was done. FWIW my current code is: import pywintypes import pythoncom import copy_reg def picklePyTime(o): return unpicklePyTime, (float(o),) def unpicklePyTime(po): return pywintypes.Time(po) copy_reg.pickle(pythoncom.PyTimeType, picklePyTime) Thanks jon N -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting the word to conventional programmers
Hey, Jeff Hobbs got the last word. ;-) -- http://mail.python.org/mailman/listinfo/python-list
Re: typo in the library reference?
nicke wrote: Peter Hansen [EMAIL PROTECTED] wrote: Scott David Daniels wrote: nicke wrote: If it really is like this it is uncoherent and quite stupid :P Name-calling won't make anyone more likely to help you out. This is a _collective_ effort. You spotted a problem; submit at least a bug report if not a fix. To be fair, Scott, I think he was saying in effect if the docs are really accurate about this, then the design is f**ked, which would be a fair and reasonable statement. I don't think he's saying that the docs are incoherent and stupid as written... just wrong. -Peter Thanks for sticking up for me, and yes, this was what i meant. I could have formulated myself a bit annorlund though, have to blame the late hours :P I'm going to submit a bug report, just don't have much experience with that... but hey, sometime must be the first! ;) nicke My apologies belong in this thread. Sorry, nicke, I react to the f**ked without considering that you might have only meant ... could not really have been designed this way. I seldom use such language, and only now noticed the smiley after it. What is the typogram for I feel like an idiot? In any case I should have been a bit more gentle in suggesting that this is the way we help ourselves forward -- by fixing when the first instinct is to curse. Certainly calling anything name-calling was a pretty lousy invitation to play along. --Scott David Daniels [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Read from the last line of a file?
Mike Rovner wrote: Anthony Liu wrote: I am wondering if it is possible to start reading from the last line of file, and then the last but one up to the first line. If you can afford to keep the whole file in memory, than: lines = open(..).readlines() print lines[::-1] Or use the new reversed generator to avoid a copy. for line in reversed(readlines()): --Scott David Daniels [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: I'm just an idiot when it comes logging
Vinay Sajip wrote: olsongt at verizon.net writes: Handlers normally process all events passed to them, but you can set a level on a handler to get it to drop events below a certain threshold. Since you haven't done this, you will see an INFO message appear even though the root logger's level is set to ERROR. (This would only affect logging calls to the root logger). Rule of thumb: Set levels on handlers only when you need them, not as common practice. If you don't want to see info messages from otherLogger, set its level to INFO. Vinay Sajip Thanks Vinay, By adding a handler with a level of ERROR I fixed my problem. Things are starting to make sense. I just feel like a logger should filter out any messages below its error level instead of sending them to its handlers. But that is obviously not the case. I just need to get used to it. -Grant -- http://mail.python.org/mailman/listinfo/python-list
Re: Anonymus functions revisited
On 23 Mar 2005 10:13:16 GMT, Duncan Booth [EMAIL PROTECTED] wrote: Do I really need to mention that the whole concept here is broken. This only works if you call it from global scope. If you call it from inside a function it [usually] won't work: That's only becuase it was asked to go up 1 frame, and not 2. def makeVars(**nameVals): sys._getframe(2).f_locals.update(nameVals) # - get 2 frames up. def test(): try: b except NameError: print Before makeVars: NameError else: print Before makeVars: Not NameError makeVars(b=2) try: b except NameError: print After makeVars: NameError else: print After makeVars: Not NameError import sys test() Before makeVars: NameError After makeVars: Not NameError -- http://mail.python.org/mailman/listinfo/python-list
Re: cross platform use of set locale
Timothy Smith wrote: Serge Orlov wrote: ... d = Dollars(100.01) print You have %s in your account % d and get You have $1,000,000.01 in your account. thats exactly what i'm trying to do, only having to do that for all my outputs is more work then i'd like :/ why is this a misuse of locale? it's exactly what locale is meant for isn't it? locale is so that you can write code that runs several different places and obeys local conventions on output at each of those places. Not so much for formatting how you like (which would be easier to write and control yourself). Just write a function commad and use it. --Scott David Daniels [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: MinGW building with Python 2.4
Since the only official way to do this is pymingw, you should at least give feedback of the steps you followed, and what didn't work (1) I have Cygwin 5.1 with GCC 3.3.1 on it. (2) I unzipped Python 2.4. (3) I unzipped pyMinGW-24-0064.zip into that directory, overwriting the appropriate files. (4) I went into the [Python]/MinGW directory and ran 'make -f python24.mak all'. (5) Here are the results: make -f pythoncore.mak make[1]: Entering directory `/home/Administrator/sgross/Python-2.4/MinGW' gcc.exe -c ../Modules/_bisectmodule.c -o ../Modules/_bisectmodule.o -I../Include -I../PC -I../Python -Wall -s -DNDEBUG -DPy_BUILD_CORE -DPy_ENABLE_SHARED -O2 In file included from ../Include/Python.h:82, from ../Modules/_bisectmodule.c:6: ../Include/intobject.h:41: error: parse error before PyInt_AsUnsignedLongLongMask ../Include/intobject.h:41: warning: type defaults to `int' in declaration of `PyInt_AsUnsignedLongLongMask' ../Include/intobject.h:41: warning: data definition has no type or storage class In file included from ../Include/Python.h:84, from ../Modules/_bisectmodule.c:6: ../Include/longobject.h:37: warning: parameter names (without types) in function declaration ../Include/longobject.h:39: error: parse error before PyLong_AsLongLong ../Include/longobject.h:39: warning: type defaults to `int' in declaration of `PyLong_AsLongLong' ../Include/longobject.h:39: warning: data definition has no type or storage class ../Include/longobject.h:40: error: parse error before PyLong_AsUnsignedLongLong ../Include/longobject.h:40: warning: type defaults to `int' in declaration of `PyLong_AsUnsignedLongLong' ../Include/longobject.h:40: warning: data definition has no type or storage class ../Include/longobject.h:41: error: parse error before PyLong_AsUnsignedLongLongMask ../Include/longobject.h:41: warning: type defaults to `int' in declaration of `PyLong_AsUnsignedLongLongMask' ../Include/longobject.h:41: warning: data definition has no type or storage class make[1]: *** [../Modules/_bisectmodule.o] Error 1 make[1]: Leaving directory `/home/Administrator/sgross/Python-2.4/MinGW' make: *** [pythoncore] Error 2 Any ideas? Thanks in advance, --Steve -- http://mail.python.org/mailman/listinfo/python-list
inter threading info
Hi All, Q: Is it possible for a thread on SocketServer.ThreadingTCPServer to get the socket info of *other* open thread/s and use that info to send data to the accepting client? I wrote a socketserver using SocketServer.ThreadingTCPServer. A client is connected to the server and expects multiple request/responses. (Not sure about the terminology but the client connects and then stay connected for a while.) I need to create a client that can connect to server and then determine how many other clients are connected, what the socket info is (ifile/ofile) and then send and receive specific data to those clients. TIA T -- http://mail.python.org/mailman/listinfo/python-list
[Python-Announce] cfgparse v01_01 released
I'm pleased to announce the V01_01 release of cfgparse. Whats New - 1) Exception argument added to the Configuration parser initializer so that exceptions may be raised when user errors are encountered instead of the default call to sys.exit() that doesn't provide traceback. 2) Error messages were enhanced giving more detailed information. Background - cfgparse is a more convenient, flexible, and powerful module for parsing configuration files than the standard library ConfigParser module. cfgparse uses a more declarative style modelled after the popular optparse standard library module. cfgparse can optionally cooperate with the optparse module to provide coordination between command line and configuration file options. In addition, the cooperation can be used to allow the user to control features of the parser from the command line. URLs - Documentation: http://cfgparse.sourceforge.net/ Download: http://sourceforge.net/projects/cfgparse/ Feature Summary - + Simple ini style configuration syntax. + Type checking with error handling and help messages. + Help summary modelled after that in optparse. + Round trip - read, modify, write configuration files with comment retention. + Cooperates with optparse so options may be overridden from command line. + Supports heirarchically organized option settings. * User may store multiple option settings in a arbitrarily deep keyed dictionary. * Application uses a key list to walk into the dictionary to obtain a setting. * User controls key list with setting in configuration file. * Keys may be added to the list using command line or environment variables. + Supports allowing user control of configuration files used. * Environment variables may be used to specify a default configuration file. * Command line may be used to specify additional configuration files. * Configuration files may include other configuration files. + Configuration files may alternatively be written in Python. * Full power and flexibility of Python available for creation of option settings. * Allows options settings to be real Python objects. * This feature is NOT enabled by default. + May be extended to support syntax such as XML. Enjoy, Dan Gass -- http://mail.python.org/mailman/listinfo/python-list
Re: Anonymus functions revisited
On 23 Mar 2005 10:13:16 GMT, Duncan Booth [EMAIL PROTECTED] wrote: Do I really need to mention that the whole concept here is broken. This only works if you call it from global scope. If you call it from inside a function it [usually] won't work: Ok... you can get globals this way if you know how many frames up it is. Not terrable useful. :/ def frame0(): print 'frame0 (locals): ',sys._getframe(0).f_locals print '\nframe1 (parent): ',sys._getframe(1).f_locals print '\n(Global) : ',sys._getframe(2).f_locals def frame1(): frame0() import sys frame1() frame0 (locals): {} frame1 (parent): {} (Global) : {'__builtins__': module '__builtin__' (built-in), 'sys': module 'sys' (built-in), '__name__': '__main__', 'frame1': function frame1 at 0x00B437B0, 'frame0': function frame0 at 0x00B43770, '__doc__': None} -- http://mail.python.org/mailman/listinfo/python-list
Re: Anonymus functions revisited
Ron wrote: On 23 Mar 2005 10:13:16 GMT, Duncan Booth [EMAIL PROTECTED] wrote: Do I really need to mention that the whole concept here is broken. This only works if you call it from global scope. If you call it from inside a function it [usually] won't work: That's only becuase it was asked to go up 1 frame, and not 2. def makeVars(**nameVals): sys._getframe(2).f_locals.update(nameVals) # - get 2 frames up. def test(): try: b except NameError: print Before makeVars: NameError else: print Before makeVars: Not NameError makeVars(b=2) try: b except NameError: print After makeVars: NameError else: print After makeVars: Not NameError import sys test() Before makeVars: NameError After makeVars: Not NameError That's true only because the globals are updated by {b:2} two levels down. If You nest the test() function You reproduce the error again: def test(): def inner(): try: b except NameError: print Before makeVars: NameError else: print Before makeVars: Not NameError makeVars(b=2) try: b except NameError: print After makeVars: NameError else: print After makeVars: Not NameError inner() Before makeVars: NameError After makeVars: NameError A working makeVars seems not to be different from def makeVars(**nameVals): globals().update(nameVals) Regards Kay -- http://mail.python.org/mailman/listinfo/python-list
Re: cross platform use of set locale
SUS has added numeric grouping For some numeric conversions a radix character (`decimal point') or thousands' grouping character is used. The actual character used depends on the LC_NUMERIC part of the locale. The POSIX locale uses `.' as radix character, and does not have a grouping character. Thus, printf(%'.2f, 1234567.89); results in `1234567.89' in the POSIX locale, in `1234567,89' in the nl_NL locale, and in `1.234.567,89' in the da_DK locale. Hmm, this C code on my system (mk_MK locale) #include locale.h #include stdio.h int main (void) { setlocale(LC_ALL,); printf(%'.2f\n, 1234567.89); return 0; } Outputs: 1 234 567,89 as expected. But this Python program (2.3.4 [GCC 3.3.3] on linux2) import locale locale.setlocale(locale.LC_ALL, ) print locale.format(%'.2f, 1234567.89, grouping=True) complains about the ' in the format ValueError: unsupported format character ''' (0x27) at index 1 without the ' it outputs: 1234567,89 -- damjan -- http://mail.python.org/mailman/listinfo/python-list
Re: Anonymus functions revisited
Kay Schluehr wrote: A working makeVars seems not to be different from def makeVars(**nameVals): globals().update(nameVals) Not quite. If Ron can come up with a working makeVars it would update the caller's globals whereas what you just posted updates makeVar's globals so there is a difference (when the makeVars and the calling function are in different modules), just not a very useful one. -- http://mail.python.org/mailman/listinfo/python-list
Re: inter threading info
Tertius Cronje wrote: Q: Is it possible for a thread on SocketServer.ThreadingTCPServer to get the socket info of *other* open thread/s and use that info to send data to the accepting client? A specific socket can be used from every thread of a process. Just make sure that you synchronize everything. I need to create a client that can connect to server and then determine how many other clients are connected, what the socket info is When you accept a socket client, a new socket is created, so you cannot determine how many clients are connected to a socket. You have to create a data structure where you insert info about accepted connections and delete the info when a connection is closed. (ifile/ofile) and then send and receive specific data to those clients. ifile/ofile are local to the server process so you cannot use them to send data from one client to another client. You have to send the data to the server first with a special tag, the server has to use that tag and send the data to the designated other client. It sounds a bit as if you want to build some kind of chat server and now you want to add private channels. Daniel -- http://mail.python.org/mailman/listinfo/python-list
Re: Lowest hassle Python web server?
kanzen wrote: I keep telling my friends that Python rocks. Now it's time to put my money where my mouth is. I'm about to start writing a server for a phone based game. It needs to handle simlpe requests from some Java code running on the phone at a fairly low transaction rate. There will also be a simple web site allowing users to edit preferences and so forth. I have just enough Python experience to decide that I prefer it over Java for this job. It'll be on a Linux box that I have full control over. I can see from FAQs that there are several possible ways of doing web server work in Python, e.g. Twisted or mod_python in Apache, etc. So I'm wondering: - Could you recommend a solution you've found to be the most convenient? - Does threading cause any more of a hassle in Python than Java? - Is there anything similar to JSP in Java? Thanks, KanZen You might want to take a look a Medusa. It is the basis for the web server that is bundled in Zope. http://www.nightmare.com/medusa/ Larry Bates -- http://mail.python.org/mailman/listinfo/python-list
Re: Python to C++ conversion substituting vectors for lists in a recursive function
lugal wrote: Your code has an undeclared int i in main(). gseq.erase(0); I think erase() takes a pointer, not the element index: gseq.erase(qseq.begin()); in the recursive function. Is my C++ translation accurate from the original Python? Coming from a Python background, you should have learned that the proper way to answer that question is to write a test suite. Generally speaking, if you want to learn a new language it is probably better to extend examples written in that language than to translate code written in another language you are already familiar with. What is idiomatic in one language may be clumsy and inefficient in another. Peter PS: Your post is off-topic in c.l.py, consider asking for further/better advice in a C++ newsgroup. -- http://mail.python.org/mailman/listinfo/python-list
Re: getting data with proper encoding to the finish
On Wed Mar 16 22:21:42 CET 2005 John Machin wrote: Apparently pyXLWriter doesn't handle Unicode at all. Although Unicode came in with Excel 1997 (BIFF8 format file), pyXLWriter appears to support only Excel 5(?) (BIFF5 format file). As Serge suggested, appeal to the porter to appeal to the author of the Perl module it's ported from; but don't hold your breath in the meantime. I don't think it's necessary to go that far back up the chain. The Perl module from which pyXLWriter is ported supports Unicode strings (and writes BIFF8 files), at least for the current version. About a week ago I wrote to Evgeny Filatov, who did the port (I'm having a difficult time mentally reconciling the name Evgeny with ASCII guy :-) ), but haven't heard anything from him. Does anyone have a better address than the one I found in the README ([EMAIL PROTECTED])? Has anyone done any work to pick up where he left off? -- Bob Kline http://www.rksystems.com mailto:[EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting the word to conventional programmers
Advocates of languages and programming methodologies sometimes compare the current version of their favorite language to an old version of their disfavored language, resulting in skewed comparisons. For example, Conway writes Interpreted languages do two things much better than compiled languages. Firstly, they provide more sophisticated programming tools and support for more advanced programming techniques. For example, Perl provides hashed look-up tables and arbitrary-length arrays as core data types. C doesn't even have a proper string type. Likewise, Perl's data sorting facilities are integrated into the language, so the sorting criteria are directly programmable. Having all the basic tools of programming (i.e. high-level data types and common algorithms) built into the language, rather than having to build them yourself, means that you need to write less code to solve a given problem. I think most of the advanced programming techniques he mentions are part of the C++ Standard Library. -- http://mail.python.org/mailman/listinfo/python-list
os.stat access and modify time same on WinXP
I'm using the standard NTFS file system. The only time the access time is updated is when the file is modified or saved (with no changes). What's up with that? Shouldn't a read/view update the access time? -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: Snakelets 1.38 (simple-to-use web app server with dynamic pages)
Irmen de Jong wrote: I'm happy to say that Snakelets 1.38 is available. Fine thing again! Maybe someone is interested in this: I just tried tlslite and did a dirty hack so you could use snakelets via SSL. See the patch below. Snip and save it, use it against snakeserver/server.py. You've to place a key-pair in your server-dir (localhost.crt/localhost.private.key in the path). You can generate a self-signed certificate easily with openssl. HtH, Roland - SNIP AND SAVE BELOW - 961d 927a def handshake(self, tlsConnection): try: tlsConnection.handshakeServer(certChain=certChain, privateKey=privateKey, sessionCache=sessionCache) tlsConnection.ignoreAbruptClose = True return True except (SyntaxError, TLSError), error: print Handshake failure:, str(error) return False . 908c if IS_SSL: tlsConnection = TLSConnection(request) if self.handshake(tlsConnection) == True: self.RequestHandlerClass(tlsConnection, client_address, self) tlsConnection.close() else: self.RequestHandlerClass(request, client_address, self) . 889c if IS_SSL: tlsConnection = TLSConnection(request) if self.handshake(tlsConnection) == True: self.RequestHandlerClass(tlsConnection, client_address, self) tlsConnection.close() else: self.RequestHandlerClass(request, client_address, self) . 21a IS_SSL=True try: from tlslite.api import * except ImportError: IS_SSL=False if IS_SSL: s = open(./localhost.crt).read() x509 = X509() x509.parse(s) certChain = X509CertChain([x509]) s = open(./localhost.private.key).read() privateKey = parsePEMKey(s, private=True) sessionCache = SessionCache() . -- http://mail.python.org/mailman/listinfo/python-list
Snakelets via SSL
Hi, after Irmen de Jong did another fine release with Snakelets-1.38 i just did a dirty hack for using snakelets with SSL-support. SSL-support is added through the use of tlslite from Trevor Perrin. You'll have to download and install it from http://trevp.net/tlslite/. Furthermore you need a key-pair in your serverdir, easily generetad with openssl. Just snip the patch below and use it against snakeserver/server.py (with standard *nix patch). HtH, Roland SNIP BELOW, SAVE AS ssl.patch 961d 927a def handshake(self, tlsConnection): try: tlsConnection.handshakeServer(certChain=certChain, privateKey=privateKey, sessionCache=sessionCache) tlsConnection.ignoreAbruptClose = True return True except (SyntaxError, TLSError), error: print Handshake failure:, str(error) return False . 908c if IS_SSL: tlsConnection = TLSConnection(request) if self.handshake(tlsConnection) == True: self.RequestHandlerClass(tlsConnection, client_address, self) tlsConnection.close() else: self.RequestHandlerClass(request, client_address, self) . 889c if IS_SSL: tlsConnection = TLSConnection(request) if self.handshake(tlsConnection) == True: self.RequestHandlerClass(tlsConnection, client_address, self) tlsConnection.close() else: self.RequestHandlerClass(request, client_address, self) . 21a IS_SSL=True try: from tlslite.api import * except ImportError: IS_SSL=False if IS_SSL: s = open(./localhost.crt).read() x509 = X509() x509.parse(s) certChain = X509CertChain([x509]) s = open(./localhost.private.key).read() privateKey = parsePEMKey(s, private=True) sessionCache = SessionCache() . -- http://mail.python.org/mailman/listinfo/python-list
Re: PyGTK Button Size Question
Am Wed, 23 Mar 2005 03:02:44 -0800 schrieb Harlin Seritt: How does one set the width of a gtk.Button explicitly? and height for that matter as well... I think it is gtk.Widget.set_size_request: http://www.pygtk.org/pygtk2reference/class-gtkwidget.html#method-gtkwidget--set-size-request HTH, Thomas -- Thomas Güttler, http://www.thomas-guettler.de/ -- http://mail.python.org/mailman/listinfo/python-list
Re: wanted: visual report templating system
Am Tue, 22 Mar 2005 20:58:12 + schrieb robin: I am looking for a client/server reporting tool to use with a web application built in Python. It would consist of three parts: 1. a data definition retrieval engine that interfaces to RDBMS or other data files 2. a visual designer in which a nontechnical person can create a report layout template (supporting charts, text, graphics, etc.) 3. a server engine to merge the two and create on-the-fly reports when requested programmatically. Hi, You can script openoffice with pyUNO. Thomas -- Thomas Güttler, http://www.thomas-guettler.de/ -- http://mail.python.org/mailman/listinfo/python-list
Re: simultaneous copy to multiple media
On Mon, 21 Mar 2005 00:17:05 +0100, rumours say that Heiko Wundram [EMAIL PROTECTED] might have written: Well, 430 MB/s is only for USB 2.0. It's 480 Mb/s (megabit or mebibit, I am not sure... :), so it maxes at about 60 MB/s (or MiB/s) for all devices on the same controller. -- TZOTZIOY, I speak England very best. Be strict when sending and tolerant when receiving. (from RFC1958) I really should keep that in mind when talking with people, actually... -- http://mail.python.org/mailman/listinfo/python-list
Re: xmlrpc with Python and large datases
Steve, Thanks for your reply, I'll look into things based on your comments. Also, I've read your book Python Web Programming and wanted you to know it has helped me a lot with various python projects, thanks! Doug -- http://mail.python.org/mailman/listinfo/python-list
Windows, Python and low level networking
Is it possible to have low level netwoking with python under Windows? Like raw sockets? Is it possible to send a single packet using python under windows? Thank you -- http://mail.python.org/mailman/listinfo/python-list
Re: Python to c++ conversion problem
Akdes Serin wrote: I have a code in python like if eval('player.moveRoom(SeLinuxMud.Direction.' + x + ')'): # moveRoom function takes Direction enum as a parameter When I am trying to write this code in c++ if (player-moveRoom(s[1])) //s[1] is a string so it outputs an error because of not taking enum as a parameter How can I change string to enum in c++? The most obvious way would be to use an std::map of strings and the enum that's equivalent to each. -- Later, Jerry. The universe is a figment of its own imagination. -- http://mail.python.org/mailman/listinfo/python-list
Pattern matching from a text document
I'm currently trying to develop a demonstrator in python for an ontology of a football team. At present all the fit players are exported to a text document. The program reads the document in and splits each line into a string (since each fit player and their attributes is entered line by line in the text document) using list = target.splitlines() The program then performs a loop like so: while foo 0: if len(list) == 0: break else: pat = ([a-z]+)(\s+)([a-z]+)(\s+)([a-z]+)(\s+)(\d{1})(\d{1})(\d{1})(\d{1})(\d{1})([a-z]+) ph = re.compile(pat,re.IGNORECASE) match = ph.match(list[1]) forename = match.group(1) surname = match.group(3) attacking = match.group(7) defending = match.group(8) fitness = match.group(9) print forename print len(list) del list[0] The two main problems I'm having are that the first and entry in the list is not printing. Once I have overcome this problem I then need each player and there related variables to be stored seperately. This is not happening at present because each time the loop runs it overwrites the value in each variable. Any help would be greatly appreciated. Ben. -- http://mail.python.org/mailman/listinfo/python-list
Re: Windows, Python and low level networking
Maybe this will help. From the interpreter - import socket help(socket) Which gives you all sorts of neat information on the socket module. jw On 23 Mar 2005 08:08:04 -0800, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Is it possible to have low level netwoking with python under Windows? Like raw sockets? Is it possible to send a single packet using python under windows? Thank you -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: os.stat access and modify time same on WinXP
rbt wrote: I'm using the standard NTFS file system. The only time the access time is updated is when the file is modified or saved (with no changes). What's up with that? Shouldn't a read/view update the access time? See http://www.microsoft.com/resources/documentation/Windows/XP/all/reskit/en-us/Default.asp?url=/resources/documentation/Windows/XP/all/reskit/en-us/prkc_fil_punq.asp Quoting: ''' The Last Access Time on disk is not always current because NTFS looks for a one-hour interval before forcing the Last Access Time updates to disk. NTFS also delays writing the Last Access Time to disk when users or programs perform read-only operations on a file or folder, such as listing the folder's contents or reading (but not changing) a file in the folder. If the Last Access Time is kept current on disk for read operations, all read operations become write operations, which impacts NTFS performance. Note * File-based queries of Last Access Time are accurate even if all on-disk values are not current. NTFS returns the correct value on queries because the accurate value is stored in memory. ''' Does that help? (Just went through this myself the other day.) -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Windows, Python and low level networking
[EMAIL PROTECTED] wrote: Is it possible to have low level netwoking with python under Windows? Like raw sockets? Is it possible to send a single packet using python under windows? Google is your friend: Try searching with python sockets, for example... (You *have* heard of Google, haven't you? It's been in the news a bit lately...) -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: typo in the library reference?
nicke [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] I'm going to submit a bug report, just don't have much experience with that... but hey, sometime must be the first! ;) If you can, you might also look at the ossaudio source to verify that the mixup is strictly in the doc and not the code. TJR -- http://mail.python.org/mailman/listinfo/python-list
Re: Windows, Python and low level networking
[EMAIL PROTECTED] wrote: Is it possible to have low level netwoking with python under Windows? Like raw sockets? Is it possible to send a single packet using python under windows? Thank you Yes http://www.python.org/doc/2.4/lib/module-socket.html -- http://mail.python.org/mailman/listinfo/python-list
Re: problems with  character
Thanks for all the replies. I just got in to work so I haven't tried any of them yet. I see that I wasn't as clear as I should have been so I'll clarify a little. I'm grabbing some data from msn's rss feed. Here's an example. http://search.msn.com/results.aspx?q=domain+nameformat=rssFORM=ZZRE The string ' all domain name extensions » Good' is where I have a problem. The '»' shows up as '  »' when I write it to a file or stick it in mysql. I did a hex dump and this is what I see. [EMAIL PROTECTED]:~/scripts cat test.txt extensions » Good [EMAIL PROTECTED]:~/scripts xxd test.txt 000: 6578 7465 6e73 696f 6e73 20c2 a020 c2a0 extensions .. .. 010: 20c2 bb20 476f 6f64 0a.. Good One thing that jumps out is that two of the Â's are c2a0, but one of them is c2bb. Well, those are the details since I wasn't clear before. -- http://mail.python.org/mailman/listinfo/python-list
Re: setattr inside a module
On Wed, 23 Mar 2005 11:35:34 +0100, kramb64 wrote: I'm trying to use setattr inside a module. From outside a module it's easy: import spam name=hello value=1 setattr(spam, name, value) But if I want to do this inside the module spam itself, what I've to pass to setattr as first argument? Thanks a lot for your time. Marco. As others point out, sys.modules[__name__] I find myself doing this more and more, not less, as I get further into Python; autogenerating many similar functions, pulling constants from an external source, stuff like that, usually very meta and every instinct says its the right thing to do. Maybe we should have a __module__ attribute that is a reference to the current module? sys.modules[__name__] is a little obtuse. -- http://mail.python.org/mailman/listinfo/python-list
Re: Anonymus functions revisited
On 23 Mar 2005 08:31:36 GMT Antoon Pardon [EMAIL PROTECTED] wrote: Can someone who thinks this way, please explain why this is acceptable [ x * x for x in some_iterator ] But this is not map(lambda x: x * x, some_iteraror) and should be replaced with def sqr(x): return x * x map(sqr , some_iterator) I guess I have similar feelings. I've only been using python for a year or two, so I'm still a relative newcomer. Like a lot of people, I found Python to be magically simple and intuitive. But I've never really found list comprehensions particularly clear. I don't know whether it's my backgroud (mainly C/C++), or my brain or what, but they are probably the only thing in Python that hasn't seemed transparent and obvious to me (apart from shadowing of variables in nested functions). Of course, I'm sure I could get used to them, given time. But that rather defeats one of the main reasons for using python in the first place - the lack of a steep learning curve. In contrast, I find lambdas, even with their significant restrictions, to be much more obvious. In fact, the proposal (sorry, don't have a link to hand) about extending lambda to allow things like `myfn = def indented block' was something that I initially assumed would become part of the language in time. Is there some definitive information that explains why python is moving away from lambdas and towards things like list comprehensions? - Julian -- http://www.op59.net/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Snakelets via SSL
Roland Heiber wrote: Hi, after Irmen de Jong did another fine release with Snakelets-1.38 i just did a dirty hack for using snakelets with SSL-support. SSL-support is added through the use of tlslite from Trevor Perrin. You'll have to download and install it from http://trevp.net/tlslite/. Furthermore you need a key-pair in your serverdir, easily generetad with openssl. Just snip the patch below and use it against snakeserver/server.py (with standard *nix patch). [...] Hey, thanks a lot! I must confess that I'm not knowledgeable in this field (HTTPS/SSL) so I really appreciate it that you did some work on this. However, may I ask you to re-submit the patch but this time in the patch tracker on SF; http://sourceforge.net/tracker/?group_id=41175 because news/mail clients often mangle source code. --Irmen -- http://mail.python.org/mailman/listinfo/python-list
IronPython 0.7 released!
http://www.gotdotnet.com/workspaces/workspace.aspx?id=ad7acff7-ab1e-4bcb-99c0-57ac5a3a9742 -- http://mail.python.org/mailman/listinfo/python-list
Re: Anonymus functions revisited
bruno modulix [EMAIL PROTECTED] wrote: in message news:[EMAIL PROTECTED] Ron wrote: The problem here is that Kay's proposition mixes two points: flexible tuple unpacking and a new syntax for anonymous functions. Yes, two different problems. I don't think anything needs to be done to tuples myself. I tend to use lists more anyway. They are two different beasts. Note that you don't have anything like list unpacking, now tuple unpacking is pretty common in Python (swap, multiple return values, formatted strings and outputs, ...). All the following are possible: (x,y,z) = (1,2,3) (x,y,z) = [1,2,3] [x,y,z] = (1,2,3) [x,y,z] = [1,2,3] What exactly do you mean by don't have anything like list unpacking ? George -- http://mail.python.org/mailman/listinfo/python-list
xml marshal of general (but non Python standard) class
Hello all, In my project, I have container classes holding lists of item classes. For example, a container class myLibrary might hold a list of item classes myNation and associated variables like myNation.name='USA' and myNation.continent='North America'. Bottom line, I was hoping to use this structure to marshal the classes to xml. However, I've got dozens of unique classes (all subclassing the container and item classes) with unique variables attached, and I do not want to write rules for each. I was looking at the source for generic in xml.marshal (from xml.marshal import generic) which will dump to xml any configuration of standard Python data types, for example, a tuple of dictionaries containing lists of strings. This source just writes a rule for each data type. Naively, I would hope that there'd be something where the marshaller could just look at my data class, see what variables were associated, and just go from there. I'm moderately experienced with Python, but by no means an expert, and I'm not an xml pro, either. Would this project (xml marshal of a new class) be worth my time? If so, what would be best way to proceed? Any other thoughts? import xml.marshal from xml.marshal import generic generic.dumps(['thank you','comp.lang.python']) '?xml version=1.0?marshallist id=i2stringthank you/stringstringcomp.lang.python/string/list/marshal -- http://mail.python.org/mailman/listinfo/python-list
Re: os.stat access and modify time same on WinXP
Peter Hansen wrote: rbt wrote: I'm using the standard NTFS file system. The only time the access time is updated is when the file is modified or saved (with no changes). What's up with that? Shouldn't a read/view update the access time? See http://www.microsoft.com/resources/documentation/Windows/XP/all/reskit/en-us/Default.asp?url=/resources/documentation/Windows/XP/all/reskit/en-us/prkc_fil_punq.asp Quoting: ''' The Last Access Time on disk is not always current because NTFS looks for a one-hour interval before forcing the Last Access Time updates to disk. NTFS also delays writing the Last Access Time to disk when users or programs perform read-only operations on a file or folder, such as listing the folder's contents or reading (but not changing) a file in the folder. If the Last Access Time is kept current on disk for read operations, all read operations become write operations, which impacts NTFS performance. Note * File-based queries of Last Access Time are accurate even if all on-disk values are not current. NTFS returns the correct value on queries because the accurate value is stored in memory. ''' Does that help? (Just went through this myself the other day.) -Peter Yes, it does. Thank you. -- http://mail.python.org/mailman/listinfo/python-list
python equivalent to the perl IDENT module
Is there an python equivalent to perl IDENT module, specifically the client functionality ? TIA -- http://mail.python.org/mailman/listinfo/python-list
Re: Pattern matching from a text document
B Ben [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] I'm currently trying to develop a demonstrator in python for an ontology of a football team. At present all the fit players are exported to a text document. The program reads the document in and splits each line into a string (since each fit player and their attributes is entered line by line in the text document) using list = target.splitlines() [snipped] The program then performs a loop like so: The two main problems I'm having are that the first and entry in the list is not printing. Once I have overcome this problem I then need each player and there related variables to be stored seperately. This is not happening at present because each time the loop runs it overwrites the value in each variable. Any help would be greatly appreciated. Ben. Ben, can you post a sample line from the document and indicate the fields you want to extract? I'm sure it will be easier to help you this way. George ~ If a slave say to his master: You are not my master, if they convict him his master shall cut off his ear. Hammurabi's Code of Laws ~ -- http://mail.python.org/mailman/listinfo/python-list
Re: Submission for Python Limmerick Contest
No pointers, no templates, no streams, These are things found only in bad dreams, Because Explicit is with it, and static typing dismiss-ed The Best language has been.joined() at the seams! -- http://mail.python.org/mailman/listinfo/python-list
Re: Pattern matching from a text document
First, if you're going to loop over each line, do it like this: for line in file('playerlist.txt'): #do stuff here Second, this statement is referencing the *second* item in the list, not the first: match = ph.match(list[1]) Third, a simple splitting of the lines by some delimiter character would be easier than regular expressions, but whatever floats your boat. If you insist on using regexen, then you should compile the pattern before the loop. No need to do it over and over again. Fourth, if you want to create a list of players in memory, then you need either a class or some other structure to represent each player, and then you need to add them to some kind of list as you go. Like this: pat = ([a-z]+)(\s+)([a-z]+)(\s+)([a-z]+)(\s+)(\d{1})(\d{1})(\d{1})(\d{1})(\d{1})([a-z]+) ph = re.compile(pat,re.IGNORECASE) players = [] for line in file('playerlist.txt'): match = ph.match(line) player = { 'forename' : match.group(1), 'surname' : match.group(3), 'attacking' : match.group(7), 'defending' : match.group(8), 'fitness' : match.group(9) } players.append(player) -- http://mail.python.org/mailman/listinfo/python-list
Re: Windows, Python and low level networking
Peter Hansen wrote: [EMAIL PROTECTED] wrote: Is it possible to have low level netwoking with python under Windows? Like raw sockets? Is it possible to send a single packet using python under windows? Google is your friend: Try searching with python sockets, for example... (You *have* heard of Google, haven't you? It's been in the news a bit lately...) The OP may get 302'd though! ;-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Lowest hassle Python web server?
Larry Bates wrote: [...] You might want to take a look a Medusa. It is the basis for the web server that is bundled in Zope. Medusa is just an asyncore framework, and not something you can develop web apps with. -- Gerhard -- http://mail.python.org/mailman/listinfo/python-list
Help me to sort.
Hi, I'll apreciate if you can guide me how to sort in Python. I'm doing a list and I want to sort it in ascendingor descending order. Please send me some examples. Thank you in advance. -- http://mail.python.org/mailman/listinfo/python-list
Re: Windows, Python and low level networking
[EMAIL PROTECTED] wrote: Is it possible to have low level netwoking with python under Windows? Like raw sockets? Is it possible to send a single packet using python under windows? Yes. But be aware of restrictions on raw sockets in XP SP2: http://blogs.msdn.com/michael_howard/archive/2004/08/12/213611.aspx and don't blame it on Python if it doesn't work :) There's a way to overcome this, but it comes with its load of other problems. Anyway, this doesn't belong there, so fu2 comp.os.ms-windows.networking.tcp-ip -- http://mail.python.org/mailman/listinfo/python-list
RE: Help me to sort.
BMS wrote: I'll apreciate if you can guide me how to sort in Python. I'm doing a list and I want to sort it in ascending or descending order. Please send me some examples. Everything you need is right here: http://www.catb.org/~esr/faqs/smart-questions.html http://www.python.org/doc/ Tim Delaney -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting the word to conventional programmers
That was a great article. I really enjoyed it. We need more like it. Robert -- http://mail.python.org/mailman/listinfo/python-list
Re: typo in the library reference?
On Wed, 23 Mar 2005 05:13:45 -0800 Scott David Daniels [EMAIL PROTECTED] wrote: My apologies belong in this thread. No worries, apology accepted On Wed, 23 Mar 2005 11:44:27 -0500 Terry Reedy [EMAIL PROTECTED] wrote: nicke [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] I'm going to submit a bug report, just don't have much experience with that... but hey, sometime must be the first! ;) If you can, you might also look at the ossaudio source to verify that the mixup is strictly in the doc and not the code. TJR Well, sorry, the ossaudiodev module seem to be coded in c or c++ (?) which i don't have any experience with. However, according to the python interpreter help the AFMT_U8...etc are differently ordered and have numeric values, which probably means that the sources doesn't say anythin to anyone without deep understanding of the oss interface. (if they aren't very well documented) nicke -- http://mail.python.org/mailman/listinfo/python-list
Use of descriptor __get__: what defines an object as being a class?
I'm talk from the point of view of descriptors. Consider a.x = lambda self:None # simple function When a.x is later got, what criterion is used to see if a class (and so the func would have __get__(None, a) called on it)? Pre-metaclasses, one might assume it was isinstance(a, (types.TypeType, types.ClassType)) but nowadays the type of a type could be anything. Is there a simple Python-level interface to determine what constitutes a type, as there is for, say, iterators? Could an object start being a type just by appropriately setting certain members, or is this distinction enforced at a lower level? To confuse matters further, the descriptor docs in 2.4 say that descriptors can only be bound to objects, not classic class instances, but a few moments with a Python console disproves this (it is the descriptors themselves that have to be objects.) def getting(*a): print Getting! class oldDesc: __get__ = getting class newDesc(object): __get__ = getting class Q:pass # classic class Q.x = oldDesc() Q.x __main__.oldDesc instance at 0x009ACAA8 Q.y = newDesc() Q.y Getting! This seems to be a more sensible state of affairs (otherwise function-to-method wrapping would have to be a special case), but http://www.python.org/doc/2.4/ref/descriptor-invocation.html says different. What is the canonical distinction between classes and types, and between instances and objects? How would it apply in the face of such perversions as from types import * class C1: __metaclass__ = TypeType class C2(object): __metaclass__ = ClassType or reassignment of __class__ from an class to a type or vice versa? I would have thought that most of the time (i.e. excluding the above tricksiness) all that would be needed was isinstance(x, object) but this returns true when x is an Exception, which is guaranteed to be an instance and hence not an object. Thanks John -- http://mail.python.org/mailman/listinfo/python-list
Changing the value of a for loop index on the fly
Hi! There goes a newbie trouble: for i in range(0, len(subject)): if subject[i] in preps: psubject.append(noun_syn_parser(subject[0:i])) subject[0:i] = [] Since the last line eliminates some elements of the list, I'm wondering if it's somehow possible to change the value of i to 0 in order not to get an index error. Any other ideas? Thanks in advance. -- http://mail.python.org/mailman/listinfo/python-list
Re: Getting the word to conventional programmers
Cameron Laird wrote: *DevSource* profiles The State of the Scripting Universe in URL: http://www.devsource.com/article2/0,1759,1778141,00.asp . It would have been nice to put in a blurb for some of the cool stuff planned for 8.5. That way people could see that things are *happening* in the Tcl world and Tcl is moving forward language wise. That doesn't take away from the article though. It was just a thought. Robert -- http://mail.python.org/mailman/listinfo/python-list
Re: cross platform use of set locale
Serge Orlov wrote: Timothy Smith wrote: Serge Orlov wrote: Timothy Smith wrote: thats ok, but how do i get it to group thousands with a , ? and thats would mean i'd have to run everything through a formatter before i displayed it :/ it'd be nicer if i could just select a proper locale I think you're misusing locale. There is no guarantee that any specific locale will have properties (like grouping) set to a known value. Are you trying to format money? Then you need a special class so that you can say: d = Dollars(100.01) print You have %s in your account % d and get You have $1,000,000.01 in your account. Serge. thats exactly what i'm trying to do, only having to do that for all my outputs is more work then i'd like :/ SUS has added numeric grouping For some numeric conversions a radix character (`decimal point') or thousands' grouping character is used. The actual character used depends on the LC_NUMERIC part of the locale. The POSIX locale uses `.' as radix character, and does not have a grouping character. Thus, printf(%'.2f, 1234567.89); results in `1234567.89' in the POSIX locale, in `1234567,89' in the nl_NL locale, and in `1.234.567,89' in the da_DK locale. but they hasn't added monetary grouping. I don't think you'll get monetary grouping anytime soon. Besides as far as I understood your question, you *always* want grouping, right? Actually I don't think a cryptic flag is better than an explicit formatter. What do you think is more clear for a maintainer of your code? print %'.2f % amount or print %s % dollars(amount) why is this a misuse of locale? it's exactly what locale is meant for isn't it? I just reacted to your words select a proper locale and how do i get it to group thousands with a ,. It's just not a good idea to select a locale and expect the grouping character to be , or expect grouping, see nl_NL locale example above. Serge. i'm pretty sure english au uses thousands grouping with , i've managers to make this work, however it just isn't cross platform at all. -- http://mail.python.org/mailman/listinfo/python-list
Re: Changing the value of a for loop index on the fly
i = 0 while i len(subject): if subject[i] in preps: psubject.append(noun_syn_parser(subject[0:i])) subject[0:i] = [] i = 0 else: i += 1 Gabriel F. Alcober wrote: Hi! There goes a newbie trouble: for i in range(0, len(subject)): if subject[i] in preps: psubject.append(noun_syn_parser(subject[0:i])) subject[0:i] = [] Since the last line eliminates some elements of the list, I'm wondering if it's somehow possible to change the value of i to 0 in order not to get an index error. Any other ideas? Thanks in advance. -- http://mail.python.org/mailman/listinfo/python-list
Re: Changing the value of a for loop index on the fly
Uh! I've not even thought in using a while... Thanks! Lonnie Princehouse wrote: i = 0 while i len(subject): if subject[i] in preps: psubject.append(noun_syn_parser(subject[0:i])) subject[0:i] = [] i = 0 else: i += 1 Gabriel F. Alcober wrote: Hi! There goes a newbie trouble: for i in range(0, len(subject)): if subject[i] in preps: psubject.append(noun_syn_parser(subject[0:i])) subject[0:i] = [] Since the last line eliminates some elements of the list, I'm wondering if it's somehow possible to change the value of i to 0 in order not to get an index error. Any other ideas? Thanks in advance. -- http://mail.python.org/mailman/listinfo/python-list
newbie help
static void testme( unsigned char *buf, unsigned long size, CODE code) { unsigned long data switch (code) { // Generate some test patterns case TEST1 : value = 0x0; while (size--) { *buf++ = (unsigned char)value++ } break case TEST2 : } return } main() { unsigned char buf[512]; CODE code = TEST1 # The index number is passed from the command line # It corresponds to one of the two buffers # if index = 1 corresponds to buf1 and if index = 2 corresponds to buf2 buf1 = getBuf(index1); testme( buf1, 512, code); return 0x0; } This is snippet code trying to generate some test patterns. How do i manage multiple buffers in python. Is it possible? If the index number at command line is 2, then buffer 2 is passed to 'testme' I went through the Python tutorial and could not find much information. Any help with python examples is appreciated. -- http://mail.python.org/mailman/listinfo/python-list
Re: Changing the value of a for loop index on the fly
On Wed, 23 Mar 2005 23:27:54 +0100, Gabriel F. Alcober [EMAIL PROTECTED] wrote: Hi! There goes a newbie trouble: for i in range(0, len(subject)): if subject[i] in preps: psubject.append(noun_syn_parser(subject[0:i])) subject[0:i] = [] Since the last line eliminates some elements of the list, I'm wondering if it's somehow possible to change the value of i to 0 in order not to get an index error. Any other ideas? Messing with the list/index concerned within the loop itself is rarely a good idea and can most often be avoided: lastFound = 0 for i in range(0, len(subject)): if subject[i] in preps: psubject.append(noun_syn_parser(subject[lastFound:i])) lastFound = i #you probably want i+1 here? your source says i, however #if having the subject list matters, you can finish it all outside the loop with subject[0:lastFound] = [] HTH Mitja -- http://mail.python.org/mailman/listinfo/python-list
Re: IronPython 0.7 released!
François Pinard emailed me that my posting of the link with no explanation appeared rude. So here is a some information. IronPython is a Python implementation targeting the .NET and Mono platforms from the same person who brought us Jython, Jim Hugunin. MS hired Jim since the first release (0.6) and this is the first and eagerly awaited release since then. Now if I hear something about the state of StarKiller, it would make my day complete :-). From the release IronPython is the code name of the early pre-alpha preview release of the new Implementation Running on .NET of the Python programming language. The .NET Framework is a managed programming model for Windows; Microsoft standardized part of it in ECMA several years ago as the Common Language Infrastructure and C# Language Specification standards. IronPython is fast - up to 1.8x faster than Python-2.4 on the standard pystone benchmark. It supports an interactive interpreter with fully dynamic compilation. It is well integrated with the rest of the framework and makes all .NET libraries easily available to Python programmers. IronPython 0.7 is a pre-alpha release. It is suitable for experimenting and playing with; however, a large amount of testing, packaging and library development remains to be done before a production-quality IronPython-1.0. We want to be sure to release IronPython in this early state in order to encourage feedback and discussion in the community of IronPython's features and designs as early as possible so that we can incorporate that into the 1.0 design. Also see Boo Boo is a new object oriented statically typed programming language for the Common Language Infrastructure with a python inspired syntax and a special focus on language and compiler extensibility. http://boo.codehaus.org/ Python for .NET Python for .NET is a near-seamless integration of the Python runtime with the .NET Common Language Runtime (CLR). It lets you script and build applications in Python, using CLR services and components written in any language that targets the CLR (C#, Managed C++, VB.NET, etc.). www.zope.org/Members/Brian/PythonNet James. -- http://mail.python.org/mailman/listinfo/python-list