Re: monitor a folder for file creation, how?
SUPER! This is exactly what I'm looking for. gene tani wrote: win32: (I posted this link in response to same question, um, day bef. yesterday) http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/9a1c7629db72d064/56008cb68eeffa23?hl=en#56008cb68eeffa23 (Thanks to Tim Golden for collecting the info) OS X: I dunno... -- http://mail.python.org/mailman/listinfo/python-list
why functions in modules need 'global foo' for integer foo but not dictionary foo?
At top of a module I have an integer like so... foo = 4 In a function in that module I know I need to do 'global foo' to get at the value 4. ... IIRC, for dictionaries you DO NOT have this issue? Why this scope problem with integers but not dictionaries? Chris -- http://mail.python.org/mailman/listinfo/python-list
Re: why functions in modules need 'global foo' for integer foo but not dictionary foo?
[EMAIL PROTECTED] wrote: At top of a module I have an integer like so... foo = 4 In a function in that module I know I need to do 'global foo' to get at the value 4. ... You don't. You need the global declaration to *set* the value of foo in the module's namespace. When getting the value of foo within the function, if it's not been defined in the function's local namespace, it automatically looks in the global namespace with or without the global foo declaration. When assigning a value to the name foo within the function, however, without the global declaration, the value will only be assigned to the name foo within the local namespace. http://docs.python.org/ref/naming.html IIRC, for dictionaries you DO NOT have this issue? Why this scope problem with integers but not dictionaries? I presume you are trying code like the following: foo = 4 bar = {} def fun1(): foo = 5 def fun2(): bar['baz'] = 4 Since integers are immutable, all that fun1() does is assign 5 to the name foo within fun1()'s namespace and doesn't touch the module-level namespace. fun2(), on the other hand, only gets the dictionary from the module-level namespace with the name bar. Then it modifies that dictionary (since it's mutable). It does not try to assign a new object to the name bar. I hope that's clear, but I'm pretty tired right now, and it may not be. -- Robert Kern [EMAIL PROTECTED] In the fields of hell where the grass grows high Are the graves of dreams allowed to die. -- Richard Harter -- http://mail.python.org/mailman/listinfo/python-list
Re: Regex for nested {}
Or use pyparsing, and do both at the same time (that spark example looks like a lot of work!). Download pyparsing at http://pyparsing.sourceforge.net. -- Paul from pyparsing import * text = outer { inner1 { ...1 } inner2 { ...2 } } simple { ...3 } null {} single { blah } LBRACE = Literal({).suppress() RBRACE = Literal(}).suppress() listKey = Word(alphanums) listValue = Forward() listEntry = Group( listKey + listValue ) listValue Group( LBRACE + ZeroOrMore( listEntry | Word(alphanums+.) ) + RBRACE) inputData = OneOrMore( listEntry ) results = inputData.parseString( text ) print results.asList() Prints : [['outer', [['inner1', ['...1']], ['inner2', ['...2', ['simple', ['...3']], ['null', []], ['single', ['blah']]] (manually formatted to show nesting) [ ['outer', [ ['inner1', ['...1']], ['inner2', ['...2']] ] ], ['simple', ['...3']], ['null', []], ['single', ['blah']] ] -- http://mail.python.org/mailman/listinfo/python-list
Re: can list comprehensions replace map?
Christopher Subich wrote: My naive solution: ... for i in ilist: try: g = i.next() count += 1 except StopIteration: # End of iter g = None ... What I didn't like about this was the extra overhead of all the StopIteration exceptions. Eg, zipfill(a, range(1000)) will raise 1000 exceptions (999 for a and 1 for the end of the range). But without doing timing tests I'm not sure which approach is fastest, and it may depend on the data set. Since this is code best not widely used, I don't think it's something anyone should look into either. :) Andrew [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: os._exit vs. sys.exit
Bryan wrote: Why does os._exit called from a Python Timer kill the whole process while sys.exit does not? On Suse. os._exit calls the C function _exit() which does an immediate program termination. See for example http://developer.apple.com/documentation/Darwin/Reference/ManPages/man2/_exit.2.html and note the statement can never return. sys.exit() is identical to raise SystemExit(). It raises a Python exception which may be caught at a higher level in the program stack. Andrew [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: functions without parentheses
On Thu, 28 Jul 2005 00:59:51 -0700 (PDT), Jerry He [EMAIL PROTECTED] wrote: Hi, Is it possible to create a function that you can use without parenthesizing the arguments? for example, for def examine(str): . . Is there some way to define it so that I can call it like examine string instead of examine(string)? I suggested in a previous thread that one could support such a syntax by supporting an invisible binary operator between two expressions, so that examine string translates to examine.__invisbinop__(string) if examine as an expression evaluates to an object that has a __invisbinop__ method. Then you wouldn't define examine as a function, you would define it as an instance of a class like class Examine(object): define __invisbinop__(self, other): #...whatever examine = Examine() and then examine string Of course this is a strange syntax mod to the language, and undoubtedly would have many strange effects, but superficially, it seems like something could be done. But a consequence of white space as potential invisible operator would be that foo() and foo () might be foo.__call__() vs foo.__invisbinop_(()) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list
Re: [path-PEP] Path inherits from basestring again
[__div__ for .joinpath()] on 29.07.2005 04:48 Tony Meyer said the following: I, herewith, claim to have used it in the past. But I am indifferent as to if its needed, it just looks natural to me. So far there seem to have been a few +0s, but no +1s... What I use quite often is:: path(__file__).dirname() / somesiblingfileiknowisthere you do not have to think about trailing slashes or absolute vs. relative. and its much better than:: from os.path import * join(dirname(__file__), somesiblingfileiknowisthere) In what way is this much better? because of the 'object-orientedness'. i hope we agree on that (that's the reason for a path PEP?). the first is only sugar for the explicit:: path(__file__).dirname().joinpath(blablablabalbal) and as i said +0 operator overloading is only good if it's intuitive for the majority. (or Guido i suppose, in case this majority-person does not show up) [snip] Would you really choose this: p = Path() / build / a / very / very / long / path (Path() is the current dir I think) Over this: p = Path(os.path.join(build, a, very, very, long, path)) ? A saving of six characters, and the second one is a lot clearer. If there was a os.path.joinPath (or whatever name) function that returned a Path object rather than a string, then you'd get: p = joinPath(build, a, very, very, long, path) Which is better (clearer, more concise) than either of the others, IMO. actually for explicitness i would choose: (original jorendorff):: p = path(build).joinpath(any, path, you, can, imagine) or otherwise maybe:: p = path(alpha) / and / omega -- http://mail.python.org/mailman/listinfo/python-list
Re: why functions in modules need 'global foo' for integer foo but not dictionary foo?
Robert Kern wrote: [EMAIL PROTECTED] wrote: At top of a module I have an integer like so... foo = 4 In a function in that module I know I need to do 'global foo' to get at the value 4. ... I presume you are trying code like the following: foo = 4 bar = {} def fun1(): foo = 5 def fun2(): bar['baz'] = 4 Since integers are immutable, all that fun1() does is assign 5 to the name foo within fun1()'s namespace and doesn't touch the module-level namespace. Hmm this is obscure to me also, what mutables has to do with this problem?A binding is always mutable. fun2(), on the other hand, only gets the dictionary from the module-level namespace with the name bar. Then it modifies that dictionary (since it's mutable). It does not try to assign a new object to the name bar. Probably the point is modifing/rebinding the bound values and not rebind them. Generally if you need to use globals for inter-instance/class communication, I suggest to define a new namespace where to put global bindings: class Globals: foo=4 spam={} for lexical coherence you can put also funtions there class Globals: foo=4 spam={} @staticmethod def func():pass then you always refer to them with Globals.foo,Globals.spam,Globals.func or with Module.Globals from outside. Finally consider to use singletons as a more common approach. Ciao ___ Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB http://mail.yahoo.it -- http://mail.python.org/mailman/listinfo/python-list
how to append cgi FieldStorage Class instance
Dear All, I have doubt in python cgi script. I describe that doubt with below code import cgi form = cgi.FieldStorage() passwd = form['passwd'].value print passwd But Now I want to assign some value to form['passwd'] field value form['passwd'] = 'surese' Now If I try to print print form['passwd'].value. It will raise error. So kinldy let me how to edit or append instance of FieldStorage class regards PRabahar ___ Too much spam in your inbox? Yahoo! Mail gives you the best spam protection for FREE! http://in.mail.yahoo.com -- http://mail.python.org/mailman/listinfo/python-list
RE: [path-PEP] Path inherits from basestring again
[Tony Meyer] | | [Tim Golden] | Well, I actually had some correspondence with Jason on this | very subject a year or so ago: | [...] | Obviously, I don't know how much weight Jason's original | ideas have on the prepped-for-syslib module, but it does | support what other people have been saying: that the Path | should behave like a string where a string is expected. | | Was that the whole email? It certainly adds weight to '+' | having the normal | string behaviour, but it didn't really say anything about why | '/' should be | a shortcut for join. Do you know if Jason had any reasoning | for this other | than laziness wink? | | =Tony.Meyer Well, he did add the following paragraph: email For example: I haven't tried it, but I don't think the most obvious two-line fix will necessarily work. If you change __add__ to call os.path.join(), you'll likely get infinite recursion, because os.path.join() probably uses + to do its work. Of course this is pretty easy to work around; call it three lines. /email which might explain why he *didn't* use __add__ but doesn't explain whey he *did* use __div__. (There was more to the original email but that was more to do with some wild-eyed ideas I'd had about adding methods for file-locking and share-mounting to the path object). FWIW, my own feeling is that / is an awkward fit and relies for its ease-of-reading on the -- admittedly common but not universal -- use of that symbol as a path separator. I don't feel terribly strongly about it, but I don't tend to use it in my own code. TJG This e-mail has been scanned for all viruses by Star. The service is powered by MessageLabs. For more information on a proactive anti-virus service working around the clock, around the globe, visit: http://www.star.net.uk -- http://mail.python.org/mailman/listinfo/python-list
Re: can list comprehensions replace map?
Andrew Dalke wrote: Steven Bethard wrote: Here's one possible solution: py import itertools as it py def zipfill(*lists): ... max_len = max(len(lst) for lst in lists) A limitation to this is the need to iterate over the lists twice, which might not be possible if one of them is a file iterator. Here's a clever, though not (in my opinion) elegant solution import itertools def zipfill(*seqs): count = [len(seqs)] def _forever(seq): for item in seq: yield item count[0] -= 1 while 1: yield None seqs = [_forever(seq) for seq in seqs] while 1: x = [seq.next() for seq in seqs] if count == [0]: break yield x This seems a bit more elegant, though the replace dictionary is still a bit of a hack from itertools import repeat, chain, izip sentinel = object() end_of_stream = repeat(sentinel) def zipfill(*seqs): replace = {sentinel: None}.get seqs = [chain(seq, end_of_stream) for seq in seqs] for term in izip(*seqs): for element in term: if element is not sentinel: break else: # All sentinels break yield [replace(element, element) for element in term] Combining your clever and your elegant approach to something fast (though I'm not entirely confident it's correct): def fillzip(*seqs): def done_iter(done=[len(seqs)]): done[0] -= 1 if not done[0]: return while 1: yield None seqs = [chain(seq, done_iter()) for seq in seqs] return izip(*seqs) Whether we ran out of active sequences is only tested once per sequence. Fiddling with itertools is always fun, but feels a bit like reinventing the wheel in this case. The only excuse being that you might need a lazy map(None, ...) someday... Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: how to append cgi FieldStorage Class instance
praba kar wrote: Dear All, I have doubt in python cgi script. I describe that doubt with below code import cgi form = cgi.FieldStorage() passwd = form['passwd'].value print passwd But Now I want to assign some value to form['passwd'] field value form['passwd'] = 'surese' Now If I try to print print form['passwd'].value. It will raise error. So kinldy let me how to edit or append instance of FieldStorage class A form *isn't* a dictionary, this means that your code : form['passwd'] = 'surese' is wrong. Turn the form into a dictionary and use that. Why are you trying to assign values directly in the form ? Best Regards, Fuzzy http://www.voidspace.org.uk/python regards PRabahar ___ Too much spam in your inbox? Yahoo! Mail gives you the best spam protection for FREE! http://in.mail.yahoo.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Advanced concurrancy
Cheers Guys, I have come across twisted and used in async code. What i'm really looking for is something that provides concurrency based on CSP or pi calculus. Or something that looks much more like Java's JSR 166 which is now integrated in Tiger. Peter Tillotson wrote: Hi, I'm looking for an advanced concurrency module for python and don't seem to be able to find anything suitable. Does anyone know where I might find one? I know that there is CSP like functionality built into Stackless but i'd like students to be able to use a standard python build. I'm trying to develop distributed / Grid computing modules based on python. The aim is to be able to use barriers for synchronisation and channels for communication between processes running on a single box. Then the jump to multiple processes on multiple boxes and eventually to MPI implementations. Hopefully, each jump should not be that big a leap. Of course it would be nice if there was a robust way of managing concurrency in python aswell ;-) p -- http://mail.python.org/mailman/listinfo/python-list
Spreadsheet with Python scripting and database interface?
Hello, I'm looking for a spreadsheet application (MacOS X prefered, but Windows, Linux ar available as well) with support for Python scripting (third-party plug-ins are ok) and a database interface. Applications that I know of (that they exist) are: MS Excel Quattro Lotus OO Calc Gnumeric Kspread Which ones have I forgotten? Which ones have support for Python scripting? Excel: I know of a module that allows to script Excel in Python from outside (COM scripting on Windows and Applescript on MacOS are know as well), but I don't know of any possibility to do Python scripting with Excel itself? OO Calc: I know that PyUNO exists, but I know nothing about what it can actually do? Kspread: Koffice seems to have Python scripting support, but I have no clue what you can actually do with it? The database interface should ideally allow to: - map database tables, views, query results to tables/lists (with as little programming as possible) - allow editing of records within those tables/lists (and write back the results) - supply possibilities to handle relationships (via foreign keys) between records in different tables in a user-friendly way (I have something like hyperlinks in mind) The database software to interface with is Postgres. The application should also provide good support for naming of cells/columns/rows/regions (including namespaces for files, sheets) and user-defined formats. TIA, Sincerely, Wolfgang Keller -- http://mail.python.org/mailman/listinfo/python-list
Re: Spreadsheet with Python scripting and database interface?
Wolfgang Keller wrote: Excel: I know of a module that allows to script Excel in Python from outside (COM scripting on Windows and Applescript on MacOS are know as well), but I don't know of any possibility to do Python scripting with Excel itself? For scripting Mac applications with Python instead of AppleScript, see: http://freespace.virgin.net/hamish.sanderson/appscript.html HTH -- http://mail.python.org/mailman/listinfo/python-list
Re: Ten Essential Development Practices
Dan Sommers wrote: On Thu, 28 Jul 2005 15:35:54 -0700, Robert Kern [EMAIL PROTECTED] wrote: That said, I made a boo-boo. The Zen of Python is really a set of design principles (and some of them, like this one, are more specifically *language* design principles), not Essential Development Practices. That'll teach me to not RTFA. May I respectfully disagree? The Zen applies to all aspects of software (and other things, too, but they're off topic here), from human readable reports and requirements and documentation, to GUI's, to test cases, to code, to database schemta, as well as the development methodology and practices themselves. Sometimes you have to look at the Zen sideways, so that implementation appears to be replaced by the particular aspect or aspects (or the software, or just software, as a whole, for the true Masters out there) you happen to be working on at the time, but such is the nature of Zen. Regards, Dan If I canpoint out the obvious, the output from import this *is* headed The Zen of Python, so clearly it isn;t intended to be universal in its applicability. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Advanced concurrancy
Peter Tillotson [EMAIL PROTECTED] writes: I have come across twisted and used in async code. What i'm really looking for is something that provides concurrency based on CSP or pi calculus. Or something that looks much more like Java's JSR 166 which is now integrated in Tiger. Python doesn't have anything that fancy. You could look at: pyro.sf.net - Python remote objects using sockets poshmodule.sf.net - objects shared between processes using shared memory Queue module - synchronized queues for interthread communications in one process It would be nice if there were something like Queue that used MPI. Underneath there could be either sockets, shared memory, some special multiprocessor interconnect, or whatever. -- http://mail.python.org/mailman/listinfo/python-list
Re: Ten Essential Development Practices
Steve Holden [EMAIL PROTECTED] writes: If I canpoint out the obvious, the output from import this *is* headed The Zen of Python, so clearly it isn;t intended to be universal in its applicability. It's also mistitled there, given that it was originally posted as '19 Pythonic Theses' and nailed to, erm, something. Cheers, mwh -- Remember - if all you have is an axe, every problem looks like hours of fun.-- Frossie -- http://home.xnet.com/~raven/Sysadmin/ASR.Quotes.html -- http://mail.python.org/mailman/listinfo/python-list
Re: how to append cgi FieldStorage Class instance
praba kar wrote: Dear All, I have doubt in python cgi script. I describe that doubt with below code import cgi form = cgi.FieldStorage() passwd = form['passwd'].value print passwd But Now I want to assign some value to form['passwd'] field value form['passwd'] = 'surese' Now If I try to print print form['passwd'].value. It will raise error. So kinldy let me how to edit or append instance of FieldStorage class You can't do that to a FieldStorage instance: it represents user input and is therefore not intended to be writable. What exactly are you trying to achieve - some kind of default value? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Opinions on KYLIX 3 (Delphi 4 Linux)
I've used Kylix 3 in the past, but would not consider it nowadays, because it's realy behind the times, it can't run on the latest linux versions and does only support Qt 2.7, while Qt4 has just been released. I'm a C++ programmer and loved Borland C++Builder, I was disappointed by how buggy the C++ side of Kylix 3 was. I think Borland is dead in the water right now, because Microsoft has been targetting their Delphi/C++Builder succes very agressively. MS has essentailly bought their entire developement team, and used them to create VS.Net as an answer to both Java and the Borland developement environment. This is more or less fact, there have enven been lawsuits about it: http://news.com.com/2100-1023-279561.html?legacy=cnet http://delphi.about.com/od/delphifornet/a/conspiracydnet_2.htm According to the article Ms is now a large shareholder in Borland, and will probably halt any further Linux developement. Adriaan Renting| Email: [EMAIL PROTECTED] ASTRON | Phone: +31 521 595 217 P.O. Box 2 | GSM: +31 6 24 25 17 28 NL-7990 AA Dwingeloo | FAX: +31 521 597 332 The Netherlands| Web: http://www.astron.nl/~renting/ David Trudgett [EMAIL PROTECTED] 07/20/05 10:37 AM Thomas Bartkus [EMAIL PROTECTED] writes: Good question! Wither Borland? My impression (second hand - based on no direct experience with Kylix!) is that Borlands wonderful Delphi product ported to Linux has been a dissapointment. * * * Someone with real experience on Kylix - please jump in here! It has been two or three years since I gave Kylix a try, so my memory is a bit vague on the specifics. I was working in a Delphi shop and wanted to port (at least some of) our apps to Linux using Kylix (I think it was version 3). I think I ported one and a half apps and more or less gave up or put it on the back burner. My impression was that Kylix still wasn't ready for serious development work. The type of application I was working on (porting) involved client/server database access, and TCP communications with other applications. It never really worked correctly (I forget what the problems were just now), but probably could have been made to work correctly. The point was, however, that porting (a relatively simple) Delphi app to Kylix shouldn't have been that hard. Calling Delphi similar to Visual Basic is hurtful because I believe that VB is the product of looting and pillaging the talent that came out of Borland. I'm guessing that Microsoft has successfully targeted this perceived competitor with destruction. If Kylix were of the quality of Delphi, it would be a killer Linux app. Possibly. Unfortunately, I don't believe that the whole GUI building approach of Delphi/Kylix (or other similar tools) is much chop. It encourages one, for instance, to just place elements on the screen in fixed positions that make no allowance for differing fonts, screen resolutions, etc. Java (my experience is with JBuilder) is much better in this regard, although the different paradigm takes some getting used to. However, all GUI builders with which I'm familiar (not many) seem to have very real limitations when it comes to designing very complex interfaces. Kenny Tilton's Cells project (ask on comp.lang.lisp) has set me to thinking along these lines. In the past, I never gave it much consideration. Programmers who like Pascal should look at Ada as a better alternative. If I wanted to program in a Pascal-like language on Linux, Ada (the GNU Gnat compiler, integrated with GCC) is the one that I would use. Ada, you could say, is like Pascal on steroids. Caveat: I've read Ada books, but haven't programmed in it, and my main concern is that its ultra strong typing might get in my way -- or alternatively, force greater rigour, as the Ada folks might say ;-). These days, for hacking about, I prefer Common Lisp. It's faster (sometimes approaching the speed of compiled C/Pascal) and much more powerful than Python, but doesn't have the same library support (smaller community), and application bundling and delivery *can* be a potential problem, depending on various factors (such as whether you want to license a commercial Common Lisp). Also, similar to Python, there is no standard GUI framework defined for Common Lisp, so choosing from the GUI frameworks available can be a challenge (I've only programmed a simple GUI app using the great little Ltk library by Peter Herth, which talks to Tk over a socket). My advice would be to steer clear of Kylix and choose one of the other environments suggested to you. If you really like Pascal, fpc may be a possibility as someone mentioned. I haven't looked into it any time in the last couple of years, though, so I don't know its status. I really would suggest a serious look at Ada, though, if you want to develop fast, industrial strength applications, or take advantage of built-in concurrency support and lots of other goodies. David -- David Trudgett
Re: codecs.getencoder encodes entire string ?
Thank you very much ! Nicolas -- http://mail.python.org/mailman/listinfo/python-list
Re: Filtering out non-readable characters
def StripNoPrint(self, S): from string import printable return .join([ ch for ch in S if ch in printable ]) Adriaan Renting| Email: [EMAIL PROTECTED] ASTRON | Phone: +31 521 595 217 P.O. Box 2 | GSM: +31 6 24 25 17 28 NL-7990 AA Dwingeloo | FAX: +31 521 597 332 The Netherlands| Web: http://www.astron.nl/~renting/ MKoool [EMAIL PROTECTED] 07/16/05 2:33 AM I have a file with binary and ascii characters in it. I massage the data and convert it to a more readable format, however it still comes up with some binary characters mixed in. I'd like to write something to just replace all non-printable characters with '' (I want to delete non-printable characters). I am having trouble figuring out an easy python way to do this... is the easiest way to just write some regular expression that does something like replace [^\p] with ''? Or is it better to go through every character and do ord(character), check the ascii values? What's the easiest way to do something like this? thanks -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: how to append cgi FieldStorage Class instance
--- Fuzzyman [EMAIL PROTECTED] wrote: praba kar wrote: Dear All, I have doubt in python cgi script. I describe that doubt with below code import cgi form = cgi.FieldStorage() passwd = form['passwd'].value print passwd But Now I want to assign some value to form['passwd'] field value form['passwd'] = 'surese' Now If I try to print print form['passwd'].value. It will raise error. So kinldy let me how to edit or append instance of FieldStorage class A form *isn't* a dictionary, this means that your code : form['passwd'] = 'surese' is wrong. Turn the form into a dictionary and use that. How Can I convert a form instance into dictionary Kindly let me know. Why are you trying to assign values directly in the form ? To reduce variable usage in my project. regards Prabahar __ How much free photo storage do you get? Store your friends 'n family snaps for FREE with Yahoo! Photos http://in.photos.yahoo.com -- http://mail.python.org/mailman/listinfo/python-list
Re: how to append cgi FieldStorage Class instance
praba kar wrote: --- Fuzzyman [EMAIL PROTECTED] wrote: praba kar wrote: Dear All, I have doubt in python cgi script. I describe that doubt with below code import cgi form = cgi.FieldStorage() passwd = form['passwd'].value print passwd But Now I want to assign some value to form['passwd'] field value form['passwd'] = 'surese' Now If I try to print print form['passwd'].value. It will raise error. So kinldy let me how to edit or append instance of FieldStorage class A form *isn't* a dictionary, this means that your code : form['passwd'] = 'surese' is wrong. Turn the form into a dictionary and use that. How Can I convert a form instance into dictionary Kindly let me know. What have you tried ? ;-) def form_to_dict(form): out_dict = {} for entry in form: out_dict[entry] = form[entry].value return out_dict UNTESTED AND FROM MEMORY If it doesn't work - try reading the manual to see what I did wrong. Why are you trying to assign values directly in the form ? To reduce variable usage in my project. At the cost of clarity ? Not a worthwhile trade off. Explicity delet variables you have finished with instead. form = cgi.FieldStorage() formdict = form_to_dict(form) del form Best Regards, Fuzzy http://www.voidspace.org.uk/python regards Prabahar __ How much free photo storage do you get? Store your friends 'n family snaps for FREE with Yahoo! Photos http://in.photos.yahoo.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Ten Essential Development Practices
On Fri, 29 Jul 2005 10:08:15 +0100, Steve Holden [EMAIL PROTECTED] wrote: If I canpoint out the obvious, the output from import this *is* headed The Zen of Python, so clearly it isn;t intended to be universal in its applicability. Ok, not universal. But as usual, Zen is not easily nailed to a tree. Was Tim writing about developing Python itself, or about developing other programs with Python? Regards, Dan -- Dan Sommers http://www.tombstonezero.net/dan/ -- http://mail.python.org/mailman/listinfo/python-list
Re: functions without parentheses
On Fri, 29 Jul 2005 06:37:52 +, Bengt Richter wrote: I suggested in a previous thread that one could support such a syntax by supporting an invisible binary operator between two expressions, so that examine string translates to examine.__invisbinop__(string) if examine as an expression evaluates to an object that has a __invisbinop__ method. Why would you want to? -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: To thread or not to thread
Some people are of the opinion that threads are evil. Best Regards, Fuzzy http://www.voidspace.org.uk/python -- http://mail.python.org/mailman/listinfo/python-list
Re: Ten Essential Development Practices
[EMAIL PROTECTED] wrote: The following url points to an article written by Damian Conway entitled Ten Essential Development Practices: http://www.perl.com/pub/a/2005/07/14/bestpractices.html Althought the article has Perl as a focus, I thought that some of the general points made might be of interest to the Python community. It would certainly be interesting to put together an analogous version of this article that centers on Python. Hmm, Perl is called a write once language, but it has thousands of libraries.Any comment appreciated. That said,those points are mixing different responsabilities in writing code.I keep on mixing for fun: -Writing libraries is not writing scripts. -Writing readable,well structured,non redundant code is somewhat perpendicular to tests. -Writing tests is a must for more people to work on the same code. -Deciding the interface and writing docs before coding can be bad for experimental coding. -Logic optimization can influence interfaces. -Time optimization is a leverage to get paid in open source software.Never think about that for free. Paolino ___ Yahoo! Mail: gratis 1GB per i messaggi e allegati da 10MB http://mail.yahoo.it -- http://mail.python.org/mailman/listinfo/python-list
Re: pySerial Windows write problem
Bob Greschke wrote: Peter Hansen [EMAIL PROTECTED] wrote in message Actually, I'm curious why you don't do the same. I'd call it very unusual (in my experience) to have a program open and close a serial port repeatedly. Among other things, this means that the DSR/DTR lines are toggling high and low repeatedly, and that alone could cause undesirable behaviour in certain devices. I guess I could. It's just that not releasing the port/not KNOWING that the port has been closed at predictible times is our chief complaint about the C++ program. As an aside, when I left work I left a version of the while-loop program running, opening the port, writing to the equipment, getting a response, and closing the port. It was up to about 180 sucessful cycles (in a row -- it will stop if it fails). I think it's a hardware problem. :) Hmm, keep the port open. One bad thing that can happen is that if you don;t keep the port open then another program running on the box and nip in and claim ownership of the port. I agree with Peter, I never relinquish the port in code unless I have a reason to (ie shutdown or chnaging the COM port I'm using). I doubt that it is a hardware problem on your device as the RS232 tandard (I prefer to call it a rumour) doesn't have any kind of RRP. Even if you are running RTS/CTS or XON/XOFF then you again shouldn't have a problem becuase once the data is sent.received then the lines should be back to normal. If you wish to test this and am not happy with writing C code to test it then maybe you could try it with something that doens;t use C code such as Java (with the javax.comm or rxtx extensions)? In none of my own serial-based programs (perhaps a few dozen such to date) have I ever opened and closed a port other than at startup and shutdown (just as your C++ program does). Unless you've got a good reason to do otherwise, if this solves your problem it's certainly the most direct approach to do so. One of the serial ports (there are actually two) is used to read some NMEA sentences from a GPS. It is only rarely read. If it is also opened when the program starts and kept open would you just dump the buffer and then read to get the most current info? What happens when the buffer fills up? The main port is just commands sent, responses received kind of traffic. PySerial doesn;t have any kind of event firing to notify you when data is available. The way I get round this is to have a loop polling (in a seperate thread) to see if any data is available (it's a method on the interface), then read all the data in and fire this off to my listeners/observers with the read data. That way your buffers will not fill up. I would also do that on your other port as well to give you a common way of receiving data. I did this and then started downloading random stuff of wiki and sending the data from one serial port to another in huge chunks with no problems. I'd write a C extension to do the serial stuff, but I don't know a thing about Windows programming. Thanks! I wouldn't bother as well - PySerial works fine for me, as I mentioned the only thing I don;t like is no evetn firing when data is availabel but you can code around taht if you wish to. Cheers, Neil -- Neil Benn Senior Automation Engineer Cenix BioScience BioInnovations Zentrum Tatzberg 47 D-01307 Dresden Germany Tel : +49 (0)351 4173 154 e-mail : [EMAIL PROTECTED] Cenix Website : http://www.cenix-bioscience.com -- http://mail.python.org/mailman/listinfo/python-list
Re: [path-PEP] Path inherits from basestring again
Tony Meyer wrote: Would you really choose this: p = Path() / build / a / very / very / long / path Over this: p = Path(os.path.join(build, a, very, very, long, path)) I'd choose neither, because both are contrived examples (who builds paths out of six literals like that?) and the second one is not something anyone would want, since it mixes Paths and old-style os.path.join() calls. We're talking at this point about how Path should work, not whether it's preferable to os.path.join, even though that was really the point of Reinhard's original post. Given that, then, of the following two I would prefer the first one, slightly: p = somePath / user.getFolder() / 'archive' / oldPath + '.bak' p = somePath.joinpath(user.getFolder(), 'archive', oldPath + '.bak') ? A saving of six characters, and the second one is a lot clearer. It's not a question of saving characters, but readability which, as you've said, is a matter of opinion. I find the former more readable. Somewhat. Not enough to make a big deal about it. I can live with the latter, but as *someone who has used the path module already* I can only say that you might want to try it for a few months before condemning the approach using / as being unacceptable. -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: os._exit vs. sys.exit
Andrew Dalke wrote: sys.exit() is identical to raise SystemExit(). It raises a Python exception which may be caught at a higher level in the program stack. And which *is* caught at the highest levels of threading.Thread objects (which Timer is based on). Exceptions raised (and caught or not) in a Thread do not have any effect on the main thread, and thus don't affect the interpreter as a whole. -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: pySerial Windows write problem
Bob Greschke wrote: Peter Hansen [EMAIL PROTECTED] wrote in message I'd call it very unusual (in my experience) to have a program open and close a serial port repeatedly. One of the serial ports (there are actually two) is used to read some NMEA sentences from a GPS. It is only rarely read. If it is also opened when the program starts and kept open would you just dump the buffer and then read to get the most current info? What happens when the buffer fills up? The main port is just commands sent, responses received kind of traffic. Generally, yes, you just dump data received up to the point you are about to send a new request (if this is a request/response type of thing). PySerial has a .flush() method of some kind I believe, or you can just loop as long as inWaiting() isn't False. If you aren't using hardware or software handshaking, then the buffer filling up is a non-issue for you or the sender. If you're using handshaking, then you do have to keep the buffer from filling. Pretty much all my interesting code runs the PySerial stuff in a separate thread, reading whenever data is available, and (this is a simplification) posting it to a Queue which the main thread can read from as required. In that scenario, you could just have a flag that causes the receive thread to stop posting stuff to the Queue where you currently have close the port to prevent data being seen. I don't recall: is NMEA 0183 asynchronous? Messages can be sent by the GPS even when you didn't ask for one explicitly? If so, then it's possible there are problems even with your current approach: what if you open the port halfway through a packet, and receive only the last few bytes? If it's synchronous (data sent only in response to your requests), then none of this is an issue since there will be no traffic unless you ask for it, so the serial port will be idle between uses. -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: os._exit vs. sys.exit
Peter Hansen [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Andrew Dalke wrote: sys.exit() is identical to raise SystemExit(). It raises a Python exception which may be caught at a higher level in the program stack. And which *is* caught at the highest levels of threading.Thread objects (which Timer is based on). Exceptions raised (and caught or not) in a Thread do not have any effect on the main thread, and thus don't affect the interpreter as a whole. -Peter Thanks for the clarifications. One more question, can I catch this exception in my main thread and then do another sys.exit() to kill the whole process? Apparently sys.exit() allows the program to clean up resources and exit gracefully, while os._exit() is rather abrupt. Bryan -- http://mail.python.org/mailman/listinfo/python-list
writing a web client
I want to write a program which will automatically login to my ISPs website, retrieve data and do some processing. Can this be done? Can you point me to any example python programs which do similar things? Regards, Ajar -- http://mail.python.org/mailman/listinfo/python-list
Async PySerial (was Re: pySerial Windows write problem)
Neil Benn wrote: PySerial doesn;t have any kind of event firing to notify you when data is available. The way I get round this is to have a loop polling (in a seperate thread) to see if any data is available (it's a method on the interface), then read all the data in and fire this off to my listeners/observers with the read data. On that note, I've got a preliminary version of something I call Bent (think slightly Twisted) which is focused for now on providing an asynchronous version of PySerial which is designed around the event-driven model instead of its current polled scheme. It shares a number of features with the Twisted-based PySerial port (also done by Chris Liechti, for the Twisted team, judging by the code comments) but doesn't require one to adopt the whole Twisted framework. Basically it provides you with the equivalent of one reactor per thread for PySerial stuff. On Win32 only for now. There are other limitations too. Not ready for prime time. On the plus side, it's been letting me convert my serial stuff to be fully event-driven and with the resulting much lower latencies and better CPU efficiency, while keeping my code more traditional instead of having to force it entirely into the Twisted point of view. Just an FYI. And, obviously, to hear back from those interested. I don't know if this is something that should be contributed to the PySerial project (it's more of a rewrite than an add-on), or set up as a new project, or passed around quietly behind the scenes for a while. No docs yet, no contrived examples (but various pieces of working code in real daily use). Did I mention it wasn't ready for prime time? If you've ever been annoyed having to do .read(1) to get characters one at a time in PySerial, or .read(100) with a timeout, or whatever, this might be of interest to you... -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: os._exit vs. sys.exit
Bryan wrote: Thanks for the clarifications. One more question, can I catch this exception in my main thread and then do another sys.exit() to kill the whole process? Not as such. Exceptions can be caught only in the thread in which they are raised. There are tricky techniques to change this, but they would have to rely on things which are themselves sufficient for what you are trying to do. Apparently sys.exit() allows the program to clean up resources and exit gracefully, while os._exit() is rather abrupt. What does the main thread do while the other thread is running? If it's just waiting for it and other threads to finish/fail, then you need to have some kind of loop that waits for all other threads to not respond True to .isAlive(), and/or you need to add a threading.Event or something like it which the main thread can wait on or poll to see whether a thread has caught an exception, *and* you need to make all those other threads catch their own exceptions at the top levels of their run() method, and to set that Event object if SystemExit is caught. Or related techniques. If that's not enough ideas for you to figure something out, please provide more detail and we can come up with something more specific and appropriate. For example, do you want to exit the app only if a thread raises SystemExit, or would other exceptions result in the same effect? -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: writing a web client
Ajar wrote: I want to write a program which will automatically login to my ISPs website, retrieve data and do some processing. Can this be done? Can you point me to any example python programs which do similar things? Regards, Ajar Very easily. Have a look at my article on the ``urllib2`` module. http://www.voidspace.org.uk/python/articles.shtml#http You may need to use ClientCookie/cookielib to handle cookies and may have to cope with BASIC authentication. There are also articles about both of these as well. If you want to handle filling in forms programattically then the module ClientForm is useful (allegedly). Best Regards, Fuzzyman http://www.voidspace.org.uk/python -- http://mail.python.org/mailman/listinfo/python-list
Re: Async PySerial (was Re: pySerial Windows write problem)
I use PySerial in a 16 line data collection system with LOTS of threads, and yes am frustrated by read(). This sounds excellent, keep us updated. BTW, haven't done any event driven Python except Tkinter. Would this a class library which would let you define an event and a handler? Do you have a one line code example? Thanks. Peter Hansen wrote: Neil Benn wrote: PySerial doesn;t have any kind of event firing to notify you when data is available. The way I get round this is to have a loop polling (in a seperate thread) to see if any data is available (it's a method on the interface), then read all the data in and fire this off to my listeners/observers with the read data. On that note, I've got a preliminary version of something I call Bent (think slightly Twisted) which is focused for now on providing an asynchronous version of PySerial which is designed around the event-driven model instead of its current polled scheme. It shares a number of features with the Twisted-based PySerial port (also done by Chris Liechti, for the Twisted team, judging by the code comments) but doesn't require one to adopt the whole Twisted framework. Basically it provides you with the equivalent of one reactor per thread for PySerial stuff. On Win32 only for now. There are other limitations too. Not ready for prime time. On the plus side, it's been letting me convert my serial stuff to be fully event-driven and with the resulting much lower latencies and better CPU efficiency, while keeping my code more traditional instead of having to force it entirely into the Twisted point of view. Just an FYI. And, obviously, to hear back from those interested. I don't know if this is something that should be contributed to the PySerial project (it's more of a rewrite than an add-on), or set up as a new project, or passed around quietly behind the scenes for a while. No docs yet, no contrived examples (but various pieces of working code in real daily use). Did I mention it wasn't ready for prime time? If you've ever been annoyed having to do .read(1) to get characters one at a time in PySerial, or .read(100) with a timeout, or whatever, this might be of interest to you... -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: why functions in modules need 'global foo' for integer foo but not dictionary foo?
[EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] At top of a module I have an integer like so... foo = 4 In a function in that module I know I need to do 'global foo' to get at the value 4. Actually, you don't need a global foo statement to _access_ the value. You do need a global foo to _rebind_ the value. ... IIRC, for dictionaries you DO NOT have this issue? Why this scope problem with integers but not dictionaries? Telling an object to mutate itself doesn't rebind the object. so, if you wanted to say: foo = 5 and have it work at the module level, you'd need a global foo statement, while foo[bar] = spam doesn't. The dictionary foo isn't rebound, all that's happening is that its state is being changed (that is, the key and value is being added to the dictionary). HTH John Roth Chris -- http://mail.python.org/mailman/listinfo/python-list
ANN: python-ldap-2.0.9
Find a new release of python-ldap: http://python-ldap.sourceforge.net/ python-ldap provides an object-oriented API to access LDAP directory servers from Python programs. It mainly wraps the OpenLDAP 2.x libs for that purpose. Additionally it contains modules for other LDAP-related stuff (e.g. processing LDIF, LDAPURLs and LDAPv3 schema). Released 2.0.9 2005-07-28 Changes since 2.0.8: Modules/ * Removed __doc__ strings from ldapcontrol.c to fix build problems with Python versions 2.2 and earlier. -- http://mail.python.org/mailman/listinfo/python-list
Re: writing a web client
fuzzy's urllib2 info is excellent. The other way peopel snarf stuff over HTTP and FTP is using 'wget' or 'libcurl'. THere's http://pycurl.sourceforge.net/ -- http://mail.python.org/mailman/listinfo/python-list
Re: functions without parentheses
Steven D'Aprano wrote: On Fri, 29 Jul 2005 06:37:52 +, Bengt Richter wrote: I suggested in a previous thread that one could support such a syntax by supporting an invisible binary operator between two expressions, so that examine string translates to examine.__invisbinop__(string) if examine as an expression evaluates to an object that has a __invisbinop__ method. Why would you want to? My best guest is that the OP uses VB, where you can do that. I personally hate this feature because it just makes me do a lot of mistakes. ie: In VB you can do: fooFunction fooParameter but if you want to assign this to a variable you **must** use this: fooVer = fooFunction(fooParaMeter) I really get confused because I automatically use the braces. Regards, Josef -- http://mail.python.org/mailman/listinfo/python-list
Re: Friend wants to learn python
EnderLocke wrote: I have a friend who wants to learn python programming. I learned off the internet and have never used a book to learn it. What books do you recommend? Any suggestions would be appreciated. I have just uploaded a podcast specifically about which tutorials and books might be best for newbies to Python, depending on their background. It can be reached at http://www.awaretek.com/python/index.html Ron -- http://mail.python.org/mailman/listinfo/python-list
Re: Filtering out non-readable characters
Adriaan Renting wrote: def StripNoPrint(self, S): from string import printable return .join([ ch for ch in S if ch in printable ]) Adriaan Renting| Email: [EMAIL PROTECTED] ASTRON | Phone: +31 521 595 217 P.O. Box 2 | GSM: +31 6 24 25 17 28 NL-7990 AA Dwingeloo | FAX: +31 521 597 332 The Netherlands| Web: http://www.astron.nl/~renting/ MKoool [EMAIL PROTECTED] 07/16/05 2:33 AM I have a file with binary and ascii characters in it. I massage the data and convert it to a more readable format, however it still comes up with some binary characters mixed in. I'd like to write something to just replace all non-printable characters with '' (I want to delete non-printable characters). I am having trouble figuring out an easy python way to do this... is the easiest way to just write some regular expression that does something like replace [^\p] with ''? Or is it better to go through every character and do ord(character), check the ascii values? What's the easiest way to do something like this? thanks I'd consider using the string's translate() method for this. Provide it with two arguments: the first should be a string of the 256 ordinals from 0 to 255 (because you won't be changing any characters, so you need a translate table that effects the null transformation) and the second argument should a string containing all the characters you want to remove. So tt = .join([chr(i) for i in range(256)]) generates the null translate table quite easily. Then import string ds = tt.translate(tt, string.printable) sets ds to be all the non-printable characters (according to the string module, anyway). Now you should be able to remove the non-printable characters from s by writing s = s.translate(tt, ds) regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Ten Essential Development Practices
[Steve Holden] If I canpoint out the obvious, the output from import this *is* headed The Zen of Python, so clearly it isn;t intended to be universal in its applicability. [Michael Hudson] It's also mistitled there, given that it was originally posted as '19 Pythonic Theses' and nailed to, erm, something. 'Twas actually posted as 20 Pythonic Theses, although most times I count them I find19. Nevertheless, that there are in fact 20 was channeled directly from Guido's perfectly Pythonic mind, so 20 there must be. I suspect he withheld one -- although, as some argue, it's possible he thinks in base 9.5, that just doesn't seem Pythonic to me. -- http://mail.python.org/mailman/listinfo/python-list
Re: poplib.POP3.list() returns extra value?
According to Jeff Epler [EMAIL PROTECTED]: I'd consider it a doc bug too. If you feel comfortable doing it, dive in and improve the documentation of poplib. Submitting a patch to the patch tracker on sf.net/projects/python is probably the best way to do this, if you have the necessary knowledge of cvs to produce a patch. Knowledge: yes; Time: maybe. If someone else gets there first, I won't be offended :-) Thanks for confirming... Steve -- Steve Greenland The irony is that Bill Gates claims to be making a stable operating system and Linus Torvalds claims to be trying to take over the world. -- seen on the net -- http://mail.python.org/mailman/listinfo/python-list
Re: Ten Essential Development Practices
[Dan Sommers] Ok, not universal. But as usual, Zen is not easily nailed to a tree. Was Tim writing about developing Python itself, or about developing other programs with Python? Tim was channeling Guido, and that's as far as our certain knowledge can go. It _seems_ reasonable to believe that since Guido's mind is, by definition, perfectly Pythonic, any truth channeled from it necessarily applies to all things Pythonic. nevertheless-we-interpret-the-gods-at-our-peril-ly y'rs - tim -- http://mail.python.org/mailman/listinfo/python-list
Re: On fighting fire with fire...
Asad Habib wrote: Well, even if you are a hobbyist, that does not excuse you from being civil. After all, we are all humans beings that deserve to be treated with respect. Professional, hobbyist, vagabond, ogre, instigator, troll ... THERE IS NO EXCUSE ... please treat others with respect. I really don't think we're disagreeing. I agree that it is inappropriate, regardless of position or experience, to be rude, hostile, or vitriolic on this newsgroup. And it should be made clear to people who are, that it isn't appropriate. However, in doing so, it is also inappropriate to become rude, hostile, or vitriolic oneself - as Skip mentioned in the post that started all this, the appropriate way of handling it is by demonstrating proper behavior yourself. If, for whatever reason, you do find the desire to be rude, hostile, or vitriolic, you can satisfy your urge by writing out your rant and then deleting it. You'll feel better by getting it off your chest, and you won't have escalated anything. The reason I point out the hobbyist issue is to disabuse people of the misperception that everyone on this list is adhering to some professional code of conduct that they should be ostracized for breaching. This isn't to excuse their behavior - I'm just pointing out that people are coming from different backgrounds, and that we should treat them with consideration and respect, even when they aren't showing us any. -- http://mail.python.org/mailman/listinfo/python-list
Re: Ten Essential Development Practices
In article [EMAIL PROTECTED], Dan Sommers [EMAIL PROTECTED] wrote: Was Tim writing about developing Python itself, or about developing other programs with Python? Yes. (C'mon, didja really expect any other answer?) -- Aahz ([EMAIL PROTECTED]) * http://www.pythoncraft.com/ The way to build large Python applications is to componentize and loosely-couple the hell out of everything. -- http://mail.python.org/mailman/listinfo/python-list
Re: Ten Essential Development Practices
snip although, as some argue, it's possible [GvR] thinks in base 9.5, that just doesn't seem Pythonic to me. +1 QOTW Peace Bill Mill [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Ten Essential Development Practices
I am new to Python. I tried it out and think it is fantastic. I really loved this from import this statements: There should be one-- and preferably only one --obvious way to do it. But this not true of Python. GUI, Web development, Application Framework - it is shambles. It is so frustrating for a person who comes from a well designed environment / framework like Delphi. -Quote - Phillip J. Eby from dirtsimple.org Python as a community is plagued by massive amounts of wheel-reinvention. The infamous web framework proliferation problem is just the most egregious example. Why is Python blessed with so much reinvention? Because it's often cheaper to rewrite than to reuse. Python code is easy to write, but hard to depend on. You pretty much have to: 1. limit yourself to platforms with a suitable packaging system, 2. bundle all your dependencies into your distribution, or 3. make your users do all the work themselves Ouch. No wonder rewriting looks easier. The only way to stop this trend is to make it easier to reuse than to rewrite, which has been my mission with setuptools and EasyInstall -UnQuote My organisation writes products for Small and Medium Enterprises. We are using Delphi, we want to do more web based and Linux solutions, so I was evaluating Python, but even though I love the language and will probably do hobby programming using the language, I wouldnt really recommend our organisation to plan and execute a tranisition. We have been around a while and we have planned and done transitions from Clipper to FoxproW to VB to Delphi. From what I understand Database access was in similar shambles in Python but a SIG took up the task and made some decisions which has now streamlined database access in Python. I really would love to have a Python where TOOWTDI Is there some place to discuss topics like this? Is this the right place? -- DarkCowherd -- http://mail.python.org/mailman/listinfo/python-list
Re: Ten Essential Development Practices
Dark Cowherd wrote: GUI, Web development, Application Framework - it is shambles. Yeah, I agree. When I finally make that GUI application I still don't know whether I am going to use wx or PyGTK. Is there some place to discuss topics like this? Is this the right place? Sure, although you might want to start a new thread. ;) -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: can list comprehensions replace map?
Peter Otten wrote: Combining your clever and your elegant approach to something fast (though I'm not entirely confident it's correct): def fillzip(*seqs): def done_iter(done=[len(seqs)]): done[0] -= 1 if not done[0]: return while 1: yield None seqs = [chain(seq, done_iter()) for seq in seqs] return izip(*seqs) Ohh, that's pretty neat passing in 'done' via a mutable default argument. It took me a bit to even realize why it does work. :) Could make it one line shorter with from itertools import chain, izip, repeat def fillzip(*seqs): def done_iter(done=[len(seqs)]): done[0] -= 1 if not done[0]: return [] return repeat(None) seqs = [chain(seq, done_iter()) for seq in seqs] return izip(*seqs) Go too far on that path and the code starts looking likg from itertools import chain, izip, repeat forever, table = repeat(None), {0: []}.get def fillzip(*seqs): def done_iter(done=[len(seqs)]): done[0] -= 1 return table(done[0], forever) return izip(*[chain(seq, done_iter()) for seq in seqs]) Now add the performance tweak def done_iter(done=[len(seqs)], forever=forever, table=table) Okay, I'm over it. :) Andrew [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Ten Essential Development Practices
Dark Cowherd wrote: There should be one-- and preferably only one --obvious way to do it. But this not true of Python. GUI, Web development, Application Framework - it is shambles. It is so That's because there is no *obvious* way to do these. -Quote - Phillip J. Eby from dirtsimple.org Python as a community is plagued by massive amounts of wheel-reinvention. The infamous web framework proliferation problem is just the most egregious example. In stark contrast to Java, where everybody uses standard components like JSP, Struts, Tapestry, JSF, Spring, ... Daniel -- http://mail.python.org/mailman/listinfo/python-list
Wheel-reinvention with Python (was: Ten Essential Development Practices)
Hallöchen! Michael Hoffman [EMAIL PROTECTED] writes: Dark Cowherd wrote: GUI, Web development, Application Framework - it is shambles. Yeah, I agree. When I finally make that GUI application I still don't know whether I am going to use wx or PyGTK. I agree, too, although I can only talk about GUI toolkits. At first one thinks well, perfect, I have the choice between four great GUI systems. However, except for very special demands, there is no clear winner. You start learning one, and immediately wonder whether the other might be better. Although it sounds paradoxical, this can be quite frustrating. After all, most of us don't have the energy or motivation to test all candidates thoroughly. Besides, development resources are shared between all projects. This is especially sad with regard to IDEs. There are even more IDEs/dialog editors/widget builders than Toolkits, none of them being mature. Is there some place to discuss topics like this? Is this the right place? Sure, although you might want to start a new thread. ;) At least a new subject ... Tschö, Torsten. -- Torsten Bronger, aquisgrana, europa vetus -- http://mail.python.org/mailman/listinfo/python-list
Re: On fighting fire with fire...
I was explaining the difference between irony and sarcasm to my daughter just the other day. It was nice of Asad to provide us with such a besutiful example. Not that I'm sure that was his intent... Jeff -- http://mail.python.org/mailman/listinfo/python-list
Re: multiple inheritance super()
Sion Arrowsmith That way lies Java well, no, a dynamic language such as Python with the possibility of adding methods on the fly and metaclasses could live pretty well without multiple inheritance. There would be no real loss of power and hopefully less monstruosities such a Zope 2. But maybe this is just wishful thinking ... Michele Simionato -- http://mail.python.org/mailman/listinfo/python-list
Re: Wheel-reinvention with Python
Torsten Bronger wrote: Hallöchen! Michael Hoffman [EMAIL PROTECTED] writes: Dark Cowherd wrote: GUI, Web development, Application Framework - it is shambles. Yeah, I agree. When I finally make that GUI application I still don't know whether I am going to use wx or PyGTK. I agree, too, although I can only talk about GUI toolkits. At first one thinks well, perfect, I have the choice between four great GUI systems. However, except for very special demands, there is no clear winner. You start learning one, and immediately wonder whether the other might be better. Although it sounds paradoxical, this can be quite frustrating. After all, most of us don't have the energy or motivation to test all candidates thoroughly. The PEP process can be quite good for whittling this down and getting the best of all worlds. For example, the current stdlib csv module was based on three previous modules[1]. We only really need one. However, since GUI toolkits are so complicated, I wonder if they will ever be subject to this process. [1] http://www.python.org/peps/pep-0305.html#existing-modules -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: Wheel-reinvention with Python (was: Ten Essential Development Practices)
The choice is GUI toolkits is largely seperate from Python. Consider that they are just bindings to libraries that are developed completely seperate of the language. GUI is should be seperate from the language, and thus not bound to same expectations and desires as elements of the language itself. Unless, of course, you're VB or Java.. On 7/29/05, Torsten Bronger [EMAIL PROTECTED] wrote: Hallöchen! Michael Hoffman [EMAIL PROTECTED] writes: Dark Cowherd wrote: GUI, Web development, Application Framework - it is shambles. Yeah, I agree. When I finally make that GUI application I still don't know whether I am going to use wx or PyGTK. I agree, too, although I can only talk about GUI toolkits. At first one thinks well, perfect, I have the choice between four great GUI systems. However, except for very special demands, there is no clear winner. You start learning one, and immediately wonder whether the other might be better. Although it sounds paradoxical, this can be quite frustrating. After all, most of us don't have the energy or motivation to test all candidates thoroughly. Besides, development resources are shared between all projects. This is especially sad with regard to IDEs. There are even more IDEs/dialog editors/widget builders than Toolkits, none of them being mature. Is there some place to discuss topics like this? Is this the right place? Sure, although you might want to start a new thread. ;) At least a new subject ... Tschö, Torsten. -- Torsten Bronger, aquisgrana, europa vetus -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Ten Essential Development Practices
On 7/29/05, Dark Cowherd [EMAIL PROTECTED] wrote: I am new to Python. I tried it out and think it is fantastic. Congrats and have fun learning all there is to learn. I really loved this from import this statements: There should be one-- and preferably only one --obvious way to do it. But this not true of Python. GUI, Web development, Application Framework - it is shambles. It is so frustrating for a person who comes from a well designed environment / framework like Delphi. Well, consider also that all these frameworks and similar such projects are not Python the Language, and as such are allowed to have a few more ways to do it. There is movement toward convergence on many fronts, with efforts such as WSGI and the anygui package. I don't believe there should be only one way to do a thing at the beginning, and in many ways we are still at the beginning of many areas, but we need to spread our collective tentacles into many ideas and try what works. What is great about Python is that after some time with works being quite seperate, such as the many implementations of interfaces and adaptation systems, we are able to converge them, as is currently proposed and likely to occure soon. We need to test out many things and get a feel for the use of something before we can decide what the one way to do it should be. Python makes it easy to test all the different waters, and then to combine them into the best solution, when the community is ready to do so. My organisation writes products for Small and Medium Enterprises. We are using Delphi, we want to do more web based and Linux solutions, so I was evaluating Python, but even though I love the language and will probably do hobby programming using the language, I wouldnt really recommend our organisation to plan and execute a tranisition. Thats a shame, really. We have been around a while and we have planned and done transitions from Clipper to FoxproW to VB to Delphi. From what I understand Database access was in similar shambles in Python but a SIG took up the task and made some decisions which has now streamlined database access in Python. I really would love to have a Python where TOOWTDI Is there some place to discuss topics like this? Is this the right place? -- DarkCowherd -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: can list comprehensions replace map?
Peter Otten wrote: def fillzip(*seqs): def done_iter(done=[len(seqs)]): done[0] -= 1 if not done[0]: return while 1: yield None seqs = [chain(seq, done_iter()) for seq in seqs] return izip(*seqs) Can I play too? How about: import itertools def fillzip(*seqs): def Nones(countactive=[len(seqs)]): countactive[0] -= 1 while countactive[0]: yield None seqs = [itertools.chain(seq, Nones()) for seq in seqs] return itertools.izip(*seqs) --Scott David Daniels [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Wheel-reinvention with Python (was: Ten Essential Development Practices)
On Fri, 2005-07-29 at 17:59 +0200, Torsten Bronger wrote: Hallöchen! Michael Hoffman [EMAIL PROTECTED] writes: Dark Cowherd wrote: GUI, Web development, Application Framework - it is shambles. Yeah, I agree. When I finally make that GUI application I still don't know whether I am going to use wx or PyGTK. I agree, too, although I can only talk about GUI toolkits. At first one thinks well, perfect, I have the choice between four Four? 1. wx 2. PyGTK 3. Tk (Are you including this one even?) 4. ??? Of the few I can think of, only one would qualify as great. :) wink great GUI systems. However, except for very special demands, there is no clear winner. You start learning one, and immediately wonder whether the other might be better. Although it sounds paradoxical, this can be quite frustrating. After all, most of us don't have the energy or motivation to test all candidates thoroughly. Besides, development resources are shared between all projects. This is especially sad with regard to IDEs. There are even more IDEs/dialog editors/widget builders than Toolkits, none of them being mature. Is there some place to discuss topics like this? Is this the right place? Sure, although you might want to start a new thread. ;) At least a new subject ... Tschö, Torsten. -- Torsten Bronger, aquisgrana, europa vetus -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: can list comprehensions replace map?
Andrew Dalke wrote: Peter Otten wrote: Combining your clever and your elegant approach to something fast (though I'm not entirely confident it's correct): def fillzip(*seqs): def done_iter(done=[len(seqs)]): done[0] -= 1 if not done[0]: return while 1: yield None seqs = [chain(seq, done_iter()) for seq in seqs] return izip(*seqs) Ohh, that's pretty neat passing in 'done' via a mutable default argument. It took me a bit to even realize why it does work. :) Though I would never have come up with it, were it not for the juxtaposition of your two variants (I initially disliked the first and tried to improve on the second), it is an unobvious merger :) It's a bit fragile, too, as Could make it one line shorter with from itertools import chain, izip, repeat def fillzip(*seqs): def done_iter(done=[len(seqs)]): done[0] -= 1 if not done[0]: return [] return repeat(None) seqs = [chain(seq, done_iter()) for seq in seqs] return izip(*seqs) that won't work because done_iter() is now no longer a generator. In effect you just say seqs = [chain(seq, repeat(None)) for seq in seqs[:-1]] + [chain(seq[-1], [])] I tried class Done(Exception): pass pad = repeat(None) def fillzip(*seqs): def check(active=[len(seqs)]): active[0] -= 1 if not active[0]: raise Done # just to turn check() into a generator if 0: yield None seqs = [chain(seq, check(), pad) for seq in seqs] try for item in izip(*seqs): yield item except Done: pass to be able to use the faster repeat() instead of the while loop, and then stared at it for a while -- in vain -- to eliminate the for item... loop. If there were a lazy ichain(iter_of_iters) you could tweak check() to decide whether a repeat(None) should follow it, but I'd rather not ask Raymond for that particular addition to the itertools. Now add the performance tweak def done_iter(done=[len(seqs)], forever=forever, table=table) Okay, I'm over it. :) Me too. I think. For now... Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Ten Essential Development Practices
Michael Hoffman wrote: He spends so much space on Create Consistent Command-Line Interfaces, a section that, in Python, could be replaced with a simple Use optparse. In Perl there's also the equivalent of optparse, but where does it guarantee that you'll use consistent name options and design a good interface? I think he's point is much broader than parsing input from the command line. -- Jorge Godoy [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Wheel-reinvention with Python (was: Ten Essential Development Practices)
Jeremy Moles wrote: Four? 1. wx 2. PyGTK 3. Tk (Are you including this one even?) 4. ??? PyQt / PyKDE. Of the few I can think of, only one would qualify as great. :) The fourth one? ;-) -- Jorge Godoy [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Ten Essential Development Practices
On 29 Jul 2005 07:45:33 -0700, [EMAIL PROTECTED] (Aahz) wrote: In article [EMAIL PROTECTED], Dan Sommers [EMAIL PROTECTED] wrote: Was Tim writing about developing Python itself, or about developing other programs with Python? Yes. (C'mon, didja really expect any other answer?) It was a rhetorical question. :-) Regards, Dan -- Dan Sommers http://www.tombstonezero.net/dan/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Wheel-reinvention with Python (was: Ten Essential Development Practices)
On Fri, 2005-07-29 at 14:19 -0300, Jorge Godoy wrote: Jeremy Moles wrote: Four? 1. wx 2. PyGTK 3. Tk (Are you including this one even?) 4. ??? PyQt / PyKDE. Ah! Can't believe I forgot that one! :) Of the few I can think of, only one would qualify as great. :) The fourth one? ;-) Hehe. :) I was going to say PyGTK... but in all honesty I'm just a GTK fanboy who hasn't really even TRIED anything else. I remember experimenting a few years back with compiled Qt apps in C/C++, but the whole notion of a MOC just scared me--not that I knew enough back then to really label it as a bad thing, nor do I now. :) -- Jorge Godoy [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Wheel-reinvention with Python (was: Ten Essential DevelopmentPractices)
On Fri, Jul 29, 2005 at 01:18:10PM -0400, Jeremy Moles wrote: On Fri, 2005-07-29 at 17:59 +0200, Torsten Bronger wrote: one thinks well, perfect, I have the choice between four Four? 1. wx 2. PyGTK 3. Tk (Are you including this one even?) 4. ??? Well, QT at least. And sure there is Tk. -- jk -- http://mail.python.org/mailman/listinfo/python-list
Re: Ten Essential Development Practices
Jorge Godoy wrote: Michael Hoffman wrote: He spends so much space on Create Consistent Command-Line Interfaces, a section that, in Python, could be replaced with a simple Use optparse. In Perl there's also the equivalent of optparse, but where does it guarantee that you'll use consistent name options and design a good interface? I think he's point is much broader than parsing input from the command line. True, but a lot of his point *is* parsing input from the command line. Consider the following points paraphrased from his article: * Don't mix multiple ways of specifying options. (Solved by optparse) * If a flag expects an associated value, allow an optional = between the flag and the value. (Solved by optparse) * Allow single-letter options to be bundled after a single dash. (Solved by optparse) * Always allow -- as a file list marker. (Solved by optparse) And a lot of the other points are things that are made much, much, simpler by optparse, to the point that they become somewhat obvious. -- Michael Hoffman -- http://mail.python.org/mailman/listinfo/python-list
Re: writing a web client
thats pretty cool, could someone post a example program of a python web-based program? -- http://mail.python.org/mailman/listinfo/python-list
Re: writing a web client
thats pretty cool, could someone post a example program of a python web-based program? -- http://mail.python.org/mailman/listinfo/python-list
Hiding
Well, im not no expert on the python programming language but i just wanted to know if there was a quick way to hide certain things when programming in python. Such as, i wanted some music or sound effects with my python program. So, i type... print Music is by blah blah music-file = open(file containing the music hide(music-file) thats wat im looking for, something i can hide the opening of files because if i open that file, Windows Media Player will open and i would like to hide that. And advise -- http://mail.python.org/mailman/listinfo/python-list
Re: can list comprehensions replace map?
Me: Could make it one line shorter with from itertools import chain, izip, repeat def fillzip(*seqs): def done_iter(done=[len(seqs)]): done[0] -= 1 if not done[0]: return [] return repeat(None) seqs = [chain(seq, done_iter()) for seq in seqs] return izip(*seqs) Peter Otten: that won't work because done_iter() is now no longer a generator. In effect you just say seqs = [chain(seq, repeat(None)) for seq in seqs[:-1]] + [chain(seq[-1], [])] It does work - I tested it. The trick is that izip takes iter() of the terms passed into it. iter([]) - an empty iterator and iter(repeat(None)) - the repeat(None) itself. 'Course then the name should be changed. Andrew [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: can list comprehensions replace map?
Scott David Daniels wrote: Can I play too? How about: Sweet! Andrew [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Dr. Dobb's Python-URL! - weekly Python news and links (Jul 29)
QOTW: Guido has marked the trail; don't ignore the signs unless you really know where you're going. - Raymond Hettinger 'Proverbs 28:14 JPS Happy is the man that feareth alway; but he that hardeneth his heart shall fall into evil. Obviously an exhortation to not ignore raised exceptions with except: pass.' - Robert Kern Jason Orendorff's path module is a popular alternative to the build in os.path and shutil modules. Michael Hoffman and Reinhold Birkenfeld are working on a PEP suggesting that it be included in the standard library: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/1f5bcb67c4c73f15 http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/df1b647a0f103640 Java has nearly as many web frameworks as Python, but you can run any of them on any of the Java web application servers because they are all built on the Java Servlet specification. PEP 333, the Python Web Server Gateway Interface, aims to bring something similar to the world of Python: http://www.python.org/peps/pep-0333.html A short but sweet day-of-the-month suffix generator from John Machin: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/904fa627890c85dd Thanos Tsouanas wants access to an object's namespace dictionary: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/d5cc509d138e1701 David Isaac wants to avoid map(), but he wants a zip() function that runs to the length of the longest sequence. It's suggested that zip() should be able to do this, but Raymond Hettinger channels Guido and thinks that this would be a bad idea: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/265675b50fee8ec1 Tiny.be release four open source enterprise applications: http://lwn.net/Articles/145209/ Who needs Ten Essential Development Practices? We've got The Zen of Python: http://groups-beta.google.com/group/comp.lang.python/browse_thread/thread/c52d3c17f1ea9ec5 Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. For far, FAR more Python reading than any one mind should absorb, much of it quite interesting, several pages index much of the universe of Pybloggers. http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog http://www.planetpython.org/ http://mechanicalcat.net/pyblagg.html comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djqas_ugroup=comp.lang.python.announce Steve Bethard, Tim Lesher, and Tony Meyer continue the marvelous tradition early borne by Andrew Kuchling, Michael Hudson and Brett Cannon of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Cetus collects Python hyperlinks. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to
Re: can list comprehensions replace map?
Andrew Dalke wrote: Me: Could make it one line shorter with from itertools import chain, izip, repeat def fillzip(*seqs): def done_iter(done=[len(seqs)]): done[0] -= 1 if not done[0]: return [] return repeat(None) seqs = [chain(seq, done_iter()) for seq in seqs] return izip(*seqs) Peter Otten: that won't work because done_iter() is now no longer a generator. In effect you just say seqs = [chain(seq, repeat(None)) for seq in seqs[:-1]] + [chain(seq[-1], [])] It does work - I tested it. The trick is that izip takes iter() of the terms passed into it. iter([]) - an empty iterator and iter(repeat(None)) - the repeat(None) itself. Seems my description didn't convince you. So here's an example: from itertools import chain, izip, repeat def fillzip(*seqs): ... def done_iter(done=[len(seqs)]): ... done[0] -= 1 ... if not done[0]: ... return [] ... return repeat(None) ... seqs = [chain(seq, done_iter()) for seq in seqs] ... return izip(*seqs) ... list(fillzip(range(6), range(3))) [(0, 0), (1, 1), (2, 2)] versus map(None, range(6), range(3)) [(0, 0), (1, 1), (2, 2), (3, None), (4, None), (5, None)] Now where's the typo? 'Course then the name should be changed. My variable names where ill-chosen to begin with. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: can list comprehensions replace map?
Scott David Daniels wrote: Can I play too? Not unless you buy the expensive but good-looking c.l.py gaming license which is only available trough me :) How about: import itertools def fillzip(*seqs): def Nones(countactive=[len(seqs)]): countactive[0] -= 1 while countactive[0]: yield None seqs = [itertools.chain(seq, Nones()) for seq in seqs] return itertools.izip(*seqs) You may be introducing a lot of extra tests in the while loop with the non-constant condition -- which in practice is fairly cheap, though. I'm willing to take the performance hit for the introduction of sane variable names alone... Peter -- http://mail.python.org/mailman/listinfo/python-list
Seeking Python expertise...
Hi, I found out about your Python community and thought you may be able to help me out. I am supporting an elitegroup of traders (more likethe Who's Whoon Wall Street). Wearebuildingalgorithmictrading modelsto analyze market movements, economicindicators, andvarious factors to predict and automate trade executions. We have quite a bit of successthusfarand are expanding into other electronic markets. Our core technologyteamwantstoadd 5-6 talented software engineers inthe next fewmonthsthat know Python well as we believe its a fast and elegant language. They also said that people with a strong background in math, statistics, modeling,chess, orvideogame developmentwill findwhat we are doingto be veryfascinating.Everything is real-time, and you get toapplywhat youknowand seethe resultsof your software modelsmaking money inthe market immediately. Are you the person we seek? Do you know anyone we can talk to about this? I am more than happy to forward a job description. We pay very well for top talents - attractive salary and triple digit percentage in bonusesfortopcontributors.And, we will relocatepeopleto Beverly Hill, CA (USA) from anywhere in the world. Also, the technology team also has a number of positions open for people with strong experience in concurrency, multi-threading, I/O, NIO, networking, operating systems internals, and performance optimization to work on our core trading platform (where we execute trades directly with the Exchange). People withexperience buildingserversthatcanhandlethousandsof simultaneous connections / concurrent users will be very helpful. Performance of our platform is very importantforus as we profit fromeven very small fluctuations in price. I don't know if people in this Pythoncommunity also know these technologies but I guess it doesn't hurt to ask. If you have a resume, I'd love to see it. If you can pass this to the right people, I'd really appreciate it. If youhave any questions, you can call me at 415-503-3998 or email meat [EMAIL PROTECTED]. Thanks so much for your help. Amanda Arnett-- http://mail.python.org/mailman/listinfo/python-list
Re: Hiding
Well, using the open function in Python doesn't launch any application associated with the file (such as Media Player). It just makes the contents of the file accessible to your Python code. Also, I think using file(C:\file.txt) is now preferred to open(C:\file.txt). To answer the specific question of how to play a music file in Python, search Google Groups for: pygame.mixer.music.load(music.mp3) That will bring up a useful thread. Note that you will need to install a module such as pygame or pymedia; they are not in the standard library. In general, I would also recommend some of the many good Python tutorials. Some are listed here: http://wiki.python.org/moin/BeginnersGuide Good luck! -- http://mail.python.org/mailman/listinfo/python-list
Re: Hiding
I can say with some certainty that opening a music file with open won't launch media player. If rather, you do os.system('musicfile.mp3') it will launch whatever application is associated with the file type .mp3. You can either automate Windows Media player or use pymedia to play such files. Here are some links that might be of interest: http://www.win32com.de/index.php?option=com_contenttask=viewid=141Itemid=259 http://pymedia.org/tut/ Larry Bates Jay wrote: Well, im not no expert on the python programming language but i just wanted to know if there was a quick way to hide certain things when programming in python. Such as, i wanted some music or sound effects with my python program. So, i type... print Music is by blah blah music-file = open(file containing the music hide(music-file) thats wat im looking for, something i can hide the opening of files because if i open that file, Windows Media Player will open and i would like to hide that. And advise -- http://mail.python.org/mailman/listinfo/python-list
Re: Filtering terminal commands on linux
Firstly, there's probably a better way to do whatever you're trying to do w.r.t cd/dvd burning. I'm not familiar with gear, but its webpage lists Batch file scripting capability as a feature, which suggests that you might be able to do what you want without parsing output intended for humans. There are also a multitude of command-line cd and dvd utilities for Linux which might be better for scripting. That said, it shouldn't be too hard to craft a regular expression that matches ANSI control sequences. Using http://www.dee.ufcg.edu.br/~rrbrandt/tools/ansi.html as a reference, here's how to do this for the first few control sequences... esc = '\x1B' start_control_sequence = esc + '[' Pn = r'\d+' # Numeric parameter Ps = '%s(;%s)*' % (Pn,Pn) # Selective parameter PL = Pn Pc = Pn control_sequences = [ PL + ';' + Pc + '[Hf]', # Cursor position Pn + '[ABCD]', # Cursor up|down|forward|backward 's',# Save cursor position 'u',# Restore cursor position '2J', # Erase display 'K',# Erase line Ps + 'm', # Set graphics mode '=' + Pn + '[hl]', # Set|Reset mode # ... etc ] match_ansi = re.compile(start_control_sequence + '(' + '|'.join(control_sequences) + ')') def strip_ansi(text): return match_ansi.sub('',text) (note: code is untested.. may contain typos) -- http://mail.python.org/mailman/listinfo/python-list
Help with Asyncore
Hello, I am using Asyncore.dispatcher around a socket (well call the wrapped version a channel). This channel is passed around to other objects. These objects call send on the channel. My question is, what do you do for writable and handle_write? Those seemed designed for channel-internal buffers. Should I also overwrite send and have the data appended to a buffer? If not, how should writable and handle_write be implemented? I'm not sure what to do here... Thank you in advance, -- Seth Nielson -- http://mail.python.org/mailman/listinfo/python-list
Re: Ten Essential Development Practices
Michael Hoffman wrote: True, but a lot of his point *is* parsing input from the command line. Consider the following points paraphrased from his article: * Don't mix multiple ways of specifying options. (Solved by optparse) * If a flag expects an associated value, allow an optional = between the flag and the value. (Solved by optparse) * Allow single-letter options to be bundled after a single dash. (Solved by optparse) * Always allow -- as a file list marker. (Solved by optparse) And a lot of the other points are things that are made much, much, simpler by optparse, to the point that they become somewhat obvious. Take a look at the Perl module, then. You'll see that all of these are also solved there automagically. I've stoped coding Perl almost 3 years ago, and even then I never had to write anything to parse command line input by hand. I suggest you take a look at Getopt::Long, at CPAN. http://search.cpan.org/~jv/Getopt-Long-2.34/ http://search.cpan.org/src/JV/Getopt-Long-2.34/README Be seeing you, -- Jorge Godoy [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Filtering out non-readable characters
Steve Holden wrote: tt = .join([chr(i) for i in range(256)]) Or: tt = string.maketrans('', '') STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: Hiding
Jason Drew wrote: Also, I think using file(C:\file.txt) is now preferred to open(C:\file.txt). Guido has said he wants to keep open() around as the way to open a file-like object, with the theory that in the future open might also support opening non-files (e.g. urls). So open(C:\file.txt) is still fine, though isinstance(f, open) is probably not. ;) STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: Hiding
Steven Bethard wrote: So open(C:\file.txt) is still fine I think it is more like it is recommended, not just OK. -- Benji York -- http://mail.python.org/mailman/listinfo/python-list
Re: PEP on path module for standard library
Michael Hoffman wrote: I use path in more of my modules and scripts than any other third-party module, and I know it will be very helpful when I no longer have to worry about deploying it. Same here. An object-oriented path module is extremely useful, and makes one's code much less cluttered. I've written an enhpath module that I used in my projects, with several convenience methods and some magic behavior. It's too ambitious for the standard library, but I'd like if people could at least look at the docstring and see whether some features might be useful in Path. I'd also like to see Path made subclass-friendly so I could implement this as a subclass, and others could make other subclasses. The docstring itself could also be ported to Path. The source and test suite (py.test) are here: http://cafepy.com/quixote_extras/rex/path/enhpath.py http://cafepy.com/quixote_extras/rex/path/enhpath_test.py append ?download=1 for download-friendly format. I sent an earlier version to Jason Orendorff and he liked some of the changes and had some ideas of his own, but said he was too busy to do much implementation work, and then my further letters never got a reply. The main changes I'd like to see in Path (some of these have been made in Python CVS at nondist/sandbox/path/path.py) are: - When methods create path objects, use self.__class__() instead of Path(). This makes it possible to subclass Path. Otherwise you have to rewrite the whole thing due to the hardcoded name. - Path.cwd() should be a class method instead of a static method, for the same reason. - The constructor behavior in CVS is good. Path(''), Path.cwd(), Path() = Path.cwd(). - Need .chdir() method, otherwise you have to import os for it. - Some way to pretty-print paths embedded in lists/dicts as strings. I have a .repr_as_str class attribute that toggles this. - .ancestor(3) is the same as .parent.parent.parent, but more concise. - I saw in a thread that .name and .parent were removed. I use them very frequently, along with .ext and .namebase. I don't want to call methods for these. - '/' vs .joinpath(), no big deal. I've been using '/' because it's there. .joinpath must take multiple *args, to prevent .joinpath().joinpath() . - .joinancestor(N, *components) is a combination of .ancestor and .joinpath. If curdir is /home/joe/Webware/www, Path.cwd().joinancestor(1, 'lib') is /home/joe/Webware/lib. - Keep .lisdir() as in CVS; it acts like os.listdir(). This is useful even with paths, when you're just going to use the string basename anyway. - Who needs .open()? open(myPath) is fine. But it can stay for backward compatibility. Less important but non-controversial: - Path.tempfile(), Path.tempdir(): Create a temporary file using tempfile.mkstemp, tempfile.mkdtemp - Path.tempfileobject(): Create a temporary file object using tempfile.TemporaryFile. (Static method.) Controversial: - Delete methods and mkdir should succeed silently if the operation is already done. Otherwise you always have to put them in an if: 'if foo.exists(): foo.remove()'. - .delete_dammit() recursively deletes it, whatever it is, without you having to do the if file/if directory dance. I suppose it would need a politically correct name. which you really have to do every time you delete. - All .dirs*, .files*, .walk* methods have a symlinks flag, default True. If false, don't yield symlinks. Add .symlinks and .walksymlinks methods. This eliminates an 'if' for programs that want to treat symlinks specially. - I have a .move method that combines .rename, .renames, and .move; and a .copy method that combines .copy, .copy2, and .copytree . I'd appreciate a Cc on replies if your newsreader allows it. -- Mike Orr [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Adding code and methods to a class dynamically
Peter Hansen [EMAIL PROTECTED] writes: I'm not sure what completion means in this case, and I'm not aware of any command-line completion support in cmd.Cmd though it may well be there, so I can't say. Certainly there is nothing in any way different about the new attribute created by the alias code, as both it and the original attribute are bound to exactly the same method. If you have the readline module, you get TAB command completion for free (a la bash, emacs, etc)...or maybe readline only gives you emacs-style command history editing, or both...not sure. -- http://mail.python.org/mailman/listinfo/python-list
Re: Advanced concurrancy
Peter Tillotson wrote: Hi, I'm looking for an advanced concurrency module for python and don't seem to be able to find anything suitable. Does anyone know where I might find one? I know that there is CSP like functionality built into Stackless but i'd like students to be able to use a standard python build. Please take a look at Kamaelia* - it /probably/ has what you're after by the sounds of things. Currently the unit for sequential process can be either generators or threads, and is single CPU, single process, however we do expect to make the system multi-process and multi-system. * http://kamaelia.sourceforge.net/ Currently it runs on Linux, Mac OS X, Windows and a subset works nicely on Series 60 mobiles. (That has separate packaging) It works with standard Python versions 2.2 and upwards. The basic idea in Kamaelia is you have a class that represents a concurrent unit that communicates with local interfaces only which are essentially queues. The specific metaphor we use is that of an office worker with inboxes and outboxes with deliveries made between outboxes to inboxes. There also exists a simple environmental/service lookup facility which acts like an assistant in the above metaphor, and has natural similarities to a Linda type system. (The actual rationale for the assistant facility though is based on biological systems. We have communicating linked concurrent components - which is much like many biological systems. However in addition to that most biological systems also have a hormonal system - which is part of the thinking behind the assistant system) Generators (when embedded in a class) lend themselves very nicely to this sort of model in our experience /because/ they are limited to a single level (with regard to yield). It's probably suitable for your students because we've tested the system on pre-university trainees, and vacation trainees, and found they're able to pick up the system, learn the basic ideas within a week or so (I have some exercises on how to build a mini- version if that helps), and build interesting systems. For example we had a pre-university trainee start with us at the beginning of the year, learn python, Kamaelia, and build a simple streaming system taking a video file, taking snapshots and sending those to mobile phones and PC's - this was over a period of 3 months. He'd only done a little bit of access in the past, and a little bit of VB. Well that as well as a simple learning system simulating a digital TV decode chain, but taking a script instead of a transport stream. We recently made a 0.2.0 release of the system (not announced on c.l.p yet) that includes (basic) support for a wide range of multimedia/networked apps which might help people getting started. Some interesting new additions in the release are an IPython integration - allowing you to build Kamaelia systems on the fly using a shell, much like you can build unix pipelines, as well as a visual introspection tool (and network graph visualiser) which allows you to see inside systems as they are running. (This has turned out to be extremely useful - as you can expect with any CSP-type system) The specific use cases you mention are also very closed aligned with our aims for the project. We're essentially working on making concurrency easy and natural to use, (starting from the domain of networked multimedia). You can do incremental development and transformation in exactly the way it sounds like you want, and build interesting systems. We're also working on the assumption that if you do that you can get performance later by specific optimisations (eg more CPUs). * Example of incremental component development here: http://tinyurl.com/dp8n7 By the time we reach a 1.0 release (of Kamaelia) we're also aiming to be able to integrate cleanly with Twisted (on Twisted's grounds), but it is highly usable already - especially in your area. (In CVS we have tools for building game type systems easily Tk integration as well. Tk based CSP systems are particularly fun to work with (as in fun, not fun :). One project we are seriously looking at is a visual editor for these CSP-type systems, since that appears now to be low hanging fruit. We've got a white paper about Kamaelia here: * http://www.bbc.co.uk/rd/pubs/whp/whp113.shtml This is textualisation of a presentation I gave at ACCU earlier in the year and is an overview of the core areas of the system - hopefully enough to let you know whether to look further! I also gave an updated talk at Europython - the presentation for which can be downloaded from here: * http://www.python-in-business.org/ep2005/talk.chtml?talk=2589track=692 Last week I also gave a more pragmatic, shorter talk at Open Tech which is an introduction to Kamaelia, it's goals, and several examples of CSP type systems ranging from simple audio clients/servers through to presentation tools. That presentation can be downloaded from here: *
Re: Ten Essential Development Practices
Dan Sommers wrote: [EMAIL PROTECTED] (Aahz) wrote: Dan Sommers [EMAIL PROTECTED] wrote: Was Tim writing about developing Python itself, or about developing other programs with Python? Yes. It was a rhetorical question. :-) That's all right... Aahz gave a rhetorical answer. ;-) -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Hiding
Jason Drew wrote: Also, I think using file(C:\file.txt) is now preferred to open(C:\file.txt). As others have noted, open is preferred as the method for opening files, while file is the _type_ involved, for testing or subclassing or what-have-you. But neither file(C:\file.txt) nor open(C:\file.txt) is actually correct at all, unless you have strange files whose names start with ASCII FF characters. '\f' is an escape sequence, equivalent to '\x0c'. Always use forward slashes (C:/file.txt) in path names unless you are passing them to the shell, or use raw strings (rC:\file.txt) to avoid mysterious problems with escape sequences. -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Adding code and methods to a class dynamically
Sarir Khamsi wrote: Peter Hansen [EMAIL PROTECTED] writes: I'm not sure what completion means in this case, and I'm not aware of any command-line completion support in cmd.Cmd though it may well be there, so I can't say. Certainly there is nothing in any way different about the new attribute created by the alias code, as both it and the original attribute are bound to exactly the same method. If you have the readline module, you get TAB command completion for free (a la bash, emacs, etc)...or maybe readline only gives you emacs-style command history editing, or both...not sure. Cool. The answer to whether a particular approach preserves command completion ability then, unfortunately, depends on how it's implemented. If it's totally dynamic, then the aliases my approach created will be supported, but if it's done at Cmd creation time, or in some other static manner, the dynamically created aliases won't be found. -Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: writing a web client
Fuzzyman [EMAIL PROTECTED] writes: Ajar wrote: I want to write a program which will automatically login to my ISPs website, retrieve data and do some processing. Can this be done? Can you point me to any example python programs which do similar things? Regards, Ajar Very easily. Have a look at my article on the ``urllib2`` module. http://www.voidspace.org.uk/python/articles.shtml#http You may need to use ClientCookie/cookielib to handle cookies and may have to cope with BASIC authentication. There are also articles about both of these as well. If you want to handle filling in forms programattically then the module ClientForm is useful (allegedly). The last piece of the puzzle is BeautifulSoup. That's what you use to extract data from the web page. For instance a lot of web pages listing data have something like this on it: table ... trthItem:/thtdValue/td/tr ... /table You can extract value from such with BeautifulSoup by doing something like: soup.fetchText('Item:')[0].findParent(['td', 'th']).nextSibling.string Where this checks works for the item being in either a td or th tag. Of course, I recommend doing things a little bit more verbosely. In my case, I'm writing code that's expected to work on a large number of web pages with different formats, so I put in a lot of error checking, along with informative errors. links = table.fetchText(name) if not links: raise BadTableMatch, %s not found in table % name td = links[0].findParent(['td', 'th']) if not td: raise BadmatchTable, td/th not a parent of %s % name next = td.nextSibling if not next: raise BadTableMatch, td for %s has no sibling % name out = get_contents(next) if not out: raise BadTableMatch, no value string found for %s % name return out BeautifulSoup would raise exceptions if the conditions I check for are true and I didn't check them - but the error messages wouldn't be as informative. Oh yeah - get_contents isn't from BeautifulSoup. I ran into cases where the td tag held other tags, and wanted the flat text extracted. Couldn't find a BeautifulSoup method to do that, so I wrote: def get_contents(ele): Utility function to return all the text in a tag. if ele.string: return ele.string # We only have one string. Done return ''.join(get_contents(x) for x in ele) mike -- Mike Meyer [EMAIL PROTECTED] http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
Re: can list comprehensions replace map?
Peter Otten wrote: Seems my description didn't convince you. So here's an example: Got it. In my test case the longest element happened to be the last one, which is why it didn't catch the problem. Thanks. Andrew [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: multiple inheritance super()
Michele Simionato [EMAIL PROTECTED] writes: adding methods on the fly and metaclasses could live pretty well without multiple inheritance. There would be no real loss of power and hopefully less monstruosities such a Zope 2. But maybe this is just wishful thinking ... Um, no real loss of power? Well, in the sense that all languages are turing-equivalent, maybe. My current project includes a small set of classes that all deal with web pages. The classes exist in three layers: the first layer is very abstract, and provides a general mechanism. The second layer adapts the general mechanasm to a specific case. The last layer provides application-specific functionality. The classes intercommunicate, but are generally completely unrelated to each other except for the more concrete classes inheriting from the layer above. So far, so good - it's all simple single inheritance. Now, I have a class Utility that collects utility methods that are useful for dealing with web pages: extracting data, filling out forms, etc. These are provided as a mixin. The classes that need this functionality inherits from it as well as their parent. The classes that don't need it don't. This makes use of multiple inheritance. Without multiple inheritance, I would have had to make the Utility class a parent of all the most abstract classes. Some of the those classes don't need that functionality - but their children do, so they have to inherit from it. Children's needs shouldn't influence the implementation of the child - that's simply ugly. Also, it creates an apparent relationship between all the most abstract classes that doesn't really exist. Do you have a proposed solution that doesn't have these problems? mike -- Mike Meyer [EMAIL PROTECTED] http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
Re: Async PySerial (was Re: pySerial Windows write problem)
phil wrote: I use PySerial in a 16 line data collection system with LOTS of threads, and yes am frustrated by read(). This sounds excellent, keep us updated. BTW, haven't done any event driven Python except Tkinter. Would this a class library which would let you define an event and a handler? Roughly speaking, yes. The primary parent class happens to be called Handler, and is a threading.Thread subclass which in its run() method basically sits in a win32 WaitForMultipleObjects() call for various things to happen, then calls handler routines based on which event fires. Do you have a one line code example? One line? No way... this isn't Perl. ;-) from bent.serial import Driver class MyDriver(Driver): def __init__(self, port, baud=9600): Driver.__init__(self, port, baud=baud, name='iodriver') self.start() # start the thread def handleSerialRead(self, data): print 'read %r' % data def handleSerialDsr(self, level): print 'DSR', level def handleSerialBreak(self): print 'break detected, ho hum' Usage for this would be simply: d = MyDriver('COM3') and then sit back and watch the, uh, fireworks... or at least the print statements. Anything interesting represents a much more sophisticated subclass which parses the data as it arrives, of course, and at least in my case then calls a handlePacket() routine where the fun really begins. -Peter -- http://mail.python.org/mailman/listinfo/python-list
A replacement for lambda
I know, lambda bashing (and defending) in the group is one of the most popular ways to avoid writing code. However, while staring at some Oz code, I noticed a feature that would seem to make both groups happy - if we can figure out how to avoid the ugly syntax. This proposal does away with the well-known/obscure lambda keyword. It gives those who want a more functional lambda what they want. It doesn't add any new keywords. It doesn't add any new magic characters, though it does add meaning to an existing one. That could be replaced by a new magic token, or adding magic meaning to a non-magic token. It breaks no old code either way. I haven't really worked out all the implications; I just wanted to throw it out and see what everyone else thought about it. As a result, the code examples tend to be ugly. As previously hinted, this feature is lifted from Oz. Currently, class and functions definitions consist of a keyword - either class or def - followed by a name, a header, then code. The code is compiled into an object, and the name is bound to that object. The proposal is to allow name to be a non-name (or rare name) token. In this case, the code is compiled and the resulting object is used as the value of the class/def expression. My choice for the non-name token is @. It's already got magic powers, so we'll give it more rather than introducing another token with magic powers, as the lesser of two evils. Rewriting a canonical abuse of lambda in this idiom gives: myfunc = def @(*args): return sum(x + 1 for x in args) In other words, this is identical to: def myfunc(*args): return sum(x + 1 for x in args) We can write the same loop with logging information as: sum(def @(arg): print Bumping, arg return arg + 1 (x) # '(' at the same indent level as def, to end the definition for x in stuff) A more useful example is the ever-popular property creation without cluttering the class namespace: class Spam(object): myprop = property(fget = def @(self): return self._properties['myprop'] , fset = def @(self, value): self._properties['myprop'] = value , fdel = def @(self) del self._properties['myprop'] , doc = Just an example) This looks like the abuse of lambda case, but these aren't assignments, they're keyword arguments. You could leave off the keywords, but it's not noticably prettier. fget can be done with a lambda, but the the others can't. Giving clases the same functionality seems to be the reasonable thing to do. It's symmetric. And if anonymous function objects are good, then anonymous class objects ought to be good as well. mike -- Mike Meyer [EMAIL PROTECTED] http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list
Block-structured resource handling via decorators
When handling resources in Python, where the scope of the resource is known, there seem to be two schools of thought: (1) Explicit: f = open(fname) try: # ... finally: f.close() (2) Implicit: let the GC handle it. I've come up with a third method that uses decorators to achieve a useful mix between the two. The scope of the resource is clear when reading the code (useful if the resource is only needed in part of a function), while one does not have to write an explicit cleanup. A couple of examples: @withFile(fname, 'w') def do(f): # ... write stuff into file f ... @withLock(aLock): def do(): # ... whatever you needed to do once the lock was acquired, # safe in the knowledge it will be released afterwards ... (The name do is arbitrary; this method has the mostly harmless side-effect of assigning None to a local variable with the function name.) I find it clear because I come from a C++/C#/Java background, and I found C#'s using-blocks to very useful, compared to the explicit finallys of Java. I know that Python's deterministic finalization sort of achieves the same effect, but I had been led to believe there were complications in the face of exceptions. The implementation is easily extensible: a handler for a new type of resource can be written in as a couple of lines. For the examples above: class withFile(blockScopedResource): init, cleanup = open, 'close' It's so simple I was wondering why I haven't seen it before. Possibly: it's a stupid idea and I just can't see why; everyone knows about it except me; it's counter-intuitive (that's not the way decorators were intended); it's writing C# in Python or in some other way unPythonic; I've actually had an idea that is both Original and non-Dumb. If the last is the case, can someone let me know, and I'll put up the code and explain how it all works. On the other hand, if there is something wrong with it, please can someone tell me what it is? Thanks John Perks -- http://mail.python.org/mailman/listinfo/python-list
urllib2 bug?
Certain pages cause urllib2 to go into an infinite loop when using readline(), but everything works fine if read() is used instead. Is this a bug or am I missing something simple? import urllib2 url = 'http://www.naylamp.com' f = urllib2.urlopen(url) i = 0 #this works fine when uncommented #print f.read() #print 'finished' #this never ends while 1: line = f.readline() if not line: break print line print i i = i + 1 #end while -- http://mail.python.org/mailman/listinfo/python-list