From jmcmonagle at velseis.com.au Mon May 19 18:44:05 2008 From: jmcmonagle at velseis.com.au (John McMonagle) Date: Tue, 20 May 2008 08:44:05 +1000 Subject: this worked before...' '.join([`x x` for x in range(1, 6)]) In-Reply-To: References: Message-ID: <483202B5.2000109@velseis.com.au> notnorwegian at yahoo.se wrote: > ' '.join([`x x` for x in range(1, 6)]) > > anyone can tell me what im doing wrong? > -- > http://mail.python.org/mailman/listinfo/python-list > ' '.join(['%s %s' % (str(x), str(x)) for x in range(1,6)]) or ' '.join([str(x)+' '+str(x) for x in range(1,6)]) outputs.... '1 1 2 2 3 3 4 4 5 5' Is that what you were after ? From slesarev.anton at gmail.com Wed May 7 06:13:04 2008 From: slesarev.anton at gmail.com (Anton Slesarev) Date: Wed, 7 May 2008 03:13:04 -0700 (PDT) Subject: python vs. grep References: <011f43ea-9bc8-499a-a3fe-dba24b47932e@c58g2000hsc.googlegroups.com> Message-ID: I try to save my time not cpu cycles) I've got file which I really need to parse: -rw-rw-r-- 1 xxx xxx 3381564736 May 7 09:29 bigfile That's my results: $ time grep "python" bigfile | wc -l 2470 real 0m4.744s user 0m2.441s sys 0m2.307s And python scripts: import sys if len(sys.argv) != 3: print 'grep.py ' sys.exit(1) f = open(sys.argv[2],'r') print ''.join((line for line in f if sys.argv[1] in line)), $ time python grep.py "python" bigfile | wc -l 2470 real 0m37.225s user 0m34.215s sys 0m3.009s Second script: import sys if len(sys.argv) != 3: print 'grepwc.py ' sys.exit(1) f = open(sys.argv[2],'r',100000000) print sum((1 for line in f if sys.argv[1] in line)), time python grepwc.py "python" bigfile 2470 real 0m39.357s user 0m34.410s sys 0m4.491s 40 sec and 5. This is really sad... That was on freeBSD. On windows cygwin. Size of bigfile is ~50 mb $ time grep "python" bigfile | wc -l 51 real 0m0.196s user 0m0.169s sys 0m0.046s $ time python grepwc.py "python" bigfile 51 real 0m25.485s user 0m2.733s sys 0m0.375s From tjreedy at udel.edu Sun May 25 21:23:42 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 25 May 2008 21:23:42 -0400 Subject: Getting a set of lambda functions References: <83bb3e45-f32f-4811-831f-d1e31d4fcb1e@d77g2000hsb.googlegroups.com><59719846-588e-414e-a1b9-cc7b04019501@k37g2000hsf.googlegroups.com> Message-ID: "Martin Manns" wrote in message news:g1cu8n$5g4$1 at aioe.org... | On Sun, 25 May 2008 14:39:28 -0700 (PDT) | bearophileHUGS at lycos.com wrote: | | > This may have some bugs left, but it looks a bit better: | [...] | > self._hash = hash(self._func.func_code) ^ \ | > hash(tuple(signature[0]) + tuple(signature[1:3])) | > def __eq__(self, other): | > return self._func.func_code == other._func.func_code and \ | > getargspec(self._func) == getargspec(other._func) | > def __hash__(self): | > return self._hash | > def __call__(self, *args, **kwargs): | > return self._func(*args, **kwargs) | > | > I haven't put a full hashing of getargspec(self._func) too into the | > __init__() because it may contain too much nested unhashable | > structures, but the __eq__() is able to tell them apart anyway, with | > some collisions. | | Looking at a function: | | >>> a=lambda x:x | >>> dir(a) | ['__call__', '__class__', '__delattr__', '__dict__', '__doc__', | '__get__', '__getattribute__', '__hash__', '__init__', '__module__', | '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', | '__setattr__', '__str__', 'func_closure', 'func_code', 'func_defaults', | 'func_dict', 'func_doc', 'func_globals', 'func_name'] | | Should func_globals and func_name also be taken into account for | __eq__()? It depends on what *you* want == to mean. tjr From castironpi at gmail.com Sat May 3 19:54:54 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 3 May 2008 16:54:54 -0700 (PDT) Subject: Light slices + COW References: Message-ID: <9c6347c2-1d28-407d-80db-37d73c5a8f22@w74g2000hsh.googlegroups.com> On May 3, 1:59?pm, bearophileH... at lycos.com wrote: > Sometimes different languages suggests me ways to cross-pollinate > them. > > (Note: probably someone has already suggested (and even implemented) > the following ideas, but I like to know why they aren't fit for > Python). > > Python generators now allow me to package some code patterns common in > my code, that other (older) languages didn't allow me to extract; for > example given a sequence (array, list, etc) of items now and then I > need to scan all the upper triangle of their cross matrix: > > def xpairs(seq): > > ? ? len_seq = len(seq) > > ? ? for i, e1 in enumerate(seq): > > ? ? ? ? for j in xrange(i+1, len_seq): > > ? ? ? ? ? ? yield e1, seq[j] > > Or adjacent ones (there are ways to generalize the following function, > but this the most common situation for me): > > def xpairwise(iterable): > > ? ? return izip(iterable, islice(iterable, 1, None)) > > That xpairs() generator is nice, but it's not the best possible code > (but you may disagree with me, and you may think that code better than > the successive D code that uses two slices). Inside it I can't use a > list slicing because it copies subparts of the list, probably becoming > too much slow (for example if len(seq) == 1000). > > Compared to Python, the D language is at lower level, so you may > expect it to have a worse syntax (but the ShedSkin compiler has shown > me once for all that you can have a language that is both high-level, > with a short & sexy syntax, and very fast), but you can define a > xpairs() iterable class in it too, and the core of that iterable class > there's a method that may look like this: > > if (this.seq.length > 1) > > ? foreach (i, e1; this.seq[0 .. $-1]) > > ? ? foreach (e2; this.seq[i+1 .. $]) { > > ? ? ? result = dg(e1, e2); if (result) break; // yield > > ? ? } > > Where the strange last line is the yield, and the $ inside [] is the > length of the current array (a very clever idea that avoids the need > for negative indexes). > > That D code is as fast or faster than the code you can back-translate > from Python, this is possible because in D arrays slices are very > light, they are a struct of (in the future they may > change to a couple of pointers, to speed up the array slice scanning). > So if you slice an array you don't copy its contents, just the start- > end points of the slice. If you read/scan the slice that's all you > have, while if you write on it, D uses a Copy-On-Write strategy, that > is a just-in-time copy of the slice contents. > > In practice this speeds up lot of code that manages strings and arrays > (like a XML parser, making it among the faster ones). > > Being the slice a struct, it's stack allocated, so the inner foreach > doesn't even create a slice object in the heap each time the outer > foreach loops. > > One problem with this strategy is that if you have a huge string, and > you keep only a little slice of it, the D garbage collector will keep > it all in memory. To avoid that problem you have to duplicate the > slice manually: > > somestring[inf...sup].dup; > > I think Psyco in some situations is able to manage string slices > avoiding the copy. > > I think Python 3.0 too may enjoy a similar strategy of light slices + > COW for strings, lists and arrays (tuples and strings don't need the > COW). > > Bye, > > bearophile In my understanding, the operating system links files across multiple sections on a disk, while keeping those details from client software. Files: AAAA BBBB AA CCCCCCCCC While File A still reads as: AAAAAA, correctly. Modifications to B as follow: Files: AAAA BBBB AA CCCCCCCCC BBBB In the case of a large mutable string, modifications can cause linear- time operations, even if only making a constant-time change. String: abcdefg Modification: aAbcdefg causes the entire string to be recopied. Expensive at scale. A string-on-disk structure could provide linking, such as a String File Allocation Table. abcdefg A correctly reads as: aAbcdefg From ivlenin at gmail.com Fri May 23 04:27:27 2008 From: ivlenin at gmail.com (I V) Date: Fri, 23 May 2008 08:27:27 GMT Subject: error using all()/numpy [TypeError: cannot perform reduce with flexible type] References: Message-ID: On Fri, 23 May 2008 00:12:35 -0700, Marc Oldenhof wrote: > It seems that Python calls numpy's "all" instead of the standard one, is > that right? If so, how can I call the standard "all" after the numpy > import? ["import numpy" is not a desirable option, I use a lot of math > in my progs] I think the ideal solution is to try and persuade yourself that typing "numpy." in front of some functions now and then is not that big a price to pay to avoid name collisions; using an editor with code completion would probably help in that task. You could also try: import numpy as n which reduces the typing a bit and limits you to one possible name collision, or from numpy import array, gradient #and whatever else you need or import numpy array = numpy.array gradient = numpy.gradient # Then you can access the names you use a lot # directly, while accessing stuff you use less # frequently via numpy.whatever in which case you'll know exactly which names you're overwriting. Peter's solution, of explicitly deleting some names that you've imported, strikes me as less good, because you might find the same problem recurs later, if the numpy developers add new names to the module. From beema.shafreen at gmail.com Wed May 21 04:40:26 2008 From: beema.shafreen at gmail.com (Beema shafreen) Date: Wed, 21 May 2008 14:10:26 +0530 Subject: Typeerror Message-ID: Hi all, I getting the following error when i run my scirpt , can somebody help me regarding this to solve the type error problem Traceback (most recent call last): File "get_one_prt_pep.py", line 59, in ? if len(data[res])<=1: TypeError: string indices must be integers -- Beema Shafreen -------------- next part -------------- An HTML attachment was scrubbed... URL: From george.sakkis at gmail.com Thu May 1 19:50:20 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Thu, 1 May 2008 16:50:20 -0700 (PDT) Subject: where do I begin with web programming in python? References: <37ea096e-cf3e-4932-8370-306a15a2aebd@25g2000hsx.googlegroups.com> Message-ID: <4b35fb1d-e273-4c94-b49c-c9e6cdee06c0@24g2000hsh.googlegroups.com> On May 1, 7:13?pm, Graham Dumpleton wrote: > On May 2, 7:45 am, Christian Heimes wrote: > > > > > jmDesktop schrieb: > > > > I have been to the main python site, but am still confused. ?I have > > > been using .net, so it may be obvious how to do this to everyone > > > else. ?I am aware there are various frameworks (Django, Pylons, etc.), > > > but I would like to know how to create web pages without these. ?If I > > > havemod_pythonor fastcgi on apache, where do I start? ?I don't have > > > clue where to begin to create a web page from scratch in python. ?I am > > > sure I will want to access database, etc., all the "normal" stuff, I > > > just want to do it myself as opposed to the frameworks, for learning. > > > I highly recommend WSGI instead ofmod_pythonor (fast)cgi. I've heard > > only bad things aboutmod_pythonover the past years and CGI is totally > > old school. > > > Check out Python Paste, CherryPy and Django. You can also try the Zope, > > Zope3 and Plone world but Zope is usually for larger and complex > > applications. > > > Most frameworks come with their own little web server for development, too. > > I'd also suggest avoiding coding anything directly to mod_python and > instead base things on WSGI. You can still run it on mod_python with a > suitable adapter, but you can also run it with mod_wsgi, mod_fastcgi, > or using pure Python web servers such as the one in Paste as well. > > For a low level nuts and bolts (anti framework) approach I'd suggest > looking at: > > ?http://dev.pocoo.org/projects/werkzeug/ > > This gives you all the basic components, but it is really up to you as > to how you put them together, which seems to be what you want to be > able to do. Or if you don't want to use any 3rd party package and have Python 2.5, you may start from http://www.xml.com/pub/a/2006/09/27/introducing-wsgi-pythons-secret-web-weapon.html. Here's the standard "Hello world!" example: from wsgiref.simple_server import make_server def application(environ, start_response): start_response('200 OK',[('Content-type','text/html')]) return ['Hello World!'] httpd = make_server('', 8000, application) print "Serving HTTP on port 8000..." httpd.serve_forever() and point your browser to http://localhost:8000/ HTH, George From tjreedy at udel.edu Wed May 14 13:48:14 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 14 May 2008 13:48:14 -0400 Subject: list.__len__() or len(list) References: <3fc761710805131718y448ef0b8r67dcc8cf118bc80a@mail.gmail.com> Message-ID: "Nikhil" wrote in message news:g0ev6o$utb$1 at registered.motzarella.org... | Then why to have __len__() internal method at all when the built-in | len() is faster? Nearly all syntax constructions and builtin functions are implemented by calling one or another of the __special__ methods. This is what makes Python code so generic and plugging your own classes into the system so easy. For example, collection[key] = value is implemented by calling collection.__setitem__(key, value). When you define a class with that method, that syntax will work with its instances just the same as for builtin classes. Similarly, a+b is implemented by calling a.__add__(b). So if a class defines __add__, you can 'add' its instances (whatever 'add' means for that class) with '+'. (The fact that an *implementation* may followup the 'as if' rule and optimize operations for certain classes by combining steps does not negate the *language* rules given above.) tjr From paul.hankin at gmail.com Tue May 27 16:35:14 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Tue, 27 May 2008 13:35:14 -0700 (PDT) Subject: Weird exception in my, um, exception class constructor References: Message-ID: <0ea08237-c9f9-441b-a744-7410114b5ae9@t54g2000hsg.googlegroups.com> On May 27, 9:21?pm, "Joel Koltner" wrote: > I have a generic (do nothing) exception class that's coded like this: > > class MyError(exceptions.Exception): > ? ? def __init__(self,args=None): > ? ? ? ? self.args = args > > When I attempt to raise this exception via 'raise MyError' I get an exception > within the MyError constructor __init__ as follows: > > Traceback (most recent call last): > [lines deleted] > ? File "c:\Documents and Settings\Joel.Kolstad\My Documents\Python\ > MyStuff.py", line 7, in __init__ > ? ? self.args = args > TypeError: 'NoneType' object is not iterable > > Ummm... why should 'args' have to be iterable anyway? ?I don't understand > what's going on here? ?Could someone help me with this? Did you actually write self,args = args? -- Paul Hankin From jackyuke at gmail.com Sat May 24 08:48:57 2008 From: jackyuke at gmail.com (Jack Yu) Date: Sat, 24 May 2008 12:48:57 +0000 (UTC) Subject: Popen: NameError: name 'PIPE' is not defined References: Message-ID: On Sat, 24 May 2008 14:09:07 +0200?Mathieu Prevot wrote? > Hi > > I import subprocess and use Popen, but PIPE is not defined. I used > 2.5.1, 2.5.2, Python 2.6a3+ (trunk:63576, May 24 2008, 12:13:40), it's > always the same. What am I missing ? > > Thanks > Mathieu Try subprocess.PIPE. From agustin.villena at gmail.com Wed May 21 19:48:04 2008 From: agustin.villena at gmail.com (Agustin Villena) Date: Wed, 21 May 2008 16:48:04 -0700 (PDT) Subject: Showing the method's class in expection's traceback References: <79c7d6fb-a6b8-481f-9a36-81b980628710@59g2000hsb.googlegroups.com> <69bi20F31j4kdU1@mid.uni-berlin.de> <0043b6d6-3e4c-4efc-a02e-5eb2c84fa009@k37g2000hsf.googlegroups.com> Message-ID: <1f686bef-db23-4e17-bedc-434495381542@d1g2000hsg.googlegroups.com> On 20 mayo, 12:10, "Gabriel Genellina" wrote: > En Mon, 19 May 2008 10:54:05 -0300, Agustin Villena > escribi?: > > > On May 18, 4:31 pm, "Diez B. Roggisch" wrote: > >> Agustin Villena schrieb: > > >> > is there anyway to show the class of amethodin anexception's > >> > traceback? > >> > I want to improve the line > >> > File "G:\dev\exceptions\sample.py", line 3, in foo > >> > to > >> > File "G:\dev\exceptions\sample.py", line 3, in Some.foo > > >> It should be. You can get a dictionary of the locals of anexception > >> stack frame, of which you could extract the self-parameter's class. > > > I digged on sys.exc_info() object and the traceback module and I > > could't figure how I can get the locals() of theexceptionstackframe > > Put this function in traceback.py, and replace the lines > name = co.co_name > with > name = guess_full_method_name(f) > everywhere. > Please read the docstring!!! > > def guess_full_method_name(frame): > """Guess classname.methodname for a given frame. > > Only a guess! > Assumes the frame belongs to an instancemethod > whose first argument is "self", or a classmethod > whose first argument is "cls". > Doesn't handle correctly any other situation. > Returns the class name of the object on which > the method was called, not the class where > the method was actually defined. > """ > cls_name = None > fun_name = frame.f_code.co_name > self = frame.f_locals.get('self', None) > if self is None: > cls = frame.f_locals.get('cls', None) > else: > cls = getattr(self, '__class__', None) > if cls is not None: > cls_name = getattr(cls, '__name__', None) > if cls_name is not None: > return '%s.%s' % (cls_name, fun_name) > return fun_name > > -- > Gabriel Genellina Thanks! I'll try it Agustin From george.sakkis at gmail.com Fri May 9 21:05:26 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 9 May 2008 18:05:26 -0700 (PDT) Subject: Property in derived class References: <31861d09-a273-45de-bc71-c8591b7722e6@w7g2000hsa.googlegroups.com> Message-ID: <7f3a3e02-8207-4661-94fa-48a518720a46@r66g2000hsg.googlegroups.com> On May 9, 5:20?pm, Joseph Turian wrote: > If I have a property in a derived class, it is difficult to override > the get and set functions: the property's function object had early > binding, whereas the overriden method was bound late. > This was previously discussed: > ? ?http://groups.google.com/group/comp.lang.python/browse_thread/thread/... > > Could someone demonstrate how to implement the proposed solutions that > allow the property to be declared in the abstract base class, and > refer to a get function which is only implemented in derived classes? Using the overridable property recipe [1], it can be written as: class AbstractFoo(object): def _getFoo(self): raise NotImplementedError('Abstract method') def _setFoo(self, signals): raise NotImplementedError('Abstract method') foo = OProperty(_getFoo, _setFoo) HTH, George [1] http://infinitesque.net/articles/2005/enhancing%20Python's%20property.xhtml From gagsl-py2 at yahoo.com.ar Sun May 11 00:16:46 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 11 May 2008 01:16:46 -0300 Subject: How to call a file References: <4825C01F.1070409@islandtraining.com> Message-ID: En Sat, 10 May 2008 12:32:47 -0300, Gary Herron escribi?: > Chris Sprinkles wrote: >> I'm still having trouble with calling a text file and I know its so >> simple here is the code >> ---------------------------------------------------- >> work = open('C:\Documents and Settings\Administrator\My >> Documents\Chris\Python\Python\work.txt', 'r') Also, remember that \ is the escape character for strings in Python. In this particular case it doesn't matter just because you didn't hit any valid escape, but in general, use: "C:\\Documents and Settings\\Adm..." r"C:\Documents and Settings\Adm..." In most cases, Windows recognizes forward slashes also: "C:/Documents and Settings/Adm..." -- Gabriel Genellina From duncan.booth at invalid.invalid Fri May 23 04:35:28 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 23 May 2008 08:35:28 GMT Subject: Python and Flaming Thunder References: <8cfd3523-8d16-40bc-b904-94a6a36a414d@p25g2000pri.googlegroups.com> Message-ID: Brian Quinlan wrote: > Dave Parker wrote: >>> Or just: >>> >>> If command is "quit" ... >> >> Hmmm. In Flaming Thunder, I'm using "is" (and "is an", "is a", etc) >> for assigning and checking types. For example, to read data from a >> file and check for errors: >> >> Read data from "input.txt". >> If data is an error then go to ... > > Hey Dave, > > Does this mean that Flaming Thunder requires explicit checking rather > than offering exceptions? It looks that way but he doesn't seem to have got as far as documenting errors: the documentation gives several examples of that form and says that 'error' is a reserved word but says nothing about how you create an error of if you can distinguish one error from another: I'm guessing you can't as FT doesn't appear to have any concept of attributes on objects (or even any concept of objects): so far as I can see the only types are integers, rationals, intervals and strings (and real numbers if you pay real money for them). Maybe I'm missing something though, because I don't see how you can do anything useful with out at least some sort of arrays (unless you are supposed to store numbers in long strings). -- Duncan Booth http://kupuguy.blogspot.com From lists at cheimes.de Wed May 7 16:47:51 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 07 May 2008 22:47:51 +0200 Subject: subprocess wait() waits forever, but os.system returns In-Reply-To: <84a23679-56e2-41b5-83eb-741a696095da@59g2000hsb.googlegroups.com> References: <84a23679-56e2-41b5-83eb-741a696095da@59g2000hsb.googlegroups.com> Message-ID: <48221577.6030408@cheimes.de> grayaii schrieb: > There are so many threads on this subject, but I ran across a > situation on Windows that I can't figure out. > > I'm trying to run this little command-line exe and when I launch like > this, it hangs: > >>>> import subprocess >>>> command = r'c:\mydir\foo.exe' >>>> run = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stdin=None, stderr=subprocess.PIPE, env=os.environ, universal_newlines=True) >>>> returncode = run.wait() ## HANGS HERE ## The code blocks because you aren't reading from stdout and stderr. Use the communicate() method instead of wait(). Christian From deets at nospam.web.de Fri May 30 13:40:17 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 30 May 2008 19:40:17 +0200 Subject: Calling instance methods from a decorator In-Reply-To: <87d4n3n1z7.fsf@internal.daycos.com> References: <87d4n3n1z7.fsf@internal.daycos.com> Message-ID: <6aasg8F35t0j9U1@mid.uni-berlin.de> Kirk Strauser schrieb: > I'm trying to write a decorator that would do something like: > > def trace(before, after): > def middle(func): > def inner(*args, **kwargs): > func.im_self.debugfunction(before) > result = func(*args, **kwargs) > func.im_self.debugfunction(after) > return result > return inner > return middle > > class Foo(object): > def __init__(self, myname): > self.name = myname > > def debugfunction(self, message): > print 'Instance %s says: %s' % (self.name, message) > > @trace('calling', 'finished') > def bar(self, arg): > print arg > >>>> Foo('snake').bar(123) > Instance snake says: calling > 123 > Instance snake says: finished > > The gotcha seems to be that there's no way to get to 'self' from within the > "inner" function, since func will only have the "normal" attributes: > >>>> print dir(func) > ['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__get__', '__getattribute__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name'] > > There's no nice im_self to bounce off of or anything. I seem to be going > about this all wrong. What's a good approach to get the desired effect? Of course you can get the self - just use the first paramter, because it *is* self. Self is just a parameter - nothing special. Alternatively, declare inner like this: def inner(self, *args, **kwargs): ... try: return func(self, *args, **kwargs) finally: .... Note the additional try/finally. It's got nothing todo with your original problem - but you should use it to guarantee that your trace gets called when leaving the call. Diez From pavlovevidence at gmail.com Fri May 2 14:07:45 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 2 May 2008 11:07:45 -0700 (PDT) Subject: #!/usr/bin/env python vs. #!/usr/bin/python References: <87abj91j8u.fsf@benfinney.id.au> <871w4l1cjj.fsf@benfinney.id.au> <87r6ckzvyv.fsf@benfinney.id.au> <87bq3ozs09.fsf@benfinney.id.au> Message-ID: On May 2, 11:07 am, "D'Arcy J.M. Cain" wrote: > On Sat, 03 May 2008 00:43:02 +1000 > > Ben Finney wrote: > > Roy Smith writes: > > > Have you ever shipped software to a customer? > > > Yes, and all parties have been quite happy with the results. > > When some of us talk about shipping software we aren't talking about a > 20 line script delivered to our uncle's construction company office. We > are talking about millions of lines of code in thousands of programs and > modules that has to run out of the box on whatever system the client > happens to run on. If you're shipping a program that large you out to be packaging the Python interpreter with it. Frankly, this whole discussion is silly, as if it's some kind hard thing to open the script with a text editor and modify the shbang line. Carl Banks > > > Customer: "I can't install it there because > > reason the customer has>. If you can't make your product work > > > without requiring me to install python in /usr/bin, I'm afraid I > > > can't buy your product". > > > At this point they have the simple option of running the program with > > 'python /path/to/the/program'. It's certainly not a case of "can't > > make the product work". > > Simple for your 20 line single script. Not so simple for my million > line, integrated system that has to work everywhere. > > > It is, however, a case of "can't automatically account for every local > > customisation sysadmins choose to make on their systems". Perfectly > > willing to work with them to get their specific environment working, > > but as a matter of simple economics it's not worth my time to attempt > > to make such corner cases work automatically. > > If by "corner case" you mean "some system that I don't personally run" > then OK but to some of us your system is the corner case and we would > like our code to run there as well. > > Real software has to deal with the fact that support costs money. > You may be able to deal with one or two clients that way but that does > not scale very well. > > > If they've already chosen to install Python to some unpredictable > > location, they know what they're doing enough to invoke the program in > > a specific way to get it working. > > Unpredictable to you. Perfectly predictable on their system. > > I do believe I am done with this thread. > > -- > D'Arcy J.M. Cain | Democracy is three wolveshttp://www.druid.net/darcy/ | and a sheep voting on > +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From needin4mation at gmail.com Tue May 6 11:09:53 2008 From: needin4mation at gmail.com (jmDesktop) Date: Tue, 6 May 2008 08:09:53 -0700 (PDT) Subject: Am I missing something with Python not having interfaces? References: <45de2f7e-484a-4871-bbaa-bf7eed5dfa40@x35g2000hsb.googlegroups.com> Message-ID: <29716374-c3b2-407e-ac54-ae2a17ccf081@2g2000hsn.googlegroups.com> On May 6, 10:26?am, "A.T.Hofkamp" wrote: > On 2008-05-06, jmDesktop wrote: > > > Studying OOP and noticed that Python does not have Interfaces. ?Is > > that correct? ?Is my schooling for nought on these OOP concepts if I > > Depends on your definition of 'Python does not have Interfaces'. They are not > in the official language, but they do exist. look into zope.interfaces, athttp://www.zope.org/Products/ZopeInterface. > > > use Python. ?Am I losing something if I don't use the "typical" oop > > constructs found in other languages (Java, C# come to mind.) ?I'm > > I think you are still thinking with a Java mind-set (no idea about C#, never > programmed with it). > > Interfaces mainly exist to formalize TO A COMPILER that an object will provide > certain stuff. In this way, the compiler can catch such errors at compile time. > > Python on the other hand does very little at compile time (other than parse > errors). Instead, at run-time it performs the checks that something you want to > use is actually there. > (in the same way that you don't declare variables a priori. You simply use them > and Python creates them for you when needed). > > As a result, you get much more light-weight, more dynamic, code, which supports > the RAD nature of Python what makes it so much more productive. > > (after a few years Python, you may find the Java way of doing things clunky). > > > afraid that if I never use them I'll lose them and when I need them > > for something beside Python, I'll be lost. ?Thank you. > > You can continue doing everything exactly in the way you do now. Effectively > you would then be programming Java/C# in Python syntax. I believe you would > gain very little by that move. > > If you dare let go of your old habits, and embrace the mindset of a new > language, you can learn a lot more, namely that programming can be done in many > different ways (even if all those ways are called OOP). > If you only have a hammer, the whole world looks like a nail. If you have a > whole toolbox, problems become much more diverse (subtle). You learn to use > the right tools for the right problem, and maybe you find new (better) ways of > approaching old problems. > > In the process, you may lose details of how something was done in language X, > but that's why they have invented books. > > Sincerely, > Albert I would imagine this is why I haven't found any schools teaching Python in their basic programming classes too. On the dynamic typing, isn't that the same sort of thing that lots of scripting languages do? VBScript doesn't require you to define your variables, but I don't really want to use it for anything (used to use it a lot in Classic ASP.) I believe everyone that Python is great, but some of it doesn't make sense to me as to why. Thanks. From ppearson at nowhere.invalid Fri May 2 10:45:19 2008 From: ppearson at nowhere.invalid (Peter Pearson) Date: Fri, 02 May 2008 09:45:19 -0500 Subject: Getting started with pyvtk References: Message-ID: On Thu, 01 May 2008 16:45:51 -0500, Robert Kern wrote: > > pyvtk is not the Python interface to VTK. It is for the > creation of VTK files. The vtk(1) command is a Tcl shell > with the VTK libraries loaded (I believe). Read the VTK > documentation for information on the Tcl interface if you > really want to use it. You're right: I don't really want to use it. > The Python interface is also included in the VTK sources, > although it might not have been built on your machine. You > have to enable it when you build VTK itself. The Python > interface is essentially the same as the C++ > interface. There are Python examples in the VTK source > tree. That's the ticket: I don't want to "import pyvtk", I want to "import vtk" and ape /usr/share/vtk/.../*.py. Thanks. -- To email me, substitute nowhere->spamcop, invalid->net. From jschroed at gmail.com Mon May 5 19:34:32 2008 From: jschroed at gmail.com (John Schroeder) Date: Mon, 5 May 2008 16:34:32 -0700 Subject: How can we write a class factory that dynamically redefines the __init__ function etc. Message-ID: <4878ad7b0805051634k2666943bmd71fa9947816ab68@mail.gmail.com> Basically I have some classes like this: ############################################################################### # 0x01: ModeCommand ############################################################################### class ModeCommand: """This is the Mode Command Packet class.""" def __init__(self, mode, command, id=0x01): """The unspecial init function.""" self.mode = mode self.command = command self.id = id def RawData(self): return [self.id, self.mode, self.command] def __getitem__(self, index): """[] operator (read): indexes from the byte data.""" return self.RawData()[index] def __str__(self): """Print a nice thing.""" string = "Mode = %d\n" % self.mode + \ "Command = %d\n" % self.command + \ "ID = %d\n\n" % self.id return string ############################################################################### # 0x02: CallRequest ############################################################################### class CallRequest: """This is the Call Request Packet class. (Look familiar?)""" def __init__(self, service_number, id=0x02): """The unspecial init function.""" self.service_number = service_number self.id = id def RawData(self): return [self.id, self.service_number] def __getitem__(self, index): """[] operator (read): indexes from the byte data.""" return self.RawData()[index] def __str__(self): """Print a nice thing.""" string = "Service Number = %d\n" % self.service_number + \ "ID = %d\n\n" % self.id return string ############################################################################### # Test Code ############################################################################### x = ModeCommand(mode=1, command=0) print x[:] print x y = CallRequest(service_number=2001) print y[:] print y Which is ok but I had to do this over 100 times. It is difficult to maintain and no one else can understand what the heck I did here. So I was trying to look a metaclasses to do something fancy like this: ############################################################################### # 0x01: ModeCommand ############################################################################### PacketModeCommand = ( ('name', "ModeCommand"), ('id', 0x01), ('action', 8), # size in bytes ('command', 8), ) ############################################################################### # Add some kind of class factory here: (metaclass, type(name, bases, dict) -> a new type, ???) ############################################################################### """???""" ############################################################################### # Add some kind of class factory here ############################################################################### """Hey this would be cool if I had a class just by making the dictionary.""" x = ModeCommand(mode=1, command=0) print x[:] print x So that I could make a dictionary that would basically define my classes on the fly. This would be simple enough for everyone to maintain and would make changes to the format of all the classes relatively simple. (So far the only way that I have thought of doing this is will a parsing script but that would be lame.) Of course, this becomes more and more complicated as my classes (representing packets) start having objects of their own and functions that need to be defined on the fly too... but for now I would be nice to know if this idea is possible. Thanks in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: From paul.hankin at gmail.com Fri May 23 11:33:56 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Fri, 23 May 2008 08:33:56 -0700 (PDT) Subject: Producing multiple items in a list comprehension References: <5RiZj.165543$ng7.151222@en-nntp-05.dc1.easynews.com> Message-ID: <264b0b3b-e755-45f6-8e6f-9e853af9232a@c58g2000hsc.googlegroups.com> On May 22, 7:21 pm, "Joel Koltner" wrote: > Is there an easy way to get a list comprehension to produce a flat list of, > say, [x,2*x] for each input argument? > > E.g., I'd like to do something like: > > [ [x,2*x] for x in range(4) ] [x * i for x in xrange(4) for i in xrange(1, 3)] -- Paul Hankin From mattheww at chiark.greenend.org.uk Sun May 25 11:36:10 2008 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 25 May 2008 16:36:10 +0100 (BST) Subject: unittest: Calling tests in liner number order References: <69t0qlF356llmU1@mid.uni-berlin.de> <69tcmkF357g9nU1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: >I don't see this as something that can be solved by ordering tests - >*especially* not on a per-method-level as the OP suggested, because I >tend to have test suites that span several files. unittest already runs multiple test suites in the order you specify (which is another clue that running tests in order is not evil). I suspect unittest's choice of alphabetical order for the tests within a suite is more an artefact of its original Java implementation than anything else. -M- From Lie.1296 at gmail.com Sun May 18 10:25:00 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 18 May 2008 07:25:00 -0700 (PDT) Subject: python newbie: some surprises References: <67b60370-bed9-4f43-b401-25ce2fd89522@t54g2000hsg.googlegroups.com> Message-ID: On May 8, 2:06?pm, v4vijayakumar wrote: > When I started coding in python, these two things surprised me. > > 1. my code is inconsistently indented with the combination of tabs and > spaces. Even lines looked intended, but it is not. The problem is in tab not Python, there is no convention on how many spaces should tab be treated, python (by default) assumes a tab to be equal to 8 spaces, but not everyone thinks the same, some code editor might consider it as 4 spaces or 2 spaces. In most python-oriented code editor, a tab might be automatically replaced with four spaces. > 2. python requires to pass "self" to all instance methods No, python doesn't requires self to be passed to all instance methods, python passes the "current instance" of a class to the first argument of a function inside the class, this first argument can be named anything, although it is traditionally named as self. In other programming languages, this current instance is implicitly passed (Me in VB, this in C/C++). > and I missed ":" often. :) Not in your smiley though. :) From ivan.illarionov at gmail.com Sun May 11 00:26:10 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Sun, 11 May 2008 04:26:10 +0000 (UTC) Subject: do you fail at FizzBuzz? simple prog test References: <39709320-66e1-40e9-a351-c769c9a94585@x41g2000hsb.googlegroups.com> Message-ID: On Sat, 10 May 2008 18:12:37 -0700, globalrev wrote: > http://reddit.com/r/programming/info/18td4/comments > > claims people take a lot of time to write a simple program like this: > > > "Write a program that prints the numbers from 1 to 100. But for > multiples of three print "Fizz" instead of the number and for the > multiples of five print "Buzz". For numbers which are multiples of both > three and five print "FizzBuzz". > > for i in range(1,101): > if i%3 == 0 and i%5 != 0: > print "Fizz" > elif i%5 == 0 and i%3 != 0: > print "Buzz" > elif i%5 == 0 and i%3 == 0: > print "FizzBuzz" > else: > print i > > > is there a better way than my solution? is mine ok? ['%s%s' % (not i%3 and 'Fizz' or '', not i%5 and 'Buzz' or '') or str(i) for i in xrange(1, 101)] -- Ivan From lists at cheimes.de Sat May 17 17:05:19 2008 From: lists at cheimes.de (Christian Heimes) Date: Sat, 17 May 2008 23:05:19 +0200 Subject: help compiling Python on vs 2008! In-Reply-To: References: Message-ID: Matthieu Brucher schrieb: > Hi, > > I did not manage to build extension with distutils with Python compiled with > VS different than 2003. The need for 2003 was hard-coded in distutils. > You can try building extensions with VS2008 with Scons. This is what I do a > lot, and everything works fine as long as the interface does not use > standard structures (like FILE, custom structures are fine) or objects > allocated in the extension is freed in the extension. Python 2.5 is compiled with VS 2003. Neither VS 2005 nor 2008 are officially supported. You can compile extensions with a different version of MS VC but it can get you in a lot of trouble. Every version of the VS Compiler uses its own C Runtime Library (MSVCRT). You can't share some resources like allocated memory and FILE* objects between MSVCRTs. Christian From Lie.1296 at gmail.com Wed May 14 00:51:05 2008 From: Lie.1296 at gmail.com (Lie) Date: Tue, 13 May 2008 21:51:05 -0700 (PDT) Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <5b0e3f70-afde-4480-8713-e7113b1250d7@x35g2000hsb.googlegroups.com> <1f537717-00d0-48ee-99b6-7125b96a6133@t12g2000prg.googlegroups.com> <68t4o0F2vaoncU1@mid.uni-berlin.de> <2a32179a-9439-449c-bd07-fff6a4075aee@s50g2000hsb.googlegroups.com> <7ee5dffd-df8f-46f0-bd78-c81ac0418a9a@d77g2000hsb.googlegroups.com> <65ef773e-a1c3-4adb-a18b-e8b8451efe5e@b5g2000pri.googlegroups.com> Message-ID: <5ef77e00-7d9c-44fa-ad4c-dd2b57fe53c2@z16g2000prn.googlegroups.com> On May 13, 11:36 pm, Dave Parker wrote: > > ... there's something that feels very unnatural about writing English as code. > > I think it is ironic that you think Flaming Thunder is unnatural > because it is more English-like, when being English-like was one of > Python's goals: "Python was designed to be a highly readable language. > It aims toward an uncluttered visual layout, using English keywords > frequently where other languages use punctuation."http://en.wikipedia.org/wiki/Python_(programming_language)#Syntax_and... Python was designed to be _highly readable language_. It aims toward _uncluttered visual layout_, using _English keywords ... where other languages uses punctuation_. Where in that statement, that says Python aims to be English-like? It only says Python uses English keywords instead of punctuations such as curly braces, &&, ||, etc which is remotely far away from trying to be English-like. What I see is that, FT in its current form, aims to be a readable language, which doesn't concern itself for cluttering the code's visual layout. Verbosity ? Readability I even remembered someone saying that probably one of Python's goal is to make you from press only the necessary keystrokes. If I don't misremember it, it was in Thinking in Python. > > Just using your "Set ... to" idiom, rather than a > > regular = assignment, makes things much more wordy, without improving > > readability. > > I think it does improve readability, especially for people who are not > very fluent mathematically. But it hurts readability for people who prefers simplicity over everything and that means you've just violated KISS design principle (Keep It Simple, Stupid) which is also a persistent feature in UNIX philosophy (Small is beautiful, Rule of Simplicity), and Python's Zen (Simple is better than Complex). > Also, in Python how do you assign a symbolic equation to a variable? > Like this? > > QuadraticEquation = a*x^2 + b*x + c = 0 > Last time I checked, it was a syntax error there. > Set statements avoid the confusion of multiple equal signs when > manipulating symbolic equations: > > Set QuadraticEquation to a*x^2 + b*x + c = 0. > (snip) From retreved at gmail.com Tue May 20 14:53:39 2008 From: retreved at gmail.com (Mark d.) Date: Tue, 20 May 2008 11:53:39 -0700 (PDT) Subject: iterate start at second row in file not first References: <5be1e521-3a32-45f6-9812-5efed0187920@b9g2000prh.googlegroups.com> Message-ID: <82eae2b4-61a5-4cc9-8fcb-d448e71bfc7d@f36g2000hsa.googlegroups.com> How about: mov = open(afile) line = mov.readline() ...(process your ':' line) for line in mov.readlines(): ... On May 20, 1:34 pm, notnorweg... at yahoo.se wrote: > i have a big file with sentences, the first file of each sentence > contains a colon(:) somewher eon that line > i want to jump past that sentence. > > if all(x != ':' for x in line): > > this way i can check but i dont want to check for every line in the > whole file, quite unnecessary when i only need to > chekc the first line. > > so the question is, when dealign with iterators like: > mov = open(afile) > for line in mov: > do y > > how do i jump the first step there? i dont want to iterate the first > row...how do i start at the second? From gagsl-py2 at yahoo.com.ar Thu May 8 05:39:59 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 08 May 2008 06:39:59 -0300 Subject: how to use subprocess.Popen execute "find" in windows References: <5666ed04-8a2f-4dad-b7bc-3e3c3c084f03@f24g2000prh.googlegroups.com> <708883cd-5cc8-4507-b91e-841dd10d149a@c19g2000prf.googlegroups.com> <8c5a14fe-dd65-4ed0-bcd5-384ba3e6ffe2@q27g2000prf.googlegroups.com> Message-ID: En Wed, 07 May 2008 23:29:58 -0300, escribi?: > On 5?7?, ??9?45?, Justin Ezequiel > wrote: >> On May 6, 5:19 pm, clyf... at gmail.com wrote: >> >> > p1 = Popen(['netstat', '-an'], stdout = PIPE) >> > p2 = Popen(['find', '"445"'], stdin = p1.stdout, stdout = PIPE) >> > print p2.stdout.read() >> >> > It doesn't work. >> > Because subprocess.Popen execute "find" like this. >> >> > C:\>find \"445\" >> >> > It adds a '\' before each '"'. >> > How to remove the '\'? >> > Thank you. >> >> cannot help with the backslashes but try findstr instead of find > > Thank you. > findstr doesn't need quotes, so it works. Build the command line yourself -instead of using a list of arguments-. Popen doesn't play with the quotes in that case: p1 = Popen(['netstat', '-an'], stdout = PIPE) # using list p2 = Popen('find "445"', stdin = p1.stdout, stdout = PIPE) # using str print p2.communicate()[0] -- Gabriel Genellina From none at this.time Mon May 26 16:57:28 2008 From: none at this.time (Paul Miller) Date: Mon, 26 May 2008 16:57:28 -0400 Subject: Tkinter = Rodney Dangerfield? References: Message-ID: <3081d$483b2438$3799@news.teranews.com> On Sun, 17 Feb 2008 11:35:35 -0800, MartinRinehart wrote: > Tkinter gets no respect. But IDLE's a Tkinter-based app and every > example I've Googled up shows Tkinter as needing about half as much code > as wx to do the same job. I'm beginning to Tkinter up my language > application. Am I making a big mistake? I like Tkinter quite a bit. I think it's relatively intuitive, and I like the Canvas and Text widgets a lot. You might check out _Thinking in Tkinter_ at http://www.ferg.org/ thinking_in_tkinter/index.html . -- code.py: a blog about Python. http://pythonista.wordpress.com ** Posted from http://www.teranews.com ** From miller.paul.w at gmail.com Sun May 25 22:29:18 2008 From: miller.paul.w at gmail.com (miller.paul.w at gmail.com) Date: Sun, 25 May 2008 19:29:18 -0700 (PDT) Subject: Performance of Python builtins References: Message-ID: <4455e670-d3af-4f26-9eb4-51f46581d5d6@l42g2000hsc.googlegroups.com> On May 25, 9:43?pm, "Terry Reedy" wrote: > wrote in message > > news:d7549dfd-6770-4924-8f0c-1746642bd8a4 at k37g2000hsf.googlegroups.com... > | Is there any place outside the actual C source for Python that has > | information about the performance of Python's built-in operations? > > Unfortunately no. ?Guido does not want to put guarantees in the language > definition, so there is no urgency to document this. ?An auxiliary doc > might be accepted. ?But the people who could write such a thing are busy > doing otherwise. ?Certainly, no one has volunteered to write *and update* > such. I see. Just to be clear, though, I wasn't looking for "guarantees" as such, like (I believe) the STL sometimes provides. I was just looking for some idea of what current implementations' performance characteristics are. I suppose I could probably create such a resource. Keeping it updated would be another thing entirely, since I don't really want to monitor every single commit to Python's svn repository. Hypothetically, if someone made such a document, do you think it could be arranged for that person to be notified whenever CPython's implementation changes to invalidate it? From dfnsonfsduifb at gmx.de Fri May 23 18:59:58 2008 From: dfnsonfsduifb at gmx.de (Johannes Bauer) Date: Sat, 24 May 2008 00:59:58 +0200 Subject: Assignment and comparison in one statement Message-ID: Hello group, I'm just starting with Python and am extremely unexperienced with it so far. Having a strong C/C++ background, I wish to do something like if (q = getchar()) { printf("%d\n", q); } or translated to Python: if (p = myfunction()): print p However, this "assignment and comparison" is not working. What's the "Python way" of doing this kind of thing? Thanks a lot, Johannes -- "Wer etwas kritisiert muss es noch lange nicht selber besser k?nnen. Es reicht zu wissen, da? andere es besser k?nnen und andere es auch besser machen um einen Vergleich zu bringen." - Wolfgang Gerber in de.sci.electronics <47fa8447$0$11545$9b622d9e at news.freenet.de> From bearophileHUGS at lycos.com Tue May 20 09:24:02 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 20 May 2008 06:24:02 -0700 (PDT) Subject: compressing short strings? References: <7xy7658k8o.fsf_-_@ruckus.brouhaha.com> <69fn92F329s6vU2@mid.dfncis.de> <3216e39c-3228-4584-bb1f-916350a23538@i76g2000hsf.googlegroups.com> Message-ID: bearophile: > So you need to store only this 11 byte long string to be able to > decompress it. Note that maybe there is a header, that may contain changing things, like the length of the compressed text, etc. Bye, bearophile From zapwireDASHgroups at yahoo.com Thu May 22 16:53:16 2008 From: zapwireDASHgroups at yahoo.com (Joel Koltner) Date: Thu, 22 May 2008 13:53:16 -0700 Subject: Producing multiple items in a list comprehension References: <5RiZj.165543$ng7.151222@en-nntp-05.dc1.easynews.com> <5PjZj.78772$%15.70394@bignews7.bellsouth.net> Message-ID: <33lZj.143344$Tj3.138473@en-nntp-02.dc1.easynews.com> "inhahe" wrote in message news:5PjZj.78772$%15.70394 at bignews7.bellsouth.net... > i figured out a solution > > sum([x,2*x] for x in range(4)],[]) #not tested Nice... thanks; I probably had seen code using 'sum' to flatten but hadn't actually understood how it worked. After playing around some it's now clear... (Add one more opening bracket to your solution to make the interpreter happy -- I know you know this and it was missed only due to not actually trying it ought) ---Joel From casey.mcginty at gmail.com Thu May 15 04:32:01 2008 From: casey.mcginty at gmail.com (Casey McGinty) Date: Wed, 14 May 2008 22:32:01 -1000 Subject: Making Variable Text Output More Pythonic? Message-ID: Hi, I have some classes that print variable outputs depending on their internal state, like so: def __str__(self): out = [] if self.opt1: out += ['option 1 is %s' % self.opt1'] if self.opt2: out += ['option 2 is %s' % self.opt2'] .... return '\n'.join(out) Is there any way to make this cleaner? -------------- next part -------------- An HTML attachment was scrubbed... URL: From nik600 at gmail.com Tue May 27 08:18:46 2008 From: nik600 at gmail.com (nik600) Date: Tue, 27 May 2008 14:18:46 +0200 Subject: integration with browser In-Reply-To: <6a2bs6F35a5cmU1@mid.uni-berlin.de> References: <69vmlgF35akucU1@mid.uni-berlin.de> <6a0722F33j3q5U1@mid.uni-berlin.de> <6a2bs6F35a5cmU1@mid.uni-berlin.de> Message-ID: <9469c3170805270518p631c50acqfbb7713962a34f5a@mail.gmail.com> On Tue, May 27, 2008 at 2:07 PM, Diez B. Roggisch wrote: >> Web developers usually check only 3 browser >> IE >> FF >> Opera >> >> I know that using an external engine limits the portability of the >> solutions, but i need something that works exaclty as the browser. > > You know that Webkit is the engine behind Safari? And one of the more > compliant implementations out there - millions of mac-users only use > Safari. > > > Diez > -- > http://mail.python.org/mailman/listinfo/python-list > No, i don't know that. I'll test it immediatly, thanks ;-) -- /*************/ nik600 https://sourceforge.net/projects/ccmanager https://sourceforge.net/projects/reportmaker https://sourceforge.net/projects/nikstresser From nick at craig-wood.com Tue May 20 04:30:05 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 20 May 2008 03:30:05 -0500 Subject: scaling problems References: <87y765hitf.fsf@benfinney.id.au> <69fbhgF2uih6aU5@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch wrote: > On Tue, 20 May 2008 13:57:26 +1000, James A. Donald wrote: > > > The larger the program, the greater the likelihood of inadvertent name > > collisions creating rare and irreproducible interactions between > > different and supposedly independent parts of the program that each > > work fine on their own, and supposedly cannot possibly interact. > > How should such collisions happen? You don't throw all your names into > the same namespace!? If you ever did a lot of programming in C with large projects you have exactly that problem a lot - there is only one namespace for all the external functions and variables, and macro definitions from one include are forever messing up those from another. I suspect the OP is coming from that background. However python doesn't have that problem at all due to its use of module namespaces - each name is confined to within a module (file) unless you take specific action otherwise, and each class attribute is confined to the class etc. >From the Zen of Python "Namespaces are one honking great idea -- let's do more of those!" - as a battle scarred C programmer I'd agree ;-) -- Nick Craig-Wood -- http://www.craig-wood.com/nick From sjdevnull at yahoo.com Fri May 16 13:46:58 2008 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: Fri, 16 May 2008 10:46:58 -0700 (PDT) Subject: Thread killing - I know I know! References: Message-ID: <6fda9c2c-84fe-4339-8ce2-25b6d6b97ba4@t54g2000hsg.googlegroups.com> On May 16, 11:40 am, Roger Heathcote wrote: > Hello everyone, this is my first post so hello & please be gentle! > > Despite many peoples insistence that allowing for the arbitrary killing > of threads is a cardinal sin and although I have no particular threading > problem to crack right now I remain interest in the taboo that is thread > killing. The real world and it's data are messy and imperfect and I can > think of several scenarios where it could be useful to be able to bump > off a naughty thread, especially when using/testing unstable 3rd party > modules and other code that is an unknown quantity. When possible, use another process _especially_ for things like this. That way you have more isolation between yourself and the unknown/ unstable code, and killing processes is well-understand and considered less harmful (precisely because of the greater isolation). In general, use processes when you can and threads only when you must. OS designers spent a lot of energy implementing protected memory, no sense throwing out a fair chunk of that hard work unless you actually need to. From alex.m.gusarov at gmail.com Thu May 29 07:58:10 2008 From: alex.m.gusarov at gmail.com (Alex Gusarov) Date: Thu, 29 May 2008 18:58:10 +0700 Subject: Unit tests? In-Reply-To: References: Message-ID: Thx, it's quite enough for a start. Yes, googling is almost ultimate answer for such questions, sorry for uneasiness. > Try googling "python unit test". I did it, and amongst the first hits > were: > > * docs.python.org/lib/module-unittest.html > > * http://www.diveintopython.org/unit_testing/index.html > > -- > Arnaud From dmitrey.kroshko at scipy.org Wed May 7 16:13:40 2008 From: dmitrey.kroshko at scipy.org (dmitrey) Date: Wed, 7 May 2008 13:13:40 -0700 (PDT) Subject: howto print binary number Message-ID: hi all, could you inform how to print binary number? I.e. something like print '%b' % my_number it would be nice would it print exactly 8 binary digits (0-1, with possible start from 0) Thank you in advance, D From gagsl-py2 at yahoo.com.ar Sun May 4 02:04:27 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 04 May 2008 03:04:27 -0300 Subject: word shifts References: Message-ID: En Sun, 04 May 2008 02:17:07 -0300, dave escribi?: > Hello, > > I made a function that takes a word list (one word per line, text file) > and searches for all the words in the list that are 'shifts' of > eachother. 'abc' shifted 1 is 'bcd' > > Please take a look and tell me if this is a viable solution. > > def shift(word, amt): > ans = '' > for letter in word: > ans = ans + chr((ord(letter) - ord('a') + amt) % 26 + ord('a')) > return ans > > def fileshift(x): > fin = open(x) > d = {} > for line in fin: > d[line.strip()] = [1] > for i in range(1, 26): > ite = shift(line.strip(), i) > if ite in d: > print ite > > > Any tips/suggestions/critiques greatly appreciated.. I'm trying to > teach myself Python (and still beginning) and would love any helpful > info. First, looking at the code, you're evaluating line.strip() a lot of times; I'd avoid it. Looks like you're using a dictionary just for the keys - the set type is more adequate here (see http://docs.python.org/lib/types-set.html ). In any case, I'd use a value like None instead of [1] But I'd use a different algorithm. Instead of generating all posible shifts for a given word, I'd substract the newly read word from each previous words (here, "substract two words" means substract the character code for corresponding positions, modulo 26). Shifted words, when substracted, have the same number on all positions. -- Gabriel Genellina From maxm at mxm.dk Tue May 6 05:43:49 2008 From: maxm at mxm.dk (Max M) Date: Tue, 06 May 2008 11:43:49 +0200 Subject: Python MIDI in 2008 In-Reply-To: <1076a133-4376-4b96-a06b-4bb990ec3f42@f63g2000hsf.googlegroups.com> References: <1076a133-4376-4b96-a06b-4bb990ec3f42@f63g2000hsf.googlegroups.com> Message-ID: <48202855.4020905@mxm.dk> Maciej Blizin'ski skrev: > For the last couple of days, I've been looking for a Python midi > library. I'm generally interested in sending MIDI events via ALSA. It > seems like everything out there is pretty old; packages are from 2003 > or 2005. > existing or very old software packages > - http://www.mxm.dk/products/public/pythonmidi/ -- no realtime support This is old in the sense that it has been a while since I wrote it. But it is virtually bug free, so nothing much is happening. The midi standard does not change so there is no real reason to change/upgrade it. It is currently being used by the very popular "frets on fire" http://fretsonfire.sourceforge.net/documentation/source/ It does not have real time support even though I did write it with that support in mind. I just never got around to write it as I did not need it myself. I also developed it on Windows and I found it to be a bore to get real time midi working. It would probably be easier now that I am on Linux. Well I just thought I would mention that it is not dead. Merely middle aged. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From tjreedy at udel.edu Tue May 27 23:30:51 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 27 May 2008 23:30:51 -0400 Subject: When was feature FOO added to Python? (was: decorators when?) References: <3m0o34hbb0c6rpr6ec0qh3hlkaagt8pfi5@4ax.com> <87zlqbs60b.fsf@benfinney.id.au> Message-ID: "Ben Finney" wrote in message news:87zlqbs60b.fsf at benfinney.id.au... | David C. Ullrich writes: | | > What version added decorators (using the @decorator syntax)? | > | > (Is there a general way I could have found out the answer myself?) | | For standard library features, the documentation for a module | usually says "(New in 2.4)" or | "(Changed in 2.4)" or the like for features that appeared in a | particular version. I think this is manually done by the | documentation maintainers, though. | | For features of the language (like decorators), the language reference | is the place that *describes* the | features; but I don't see any similar "(New in 2.4)" annotations, so | e.g. doesn't mention | when the decorator syntax appeared in the language. | | Any documentation maintainers reading: Please consider updating the | documents to give this useful "(New in 2.x)" or "(Changed in 2.x)" | annotation for just such a situation. | | You can get closer to the answer by browsing the "What's New in | Python" documents by | version. Missing 'New' or 'Changed' annotations might be considered doc bugs. Certainly there should be one for decorators. Anyone who wants such omissions fixed should file a report on bugs.python.org listing the *specific* annotations you think should be added and where. Cite which documents you used as sources so they can be checked. This is something that a new volunteer could do, since it does not need the special skill of older volunteers. Note 1: probably best to check against 2.6 docs, as I am not sure that fixes will go back 2.5. Note 2: the 3.0 docs start with a 'clean slate'. All such annotations are or should be wiped. But changes in 3.1 will be annotated as usual. TJR From usenet1.3.CalRobert at SpamGourmet.Com Thu May 8 06:25:54 2008 From: usenet1.3.CalRobert at SpamGourmet.Com (Robert Maas,) Date: Thu, 08 May 2008 03:25:54 -0700 Subject: The Importance of Terminology's Quality References: Message-ID: > From: "xah... at gmail.com" > the importance of naming of functions. I agree, that's a useful consideration in the design of any system based on keywords, such as names of functions or operators. (I'm not using "keyword" in the sense of a symbol in the KEYWORD package.) > the naming in Mathematica, as Stephen Wolfram implied in his blog > above, takes the perspective of naming by capturing the essense, or > mathematical essence, of the keyword in question. For concepts adapted from mathematics, that naming meta-convention makes sense. For concepts adapted from data-processing, it's not so clearly good. > lambda, widely used as a keyword in functional languages, is > named just Function in Mathematica. That makes sense, but then what does Mathematica call the special operator which Common Lisp calls Function? Or is that not provided, and the programmer must case-by-case handcode what they really mean? (function foo) == (symbol-function 'foo) ;so FUNCTION not really needed there (function (lambda (x) (+ x y)) ;y is a lexical variable to be encapsulated ; into the resultant closure How would you do something like that in mathematica? > Module, Block, in Mathematica is in lisp's various let* > The lisp's keywords let, is based on the English word let. No, that's not correct. It's based on the mathematical use of "let": Let R be the complete ordered field of real numbers. Let S be the subset of R consisting of numbers which satisfy equations expressed in transcendental functions with rational parameters. Prove that S is dense in R. (Yeah, the question is trivial, but I'm just showing how "let" might be used.) I see nothing wrong with LET used in that way in Lisp. Bind would be good too. I don't like Module or Block at all, because those words convey nothing about binding some temporary local name to represent some globally-definable concept, and they actually mis-lead because module can mean either something like a vector space over a ring, or a set of functions/methods that serve some small problem domain within a larger library of functions/methods, or a set of lectures on a single-topic within a curriculum, while Block sounds more like just some random consecutive interval of statements rather having nothing specific to do with bindings. TAGBODY or PROGN would be more properly called Block perhaps. > One easy way to confirm this, is taking a keyword and ask a wide > audience, who doesn't know about the language or even unfamiliar of > computer programing, to guess what it means. That is a biassed question because the only options are the words you choose in advance. Better would be to reverse the question: Ask random people on the street what they would like to call these concepts: 1 You set up a temporary relation between a name and some datum, such that all references to that name give you that same datum. For example you might set up the name 'n' to temporarily mean 5. Fill in the missing word: (word (n 5) ) 2 You set up a rule by which one step of data-processing is performed, taking input to produce output. For example you set up a rule by which the input value is divided by two if it's even but multiplied by three and then 1 added if it was odd. Fill in the missing word: (word (n) ) 3 You set up a rule as above, but also give it a permanent name. Fill in the missing word: (word collatz (n) ) 4 You already have a rule that takes two input data and produces one output. (oldword foo (x y) ) You now know one of the two inputs, and that info won't change for a while, and you hate to keep repeating it. So you want to define a new rule that has that one known parameter built-in so that you only have to say the *other* parameter each time you use the new rule. Fill in the missing newword: (newword foo ) So I'd choose words: 1=let 2=lambda 3=defun 4=curry. What words would a typical man on the street choose instead? > The name regex has done major hidden damage to the computing industry I have my own gripe against regular expressions ("regex" for short). I hate the extremely terse format, with horrible concoctions of escape and anti-escape magic characters, to fit within Unix's 255-character limit on command lines, compared to a nicely s-expression nested notation that would be possible if regex hadn't entrenched itself so solidly. From PatrickMinnesota at gmail.com Wed May 14 20:53:30 2008 From: PatrickMinnesota at gmail.com (PatrickMinnesota) Date: Wed, 14 May 2008 17:53:30 -0700 (PDT) Subject: Passing functions around and executing Message-ID: <20fafcf9-a311-4f9e-ad61-ee8be2e1d4f6@y21g2000hsf.googlegroups.com> I've been reading the docs and looking for an answer and seem stuck. I'm either not looking in the right places or not understanding what I'm reading. I have a bunch of functions. I want to put them in a list. Then I want to pass that list into another function which does some setup and then loops through the list of passed in functions and executes them. Some of them need arguments passed in too. Can someone point me to where to read about this? I know it's do-able since it's basically doing something like a callback would do. Thanks for any pointers. From __peter__ at web.de Fri May 30 11:41:57 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 30 May 2008 17:41:57 +0200 Subject: Python 2.5.2 on Ubuntu Hardy Utf-8-Euro error References: Message-ID: Josep wrote: > I'm playing with an application framework (or kinda) that's developed > with python, and it throws this error: > > >> File >> "/usr/lib/python2.5/site-packages/Dabo-0.8.3-py2.5.egg/dabo/db/dCursorMixin.py", >> line 281, in execute >> sql = unicode(sql, self.Encoding) >> LookupError: unknown encoding: utf_8_euro > > At the application (DABO) mailing list, they have pointed that this has > to be a Python issue. As I'm a totally python newbie, I would ask if > somebody has experimented this kind of error, and if there is any known > solution. I've found no clue searching at Google right now. > > My Python version is 2.5.2, Ubuntu Hardy .deb package. Python might get confused by an @EURO suffix in the locale: $ LANG=de_DE.UTF-8 at EURO $ python -c"import locale; print locale.getdefaultlocale()" ('de_DE', 'utf_8_euro') Try setting the LANG environment variable to something like $ LANG=de_DE.UTF-8 $ python -c"import locale; print locale.getdefaultlocale()" ('de_DE', 'UTF8') before you run your program (use ca_ES or whatever you need instead of de_DE). Peter From bruno.42.desthuilliers at websiteburo.invalid Fri May 16 08:23:34 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 16 May 2008 14:23:34 +0200 Subject: default object comparison considered harmful? In-Reply-To: References: Message-ID: <482d7cc6$0$10756$426a34cc@news.free.fr> Kay Schluehr a ?crit : > On 16 Mai, 10:03, "A.T.Hofkamp" wrote: >> Hello all, >> >> Yesterday we found the cause of a bug that has caused problems for a long time. >> It appeared to be the following: >> >> class A(object): >> pass >> >> print min(1.0, A()) >> >> which is accepted by Python even though the A() object is not numerical in >> nature. >> >> The cause of this behavior seems to be the compare operation of the object >> class. >> >> Is there a way to disable this behavior in Python (other than deriving a new >> 'object-like' class that doesn't do comparisons?) >> > Are you sure you don't want to use a statically typed language that > captures all type errors just by inspecting your source code? This is not necessarily a static vs dynamic typing problem. The following code will raise a TypeError for very good reasons: print 1.0 + A() From jorge.vargas at gmail.com Tue May 6 05:07:53 2008 From: jorge.vargas at gmail.com (Jorge Vargas) Date: Tue, 6 May 2008 05:07:53 -0400 Subject: config files in python In-Reply-To: <482017EA.40706@egenix.com> References: <44f9662d-a88d-418c-a11d-b7b472b01fc3@j33g2000pri.googlegroups.com> <87332548-4f15-49c3-8c92-4aa20e355747@n1g2000prb.googlegroups.com> <482017EA.40706@egenix.com> Message-ID: <32822fe60805060207w46752243tdb0e4cad19ffa78b@mail.gmail.com> On Tue, May 6, 2008 at 4:33 AM, M.-A. Lemburg wrote: > > On 2008-05-06 01:16, Matimus wrote: > > > On May 4, 11:35 pm, sandipm wrote: > > > > > Hi, > > > In my application, I have some configurable information which is used > > > by different processes. currently I have stored configration in a > > > conf.py file as name=value pairs, and I am importing conf.py file to > > > use this variable. it works well > > > > > > import conf > > > print conf.SomeVariable > > > > > > but if I need to change some configuration parameteres, it would need > > > me to restart processes. > > > > > > I want to store this data in some conf file (txt) and would like to > > > use it same way as I am using these variables as defined in py > > > files. > > > > > > one solution I can think of is writing data as a dictionary into conf > > > file. and then by reading data, apply eval on that data. and update > > > local dict? but this is not a good solution.... > > > > > > any pointers? > > > > > > Sandip > > > > > > > I would load the configuration file using `imp.load_source'. This > > allows you to load the config file by filename, and gets away from the > > issue of accidentally importing a file somewhere else in pythons > > search path. Also, calling imp.load_source will reload the module when > > called a second time. > > > > > > > http://docs.python.org/lib/module-imp.html > > > > Why not just use execfile() ? > > http://www.python.org/doc/2.2.3/lib/built-in-funcs.html > that is very bad for this case, from what he is suggesting this is a server install so you are basically giving a vector of remote code execution (same with the first approach) but then execfile has the issue that it goes into your current namespace possibly creating a namespace crash which is even worst because an attacker can shallow say your auth module with something that will just return. > > > > > [conf.py] > > a = 1 > > b = 2 > > class c: > > a = "hello" > > b = "world" > > [/end conf.py] > > > > > > > > > > > > > > > > conf = imp.load_source("conf", "./conf.py") > > > > > conf.a > > > > > > > > > > > > > > 1 > > > > > > > > > > > > > > conf.b > > > > > > > > > > > > > > 2 > > > > > > > > > > > > > > conf.c.a > > > > > > > > > > > > > > 'hello' > > > > > > > > > > > > > > conf.c.b > > > > > > > > > > > > > > 'world' > > > > > > > > There are so many ways potential solutions to your problem that, > > without any more details, it is hard to suggest anything. > > > > Here are some potential solutions: > > > > ConfigParser - module for handling ini files > > xml - several built-in modules for handling XML files > > sqlite3 - a `lite' SQL database built-in in python 2.5 + (can be used > > for config data) > > windows registry - _winreg module > > pickle - serialize python objects > > marshal - similar to pickle, only works for simple objects > > > > Those are just the built-in solutions. If you wanna look at 3rd party > > solutions, prepare for overload. The number of alternative INI parsers > > alone is staggering. > > > > Also, there are many ways to organize your data and use a solution > > similar to what you are already using. > > > > I guess what I'm trying to say is... don't roll your own, it would be > > a waste of time, this problem has been solved 100s of times. That is, > > unless you want to do it for fun. > > > > Matt > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > -- > Marc-Andre Lemburg > eGenix.com > > Professional Python Services directly from the Source (#1, May 06 2008) > >>> Python/Zope Consulting and Support ... http://www.egenix.com/ > >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ > >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ > ________________________________________________________________________ > > :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: > > > eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 > D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg > Registered at Amtsgericht Duesseldorf: HRB 46611 > > > -- > http://mail.python.org/mailman/listinfo/python-list > From renesd at gmail.com Fri May 2 05:47:26 2008 From: renesd at gmail.com (illume) Date: Fri, 2 May 2008 02:47:26 -0700 (PDT) Subject: dropping win98 support? was Re: Python 2.6 and wrapping C libraries on Windows References: <_X8Sj.3499$XI1.3261@edtnps91> <9a4cc17e-deb2-4219-a093-bff5c1a20d5e@s33g2000pri.googlegroups.com> <372ae26a-d772-4182-aa4b-64330626d60f@l25g2000prd.googlegroups.com> Message-ID: <86718726-ca5b-4f84-9fc9-7e13bcd25140@q24g2000prf.googlegroups.com> On May 2, 8:37?am, "Terry Reedy" wrote: > "illume" wrote in message > > news:372ae26a-d772-4182-aa4b-64330626d60f at l25g2000prd.googlegroups.com... > | Ah, why is that? > > Were any of the reasons given inhttp://www.python.org/dev/peps/pep-0011/ > unclear? > It appears you are already aware of MS's non-support of Win98 Hello, It seems the main reason is for ease of maintenance. However the Pep title is misleading with regards to win9x+winMe+win2k - which is where my confusion, questions and argument came from. "Title: Removing support for little used platforms" There are still *lots* of people who still use win95, 98, 98se, me, and win2k - as shown by the statistics I linked to in a previous post. If you want more statistics about the number of people using what OS they are fairly easy to find with a search engine. One day win9x will be finally dead, but that's not yet(and the w3c stats show it's usage actually increasing in march!). It is probably way too late in the process to put back code - and as you say no python developers have volunteered. So I won't argue any more for it to come back. We'll just have to recommend a different python implementation than 2.6 or 3.0 for people who want to support people with these old computers. cheers, From deets at nospam.web.de Tue May 13 10:46:32 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 13 May 2008 16:46:32 +0200 Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <2b66a86e-5a05-4262-b3c9-4703b0ae3372@d1g2000hsg.googlegroups.com> <5b0e3f70-afde-4480-8713-e7113b1250d7@x35g2000hsb.googlegroups.com> <1f537717-00d0-48ee-99b6-7125b96a6133@t12g2000prg.googlegroups.com> <68t4o0F2vaoncU1@mid.uni-berlin.de> Message-ID: <68tnvfF2t99pnU1@mid.uni-berlin.de> Dave Parker wrote: >> Don't let yourself be irritated by castironpi > > I'm not the sort to get irritated by anyone. There is value in all > interaction. Flaming Thunder is itself the averaging of interactions > with many computer languages and conversations with many people, so as > to create a language that allows people to tell a computer what they > want it to do, without having to know very much about how the computer > does it. > Well, if your actual goal is to create traffic to promote your own product (I presume so from your mailaddress) then I'm not surprised that you not *really* care who is responding how... Diez From darcy at druid.net Wed May 28 06:43:10 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Wed, 28 May 2008 06:43:10 -0400 Subject: A quick question In-Reply-To: References: Message-ID: <20080528064310.6b2d4f6e.darcy@druid.net> On Wed, 28 May 2008 10:25:01 -0000 "James" wrote: > Hey everyone, > > I just started using python and cant figure this out, I'm trying to > make a program where someone types in a word and the program gives it > back backwards. For example if the person puts in "cat" I want the > program to give it back as "tac" and what it does is prints out 3,2,1. > How can I get these integers to print as letters? This is what I have, > > word = raw_input("Type a word:") > start = len(word) > > for letter in range(start, 0, -1): > print letter Ignore my previous message. Too early. Here is your script: word = raw_input("Type a word:") for i in range(len(word), 0, -1): print word[i] Sorry about that. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From vijayakumar.subburaj at gmail.com Fri May 9 09:37:30 2008 From: vijayakumar.subburaj at gmail.com (v4vijayakumar) Date: Fri, 9 May 2008 06:37:30 -0700 (PDT) Subject: python newbie: some surprises References: <67b60370-bed9-4f43-b401-25ce2fd89522@t54g2000hsg.googlegroups.com> <48240fe6$0$5108$426a34cc@news.free.fr> Message-ID: <53e8ab1c-d786-493b-82df-66055949172a@w4g2000prd.googlegroups.com> On May 9, 1:48 pm, Bruno Desthuilliers wrote: > v4vijayakumar a ?crit : > > > When I started coding in python, these two things surprised me. > > > 1. my code is inconsistently indented with the combination of tabs and > > spaces. Even lines looked intended, but it is not. > > Then you have a problem with your code editor - not with Python. > Editors can not be wrong. :) I think there should be some way to say python compiler, to consider tab and two blank spaces equal, when tab space = 2. From kyosohma at gmail.com Fri May 9 10:25:40 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 9 May 2008 07:25:40 -0700 (PDT) Subject: Can I "delete" the namespace of a module that i import? References: Message-ID: <1072bcd6-b30b-4e51-b79a-f7e9cfd80976@e39g2000hsf.googlegroups.com> On May 9, 9:06?am, "gbin,Zhou" wrote: > Hi,all. > ? ?I see from "http://docs.python.org/tut/node11.html" that "Name > spaces are created at different moments and have different lifetimes. > The namespace containing the built-in names is created when the Python > interpreter starts up, and is never deleted. The global namespace for > a module is created when the module definition is read in; normally, > module namespaces also last until the interpreter quits." > ? ?So can I "delete" the namespace of a module that i import? > ? ?thanks. I did some searching and haven't found much. The closest I've found so far is this old thread: http://mail.python.org/pipermail/python-list/2000-February/022526.html You might look at IDLE's code to see what it does when you tell it to "restart" too. Good luck! Mike From deets at nospam.web.de Wed May 28 15:52:26 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 28 May 2008 21:52:26 +0200 Subject: Threads and import In-Reply-To: <0d96c6da-d239-4b15-8456-70e2d9e67fa2@59g2000hsb.googlegroups.com> References: <6d04f375-9cc6-428b-aafb-d5b947d6e915@b1g2000hsg.googlegroups.com> <6a5pulF36888qU1@mid.uni-berlin.de> <0d96c6da-d239-4b15-8456-70e2d9e67fa2@59g2000hsb.googlegroups.com> Message-ID: <6a5rfvF36c899U1@mid.uni-berlin.de> rsoh.woodhouse at googlemail.com schrieb: > On May 28, 8:26 pm, "Diez B. Roggisch" wrote: >> rsoh.woodho... at googlemail.com schrieb: >> >> >> >>> Hi, >>> I'm trying to work out some strange (to me) behaviour that I see when >>> running a python script in two different ways (I've inherited some >>> code that needs to be maintained and integrated with another lump of >>> code). The sample script is: >>> # Sample script, simply create a new thread and run a >>> # regular expression match in it. >>> import re >>> import threading >>> class TestThread(threading.Thread): >>> def run(self): >>> print('start') >>> try: >>> re.search('mmm', 'mmmm') >>> except Exception, e: >>> print e >>> print('finish') >>> tmpThread = TestThread() >>> tmpThread.start() >>> tmpThread.join() >>> import time >>> for i in range(10): >>> time.sleep(0.5) >>> print i >>> # end of sample script >>> Now if I run this using: >>> $ python ThreadTest.py >>> then it behaves as expected, ie an output like: >>> start >>> finish >>> 0 >>> 1 >>> 2 >>> ... >>> But if I run it as follows (how the inherited code was started): >>> $ python -c "import TestThread" >>> then I just get: >>> start >>> I know how to get around the problem but could someone with more >>> knowledge of how python works explain why this is the case? >> Works for me. And I don't see any reason why it shouldn't for you - >> unless you didn't show us the actual code. >> >> Diez > > Strange. That is the code exactly as I run it using python 2.4.4 2.5.1 > on Ubuntu 7.10. Which version of python/what platform were you using? mac-dir:/tmp deets$ python Python 2.5.1 (r251:54869, Apr 18 2007, 22:08:04) [GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin Type "help", "copyright", "credits" or "license" for more information. Welcome to rlcompleter2 0.96 for nice experiences hit multiple times >>> But I doubt this changes anything. Diez From arnodel at googlemail.com Tue May 20 13:12:14 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 20 May 2008 18:12:14 +0100 Subject: Accumulating values in dictionary References: <07fbc8ec-924a-4e90-b212-ca4cc66f2b85@i76g2000hsf.googlegroups.com> Message-ID: Zack writes: > Given a bunch of objects that all have a certain property, I'd like to > accumulate the totals of how many of the objects property is a certain > value. Here's a more intelligible example: > > Users all have one favorite food. Let's create a dictionary of > favorite foods as the keys and how many people have that food as their > favorite as the value. > > d = {} > for person in People: > fav_food = person.fav_food > if d.has_key(fav_food): > d[fav_food] = d[fav_food] + 1 > else: > d[fav_food] = 1 This is fine. If I wrote this, I'd write it like this: d = {} for person in people: fav_food = person.fav_food if fav_food in d: d[fav_food] += 1 else: d[fav_food] = 1 You can use d.get() instead: d = {} for person in people: fav_food = person.fav_food d[fav_food] = d.get(fav_food, 0) + 1 Or you can use a defaultdict: from collections import defaultdict d = defaultdict(int) # That means the default value will be 0 for person in people: d[person.fav_food] += 1 HTH -- Arnaud From salgerman at gmail.com Tue May 13 09:23:33 2008 From: salgerman at gmail.com (gsal) Date: Tue, 13 May 2008 06:23:33 -0700 (PDT) Subject: where to get McMillan Installer? References: <74f142de-6485-4773-bae8-2a274be19b80@w7g2000hsa.googlegroups.com> <537c541a-4e96-404b-81c3-68ffa9a025b8@b64g2000hsa.googlegroups.com> Message-ID: <3ef2200e-5520-4fcf-9f2c-8667fc1733c4@s50g2000hsb.googlegroups.com> hhhmmm...py2exe...I tried it earlier and it couldn't handle some of the packages I was using because they were in the "egg" form. I was hoping Installer could...then again, I don't know how long ago Installer was written and whether eggs came along after that... Regarding the word 'copy'...will you please enlighten me? were you serious? is it really banned (around here)? I mean, I thought we were talking about an open application which, for as long as you pass along the (GNU,GPL) license, you are allowed to provide it to other people. So, then, allow me to ask the real question: how do I go about deploying a Python application to somebody who has nothing (python nor related modules) where my application uses modules from Lib/site- packages that are in "egg" form? Regards, gsal From mishok13 at gmail.com Wed May 7 03:54:40 2008 From: mishok13 at gmail.com (Andrii V. Mishkovskyi) Date: Wed, 7 May 2008 10:54:40 +0300 Subject: strftime() argument 1 must be str, not unicode In-Reply-To: <48215537.100@promsoft.ru> References: <48215537.100@promsoft.ru> Message-ID: <192840a00805070054o22eb17ach519098da27258269@mail.gmail.com> 2008/5/7 Alexandr N Zamaraev : > Subj is bag? > > Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit > (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> from datetime import datetime > >>> datetime.today().strftime('%Y_%m_%d %H_%M_%S.csv') > '2008_05_07 12_30_22.csv' > >>> datetime.today().strftime(u'%Y_%m_%d %H_%M_%S.csv') > Traceback (most recent call last): > File "", line 1, in > TypeError: strftime() argument 1 must be str, not unicode Unicode and str objects are not the same. Why do you think that this is a bug? Anyway, you can always use 'encode' method of unicode objects: In [2]: datetime.today().strftime('%Y-%m-%d %H-%M-%S.csv') Out[2]: '2008-05-07 10-49-24.csv' In [3]: datetime.today().strftime(u'%Y-%m-%d %H-%M-%S.csv') --------------------------------------------------------------------------- TypeError Traceback (most recent call last) /home/mishok/doc/python/ in () TypeError: strftime() argument 1 must be str, not unicode In [4]: datetime.today().strftime(u'%Y-%m-%d %H-%M-%S.csv'.encode('utf-8')) Out[4]: '2008-05-07 10-51-19.csv' No offence, but have you read the tutorial? > -- > http://mail.python.org/mailman/listinfo/python-list > -- Wbr, Andrii Mishkovskyi. He's got a heart of a little child, and he keeps it in a jar on his desk. From florencio.cano at gmail.com Thu May 8 03:14:24 2008 From: florencio.cano at gmail.com (Florencio Cano) Date: Thu, 8 May 2008 09:14:24 +0200 Subject: How to gather information about the system hardware? Message-ID: Hi, I'm looking for a method of gathering information about the system hardware and software installed using Python. I would like to do it in UNIX and in Windows. I think that it would be good in Windows to look in the registry and be able to parse and search it. Any pointer to information would be appreciated. Thanks. From workitharder at gmail.com Tue May 27 17:49:12 2008 From: workitharder at gmail.com (bukzor) Date: Tue, 27 May 2008 14:49:12 -0700 (PDT) Subject: call f(a, *b) with f(*a, **b) ? References: <55bc8846-107e-461a-89de-25c83cbcfa27@2g2000hsn.googlegroups.com> <5coZj.13951$hv2.4218@bignews5.bellsouth.net> <9e688dbd-43fb-43ca-8c60-8dd2aaa66aa1@x1g2000prh.googlegroups.com> <69670280-f9e7-43f8-9750-09374f907332@j33g2000pri.googlegroups.com> Message-ID: <4787d8f0-c147-4a6a-8cc7-e354ce41a33a@j22g2000hsf.googlegroups.com> On May 23, 1:17 pm, bukzor wrote: > On May 23, 12:35 pm, "inhahe" wrote: > > > > > " > > I wish this worked:>>> def main(a,b,*argv): pass > > >>> options['argv'] = argv > > >>> main(**options) > > > TypeError: main() got an unexpected keyword argument 'argv' > > " > > ----- > > I was thinking about that exact same thing actually. Except that I was > > thinking you might want it like this, otherwise it could be ambiguous: > > > >>> def main(a,b,*argv): pass > > >>> options['*argv'] = argv > > >>> main(**options) > > > Weird I know, to put the * operator inside the string. I suppose the > > necessity of doing that just shows why it wasn't implemented in the first > > place. But still, it would be neat... > > > Also, of course, you could then do > > main(*argv=[2,3]) > > > or rather > > > main(*argv=[3,4],a=1,b=2) #in random order > > Yes I think something like that would be an improvement. I wonder if > anyone would help me write a PEP... It might not be too hard to pass > since it would be compatible with all existing code. I'd be willing to > produce a patch against python2 or py3k. > > I don't see that leaving off the * makes it ambiguous, since there can > only be one argument with that name: > def f(args, *args): pass > SyntaxError: duplicate argument 'args' in function definition I guess that's a no... From casey.mcginty at gmail.com Wed May 21 06:44:50 2008 From: casey.mcginty at gmail.com (Casey McGinty) Date: Wed, 21 May 2008 00:44:50 -1000 Subject: Organizing a Python project In-Reply-To: <960da03c-1edf-4fa4-b434-6656e8a8884f@e39g2000hsf.googlegroups.com> References: <960da03c-1edf-4fa4-b434-6656e8a8884f@e39g2000hsf.googlegroups.com> Message-ID: > I'm starting work on what is going to become a fairly substantial > Python project, and I'm trying to find the best way to organize > everything. I'd like to add a follow up question. Are there any idioms for writing /usr/bin scripts to run installed package modules? For this I am assuming a simple case where there is a single package with one or more modules all making up a single application. A have a few thoughts, please correct me if I'm wrong. 1. Script code should be as basic as possible, ideally a module import line and function or method call. This is so you don't have to worry about script errors and/or increase startup time because a *.pyc file can not be store in /usr/bin. 2. In the top of your package directory it is typical to have a module name '_package.py'. This is ideally where the main command line entry point for the package code should be placed. 3. In the _package.py file you should add a "class Package" that holds most or all of the application startup/execution code not designated to other modules. Then run the application with the call to "Package()", as in if __name__ == '__main__': Package() Some other questions I have are: A. What should go in the package __init__.py file? For example, a doc describing the program usage seems helpful, but maybe it should have info about your modules only? Assuming the __init__.py code gets executed when you import the module, you could place part or all of the application code here as well. I'm guessing this is not a good idea, but not really convinced. B. How should you import your _package.py module into your /usr/bin script. Is there a way to use an '__all__' to simplify this? Again this goes back to question A, should there be any code added to __init__.py? C. If you have a _package.py file as the application entry, is it worth it to place most of the application code in a class, described in part 3? D. When I import a package._package module, I get a lot of junk in my namespace. I thought an '__all__' define in the module would prevent this, but it does not seem to work. Thanks for reading, - Casey -------------- next part -------------- An HTML attachment was scrubbed... URL: From bruno.desthuilliers at gmail.com Wed May 14 17:41:58 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Wed, 14 May 2008 14:41:58 -0700 (PDT) Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <5b0e3f70-afde-4480-8713-e7113b1250d7@x35g2000hsb.googlegroups.com> <1f537717-00d0-48ee-99b6-7125b96a6133@t12g2000prg.googlegroups.com> <68t4o0F2vaoncU1@mid.uni-berlin.de> <2a32179a-9439-449c-bd07-fff6a4075aee@s50g2000hsb.googlegroups.com> <7ee5dffd-df8f-46f0-bd78-c81ac0418a9a@d77g2000hsb.googlegroups.com> <65ef773e-a1c3-4adb-a18b-e8b8451efe5e@b5g2000pri.googlegroups.com> Message-ID: <45b8aef5-50d9-4b83-98c0-104dddd03d26@y38g2000hsy.googlegroups.com> On 13 mai, 18:36, Dave Parker wrote: (snip) > Also, in Python how do you assign a symbolic equation to a variable? > Like this? > > QuadraticEquation = a*x^2 + b*x + c = 0 quadratic_equation = lambda x, b, c : a*(x**2) + b*x + c == 0 or if x, b and c are supposed to be captured from the current namespace: quadratic_equation = lambda : a*(x**2) + b*x + c == 0 > Set statements avoid the confusion of multiple equal signs when > manipulating symbolic equations: using '=' for assignement and '==' for equality test does the same thing. And it's a very common pattern in programming languages. From hdante at gmail.com Tue May 13 10:34:09 2008 From: hdante at gmail.com (hdante) Date: Tue, 13 May 2008 07:34:09 -0700 (PDT) Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <2b66a86e-5a05-4262-b3c9-4703b0ae3372@d1g2000hsg.googlegroups.com> <5b0e3f70-afde-4480-8713-e7113b1250d7@x35g2000hsb.googlegroups.com> <1f537717-00d0-48ee-99b6-7125b96a6133@t12g2000prg.googlegroups.com> <68t4o0F2vaoncU1@mid.uni-berlin.de> <2a32179a-9439-449c-bd07-fff6a4075aee@s50g2000hsb.googlegroups.com> Message-ID: <7ee5dffd-df8f-46f0-bd78-c81ac0418a9a@d77g2000hsb.googlegroups.com> On May 13, 10:58?am, Paul McGuire wrote: > On May 13, 8:32?am, Dave Parker wrote: > > > > Don't let yourself be irritated by castironpi > > > I'm not the sort to get irritated by anyone. ?There is value in all > > interaction. > > Not this interaction, I'm afraid. ?What irritates *me* about > castironpi is that he uses a chatterbot to clutter up the threads > here. ?If you go back to his postings from a year ago (and selected > ones since), his comments are coherent and sensible. ?These rambling > stream-of-consciousness rants about t.v.'s and coffee are (I guess) > his idea of a joke. ?But they are certainly not worth your time in > trying to respond to them. > > -- Paul I don't think castironpi so annoying that I should filter its messages. It would be enough if he were better tuned. He is much smarter than the emacs shrink, for example. :-P The "Flaming Thunder" looks promising, but without being free software, it's unlikely it will create a large developer community, specially considering both free general purpose and scientific programming languages. From johnjsal at NOSPAMgmail.com Mon May 12 23:42:43 2008 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: 13 May 2008 03:42:43 GMT Subject: Learning Python for no reason References: <0383f3b8$0$27282$c3e8da3@news.astraweb.com> <4828806c$0$11583$9b622d9e@news.freenet.de> Message-ID: <48290e33$0$11631$607ed4bc@cv.net> Martin v. L?wis wrote: > OTOH: do you plan to do any programming at all, in your > life? If yes: consider using Python for every programming > task you'll encounter Yeah, I do plan to use it for fun (if I can think of little projects to work on!), and Python is definitely the only language I care to learn. It's simple and fun to use, which is why I hate that I don't have more reasons to use it! :) From aguirre.adolfo at gmail.com Sun May 4 18:01:06 2008 From: aguirre.adolfo at gmail.com (adolfo) Date: Sun, 4 May 2008 15:01:06 -0700 (PDT) Subject: Can I install Python 2.4 and 2.5 ? Message-ID: I am reviewing various visualization programs (Scipy, PYGNL, etc) and IDE?s. Some run on Python 2.4 others in 2.5. Can I have both installed at the same time if I don?t run them concurrently? Now in Windows XP soon on Ubuntu 8 Appreciating your help, Adolfo From duncan.booth at invalid.invalid Sun May 18 08:57:04 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 18 May 2008 12:57:04 GMT Subject: secret code? References: <5bc52ed9-855e-4569-b3bd-a0c1ab6941d7@k37g2000hsf.googlegroups.com> Message-ID: Sanoski wrote: > What would you guys says about this secret code? The key was > apparently lost. The guy never sent it, and he was never seen again. > It must stand for letters in the alphabet, but it almost looks like > trajectory tables. I don't know. What do you guys think? > > http://i243.photobucket.com/albums/ff273/ezname420/code.jpg > Try Googling for 'Beale Cipher'. From mario at ruggier.org Sat May 31 06:57:56 2008 From: mario at ruggier.org (Mario Ruggier) Date: Sat, 31 May 2008 12:57:56 +0200 Subject: ValueError: unknown locale: UTF-8 Message-ID: <305017A1-F5F5-47E2-BB20-0B2A1FD4C5E8@ruggier.org> On OS X 10.5.2 : $ python Python 2.5.1 (r251:54863, Feb 4 2008, 21:48:13) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import locale >>> locale.getdefaultlocale() Traceback (most recent call last): File "", line 1, in File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/locale.py", line 441, in getdefaultlocale return _parse_localename(localename) File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/locale.py", line 373, in _parse_localename raise ValueError, 'unknown locale: %s' % localename ValueError: unknown locale: UTF-8 >>> This is on open bug or is there more to it? Regards, mario From wizzardx at gmail.com Sun May 4 17:12:13 2008 From: wizzardx at gmail.com (David) Date: Sun, 4 May 2008 23:12:13 +0200 Subject: unicode newbie - printing mixed languages to the terminal Message-ID: <18c1e6480805041412s37085709q511eb3a3c86e36c5@mail.gmail.com> Hi list. I've never used unicode in a Python script before, but I need to now. I'm not sure where to start. I'm hoping that a kind soul can help me out here. My current (almost non-existant) knowledge of unicode: >From the docs I know about the unicode string type, and how to declare string types. What I don't understand yet is what encodings are and when you'd want/need to use them. What I'd like is to just be able to print out unicode strings in mixed languages, and they'd appear on the terminal the same way they get shown in a web browser (when you have appropriate fonts installed), without any fuss. Here is an example of how I'd like my script to work: $ ./test.py Random hiragana: Random romaji: kakikukeko Is this possible? >From my limited knowledge, I *think* I need to do to things: 1) In my Python script, run .encode() on my unicode variable before printing it out (I assume I need to encode into Japanese) Question: How does this work when you have multiple languages in a single unicode string? Do you need to separate them into separate strings (one per language) and print them separately? Or is it the case that you can (unlike a web browser) *only* display/print one language at a time? (I really want mixed language - English AND Japanese). 2) Setup the terminal to display the output. From various online docs it looks like I need to set the LANG environment variable to Japanese, and then start konsole (or gnome-terminal if that will work better). But again, it looks like this limits me to 1 language. If what I want to do is very hard, I'll output html instead and view it in a web browser. But I'd prefer to use the terminal instead if possible :-) Thanks in advance. David. From notontheweb at noisp.com Wed May 7 23:22:12 2008 From: notontheweb at noisp.com (Jive Dadson) Date: Thu, 08 May 2008 03:22:12 GMT Subject: web client in Python Q In-Reply-To: References: Message-ID: Thanks, Jerry! That's so cool. I actually managed to blunder through with sockets and so forth, but this is much cleaner. I wonder why it does not work with http://stockcharts.com/webcgi/wb.exe?Data.web+SLW I get a connection reset by peer error. From notbob at nothome.com Tue May 6 14:07:51 2008 From: notbob at nothome.com (notbob) Date: Tue, 06 May 2008 18:07:51 GMT Subject: Are rank noobs tolerated, here? References: <3zITj.35199$gB5.25251@fe105.usenetserver.com> Message-ID: On 2008-05-06, Jeffrey Froman wrote: > Nice to see another Slackware user around here! Likewise. ;) > That's correct. A function doesn't generally *do* anything until it is > called. Here, it is only defined. The only thing this function does when > called is to print the value of bruce twice. I suspected as much. It was a bit confusing, but I get it now. > Functions are objects too, and this is a printed representation of that > function object. It still hasn't been "called" at this point. Good to know. Thnx. > other python "special" attributes, it starts and ends with TWO underscores. ...as Alex also pointed out. I didn't notice that. Thnx. > You are correct to create this script yourself from scratch. Do python scripts require the: #!/usr/bin/env python ....line at the beginning of every script or just the .py file extension? I see examples both ways, with and without. > Your module files, i.e., chap03.py, should be in one of the directories on > that path. Gotchya. > "from" modifies a *module* name, not a path component. So "from module > import one_function, another_function". This allows you to use one_function > without referencing it through the imported module name. In other words, > these two are equivalent: > >>>> import chap03 >>>> chap03.print_twice() > > and: > >>>> from chap03 import print_twice >>>> print_twice() > > In the above examples, "chap03" is the *module* file, chap03.py. mmmmm..... that's still a bit much to wrap my feeble brain around, but I get your drift. I'm still working on the basic function concept as python uses it. But, I found two more websites that explain it better and I think I pretty much get it, now. Thank you, and the others, for your help. It's very much appreciated. nb Slackware: simplicity through transparency From Joshuajruss at gmail.com Sat May 17 00:43:46 2008 From: Joshuajruss at gmail.com (Sanoski) Date: Fri, 16 May 2008 21:43:46 -0700 (PDT) Subject: how would you...? Message-ID: <1449c36e-10ce-42f4-bded-99d53a0a2569@a1g2000hsb.googlegroups.com> I'm pretty new to programming. I've just been studying a few weeks off and on. I know a little, and I'm learning as I go. Programming is so much fun! I really wish I would have gotten into it years ago, but here's my question. I have a longterm project in mind, and I wont to know if it's feasible and how difficult it will be. There's an XML feed for my school that some other class designed. It's just a simple idea that lists all classes, room number, and the person with the highest GPA. The feed is set up like this. Each one of the following lines would also be a link to more information about the class, etc. Economics, Room 216, James Faker, 3.4 Social Studies, Room 231, Brain Fictitious, 3.5 etc, etc The student also has a picture reference that depicts his GPA based on the number. The picture is basically just a graph. I just want to write a program that uses the information on this feed. I want it to reach out to this XML feed, record each instance of the above format along with the picture reference of the highest GPA student, download it locally, and then be able to use that information in various was. I figured I'll start by counting each instance. For example, the above would be 2 instances. Eventually, I want it to be able to cross reference data you've already downloaded, and be able to compare GPA's, etc. It would have a GUI and everything too, but I am trying to keep it simple right now, and just build onto it as I learn. So lets just say this. How do you grab information from the web, in this case a feed, and then use that in calculations? How would you implement such a project? Would you save the information into a text file? Or would you use something else? Should I study up on SQLite? Maybe I should study classes. I'm just not sure. What would be the most effective technique? From zephyrfalcon!NO_SPAM! at gmail.com Fri May 16 19:02:33 2008 From: zephyrfalcon!NO_SPAM! at gmail.com (Hans Nowak) Date: Fri, 16 May 2008 19:02:33 -0400 Subject: SImple python print question In-Reply-To: <47054b9b-fb5e-4601-9e2d-75bfe61e9cb8@w1g2000prd.googlegroups.com> References: <47054b9b-fb5e-4601-9e2d-75bfe61e9cb8@w1g2000prd.googlegroups.com> Message-ID: amit.uttam at gmail.com wrote: > Hey there, > > I have a simple question about python print statement. Take the > following code snippet for example... > > 1 print "-#- executing: %s" % section, > 2 tests[section] = test.testcase(name=config.get(section,'name')) > 3 tests[section].runTest() > 4 printStatus(tests[section]) > > Now the problem is that line 1 does not get printed until line 4. What > I thought would happen is that line 1 gets executed and the user sees > that the statement that the test case is executing. Then after the > test case executes a "PASS" or "FAIL" appears on the same line as the > "-#- executing: 0053" statement. > > e.g. > -#- executing: 0053 FAIL > > Some tests take a long time to finish thus the screen is blank until > the entire test finishes and the above statement is outputted. > > Thanks for any help. 'print' sends its output to sys.stdout, which is buffered, and may not be displayed immediately (because it's held in the buffer). To force the output to be displayed, use flush(): print "-#- executing: %s" % section, sys.stdout.flush() ...tests here... Hope this helps! --Hans From fc14301589 at icqmail.com Wed May 21 09:31:24 2008 From: fc14301589 at icqmail.com (TheSaint) Date: Wed, 21 May 2008 21:31:24 +0800 Subject: Publish a program References: <4833f0ff_2@news.tm.net.my> Message-ID: <48342434_2@news.tm.net.my> On 18:15, mercoled? 21 maggio 2008 alex23 wrote: > On May 21, 7:52 pm, TheSaint wrote: > There's also http://python.pastebin.com, which lets you create a new > paste by modifying an existing one, and keeps them linked for easy > diff'ing. > > Sample: http://python.pastebin.com/d3964b241 Thank you for the reply :) In my case, it's rather a set of modules which trying to remove spam from the mailbox(es) either by POP3 or IMAP4 according regex criteria. The project is working quiet good, the most advantage is that it downloads only the header for speed needs. Some time I'm doing it by GPRS in roaming and volume it _matters_ much. I simply like that somebody will express some opinion about my job, as meaning of teaching me better. After all that's what I'm trying to do ;) Other idea, I'll apreciate somebody to join and put new views on this project. From nospam103 at jmiaz.com Fri May 23 13:52:08 2008 From: nospam103 at jmiaz.com (Aaron Lance) Date: Fri, 23 May 2008 10:52:08 -0700 Subject: Python is slow References: Message-ID: Troll much? From rdm at rcblue.com Sun May 18 01:49:03 2008 From: rdm at rcblue.com (Dick Moores) Date: Sat, 17 May 2008 22:49:03 -0700 Subject: r' question In-Reply-To: References: <20080518023835.61FE61E4009@bag.python.org> Message-ID: <20080518054915.9555B1E4007@bag.python.org> At 10:17 PM 5/17/2008, Gabriel Genellina wrote: >En Sat, 17 May 2008 23:37:16 -0300, Dick Moores escribi?: > > > I have a text file of phone numbers, which I'd like to search with a regex. > > > > fstr = "\sjoe\s" > > regex = "^.*" + fstr + ".*$" > > > > fstr = "\sjoe\s" > > regex = "r'^.*" + fstr + ".*$'" > >The r"..." is a signal to the parser - meaning >"don't interpret the escape characters here". >Note that the r is OUTSIDE the quotes. In your >example, the escape characters are in fstr, so >it should be written as r"\sjoe\s" However, (please refer back to my original post) I want to keep the fstr, ultimately to be the string entered by the user who knows a bit about regex, but not how to use r' ' . Or alternatively, not assume any knowledge of regex, but build in some options, such as ignoring/not ignoring case, searching on just a string, or on a word. So I want to know how to build the user's fstr into regex. I apologize for not making this clear. >Now, if you want "the lines that contain the >word joe surrounded by space", just use: > >import re >regex = r"\sjoe\s" >p = re.compile(regex, re.I) >f = open('phone.txt', 'r') >for line in f: > m = p.search(line) > if m: > print m.group() >f.close() > >A file is its own line iterator (no need for >readlines). And since you're iterating over >lines, the regex doesn't have to test for it ^ and $. Yes, that works. Thanks. Dick Moores From inhahe at gmail.com Tue May 13 11:48:26 2008 From: inhahe at gmail.com (inhahe) Date: Tue, 13 May 2008 11:48:26 -0400 Subject: how to pass a python socket to a .dll? Message-ID: i'm trying to make a .dll that will let me use WSAPoll, which is a windows sockets function, to mimic select.poll on a windows box. i cbb learning python extensions, so i'm just going to use ctypes with a dll, so I hope that it doesn't bring up a big performance issue. anyway, the problem is that I want to use Python-created sockets with it, but WSAPoll requires winsock2.h SOCKET objects. so unless someone can tell me how to create/reference a windows socket object using the winsock2 lib from just a file/socket descriptor (being that this isn't a windows programming forum), i'm just asking how I could gain access to the actual Windows socket associated with a Python socket that Python for Windows has to store somewhere. even if I have to modify socketmodule.c. btw, i don't know much about this stuff, i hardly ever even program in c++, so i hope anybody's not too cryptic :P From upton at virginia.edu Thu May 29 18:53:29 2008 From: upton at virginia.edu (Dan Upton) Date: Thu, 29 May 2008 18:53:29 -0400 Subject: question In-Reply-To: <13801bd3-50da-4773-a0aa-edcaf27e0c4d@34g2000hsf.googlegroups.com> References: <6a8o5pF34umpoU1@mid.individual.net> <13801bd3-50da-4773-a0aa-edcaf27e0c4d@34g2000hsf.googlegroups.com> Message-ID: <5504f9ac0805291553n953f44o67a46886f796fc63@mail.gmail.com> On Thu, May 29, 2008 at 6:41 PM, Gandalf wrote: > On May 30, 12:14 am, John Henderson wrote: >> Gandalf wrote: >> > how do i write this code in order for python to understand it >> > and print me the x variable >> >> > x=1 >> > def aaaa(): >> > x++ >> > if x > 1: >> > print "wrong" >> > else : >> > print x >> >> > aaaa() >> >> Example: >> >> x=1 >> def aaaa(x): >> x += 1 >> if x > 1: >> return "wrong" >> else : >> return x >> >> print aaaa(x) >> >> John > > mmm isn't their any global variable for functions? If I get what you're asking, you have to tell the function there exists a global: IDLE 1.2 >>> x=1 >>> def a(): global x x+=1 if x > 1: print x else: print "nope" >>> print x 1 >>> a() 2 >>> print x 2 From artyprog at gmail.com Sun May 18 14:41:25 2008 From: artyprog at gmail.com (Salvatore DI DI0) Date: Sun, 18 May 2008 20:41:25 +0200 Subject: Compress a string References: Message-ID: <48307858$0$906$ba4acef3@news.orange.fr> Try this t = set("aaaaaaaaaaaabbbbbbbbbbccccccccc") list(t) Regards Salvatore "Matt Porter" a ?crit dans le message de news: mailman.1315.1211133997.12834.python-list at python.org... > Hi guys, > > I'm trying to compress a string. > E.g: > "AAAABBBC" -> "ABC" > > The code I have so far feels like it could be made clearer and more > succinct, but a solution is currently escaping me. > > > def compress_str(str): > new_str = "" > for i, c in enumerate(str): > try: > if c != str[i+1]: > new_str += c > except IndexError: > new_str += c > return new_str > > > Cheers > Matt > -- > -- > From bignose+hates-spam at benfinney.id.au Fri May 2 19:40:03 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 03 May 2008 09:40:03 +1000 Subject: #!/usr/bin/env python vs. #!/usr/bin/python References: <87abj91j8u.fsf@benfinney.id.au> <871w4l1cjj.fsf@benfinney.id.au> <87r6ckzvyv.fsf@benfinney.id.au> <87bq3ozs09.fsf@benfinney.id.au> Message-ID: <871w4kz358.fsf@benfinney.id.au> "D'Arcy J.M. Cain" writes: > On Sat, 03 May 2008 00:43:02 +1000 > Ben Finney wrote: > > Roy Smith writes: > > > Have you ever shipped software to a customer? > > > > Yes, and all parties have been quite happy with the results. > > When some of us talk about shipping software we aren't talking about > a 20 line script delivered to our uncle's construction company > office. Nor was I. Thanks for the condescension and straw-man attacks, but... > I do believe I am done with this thread. That's a relief. -- \ ?He that would make his own liberty secure must guard even | `\ his enemy from oppression.? ?Thomas Paine | _o__) | Ben Finney From dteslenko at gmail.com Wed May 14 03:04:19 2008 From: dteslenko at gmail.com (Dmitry Teslenko) Date: Wed, 14 May 2008 11:04:19 +0400 Subject: file locked for writing In-Reply-To: References: <91325fec0805130757neb11c4aucfdf825db300d942@mail.gmail.com> Message-ID: <91325fec0805140004r3ced1ecdy94d48fbfc660136d@mail.gmail.com> On Wed, May 14, 2008 at 8:18 AM, Gabriel Genellina wrote: > En Tue, 13 May 2008 11:57:03 -0300, Dmitry Teslenko > Is the code above contained in a function? So all references are released > upon function exit? Yes, it's a function > If not, you could try using: del input, output, filter > That should release all remaining references to the output file, I presume. > Or locate the inner reference to the output file (filter.something perhaps?) > and explicitely close it. That doesn't help either. When I've rewrite code something like that: with open(backup_file_name, 'w') as backup_file: ..... filter.parse('') del input, output, filter os.remove(project.get_vcproj()) os.rename(backup_file_name, project.get_vcproj()) It triggers WindowsError on os.remove() From miller.paul.w at gmail.com Sun May 25 22:46:14 2008 From: miller.paul.w at gmail.com (miller.paul.w at gmail.com) Date: Sun, 25 May 2008 19:46:14 -0700 (PDT) Subject: set partition question References: Message-ID: <7b64328e-d4e0-4ec1-8918-3cab94e2f815@e39g2000hsf.googlegroups.com> On May 25, 3:51?pm, pball.benet... at gmail.com wrote: > dear pythonistas, > > I think this problem is related to integer partitioning, but it's not > quite the same. The range of answers has a little combinatorial > explosion problem as S gains new members. In my problem, len(S) is > usually on the order of 1M, and in the worst case, 10M, and there are > on the order of 10k elements. If, by "integer partitioning," you mean the "subset sum problem" (given a finite set S of integers, does S contain a subset which sums up to some given integer k?), then you are right. I'm reasonably sure there's a polynomial reduction from your problem to the subset sum problem. That would make your problem NP-complete. As for algorithms, I don't think there's an exact algorithm any better than trying all the possibilities and stopping when one comes close. Say, for example, we specify the problem to be: given sets s_0, s_1, s_2, ..., s_n, with S defined to be the union of all the s_i's, return all functions f which, using the sets s_1, s_2, ..., s_n and the elementary set operations (union, intersection, difference), returns the set s_0. Now, you need to be a little more careful, because, given a function f which satisfies the problem, I can always define f' = f(S) + s_1 - s_1 and get another function which satisfies the definition. Like I said, because this looks related to the subset sum problem (though harder, because you're asking for "all" such functions, for some rigorous definition of "all," as per the previous sentence), I suspect it's NP-complete. However, there are probably some good heuristics, such as if s1 has a large intersection with s0, it's probably a good idea to use s1 in whatever formula you come up with. Other than that, I don't really have an idea. Can you say what the application of this algorithm would be? Knowing the use case might suggest a better approach. From cnshoes76 at yahoo.com.cn Sat May 10 04:11:16 2008 From: cnshoes76 at yahoo.com.cn (cnshoes76 at yahoo.com.cn) Date: Sat, 10 May 2008 01:11:16 -0700 (PDT) Subject: CHINA WHOLESALE MEN 'S PRADA GUCCI SANDALS Message-ID: European and South America market. All the products are in high quality with reasonable price. Most of the items listed in our website ,we have got them in stocks, if there isn't ,please let us know your specific requirements. From geoldr at gmail.com Thu May 22 11:59:40 2008 From: geoldr at gmail.com (Geoldr) Date: Thu, 22 May 2008 08:59:40 -0700 (PDT) Subject: Restarting a program Message-ID: Hello all, I have written a simple program, and at the end of it, instead of it closing I would like it to restart from the beggining. Is there a way to do this? Put my code into a class function, or something? I guess I could do a while loop, but I think if there is a way to run my code if it's in a class would be an easier option. I can't seem to find many guides online but maybe I have not been looking in the right places. Anybody have any ideas? From saluk64007 at gmail.com Fri May 2 13:36:58 2008 From: saluk64007 at gmail.com (Patrick Mullen) Date: Fri, 2 May 2008 10:36:58 -0700 Subject: pygame.key.get_pressed[K_a], K_a is not defined!? In-Reply-To: <8f3fead6-895a-4ee4-9fff-2190775da3e9@w7g2000hsa.googlegroups.com> References: <680su7F2q6qo2U1@mid.uni-berlin.de> <8f3fead6-895a-4ee4-9fff-2190775da3e9@w7g2000hsa.googlegroups.com> Message-ID: The K_a is a constant integer, but you don't need to worry about it's value. It tells you the index in get_pressed() to check for. So: print pygame.key.get_pressed()[pygame.K_a] Says, look at the 97th index in the get_pressed() list and see if that is a 1 or a 0. Or if you use the pygame events: for evt in pygame.event.get(): if evt.type == pygame.KEYDOWN and evt.key == pygame.K_a: print "a pressed" evt.type and evt.key will both be integers that map to one of the type constants and one of the key constants respectively. This way the key constant works in both types of input handling (which are both useful for different types of input). -------------- next part -------------- An HTML attachment was scrubbed... URL: From mal at egenix.com Thu May 1 06:03:33 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Thu, 01 May 2008 12:03:33 +0200 Subject: Python -v import behavior In-Reply-To: <357b87b40804300942v371152b0u9dcc6d8b8d0a3b32@mail.gmail.com> References: <357b87b40804300942v371152b0u9dcc6d8b8d0a3b32@mail.gmail.com> Message-ID: <48199575.9020608@egenix.com> On 2008-04-30 18:42, Sean Ryan wrote: > Hi all, > (A similar question was posted by a colleague, but did not appear to reach > comp.lang.python or this list). > > I am wondering if the -v option causes the python application to be more > tolerant to module import warnings and / or errors. > > The reason is that a module is failing to import correctly (generating an > ImportError exception). Examining this closer we re-ran the script using > the -v option. to find that "Unsatisfied symbol" errors we being displayed > during import (cx_Oracle 4.3.1, python 2.5.1, HP-UX 11, oracle 9.2). > However, the module is usable from the python prompt (when using -v) > displayed, i.e. dir (cx_Oracle) works correctly, as does database > interaction. Without the -v option the script is halted due to the > ImportError exception. > > My questions are: > 1. Is there a way to mimic the seemingly more tolerant import behavior of > python -v without producing the verbose output ? > 2. Is the behavior described above expected and documented ? The -v option only causes Python to print more information to stderr explaining where it is looking for modules. You should be seeing any dynamic loader messages in both cases, ie. when running with or without -v. While it is possible that cx_Oracle does some extra processing when running Python in -v mode, this is rather unlikely. Note that the best way to track down "unsatified symbol" errors is to inspect the dependencies of the modules and other shared libs involved. Running an strace (or similar system trace utility) will also help to identify the problem, since this lists the shared libs the process tries to load when starting up and also during import of Python modules. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, May 01 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From kyosohma at gmail.com Sat May 10 14:43:06 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Sat, 10 May 2008 11:43:06 -0700 (PDT) Subject: Is there a PyPI API? Message-ID: <7acaec98-73ca-436c-b153-4d34599a5f0c@8g2000hse.googlegroups.com> Hi, I am experimenting on creating a GUI wrapper for easy_install and I would like to be able to allow the user the browse PyPI topically. However, I am having some trouble figuring out how to get the information in a topical manner. I can get the list of classifiers easily using urllib2 like so: def getPyPiClassifiers(): print 'Get list of Topics from PyPI...' url = 'http://pypi.python.org/pypi?%3Aaction=list_classifiers' res = urllib2.urlopen(url) page = res.read() And there's a "light-weight" list of all the packages on PyPI here: http://pypi.python.org/simple/ I just can't figure out how to get the metadata, I guess. I found Paul Boddies SGMLParser example (http://www.boddie.org.uk/python/HTML.html) which can get me some URLs, but what I really need is some kind of dict of tuples or lists like this: {'Framework':(('Buildout', 'bazaarrecipe', 'Buildout recipe for Bazaar'), ('Buildout', 'buildout_script', 'zc.buildout recipes for generating script and conf files from templates.') )} Any ideas on how best to approach this would be great. I'm still learning HTML/XML parsing techniques and am having trouble wrapping my mind around it. Thanks! Mike From efurman at admailinc.com Thu May 22 13:13:57 2008 From: efurman at admailinc.com (Ethan Furman) Date: Thu, 22 May 2008 09:13:57 -0800 Subject: Struct usage and varying sizes of h, l, etc In-Reply-To: <48340df7$1@news.mel.dft.com.au> References: <48335269.2000809@admailinc.com> <48340df7$1@news.mel.dft.com.au> Message-ID: <4835A9D5.9060607@admailinc.com> John Machin wrote: > Robert Kern wrote: > >> Ethan Furman wrote: >> >>> Greetings, >>> >>> I'm looking at the struct module for binary packing of ints and >>> floats. The documentation refers to C datatypes. It's been many >>> years since I looked at C, but I seem to remember that the data type >>> sizes were not fixed -- for example, an int might be two byes on one >>> machine, and four bytes on the next. Can any C programmers verify >>> this? If it is true, does that mean that struct.pack('h', 8001) >>> might give me different results depending on the machine it's >>> running on? >> >> >> Right. I believe (but could be wrong) that "char" is defined to be >> one byte, but that "short", "int", "long", and "long long" are >> defined as "at least as big as the previous type". >> >> In practice, though, on nearly every machine that Python runs on, >> "char" is one byte, "short" is two bytes, and "int" is four bytes. >> "longs" and "long longs" tend to vary substantially, though; never >> assume sizes for them. >> >> Single-precision floats are always four bytes and double-precision >> floats are always eight bytes. "long doubles" vary; they could be >> twelve bytes or sixteen. >> >> If you want to deal with fixed sizes, use struct.calcsize() to test >> the sizes of each of the integer types, assign them to width-specific >> aliases, and always use these aliases. >> > > This is all true if you want to operate in "native" mode; however in > "standard" mode the sizes are fixed -- otherwise there'd be no easy > way of reading/writing the fixed-size fields in many common file formats. > > As the manual says: > """ > Native size and alignment are determined using the C compiler's sizeof > expression. This is always combined with native byte order. > > Standard size and alignment are as follows: no alignment is required > for any type (so you have to use pad bytes); short is 2 bytes; int and > long are 4 bytes; long long (__int64 on Windows) is 8 bytes; float and > double are 32-bit and 64-bit IEEE floating point numbers, respectively. > """ > > If, as I suspect, Ethan's purpose is be able to read/write files in a > long-established PC file format, he will need to '<' for littleendian > order, and an appropriate selection from bBhHiI and d will do what he > needs. > > HTH, > John > -- > http://mail.python.org/mailman/listinfo/python-list Next question: when using struct.pack to store an integer, I get a deprecation warning if the int is too big... I would rather have an error. Is there a setting somewhere that controls this? >>> struct.pack(' Hello, I'm not a master of python :) If I would publish my program for reviewing, where should I upload it? From ethan.mallove at sun.com Tue May 20 15:15:28 2008 From: ethan.mallove at sun.com (emallove) Date: Tue, 20 May 2008 12:15:28 -0700 (PDT) Subject: Python in non-standard location erring with "No module named _sha256" References: <0eecaca1-b32d-42e8-ade6-3001004e3e19@34g2000hsf.googlegroups.com> Message-ID: <3bcbc67a-2293-4a38-b335-43d8791232d6@z24g2000prf.googlegroups.com> On May 20, 11:27?am, emallove wrote: > I'm running into the below "No modules named _sha256" issue, with a > python installed in a non-standard location. > > $ python > Python 2.5.2 (r252:60911, May 20 2008, 09:46:50) > [GCC 3.3.3 (SuSE Linux)] on linux2 > Type "help", "copyright", "credits" or "license" for more information.>>> import md5 > > Traceback (most recent call last): > ? File "", line 1, in > ? File "/ws/ompi-tools/lib/python2.5/md5.py", line 6, in > ? ? from hashlib import md5 > ? File "/ws/ompi-tools/lib/python2.5/hashlib.py", line 135, in > > ? ? sha224 = __get_builtin_constructor('sha224') > ? File "/ws/ompi-tools/lib/python2.5/hashlib.py", line 63, in > __get_builtin_constructor > ? ? import _sha256 > ImportError: No module named _sha256 > > Googling around, this seems to be related to OpenSSL being in a non- > standard location? I've edited the Setup file to set $(SSL) to the non- > standard location. Now Python compiles fine, but I still get the above > error. > > Any help would be much appreciated. > > Thanks, > Ethan One solution was to just use Python 2.3.7 (instead of 2.5). -Ethan From aguirre.adolfo at gmail.com Tue May 6 17:58:18 2008 From: aguirre.adolfo at gmail.com (adolfo) Date: Tue, 6 May 2008 14:58:18 -0700 (PDT) Subject: DISLIN Manual Message-ID: <61d60fe6-271a-4f33-b1a7-a2059a08c810@j22g2000hsf.googlegroups.com> I am at the very beginning of the DISLIN 9.3 Manual: 1.4 Quickplots Some quickplots are added to the DISLIN module which are collections of DISLIN routines for displaying data with one command. For example, the function ?plot? displays two-dimensional curves. Example: from Numeric import * from dislin import * x = arange (100, typecode=Float32) plot (x, sin (x/5)) disfin () Problems: 1. "from Numeric import * " statement produced an error message, I had to replace it with "from numpy import *" 2. The "from dislin import *" statement produced an error message: Traceback (most recent call last): File "", line 1, in from dislin import * ImportError: No module named dislin I checked the environmental variables paths and they are according to instructions. What else to do? Any help will be much appreciated Adolfo From gagsl-py2 at yahoo.com.ar Mon May 26 01:37:45 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 26 May 2008 02:37:45 -0300 Subject: Why Turn "Print" into "Print()"???? References: <248a2c45-caae-49bb-b8ff-701af8b86207@p25g2000hsf.googlegroups.com> Message-ID: En Mon, 26 May 2008 02:06:02 -0300, Prisoner at War escribi?: > Might you have any idea, BTW, whether the upcoming "Head First > Programming" from O'Reilly, coming in August, will cover Python 3?? > Unlikely, right? Unless maybe if that guy Vern Ceder (the author) is > active in the Python development community?? > > I'd already pre-ordered the book...but it makes no sense to get a book > on "old" Python 2.x if it's just going to get deprecated in like a > year or two! Then again, current Python programs would still work, > right? I mean, once it's been done up as an executable...PySol or > something should still work, right? (Sorry, iman00b, I don't really > know how this stuff works....) The differences aren't so fundamental or important: it's not an entirely new language, just some ugly old things are being removed or changed in incompatible ways (at *some* time it was supposed to happen - but could not happen on the 2.x series which has to remain backwards compatible) Also, Python 3.0 will be released simultaneously with 2.6, and there will be other 2.x releases. Python 2 won't magically disappear from Earth, I don't think Linux distros will come with Python 3.0 by default anytime soon (perhaps not before 3.1). So learning Python with a book targeted to 2.5 isn't a waste of time - not at all. (This subject has already been discussed several times in this group.) -- Gabriel Genellina From kw at codebykevin.com Sun May 25 10:42:06 2008 From: kw at codebykevin.com (Kevin Walzer) Date: Sun, 25 May 2008 10:42:06 -0400 Subject: finding icons for Apps In-Reply-To: <0dc1f496-53b4-44bc-bdf2-3c44b31e2183@c58g2000hsc.googlegroups.com> References: <0dc1f496-53b4-44bc-bdf2-3c44b31e2183@c58g2000hsc.googlegroups.com> Message-ID: <48397ABE.2070006@codebykevin.com> Sanoski wrote: > This might be a dumb question. I don't know. I'm new to all this. How > do you find icons for your programs? All GUI applications have cool > icons that represent various things. For instance, to save is often > represented as a disk, etc. You know, the small little picture > references that give meaning to the phrase 'Graphical User Interface'. > But I'm not a graphics artist! Drawing is simply one talent that > skipped me completely. Where can I find icons to use with my programs? > > I don't even know how to search for them, because I'm not sure how to > word it. I tried Googling various things: icons, software graphics, > application icons, custom graphics, etc, etc. But I'm not getting much > luck here you guys. > > Also, besides just finding a collection of various pre-made icons, who > would I talk to to make me some original custom made icons? I'll look > for hours and find one or two places, but they never respond to my > messages, so I figure they must not do that kind of art work. > > I'm looking for both: a collection of graphics and some place (or > someone) that can make custom original graphics. The latter is just > for future reference. The more important one is the former, because I > can't even afford to pay for originals right now. But maybe I will > soon, so it would be nice to have a resource. > > Thanks in advance, > Joshua http://tango.freedesktop.org/Tango_Desktop_Project http://www.oxygen-icons.org/ http://everaldo.com/crystal/ -- Kevin Walzer Code by Kevin http://www.codebykevin.com From d3vvnull at gmail.com Sat May 3 12:34:39 2008 From: d3vvnull at gmail.com (Michael Mabin) Date: Sat, 3 May 2008 11:34:39 -0500 Subject: Why is None <= 0 In-Reply-To: <4d86a7ce-8f3f-493b-b1c2-a2659817b215@k13g2000hse.googlegroups.com> References: <481226f9$0$20866$9b622d9e@news.freenet.de> <4d86a7ce-8f3f-493b-b1c2-a2659817b215@k13g2000hse.googlegroups.com> Message-ID: <170543c70805030934x2d1c23es90c424c0592590f4@mail.gmail.com> New style classes are classes inherited from class object. Therefore: class A: pass is oldstyle, while class B(object): pass is newstyle. On Tue, Apr 29, 2008 at 8:29 AM, blaine wrote: > On Apr 29, 5:32 am, Duncan Booth wrote: > > =?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?= wrote: > > > (FWIW, in 2.x, x>=4?, it's None < numbers < anything else; > > > numbers are ordered by value, everything else is ordered > > > by type name, then by address, unless comparison functions > > > are implemented). > > > > Quite apart from Jon pointing out that this isn't true for all cases > when > > copmparing against None, the other half also isn't true: > > > > >>> class C: pass > > >>> C() < 5 > > > > True > > > > That happens at least in Python 2.5.2 on win32. Yet another reason to > avoid > > old-style classes. > > Sorry - but what are new style classes? > -- > http://mail.python.org/mailman/listinfo/python-list > -- | _ | * | _ | | _ | _ | * | | * | * | * | -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Wed May 14 19:21:50 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 14 May 2008 16:21:50 -0700 (PDT) Subject: named tuple mutability References: Message-ID: On May 14, 12:41?pm, Raymond Hettinger wrote: > >?Should tuples be named? > > Yes. Good; they're named sequences. From arnodel at googlemail.com Wed May 7 16:12:18 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 07 May 2008 21:12:18 +0100 Subject: Idea for P3K References: <4821d418$0$932$ba4acef3@news.orange.fr> <4821fea4$0$880$ba4acef3@news.orange.fr> Message-ID: "M?ta-MCI (MVP)" writes: > Hi! > >> I don't often feel like using this word > > Look at languages like OCAML or F # While I like Objective Caml, it is definitively not Python! -- Arnaud From rhamph at gmail.com Mon May 12 04:40:01 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Mon, 12 May 2008 01:40:01 -0700 (PDT) Subject: threading - race condition? References: <4823f61e$0$34533$742ec2ed@news.sonic.net> <7bbbb71e-d163-4978-ab90-b96652598757@u6g2000prc.googlegroups.com> <07d4f574-ffda-4c7f-9561-b3be424b141f@y18g2000pre.googlegroups.com> Message-ID: <339cd7bd-0406-430f-93af-148e02c050ca@l17g2000pri.googlegroups.com> On May 11, 10:16 am, skunkwerk wrote: > On May 10, 1:31 pm, Dennis Lee Bieber wrote: > > > > > On Fri, 9 May 2008 08:40:38 -0700 (PDT),skunkwerk > > declaimed the following in comp.lang.python: > > > Coming in late... > > > > On May 9, 12:12 am, John Nagle wrote: > > > >skunkwerkwrote: > > > > > i've declared a bunch of workerthreads(100) and a queue into which > > > > > new requests are inserted, like so: > > > > > > > > > queue = Queue.Queue(0) > > > > > WORKERS=100 > > > > > for i in range(WORKERS): > > > > > thread = SDBThread(queue) > > > > > thread.setDaemon(True) > > > > > thread.start() > > > > > > the thread: > > > > > > class SimpleDBThread ( threading.Thread ): > > > > > def __init__ ( self, queue ): > > > > > self.__queue = queue > > > Note: double-leading __ means "name mangling" -- typically only > > needed when doing multiple layers of inheritance where different parents > > have similar named items that need to be kept independent; a single _ is > > the convention for "don't touch me unless you know what you are doing" > > > > > > threading.Thread.__init__ ( self ) > > > > > def run ( self ): > > > > > while 1: > > > > > item = self.__queue.get() > > > > > if item!=None: > > > > > model = domain.get_item(item[0]) > > > > > logger.debug('sdbthread item:'+item[0]) > > > > > title = model['title'] > > > > > scraped = model['scraped'] > > > > > logger.debug("sdbthread title:"+title) > > > > > > any suggestions? > > > > > thanks > > > > > > > thanks John, Gabriel, > > > here's the 'put' side of the requests: > > > > def prepSDBSearch(results): > > > modelList = [0] > > > counter=1 > > > for result in results: > > > data = [result.item, counter, modelList] > > > queue.put(data) > > > counter+=1 > > > while modelList[0] < len(results): > > > print 'waiting...'#wait for them to come home > > > modelList.pop(0)#now remove '0' > > > return modelList > > > My suggestion, if you really want diagnostic help -- follow the > > common recommendation of posting the minimal /runable (if erroneous)/ > > code... If "domain.get_item()" is some sort of RDBM access, you might > > fake it using a pre-loaded dictionary -- anything that allows it to > > return something when given the key value. > > > > responses to your follow ups: > > > 1) 'item' in thethreadsis a list that corresponds to the 'data' > > > list in the above function. it's not global, and the initial values > > > seem ok, but i'm not sure if every time i pass in data to the queue it > > > passes in the same memory address or declares a new 'data' list (which > > > I guess is what I want) > > > Rather confusing usage... In your "put" you have a list whose first > > element is "result.item", but then in the work thread, you refer to the > > entire list as "item" > > > > 3) the first item in the modelList is a counter that keeps track of > > > the number ofthreadsfor this call that have completed - is there any > > > better way of doing this? > > > Where? None of your posted code shows either "counter" or modelList > > being used by thethreads. > > > And yes, if you havethreadstrying to update a shared mutable, you > > have a race condition. > > > You also have a problem if you are using "counter" to define where > > in modelList a thread is supposed to store its results -- as you can not > > access an element that doesn't already exist... > > > a = [0] > > a[3] = 1 #failure, need to create elements 1, 2, 3 first > > > Now, if position is irrelevant, and a thread just appends its > > results to modelList, then you don't need some counter, all you need is > > to check the length of modelList against the count expected. > > > Overall -- even though you are passing things via the queue, the > > contents being pass via the queue are being treated as if they were > > global entities (you could make modelList a global, remove it from the > > queue entries, and have the same net access)... > > > IOWs, you have too much coupling between thethreadsand the feed > > routine... > > > As for me... I'd be using a second queue for return values... > > > WORKERTHREADS = 100 > > feed = Queue.Queue() > > result = Queue.Queue() > > > def worker(): > > while True: > > (ID, item) = feed.get() #I leave the queues globals > > #since they perform locking > > #internally > > model = domain.get_item(item) > > results.put( (ID, model["title"], model["scraped"]) ) > > > for i in range(WORKERTHREADS): > > aThread = threading.Thread(target=worker) > > #overkill to subclass as there is now no specialized init > > #and if I really wanted to make the queues non-global > > #I'd pass them as arguments: > > # threading.Thread(target=worker, args=(feed, results)) > > #where worker is now > > # def worker(feed, results): > > aThread.setDaemon(True) > > aThread.start() > > > ... > > > def prepSearch(searches): > > modelList = [] > > counter = 0 > > for searchItem in searches: > > feed.put( (counter, searchItem) ) > > counter += 1 > > modelList.append(None) #extend list one element per search > > while counter: > > (ID, title, scraped) = results.get() > > modelList[ID] = (title, scraped) > > counter -= 1 > > return modelList > > > The only place counter and modelList are modified are within the > > prepSearch. I'm passing counter out and back to use as an ID value if > > the final results are supposed to be in order -- that way if one thread > > finishes before another, the items can be placed into the list where > > they'd have been sequentially. > > > I can only hope that "domain.get_item" is an activity that is I/O > > bound AND that it supports parallel accesses... Otherwise the above > > workerthreadsseem to be adding a lot of overhead for queue I/O and > > threading swaps for what is otherwise a rather linear process. > > > Perhaps your posts don't reveal enough... Maybe you have multiple > > mainthreadsthat are posting to the worker feed queue (and you were > > using separate mutables for storing the results). In this situation, I'd > > remove the results queue from being a global entity, create one queue > > per main processing thread, and pass the queue as one of the parameters. > > This way, a worker can return data to any source thread by using the > > supplied queue for the return... > > > Modify prepSearch with: > > > myQueue = Queue.Queue() > > ... > > feed.put( (counter, searchItem, myQueue) ) > > ... > > (ID, title, scraped) = myQueue.get() > > > Modify worker with: > > > (ID, item, retqueue) = feed.get() > > ... > > retqueue.put( (ID, model["title"], model["scraped"]) ) > > wow. thanks for the help. > i seem to have fixed my problem though - it turns out > domain.get_item was not thread safe as it was using the underlying > httplib. the solution was to create a new connection to the database > for each thread (which is ok as the database is meant to be queried in > a massively paralell fashion). the missing part of the code included > a part where i inserted the results at the given position into the > list. > > the only issue i have now is that it takes a long time for 100 threads > to initialize that connection (>5 minutes) - and as i'm doing this on > a webserver any time i update the code i have to restart all those > threads, which i'm doing right now in a for loop. is there any way I > can keep the thread stuff separate from the rest of the code for this > file, yet allow access? It wouldn't help having a .pyc or using > psycho, correct, as the time is being spent in the runtime? something > along the lines of 'start a new thread every minute until you get to a > 100' without blocking the execution of the rest of the code in that > file? or maybe any time i need to do a search, start a new thread if > the #threads is <100? $ python2.5 -m timeit -s 'import threading' 't = threading.Thread(); t.start(); t.join()' 10000 loops, best of 3: 131 usec per loop Clearly it is not the threads themselves, but something else which is expensive. It's not clear why you need threads at all. Unless you've got a lot of cpus/cores running that DBMS, or it's got fairly high latency (and no way to pipeline), attacking it with more threads isn't gonna give significant speedups. From goodprada at 126.com Sat May 10 19:46:51 2008 From: goodprada at 126.com (128) Date: Sat, 10 May 2008 16:46:51 -0700 (PDT) Subject: paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) Message-ID: paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) paypal wholesale, NBA,adidas ( paypal accept ) ( www.honest-shop.cn ) From dteslenko at gmail.com Tue May 13 10:57:03 2008 From: dteslenko at gmail.com (Dmitry Teslenko) Date: Tue, 13 May 2008 18:57:03 +0400 Subject: file locked for writing Message-ID: <91325fec0805130757neb11c4aucfdf825db300d942@mail.gmail.com> Hello! I use some script in python 2.5 from vim editor (it has python bindings) that updates some file and then launches another program (ms visual studio, for example) to do something with updated file. I faced problem when updated file is locked for writing until vim editor is closed. launch vim -> update file -> launch msvc -> file locked launch vim -> update file -> launch msvc -> close vim -> file locked launch vim -> update file -> -> close vim -> launch msvc -> file okay Update code is something like that: backup_file_name = '' with open(backup_file_name, 'w') as backup_file: input = sax.make_parser() output = saxutils.XMLGenerator(backup_file, 'cp1252') filter = __vcproj_config_filter('', input, output) filter.parse('') shutil.copyfile(backup_file_name, '') os.remove(backup_file_name) __vcproj_config_filter is a descent of a XMLFilterBase; it substitutes some attributes in xml file and that's all. must be noted that __vcproj_config_filter instance holds reference to output (sax xml parser) object. From inhahe at gmail.com Wed May 21 01:58:23 2008 From: inhahe at gmail.com (inhahe) Date: Wed, 21 May 2008 01:58:23 -0400 Subject: Removing Space and "-" from a string References: Message-ID: wrote in message news:mailman.1387.1211301238.12834.python-list at python.org... > Shakir, > >> I have thousands of records in MS Access database table, which records I >> am fetching using python script. One of the columns having string like >> '8 58-2155-58' >> >> Desired output: '858215558' >> >> I want to remove any spaces between string and any dashes between >> strings. I could do it in access manually but want to do from python >> script > > Try this: > >>>> input = '8 58-2155-58' >>>> output = ''.join( [ c for c in input if c not in ' -' ] ) >>>> output > '858215558' > > Malcolm how about output = ''.join(input.replace('-',' ').split()) or output = input.replace('-','').replace(' ','') From grante at visi.com Wed May 14 09:51:31 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 14 May 2008 08:51:31 -0500 Subject: Fill memeory with endless loop? References: <252c17a9-01a6-4abe-9515-2507e0e50a20@l64g2000hse.googlegroups.com> Message-ID: On 2008-05-14, Tim Roberts wrote: > globalrev wrote: > >>and when the program gets killed because out of memory all this >>will be deleted from the memory? > > Yes. When a process is killed, all of the memory it was using > is released. > >>so there is no way that you can, by accident, fill your whole >>harddrive and make it unusable? > > Of course not. Where do you see a connection between memory > and your hard drive? > > Now, you can certainly fill your hard drive by running your > little infinite loop application and storing the results in a > file: Again, that's only a problem if the OS lets it be problem. No real OS will let a drive become unusable because of a runaway user program. Any decent filesystem can provide per-user disk quotas and a "reserve" of space for system/root use. -- Grant Edwards grante Yow! I just had a NOSE at JOB!! visi.com From jcd at unc.edu Mon May 5 08:51:25 2008 From: jcd at unc.edu (J. Cliff Dyer) Date: Mon, 05 May 2008 08:51:25 -0400 Subject: confused about self, why not a reserved word? In-Reply-To: <972f7226-baef-4f94-a8ea-5bec99213540@34g2000hsf.googlegroups.com> References: <972f7226-baef-4f94-a8ea-5bec99213540@34g2000hsf.googlegroups.com> Message-ID: <1209991885.3300.2.camel@aalcdl07.lib.unc.edu> On Mon, 2008-05-05 at 04:57 -0700, globalrev wrote: > class Foo(object): > def Hello(self): > print "hi" > > object is purple, ie some sort of reserved word. > > why is self in black(ie a normal word) when it has special powers. > replacing it with sel for example will cause an error when calling > Hello. > Wow. No it won't. sel is perfectly legal. I've seen s used on occasion, and of course metaclass methods often use cls. Direct ^C^V from my python interpreter: $ python Python 2.4.3 (#1, Dec 11 2006, 11:38:52) [GCC 4.1.1 20061130 (Red Hat 4.1.1-43)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> class Foo(object): ... def Hello(sel): ... print "hi" ... >>> f = Foo() >>> f.Hello() hi >>> Can you paste an example that breaks for you? -- Oook, J. Cliff Dyer Carolina Digital Library and Archives UNC Chapel Hill From sebey at mac.com Thu May 29 10:26:18 2008 From: sebey at mac.com (sebey) Date: Thu, 29 May 2008 07:26:18 -0700 (PDT) Subject: feedparser html sanitizion how-to disable it References: Message-ID: oh sorry here is the rss feed I am using http://recordings.talkshoe.com/rss39293.xml From parimala.kalavala at gmail.com Tue May 20 00:18:29 2008 From: parimala.kalavala at gmail.com (PARIMALA KALAVALA) Date: Tue, 20 May 2008 09:48:29 +0530 Subject: regarding process preemption in linux Message-ID: <67eb1c790805192118l646fd5c4l681b196ade76b5d2@mail.gmail.com> Hello, I am presently working on linux. I wanted to know how to view the preemption of one process by another process. If we give TOP command we are not able to visualize it or do we need to write any different code to see it or is it possible to see it in the proc file system. Any help would be appreciated. Thanks Parimala -------------- next part -------------- An HTML attachment was scrubbed... URL: From nevillednz at gmail.com Sat May 3 21:38:46 2008 From: nevillednz at gmail.com (NevilleDNZ) Date: Sat, 3 May 2008 18:38:46 -0700 (PDT) Subject: RegEx for matching brackets References: <713f6d61-906d-490f-bcbc-befd19e086e5@d19g2000prm.googlegroups.com> <4465e4ed-6a37-48a3-ac0d-f3da316301a4@26g2000hsk.googlegroups.com> Message-ID: To check a complete python expression use: def check_open_close(expr): try: eval(expr) except SyntaxError: return False else: return True This also ignores brackets in quotes, and checks <= & >= operators are syntatically correct etc... But is may have side effects... ;-) eg. check_open_close('__import__("os").system("echo rm -rf /") # OK') c.f http://en.wikipedia.org/wiki/Scope_creep N From python at hope.cz Thu May 15 11:38:38 2008 From: python at hope.cz (Johny) Date: Thu, 15 May 2008 08:38:38 -0700 (PDT) Subject: Dbase / foxpro files References: <482c54f2$1@news.mel.dft.com.au> Message-ID: <3e9fcb51-abe6-4a6a-bd1a-9adb5bd155c4@y21g2000hsf.googlegroups.com> On May 15, 5:21?pm, John Machin wrote: > Johny wrote: > > Is there a module for reading/modifing db files from Python? > > Thanks for help > > B. > > I have a module -- which I'm going to get around to releasing one of > these days :-) -- which allows to read dBase III, dBase IV and Foxpro > files (sequentially only, not randomly) and to write dBaseIII files > sequentially. Index files if any are ignored. > > Field types supported for reading: > C character > D date > F float > I integer (32 bits) > L logical > M memo (stored in a .DBT (dBase) or .FPT (FoxPro) file) > N number > T time > > Writing supports only dBaseIII with C, D, L and N fields, but could be > extended easily enough (I've never had the need). No index files are > written. > > E-mail me if you are interested. > > Cheers, > John Hello John, Yes, I am interested. Is it possible to download the module? Thanks Lad From goldnery at gmail.com Fri May 30 08:57:03 2008 From: goldnery at gmail.com (Gandalf) Date: Fri, 30 May 2008 05:57:03 -0700 (PDT) Subject: Generating event from event Message-ID: <37f8a6a1-dc98-4985-a84d-f74ead1ec2b7@z72g2000hsb.googlegroups.com> I have script which being triggered by pressing CTRL+Right mouse click from any place in my O.P , Now I need to generate automatically event like copy my selected item or double clicking the right mouse cursor without user interfering. how can i implement this width python? thanks! From sn at sncs.se Tue May 27 11:21:13 2008 From: sn at sncs.se (Sverker Nilsson) Date: Tue, 27 May 2008 08:21:13 -0700 (PDT) Subject: New chairman References: <3720fb99-ac37-469b-b8ce-ece3ed27b8e5@m36g2000hse.googlegroups.com> Message-ID: I was talking about Guido van Rossum The one who decides, so far when people agree But we can make a new fork He is the originator, but now it seems, for me, it is hanging out in the air So we need some new leadership >From somebody, somebody like you perhaps. Or me. Sverker On May 27, 4:50 pm, "Andrii V. Mishkovskyi" wrote: > 2008/5/27 Sverker Nilsson : > > > seems to be needed > > > He doesn't seem to care much anyway now > > > Or if he cares, he have many other assignments > > Who are you talking about? > > > > > So should we try to elect a new chairman? > > Chairman? Elaborate please. > > > > > I am probably not eligible. There must be many others.! > > > Do you dare?consper > > Hm, are you and castrionpi twin brothers or something? > > > S. > > -- > >http://mail.python.org/mailman/listinfo/python-list > > -- > Wbr, Andrii Mishkovskyi. > > He's got a heart of a little child, and he keeps it in a jar on his desk. From goldnery at gmail.com Sat May 24 09:53:24 2008 From: goldnery at gmail.com (Gandalf) Date: Sat, 24 May 2008 06:53:24 -0700 (PDT) Subject: About events Message-ID: <97a6bea0-69a4-424f-b512-26ff80cecdb8@x41g2000hsb.googlegroups.com> As i said before I work with the WX library on a windows XP operation system. Now i wont to create an application which ran at the background and wait till the user double click on a text word OF any other python or none python application which ran on the desktop, and when this event append i wont my application to pup up a translation of this word. I figured that I need to understand how can i select text automaticlly and copy it to the clipbord for doing that if someone know how to do it, or know whether this WX library capable of doing it (and if not which library can...) i would be very thankful Have a nice day From gherron at islandtraining.com Sat May 3 11:11:12 2008 From: gherron at islandtraining.com (Gary Herron) Date: Sat, 03 May 2008 08:11:12 -0700 Subject: How to use a parameter in a class In-Reply-To: <4923419b-4de0-4739-b02d-753636ef0220@y21g2000hsf.googlegroups.com> References: <4923419b-4de0-4739-b02d-753636ef0220@y21g2000hsf.googlegroups.com> Message-ID: <481C8090.6030905@islandtraining.com> Decebal wrote: > I have the following class: > ##### > class Dummy(): > value = 0 > def __init__(self, thisValue): > print thisValue > self.value = thisValue > value = thisValue > > def testing(self): > print 'In test: %d' % self.value > > def returnValue(self): > return self.value > > result = someFuntion(default = value) > But of course it doesn't work, as it tries to call someFunction and no such thing is define anywhere. But that can't be the answer to the *real* question you are trying to ask. Why don't you tell us what you are trying to do here, and we'll wee if we can help. Gary Herron P.S. Having a class attribute AND an instance attribute, both named "value" is going to cause trouble. > > > ##### > > But the last line does not work. > I would like to do a call like: > dummy = Dummy(thisValue = 12) > > And that someFunction gets a default value of 12. How can I do that? > -- > http://mail.python.org/mailman/listinfo/python-list > From mal at egenix.com Thu May 8 12:13:01 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Thu, 08 May 2008 18:13:01 +0200 Subject: Best technology for agent/web server architecture In-Reply-To: References: Message-ID: <4823268D.1060602@egenix.com> On 2008-05-08 16:16, Florencio Cano wrote: > Hi, > I would be interested in your opinion about what technology you > considear the ideal technology for implementing in Python an agent > that should comunicate information to a web server. I have read about > SOAP but I'm now sure if this will be the right one. > The aim of the agent is gather inventory information and the web > application (I'm programming it in Django) will receive this > information and will store it in the database and will show it in > tables. The choice of protocol depends a lot on what you want to transfer. SOAP would be a good choice if you want to send to data to other servers as well, e.g. Java-based ones. XML-RPC and JSON are better for simple data structures. If you have control over both client and server and don't need to bother with other backends or frontends, Python pickle is the best choice. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, May 08 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From timr at probo.com Thu May 22 00:52:16 2008 From: timr at probo.com (Tim Roberts) Date: Thu, 22 May 2008 04:52:16 GMT Subject: Write bits in file References: <94ce5e02-0185-4513-9bc1-7ec483be57aa@y21g2000hsf.googlegroups.com> Message-ID: "sjdevnull at yahoo.com" wrote: >On May 20, 12:14 am, Tim Roberts wrote: >> Monica Leko wrote: >> >> >I have a specific format and I need binary representation. Does >> >Python have some built-in function which will, for instance, represent >> >number 15 in exactly 10 bits? >> >> For the record, I'd like to point out that even C cannot do this. You need >> to use shifting and masking to produce a stream of 8-bit bytes, or to >> extract your values from a stream of 8-bit bytes. > >Technically specifying 8-bits isn't quite accurate, as C allows for 9- >bit bytes and other variations depending on the architecture. But >that may be overly pedantic unless you have a PDP-10 laying around >that you're writing C code on or something like that. As long as we are being pedantic, and I don't mind that, I would point out that I didn't actually say that C worked in 8-bit bytes. I was very careful to say merely that, assuming you wanted a stream of 8-bit bytes, you need to use shifting and masking to produce it. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From __peter__ at web.de Thu May 29 09:33:25 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 29 May 2008 15:33:25 +0200 Subject: Reporting the line number of an exception References: <229d7d86-c652-4282-aaa9-4274cd0d63fd@a1g2000hsb.googlegroups.com> Message-ID: sophie_newbie wrote: > I'm sure this is exceedingly simple but I can't find it anywhere. When > I catch an exception I would like to report the line number of the > exception as well as the error info. > > try: > someError() > except Exception, e: > "print_error_and_line_number" > > How do I find the line number? If you want just the line number: tb = sys.exc_info()[2] print tb.tb_lineno You may also have a look at the traceback module, e. g.: traceback.print_exc() Peter From musiccomposition at gmail.com Sun May 25 23:05:13 2008 From: musiccomposition at gmail.com (Benjamin) Date: Sun, 25 May 2008 20:05:13 -0700 (PDT) Subject: Performance of Python builtins References: Message-ID: On May 25, 6:19 pm, miller.pau... at gmail.com wrote: > Is there any place outside the actual C source for Python that has > information about the performance of Python's built-in operations? For > example, I'd *expect* list.append to be O(1), and I hope that list[i] > is O(1), but I don't really know that for sure, since it would depend > a lot on the internal implementation. > > I'm really only asking this for curiosity's sake --- more as a > reasonable, non-trollish version of the "Python is slow" post than > anything. :-) I've never really had any problems with the performance > of Python code that I couldn't solve by either changing my algorithm > or, if all else has truly failed, rewriting in C or Pyrex. > > What I'd like to see is something likehttp://svn.python.org/projects/python/trunk/Objects/listsort.txt > where Python's sorting algorithm is described, except with the focus > on other built-in constructs. http://wiki.python.org/moin/TimeComplexity is a start. > > Thanks! From deets at nospam.web.de Tue May 13 12:40:54 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 13 May 2008 18:40:54 +0200 Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <2b66a86e-5a05-4262-b3c9-4703b0ae3372@d1g2000hsg.googlegroups.com> <5b0e3f70-afde-4480-8713-e7113b1250d7@x35g2000hsb.googlegroups.com> <1f537717-00d0-48ee-99b6-7125b96a6133@t12g2000prg.googlegroups.com> <68t4o0F2vaoncU1@mid.uni-berlin.de> <2a32179a-9439-449c-bd07-fff6a4075aee@s50g2000hsb.googlegroups.com> <7ee5dffd-df8f-46f0-bd78-c81ac0418a9a@d77g2000hsb.googlegroups.com> <65ef773e-a1c3-4adb-a18b-e8b8451efe5e@b5g2000pri.googlegroups.com> <68trmmF2vjivnU1@mid.uni-berlin.de> <68tuhfF2unducU1@mid.uni-berlin.de> Message-ID: <68tulsF2unducU2@mid.uni-berlin.de> > This shows how much you don't know about customers, and their needs. A > customer gives a s**t about 5-10 times faster sites. They care if it is > *fast enough*, but beyond that they don't bother. But what *always* > bothers them is development time & flexibility. Because that directly > affects the price they pay. Just to support this statement: PHP runs an order of magnitude slower than python. Yet a great deal (if not the majority) of dynamic sites out there run under PHP. All of these are unhappy customers? Diez From geonomica at gmail.com Fri May 23 02:03:17 2008 From: geonomica at gmail.com (gianluca) Date: Thu, 22 May 2008 23:03:17 -0700 (PDT) Subject: ctypes help References: <6a3247f6-3ea2-4c8c-b66b-43f31878fb01@z72g2000hsb.googlegroups.com> <8bc14652-a62e-4724-99b8-afee7ce41511@2g2000hsn.googlegroups.com> <69n463F33hfhfU2@mid.uni-berlin.de> Message-ID: On 23 Mag, 07:48, Marc 'BlackJack' Rintsch wrote: > On Thu, 22 May 2008 21:55:41 -0700, gianluca wrote: > > Yes, I know it but when I load a function (a=myDLL.myFUNCT()) I've an > > exception like this: > > > Traceback (most recent call last): > > File "", line 1, in > > myDLL.myFUNCT() > > File "C:\Python25\lib\ctypes\__init__.py", line 353, in __getattr__ > > func = self.__getitem__(name) > > File "C:\Python25\lib\ctypes\__init__.py", line 358, in __getitem__ > > func = self._FuncPtr((name_or_ordinal, self)) > > AttributeError: function 'myFUNCT' not found > > Then maybe the DLL doesn't contain a function called `myFUNCT`. Any > chance you compiled your C as C++ and name mangling kicked in? > > Can you show a minimal C source for a DLL, how you compiled it, what you > did on the Python side to call it, and how it fails? > > Ciao, > Marc 'BlackJack' Rintsch I've located my dll in c:\windows\system32 (in linux I aven't any problem) and I compiled it with dev-c++. The source code is C standard ANSII and is quite havy. If you like I can send it via mail (you can realy at geonomica at gmail.com) . I've tryed to build a wrape with swig olso with same code and I can access at all the function. thanks Gianluca From bearophileHUGS at lycos.com Sun May 4 06:50:00 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sun, 4 May 2008 03:50:00 -0700 (PDT) Subject: Light slices + COW References: Message-ID: <53fa8195-ae1c-42c0-8a56-d9ffce39b5f0@r66g2000hsg.googlegroups.com> David: > What do you mean by best possible? Most efficient? Most readable? What's a good wine? It's not easy to define what's "good/best". In such context it's a complex balance of correct, short, fast and readable (and more, because you need to define a context. This context refers to Psyco too). > And why don't you use islice? You are right, but the purpose of light slices that I have suggested is to avoid using islice so often. And currently Psyco doesn't digest itertools well. > D compiles to efficient machine code so Python is at a disadvantage > even if you use the same syntax (see my first example). You can make > the Python version faster, but beware of premature optimization. This time I don't agree with this "premature optimization" thing. My original Python version is just 5 lines long, it's readable enough, and it's a part of a large library of mine of similar functions, they must be fast because I use them all the time as building blocks in programs. > What I'dlike to see is a rope[1] module for Python. People have already suggested it, and there's even an implementation to replace Python strings. It was refused because... I don't know why, maybe its implementation was too much more complex than the current one, and it wasn't faster in all situations (and I think Guido wants data structures that try to replace the basic built-in ones to be faster in all situations and user-transparent too). Bye, bearophile From ivan.illarionov at gmail.com Fri May 16 21:48:53 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Sat, 17 May 2008 01:48:53 +0000 (UTC) Subject: addendum Re: working with images (PIL ?) References: Message-ID: On Wed, 14 May 2008 14:35:25 -0400, Poppy wrote: > I've put together some code to demonstrate what my goal is though > looping pixel by pixel it's rather slow. > > import Image > > def check_whitespace(): > im = Image.open("\\\\server\\vol\\temp\\image.jpg") > > size = im.size > > i = 0 > whitePixCount = 0 > while i in range(size[1]): > j = 0 > while j in range(size[0]): > p1 = im.getpixel((j,i)) > if p1 == (255, 255, 255): > whitePixCount = whitePixCount + 1 > if whitePixCount >= 492804: ## ((image dimensions 1404 > x > 1404) / 4) 25% > return "image no good" > j = j + 1 > i = i + 1 > > print whitePixCount > > return "image is good" > > print check_whitespace() > > > "Poppy" wrote in message news:... >>I need to write a program to examine images (JPG) and determine how much >>area is whitespace. We need to throw a returned image out if too much of >>it is whitespace from the dataset we're working with. I've been >>examining the Python Image Library and can not determine if it offers >>the needed functionality. Does anyone have suggestions of other image >>libraries I should be looking at it, or if PIL can do what I need? >> PIL will do this, use histogram() method of Image objects. -- Ivan From torriem at gmail.com Mon May 12 00:09:11 2008 From: torriem at gmail.com (Michael Torrie) Date: Sun, 11 May 2008 22:09:11 -0600 Subject: Module python-magic on/for Windows? In-Reply-To: <3a66adfe-3fd6-4f23-a6e8-4b219db1a3cd@x41g2000hsb.googlegroups.com> References: <3a66adfe-3fd6-4f23-a6e8-4b219db1a3cd@x41g2000hsb.googlegroups.com> Message-ID: <4827C2E7.2040703@gmail.com> Larry Hale wrote: > ALSO: I've even tried putting the 4 "magic" files INTO the .egg > file... still no-go. :/ It's often the custom of programs ported from unix to windows to use the dll location as a key to find the other files that are typically in share, or etc. GTK, for example uses ../share and ../etc from the location where the dlls are stored (if the dlls are in a folder called bin). In this case I'd try making a folder in the Python25 folder called "share" and put the contents of the gnuwin32 share/file stuff in there. Should look something like this: c:/python25/share/file/magic.mime.mgc c:/python25/share/file/magic c:/python25/share/file/magic.mgc c:/python25/share/file/magic.mime Or, judging by a string I found in the dll itself, you might have to put the files here: c:/progra~1/File/share/file/magic Although if such a path really is hardcoded into the dll, this is certainly a bug, since it will fail on certain non-english windows systems. Anyway, who knows. Give these options a try. From larzluv at hotmail.com Sun May 11 21:51:28 2008 From: larzluv at hotmail.com (Larry Hale) Date: Sun, 11 May 2008 18:51:28 -0700 (PDT) Subject: list object References: <066c62a8-4400-4f94-bddb-d23eac01486a@27g2000hsf.googlegroups.com> Message-ID: <4dbdd79b-3364-4fe1-9cd8-6ae5e1394309@d45g2000hsc.googlegroups.com> On May 10, 12:39 pm, Gandalf wrote: > my manual contain chapter about lists with python. when i try to copy > paste : > > li = ["a", "b", "mpilgrim", "z", "example"] (1) > > it i get this errore: > > "TypeError: 'list' object is not callable" > > i was wondering if their is any special module I should import before > i use this function > > i know i ask foolish questions it's my first day with python and i > have experience only with PHP and javascript, so please be patient > > thanks To expand upon what others have already mentioned, and/or to explain what's going on... li ==>> a label for a "list" (presume the author used it as short- hand?); trying to set it to point-to/"equal"... ["a", "b", "mpilgrim", "z", "example"] ==>> THE LIST A "list" is a mutable (changeable in-place) container object. See e.g.: http://www.diveintopython.org/native_data_types/lists.html (1) ==>> the Python interpreter will interpret this as if you're attempting to "call" the list object (["a", "b", ...]) as if it were a function/method Indeed, the "(1)" is what's causing the problem, but it's -because- the list *object* is, well, "not callable". :) As an aside, see what "li" contains if you do: li = ["a", "b", "mpilgrim", "z", "example"][1] ;) Cheers! -Larry Hale From ivan.illarionov at gmail.com Tue May 27 21:32:24 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Wed, 28 May 2008 01:32:24 +0000 (UTC) Subject: php vs python References: <5l%Yj.77$mz3.53@fe101.usenetserver.com> <37b112d8-a3ba-446d-9d2f-d907d93c637b@w8g2000prd.googlegroups.com> <-t-dnWQ4bZN2MaTVnZ2dnUVZ_qGdnZ2d@comcast.com> <68cb8bb1-4cc5-4a28-8915-46e7d4e316d9@d1g2000hsg.googlegroups.com> <613388153.20080528051020@freemail.ru> Message-ID: On Wed, 28 May 2008 05:10:20 +0400, AnrDaemon wrote: > Greetings, Ivan Illarionov. > In reply to Your message dated Monday, May 26, 2008, 04:47:00, > >>> As I've said before - good programmers can write good code in any >>> language. > >> Yes, they can. But it may be harder to do for them in one language and >> easier in another. > > It's obvious lie. If you have clear mind and you know language you're > using, there are absolutely NOTHING can deny you to write clear code. > Even using forth postfix notation, I have no problem writing good code, > it's as easy as writing bad code. And yes, I do see the difference. No. Language does matter. From casey.mcginty at gmail.com Mon May 26 04:00:07 2008 From: casey.mcginty at gmail.com (Casey McGinty) Date: Sun, 25 May 2008 22:00:07 -1000 Subject: Fwd: Organizing a Python project In-Reply-To: References: <960da03c-1edf-4fa4-b434-6656e8a8884f@e39g2000hsf.googlegroups.com> Message-ID: On Sun, May 25, 2008 at 4:51 PM, Gabriel Genellina wrote: > En Sun, 25 May 2008 19:46:50 -0300, Casey McGinty > escribi?: > > The '_' should indicate that any other modules using your package should > import > > that module. > > Not only using _package isn't very common - it goes against the general > rule (this one very well established) that names with a single leading > _underscore are private (implementation details). > My mistake. I meant to write, "should *not*", as you pointed out. - Casey -------------- next part -------------- An HTML attachment was scrubbed... URL: From rdm at rcblue.com Fri May 30 13:56:04 2008 From: rdm at rcblue.com (Dick Moores) Date: Fri, 30 May 2008 10:56:04 -0700 Subject: A video introducing Ulipad, an IDE mainly for Python In-Reply-To: References: Message-ID: <20080530175628.BCCB01E4005@bag.python.org> At 07:57 AM 5/30/2008, David C. Ullrich wrote: >In article , > Dick Moores wrote: > > > I've been using Ulipad, a free IDE mainly for Python, and written in > > wxPython, for a couple of years, and think it's terrific. Now another > > user, Kelie Feng, has made an 8-minute video showing it off. The > > visual clarity of the video is remarkable. You can download it > > (Introducing_Ulipad_2008-05-22.avi), and a codec (tscc.exe) that may > > be necessary for your player, from . > >I skipped the video and tried Ulipad. Looks very interesting. > >The documentation I got is mostly in Chinese. Is there an >English version somewhere? F1 will open "UliPad Documentations". Check out the HowTo's and the FAQ. And subscribe to the Ulipad list at Google Groups (). The main developer, Limodou, is in Beijing, but he's very quick in answering questions posed to the list. Dick Moores From tjreedy at udel.edu Sat May 10 14:56:41 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 10 May 2008 14:56:41 -0400 Subject: list object References: <066c62a8-4400-4f94-bddb-d23eac01486a@27g2000hsf.googlegroups.com> <3d881a310805101047s1cc9c803wb87805e8044b514c@mail.gmail.com> Message-ID: "member thudfoo" wrote in message news:3d881a310805101047s1cc9c803wb87805e8044b514c at mail.gmail.com... | On 5/10/08, Gandalf wrote: | > my manual contain chapter about lists with python. when i try to copy | > paste : | > | > li = ["a", "b", "mpilgrim", "z", "example"] (1) | > | > | > it i get this errore: | > | > "TypeError: 'list' object is not callable" | Remove the "(1)" The '(1)' was almost certainly an 'equation number' or 'line label' added so the author could refer it in the text, like 'type line (1) into the interpreter and... . This is a standard mathematical idiom, but sometimes confusing when there is not enough space between the equation and the label, and especially when the equation label *could* be part of the equation, as with Python. From upton at virginia.edu Wed May 28 14:48:36 2008 From: upton at virginia.edu (Dan Upton) Date: Wed, 28 May 2008 14:48:36 -0400 Subject: Python and Flaming Thunder In-Reply-To: <3dd6fa95-e9fe-4922-a46d-020cf9263469@w4g2000prd.googlegroups.com> References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <20080514215943.14c92f16.johnjsal@NOSPAMgmail.com> <94bac166-d13c-44dd-af84-db19e19488b8@w1g2000prd.googlegroups.com> <8cfd3523-8d16-40bc-b904-94a6a36a414d@p25g2000pri.googlegroups.com> <5c98049e-e62e-4ab1-afed-b0a3e186bd05@w1g2000prd.googlegroups.com> <3dd6fa95-e9fe-4922-a46d-020cf9263469@w4g2000prd.googlegroups.com> Message-ID: <5504f9ac0805281148w11581481x4257af4a5f6f762b@mail.gmail.com> On Wed, May 28, 2008 at 11:09 AM, Dave Parker wrote: >> > If catch(set x to y+z.) < 0.1 then go to tinyanswer. >> >> So what does this do exactly if the set throws an error? > > I think the catch should catch the error thrown by set, compare it to > 0.1, the comparison will not return true because the error is not less > than 0.1, and so the go-to to tinyanswer will not be taken. > The semantics you're describing aren't clear here. I suppose that's sort of reasonable, given that you haven't implemented it yet, but let's think about it for a second. You say the catch construct should catch the error thrown by set, but there's no reason "set" itself should throw any sort of error in the sense of an exception--in a statement like "Set x to SomeFunctionThatCanBlowUp()", the semantics should clearly be that the error comes from the function. In a simple addition statement, that makes no sense. So then I considered that maybe you meant the error in the sense of some determination of floating point roundoff error, but that can't be it, since you've claimed recently a big win over Python with FT in that it has no roundoff error. So what, exactly, is the error you could even be catching in that? Assuming the answer is "You're right, there's no actual error that could generated by that assignment," there are two options: the compiler optimizes it away, or you throw a compile-time error. The latter makes more sense, as someone trying to catch an exception where one can't possibly exist probably indicates a misunderstanding of what's going on. > ... That's why C had to > resort to the confusing "=" vs "==" notation -- to disambiguate the > two cases. The "catch" keyword unambiguously alerts the reader that > the parenthesis contain a statement (or a whole list of statements). > However, I think overloading your catch error types to include objects (or integral values, I guess, your example below isn't clear) along with real values (ignoring the bit above about whether floating-point assignment could throw an error) makes things confusing. It's nice that "catch(stuff)" indicates that there's one or more statements inside, but so does indentation in Python, bracketing in C/C++, Begin/End in , and so forth, but it doesn't give any indication to what could come out and ideally, only one thing (or its descendants in a type hierarchy) can come out. (I suppose this can be solved by overloading your comparison operators.) Beyond that, I think you would want a good mechanism for comparing ranges of values if you want to make exceptions/errors real-valued. >> For that matter, is there any way to distinguish between different errors >> and only catch particular ones? > > I think the catch function should catch all of the errors (and the non- > error result if no error occured), so I think distinguishing the error > would have to come after. Maybe something like: > > Set result to catch(read x from "input.txt".). > If result = dividebyzeroerror then ... else throw result. > > I'm open to alternate suggestions, though. > From skunkwerk at gmail.com Tue May 6 14:41:07 2008 From: skunkwerk at gmail.com (skunkwerk) Date: Tue, 6 May 2008 11:41:07 -0700 (PDT) Subject: logger output References: <1e6846b9-67b9-4a79-9454-a528aa8aca17@j33g2000pri.googlegroups.com> <65a6be8e-d67f-4255-938a-fcfbfb8b4eb1@z16g2000prn.googlegroups.com> Message-ID: On May 5, 3:44?pm, "Gabriel Genellina" wrote: > En Mon, 05 May 2008 13:02:12 -0300,skunkwerk escribi?: > > > > > On May 4, 10:40 pm, "Gabriel Genellina" > > wrote: > >> En Mon, 05 May 2008 00:33:12 -0300,skunkwerk escribi?: > > >> > i'm redirecting the stdout & stderr of my python program to a log. > >> > Tests i've done on a simple program with print statements, etc. work > >> > fine. ?however, in my actual program i get weird output like this: > > >> > 2008-05-04 20:20:44,790 DEBUG Grabbing message from queue, if any > >> > 2008-05-04 20:20:44,790 DEBUG DEBUG:doit:Grabbing message from queue, > >> > if any > >> > 2008-05-04 20:20:44,790 DEBUG DEBUG:doit:DEBUG:doit:Grabbing message > > >> Try this simplified example and see by yourself: > > >> import sys > > >> class Write2Log: > >> ? ? ?def write(self, x): > >> ? ? ? ? ?sys.__stdout__.write('[%s]' % x) > > >> sys.stdout = Write2Log() > > >> print "Hello world!" > >> age = 27 > >> name = "John" > >> print "My name is", name, "and I am", age, "years old." > > > thanks Gabriel, > > ? ?i tried the code you sent and got output like the following: > > [My name is][][john][][and I am][][27][][years old.] > > > it doesn't really help me though. ?does this have any advantages over > > the syntax i was using? > > are there any limits on what kind of objects the logger can write? ?ie > > ascii strings of any length? > > The example doesn't use any logger, so loggers aren't the problem here, ok? > > The write function above puts square brackets [] around anything it receives. This way you can see exactly how write() is called: once per *item* in the print statement, plus once per comma used (with an space character that you didn't copy correctly). > > Back to your original code, you have to call logger.debug with a *line* of text, but you are calling it with many small pieces - that's the problem. Accumulate output until you see a '\n' - then join all the pieces into a single, complete line and finally call logger.debug > > -- > Gabriel Genellina thanks Gabriel, i wrote the function below, but am now getting an "Error in sys.exitfunc:" error (which disappears when i comment out the last two lines below): class write2Log: def write(self, x): if x!=',':#ignore if a comma if str(x).count('\n')==0: buffer += str(x) else: list = str(x).split('\n') logger.debug(buffer) buffer = "" for text in list: logger.debug(text) sys.stdout = write2Log() sys.stderr= write2Log() any ideas what might be wrong? thanks again From xahlee at gmail.com Wed May 21 12:28:43 2008 From: xahlee at gmail.com (Xah) Date: Wed, 21 May 2008 09:28:43 -0700 (PDT) Subject: Python's doc problems: sort References: <929d5ce9-9063-4e6c-98aa-89526f89fba3@y18g2000pre.googlegroups.com> Message-ID: <6c89401d-992c-44a2-b650-f28b2d2d537f@f24g2000prh.googlegroups.com> alex23 wrote: ?No, what was generally rejected was the idea that *you* could bring more clarity to the documentation, based on the complete absence of it in your posts & "essays". Basically, noone wanted docs that would randomly degenerate into ad hominem accusations of elitism aimed at the module authors.? Dear Alex moron number 23, The art of writing takes many forms. Let's take, the hallowed name Shakespeare. Imagine, we injest his writing style into modern journalism. What is the resulting quality? It would be condemned as the worst journalism possible. Imprecise, logorrhea, obscure, and in general, much ado about nothing. On the other hand, if we apply the spirit of scientific report into poetry, what is the resulting quality? Dry, inert, dead. A man without a cock, a woman without tits. You see, i had to craft my style to fit occasions. In dealing with newsgroup morons like yourself, the proper style is to infuse insult with fanfare. Further readings: The Tragedy Of Titus Andronicus http://xahlee.org/p/titus/titus.html Politics and the English Language http://xahlee.org/p/george_orwell_english.html English Lawers (or, how to master writing) http://xahlee.org/UnixResource_dir/writ/english_lawers.html Xah xah at xahlee.org ? http://xahlee.org/ ? From chris.lyon at spritenote.co.uk Tue May 6 05:53:08 2008 From: chris.lyon at spritenote.co.uk (wyleu) Date: Tue, 6 May 2008 02:53:08 -0700 (PDT) Subject: parameters to lambda's executed at run time. Message-ID: I'm trying to supply parameters to a function that is called at a later time as in the code below: llist = [] for item in range(5): llist.append(lambda: func(item)) def func(item): print item for thing in llist: thing() which produces the result IDLE 1.2.1 >>> ================================ RESTART ================================ >>> at 0xb716356c> at 0xb71635a4> at 0xb71635dc> at 0xb7163614> at 0xb716364c> >>> ================================ RESTART ================================ >>> 4 4 4 4 4 >>> How can one allocate a different parameter to each instance of the function rather than all of them getting the final value of the loop? From kyosohma at gmail.com Sun May 18 13:04:42 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Sun, 18 May 2008 10:04:42 -0700 (PDT) Subject: Distributing applications that use 3rd party modules References: <8728ad1c-2b4a-47db-aeda-8d2416b6bdc8@i76g2000hsf.googlegroups.com> Message-ID: On May 17, 10:13?am, eliben wrote: > On May 17, 3:23 pm, Mike Driscoll wrote: > > > > > On May 17, 4:42 am, eliben wrote: > > > > Hello, > > > > I'm getting into Python now after years of Perl, and as part of my > > > research I must understand how to do some common tasks I need. > > > > I have a bunch of Windows PCs at work to which I want to distribute an > > > application I've developed on my PC. All these PCs have Python 2.5 > > > installed. > > > > If my application contains only code I've developed, I simply zip its > > > directory with .py files and send it to everyone, who can then use it > > > by running the entry-point .py file. However, what if I've installed > > > some 3rd party modules on my PC, and my application uses them (for > > > example pyparsing, PiYAML and some others) ? I don't want to manually > > > install all these packages (there may be dozens of them) on all those > > > PCs (there may be dozens of those too). What is the best method I can > > > use ? Naturally, I want all the non-standard packages my app uses to > > > be detected automatically and collected into some kind of convenient > > > distributable that is easy to pass around and run. > > > > I'm aware of py2exe - tried it and it works fine. But it creates huge > > > executables, and I don't want to distribute those all the time. I much > > > prefer a zipped directory of .py scripts that takes some 10s of KBs. > > > > Thanks in advance, > > > Eli > > > You might want to check out Buildout. It allows you to run all that > > stuff in it's own virtual world, so to speak. I'm planning on playing > > with it this week. > > I looked at its examples and I'm not sure it's what I need. It seems > useful for other cases though. > > > Also, there's this site which has collected the various means of > > distributing Python apps: > > >http://www.freehackers.org/Packaging_a_python_program > > This page only talks about the packagers that create .exe files that > don't need Python installed. > > Is there a simple way to find out which packages are used by my > script ? > > Eli I'm fairly certain you can use that Freeze application to do the dirty work for you. Or you can just distribute the pyc files...I've heard that works somehow too. Mike From clyfish at gmail.com Wed May 7 23:11:04 2008 From: clyfish at gmail.com (clyfish at gmail.com) Date: Wed, 7 May 2008 20:11:04 -0700 (PDT) Subject: how to use subprocess.Popen execute "find" in windows References: <5666ed04-8a2f-4dad-b7bc-3e3c3c084f03@f24g2000prh.googlegroups.com> <0c999d92-e3e5-4f5c-b636-73739abd675a@1g2000prg.googlegroups.com> Message-ID: <482d3eed-a7ff-4419-9340-64b7809beea0@n1g2000prb.googlegroups.com> On 5?7?, ??2?41?, alito wrote: > On May 6, 7:19 pm, clyf... at gmail.com wrote: > > > In cmd, I can use find like this. > > > C:\>netstat -an | find "445" > > TCP 0.0.0.0:445 0.0.0.0:0 LISTENING > > UDP 0.0.0.0:445 *:* > > > C:\> > > > And os.system is OK.>>> import os > > >>> os.system('netstat -an | find "445"') > > > TCP 0.0.0.0:445 0.0.0.0:0 LISTENING > > UDP 0.0.0.0:445 *:* > > 0 > > > But I don't know how to use subprocess.Popen to do this. > > > from subprocess import Popen, PIPE > > > p1 = Popen(['netstat', '-an'], stdout = PIPE) > > p2 = Popen(['find', '"445"'], stdin = p1.stdout, stdout = PIPE) > > print p2.stdout.read() > > Get rid of the extra quotes. ie: > p2 = Popen(['find', '445'], stdin = p1.stdout, stdout = PIPE) > > The quotes on the command line and on the os.system call are consumed > by the shell. The program doesn't see them. You must be a linux user:) I guess, in windows, the quotes are consumed by the c runtime library. Mayby the "find" in windows doesn't use the argc/argv but the windows API GetCommandLine(). I wrote a c program to prove it. #include #include int main(int argc, char **argv) { int i; printf("%s\n", GetCommandLine()); for (i = 0; i < argc; ++i) printf("%d: %s\n", i, argv[i]); return 0; } The output is: C:\>test 1 2 "3" test 1 2 "3" 0: test 1: 1 2: 2 3: 3 C:\> Notice that, GetCommandLine() does not consume the quotes, but the (char **argv) does. From gagsl-py2 at yahoo.com.ar Fri May 2 12:30:24 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 02 May 2008 13:30:24 -0300 Subject: Best way to store config or preferences in a multi-platform way. References: Message-ID: En Thu, 01 May 2008 10:30:03 -0300, Nick Craig-Wood escribi?: > As for where to store it, I use os.path.expanduser("~") to find the > base directory and a bit of platform specific code. > > Something like this snippet > > self.is_windows = sys.platform == 'win32' > self.home = os.path.expanduser("~") > if self.is_windows: > self.config_dir = os.path.join(self.home, "Application Data", > self.NAME) > else: > self.config_dir = os.path.join(self.home, "."+self.NAME) > if not os.path.isdir(self.config_dir): > os.makedirs(self.config_dir, mode=0700) > self.config_file = os.path.join(self.config_dir, "config") Please don't do that if you distribute your programs. "Application Data" is a localized name, like "Program Files" and all special folders. On my Spanish version of Windows, they're "Datos de programa" y "Archivos de Programa" respectively, and the user may choose to move them to another location. Use SHGetFolderPath to obtain the path; see http://msdn.microsoft.com/en-us/library/bb762181(VS.85).aspx -- Gabriel Genellina From kyrie at uh.cu Wed May 7 16:39:30 2008 From: kyrie at uh.cu (Luis Zarrabeitia) Date: Wed, 7 May 2008 16:39:30 -0400 Subject: Am I missing something with Python not having interfaces? In-Reply-To: <200805072119.30744.onsen-neko@gmx.net> References: <45de2f7e-484a-4871-bbaa-bf7eed5dfa40@x35g2000hsb.googlegroups.com> <74f98740-6f44-44da-b546-dc1cb1bb9006@a23g2000hsc.googlegroups.com> <200805072119.30744.onsen-neko@gmx.net> Message-ID: <200805071639.30414.kyrie@uh.cu> On Wednesday 07 May 2008 03:19:30 pm Daniel Marcel Eichler wrote: > Am Dienstag 06 Mai 2008 16:07:01 schrieb Mike Driscoll: > > Well, no. It's a litte different. Interfaces force to implement methods. > Simple inheritance with method-stubs can't garantee that a specific > method is reimplementat in a sub-class. Interfaces work at > compile-time, while method-stubs raise at their first call, so in worst > case, never (when the developer is available). class MyClass implements MyInterfaceWithPassMethod { function Pass() { } } There you have it, interfaces are not enough to ensure that the implementors actually implement the methods. They are useful for warning at compile time if there is a missing method, but nothing more. I believe you could achieve a very similar warning in python using some kind of Interface metaclass (too lazy right now to hack a proof of concept, but it looks doable). I actually like the Interface concept... as portrayed by zope.Interfaces and pyprotocols (not the same thing, but I like them), and the ABCs (these, not so much). But Java interfaces are barely a replacement for multiple inheritance+abstract methods. > That's the point. Interfaces garantee that a duck is a duck, an not only > a chicken that quack. Not really. (See the NotImplementedExceptions in .NET 1.1 and window forms, and/or their TabbedControl/TabPage background color attribute. Can't find them now, as I don't have .NET anymore, but I consider that an example of why the static typing are... overrated) -- Luis Zarrabeitia (aka Kyrie) Fac. de Matem?tica y Computaci?n, UH. http://profesores.matcom.uh.cu/~kyrie From see at sig.below Sat May 10 19:25:43 2008 From: see at sig.below (Barb Knox) Date: Sun, 11 May 2008 11:25:43 +1200 Subject: implementation for Parsing Expression Grammar? References: <48257ab7$0$29576$c83e3ef6@nn1-read.tele2.net> Message-ID: In article <48257ab7$0$29576$c83e3ef6 at nn1-read.tele2.net>, Lars Rune N??stdal wrote: > Hi, > Finite automata works for "nested things". Only in the special case when the depth of nesting is bounded ahead of time. If it's unbounded then there is an unbounded amount of "stack" information that the automaton needs to remember, therefore a finite automaton cannot do it. That should be "Finite automata WORK ...", since "automata" is plural. > http://en.wikipedia.org/wiki/Automata_theory -- --------------------------- | BBB b \ Barbara at LivingHistory stop co stop uk | B B aa rrr b | | BBB a a r bbb | Quidquid latine dictum sit, | B B a a r b b | altum viditur. | BBB aa a r bbb | ----------------------------- From deets at nospam.web.de Tue May 6 08:53:06 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 06 May 2008 14:53:06 +0200 Subject: Comparing strings - akin to Perl's "=~" References: Message-ID: <68b2meF2s3iqjU1@mid.uni-berlin.de> krumblebunk at gmail.com wrote: > Hello gurus, > > I am learning Python to take the place of Perl in my toolbox of bits > and bobs, and writing something pretty simple in theory, but having a > hard time in Python with it - I am using a 3rd party module, and I am > sure the etiquette of this channel states that this is pure Python > questions only, but please bare with me in light of this, as my > question does indeed relate to Python only. > > I am grabbing the output from a SQL statement (using PyGreSQL 'pg' > module), and when it returns the result, I am pulling it out as such: > > try: > sc=pg.connect(dbname='mydb',host='dbhost',user='ppp') > except pg.InternalError: > print "Failed to execute SQL: %s" % sql > exit > > for foo in sc.query(sql).dictresult(): <- this returns a dict of the > result > f=dict(foo) > for k in f.iteritems() > if k == '^Hostname': <-- need this sort of > behaviour - match a partial string. > print "%s" % f[3] <-- ..and if true, need to pull > out the 4th column on that line. > > This breaks spectacularly - > > any ideas? Use the module "re" to create regular expressions & out of these mather-objects that will give you what you need. The idiom is roughly translated to this: m = re.search(r"^Hostname') if m: ... Diez From tjreedy at udel.edu Sun May 25 21:43:22 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 25 May 2008 21:43:22 -0400 Subject: Performance of Python builtins References: Message-ID: wrote in message news:d7549dfd-6770-4924-8f0c-1746642bd8a4 at k37g2000hsf.googlegroups.com... | Is there any place outside the actual C source for Python that has | information about the performance of Python's built-in operations? Unfortunately no. Guido does not want to put guarantees in the language definition, so there is no urgency to document this. An auxiliary doc might be accepted. But the people who could write such a thing are busy doing otherwise. Certainly, no one has volunteered to write *and update* such. From kyosohma at gmail.com Sat May 10 15:28:53 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Sat, 10 May 2008 12:28:53 -0700 (PDT) Subject: Is there a PyPI API? References: <7acaec98-73ca-436c-b153-4d34599a5f0c@8g2000hse.googlegroups.com> <4825F62C.9050407@v.loewis.de> Message-ID: On May 10, 2:23 pm, "Martin v. L?wis" wrote: > > I just can't figure out how to get the metadata, I guess. > > See > > http://wiki.python.org/moin/PyPiXmlRpc > > Regards, > Martin Ah-so. Most helpful, Martin. Thanks a lot! Mike From cjames at callone.net Mon May 5 08:31:35 2008 From: cjames at callone.net (c james) Date: Mon, 05 May 2008 07:31:35 -0500 Subject: Problems with psycopg2 In-Reply-To: <5dc598e30805031537x20729eaarc611d1a12bfbdc91@mail.gmail.com> References: <5dc598e30805011731g1022de5bq750f890a284e5880@mail.gmail.com> <5dc598e30805031537x20729eaarc611d1a12bfbdc91@mail.gmail.com> Message-ID: David Anderson wrote: > The thing is this query works fine on the console through psql, but not > in my code? can anyone explain me why? > > On Thu, May 1, 2008 at 9:31 PM, David Anderson > wrote: > > Hi all > I have this function: > def checkName(self, name): > cur = self.conn.cursor() > > sql = "SELECT * from patient WHERE fn_pat = '" + name + "'" > cur.execute(sql) > rows = cur.fetchall() > > if rows == "[]": > self.insert() > > It seems to work fine, But I'm getting this exception: > psycopg2.ProgrammingError: current transaction is aborted, commands > ignored until end of transaction block > at: cur.execute(sql) > > What's the problem? > thx > > ps: fn_pat is the column of the db, name is the string passed in the > function parameter > > > > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list Does `name` happen to have an apostrophe in it? You may want to look at using bind variables. cur.execute("SELECT * from patient WHERE fn_pat=%(name)s", {'name': name}) http://wiki.python.org/moin/DbApiCheatSheet http://mail.python.org/pipermail/python-list/2005-March/314154.html From http Fri May 2 03:28:40 2008 From: http (Paul Rubin) Date: 02 May 2008 00:28:40 -0700 Subject: is +=1 thread safe References: <4819DA2D.3030508@ggmail.com> Message-ID: <7xbq3pjhav.fsf@ruckus.brouhaha.com> AlFire writes: > But I still can not believe that +=1 is not a thread safe operation. In CPython I believe it is thread safe, because of the global interpreter lock. Thread switches can happen only between bytecode executions, not in the middle of a bytecode, even though executing a bytecode can take several machine instructions. From conrad at lewscanon.com.invalid Fri May 30 19:33:22 2008 From: conrad at lewscanon.com.invalid (Lew) Date: Fri, 30 May 2008 19:33:22 -0400 Subject: The Importance of Terminology's Quality In-Reply-To: <6abgirF358rgoU1@mid.individual.net> References: <6abgirF358rgoU1@mid.individual.net> Message-ID: Gordon Etly wrote: > Lew wrote: >> John Thingstad wrote: > >>> Perl is solidly based in the UNIX world on awk, sed, bash and C. >>> I don't like the style, but many do. > >> Please exclude the Java newsgroups from this discussion. > > Why? Do you speak for everyone in that, this, or other groups? I don't know why you'd even want to impose your Perl conversation on the Java group in the first place, troll. Plonk. -- Lew From dullrich at sprynet.com Fri May 16 11:58:46 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Fri, 16 May 2008 10:58:46 -0500 Subject: "indexed properties"... References: Message-ID: <7o7r245pb3kqk42odihmf95sifpbbv0rqp@4ax.com> On Thu, 15 May 2008 10:59:41 -0300, "Gabriel Genellina" wrote: >En Wed, 14 May 2008 18:15:41 -0300, David C. Ullrich escribi?: > >> Having a hard time phrasing this in the form >> of a question... >> >> The other day I saw a thread where someone asked >> about overrideable properties and nobody offered >> the advice that properties are Bad. So maybe we've >> got over that. I suppose properties could have >> Bad consequences if a user doesn't know they exist >> and think that a certain property of an object is >> just an ordinary attribute. But that applies to >> almost any aspect of any language. > >Which "bad consequences" are you thinking of? Didn't have anything specific in mind - there I was just playing devil's advocate. I've seen a lot of people here say things like "properties should only be used when refactoring" without any explanation that I could see of why properties were bad things. I was referring to whatever problems they had in mind. >Apart from the user not being aware of the complexity of certain operations, or a getter/setter very time-consuming (in that case I'd use public getXXX/setXXX functions instead, to emphasize that "something" is happening, not just an attribute lookup) > >> If a person comes from, say, Object Pascal (Delphi) >> then properties are hard to live without. The > >You should read the article "Python is not Java" if you haven't done it yet. >http://dirtsimple.org/2004/12/python-is-not-java.html I suspect you misunderstood my point there. I actually read that article years ago. Been using Python for years. I'd never confuse it with OP, I promise (luckily I don't know any Java and don't intend to). I really didn't express what I meant very well - what I should have said was more like "If you're accustomed to properties from a language like OP they seem like a very useful addition to Python". Looking at the article it seems like two points are relevant. (i) I'm well aware that chains of attribute accesses don't get compiled away in Python the way they do in OP. (ii) Regarding the bit about how getters and setters are evil, and it's also bad to wrap things in properties when simple attributes would do. Yes. Thanks for pointing that out, but I wouldn't do that - using a property where a simple attribute would do would be stupid. But they _can_ be much nicer than having to use explicit getters and setters, in cases where a simple attribute won't do. I got started on this thinking about making myself a nicer interface (nicer-seeming to me) to the wxPython grid object. Being able to say grid[row, col] = value seems much nicer and more natural than grid.SetCellValue(row, col, value) (yes, _that_ one is just __get(set)item__, no property needed), just as window.pos = (x,y) seems more natural than window.SetPos(x,y); in these cases the work involved in changing the cell value or the window position is going to make the extra overhead of the property interface irrelevant. >> other day I decided I wanted what OP calls an >> "indexed property" or "array property". Couldn't >> figure out how to make a _property_ behave that way. >> So I read a little bit about descriptors, and a >> few minutes later I had an indexedproperty thing >> that works just like property, except it gives >> an indexed property! This is just too cool. >> >> Why? For example, a Matrix should have a row[n] >> property allowing things like >> >> m.row[0] = m.row[1] + m.row[2] >> >> Ok, you could do _that_ by just making row >> an ordinary list of Row objects. But then >> you'd have to say >> >> m.row[0] = Row([1,2,3]) >> >> where I want to be able to say >> >> m.row[0] = [1,2,3] >> >> and have the Row created automatically. > >One could make *row* an object with a custom __getitem__/__setitem__ in this case. But then [see below] >But I prefer to have as little magic as possible on my objects: if it says m.row[0] = [1,2,3] I >expect m.row[0] to actually *be* that list (whenever possible), and not any other object initialized >from the [1,2,3] arguments. (Maybe this is some overreaction against C++ "magic" constructors and such horrible things...) Whatever - the idea here is that m.row[0] is going to walk and quack exactly like that list would, but also do other things that the liist can't do, like you can add two of them. (When you say anobject.aproperty = 2 you also expect aproperty to be 2? But if aproperty is a property that's not necessarily so - this seems like as much an argument against properties in general as against my version. Or perversion, if you like.) >> _Also_ with these indexed properties my Matrix >> can have m.row[j] and m.col[k] that look exactly >> the same to a client - we don't want to store a >> list of rows internally and also store the same >> data in a list of columns. Too cool. > >The same can be achieved having m.row and m.col be custom objects like I said above. > >> Hmm, none of that's a valid excuse for a post here. >> Um, right, here we go: Anyone see problems or >> possible improvements with the implementation >> of indexedproperty below? > >Note that the property object (or your indexedproperty) is a *class* attribute. That is, shared among all instances. > >> class indexedproperty(object): >> def __init__(self, getitem=None, setitem=None): >> self.getitem = getitem >> self.setitem = setitem >> >> def __get__(self, obj, owner): >> self.obj = obj >> return self > >Here is the problem. You can't store "obj" in "self" because it is shared among all instances. Your examples don't show any problem because all property accesses are immediately followed by a getitem access using the same object. Try this: > >x = AClass() >y = AClass() >x.cell[0,0] = 1 >print x.cell[1,1] # output: 0 >y.cell[x.cell[0,0], x.cell[0,0]] = 2 >print y.cell[1,1] # should be 2, still 0 >print x.cell[1,1] # should still be 0, but changed, now 2 Eewps. I did realize that the "indexedproperty" object was going to be shared, but I thought this sort of problem would be taken care of by the fact that self.obj was reset each time __get__ was called. I guess not. _A_ workaround would be to simply not have indexedproperties be class attributes, instead saying self.whatever = indexedproprty(whatever) in __init__. >A workaround would be to return another object in __get__ instead of self, which remembers the "obj" instance, or a closure, or... >But I don't really see the point, it's a lot easier to use another object for .cell (it's more clear, doesn't break encapsulation, divides responsabilities...) > >class Matrix2x2(object): > def __init__(self): > self.cells = [[0,0], [0,0]] > > def __setitem__(self, (row, col), value): > self.cells[row][col] = value > > def __getitem__(self, (row, col)): > return self.cells[row][col] > >class AClass(object): > def __init__(self): > self.cell = Matrix2x2() Well, something like this is where I was before coming up with the indexedproperty thing. Unless I'm missing something, which has happened before, what you write above can't work, because self.cell has to know what Matrix2x2 created it so it knows what AClass instance to modify when it's modified. (No, we can't just leave the state information in self.cells; think of the case of a Matrix with a row[] property and also a col[] property - they have to be modifying the data stored in the owning matrix.) So it would have to be more something like (untested, I don't have Python on this machine right now) class Matrix2x2(object): def __init__(self, owner): self.owner = owner def __setitem__(self, (row, col), value): self.owner.data[row][col] = value def __getitem__(self, (row, col)): return self.owner.data[row][col] class AClass(object): def __init__(self): self.cell = Matrix2x2(self) self.data = [[0, 0], [0, 0]] (again, it doesn't have to be like that in this case, but it does in the case where various "properties" like cells are giving different sorts of access to the same data, which data then has to be stored in AClass.) And then that's the point to the indexedproperty; the code passing data back and forth doesn't need to be rewritten with each property, it's all done inside the implementation of the indexedproperty class. I realized that I could just use object attributes instead, but it seems to me that indexedproperty encapsulates the data-passing protcol once and for all instead of requiring it to be redone each time. Thanks for the comments, especially for pointing out the bug. Before doing this I reproduced a Python implementation of "property". Gonna have to look that up instead of figuring it out to make sure I got it right, then look at it to see why property doesn't have the same problem... David C. Ullrich From gagsl-py2 at yahoo.com.ar Wed May 14 01:48:01 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 14 May 2008 02:48:01 -0300 Subject: help with file path exceeding 255 characters References: <411ca062-faa9-4635-8d69-90e69f465729@z72g2000hsb.googlegroups.com> Message-ID: En Tue, 13 May 2008 18:06:13 -0300, escribi?: > On May 13, 3:49?pm, Arnaud Delobelle wrote: >> ygua... at gmail.com writes: >> > I have trouble of obtaining the file size of a file because the >> > fullpath exceeds 255 characters. I get this message with > WindowsError: [Error 206] The filename or extension is too long: '\\\\? > \\UNC\\LOSSSFS002\\NWE_TECHNICAL\\05. UK\\Schiehallion (204_25a)\ > \Amos&Burke_P559\\07. Technical (Subsurface)\\06. Well Planning\\Amos\ > \Daily Reports\\Wireline\\final_204_25a_8z\\204_25a_8z\\Run_1A\ > \HRLA_SP_DSI_PEX_HNGS_ECRD\\ANCILLARY\\Amos_204_25a-8Z_GR_to_surface_3- > Mar-2008_DSI_HRLA_TLD_MCFL_047PUC.las' In addition to starting with \\?\UNC\, the path has to be an Unicode string, and already normalized (that is, it cannot contain . nor .. components) -- Gabriel Genellina From jeffober at gmail.com Thu May 22 08:06:32 2008 From: jeffober at gmail.com (Jeff) Date: Thu, 22 May 2008 05:06:32 -0700 (PDT) Subject: wsdl2py throwing error while creating client side code References: Message-ID: <7df9d525-4fd5-4175-b5c4-67cab5184bed@e39g2000hsf.googlegroups.com> Looks to me like you have the incorrect version of ZSI installed. From paddy3118 at googlemail.com Wed May 21 01:22:38 2008 From: paddy3118 at googlemail.com (Paddy) Date: Tue, 20 May 2008 22:22:38 -0700 (PDT) Subject: Using Python for programming algorithms References: <98fa5fa3-45ae-4df1-9fd3-1a227641244f@p25g2000hsf.googlegroups.com> <48314dd0$0$32138$426a34cc@news.free.fr> Message-ID: <3c04a0da-eb5c-4db6-8416-1b04ea9a4603@y38g2000hsy.googlegroups.com> On May 19, 8:09 pm, Lou Pecora wrote: > In article , > Roel Schroeven wrote: > > > > > Bruno Desthuilliers schreef: > > > 1/ being interpreted or compiled (for whatever definition of these > > > terms) is not a property of a language, but a property of an > > > implementation of a language. > > > > 2/ actually, all known Python implementations compile to byte-code. > > > You keep saying that, and in theory you're right. But I'm still inclined > > to disagree with it, since the practical reality is different. Python is > > indeed compiled to byte code, but if you compare that byte code with > > assembly code you'll see that there's a whole world of difference > > between the two, largely because of the dynamical nature of Python. Fact > > is that Python was designed from the start to run on a virtual machine, > > not on the native hardware. > > > C OTOH was designed to be compiled to assembly code (or directly to > > machine code) and as a result there are no (or virtually) no > > implementations that interpret C or compile it to bytecode. > > But how about this C/C++ interpreter. Dr. Dobbs article: http://www.ddj.com/cpp/184402054. Title and first two paragraphs: > > Ch: A C/C++ Interpreter for Script Computing > Interactive computing in C > > Ch is a complete C interpreter that supports all language features and > standard libraries of the ISO C90 Standard, but extends C with many > high-level features such as string type and computational arrays as > first-class objects. > If you still end up chasing pointers to implement your data structures then its still hampered. From ZeeGeek at gmail.com Sun May 4 13:56:52 2008 From: ZeeGeek at gmail.com (ZeeGeek) Date: Sun, 4 May 2008 10:56:52 -0700 (PDT) Subject: default gettext localedir on windows References: Message-ID: <6e4b1599-bdbd-4bb1-a104-1f2e8c66b33e@t12g2000prg.googlegroups.com> On May 5, 1:16?am, Thorsten Kampe wrote: > * ZeeGeek (Sun, 4 May 2008 08:59:05 -0700 (PDT)) > > > Hi, what's the default localedir for gettext module on windows? In > > Linux, it's /usr/share/locale. Where should I put the *.mo file in > > order to make the translation work? > > %PYTHONHOME%\share\locale I tried moving the *.mo file into %PYTHONHOME%\share\locale\zh_CN \LC_MESSAGES, but still no luck. The following is the code snippet I use: import gettext gettext.install('testprogram', unicode = True) From levlozhkin at gmail.com Sat May 3 22:43:39 2008 From: levlozhkin at gmail.com (lev) Date: Sat, 3 May 2008 19:43:39 -0700 (PDT) Subject: Script Optimization Message-ID: <6ed749de-1a7d-4db5-a229-d3400da4d24b@f24g2000prh.googlegroups.com> Can anyone provide some advice/suggestions to make a script more precise/efficient/concise, etc.? The script verifies checksums, renames dirs/files, edits checksum filenames, and htm page filenames, all from mp3cd format ([0-9][0-9] [0-9]xxx.yyy) to something more usable: for ripping an mp3cd to disk (everything works, but I think it's a bit bulky). It's too long to post here (160 lines) so here's the link: http://uppit.com/d2/CKOYHE/af78a6beeeed3e21a19d5871abb9b879/utils.py (if that doesn't work: http://uppit.com/CKOYHE) Thanks in advance, lev From mh at pixar.com Wed May 21 03:54:32 2008 From: mh at pixar.com (mh at pixar.com) Date: Wed, 21 May 2008 07:54:32 GMT Subject: getting dir(x), but not as list of strings? Message-ID: I want to iterate over members of a module, something like: for i in dir(x): if type(i) == types.FunctionType: ... but of course dir() returns a list of strings. If x is a module, how can I get the list of its members as their actual types? Many TIA! Mark -- Mark Harrison Pixar Animation Studios From casey.mcginty at gmail.com Thu May 15 04:36:42 2008 From: casey.mcginty at gmail.com (Casey McGinty) Date: Wed, 14 May 2008 22:36:42 -1000 Subject: Sanitised Newsgroup Feeds? In-Reply-To: References: Message-ID: On Wed, May 14, 2008 at 7:47 PM, Paddy wrote: > Hi, > Does anyone do a sanitised newsgroup feed? Something like what mail > filters do for email? > > Hi, I used to read the summary emails and had the same problem. I think the best method is to subscribe to the list using an e-mail program that can do spam filtering. Gmail gets rid of about 98% of the spam for me right now and I mark any spam that gets by. Also, I would put a filter on the python emails so they don't show up directly in your Inbox. Good luck. - Casey -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Wed May 14 11:09:34 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 14 May 2008 17:09:34 +0200 Subject: Rename field in Access DB References: Message-ID: <690dmjF2tkmhnU1@mid.uni-berlin.de> Iain King wrote: > I'm manipulating an MS Access db via ADODB with win32com.client. I > want to rename a field within a table, but I don't know how to. I > assume there is a line of SQL which will do it, but nothing I've tried > (from searching) has worked. > Basic code: > > import win32com.client > connection = win32com.client.Dispatch(r'ADODB.Connection') > DSN = 'PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=dbfile.mdb;' > connection.Open(DSN) > connection.Execute("ALTER TABLE tablename CHANGE from to") #this sql > doesn't work > connection.Close() > > Anyone know how to get this to work? I don't think Access supports SQL on the DDL-side. Try looking into the Access COM-Api, maybe you can get a reference to the table and modify it. Diez From asmodai at in-nomine.org Fri May 2 03:54:05 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Fri, 2 May 2008 09:54:05 +0200 Subject: #!/usr/bin/env python vs. #!/usr/bin/python In-Reply-To: <871w4l1cjj.fsf@benfinney.id.au> References: <87abj91j8u.fsf@benfinney.id.au> <871w4l1cjj.fsf@benfinney.id.au> Message-ID: <20080502075405.GS78165@nexus.in-nomine.org> -On [20080502 07:51], Ben Finney (bignose+hates-spam at benfinney.id.au) wrote: >To my mind, the Python interpreter installed by a package as >distributed with the OS *is* OS territory and belongs in /usr/bin/. That's the difference with a distribution, such as Linux, and full OSes , such as BSDs or commercial Unix variants. They prefer to keep a pristine state for the OS vendor files versus what the user can opt to install himself, hence the /usr/bin - /usr/local/bin separation. Same for sbin, lib, and so on. It effectively guarantees you can nuke /usr/local without ill consequences for your OS. Different philosophies, but after having spent more than 10+ years on too many Unix and Unix-like systems I know the importance of platform portability a bit too much and hardcoding a shebang sequence is not the solution in general. Using env is the, arguably, best solution available. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ | GPG: 2EAC625B Felix, qui potuit rerum cognoscere causas... From Lie.1296 at gmail.com Sun May 18 09:23:49 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 18 May 2008 06:23:49 -0700 (PDT) Subject: explain this function to me, lambda confusion References: Message-ID: <5cc7ef7a-dd21-4772-a7e3-765410f810bb@l17g2000pri.googlegroups.com> On May 9, 8:57?am, andrej.panj... at climatechange.qld.gov.au wrote: > On May 8, 6:11 pm, Duncan Booth wrote: > > > > > No, no, no, no, no! > > Geez. ?Go easy. > > > > > You have got it entirely wrong here. Your XOR function simply returns a > > function which gives you the result of xoring the parameters AT THE TIME > > WHEN YOU ORIGINALLY CREATED IT. I'm guessing that you had already set > > cream and icecream (otherwise the call to XOR would have thrown an > > exception) and at leas one was true. Try setting them both False at the > > beginning: > > > >>> cream = False > > >>> icecream = False > > >>> topping = XOR( cream, icecream) > > >>> cream = True > > >>> icecream = False > > >>> print topping() > > > False > > Ok. I understand this better now. ?I did say I found the documentation > rather terse on this. > > > Using a lambda was a completely pointless exercise here, you could have > > just returned the result directly: > > If I try out a new language, I try to exercise those parts of the > language that are new to me. ?Now I saw lambdas, an interesting > structure I hadn't seen before. So I tried them out. ?I get to learn a > little at the same time as scripting. ?That was the "point". ?I only > get to optimise my use of a language by trying out various corners of > it. > > > > > def TFF(x,y,z) : > > ? return x and not y and not z > > > AddOnly = TFF( options.AddAction, options.ReplaceAction, > > options.DeleteAction ) > > DeleteOnly = TFF( options.DeleteAction, options.AddAction, > > options.ReplaceAction ) > > ReplaceOnly = TFF( options.ReplaceAction, options.AddAction, > > options.DeleteAction ) > > > if not (DeleteOnly or AddOnly or ReplaceOnly): > > ? print "Error: ?Exactly one of ?[ --add | --replace | --delete ] > > allowed. " > > ? parser.print_help() > > ? exit > > > which boils down to: > > > if (options.AddAction + options.ReplaceAction + > > ? ? ? ? options.DeleteAction) != 1: > > ? ? print "Error: ..." > > Indeed, there are many ways this could be done. ?Some are more > concise, some are more efficient. ?As I said, I did it the way I did > it to try out lambdas. ?Your way achieves the result, rather elegantly > I think, but teaches me nothing about using lambdas. > > Pardon my tetchiness, but it is a little hard to receive such blunt > and inflexible replies to my posts. > > Both the responses offer lambda free alternatives. ?That's fine, and > given the terse documentation and problems that I had understanding > them, I would agree. ?So what applications are lambdas suited to? ?I > think the parameterised function model is one. > What else? Lambda can actually be safely removed from python and no other features would be missing. It is always possible to create a def version of any lambda, so lambda is useless. It is just a convenience for the times where we're just too lazy to invent a name and find a place to place the def, instead just inlining the function. From amat at kabsi.at Thu May 22 19:38:39 2008 From: amat at kabsi.at (Andreas Matthias) Date: Fri, 23 May 2008 01:38:39 +0200 Subject: Overloading __getitem__ References: Message-ID: inhahe at gmail.com wrote: > actually i ddin't think about the fact that you're overloading dict, which > can already take multiple values in getitem Oh, I didn't know that. I totally misinterpreted the error message. > so how about > > class crazy: pass > > and then in your dict class: > > def __getitem__(*args): Apparently, args already is a tuple, so this should be: def __getitem__(self, args): Is this documented somewhere? I couldn't find it anywhere. Thanks. Ciao Andreas From grante at visi.com Mon May 12 13:48:51 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 12 May 2008 12:48:51 -0500 Subject: Learning Python for no reason References: <0383f3b8$0$27282$c3e8da3@news.astraweb.com> <4828806c$0$11583$9b622d9e@news.freenet.de> Message-ID: <1emdnZDhZ6KeHrXVnZ2dnUVZ_j2dnZ2d@posted.visi> On 2008-05-12, Martin v. L?wis wrote: > OTOH: do you plan to do any programming at all, in your > life? If yes: consider using Python for every programming > task you'll encounter - unless there are outside constraints > demanding a different language. Python is flexible enough > for *all* you programming needs (I claim); Many, but not all. Python doesn't work well on microprocessors with a few thousand bytes of ROM and a few hundred bytes of RAM. Nor does it work well for writing device drivers for any popular OS. For windows/unix hosted user-space applications, Python is pretty hard to beat. -- Grant Edwards grante Yow! I feel like I'm at in a Toilet Bowl with a visi.com thumbtack in my forehead!! From gagsl-py2 at yahoo.com.ar Sat May 17 23:50:41 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 18 May 2008 00:50:41 -0300 Subject: write to specific line in file? References: <104ddf01-e860-4194-87bb-753a5e837ec0@s50g2000hsb.googlegroups.com> <29b9fb36-17bb-4449-aab9-e10361d0b0e4@b1g2000hsg.googlegroups.com> <2c673602-8b32-43cf-be47-2e981b971973@b64g2000hsa.googlegroups.com> Message-ID: En Sat, 17 May 2008 21:58:50 -0300, castironpi escribi?: > I am still interested in this one, but doubt if anyone still reading. I've not filtered you out *yet* - but that may happen very soon. -- Gabriel Genellina From krustymonkey at gmail.com Sun May 11 19:21:47 2008 From: krustymonkey at gmail.com (krustymonkey at gmail.com) Date: Sun, 11 May 2008 16:21:47 -0700 (PDT) Subject: pickle problem References: <68g456F2t41nqU1@mid.uni-berlin.de> <97b9fbd1-3725-4a7d-9ecb-1d2af6f35665@y21g2000hsf.googlegroups.com> <68h7p7F2su97jU3@mid.uni-berlin.de> <8763tofpiv.fsf@mulj.homelinux.net> <875ee438-b682-489e-b284-b22620384a75@m44g2000hsc.googlegroups.com> Message-ID: On May 8, 7:29 pm, castiro... at gmail.com wrote: > On May 8, 4:35 pm, Hrvoje Niksic wrote: > > > > > Marc 'BlackJack' Rintsch writes: > > > > On Thu, 08 May 2008 08:55:35 -0700, krustymonkey wrote: > > > >> The thing is, I'm not using slots by choice. I'm using the standard > > >> lib "socket" class, which apparently uses slots. > > > > `socket` objects can't be pickled. Not just because of the > > > `__slot__`\s but because a substantial part of their state lives in > > > the operating system's space. > > > Of course, if it makes sense to pickle sockets in the application, one > > is can do so by defining __getstate__ and __setstate__: > > > class Connection(object): > > def __init__(self, host, port): > > self.host = host > > self.port = port > > self.init_sock() > > > def init_sock(self): > > self.sock = socket.socket() > > self.sock.connect((host, port)) > > ... init communication ... > > > def __getstate__(self): > > # pickle self as a (host, port) pair > > return self.host, self.port > > > def __setstate__(self, state): > > # reinstate self by setting host and port and > > # recreating the socket > > self.host, self.port = state > > self.init_sock() > > I, local, am mystified that you'd want to pickle a socket. It's a > live connection, which flies on a pocket dollar. You don't want it on > disk, do you? > > If you're running a net buoy through a cluster somewhere, do you want > to drop a server and reconnect? Is Amazon's EC2 up and running? > > Certainly no one was talking on the internet. Were you? > > I don't think you hit anything but banks surfing the web, and the > American dollar is notoriously stuffy. Pump a wi-fi to a diner, > though, and you're just talking more. Where's Usenet? The idea is a pre-fork socket server. What I want to do is fork off some child processes from the parent and use IPC to send the connection object (via socket.accept()) over a pipe to one of the preexisting child processes and have said child handle the transaction. Think Apache, if you want an example of what I'm trying to do here. This alleviates the process startup cost that occurs when you fork. If the socket object can't be serialized, is there another way to go about handling this in python? From shahmed at sfwmd.gov Tue May 20 12:38:08 2008 From: shahmed at sfwmd.gov (Ahmed, Shakir) Date: Tue, 20 May 2008 12:38:08 -0400 Subject: Removing Space and "-" from a string In-Reply-To: <93123e81-2b7f-43c9-bc1c-74d80f83cae5@d1g2000hsg.googlegroups.com> References: <88a2268e-4e9c-48a6-9d23-30a34f751025@z16g2000prn.googlegroups.com> <93123e81-2b7f-43c9-bc1c-74d80f83cae5@d1g2000hsg.googlegroups.com> Message-ID: <14A2A120D369B6469BB154B2D2DC34D20B0F17BF@EXCHVS01.ad.sfwmd.gov> Thanks, works exactly what I needed. -----Original Message----- From: python-list-bounces+shahmed=sfwmd.gov at python.org [mailto:python-list-bounces+shahmed=sfwmd.gov at python.org] On Behalf Of s0suk3 at gmail.com Sent: Tuesday, May 20, 2008 12:22 PM To: python-list at python.org Subject: Re: Removing Space and "-" from a string On May 20, 11:02 am, "Ahmed, Shakir" wrote: > I have thousands of records in MS Access database table, which records I > am fetching using python script. One of the columns having string like > '8 58-2155-58' > > Desired output: '858215558' > > I want to remove any spaces between string and any dashes between > strings. I could do it in access manually but want to do from python > script > > Any help is highly appreciated. string.replace('-', '').replace(' ', '') -- http://mail.python.org/mailman/listinfo/python-list From george.sakkis at gmail.com Thu May 8 09:35:37 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Thu, 8 May 2008 06:35:37 -0700 (PDT) Subject: The del statement References: <02860f2a-cd1d-4b1d-ad49-08b13032ba21@2g2000hsn.googlegroups.com> Message-ID: <3039eed5-503c-4356-9f1b-ded48fcff855@f63g2000hsf.googlegroups.com> On May 8, 2:58?am, Arnaud Delobelle wrote: > George Sakkis wrote: > > One of the few Python constructs that feels less elegant than > > necessary to me is the del statement. For one thing, it is overloaded > > to mean three different things: > > (1) del x: Remove x from the current namespace > > (2) del x[i]: Equivalent to x.__delitem__(i) > > (3) del x.a: Equivalent to x.__delattr__('a') (or delattr(x,'a')) > > Note that the 'X = Y' construct has the corresponding three meanings: > > (1) x = 4 # Bind x to 4 in the 'current namespace' > (2) x[i] = 4 # equivalent to x.__setitem__(i, 4) > (3) x.a = 4 # Equivalent to x.__setattr__('a', 4) > > What conclusion should we draw from that? I think you're trying to imply that it is consistent with setting a value (same with getting). I guess what bugs me about "del" is that it's a keyword and not some universally well-known punctuation. Do you you feel that Python misses a "pop" keyword and respective expressions ? (1) pop x: Remove x from the current namespace and return it. (2) pop x[i]: Instead of x.pop(i) (3) pop x.a: Equivalent to "_y=x.a; del x.a; return y" George From hdante at gmail.com Fri May 16 10:25:15 2008 From: hdante at gmail.com (Henrique Dante de Almeida) Date: Fri, 16 May 2008 07:25:15 -0700 (PDT) Subject: TPCServer and xdrlib References: <5d56b071-1184-4112-bd82-89c00975b939@m73g2000hsh.googlegroups.com> <695crbF303jk4U1@mid.uni-berlin.de> Message-ID: <41da63d3-7b9c-4fd4-8fcc-7a115e6427a8@25g2000hsx.googlegroups.com> On May 16, 9:26?am, "Diez B. Roggisch" wrote: > > ?Did you consider gzipping your XML (or YAML) packets ? Would the > > transfer time be acceptable in this case ? > > That would add even more to the overhead of transcoding the > transportlayer. Switching from XMLRPC to a json-based protocol reduced Yes, that's why I suggested YAML. > in a project of mine reduced the overhead 10-20fold - mainly because of > reduced size and parsing efforts. I don't think so. It probably just the reduced size (check if the json file is around 10 times smaller). I believe the server will be mostly I/O-bound, ie, most overhead will be in the data link/physical layers. The compression/parsing time (a few microseconds) should be a small fraction of the total transfer time (a few milliseconds). Even if the service is not I/O bound, (considering the Youtube example) if there's significant traffic in the server, the database access time should be the most significant. I have used compression for SOAP messages in a GPRS (~20kbps) link and got similar performance improvements (the web server was set to automatically compress the data). > > Diez From jon+usenet at unequivocal.co.uk Thu May 1 12:11:29 2008 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: Thu, 01 May 2008 11:11:29 -0500 Subject: Best way to store config or preferences in a multi-platform way. References: Message-ID: On 2008-05-01, Ivan Illarionov wrote: > IMO .ini-like config files are from the stone age. The modern approach is > to use YAML (http://www.yaml.org). You mean YAML isn't a joke!? It's so ludicrously overcomplicated, and so comprehensively and completely fails to achieve its stated main goal of being "readable by humans", that I had assumed it was an April Fool along the lines of Intercal or brainf***. I certainly wouldn't recommend it as being suitable for, well, anything at all. Or were you trolling and I missed the joke? ;-) From pavlovevidence at gmail.com Fri May 30 05:15:47 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 30 May 2008 02:15:47 -0700 (PDT) Subject: should I put old or new style classes in my book? References: Message-ID: <734f0e6a-ce91-45f8-a0f2-e3cd4faacf6c@c65g2000hsa.googlegroups.com> On May 29, 12:07 pm, allendow... at gmail.com wrote: > The current edition of the book presents old style classes. I am > considering > switching to new style classes on the assumption that this should be > the default > choice for new programs. The drawback is that a lot of the online > documentation > still uses old style classes. New style, all the way. The drawback you speak of for new-style classes I think is today more of a drawback for old-style. The problem is, when a newbie goes looking for examples, there is a lot of code out there that uses things like properties, type(instance), @staticmethods, and so on. Those won't work, and will confuse the hell out of newbies, if you teach them old-style. OTOH, the examples out there that are written for old-style usually still work for new-style classes. The only significant issue, as far as I'm concerned, is the list of bases. Which is why, even if you only cover new-style classes, it's important to at least mention that there used to exist old-style that don't list any bases (in Python 2.x). And then tell the user, "We're not covering it, it's not something you need to worry about, and most of the time you can and should add (object) and the code will still work." And leave it at that--let the interested newbie seek out more information on their own. Carl Banks From jacob at cd.chalmers.se Sat May 24 12:32:35 2008 From: jacob at cd.chalmers.se (Jacob Hallen) Date: Sat, 24 May 2008 16:32:35 +0000 (UTC) Subject: Code correctness, and testing strategies References: Message-ID: In article , David wrote: >> I work in small increments, writing one test at a time, then some code, >> then another test, then some more code, etc. In fact, I take this to what >> many people might call an extreme. > >Thanks for the replies. > >I've read about the TDD (and similar) approaches. Maybe I need to try >it and get used to it, but there are a few things I don't like about >it on a gut level. I'll try to enumerate my concerns here. > >Problem 1: You can only code against tests > >Basically, with TDD you write the tests first, then the code which >passes/fails the tests as appropriate. However, as you're writing the >code you will also think of a lot of corner cases you should also >handle. The natural way to do this is to add them to the code first. >But with TDD you have to first write a test for the corner case, even >if setting up test code for it is very complicated. So, you have these >options: > >- Take as much time as needed to put a complicated test case in place. >- Don't add corner case to your code because you can't (don't have >time to) write a test for it. >- Add the corner case handling to the code first, and try to add a >test later if you have time for it. As you come up with the corner case, write a test for it and leave the implementation for later. The hard part of coding is always defining your problem. Once it is defined (by a test) the solution is just a matter of tidy work. >Problem 2: Slows down prototyping > >In order to get a new system working, it's nice to be able to throw >together a set of modules quickly, and if that doesn't work, scrap it >and try something else. There's a rule (forget where) that your first >system will always be a prototype, regardless of intent. > >With TDD, you have to first write the tests for the first version. >Then when that first version doesn't work out, you end up scrapping >the tests and the code. The time spent writing the tests was wasted. > Agreed. There is no good way of reusing your prototype code in TDD. You end up having to throw your propotype away in order to have a proper tested implementation in the end. Takes more time up front, but less time over the lifecycle of the program you are building. >Problem 3: Slows down development in general > >Having to write tests for all code takes time. Instead of eg: 10 hours >coding and say 1/2 an hour manual testing, you spend eg: 2-3 hours >writing all the tests, and 10 on the code. This is incorrect. It speeds up development in general. The debugging phase of development becomes much shorter because the bugs are fewer and the ones you have a much shallower. There are so many tests that reduce the scope in which you have to search for the bug that it usually becomes trivial to find. I have direct experience from this, getting my company to change to TDD about 10 months ago. Productivity has improved enormously. I'd say that we have cut between 25 and 50% in development time. >Problem 4: Can make refactoring difficult. > >If you have very complete & detailed tests for your project, but one >day you need to change the logic fundamentally (maybe change it from >single-threaded to multi-threaded, or from running on 1 server to >distributed), then you need to do a large amount of test refactoring >also. The more tests you have (usually a good thing), the longer it >will take to update all the tests, write new ones, etc. It's worse if >you have to do all this first before you can start updating the code. No, this is a total misunderstanding. It makes refactoring much easier. It takes a bit of time to refactor the affected tests for the module, but you gain so much by having tests that show that your refactoring is not breaking code that should be unaffected that it saves the extra time spent many times over. Introducing bugs because you missed some aspect in a refactoring is one of the most common problems in non-TDD code and it is a really nasty quality concern. > >Problem 5: Tests are more important than code > >You need to justify the extra time spent on writing test code. Tests >are nice, and good to have for code maintainability, but they aren't >an essential feature (unless you're writing critical software for life >support, etc). Clients, deadlines, etc require actual software, not >tests for software (that couldn't be completed on time because you >spent too much time writing tests first ;-)). > The tests are as important as the code. As a customer, I don't think I'd buy software today unless I know that it has been built using TDD. Certainly I am ahead of the curve in this, but it won't be long before this will be required by skilled organisations buying software and sooner or later the rest of the world will follow. Getting into a TDD mindset is hard work, but those who succeed produce better software with less effort. Jacob Hall??n -- From mrkafk at gmail.com Sat May 3 16:50:10 2008 From: mrkafk at gmail.com (mrkafk at gmail.com) Date: Sat, 3 May 2008 13:50:10 -0700 (PDT) Subject: Daily WTF with XML, or error handling in SAX Message-ID: So I set out to learn handling three-letter-acronym files in Python, and SAX worked nicely until I encountered badly formed XMLs, like with bad characters in it (well Unicode supposed to handle it all but apparently doesn't), using http://dchublist.com/hublist.xml.bz2 as example data, with goal to extract Users and Address properties where number of Users is greater than given number. So I extended my First XML Example with an error handler: # ========= snip =========== from xml.sax import make_parser from xml.sax.handler import ContentHandler from xml.sax.handler import ErrorHandler class HubHandler(ContentHandler): def __init__(self, hublist): self.Address = '' self.Users = '' hl = hublist def startElement(self, name, attrs): self.Address = attrs.get('Address',"") self.Users = attrs.get('Users', "") def endElement(self, name): if name == "Hub" and int(self.Users) > 2000: #print self.Address, self.Users hl.append({self.Address: int(self.Users)}) class HubErrorHandler(ErrorHandler): def __init__(self): pass def error(self, exception): import sys print "Error, exception: %s\n" % exception def fatalError(self, exception): print "Fatal Error, exception: %s\n" % exception hl = [] parser = make_parser() hHandler = HubHandler(hl) errHandler = HubErrorHandler() parser.setContentHandler(hHandler) parser.setErrorHandler(errHandler) fh = file('hublist.xml') parser.parse(fh) def compare(x,y): if x.values()[0] > y.values()[0]: return 1 elif x.values()[0] < y.values()[0]: return -1 return 0 hl.sort(cmp=compare, reverse=True) for h in hl: print h.keys()[0], " ", h.values()[0] # ========= snip =========== And then BAM, Pythonwin has hit me: >>> execfile('ph.py') Fatal Error, exception: hublist.xml:2247:11: not well-formed (invalid token) Fatal Error, exception: hublist.xml:2247:11: not well-formed (invalid token) Fatal Error, exception: hublist.xml:2247:11: not well-formed (invalid token) Fatal Error, exception: hublist.xml:2247:11: not well-formed (invalid token) Fatal Error, exception: hublist.xml:2247:11: not well-formed (invalid token) >>> ================================ RESTART ================================ Just before the "RESTART" line, Windows has announced it killed pythonw.exe process (I suppose it was a child process). WTF is happening here? Wasn't fatalError method in the HubErrorHandler supposed to handle the invalid tokens? And why is the message repeated many times? My method is called apparently, but something in SAX goes awry and the interpreter crashes. From neerashish at gmail.com Thu May 8 13:58:45 2008 From: neerashish at gmail.com (neerashish) Date: Thu, 8 May 2008 10:58:45 -0700 (PDT) Subject: Python Syntax and misspelled variable and method name checker? Message-ID: <17130132.post@talk.nabble.com> Is there a good Python Syntax and mis-spelled variable and method name checker available. I have been programming in python for last 6 months and misspelled variables and method names have been bane of my python life. In complied languages, compiler checks for these mistakes. I come from Java , C++ background. I use komodo as editor on mac. I use python 2.4 Please suggest some good tool and utilities. thanks Ashish -- View this message in context: http://www.nabble.com/Python-Syntax-and-misspelled-variable-and-method-name-checker--tp17130132p17130132.html Sent from the Python - python-list mailing list archive at Nabble.com. From deets at nospam.web.de Mon May 5 07:47:18 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 05 May 2008 13:47:18 +0200 Subject: pygame music, cant read mp3? References: <30fe7c79-dbac-47bb-9e29-bea61b7c3da8@56g2000hsm.googlegroups.com> Message-ID: <688af0F2pc3jjU1@mid.uni-berlin.de> globalrev wrote: > http://www.pygame.org/docs/ref/mixer.html > > import pygame > > #pygame.mixer.init(frequency=22050, size=-16, channels=2, > buffer=3072) //it complained abiout words= > so i guess its only the nbrs should be there// > > pygame.mixer.init(22050, -16, 2, 3072) > pygame.mixer.music.load("example1.mp3") > pygame.mixer.music.play(loops=1, start=0.0) > > > > Traceback (most recent call last): > File "C:\Python25\myPrograms\pygameProgs\musicexp.py", line 5, in > > pygame.mixer.music.load("example1.mp3") > error: Couldn't read from 'example1.mp3' Give it the full path to the MP3. Be aware of backward slashes + the need to escape them. Diez From gagsl-py2 at yahoo.com.ar Sat May 10 23:46:18 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 11 May 2008 00:46:18 -0300 Subject: Free Memory References: <8a6035a00805081730g2a18b97cxc32ae6568fb10b81@mail.gmail.com> Message-ID: En Fri, 09 May 2008 12:44:21 -0300, Patrick Mullen escribi?: > I had some very interesting results with this code to do what is asked: > > for key in globals().keys(): > del globals()[key] > for key in locals().keys(): > del locals()[key] Removing items from locals() has no effect, at least on CPython. Local variables doesn't "live" on that dictionary, locals() is built on demand when required. At module level, locals and globals are the same thing. py> def foo(): ... x = 1 ... y = "hello" ... print locals() ... for key in locals().keys(): ... print "deleting", key ... del locals()[key] ... print locals() ... print x, y ... py> foo() {'y': 'hello', 'x': 1} deleting y deleting x {'y': 'hello', 'x': 1, 'key': 'x'} 1 hello BTW, if you want to clear a dictionary, just use its clear() method. So a more compact form of your code would be: globals.clear(). Anyway I don't see why do you want to keep an empty module around - just remove it from sys.modules, and if nobody else holds a reference to it, it will be destroyed. > It might be better to reverse the two steps, I didn't give it much thought. > Anyway, when this is done, all of the builtins spill into globals and locals > (since __builtin__ was deleted). I thought that was interesting. Sorry I don't understand you... > It did have the effect that is asked for, although there may be more > unintended consequences. Also if any objects are attached to any of the > builtins I expect they will still be around. Your code removes all direct references to objects from the current module, it does not free memory "per se". There may be other references elsewhere. Objects are deleted (and memory freed) only when their reference count reaches zero. -- Gabriel Genellina From slesarev.anton at gmail.com Tue May 6 15:42:26 2008 From: slesarev.anton at gmail.com (Anton Slesarev) Date: Tue, 6 May 2008 12:42:26 -0700 (PDT) Subject: python vs. grep Message-ID: <011f43ea-9bc8-499a-a3fe-dba24b47932e@c58g2000hsc.googlegroups.com> I've read great paper about generators: http://www.dabeaz.com/generators/index.html Author say that it's easy to write analog of common linux tools such as awk,grep etc. He say that performance could be even better. But I have some problem with writing performance grep analog. It's my script: import re pat = re.compile("sometext") f = open("bigfile",'r') flines = (line for line in f if pat.search(line)) c=0 for x in flines: c+=1 print c and bash: grep "sometext" bigfile | wc -l Python code 3-4 times slower on windows. And as I remember on linux the same situation... Buffering in open even increase time. Is it possible to increase file reading performance? From torriem at gmail.com Mon May 12 08:54:35 2008 From: torriem at gmail.com (Michael Torrie) Date: Mon, 12 May 2008 06:54:35 -0600 Subject: Module python-magic on/for Windows? In-Reply-To: References: <3a66adfe-3fd6-4f23-a6e8-4b219db1a3cd@x41g2000hsb.googlegroups.com> Message-ID: <48283E0B.4060001@gmail.com> Larry Hale wrote: > Alternately, if one wishes to leave/place the magic files elsewhere, > do like: > > >>> test = magic.Magic( magic_file = 'C:\\Program Files\\GnuWin32\ > \share\\file\\magic' ) # <-- spec where/what the file is > > NOTE: Even if the "magic_file" location *is* specified, "mime = True" > still works fine. (Haven't checked, but I presume the source simply > tacks ".mime" to the filename automagically.) Obviously/also, one > needn't specify the argument names if one uses proper argument order: > magic.Magic( mime, magic_file ) :) > > > THANKS SO MUCH, Michael, for your answers and helping me alone the > way... :) Glad it's working for you. From terry.yinzhe at gmail.com Sat May 10 19:39:56 2008 From: terry.yinzhe at gmail.com (Terry) Date: Sat, 10 May 2008 16:39:56 -0700 (PDT) Subject: Initializing a subclass with a super object? References: <17fce6b5-6506-4e78-8ba1-d8d1bb33c8a4@34g2000hsh.googlegroups.com> Message-ID: <7242ff91-dac4-4380-ba80-c18fa9494181@v26g2000prm.googlegroups.com> On May 11, 7:22 am, frankdmarti... at gmail.com wrote: > Class A inherits from class B. Can anyone point me in the direction > of documentation saying how to initialize an object of A, a1, with an > object of B, b1? This is called a 'factory'in design patterns. Search 'python factory', you will get a lot of examples. br, Terry From zerty.david at gmail.com Sun May 11 20:15:25 2008 From: zerty.david at gmail.com (David Anderson) Date: Sun, 11 May 2008 21:15:25 -0300 Subject: how to separate words from a string? Message-ID: <5dc598e30805111715k43114274jbc4b7c0bf4158494@mail.gmail.com> Hi, how can I separate words from a sentence in a string? Like the java.String.split method I need something that gets an string "This is a sentence", and return to em a list["This","is","a","sentence"] Can anyone help? Thx -------------- next part -------------- An HTML attachment was scrubbed... URL: From pierre.gronlier at gmail.com Fri May 23 04:04:28 2008 From: pierre.gronlier at gmail.com (ticapix) Date: Fri, 23 May 2008 01:04:28 -0700 (PDT) Subject: webcam (usb) access under Ubuntu References: <66jlk1F2ju6c8U1@mid.uni-berlin.de> <66kkedF2l526dU2@mid.uni-berlin.de> <455760fb-8229-4be3-ba7f-7c41bdcd66de@a22g2000hsc.googlegroups.com> <362eb242-2adc-4d7b-9c0a-95e72f4b22b6@e67g2000hsa.googlegroups.com> Message-ID: <6a228393-1b14-4c4e-9a39-b15a77270994@a1g2000hsb.googlegroups.com> On 16 avr, 09:41, Berco Beute wrote: > On Apr 15, 11:45 pm, Berco Beute wrote: > > > I've tried reinstalling gstreamer (for windows): > > >http://gstreamer.freedesktop.org/pkg/windows/releases/gstreamer/gstre...... > > > but that didn't help. I get some complaints about 'libgstinterfaces' > > as well... > > To be more precise, when doing an 'import gst' Python shell pops up an > error dialog saying: > > "This application has failed to start because > libgstinterfaces-0.10.dll was not found." > > 2B You need to install gst-plugins-good too -- pierre From Scott.Daniels at Acm.Org Wed May 21 23:07:25 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 21 May 2008 20:07:25 -0700 Subject: about python modules In-Reply-To: <2fc55c56-7408-4f44-b6e2-64f85f341ac9@i36g2000prf.googlegroups.com> References: <2fc55c56-7408-4f44-b6e2-64f85f341ac9@i36g2000prf.googlegroups.com> Message-ID: srinivas wrote: > ... i want to know how to import my functions folder to python in > sucha way that the functions in functions folder should work like > python library modules . > > i have python in folder C:\python25\.. > and functions folder D:\programs\Functions\ > > pls help me friends how to do that. An unmentioned possibility: Create a file named "whatever.pth" (where the "whatever" is your choice). The contents of this file should be a line containing the path to your directory (in your case a single line containing "D:\programs\Functions" (w/o the quotes). Put this file in your site-packages file (for windows in your case, that is C:\Python25\Lib\site-packages --Scott David Daniels Scott.Daniels at Acm.Org From benkasminbullock at gmail.com Mon May 19 23:00:03 2008 From: benkasminbullock at gmail.com (Ben Bullock) Date: Tue, 20 May 2008 03:00:03 +0000 (UTC) Subject: pop langs website ranking References: <41fbaf27-a80b-402b-b406-c048a65a8643@b64g2000hsa.googlegroups.com> Message-ID: In comp.lang.perl.misc xahlee at gmail.com wrote: > In February, i spent few hours researching the popularity of some > computer language websites. One way to do such research is for you to publish the actual number of hits on your website. It's also easy to analyze logfile data with free tools like analog or awstats, and publish the number of unique visitors, pages hit, bandwidth, etc. It would also be possible for you to work out how accurate the Alexa numbers actually are compared to the numbers you see in your logs. From john106henry at hotmail.com Tue May 13 18:22:44 2008 From: john106henry at hotmail.com (John Henry) Date: Tue, 13 May 2008 15:22:44 -0700 (PDT) Subject: Why can't I import this? References: Message-ID: <7ddb9a42-9d5c-4266-aa0c-95466af10b6b@w34g2000prm.googlegroups.com> On May 13, 1:49 pm, Gary Herron wrote: > John Henry wrote: > > Hi list, > > > I can't understand this. The following import statement works fine: > > > from PythonCard.templates.dialogs import runOptionsDialog > > > but this one fails: > > > from PythonCard.tools.codeEditor.codeEditor import CodeEditor > > This kind of "dotted" name import only works for packages, and a > directory is considered a package only if it contains a file name > __init__.py. Looking around my installation of PythonCard (on Linux) > I see that most of those directories *do NOT* have a __init__.py, so > they are not packages and cannot be imported that way. > > Of course this leaves unanswered the question of *how* you are supposed > to import that code. I've never used PythonCard so I can't help > further, but I suggest looking at the documentation and examples > supplied. And perhaps waiting for someone with experience with > PythonCard to answer. > > Gary Herron > > P.S. It is usually a waste of time to tell us that something fails > without telling us *how* it fails. (Cut and paste the error message > always, and the traceback usually.) If you don't, you will usually get > a request to supply that information, and then have wast3ed the time for > one full round of message to the group. Even in this case, I'm only > guessing how it failed for you. > > > I've checked and rechecked to make sure that the spellings are proper > > and that the tools, the codeEditor directory, and codeEditor.py, and > > the class CodeEditor all exists and yet idle keep complaining that it > > can't import from PythonCard.tools. > > > What's going on? (Running Python2.5 under WinXP). > > > Regards, > > -- > >http://mail.python.org/mailman/listinfo/python-list Thank you very much. I didn't know about the __init__.py requirement. Appreciate it. From matthieu.brucher at gmail.com Tue May 13 14:05:14 2008 From: matthieu.brucher at gmail.com (Matthieu Brucher) Date: Tue, 13 May 2008 20:05:14 +0200 Subject: Python and Flaming Thunder In-Reply-To: <8bd40bb6-5f8d-4256-a41a-fe341d10d476@q1g2000prf.googlegroups.com> References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <5b0e3f70-afde-4480-8713-e7113b1250d7@x35g2000hsb.googlegroups.com> <1f537717-00d0-48ee-99b6-7125b96a6133@t12g2000prg.googlegroups.com> <68t4o0F2vaoncU1@mid.uni-berlin.de> <2a32179a-9439-449c-bd07-fff6a4075aee@s50g2000hsb.googlegroups.com> <7ee5dffd-df8f-46f0-bd78-c81ac0418a9a@d77g2000hsb.googlegroups.com> <65ef773e-a1c3-4adb-a18b-e8b8451efe5e@b5g2000pri.googlegroups.com> <02a10e4b-5017-463c-96d2-e1779f2b9ebd@j22g2000hsf.googlegroups.com> <8bd40bb6-5f8d-4256-a41a-fe341d10d476@q1g2000prf.googlegroups.com> Message-ID: So does every other compiler like gcc or interpreters like Python. What is your point ? Matthieu 2008/5/13 Dave Parker : > > Notice that I said "free software", not "*** FREE *** software !!!! > > 1!" (that is, free as in freedom, not free as in beer). Read again my > > answer, considering this. > > I misread your meaning. In a sense, Flaming Thunder is even more free > than "free software". Flaming Thunder doesn't place any restrictions > on how you use your source code or the executables you create. There > is no GNU license that you need to worry about. > > On May 13, 11:06 am, hdante wrote: > > On May 13, 12:24 pm, Dave Parker > > wrote: > > > > > > > > > > > > > > The "Flaming Thunder" looks promising, but without being free > > > > software, it's unlikely it will create a large developer community, > > > > specially considering both free general purpose and scientific > > > > programming languages. > > > > > Perhaps. Flaming Thunder is only $19.95 per year for an individual > > > (and even less per individual for site licenses), which is less than > > > the cost of just one book on Python. > > > > > I think that many people will find that Flaming Thunder is easier to > > > use and understand than Python -- so for many people the amount of > > > time they save will be worth more than the cost of Flaming Thunder > > > (unless, of course, their time is worth $0). > > > > > Also, several users have rewritten their Python programs in Flaming > > > Thunder, and found that Flaming Thunder was 5 to 10 times faster > > > (Flaming Thunder compiles to native executables). So again, since > > > many people value their time at more than $0, I think that many people > > > will find that Flaming Thunder is worth $19.95 per year. > > > > > Plus, me getting paid to work on Flaming Thunder is far more > > > motivating than me not getting paid to work on Python. This weekend, > > > Python users will still be debating how to fix awkwardnesses in the > > > languages (such as FOR loops where you're just counting the loops and > > > not referencing the loop variable) -- but Flaming Thunder users will > > > be getting work done using the REPEAT n TIMES constructs that I'll be > > > implementing. > > > > > Python has been around about 15 years, yet still has those > > > awkwardnesses. Flaming Thunder has been out less than 6 months and > > > those awkwardnesses are already getting fixed. The difference: I > > > can't afford to ignore users. > > > > > But the future is one of the hardest things to predict, so we'll see. > > > > > On May 13, 8:34 am, hdante wrote: > > > > > > On May 13, 10:58 am, Paul McGuire wrote: > > > > > > > On May 13, 8:32 am, Dave Parker > wrote: > > > > > > > > > Don't let yourself be irritated by castironpi > > > > > > > > I'm not the sort to get irritated by anyone. There is value in > all > > > > > > interaction. > > > > > > > Not this interaction, I'm afraid. What irritates *me* about > > > > > castironpi is that he uses a chatterbot to clutter up the threads > > > > > here. If you go back to his postings from a year ago (and selected > > > > > ones since), his comments are coherent and sensible. These > rambling > > > > > stream-of-consciousness rants about t.v.'s and coffee are (I guess) > > > > > his idea of a joke. But they are certainly not worth your time in > > > > > trying to respond to them. > > > > > > > -- Paul > > > > > > I don't think castironpi so annoying that I should filter its > > > > messages. It would be enough if he were better tuned. He is much > > > > smarter than the emacs shrink, for example. :-P > > > > > > The "Flaming Thunder" looks promising, but without being free > > > > software, it's unlikely it will create a large developer community, > > > > specially considering both free general purpose and scientific > > > > programming languages.- Hide quoted text - > > > > > > - Show quoted text - > > > > Notice that I said "free software", not "*** FREE *** software !!!! > > 1!" (that is, free as in freedom, not free as in beer). Read again my > > answer, considering this.- Hide quoted text - > > > > - Show quoted text - > > -- > http://mail.python.org/mailman/listinfo/python-list > -- French PhD student Website : http://matthieu-brucher.developpez.com/ Blogs : http://matt.eifelle.com and http://blog.developpez.com/?blog=92 LinkedIn : http://www.linkedin.com/in/matthieubrucher -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Fri May 9 21:55:44 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 9 May 2008 18:55:44 -0700 (PDT) Subject: RELEASED Python 2.6a3 and 3.0a5 References: <26dacfd7-e698-46c6-affb-7b4d6b18c3f5@59g2000hsb.googlegroups.com> Message-ID: On May 9, 7:55?pm, St?phane Larouche wrote: > > On 9 Mai, 01:50, Barry Warsaw wrote: > > > On behalf of the Python development team and the Python community, I > > > am happy to announce the third alpha release of Python 2.6, and the > > > fifth alpha release of Python 3.0. > > After I installer Python 2.6a3, Matlab R2007a began having problems. When I > start Matlab, it shows a window indicating that it is installing Microsoft > Visual C++ 2005 Redistributable, which fails, and then Matlab closes. This > problem did not happen with Python 2.6a2 and removing Python 2.6a3 solves the > problem. > > Is anybody else having the same problem? Do you know what causes it? Is there a > workaround? That one might be a true, "Don't stampede the Python." Numbers have been known grow. (...not that the numbers do.) Bread and butter, new butter. From http Sun May 11 22:37:06 2008 From: http (Paul Rubin) Date: 11 May 2008 19:37:06 -0700 Subject: anonymous assignment References: <1XNVj.133805$Cj7.33096@pd7urf2no> Message-ID: <7xmymwuu25.fsf@ruckus.brouhaha.com> Yves Dorfsman writes: > import time > y, None, d, None, None, None, None = time.localtime() > > I know you can't assign anything to None, but I'm sure you get what I > mean, a special keyword that means I don't care about this value. You can just use a variable name than you ignore. It's traditional to use _ but it's not a special keyword, it's just a another variable name: y, _, d, _, _, _, _, _, _ = time.localtime() From lists at cheimes.de Fri May 9 05:36:01 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 09 May 2008 11:36:01 +0200 Subject: RELEASED Python 2.6a3 and 3.0a5 In-Reply-To: <26dacfd7-e698-46c6-affb-7b4d6b18c3f5@59g2000hsb.googlegroups.com> References: <26dacfd7-e698-46c6-affb-7b4d6b18c3f5@59g2000hsb.googlegroups.com> Message-ID: <48241B01.8050009@cheimes.de> Kay Schluehr schrieb: > http://www.python.org/ftp/python/3.0/python-3.0a5.msi > Error 404: File Not Found > http://www.python.org/ftp/python/3.0/python-3.0a5.amd64.msi > Error 404: File Not Found The Windows binaries usually take a while. I'm adding Martin to the CC list. His is most like building the files today. Christian From deets at nospam.web.de Thu May 29 06:03:00 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 29 May 2008 12:03:00 +0200 Subject: php vs python References: <-t-dnWQ4bZN2MaTVnZ2dnUVZ_qGdnZ2d@comcast.com> <613388153.20080528051020@freemail.ru> <298ffbe3-5094-432a-a769-3170fa0cd072@x35g2000hsb.googlegroups.com> Message-ID: <6a7dblF35fm1rU1@mid.uni-berlin.de> > A good OO programmer could easily write good functional code. You are aware that functional programming is *not* procedural or imperative programming? http://en.wikipedia.org/wiki/Functional_programming OO is *heavily* depending on state and state modification. I've seen OO programmers weep over functional programming assignments. Which is not to say that FP is in any sense bad - au contraire, knowing it is important because it is a different school of thought that's very valuable to know of. And Python allows for many of the FP concepts to be used. See map, filter and other HOFs. Diez From gagsl-py2 at yahoo.com.ar Sat May 24 23:52:50 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 25 May 2008 00:52:50 -0300 Subject: Google Treasure solution in python - first time python user, help whats wrong References: <44de619e-14f3-49d2-b336-a14e5dca12cd@e39g2000hsf.googlegroups.com> Message-ID: En Fri, 23 May 2008 05:40:26 -0300, x40 escribi?: > I try to learn python thru solving some interisting problem, found > google trasure hunt, > write first program ( but cant find whats wrong). And what happens? You don't get the expected result? The program aborts with an exception? Or what? -- Gabriel Genellina From ivan.illarionov at gmail.com Sun May 18 06:09:57 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Sun, 18 May 2008 10:09:57 +0000 (UTC) Subject: morning in Python References: <409ea9f1-9774-4bf2-abac-2daf997bc97f@c65g2000hsa.googlegroups.com> <143b1593-658c-4a1c-9826-72af517b3ad0@m36g2000hse.googlegroups.com> <482FF39A.5010604@v.loewis.de> Message-ID: On Sun, 18 May 2008 11:15:06 +0200, Martin v. L?wis wrote: > There is also the issue of aliases. Some call it Moscow, some Moskau, > when it is really called ??????. Of course, the same issue exists for > states: some call it Kalifornien, others California. I don't see any issues here. Everybody call it "Moscow" when they speak English and "??????" when they speak Russian. Calling it "??????" or "Moskva" in English would be simply not correct and confusing. -- Ivan From sturlamolden at yahoo.no Sun May 18 08:20:09 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sun, 18 May 2008 05:20:09 -0700 (PDT) Subject: Using Python for programming algorithms References: <7ENXj.6906$255.106@bignews8.bellsouth.net> Message-ID: <71dc01f3-0084-4878-a4f0-5792e2648f77@y21g2000hsf.googlegroups.com> On May 18, 5:46 am, "inhahe" wrote: > The numbers I heard are that Python is 10-100 times slower than C. Only true if you use Python as if it was a dialect of Visual Basic. If you use the right tool, like NumPy, Python can be fast enough. Also note that Python is not slower than any other language (including C) if the code is i/o bound. As it turns out, most code is i/o bound, even many scientific programs. In scientific research, CPU time is cheap and time spent programming is expensive. Instead of optimizing code that runs too slowly, it is often less expensive to use fancier hardware, like parallell computers. For Python, we e.g. have mpi4py which gives us access to MPI. It can be a good advice to write scientific software parallelizable from the start. I learned Pascal my first year in college. When I started programming Matlab, I brought with me every habits of a novice Pascal programmer. Needless to say, my programs ran excruciatingly slow. I learned C just to write faster "mex" extensions for Matlab. But eventually, my skills improved and I found that my Matlab programs did not need C anymore. It took me almost 3 years to unlearn the bad habits I had acquired while programming Pascal. It is very easy to blame the language, when in fact it is the programmer who is not using it properly. From chandran.ramu1 at gmail.com Mon May 12 02:16:24 2008 From: chandran.ramu1 at gmail.com (chandran.ramu1 at gmail.com) Date: Sun, 11 May 2008 23:16:24 -0700 (PDT) Subject: hai friends Message-ID: hai dear, "may all good things come into your life today and always" www.goodhistory5.blogspot.com From Tymoteusz.Jankowski at gmail.com Fri May 9 05:13:34 2008 From: Tymoteusz.Jankowski at gmail.com (XLiIV) Date: Fri, 9 May 2008 02:13:34 -0700 (PDT) Subject: the lvalue curse? let's play with this crazy idea ;) Message-ID: <68618c8b-f17e-496a-9092-5e2cd16b365b@p25g2000hsf.googlegroups.com> I started playing with Python and love it since the very beginning, programming using Python is so ...human-like? but one thing returns to me almost everytime when I see/write the code Let's take a look at two ways of thinking... the standard one which is well-known and loved by almost everyone :) and that crazy concept below which suprised evan me :wacko: import time ftime = time.time() localtime = time.localtime(ftime) localtime = list(localtime[:3]) localtime = [str(i) for i in localtime] print '-'.join(localtime) It's harder to read than the below concept, isn't? Maybe I didn't used to this way of thinking yet. I hope it'll change soon or i'll quit ;) time.time() -> ftime -> time.localtime() -> p -> p[:3] -> g -> list(g) -> '-'.join() My example conclusion and not-ansewered-yet question... -it's nice to read and choosing the good names to variables aren't so important -what is the purpose of the variables here? :) I realize that there is no chance to implement it, but I really want to share it :] Peace, T. PS forgive my my english [shall I set it as a signature? ;) ] From grahamjfeeley at optusnet.com.au Thu May 29 04:23:03 2008 From: grahamjfeeley at optusnet.com.au (Graham Feeley) Date: Thu, 29 May 2008 18:23:03 +1000 Subject: run a script in vista Message-ID: <483e67e8$0$30464$afc38c87@news.optusnet.com.au> Hi, I have a script which runs in xp, however now I have upgraded to vista this script now does'nt work Can someone help with this problem please ? this is the start of the script import cPAMIE import cModalPopUp import winGuiAuto as wga import time, datetime import os, sys, re import mx.ODBC.Windows as odbc appreciate any help here Regards Graham From gherron at islandtraining.com Wed May 21 11:43:31 2008 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 21 May 2008 08:43:31 -0700 Subject: getting dir(x), but not as list of strings? In-Reply-To: References: Message-ID: <48344323.1040401@islandtraining.com> mh at pixar.com wrote: > I want to iterate over members of a module, something like: > > for i in dir(x): > if type(i) == types.FunctionType: ... > > but of course dir() returns a list of strings. If x is a module, > how can I get the list of its members as their actual types? > > Many TIA! > Mark > > Use the builtin vars to get a dictionary of names and associated objects. import sys for name,ob in vars(sys).items(): print name,type(ob) Gary Herron setrecursionlimit getfilesystemencoding path_importer_cache stdout version_info exc_clear prefix getrefcount byteorder ... From wollez at gmx.net Wed May 7 11:51:56 2008 From: wollez at gmx.net (WolfgangZ) Date: Wed, 07 May 2008 17:51:56 +0200 Subject: What is the purpose of ptyhon in Windows In-Reply-To: References: Message-ID: parag_paul at hotmail.com schrieb: > hi All, > I have no idea why I need to learn a new scripting language, > nothing much to the sytnax, > I need to understand what could be the prupose of another scripting > language > > Cna you please help me with this, > Is there a possibilty to work on bigger projects with Python > -- > http://mail.python.org/mailman/listinfo/python-list > At least I'm living in a free country and nobody forces me to learn python. So I don't fully understand why you HAVE TO learn it. When your problems can be solved in a different programming language than you should be free to use whatever you like. And also why should it be forbidden to create a new programming language? Diversity and competition is usually not bad. From garrickp at gmail.com Tue May 20 14:48:46 2008 From: garrickp at gmail.com (Falcolas) Date: Tue, 20 May 2008 11:48:46 -0700 (PDT) Subject: iterate start at second row in file not first References: <5be1e521-3a32-45f6-9812-5efed0187920@b9g2000prh.googlegroups.com> Message-ID: <34393ad5-59d1-4772-92c3-7e4d44a643c2@w4g2000prd.googlegroups.com> On May 20, 12:34 pm, notnorweg... at yahoo.se wrote: > how do i jump the first step there? i dont want to iterate the first > row...how do i start at the second? To simply bypass the first line, do a readline() on the file object before starting to process the file. To filter out particular lines throughout the file, you can either do a check in the for loop and continue if it is true, or create a generator which filters out unwanted content. untested: fd = open(some_file) fi = (x for x in fd if (x.search(':') < 0)) for line in fi: pass It gets a bit more complicated if you want to actually split on sentences, not lines. From aspersieman at gmail.com Thu May 8 08:24:37 2008 From: aspersieman at gmail.com (Aspersieman) Date: Thu, 08 May 2008 14:24:37 +0200 Subject: POP connection timeout. Message-ID: <4822F105.5050505@gmail.com> Hi All I have written an application that queries a POP mailbox and downloads messages. When the application tries to connect to the mail server, but takes too long (eg. longer than 60 seconds) I want to have it time out. Something like try: pop = poplib.POP3(POPHOST, POPPORT) except someerror, err: print "Connecting to mail box has timed out:\n", err I know that in python 2.5 I could pass an additional timeout parameter to the above statement ( ie: pop = poplib.POP3(POPHOST, POPPORT, TIMEOUTINSECONDS), but I am using python 2.4. Can anyone help me implement this timeout functionality. Regards Nicol -- The three things to remember about Llamas: 1) They are harmless 2) They are deadly 3) They are made of lava, and thus nice to cuddle. -- The three things to remember about Llamas: 1) They are harmless 2) They are deadly 3) They are made of lava, and thus nice to cuddle. From arnodel at googlemail.com Thu May 8 05:22:01 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Thu, 8 May 2008 02:22:01 -0700 (PDT) Subject: The del statement References: <02860f2a-cd1d-4b1d-ad49-08b13032ba21@2g2000hsn.googlegroups.com> Message-ID: Duncan Booth wrote: > Arnaud Delobelle wrote: > > > > > > > George Sakkis wrote: > >> One of the few Python constructs that feels less elegant than > >> necessary to me is the del statement. For one thing, it is overloaded > >> to mean three different things: > >> (1) del x: Remove x from the current namespace > >> (2) del x[i]: Equivalent to x.__delitem__(i) > >> (3) del x.a: Equivalent to x.__delattr__('a') (or delattr(x,'a')) > > > > Note that the 'X = Y' construct has the corresponding three meanings: > > > > (1) x = 4 # Bind x to 4 in the 'current namespace' > > (2) x[i] = 4 # equivalent to x.__setitem__(i, 4) > > (3) x.a = 4 # Equivalent to x.__setattr__('a', 4) > > I think you both missed a case: > > (1b) global x; del x # Remove x from global namespace > (1b) global x; x = 4 # Bind x to 4 in the global namespace This is why you put 'current namespace' in quotes! But all three of us missed the case: (1-3000) What about nonlocal? > That Python is simple and consistent. Seems reasonable to me. -- Arnaud From goldnery at gmail.com Sat May 31 17:38:29 2008 From: goldnery at gmail.com (Gandalf) Date: Sat, 31 May 2008 14:38:29 -0700 (PDT) Subject: Need Tutorial For the following lib Message-ID: <9950cf3f-e58a-413a-bdff-a40cc1c6cf6d@8g2000hse.googlegroups.com> Hi every one. I need comprehensive tutorial for the following library : 1. pyWinAuto 2. winGuiAuto Thanks in advance From kyosohma at gmail.com Fri May 2 09:32:56 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 2 May 2008 06:32:56 -0700 (PDT) Subject: Python documentation References: <02e9821d-10db-4164-bdf7-4285ee659fbb@w74g2000hsh.googlegroups.com> Message-ID: <2713f3f1-55e0-42a7-94eb-e0bea505ce60@m45g2000hsb.googlegroups.com> On May 2, 4:34 am, ad... at remembernobody.com wrote: > Hello, > > I have been learning python for some time using the dive into python > book. I am interested to know if anyone can recommend a book which > covers more advanced topics like threading and potentially GUI style > coding. > > Regards, > > Ronald Lutz's book, "Programming Python" covers a lot of advanced topics, including building various GUI-oriented programs with Tkinter. There's also "Core Python Programming" by Chun, which has some good internals stuff in it. I prefer using wxPython for my GUI work, so I'll also recommend Robin Dunn's "wxPython in Action". Mike From Sam.Dutton at itn.co.uk Thu May 22 12:32:13 2008 From: Sam.Dutton at itn.co.uk (Dutton, Sam) Date: Thu, 22 May 2008 17:32:13 +0100 Subject: Why is math.pi slightly wrong? Message-ID: I've noticed that the value of math.pi -- just entering it at the interactive prompt -- is returned as 3.1415926535897931, whereas (as every pi-obsessive knows) the value is 3.1415926535897932... (Note the 2 at the end.) Is this a precision issue, or from the underlying C, or something else? How is math.pi calculated? I searched for this on the web and in this group and couldn't find anything -- but humble apologies if this has been asked before/elsewhere. Sam Dutton SAM DUTTON SENIOR SITE DEVELOPER 200 GRAY'S INN ROAD LONDON WC1X 8XZ UNITED KINGDOM T +44 (0)20 7430 4496 F E Sam.Dutton at itn.co.uk WWW.ITN.CO.UK P Please consider the environment. Do you really need to print this email? Please Note: Any views or opinions are solely those of the author and do not necessarily represent those of Independent Television News Limited unless specifically stated. This email and any files attached are confidential and intended solely for the use of the individual or entity to which they are addressed. If you have received this email in error, please notify postmaster at itn.co.uk Please note that to ensure regulatory compliance and for the protection of our clients and business, we may monitor and read messages sent to and from our systems. Thank You. From gnewsg at gmail.com Tue May 13 17:05:43 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Tue, 13 May 2008 14:05:43 -0700 (PDT) Subject: asynchat sends data on async_chat.push and .push_with_producer References: Message-ID: <2567d557-b5cd-4b12-ad09-67f30ce1078d@b1g2000hsg.googlegroups.com> On 13 Mag, 22:16, Jean-Paul Calderone wrote: > On Tue, 13 May 2008 11:50:30 -0700 (PDT), Giampaolo Rodola' wrote: > >On 13 Mag, 17:59, Josiah Carlson wrote: > > >> We do not live in a pure world, Python isn't pure (practicality beats > >> purity), and by attempting to send some data each time a .push*() > >> method is called, there are measurable increases in transfer rates. > > >Good point. I'd like to ask a question: if we'd have a default > >asyncore.loop timeout of (say) 0.01 ms instead of 30 could we avoid > >such problem? > >I've always found weird that asyncore has such an high default timeout > >value. > >Twisted, for example, uses a default of 0.01 ms for all its reactors. > > I'm not sure this is right. ?What timeout are we talking about? ?Twisted > only wakes up when necessary. > > Jean-Paul I'm talking about the asyncore.loop timeout parameter which defaults to 30 (seconds). I don't think that Twisted only wakes up when necessary (surely not by using the select reactor). Think about the schedule calls feature (reactor.callLater). To have that work I guess that a continuous loop must always be kept alive, regardless of the reactor used. --- Giampaolo http://code.google.com/p/pyftpdlib From squareswallower at 1ya2hoo3.net Fri May 9 23:19:19 2008 From: squareswallower at 1ya2hoo3.net (dave) Date: Fri, 9 May 2008 21:19:19 -0600 Subject: anagram finder / dict mapping question References: <0ebda682-6c99-43b2-b88b-80f6c88e1c98@p25g2000hsf.googlegroups.com> <54f75240-d8ee-482c-baea-d37bf3900b76@i36g2000prf.googlegroups.com> <494e9c6a-9346-4134-943b-249956bebdd0@a23g2000hsc.googlegroups.com> Message-ID: On 2008-05-09 18:53:19 -0600, George Sakkis said: > On May 9, 5:19?pm, umpsu... at gmail.com wrote: >>>> What would be the best method to print the top results, the one's that > >>>> had the highest amount of anagrams?? ?Create a new histogram dict? >> >>> You can use the max() function to find the biggest list of anagrams: >> >>> top_results = max(anagrams.itervalues(), key=len) >> >>> -- >>> Arnaud >> >> That is the biggest list of anagrams, what if I wanted the 3 biggest >> lists? ?Is there a way to specific top three w/ a max command?? > >>>> import heapq >>>> help(heapq.nlargest) > Help on function nlargest in module heapq: > > nlargest(n, iterable, key=None) > Find the n largest elements in a dataset. > > Equivalent to: sorted(iterable, key=key, reverse=True)[:n] > > > HTH, > George I both the 'nlargest' and the 'sorted' methods.. I could only get the sorted to work.. however it would only return values like (3, edam) not the list of words.. Here is what I have now.. Am I over-analyzing this? It doesn't seem like it should be this hard to get the program to print the largest set of anagrams first... def anafind(): fin = open('text.txt') mapdic = {} finalres = [] # top answers go here for line in fin: line = line.strip() alphaword = ''.join(sorted(line)) #sorted word as key if alphaword not in mapdic: mapdic[alphaword] = [line] else: mapdic[alphaword].append(line) topans = sorted((len(mapdic[key]), key) for key in mapdic.keys())[-3:] #top 3 answers for key, value in topans: # finalres.append(mapdic[value]) print finalres From mnikhil at gmail.com Tue May 13 19:57:07 2008 From: mnikhil at gmail.com (Nikhil) Date: Wed, 14 May 2008 05:27:07 +0530 Subject: list.__len__() or len(list) Message-ID: which one is better? and why? __len__() is a built-in function of the list object and is updated along with the list object elements and will be useful incase the list is very huge. len() is an external method again, which may require the processing cycles again. Is it right? From conradwt at gmail.com Mon May 26 10:09:27 2008 From: conradwt at gmail.com (Con) Date: Mon, 26 May 2008 07:09:27 -0700 (PDT) Subject: Cannot Read MySQLdb docs within Python interpreter Message-ID: Hi, I'm gettting a traceback when I attempt to read the MySQLdb docs after installation on Mac OS X 10.5.2: BEGIN TRACEBACK: >>> help( "MySQLdb" ) Traceback (most recent call last): File "", line 1, in File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/site.py", line 346, in __call__ return pydoc.help(*args, **kwds) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/pydoc.py", line 1645, in __call__ self.help(request) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/pydoc.py", line 1687, in help elif request: doc(request, 'Help on %s:') File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/pydoc.py", line 1481, in doc pager(title % desc + '\n\n' + text.document(object, name)) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/pydoc.py", line 324, in document if inspect.ismodule(object): return self.docmodule(*args) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/pydoc.py", line 1072, in docmodule contents.append(self.document(value, key, name)) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/pydoc.py", line 325, in document if inspect.isclass(object): return self.docclass(*args) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/pydoc.py", line 1196, in docclass lambda t: t[1] == 'method') File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/pydoc.py", line 1146, in spill name, mod, object)) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/pydoc.py", line 326, in document if inspect.isroutine(object): return self.docroutine(*args) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/pydoc.py", line 1257, in docroutine doc = getdoc(object) or '' File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/pydoc.py", line 82, in getdoc result = inspect.getdoc(object) or inspect.getcomments(object) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/inspect.py", line 521, in getcomments lines, lnum = findsource(object) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/inspect.py", line 510, in findsource if pat.match(lines[lnum]): break IndexError: list index out of range END TRACEBACK: If anyone has any ideas as to how to resolve this issue, please feel free to post the solution and thanks in advance. -Conrad From Scott.Daniels at Acm.Org Sun May 4 19:41:34 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sun, 04 May 2008 16:41:34 -0700 Subject: Please help - Tkinter not doing anything In-Reply-To: References: <20562a9d-200c-40ae-a850-eb0f9a943d3f@l42g2000hsc.googlegroups.com> <237aa3894dff4c8976896df85f4d7d23@localhost> <3ab5d06a0805040239m6cf12d39ufcde4fcc585f81e4@mail.gmail.com> Message-ID: s0suk3 at gmail.com wrote: > On May 4, 5:22 am, Protected wrote: >> .... I'm pasting the code in IDLE and using Windows XP.... > > Tkinter doesn't work if you type the statements in IDLE.... it doesn't > work because IDLE is itself a Tkinter app. Actually, _because_ IDLE is a Tkinter app,you can use it to experiment with Tkinter in a very useful way. The trick is that you need to start idle with the "-n" (No subprocesses) switch. This is so useful that I build a shortcut on my desktop to do exactly this. Using this shortcut you can see the effect of each action as you type it, giving you an idea of exactly what must happen. I'm assuming you are using Python 2.5 here (other versions have related recipes, but slightly more complicated). Right click on the desktop, and choose "New Shortcut." For "Choose the location of the item", browse to (or type in) C:\Python25\pythonw.exe Then (after your next) pick a name for your shortcut. Right click on the resulting shortcut, and go to "properties" Change the "Target" entry from: C:\Python25\pythonw.exe to: C:\Python25\pythonw.exe -m idlelib.idle -n Also, if you are like me, you'll want to change the "Start in" directory to wherever you work on python code --so imports of your own stuff "just work", and so "File open'" and "Save As" default to a "nice" directory. The Idle you get with this "corrupts" more easily, since the "-n" says "no subprocess." Things like restarting the shell don't work. _But_ Tkinter stuff is available (there is already a running mainloop). You can interactively do simple things a step at a time and watch the results. It is a _great_ way to experiment with Tkinter. --Scott David Daniels Scott.Daniels at Acm.Org From robert.kern at gmail.com Mon May 19 16:47:44 2008 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 19 May 2008 15:47:44 -0500 Subject: arrays In-Reply-To: <48313A7F.4050909@islandtraining.com> References: <48313A7F.4050909@islandtraining.com> Message-ID: Gary Herron wrote: > 1. Why have you flooded this news group with three identical copies of > a question under three different subject? This is a (mild) bit of abuse > of the newsgroup. One copy with a reasonable subject line is enough. If you look at the dates, they are a few days old. I imagine he was having posting problems, and the messages finally worked their way out of whatever queue they were being held up in. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From darcy at druid.net Mon May 12 16:17:45 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Mon, 12 May 2008 16:17:45 -0400 Subject: thread stomp? In-Reply-To: References: Message-ID: <20080512161745.186618bf.darcy@druid.net> On Mon, 12 May 2008 20:00:52 GMT pyn3wb wrote: > class1 (threading.Thread): ^ SyntaxError: invalid syntax Give us a script that works. Ideally it should output something that indicates what the error is. > //run over files This is not a comment in Python. > class2 threads seems to start prior to class1 threads done; class2 > results depend on class1 finish first What are you trying to do? If all you care about is making one thread depend on another finishing, why make two threads? Just have one thread do one thing and then do the other. Not every problem is a threading problem. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From lists at cheimes.de Tue May 13 06:37:38 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 13 May 2008 12:37:38 +0200 Subject: The 'is' identity operator checking immutable values caution In-Reply-To: <5353c776-6ef7-4d2f-8769-e3ace320d2c6@b64g2000hsa.googlegroups.com> References: <5353c776-6ef7-4d2f-8769-e3ace320d2c6@b64g2000hsa.googlegroups.com> Message-ID: wxPythoner at gmail.com schrieb: > We have to avoid the use of the 'is' identity operator with basic, > immutable values such as numbers and strings. The result is > unpredictable because of the way Python handles these objects > internally. You are confusing immutable objects with singletons. Never use "is" with strings and numbers. Christian From dullrich at sprynet.com Fri May 30 10:50:16 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Fri, 30 May 2008 09:50:16 -0500 Subject: Getting up and running with Python on a Mac References: <7d593f8a-92b8-4dfe-935f-dd6a22c70faf@m45g2000hsb.googlegroups.com> Message-ID: In article <7d593f8a-92b8-4dfe-935f-dd6a22c70faf at m45g2000hsb.googlegroups.com>, tkpmep at hotmail.com wrote: > I've just bought an iMac (OS X 10.5.2, will almost immediately jump to > 10.5.3), and am looking to install Python on it, and to use it with > XCode, Apple's IDE. If that's what you really want to do then start XCode, select New Project and look for the ones with "Python" in their names. I was excited to hear that Python was going to be automatically integrated into XCode in OS 10.5. I tried it once. I should say I really didn't give it a fair trial - the impression I got from my unfair trial was I'd have to learn a lot about Cocoa to do anything useful. Searched a little, decided to try wxPython next, and I was very happy with that. Seems much easier - also as far as I could see there was nothing but a 'Hello World' example included in XCode, while wxPython comes with a truly amazing suite of complete examples (the C++ wxWidgets book recommends looking at wxPython for the examples!) >Some googling suggests that a number of people > have had trouble getting Python to run satisfactorily on their Macs. > This is my first Mac, and I'd appreciate some guidance on what to do > (and what not to) when installing Python and potential problems to > keep an eye open for. I want to do a fair bit of scientific / > numerical computing, so it would seem that SAGE ot the Enthought > Python distribution would seem to be the most relevant - I'd > appreciate your guidance on getting Python to run on a Mac with a > particular focus on these two distributions. > > Thank you in advance > > Thomas Philips -- David C. Ullrich From arnodel at googlemail.com Wed May 14 15:20:44 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 14 May 2008 20:20:44 +0100 Subject: readlines with line number support? References: Message-ID: Nikhil writes: > Arnaud Delobelle wrote: > >> The standard Python way is using enumerate() >> >> for i, line in enumerate(fp): >> print "line number: " + lineno + ": " + line.rstrip() >> > > I guess you meant to say : > > for lineno, line in enumerate(fp): > print "line number: " + lineno + ": " + line.rstrip() Yes! -- Arnaud From tjreedy at udel.edu Mon May 19 09:06:50 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 19 May 2008 09:06:50 -0400 Subject: explain this function to me, lambda confusion References: <5cc7ef7a-dd21-4772-a7e3-765410f810bb@l17g2000pri.googlegroups.com> <6062786d-6f83-4850-bf55-4db4ec27bdea@b1g2000hsg.googlegroups.com> Message-ID: "Arnaud Delobelle" wrote in message news:6062786d-6f83-4850-bf55-4db4ec27bdea at b1g2000hsg.googlegroups.com... | On May 19, 5:22 am, "Terry Reedy" wrote: | > "Arnaud Delobelle" wrote in message | [...] | > | Note that the same thing can be said about generator expressions, | > | which are nothing more than anonymous, non-reusable, generator | > | functions. | > | > Right. So if someone posted on genexp confusion, I would suggest | > 'write a full generator function'. | | I was just arguing against arguing for the removal of lambda on the | basis that it doesn't add any functionality to the language! I sort of understood that ;-) Like Guido, I am split on keep/remove. However, I have decided to leave lambda out of my Python-subset executable-pseudocode algorithm language. I have not decided whether or not to include genexps. | > | Instead these were _added_ to the language! | > | > As a convenience. | > Actually, if one uses more that one for-clause in a generator expression, | > there is a potential gotcha in relation to name capture. So if that bites, | > the genexp is not so much a convenience, and one might better write | > the full function. | Yes, IMHO this is a bug, and I wish I had the time to dive into the | code to see if I can fix it. If I do include them, I might restrict them to one for-clause because of that glitch, whose details I keep forgetting. tjr | From dullrich at sprynet.com Wed May 14 16:47:18 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Wed, 14 May 2008 15:47:18 -0500 Subject: sys.excepthack... Message-ID: Becoming a fan of wxPython, but I can't stand what it does with error messsages (I can't find a way to dismiss that window with the error message from the keyboard. Seems to be anti-modal - the key strokes that normally kill the active window kill the main window (sitting behind the window with the error message) instead. If the window only had an OK button...) So I want to pop up a modal dialog on error. Tried setting sys.stderr to an object with a write method that pops up a dialog. The problem with that is write() gets called several times per exception - I don't see how to get my new sys.stderr object to figure out when it's time to show the message. So then I found sys.excepthook. The problem with that was that I was too stoopid to figure out how to get a readable error message from the parameters passed to excepthook. Came up with a ridiculous hack involving both sys.stderr and sys.excepthook. Works exactly the way I want. Seems ridiculous - what's the right way to do this? Ridiculous_hack.py: import sys import wx def hook(*args): try: sys.__excepthook__(*args) finally: printer.Show() class ErrorDisplay: def __init__(self): self.buffer = '' def write(self, text): self.buffer = self.buffer + text def Show(self): wx.MessageDialog(None, str(self.buffer), 'Error:',wx.OK).ShowModal() self.buffer = '' printer = ErrorDisplay() sys.stderr = printer sys.excepthook = hook -- David C. Ullrich From gagsl-py2 at yahoo.com.ar Mon May 26 19:25:56 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 26 May 2008 20:25:56 -0300 Subject: Cannot Read MySQLdb docs within Python interpreter References: Message-ID: En Mon, 26 May 2008 11:09:27 -0300, Con escribi?: > Hi, I'm gettting a traceback when I attempt to read the MySQLdb docs > after installation on Mac OS X 10.5.2: Better to report it at bugs.python.org -- Gabriel Genellina From alokkat at gmail.com Wed May 28 00:22:59 2008 From: alokkat at gmail.com (Alok Kumar) Date: Wed, 28 May 2008 00:22:59 -0400 Subject: multi dimensional dictionary Message-ID: Dear All, I am using dictionary for filling my xpath parsed data. I wanted to use in the following manner. mydict[index] ["key1"] ["key2"] #Can someone help me with right declaration. So that I can fill my XML xpath parsed data mydict[0] ["person"] ["setTime"] = "12:09:30" mydict[0] ["person"] ["clrTime"] = "22:09:30" Can someone help me with right declaration usages. Your help will be highly appreciated. Regards Alok -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Sat May 17 05:12:40 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 17 May 2008 09:12:40 GMT Subject: Getting elements and text with lxml In-Reply-To: <6af73a72-1a0c-40c4-8bc0-58c41e75fc4c@d45g2000hsc.googlegroups.com> References: <6af73a72-1a0c-40c4-8bc0-58c41e75fc4c@d45g2000hsc.googlegroups.com> Message-ID: <482ea185$1@news.mel.dft.com.au> J. Pablo Fern?ndez wrote: > On May 17, 2:19 am, "Gabriel Genellina" > wrote: >> En Fri, 16 May 2008 18:53:03 -0300, J. Pablo Fern?ndez >> escribi?: >> >> >> >>> Hello, >>> I have an XML file that starts with: >>> >>> >>> >>> *-a >>> >>> out of it, I'd like to extract something like (I'm just showing one >>> structure, any structure as long as all data is there is fine): >>> [("ofc", "*"), "-", ("rad", "a")] >>> How can I do it? I managed to get the content of boths tags and the >>> text up to the first tag ("\n "), but not the - (and in other XML >>> files, there's more text outside the elements). >> Look for the "tail" attribute. > > That gives me the last part, but not the one in the middle: > > In : etree.tounicode(e) > Out: u'\n *-a\n\n' > > In : e.text > Out: '\n ' > > In : e.tail > Out: '\n' > You need the text content of your initial element's children, which needs that of their children, and so on. See http://effbot.org/zone/element-bits-and-pieces.htm HTH, John From benjamin.kaplan at case.edu Thu May 29 09:47:10 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Thu, 29 May 2008 09:47:10 -0400 Subject: Tuple of coordinates In-Reply-To: References: Message-ID: On Thu, May 29, 2008 at 8:16 AM, victor.herasme at gmail.com < victor.herasme at gmail.com> wrote: > Hi, > > i am using a software which uses python as its scripting language. I > want to generate a list of coordinates more or less this way: > > for i in (beg, end, step): > for j in (beg, end, step): > for k in (beg, end, step): > ......... > > Coords = ((i1,j1,k1), (i2,j2,k2), ...,(in,jn.kn)) > > > Can anyone give me some advice on how to achieve this ? I got a little > idea, but still need to keep working til i get it. Thanks in advance, > The pseudo-code and the intended result are two completely different things. The pseudo-code would give you [(i1,j1,k1),(i1,j1,k2),(i1,j2,k1)...]. That code would be written coords = list() for i in xrange(beg, end, step) : for j in xrange(beg, end, step) : for k in xrange(beg, end, step) : coords.append((i,j,k)) for the result you gave, you would do i = xrange(beg, end, step) j = xrange(beg, end, step) k = xrange(beg, end, step) coords = zip(i,j,k) > > Victor > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From BrianVanderburg2 at aim.com Tue May 13 01:50:18 2008 From: BrianVanderburg2 at aim.com (Brian Vanderburg II) Date: Tue, 13 May 2008 01:50:18 -0400 Subject: Learning Python for no reason In-Reply-To: <0383f3b8$0$27282$c3e8da3@news.astraweb.com> References: <0383f3b8$0$27282$c3e8da3@news.astraweb.com> Message-ID: <48292C1A.5030200@aim.com> John Salerno wrote: > Just something that crosses my mind every time I delve into "Learning > Python" each night. Does anyone see any value in learning Python when you > don't need to for school, work, or any other reason? I mean, sure, there's > value in learning anything at any time, but for something like a programming > language, I can't help but feel that I will be mostly unable to use what I > learn simply because I have no reason to use it. > > The *process* of learning is enough fun for me, and every now and then I do > find a small use for Python that really pays off, but for the most part I'm > wondering what people's thoughts are as far as simply learning it for the > sake of learning. Does it seem like a silly endeavor to most people? Did > anyone here learn a programming language when you didn't need to? If so, how > much and in what capacity did you use it after you learned it? > > Hopefully this question even makes sense! > > > -- > http://mail.python.org/mailman/listinfo/python-list > I think almost anyone especially if frequently uses computer could benefit from learning a scripting language. I'm mainly a C and C++ person and most of my programs use it. But when I want to do a simple one-time task or something that will change frequently I'll use a scripting language to quickly get it done, such as extracting information from a web page or whatever. With C, C++, and Python I do just about whatever I want/need, and they can be combined/embedded as well. In general I think that learning some basics of programming can help develop pretty good logic/analytic skills as well, but that's just my opinion. Maybe it's the other way around and logic/analytic skills lead to easily learning programing languages. As for learning for the sake of it, if it's fun I don't see how it could hurt any. Brian Vanderburg II From tdahsu at gmail.com Wed May 21 10:23:27 2008 From: tdahsu at gmail.com (tdahsu at gmail.com) Date: Wed, 21 May 2008 07:23:27 -0700 (PDT) Subject: Code For Five Threads To Process Multiple Files? Message-ID: <8ddc1f4d-b6c1-4380-baaa-ab7e58d980ad@f36g2000hsa.googlegroups.com> All, I'd appreciate any help. I've got a list of files in a directory, and I'd like to iterate through that list and process each one. Rather than do that serially, I was thinking I should start five threads and process five files at a time. Is this a good idea? I picked the number five at random... I was thinking that I might check the number of processors and start a multiple of that, but then I remembered KISS and it seemed that that was too complicated. If it's not a horrible idea, would anyone be able to provide some quick code as to how to do that? Any and all help would be greatly appreciated! Thanks in advance! From johnjsal at NOSPAMgmail.com Mon May 19 23:42:14 2008 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 19 May 2008 23:42:14 -0400 Subject: conventions/requirements for 'is' vs '==', 'not vs '!=', etc References: <4dc24f2e-04f5-4ad6-b021-f416ef5c7415@z72g2000hsb.googlegroups.com> <8ebd28f1-887f-45c9-a35f-af9023b062ea@u12g2000prd.googlegroups.com> <3629843a-ebcb-4f15-82f1-899500f7b91f@t54g2000hsg.googlegroups.com> Message-ID: <20080519234214.beae9314.johnjsal@NOSPAMgmail.com> On Mon, 19 May 2008 20:34:22 -0700 (PDT) notnorwegian at yahoo.se wrote: > i am confused. > > x=5 > y=5 > > x==y -> True > x is y -> True > > shouldnt x is y return False since they shouldnt(dont?) point to the > same place in memory, they just store an equal value? > For some immutable values (such as numbers and strings), Python will have separate variables reference the same object, as an optimization. This doesn't affect anything, since the numbers are immutable anyway and a shared reference won't create any unexpected changes. It also works with small, but not large, strings: >>> x = 'hello' >>> y = 'hello' >>> x == y True >>> x is y True >>> a = 'this is longer' >>> b = 'this is longer' >>> a == b True >>> a is b False >>> In the above example, Python has created only one string called 'hello' and both x and y reference it. However, 'this is longer' is two completely different objects. From efurman at admailinc.com Wed May 14 12:51:40 2008 From: efurman at admailinc.com (Ethan Furman) Date: Wed, 14 May 2008 08:51:40 -0800 Subject: cgitb performance issue In-Reply-To: References: <481F585A.5080707@admailinc.com> Message-ID: <482B189C.1050302@admailinc.com> Gabriel Genellina wrote: >En Mon, 05 May 2008 15:56:26 -0300, Ethan Furman escribi?: > > > >>I tried adding a form to our website for uploading large files. >>Personally, I dislike the forms that tell you you did something wrong >>and make you re-enter *all* your data again, so this one cycles and >>remembers your answers, and only prompts for the file once the rest of >>the entered data is good. However, the first time the form loads it can >>take up to 30 seconds... any ideas why? >> >> > >Hard to tell without looking at the code... And what has cgitb to do with this? > > Hmmmm... excellent question, and the answer is -- Nothing. My apologies. I'm importing cgi (cgitb was while I was debugging it), as well as a bunch of others. Here's the source, with a bunch of the actual html stripped out. The -u as well as the last two lines were an attempt to eliminate the 30-second pause while it loads, as it seems to get all data transferred, then just waits for a while. Any ideas appreciated. My apologies for the ugly code. -- Ethan #!/usr/local/bin/python -u import cgi #import cgitb; cgitb.enable() import smtplib import mimetypes import os import sys from email.Encoders import encode_base64 from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email.MIMEMultipart import MIMEMultipart HEADER = """Content-type: text/html\n """ SELECTFILES = """ """ FILESRECEIVED = """ """ VERIFIED = """ """ FOOTER = """ """ REQUIRED = '
*required' form = cgi.FieldStorage() clientname = clientemail = clientcsr = subject = body = "" csrs = {"frank":{'html':'selected="yes"', 'name':'', 'email':''}, \ "kathy":{'html':'', 'name':'', 'email':''}, \ "chris":{'html':'', 'name':'', 'email':''}, \ "tracy":{'html':'', 'name':'', 'email':''}, \ "susi": {'html':'', 'name':'', 'email':''}, \ "bill": {'html':'', 'name':'', 'email':''}} incomplete = False files = [] filelist = [] if form: if form.has_key("name"): clientname = form["name"].value if form.has_key("email"): clientemail = form["email"].value if form.has_key("CSR"): clientcsr = form["CSR"].value csrs["frank"]['html'] = '' # clear default csrs[clientcsr]['html'] = 'selected="yes"' if form.has_key("subject"): subject = form["subject"].value if form.has_key("body"): body = form["body"].value incomplete = not (clientname and clientemail and clientcsr and subject) if form.has_key("file1"): file1 = form["file1"] if file1.filename: files.append(file1.filename + "
") filelist.append(file1) if form.has_key("file2"): file2 = form["file2"] if file2.filename: files.append(file2.filename + "
") filelist.append(file2) if form.has_key("file3"): file3 = form["file3"] if file3.filename: files.append(file3.filename + "
") filelist.append(file3) if form.has_key("file4"): file4 = form["file4"] if file4.filename: files.append(file4.filename + "
") filelist.append(file4) if form.has_key("file5"): file5 = form["file5"] if file5.filename: files.append(file5.filename + "
") filelist.append(file5) def csrform(): cn_present = '' ce_present = '' sb_present = '' if incomplete: if not clientname: cn_present = REQUIRED if not clientemail: ce_present = REQUIRED if not subject: sb_present = REQUIRED print """

Please fill in your name, e-mail address, subject, and select your CSR. You will then be able to upload files on the next screen. Any additional notes may go in the Message field.

""" print """ """ \ % (clientname, cn_present) print """ """ \ % (clientemail, ce_present) print """ """ \ % (subject, sb_present) print """ """ \ % (csrs["frank"]['html'], csrs["kathy"]['html'], csrs["chris"]['html'], csrs["tracy"]['html'], csrs["susi"]['html'], csrs["bill"]['html']) print """ """ % (body) def uploadform(): try: msg = MIMEMultipart() msg['To'] = "%s <%s>" % (csrs[clientcsr]['name'], csrs[clientcsr]['email']) msg['From'] = "Ad-Mail Upload Manager for %s " % (clientname, ) msg['Reply-to'] = clientemail msg['Subject'] = subject msg.attach(MIMEText(body)) for file in filelist: attachment = MIMEBase('application', 'octet-stream') attachment.set_payload(file.file.read()) encode_base64(attachment) attachment.add_header('Content-Disposition', 'attachment', filename=os.path.split(file.filename)[1]) msg.attach(attachment) smtp = smtplib.SMTP() smtp.connect() smtp.sendmail('Ad-Mail Upload Manager ', csrs[clientcsr]['email'], msg.as_string()) smtp.close except: print "

Unknown error. Please try again later.

" smtp = smtp if not (form and clientname and clientemail and clientcsr): print HEADER csrform() print FOOTER elif files: print HEADER print FILESRECEIVED % (' '.join(files), csrs[clientcsr]['name']) uploadform() print FOOTER else: print HEADER print SELECTFILES % (clientname, clientemail, subject, clientcsr, body, clientname.split()[0], csrs[clientcsr]['name'].split()[0]) print FOOTER sys.stdout.flush() sys.stdout.close() -------------- next part -------------- An HTML attachment was scrubbed... URL: From google at mrabarnett.plus.com Thu May 15 18:18:57 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 15 May 2008 15:18:57 -0700 (PDT) Subject: no inputstream? References: <87lk2ba4b4.fsf@mulj.homelinux.net> <8d566db4-c626-491f-82e4-303308c5b8da@25g2000hsx.googlegroups.com> Message-ID: On May 15, 9:00 pm, max wrote: > you're right, my java implementation does indeed parse for Id3v2 > (sorry for the confusion). i'm using the getrawid3v2() method of this > bitstream class (http://www.javazoom.net/javalayer/docs/docs0.4/ > javazoom/jl/decoder/Bitstream.html) to return an inputstream that then > i buffer and parse. apologies if i misrepresented my code! > > back to python, i wonder if i'm misusing the mutagen id3 module. this > brief tutorial (http://www.sacredchao.net/quodlibet/wiki/Development/ > Mutagen/Tutorial) leads me to believe that something like this might > work: > > from mutagen.mp3 import MP3 > id3tags = MP3(urllib2.urlopen(URL)) > > but this gives me the following TypeError: "coercing to Unicode: need > string or buffer, instance found". does this mean i need to convert > the "file-like object" that is returned by urlopen() into a unicode > object? if so, do i just decode() with 'utf-8', or is this more > complex? as of now, doing so gives me mostly "No such file or > directory" errors, with a few HTTP 404s. > [snip] I think it's expecting the path of the MP3 but you're giving it the contents. From gagsl-py2 at yahoo.com.ar Sun May 18 00:45:57 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 18 May 2008 01:45:57 -0300 Subject: Shelve or pickle module References: Message-ID: En Sun, 18 May 2008 00:14:19 -0300, Guillaume Bog escribi?: > I read and re-read "Python in a Nutshell" written by Alex Martelli, > who knows what he is talking about. I'm a bit new to python and I'm > going to start doing persistence side on a project. Martelli's book > seems to tell me that I should use shelve module, but any code I > browsed is using pickle instead. Is there any reason to prefer pickle > over shelve? A shelve is just a persistent dictionary that uses pickle to store the objects. If you want to store one or a few objects, using pickle directly may be easier. Any problem you may have with pickle (nonpickleable objects, security risks) will happen with shelve too. -- Gabriel Genellina From skunkwerk at gmail.com Mon May 5 12:02:12 2008 From: skunkwerk at gmail.com (skunkwerk) Date: Mon, 5 May 2008 09:02:12 -0700 (PDT) Subject: logger output References: <1e6846b9-67b9-4a79-9454-a528aa8aca17@j33g2000pri.googlegroups.com> Message-ID: <65a6be8e-d67f-4255-938a-fcfbfb8b4eb1@z16g2000prn.googlegroups.com> On May 4, 10:40 pm, "Gabriel Genellina" wrote: > En Mon, 05 May 2008 00:33:12 -0300,skunkwerk escribi?: > > > > > i'm redirecting the stdout & stderr of my python program to a log. > > Tests i've done on a simple program with print statements, etc. work > > fine. however, in my actual program i get weird output like this: > > > 2008-05-04 20:20:44,790 DEBUG Grabbing message from queue, if any > > 2008-05-04 20:20:44,790 DEBUG DEBUG:doit:Grabbing message from queue, > > if any > > 2008-05-04 20:20:44,790 DEBUG DEBUG:doit:DEBUG:doit:Grabbing message > > from queue, if any > > 2008-05-04 20:20:44,790 DEBUG > > DEBUG:doit:DEBUG:doit:DEBUG:doit:Grabbing message from queue, if any > > > class write2Log: > > def write(self, x): > > if x!='\n': > > logger.debug(str(x)) > > > any ideas what might be causing the problems? some of the messages > > being output are quite long - might this be a problem? > > Try this simplified example and see by yourself: > > import sys > > class Write2Log: > def write(self, x): > sys.__stdout__.write('[%s]' % x) > > sys.stdout = Write2Log() > > print "Hello world!" > age = 27 > name = "John" > print "My name is", name, "and I am", age, "years old." > > -- > Gabriel Genellina thanks Gabriel, i tried the code you sent and got output like the following: [My name is][][john][][and I am][][27][][years old.] it doesn't really help me though. does this have any advantages over the syntax i was using? are there any limits on what kind of objects the logger can write? ie ascii strings of any length? thanks From deets at nospam.web.de Tue May 20 09:34:16 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 20 May 2008 15:34:16 +0200 Subject: Misuse of list comprehensions? References: <038e4418$0$27258$c3e8da3@news.astraweb.com> Message-ID: <69g2bpF31ttuuU1@mid.uni-berlin.de> John Salerno wrote: > I posted this code last night in response to another thread, and after I > posted it I got to wondering if I had misused the list comprehension. > Here's the two examples: > > Example 1: > -------------------- > def compress(s): > new = [] > > for c in s: > if c not in new: > new.append(c) > return ''.join(new) > ---------------------- > > Example 2: > ------------------------ > def compress(s): > new = [] > [new.append(c) for c in s if c not in new] > return ''.join(new) > -------------------------- > > In example 1, the intention to make an in-place change is explicit, and > it's being used as everyone expects it to be used. In example 2, however, > I began to think this might be an abuse of list comprehensions, because > I'm not assigning the result to anything (nor am I even using the result > in any way). > What does everyone think about this? Should list comprehensions be used > this way, or should they only be used to actually create a new list that > will then be assigned to a variable/returned/etc.? the above code is pretty much of a no-no because it has quadratic runtime behavior. That being said, I use that idiom myself. But I don't see anything wrong with using a list-comp as loop-abbreviation. because that is it's actual purpose. And also it is common in non-functional languages that l-values aren't always assigned, if the aren't needed. It's the consequence of having side-effects in a language - and python has them. Diez From danb_83 at yahoo.com Wed May 21 00:55:14 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Tue, 20 May 2008 21:55:14 -0700 (PDT) Subject: Struct usage and varying sizes of h, l, etc References: <48335269.2000809@admailinc.com> Message-ID: <30577157-d93c-4e7c-90bb-f9d8dfee56d7@8g2000hse.googlegroups.com> On May 20, 5:59?pm, Robert Kern wrote: > Ethan Furman wrote: > > Greetings, > > > I'm looking at the struct module for binary packing of ints and floats. ? > > The documentation refers to C datatypes. ?It's been many years since I > > looked at C, but I seem to remember that the data type sizes were not > > fixed -- for example, an int might be two byes on one machine, and four > > bytes on the next. ?Can any C programmers verify this? ?If it is true, > > does that mean that struct.pack('h', 8001) might give me different > > results depending on the machine it's running on? > > Right. I believe (but could be wrong) that "char" is defined to be one byte, but > that "short", "int", "long", and "long long" are defined as "at least as big as > the previous type". There are also minimum sizes for each type: char: 8 bits short: 16 bits int: 16 bits long: 32 bits long long: 64 bits > In practice, though, on nearly every machine that Python runs on, "char" is one > byte, "short" is two bytes, and "int" is four bytes. "longs" and "long longs" > tend to vary substantially, though; never assume sizes for them. > > Single-precision floats are always four bytes and double-precision floats are > always eight bytes. "long doubles" vary; they could be twelve bytes or sixteen. > > If you want to deal with fixed sizes, use struct.calcsize() to test the sizes of > each of the integer types, assign them to width-specific aliases, and always use > these aliases. Also, according to the documentation for the struct module, the =, <, and > format characters specify "std. size" rather than "native size". From notnorwegian at yahoo.se Tue May 20 14:34:15 2008 From: notnorwegian at yahoo.se (notnorwegian at yahoo.se) Date: Tue, 20 May 2008 11:34:15 -0700 (PDT) Subject: iterate start at second row in file not first Message-ID: <5be1e521-3a32-45f6-9812-5efed0187920@b9g2000prh.googlegroups.com> i have a big file with sentences, the first file of each sentence contains a colon(:) somewher eon that line i want to jump past that sentence. if all(x != ':' for x in line): this way i can check but i dont want to check for every line in the whole file, quite unnecessary when i only need to chekc the first line. so the question is, when dealign with iterators like: mov = open(afile) for line in mov: do y how do i jump the first step there? i dont want to iterate the first row...how do i start at the second? From woodygar at sky.com Wed May 21 12:42:51 2008 From: woodygar at sky.com (garywood) Date: Wed, 21 May 2008 17:42:51 +0100 Subject: can someone with guessing a number Message-ID: <005101c8bb61$b78fb710$1300a8c0@Home> I would just like the program to exit after guessing the amount of numbers wrong # Guess My Number import random the_number = random.randrange(100) + 1 tries = 1 # guessing loop while (guess != the_number): if (guess > the_number): print "Lower..." else: print "Higher..." guess = int(raw_input("Take a guess: ")) tries += 1 if tries > 10: print 'you failed- give up' print "You guessed it! The number was", the_number print "And it only took you", tries, "tries!\n" raw_input("\n\nPress the enter key to exit.") many Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From dullrich at sprynet.com Sat May 24 07:23:48 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Sat, 24 May 2008 06:23:48 -0500 Subject: Relationship between GUI and logic? References: <48363c34$0$15204$607ed4bc@cv.net> Message-ID: <2auf34dc59ajcjfq7f3fl0366eukfd98d5@4ax.com> On 23 May 2008 18:23:04 +0100 (BST), Matthew Woodcraft wrote: >John Salerno wrote: >> Basically, the question is this: can you write the logic behind a >> program (whether it be a game, an email client, a text editor, etc.) >> without having any idea of how you will implement the GUI? > >You probably could, but it's best not to unless you're somehow forced >to. > >In practice, the interface that you want your 'logic' layer to provide >to the GUI is likely to depend on some of the details of how the GUI >works. > >If you did the lower levels first without having any idea at all of >what you were going to do with the GUI, it's quite likely that you'd >find you'd written a few functions which turned out not to be needed at >all, or that some functionality that the GUI needs to use very >frequently is rather slow to execute, or that some functionality that >you thought belonged to the 'logic' is really better done in the GUI >layer, and so on and so forth. > >For example, if you were writing the 'logic' for a chess program you >might choose a way of modelling the board that can't represent a >position with more than one black king. And then when you got round to >doing the GUI you might find out that your users would like to be able >to have this temporarily when setting up a position. What you say may be true, but this doesn't seem to me like a good example. Not that I see _why_ the player would want to have two kings temporarily, but if so I wouldn't have the view report this state to the model, I'd have the view wait until the player had decided on the final configuration betore saying anything to the model. The model should only deal with legal positions. (Could be that it's not until we start actually playing the game through the GUI that we find the model can't deal with two black queens. But that's not an example either, that would just mean the model is wrong, not allowing every legal position.) >-M- David C. Ullrich From pauljefferson at gmail.com Sat May 3 19:02:29 2008 From: pauljefferson at gmail.com (Paul Jefferson) Date: Sun, 4 May 2008 00:02:29 +0100 Subject: Encoding Text Message-ID: Hi, I'm learning this and I'm making a program which takes RSS feeds and processes them and then outputs them to a HTML file. The problem I have is that some of the RSS feeds contain chachters which I think are outside of the ascii range as when I attempt to write the file containing themI get the follwoign error: File "C:\Users\Paul\Desktop\python\Feed reader\test.py", line 201, in runner(1,"save.ahc") File "C:\Users\Paul\Desktop\python\Feed reader\test.py", line 185, in runner h.write(html[countera]) UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 1147: ordinal not in range(128) For the life of me I can't figure out what I should do to stop this - I tried to change the html by doing a html[countera] = unicode(html[countera]) but it didn't seem to chaneg anything. Any help would be greatly appreciated, Thanks Paul > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Sun May 25 20:16:39 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 25 May 2008 21:16:39 -0300 Subject: Storing a function References: Message-ID: En Sun, 25 May 2008 18:00:12 -0300, Kuros escribi?: > Hi, > Hoping I could get some help with a python question. > > I want to be able to store the code for a single function in a .py file, > such as: > > def test(): > print "Test" > > From within a Python script, I would like to be able to get a handler so I > can do something like: > > handler.test() The "handler" is called a "module" and is created from the .py file by using import... > I want to be able to store the handlers in a blob in a SQLite DB. So store the .py file... > Essentially, I want to store a compiled version of a function. I have tried > using compile() and exec, and while it sort of works, it seems to import the > code into the global namespace. I can do: > > x = compile(file.read(), "", 'exec') > exec x > test() > > and it calls test, but I may have several functions with the same name, all > read from different files. So I need to be able to do handler.test(). If you don't want to store the .py, store the compiled module .pyc If you still want to create and manage your own fake version of modules, use an explicit namespace: ns = {} compiled = compile(...) exec compiled in ns test = ns['test'] test() -- Gabriel Genellina From pball.benetech at gmail.com Sun May 25 23:40:16 2008 From: pball.benetech at gmail.com (pball.benetech at gmail.com) Date: Sun, 25 May 2008 20:40:16 -0700 (PDT) Subject: set partition question References: <7b64328e-d4e0-4ec1-8918-3cab94e2f815@e39g2000hsf.googlegroups.com> Message-ID: <3cf66f61-5a7e-44a2-8cc4-b879269fd98b@y22g2000prd.googlegroups.com> On May 25, 7:46?pm, miller.pau... at gmail.com wrote: > > I think this problem is related to integer partitioning, but it's not > > If, by "integer partitioning," you mean the "subset sum > problem" (given a finite set S of integers, does S contain a subset > which sums up to some given integer k?), then you are right. ?I'm > reasonably sure there's a polynomial reduction from your problem to > the subset sum problem. ?That would make your problem NP-complete. Wow, that's helpful. http://en.wikipedia.org/wiki/Subset_sum clarifies what I'm trying to do. Yes, it probably is NP-complete. Fortunately my use case doesn't require that the process finish, just that it produce a lot. I can exclude trivial cases (e.g., f' = f(S) + s_1 - s_1) with some sort of simplifier. > Like I said, because this looks related to the subset sum problem > (though harder, because you're asking for "all" such functions, for > some rigorous definition of "all," as per the previous sentence), I > suspect it's NP-complete. ?However, there are probably some good > heuristics, such as if s1 has a large intersection with s0, it's > probably a good idea to use s1 in whatever formula you come up with. There are a few real-world constraints which make the problem easier, but only by linear factors, I suspect. More on this below. > Other than that, I don't really have an idea. ?Can you say what the > application of this algorithm would be? ?Knowing the use case might > suggest a better approach. This is a problem in statistical estimation. Given n records made up of k variables, define a cell as the point in the cartesian product of v_1 * v_2 * ... * v_k. I want to apply an estimator on the data in each cell. However, many cells are empty, and others are too sparse to support estimation. One solution is to build lots of valid aggregations, called "strata," for which estimates can be made for chunks of cells. A "valid aggregation" is a sequence of *adjacent* cells (see below) whose data are pooled (by whatever mechanism is relevant to the estimator). The cells are "elements" in my initial problem statement, and the strata are the sets. The constraints I mentioned are on the composition of strata: strata can only contain sequences of adjacent cells, where adjacency is defined for each variable. Two cells are adjacent if they are equal on every variable except one, and on that one and by its definition, they are adjacent. Does this make it easier to understand, or more difficult? thanks -- PB. From gabe at dragffy.com Thu May 15 06:51:27 2008 From: gabe at dragffy.com (Gabriel) Date: Thu, 15 May 2008 10:51:27 +0000 (UTC) Subject: List behaviour References: <905611fd-e5c4-478f-a0bd-417ccc5fe0a1@d77g2000hsb.googlegroups.com> Message-ID: virgilio.it> writes: > >>> tasks = [ [] for x in xrange(6) ] > >>> tasks[0].append(1) > >>> tasks > [[1], [], [], [], [], []] > >>> > Thanks, Bockman From zephyrfalcon!NO_SPAM! at gmail.com Fri May 30 18:58:09 2008 From: zephyrfalcon!NO_SPAM! at gmail.com (Hans Nowak) Date: Fri, 30 May 2008 18:58:09 -0400 Subject: accumulator generators In-Reply-To: <11c56180-f3b1-4ff7-83fe-56dffb1d532b@c19g2000prf.googlegroups.com> References: <6ab4u7F35bmisU1@mid.uni-berlin.de> <11c56180-f3b1-4ff7-83fe-56dffb1d532b@c19g2000prf.googlegroups.com> Message-ID: Cameron wrote: > On May 30, 1:04 pm, "Diez B. Roggisch" wrote: >> Cameron schrieb: >> >> >> >>> I was reading this Paul >>> Graham article and he builds an accumuator generator function in >>> the appendix. His looks like this: >>>
>>> def foo(n):
>>>   s = [n]
>>>   def bar(i):
>>>     s[0] += i
>>>     return s[0]
>>>   return bar
>>> 
>>> Why does that work, but not this: >>>
>>> def foo(n):
>>>   s = n
>>>   def bar(i):
>>>     s += i
>>>     return s
>>>   return bar
>>> 
>> Because python's static analysis infers s as being a variable local to >> bar in the second case - so you can't modify it in the outer scope. >> >> In the future, you may declare >> >> def bar(i): >> nonlocal s >> ... >> >> Diez > > thanks for the response. Just to make sure I understand- Is the reason > it works in the first case because s[0] is undefined at that point (in > bar), and so python looks in the outer scope and finds it there? You can refer to variables in enclosing scopes, just not redefine them in that same scope. That's why in the first example, bar can refer to to s (defined in foo). By assigning to s[0], it modifies the list, which is OK; trying to redefine the name 's' (like the second example tries to do) would not be OK. Also see: http://zephyrfalcon.org/labs/python_pitfalls.html (pitfall #6). -- Hans Nowak (zephyrfalcon at gmail dot com) http://4.flowsnake.org/ From zerty.david at gmail.com Mon May 5 18:43:24 2008 From: zerty.david at gmail.com (David Anderson) Date: Mon, 5 May 2008 19:43:24 -0300 Subject: How to generate binary python? Message-ID: <5dc598e30805051543g243ed4daw119c7579f3ae4095@mail.gmail.com> Hi, i'm comingo from Java and I'm wanting to know what in Python is the equivalent to the file.class in java, I am producing some apps that ar not open source, so I would like to share only the binaries, Both for Windows and for Linux, Can you suggest me anything? Bye -------------- next part -------------- An HTML attachment was scrubbed... URL: From duncan.booth at invalid.invalid Sun May 11 07:57:48 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 11 May 2008 11:57:48 GMT Subject: Python doesn't recognize quote types References: Message-ID: wxPythoner at gmail.com wrote: > There's a thing that bugs me in Python. Look at this... > >>>> print "Testing\" > SyntaxError: EOL while scanning single-quoted string > > > Please focus on the part of the error message that states "while > scanning single-quoted string". How can Python claim it scanned a > single-quoted string when I fed it with a double-quoted string? Is > quote type (single quote and double quote) recognition not implemented > in Python? > Of course it is, but that isn't what is meant here. Python supports single-quoted strings which are delimited by either a single quote or a double quote mark. It also supports triple-quoted strings which are delimited either by three single quotes or three double quotes. The overloaded meaning of 'single' is perhaps unfortunate. From notnorwegian at yahoo.se Mon May 26 16:52:35 2008 From: notnorwegian at yahoo.se (notnorwegian at yahoo.se) Date: Mon, 26 May 2008 13:52:35 -0700 (PDT) Subject: python raycaster, pycaster, where? Message-ID: <1e8fccc5-21d1-4194-95ff-7f57939f184c@c58g2000hsc.googlegroups.com> i tried googling this thing but couldnt find it. i cant find it in pyagme either. anyone know? From Lie.1296 at gmail.com Thu May 15 11:48:06 2008 From: Lie.1296 at gmail.com (Lie) Date: Thu, 15 May 2008 08:48:06 -0700 (PDT) Subject: List behaviour References: Message-ID: <9928a35e-9fa7-4df2-9b5c-ad078ecac566@y18g2000pre.googlegroups.com> On May 15, 5:08?pm, Gabriel wrote: > Hi all > > Just wondering if someone could clarify this behaviour for me, please? > > >>> tasks = [[]]*6 > >>> tasks > > [[], [], [], [], [], []]>>> tasks[0].append(1) > >>> tasks > > [[1], [1], [1], [1], [1], [1]] > > Well what I was expecting to end up with was something like: > ?>>> tasks > [[1], [], [], [], [], []] > > I got this example from page 38 of Beginning Python. > > Regards > > Gabriel As a complementary note, if you want to copy a list (probably a filled one instead of blank ones like here) and wanted to copy a list so that the new copy is a completely separate instance from the old copy, you may use deepcopy (from copy import deepcopy). From mensanator at aol.com Tue May 13 13:10:56 2008 From: mensanator at aol.com (Mensanator) Date: Tue, 13 May 2008 10:10:56 -0700 (PDT) Subject: Fill memeory with endless loop? References: <252c17a9-01a6-4abe-9515-2507e0e50a20@l64g2000hse.googlegroups.com> Message-ID: On May 13, 11:59?am, Filip ?t?dronsk? wrote: > On ?t, kv? 13, 2008 at 06:49:33 +0200, globalrev wrote: > > > if i do something like > > while 1: > > ? ? print "x" > > > will the program ever stop because it runs out of memory? > > No, there is no reason to run out of memory. This will simply > make an everlasting x-printer and there is no need to store > anything (except output buffers, terminal scrollback, etc., > but all of this is temporary and of limited size). In case of > adding elements to a list, the memory usage can, of course, > grow unlimitedly. On linux, if the process eats up too much > memory, it gets killed. I do not know about windows, but > they would probably crash with a BSOD or something of that > sort. Usually, Windows just says "out of memory". From artasis at gmail.com Tue May 6 03:56:52 2008 From: artasis at gmail.com (artasis at gmail.com) Date: Tue, 6 May 2008 00:56:52 -0700 (PDT) Subject: use php in python httpservers References: <36960658-388b-48f9-84d0-38aab3e336f0@s50g2000hsb.googlegroups.com> <3b460037-46ea-4944-9dc1-516666889da2@2g2000hsn.googlegroups.com> Message-ID: <0bb87a79-4862-40e5-91cf-92c2f83d43ac@a1g2000hsb.googlegroups.com> On May 5, 3:48 pm, Jeff wrote: > ctypes? hm..may you explain it? From skanemupp at yahoo.se Fri May 16 08:41:15 2008 From: skanemupp at yahoo.se (globalrev) Date: Fri, 16 May 2008 05:41:15 -0700 (PDT) Subject: free dictionary english - spanish? Message-ID: <9d06558e-dc75-469c-b572-e08095505007@k37g2000hsf.googlegroups.com> i want to write a translationprogram, i have the webapp done already. i need a big free dictionary though. english-spanish/spanish-english seems like the best i know some spanish and thats what also is needed the most i think together with chinese. anywhere you can download one? preferrably easy to parse... From lobais at gmail.com Sat May 3 18:31:01 2008 From: lobais at gmail.com (Thomas Dybdahl Ahle) Date: Sun, 04 May 2008 00:31:01 +0200 Subject: Feature suggestion: sum() ought to use a compensated summation algorithm In-Reply-To: References: <481CB283.107@gmail.com> Message-ID: <1209853861.29405.1.camel@localhost.localdomain> On Sat, 2008-05-03 at 21:37 +0000, Ivan Illarionov wrote: > On Sat, 03 May 2008 20:44:19 +0200, Szabolcs Horv?t wrote: > > > Arnaud Delobelle wrote: > >> > >> sum() works for any sequence of objects with an __add__ method, not > >> just floats! Your algorithm is specific to floats. > > > > This occurred to me also, but then I tried > > > > sum(['abc', 'efg'], '') > > Interesting, I always thought that sum is like shortcut of > reduce(operator.add, ...), but I was mistaken. > > reduce() is more forgiving: > reduce(operator.add, ['abc', 'efg'], '' ) # it works > 'abcefg' Hm, it works for lists: sum(([1], [2]), []) [1, 2] However I find the seccond argument hack ugly. Does the sum way have any performance advantages over the reduce way? -- Best Regards, Med Venlig Hilsen, Thomas From jcd at sdf.lonestar.org Thu May 8 09:46:51 2008 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Thu, 08 May 2008 09:46:51 -0400 Subject: Parsing Email 'References' header. In-Reply-To: <4822F7B6.2000403@gmail.com> References: <4822F7B6.2000403@gmail.com> Message-ID: <1210254412.8236.3.camel@aalcdl07.lib.unc.edu> On Thu, 2008-05-08 at 14:53 +0200, Aspersieman wrote: > Hi > > I have a python script that parses email headers to extract information > from them. I need to get the _last_ messageid in the 'References' field > (http://cr.yp.to/immhf/thread.html) to create a threaded view of these > emails (these messageid's are stored in a database). > > Now, I can easily access the 'References' field using the python 'email' > module, but I need a regular expression to get the last messageid in the > 'References' field. > > Here's what I have so far: > > rx_lastmesgid = re.compile(r"(<.+>$)") > lastmesgid = "".join( filter( rx_lastmesgid.match, parentid ) ) # > parentid's value is > eg:"<1 at mail.gmail.com><2 at mail.gmail.com><3 at mail.gmail.com><4 at mail.gmail.com><5 at mail.gmail.com>" > lastmesgid = "".join( filter( rx_lastmesgid.match, parentid ) ) > > > I need it to return "<5 at mail.gmail.com>" > > Can anyone help? > > Thanks > > Nicol > Forget regular expressions. py>>> lastmesgid = '<' + parentid.split('<')[-1] From bignose+hates-spam at benfinney.id.au Sat May 24 21:42:48 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 25 May 2008 11:42:48 +1000 Subject: Code correctness, and testing strategies References: <18c1e6480805240851t9aa79b4u6f1056a37e011afa@mail.gmail.com> Message-ID: <87ej7r9n1j.fsf@benfinney.id.au> "D'Arcy J.M. Cain" writes: > On Sat, 24 May 2008 17:51:23 +0200 > David wrote: > > If I did start doing some kind of TDD, it would be more of the > > 'smoke test' variety. Call all of the functions with various > > parameters, test some common scenarios, all the 'low hanging > > fruit'. But don't spend a lot of time trying to test all possible > > scenarios and corner cases, 100% coverage, etc, unless I have > > enough time for it. > > Penny wise, pound foolish. Spend the time now or spend the time > later after your client complains. Worse, if you don't spend the time now, you'll end up spending the time later *plus* all the time to find the bug in the first place, all the time to tease its behaviour out from all the interdependent code, all the time to go through more rounds of QA, etc. With BDD, only the time to code the test is spent, so you save all that other time. -- \ "Laugh and the world laughs with you; snore and you sleep | `\ alone." -- Anonymous | _o__) | Ben Finney From dsc at ecs.soton.ac.uk Thu May 29 06:57:47 2008 From: dsc at ecs.soton.ac.uk (Dave Challis) Date: Thu, 29 May 2008 11:57:47 +0100 Subject: Any way to loop through object variables? In-Reply-To: <7695C97A-008C-46A1-A872-1E8F73A560B4@ideadevice.com> References: <483D7A47.3030606@ecs.soton.ac.uk> <483D8614.7000808@islandtraining.com> <7695C97A-008C-46A1-A872-1E8F73A560B4@ideadevice.com> Message-ID: <483E8C2B.4050700@ecs.soton.ac.uk> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Ah thanks, vars(...) was exactly what I was after. I'd come across dir() before, but this returns more than I need. Thanks again, Dave Saju Pillai wrote: > > On 28-May-08, at 9:49 PM, Gary Herron wrote: > >> Dave Challis wrote: >>> Hi, >>> Just wondering if there's a way to iterate through all variables which >>> an object has set? >>> >>> Specifically, I'm using the OptionParser module, which returns an >>> options object, containing all command line options as object variables. >>> I'd like to iterate over these rather than getting at them by name. >>> >>> Cheers, >>> Dave >> >> For this object (and many others), you can get at the attributes with >> the vars(...) builtin. >> It returns a dictionary of attribute names and values. > > > Also dir(object) will get you the list of attributes of that object. > > -srp > >> >> >> Gary Herron >> >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> >> >> -- >> http://mail.python.org/mailman/listinfo/python-list > > -- > http://mail.python.org/mailman/listinfo/python-list - -- ~~~~~~~~~~~~~~~~~o~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ . <>< ( ) Dave Challis ><> ) ) _(__dsc at ecs.soton.ac.uk__________________________________(____(___________ -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.6 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFIPowrv26GZvAVVFERApQfAJ96bFa1wl1sbnDCNmbtf5/tpNqTaQCdHKwf k8+Uv8yXn2Bh5ri6sf5qMmA= =cnfO -----END PGP SIGNATURE----- From nevillednz at gmail.com Fri May 2 18:51:16 2008 From: nevillednz at gmail.com (NevilleDNZ) Date: Fri, 2 May 2008 15:51:16 -0700 (PDT) Subject: RegEx for matching brackets References: <713f6d61-906d-490f-bcbc-befd19e086e5@d19g2000prm.googlegroups.com> Message-ID: <4465e4ed-6a37-48a3-ac0d-f3da316301a4@26g2000hsk.googlegroups.com> On May 2, 11:13 am, George Sakkis wrote: > [1]http://en.wikipedia.org/wiki/Context-free_language > [2]http://en.wikipedia.org/wiki/Regular_language > [3]http://wiki.python.org/moin/LanguageParsing Thanx for the link to these parsers. ANTLR looks interesting. Yoyo: http://www-users.cs.york.ac.uk/~fisher/software/yoyovwg/readme I figured out a way to do it in python. #!/usr/bin/env python2 # -*- coding: utf-8 -*- import re tests=""" { a test BAD { a test } OK { a test } { a test } OK { a test } { this { a test } is a test } OK { a test { this { a test } is a test } missing close BAD a test } { this { a test } is a test } BAD { a test } this { a test } is a test } BAD """.splitlines()[1:] def referee(str): return bool(re.search("OK",test)) def check_open_close(str): try: eval("".join({"{":"[","}":"],"}[c] for c in re.findall( "([{}])|(?: [^{}]+)", str) if c)) except SyntaxError: return False else: return True for test in tests: if check_open_close(test) == referee(test): print "DETECTED:",test else: print "MISSED:",test [linux]$ ./matchall_open_close.py DETECTED: { a test BAD DETECTED: { a test } OK DETECTED: { a test } { a test } OK DETECTED: { a test } { this { a test } is a test } OK DETECTED: { a test { this { a test } is a test } missing close BAD DETECTED: a test } { this { a test } is a test } BAD DETECTED: { a test } this { a test } is a test } BAD It's not exactly what I planned, but as a python one/two-liner it works fine. eval("".join({"{":"[","}":"],"}[c] for c in re.findall( "([{}])|(?: [^{}]+)", str) if c)) ThanX again N From ramu.chandrut at gmail.com Sun May 11 00:23:06 2008 From: ramu.chandrut at gmail.com (ramu) Date: Sat, 10 May 2008 21:23:06 -0700 (PDT) Subject: hai dear Message-ID: <9316f971-57e5-46e2-9d2f-3d522f6e5588@w8g2000prd.googlegroups.com> hai friends, "each day is a new adventure to dream search and discover" www.goodhistory5.blogspot.com From tdelaney at avaya.com Sun May 11 20:05:11 2008 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Mon, 12 May 2008 08:05:11 +0800 Subject: do you fail at FizzBuzz? simple prog test In-Reply-To: Message-ID: Mensanator wrote: > Ok, I agree with 101, but I wouldn't necessarily > say the others were unfortunate. You might be > surprised at how often such fixations discover > bugs, something that I have a gift for. The discovering, the making, or both? ;) Tim Delaney From deets at nospam.web.de Wed May 21 11:10:56 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 21 May 2008 17:10:56 +0200 Subject: C-like assignment expression? References: <68b5d090-9e3b-4e7d-9dda-fc1b099822c2@m73g2000hsh.googlegroups.com> <48340412$0$10773$426a74cc@news.free.fr> <87fxsbzxn4.fsf@mulj.homelinux.net> <7df99fd4-21c9-49a1-ba65-e55794fd4c12@26g2000hsk.googlegroups.com> <75ca6227-435c-46bf-8701-aa326d3533e0@p25g2000hsf.googlegroups.com> <69in0tF33sdj6U2@mid.uni-berlin.de> <07561bbe-0084-467d-b408-a53cfdc8b832@26g2000hsk.googlegroups.com> <69ioqaF32l8buU1@mid.uni-berlin.de> <4540a28e-59b4-4903-8c93-6239eb257c1f@j22g2000hsf.googlegroups.com> Message-ID: <69iscvF33u2peU1@mid.uni-berlin.de> cokofreedom at gmail.com wrote: > On May 21, 4:09 pm, "Diez B. Roggisch" wrote: >> cokofree... at gmail.com wrote: >> >> >> And wastes time. regular expressions can become expensive to match - >> >> doing it twice might be hurtful. >> >> >> Diez >> >> > match = (my_re1.match(line) or my_re2.match(line)) or >> > my_re3.match(line) >> >> How do you know *which* of the three has matched then? >> >> Diez > > Depends if the OP wants to know that... Well, in *general* one wants that. So as a general-purpose solution this is certainly *not* the way to go. Diez From george.sakkis at gmail.com Mon May 5 23:22:49 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 5 May 2008 20:22:49 -0700 (PDT) Subject: word shifts References: Message-ID: <96a41fd1-23ca-482f-9575-5123611ade8a@z72g2000hsb.googlegroups.com> On May 5, 11:02 pm, dave wrote: > On 2008-05-04 01:10:40 -0600, Arnaud Delobelle said: > > > > > dave writes: > > >> Hello, > > >> I made a function that takes a word list (one word per line, text > >> file) and searches for all the words in the list that are 'shifts' of > >> eachother. 'abc' shifted 1 is 'bcd' > > >> Please take a look and tell me if this is a viable solution. > > >> def shift(word, amt): > >> ans = '' > >> for letter in word: > >> ans = ans + chr((ord(letter) - ord('a') + amt) % 26 + ord('a')) > >> return ans > > > In Python, if you want to build a string from lots of parts you can > > use ''.join(parts). I think it is considered more efficient. > > what would be the best way to write a "ans = ans + chr" into a > ''.join(parts) ?? Well if you do it once, that would be simply "ans += chr". Arnaud was referring to the case where you do it in a loop, like in your snippet. A direct translation to use ''.join would be: ans = ''.join(chr((ord(letter) - ord('a') + amt) % 26 + ord('a')) for letter in word) Of course it is simpler and more efficient if you factor out of the loop the subexpressions that don't need to be recomputed: ord_a = ord('a') shift = ord_a - amt ans = ''.join(chr((ord(letter) - shift) % 26 + ord_a) for letter in word) George From mail at timgolden.me.uk Thu May 8 10:06:16 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 08 May 2008 15:06:16 +0100 Subject: PCBuild.sin - Attempt to compile Python using Visual Studio 2008 In-Reply-To: References: Message-ID: <482308D8.3050106@timgolden.me.uk> Gabriel Genellina wrote: > En Thu, 08 May 2008 09:55:36 -0300, Colin J. Williams escribi?: > >> The readme.txt has: >> >> All you need to do is open the workspace >> "pcbuild.sln" in Visual Studio, >> select the desired combination of >> configuration and platform and eventually >> build the solution. Unless you are going >> to debug a problem in the core or >> you are going to create an optimized >> build you want to select "Release" as >> configuration. >> >> Unfortunately, the Express Edition >> (Free) doesn't handle "solution" files. > > Python builds fine with Visual C++ Express Edition. > Select Release, Win32 from the dropdown lists, press F7, > and wait for compilation to complete... Or, if you prefer not to have the long startup time for Visual Studio, simple start a command prompt in python\pcbuild, call the env cmd script and then the build script: C:\temp>cd \work_in_progress C:\work_in_progress>cd python C:\work_in_progress\python>cd PCbuild C:\work_in_progress\python\PCbuild>env Build environments: x86, ia64, amd64, x86_amd64, x86_ia64 Setting environment for using Microsoft Visual Studio 2008 x86 tools. C:\work_in_progress\python\PCbuild>build vcbuild /useenv pcbuild.sln "Release|Win32" Microsoft (R) Visual C++ Project Builder - Command Line Version 9.00.21022 Copyright (C) Microsoft Corporation. All rights reserved. Build started: Project: make_versioninfo, Configuration: Release|Win32 Compiling... TJG From johnroth1 at gmail.com Fri May 23 11:01:52 2008 From: johnroth1 at gmail.com (John Roth) Date: Fri, 23 May 2008 08:01:52 -0700 (PDT) Subject: unittest: Calling tests in liner number order References: Message-ID: <84ff733a-e364-437d-9b5d-d8bb14cc692d@m73g2000hsh.googlegroups.com> On May 23, 3:36 am, Antoon Pardon wrote: > Some time ago I asked whether is would be possible that unittest would > perform the test in order of appearence in the file. > > The answers seemed to be negative. Since I really would like this > behaviour I took the trouble of looking throught the source and > I think I found a minor way to get this behaviour. > > Now my questions are: > > Are other people interested in this behavior? I'm not. If there are any changes in the current behavior I'd much prefer that unittest create a random permutation as a way of flushing out intertest dependencies. > Does the following patch has a chance of being introduced in the > standard python distribution? I certainly hope not! John Roth Python FIT From murder_113 at hotmail.com Sun May 4 19:46:31 2008 From: murder_113 at hotmail.com (Chunky) Date: Mon, 5 May 2008 01:46:31 +0200 Subject: Python Poker Message-ID: hey Jeff Sandys sandysj at juno.com did you manage to get your game up for download it sounds really interesting i love "home made games" -------------- next part -------------- An HTML attachment was scrubbed... URL: From dcoffin at gmail.com Mon May 5 10:14:48 2008 From: dcoffin at gmail.com (dcoffin at gmail.com) Date: Mon, 5 May 2008 07:14:48 -0700 (PDT) Subject: confused about self, why not a reserved word? References: <972f7226-baef-4f94-a8ea-5bec99213540@34g2000hsf.googlegroups.com> <9c619edb-303b-439b-ad65-995fb76f70d5@y38g2000hsy.googlegroups.com> Message-ID: <2e022afa-8593-452f-aa73-1837f339944a@m44g2000hsc.googlegroups.com> > the class-thing seems inside out somehow in python. if im doing > foo.Hello() im already saying that im using the class foo because i > did foo=Foo() before and then still when calling Hello() i am > invisibly passing the class itself a s a parameter by default? > just seems backwards and weird. You're not passing a reference to the class, you're passing a reference to the object. Any object-orientated programming language will be passing methods references to an object; Python just makes that explicit within the method definition. See http://www.python.org/doc/faq/general/#id35 From johnjsal at NOSPAMgmail.com Tue May 20 16:21:04 2008 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 20 May 2008 16:21:04 -0400 Subject: Misuse of list comprehensions? References: <038e4418$0$27258$c3e8da3@news.astraweb.com> <69g2bpF31ttuuU1@mid.uni-berlin.de> <027e4d96$0$25054$c3e8da3@news.astraweb.com> Message-ID: <48333296$0$28632$c3e8da3@news.astraweb.com> "Thomas Bellman" wrote in message news:g0umoh$i0s$1 at news.lysator.liu.se... > "John Salerno" writes: > >> "Diez B. Roggisch" wrote in message >> news:69g2bpF31ttuuU1 at mid.uni-berlin.de... >>> the above code is pretty much of a no-no because it has quadratic >>> runtime >>> behavior. > >> What's that mean, exactly? > However, it actually depends on what your input is. For the > runtime to increase with the square of the input length in your > function, the number of *unique* items on the input must be a > constant fraction of the input length. Whew! Let me re-read your post........... :) From Thomas.Karolski at googlemail.com Fri May 23 15:25:19 2008 From: Thomas.Karolski at googlemail.com (Thomas Karolski) Date: Fri, 23 May 2008 21:25:19 +0200 Subject: Decorator metaclass In-Reply-To: <200805230739.29745.maric@aristote.info> References: <219a475b-c6e3-4128-98bc-d73fd215ce67@w7g2000hsa.googlegroups.com> <200805230739.29745.maric@aristote.info> Message-ID: Turns out the first msg I sent did not reach the list, so I'll just post what I've achieved by now: ------------------------------------------ class DecoratorDummy(object): pass class InheritedDecoratorType(type): def __new__(cls, name, bases, dct): # return if its a class which inherited from Decorator if Decorator in bases: return type.__new__(cls, name, bases, {}) # if its a class which did not directly inherit from Decorator, # then it inherited from a class which has been manipulated using the # Decorator class. # in that case we change the bases of the inheriting class. # We'll split the manipulated class into Decorator and its implementation for b in bases: if type(b) is InheritedDecoratorType: break newbases = [x for x in bases] # remove the manipulated base class newbases.remove(b) # and add the impl of the manipulated base class newbases.append(b._impl_type) # and add the Decorator class newbases.append(Decorator) # now we'll have to make sure the dict of the new class shows the original base class # (which has been removed) as the implementation class dct[b.__name__] = b._impl_type # since we have added a Decorator class, we ought to get rid of it # through the DecoratorType metaclass r = DecoratorType.__new__(cls, name, tuple(newbases), dct) return r class DecoratorType(type): def __new__(cls, name, bases, dct): # if the first class is DecoratorDummy, then we're handling the # Decorator class, which is not supposed to be modified if bases[0] is DecoratorDummy: return type.__new__(cls, name, bases, {}) # if one of the bases is the Decorator class b = [x for x in bases] if Decorator in b: # create a new impl type which inherits from every but the decorator class b.remove(Decorator) impl_type = type('%sImpl'%name, tuple(b), dict(dct)) # make the returned type no longer a DecoratorType, but rather a normal type # Types which inherit from a class which inherited from Decorator, will thus # *not* be put through this metaclass. #dectype = type.__new__(type, name, tuple(b), {'_impl_type' : impl_type }) dectype = type.__new__(InheritedDecoratorType, name, tuple(b), {'_impl_type' : impl_type }) # update the old class to implement this implementation def __init__(self, *args, **dargs): new_impl = impl_type(*args, **dargs) super(dectype._impl_type, new_impl).__init__(*args, **dargs) object.__setattr__(self, '_impl', new_impl) def decorator(self): return object.__getattribute__(self, '_impl') def __getattribute__(self, attr): if attr=="decorator": return object.__getattribute__(self, 'decorator') # if we have a specified method inside the decorator().__decorate__ var, # then call decorator().attr(), otherwise proxy the call d = object.__getattribute__(self, 'decorator')() if attr in d.__decorate__: return getattr(d, attr) return getattr(d.getParent(), attr) dectype.__init__ = __init__ dectype.decorator = decorator dectype.__getattribute__ = __getattribute__ return dectype class Decorator(DecoratorDummy): __metaclass__ = DecoratorType class Window(object): def __init__(self, parent): print "Window::__init__(%s)"%self self._parent = parent def setParent(self, parent): self._parent = parent def getParent(self): return self._parent class Textarea(Window): def draw(self): print "Textarea::draw()" class HBar(Decorator, Window): __decorate__ = ["draw"] def __init__(self, parent): print "HBar::__init__(%s)"%self Window.__init__(self, parent=parent) self._progress = 0.0 def setProgress(self, p): print "setting progress to %s"%p self._progress= p def getProgress(self): return self._progress def draw(self): self.getParent().draw() print "HBar::draw()" class HBarTrue(HBar): # HBar's bases: Window (Decorator removed by metaclass) # HBar's methods: __init__, decorator, __getattribute__ # everything else is inside decorator() # we thus need to make calls to self within HBarTrue, # calls to self.decorator() - this is not possible # Otherwise we could also let HBarTrue inherit from HBarImpl, # however then a call to HBar.__init__ would be invalid inside # HBarTrue.__init__ unless we specify HBar internally as being HBarImpl # - this however is not possible # if we inherit from HBarImpl, then we no longer have the decorator # functionality. We'd thus have to include Decorator in the list of bases # Inherit normally from HBar and not Decorator. # Move all methods from HBarTrue to HBar.decorator() # create a custom __init__ method which calls HBar.decorator().__init__ def __init__(self, parent): print "HBarTrue::__init__(%s)"%self for each in dir(self): print each HBar.__init__(self, parent) self.setProgress(0.0) myTextarea = Textarea("main.parent") myTextarea.draw() myTextarea = HBarTrue(myTextarea) myTextarea.draw() myTextarea.decorator().setProgress(100.0) ------------------------------------------ The code above works only if I don't inherit from HBar like I did. As it is now, the HBar class, which inherits from Decorator and Window, is going to be manipulated by the metaclass. During this process the Decorator base-class is removed, the implementation of HBar moved into _impl_type and the methods __init__, decorator and __getattribute__ are being assigned to the new class. Everything works so far if I don't subclass HBar. If I do subclass HBar, then the subclass goes through the second metaclass (InheritedDecoratorType). In there I replace the base class HBar with HBarImpl and Decorator. This way the subclass inherits the implementation of HBar and through the Decorator class then the subclass goes through the same metaclass magic as HBar in the first step. Of course however, since HBarTrue is no longer a subclass of HBar (since that baseclass has been removed), the HBar.__init__ method won't accept the non HBar self parameter. Now the reason why I'm using decorators, is because I want to be ably to add the functionality dynamicly - without the need of construction classes for the different possibilities. Composite pattern does not help in this case, since I lose the ability to choose in what order I call the decorator's and the decorated's methods. I'll just keep trying. Any input greatly appreciated. Regards, Thomas K. From VBG at extnet.net Thu May 29 16:26:52 2008 From: VBG at extnet.net (Hung Well (no comma)) Date: Thu, 29 May 2008 15:26:52 -0500 Subject: so funny... References: <620361d6-5eb2-482a-8e28-4b2e9c906ece@26g2000hsk.googlegroups.com> Message-ID: "John" wrote in message news:620361d6-5eb2-482a-8e28-4b2e9c906ece at 26g2000hsk.googlegroups.com... > http://sitscape.com/topic/funny > > Just keep hit the "Surprise->" button there for amazing fun. > Click on "channel" will show you other topics, lots of fun! You tickle easy. --WH From bruno.desthuilliers at gmail.com Mon May 19 16:42:16 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Mon, 19 May 2008 13:42:16 -0700 (PDT) Subject: Using Python for programming algorithms References: <48315082$0$24599$426a74cc@news.free.fr> <62884fc6-6c74-4477-91de-7b7689b5fa75@m44g2000hsc.googlegroups.com> Message-ID: <52b543da-90f3-4624-a11c-553159832764@l42g2000hsc.googlegroups.com> On 19 mai, 20:07, Vicent Giner wrote: > On May 19, 6:11 pm, Henrique Dante de Almeida > wrote: > (snip) > > The situation would be simpler if there were good well-known toolkits > > for optimization in python (like numpy for matrix operations), but > > that's not the case. > > Are there such toolkits in other languages? I am not sure they exist > in C, for example. Well... They do - they are called 'C compilers' !-) As Roel Schroven mentioned - and he is at least partially right on this point - C has been designed to make optimizing C compiler not to hairy to write. > By the way, is it possible (and easy) to call a C function from a > Python program?? Possible, yes, indeed. Easy depends on your definition of easiness, but going down to C for computation-heavy performance-critical parts of a program or library is not that uncommon. From skanemupp at yahoo.se Tue May 13 14:41:58 2008 From: skanemupp at yahoo.se (globalrev) Date: Tue, 13 May 2008 11:41:58 -0700 (PDT) Subject: variable scope question? Message-ID: <0b0ffc2e-4a41-4399-b1bf-68b80ea00605@k13g2000hse.googlegroups.com> http://mail.python.org/pipermail/python-list/2003-October/233435.html why isnt it printing a in the second(second here, last one in OP) example before complaining? def run(): a = 1 def run2(b): a = b print a run2(2) print a run() def run(): a = 1 def run2(b): print a a = b run2(2) print a run() From GustavoTabares at gmail.com Mon May 12 10:41:19 2008 From: GustavoTabares at gmail.com (GustavoTabares at gmail.com) Date: Mon, 12 May 2008 07:41:19 -0700 (PDT) Subject: Removing option from optparse Message-ID: Hello, I'm trying to figure out if the following is a bug or if I'm using the remove_option in the wrong way. #!/usr/bin/env python import optparse parser = optparse.OptionParser() parser.add_option("--test", help="This is a test option") parser.remove_option('--test') print parser.parse_args() this will output: (, []) If you execute the --help on the file above you will not see --test as expected. I'm curious as to why parse_args is still returning this as an option. Thanks, Gustavo From kamhung.soh at gmail.com Thu May 1 02:00:33 2008 From: kamhung.soh at gmail.com (Kam-Hung Soh) Date: Thu, 01 May 2008 16:00:33 +1000 Subject: sed to python: replace Q References: <48180348$0$34534$742ec2ed@news.sonic.net> Message-ID: On Wed, 30 Apr 2008 17:12:15 +1000, Kam-Hung Soh wrote: > On Wed, 30 Apr 2008 15:27:36 +1000, Raymond > wrote: > >> For some reason I'm unable to grok Python's string.replace() function. >> Just trying to parse a simple IP address, wrapped in square brackets, >> from Postfix logs. In sed this is straightforward given: >> >> line = "date process text [ip] more text" >> >> sed -e 's/^.*\[//' -e 's/].*$//' >> >> yet the following Python code does nothing: >> >> line = line.replace('^.*\[', '', 1) >> line = line.replace('].*$', '') > > str.replace() doesn't support regular expressions. > > Try: > > import re > p = re.compile("^.*\[") > q = re.compile("].*$") > q.sub('',p.sub('', line)) > Another approach is to use the split() function in "re" module. import re re.split("[\[\]]", line)[1] See http://docs.python.org/lib/node46.html -- Kam-Hung Soh Software Salariman From netizen at gmx.de Fri May 23 10:59:17 2008 From: netizen at gmx.de (Michael Fesser) Date: Fri, 23 May 2008 16:59:17 +0200 Subject: php vs python References: <5l%Yj.77$mz3.53@fe101.usenetserver.com> <48369413$0$25059$607ed4bc@cv.net> <4836ac7b$0$14350$e4fe514c@news.xs4all.nl> <5tdd34tqp80s2va8h3ntpu04gj9knad393@4ax.com> Message-ID: <4jmd34h5cjigp50uvk0p14td5sjqiokgj2@4ax.com> .oO(Duncan Booth) >Michael Fesser wrote: > >> The only little problem is that PHP doesn't have native Unicode >> support yet, which will change with PHP 6. But of course you can still >> use UTF-8 without any trouble, I do it all the time. You just have to >> keep in mind that many string functions still work on bytes, not on >> characters, but this can almost always be solved with the Multibyte >> extension. Apart from that there's no problem with PHP and UTF-8. It's >> also easily possible to convert between various encodings using the >> iconv extension. >> >As I remember it the problem was that the data was stored in a database >in latin-1 but the HTML page had to be in utf-8 (because the rest of the >server and therefore all the page skins were already in utf-8). In >python that would be a trivial conversion but I was told that in PHP it >wasn't. It would have been trivial in PHP as well, assuming the DB was MySQL, which could have done this conversion automatically when sending the data to the script. >But one small example isn't really the point. It's that the whole way >Python works seems *to me* to make sense and (mostly) fits together >cleanly and consistently. YMMV Fair enough. The nature of PHP as being a grown language has its advantages, but also a lot of drawbacks, which are hard to solve. Micha From bruno.42.desthuilliers at websiteburo.invalid Thu May 15 03:28:33 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 15 May 2008 09:28:33 +0200 Subject: named tuple mutability In-Reply-To: <873aokzgs9.fsf@benfinney.id.au> References: <844dc74c-1812-4599-934e-8fb63878b5cf@p25g2000hsf.googlegroups.com> <873aokzgs9.fsf@benfinney.id.au> Message-ID: <482be615$0$10798$426a34cc@news.free.fr> Ben Finney a ?crit : > "bruno.desthuilliers at gmail.com" writes: > >> On 14 mai, 18:20, castiro... at gmail.com wrote: >>> I'm concerned over the future of Python. Should tuples be named? >> Obviously not, unless they should. > > Clearly they should, unless not. > May we agree to disagree here - unless we don't ? From skanemupp at yahoo.se Mon May 5 07:57:25 2008 From: skanemupp at yahoo.se (globalrev) Date: Mon, 5 May 2008 04:57:25 -0700 (PDT) Subject: confused about self, why not a reserved word? Message-ID: <972f7226-baef-4f94-a8ea-5bec99213540@34g2000hsf.googlegroups.com> class Foo(object): def Hello(self): print "hi" object is purple, ie some sort of reserved word. why is self in black(ie a normal word) when it has special powers. replacing it with sel for example will cause an error when calling Hello. From efurman at admailinc.com Mon May 19 13:42:58 2008 From: efurman at admailinc.com (Ethan Furman) Date: Mon, 19 May 2008 09:42:58 -0800 Subject: Dbase / foxpro files In-Reply-To: <1badfadf-f47f-4502-a7ec-fafd78eb5104@d1g2000hsg.googlegroups.com> References: <1badfadf-f47f-4502-a7ec-fafd78eb5104@d1g2000hsg.googlegroups.com> Message-ID: <4831BC22.1040809@admailinc.com> Johny wrote: >Thanks for your reply.Is it possible to delete a record by using the >module? >Thanks >L> >-- >http://mail.python.org/mailman/listinfo/python-list > > It is possible with mine. To clarify an earlier post, my module is for dBase III and VFP 6.0 files only (those were the only two I needed :). Hope this helps. -- Ethan From darcy at druid.net Thu May 8 16:14:37 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Thu, 8 May 2008 16:14:37 -0400 Subject: Running a python code periodically In-Reply-To: References: Message-ID: <20080508161437.531ab1d9.darcy@druid.net> On Thu, 8 May 2008 11:02:14 -0500 "Maryam Saeedi" wrote: > I was wondering if you know how can I run a python code once every five > minutes for a period of time either using python or some other program like > a bash script. Use cron. > I have asked this question before and some of you answered me but I still > have problem. Most of the answers was to use cron and crontab which works on > my computer but not if I want to do it on department's computer since I do > not have permission to change those files. Is there any other way which does > not need administrator permission? Same answer. Download the source for cron from somewhere (NetBSD, FreeBSD, Linux, whatever), compile it and run it yourself. You can't run setuid but if you want something that acts like cron, cron fits the bill. Ain't open source wonderful? :-) -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From skanemupp at yahoo.se Mon May 5 09:37:35 2008 From: skanemupp at yahoo.se (globalrev) Date: Mon, 5 May 2008 06:37:35 -0700 (PDT) Subject: confused about self, why not a reserved word? References: <972f7226-baef-4f94-a8ea-5bec99213540@34g2000hsf.googlegroups.com> Message-ID: <9c619edb-303b-439b-ad65-995fb76f70d5@y38g2000hsy.googlegroups.com> sorry i noticed now a little error, i was playing around a lot and saw that on the sel-example i had then called foo.hello() instead of foo.Hello(). but it was an informing error now i egt it. was wondering about self anyway so thanks for clearing it up. but it still is a bit confusing that u can pass with any word. wouldnt: class Foo(object): def Hello(): print "hi" make more sense? the class-thing seems inside out somehow in python. if im doing foo.Hello() im already saying that im using the class foo because i did foo=Foo() before and then still when calling Hello() i am invisibly passing the class itself a s a parameter by default? just seems backwards and weird. From gagsl-py2 at yahoo.com.ar Fri May 9 02:55:27 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 09 May 2008 03:55:27 -0300 Subject: Bug in email.utils, parseaddr References: Message-ID: En Fri, 09 May 2008 02:55:46 -0300, Roopesh escribi?: > I tried using parseaddr of email.utils, but it gave the following > result when the name had a comma inside. > >>>> e = 'K,Vishal ' >>>> from email.utils import parseaddr >>>> parseaddr(e) > ('', 'K') That's an invalid address. A comma "," is a special character and it cannot happen inside an atom, it must be quoted. See section 3.4 in RFC2822 -- Gabriel Genellina From zaphotbretzel at yahoo.com Mon May 19 11:06:47 2008 From: zaphotbretzel at yahoo.com (zaphotbretzel at yahoo.com) Date: Mon, 19 May 2008 08:06:47 -0700 (PDT) Subject: installing MySQLdb module References: <80f805f0-6829-4da3-bfb4-79875bb16114@a22g2000hsc.googlegroups.com> Message-ID: <75c38402-41a5-480b-b65d-463c8cc43fc4@25g2000hsx.googlegroups.com> Hi Rafael, > I googled around and people say you need the "-dev" package of mysql > in order to have the C headers...where can you download this for mac > os? > PS I am running XAMPP (http://www.keitr.com/tutorials/xampp) if that > changes anything Ok, here my solution to the problem (Mac OS X 10.4, Xampp and MySQLdb) 1) install Xcode from apple (for gcc, need free account for that, http://developer.apple.com/) 2) get Mac binary tar from MySQL (http://dev.mysql.com/downloads/mysql/ 5.0.html#macosx) 3) edit site.cfg (mysql_config = /Applications/xampp/xamppfiles/bin/ mysql_config) 4) copy include dir from MySQL package to /Applications/xampp/ xamppfiles/include/mysql I bet downloading the same version from MySQL as installed from Xampp could help. And yes, you only need the include folder from the MySQL binary package, do not install it. Peace, Zaphot From gagsl-py2 at yahoo.com.ar Fri May 2 17:23:40 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 02 May 2008 18:23:40 -0300 Subject: how to pass C++ object to another C++ function via Python function References: <1810b155-5598-4f17-a8e9-e4aa848db5de@i36g2000prf.googlegroups.com> <136a9a29-1193-4ebc-89de-7fa6b9c7dfd5@r9g2000prd.googlegroups.com> Message-ID: En Fri, 02 May 2008 00:26:38 -0300, grbgooglefan escribi?: > On Apr 22, 7:54?am, "Gabriel Genellina" > wrote: >> >> If you have a C function that receives a PyCObject, just include the ? >> relevant headers (cobject.h) and you can retrieve the original pointer ? >> using PyCObject_AsVoidPtr: >> > > This works. But only once, means if I try to use this object second > time in Python function it causes crash. > > What I am doing in my program is that I am putting STL map in a > structure & passing that structure as object to a Python function > alongwith other agurments of that Python function. This briefly as > below: > > // In pyinterface.h file:--- > typedef hash_map Elements; > typedef hash_map > PerExchGroupsElementsTable; > typedef struct capsule { > PerExchGroupsElementsTable* refgrps; > } *pcapsule; > > // In pyinterface.cpp file:--- > numvars = // value set depending on number of variables of that python > function > PyObject *pTuple = PyTuple_New(numvars); > > // Set variables as below: > for(nCtr = 0; nCtr < numvars; nCtr++){ > slot = prul->pVarLst[nCtr].slot; > ndtyp = ordvars[slot].dtype; > switch(ndtyp){ > case(INT_T): > PyTuple_SetItem(pTuple,nCtr,PyInt_FromLong(ordvars[slot].nvalue)); > break; > case(FLOAT_T): > PyTuple_SetItem(pTuple,nCtr,PyFloat_FromDouble(ordvars[slot].fvalue)); > break; > case(STRING_T): > PyTuple_SetItem(pTuple,nCtr,PyString_FromString(ordvars[slot].cvalue)); > break; > default: > printf("\nUnknown data type [%d] for %s\n",ndtyp,prul- >> pVarLst[nCtr].var); > bUnknownDataType = true; > break; > } > if(bUnknownDataType){ > ret = -1; > break; > } > } > > // Then set the C++ object as below: > if(ret == 0){ > capsule grpob; > if(pGroups){ > grpob.refgrps = pGroups; // pGroups is pointer to > PerExchGroupsElementsTable map & is global. > int ret = PyTuple_SetItem(pTuple, > (numvars-1),PyCObject_FromVoidPtr((void *)&grpob, NULL)); > } This look suspicious - what if !pGroups? You can't leave a tuple item uninitialized - if you create a tuple with PyTuple_New(3), then you have to fill the 3 items. And beware of that local variable grpob - you're using a pointer to it, and it won't be valid when execution goes out of this block. You must ensure that nobody stores a reference to it. And you should decref the tuple even if this block isn't executed. > PyObject *ptr = PyObject_GetAttrString(_pPyModule,fname); > if(PyErr_Occurred() || *ptr == NULL){ > printf("PyObject_GetAttrString failed:%s",fname); > return; > } > if(!PyCallable_Check(*ptr)){ > printf("%s not a callable Python code\n",fname); > Py_XDECREF(*ptr); > *ptr = NULL; > return; > } All those *ptr should be ptr (the compiler should issue a lot of warnings, I presume?) > What happens is that when Python function TSE581 gets called from my C > Program via PyObject_CallObject (as shown at top of this post), co1 > function works fine & can access the map pointer properly. > But when next function like1 gets called, crash happens. > > My queries are & things on which I need help are: > 1) Is there anything wrong I am doing when I am passing the C-Object > from my C++ code->Python -> C++ code again? I see nothing obviously wrong, except the above notes. If you get warnings from the C++ compiler, try to fix all of them. > 2) Am I missing to increase or decrease the reference count somewhere. In case of error you exit early but without releasing some existing objects. (Sometimes a goto statement *is* the right thing to do) > 3) I dont want map pointer to be ever freed because it is Process > level data structure & requried at every execution of these Python > functions. How do I avoid its cleanup when it gets passed to Python & > Python cleans up those objects. Python will do nothing with the pointer inside a PyCObject - unless you want to, and pass a cleanup function as the second argument to the PyCObject constructor. -- Gabriel Genellina From dullrich at sprynet.com Tue May 27 11:59:24 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Tue, 27 May 2008 10:59:24 -0500 Subject: decorators when? References: <3m0o34hbb0c6rpr6ec0qh3hlkaagt8pfi5@4ax.com> <6a2edeF356g4eU1@mid.uni-berlin.de> Message-ID: In article , "Gabriel Genellina" wrote: > En Tue, 27 May 2008 11:52:25 -0300, David C. Ullrich > escribi?: > > > Oh. Never mind the details, let's just say that having 2.3 and > > 2.5 installed on the same machine can lead to confusion > > about exactly which one you're running a script under. > > Duh. > > You might change the prompt; put these lines in your sitecustomize.py (or > create it if you don't have one): > > import sys > sys.ps1 = 'p23> ' > sys.ps2 = ' ... ' Thanks. I guess I should have included details that I thought would be of no interest to save people time with replies. The problem is that on the Mac in question Terminal thinks python is 2.5 (as does Idle) while when I double-click on a file in Finder it runs under python 2.3. In particular it never happens that I'm running an interactive session under 2.3. (No, I'm not saying that's a good setup - it's a mess. The other Mac, at the office, is not such a mess, but I never could get things like Idle to work under the Apple Python...) > > Sorry. Thanks. I don't suppose that decorators are available > > from __future__ somehow in 2.3? > > No. But a decorator is only syntax sugar. > > @decorator > def f(): > ... > > is the same thing as: > > def f(): > ... > f = decorator(f) > > (just more convenient) -- David C. Ullrich From jamesd at echeque.com Thu May 22 05:48:52 2008 From: jamesd at echeque.com (James A. Donald) Date: Thu, 22 May 2008 19:48:52 +1000 Subject: writing python extensions in assembly References: Message-ID: On Fri, 16 May 2008 11:21:39 -0400, "inhahe" wrote: > They say that the C++ optimizer can usually optimize > better than a person coding in assembler by hand can, > but I just can't believe that, at least for me, > because when I code in assembler, if one hand compiles C++ into assembler, the result will doubtless be crap compared to what the compiler will generate. If, however, one expresses one's algorithm in assembler, rather than in C++, the result may well be dramatically more efficient than expressing one's algorithm in C++ and the compiler translating it into assembler. A factor of ten is quite common. -- ---------------------- We have the right to defend ourselves and our property, because of the kind of animals that we are. True law derives from this right, not from the arbitrary power of the omnipotent state. http://www.jim.com/ James A. Donald From krumblebunk at gmail.com Tue May 6 11:20:37 2008 From: krumblebunk at gmail.com (krumblebunk at gmail.com) Date: Tue, 6 May 2008 08:20:37 -0700 (PDT) Subject: Reversing a dict? Message-ID: <6e3fdb8c-687f-42b6-b544-19c88950cc00@q1g2000prf.googlegroups.com> Hi - further to my earlier query regarding partial matches (which with all your replies enabled me to advance my understanding, thanks), I now need to reverse a dict. I know how to reverse a list (with the reverse method - very handy), but it doesn't seem possible to reverse a dict. I suspect what I need to do is somehow go from: thelist=list(thedict) thelist.reverse() thedict=dict(thelist) Does anyone know how to convert / or reverse a dict? thanks kb. From duncan.booth at invalid.invalid Sun May 11 15:50:34 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 11 May 2008 19:50:34 GMT Subject: File Creation Not Working In A Thread Class? References: <7qGVj.32505$KJ1.18416@newsfe19.lga> Message-ID: bc90021 wrote: > The error message was at the top of the thread (am I incapable of > posting it, or are you incapable of following a thread?), but here it > is again: > > IOError: [Errno 2] no such file u'tempfileName' So which was it? At the top of the thread you said it was: IOError: [Errno 2] no such file u'fileName' How about posting the exact error message you got, including all of the traceback and the complete original code: even when you posted "Here's the thread class" you actually posted a modified version of your thread class (with sarky comments added even if nothing else was changed). If you post complete code and the full traceback then you'll probably get a quick and accurate response telling you what the problem is. If you continue to paraphrase and post bits and pieces you'll continue to get random guesses. From bignose+hates-spam at benfinney.id.au Sun May 11 23:46:07 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 12 May 2008 13:46:07 +1000 Subject: anonymous assignment References: <1XNVj.133805$Cj7.33096@pd7urf2no> <7xmymwuu25.fsf@ruckus.brouhaha.com> Message-ID: <87zlqw6v7k.fsf@benfinney.id.au> Paul Rubin writes: > Yves Dorfsman writes: > > I know you can't assign anything to None, but I'm sure you get what I > > mean, a special keyword that means I don't care about this value. Snap. This topic was raised today in another thread. > You can just use a variable name than you ignore. It's traditional > to use _ but it's not a special keyword, it's just a another > variable name: > > y, _, d, _, _, _, _, _, _ = time.localtime() It's a terrible name for that purpose, since it doesn't indicate the intention explicitly, and it's already overloaded in meaning by a pre-existing convention (ref. the 'gettext' module in Python and many other languages). Far better to use the name 'unused' as suggested by Carl Banks earlier today. (good sigmonster, have a cookie) -- \ "Choose mnemonic identifiers. If you can't remember what | `\ mnemonic means, you've got a problem." ?Larry Wall | _o__) | Ben Finney From stefan_ml at behnel.de Fri May 9 11:50:14 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 09 May 2008 17:50:14 +0200 Subject: A question about python and xml In-Reply-To: <0507ffd8-6842-4546-a635-414fabf481fb@y21g2000hsf.googlegroups.com> References: <0507ffd8-6842-4546-a635-414fabf481fb@y21g2000hsf.googlegroups.com> Message-ID: <482472B6.603@behnel.de> Holden wrote: > I want to make a web site that uses the python programming > language which I am VERY new at. This website would store simple data > such as names in a form. At first I wanted to use mysql to store the > data but I want to export the data using xml. > > So say if a user logged in they would be able to store there basic > information in an xml file and download it whenever. Is that possible > using XML and Python. I am sorry if this post doesn't make much sense > but any advice would be greatly appreciated. You can also e-mail me if > you need further information or clarification. Generating XML from your data shouldn't be too hard once it's in a database. The harder part is getting it in there through a web interface. I would look at a dedicated web framework like Django first: http://www.djangoproject.com/ Stefan From skanemupp at yahoo.se Fri May 16 09:04:16 2008 From: skanemupp at yahoo.se (globalrev) Date: Fri, 16 May 2008 06:04:16 -0700 (PDT) Subject: class problem, NoneType obj has no attribute References: <10bbf997-3520-4920-b225-8685b98d9079@59g2000hsb.googlegroups.com> Message-ID: <9355f9ed-032c-44e1-bf8d-183092e5b201@e53g2000hsa.googlegroups.com> On 16 Maj, 13:54, Peter Otten <__pete... at web.de> wrote: > Christian Heimes wrote: > > globalrev schrieb: > >> cust1 = customer.__init__('12',['1','435','2332']) > > > cust1 = customer('12',['1','435','2332']) > > ... and before that > > from customer import customer > > Peter why do i have to write that? if i do import customer im importing everything no? but youre right it doesnt work unless i do, i just dont get why. From arnodel at googlemail.com Thu May 15 02:09:31 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Thu, 15 May 2008 07:09:31 +0100 Subject: Class Methods Vs Any Other Callable References: <98b4a67c-9ec7-407c-8c80-06488bd48a68@e39g2000hsf.googlegroups.com> <690ap7F2u0ftdU1@mid.uni-berlin.de> <238061d6-9423-44c1-90b2-cc09f392db9b@p25g2000hsf.googlegroups.com> <2851a281-d3f2-46c5-8afe-a5dcd6fa31a6@59g2000hsb.googlegroups.com> Message-ID: "bruno.desthuilliers at gmail.com" writes: > On 14 mai, 22:44, Arnaud Delobelle wrote: >> "bruno.desthuilli... at gmail.com" writes: >> > On 14 mai, 19:45, Arnaud Delobelle wrote: >> >> __new__ is a static method! >> >> > __new__ is a special-cased staticmethod that 1/ must not be declared >> > as such and 2/ takes the class object as first args. As far as I'm >> > concerned, it's semantically a classmethod. >> >> It's a static method! > > Sorry Arnaud, I probably didn't made it clear enough : I do know it is > a staticmethod object. What I say is that > 1/ it's special-cased since you don't *explicitely* declare it as a > staticmethod > 2/ it behaves just like a classmethod, since it takes the class as > first argument. > > IOW, I'm talking about semantic, not implementation. ... and I was being facetious, not serious :) -- Arnaud From kyosohma at gmail.com Fri May 16 09:22:01 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 16 May 2008 06:22:01 -0700 (PDT) Subject: Problem creating a shorcut References: <2715b502-d636-4541-ac0e-05697f02b2ae@m44g2000hsc.googlegroups.com> <577a0ed4-afe9-4bd2-8ef9-74d3051bf27b@a1g2000hsb.googlegroups.com> Message-ID: On May 16, 8:09?am, Larry Bates wrote: > Mike Driscoll wrote: > > On May 15, 2:03 pm, Larry Bates wrote: > >> Mike Driscoll wrote: > >>> Hi, > >>> I've had this niggling issue from time to time. I want to create a > >>> shortcut on the user's desktop to a website that specifically loads > >>> Firefox even if Firefox is not the default browser. > >>> I usually use COM as it allows very specific settings of the shortcut, > >>> such as the Working Directory and the Target Path. However, the > >>> following will not work for some reason: > >>> > >>> import win32com.client > >>> import winshell > >>> shell = win32com.client.Dispatch('WScript.Shell') > >>> userDesktop = winshell.desktop() > >>> shortcut = shell.CreateShortCut(userDesktop + '\\MyShortcut.lnk') > >>> shortcut.Targetpath = r'"C:\Program Files\Mozilla Firefox\firefox.exe" > >>> https:\www.myCompanyWebsite.com\auth\preauth.php' > >>> shortcut.WorkingDirectory = r'C:\Program Files\Mozilla > >>> Firefox' > >>> shortcut.save() > >>> > >>> This creates the following target path (which doesn't work): > >>> "C:\"C:\Program Files\Mozilla Firefox\firefox.exe" https: > >>> \www.myCompanyWebsite.com\auth\preauth.php" > >>> If I leave the website off, it works. If I leave the path to Firefox > >>> out, it works too. Is there another method I can use other than > >>> creating the shortcut by hand and using the shutil module? > >>> Thank you for any ideas. > >>> Mike > >> Either you copied wrong or the problem is: > > >> "C:\"C:\Program Files... > > >> Note the C:\ is specified twice in the string. ?I think it should read: > > >> ?> "C:\Program Files\Mozilla Firefox\firefox.exe" https: > >> ?> \www.myCompanyWebsite.com\auth\preauth.php" > > >> -Larry > > > Yeah, I know that it's in there twice and that that is the problem. > > But I'm not causing that extra C:\. I run it exactly as above and that > > is what I get for the output. I think it's the COM object. Maybe I > > better just re-post this to the PyWin32 list... > > > Thanks, > > > Mike > > I use Inno Setup on most of my applications and use it to create my desktop, > quicklaunch and Start shortcuts. ?Would that be an option for you? > > -Larry I use Inno too for my applications. However, in this case, I have to create the shortcut as part of the login process based on what group the user is in. Chris's solution worked for my needs and I think Gabriel's will work too, if I figure it out. Mike From arnodel at googlemail.com Mon May 12 08:59:58 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 12 May 2008 05:59:58 -0700 (PDT) Subject: do you fail at FizzBuzz? simple prog test References: <39709320-66e1-40e9-a351-c769c9a94585@x41g2000hsb.googlegroups.com> <48283881@news.mel.dft.com.au> Message-ID: On May 12, 1:30?pm, John Machin wrote: > Duncan Booth wrote: [...] > > I think the variant I came up with is a bit clearer: > > > for i in range(1,101): > > ? ?print '%s%s' % ('' if i%3 else 'Fizz', '' if i%5 else 'Buzz') or i > > More than a bit clearer, IMO. How about > ? ? ?print ('' if i%3 else 'Fizz') + ('' if i%5 else 'Buzz') or i > (or perhaps > ? ? ?print (('' if i%3 else 'Fizz') + ('' if i%5 else 'Buzz')) or i > to save looking up the precedence rules) ? Stuff clarity! How about for i in xrange(1, 101): print 'FizzBuzz'[4*(i%3>0):4+4*(i%5<1)] or i -- Arnaud From wizzardx at gmail.com Sat May 3 15:56:38 2008 From: wizzardx at gmail.com (David) Date: Sat, 3 May 2008 21:56:38 +0200 Subject: State machine Example in Python In-Reply-To: <18c1e6480805031254j7647d5a4rfa4aeb4b5613298f@mail.gmail.com> References: <18c1e6480805031254j7647d5a4rfa4aeb4b5613298f@mail.gmail.com> Message-ID: <18c1e6480805031256i597eaa1jb9dbcffecee9c169@mail.gmail.com> > There's plenty of results. Be more specific if you can't get what you > want from Google. You'll probably find what you're looking for here: http://wiki.python.org/moin/FiniteStateMachine David. From alokkat at gmail.com Wed May 28 09:31:22 2008 From: alokkat at gmail.com (Alok Kumar) Date: Wed, 28 May 2008 09:31:22 -0400 Subject: Struct usages in Python In-Reply-To: References: Message-ID: I am getting following error when tried as you suggested. self.event = [] #Create an empty list, bind to the name "event" under the "self" namespace self.event.append(Event()) #Create an event object and append to the end of the list *class Event(): ^ SyntaxError: invalid syntax* On Wed, May 28, 2008 at 1:07 AM, Patrick Mullen wrote: > I don't know if this will go through (my posts seem to have become blocked > lately), but I'll give it a shot anyhow. > > You seem to be under a misconception that a python list is similar to a > list in say, Java or other languages that have a rigid idea of variables and > types. In python, a list is a list of objects - any type of object can be > stored in a list. Just as you don't declare types for variables, you also > don't declare types for lists. Here is your modified code: > > class Event(): > def __init__(self, cameraEventType="", zone=99, setDay="",setTime ="", > clrTime=""): > self.cameraEventType = cameraEventType > self.zone = zone > self.setDay = setDay > self.setTime = setTime > self.clrTime = clrTime > > class EventTimeFilter: > def __init__(self): > self.event = [] #Create an empty list, bind to the name "event" > under the "self" namespace > self.event.append(Event()) #Create an event object and append > to the end of the list > > > Python won't stop you from putting other objects into self.event besides > Event objects, but in practice this isn't often an issue. The real benefit, > is if you subclass event or make some other type of object that is similar > to events, with maybe some of the same fields, you can still store them in > the list and it will play along with the rest of your code. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Regards Alok Kumar -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Mon May 12 20:32:48 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 12 May 2008 17:32:48 -0700 (PDT) Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> Message-ID: <2b66a86e-5a05-4262-b3c9-4703b0ae3372@d1g2000hsg.googlegroups.com> On May 12, 6:39?pm, Dave Parker wrote: > I've read that one of the design goals of Python was to create an easy- > to-use English-like language. ?That's also one of the design goals of > Flaming Thunder athttp://www.flamingthunder.com/?, which has proven > easy enough for even elementary school students, even though it is > designed for scientists, mathematicians and engineers. Can you render some furniture for me... to try to see some human posture to lowest energy levels. From afrobeard at gmail.com Thu May 15 17:25:29 2008 From: afrobeard at gmail.com (afrobeard) Date: Thu, 15 May 2008 14:25:29 -0700 (PDT) Subject: FTP upload issue References: <44eede8c-05b5-441d-9207-210074e55f8f@f36g2000hsa.googlegroups.com> Message-ID: First of all, it would be better to use:- ftp.storlines("STOR " + remoteFileName, open(localFileName, "rb")) rather than:- ftp.storlines("STOR" + filename, file(filename)) Since the Python Documentation has this to say for open(): [Although ] When opening a file, it's preferable to use open() instead of invoking this constructor directly. file is more suited to type testing (for example, writing "isinstance(f, file)"). Secondly Referring to another mail thread : http://mail.python.org/pipermail/tutor/2006-February/045347.html Quoting Kent : fname should be just a bare name, e.g. 'mac.info2.txt'. You have to ftp.cwd() to the correct directory yourself. If it does not exists, create a tmp directory. You're currently passing /tmp/mac.info2.txt to the ftp. This should hopefully solve your problem. P.S. I personally used to use ftputil[Really easy to use] and now I use twisted. These libraries abstract a lot of stuff out for you. On May 16, 1:25?am, davidj411 wrote: > I am having difficulty uploading a text file using Python 2.5 on MAC > OSX. > > SCRIPT > > filename='/tmp/mac.info2.txt' > fh=open(filename,'w') > fh.write('yes, i have a mac but don't hold that against me - just > example data') > fh.close() > > from ftplib import FTP > 'host, username, and password are string variables that have already > been defined. > ftp = FTP(host) > ftp.login(username,password) > 'so far, logged in, all is well , error is on next line. > > ftp.storlines("STOR" + filename, file(filename)) > ftp.quit() > > What am i doing wrong? ?the file DOES exist, the path is correct, and > the file ?was closed after being written. file(filename) should open > it again for the upload? > > http://www.python.org/doc/lib/ftp-objects.htmlsays that the command > should be an appropriate "STOR" command: "STOR filename". file is an > open file object which is read... > > ERROR > ? File "mac.inventory.py", line 44, in > ? ? ftp.storlines("STOR " + filename, file(filename)) > ? File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/ftplib.py", line 437, in storlines > ? ? conn = self.transfercmd(cmd) > ? File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/ftplib.py", line 356, in transfercmd > ? ? return self.ntransfercmd(cmd, rest)[0] > ? File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/ftplib.py", line 327, in ntransfercmd > ? ? resp = self.sendcmd(cmd) > ? File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/ftplib.py", line 241, in sendcmd > ? ? return self.getresp() > ? File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/ftplib.py", line 216, in getresp > ? ? raise error_perm, resp > ftplib.error_perm: 550 /tmp/mac.info2.txt: The system cannot find the > path specified. From arnodel at googlemail.com Mon May 12 04:57:13 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 12 May 2008 01:57:13 -0700 (PDT) Subject: anonymous assignment References: <1XNVj.133805$Cj7.33096@pd7urf2no> Message-ID: On May 12, 7:31?am, Arnaud Delobelle wrote: > Yves Dorfsman writes: > > Is there anyway to tell python I don't care about a value ? > > > Say I want today's year and day, I'd like to do something like: > > > import time > > y, None, d, None, None, None, None = time.localtime() > > > I know you can't assign anything to None, but I'm sure you get what I > > mean, a special keyword that means I don't care about this value. In > > this particular case, there's got to be a better way than: > > > d = time.local() > > y = d[0] > > d = d[1] > > I use Paul Rubin's solution (which is frown upon by many:), but it's > true it would be nice for tuples to have something like an extract() > method: > > y, d = time.localtime.extract(0, 2) > > Where > > ? ? mytuple.extract(i1, i2, i3...) > > would mean: > > ? ? tuple(mytuple[i] for i in (i1, i2, i3...)) > > Or perhaps allow indexing by tuples: > > ? ? mytuple[i1, i2, i3...] > > -- > Arnaud here is a very sophisticated implementation :) >>> def extract(indices, seq): ... return tuple(seq[i] for i in indices) ... >>> y, d = extract((0, 2), time.localtime()) >>> y, d (2008, 12) -- Arnaud From paul at boddie.org.uk Wed May 7 06:56:30 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 7 May 2008 03:56:30 -0700 (PDT) Subject: License selection for free software References: <3a8e0a8f-3bd1-4650-9104-5c273f14b097@w7g2000hsa.googlegroups.com> <1w4gs9bk.fsf@gmail.com> <87ve1se6q5.fsf_-_@benfinney.id.au> <8763tr5ov1.fsf@gmail.com> Message-ID: <6b46e4e9-4c71-47b7-aac8-3d3340b61b64@26g2000hsk.googlegroups.com> On 6 Mai, 19:22, vivai... at gmail.com (Ville M. Vainio) wrote: > Excuse the long post. Excuse the cherry-picking from your long post. ;-) [...] > Also, you can do what Paul Boddie did - fork the project, or maintain > patches that are under LGPL. With a liberal license, you have that > privilege. Sure, my patches were LGPL, if you'd like to consider it that way, but I have to point out that the derived work maintained by me became LGPL as a result - I wasn't offering the non-Paul Boddie version under the original licence as well. Now, I did leave a fair amount of information about the heritage of the code, so that anyone who is scared of the LGPL could just go and get the original work, but that is probably your only viable option if you want to revert to the old licensing. [...] > I don't think BSD/MIT like license really annoys anyone. Think python > here ;-) As some have pointed out, it can discourage people from contributing. I've said many times before that some companies might not contribute to a permissively licensed project because their competitors could leverage the benefit in proprietary software, and I consider Linux and the involvement of companies like IBM to be a reasonable example of this. [...] > Not at all, it's a very practical thing related to all the > intellectual property lawyerage in corporate setting. With Vellum, it > doesn't matter a lot because most of the tools are only used in-house, > but it would still be nice if you could just grab the code from > somewhere without having to think about license at all, or considering > whether any of this would ever be needed for something that involves > selling stuff under proprietary license. You can almost never just "grab the code from somewhere without having to think about [the] license" since even permissive licences typically have a list of conditions that must be observed. Certainly, they aren't as demanding as those in copyleft licences, but by not observing them you are infringing someone's copyright. [...] > Also, for some reason, GPL is used for evil (dual-licensing schemes - > make money but still gain the open source mindshare, and possibly rack > up free contributions to something that is your *commercial product*) > more often than it's used for good (gcc, Linux kernel - prevent IP > exploitation and ensure that all improvements are freely accessible). The whole "evil" aspect of dual-licensing schemes is mostly to do with copyright assignment (or the contribution agreement), not licensing, although the licences typically employed obviously prevent the wider community from making proprietary versions of the software, thus creating the conditions for a dual-licensing business. That said, it's easy to refuse to play along with such schemes if you're motivated: just don't agree to assign your copyright to someone else, or don't license your contributions under permissive licences (which interestingly takes us back to the issue of Python contributions and the associated list of acceptable licences). These days, some companies are getting a lot of bad publicity about their project governance: Sun seem to be getting continuous criticism about the management of OpenOffice.org, and now that they've picked up MySQL, they'll presumably be the target of criticism by people who had to sign over their ownership of patches in order to feed the MySQL corporate machine. But again, this isn't a sign that the licence was the problem: it's what people were asked to do with the copyright which effectively negated the benefits of the licence for those wanting to keep the software free and open. Paul From arnodel at googlemail.com Tue May 13 02:07:15 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 13 May 2008 07:07:15 +0100 Subject: anonymous assignment References: <1XNVj.133805$Cj7.33096@pd7urf2no> Message-ID: "Terry Reedy" writes: > "Arnaud Delobelle" wrote in message > news:c689625d-b2d2-4268-ae40-15e3c9b78ea2 at x41g2000hsb.googlegroups.com... > > here is a very sophisticated implementation :) > >>>> def extract(indices, seq): > ... return tuple(seq[i] for i in indices) > ... >>>> y, d = extract((0, 2), time.localtime()) >>>> y, d > (2008, 12) > > =================== > Or a generator version: > > # 3.0 > def extract(iterable, indexes): > # assume indexes are all legal > enext = enumerate(iterable).__next__ > i,item = enext() > for index in indexes: > while i < index: > i,item = enext() > yield item > > import time > print(list(extract(time.localtime(), (0,2)))) > > #prints [2008, 12] but extract('python', (3, 1)) won't work! -- Arnaud From mdw at distorted.org.uk Tue May 13 06:20:42 2008 From: mdw at distorted.org.uk (Mark Wooding) Date: Tue, 13 May 2008 10:20:42 +0000 (UTC) Subject: anonymous assignment References: <1XNVj.133805$Cj7.33096@pd7urf2no> <7xmymwuu25.fsf@ruckus.brouhaha.com> <87zlqw6v7k.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > Paul Rubin writes: >> You can just use a variable name than you ignore. It's traditional >> to use _ but it's not a special keyword, it's just a another >> variable name: >> >> y, _, d, _, _, _, _, _, _ = time.localtime() > > It's a terrible name for that purpose, since it doesn't indicate the > intention explicitly, There's a lot of tradition behind _ for this purpose, not just in Python. For example, pattern-matching function languages, like ML and Haskell, have been using _ to mean `don't care' for a long time. Just the fact that the name is repeated suggests that you don't care about its value. Besides, it's a good choice for other reasons: because the symbol is short, the variables you do care about stand out clearly. > Far better to use the name 'unused' as suggested by Carl Banks earlier > today. Other traditional names are `hunoz', `hukairz' and (apparently) `huaskt. But these have much more visual clutter than the humble _. You actually need to do reading to pick out the bindings which you /are/ interested in. -- [mdw] From gagsl-py2 at yahoo.com.ar Wed May 14 02:18:00 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 14 May 2008 03:18:00 -0300 Subject: do you fail at FizzBuzz? simple prog test References: <39709320-66e1-40e9-a351-c769c9a94585@x41g2000hsb.googlegroups.com> <688a0f5a-2cdf-45ca-abe7-5bbb89aac32f@s50g2000hsb.googlegroups.com> <482a00a2@news.mel.dft.com.au> <249560b3-7dd8-4fc1-8c14-11bc98a105ca@c65g2000hsa.googlegroups.com> Message-ID: En Tue, 13 May 2008 19:31:03 -0300, Mensanator escribi?: > Such as what's the voltage at point A? > > +5v > | > 220 ohm > | > +-- A > | > 330 ohm > | > ground > > Would you be surprised at how many applicants couldn't > figure that out because they forgot to bring their > calculator? Just a few hours ago I was helping a high school boy (senior) with some chemistry homework. He actually had to use a calculator to evaluate 120*1/1 (and didn't even noticed he got the "same" number until I told him!) I hope he'll pass his test tomorrow... -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Fri May 2 15:45:11 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 02 May 2008 16:45:11 -0300 Subject: portable /dev/null References: <1jkwzhktzddwv.xxl22p30ivrs.dlg@40tude.net> Message-ID: En Fri, 02 May 2008 16:20:04 -0300, Brendan Miller escribi?: > I have functions that take a file object and write to it. In some cases I > just want to throw out what is written to that file object. I want > something like open('/dev/null', 'w'), but portable. > > It needs to have an underlying file descriptor/file handle, as it will be > passed to non python code. > > Is there a portable /dev/null somewhere in the standard library? py> import os py> print os.devnull nul (this is on Windows) -- Gabriel Genellina From spectrumdt at gmail.com Thu May 8 11:29:33 2008 From: spectrumdt at gmail.com (spectrumdt at gmail.com) Date: Thu, 8 May 2008 08:29:33 -0700 (PDT) Subject: How to kill Python interpreter from the command line? Message-ID: <10fdb79d-8ac2-4bf3-bbdc-a825ae2c44c8@l42g2000hsc.googlegroups.com> Hello. I am running Fedora Linux and KDE, using the Konsole command line. When coding Python, I regularly make a bug causing my program to not terminate. But how do I kill the non-terminating Python interpreter without killing the entire Konsole? The default way of killing the current process on the command line is Ctrl+C, but that doesn't work with Python. Neither do the "terminate task", "suspend task" or "interrupt task" commands (available from right-click in Konsole). So, can someone please help? How do I kill Python without having to restart Konsole? Thanks in advance. From vivainio at gmail.com Sun May 11 15:59:35 2008 From: vivainio at gmail.com (Ville M. Vainio) Date: Sun, 11 May 2008 19:59:35 GMT Subject: observer pattern (notification chain synchronization) References: Message-ID: <87tzh4wr12.fsf@gmail.com> Alan Isaac writes: > Here is one way: > > - for each fund, create a ``reportreceived`` dict that maps stocks to booleans (initially False) > - as each stock notifies its funds, the fund changes False to True and checks ``all(reportreceived.values())`` to determine whether it is ok to notify investors. > - When it is ok, the fund notifies investors and resets all the > ``reportreceived`` values. > > Is this sensible enough? What are standard and better ways? You could explore the performance of popping items from the dict/set, instead of toggling the value so to true. Once the dict is empty, you are done. Of course the dict/set would be called stocks_that_havent_reported, or a saner & shorter variant of that. The idea here is that checking a dict/set for emptiness is close-to-zero time operation. From saptarshi.guha at gmail.com Mon May 19 02:04:57 2008 From: saptarshi.guha at gmail.com (sapsi) Date: Sun, 18 May 2008 23:04:57 -0700 (PDT) Subject: Reading Java byte[] data stream over standard input References: <59da4e60-f4ac-4fa0-9c86-5e4a0c7cf423@m73g2000hsh.googlegroups.com> Message-ID: <02cac1ae-6f97-4d63-a9fe-73172df95770@l64g2000hse.googlegroups.com> I should also mention that for some reason there are several binay values popping in between for some reason. This behavior (for the inputr stream) is not expected > Now, the incoming data is binary(though mine is actually merely ascii > text) but the output is not what is expected. I expect for e.g > > all/86000/114.310.151.209.60370-121.110.5.176.113\n62485.9718 > 118.010.241.12 60370 128.210.5.176 > > However i get a 1 before all and a 4 just after \n and before the 6. > > My question is : how do i read binary data(Java's byte stream) from > stdin? > Or is this actually what i'm getting? > > Thanks > Sapsi From gneuner2/ at /comcast.net Fri May 9 17:56:48 2008 From: gneuner2/ at /comcast.net (George Neuner) Date: Fri, 09 May 2008 17:56:48 -0400 Subject: The Importance of Terminology's Quality References: <68i6b5F2soauaU1@mid.individual.net> Message-ID: On Thu, 8 May 2008 22:38:44 -0700, "Waylen Gumbal" wrote: >Sherman Pendley wrote: >> kodifik at eurogaran.com writes: >> > >> > > PLEASE DO NOT | :.:\:\:/:/:.: >> > > FEED THE TROLLS | :=.' - - '.=: >> > >> > I don't think Xah is trolling here (contrary to his/her habit) >> > but posing an interesting matter of discussion. >> >> It might be interesting in the abstract, but any such discussion, when >> cross-posted to multiple language groups on usenet, will inevitably >> devolve into a flamewar as proponents of the various languages argue >> about which language better expresses the ideas being talked about. >> It's like a law of usenet or something. >> >> If Xah wanted an interesting discussion, he could have posted this to >> one language-neutral group such as comp.programming. He doesn't want >> that - he wants the multi-group flamefest. > >Not everyone follows language-neutral groups (such as comp,programming >as you pointed out), so you actually reach more people by cross posting. >This is what I don't understand - everyone seems to assume that by cross >posting, one intends on start a "flamefest", when in fact most such >"flamefests" are started by those who cannot bring themselves to >skipping over the topic that they so dislike. The problem is that many initial posts have topics that are misleading or simplistic. Often an interesting discussion can start on some point the initial poster never considered or meant to raise. George -- for email reply remove "/" from address From piotr_chamera at poczta.onet.pl Sat May 24 07:01:30 2008 From: piotr_chamera at poczta.onet.pl (Piotr Chamera) Date: Sat, 24 May 2008 13:01:30 +0200 Subject: Storing objects in relational database In-Reply-To: References: <03a17198-3eb2-438e-97c9-db18c0c24a80@c65g2000hsa.googlegroups.com> Message-ID: bruno.desthuilliers at gmail.com pisze: > I don't know if you'd label it 'elegant', but as far as I'm concerned, > storing serialized objects as blobs in a relational database is mostly > non-sense. If I use a relational database, it's because it is a > *relational* database. If you want an OODB, then we have the ZODB, > Durus and a couple others. It is sometimes convenient to store objects in mature relational database backend (reliability, stability, support, tools, replication, etc.). See latst efforts with RelStorage backend for ZODB (http://wiki.zope.org/ZODB/RelStorage) - it stores pickled Python objects in Oracle, PostgreSQL or MySQL) From gherron at islandtraining.com Sat May 3 19:44:15 2008 From: gherron at islandtraining.com (Gary Herron) Date: Sat, 03 May 2008 16:44:15 -0700 Subject: is +=1 thread safe In-Reply-To: References: <4819DA2D.3030508@ggmail.com> <481BD50F.5080608@ggmail.com> Message-ID: <481CF8CF.1020302@islandtraining.com> Alexander Schmolck wrote: > AlFire writes: > > >>> The threading module already has a function to return the number of Thread >>> objects currently alive. >>> >> I have threads within threads - so it does not suit me :-(. >> > > How about using a scalar numpy array? They are mutable, so I assume that x += > 1 should be atomic. > No NO NO! The only way to increment a variable in memory is through a three step process: Load a register from a memory location Increment the register Store the value back into memory. Ages ago, there were architectures that would do an increment on a memory location in an atomic way, but with the current (RISC) architectures these are three separate operations. A good compiler may be able to eliminate some of these operations by keeping the variable in question in a register, but this just worsens the problem with respect to threads since each thread has it's own set of register values. Gary Herron > 'as > -- > http://mail.python.org/mailman/listinfo/python-list > From duncan.booth at invalid.invalid Wed May 7 08:14:32 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 7 May 2008 12:14:32 GMT Subject: Why don't generators execute until first yield? References: Message-ID: Martin Sand Christensen wrote: >>>>>> "Duncan" == Duncan Booth writes: > [...] > Duncan> Now try: > Duncan> > Duncan> for command in getCommandsFromUser(): > Duncan> print "the result of that command was", > execute(command) Duncan> > Duncan> where getCommandsFromUser is a greedy generator that reads > from stdin, Duncan> and see why generators don't work that way. > > I don't see a problem unless the generator isn't defined where it's > going to be used. In other similar input bound use cases, such as the > generator iterating over a query result set in my original post, I see > even less of a problem. Maybe I'm simply daft and you need to spell it > out for me. :-) It does this: >>> @greedy def getCommandsFromUser(): while True: yield raw_input('Command?') >>> for cmd in getCommandsFromUser(): print "that was command", cmd Command?hello Command?goodbye that was command hello Command?wtf that was command goodbye Command? Traceback (most recent call last): File "", line 1, in for cmd in getCommandsFromUser(): File "", line 11, in delayed for value in it: File "", line 4, in getCommandsFromUser yield raw_input('Command?') KeyboardInterrupt From inhahe at gmail.com Fri May 16 12:58:07 2008 From: inhahe at gmail.com (inhahe) Date: Fri, 16 May 2008 12:58:07 -0400 Subject: Thread killing - I know I know! References: Message-ID: I'm not sure it's possible to kill a thread in Python that's in the middle of a C function. I know you can't do it with signals, for example. Or can you? I'm on Windows and signals isn't fully implemented. I had to do just this, btw, so I wrote another Python program that communicates with the main one over a socket and then if it misbehaves I can kill it using an OS command because it's a process and there's an OS command for killing processes, and then I'd restart it. The problem is that, sometimes the OS kill command would work, sometimes it wouldn't, and I never did figure what makes the difference. "Roger Heathcote" wrote in message news:DZSdnYx_IraeNrDVnZ2dneKdnZydnZ2d at bt.com... > Hello everyone, this is my first post so hello & please be gentle! > > Despite many peoples insistence that allowing for the arbitrary killing of > threads is a cardinal sin and although I have no particular threading > problem to crack right now I remain interest in the taboo that is thread > killing. The real world and it's data are messy and imperfect and I can > think of several scenarios where it could be useful to be able to bump off > a naughty thread, especially when using/testing unstable 3rd party modules > and other code that is an unknown quantity. > > With this in mind I am experimenting with a set of threading subclasses > that would permit timeouts and the manual killing of threads. I'm trying > to evaluate how robust such a scheme can be made and what the limitations > would be in practice. > > So far I can seemingly murder/timeout pure python threads that are stuck > blocking for input and stuck in infinite loops but I'm guessing there are > many more awkward cases. What I'm looking for are examples of code/modules > that can get stuck in dead ends or might otherwise be problematic to > terminate. > > In particular I'd be interested to see if I could kill a non-returning c > module. Of course naturally no one wants to be publishing buggy modules > and the like so I am having trouble finding examples of misbehaving c code > to explore further. I figure I could learn how to write c modules for > python but, while it's something I'd like to know someday, I'm guessing > that will be too long to fit into the immediate future :/ Consequently if > anyone has detailed knowledge of what is and isn't fundamentally possible > in the world of thread culling, or if you can point me to some > gnarly/non-returning thread code to test with I would be forever grateful. > > Oh yes, I'm working primarily with 2.5 on XP however I have access to > linux & OSX boxen and I'd be interested to learn about problematic thread > code for either of those platforms as well. > > Thanks for reading, > > Roger Heathcote - www.technicalbloke.com From kyosohma at gmail.com Thu May 15 16:11:24 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 15 May 2008 13:11:24 -0700 (PDT) Subject: Problem creating a shorcut References: <2715b502-d636-4541-ac0e-05697f02b2ae@m44g2000hsc.googlegroups.com> Message-ID: <577a0ed4-afe9-4bd2-8ef9-74d3051bf27b@a1g2000hsb.googlegroups.com> On May 15, 2:03 pm, Larry Bates wrote: > Mike Driscoll wrote: > > Hi, > > > I've had this niggling issue from time to time. I want to create a > > shortcut on the user's desktop to a website that specifically loads > > Firefox even if Firefox is not the default browser. > > > I usually use COM as it allows very specific settings of the shortcut, > > such as the Working Directory and the Target Path. However, the > > following will not work for some reason: > > > > > > import win32com.client > > import winshell > > > shell = win32com.client.Dispatch('WScript.Shell') > > userDesktop = winshell.desktop() > > > shortcut = shell.CreateShortCut(userDesktop + '\\MyShortcut.lnk') > > shortcut.Targetpath = r'"C:\Program Files\Mozilla Firefox\firefox.exe" > > https:\www.myCompanyWebsite.com\auth\preauth.php' > > shortcut.WorkingDirectory = r'C:\Program Files\Mozilla > > Firefox' > > shortcut.save() > > > > > > This creates the following target path (which doesn't work): > > > "C:\"C:\Program Files\Mozilla Firefox\firefox.exe" https: > > \www.myCompanyWebsite.com\auth\preauth.php" > > > If I leave the website off, it works. If I leave the path to Firefox > > out, it works too. Is there another method I can use other than > > creating the shortcut by hand and using the shutil module? > > > Thank you for any ideas. > > > Mike > > Either you copied wrong or the problem is: > > "C:\"C:\Program Files... > > Note the C:\ is specified twice in the string. I think it should read: > > > "C:\Program Files\Mozilla Firefox\firefox.exe" https: > > \www.myCompanyWebsite.com\auth\preauth.php" > > -Larry Yeah, I know that it's in there twice and that that is the problem. But I'm not causing that extra C:\. I run it exactly as above and that is what I get for the output. I think it's the COM object. Maybe I better just re-post this to the PyWin32 list... Thanks, Mike From bbxx789_05ss at yahoo.com Sat May 17 14:15:31 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Sat, 17 May 2008 11:15:31 -0700 (PDT) Subject: Cookies and CookieJar References: Message-ID: <9fa71b33-3783-41c0-9897-1785d5bf1ca9@25g2000hsx.googlegroups.com> Larry Bates wrote: > I'm struggling with a project using mechanize and cookies to screen scape a > website. The site requires a client created cookie for authentication. Are you sure that is correct? As far as I know, the usual course of events is for a site to set a cookie header in the response it sends back to the client browser, which gets stored on the client's computer. Then when the browser makes subsequent requests to that site, the browser will automatically include the cookies that were set by that site. From bbxx789_05ss at yahoo.com Sun May 11 15:48:11 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Sun, 11 May 2008 12:48:11 -0700 (PDT) Subject: File Creation Not Working In A Thread Class? References: Message-ID: bc90021 wrote: > Hi All, > > Thanks in advance for any and all help! > > I have this code: > > g = open(fileName, 'a') > > where fileName is defined before the line it's used in. It works fine > when I use it outside a thread class. > > When I put the same line in a thread class, it no longer works, and I get > an error: > > IOError: [Errno 2] no such file u'fileName' > > Are threads not allowed to create files? ...oh yeah: import threading import time fname = "data.txt" f = open(fname) print f.read() f.close() f = open(fname, "a") f.write("some text\n") f.close() f = open(fname) print f.read() f.close() class MyThread(threading.Thread): def __init__(self, file_name): threading.Thread.__init__(self) def run(self): time.sleep(3) f = open(fname) print f.read() f.close() f = open(fname, "a") f.write("other text\n") f.close() f = open(fname) print f.read() f.close() my_t = MyThread(fname) my_t.start() my_t.join() --output:-- hello world hello world some text hello world some text hello world some text other text From levlozhkin at gmail.com Wed May 7 01:04:58 2008 From: levlozhkin at gmail.com (lev) Date: Tue, 6 May 2008 22:04:58 -0700 (PDT) Subject: Script Optimization References: <6ed749de-1a7d-4db5-a229-d3400da4d24b@f24g2000prh.googlegroups.com> <15e73598-1186-40d5-af63-f176976c5ed1@s33g2000pri.googlegroups.com> Message-ID: On May 4, 10:04 pm, "Gabriel Genellina" wrote: > En Sun, 04 May 2008 17:01:15 -0300, lev escribi?: > > >> * Change indentation from 8 spaces to 4 > > I like using tabs because of the text editor I use, the script at > > the end is with 4 though. > > Can't you configure it to use 4 spaces per indent - and not use "hard" tabs? > > >> * Remove useless "pass" and "return" lines > > I replaced the return nothing lines with passes, but I like > > keeping them in case the indentation is ever lost - makes it easy to > > go back to original indentation > > I can't think of a case when only indentation "is lost" - if you have a crash or something, normally you lose much more than indentation... Simple backups or a SCM system like cvs/svn will help. So I don't see the usefulness of those "pass" statements; I think that after some time using Python you'll consider them just garbage, as everyone else. > > >> * Temporarily change broken "chdir" line > > removed as many instances of chdir as possible (a few useless ones > > to accomodate the functions - changed functions to not chdir as much), > > that line seems to work... I made it in case the script is launched > > with say: 'python somedir\someotherdir\script.py' rather than 'python > > script.py', because I need it to work in it's own and parent > > directory. > > You can determine the directory where the script resides using > > import os > basedir = os.path.dirname(os.path.abspath(__file__)) > > This way it doesn't matter how it was launched. But execute the above code as soon as possible (before any chdir) > > > checksums = open(checksums, 'r') > > for fline in checksums.readlines(): > > You can directly iterate over the file: > > for fline in checksums: > > (readlines() reads the whole file contents in memory; I guess this is not an issue here, but in other cases it may be an important difference) > Although it's perfectly valid, I would not reccomend using the same name for two different things (checksums refers to the file name *and* the file itself) > > > changed_files_keys = changed_files.keys() > > changed_files_keys.sort() > > missing_files.sort() > > print '\n' > > if len(changed_files) != 0: > > print 'File(s) changed:' > > for key in changed_files_keys: > > You don't have to copy the keys and sort; use the sorted() builtin: > > for key in sorted(changed_files.iterkeys()): > > Also, "if len(changed_files) != 0" is usually written as: > > if changed_files: > > The same for missing_files. > > > for x in range(len(missing_files)): > > print '\t', missing_files[x] > > That construct range(len(somelist)) is very rarely used. Either you don't need the index, and write: > > for missing_file in missing_files: > print '\t', missing_file > > Or you want the index too, and write: > > for i, missing_file in enumerate(missing_files): > print '%2d: %s' % (i, missing_file) > > > def calculate_checksum(file_name): > > file_to_check = open(file_name, 'rb') > > chunk = 8196 > > Any reason to use such number? 8K is 8192; you could use 8*1024 if you don't remember the value. I usually write 1024*1024 when I want exactly 1M. > > -- > Gabriel Genellina Thank you Gabriel, I did not know about a number of the commands you posted, the use of 8196 was error on my part. I will change the script to reflect your corrections later tonight, I have another project I need to finish/comment/submit for corrections later on, so I will be using the version of the script that I will come up with tonight. Thank you for your invaluable advice, The python community is the first online community that I have had this much help from, Thank you all. From bignose+hates-spam at benfinney.id.au Wed May 28 18:01:55 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 29 May 2008 08:01:55 +1000 Subject: Traling white space on program source lines (was: Simple Doc Test failing without any reason [Help Needed]) References: <22fe8c7c-f2fa-4fe5-92c0-a3934229fb5e@u6g2000prc.googlegroups.com> <6ec02c90-be78-44b7-9838-a7e540a56a0d@m3g2000hsc.googlegroups.com> <6117786a-ae42-493f-8120-be16233b2980@l17g2000pri.googlegroups.com> Message-ID: <87mymarsto.fsf_-_@benfinney.id.au> afrobeard writes: > >>> sanitize_number('0321-4683113') > > Apparently they caused the test case to fail on this. > > Weird behavior :/ Nope, exactly as specified: doctest is reporting differences berween what output was generated and what output you described. > Thanks for your time Gerard and thanks to everyone else too. Moral of the story: Configure your editor to highlight trailing space on a line as an error, and always remove it before saving a program source code file. -- \ ?Men never do evil so completely and cheerfully as when they | `\ do it from religious conviction.? ?Blaise Pascal | _o__) (1623-1662), Pens?es, #894. | Ben Finney From brian at sweetapp.com Thu May 22 18:19:35 2008 From: brian at sweetapp.com (Brian Quinlan) Date: Thu, 22 May 2008 23:19:35 +0100 Subject: Python and Flaming Thunder In-Reply-To: <8cfd3523-8d16-40bc-b904-94a6a36a414d@p25g2000pri.googlegroups.com> References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <20080514215943.14c92f16.johnjsal@NOSPAMgmail.com> <94bac166-d13c-44dd-af84-db19e19488b8@w1g2000prd.googlegroups.com> <8cfd3523-8d16-40bc-b904-94a6a36a414d@p25g2000pri.googlegroups.com> Message-ID: <4835F177.9090905@sweetapp.com> Dave Parker wrote: >> Or just: >> >> If command is "quit" ... > > Hmmm. In Flaming Thunder, I'm using "is" (and "is an", "is a", etc) > for assigning and checking types. For example, to read data from a > file and check for errors: > > Read data from "input.txt". > If data is an error then go to ... Hey Dave, Does this mean that Flaming Thunder requires explicit checking rather than offering exceptions? Cheers, Brian From daveparker at flamingthunder.com Wed May 28 09:26:05 2008 From: daveparker at flamingthunder.com (Dave Parker) Date: Wed, 28 May 2008 06:26:05 -0700 (PDT) Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> Message-ID: <01a1457d-4734-4a6b-8fb8-816a54e4d770@p39g2000prm.googlegroups.com> > That error message is the erlang interpreter saying "Hey I know X is > 8, and you've said it is 10 - that can't be right", which is pretty > much what math teachers say too... I enjoyed the discussion of how different languages handle the notion of "="; I learned something new. Thanks. On May 22, 9:30?am, Nick Craig-Wood wrote: > Dave Parker wrote: > > ?But after getting input from children and teachers, etc, it started > > ?feeling right. > > > ?For example, consider the two statements: > > > ? ? ? x = 8 > > ? ? ? x = 10 > > > ?The reaction from most math teachers (and kids) was "one of those is > > ?wrong because x can't equal 2 different things at the same time". > > This is a common feature in functional languages... > > Eg > > Erlang (BEAM) emulator version 5.6.2 [source] [smp:2] > [async-threads:0] [kernel-poll:false] > > Eshell V5.6.2 ?(abort with ^G) > 1> X = 8. > 8 > 2> X = 10. > ** exception error: no match of right hand side value 10 > 3> > > That error message is the erlang interpreter saying "Hey I know X is > 8, and you've said it is 10 - that can't be right", which is pretty > much what math teachers say too... > > -- > Nick Craig-Wood --http://www.craig-wood.com/nick From spoier at gmail.com Tue May 20 15:58:49 2008 From: spoier at gmail.com (Skye) Date: Tue, 20 May 2008 12:58:49 -0700 (PDT) Subject: Access to sysctl on FreeBSD? References: <48331cef$0$32633$9b622d9e@news.freenet.de> Message-ID: <8fb9d8a3-caac-45af-92ff-4540dc14f596@v26g2000prm.googlegroups.com> Nevermind, I seem to have found it on my own =] http://python.org/doc/2.5/lib/module-struct.html This module performs conversions between Python values and C structs represented as Python strings. It uses format strings (explained below) as compact descriptions of the lay-out of the C structs and the intended conversion to/from Python values. This can be used in handling binary data stored in files or from network connections, among other sources. I freakin' love Python!! Skye From torriem at gmail.com Mon May 19 20:14:12 2008 From: torriem at gmail.com (Michael Torrie) Date: Mon, 19 May 2008 18:14:12 -0600 Subject: How do *you* use Python in non-GUI work? In-Reply-To: <4831DDCA.2050005@gmail.com> References: <20080518182022.990193bd.johnjsal@NOSPAMgmail.com> <4831DDCA.2050005@gmail.com> Message-ID: <483217D4.8010303@gmail.com> Michael Torrie wrote: > And of course Python is perfect in this area. A great example is found > here: ahem, http://www.dabeaz.com/generators/Generators.pdf From darcy at druid.net Fri May 2 09:21:27 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Fri, 2 May 2008 09:21:27 -0400 Subject: #!/usr/bin/env python vs. #!/usr/bin/python In-Reply-To: <87ve1xz23l.fsf@benfinney.id.au> References: <87abj91j8u.fsf@benfinney.id.au> <87ve1xz23l.fsf@benfinney.id.au> Message-ID: <20080502092127.fa308411.darcy@druid.net> On Fri, 02 May 2008 15:50:22 +1000 Ben Finney wrote: > > You have lived a sheltered life. Not every packaging system puts the > > executible in /usr/bin. Many systems use /usr/local/bin. > > They use that for the operating-system-installed default Python > interpreter? Colour me incredulous. OK, let me get out my crayons. However, note that I did not say "operating-system-installed." I said a packaging system puts it there. In fact, the NetBSD packaging system works on many systems including Linux and thus is not an operating system packager. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From martindesalinas at gmail.com Fri May 16 04:22:01 2008 From: martindesalinas at gmail.com (martindesalinas at gmail.com) Date: Fri, 16 May 2008 01:22:01 -0700 (PDT) Subject: datamining .txt-files, library? References: <8ab6802f-ac2c-4492-b793-704126567a8e@a1g2000hsb.googlegroups.com> <96f60dc3-fe60-45fa-befe-70d7ae5a330a@d77g2000hsb.googlegroups.com> <482c4934$0$6041$426a74cc@news.free.fr> Message-ID: <60e2ee6e-955a-49f2-a87a-ad8c3908d2c8@l42g2000hsc.googlegroups.com> look at module re (rgular expression) or pyparser see http://nedbatchelder.com/text/python-parsers.html From a.harrowell at gmail.com Thu May 29 09:09:06 2008 From: a.harrowell at gmail.com (TYR) Date: Thu, 29 May 2008 06:09:06 -0700 (PDT) Subject: Strange thing with types Message-ID: <969d0015-b689-48b0-966e-0f709574deea@m3g2000hsc.googlegroups.com> I'm doing some data normalisation, which involves data from a Web site being extracted with BeautifulSoup, cleaned up with a regex, then having the current year as returned by time()'s tm_year attribute inserted, before the data is concatenated with string.join() and fed to time.strptime(). Here's some code: timeinput = re.split('[\s:-]', rawtime) print timeinput #trace statement print year #trace statement t = timeinput.insert(2, year) print t #trace statement t1 = string.join(t, '') timeobject = time.strptime(t1, "%d %b %Y %H %M") year is a Unicode string; so is the data in rawtime (BeautifulSoup gives you Unicode, dammit). And here's the output: [u'29', u'May', u'01', u'00'] (OK, so the regex is working) 2008 (OK, so the year is a year) None (...but what's this?) Traceback (most recent call last): File "bothv2.py", line 71, in t1 = string.join(t, '') File "/usr/lib/python2.5/string.py", line 316, in join return sep.join(words) TypeError From bignose+hates-spam at benfinney.id.au Wed May 14 18:01:42 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 15 May 2008 08:01:42 +1000 Subject: named tuple mutability References: <844dc74c-1812-4599-934e-8fb63878b5cf@p25g2000hsf.googlegroups.com> Message-ID: <873aokzgs9.fsf@benfinney.id.au> "bruno.desthuilliers at gmail.com" writes: > On 14 mai, 18:20, castiro... at gmail.com wrote: > > I'm concerned over the future of Python. Should tuples be named? > > Obviously not, unless they should. Clearly they should, unless not. -- \ ?It is seldom that liberty of any kind is lost all at | `\ once.? ?David Hume | _o__) | Ben Finney From jon+usenet at unequivocal.co.uk Thu May 1 15:13:08 2008 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: Thu, 01 May 2008 14:13:08 -0500 Subject: Best way to store config or preferences in a multi-platform way. References: Message-ID: On 2008-05-01, Ivan Illarionov wrote: > I used XML files before for this purpose and found YAML much easier and > better suitable for the task. > > Please explain why don't like YANL so much? Because even the examples in the spec itself are unreadable gibberish. The PyYAML library is over 300kB! These are rather big clues that it's unsuitable for the purpose for which it was designed. It's certainly unsuitable for use as a configuration file format, where it is overkill by several orders of magnitude. !!str &a1 "foo": !!str bar &a2 baz : *a1 ! foo : ! baz This is supposed to be human readable? > PS. Your reply remind me of early days of Python when Perl programmers > said exacly the same thing about Python. I think I would suffer irony overload if I saw a Perl programmer criticising Python for being hard to read ;-) From collinyeung at shaw.ca Tue May 13 21:02:36 2008 From: collinyeung at shaw.ca (Collin) Date: Wed, 14 May 2008 01:02:36 GMT Subject: Accepting text input In-Reply-To: References: <72QVj.262833$pM4.115744@pd7urf1no> <84QVj.133083$rd2.94188@pd7urf3no> Message-ID: Gabriel Genellina wrote: > En Mon, 12 May 2008 01:54:28 -0300, Collin escribi?: > >> Collin wrote: >>> I'm pretty new to Python, but this has really bugged me. I can't find a >>> way around it. >>> >>> >>> The problem is that, when I use raw_input("sajfasjdf") whatever, or >>> input("dsjfadsjfa"), you can only have numerical values as answers. >>> >>> Any help would be appreciated. Thanks. >> >> Oh, wow. I feel so stupid. Please disregard this message. <_< > > No need to apologize... > >> I read the error message just now a bit more carefully, and I tried >> something. I tried defining "yes" as some random numerical value. Then >> when I did: >> (example code) >> >> yes = 123123983 #some number >> test = input("Test test test ") >> if test == yes: >> print "It worked." >> else: >> print "failed" >> >> (example code off) > > The usual way for Python<3.0 is: > > answer = raw_input("Test test test ").lower() > if answer == "yes": > ... > > The input() function evaluates user input as an expression: if he types 2+5 the input() function returns the integer 7. I would never use input() in a program - it's way too unsafe; use always raw_input instead. > If I use it like that, do I have to import anything to have the .lower() work? And if I do, what does the .lower() signify? From bignose+hates-spam at benfinney.id.au Sat May 24 21:04:26 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 25 May 2008 11:04:26 +1000 Subject: Code correctness, and testing strategies References: Message-ID: <87ve139oth.fsf@benfinney.id.au> David writes: > Problem 1: You can only code against tests > > Basically, with TDD you write the tests first, then the code which > passes/fails the tests as appropriate. However, as you're writing > the code you will also think of a lot of corner cases you should > also handle. The natural way to do this is to add them to the code > first. In Behaviour Driven Development, that's not the natural way, since you don't add code unless a test requires you to add it. Very often, by designing the code to the point where you write an automated test for it, you find You Aren't Gonna Need It for many of the corner cases you envisaged, so you *save* time by thinking about the code design first. > But with TDD you have to first write a test for the corner case, > even if setting up test code for it is very complicated. For this, unit test frameworks have "fixtures": a common test environment that will be set up before each test case that is defined to need that fixture, and torn down after the test runs (whether the test result is pass, fail, or error). In Python's 'unittest', this is done by grouping related test cases together into methods of a TestCase class, and defining fixtures that will be present for every test case in that class. > So, you have these options: > > - Take as much time as needed to put a complicated test case in > place. Which is a motivator to make the interfaces less complicated, *before* implementing them, so the code becomes easier to test. > - Don't add corner case to your code because you can't (don't have > time to) write a test for it. That's a false economy. If you don't have the time to write a test for it, that's the same thing as saying you don't have the time to know whether you've done the implementation right. You pay for it later, with *much* interest, in time spent hunting down bugs caused by that code, when you could have had an automated test simply tell you the breakage and its location as soon as it happened. That's time that you spend before even getting to the point of fixing the bug. Thus, writing tests first *saves* time, by not having to hunt those bugs that could be found by automated tests at all. > - Add the corner case handling to the code first, and try to add a > test later if you have time for it. A recipe for disaster: now you have code which isn't there to satisfy a test, and since you say it's for a corner case, it's likely not exercised by the test suite at all. Take everything said above about debugging time and multiply it. > Problem 2: Slows down prototyping > > In order to get a new system working, it's nice to be able to throw > together a set of modules quickly, and if that doesn't work, scrap > it and try something else. There's a rule (forget where) that your > first system will always be a prototype, regardless of intent. Fred Brooks gave that law. "Plan to throw one away; you will, anyhow." The same rule also implies that throwing it away is worthwhile because the main value of the first version is not in the code itself, but in what it *taught* you about how to make the second version. > With TDD, you have to first write the tests for the first version. > Then when that first version doesn't work out, you end up scrapping > the tests and the code. The time spent writing the tests was wasted. I find that, with a good unit test suite in place, the first version can much more easily *evolve* into the second version: the first version gets thrown away, but in pieces over a short time, instead of a whole lump. Complete coverage by unit tests makes bold changes to the code far less risky, so as enlightenment dawns about how crappy the original design was, altering the existing system is much more natural. > Having to write tests for all code takes time. Yes. That's time you'll have to spend anyway, if you want your code tested. Whether you write the tests, early or late, they'll still take time to write. But writing them *while* you develop the code means you actually *do* write them, instead of putting them off to the point where they never get written. also, since with Behaviour Driven Development you're writing tests at the point where you implement the code, you are writing *only* tests that are needed to assert behaviour for the code you're about to write. This results in countless wrong paths not being taken as a result of smaller feedback cycles, so you save time in all the unnecessary tests you *don't* write. If you don't want your code to have complete automated unit test suites, I don't want to be your customer. > Instead of eg: 10 hours coding and say 1/2 an hour manual testing, > you spend eg: 2-3 hours writing all the tests, and 10 on the code. This is a false economy. If all you do is 2-3 hours of manual testing, are you then prepared to say the code works for *all* requirements with a high degree of confidence? As I'm sure you'll agree, automated, complete-coverage testing for all code paths is far superior confidence to 2-3 hours of manual testing. > Problem 4: Can make refactoring difficult. Your explanation for this below is only that it takes time, not that it's difficult to do. > If you have very complete & detailed tests for your project, but one > day you need to change the logic fundamentally (maybe change it from > single-threaded to multi-threaded, or from running on 1 server to > distributed), then you need to do a large amount of test refactoring > also. Again, this is not a problem with the *way* the tests are written, nor *when* they're written, but the fact that they're there at all. > The more tests you have (usually a good thing), the longer it will > take to update all the tests, write new ones, etc. It's worse if you > have to do all this first before you can start updating the code. Who says you have to do all the changes to all the tests before changing any of the code? That would be spectacularly bad practice. Behaviour Driven Development says that you address *one* change in behaviour at a time, so that you know which failing tests to address. This makes the work much more manageable, since it localises the changes to both the tests and the application. > You need to justify the extra time spent on writing test code. >From the perspective of someone who once thought this way, and then dug in and did Behaviour Driven Development, I can tell you the time is entirely justified: by better design, more maintainable code, higher confidence when speaking to customers, high visibility of progress toward completion, freedom to refactor code when it needs it, and many other benefits. > Tests are nice, and good to have for code maintainability, but they > aren't an essential feature (unless you're writing critical software > for life support, etc). Whether your customers express it at the time they specify the system, they want as much testing as you can fit in. Whom do you think they will blame when the application breaks? If their specified requirements explicitly describe some behaviour, but you don't have automated tests to tell you whether or not the application actually behaves that way, and the application breaks when they try it after paying you to implement it, what possible excuse do you think the customers will accept? > Clients, deadlines, etc require actual software, not tests for > software (that couldn't be completed on time because you spent too > much time writing tests first ;-)). Clients also require meaningful feedback on progress toward the goal. Without a complete-coverage unit test suite, you have a completely unknown amount of debugging time looming that grows the longer the project continues. Any figure of completion that you give to the customer will be wildly inaccurate because of this unknown factor, and it will bits when you get to the point of "90% feature complete", but the project blows out hugely because completing that last 10% involves masses of debugging time. You've no doubt heard the old saw about software project development: 90% of the implementation consumes 90% of the schedule. The last 10% consumes another 90% of the schedule." With an automated unit test suite that has complete coverage of the code at all stages of implementation, you can be much more confident that the features *are* complete as specified, because the specifications are codified as unit tests, and the unit tests pass. You're checking items off a meaningful list, rather than coding and praying that you got it right. > I think that automated tests can be very valuable for > maintainability, making sure that you or other devs don't break > something down the line. But these benefits must be worth the time > (and general inconvenience) spent on adding/maintaining the tests. I encourage you to try it. Learn your unit test suite (Python's 'unittest' and 'doctest' modules are fine), learn how to easily run it automatically (the third-party 'nose' package is great for this), and follow Behaviour Driven Development on one small aspect of your code; perhaps a single module. > If I did start doing some kind of TDD, it would be more of the > 'smoke test' variety. Call all of the functions with various > parameters, test some common scenarios, all the 'low hanging fruit'. > But don't spend a lot of time trying to test all possible scenarios > and corner cases, 100% coverage, etc, unless I have enough time for > it. This was my point of view too. Then I discovered that the code I was writing under Behaviour Driven Development involved far fewer dead-ends, far better designs, and far more constant forward progress ? all as a result of the fact that I had to design the code well enough to write tests for it, *before* actually implementing that code. > I'm going to read more on the subject (thanks to Ben for the link). > Maybe I have some misconceptions. If so, you're certainly not alone. Happy hacking! -- \ ?You can be a victor without having victims.? ?Harriet | `\ Woods | _o__) | Ben Finney From inhahe at gmail.com Wed May 21 02:22:03 2008 From: inhahe at gmail.com (inhahe) Date: Wed, 21 May 2008 02:22:03 -0400 Subject: persistent deque References: <29451c2a-cb0a-43a6-b140-6c16e3cb46ac@c65g2000hsa.googlegroups.com> <0uednUCD-McN-a7VnZ2dnUVZ_tzinZ2d@comcast.com> Message-ID: > > i don't know how i would get around the problem, though, because i'd have > to know how to access the deque object that my class stores when i do > deque.__init__ in my constructor, so that i could pickle it and my class > variables separately. > > i decided i could just pickle deque(self), which should return a regular deque object with the data from self, and then in the load routine make a pdeque object from it. that, of couse, gives me another error. 'collections.deque' object has no attribute 'write'. from the line 'self.write = file.write', which is in pickle.py pickling list(self) doesnt work either. From roy at panix.com Sat May 24 11:01:48 2008 From: roy at panix.com (Roy Smith) Date: Sat, 24 May 2008 11:01:48 -0400 Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <8763t3by81.fsf@benfinney.id.au> <5ea78616-e955-4ee0-8e60-a22734ec31be@79g2000hsk.googlegroups.com> Message-ID: In article <5ea78616-e955-4ee0-8e60-a22734ec31be at 79g2000hsk.googlegroups.com>, Fuzzyman wrote: > The 'we told you not to use that' approach, when applied to paying > customers doesn't really work... all they see is that you broke their > spreadsheet code by changing your API. I hear what you're saying, friend, and I feel your pain! Life gets so much more complicated when you've got paying customers. It's especially complicated when your customers have a market cap an order of magnitude greater than your own :-) From yves at zioup.com Sun May 11 23:42:03 2008 From: yves at zioup.com (Yves Dorfsman) Date: Mon, 12 May 2008 03:42:03 GMT Subject: anonymous assignment In-Reply-To: References: <1XNVj.133805$Cj7.33096@pd7urf2no> Message-ID: D'Arcy J.M. Cain wrote: > On Mon, 12 May 2008 02:28:13 GMT > Yves Dorfsman wrote: >> particular case, there's got to be a better way than: >> >> d = time.local() >> y = d[0] >> d = d[1] > > Like this? > > y, d = time.local()[:2] Sorry this was a typo (again :-), I meant: d = time.local() y = d[0] d = d[2] Yves. http://www.SollerS.ca From deets at nospam.web.de Tue May 27 05:47:07 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 27 May 2008 11:47:07 +0200 Subject: Overloading virtual method of widget without inheriting (PyQt) References: <6a53c9ff-d4ce-483e-959f-2505ad107093@a1g2000hsb.googlegroups.com> <1997713b-6fc0-497b-ae66-e90626b6645a@m73g2000hsh.googlegroups.com> Message-ID: <6a23lqF32p1e5U1@mid.uni-berlin.de> Alex Gusarov wrote: >> class MyPaintCell(PaintCell): >> def paintcell(self): >> PaintCell.paintcell(self) >> myPaintCell(self) >> >> (hmm, only 4 lines, I overestimated the cost. Sorry) > > Yeah, that's funny.. > > I don't want to do it 'cause I create my form within Designer and > simply drop Calendar widget to it. Then I need to translate it > into .py file, it's OK. But if I want to use a custom derived from > Calendar class instead of it, I need after every refreshing/ > translating of form replace few lines in translated file. > > I just want to know about existence of other method to do this in > class, that contain instance of Calendar. > > By "this" I mean: > Instead of calling original method "paintcell" alone, call it with my > custom metod. You should ask this on the PyQt-mailing-list. And you can try and experiment with the module new & the function instancemethod in there. Diez From jason.scheirer at gmail.com Mon May 19 19:05:15 2008 From: jason.scheirer at gmail.com (Jason Scheirer) Date: Mon, 19 May 2008 16:05:15 -0700 (PDT) Subject: Serious Problem with Timezone References: <95b65707-35d1-4ce7-9138-b89c44d8084a@w7g2000hsa.googlegroups.com> Message-ID: <6f9c7cee-5b6a-41e1-8752-a145c84eb872@w34g2000prm.googlegroups.com> On May 19, 3:02?pm, T-u-N-i-X wrote: > Hey There, > > I'm a django developer and working on a project right now.. Last week > I just discovered a new problem in Python.. Here's what I do.. > > [01:00] (tunix at penguix ~)$ date > Sal May 20 01:00:10 EEST 2008 > [01:00] (tunix at penguix ~)$ python > Python 2.5.2 (r252:60911, Feb 23 2008, 21:20:32) > [GCC 4.2.3] on linux2 > Type "help", "copyright", "credits" or "license" for more information.>>> from datetime import datetime > >>> datetime.now() > > datetime.datetime(2008, 5, 20, 1, 0, 21, 131804)>>> import os > >>> os.environ["TZ"] = "Europe/Istanbul" > >>> datetime.now() > > datetime.datetime(2008, 5, 19, 22, 0, 38, 578438) > > > > It's 01:00 in Istanbul now and Python shows 22:00 on 19th of May if I > set the TZ environment variable.. Django sets that variable > automatically so I'm having problems with scheduled posts.. > > I controlled my system's BIOS time.. It was wrong before, so I just > corrected it.. I set the time to UTC on Linux.. What else can I do ? You may want to investigate the datetime.astimezone() method, as well as getting comfortable with using tzinfo objects. Check out http://pypi.python.org/pypi/pytz/ for a module that can give you the tz objects you want. Also useful is datetime.utcnow()* and datetime.replace(tzinfo=other_tzinfo), which will give you that same time but not 'smartly' try to adjust the components in the datetime object. I've found datetime.utcnow() is a little temperamental (bad tzinfo is assigned by default, making it impossible to do conversions) and you still need to do datetime.utcnow().replace(tzinfo=utctz) to get it to behave well. From castironpi at gmail.com Sat May 17 20:05:30 2008 From: castironpi at gmail.com (castironpi) Date: Sat, 17 May 2008 17:05:30 -0700 (PDT) Subject: Using Python for programming algorithms References: Message-ID: <8f963d30-76f6-4ef8-998d-b848c83a74c8@x41g2000hsb.googlegroups.com> On May 17, 5:32?pm, Vicent Giner wrote: > Hello. > > I am new to Python. It seems a very interesting language to me. Its > simplicity is very attractive. > > However, it is usually said that Python is not a compiled but > interpreted programming language ?I mean, it is not like C, in that > sense. > > I am working on my PhD Thesis, which is about Operations Research, > heuristic algorithms, etc., and I am considering the possibility of > programming all my algorithms in Python. > > The usual alternative is C, but I like Python more. > > The main drawbacks I see to using Python are these: > > * As far as I understand, the fact that Python is not a compiled > language makes it slower than C, when performing huge amounts of > computations within an algorithm or program. > > * I don't know how likely it is to find libraries in Python related to > my research field. > > * I know Python is a "serious" and mature programming language, of > course. But I do not know if it is seen as "just funny" in a research > context. Is Python considered as a good programming language for > implementing Operations Research algorithms, such as heuristics and > other soft-computing algorithms? > > Maybe this is not the right forum, but maybe you can give me some > hints or tips... > > Thank you in advance. You're hearing from 'impossible and useless'-- neither operations. 'Stacks' are pretty important to Python (there is a Stackless Python, I understand), which makes persistence a little more handy. It's still a computer and still a language. You may be asking how well its best speakers know, and look at that, I can't tell you. Some of the fundamentals of Python may be unexplored to date, as its from the 90s, and stacks are elements. I, for one, will assume you're interested in control operations, which yes Python has, and control is important. The standard library is a good size to me (I wouldn't go doubling). There's a ready graphics module. There are code-primitive literals, including lists -and- a tuple. I think you're looking for the selling points of dynamic assignment (a.barproperty= 'unheardof'), typefreeness (a= [2,'bcd']), dynamic execution (exec('print 2'), which promotes a possibility of self-referentiality), type-aware function pointers, variable-length procedure arguments, and platform independence. I think you just asked at the right time. Yes that's an impressive list. There is one catch to Python, of the importance of which of the powers that be, I am unaware. But I do know what you are liable to find on the newsgroup. Now, with thousands of dollars of institution time on the money, what control? I will be tentatively assuming that you are not covertly comparing other languages. I don't think you'll like it if you're unwise. From castironpi at gmail.com Fri May 16 09:56:12 2008 From: castironpi at gmail.com (castironpi) Date: Fri, 16 May 2008 06:56:12 -0700 (PDT) Subject: Instance of class "object" References: Message-ID: On May 16, 8:51 am, castironpi wrote: > On May 16, 4:26 am, Peter Otten <__pete... at web.de> wrote: > > > ?? wrote: > > > I wonder why below does not work. > > > > a = object() > > > a.b = 1 # dynamic bind attribute failed... > > > The implementation of slots depends on that behaviour: > > >http://docs.python.org/ref/slots.html > > > > Does this strange behavior break the LSP (Liskov substitution principle)? > > > Can you expand on that? > > > Peter > > Spirals are important. I'd be modeling streams, in par. crossing them. From szhorvat at gmail.com Mon May 5 03:31:14 2008 From: szhorvat at gmail.com (=?ISO-8859-1?Q?Szabolcs_Horv=E1t?=) Date: Mon, 05 May 2008 09:31:14 +0200 Subject: Feature suggestion: sum() ought to use a compensated summation algorithm In-Reply-To: References: Message-ID: <481EB7C2.1040400@gmail.com> Duncan Booth wrote: > Szabolcs Horv?t wrote: > >> I thought that it would be very nice if the built-in sum() function used >> this algorithm by default. Has this been brought up before? Would this >> have any disadvantages (apart from a slight performance impact, but >> Python is a high-level language anyway ...)? > > There's a thread you might find interesting: > > http://groups.google.com/group/comp.lang.python/browse_thread/thread/9eda29faf92f532e/027cef7d4429aa3a > > In that thread I suggested that Python ought to implement sum by adding > together each pair of values, then each pair of results and so on. This > means that for input values of a similar magnitude the intermediate results > stay balanced. The implementation doesn't actually do all the first level > sums first, it builds up a stack containing the sum of 2^k, 2^(k-1)...2 > values. Also it works for other types as well, and for strings or lists has > the advantage of minimising the number of large string or list concatenations. > > If you follow that thread far enough you'll find a post by Jussi Salmela > which shows that summing adjacent pairs performs as well as Kahan summation > (he says 'almost as good' but in fact the only time they get different > results the 'correct' answer is 500000.000005 and Kahan and sumpairs get > the two nearest representable results either side: 500000.00000499998 and > 500000.00000500004 respectively). > > I never did get round to re-coding my sumpairs() function in C, I would be > interested to see just how much overhead it introduces (and I suspect it > would be faster than the existing sum in some cases such as for lists). Thanks for this link! Though some of the thread is missing, it was an interesting read. This sounds like a very good idea: it is more generally applicable than the Kahan summation because it does not require subtraction/negation, so it would work with user-defined types, too. While now I am convinced that using Kahan summation by default is not such a good idea, I cannot see any serious disadvantages/problems with pairwise summation! From upton at virginia.edu Fri May 16 13:44:32 2008 From: upton at virginia.edu (Dan Upton) Date: Fri, 16 May 2008 13:44:32 -0400 Subject: writing python extensions in assembly In-Reply-To: References: Message-ID: <5504f9ac0805161044r7756045cvec72cbc5f8a2f175@mail.gmail.com> >> 3. If it is still slow, embed some assembler where it is slowing down. >> > > I won't know if the assembler is faster until I embed it, and if I'm going > to do that I might as well use it. > Although it's true I'd only have to embed it for one system to see (more or > less). > Regardless of whether it's faster, I thought you indicated that really it's most important that it's fast enough. That said, it's not true that you won't know if it's faster until you embed it--that's what unit testing would be for. Write your loop(s) in Python, C, ASM, and run them, on actual inputs (or synthetic, if necessary, I suppose). That's how you'll be able to tell whether it's even worth the effort to get the assembly callable from Python. On Fri, May 16, 2008 at 1:27 PM, Mensanator wrote: > > Why wouldn't the compilers support it? It's part of the x86 > architexture, > isn't it? Yeah, but I don't know if it uses it by default, and my guess is it depends on how the compiler back end goes about optimizing the code for whether it will see data access/computation patterns amenable to SIMD. From mabbikeel at gmail.com Tue May 6 15:29:48 2008 From: mabbikeel at gmail.com (Matt Porter) Date: Tue, 06 May 2008 20:29:48 +0100 Subject: License selection for free software References: <3a8e0a8f-3bd1-4650-9104-5c273f14b097@w7g2000hsa.googlegroups.com> <1w4gs9bk.fsf@gmail.com> <87ve1se6q5.fsf_-_@benfinney.id.au> <8763tr5ov1.fsf@gmail.com> <7xprrz2r42.fsf@ruckus.brouhaha.com> Message-ID: On Tue, 06 May 2008 20:02:21 +0100, Paul Rubin <"http://phr.cx"@nospam.invalid> wrote: > vivainio at gmail.com (Ville M. Vainio) writes: > vivainio at gmail.com (Ville M. Vainio) writes: >> I don't think BSD/MIT like license really annoys anyone. Think python >> here ;-) > > Python's non-GPL license certainly is annoying to some of us. I'm intrigued - how can it be annoying? > -- > http://mail.python.org/mailman/listinfo/python-list > -- Using Opera's revolutionary e-mail client: http://www.opera.com/mail/ From inhahe at gmail.com Thu May 22 19:02:24 2008 From: inhahe at gmail.com (inhahe) Date: Thu, 22 May 2008 19:02:24 -0400 Subject: Overloading __getitem__ References: Message-ID: actually i ddin't think about the fact that you're overloading dict, which can already take multiple values in getitem so how about class crazy: pass and then in your dict class: def __getitem__(*args): if args[-1] is crazy: return self.get(args[:-1])*5 else: return self.get(args) and then print foo[1,2] #not crazy print foo[1,2,crazy] #crazy I *think* that would work "Andreas Matthias" wrote in message news:uf6hg5-ca9.ln1 at buckbeak.hogwarts... > The following code doesn't run but I hope you get what I > am trying to do. > > > class my_dict (dict): > > def __getitem__ (self, key, crazy = False): > if crazy == True: > return 5 * self.get(key) > else: > return self.get(key) > > > foo = my_dict() > foo['a'] = 123 > > print foo['a'] > print foo['a', crazy = True] > > > Is it somehow possible to overload __getitem__ with an additional > argument? Are there other possibilities to achiev this? Or is > the only solution to this to write a normal function call > `def my_get (self, key, crazy=False)'? > > > Ciao > Andreas From nick at craig-wood.com Sat May 3 09:30:04 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Sat, 03 May 2008 08:30:04 -0500 Subject: Newbie question - probably FAQ (but not exactly answered by regular FAQ) References: Message-ID: Banibrata Dutta wrote: > I've gone through the list of "language differences" between 2.3 / 2.4 > & 2.5 of CPython. I've spend around 2 weeks now, learning v2.5 of > CPython, and I consider myself still very very newbie. So, unable to > take a call as to how-important or desirable the newer language > features are -- so whether to write my app for v2.5 of Python, versus, > as few others on this list have recommended, i.e. to stick to v2.3 ?? > Are the preformance improvements, and memory footprint / leak fix in > 2.5 enough to justify moving to it ? What all do I stand to lose (or > gain) by writing on v2.3 ?? If you are writing for 2.3 you are writing for 2.4 and 2.5 also. There are some nice things in 2.4 and 2.5 but nothing you really need IMHO. So I'd say writing in a 2.3 subset would be perfectly sensible. > I've a constraint due to which I might have to also write parts of my > app (client side) in Jython (because I want to eventually ship Java -- > yet benefit from the rapid development and clarity of Python). Would > sticking to v2.3 in such a case be a better idea ? Suggestions with > reasoning would be very helpful. Jython seems to be based off python 2.2 so you would be limited to 2.2 features in that case. No big deal in my opinion. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From hdante at gmail.com Tue May 13 13:06:48 2008 From: hdante at gmail.com (hdante) Date: Tue, 13 May 2008 10:06:48 -0700 (PDT) Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <2b66a86e-5a05-4262-b3c9-4703b0ae3372@d1g2000hsg.googlegroups.com> <5b0e3f70-afde-4480-8713-e7113b1250d7@x35g2000hsb.googlegroups.com> <1f537717-00d0-48ee-99b6-7125b96a6133@t12g2000prg.googlegroups.com> <68t4o0F2vaoncU1@mid.uni-berlin.de> <2a32179a-9439-449c-bd07-fff6a4075aee@s50g2000hsb.googlegroups.com> <7ee5dffd-df8f-46f0-bd78-c81ac0418a9a@d77g2000hsb.googlegroups.com> <65ef773e-a1c3-4adb-a18b-e8b8451efe5e@b5g2000pri.googlegroups.com> Message-ID: <02a10e4b-5017-463c-96d2-e1779f2b9ebd@j22g2000hsf.googlegroups.com> On May 13, 12:24?pm, Dave Parker wrote: > > ?The "Flaming Thunder" looks promising, but without being free > > software, it's unlikely it will create a large developer community, > > specially considering both free general purpose and scientific > > programming languages. > > Perhaps. ?Flaming Thunder is only $19.95 per year for an individual > (and even less per individual for site licenses), which is less than > the cost of just one book on Python. > > I think that many people will find that Flaming Thunder is easier to > use and understand than Python -- so for many people the amount of > time they save will be worth more than the cost of Flaming Thunder > (unless, of course, their time is worth $0). > > Also, several users have rewritten their Python programs in Flaming > Thunder, and found that Flaming Thunder was 5 to 10 times faster > (Flaming Thunder compiles to native executables). ?So again, since > many people value their time at more than $0, I think that many people > will find that Flaming Thunder is worth $19.95 per year. > > Plus, me getting paid to work on Flaming Thunder is far more > motivating than me not getting paid to work on Python. ?This weekend, > Python users will still be debating how to fix awkwardnesses in the > languages (such as FOR loops where you're just counting the loops and > not referencing the loop variable) -- but Flaming Thunder users will > be getting work done using the REPEAT n TIMES constructs that I'll be > implementing. > > Python has been around about 15 years, yet still has those > awkwardnesses. ?Flaming Thunder has been out less than 6 months and > those awkwardnesses are already getting fixed. ?The difference: I > can't afford to ignore users. > > But the future is one of the hardest things to predict, so we'll see. > > On May 13, 8:34?am, hdante wrote: > > > On May 13, 10:58?am, Paul McGuire wrote: > > > > On May 13, 8:32?am, Dave Parker wrote: > > > > > > Don't let yourself be irritated by castironpi > > > > > I'm not the sort to get irritated by anyone. ?There is value in all > > > > interaction. > > > > Not this interaction, I'm afraid. ?What irritates *me* about > > > castironpi is that he uses a chatterbot to clutter up the threads > > > here. ?If you go back to his postings from a year ago (and selected > > > ones since), his comments are coherent and sensible. ?These rambling > > > stream-of-consciousness rants about t.v.'s and coffee are (I guess) > > > his idea of a joke. ?But they are certainly not worth your time in > > > trying to respond to them. > > > > -- Paul > > > ?I don't think castironpi so annoying that I should filter its > > messages. It would be enough if he were better tuned. He is much > > smarter than the emacs shrink, for example. :-P > > > ?The "Flaming Thunder" looks promising, but without being free > > software, it's unlikely it will create a large developer community, > > specially considering both free general purpose and scientific > > programming languages.- Hide quoted text - > > > - Show quoted text - > > Notice that I said "free software", not "*** FREE *** software !!!! 1!" (that is, free as in freedom, not free as in beer). Read again my answer, considering this. From george.sakkis at gmail.com Fri May 9 20:53:19 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 9 May 2008 17:53:19 -0700 (PDT) Subject: anagram finder / dict mapping question References: <0ebda682-6c99-43b2-b88b-80f6c88e1c98@p25g2000hsf.googlegroups.com> <54f75240-d8ee-482c-baea-d37bf3900b76@i36g2000prf.googlegroups.com> Message-ID: <494e9c6a-9346-4134-943b-249956bebdd0@a23g2000hsc.googlegroups.com> On May 9, 5:19?pm, umpsu... at gmail.com wrote: > > > What would be the best method to print the top results, the one's that > > > had the highest amount of anagrams?? ?Create a new histogram dict? > > > You can use the max() function to find the biggest list of anagrams: > > > top_results = max(anagrams.itervalues(), key=len) > > > -- > > Arnaud > > That is the biggest list of anagrams, what if I wanted the 3 biggest > lists? ?Is there a way to specific top three w/ a max command?? >>> import heapq >>> help(heapq.nlargest) Help on function nlargest in module heapq: nlargest(n, iterable, key=None) Find the n largest elements in a dataset. Equivalent to: sorted(iterable, key=key, reverse=True)[:n] HTH, George From skanemupp at yahoo.se Tue May 13 21:40:36 2008 From: skanemupp at yahoo.se (globalrev) Date: Tue, 13 May 2008 18:40:36 -0700 (PDT) Subject: 2004 example, passing function error Message-ID: <3a70d3c9-41b9-4dfa-9127-ed6d1a8abda5@s50g2000hsb.googlegroups.com> http://linuxgazette.net/109/pramode.html >>> >>>def sqr(x): return x*x ... >>>def cube(x): return x*x*x ... >>>sqr >>>a = [sqr, cube] >>>a[0](2) >>>def compose(f, g): return f(g(x)) ... >>>compose(sqr, cube, 2) 64 >>> but i get: >>> compose(sqr, cube, 2) Traceback (most recent call last): File "", line 1, in compose(sqr, cube, 2) TypeError: compose() takes exactly 2 arguments (3 given) this: >>> def compose(f, g, x): return f(g(x)) >>> compose(sqr, cube, 2) 64 works though . so just a mistake on his part? but it looks like he just copied his shell...has there been a change since 2004 inr egards to how you can pass functions as arguments to functions?? From daveparker at flamingthunder.com Tue May 13 09:14:34 2008 From: daveparker at flamingthunder.com (Dave Parker) Date: Tue, 13 May 2008 06:14:34 -0700 (PDT) Subject: Is using range() in for loops really Pythonic? References: <482657ca$0$25026$607ed4bc@cv.net> <41078222-aec0-4e8b-8a1f-945cdf814498@m73g2000hsh.googlegroups.com> <48275446$0$11628$607ed4bc@cv.net> <0001HW.C44D0ADD008F9F39F0284530@news.verizon.net> Message-ID: > REXX's loop construct subsumes all the common uses... And worse, it > appears that a repetition and a condition can be part of the single > statement. Thank you for pointing out the REXX examples. I am a Kedit user, but had forgotten about the REXX do-loops. I'll keep them in mind when I add an easy way to "do this n times" to Flaming Thunder this weekend. On May 11, 8:53?pm, Dennis Lee Bieber wrote: > On Mon, 12 May 2008 00:43:08 GMT, Jonathsn Cronin > declaimed the following in comp.lang.python: > > > I agree in principle; the first is iteration and the second is repetition. > > In Python, the common idiom for a fixed number of repetitions is iterating > > over a number range. ?This is true in most languages I am familiar with, > > probably because fixed repetition, where you don't care about the "index" > > value, is rarely used. > > > The only language I've used that does have fixed repetition is an (old) > > dialect of lisp, and I'm not sure it even made it into Common Lisp. ? > > Smalltalk and Ruby do have fixed repetition. > > ? ? ? ? REXX's loop construct subsumes all the common uses... And worse, it > appears that a repetition and a condition can be part of the single > statement. > > DO FOREVER > ... > END > > DO repeatcount > ... > END > > DO loopvar=first TO last BY step FOR reptcount > ... > END > > (where "TO last", "BY step", "FOR reptcount" are all optional clauses!) > > DO WHILE conditional > ... > END > > DO UNTIL conditional > ... > END > > ? ? ? ? Mixing modes > > DO loopvar=first BY step UNTIL conditional > ... > END > > Hmmm, looks like it's been extended for container objects (those that > support MAKEARRAY): > > DO item OVER container > ... > END > -- > ? ? ? ? Wulfraed ? ? ? ?Dennis Lee Bieber ? ? ? ? ? ? ? KD6MOG > ? ? ? ? wlfr... at ix.netcom.com ? ? ? ? ? ? ?wulfr... at bestiaria.com > ? ? ? ? ? ? ? ? HTTP://wlfraed.home.netcom.com/ > ? ? ? ? (Bestiaria Support Staff: ? ? ? ? ? ? ? web-a... at bestiaria.com) > ? ? ? ? ? ? ? ? HTTP://www.bestiaria.com/ From bruno.desthuilliers at gmail.com Fri May 23 17:00:33 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Fri, 23 May 2008 14:00:33 -0700 (PDT) Subject: Python is slow References: <4836772e$0$6097$426a74cc@news.free.fr> Message-ID: <89be7f59-4c08-4739-ab07-d310e0c6aef3@2g2000hsn.googlegroups.com> On 23 mai, 10:42, "inhahe" wrote: > "Bruno Desthuilliers" wrote in > messagenews:4836772e$0$6097$426a74cc at news.free.fr... > > > Brad a ?crit : > >> cm_gui wrote: > >>> Python is slow. > > >> It ain't C++, but it ain't a punch card either... somewhere in between. I > >> find it suitable for lots of stuff. I use C++ when performance really > >> matters tho... right tool for the job. Learn a good interpreted language > >> (Pyhton) and a good compiled language (C or C++) > > > LordHaveMercy(tm). Could you guys please learn what you're talking about? > > > 1/ being interpreted or compiled (for whatever definition of these > > terms) is not a property of a language, but a property of an > > implementation of a language. > > That's like saying being spherical is not a property of planets, it's a > property of an instanciation of a planet. I do definitively not have the required knowledge to say anything about "being spherical" being part of the definition of what a "planet" is or not. >, and b) It's a far cry to > imagine a planet coming into being that's not spherical Idem > (a language as > dynamic as Python, or most other scripting languages, would be either > extremely difficult or impossible to make a native compiler for). Now this I can tell is false. The problem is not that it's difficult to "make a native compiler for" dynamic languages, the problem is that it's difficult to write native compiler for dynamic languages that generates code that beats the VM/byte-code interpreter/whatever you name it to be wotrh the effort. > I guess I > should also mention that Python isn't very practical (as in "suitable", > "right tool for the job", and "perfomance", as mentioned in the above post) > without an implementation. That is debatable. There are algorithm courses taught in "pseudo-code" - that is, a language that doesn't have any known implementation. > So I don't think this distinction has any use > other than to beat other people over the head with a bat. Ok, *you* know this - I mean, the distinction between a language and a language's implementation(s). Are you sure everyone saying - or reading - assertions such as "language XXX is slow" or "compiled languages are faster" etc really know what they're talking about ? > > 2/ actually, all known Python implementations compile to byte-code. > > Which is then interpreted, but you're still technically right, because > "compiled" can mean either compiled to bytecode or compiled to native code, > despite what it actually did mean. Semantics FTW!! Yes, semantics. But a bit more than semantics - byte-code interpreters are usually way faster than "pure" interpreter, and start to be fast enough for quite a lot of practical use. Ok, I'll stop on this - once again, sorry for the noise, and please bear with me, I tend to be a bit too much on the pedantic side sometimes. But still, thanks to the pedantics peoples on usenet that taught me so much so far and still teach me more and more... From rowen at cesmail.net Thu May 15 16:03:08 2008 From: rowen at cesmail.net (Russell E. Owen) Date: Thu, 15 May 2008 13:03:08 -0700 Subject: Pass data from Python to C++ References: Message-ID: In article , brad wrote: > I have some c++ binaries that do rather intense number computations. > They do it well and rather quickly compared to other languages (not just > Python). ... > > However, other components can be written in a more user friendly, more > easily maintained language. We've chosen Python for this. The main > question now is how to pass the computationally heavy info to c++ from > within Pyhton. os.system is not ideal. Just wondering how other folks do > this? I have source to some of the c++ code, but some of it is in binary > from only. It can take stdin or arguments. You say you have "binary only", but I hope you have the header files as well. If so I would try SWIG first since it is mature and handles C++ quite well. If you don't have headers then I have no idea if it's even possible. (For plain C I would start with ctypes, but that doesn't cover this case. There are many other options including boost and Pyrex, but I've not used those.) -- Russell From rares at ics.uci.edu Sun May 25 02:56:10 2008 From: rares at ics.uci.edu (Rares Vernica) Date: Sat, 24 May 2008 23:56:10 -0700 Subject: which datastructure for fast sorted insert? References: Message-ID: use a set to store them: >>> s=set() >>> s.add('a') >>> s.add('b') >>> s set(['a', 'b']) >>> s.add('a') >>> s set(['a', 'b']) >>> s.add('c') >>> s set(['a', 'c', 'b']) >>> it does remove duplicates, but is it not ordered. to order it you can use: >>> l=list(s) >>> l.sort() >>> l ['a', 'b', 'c'] hth, Rares From pavlovevidence at gmail.com Tue May 13 19:46:23 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 13 May 2008 16:46:23 -0700 (PDT) Subject: Purpose of operator package References: Message-ID: On May 13, 6:09 pm, Eric Anderson wrote: > I mainly work in other languages (mostly Ruby lately) but my text > editor (Scribes) is python. With python being everywhere for dynamic > scripting I thought I would read the source to learn the language > better (I've gone through some basic tutorials but I always prefer to > learn from real source). There is one significant drawback of that.... > So right from the start I see the following: > > from operator import truth > if truth(argv): > # blah blah blah > > It is obvious they are testing to see if any command line arguments. > But curious for why the function is needed. It isn't. The above is terrible code. 1. You don't even need operator.truth; the built-in bool performs that job. However, this code could have been written before the advent of bool, so we'll give it a temporary pass. 2. bool in unnecessary in this context. 3. Lest someone claim that truth serves to document that you are asking for the boolean value of argv (i.e., whether it's not empty), it's redundnant since the if statement implies that. > So I look up the operator > package and fine it provides functions that are equivalent to the > native operators. So my question is why would someone right the above > instead of just > > if argv: > # blah blah blah > > Seems like unnecessary code but obviously I know nothing about Python. You know more than the person who wrote the code above. The purpose of the operator module is to provide functional representations of Python operators (and a few non-operators) for functional programming. They could, for example, be useful as the arguments of map and reduce. Few beginners use functional programming so you might not want to worry about it now, though if you've been using Ruby you might have done it before. operator.truth was one of the few things in that module that was useful for things other than functional programming, since there is no truth operator in Python. Now that the language has bool it's no longer needed. Carl Banks From bruno.desthuilliers at gmail.com Thu May 15 17:25:40 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Thu, 15 May 2008 14:25:40 -0700 (PDT) Subject: Class Methods Vs Any Other Callable References: <98b4a67c-9ec7-407c-8c80-06488bd48a68@e39g2000hsf.googlegroups.com> <690ap7F2u0ftdU1@mid.uni-berlin.de> <238061d6-9423-44c1-90b2-cc09f392db9b@p25g2000hsf.googlegroups.com> <2851a281-d3f2-46c5-8afe-a5dcd6fa31a6@59g2000hsb.googlegroups.com> <10cce8be-657c-4c40-9705-baebaf90301b@a70g2000hsh.googlegroups.com> <482c428c$0$9669$426a34cc@news.free.fr> Message-ID: On 15 mai, 17:53, Arnaud Delobelle wrote: > Bruno Desthuilliers writes: > > FWIW, I wonder why the BDFL choosed to implement __new__ as a > > staticmethod - there are probably some pretty good reasons, but not > > knowing them, it looks like __new__ would have been a perfect > > candidate for a classmethod. > > > So far, the only reason I can think of is that making it a classmethod > > would have required the use of super(Parent, cls) to call the parent's > > class __new__, which may (or may not - never had the case) be > > problematic (any guru on this ?) > > Don't know but I remember something about this in 'Unifying types and > classes'. There it is: > > Factoid: __new__ is a static method, not a class method. I > initially thought it would have to be a class method, and that's > why I added the classmethod primitive. Unfortunately, with class > methods, upcalls don't work right in this case, so I had to make > it a static method with an explicit class as its first > argument. Ironically, there are now no known uses for class > methods in the Python distribution (other than in the test > suite). I might even get rid of classmethod in a future release if > no good use for it can be found! > > (http://www.python.org/download/releases/2.2/descrintro/) Thanks Arnaud. I knew there was something about this, but just couldn't remember what. Now at least this factoid makes sense to me :-) Strange enough, it happened that classmethods ended being much more used that staticmethods... > I don't have the time to try to figure it out :( class Foo(object): @classmethod def dothis(cls): print "Foo.dothis, cls is %s" % cls @staticmethod def dothat(cls): print "Foo.dothat, cls is %s" % cls class Bar(Foo): @classmethod def dothis(cls): print "Bar.dothis, cls is %s" % cls try: Foo.dothis(cls) except Exception, e: print "trying direct call to Foo.dothis(cls), got %s" % e try: super(Bar, cls).dothis() except Exception, e: print "trying call to super(Bar, cls).dothis(), got %s" % e @staticmethod def dothat(cls): print "Bar.dothat, cls is %s" % cls try: Foo.dothat(cls) except Exception, e: print "trying direct call to Foo.dothat(cls), got %s" % e try: super(Bar, cls).dothat(cls) except Exception, e: print "trying call to super(Bar, cls).dothat(), got %s" % e For classmethods, you *need* to use super to call the parent's class classmethod from within the overridden child class classmethod. Which sometimes may not be what you want for __new__. While this is a kind of a corner case (that I never met so far, hence my interrogations about why is __new__ a staticmethod taking the class as argument instead of a classmethod), it is still a potential showstopper. From workitharder at gmail.com Wed May 21 20:06:07 2008 From: workitharder at gmail.com (bukzor) Date: Wed, 21 May 2008 17:06:07 -0700 (PDT) Subject: Returning to 'try' block after catching an exception References: Message-ID: On May 21, 4:33 pm, Karlo Lozovina <_karlo_ at _mosor.net_> wrote: > Andr? wrote innews:a9913f2d-0c1a-4492-bf58-5c78813c4458 at s50g2000hsb.googlegroups.com: > > > How about something like the following (untested) > > > done = False > > while not done: > > try: > > some_function() > > done = True > > except: > > some_function2() > > some_function3() > > Sure, that works, but I was aiming for something more elegant and Pythonic > ;). > > -- > _______ Karlo Lozovina - Mosor > | | |.-----.-----. web:http://www.mosor.net|| ICQ#: 10667163 > | || _ | _ | Parce mihi domine quia Dalmata sum. > |__|_|__||_____|_____| It's hard to get around a while loop if you want to conditionally repeat something. There's no built-in way to do what you ask. From kyosohma at gmail.com Fri May 23 16:53:28 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 23 May 2008 13:53:28 -0700 (PDT) Subject: csv iterator question References: <9bf8ca4b-5f5e-4c5f-ba3f-892a9430b1dd@t54g2000hsg.googlegroups.com> Message-ID: On May 23, 3:36?pm, davidj411 wrote: > When you save an open file to a variable, you can re-use that variable > for membership checking. > it does not seem to be that way with the csv.reader function, even > when set to a variable name. > > what is the best way to store the open CSV file in memory or do i need > to open the file each time? > > example of open method on file object: > fhandle=open(filename).readelines() > > example of csv.reader method: > reader = csv.reader(open(csvfilename)) > > here are my results:>>> reader = csv.reader(open('export.csv')) > >>> for line in reader: > > ... ?print line > > > > but when i try to iterate through it again, it appears to print > nothing (no error either). the file is exhausted? > > >>> for line in reader: > > ... ?print line > ... > > do i need to seek() the beginning of this file object ? any help is > greatly appreciated here. I think using seek() is what you need as it is currently starting on the last line that it read, so to speak. You should have just tried it...experimenting is part of the fun of Python, after all. Mike From tjreedy at udel.edu Sat May 17 13:54:05 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 17 May 2008 13:54:05 -0400 Subject: Distributing applications that use 3rd party modules References: <8728ad1c-2b4a-47db-aeda-8d2416b6bdc8@i76g2000hsf.googlegroups.com> Message-ID: "eliben" wrote in message news:b439e7f0-685b-46b6-b0ea-3161cc548868 at m45g2000hsb.googlegroups.com... | Is there a simple way to find out which packages are used by my | script ? Ggrep for import statements? (But that only only gives direct dependencies.) Does py2exe have an option to output the list it collects?| I think people have mentioned such here. From bruno.desthuilliers at gmail.com Wed May 7 15:10:26 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Wed, 7 May 2008 12:10:26 -0700 (PDT) Subject: Am I missing something with Python not having interfaces? References: <45de2f7e-484a-4871-bbaa-bf7eed5dfa40@x35g2000hsb.googlegroups.com> <68e2a1F2s43b2U1@mid.individual.net> Message-ID: On 7 mai, 18:05, Bjoern Schliessmann wrote: > jmDesktop wrote: > > Studying OOP and noticed that Python does not have Interfaces. > > By "OOP", you mean "Java", right? 8) > > > Is that correct? Is my schooling for nought on these OOP concepts > > if I use Python. Am I losing something if I don't use > > the "typical" oop constructs found in other languages (Java, C# > > come to mind.) > > AFAIK, Interfaces weren't "typical" before Java. CMIIW. > > BTW, Zope has interfaces. Not sure if it's exactly the same. > It isn't. From ivan.illarionov at gmail.com Mon May 26 18:24:14 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Mon, 26 May 2008 22:24:14 +0000 (UTC) Subject: Keyboard Events References: <14d057b1-3b62-4efb-bdb2-c20394c7268c@r66g2000hsg.googlegroups.com> <1e920a06-3741-4154-94a1-73b90f659e1b@z72g2000hsb.googlegroups.com> Message-ID: On Mon, 26 May 2008 15:18:00 -0700, Gandalf wrote: > On May 27, 12:00 am, Ivan Illarionov wrote: >> On Mon, 26 May 2008 14:40:18 -0700, Gandalf wrote: >> > Thanks! >> > Anyone know which library should i learn then? >> >> Looks like you need to dive into Win32 >> APIhttp://msdn.microsoft.com/en-us/library/ms697544(VS.85).aspxhttp:// msdn.microsoft.com/en-us/library/ms645530(VS.85).aspx >> and others >> combined with ctypes. >> >> Ivan > > well, that seems extremely valuable but how can i implement those > functions with python? Google is your friend Some links with examples: http://www.brunningonline.net/simon/blog/archives/000652.html http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/208699 From ivan.illarionov at gmail.com Mon May 26 14:54:50 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Mon, 26 May 2008 18:54:50 +0000 (UTC) Subject: Python web development that resembles PHP or classic ASP References: <66a261d8-c31d-4519-beb9-c8913f61a87d@m44g2000hsc.googlegroups.com> Message-ID: Sebastian 'lunar' Wiesner wrote: >>> Modern frameworks like Django or Grok require a somewhat great >>> adaption, since they strongly restrict the programmer's freedom. I >>> doubt, that you would get Django or Grok working like your asp >>> framework. >> >> Actually, modern frameworks (at least Djagno) does not "restrict the >> programmer's freedom", they only encourage clean design. > > Can we agree on the fact, that Django _encourages clean design_ by > _restricting the programmers freedom to some degree_? This comprise > would avoid an endless war about framework philosophy ;) (and isn't so > far from the truth, btw) Yes, it makes very little sense to not follow conventions in Django. I have no problem with some people call it "some degree of restriction" ;) If the OP wants PHP-style programming he will get better results with PHP because PHP was designed this way. Any Pythonic solution will be an overkill. Ivan From bruno.42.desthuilliers at websiteburo.invalid Mon May 19 06:16:56 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 19 May 2008 12:16:56 +0200 Subject: explain this function to me, lambda confusion In-Reply-To: References: <5cc7ef7a-dd21-4772-a7e3-765410f810bb@l17g2000pri.googlegroups.com> Message-ID: <48315398$0$14949$426a34cc@news.free.fr> inhahe a ?crit : >> Both the responses offer lambda free alternatives. That's fine, and >> given the terse documentation and problems that I had understanding >> them, I would agree. So what applications are lambdas suited to? I >> think the parameterised function model is one. >> What else? > > i've hardly ever used lambdas since map() and filter() were replaced by list > comprehension. two other uses I can think of for it are: using it as a > sorting key (which takes a function and lambdas are perfect for that when a > direct function isn't available. for example, lambda x: x.myName), import operator foos.sort(key=operator.attrgetter('myName')) From gagsl-py2 at yahoo.com.ar Mon May 12 02:25:41 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 12 May 2008 03:25:41 -0300 Subject: cgitb performance issue References: <481F585A.5080707@admailinc.com> Message-ID: En Mon, 05 May 2008 15:56:26 -0300, Ethan Furman escribi?: > I tried adding a form to our website for uploading large files. > Personally, I dislike the forms that tell you you did something wrong > and make you re-enter *all* your data again, so this one cycles and > remembers your answers, and only prompts for the file once the rest of > the entered data is good. However, the first time the form loads it can > take up to 30 seconds... any ideas why? Hard to tell without looking at the code... And what has cgitb to do with this? -- Gabriel Genellina From tarun.kap at gmail.com Mon May 5 14:11:19 2008 From: tarun.kap at gmail.com (TkNeo) Date: Mon, 5 May 2008 11:11:19 -0700 (PDT) Subject: SSL through python. possible ? References: <6ca74a29-1121-4b53-abb9-6bcecf33272a@m3g2000hsc.googlegroups.com> Message-ID: <715b8048-8b88-44cd-a40a-722650125f19@e53g2000hsa.googlegroups.com> On May 2, 1:52 pm, Mike Driscoll wrote: > On May 2, 1:20 pm, Heikki Toivonen wrote: > > > Mike Driscoll wrote: > > > On Apr 29, 8:56 am,TkNeo wrote: > > >> I need to do SSL file transfer using python? Is there a library i can > > >> use ? > > > >http://sandbox.rulemaker.net/ngps/m2/ > > > M2Crypto has since moved tohttp://chandlerproject.org/Projects/MeTooCrypto > > > -- > > Heikki Toivonen > > Whoops...I just went with the first link Google gave me. The link I > gave doesn't mention that the project has moved. Looks like the one > you link to is the 9th link on my Google search using the terms: > "python m2crypto". > > Sorry if I spread misinformation though. > > Mike ok i have tried around a lot but no luck. I think M2Crypto is my best option except it requires a minimum of python 2.4 which i don't have. What i am trying to do is to do an FTP transfer that uses SSL (username, password authentication) and not a certificate file. The few example i have found of the Openssl module use a certificate for authentication unlike what i want to do. Anyone has any ideas ? From wuwei23 at gmail.com Mon May 26 19:24:20 2008 From: wuwei23 at gmail.com (alex23) Date: Mon, 26 May 2008 16:24:20 -0700 (PDT) Subject: Using poplib to parse headers References: Message-ID: <25ad2c27-1a79-4402-99de-034fc2d59f77@v26g2000prm.googlegroups.com> On May 27, 8:39 am, Jean-Claude Neveu wrote: > I tried to do this by using in the i loop the line: > > message = email.message_from_file(j) > > but I get the error: "AttributeError: 'str' object has no attribute 'readline'" Heya, The email module has a second function - 'message_from_string' - which might be more useful here. Currently, you're passing to 'message_from_file' a string that it tries to treat as a file, hence it complaining about the string object not having part of the file object interface. (I've never used email or poplib, so this is just a guess...) - alex23 From ethan at stoneleaf.us Fri May 30 16:46:52 2008 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 30 May 2008 12:46:52 -0800 Subject: php vs python Message-ID: <484067BC.6090005@stoneleaf.us> Jerry Stuckle wrote: > > As I've said before - good programmers can write good code in any > language. > So... an eloquent speaker of English is also an eloquent speaker of Spanish/French/German? I think your statement would be correct if worded: some programmers can write good code in any language. There's a reason why computer coding paradigms are called 'languages' -- because they are, and as such they require different ways of thinking. Just because someone is good at playing pianos doesn't mean they are also good at wood carving. Just because someone is good (i.e. writes good code) in C / PHP / Python / Perl / Assembly / whatever does not inherently mean that that same person will be able to write good code in any other language. That's one reason why there are so many to choose from: different people think differently and most are only optimal in certain areas. Or perhaps your definition of a good programmer means somebody who can write good code in any language? What then is a programmer who can only write good code in a handful of languages? Or maybe only two languages? Or even only one? My definition of a good programmer is someone who can write good code in a computer language. I would use the word 'versatile' or even 'multi-lingual' to broaden the scope to more than one language. -- Ethan P.S. My apologies, Jerry, for writing back to you directly -- I haven't yet discovered how to post to newsgroups, and I do not know the php mailing list address. I guess by both our definitions I am not a 'good newsgroup poster.' ;-) From grante at visi.com Wed May 7 12:21:48 2008 From: grante at visi.com (Grant Edwards) Date: Wed, 07 May 2008 11:21:48 -0500 Subject: listening on TCP port References: <1515d2cc-6dec-4552-822c-0ba558be98c6@t54g2000hsg.googlegroups.com> Message-ID: On 2008-05-07, petr.poupa at gmail.com wrote: > is there anybody who has experience with listening on TCP port > with python? I am looking for anything codes, tutorials,... . http://docs.python.org/lib/module-socket.html -- Grant Edwards grante Yow! With YOU, I can be at MYSELF ... We don't NEED visi.com Dan Rather ... From afrobeard at gmail.com Thu May 15 17:51:48 2008 From: afrobeard at gmail.com (afrobeard) Date: Thu, 15 May 2008 14:51:48 -0700 (PDT) Subject: Making Variable Text Output More Pythonic? References: <015e35b2-165c-4693-bf6c-38ad0cce7553@t12g2000prg.googlegroups.com> Message-ID: <781ccceb-2474-484f-b6c8-f4b59b2396b5@27g2000hsf.googlegroups.com> Arnaud's code wont work if self.opt1 is None, an empty list, an empty tuple, False, etc, because all these evaluate to false. They wont print the internal state of these variables. [Just an informational notice, this may be the behavior you expect] Secondly, I'm not sure if you know the variable names from before hand in which case Casey's approach will work, or you need to know them via introspection. http://www.ibm.com/developerworks/library/l-pyint.html [Scroll down to attributes]. On May 16, 1:44?am, Arnaud Delobelle wrote: > Casey writes: > > Hi, > > > I have some classes that print variable outputs depending on their > > internal state, like so: > > > def __str__(self): > > ? ? out = [] > > ? ? if self.opt1: out += ['option 1 is %s' % self.opt1'] > > ? ? if self.opt2: out += ['option 2 is %s' % self.opt2'] > > ? ? .... > > ? ? return '\n'.join(out) > > > Is there any way to make this cleaner? > > Maybe. > > Have a dictionary of options rather than individual attributes; > options not in the dictionary are not set. E.g. > > mask = { > ? ? 'opt1': 'option 1 is %s', > ? ? 'opt2': 'option 2 is %s', > ? ? ... > ? ? } > > def __str__(self): > ? ? return '\n'.join(mask[o] % v for o,v in self.options.iteritems()) > > -- > Arnaud From Graham.Dumpleton at gmail.com Tue May 20 04:13:12 2008 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Tue, 20 May 2008 01:13:12 -0700 (PDT) Subject: scaling problems References: <1fi434dog4u92tk7na5qhvfapl70mg8d93@4ax.com> Message-ID: <6c980775-c761-45d3-aeee-7bb24ff14b57@k1g2000prb.googlegroups.com> On May 20, 2:00?pm, James A. Donald wrote: > > > 2. ?It is not clear to me how a python web application scales. ?Python > > > is inherently single threaded, so one will need lots of python > > > processes on lots of computers, with the database software handling > > > parallel accesses to the same or related data. ?One could organize it > > > as one python program for each url, and one python process for each > > > http request, but that involves a lot of overhead starting up and > > > shutting down python processes. ?Or one could organize it as one > > > python program for each url, but if one gets a lot of http requests > > > for one url, a small number of python processes will each sequentially > > > handle a large number of those requests. ?What I am really asking is: > > > Are there python web frameworks that scale with hardware and how do > > > they handle scaling? > > Reid Priedhorsky > > > This sounds like a good match for Apache withmod_python. > > I would hope that it is, but the question that I would like to know is > how does mod_python handle the problem - how do python programs and > processes relate to web pages and http requests when one is using mod_python, and what happens when one has quite a lot of web pages and > a very large number of http requests? Read: http://blog.dscpl.com.au/2007/09/parallel-python-discussion-and-modwsgi.html http://code.google.com/p/modwsgi/wiki/ProcessesAndThreading They talk about multi process nature of Apache and how GIL is not as big a deal when using it. The latter document explains the various process/threading modes when using Apache/mod_wsgi. The embedded modes described in that documentation also apply to mod_python. The server is generally never the bottleneck, but if you are paranoid about performance, then also look at relative comparison of mod_wsgi and mod_python in: http://code.google.com/p/modwsgi/wiki/PerformanceEstimates Graham From dieter at handshake.de Thu May 1 13:55:40 2008 From: dieter at handshake.de (Dieter Maurer) Date: 01 May 2008 19:55:40 +0200 Subject: Tremendous slowdown due to garbage collection In-Reply-To: <48161A65.6040705@animats.com> References: <49b55bca-cbb8-4ac9-8720-4be87b930d5c@m3g2000hsc.googlegroups.com> <03594410-2463-430a-81b1-3005cc7e7bac@m44g2000hsc.googlegroups.com> <48161A65.6040705@animats.com> Message-ID: John Nagle writes on Mon, 28 Apr 2008 11:41:41 -0700: > Dieter Maurer wrote: > > Christian Heimes writes on Sat, 12 Apr 2008 18:47:32 +0200: > >> andreas.eisele at gmail.com schrieb: > >>> which made me suggest to use these as defaults, but then > > > We observed similar very bad behaviour -- in a Web application server. > > Apparently, the standard behaviour is far from optimal when the > > system contains a large number of objects and occationally, large > > numbers of objects are created in a short time. > > We have seen such behaviour during parsing of larger XML documents, for > > example (in our Web application). > > Our solution to that was to modify BeautifulSoup to use weak pointers. > All the pointers towards the root and towards previous parts of the > document are "weak". As a result, reference counting alone is sufficient > to manage the tree. We still keep GC enabled, but it doesn't find much > to collect. It will not help in our setup. We, too, have almost no cycles -- but the GC does not know this: If a large number of objects are created temporarily and not released before the generation 1 threshoold is reached, then the garbage collector will start collections -- even, if there are no or very few cycles. A generation 2 garbage collection takes time proportional to the total number of (GC aware) objects -- independent of the number of cycles. Dieter From terry.yinzhe at gmail.com Sun May 18 11:32:28 2008 From: terry.yinzhe at gmail.com (Terry) Date: Sun, 18 May 2008 08:32:28 -0700 (PDT) Subject: Get all the instances of one class References: <29f39184-2daa-49fc-a7af-7f869fd2d688@h1g2000prh.googlegroups.com> Message-ID: <24267a4f-1406-42c2-bffc-f1ccd64f0218@w34g2000prm.googlegroups.com> On May 17, 8:04 am, "Gabriel Genellina" wrote: > En Fri, 16 May 2008 20:44:00 -0300, Terry > escribi?: > > > Is there a simple way to get all the instances of one class? I mean > > without any additional change to the class. > > Try with gc.get_referrers() > > py> import gc > py> class A(object): pass > ... > py> a,b,c = A(),A(),A() > py> A > > py> for item in gc.get_referrers(A): print type(item) > ... > > > > > > > > > > We need to filter that list, keeping only A's instances: > > py> [item for item in gc.get_referrers(A) if isinstance(item,A)] > [<__main__.A object at 0x00A40DC8>, <__main__.A object at 0x00A40DF0>, > <__main__.A object at 0x00A40E18>] > > -- > Gabriel Genellina But I saw in the help that we should "Avoid using get_referrers() for any purpose other than debugging. " From ivan.illarionov at gmail.com Tue May 27 03:36:20 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Tue, 27 May 2008 07:36:20 +0000 (UTC) Subject: Python web development that resembles PHP or classic ASP References: <66a261d8-c31d-4519-beb9-c8913f61a87d@m44g2000hsc.googlegroups.com> <483bb3e9$0$5100$426a74cc@news.free.fr> Message-ID: On Tue, 27 May 2008 09:10:40 +0200, Bruno Desthuilliers wrote: > Ivan Illarionov a ?crit : >> On Mon, 26 May 2008 21:26:55 +0200, Sebastian 'lunar' Wiesner wrote: >> >>> [ Ivan Illarionov ] >>> >>>> If the OP wants PHP-style programming he will get better results with >>>> PHP because PHP was designed this way. Any Pythonic solution will be >>>> an overkill. >>> Better shoot yourself in the foot with a PHP-like Python-thing, than >>> committing suicide by shooting yourself into the head with PHP ... >> >> :) I can't imagine anything uglier than Python with its significant >> whitespace wrapped inside HTML. I guess it could be more damaging than >> PHP which was written exactly for this purpose. > > Mako template's syntax looks not so ugly to me: > > <%inherit file="base.html"/> > <% rows = [[v for v in range(0,10)] for row in range(0,10)] %>
Your name%s
Your e-mail%s
Subject line%s
Your CSR
> % for row in rows: > ${makerow(row)} > % endfor >
> > <%def name="makerow(row)"> > > % for name in row: > ${name}\ > % endfor > > Mako templates are alright. I like them more than Django templates. From dave.g1234 at gmail.com Fri May 16 14:44:11 2008 From: dave.g1234 at gmail.com (dave.g1234 at gmail.com) Date: Fri, 16 May 2008 11:44:11 -0700 (PDT) Subject: namespaces and eval Message-ID: Suppose I have a function in module X that calls eval e.g, X.py _______ Def foo(bar): Eval(bar) _______ Now eval will be called using the default eval(bar,globals(),locals()) and globals will pull in anything in module X. Now I have module Y that calls bar like so Y.py ________ from x import * def biz(): print "Im a silly example!" Foo("biz()") _______ Python will complain that it cannot find biz because it's not the X module. My question - is there any way to a) get a listing of active namespaes search ALL active namespaces for a particular variable b) get the namespace of the caller withing passing it in (here, Y) c) do anything else to get biz without passing foo("biz()",locals(),globals()) or hacking biz into the __builtin__ namespace(don't know if it's even possible, but it defeats the purpose of what I'm trying to do) ? I realize this is here for a reason, but I'm working on something that's kind of a hack already Thanks dave More gratuitous context. Long story I'm trying to write a hack for a concise way of adding arbitrary methods to objects for JPA/JQuery like chaning eg. def foo(self): class wrap: def __init__(self, obj, globalz=globals(),localz= locals()): self.obj = obj self.localz = localz; self.globalz = globalz; def __callback__(self, *args, **kw): newargs = [self.obj]; newargs.extend(args); print locals ret = eval(self.name, self.globalz, self.localz) (*newargs,**kw); return wrap(ret); def __getattr__(self,name): if hasattr(self.obj,name): return getattr(self.obj,name); self.name = name; return self.__callback__; From duncan.booth at invalid.invalid Fri May 2 03:33:52 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 2 May 2008 07:33:52 GMT Subject: is +=1 thread safe References: <4819DA2D.3030508@ggmail.com> <67vs9qF2r409aU2@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch wrote: > On Thu, 01 May 2008 15:33:09 -0700, Gary Herron wrote: > >> Of course it's not thread safe. For the same reason and more basic, >> even the expression i++ is not thread safe in C++. >> >> Any such calculation, on modern processors, requires three operations: >> retrieve value of i into a register, >> increment the register >> write the value into i. > > There are no modern processors with an opcode for incrementing a memory > location!? At least my C64 can do that. ;-) > The operation i++ in C/C++ implies two things: it increments the memory location and returns the new result. That means there are at least two ways to generate code for this: increment memory load new value or load value incremenent store Neither of these is going to be thread-safe (even on a C64) unless you protect the operations somehow. The latter is probably preferred as it only implies two operations to memory whereas the former implies three. Even on your C64 incrementing a memory location involves both a read and a write, so if you have a multi-core C64(!) there is still scope for another processor to get into the middle of that increment instruction. From yguan08 at gmail.com Tue May 13 18:33:17 2008 From: yguan08 at gmail.com (yguan08 at gmail.com) Date: Tue, 13 May 2008 15:33:17 -0700 (PDT) Subject: help with file path exceeding 255 characters References: <411ca062-faa9-4635-8d69-90e69f465729@z72g2000hsb.googlegroups.com> <482a0a52@news.mel.dft.com.au> <4c4bce8e-d4b6-41ca-9a5c-ed2504a0c883@27g2000hsf.googlegroups.com> <482a16a5@news.mel.dft.com.au> Message-ID: <1c952025-9673-490a-8282-37903fd70dfc@8g2000hse.googlegroups.com> On May 13, 5:31?pm, John Machin wrote: > ygua... at gmail.com wrote: > > On May 13, 4:38 pm, John Machin wrote: > >> ygua... at gmail.com wrote: > >>> I have trouble of obtaining the file size of a file because the > >>> fullpath exceeds 255 characters. I get this message with > >> At the DOS command level, you can do > >> ? ? ?subst x: very\long\path > >> and then refer to > >> ? ? ?x:filestem.ext > >> where x is any unused drive letter. > > Good idea. But subst does not see to work with path that has spaces. > > It gives "Incorrect number of parameters" > > If any DOS command-line argument includes spaces, you need to quote it. > > os.system(r'subst x: "c:\my big fat path\rab oof\etc etc etc"') Yes, it works now. I am getting more on windows after coming a long way from Unix. Thanks a lot. From dstanek at dstanek.com Mon May 19 21:04:28 2008 From: dstanek at dstanek.com (David Stanek) Date: Mon, 19 May 2008 21:04:28 -0400 Subject: scaling problems In-Reply-To: References: Message-ID: On Mon, May 19, 2008 at 8:47 PM, James A. Donald wrote: > I am just getting into python, and know little about it, and am > posting to ask on what beaches the salt water crocodiles hang out. > > 1. Looks to me that python will not scale to very large programs, > partly because of the lack of static typing, but mostly because there > is no distinction between creating a new variable and utilizing an > existing variable, so the interpreter fails to catch typos and name > collisions. I am inclined to suspect that when a successful small > python program turns into a large python program, it rapidly reaches > ninety percent complete, and remains ninety percent complete forever. I can assure you that in practice this is not a problem. If you do proper unit testing then you will catch many, if not all, of the errors that static typing catches. There are also tools like PyLint, PyFlakes and pep8.py will also catch many of those mistakes. > 2. It is not clear to me how a python web application scales. Python > is inherently single threaded, so one will need lots of python > processes on lots of computers, with the database software handling > parallel accesses to the same or related data. One could organize it > as one python program for each url, and one python process for each > http request, but that involves a lot of overhead starting up and > shutting down python processes. Or one could organize it as one > python program for each url, but if one gets a lot of http requests > for one url, a small number of python processes will each sequentially > handle a large number of those requests. What I am really asking is: > Are there python web frameworks that scale with hardware and how do > they handle scaling? What is the difference if you have a process with 10 threads or 10 separate processes running in parallel? Apache is a good example of a server that may be configured to use multiple processes to handle requests. And from what I hear is scales just fine. I think you are looking at the problem wrong. The fundamentals are the same between threads and processes. You simply have a pool of workers that handle requests. Any process is capable of handling any request. The key to scalability is that the processes are persistent and not forked for each request. > Please don't read this as "Python sucks, everyone should program in > machine language expressed as binary numbers". I am just asking where > the problems are. The only real problem I have had with process pools is that sharing resources is harder. It is harder to create things like connection pools. -- David http://www.traceback.org From cjw at ncf.ca Tue May 20 20:43:01 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Tue, 20 May 2008 20:43:01 -0400 Subject: Misuse of list comprehensions? In-Reply-To: <038e4418$0$27258$c3e8da3@news.astraweb.com> References: <038e4418$0$27258$c3e8da3@news.astraweb.com> Message-ID: <48337015.80202@ncf.ca> John Salerno wrote: > I posted this code last night in response to another thread, and after I > posted it I got to wondering if I had misused the list comprehension. Here's > the two examples: > > Example 1: > -------------------- > def compress(s): > new = [] > > for c in s: > if c not in new: > new.append(c) > return ''.join(new) > ---------------------- > > Example 2: > ------------------------ > def compress(s): > new = [] > [new.append(c) for c in s if c not in new] > return ''.join(new) > -------------------------- > > In example 1, the intention to make an in-place change is explicit, and it's > being used as everyone expects it to be used. In example 2, however, I began > to think this might be an abuse of list comprehensions, because I'm not > assigning the result to anything (nor am I even using the result in any > way). > > What does everyone think about this? Should list comprehensions be used this > way, or should they only be used to actually create a new list that will > then be assigned to a variable/returned/etc.? > > Alternative ways of of looking at the problem are: # compress.py import sets def compress(s): new = [] [new.append(c) for c in s if c not in new] return ''.join(new) def compress1(s): new= [] d= dict(zip(s, len(s)*[[]])) return d.keys() def compress2(st): s= sets.Set(st) return s if __name__ == "__main__": s= 'In example 1, the intention to make an in-place change is explicit, and it is' print (compress(s)) print (compress1(s)) print (compress2(s)) Results: In exampl1,thiok-cgsd ['a', ' ', 'c', 'e', 'i', 'g', 'I', 'h', 'k', '-', 'm', 'l', 'o', 'n', '1', 'p', 's', 't', 'x', ',', 'd'] Set(['a', ' ', 'c', 'e', 'i', 'g', 'I', 'h', 'k', '-', 'm', 'l', 'o', 'n', '1', 'p', 's', 't', 'x', ',', 'd']) Colin W. From ivlenin at gmail.com Tue May 13 19:30:22 2008 From: ivlenin at gmail.com (I V) Date: Tue, 13 May 2008 23:30:22 GMT Subject: Purpose of operator package References: Message-ID: On Wed, 14 May 2008 00:38:44 +0200, Christian Heimes wrote: > Eric Anderson schrieb: >> Seems like unnecessary code but obviously I know nothing about Python. > > Correct, the truth example isn't a good example. "if argv" is better. I hadn't heard of operator.truth before. Does it do anything different from bool(x) ? From stefan_ml at behnel.de Thu May 15 14:14:43 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 15 May 2008 20:14:43 +0200 Subject: Using file objects with elementtree In-Reply-To: References: <5dca8f2f-ba08-4cf6-9d45-da2b2e532af8@x35g2000hsb.googlegroups.com> <69184aF2tsmnaU1@mid.uni-berlin.de> Message-ID: <482C7D93.2080809@behnel.de> castironpi at gmail.com wrote: > What do we render? Sur. Stefan From mattheww at chiark.greenend.org.uk Fri May 23 13:23:04 2008 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 23 May 2008 18:23:04 +0100 (BST) Subject: Relationship between GUI and logic? References: <48363c34$0$15204$607ed4bc@cv.net> Message-ID: John Salerno wrote: > Basically, the question is this: can you write the logic behind a > program (whether it be a game, an email client, a text editor, etc.) > without having any idea of how you will implement the GUI? You probably could, but it's best not to unless you're somehow forced to. In practice, the interface that you want your 'logic' layer to provide to the GUI is likely to depend on some of the details of how the GUI works. If you did the lower levels first without having any idea at all of what you were going to do with the GUI, it's quite likely that you'd find you'd written a few functions which turned out not to be needed at all, or that some functionality that the GUI needs to use very frequently is rather slow to execute, or that some functionality that you thought belonged to the 'logic' is really better done in the GUI layer, and so on and so forth. For example, if you were writing the 'logic' for a chess program you might choose a way of modelling the board that can't represent a position with more than one black king. And then when you got round to doing the GUI you might find out that your users would like to be able to have this temporarily when setting up a position. -M- From johnjsal at NOSPAMgmail.com Sun May 18 20:25:16 2008 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sun, 18 May 2008 20:25:16 -0400 Subject: How do *you* use Python in non-GUI work? References: <20080518182022.990193bd.johnjsal@NOSPAMgmail.com> <6fb308f2-a5be-4641-aa04-561b1782c6bb@z72g2000hsb.googlegroups.com> Message-ID: <20080518202516.e858910c.johnjsal@NOSPAMgmail.com> On Sun, 18 May 2008 16:17:55 -0700 (PDT) Mensanator wrote: > I see no need for GUI in any of these applications. Yeah, I try to find little projects to write in Python that don't involve a GUI. It's quicker, for one thing, and I also find that there is much more of a focus on the actual problem rather than wasting time trying to get a button positioned just right. :) Even back when I was using Windows 3.1 and 95, I enjoyed doing stuff in DOS because it made me feel like I was actually getting work done. :) From upton at virginia.edu Wed May 14 14:22:02 2008 From: upton at virginia.edu (Dan Upton) Date: Wed, 14 May 2008 14:22:02 -0400 Subject: I'm stuck in Python! In-Reply-To: References: <0563506d-bd36-404d-8961-4c4c5d1cc029@t54g2000hsg.googlegroups.com> Message-ID: <5504f9ac0805141122k18ca0a57l2da0b95c4a76db41@mail.gmail.com> On Tue, May 13, 2008 at 10:55 PM, alex23 wrote: > On May 14, 5:41 am, "inhahe" wrote: >> "George Sakkis" wrote in message >> > You must be new here. It is an AS (Artificial Stupidity) trolling bot, >> > you can safely ignore its posts. >> >> How does it generate text? > > My guess is by inhaling a lot of intoxicants. > -- > http://mail.python.org/mailman/listinfo/python-list > I assumed his message with the subject "bytes1.shuffle()" from a few days ago was a glimpse into his source code. Or something like it. From gagsl-py2 at yahoo.com.ar Sun May 18 04:49:33 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 18 May 2008 05:49:33 -0300 Subject: morning in Python References: <409ea9f1-9774-4bf2-abac-2daf997bc97f@c65g2000hsa.googlegroups.com> Message-ID: En Sun, 18 May 2008 04:42:58 -0300, inhahe escribi?: > To those who don't want me to feed the bot, I'm sorry. It's not a bot, and > I don't know the policy on having philosophical conversations. If you manage to stay on topic... -- Gabriel Genellina From catphive at catphive.net Thu May 1 22:17:34 2008 From: catphive at catphive.net (Brendan Miller) Date: Thu, 1 May 2008 19:17:34 -0700 Subject: portable fork+exec/spawn Message-ID: <1msaxj5xgfjyf.u0cdrgdllnus$.dlg@40tude.net> I want to spawn a child process based on an external executable that I have the path for. I then want to wait on that executable, and capture it's output. In the os module, fork is only supported on unix, but spawn is only supported on windows. The os.system call is implemented by calling the C system call, which is of course inefficient and has portability gotchas because it calls the underlying system shell (sh for unix, cmd for windows, and who knows what on non unix, non windows platforms like VMS and mac os9). Most importantly, os.system forces you to wait on the process. Is there an actual portable means of asynchronously spawning a process and getting a handle to it, being able to write stdin and read stdout, or does everyone just write their own wrapper for fork and spawn? Sorry if this post sounds a little complainy. I was just surprised to find the os module lacking in portable abstractions over system services. Brendan From deets at nospam.web.de Wed May 7 09:31:02 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 07 May 2008 15:31:02 +0200 Subject: PHP + TinyButStrong Python replacement References: Message-ID: <68dp9jF2sko92U1@mid.uni-berlin.de> pistacchio wrote: > Mike Driscoll ha scritto: >> On May 7, 6:12 am, pistacchio wrote: >>> hi! i'm a php user and a python programmer. i'd love to use python for >>> my server side needs but i can't seem to find what i'm looking for. for >>> most of my php work i use mysql and tinyButStrong >>> (http://www.tinybutstrong.com) which is a very lightweight template >>> engine that offers powerful functionalities. you insert TBS tags in web >>> pages like: >>> >>>
[var.x]
>>> >>> and it replaces [var.x] with the value of global variable x. it also >>> makes blocks (and nested blocks) easy to implement: >>> >>>

[blk1;block=begin] [blk1.val]
>>> [blk1;block=end]

>>> >>> in the previous code it cycles throu all the values of the array blk1. >>> >>> it does many more things, like htlm escaping, url and js encoding etc, >>> conditional displaying etc, but it is not more confusing that inserting >>> pieces of code into the HTML (aka: littering the code and kissing >>> goodbye to the code/presentation separation). it comes in the form of a >>> single file with a single class that you can easily include in the code >>> and go. >>> >>> now, i've searched the net and it seems full of python-based frameworks >>> for doing server side scripting and templating, but none that suits my >>> needs. >>> >>> 1. i like writing code and i like control. i mean, open up the >>> simplest text editor and write in it. i don't want something that is >>> command-line driven or that writes code for me like ">>> >>> makePagesFromThisDatabase()". >>> 2. i want something very lightweight. i don't want dozen of options, >>> pre-made blogging parts ecc. i just need a good non invasive template >>> engine and the basic functions for server side scripting, like session >>> managing, request parsing, functions to manipulate html code (encodings >>> etc) >>> 3. i don't want to beg my hosting provider to install the libraries. >>> a simple include file should do the work. >>> 4. object oriented programming is not required (better: i prefer >>> plain old procedural programming). >>> >>> any help? thanks in advance >> > > hi, thanks for replaying > >> Did you look at TurboGears or Django? TG uses Kid in the 1.x series >> and Genshi in 2.x (I think) for templating purposes. There's also >> Cheetah, one of the more powerful Python templating engines out there. >> > > django is exacly the kind of giant i'm trying to avoid > >> http://genshi.edgewall.org/ > > the first lines of the tutorial read: > "First, make sure you have CherryPy 3.0.x installed" > Now, cherrypy is something that is not properly "include a file and get > going!" >> http://www.kid-templating.org/ > > kid seems to have a non-linear approach, but i may give it a try > >> http://www.cheetahtemplate.org/ > > cheetah was something that i already considered using. have i to > "install" it or can i just import it? You will need to install any of these. It is part of how python is designed. Extendability comes with a price-tag. I don't know for sure, but I guess the cherrypy-requirement of genshi is more for the tutorial, not for the templating itself. Diez From castironpi at gmail.com Mon May 12 21:20:54 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 12 May 2008 18:20:54 -0700 (PDT) Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <2b66a86e-5a05-4262-b3c9-4703b0ae3372@d1g2000hsg.googlegroups.com> Message-ID: <5b0e3f70-afde-4480-8713-e7113b1250d7@x35g2000hsb.googlegroups.com> On May 12, 8:18?pm, Dave Parker wrote: > On May 12, 7:12?pm, castiro... at gmail.com wrote: > > > Mine's been always messing up the color wheel. > > Messing up in what way? ?Are you using the colors to visualize > something? In a manner of speaking. I'm a first-time-live Information scientist, just out of work. LIS at school and plenty of computer study, which is fine. Yes, I am trying to visualize something. From alhanan_clinic at hotmail.com Tue May 6 16:05:22 2008 From: alhanan_clinic at hotmail.com (Issam) Date: Wed, 7 May 2008 00:05:22 +0400 Subject: Java or C++? Message-ID: I need to help me.. please.. I have assingment for C++ programe -------------- next part -------------- An HTML attachment was scrubbed... URL: From bruno.desthuilliers at gmail.com Wed May 14 17:23:09 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Wed, 14 May 2008 14:23:09 -0700 (PDT) Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <5b0e3f70-afde-4480-8713-e7113b1250d7@x35g2000hsb.googlegroups.com> <1f537717-00d0-48ee-99b6-7125b96a6133@t12g2000prg.googlegroups.com> <68t4o0F2vaoncU1@mid.uni-berlin.de> <2a32179a-9439-449c-bd07-fff6a4075aee@s50g2000hsb.googlegroups.com> <7ee5dffd-df8f-46f0-bd78-c81ac0418a9a@d77g2000hsb.googlegroups.com> <65ef773e-a1c3-4adb-a18b-e8b8451efe5e@b5g2000pri.googlegroups.com> <68trmmF2vjivnU1@mid.uni-berlin.de> <68tuhfF2unducU1@mid.uni-berlin.de> <68tulsF2unducU2@mid.uni-berlin.de> Message-ID: On 13 mai, 19:05, Dave Parker wrote: > > Just to support this statement: PHP runs an order of magnitude slower than > > python. Yet a great deal (if not the majority) of dynamic sites out there > > run under PHP. All of these are unhappy customers? > > The websites owners might not be unhappy, but lots of customers > complain about slow websites, so if the market is competitive then > eventually the PHP fad will die out. > Some of the slower websites I've seen where using Java - which is supposedly way faster than Python. And even a static (pure HTML) web site can become more than painfully slow if the server can't handle the load, as anyone working in the field could tell you. But this is obviously one more area where you are just totally clueless. From rpm9deleteme at earthlink.net Thu May 22 21:35:10 2008 From: rpm9deleteme at earthlink.net (RPM1) Date: Thu, 22 May 2008 21:35:10 -0400 Subject: Python is slow References: <3J6dnbQZld6PZKjVnZ2dnUVZ_sDinZ2d@comcast.com> Message-ID: Larry Bates wrote: > If your Python program is > slow, you have almost assuredly approached it with a wrong method or > algorithm. I agree for most applications. There are however times where Python just isn't fast enough, and that's usually when people write extension modules. I have yet to see a chess engine written in Python that is competitive with even a below average C or C++ chess engine. The same could be said of Java, VB, C#, Pearl, ... So there ARE some tasks that Python just isn't suited for due to performance, but not enough for it to steer anyone away from Python. I have been working on a chess engine and have found that I prototype in Python and then port to the D programming language, (which IS fast). For example, one of my routines, (generating pseudo-legal moves -- no evaluation), in Python runs at 700,000 moves per second, (using Psyco). Ported to D it runs at 22 million moves per second. Python's advantage is in the software development and maintenance phases. As long as the runtime phase is fast ENOUGH, Python kicks most other languages butts. Patrick From castironpi at gmail.com Thu May 15 09:32:37 2008 From: castironpi at gmail.com (castironpi) Date: Thu, 15 May 2008 06:32:37 -0700 (PDT) Subject: send yield Message-ID: <6a19b5bf-ed71-499c-a348-6e26e2f523eb@m45g2000hsb.googlegroups.com> Why can't I write this? From grante at visi.com Mon May 5 10:35:44 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 05 May 2008 09:35:44 -0500 Subject: Nested os.path.join()'s References: Message-ID: On 2008-05-05, Paul Scott wrote: > Today, I needed to concatenate a bunch of directory paths and files > together based on user input to create file paths. I achieved this > through nested os.path.join()'s which I am unsure if this is a good > thing or not. > > example: > > if os.path.exists(os.path.join(basedir,picdir)) == True : > blah blah That's not an example of nested os.path.join()'s. > Question is, is there a better way of doing this? I don't think so. > The above *works* but it looks kinda hackish... What about it do you think looks hackish? I supposed you could do this instead: path = os.path.join(basedir,picdir) if os.path.exists(path) == True : blah blah But I don't really see why that's any better. -- Grant Edwards grante Yow! Like I always say at -- nothing can beat visi.com the BRATWURST here in DUSSELDORF!! From bronger at physik.rwth-aachen.de Fri May 2 11:01:12 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Fri, 02 May 2008 17:01:12 +0200 Subject: #!/usr/bin/env python vs. #!/usr/bin/python References: <87abj91j8u.fsf@benfinney.id.au> <87k5iczvdy.fsf@benfinney.id.au> <87y76ssrx0.fsf@physik.rwth-aachen.de> Message-ID: <87tzhgsqbr.fsf@physik.rwth-aachen.de> Hall?chen! D'Arcy J.M. Cain writes: > On Fri, 02 May 2008 16:26:51 +0200 > Torsten Bronger wrote: > >>> Certainly #! /usr/bin/python is fine if you never expect your >>> software to run outside of your own little corner of the world >>> but you asked why people prefer the env version and the answer >>> is that we want to write software that runs everywhere that >>> Python runs. >> >> Granted, but you must draw the line somewhere anyway. I cannot > > No one is talking about if statements here. Sorry to become laconical, but your reply was so, too: http://en.wikipedia.org/wiki/Abstraction Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From Fdateyhj at gmail.com Sat May 10 17:21:20 2008 From: Fdateyhj at gmail.com (law) Date: Sat, 10 May 2008 14:21:20 -0700 (PDT) Subject: =?windows-1252?Q?Special_INFORMATION_=96_a_must_read?= Message-ID: <8ed93ac5-37e6-4347-ba46-ceb3d99d1a59@26g2000hsk.googlegroups.com> Interesting information found at PASGOM. Just click on; http://www.pasgom.org/traffic.html http://www.pasgom.org/Stores.html You may look at this important INFO, view the short but interesting movies, and even share with others. Interestingly, Registration for all these is FREE. Nkaw From marco at sferacarta.com Tue May 6 08:15:33 2008 From: marco at sferacarta.com (Marco Mariani) Date: Tue, 06 May 2008 14:15:33 +0200 Subject: parameters to lambda's executed at run time. In-Reply-To: <48203672$1_4@news.bluewin.ch> References: <48203672$1_4@news.bluewin.ch> Message-ID: Boris Borcic wrote: > One way : > > >>> from functools import partial > >>> def func(item) : print item > > >>> llist = [partial(func,item) for item in range(5)] > >>> for thing in llist : thing() > > 0 > 1 > 2 > 3 > 4 Another way: class Func(object): def __init__(self, item): self.item = item def __call__(self): print self.item llist = [Func(item) for item in range(5)] for thing in llist: thing() From george.sakkis at gmail.com Mon May 12 21:52:49 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 12 May 2008 18:52:49 -0700 (PDT) Subject: Is using range() in for loops really Pythonic? References: <482657ca$0$25026$607ed4bc@cv.net> <48275316$0$11629$607ed4bc@cv.net> <3042f24f-f32e-4266-8bf5-41cdb511b78d@m45g2000hsb.googlegroups.com> <873aoo6k8z.fsf@benfinney.id.au> <87skwn5dly.fsf@benfinney.id.au> Message-ID: <761a3c96-3faf-4347-aeb7-4ca9cba67e42@a23g2000hsc.googlegroups.com> On May 12, 7:03?pm, Ben Finney wrote: > Carl Banks writes: > > IMHO, whether a varibale is used or not has got to be one of the least > > important things of all (in no small part because it's easily > > discernable from nearby code). > > I couldn't disagree more. > > If you're binding a name to a value that will never be used, you're > doing me (the reader of the code) a great favour if you indicate > clearly and concisely that this value is not intended to be referenced > anywhere else. Saving time for the reader is a very important job of > the writer of code. If you push this logic too far, you should del every name immediately after the last statement it is used in the scope. I would generally find less readable some code spread with del every few lines, micro- managing the effective scope of each name. YMMV. George From bruno.42.desthuilliers at websiteburo.invalid Thu May 15 06:36:34 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 15 May 2008 12:36:34 +0200 Subject: List behaviour In-Reply-To: References: Message-ID: <482c1226$0$28403$426a34cc@news.free.fr> Gabriel a ?crit : > Hi all > > Just wondering if someone could clarify this behaviour for me, please? > >>>> tasks = [[]]*6 >>>> tasks > [[], [], [], [], [], []] >>>> tasks[0].append(1) >>>> tasks > [[1], [1], [1], [1], [1], [1]] > > Well what I was expecting to end up with was something like: > ?>>> tasks > [[1], [], [], [], [], []] The problem here is that your first statement #>>> tasks = [[]]*6 creates a list (task) containing 6 references to the *same* (empty) list object. You can check this easily using the identity test operator 'is': #>>> tasks[0] is tasks[1] True In fact, it's exactly as if you had written: #>>> task = [] #>>> tasks = [] #>>> for i in range(6): #... tasks.append(task) #... If you want 6 different list objects in tasks, you can use a list comprehension instead: #>>> tasks = [[] for i in range(6)] #>>> tasks [[], [], [], [], [], []] #>>> tasks[0].append(1) #>>> tasks [[1], [], [], [], [], []] HTH From christof.ecker at googlemail.com Fri May 23 09:43:33 2008 From: christof.ecker at googlemail.com (christof) Date: Fri, 23 May 2008 06:43:33 -0700 (PDT) Subject: KeyError in pickle References: <6eb38a0e-1ecc-46f7-92b7-1dd816efe206@8g2000hse.googlegroups.com> Message-ID: <972ec25f-4ff5-48d6-8c10-7578584d76d7@8g2000hse.googlegroups.com> On 23 Mai, 10:48, Peter Otten <__pete... at web.de> wrote: > christof wrote: > > I am using pickle/unpickle to let my program save its documents to > > disk. While this it worked stable for a long time, one of my users now > > complained, that he had a file which can't be loaded. > > > The traceback is: > > > File "pickle.pyo", line 1374, in loads > > File "pickle.pyo", line 858, in load > > KeyError: 'A' > > > Does anybody know this problem. How this can happen and how can I > > avoid it? > > Is this reproducible? How? If not I would guess that the file is corrupted. > > Peter I found the problem: the user did a text export and gave the exported file the wrong extension. So: the file was not valid python pickle. I should add a type signature to fhe file format to avoid this. Thanks anyway, Christof From skanemupp at yahoo.se Thu May 15 13:04:08 2008 From: skanemupp at yahoo.se (globalrev) Date: Thu, 15 May 2008 10:04:08 -0700 (PDT) Subject: exists=false, but no complaint when i open it!? References: <285e0ce6-1371-4ab7-9281-ad1d664a480f@a23g2000hsc.googlegroups.com> Message-ID: <6ee5c146-dfe7-4b0b-99e7-b0905023b62a@d1g2000hsg.googlegroups.com> when i try to write to the file... Traceback (most recent call last): File "C:\Python25\myPrograms\netflix\netflix.py", line 10, in d.write('hej du galne kock') IOError: [Errno 0] Error From a.harrowell at gmail.com Thu May 29 10:17:12 2008 From: a.harrowell at gmail.com (TYR) Date: Thu, 29 May 2008 07:17:12 -0700 (PDT) Subject: Strange thing with types References: <969d0015-b689-48b0-966e-0f709574deea@m3g2000hsc.googlegroups.com> <138c1ce9-80b1-4123-b88d-364055f63d78@i18g2000prn.googlegroups.com> Message-ID: <908ec1ac-b449-4c99-9f09-5018bc13d4f4@l42g2000hsc.googlegroups.com> On May 29, 2:24 pm, alex23 wrote: > On May 29, 11:09 pm, TYR wrote: > > > > > I'm doing some data normalisation, which involves data from a Web site > > being extracted with BeautifulSoup, cleaned up with a regex, then > > having the current year as returned by time()'s tm_year attribute > > inserted, before the data is concatenated with string.join() and fed > > to time.strptime(). > > > Here's some code: > > timeinput = re.split('[\s:-]', rawtime) > > print timeinput #trace statement > > print year #trace statement > > t = timeinput.insert(2, year) > > print t #trace statement > > t1 = string.join(t, '') > > timeobject = time.strptime(t1, "%d %b %Y %H %M") > > > year is a Unicode string; so is the data in rawtime (BeautifulSoup > > gives you Unicode, dammit). And here's the output: > > > [u'29', u'May', u'01', u'00'] (OK, so the regex is working) > > 2008 (OK, so the year is a year) > > None (...but what's this?) > > Traceback (most recent call last): > > File "bothv2.py", line 71, in > > t1 = string.join(t, '') > > File "/usr/lib/python2.5/string.py", line 316, in join > > return sep.join(words) > > TypeError > > list.insert modifies the list in-place: > > >>> l = [1,2,3] > >>> l.insert(2,4) > >>> l > > [1, 2, 4, 3] > > It also returns None, which is what you're assigning to 't' and then > trying to join. > > Replace your usage of 't' with 'timeinput' and it should work. Thank you. From tjreedy at udel.edu Fri May 9 15:53:13 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 9 May 2008 15:53:13 -0400 Subject: the lvalue curse? let's play with this crazy idea ;) References: <68618c8b-f17e-496a-9092-5e2cd16b365b@p25g2000hsf.googlegroups.com> Message-ID: "XLiIV" wrote in message news:68618c8b-f17e-496a-9092-5e2cd16b365b at p25g2000hsf.googlegroups.com... Pipelining works best when all functions have just one input. But that is a small subset of actual programs. From Lie.1296 at gmail.com Fri May 16 16:56:10 2008 From: Lie.1296 at gmail.com (Lie) Date: Fri, 16 May 2008 13:56:10 -0700 (PDT) Subject: Scanning through Windows registry... References: <48216129.5090405@timgolden.me.uk> <2f0e3ef0-c33d-4dc3-819e-1c78e5bccb31@8g2000hse.googlegroups.com> <3a2ea1ec-7fa1-4740-aefa-ff83807fc227@x35g2000hsb.googlegroups.com> <6895c7ef-7886-4cf4-b558-a869a4bb9d06@z24g2000prf.googlegroups.com> Message-ID: On May 17, 2:06?am, Lie wrote: > On May 9, 7:36?pm, Unknown Hero wrote:> Ah, never mind, got it to work. Here's the code now. I hope I won't > > run into another problems later :D > > > > > #Goes through all keys and subkeys in the selected hive (defined as > > root) and replaces the value 'old' with the value 'new' > > # > > #IMPORTANT! You should always back up the registry before attempting > > to modify it. > > #The author of this script CANNOT BE HELD RESPONSIVE for any damage > > caused by running this script. > > (snip) > > One thing though, the disclaimer should not said the author cannot be > held responsive, or you would be Windows that is not responsive all > the times. I think it should say "responsible". > > I'm quite confused though, the code could be made simpler by dozens > using Python's high-level functionalities. Particularly the lengthy > code that checked whether the string contained a substring and replace > the substring with new could be done easily (and faster) using > python's in and replace function. I'll post the code later when I > finished checking places where the codes could be simplified, and I'll > also polish the entry code and a few other things (and pythonify the > code according to the PEP 8's guide lines). The tidied code ++ ''' Goes through all keys and subkeys in the selected hive (defined as root) and replaces the value 'old' with the value 'new' IMPORTANT! You should always back up the registry before attempting to modify it. The author of this script CANNOT BE HELD RESPONSIBLE for any damage caused by running this script. You can call the script from a command line and pass two or three values: HIVE, OLD, and NEW. OLD and NEW can be any string value HIVE has to be one of the following: HKEY_LOCAL_MACHINE / HKLM HKEY_CURRENT_USER / HKCU HKEY_CLASSES_ROOT / HKCR HKEY_USERS / HKU HKEY_CURRENT_CONFIG / HKCC If NEW is not specified, values that matches OLD will be replaced with empty string (i.e. deleted) ''' import _winreg import sys HIVES = { "HKEY_LOCAL_MACHINE" : _winreg.HKEY_LOCAL_MACHINE, "HKEY_CURRENT_USER" : _winreg.HKEY_CURRENT_USER, "HKEY_CLASSES_ROOT" : _winreg.HKEY_CLASSES_ROOT, "HKEY_USERS" : _winreg.HKEY_USERS, "HKEY_CURRENT_CONFIG" : _winreg.HKEY_CURRENT_CONFIG, } AccessError = False class RegKey(object): def __init__ (self, name, key): self.name = name self.key = key def __str__ (self): return self.name def walk(top): """ Walk through each key, subkey, and values Walk the registry starting from the key top in the form HIVE\\key\\subkey\\..\\subkey and generating key, subkey_names, values at each level. key is a lightly wrapped registry key, including the name and the HKEY object. subkey_names are simply names of the subkeys of that key values are 3-tuples containing (name, data, data-type). See the documentation for _winreg.EnumValue for more details. """ try: if "\\" not in top: top += "\\" root, subkey = top.split ("\\", 1) key = _winreg.OpenKey(HIVES[root], subkey, 0, _winreg.KEY_READ | _winreg.KEY_SET_VALUE) subkeys = [] i = 0 while True: try: subkeys.append(_winreg.EnumKey(key, i)) i += 1 except EnvironmentError: break values = [] i = 0 while True: try: values.append(_winreg.EnumValue(key, i)) i += 1 except EnvironmentError: break yield RegKey(top, key), subkeys, values for subkey in subkeys: for result in walk(top + "\\" + subkey): yield result except WindowsError: global AccessError AccessError = True def main(start, startHandle, old, new): basickeys = [] i = 0 while True: try: basickeys.append(_winreg.EnumKey(startHandle, i)) i += 1 except EnvironmentError: break for x in basickeys: for key, subkey_names, values in walk(start + "\\" + x): for (name, data, type) in values: if type == _winreg.REG_SZ: if old in data: winreg.SetValueEx(key.key, name, 0, type, data.replace(old, new)) print key.key, name, 0, type, data.replace(old, new) def help(): #Show help print ''' USAGE: Registry.py HIVE OLD [NEW] HIVE: The root key in registry you want to go through. HKEY_CLASSES_ROOT / HKCR HKEY_CURRENT_USER / HKCU HKEY_LOCAL_MACHINE / HKLM HKEY_USERS / HKU HKEY_CURRENT_CONFIG / HKCC OLD: The value to search for. Wrap multiword strings with "". NEW: The value which will replace OLD. Wrap multiword strings with "". If not supplied, it default to empty string which means delete all occurence of OLD in the registry. ''' if __name__ == '__main__': if len(sys.argv) < 3 or len(sys.argv) > 4: print 'Invalid Number of Arguments' help() exit() ## Root Hive try: start = { 'HKCU' : 'HKEY_CURRENT_USER', 'HKLM' : 'HKEY_LOCAL_MACHINE', 'HKCR' : 'HKEY_CLASSES_ROOT', 'HKU' : 'HKEY_USERS', 'HKCC' : 'HKEY_CURRENT_CONFIG', }[sys.argv[1].upper()] except KeyError: start = sys.argv[1].upper() try: startHandle = { 'HKEY_CURRENT_USER' : _winreg.HKEY_CURRENT_USER, 'HKEY_LOCAL_MACHINE' : _winreg.HKEY_LOCAL_MACHINE, 'HKEY_CLASSES_ROOT' : _winreg.HKEY_CLASSES_ROOT, 'HKEY_USERS' : _winreg.HKEY_USERS, 'HKEY_CURRENT_CONFIG' : _winreg.HKEY_CURRENT_CONFIG, }[start] except KeyError: print >> sys.stderr, 'Invalid Hive' help() exit() ## The substring to be replaced old = sys.argv[2] ## The replacement string try: new = sys.argv[3] except: new = '' main(start, startHandle, old, new) if AccessError: print ''' Some keys cannot be changed because you don't have the appropriate permission to modify those keys, please try again with a suitable user account. ''' From spectrumdt at gmail.com Fri May 9 06:19:03 2008 From: spectrumdt at gmail.com (spectrumdt at gmail.com) Date: Fri, 9 May 2008 03:19:03 -0700 (PDT) Subject: How to kill Python interpreter from the command line? References: Message-ID: <3d47e5d2-8e7c-497d-b461-7cc6ff1beb58@a1g2000hsb.googlegroups.com> Thanks for the replies. On May 8, 5:50?pm, Jean-Paul Calderone wrote: > Ctrl+C often works with Python, but as with any language, it's possible > to write a program which will not respond to it. ?You can use Ctrl+\ > instead (Ctrl+C sends SIGINT which can be masked or otherwise ignored, > Ctrl+\ sends SIGQUIT which typically isn't) Yes, thank you, this seems to work. :) I did some more testing and found out that the problem seems to be thread-related. If I have a single-threaded program, then Ctrl+C usually works, but if I have threads, it is usually ignored. For instance, the below program does not respond to Ctrl+C (but it does die when issued Ctrl+\): import threading def loop(): while True: pass threading.Thread(target=loop,args=()).start() From d3vvnull at gmail.com Sat May 3 12:30:54 2008 From: d3vvnull at gmail.com (Michael Mabin) Date: Sat, 3 May 2008 11:30:54 -0500 Subject: #!/usr/bin/env python vs. #!/usr/bin/python In-Reply-To: References: <87abj91j8u.fsf@benfinney.id.au> <87k5iczvdy.fsf@benfinney.id.au> <877ieczryn.fsf@benfinney.id.au> Message-ID: <170543c70805030930u5130cb42w5b55248038f42997@mail.gmail.com> I work on an AIX system where /usr/bin and /usr/local/bin apps can only be installed by root. Our system doesn't have python or many other tools we like to use installed so we have to install python in an alternate directory location. We have a system installation of Perl installed, but it's a release or two older than what we need, so we have done the same for perl. Thus, #!/usr/bin/env whatever allows our developers to experiment without always requiring the services of the admins, who are spread too thinly amongst all the other *Nixes they have to support, and who are also separated by many layers of red tape from us. On Sat, May 3, 2008 at 10:24 AM, Lou Pecora wrote: > In article , > Grant Edwards wrote: > > > On 2008-05-02, D'Arcy J.M. Cain wrote: > > > On Sat, 03 May 2008 00:44:00 +1000 > > > Ben Finney > > wrote: > > >> "D'Arcy J.M. Cain" writes: > > >> > As someone else pointed out, not all the world is Linux. > > >> > > >> It's a good thing I've never implied such to be the case. > > > > > > You haven't *said* it but you have definitely *implied* it. > > > Installing Python in /usr/bin is not common. > > > > It is common. That's where it's installed by almost all Linux > > distributions. > > MacOS X system python (or links to them) is in the same place. > > -- > -- Lou Pecora > -- > http://mail.python.org/mailman/listinfo/python-list > -- | _ | * | _ | | _ | _ | * | | * | * | * | -------------- next part -------------- An HTML attachment was scrubbed... URL: From wuwei23 at gmail.com Thu May 29 07:45:06 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 29 May 2008 04:45:06 -0700 (PDT) Subject: Compare 2 files and discard common lines References: <8d55718c-6881-4844-b8d1-bbe1c5929f46@x35g2000hsb.googlegroups.com> Message-ID: <4dadfe24-4c0c-4bd3-8e7c-d3d8ab2ef911@g16g2000pri.googlegroups.com> On May 29, 6:36 pm, loial wrote: > I have a requirement to compare 2 text files and write to a 3rd file > only those lines that appear in the 2nd file but not in the 1st file. > > Rather than re-invent the wheel I am wondering if anyone has written > anything already? >>> file1 = set((x for x in open('file1'))) >>> file2 = set((x for x in open('file2'))) >>> file3 = file2.difference(file1) >>> open('file3','w').writelines(file3) From stef.mientki at gmail.com Sun May 18 17:15:10 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Sun, 18 May 2008 23:15:10 +0200 Subject: multiple databases, what's the best interface ? In-Reply-To: <483021A3.9060908@egenix.com> References: <482F29DF.2040804@gmail.com> <483021A3.9060908@egenix.com> Message-ID: <48309C5E.5060902@gmail.com> thanks guys, I'll take a look at your suggestions. cheers, Stef M.-A. Lemburg wrote: > On 2008-05-17 20:54, Stef Mientki wrote: >> hello, >> >> I need to switch fluently between 2 or 3 types of dbases: >> SQLite, Sybase ( and in the future MS SQL-server). >> >> I need both closed application and general purpose database manager, >> which should run on different platforms (windows, windows mobile, not >> web based). >> >> I would like to write the applications in Python. >> What's the best interface so I can use the same program for all >> databases, >> and just have to change the database name, if I want to use another >> database ? > > If you need a common interface on all the platforms, then I'd suggest > you have a look at our mxODBC: > > http://www.egenix.com/products/python/mxODBC/ > > If you also need to support Windows Mobile, then you'll be interested > in our upcoming new product called "mxODBC Connect" which separates > the client from the server. > > mxODBC Connect allows using the mxODBC API on platforms which don't > come with ODBC drivers or where getting ODBC drivers is difficult. > Due to it's client-server approach it also simplifies configuration > a lot. > From mail at timgolden.me.uk Tue May 6 07:44:49 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 06 May 2008 12:44:49 +0100 Subject: Scanning through Windows registry... In-Reply-To: References: Message-ID: <482044B1.5040906@timgolden.me.uk> Unknown Hero wrote: > Hi everyone! > > Well, I have this need for a Python script that will scan through a > selected hive (like HKEY_LOCAL_MACHINE) and replace all strings that > contain word xxx (IE. foo) with yyy (IE. moo). I do not want partial > results, but rather complete strings (no foome or the like, just foo). > > > I have a basic understanding of Python, but this is beyond my skills. > > I was looking for something like this: > > open key (HKEY_LOCAL_MACHINE) > while (not end of list) > open next subkey > search subkey for value (old) > SetValue(key, subkey, REG_SZ, new) > close subkey > end while > close key In a spirit of teaching people to fish... ... If you put something like "Python windows registry" into Google, you get quite a few hits, the top one of which is probably pointing to the stdlib _winreg module, but several others point towards wrapper classes, modules etc. which provide a simpler or at least a different interface to the registry. Have a look at those and see if you can't work out what to do. TJG From darcy at druid.net Wed May 28 06:39:12 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Wed, 28 May 2008 06:39:12 -0400 Subject: A quick question In-Reply-To: References: Message-ID: <20080528063912.3a10053b.darcy@druid.net> On Wed, 28 May 2008 10:25:01 -0000 "James" wrote: > I just started using python and cant figure this out, I'm trying to > make a program where someone types in a word and the program gives it > back backwards. For example if the person puts in "cat" I want the > program to give it back as "tac" and what it does is prints out 3,2,1. > How can I get these integers to print as letters? This is what I have, > > word = raw_input("Type a word:") > start = len(word) > > for letter in range(start, 0, -1): > print letter Try "for letter in start:" -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From guptaabhishek1983 at gmail.com Thu May 29 15:38:22 2008 From: guptaabhishek1983 at gmail.com (abhishek) Date: Thu, 29 May 2008 12:38:22 -0700 (PDT) Subject: Help needed in choosing an algorithm for Cryptographic services. Message-ID: Hi group, recently my employer asked me too implement encryption/ decryption for secure data transfer over internet. Problem is that the client application is written using C# and the webserver where i need to store the information is developed using python. My situation of dilemma is which cryptographic method suits me best for this purpose. Help/Suggestions are urgently required Thank you , Abhishek From tjreedy at udel.edu Fri May 16 19:46:52 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 16 May 2008 19:46:52 -0400 Subject: can't delete from a dictionary in a loop References: <5504f9ac0805161422r31f3a0d6sbe4e49914ade7383@mail.gmail.com> Message-ID: "Dan Upton" wrote in message news:5504f9ac0805161422r31f3a0d6sbe4e49914ade7383 at mail.gmail.com... | RuntimeError: dictionary changed size during iteration If you do not actually need a dict, an explicitly managed list is an [untested]alternative. maxproc = # procs = [] while True: if len(procs) < maxproc: [populate procs up to maxproc] i, nprocs = 0, len(procs) if not nprocs: break while i < nprocs: if terminated(procs[i]): del procs[i] nprocs -= 1 else: i += 1 I am assuming that maxproc is low enough that the O(n) behavior of deletion is inconsequential. tjr From pavlovevidence at gmail.com Wed May 21 21:01:53 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 21 May 2008 18:01:53 -0700 (PDT) Subject: Bug in floating-point addition: is anyone else seeing this? References: <8187c3b6-a772-456f-a54f-0af7babb353e@w34g2000prm.googlegroups.com> Message-ID: <399b9f4e-3e36-40a5-bf02-ab2b25c1f4ef@d1g2000hsg.googlegroups.com> On May 21, 4:56 pm, Dave Parker wrote: > On May 21, 2:44 pm, "Jerry Hill" wrote: > > > My understand is no, not if you're using IEEE floating point. > > Yes, that would explain it. I assumed that Python automatically > switched from hardware floating point to multi-precision floating > point so that the user is guaranteed to always get correctly rounded > results for +, -, *, and /, like Flaming Thunder gives. Correct > rounding and accurate results are fairly crucial to mathematical and > scientific programming, in my opinion. Having done much mathematical and scientific prorgamming in my day, I would say your opinion is dead wrong. The crucial thing is not to slow down the calculations with useless bells and whistles. Scientists and engineers are smart enough to use more precision than we need, and we don't really need that much. For instance, the simulations I run at work all use single precision (six decimal digits) even though double precision is allowed. Carl Banks From jpthing at online.no Fri May 30 16:03:37 2008 From: jpthing at online.no (John Thingstad) Date: Fri, 30 May 2008 22:03:37 +0200 Subject: The Importance of Terminology's Quality References: Message-ID: P? Fri, 30 May 2008 02:56:37 +0200, skrev David Combs : > In article , > Robert Maas, http://tinyurl.com/uh3t > wrote: >>> From: "xah... at gmail.com" >>> the importance of naming of functions. >> > > Lisp is *so* early a language (1960?), preceeded mainly only by Fortran > (1957?)?, > and for sure the far-and-away the first as a platform for *so many* > concepts > of computer-science, eg lexical vs dynamic ("special") variables, passing > *unnamed* functions as args (could Algol 60 also do something like that, > via something it maybe termed a "thunk"), maybe is still the only one > in which program and data have the same representation -- that it'd > seem logical to use it's terminology in all languages. > > From C is the very nice distinction between "formal" and "actual" args. > > And from algol-60, own and local -- own sure beats "static"! > > And so on. > > > To me, it's too bad that that hacker-supreme (and certified genius) > Larry W. likes to make up his own terminology for Perl. Sure makes > for a lot of otherwise-unnecessary pages in the various Perl texts, > as well as posts here. > > Of course, a whole lot better his terminology than no language at all! > > > David > > Perl is solidly based in the UNIX world on awk, sed, bash and C. I don't like the style, but many do. -------------- John Thingstad From deets at nospam.web.de Wed May 21 18:21:38 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 22 May 2008 00:21:38 +0200 Subject: Bug in floating-point addition: is anyone else seeing this? In-Reply-To: References: <8187c3b6-a772-456f-a54f-0af7babb353e@w34g2000prm.googlegroups.com> Message-ID: <69jlk4F330nmpU1@mid.uni-berlin.de> Dave Parker schrieb: > On May 21, 3:19 pm, "Dan Upton" wrote: >> The fact is, sometimes it's better to get it fast and be good enough, >> where you can use whatever methods you want to deal with rounding >> error accumulation. > > I agree. > > I also think that the precision/speed tradeoff should be under user > control -- not at the whim of the compiler writer. So, for example, > if a user says: > > Set realdecimaldigits to 10. > > then it's okay to use hardware double precision, but if they say: > > Set realdecimaldigits to 100. > > then it's not. The user should always be able to specify the > precision and the rounding mode, and the program should always provide > correct results to those specifications. Which is exactly what the python decimal module does. Diez From gabriel.hasbun at gmail.com Tue May 6 00:00:24 2008 From: gabriel.hasbun at gmail.com (Gasto) Date: Mon, 5 May 2008 21:00:24 -0700 (PDT) Subject: Decimal vs Float comparasion References: Message-ID: I still don't see why such a module exists. On 5 mayo, 21:52, "Yuan HOng" wrote: > Hi, > > It seems decimal object will always be larger than float in > comparasion, which goes against common sense: > > >>> from decimal import Decimal > >>> a = Decimal('0.5') > >>> a > 99999 > False > >>> a > 99999.0 > > True > > It seems to me that rather than allowing this to happen, comparasion > between the two should either be made correct (by convertion decimal > to float e.g.) or forbidden, like arithmatic operations between the > two types. > > -- > Hong Yuan > > ????????? > ???????????http://www.homemaster.cn From cwitts at gmail.com Mon May 12 06:31:21 2008 From: cwitts at gmail.com (Chris) Date: Mon, 12 May 2008 03:31:21 -0700 (PDT) Subject: do you fail at FizzBuzz? simple prog test References: <39709320-66e1-40e9-a351-c769c9a94585@x41g2000hsb.googlegroups.com> Message-ID: On May 11, 3:12?am, globalrev wrote: > http://reddit.com/r/programming/info/18td4/comments > > claims people take a lot of time to write a simple program like this: > > "Write a program that prints the numbers from 1 to 100. But for > multiples of three print "Fizz" instead of the number and for the > multiples of five print "Buzz". For numbers which are multiples of > both three and five print "FizzBuzz". > > for i in range(1,101): > ? ? if i%3 == 0 and i%5 != 0: > ? ? ? ? print "Fizz" > ? ? elif i%5 == 0 and i%3 != 0: > ? ? ? ? print "Buzz" > ? ? elif i%5 == 0 and i%3 == 0: > ? ? ? ? print "FizzBuzz" > ? ? else: > ? ? ? ? print i > > is there a better way than my solution? is mine ok? personally if you're just checking if a modulus result is 0 or not I would rather do as it looks neat imho. for i in xrange(1,101): if not i % 3 and i % 5: print 'Fizz' elif i % 3 and not i % 5: print 'Buzz' elif not i % 3 and not i % 5: print 'FizzBuzz' else: print i From timr at probo.com Tue May 6 02:13:36 2008 From: timr at probo.com (Tim Roberts) Date: Tue, 06 May 2008 06:13:36 GMT Subject: USB HID documentation? References: <6885g8F2s6gaeU1@mid.uni-berlin.de> Message-ID: <1ktv14drbmuknvjrbf9kmnd8jb9mqv69so@4ax.com> "Diez B. Roggisch" wrote: > >You seem to misunderstand HID. HID is a protocol over USB (and Bluetooth I >believe) that will create user input device events which are mapped to your >OS input layer. That means that whenever you e.g. attach a keyboard device, >it's keyboard events will generate key-strokes on screen. No, it's more than that. HID devices that are not of a type directly claimed by the operating system (keyboards, mice) can be accessed by user-mode programs very easily on both Linux and Windows, without writing a custom driver. For low-bandwidth data sources, USB HID is an excellent way to provide general-purpose access to a USB device. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From bj_666 at gmx.net Thu May 8 16:57:11 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 8 May 2008 20:57:11 GMT Subject: pickle problem References: <68g456F2t41nqU1@mid.uni-berlin.de> <97b9fbd1-3725-4a7d-9ecb-1d2af6f35665@y21g2000hsf.googlegroups.com> Message-ID: <68h7p7F2su97jU3@mid.uni-berlin.de> On Thu, 08 May 2008 08:55:35 -0700, krustymonkey wrote: > The thing is, I'm not using slots by choice. I'm using the standard > lib "socket" class, which apparently uses slots. `socket` objects can't be pickled. Not just because of the `__slot__`\s but because a substantial part of their state lives in the operating system's space. Ciao, Marc 'BlackJack' Rintsch From ggpolo at gmail.com Wed May 7 17:04:12 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Wed, 7 May 2008 18:04:12 -0300 Subject: Looking for Fredrik Lundh; documentation and code examples for elementtree In-Reply-To: <7ac9f86d-d58b-4dee-b07d-e1b05390e185@e39g2000hsf.googlegroups.com> References: <7ac9f86d-d58b-4dee-b07d-e1b05390e185@e39g2000hsf.googlegroups.com> Message-ID: 2008/5/7 dj : > Hello All, > > I am trying to get in touch with Mr. Lundh. I am looking for exmaple > code regarding the use of elementtree. I have read through most of the > examples on http://effbot.org and I am hoping he can suggest some > others. Additionally, I am hoping he can give me an example use of the > comment method. I have tried a couple times, but I can not figure it > out. Thank you so very much. You should post some question actually, otherwise we can just point at google and some other links like: http://effbot.org/zone/element.htm, http://www.ibm.com/developerworks/xml/library/x-matters28/ And.. I think he has been busy these days because I also tried contacting him ;) Regards, > > DJ > -- > http://mail.python.org/mailman/listinfo/python-list > -- -- Guilherme H. Polo Goncalves From inhahe at gmail.com Mon May 26 16:46:55 2008 From: inhahe at gmail.com (inhahe) Date: Mon, 26 May 2008 16:46:55 -0400 Subject: definition of a highlevel language? References: <2759eed3-956d-45c7-8dfb-9557f74133b3@56g2000hsm.googlegroups.com> <7ac2b19c-2835-41dc-8099-ed1cec20253b@z72g2000hsb.googlegroups.com> Message-ID: > is it machine -> low-level -> highlevel > or is it machine -> highlevel > > ? yeah, machine is the lowest level, c is higher than machine. there isn't much that is lower level than c that isn't machine code. (assembler is just mnemonics for machine code, for the most part). it's machine -> low-level -> high level From daveparker at flamingthunder.com Tue May 13 13:14:21 2008 From: daveparker at flamingthunder.com (Dave Parker) Date: Tue, 13 May 2008 10:14:21 -0700 (PDT) Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <2b66a86e-5a05-4262-b3c9-4703b0ae3372@d1g2000hsg.googlegroups.com> <5b0e3f70-afde-4480-8713-e7113b1250d7@x35g2000hsb.googlegroups.com> <1f537717-00d0-48ee-99b6-7125b96a6133@t12g2000prg.googlegroups.com> <68t4o0F2vaoncU1@mid.uni-berlin.de> <2a32179a-9439-449c-bd07-fff6a4075aee@s50g2000hsb.googlegroups.com> <7ee5dffd-df8f-46f0-bd78-c81ac0418a9a@d77g2000hsb.googlegroups.com> <65ef773e-a1c3-4adb-a18b-e8b8451efe5e@b5g2000pri.googlegroups.com> <02a10e4b-5017-463c-96d2-e1779f2b9ebd@j22g2000hsf.googlegroups.com> Message-ID: <8bd40bb6-5f8d-4256-a41a-fe341d10d476@q1g2000prf.googlegroups.com> > Notice that I said "free software", not "*** FREE *** software !!!! > 1!" (that is, free as in freedom, not free as in beer). Read again my > answer, considering this. I misread your meaning. In a sense, Flaming Thunder is even more free than "free software". Flaming Thunder doesn't place any restrictions on how you use your source code or the executables you create. There is no GNU license that you need to worry about. On May 13, 11:06?am, hdante wrote: > On May 13, 12:24?pm, Dave Parker > wrote: > > > > > > > > ?The "Flaming Thunder" looks promising, but without being free > > > software, it's unlikely it will create a large developer community, > > > specially considering both free general purpose and scientific > > > programming languages. > > > Perhaps. ?Flaming Thunder is only $19.95 per year for an individual > > (and even less per individual for site licenses), which is less than > > the cost of just one book on Python. > > > I think that many people will find that Flaming Thunder is easier to > > use and understand than Python -- so for many people the amount of > > time they save will be worth more than the cost of Flaming Thunder > > (unless, of course, their time is worth $0). > > > Also, several users have rewritten their Python programs in Flaming > > Thunder, and found that Flaming Thunder was 5 to 10 times faster > > (Flaming Thunder compiles to native executables). ?So again, since > > many people value their time at more than $0, I think that many people > > will find that Flaming Thunder is worth $19.95 per year. > > > Plus, me getting paid to work on Flaming Thunder is far more > > motivating than me not getting paid to work on Python. ?This weekend, > > Python users will still be debating how to fix awkwardnesses in the > > languages (such as FOR loops where you're just counting the loops and > > not referencing the loop variable) -- but Flaming Thunder users will > > be getting work done using the REPEAT n TIMES constructs that I'll be > > implementing. > > > Python has been around about 15 years, yet still has those > > awkwardnesses. ?Flaming Thunder has been out less than 6 months and > > those awkwardnesses are already getting fixed. ?The difference: I > > can't afford to ignore users. > > > But the future is one of the hardest things to predict, so we'll see. > > > On May 13, 8:34?am, hdante wrote: > > > > On May 13, 10:58?am, Paul McGuire wrote: > > > > > On May 13, 8:32?am, Dave Parker wrote: > > > > > > > Don't let yourself be irritated by castironpi > > > > > > I'm not the sort to get irritated by anyone. ?There is value in all > > > > > interaction. > > > > > Not this interaction, I'm afraid. ?What irritates *me* about > > > > castironpi is that he uses a chatterbot to clutter up the threads > > > > here. ?If you go back to his postings from a year ago (and selected > > > > ones since), his comments are coherent and sensible. ?These rambling > > > > stream-of-consciousness rants about t.v.'s and coffee are (I guess) > > > > his idea of a joke. ?But they are certainly not worth your time in > > > > trying to respond to them. > > > > > -- Paul > > > > ?I don't think castironpi so annoying that I should filter its > > > messages. It would be enough if he were better tuned. He is much > > > smarter than the emacs shrink, for example. :-P > > > > ?The "Flaming Thunder" looks promising, but without being free > > > software, it's unlikely it will create a large developer community, > > > specially considering both free general purpose and scientific > > > programming languages.- Hide quoted text - > > > > - Show quoted text - > > ?Notice that I said "free software", not "*** FREE *** software !!!! > 1!" (that is, free as in freedom, not free as in beer). Read again my > answer, considering this.- Hide quoted text - > > - Show quoted text - From workitharder at gmail.com Wed May 21 16:27:18 2008 From: workitharder at gmail.com (bukzor) Date: Wed, 21 May 2008 13:27:18 -0700 (PDT) Subject: best way to check if pid is dead? References: <90ecca29-c4d8-4e89-908a-93850d7de1bf@i76g2000hsf.googlegroups.com> Message-ID: <7b049fb8-c196-4ff6-873b-3893ab670b95@m3g2000hsc.googlegroups.com> On May 21, 12:13 pm, Roy Smith wrote: > In article > <90ecca29-c4d8-4e89-908a-93850d7de... at i76g2000hsf.googlegroups.com>, > > bukzor wrote: > > Does anyone have a pythonic way to check if a process is dead, given > > the pid? > > > This is the function I'm using is quite OS dependent. A good candidate > > might be "try: kill(pid)", since it throws an exception if the pid is > > dead, but that sends a signal which might interfere with the process. > > > Thanks. > > --Buck > > The canonical way is to do kill(pid, 0). If it doesn't throw, the process > exists. No actual signal is sent to the process either way. > > Of course, the process could exit immediately after the kill() call, so by > the time you find out it's alive, it's dead. Such is life. Thanks! That's exactly what I was looking for. A little more background: "If sig is 0 (the null signal), error checking is performed but no signal is actually sent. The null signal can be used to check the validity of pid." Taken from : http://www.opengroup.org/onlinepubs/009695399/functions/kill.html From pecora at anvil.nrl.navy.mil Sat May 10 11:06:56 2008 From: pecora at anvil.nrl.navy.mil (Lou Pecora) Date: Sat, 10 May 2008 11:06:56 -0400 Subject: Mathematics in Python are not correct References: <52c855d8-5609-43e0-b98f-9fa87b2808c2@m3g2000hsc.googlegroups.com> Message-ID: In article , "Terry Reedy" wrote: > "Lou Pecora" wrote in message > news:pecora-DFE713.11234209052008 at ra.nrl.navy.mil... > | In article , > | "Terry Reedy" wrote: > | > | > "Luis Zarrabeitia" wrote in message > | > news:200805081914.06459.kyrie at uh.cu... > | > | Btw, there seems to be a math problem in python with > exponentiation... > | > | >>> 0**0 > | > | 1 > | > | That 0^0 should be a nan or exception, I guess, but not 1. > | > > | > a**b is 1 multiplied by a, b times. 1 multiplied by 0 no times is 1. > | > But there are unenlighted people who agree with you ;-) > | > Wikipedia has a discussion of this. > | > > | > tjr > | > | I like that argument better. But... > | > | I've also heard the very similar a**b is a multiplied by a b-1 times. > > Me too, in school, but *that* definition is incomplete: it excludes b=0 and > hence a**0 for all a. It was the best people could do before 0 was known. > But 0 was introduced to Europe just over 800 years ago ;-) [cut some interesting examples] Yes, I was also thinking about the b=0 case and then the case when b<0. If you solve the b<0 case, you solve the b=0 case for a !=0. Define a**b= a multiplied by 1/a |b-1| times when b<0. Then for b=0 we get a*(1/a)=1. Of course, I can avoid all this mathematical dancing around by using some of the other simpler definitions like the original one. :-) -- -- Lou Pecora From wizzardx at gmail.com Sat May 24 05:54:11 2008 From: wizzardx at gmail.com (David) Date: Sat, 24 May 2008 11:54:11 +0200 Subject: Unhandled exceptions checking In-Reply-To: <5bc79d5b-d22b-49a4-bab4-424230465818@y21g2000hsf.googlegroups.com> References: <5bc79d5b-d22b-49a4-bab4-424230465818@y21g2000hsf.googlegroups.com> Message-ID: <18c1e6480805240254s274cb71am25fb2cf1cfb32b72@mail.gmail.com> On Sat, May 24, 2008 at 3:31 AM, Yosifov Pavel wrote: > Does somebody know existent tool for checking unhandled exceptions? > Like in Java when method throws exception but in code using this > method, try...catch is missed. May be something like PyChecker? > Python is too dynamic to do this reliably. eg: e = exception_returning_func() raise e You'll probably be better served by capturing and logging all unhandled exceptions in your app ("logger.exception(e)" works nicely in a high level "catch Exception e" block), and then notifying users. Another thing to try is coverage testing. Won't raise all possible exceptions in a given piece of code, but at least you can check if all lines get run once. David. From hniksic at xemacs.org Fri May 16 05:16:34 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 16 May 2008 11:16:34 +0200 Subject: Instance of class "object" References: Message-ID: <8763tea9sd.fsf@mulj.homelinux.net> "??" writes: > Howdy, > I wonder why below does not work. > > a = object() > a.b = 1 # dynamic bind attribute failed... Because the default object class doesn't have a dict or other indication of state. It's a "pure" Python object whose only visible properties are its type and its identity. (On the implementation level it also has a refcount.) This is necessary because all other Python objects (both new-style classes and C extensions) inherit from 'object', on the C level. Having state in 'object' would mean having that same in *all* other Python objects. The current design, on the other hand, allows creation of very lightweight python objects that don't even have a dict. Subclassing object instructs Python as to what kind of state you want your class to have. The default is to have a dict to store properties: # a class with dict -- any property goes through dict, and creating a # Foo object actually creates two objects, one Foo and one dict class Foo(object): pass But you can also specify: # an efficient 'Pair' class holding two objects class Pair(object): __slots__ = 'first', 'second' Instances of Pair take up even less room that 2-element tuples because they don't carry the size information in the object. Now, if the object class carried a dict with it, it would be impossible to create a class like 'Pair'. > To make it correct, we have to create a new class: > class MyClass(object): pass > a = MyClass() > a.b = 1 # OK > > Does this strange behavior break the LSP (Liskov substitution > principle)? It follows from LSP that what the subclass may not introduce new preconditions. In this case the subclass accepts a case that the original class didn't, so it doesn't introduce a new precondition, it simply weakens (removes) an existing one. From saluk64007 at gmail.com Sat May 10 19:12:20 2008 From: saluk64007 at gmail.com (Patrick Mullen) Date: Sat, 10 May 2008 16:12:20 -0700 Subject: Now what!? In-Reply-To: <5dednf9GS5nNtbvVnZ2dnUVZ_qLinZ2d@posted.visi> References: <68m0i1F2t8265U1@mid.uni-berlin.de> <7363f4c0-1dec-4943-a9f6-7a24c3aff971@e39g2000hsf.googlegroups.com> <9GlVj.168$PE5.102@fe087.usenetserver.com> <5dednf9GS5nNtbvVnZ2dnUVZ_qLinZ2d@posted.visi> Message-ID: On Sat, May 10, 2008 at 3:57 PM, Grant Edwards wrote: > On a Linux system (and I presume on other Unixes), the kernel > itself (if built with the proper options) knows know how start > a "script" file that starts with the characters "#!". When the > kernel is told to execute a file whose first two bytes are "#!" > (0x32,0x21), it knows to read the newline terminated path of an > executable starting at the byte following the "!" (the third > byte in the file). The kernel then executes that file, > appending the name of the original "script" file to the argv > list. Wow, thanks for the history lesson. I was under the impression that this was a bash thing, I had no idea it went as deep as the kernel! -------------- next part -------------- An HTML attachment was scrubbed... URL: From duncan.booth at invalid.invalid Mon May 12 03:31:09 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 12 May 2008 07:31:09 GMT Subject: Python doesn't recognize quote types References: Message-ID: Dennis Lee Bieber wrote: > The sloppy use of "single quote" for the "apostrophe" is unfortunate > True, but that problem is outside of the Python community's control. Given that people do often refer to single quote when they mean apostrophe the error message should be written so as to minimise confusion. From tim.arnold at sas.com Mon May 12 17:45:00 2008 From: tim.arnold at sas.com (Tim Arnold) Date: Mon, 12 May 2008 17:45:00 -0400 Subject: using PIL for good screenshots Message-ID: Hi, I'm using PIL to enhance screenshots for print and online publication. I'm writing to see if someone else is doing similar work. The shots are dialogs, menus, etc. -- my workflow to create the print images: (1) writer takes screenshot on Windows XP box (96dpi) ---------------------- *** Python Image Library *** (2) convert to RGB (3) resize to a writer-specified width using nearest neighbor* (4) enhance with Sharpness enhancer, factor=2 I think these look pretty good, but if you have a different method or good advice, I'd like to hear from you. *nearest neighbor used for going up in size, antialias for going down in size. thanks, --Tim Arnold From ivlenin at gmail.com Thu May 22 23:00:28 2008 From: ivlenin at gmail.com (I V) Date: Fri, 23 May 2008 03:00:28 GMT Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> Message-ID: On Thu, 22 May 2008 19:35:50 -0700, Charles Hixson wrote: > Although when comparing Candygram with Erlang it's worth noting that > Candygram is bound to one processor, where Erlang can operate on > multiple processors. (I'd been planning on using Candygram for a project > at one point, but this made it unusable.) Really? The FAQ says it uses operating system threads, which I would have thought would mean it runs on multiple processors (modulo, I suppose, the issues with the GIL). From roopesh.raj at gmail.com Fri May 9 01:55:46 2008 From: roopesh.raj at gmail.com (Roopesh) Date: Thu, 8 May 2008 22:55:46 -0700 (PDT) Subject: Bug in email.utils, parseaddr Message-ID: Hi, I tried using parseaddr of email.utils, but it gave the following result when the name had a comma inside. >>> e = 'K,Vishal ' >>> from email.utils import parseaddr >>> parseaddr(e) ('', 'K') Thanks and Regards, Roopesh From gagsl-py2 at yahoo.com.ar Mon May 5 03:18:41 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 05 May 2008 04:18:41 -0300 Subject: bisect intersection References: <48160045.1030806@jouy.inra.fr> Message-ID: En Mon, 28 Apr 2008 13:50:13 -0300, Robert Bossy escribi?: > I stumbled into a sorted list intersection algorithm by Baeza-Yates > which I found quite elegant. For the lucky enough to have a springerlink > access, here's the citation: > http://dblp.uni-trier.de/rec/bibtex/conf/cpm/Baeza-Yates04 > > I implemented this algorithm in python and I thought I could share it. > I've done some tests and, of course, it can't compete against dict/set > intersection, but it will perform pretty well. Computing union and > differences are left as an exercise... Nice. As it only uses comparisons, it can be used even if the elements aren't hashable, that's good. But if they are hashable, using a set and sorting again at the end is much faster, as you discovered. -- Gabriel Genellina From s0suk3 at gmail.com Thu May 8 07:17:01 2008 From: s0suk3 at gmail.com (s0suk3 at gmail.com) Date: Thu, 8 May 2008 04:17:01 -0700 (PDT) Subject: Newbie to python --- why should i learn ! References: <9f5ee6c3-86f7-401a-acc8-cd2c9b059fbd@x19g2000prg.googlegroups.com> Message-ID: On May 8, 5:25 am, "Ra... at MyKavita.com" wrote: > Hi, > > i was reading/learning some hello world program in python. > I think its very simillar to Java/C++/C#. What's different (except > syntax) ? > > what can i do easily with python which is not easy in c++/java !? > Are you a newbie to Python, or to programming in general? I'll assume you are a newbie to programming in general because of that last question you asked. Things in Python are easier than in almost any other programming language. Here are three Hello World programs: --------------C++--------------------- #include main() { cout << "Hello World!"; return 0; } -------------------------------------- -------------Java--------------------- class HW { public static void main(String args[]) { System.out.println("Hello World!"); } } -------------------------------------- ------------Python-------------------- print "Hello World!" -------------------------------------- --------------C#---------------------- -------------------------------------- I think you can clearly see which one is easiest. Of course, that doesn't mean that the "easiest" language is always the "best" language, although it is a strong point. But ease of use is just a one- in-a-million characteristic of Python. If you're a total beginner, I'd recommend you learning the one that attracts you the most. From usenet1 at anton.e4ward.com Mon May 5 05:21:21 2008 From: usenet1 at anton.e4ward.com (Anton81) Date: Mon, 05 May 2008 11:21:21 +0200 Subject: Weird import problem References: <68674mF2rjrt5U1@mid.uni-berlin.de> Message-ID: >> NS/dir1/file1.py >> NS/dir2/file2.py > This *must* be wrong or at least not the full directory listing - please > read It is the directory structure in one of the python paths. > Missing __init__.py in the dir2? Oh right. I forgot about this. Thank you! From duncan.booth at invalid.invalid Thu May 1 03:59:35 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 1 May 2008 07:59:35 GMT Subject: calling variable function name ? References: <57461074-8fd1-4e65-9bc9-2ac916aa1fb5@y21g2000hsf.googlegroups.com> Message-ID: "thinkofwhy" wrote: > Try a dictionary: > > def funcA(blah, blah) > def funcB(blah, blah) > def funcC(blah, blah) > functions = {'A': funcA, 'B': funcB, 'C': > funcC} > user_func = 'A' > functions[user_func] #execute function Python has a neat concept for making this easy :^) it is called a class. class MyFunctions(object): def funcA(self, param1, param2): print "FA " + param1 + " " + param2 def funcB(self, param1, param2): print "FB " + param1 + " " + param2 def funcC(self, param1, param2): print "FC " + param1 + " " + param2 def defaultFunc(self, *args): print "Command not recognised" def doCommand(self, cmd, *args): return getattr(self, 'func'+cmd, self.defaultFunc)(*args) functions = MyFunctions() result = functions.doCommand('A', 'foo', 'bar') You have to add an extra 'self' argument to each function (or make it a staticmethod), but you could always use it to store state without resorting to globals. From tkpmep at hotmail.com Thu May 29 16:57:57 2008 From: tkpmep at hotmail.com (tkpmep at hotmail.com) Date: Thu, 29 May 2008 13:57:57 -0700 (PDT) Subject: Getting up and running with Python on a Mac Message-ID: <7d593f8a-92b8-4dfe-935f-dd6a22c70faf@m45g2000hsb.googlegroups.com> I've just bought an iMac (OS X 10.5.2, will almost immediately jump to 10.5.3), and am looking to install Python on it, and to use it with XCode, Apple's IDE. Some googling suggests that a number of people have had trouble getting Python to run satisfactorily on their Macs. This is my first Mac, and I'd appreciate some guidance on what to do (and what not to) when installing Python and potential problems to keep an eye open for. I want to do a fair bit of scientific / numerical computing, so it would seem that SAGE ot the Enthought Python distribution would seem to be the most relevant - I'd appreciate your guidance on getting Python to run on a Mac with a particular focus on these two distributions. Thank you in advance Thomas Philips From goldnery at gmail.com Sat May 31 19:25:10 2008 From: goldnery at gmail.com (Gandalf) Date: Sat, 31 May 2008 16:25:10 -0700 (PDT) Subject: Need Tutorial For the following lib References: <9950cf3f-e58a-413a-bdff-a40cc1c6cf6d@8g2000hse.googlegroups.com> Message-ID: <0bdd04b8-23b6-4a68-bda2-6984428ce7bd@b1g2000hsg.googlegroups.com> Hi scott, you couldn't be more wrong about my laziness. I straggle with my poor English for hours to fined what I'm looking for. I found a very simple and not comprehensive tutorial for the pyWinAuto lib in this address http://pywinauto.openqa.org/ but it only show how to do the basic, and my knowledge at this point is not enough to figure the rest I need to know by myself I found another simple lib for the watsup that based on winGuiAuto lib in this address http://www.tizmoi.net/watsup/intro.html But for some risen I couldn't manage to ran it in my computer I'm trying to generate auto mouse double click or auto selecting text (the selecting text part is the one I interest in. mouse double click just do the same effect if the mouse cursor is on text) I'm sorry you feel I'm lazy. The truth is that event writing this message takes me an enormous power. weather you choose to help me or not I still going to keep trying , But you have the opportunity to save me lots of trouble, So maybe one day I could help others. so if you familiar with any good tutorial for this library please let me know and if not then thank you anyway for wonting to help Y.G From mccredie at gmail.com Mon May 5 18:57:52 2008 From: mccredie at gmail.com (Matimus) Date: Mon, 5 May 2008 15:57:52 -0700 (PDT) Subject: config files in python References: <44f9662d-a88d-418c-a11d-b7b472b01fc3@j33g2000pri.googlegroups.com> Message-ID: On May 5, 10:22 am, Francesco Bochicchio wrote: > On Mon, 05 May 2008 00:35:51 -0700, sandipm wrote: > > Hi, > > In my application, I have some configurable information which is used > > by different processes. currently I have stored configration in a > > conf.py file as name=value pairs, and I am importing conf.py file to > > use this variable. it works well > > > import conf > > print conf.SomeVariable > > > but if I need to change some configuration parameteres, it would need > > me to restart processes. > > > I want to store this data in some conf file (txt) and would like to > > use it same way as I am using these variables as defined in py > > files. > > > one solution I can think of is writing data as a dictionary into conf > > file. and then by reading data, apply eval on that data. and update > > local dict? but this is not a good solution.... > > > any pointers? > > > Sandip > > The 'simple but relatively dangerous way', already suggested, is to > reload() the module. > > A safer way - but requiring more work - could be to build something around > the Configparser module in the standard library ... > > Ciao > ----- > FB How is it relatively dangerous? I mean, aside from any `dangers' associated with importing a user defined module in the first place. Matt From afilash+python at gmail.com Tue May 20 13:52:01 2008 From: afilash+python at gmail.com (abhilash pp) Date: Tue, 20 May 2008 23:22:01 +0530 Subject: AttributeError: module object has no attribute In-Reply-To: References: Message-ID: <9f9d35df0805201052r7fd6b54dof70822a0a820e23d@mail.gmail.com> hai nikhil, please check your __init__ file if you had any cheers, abhilash On Tue, May 20, 2008 at 11:00 PM, Nikhil wrote: > I have recently written a small module. When I import the module, I always > get the error > > > only when I do > > >>> from local.my.module import * > > -- > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'module' object has no attribute '/xyz/py/file' > --- > > > but when I do the below, I do not get any error. > > -- > >> import local.my.module > >> > -- > > Any ideas on what could be wrong? > > > Thanks in advance. > > Nikhil > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Fri May 23 07:59:43 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 23 May 2008 13:59:43 +0200 Subject: can python do some kernel stuff? In-Reply-To: <4836a876$0$11623$607ed4bc@cv.net> References: <983ec0f6-1316-40cd-a4d4-ce9b5e272a60@h1g2000prh.googlegroups.com> <48366cfa$0$15168$607ed4bc@cv.net> <28c432f0-657c-4272-8cd4-a9081b013279@w5g2000prd.googlegroups.com> <69nigsF3499pqU2@mid.uni-berlin.de> <4836994e$0$11625$607ed4bc@cv.net> <69nls3F344g2cU1@mid.uni-berlin.de> <4836a876$0$11623$607ed4bc@cv.net> Message-ID: <69nptfF318ps2U1@mid.uni-berlin.de> > > OP: "I am wondering if python can do some kernel coding that > used to be the private garden of C/C++." "kernel coding" is pretty clear I'd say - coding a or in the kernel. Not coding that runs on an OS that happens to have a kernel. > The answer is yes. IPC and py-pf are examples. If you don't think of > packet filtering as kernel coding, I can understand. But clearly the > Python interfaces to fork(), waitpid(), signal(), alarm() and so forth > are forays into the once private garden of C. Also not "kernel coding" in my book. system-near coding - yes. But not coding a kernel... Diez From omirek10 at poczta.onet.pl Mon May 12 09:54:41 2008 From: omirek10 at poczta.onet.pl (Odys) Date: Mon, 12 May 2008 06:54:41 -0700 (PDT) Subject: execfile python3k Message-ID: Hi there, Since execfile() is removed in Python 3.0 I have question about using exec. I know about exec(open('filename').read()) but from documentation the 1st arg of exec can be 'file object'. However exec(open('filename')) does not work. Does anybody have idea how to construct 'file object' then? Thanks, From see.signature at no.spam Fri May 2 04:53:08 2008 From: see.signature at no.spam (Eric Brunel) Date: Fri, 02 May 2008 10:53:08 +0200 Subject: Simple TK Question - refreshing the canvas when not in focus References: <16d36d38-43fe-4863-8df7-02c60c18600c@j22g2000hsf.googlegroups.com> <4818349e$0$2959$ba620e4c@news.skynet.be> <182ace66-bdf6-409c-85ee-fd764de8e1c6@z72g2000hsb.googlegroups.com> <8fbf2b85-1b6a-4f6c-a84e-934609fd0e4e@c58g2000hsc.googlegroups.com> Message-ID: On Wed, 30 Apr 2008 20:19:32 +0200, blaine wrote: > On Apr 30, 10:41 am, Peter Otten <__pete... at web.de> wrote: >> blaine wrote: >> > Still doesn't work. I'm looking into using wx instead... >> >> > This is the full code - does it work for anyone else? Just do a echo >> > 'line 0 0 10 10' > dev.file >> >> Haven't tried it, but I think that the problem is that you are updating >> the >> UI from the "readthread". A good example to model your app after is >> here: >> >> http://effbot.org/zone/tkinter-threads.htm >> >> Peter > > Update: Not only is that a good model, its exactly what I'm trying to > do. Thanks again! BTW, instead of reading the queue periodically, you can also use the event loop for that: in the secondary thread, generate a custom event using the event_generate method. Custom events are enclosed in '<<...>>', the '...' can be whatever you like. Be sure to generate the event with the when='tail' option or the event might get handled immediatly. To treat the event, do a binding on it: it will be called in your main thread. It's a common trick to switch threads so that GUI events are treated in the main thread and not in secondary ones. Example: ------------------------------------------ import threading import time import Queue from Tkinter import * root = Tk() q = Queue.Queue() def thread_action(): i = 1 while 1: time.sleep(1) q.put(i) root.event_generate('<>', when='tail') i += 1 v = StringVar() def ping_received(event): v.set(q.get()) Label(root, textvariable=v, width=10).pack() root.bind('<>', ping_received) th = threading.Thread(target=thread_action) th.setDaemon(1) th.start() root.mainloop() ------------------------------------------ HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From scuteezgb at gmail.com Fri May 9 10:06:49 2008 From: scuteezgb at gmail.com (gbin,Zhou) Date: Fri, 9 May 2008 07:06:49 -0700 (PDT) Subject: Can I "delete" the namespace of a module that i import? Message-ID: Hi,all. I see from "http://docs.python.org/tut/node11.html" that "Name spaces are created at different moments and have different lifetimes. The namespace containing the built-in names is created when the Python interpreter starts up, and is never deleted. The global namespace for a module is created when the module definition is read in; normally, module namespaces also last until the interpreter quits." So can I "delete" the namespace of a module that i import? thanks. From notbob at nothome.com Wed May 21 17:57:00 2008 From: notbob at nothome.com (notbob) Date: Wed, 21 May 2008 21:57:00 GMT Subject: php vs python References: <5l%Yj.77$mz3.53@fe101.usenetserver.com> Message-ID: On 2008-05-21, Damon Getsman wrote: > My suggestion, if you want to keep that gray meat sparking, is to go > with only html & php. You could have the php dumping your entries > into date/time named textfiles on there when you're writing, and when > someone is reading, it just orders them sequentially by the date & > time in their filenames. > > Then again, you learn the HTML+PHP+MySQL thing and you've got a skill > that you can market on Craigslist to a bunch of people for $20/hr > +. :) That certainly couldn't hurt. Thank you for your advice. nb From jon at ffconsultancy.com Thu May 15 13:00:35 2008 From: jon at ffconsultancy.com (Jon Harrop) Date: Thu, 15 May 2008 18:00:35 +0100 Subject: generate all possible math expr of one term References: <3abbfdf0-7e2a-4171-bbd9-dbb33ea81e6b@w4g2000prd.googlegroups.com> Message-ID: xahlee at gmail.com wrote: > Here's a example of Expressiveness of a Language. > > The following is Mathematica code that generates all possible > equations of one term involving trig function. (tweak the funList and > nesting level to define what ?all possible? means. if nesting level is > 2, it takes about 20 minutes and returns a list of 2876 terms on a > 2004 personal computer. > > << DiscreteMath`Combinatorica` > funList = {Sin, Tan, Power[#, -1] &}; > Nest[Module[{li = #}, > (Union[#, SameTest -> (Module[{arg1 = #1, arg2 = #2}, > If[(*both expression contains both x and y*) > And @@ (((((StringMatchQ[#, "*x*"] && > StringMatchQ[#, "*y*"]) &)@ > ToString@#) &) /@ {arg1, arg2}) > , SameQ[arg1, arg2 /. {x -> y, y -> x}], > SameQ[arg1, arg2]] > ] &)] &)@ > Union at Flatten@(Table[(Times @@ # &) /@ KSubsets[#, i], {i, 1, > 2}] &)@Flatten@{li, Outer[#1@#2 &, funList, li]} > ] &, {x, y}, 1]; > Select[%, (StringMatchQ[ToString@#, "*x*"] && > StringMatchQ[ToString@#, "*y*"]) &] This does not even start running in Mathematica 6, let alone produce any correct results. The first line was deprecated some time ago. I don't know what is wrong with the rest of your program but it takes a while to produce the empty list. > The problem is this: generate a list of all possible math expressions > using the following combination and rules: > > ? the math expression involves both x and y. (must have both present) > ? you can use any of the 6 trig functions (you must, since the goal is > to create all possibilities) > ? The binary operations you can use are multiply, divide. (no addition > or substraction, since that can make the result 2 terms) > ? a sub-expression (such as x or y) can be replaced by a more > complicated one. (i.e. you can nest) Then your program should produce an infinite number of terms, e.g. x, Sin[x], Sin[Sin[x]], ... > The above i wrote in 2002. If there are requests, i'll translate the > above code into emacs lisp. A correct definition of what the program is supposed to do with a correct implementation in any language would be a good start. If you are trying to do what I think you are trying to do then this is a trivial recursive definition in just about any language and it does not take advantage of anything specific to Mathematica anyway. -- Dr Jon D Harrop, Flying Frog Consultancy http://www.ffconsultancy.com/products/?u From msc at es.aau.dk Mon May 19 04:17:03 2008 From: msc at es.aau.dk (Martin Sand Christensen) Date: Mon, 19 May 2008 10:17:03 +0200 Subject: how would you...? References: <1449c36e-10ce-42f4-bded-99d53a0a2569@a1g2000hsb.googlegroups.com> <3xUXj.11305$hv2.9481@bignews5.bellsouth.net> Message-ID: >>>>> "inhahe" == inhahe writes: inhahe> Btw, use float() to convert a textual GPA to a number. It would be much better to use Decimal() instead of float(). A GPA of 3.6000000000000001 probably doesn't make much sense; this problem doesn't arise when using the Decimal type. Martin From gherron at islandtraining.com Thu May 15 16:46:06 2008 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 15 May 2008 13:46:06 -0700 Subject: How do I use the unpack function? In-Reply-To: References: <482C6E59.3020503@islandtraining.com> Message-ID: <482CA10E.1040602@islandtraining.com> Marlin Rowley wrote: > Gary, > > I'm getting streaming tile data from a renderer in order to allow the > user to see the rendering of tiles in real-time to create the total > image. I'm NOT reading an entire image scanline-by-scanline. The > renderer streams in a series of floats (for each tile) and I build > this tile up from each individual color component passed in. I then > convert it to a small bitmap and blit() it to the window that will > eventually make up my entire image. I'm just wanting to make the > process as fast as the renderer can render the tiles. I've noticed on > scenes that aren't very complex for the renderer that my python script > is spending most of it's time drawing while the renderer is already > done. What you've given me has sped up the drawing a lot, but I'm > hungry for more optimization! > > There is no file format to be read. The data is raw bytes and can be > any format. You are misinterpreting what I mean by a format. All data is a string of bytes, and interpreting that string of bytes to have some particular form is applying a format to it. Your particular format is: each 4 bytes represents a float, and a string of such floats give the RGBA values for a rectangle (of some size) of pixels. I doubt that you are the first ever to use that particular format to encode an image, but I also don't believe it matches any of the standard image formats. So... There is still hope to use already written tools to decode your format. Here's a hint on how to use numpy for decoding a byte string into an array of floats. My example byte string is a hand coded string of just 12 bytes -- you should replace that with a whole row or better yet, a whole tile's worth of bytes. >>> import numpy >>> byteString = '\x00\x00\x80?\x00\x00\x00@\x00\x00@@' >>> b = numpy.frombuffer(byteString, dtype=numpy.float32) >>> b array([ 1., 2., 3.], dtype=float32) If you want to use the array module instead: >>> import array >>> a = array.array('f') >>> a.fromstring(byteString) >>> a array('f', [1.0, 2.0, 3.0]) In either case ANY number of bytes can be decoded into an array of floats, in one highly efficient call from Python. What you do with that array of float afterwards is up to you.... If I read your note correctly, here's what I'd do to turn the array of bytes into an image of a tile to be displayed on the screen. Get the whole tile's worth of bytes with one read into a single string. Decode that string into an array of floats (as above). Reshape the array into a 3D array (i.e., a rectangular array of RGBA values) Convert that array of floats into an array of 8-bit integers (scaling all by 255). Extract (via tostring) that array into a string of bytes. Send that string of bytes to the graphics system as an RGBA array of pixels. Each of these calls is one Python call into a highly efficient library. This is using Python as a, so called, glue language. Gary Herron > > > Date: Thu, 15 May 2008 10:09:45 -0700 > > From: gherron at islandtraining.com > > CC: python-list at python.org > > Subject: Re: How do I use the unpack function? > > > > John Machin wrote: > > > On May 16, 2:11 am, Gary Herron wrote: > > > > > >> Marlin Rowley wrote: > > >> > > >>> All: > > >>> > > >>> I've got a script that runs really slow because I'm reading from a > > >>> stream a byte at a time: > > >>> > > >>> // TERRIBLE > > >>> for y in range( height ): > > >>> for color in range(4): > > >>> for x in range( width ): > > >>> pixelComponent = fileIO.read(4) > > >>> buffer = unpack("!f",pixelComponent) << unpacks ONE > > >>> > > > > > > [snip] > > > Perhaps the OP might be able to use the Python Imaging Library (PIL) > > > instead of reinventing an image-file handler. > > > > > > > Indeed. That's why my original answer included the line: > > There are probably better ways overall, but this directly answers > > your question. > > > > Other possibilities. > > > > I don't recognize the file format being read in here, but if it is a > > standard image format, the PIL suggestion is a good way to go. > > > > Or, if it is an image of not too enormous size, read the *whole* thing > > in at once. > > > > Or rather than manipulate the array by carving off 4 bytes at a time, > > just index through it in 4 byte chunks: > > for i in range(width): > > buffer = unpack("!f", pixelComponent[4*i:4*i+4]) > > > > Or > > for i in range(0,4*width,4): > > buffer = unpack("!f", pixelComponent[i:i+4]) > > > > Or > > Use numpy. Create an array of floats, and initialize it with the byte > > string, making sure to take endianess int account. (I'm quite sure this > > could be made to work, and then the whole operation is enormously fast > > with only several lines of Python code and *no* Python loops. > > > > Or > > ...? > > > > Gary Herron > > > > > -- > > > http://mail.python.org/mailman/listinfo/python-list > > > > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > ------------------------------------------------------------------------ > Windows Live SkyDrive lets you share files with faraway friends. Start > sharing. > > > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list From gherron at islandtraining.com Thu May 15 15:24:15 2008 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 15 May 2008 12:24:15 -0700 Subject: Pass data from Python to C++ In-Reply-To: References: Message-ID: <482C8DDF.7070306@islandtraining.com> brad wrote: > I have some c++ binaries that do rather intense number computations. > They do it well and rather quickly compared to other languages (not > just Python). An example: > >> brad at qu:~/$ date && ./compute.cpp.o < 1_million.txt > /dev/null && date >> Thu May 15 13:08:28 EDT 2008 >> Thu May 15 13:08:31 EDT 2008 >> brad at qu:~/$ date && python compute.py < 1_million.txt > /dev/null && >> date >> Thu May 15 13:08:38 EDT 2008 >> Thu May 15 13:14:50 EDT 2008 > > In this case, c++ does one million things in 3 seconds that Python > takes more than 6 minutes to do. The one million is a minimum. At > times the computations are in the billions. This is why c++ was chosen. > > However, other components can be written in a more user friendly, more > easily maintained language. We've chosen Python for this. The main > question now is how to pass the computationally heavy info to c++ from > within Pyhton. os.system is not ideal. Just wondering how other folks > do this? I have source to some of the c++ code, but some of it is in > binary from only. It can take stdin or arguments. > > Thanks for any tips, > > Brad > > -- > http://mail.python.org/mailman/listinfo/python-list There are lots of ways to do this. Lots of the modules you use are written in C and callable from Python. (Including sys, os, socket, PIL, numpy, all graphics and GUI modules, ...) And that's exactly what you want here -- a module that you can import into Python which gives you the ability to make calls into your C++ code. This is often called *wrapping* your C++ library. This is no small task, and it depends heavily on the size/complexity of the API you wish to wrap, and whether it's C (easier) or C++(harder). However, there are *lots* of tools to help. I'd start by looking here: http://wiki.python.org/moin/AdvocacyWritingTasks/GlueLanguage Good luck, Gary Herron From bronger at physik.rwth-aachen.de Thu May 1 17:03:38 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Thu, 01 May 2008 23:03:38 +0200 Subject: Best way to store config or preferences in a multi-platform way. References: Message-ID: <878wytvis5.fsf@physik.rwth-aachen.de> Hall?chen! Ivan Illarionov writes: > [...] > > I took the example from > http://www.kuro5hin.org/story/2004/10/29/14225/062 I haven't use > my own example only because I don't have one at hand right > now. YAML, in its simple form, definetely makes me more > productive. I wasted too much time with XML in the past and I > won't ever use it as a serialization or config/settings format > again. .INI/ConfigParser is too limited and has no standards. I > just don't see anything better than YAML to do human and Python > editable config files and to serialize information for later use. Okay, but serialisation is something completely different. Nobody would use INI files for it. For other things, it simply depends on the use case. For example, I *know* that the configuration files of my pet project will not exceed the dumb section.key=value scheme so anything else would be overkill. Besides, YAML adds another dependency. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From kyosohma at gmail.com Tue May 13 14:17:04 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 13 May 2008 11:17:04 -0700 (PDT) Subject: Usenet References: <6bafdf82-cf8a-42cd-9f72-d98a39fab5b5@j22g2000hsf.googlegroups.com> Message-ID: <835cca6a-dc35-44fa-a72e-7365e7a0bfb2@y21g2000hsf.googlegroups.com> On May 13, 1:02?pm, hdante wrote: > Hello, > > ?How can I access Usenet without using Google Groups ? (my ISP doesn't > have a NNTP server). Do you recommend doing so ? > > ?What's your prefered news reader ? You can use Gmane or Nabble or you could subscribe to c.l.py as a mailing list here: http://mail.python.org/mailman/listinfo/python-list Mike From marlin_rowley at hotmail.com Thu May 15 12:53:32 2008 From: marlin_rowley at hotmail.com (Marlin Rowley) Date: Thu, 15 May 2008 11:53:32 -0500 Subject: How do I use the unpack function? In-Reply-To: <482C6A0A.8080308@islandtraining.com> References: <482C60AB.2060406@islandtraining.com> <482C6A0A.8080308@islandtraining.com> Message-ID: Sorry Gary, I found out that I wasn't reassigning the array back once I got the first 4 bytes. I don't mean to appear lazy..:( Thanks for the help! -M > Date: Thu, 15 May 2008 09:51:22 -0700> From: gherron at islandtraining.com> To: marlin_rowley at hotmail.com> CC: python-list at python.org> Subject: Re: How do I use the unpack function?> > Marlin Rowley wrote:> > Thanks for the advice!> > > > However, I assumed that:> > > > fourbytes = pixelComponent[:4]> > > > would shave that byte off the array in pixelComponent. So that the > > array is smaller by one on the next iteration. Is this not the case?> You don't need the newsgroup to answer this kind of question. Just try it!> > >>> a = 'abcdefghi'> >>> b = a[:4]> >>> print a,b> abcdefghi abcd> > Notice that the [:4] index does not change the original array.> > Gary Herron> > > > > > > I'm getting weird results now..> > > > -M> >> >> >> >> > ------------------------------------------------------------------------> >> > > Date: Thu, 15 May 2008 09:11:23 -0700> > > From: gherron at islandtraining.com> > > To: marlin_rowley at hotmail.com> > > CC: python-list at python.org> > > Subject: Re: How do I use the unpack function?> > >> > > Marlin Rowley wrote:> > > > All:> > > >> > > > I've got a script that runs really slow because I'm reading from a> > > > stream a byte at a time:> > > >> > > > // TERRIBLE> > > > for y in range( height ):> > > > for color in range(4):> > > > for x in range( width ):> > > > pixelComponent = fileIO.read(4)> > > > buffer = unpack("!f",pixelComponent) << unpacks ONE> > > > float, but we now can do something with that pixel component.> > > >> > > >> > > > I can speed this up dramatically if I did this:> > > >> > > > // MUCH FASTER> > > > for y in range( height ):> > > > for color in range(4):> > > > pixelComponent = fileIO.read(4*width) <<<<<<<<< GET a LOT more> > > > data from the stream into memory FIRST!!> > > > for x in range( width ):> > > > buffer = unpack( ?????? ) <<<< how do I get each float from> > > > the pixelComponent???> > >> > > Just carve of the first four bytes of pixelComponent on each pass> > > through the loop, and unpack that.> > >> > > for x in range(width):> > > fourbytes = pixelComponent[:4] # first 4 bytes> > > pixelComponent = pixelComponent[4:] # All but first four bytes> > > buffer = unpack("!f", fourbytes)> > >> > >> > > There are probably better ways overall, but this directly answers your> > > question.> > >> > > Gary Herron> > >> > >> > > >> > > >> > > > -M> > > > > > ------------------------------------------------------------------------> > > > With Windows Live for mobile, your contacts travel with you. Connect> > > > on the go.> > > > > > > >> > > >> > > > > > ------------------------------------------------------------------------> > > >> > > > --> > > > http://mail.python.org/mailman/listinfo/python-list> > >> >> >> > ------------------------------------------------------------------------> > Get Free (PRODUCT) RED? Emoticons, Winks and Display Pics. Check it > > out! > > > > ------------------------------------------------------------------------> >> > --> > http://mail.python.org/mailman/listinfo/python-list> _________________________________________________________________ With Windows Live for mobile, your contacts travel with you. http://www.windowslive.com/mobile/overview.html?ocid=TXT_TAGLM_WL_Refresh_mobile_052008 -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Thu May 29 05:26:25 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 29 May 2008 11:26:25 +0200 Subject: cmd.Cmd bug or at least docu-bug Message-ID: <6a7b72F3467inU1@mid.uni-berlin.de> Hi, I'm fiddling around with module cmd. I tried to pass my own streams as replacements for stdin and stdout. However, stdin wasn't working. After a look into the sourcecode I discovered that there is an class-variable called use_rawinput that prevents using the passed stdin. I then read the docs again - and found it described. However, I think it should be mentioned on the first page where the constructor is described that without setting use_rawinput to False, stdin will be ignored. Or even better either make use_rawinput set to false in case stdin is passed anything but None or at least make it a keyword argument. Any thoughts about this? Diez From robert.kern at gmail.com Thu May 1 17:45:51 2008 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 01 May 2008 16:45:51 -0500 Subject: Getting started with pyvtk In-Reply-To: References: Message-ID: Peter Pearson wrote: > I'm trying to get started with pyvtk, the Python interface > to the Visualization Toolkit, but there's obviously > something important that I haven't figured out after an > embarrassingly long morning of googling around. When I run > sample pyvtk code (example1.py, from > http://cens.ioc.ee/cgi-bin/viewcvs.cgi/python/pyvtk/examples/example1.py), > nothing graphical happens, but some text files appear named > example1.vtk and example1b.vtk. Guessing that I need to > feed one of these to vtk, I tried "vtk "vtk example1.vtk", but those result in (different) error > messages that I think mean example1.vtk is not the language > that vtk expects. Simply running "vtk" (apparently 4.0) > gets a prompt that has no help command, and "man vtk" just > tells me it's like "wish", and "man wish" doesn't address > what to do with a vtk file. > > What key piece am I missing? pyvtk is not the Python interface to VTK. It is for the creation of VTK files. The vtk(1) command is a Tcl shell with the VTK libraries loaded (I believe). Read the VTK documentation for information on the Tcl interface if you really want to use it. The Python interface is also included in the VTK sources, although it might not have been built on your machine. You have to enable it when you build VTK itself. The Python interface is essentially the same as the C++ interface. There are Python examples in the VTK source tree. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From aisaac at american.edu Thu May 29 18:05:49 2008 From: aisaac at american.edu (Alan Isaac) Date: Thu, 29 May 2008 22:05:49 GMT Subject: make a string a list In-Reply-To: References: Message-ID: <1NF%j.9238$u7.4650@trnddc07> Nikhil wrote: > or a string iterable ? How can I do that. I have lots of '\r\n' > characters in the string which I think can be easier if it were made > into a list and I can easily see if the required value (its a numeral) > is present in it or not after some position or after some characters' > position. Why dont the ``find`` or ``index`` methods work for you? http://docs.python.org/lib/string-methods.html Cheers, Alan Isaac From info at wingware.com Thu May 22 08:56:18 2008 From: info at wingware.com (Wingware) Date: Thu, 22 May 2008 08:56:18 -0400 Subject: ANN: Wing IDE 3.1.1 released Message-ID: <48356D72.1060509@wingware.com> Hi, Wingware has released version 3.1.1 of Wing IDE. This bug fix release is available for all three product levels of Wing IDE. *Release Highlights* This release includes the following: * Template tool properly supports 2nd+ like-named fields * Several VI mode improvements * Replace in selection fixes * Maintain caret position when auto-strip trailing white space * Avoid trying to use unsupported Python versions * About 20 other bug fixes: see the change log for details: http://wingware.com/pub/wingide/3.1.1/CHANGELOG.txt *Downloads* Wing IDE Professional and Wing IDE Personal are commercial software and require a license to run. A free trial license can be obtained directly from the product when launched. Wing IDE Pro 3.1.1 http://wingware.com/downloads/wingide/3.1 Wing IDE Personal 3.1.1 http://wingware.com/downloads/wingide-personal/3.1 Wing IDE 101 3.1.1 http://wingware.com/downloads/wingide-101/3.1 *About Wing IDE* Wing IDE is an integrated development environment for the Python programming language. It provides powerful debugging, editing, code intelligence, testing, and search capabilities that reduce development and debugging time, cut down on coding errors, and make it easier to understand and navigate Python code. Wing IDE is available in three product levels: Wing IDE Professional is the full-featured Python IDE, Wing IDE Personal offers a reduced feature set at a low price, and Wing IDE 101 is a free simplified version designed for teaching entry level programming courses with Python. System requirements are Windows 2000 or later, OS X 10.3.9 or later for PPC or Intel (requires X11 Server), or a recent Linux system (either 32 or 64 bit). Wing IDE 3.1 supports Python versions 2.0.x through 2.5.x. *New Features in Wing 3.1* This release adds the following features not found in Wing 3.0.x: * Support for zip archives * Support for pkg_resources name spaces and eggs * Support for doctest and nose style unit tests (*) * Scan for sys.path changes such as those used in buildout * How-To and support for Google App Engine * Inline context appropriate templates/snippets integrated with autocompleter (*) * Word list driven auto-completion in non-Python files (**) * Quick navigation to files and symbols by typing a fragment (**) * Improved support for Stackless Python * Preference to strip trailing white space on save * Display gi_running and gi_frame for generators * Improved code analysis for Python 2.5 * Other minor features and bug fixes not found in Wing 3.0.x (*)'d items are available in Wing IDE Professional only. (**)'d items are available in Wing IDE Personal or Professional only. Please see the change log for a detailed list of changes: http://wingware.com/pub/wingide/3.1.1/CHANGELOG.txt *Purchasing and Upgrading* Wing 3.1 is a free upgrade for all Wing IDE 3.0 users. Any 2.x license sold after May 2nd 2006 is free to upgrade; others cost 1/2 the normal price to upgrade. Upgrade a 2.x license: https://wingware.com/store/upgrade Purchase a 3.x license: https://wingware.com/store/purchase -- The Wingware Team Wingware | Python IDE Advancing Software Development www.wingware.com From lists at cheimes.de Fri May 2 05:59:33 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 02 May 2008 11:59:33 +0200 Subject: no cleanup on TERM signal In-Reply-To: <481AE22E.3040906@shopzeus.com> References: <481AE22E.3040906@shopzeus.com> Message-ID: <481AE605.50102@cheimes.de> Laszlo Nagy schrieb: > For sensitive resources, instead of writing __del__ methods, you should > create a "close()" method. Python does this with file objects, DB API > 2.0 with database connection objects etc. Then you can do > > res = create_resource() > try: > use_resource() > finally: > res.close() # Must free resource, but the object can still be alive... You can replace the try/finally code with a "with resource: do_something()" block if the object supporst the context manager protocol. If you want to run some code during the shutdown phase of the Python process you can register a callback function in the "atexit" module. > It is more common to use signals when you have more threads or child > processes. You can use something like: Do NOT mix threads and signals. It's usually a very bad idea and may lead to surprising side effects. Signals are only handled by the main thread. Christian From castironpi at gmail.com Sun May 11 01:15:49 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 10 May 2008 22:15:49 -0700 (PDT) Subject: People still using Tkinter? References: <4825cd01$0$14982$9b622d9e@news.freenet.de> Message-ID: On May 10, 1:57?pm, Kenneth McDonald wrote: > The only trick it that sometimes it isn't obvious how to make the Tcl/ > Tk call via Python. > > Ken > > On May 10, 2008, at 11:27 AM, Martin v. L?wis wrote: > > > > >> I am, but "still" isn't the word, I just started. ?Good, *complete* > >> docs seem to be hard to find, but using a combination of the free > >> resources and going back and forth between them seems to work all > >> right so far. > > > IMO, the trick really is to also have a Tk documentation around. > > If you need to find out what option is supported by what widget, > > there isn't really much point in duplicating that information in > > Tkinter, IMO - the Tk documentation has it all. > > > Regards, > > Martin > > -- > >http://mail.python.org/mailman/listinfo/python-list- Hide quoted text - > > - Show quoted text - A limited browser-set from browserset remove imported.sys.modules[ '__main__' ] which should be a snytactically consistent expression. or, from imported.sys.modules[ '__main__' ] remove browserset Could make tkinter-complexity applications for browsers. Argue it's sufficiently general to spend a dollar on. From rhamph at gmail.com Tue May 6 11:56:31 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Tue, 6 May 2008 08:56:31 -0700 (PDT) Subject: Decimal vs Float comparasion References: Message-ID: On May 6, 1:31 am, Dennis Lee Bieber wrote: > On Tue, 6 May 2008 11:52:10 +0800, "Yuan HOng" > declaimed the following in comp.lang.python: > > > > > It seems to me that rather than allowing this to happen, comparasion > > between the two should either be made correct (by convertion decimal > > to float e.g.) or forbidden, like arithmatic operations between the > > two types. > > Why should decimal be coerced to float? Maybe float should be > coerced to decimal? > > Or... the programmer should explicitly specify what comparison is > wanted -- if any... > > Or... Isn't Python 3.x supposed to forbid mixed type comparisons > unless the types implement suitable handling? Yes, it is fixed in 3.0. Unfortunately it's well established behaviour in 2.x, so it won't be changing there. Don't bother reporting a bug about this unless it's about 3.0. From gregturn at mindspring.com Fri May 30 15:00:48 2008 From: gregturn at mindspring.com (Goldfish) Date: Fri, 30 May 2008 12:00:48 -0700 (PDT) Subject: Spring Python version 0.5.0 is released Message-ID: Spring Python (http://springpython.webfactional.com) version 0.5.0 was released today. It contains updates to DatabaseTemplate and DatabaseTransactions, along with more testing underneath MySQL, PostGreSQL, and Sqlite. Support for Oracle has been added, but only minimally tested so far. Spring Python has been re-licensed underneath the Apache License 2.0, making it more business friendly. Greg From squareswallower at 1ya2hoo3.net Thu May 8 01:42:07 2008 From: squareswallower at 1ya2hoo3.net (dave) Date: Wed, 7 May 2008 23:42:07 -0600 Subject: anagram finder / dict mapping question References: Message-ID: This is what i've came up with. My problem is that I can't get them to properly evaluate.. when comparewords() runs it finds itself... Should I have the keys of mapdict iterate over itself? Is that possible? def annafind(): fin = open('text.txt') # file has one word per line mapdic = {} # each word gets sorted & goes in here for line in fin: rawword = line.strip() word = list(rawword) word.sort() mapdic[''.join(word)] = 0 return mapdic def comparewords(): ***not working as intended fin = open('text.txt') for line in fin: line = line.strip() word = list(line) word.sort() sortedword = (''.join(word)) if sortedword in mapdic: print line On 2008-05-07 19:25:53 -0600, "Kam-Hung Soh" said: > On Thu, 08 May 2008 11:02:12 +1000, dave > wrote: > >> Hi All, >> >> I wrote a program that takes a string sequence and finds all the words > >> inside a text file (one word per line) and prints them: >> >> def anagfind(letters): #find anagrams of these letters >> fin = open('text.txt') #one word per line file >> wordbox = [] #this is where the words will go >> for line in fin: >> word = line.strip() >> count = 0 >> for char in letters: >> if char not in word: >> break >> else: >> count += 1 >> if count == len(word): >> wordbox.append(word) >> return wordbox >> >> Now I'd like to modify the code to naturally find all anagrams inside > a >> wordlist. What would be the best way to do this? Using Hints? Is it > >> possible to iterate over dict keys? How can I make a dict that maps > >> from a set of letters to a list of words that are spelled from those > >> letters? Wouldn't I need to make the set of letters a key in a dict? >> >> As always - Thanks for helping someone trying to learn... >> >> Dave >> > > Suggestion: for each word, sort their characters and use them as the > dictionary key. If two words have the same combination of characters, > then they are anagrams. For example: "edam" and "made" are anagrams > because they have the letters 'a', 'd', 'e' and 'm'. > > Refer "Programming Pearls" by Jon Bentley. > > -- > Kam-Hung Soh Software Salariman From zerty.david at gmail.com Thu May 8 21:44:39 2008 From: zerty.david at gmail.com (David Anderson) Date: Thu, 8 May 2008 22:44:39 -0300 Subject: Weird bug with an integer Message-ID: <5dc598e30805081844n834a776v812be9afd61e496@mail.gmail.com> Look this slice of code: rowN = int(0) for row in rows: success = self.resultGrid.AppendRows(); colN = int(0) for col in row: self.resultGrid.SetReadOnly(self.resultGrid.GetNumberRows() - 1,colN,isReadOnly = True) print rowN self.resultGrid.SetCellValue(int(rowN),int(colN),col) I am getting this output: 0 0 0 0 0 0 0 (1,) Traceback (most recent call last): in populateGrid self.resultGrid.SetCellValue(int(rowN),int(colN),col) TypeError: int() argument must be a string or a number, not 'tuple' Why is this happening? -------------- next part -------------- An HTML attachment was scrubbed... URL: From workitharder at gmail.com Wed May 21 20:56:38 2008 From: workitharder at gmail.com (bukzor) Date: Wed, 21 May 2008 17:56:38 -0700 (PDT) Subject: simple way to touch a file if it does not exist References: <68629786-1cef-4dc5-99d9-4967ebecd10f@r66g2000hsg.googlegroups.com> <4834C05D.6020608@gmail.com> Message-ID: <0cada27d-8f5f-482e-9acc-4da032edb27e@f36g2000hsa.googlegroups.com> On May 21, 5:37 pm, Nikhil wrote: > bukzor wrote: > > On May 21, 5:10 pm, "Giampaolo Rodola'" wrote: > >> On 22 Mag, 01:15, Nikhil wrote: > > >>> what are the simple ways? > >>> I could think of os.open(), os.exec(touch file) > >>> are there any simpler methods? > >> Just use os.path.exists to check for file existence and open() as > >> replacement for touch. > > >>>>> import os > >>>>> if not os.path.exists('file'): > >> ... open('file', 'w').close() > >> ... > > >> --- Giampaolohttp://code.google.com/p/pyftpdlib/ > > > As simple as it gets is a single builtin function call: > > > open("somefile.txt", "a") > > > Leave out the ,"a" if you don't mind blanking a pre-existing file. > > Thanks :-) > > That reminds me to check if I could quickly nullify a file if it exists > > if os.path.exists('file'): > open('file', 'w').close() > > Right? You only want to blank it if it exists? If it doesn't exist you won't create it. The .close() is superlative: since you don't keep the value, it gets deallocated and closed by the destructor. From johnjsal at NOSPAMgmail.com Mon May 12 13:27:57 2008 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 12 May 2008 13:27:57 -0400 Subject: Learning Python for no reason Message-ID: <0383f3b8$0$27282$c3e8da3@news.astraweb.com> Just something that crosses my mind every time I delve into "Learning Python" each night. Does anyone see any value in learning Python when you don't need to for school, work, or any other reason? I mean, sure, there's value in learning anything at any time, but for something like a programming language, I can't help but feel that I will be mostly unable to use what I learn simply because I have no reason to use it. The *process* of learning is enough fun for me, and every now and then I do find a small use for Python that really pays off, but for the most part I'm wondering what people's thoughts are as far as simply learning it for the sake of learning. Does it seem like a silly endeavor to most people? Did anyone here learn a programming language when you didn't need to? If so, how much and in what capacity did you use it after you learned it? Hopefully this question even makes sense! From jcd at sdf.lonestar.org Sat May 24 19:21:01 2008 From: jcd at sdf.lonestar.org (J. Clifford Dyer) Date: Sat, 24 May 2008 19:21:01 -0400 Subject: Hexadecimal: how to convert 'ED6F3C01' to "\xED\x6F\x3C\x01" in python coding? In-Reply-To: References: Message-ID: <1211671262.21932.44.camel@jcd-desktop> On Sat, 2008-05-24 at 15:36 -0700, zxo102 wrote: > Hi, > how to change the hexadecimal 'ED6F3C01' (or 'ED 6F 3C 01') to > "\xED\x6F\x3C\x01" in python coding? > When I take 'ED6F3C01' as a string and insert '\x' into it, I just got > the error information : invalid \x escape. > Thanks. > > ouyang A string is made up of a list of bytes, and when you use hexadecimal character references, the \ and the x do not represent bytes on their own, hence they cannot be manipulated as though they were individual characters of the string. The sequence \xNN is one byte, as a unit. It cannot be divided. So if you try: '\x%s" % 'ef' you will get an error, because you are substituting a two-byte string 'ef', where in fact you only wanted to complete the one byte in question. \x can never be separated from the two hexadecimal digits that follow it. They must be treated as a unit. To get the two-byte string 'ef' converted to the one byte character '\xef', you have to find a way to get the numerical value of ef, and create a character of that value. The first part is done as follows: int('ef', 16) which means "get the integer value of 'ef', where 'ef' is represented in base 16. In order to get the byte of hexadecimal numeric value 0xef, you use the chr() function: '\xef' == chr(int('ef', 16)) Or if you are working with unicode, use unichr() instead of chr(). If you always treat \xNN escape sequences as indivisible, you won't go wrong. Cheers, Cliff From gagsl-py2 at yahoo.com.ar Tue May 6 00:16:10 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 06 May 2008 01:16:10 -0300 Subject: threading: getting latest elements from list/dict References: <17d58cc40805050412l2cc0340cs2b84916d0af0760c@mail.gmail.com> <17d58cc40805050426w3282bb3eyc9c1831d1d37d705@mail.gmail.com> Message-ID: En Mon, 05 May 2008 08:26:45 -0300, Vaibhav.bhawsar escribi?: > Hello > I have a thread updating a dictionary with new elements. How can I check > for > new elements as they are inserted into the dictionary by the thread? In > general is it safe to read a dictionary or a list while it is being > updated > by a running thread? Does the dictionary or list have to be locked while > reading? > many questions! :) Use a Queue object to communicate between threads. The language itself doesn't guarantee anything about atomicity. You might put the new elements in a queue, and make the consumer update the dictionary instead of the producer. -- Gabriel Genellina From alex.m.gusarov at gmail.com Tue May 27 07:50:36 2008 From: alex.m.gusarov at gmail.com (Alex Gusarov) Date: Tue, 27 May 2008 18:50:36 +0700 Subject: graphical ide?? In-Reply-To: <1d3e7b3c-1767-4c26-ba4c-cba86189f8c7@k30g2000hse.googlegroups.com> References: <1d3e7b3c-1767-4c26-ba4c-cba86189f8c7@k30g2000hse.googlegroups.com> Message-ID: I tried Eric (on windows), but then decided in favour of Eclipse + PyDev. It's really good combination and if you want to develop PyQt apps, you can also install Qt Integration plugin to Eclipse, so you will have all what you need for PyQt development, include form designer and resource editor. PyQt + Eclipse Qt plugin distributed under GPL. -- Best regards, Alex Gusarov -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Tue May 13 06:26:11 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 13 May 2008 03:26:11 -0700 (PDT) Subject: The 'is' identity operator checking immutable values caution References: <5353c776-6ef7-4d2f-8769-e3ace320d2c6@b64g2000hsa.googlegroups.com> Message-ID: On May 13, 5:10?am, wxPytho... at gmail.com wrote: > We have to avoid the use of the 'is' identity operator with basic, > immutable values such as numbers and strings. The result is > unpredictable because of the way Python handles these objects > internally. > > How is with this issue in Python 3.0? Is it fixed? Does Python handle > this things properly now? Ooo. Timing. Good one. Writer's other wanderings bring Microsoft Research. Who talks to that on a daily basis? From metallourlante at gmail.com Sat May 17 10:03:27 2008 From: metallourlante at gmail.com (Alex) Date: Sat, 17 May 2008 07:03:27 -0700 (PDT) Subject: Help on thread pool References: <323a8e66-7cc0-4d1f-9d7a-fc70f0c0a442@56g2000hsm.googlegroups.com> <262b4f46-f3d6-4a29-b7a6-91eb279d1f29@j22g2000hsf.googlegroups.com> Message-ID: <334cc5e1-5f28-4f74-b316-7d30b194f4ab@8g2000hse.googlegroups.com> On May 17, 2:23 pm, Jeff wrote: > Your worker threads wait around forever because there is no place for > them to exit. Queue.get() by default blocks until there is an item in > the queue available. You can do something like this to cause the > worker to quit when the queue is empty. Just make sure that you fill > the queue before starting the worker threads. > > from Queue import Queue, Empty > > # in your worker > while True: > try: > item = q.get(block=False) > except Empty: > break > do_something_with_item() > q.task_done() > > You can also use a condition variable and a lock or a semaphore to > signal the worker threads that all work has completed. Thanks a lot, it works! Alex From castironpi at gmail.com Wed May 14 13:08:49 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 14 May 2008 10:08:49 -0700 (PDT) Subject: Purpose of operator package References: Message-ID: On May 14, 11:58?am, Matthew Woodcraft wrote: > I V ? wrote: > > > I hadn't heard of operator.truth before. Does it do anything different > > from bool(x) ? > > Not really. It was occasionally useful before the bool type existed; > now it's just a leftover. > > -M- Now as for ints, I could see that going in to 8-by-8s and crosses. Anyone for? From jcd at sdf.lonestar.org Thu May 8 16:36:44 2008 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Thu, 08 May 2008 16:36:44 -0400 Subject: Surprising difference in behavior between "import blah" and "from blah import thing" In-Reply-To: <874p984o4c.fsf@offby1.atm01.sea.blarg.net> References: <874p984o4c.fsf@offby1.atm01.sea.blarg.net> Message-ID: <1210279004.12106.25.camel@aalcdl07.lib.unc.edu> On Thu, 2008-05-08 at 12:00 -0700, Eric Hanchrow wrote: > (This is with Python 2.5.2, on Ubuntu Hardy, if it matters.) > > This seems so basic that I'm surprised that I didn't find anything > about it in the FAQ. (Yes, I am fairly new to Python.) > > Here are three tiny files: > > ==== mut.py ==== > > import system > from system import thing > > def doit(): > print " thing is", thing > > def do_it_slightly_differently(): > print "system.thing is", system.thing > > ==== system.py ==== > thing = "I am the original thing!!" > > ==== test.py ==== > import mut > mut.doit() > mut.do_it_slightly_differently() > import system > > system.thing = "The new improved thing" > mut.doit() > mut.do_it_slightly_differently() > > When I run "python test.py", I see > > thing is I am the original thing!! > system.thing is I am the original thing!! > thing is I am the original thing!! > system.thing is The new improved thing > > What surprises me is that the assignment to "system.thing" in test.py > only seems to affect the use of "system.thing" in mut.py, and not > affect the use of just plain "thing" in that same file. I would have > expected my assignment to have affected both, or perhaps neither. > > I have no idea why these two differ. Can someone explain? It's the same reason as this: >>> x=5 >>> y=x >>> x 5 >>> y 5 >>> x=6 >>> x 6 >>> y 5 >>> Python "variables" are just names that point at objects. When you import, the imported module gets bound to a name. When you use the an assignment statement, you bind a new object to the name, but other names bound to the object are not affected. So in your code, when you say >>> system.thing = "The new improved thing" You rebind the name system.thing, but the object it was originally bound to is unaffected. Strings are immutable, so you couldn't change that object if you tried. thing is still bound to the original object. Another feature of this behavior is as follows: >>> x=5 >>> x is y True >>> x=5 >>> y=x >>> x is y True >>> x=6 >>> x is y False >>> The "is" operator tells you that the two objects are the same object. When you reassign one, it no longer points to the same object as the other. You would get the same behaviour in your code comparing system.thing and thing. Cheers, Cliff From lew at lewscanon.com Thu May 8 06:52:22 2008 From: lew at lewscanon.com (Lew) Date: Thu, 08 May 2008 06:52:22 -0400 Subject: The Importance of Terminology's Quality In-Reply-To: References: Message-ID: kodifik at eurogaran.com wrote: >> | PLEASE DO NOT | :.:\:\:/:/:.: >> | FEED THE TROLLS | :=.' - - '.=: > > I don't think Xah is trolling here (contrary to his/her habit) > but posing an interesting matter of discussion. Interesting is in the eye of the beholder. After you'd read the same recycled crud from certain posters again and again, it because trollish spam. -- Lew From deets at nospam.web.de Mon May 19 10:01:37 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 19 May 2008 16:01:37 +0200 Subject: printing class __dict__ References: <691285ac-b506-4d9a-8a4c-9a7d53dc9438@b9g2000prh.googlegroups.com> Message-ID: <69dfj3F32oohpU1@mid.uni-berlin.de> piyush.subscription at gmail.com wrote: > hi, > i am a newbie. so bear wth me > i wrote a program like this > -- > class H(object): > def __init__( self): > self.data =10 > def e ( self ): > pass > def f ( self ): > pass > > class H1(H): > x2 = 11 > def __init__(self): > self.x = 10 > > class details(object): > def data(self,className): > print classname.__dict__ > print classname.__name__ > print classname.__bases__ > > bc = details() > bc.data(H1) > > when i run it, i get error like this > NameError: global name 'classname' is not defined > > can't i pass 'class' like an 'object'? > > any suggestions to access other classes details inside a class? Python is case-sensitive. Now analyze your code. Diez From john106henry at hotmail.com Tue May 6 22:07:30 2008 From: john106henry at hotmail.com (John Henry) Date: Tue, 6 May 2008 19:07:30 -0700 (PDT) Subject: So you think PythonCard is old? Here's new wine in an old bottle. References: <9028496e-30de-4853-8f57-b55d14e52358@h1g2000prh.googlegroups.com> <070fc7e3-3e51-40b2-a6f2-026d00f8fa2f@m73g2000hsh.googlegroups.com> Message-ID: <84375e0d-fa3e-4d0f-9701-c0a9f0dd94cc@p39g2000prm.googlegroups.com> On May 5, 11:04 am, jbarci... at gmail.com wrote: > John, you are the man > > > during my search for perfection, I found Qooxdoo (http://qooxdoo.org/). > > > ... > > > I found QxTransformer (http://sites.google.com/a/qxtransformer.org/qxtransformer/Home) which is a > > XSLT toolkit that creats XML code that invoke qooxdoo. > > Qooxdoo is indeed really impressive. But I read that YAHOO will serve > the javascript files for you from their CDN when you use YUI, for > free, and that's no peanuts, so I wonder, did you find anything at all > like that that could be used with YUI? > Sorry but I don't know any of this. I am pretty new to web programming. > I have evaluated XForms, Laszlo, Flex, ZK, ... but I have to say > QxTransformer is the cleverest solution I have found so far (thanks to > you). I love it. > > > I want Pythoncard. > > I feel with you > I have done quite a bit of work to improve things. We are now officially calling the project PyQooxCard. See: http://sites.google.com/a/qxtransformer.org/qxtransformer/Home I put together my first app which took less than a day. Not bad because there are 36 screens, and over 100 data fields. See: http://epc.powersystemadvisors.com 3 cheers to PythonCard. > Thanks! > Jaime From deets at nospam.web.de Wed May 21 02:25:00 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 21 May 2008 08:25:00 +0200 Subject: Processing in Python In-Reply-To: References: <483345f5$0$902$ba4acef3@news.orange.fr> <69h0p9F327mqgU1@mid.uni-berlin.de> Message-ID: <69htifF319c5iU1@mid.uni-berlin.de> Istvan Albert schrieb: > On May 20, 6:13 pm, "Diez B. Roggisch" wrote: >> Salvatore DI DI0 schrieb: >> >>> Hello, >>> The Processing Graphics language has been implemented in Javascript. >> No, it hasn't. Processing is written in Java. > > He meant it has been re-implemented in Javascript: > > http://ejohn.org/blog/processingjs/ I even tried to google to be sure that my statement was true - but the terms are to generic :( > The closest python based equivalent of Processing is NodeBox but it is > a OS X product: > > http://nodebox.net/code/index.php/Home That *really* looks promising! Thanks for that link. Diez From guillermo.listas at googlemail.com Mon May 12 12:19:00 2008 From: guillermo.listas at googlemail.com (Guillermo) Date: Mon, 12 May 2008 09:19:00 -0700 (PDT) Subject: passing *args "recursively" Message-ID: Hi, This must be very basic, but how'd you pass the same *args several levels deep? def func2(*args) print args # ((1, 2, 3),) # i want this to output (1, 2, 3) as func1! # there must be some better way than args[0]? def func1(*args): print args # (1, 2, 3) func2(args) func1(1,2,3) Thanks! Guillermo From seberino at spawar.navy.mil Wed May 7 14:53:46 2008 From: seberino at spawar.navy.mil (seberino at spawar.navy.mil) Date: Wed, 7 May 2008 11:53:46 -0700 (PDT) Subject: Bad form to access a *private variable* like _foo? References: <48200a7f$0$23642$426a74cc@news.free.fr> <68aq4nF2r9b93U4@mid.uni-berlin.de> Message-ID: On May 6, 3:27 am, "Diez B. Roggisch" wrote: > There are other ways. For example, > > sqlobject.sqlhub.threadingLocal.connection > > if your system is using multiple threads correctly. Generally speaking, > sqlhub could/should be used. That's actually quite involved. You must first get a reference to a PackageHub object, then invoke connectionToURI, etc. lots of steps! cs From kerstin.viltersten at semcon.com Tue May 27 04:54:36 2008 From: kerstin.viltersten at semcon.com (Giraffe) Date: Tue, 27 May 2008 01:54:36 -0700 (PDT) Subject: Problems with Python IDLE Message-ID: <2fc399e1-3cf3-43fa-ad95-55bc06b62ea1@e53g2000hsa.googlegroups.com> I have the followong class in a file: -------------------------------------------- class someClass: def __init__ (self): self.someVar = 10 def getSomeVar (self): return self.someVar -------------------------------------------- In another file a do the following: -------------------------------------------- tmp = someClass () tmp.getSomeVar () -------------------------------------------- I run the second file in the IDLE environment and everything seems to be working fine until I start to modify in the first file: -------------------------------------------- class someClass: def __init__ (self): self.someVar = 10 def getSomeVar (self): print "Modified class!" return self.someVar ------------------------------------------- When I now try to run the second file in the IDLE environment again, I DO NOT get the newly added printout. I have saved and compiled (run) both files but there is still no change. What have I missed? From cheryl.giomi at comcast.net Sat May 17 14:18:29 2008 From: cheryl.giomi at comcast.net (cher) Date: Sat, 17 May 2008 11:18:29 -0700 Subject: smtplib "authentication required" error References: 1143858027.337885.24650@j33g2000cwa.googlegroups.com Message-ID: <482F2175.1070702@comcast.net> Hey, Don't know if you can help, but I'm trying to import archived messages from Thunderbird into my gmail account and keep getting these types of errors. I am using the GML program to help incorporate, but the SMTP server is not being recognized by gmail. Am I doing something wrong? Anything else I can try? SMTP I've tried: smtp.gmail.com gsmtp56.google.com Error Val : (530, '5.7.0 Must issue a STARTTLS command first. m29sm9416768poh.4', *** 76 ERROR SENDING MESSAGE FROM: rick at bassisloadeddj.com *** UNABLE TO CONNECT TO SERVER OR SEND MESSAGE. ERROR FOLLOWS. Error Type: smtplib.SMTPSenderRefused Error Val : (530, '5.7.0 Must issue a STARTTLS command first. n22sm9448670pof.3', 'rick at bassisloadeddj.com') Thanks, Cher From mal at egenix.com Thu May 8 12:08:28 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Thu, 08 May 2008 18:08:28 +0200 Subject: Writing elapsed time as a string In-Reply-To: References: <481B67E5.7040507@googlemail.com> Message-ID: <4823257C.3070106@egenix.com> On 2008-05-08 14:31, Gabriel Genellina wrote: > En Fri, 02 May 2008 16:13:41 -0300, Simon Pickles escribi?: > >> I'm sorry if this has been asked a thousand (million) times. >> >> Is there a nifty pythonesque way to produce a string representing an >> elapsed time period, in terms of years, months, days, hours, mins, seconds? >> >> I am storing times in a MySQL db, and would love to be able to write the >> time elapsed between accesses of certain data. These are in seconds >> since the epoch, as produced by time.time() Using mxDateTime that's pretty easy (using number of days): >>> from mx.DateTime import * >>> delta = now() - Date(2000,1,1) >>> print delta 3050:18:01:25.91 or, if you'd rather like to see things broken down as relative date/time diff (this is a calendar based diff): >>> print RelativeDateTimeDiff(now(), Date(2000,1,1)) (+0008)-(+04)-(+07) (+18):(+04):(+41) i.e. 8 years, 4 months, 7 days, etc. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, May 08 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From rileyrgdev at gmail.com Mon May 12 09:10:44 2008 From: rileyrgdev at gmail.com (Richard G Riley) Date: Mon, 12 May 2008 15:10:44 +0200 Subject: anonymous assignment References: <1XNVj.133805$Cj7.33096@pd7urf2no> Message-ID: Yves Dorfsman writes: > D'Arcy J.M. Cain wrote: >> On Mon, 12 May 2008 02:28:13 GMT >> Yves Dorfsman wrote: >>> particular case, there's got to be a better way than: >>> >>> d = time.local() >>> y = d[0] >>> d = d[1] >> >> Like this? >> >> y, d = time.local()[:2] > > Sorry this was a typo (again :-), I meant: > > d = time.local() > y = d[0] > d = d[2] > > Yves. > http://www.SollerS.ca or .localtime()? or is this local() specific to a different python version? From bruno.desthuilliers at gmail.com Mon May 5 16:31:02 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Mon, 5 May 2008 13:31:02 -0700 (PDT) Subject: Colors for Rows References: <4dc0cfea0804290733ic99e45eyec23a6d5b719eb8@mail.gmail.com> Message-ID: <55f7573f-bb55-483b-9e59-12f0469174a3@f63g2000hsf.googlegroups.com> > On Tue, 29 Apr 2008 09:33:32 -0500 > "Victor Subervi" wrote: > print '' % bg You'd better learn to use css instead. From __peter__ at web.de Tue May 27 06:01:31 2008 From: __peter__ at web.de (Peter Otten) Date: Tue, 27 May 2008 12:01:31 +0200 Subject: Problems with Python IDLE References: <2fc399e1-3cf3-43fa-ad95-55bc06b62ea1@e53g2000hsa.googlegroups.com> Message-ID: Giraffe wrote: > I have the followong class in a file: > -------------------------------------------- > class someClass: > def __init__ (self): > self.someVar = 10 > > def getSomeVar (self): > return self.someVar > -------------------------------------------- > > In another file a do the following: > -------------------------------------------- > tmp = someClass () > tmp.getSomeVar () > -------------------------------------------- > > I run the second file in the IDLE environment and everything seems to > be working fine until I start to modify in the first file: > -------------------------------------------- > class someClass: > def __init__ (self): > self.someVar = 10 > > def getSomeVar (self): > print "Modified class!" > return self.someVar > ------------------------------------------- > > When I now try to run the second file in the IDLE environment again, I > DO NOT get the newly added printout. I have saved and compiled (run) > both files but there is still no change. What have I missed? You probably start idle with the -n option. If so, IDLE shows something like IDLE 1.2.1 ==== No Subprocess ==== in its shell. Here's what IDLE's help says about that: """ Running without a subprocess: If IDLE is started with the -n command line switch it will run in a single process and will not create the subprocess which runs the RPC Python execution server. This can be useful if Python cannot create the subprocess or the RPC socket interface on your platform. However, in this mode user code is not isolated from IDLE itself. Also, the environment is not restarted when Run/Run Module (F5) is selected. If your code has been modified, you must reload() the affected modules and re-import any specific items (e.g. from foo import baz) if the changes are to take effect. For these reasons, it is preferable to run IDLE with the default subprocess if at all possible. """ If you use a shortcut to start IDLE, remove the -n option and you should be OK. Peter From dullrich at sprynet.com Wed May 14 17:15:41 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Wed, 14 May 2008 16:15:41 -0500 Subject: "indexed properties"... Message-ID: Having a hard time phrasing this in the form of a question... The other day I saw a thread where someone asked about overrideable properties and nobody offered the advice that properties are Bad. So maybe we've got over that. I suppose properties could have Bad consequences if a user doesn't know they exist and think that a certain property of an object is just an ordinary attribute. But that applies to almost any aspect of any language. If a person comes from, say, Object Pascal (Delphi) then properties are hard to live without. The other day I decided I wanted what OP calls an "indexed property" or "array property". Couldn't figure out how to make a _property_ behave that way. So I read a little bit about descriptors, and a few minutes later I had an indexedproperty thing that works just like property, except it gives an indexed property! This is just too cool. Why? For example, a Matrix should have a row[n] property allowing things like m.row[0] = m.row[1] + m.row[2] Ok, you could do _that_ by just making row an ordinary list of Row objects. But then you'd have to say m.row[0] = Row([1,2,3]) where I want to be able to say m.row[0] = [1,2,3] and have the Row created automatically. _Also_ with these indexed properties my Matrix can have m.row[j] and m.col[k] that look exactly the same to a client - we don't want to store a list of rows internally and also store the same data in a list of columns. Too cool. Hmm, none of that's a valid excuse for a post here. Um, right, here we go: Anyone see problems or possible improvements with the implementation of indexedproperty below? """indexed.py: "indexedproperty" works more or less like "property" except it gives what in Object Pascal would be an "indexed property". See the __name__="__main__" section below for a demo """ class WriteOnlyIP(Exception): def __str__(self): return """ indexed property is write-only """ class ReadOnlyIP(Exception): def __str__(self): return """ indexed property is read-only """ class indexedproperty(object): def __init__(self, getitem=None, setitem=None): self.getitem = getitem self.setitem = setitem def __get__(self, obj, owner): self.obj = obj return self def __getitem__(self, index): if self.getitem: return self.getitem(self.obj, index) else: raise WriteOnlyIP def __setitem__(self, index, value): if self.setitem: self.setitem(self.obj, index, value) else: raise ReadOnlyIP if __name__ == "__main__": class AClass(object): def __init__(self): self.cells = [[0,0], [0,0]] def SetCell(self, (row, col), value): self.cells[row][col] = value def GetCell(self, (row, col)): return self.cells[row][col] cell = indexedproperty(GetCell, SetCell) C = AClass() for row in range(2): for col in range(2): C.cell[row, col] = "row: %s, col: %s" % (row, col) for row in range(2): for col in range(2): print C.cell[row, col] C.cell[0,0], C.cell[1,1] = C.cell[1,1], C.cell[0,0] print "After C.cell[0,0], C.cell[1,1] = C.cell[1,1], C.cell[0,0]:" for row in range(2): for col in range(2): print C.cell[row, col] -- David C. Ullrich From mensanator at aol.com Fri May 9 00:50:17 2008 From: mensanator at aol.com (Mensanator) Date: Thu, 8 May 2008 21:50:17 -0700 (PDT) Subject: Mathematics in Python are not correct References: <52c855d8-5609-43e0-b98f-9fa87b2808c2@m3g2000hsc.googlegroups.com> <200805081914.06459.kyrie@uh.cu> <48239601.1070200@cheimes.de> <1210306536.4823cfe8be627@comuh.uh.cu> Message-ID: <4fcecd86-eb19-4443-b218-fc4cfcd4a36c@m3g2000hsc.googlegroups.com> On May 8, 11:28?pm, "Ian Kelly" wrote: > On Thu, May 8, 2008 at 10:15 PM, Luis Zarrabeitia wrote: > > ?Weird, I can't find neither... (which wikipedia article? Couldn't find one about > > ?C99.) > > Tryhttp://en.wikipedia.org/wiki/Exponentiation#Zero_to_the_zero_power So it IS correct. From upton at virginia.edu Tue May 13 11:50:19 2008 From: upton at virginia.edu (Dan Upton) Date: Tue, 13 May 2008 11:50:19 -0400 Subject: Python and Flaming Thunder In-Reply-To: <65ef773e-a1c3-4adb-a18b-e8b8451efe5e@b5g2000pri.googlegroups.com> References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <5b0e3f70-afde-4480-8713-e7113b1250d7@x35g2000hsb.googlegroups.com> <1f537717-00d0-48ee-99b6-7125b96a6133@t12g2000prg.googlegroups.com> <68t4o0F2vaoncU1@mid.uni-berlin.de> <2a32179a-9439-449c-bd07-fff6a4075aee@s50g2000hsb.googlegroups.com> <7ee5dffd-df8f-46f0-bd78-c81ac0418a9a@d77g2000hsb.googlegroups.com> <65ef773e-a1c3-4adb-a18b-e8b8451efe5e@b5g2000pri.googlegroups.com> Message-ID: <5504f9ac0805130850u395ce913le84d65d172c76069@mail.gmail.com> On Tue, May 13, 2008 at 11:24 AM, Dave Parker wrote: > > The "Flaming Thunder" looks promising, but without being free > > software, it's unlikely it will create a large developer community, > > specially considering both free general purpose and scientific > > programming languages. > > Perhaps. Flaming Thunder is only $19.95 per year for an individual > (and even less per individual for site licenses), which is less than > the cost of just one book on Python. Bah, subscription for a programming language? As far as I'm concerned, that's reason enough not to bother with it. Paying a one-time fee, or even once per upgrade, for a full-featured IDE and lots of support tools is painful but at least justifiable, whereas paying a yearly license just to even be able to try something out when there are so many free, sufficient options... There was an article on/in Wired not so long ago about the economics of free, and how there's a huge difference mentally between free and not-free, even if the practical difference is "free" and "$0.01." (Also, I assume hdante meant, at least partly, free as in speech, not free as in beer.) As an aside, I clearly haven't written anything in FT, but looking at your examples I don't know that I would want to--there's something that feels very unnatural about writing English as code. It also somehow seems a bit verbose, while one of the strengths of something like Python (since that's what you're comparing it to) is rapid implementation. Just using your "Set ... to" idiom, rather than a regular = assignment, makes things much more wordy, without improving readability. Some of your other structures are awkward, for instance "Something is a function doing" Again, more text with arguably no gain in readability. Just my two cents, anyway. I now return you to the resident madman, who I see has sent 4 or 5 messages while I was typing this one... From george.sakkis at gmail.com Fri May 9 09:24:19 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 9 May 2008 06:24:19 -0700 (PDT) Subject: Function creation (what happened?) References: <199c06d7-601c-49f3-a88c-c28f7283e619@25g2000hsx.googlegroups.com> Message-ID: <50ea9d09-a315-4342-aaac-f5d8e5c5da15@x41g2000hsb.googlegroups.com> On May 9, 9:02?am, Viktor wrote: > This completely slipped of my mind... :) > > I'm trying to change the:http://wordaligned.org/svn/etc/echo/echo.py > > So if the function is method it prints ClassName.MethodName instead of > MethodName(self|klass|cls=<... ClassName>). > > But it turned out that in the decorator, the wrapped function is > always just a TypeFunction (I cannot find out if the function is > method, classmethod, staticmethod or just a plain function - tried > with inspect also)... And what is most interesting, when I do: > > def w(fn): > ? ? print 'fn:', id(fn) > ? ? return fn > > class A: > ? ? @w > ? ? def __init__(self): pass > > print 'A.__init__:', id(A.__init__) > > It turns out that the function I receive in the wrapper (even when I > return the same function) is not the function which will finally be > attached to the class... > > Is there a way to find out in the decorator "what will the decorated > function be"? The decorator does receive the correct function. The problem is that at this point __init__ is still a plain function, not a method, i.e. the sequence is: function -> decorated function -> method There are several workarounds if you really want to differentiate between functions and methods, none of them perfect: - Apply the decorator after the class has been built, i.e. after the functions have been wrapped in (unbound) methods: A.__init__ = w(A.__init__) - (Risky Hack): Guess whether a function is intended to be wrapped in a method by checking whether its first argument is named "self". Obviously this is not foolproof and it doesn't work for static/class methods. - Have two different decorators, one intended for plain functions and one for functions-to-be-methods (e.g. @deco, @decomethod). George From timj at tolisgroup.com Mon May 5 13:43:58 2008 From: timj at tolisgroup.com (brucoder) Date: Mon, 5 May 2008 10:43:58 -0700 (PDT) Subject: Visual Studio 6 compile of 2.5.2 fails with missing db.h Message-ID: <1f1a09ff-5800-4ecb-ac9f-f2604454edfb@q1g2000prf.googlegroups.com> Hi Folks, Searched the archives, but I can only find mention of db.h problems relating to Linux. I've downloaded the source for 2.5.2 and am trying to compile it in Visual Studio 6 (SP6). The error reports read: --------------------Configuration: _bsddb - Win32 Debug-------------------- Compiling... _bsddb.c C:\Documents and Settings\Tim\My Documents\Python-2.5.2\Modules \_bsddb.c(90) : fatal error C1083: Cannot open include file: 'db.h': No such file or directory Error executing cl.exe. _bsddb_d.pyd - 1 error(s), 0 warning(s) Any pointers? A prerequisite that I might be missing? The source is the Python-2.5.2.tar.gz from the Python.org site. Thanks for any help, Tim From hdante at gmail.com Sun May 4 11:19:34 2008 From: hdante at gmail.com (hdante) Date: Sun, 4 May 2008 08:19:34 -0700 (PDT) Subject: Feature suggestion: sum() ought to use a compensated summation algorithm References: <481CB283.107@gmail.com> Message-ID: On May 3, 7:05?pm, sturlamolden wrote: > On May 3, 10:13 pm, hdante wrote: > > > ?I believe that moving this to third party could be better. What about > > numpy ? Doesn't it already have something similar ? > > Yes, Kahan summation makes sence for numpy arrays. But the problem > with this algorithm is optimizing compilers. The programmer will be No, optimizing compilers shouldn't discard floating point operations by default, since it changes program behavior. If they do, at least there should be a flag to turn it off. > forced to use tricks like inline assembly to get around the optimizer. > If not, the optimizer would remove the desired features of the > algorithm. But then we have a serious portability problem. From ewertman at gmail.com Thu May 29 20:43:41 2008 From: ewertman at gmail.com (Eric Wertman) Date: Thu, 29 May 2008 20:43:41 -0400 Subject: Code execution in imported modules Message-ID: <92da89760805291743p4f88b15ao14c9f990c1c50162@mail.gmail.com> So I'm working on some file parsing and building up a stack of regular expressions that I need to use. I was thinking of dropping them in an external module. I was wondering.. if I put them in a file called regex.py like so : import re re1 = ".. re2 = ".. and then do: rgx1 = re.compile(re1) rgx2 = re.compile(re2) and, in my script, parse.py py I do: from regex import * text = "bunch of stuff......." m = rgx1.search(text) Does the re get compiled when I import it, or every time I call it? Since I'm calling it often, I'd like to compile it once. Thanks! From gagsl-py2 at yahoo.com.ar Wed May 14 00:56:07 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 14 May 2008 01:56:07 -0300 Subject: how to pass a python socket to a .dll? References: Message-ID: En Tue, 13 May 2008 12:48:26 -0300, inhahe escribi?: > i'm trying to make a .dll that will let me use WSAPoll, which is a > windows > sockets function, to mimic select.poll on a windows box. i cbb learning > python extensions, so i'm just going to use ctypes with a dll, so I hope > that it doesn't bring up a big performance issue. anyway, the problem > is > that I want to use Python-created sockets with it, but WSAPoll requires > winsock2.h SOCKET objects. Use the fileno() method to get the SOCKET handle. If you're going to use ctypes anyway, why bother to write a DLL? Just declare the required structures and functions using ctypes. Good luck! -- Gabriel Genellina From upton at virginia.edu Wed May 21 12:42:44 2008 From: upton at virginia.edu (Dan Upton) Date: Wed, 21 May 2008 12:42:44 -0400 Subject: Python and Flaming Thunder In-Reply-To: References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <20080514215943.14c92f16.johnjsal@NOSPAMgmail.com> <94bac166-d13c-44dd-af84-db19e19488b8@w1g2000prd.googlegroups.com> <8cfd3523-8d16-40bc-b904-94a6a36a414d@p25g2000pri.googlegroups.com> <48343e56$0$5866$426a74cc@news.free.fr> Message-ID: <5504f9ac0805210942r54de2f1fl2230c7e297acd5b6@mail.gmail.com> On Wed, May 21, 2008 at 12:33 PM, Daniel Fetchinson wrote: >>>> Or just: >>>> >>>> If command is "quit" ... >>> >>> Hmmm. In Flaming Thunder, I'm using "is" (and "is an", "is a", etc) >>> for assigning and checking types. For example, to read data from a >>> file and check for errors: >>> >>> Read data from "input.txt". >>> If data is an error then go to ... >> >> Arf ! A goto ! > > You are surely aware of the fact that the C source of python also uses > goto at tons of places. Is that Arf! too? > And in the Linux kernel, and probably lots of other places too--several places I've seen it used, they explain it as "this helps clue in the optimizer" or something to that effect. (That doesn't mean it's a good idea to use it in everyday code though.) From mnikhil at gmail.com Thu May 29 17:30:59 2008 From: mnikhil at gmail.com (Nikhil) Date: Fri, 30 May 2008 03:00:59 +0530 Subject: make a string a list Message-ID: or a string iterable ? How can I do that. I have lots of '\r\n' characters in the string which I think can be easier if it were made into a list and I can easily see if the required value (its a numeral) is present in it or not after some position or after some characters' position. Thanks, Nikhil From tarun.kap at gmail.com Mon May 5 10:17:50 2008 From: tarun.kap at gmail.com (TkNeo) Date: Mon, 5 May 2008 07:17:50 -0700 (PDT) Subject: SSL through python. possible ? References: Message-ID: <364d19ac-6ad4-4191-864c-8f2f305d2b21@34g2000hsh.googlegroups.com> On May 2, 1:43 pm, "Giampaolo Rodola'" wrote: > On 29 Apr, 15:56,TkNeo wrote: > > > I need to do SSL file transfer using python? Is there a library i can > > use ? > > > Thanks. > > If you have patience you can wait for Python 2.6 which will include a > new ssl module, otherwise there are a lot of third party libraries out > there which already binds OpenSSL for Python. > > --- Giampaolohttp://code.google.com/p/pyftpdlib/ Python 2.6. Ah, that sounds very nice. I would be happy to upgrade to 2.4 from 2.3. My boss does not think we need to upgrade. From gagsl-py2 at yahoo.com.ar Wed May 14 00:18:24 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 14 May 2008 01:18:24 -0300 Subject: file locked for writing References: <91325fec0805130757neb11c4aucfdf825db300d942@mail.gmail.com> Message-ID: En Tue, 13 May 2008 11:57:03 -0300, Dmitry Teslenko escribi?: > Hello! > I use some script in python 2.5 from vim editor (it has python > bindings) that updates some file > and then launches another program (ms visual studio, for example) to > do something with updated file. > I faced problem when updated file is locked for writing until vim > editor is closed. > > launch vim -> update file -> launch msvc -> file locked > launch vim -> update file -> launch msvc -> close vim -> file locked > launch vim -> update file -> -> close vim -> launch msvc -> file okay > > Update code is something like that: > > backup_file_name = '' > with open(backup_file_name, 'w') as backup_file: > input = sax.make_parser() > output = saxutils.XMLGenerator(backup_file, 'cp1252') > filter = __vcproj_config_filter('', input, output) > filter.parse('') > shutil.copyfile(backup_file_name, '') > os.remove(backup_file_name) > > __vcproj_config_filter is a descent of a XMLFilterBase; it substitutes > some attributes in xml file and that's all. > must be noted that __vcproj_config_filter instance holds reference to > output (sax xml parser) object. Is the code above contained in a function? So all references are released upon function exit? If not, you could try using: del input, output, filter That should release all remaining references to the output file, I presume. Or locate the inner reference to the output file (filter.something perhaps?) and explicitely close it. -- Gabriel Genellina From yhvh2000 at googlemail.com Thu May 8 23:42:59 2008 From: yhvh2000 at googlemail.com (yhvh) Date: Thu, 8 May 2008 20:42:59 -0700 (PDT) Subject: range with variable leading zeros Message-ID: <52c13461-f1e6-45f7-9131-8b311bb59ecc@i76g2000hsf.googlegroups.com> I want to generate a range with variable leading zeros x = [0010, 0210] padding = len(x[1]) for j in range(x[0], x[1]): print (url).join('%0(pad)d(jj)'+'.jpg') %{'pad':padding, 'jj':j} This is syntactically incorrect, you can't insert a variable into the string format options. Any ideas? From arkanes at gmail.com Mon May 19 13:31:08 2008 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 19 May 2008 12:31:08 -0500 Subject: Thread killing - I know I know! In-Reply-To: References: <6fda9c2c-84fe-4339-8ce2-25b6d6b97ba4@t54g2000hsg.googlegroups.com> Message-ID: <4866bea60805191031p2e70a085s3475e179a3799089@mail.gmail.com> On Mon, May 19, 2008 at 11:36 AM, Roger Heathcote wrote: > sjdevnull at yahoo.com wrote: >> >> On May 16, 11:40 am, Roger Heathcote >> wrote: >>> >>> Despite many peoples insistence that allowing for the arbitrary killing >>> of threads is a cardinal sin and although I have no particular threading >>> problem to crack right now I remain interest in the taboo that is thread >>> killing. The real world and it's data are messy and imperfect and I can > > >> >> In general, use processes when you can and threads only when you >> must. OS designers spent a lot of energy implementing protected >> memory, no sense throwing out a fair chunk of that hard work unless >> you actually need to. > > Fair point, but for sub processes that need to be in close contact with the > original app, or very small functions that you'd like 100s or 1000s of it > seems like a kludge having to spawn whole new processes build in socket > communications and kill via explicit OS calls. I can't see that approach > scaling particularly well but I guess there's no choice. > It's not a kludge - the whole reason why killing a thread is undefined and a "cardinal sin" is because it's in your own address space and you can't guarantee anything about how it left things when you killed it. You simply can't have it both ways. If you want to be able to safely and sanely kill an uncooperative thread (*especially* third party code you don't control) you have to isolate it from your address space, and this means a process. This is a fundamental problem with the entire idea of shared-state concurrency. For the record, you can't use 1000s of threads either - if you really need 1000s of concurrent things running you need to re-think your concurrency model and possibly your choice of languages and environment. The messiness of the real world is *why* you should use processes, not a reason to avoid them. > Does anyone think it likely that the threading module (and threading in > general) will be improved and augmented with features like timeouts and > arbitrary threadicide in the next year or two? Seems there's little scope > for tapping the power of the current generation of multiple cores with the > current pythons, tho I appreciate breakneck speed has never been a design > objective it looks like multicore is set to be the next generation PC > architecture. > They absolutely should not be. Adding an API which can't work in the general case and is dangerous even when it can work does not do anyone any favors. > Roger Heathcote - technicalbloke.com > -- > http://mail.python.org/mailman/listinfo/python-list > From __peter__ at web.de Tue May 13 09:32:00 2008 From: __peter__ at web.de (Peter Otten) Date: Tue, 13 May 2008 15:32:00 +0200 Subject: Best way to delimit a list? References: <57129f75-b496-40fc-8b2d-d93ba544d4c5@u6g2000prc.googlegroups.com> Message-ID: Giuseppe Ottaviano wrote: > def ichain(seq): > ????????for s in seq: > ????????????????for x in s: yield x > > (which is often useful and I don't think it has been included in ? > itertools) you can iterate lazily on the file: Python 2.6 includes itertools.chain.from_iterable() with that functionality. Peter From sebastian.noack at googlemail.com Wed May 28 06:13:10 2008 From: sebastian.noack at googlemail.com (sebastian.noack at googlemail.com) Date: Wed, 28 May 2008 03:13:10 -0700 (PDT) Subject: tarfile.open(mode='w:gz'|'w|gz'|..., fileobj=StringIO()) fails. References: <133193d2-a87f-4000-b70c-29fdbb36f6d0@59g2000hsb.googlegroups.com> <35552ee8-4c87-4694-b783-aa4315f3ce18@m73g2000hsh.googlegroups.com> <414185e8-26cb-437f-abc5-70cd547450a8@34g2000hsh.googlegroups.com> Message-ID: <7c614790-5233-45c2-bcda-4eee0a9c4bcb@z72g2000hsb.googlegroups.com> That is right, only bz2 is affected. I am happy that i could help. ;) Regards Sebastian Noack From dkcombs at panix.com Thu May 29 21:08:47 2008 From: dkcombs at panix.com (David Combs) Date: Fri, 30 May 2008 01:08:47 +0000 (UTC) Subject: VERY SORRY FOR THAT CROSSPOST; Re: The Importance of Terminology's Quality References: Message-ID: (This one is also cross-posted, to apologize to one and all about my just-prior followup.) I stupidly didn't remember that whatever followup I made would also get crossposted until *after* I had kneejerked hit "s" (send) before I noticed the warning (Pnews?) on just how many groups it would be posted to. A suggestion for Pnews: that as soon as you give the F (followup for trn), ie as soon as Pnews starts-up on this followup, before you've typed in anything or given it a filename to include, that AT THAT TIME it remind you that it'll be crossposted to the following 25 newsgroups: 1: foo 2: comp.lang.perl.misc 3: other-group 4: ... , so way before you've said anything, you can abort it if you want to. SORRY! David From rsoh.woodhouse at googlemail.com Wed May 28 15:31:45 2008 From: rsoh.woodhouse at googlemail.com (rsoh.woodhouse at googlemail.com) Date: Wed, 28 May 2008 12:31:45 -0700 (PDT) Subject: Threads and import References: <6d04f375-9cc6-428b-aafb-d5b947d6e915@b1g2000hsg.googlegroups.com> <6a5pulF36888qU1@mid.uni-berlin.de> Message-ID: <0d96c6da-d239-4b15-8456-70e2d9e67fa2@59g2000hsb.googlegroups.com> On May 28, 8:26 pm, "Diez B. Roggisch" wrote: > rsoh.woodho... at googlemail.com schrieb: > > > > > Hi, > > > I'm trying to work out some strange (to me) behaviour that I see when > > running a python script in two different ways (I've inherited some > > code that needs to be maintained and integrated with another lump of > > code). The sample script is: > > > # Sample script, simply create a new thread and run a > > # regular expression match in it. > > import re > > > import threading > > class TestThread(threading.Thread): > > > def run(self): > > print('start') > > try: > > re.search('mmm', 'mmmm') > > except Exception, e: > > print e > > print('finish') > > > tmpThread = TestThread() > > tmpThread.start() > > tmpThread.join() > > import time > > for i in range(10): > > time.sleep(0.5) > > print i > > > # end of sample script > > > Now if I run this using: > > > $ python ThreadTest.py > > > then it behaves as expected, ie an output like: > > > start > > finish > > 0 > > 1 > > 2 > > ... > > > But if I run it as follows (how the inherited code was started): > > > $ python -c "import TestThread" > > > then I just get: > > > start > > > I know how to get around the problem but could someone with more > > knowledge of how python works explain why this is the case? > > Works for me. And I don't see any reason why it shouldn't for you - > unless you didn't show us the actual code. > > Diez Strange. That is the code exactly as I run it using python 2.4.4 2.5.1 on Ubuntu 7.10. Which version of python/what platform were you using? Rowan From maxerickson at gmail.com Thu May 15 10:01:51 2008 From: maxerickson at gmail.com (Max Erickson) Date: Thu, 15 May 2008 14:01:51 +0000 (UTC) Subject: send yield References: <6a19b5bf-ed71-499c-a348-6e26e2f523eb@m45g2000hsb.googlegroups.com> Message-ID: castironpi wrote: > Why can't I write this? > -- > http://mail.python.org/mailman/listinfo/python-list > > Because you don't know how? max From nick at craig-wood.com Fri May 30 07:30:20 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Fri, 30 May 2008 06:30:20 -0500 Subject: ctypes, function pointers and a lot of trouble References: Message-ID: Matt wrote: > Okay, thanks a lot for your reply Nick, I think you pushed me back on > the right way. Good! > Now I started with trying to implement the callback functions and am > stuck at the following point: > > I define my classes/structures/unions: > > class cdStream(Structure): > _fields_ = [("contextH", c_uint), > ("open", c_void_p), [snip] > then i define my functions (right now I do just nothing) and at the same > time I define the datatypes like they're listed in my C sample program: > > def pystreamopen (contextH, mode, pErr): > pass > > cstreamopen = CFUNCTYPE(c_uint, c_ushort, c_uint) [snip] > and now the problem starts: i want the pointers in the cdStream > Structure point at my functions and tried to do it the following way: > > data = cdStgMedium() > data.type = 0 > data.u.pStream.contextH = c_uint(3) #must be some kind of identifier. > data.u.pStream.open = cstreamopen(pystreamopen) [snip] > unfortunately that doesn't work because Python returns a TypeError: > incompatible types, CFunctionType instance instead of c_void_p instance > > Any ideas/help (please)? Probably the best thing is if you define the union with the types of the pointers to your functions instead of c_void_p, eg class cdStream(Structure): _fields_ = [("contextH", c_uint), ("open", cstreamopen), ("close", cstreamclose), # etc... This will involve you re-ordering your definitions. Or alternatively, you could cast the function pointer to a c_void_p first, eg data.u.pStream.open = c_void_p( cstreamopen(pystreamopen) ) which should work but is less typesafe. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From kamhung.soh at gmail.com Mon May 19 19:05:48 2008 From: kamhung.soh at gmail.com (Kam-Hung Soh) Date: Tue, 20 May 2008 09:05:48 +1000 Subject: Separate output for log file and stdout References: <54a53d7f-b137-49cc-8ea4-cc0b184384f0@k1g2000prb.googlegroups.com> <878wy9soce.fsf@benfinney.id.au> <60a036c9-aa6b-4751-b956-8bb8b04459f1@c19g2000prf.googlegroups.com> Message-ID: On Tue, 20 May 2008 06:58:28 +1000, wrote: > On May 16, 6:37 pm, Ben Finney > wrote: >> amit.ut... at gmail.com writes: >> > I've recently jumped big time into python and I'm working on a >> > software program for testing automation. >> >> Welcome, to both fields :-) >> > > Thanks! I am having a great time learning and coding in python. It's > an amazing programming language. > >> > I had a question about proper logging of output. What I would like >> > is: >> >> > 1. a function syslog (to log output to log file only) >> > 2. a function stdout (to log output to stdout only) >> > 3. a function sslog (to log output to both log and stdout) >> >> > Right now I am using StandOut module >> >> Have you investigated the 'logging' module in the Python standard >> library ? It appears >> to meet your listed requirements, without need of external >> dependencies. > > Hmm..Yeah I didn't realize python had its own standard logging > facility. I took a look at it and it seems to do the job. However, the > output seems to be syslog style output. In the program I am writing, > the log file stores all the output of the commands being run (e.g. tcl > scripts, etc). Will this be possible using the built in python logging > module? > > Thanks, > Amit > -- > http://mail.python.org/mailman/listinfo/python-list > You can define the format of the log output in basicConfig(), for example: from logging import basicConfig, error, info, INFO ... basicConfig( datefmt='%Y%m%d_T%H%M%S', filemode='a', filename=LOG_PATH, format='%(asctime)s,%(levelname)s,%(message)s', level=INFO ) If you want to log the output of other commands in your log file, you can connect a pipe to that command. Maybe look at "subprocess -- Subprocess management" in http://docs.python.org/lib/module-subprocess.html -- Kam-Hung Soh Software Salariman From exarkun at divmod.com Mon May 5 09:48:36 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 5 May 2008 09:48:36 -0400 Subject: How to convert unicode string to unsigned char * In-Reply-To: <725404980805050641s52cac3b8mf238ff29883c6dba@mail.gmail.com> Message-ID: <20080505134836.6859.727372751.divmod.quotient.59037@ohm> On Mon, 5 May 2008 15:41:08 +0200, Simon Posnjak wrote: >Hi! > >I have a C module for which I created a wrapper with swig. The function def is: > >C: > >int some_thing(unsigned char * the_str); > >eg: > >Python: > >some_module.some_thing (the_str) > >Now I would like to feed it with a UTF-8 formatted string: > >test = u'Make \u0633\u0644\u0627\u0645, not war.' `test? is not a UTF-8 encoded string. It's a unicode string. To get a UTF-8 encoded string from a unicode string, use the `encode? method: some_module.some_thing(test.encode('utf-8')) Jean-Paul From fred.sells at adventistcare.org Tue May 20 09:52:12 2008 From: fred.sells at adventistcare.org (Sells, Fred) Date: Tue, 20 May 2008 09:52:12 -0400 Subject: Newbie In Python In-Reply-To: <4832a6e3$0$28693$426a74cc@news.free.fr> Message-ID: <0A53725C4A497848A7B3A0874B259831011B090D@acesxch01.ADVENTISTCORP.NET> get a python-aware editor. I vary between emacs and Eclipse, depending on my mood and the size of the project. > -----Original Message----- > From: python-list-bounces+frsells=adventistcare.org at python.org > [mailto:python-list-bounces+frsells=adventistcare.org at python.org]On > Behalf Of Bruno Desthuilliers > Sent: Tuesday, May 20, 2008 6:25 AM > To: python-list at python.org > Subject: Re: Newbie In Python > > > andrew.smith.cpp at gmail.com a ?crit : > > I have Heard About "Python" its a OOD Language. > > 'OOD' => 'object oriented ???' ? > > > i have to Learn it > > where from i should start it. > > Err... What about reading the docs on python.org - possibly starting > with the tutorial: > http://docs.python.org/tut/tut.html > > You'll find other tutorial etc here: > http://www.python.org/doc/ > > > > i have python compiler > > Just for the record, "python" is also the name of a compiler for CMU > Common Lisp (totally unrelated to the Python language), so make sure > that what you have is the CPython language install. > > HTH > -- > http://mail.python.org/mailman/listinfo/python-list > From tjreedy at udel.edu Tue May 13 03:11:30 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 13 May 2008 03:11:30 -0400 Subject: Is using range() in for loops really Pythonic? References: <482657ca$0$25026$607ed4bc@cv.net><41078222-aec0-4e8b-8a1f-945cdf814498@m73g2000hsh.googlegroups.com><48275446$0$11628$607ed4bc@cv.net> <87mymw8nr0.fsf@benfinney.id.au><4827bda2$0$11606$607ed4bc@cv.net> <87od7c6qua.fsf@benfinney.id.au> <482912b7$0$11641$607ed4bc@cv.net> Message-ID: "John Salerno" wrote in message news:482912b7$0$11641$607ed4bc at cv.net... | The reason I even brought this up is because I remember someone saying a | while back (probably here on the newsgroup) that the true use of a for | loop was to iterate through a sequence (for the purpose of using that | sequence), not to do something X number of times. I believe the specific context was to counteract some people's tendency to write for i in range(len(seq)): do stuff with seq[i] when they would better (more Pythonically) write for item in seq: do stuff with item or even for i,item in enumerate(seq): do stuff with i and item. One subtle but real advantage is that the latter two forms work with iterables that do not have a known-ahead length or which even continue indefinitely. | Once they made this | comment, I suddenly saw the for loop in a new (and I believe purer) | light. That was the first time I realized what it was really meant | to do. That is an important insight. But to me it does not negate the "do something n times" usage when there is no iterable other than range to iterate. Do note that range has *not* been removed from 3.0 and that its main intended usage is for looping. | Now, you could easily make the argument that the Python for loop is a | much simpler tool to accomplish *both* of the above, and I suppose that | makes sense. Yes. Python leans toward minimalism. Proposals for various special-purpose loopin constructs have been rejected. For-loops cover most looping needs; while-loops cover everything else. Terry Jan Reedy From terry at jon.es Mon May 5 16:01:02 2008 From: terry at jon.es (Terry Jones) Date: Mon, 5 May 2008 22:01:02 +0200 Subject: [Twisted-Python] Counting errors in a DeferredList and avoiding Unhandled error in Deferred messages In-Reply-To: Your message at 13:38:13 on Monday, 5 May 2008 References: <18463.16271.516266.379803@jon.es> <20080505173813.6859.2132215018.divmod.quotient.59119@ohm> Message-ID: <18463.26494.36090.371860@jon.es> Hi Jean-Paul > You can do this (if you replace `pass? with `None?, anyway) or you can pass > `consumeErrors=True? to the `DeferredList? initializer which will make it > do something equivalent. Thanks. Sorry - I should have just read the docs again :-) Terry From ranjan.suruchi at gmail.com Thu May 8 07:19:08 2008 From: ranjan.suruchi at gmail.com (ranjan) Date: Thu, 8 May 2008 04:19:08 -0700 (PDT) Subject: Urgent opening for Engineer (Open Source Technologies) Message-ID: <2706fed6-8d00-4dd3-b6ea-815e1b607516@f24g2000prh.googlegroups.com> Hi,This is regarding an opening for software Engineer(Open Source Technologies) The opening is with our client for their Noida branch.They are working on various platforms like Microsoft,Open Source Technology. The designation will be of software engineer/senior software engineer. Skillset Required will be Plone,experience in development & implementation of applications using Python & open source technologies. Experience : 2-3 years Qualification : BE/B.Tech/MCA/PGDCA or equivalent. If you are interested you can forward your CV on this mail id ranjan.suruchi at gmail.com as early as possible. From wojtek.gminick.walczak at gmail.com Tue May 6 02:32:03 2008 From: wojtek.gminick.walczak at gmail.com (Wojciech Walczak) Date: Tue, 6 May 2008 08:32:03 +0200 Subject: Decimal vs Float comparasion In-Reply-To: <91320d220805052052r56b61880v2cfb46ff89e605be@mail.gmail.com> References: <91320d220805052052r56b61880v2cfb46ff89e605be@mail.gmail.com> Message-ID: <2c3c21060805052332r6261d8cbt59817603a2d37e00@mail.gmail.com> 2008/5/6, Yuan HOng : > It seems decimal object will always be larger than float in > comparasion, which goes against common sense: > > >>> from decimal import Decimal > >>> a = Decimal('0.5') > >>> a > 99999 > False > >>> a > 99999.0 > True > > It seems to me that rather than allowing this to happen, comparasion > between the two should either be made correct (by convertion decimal > to float e.g.) or forbidden, like arithmatic operations between the > two types. Looks like a nasty bug. a > 99999.0 returns True because NotImplemented > 99999.0 returns True. a < 99999.0 returns False because NotImplemented < 99999.0 returns False. As you can see the real comparision has nothing to do with your Decimal number. I think you can report it at bugs.python.org. -- Regards, Wojtek Walczak http://www.stud.umk.pl/~wojtekwa/ From pavlovevidence at gmail.com Fri May 23 21:00:29 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 23 May 2008 18:00:29 -0700 (PDT) Subject: Assignment and comparison in one statement References: Message-ID: <10f19bee-1e0a-4401-a03b-18c458388297@s50g2000hsb.googlegroups.com> On May 23, 6:59 pm, Johannes Bauer wrote: > Hello group, > > I'm just starting with Python and am extremely unexperienced with it so > far. Having a strong C/C++ background, I wish to do something like > > if (q = getchar()) { > printf("%d\n", q); > > } > > or translated to Python: > > if (p = myfunction()): > print p > > However, this "assignment and comparison" is not working. What's the > "Python way" of doing this kind of thing? p = myfunction() if p: print p (I recommend doing it this way in C, too.) For the case where you want to do this in an elif-clause, look for the recent thread "C-like assignment expression?" which list some workarounds. Or just Google this newsgroup for "assignment expression". It's one of few minor irritating things in Python syntax. Carl Banks From unknown_hero007 at hotmail.com Tue May 6 08:05:21 2008 From: unknown_hero007 at hotmail.com (Unknown Hero) Date: Tue, 6 May 2008 05:05:21 -0700 (PDT) Subject: Scanning through Windows registry... References: Message-ID: Tim Golden wrote: > In a spirit of teaching people to fish... > > ... If you put something like "Python windows registry" into Google, you > get quite a few hits, the top one of which is probably pointing to the stdlib > _winreg module, but several others point towards wrapper classes, modules > etc. which provide a simpler or at least a different interface to the registry. > > Have a look at those and see if you can't work out what to do. > > TJG The first link which points to the Python documentation for the _winreg module I already checked, even before coming here. I am wondering how I should do the loop I need (go through HKEY_LOCAL_MACHINE and read one subkey at a time, if it contains this 'foo' then change it into 'moo'). As I already said, I am by no means an expert in Python (heck, I learned the basics only a month ago). However, I am willing to learn. Also my prior experience with the Windows registry is mostly by the Registry Editor shipped with Windows. While I do understand what keys, values and hives are, I do not have a great experience in the others. If it's not too much to ask, maybe someone (who is much better than me) could make a code snippet that reads a certain hive and replaces values that are predetermined (preferably variables, not arguments if possible). If that's out of the question, at least push me gently into the right direction. So basically I am looking for these things: 1) Read one subkey from HKEY_LOCAL_MACHINE at a time (I think QueryValueEx() is needed here) 2) Check if said subkey contains some predetermined string (like 'foo' here) 3) If the above applies, change the value into another predetermined string (like 'moo' here) Also, how should I determine the length of the loop? I personally am too fond of the for loop, but if I need to use, like, while, then so be it. Thanks in advance. From deets at nospam.web.de Wed May 7 08:36:51 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 07 May 2008 14:36:51 +0200 Subject: Learning question... References: Message-ID: <68dm40F2rekquU1@mid.uni-berlin.de> swapsun at gmail.com wrote: > Any idea why the following program does not work? I was learning IO on > Python and the following generates a TypeError: range() integer end > argument expected, got str. > I am a beginner. Because raw_input does return you as string which you need explicitly convert to a number, e.g. doing i = int(input) Diez From skanemupp at yahoo.se Thu May 15 12:03:31 2008 From: skanemupp at yahoo.se (globalrev) Date: Thu, 15 May 2008 09:03:31 -0700 (PDT) Subject: exists=false, but no complaint when i open it!? Message-ID: <285e0ce6-1371-4ab7-9281-ad1d664a480f@a23g2000hsc.googlegroups.com> print os.path.exists('C:\Users\saftarn\Desktop\NetFlixDataSet \trainingsetunzipped\training_set\mv_0000001.txt') d=open('C:/Python25/myPrograms/mapexperiments/maps/provinces-of- sweden.gif') d.close() exists returns false but when i open it doesnt complain. how come? another file that exists returned false for complained when i tried to open it. From castironpi at gmail.com Thu May 15 09:51:38 2008 From: castironpi at gmail.com (castironpi) Date: Thu, 15 May 2008 06:51:38 -0700 (PDT) Subject: no inputstream? References: <692sk0F3090hfU1@mid.uni-berlin.de> Message-ID: <46abd84e-f943-48a5-94b9-81f2f47cc887@f63g2000hsf.googlegroups.com> On May 15, 8:37?am, Marc 'BlackJack' Rintsch wrote: > On Thu, 15 May 2008 06:08:35 -0700, max wrote: > > i currently have locations of the mp3s in question as strings, which > > works for parsing local files, but gives me a "No such file or > > directory" error when it tries to process URLs. ?it seems terribly > > inefficient to download each mp3 just to get at that small tag data, > > and i assume there's a way to do this with file() or open() or > > something, i just can't get it to work. > > You can use `urllib2.urlopen()` to open URLs as files. ?But if you deal > with ID3 V1 tags you'll have to download the file anyway because those are > in the last 128 bytes of an MP3 file. > > Ciao, > ? ? ? ? Marc 'BlackJack' Rintsch Just don't import time. What would you do with an autolocking timer, such as time.sleep( ) on a thread? I am tongue tied in the presence of a lady. From sjmachin at lexicon.net Sat May 24 09:29:58 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 24 May 2008 13:29:58 GMT Subject: SQLite import fails sometimes ? In-Reply-To: References: <4837f7d1$1@news.mel.dft.com.au> Message-ID: <48381851$1@news.mel.dft.com.au> Stef Mientki wrote: > I don't know if this matters, but I also use sqlite3 from other than > Python programs. You have an instance of sqlite3.dll in P:\Python\DLLs for use with Python, and (I guess) you have another instance of sqlite3.dll somewhere else, for use "from other than Python programs". Are they the same version? If not, this may be the problem. Start up your other application, then try to import sqlite3 from Python. If this is the problem, and you must be able to run both apps simultaneously, you will probably need to update one or the other. Cheers, John From mde at MicahElliott.com Tue May 6 19:00:13 2008 From: mde at MicahElliott.com (Micah Elliott) Date: Tue, 06 May 2008 16:00:13 -0700 Subject: open filename with spaces in path In-Reply-To: References: Message-ID: <20080506230013.GE6567@micahelliott.com> On 2008-05-06 Michael Robertson wrote: > I'm having trouble opening a file in linux, whose path has > spaces in it. > > $ mkdir my\ test > $ echo test > my\ test/test.txt > $ python > > >>> open('./my test/test.txt') > Exception That's funny. These exact steps work fine for me on Linux, with Python 2.5.2, and even 1.5.2. Does 'os.path.normpath' have anything interesting to say about what you're passing it? > but yet... > > >>> import os > >>> os.chdir('./my test') > >>> open('./test') > > works just fine. How doctored up is this example? In the above ./test should not actually exist. Did the chdir actually work? Or did you remove the .txt? -- Micah Elliott | mde at MicahElliott.com | http://MicahElliott.blogspot.com From zephyrfalcon!NO_SPAM! at gmail.com Fri May 16 17:51:12 2008 From: zephyrfalcon!NO_SPAM! at gmail.com (Hans Nowak) Date: Fri, 16 May 2008 17:51:12 -0400 Subject: can't delete from a dictionary in a loop In-Reply-To: <43a76233-01cd-4350-b486-cf3e1b32d9dd@k13g2000hse.googlegroups.com> References: <43a76233-01cd-4350-b486-cf3e1b32d9dd@k13g2000hse.googlegroups.com> Message-ID: bruno.desthuilliers at gmail.com wrote: > On 16 mai, 23:34, "bruno.desthuilli... at gmail.com" > wrote: >> On 16 mai, 23:28, Hans Nowak wrote: >> >> >>> Dan Upton wrote: >>>> for pid in procs_dict: > (snip) >>> for pid in procs_dict.keys(): >> I'm afraid this will do the same exact thing. A for loop on a dict >> iterates over the dict keys, so both statements are strictly >> equivalent from a practical POV. > > Hem. Forget it. I should think twice before posting - this will > obviously make a big difference here. Sorry for the noise. :-) It appears that you would be right if this was Python 3.0, though: Python 3.0a5 (r30a5:62856, May 16 2008, 11:43:33) [GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> d = {1: 2, 3: 4, 5: 6} >>> for i in d.keys(): del d[i] ... Traceback (most recent call last): File "", line 1, in RuntimeError: dictionary changed size during iteration Maybe 'for i in d' and 'for i in d.keys()' *are* functionally equivalent in 3.0, as d.keys() returns an object that iterates over d's keys... but I haven't read enough about it yet to be sure. In any case, the problem goes away when we force a list: >>> d = {1: 2, 3: 4, 5: 6} >>> for i in list(d.keys()): del d[i] ... >>> d {} --Hans From jenn.duerr at gmail.com Tue May 13 15:02:29 2008 From: jenn.duerr at gmail.com (Jennifer Duerr) Date: Tue, 13 May 2008 12:02:29 -0700 (PDT) Subject: SOAP/ZSI post/get for Java Web App Message-ID: All, I need help concerning SOAP, Python and XML. I am very new to this, so dumbing it down for me will not offend me! I'm using Python and want to send a user-inputted string to an existing Java web app that will output results to XML. I need to capture elements of the XML and put the info into a table. (say I send a single/simple address string to this webservice/geocode, which then returns numerous possible matches with XY values and score values, and I want to capture that into a table) How do I go about doing this? I'm told I need to use SOAP. I discovered that the best module to use is ZSI (please correct me if I'm wrong). I have installed the necessary module. Examples I have seen are plenty and all so different, its not clear to me how to go about. I have been spinning my wheels for too long on this! Can someone provide some example code similar to what I need to do? Or any guidance would be appreciated. Thanks! From ladynikon at gmail.com Thu May 1 14:39:47 2008 From: ladynikon at gmail.com (Danyelle Gragsone) Date: Thu, 1 May 2008 14:39:47 -0400 Subject: DO U WANT TO KNOW ABOUT SCIENTOLOGY? In-Reply-To: <72c27738-3d8a-4a9d-8250-17e4d4f8cad3@a70g2000hsh.googlegroups.com> References: <7fe132fe-8a8a-4abc-9d8e-f1c27d00cc48@z24g2000prf.googlegroups.com> <72c27738-3d8a-4a9d-8250-17e4d4f8cad3@a70g2000hsh.googlegroups.com> Message-ID: <59f9c5160805011139g47089eaah95f4281e6036f00@mail.gmail.com> <3 BAHAHAHAA From pm604407 at gmail.com Sat May 31 00:49:07 2008 From: pm604407 at gmail.com (meg) Date: Fri, 30 May 2008 21:49:07 -0700 (PDT) Subject: TRISHA FILM ACTRESS Message-ID: <12acbb43-d107-47ff-869a-a161af8bd59f@w34g2000prm.googlegroups.com> http://trishafilmactress.blogspot.com/2008/05/modern-trisha.html From robin at NOSPAMreportlab.com Tue May 20 16:51:33 2008 From: robin at NOSPAMreportlab.com (Robin Becker) Date: Tue, 20 May 2008 21:51:33 +0100 Subject: Report Lab Image Flowable Issue .. In-Reply-To: References: Message-ID: <483339D5.5000308@jessikat.plus.net> dbee wrote: > I'm try to generate a report that will span multiple pages and have > dynamic content using python reportlab. I have no issues with regards > to generating images and then using p.drawInlineImage(signup_img, > 100,150) to draw them onto the canvas. > > The problem that i have comes when i try to create flowables so that > my layout can span multiple pages. The images themselves never > actually show up on the page ... ...... I think you should ask this on the reportlab users list which you can find at http://two.pairlist.net/pipermail/reportlab-users/ As for your specific problem perhaps you should start with some simple examples. -- Robin Becker From niklas.norrthon at hotmail.com Fri May 9 06:46:49 2008 From: niklas.norrthon at hotmail.com (Niklas Norrthon) Date: Fri, 9 May 2008 03:46:49 -0700 (PDT) Subject: Pythonwin References: Message-ID: On 9 Maj, 12:30, Clive_S wrote: > Hi > > I am trying to use Python with ArcGIS. > > I have installed Python 2.4. I have an icon for IDLE and command line. > I do not see Python PythonWin. > > How do you install or launch pythonwin?? There is a distribution of PythonWin bundled with the ArcGIS Desktop installation media, but it is not installed by the ArcGIS installer. You have three options: 1. Install it manually from the ArcGIS installation media. 2. Find it on the web (google for it), download and install. 3. (My recommendation) Don't bother. IDLE is pretty good. Emacs even better (unless you hate emacs). -- Niklas Norrthon ESRI S-GROUP From dullrich at sprynet.com Wed May 14 16:37:50 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Wed, 14 May 2008 15:37:50 -0500 Subject: wxpython dialog - do something after ShowModal()? References: Message-ID: In article , Iain King wrote: > Hi. I have a modal dialog whcih has a "Browse..." button which pops > up a file selector. This all works fine, but the first thing the user > has to do when they open the dialog is select a file, so I would like > the dialog to automatically call the onBrowse function as soon as the > dialog opens. However, I don't know how to do this. > > dlg.ShowModal() > onBrowse() > > obviously doesn't work, and neither does the reverse. I was hoping > that the dialog would throw some kind of "I have been shown" event, > but it doesn't (as far as I can tell). How do I make the dialog do > something as soon as it's been shown? It's too bad that you found an answer. You _shouldn't_ have your dialog pop up a file-selection box as soon as it's shown! That's not the way dialogs usually work, so you're going to confuse people. Instead, first pop up the file-selection box, and then pop up the dialog (without the Browse button) to do whatever else it does after you've got the filename. > Iain From aisaac at american.edu Sun May 11 00:08:38 2008 From: aisaac at american.edu (Alan Isaac) Date: Sun, 11 May 2008 04:08:38 GMT Subject: observer pattern (notification chain synchronization) In-Reply-To: References: Message-ID: J. Cliff Dyer wrote: > looks like a good approach to me OK, thanks. Another approach is to begin with a set of stocks and remove them as they report. You can then trigger a report with the empty set instead of repeatedly calling ``all``. After a report the set can be "refilled". Cheers, Alan Isaac From gherron at islandtraining.com Wed May 28 12:19:32 2008 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 28 May 2008 09:19:32 -0700 Subject: Any way to loop through object variables? In-Reply-To: <483D7A47.3030606@ecs.soton.ac.uk> References: <483D7A47.3030606@ecs.soton.ac.uk> Message-ID: <483D8614.7000808@islandtraining.com> Dave Challis wrote: > Hi, > Just wondering if there's a way to iterate through all variables which > an object has set? > > Specifically, I'm using the OptionParser module, which returns an > options object, containing all command line options as object variables. > I'd like to iterate over these rather than getting at them by name. > > Cheers, > Dave For this object (and many others), you can get at the attributes with the vars(...) builtin. It returns a dictionary of attribute names and values. Gary Herron -- http://mail.python.org/mailman/listinfo/python-list From inhahe at gmail.com Fri May 16 14:12:47 2008 From: inhahe at gmail.com (inhahe) Date: Fri, 16 May 2008 14:12:47 -0400 Subject: morning in Python References: <409ea9f1-9774-4bf2-abac-2daf997bc97f@c65g2000hsa.googlegroups.com> <19286799-53b1-4ba9-bb16-e3f963da7dc6@m3g2000hsc.googlegroups.com> Message-ID: <28kXj.142759$Er2.39732@bignews6.bellsouth.net> "George Sakkis" wrote in message news:19286799-53b1-4ba9-bb16-e3f963da7dc6 at m3g2000hsc.googlegroups.com... On May 16, 11:58 am, "inhahe" wrote: > I'm not an expert in this but what does it mean to emphasize state? It > seems the opposite of that would be a) functional programming, and b) > passing parameters instead of using global or relatively local variables. > And maybe c) coroutines (generators as implemented in Python), although > perhaps coroutines could be said to emphasize state inasmuch as they go > out > of their way to capture, objectify and reuse it (Stackless' microthreads, > even moreso). And Python seems to be well-noted for implementing some > functional programming methodology, and as for passing parameters it's > just > as object-oriented as the rest of them. > > But as I said, I'm not an expert, so let me know if I've gone astray.. > > > I have a proposition to ask you all: Python emphasizes state. Is it > > true? Please don't feed the bots. -- I figured the question was interesting enough to warrant discussion whether it was a bot or not. But i'm not an avid forum user, so maybe I'm wrong. Also, if it's a bot I'm floored and the man who wrote it could probably solve cancer and world hunger with five lines of asm. From castironpi at gmail.com Wed May 7 05:59:53 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 7 May 2008 02:59:53 -0700 (PDT) Subject: saving a webpage's links to the hard disk References: <9a4733b4-5320-4a66-b0ce-5dcebc02d9a7@y38g2000hsy.googlegroups.com> <7ccc9c7b-002c-4385-9832-aaa0981638da@2g2000hsn.googlegroups.com> Message-ID: On May 7, 1:40?am, Jetus wrote: > On May 4, 7:22 am, castiro... at gmail.com wrote: > > > > > > > On May 4, 12:33 am, "Gabriel Genellina" > > wrote: > > > > En Sun, 04 May 2008 01:33:45 -0300, Jetus escribi?: > > > > > Is there a good place to look to see where I can find some code that > > > > will help me to save webpage's links to the local drive, after I have > > > > used urllib2 to retrieve the page? > > > > Many times I have to view these pages when I do not have access to the > > > > internet. > > > > Don't reinvent the wheel and use wgethttp://en.wikipedia.org/wiki/Wget > > > > -- > > > Gabriel Genellina > > > A lot of the functionality is already present. > > > import urllib > > urllib.urlretrieve( 'http://python.org/', 'main.htm' ) > > from htmllib import HTMLParser > > from formatter import NullFormatter > > parser= HTMLParser( NullFormatter( ) ) > > parser.feed( open( 'main.htm' ).read( ) ) > > import urlparse > > for a in parser.anchorlist: > > ? ? print urlparse.urljoin( 'http://python.org/', a ) > > > Output snipped: > > > ...http://python.org/psf/http://python.org/dev/http://python.org/links/h... > > ... > > How can I modify or add to the above code, so that the file references > are saved to specified local directories, AND the saved webpage makes > reference to the new saved files in the respective directories? > Thanks for your help in advance.- Hide quoted text - > > - Show quoted text - You'd have to convert filenames in the loop to a file system path; try writing as is with makedirs( ). You'd have to replace contents in a file for links, so your best might be prefixing them with localhost and spawning a small bounce-router. From banibrata.dutta at gmail.com Fri May 9 09:17:27 2008 From: banibrata.dutta at gmail.com (Banibrata Dutta) Date: Fri, 9 May 2008 18:47:27 +0530 Subject: How to kill Python interpreter from the command line? In-Reply-To: <383c934a-0a23-401f-bc09-898be0941be0@e39g2000hsf.googlegroups.com> References: <3d47e5d2-8e7c-497d-b461-7cc6ff1beb58@a1g2000hsb.googlegroups.com> <383c934a-0a23-401f-bc09-898be0941be0@e39g2000hsf.googlegroups.com> Message-ID: <3de8e1f70805090617g4f51d40fo57965ae293562979@mail.gmail.com> Any chance that there is a "catch-all" in the code. As per PEP8 and I'm sure common knowledge of all the folks programming in Python for a while -- a >>>catch: could just lead to this problem. On 5/9/08, Floris Bruynooghe wrote: > > On May 9, 11:19 am, spectru... at gmail.com wrote: > > Thanks for the replies. > > > > On May 8, 5:50 pm, Jean-Paul Calderone wrote: > > > > > Ctrl+C often works with Python, but as with any language, it's possible > > > to write a program which will not respond to it. You can use Ctrl+\ > > > instead (Ctrl+C sends SIGINT which can be masked or otherwise ignored, > > > Ctrl+\ sends SIGQUIT which typically isn't) > > > > Yes, thank you, this seems to work. :) > > > > I did some more testing and found out that the problem seems to be > > thread-related. If I have a single-threaded program, then Ctrl+C > > usually works, but if I have threads, it is usually ignored. For > > instance, the below program does not respond to Ctrl+C (but it does > > die when issued Ctrl+\): > > > > import threading > > > > def loop(): > > while True: > > pass > > > > threading.Thread(target=loop,args=()).start() > > Your thread needs to be daemonised for this work. Othewise your main > thread will be waiting for your created thread to finish. E.g.: > > thread = threading.Thread(target=loop) > thread.setDaemon(True) > thread.start() > > But now it will exit immediately as soon as your main thread has > nothing to do anymore (which is right after .start() in this case), so > plug in another infinite loop at the end of this: > > while True: > time.sleep(10) > > And now your threaded app will stop when using C-c. > -- > http://mail.python.org/mailman/listinfo/python-list > -- regards, Banibrata http://www.linkedin.com/in/bdutta http://octapod.wordpress.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From alangrow at gmail.com Sat May 17 16:14:50 2008 From: alangrow at gmail.com (alan grow) Date: Sat, 17 May 2008 15:14:50 -0500 Subject: waiting on an event blocks all signals In-Reply-To: <4878ad7b0805171249r58428b47g4f6ebd8d0e3fcd0@mail.gmail.com> References: <27553255-72e6-4df6-944b-ac4637a78f3d@m3g2000hsc.googlegroups.com> <4878ad7b0805171249r58428b47g4f6ebd8d0e3fcd0@mail.gmail.com> Message-ID: On Sat, May 17, 2008 at 2:49 PM, John Schroeder wrote: > ^C only kills the main thread. Use Control-Break to kill all threads. >> >> python -c "import threading; threading.Event().wait()" >> ^C^C^C^C There's a single main thread here though. Or am I missing something? From eliben at gmail.com Sun May 25 11:40:26 2008 From: eliben at gmail.com (eliben) Date: Sun, 25 May 2008 08:40:26 -0700 (PDT) Subject: SocketServer, its offspring, and threads Message-ID: Hello, I have a small wxPython application. Today I was trying to add some RPC capability to it, so I implemented an instance of SimpleXMLRPCServer that runs in a separate thread when invoked and answers requests. All went fine until I realized that I have to sometimes stop the server - which is where I ran into a problem. Python threads can not be killed after they've been started. They can be kindly requested to end, but it's up to the thread itself to decide when it wants to finish. At least this is my understanding. It probably makes sense, because threads can hold resources which can't just be dropped suddenly, and have to be cleaned in a proper manner. (Does this sound like the truth ?) Anyway, this creates a problem because SimpleXMLRPCServer likes to block and never return. I dug deeper and found out that all offspring of SocketServer can only handle requests in a blocking manner. Even if you call handle_request( ) and not serve_forever(), it will block until a request is received and handled. This means that a SocketServer object running in a thread blocks the thread, and this thread can not be stopped. Is there any graceful solution to this problem ? I suppose I can use sockets in non-blocking mode, or use select(), but this will mean I will have to implement my server with raw sockets and not a handy helper like SocketServer. For the XML-RPC server I want this is a headache, as I will probably have to implement my own XML- RPC server based on raw non-blocking sockets. Thanks in advance for any ideas and suggestions Eli From maxm at mxm.dk Tue May 6 16:06:23 2008 From: maxm at mxm.dk (Max M) Date: Tue, 06 May 2008 22:06:23 +0200 Subject: Am I missing something with Python not having interfaces? In-Reply-To: References: <45de2f7e-484a-4871-bbaa-bf7eed5dfa40@x35g2000hsb.googlegroups.com> Message-ID: Arnaud Delobelle skrev: > jmDesktop writes: > >> Studying OOP and noticed that Python does not have Interfaces. Is >> that correct? Is my schooling for nought on these OOP concepts if I >> use Python. Am I losing something if I don't use the "typical" oop >> constructs found in other languages (Java, C# come to mind.) I'm >> afraid that if I never use them I'll lose them and when I need them >> for something beside Python, I'll be lost. Thank you. > > You're not missing anything. An Interface is the Poor Man's Multiple > Inheritance. But in truth, even without multiple inheritance, Python > wouldn't need java-like interfaces. Interfaces are a great concept for many things, and they can cover a few soft spots in Python. There is the possibility of using the great zope.interface library http://pypi.python.org/pypi/zope.interface. Just use: "easy_install zope.interface" And you have interfaces. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From kyosohma at gmail.com Fri May 2 13:43:57 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 2 May 2008 10:43:57 -0700 (PDT) Subject: pygame.key.get_pressed[K_a], K_a is not defined!? References: <680su7F2q6qo2U1@mid.uni-berlin.de> <8f3fead6-895a-4ee4-9fff-2190775da3e9@w7g2000hsa.googlegroups.com> Message-ID: On May 2, 12:03 pm, globalrev wrote: > print pygame.K_a displays 97 btw. what does that mean? i though it > would return true or false or 0 or 1. That's probably the key code value. Or the ASCII representation for the key. You'd have to read the pygame docs to really know. Mike From celoserpa at gmail.com Thu May 15 13:21:34 2008 From: celoserpa at gmail.com (Marcelo de Moraes Serpa) Date: Thu, 15 May 2008 14:21:34 -0300 Subject: Handling test data that depends on temporal data (that might change while the test runs) Message-ID: <1e5bcefd0805151021i6306946dre6e54307e91d9c1c@mail.gmail.com> Hello, So, I have this particular method, generate_chat_dir_string, which should generate a string in the following format: "md5hexstring-day-month-year-hour-minute" This string will be used to create a directory in the filesystem. I'm trying to adopt the TDD approach, so, I'm starting by testing all the methods of the Chat class, including this one. However, an issue just popped up, this is the test code: 1. def test_generate_chat_dir_string(self): 2. import md5 3. import random 4. import datetime 5. md5_handler = md5.new() 6. users = [{"user":"pedro","atendente":False},{ "user":"jo?o","atendente":True}] 7. #salt = random.random().to_s() 8. #md5_handler.update(salt) 9. now = datetime.datetime.now() 10. ts = now.strftime("%d-%m-%Y-%H-%M") 11. for user in users: 12. md5_handler.update(user["user"]) 13. 14. 15. seed = md5_handler.hexdigest() 16. 17. final_string = seed + "-" + ts 18. 19. method_generated_string = self.chat.generated_chat_dir_string (users,seed) 20. 21. self.assertEquals(final_string,method_generated_string) As you can see, it generates a specific set of data and assembles a final_string. It then feeds the same data to generate_chat_dir_string and compare to see if the final_string is equal to the string generated by the tested method. However, they might not be equal becouse of the temporal data. In this case I'm not using seconds, but in a bizarre situation a minute could have passed and the test would faile becouse the two strings would have a different minute portion. Something like this: "b2ef9c7b10eb0985365f913420ccb84a-30-10-2008-10-31" "b2ef9c7b10eb0985365f913420ccb84a-30-10-2008-10-32" How could I handle this issue? Thanks in advance, Marcelo. -------------- next part -------------- An HTML attachment was scrubbed... URL: From aahz at pythoncraft.com Sat May 3 15:55:04 2008 From: aahz at pythoncraft.com (Aahz) Date: 3 May 2008 12:55:04 -0700 Subject: Do you know of a much simpler way of writing a program that writes a program? References: <481B27D9.3000107@behnel.de> <286490d5-01ce-40c5-8965-9e3da4fea1c9@w74g2000hsh.googlegroups.com> Message-ID: In article <286490d5-01ce-40c5-8965-9e3da4fea1c9 at w74g2000hsh.googlegroups.com>, Jeff wrote: > >Use lisp? :-))))))) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Help a hearing-impaired person: http://rule6.info/hearing.html From gagsl-py2 at yahoo.com.ar Sat May 24 21:36:58 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 24 May 2008 22:36:58 -0300 Subject: Showing the method's class in expection's traceback References: <79c7d6fb-a6b8-481f-9a36-81b980628710@59g2000hsb.googlegroups.com> <69bi20F31j4kdU1@mid.uni-berlin.de> <483406a0$0$10773$426a74cc@news.free.fr> <6a8c7499-7d8c-4d5d-9ea6-a3e1ba2f9565@c58g2000hsc.googlegroups.com> <48353a94$0$12639$426a74cc@news.free.fr> Message-ID: En Thu, 22 May 2008 07:55:44 -0300, Duncan Booth escribi?: > Bruno Desthuilliers wrote: > >> Not to say that your concerns are pointless, and that things cannot be >> improved somehow, but this is not that trivial, and there may be >> ambuiguities in some not so rare cases. > > It might be worth considering an alternative approach here: a formatted > exception includes the relevant source lines (where possible). Just to note that the standard cgitb module already does that, among other things. -- Gabriel Genellina From mensanator at aol.com Sat May 17 01:08:56 2008 From: mensanator at aol.com (Mensanator) Date: Fri, 16 May 2008 22:08:56 -0700 (PDT) Subject: how would you...? References: <1449c36e-10ce-42f4-bded-99d53a0a2569@a1g2000hsb.googlegroups.com> Message-ID: <92880295-482a-4ae1-a746-9056ef58f2f7@l64g2000hse.googlegroups.com> On May 16, 11:43?pm, Sanoski wrote: > I'm pretty new to programming. I've just been studying a few weeks off > and on. I know a little, and I'm learning as I go. Programming is so > much fun! I really wish I would have gotten into it years ago, but > here's my question. I have a longterm project in mind, and I wont to > know if it's feasible and how difficult it will be. > > There's an XML feed for my school that some other class designed. It's > just a simple idea that lists all classes, room number, and the person > with the highest GPA. The feed is set up like this. Each one of the > following lines would also be a link to more information about the > class, etc. > > Economics, Room 216, James Faker, 3.4 > Social Studies, Room 231, Brain Fictitious, 3.5 > > etc, etc > > The student also has a picture reference that depicts his GPA based on > the number. The picture is basically just a graph. I just want to > write a program that uses the information on this feed. > > I want it to reach out to this XML feed, record each instance of the > above format along with the picture reference of the highest GPA > student, download it locally, and then be able to use that information > in various was. I figured I'll start by counting each instance. For > example, the above would be 2 instances. > > Eventually, I want it to be able to cross reference data you've > already downloaded, and be able to compare GPA's, etc. It would have a > GUI and everything too, but I am trying to keep it simple right now, > and just build onto it as I learn. > > So lets just say this. How do you grab information from the web, Depends on the web page. > in this case a feed, Haven't tried that, just a simple CGI. > and then use that in calculations? The key is some type of structure be it database records, or a list of lists or whatever. Something that you can iterate through, sort, find max element, etc. > How would you > implement such a project? The example below uses BeautifulSoup. I'm posting it not because it matches your problem, but to give you an idea of the techniques involved. > Would you save the information into a text file? Possibly, but generally no. Text files aren't very useful except as a data exchange media. > Or would you use something else? Your application lends itself to a database approach. Note in my example the database part of the code is disabled. Not every one has MS-Access on Windows. > Should I study up on SQLite? Yes. The MS-Access code I have can be easily changed to SQLlite. > Maybe I should study classes. I don't know, but I've always gotten along without them. > I'm just not sure. What would be the most effective technique? Don't know that either as I've only done it once, as follows: ## I was looking in my database of movie grosses I regulary copy ## from the Internet Movie Database and noticed I was _only_ 120 ## weeks behind in my updates. ## ## Ouch. ## ## Copying a web page, pasting into a text file, running a perl ## script to convert it into a csv file and manually importing it ## into Access isn't so bad when you only have a couple to do at ## a time. Still, it's a labor intensive process and 120 isn't ## anything to look forwards to. ## ## But I abandoned perl years ago when I took up Python, so I ## can use Python to completely automate the process now. ## ## Just have to figure out how. ## ## There's 3 main tasks: capture the web page, parse the web page ## to extract the data and insert the data into the database. ## ## But I only know how to do the last step, using the odnc tools ## from win32, ####import dbi ####import odbc import re ## so I snoop around comp.lang.python to pick up some ## hints and keywords on how to do the other two tasks. ## ## Documentation on urllib2 was a bit vague, but got the web page ## after only a ouple mis-steps. import urllib2 ## Unfortunately, HTMLParser remained beyond my grasp (is it ## my imagination or is the quality of the examples in the ## doumentation inversely proportional to the subject ## difficulty?) ## ## Luckily, my bag of hints had a reference to Beautiful Soup, ## whose web site proclaims: ## Beautiful Soup is a Python HTML/XML parser ## designed for quick turnaround projects like ## screen-scraping. ## Looks like just what I need, maybe I can figure it out after all. from BeautifulSoup import BeautifulSoup target_dates = [['4','6','2008','April']] ####con = odbc.odbc("IMDB") # connect to MS-Access database ####cursor = con.cursor() for d in target_dates: # # build url (with CGI parameters) from list of dates needing updating # the_year = d[2] the_date = '/'.join([d[0],d[1],d[2]]) print '%10s scraping IMDB:' % (the_date), the_url = ''.join([r'http://www.imdb.com/BusinessThisDay? day=',d[1],'&month=',d[3]]) req = urllib2.Request(url=the_url) f = urllib2.urlopen(req) www = f.read() # # ok, page captured. now make a BeatifulSoup object from it # soup = BeautifulSoup(www) # # that was easy, much more so than HTMLParser # # now, _all_ I have to do is figure out how to parse it # # ouch again. this is a lot harder than it looks in the # documentation. I need to get the data from cells of a # table nested inside another table and that's hard to # extrapolate from the examples showing how to find all # the comments on a web page. # # but this looks promising. if I grab all the table rows # (tr tags), each complete nested table is inside a cell # of the outer table (whose table tags are lost, but aren't # needed and whose absence makes extracting the nested # tables easier (when you do it the stupid way, but hey, # it works, so I'm sticking with it)) # tr = soup.tr # table rows tr.extract() # # now, I only want the third nested table. how do I get it? # can't seem to get past the first one, should I be using # NextSibling or something? # # but wait...I don't need the first two tables, so I can # simply extract and discard them. and since .extract() # CUTS the tables, after two extractions the table I want # IS the first one. # the_table = tr.find('table') # discard the_table.extract() the_table = tr.find('table') # discard the_table.extract() the_table = tr.find('table') # weekly gross the_table.extract() # # of course, the data doesn't start in the first row, # there's formatting, header rows, etc. looks like it starts # in tr number [3] # ## >>> the_table.contents[3].td ## How the Grinch Stole Christmas (2000) # # and since tags always imply the first one, the above # is equivalent to # ## >>> the_table.contents[3].contents[0] ## How the Grinch Stole Christmas (2000) # # and since the title is the first of three cells, the # reporting year is # ## >>> the_table.contents[3].contents[1] ## 2001 # # finally, the 3rd cell must contain the gross # ## >>> the_table.contents[3].contents[2] ## 259,674,120 # # but the contents of the first two cells are anchor tags. # to get the actual title string, I need the contents of the # contents. but that's not exactly what I want either, # I don't want a list, I need a string. and the string isn't # always in the same place in the list # # summarizing, what I need is # ## print the_table.contents[3].contents[0].contents[0].contents, ## print the_table.contents[3].contents[1].contents[1].contents, ## print the_table.contents[3].contents[2].contents # # and that almost works, just a couple more tweaks and I can # shove it into the database parsed = [] for rec in the_table.contents[3:]: the_rec_type = type(rec) # some rec are NavSrings, skip if str(the_rec_type) == "": # # ok, got a real data row # TITLE_DATE = rec.contents[0].contents[0].contents # a list inside a tuple # # and that means we still have to index the contents # of the contents of the contents of the contents by # adding [0][0] to TITLE_DATE # YEAR = rec.contents[1].contents[1].contents # ditto # # this won't go into the database, just used as a filter to grab # the records associated with the posting date and discard # the others (which should already be in the database) # GROSS = rec.contents[2].contents # just a list # # one other minor glitch, that film date is part of the title # (which is of no use in the database, so it has to be pulled out # and put in a separate field # # temp_title = re.search('(.*?)( \()([0-9]{4}.*)(\)) (.*)',str(TITLE_DATE[0][0])) temp_title = re.search('(.*?)( \()([0-9]{4}.*)(\)) (.*)',str(TITLE_DATE)) # # which works 99% of the time. unfortunately, the IMDB # consitency is somewhat dubious. the date is _supposed_ # to be at the end of the string, but sometimes it's not. # so, usually, there are only 5 groups, but you have to # allow for the fact that there may be 6 # try: the_title = temp_title.group(1) + temp_title.group(5) except: the_title = temp_title.group(1) the_gross = str(GROSS[0]) # # and for some unexplained reason, dates will occasionally # be 2001/I instead of 2001, so we want to discard the trailing # crap, if any # the_film_year = temp_title.group(3)[:4] # if str(YEAR[0][0])==the_year: if str(YEAR[0])==the_year: parsed.append([the_date,the_title,the_film_year,the_gross]) print '%3d records found ' % (len(parsed)) # # wow, now just have to insert all the update records directly # into the database...into a temporary table, of course. as I said, # IMDB consistency is somewhat dubious (such as changing the spelling # of the titles), so a QC check will be required inside Access # #### if len(parsed)>0: #### print '...inserting into database' #### for p in parsed: #### cursor.execute(""" ####INSERT INTO imdweeks2 ( Date_reported, Title, Film_Date, Gross_to_Date ) ####SELECT ?,?,?,?;""",p) #### else: #### print '...aborting, no records found' #### ####cursor.close() ####con.close() for p in parsed: print p # and just because it works, doesn't mean it's right. # but hey, you get what you pay for. I'm _sure_ if I were # to pay for a subscription to IMDBPro, I wouldn't see # these errors ;-) ##You should get this: ## ## 4/6/2008 scraping IMDB: 111 records found ##['4/6/2008', "[u'I Am Legend']", '2007', ' 256,386,216'] ##['4/6/2008', "[u'National Treasure: Book of Secrets']", '2007', ' 218,701,477'] ##['4/6/2008', "[u'Alvin and the Chipmunks']", '2007', ' 216,873,487'] ##['4/6/2008', "[u'Juno']", '2007', ' 142,545,706'] ##['4/6/2008', "[u'Horton Hears a Who!']", '2008', ' 131,076,768'] ##['4/6/2008', "[u'Bucket List, The']", '2007', ' 91,742,612'] ##['4/6/2008', "[u'10,000 BC']", '2008', ' 89,349,915'] ##['4/6/2008', "[u'Cloverfield']", '2008', ' 80,034,302'] ##['4/6/2008', "[u'Jumper']", '2008', ' 78,762,148'] ##['4/6/2008', "[u'27 Dresses']", '2008', ' 76,376,607'] ##['4/6/2008', "[u'No Country for Old Men']", '2007', ' 74,273,505'] ##['4/6/2008', "[u'Vantage Point']", '2008', ' 71,037,105'] ##['4/6/2008', "[u'Spiderwick Chronicles, The']", '2008', ' 69,872,230'] ##['4/6/2008', '[u"Fool\'s Gold"]', '2008', ' 68,636,484'] ##['4/6/2008', "[u'Hannah Montana/Miley Cyrus: Best of Both Worlds Concert Tour']", '2008', ' 65,010,561'] ##['4/6/2008', "[u'Step Up 2: The Streets']", '2008', ' 57,389,556'] ##['4/6/2008', "[u'Atonement']", '2007', ' 50,921,738'] ##['4/6/2008', "[u'21']", '2008', ' 46,770,173'] ##['4/6/2008', "[u'College Road Trip']", '2008', ' 40,918,686'] ##['4/6/2008', "[u'There Will Be Blood']", '2007', ' 40,133,435'] ##['4/6/2008', "[u'Meet the Spartans']", '2008', ' 38,185,300'] ##['4/6/2008', "[u'Meet the Browns']", '2008', ' 37,662,502'] ##['4/6/2008', "[u'Deep Sea 3D']", '2006', ' 36,141,373'] ##['4/6/2008', "[u'Semi-Pro']", '2008', ' 33,289,722'] ##['4/6/2008', "[u'Definitely, Maybe']", '2008', ' 31,973,840'] ##['4/6/2008', "[u'Eye, The']", '2008', ' 31,397,498'] ##['4/6/2008', "[u'Great Debaters, The']", '2007', ' 30,219,326'] ##['4/6/2008', "[u'Bank Job, The']", '2008', ' 26,804,821'] ##['4/6/2008', "[u'Other Boleyn Girl, The']", '2008', ' 26,051,195'] ##['4/6/2008', "[u'Drillbit Taylor']", '2008', ' 25,490,483'] ##['4/6/2008', "[u'Magnificent Desolation: Walking on the Moon 3D']", '2005', ' 23,283,158'] ##['4/6/2008', "[u'Shutter']", '2008', ' 23,138,277'] ##['4/6/2008', "[u'Never Back Down']", '2008', ' 23,080,675'] ##['4/6/2008', "[u'Mad Money']", '2008', ' 20,648,442'] ##['4/6/2008', "[u'Galapagos']", '1955', ' 17,152,405'] ##['4/6/2008', "[u'Superhero Movie']", '2008', ' 16,899,661'] ##['4/6/2008', "[u'Wild Safari 3D']", '2005', ' 16,550,933'] ##['4/6/2008', "[u'Kite Runner, The']", '2007', ' 15,790,223'] ##['4/6/2008', '[u"Nim\'s Island"]', '2008', ' 13,210,579'] ##['4/6/2008', "[u'Leatherheads']", '2008', ' 12,682,595'] ##['4/6/2008', "[u'Be Kind Rewind']", '2008', ' 11,028,439'] ##['4/6/2008', "[u'Doomsday']", '2008', ' 10,955,425'] ##['4/6/2008', "[u'Sea Monsters: A Prehistoric Adventure']", '2007', ' 10,745,308'] ##['4/6/2008', "[u'Miss Pettigrew Lives for a Day']", '2008', ' 10,534,800'] ##['4/6/2008', "[u'Môme, La']", '2007', ' 10,299,782'] ##['4/6/2008', "[u'Penelope']", '2006', ' 9,646,154'] ##['4/6/2008', "[u'Misma luna, La']", '2007', ' 8,959,462'] ##['4/6/2008', "[u'Roving Mars']", '2006', ' 8,463,161'] ##['4/6/2008', "[u'Stop-Loss']", '2008', ' 8,170,755'] ##['4/6/2008', "[u'Ruins, The']", '2008', ' 8,003,241'] ##['4/6/2008', "[u'Bella']", '2006', ' 7,776,080'] ##['4/6/2008', "[u'U2 3D']", '2007', ' 7,348,105'] ##['4/6/2008', "[u'Orfanato, El']", '2007', ' 7,159,147'] ##['4/6/2008', "[u'In Bruges']", '2008', ' 6,831,761'] ##['4/6/2008', "[u'Savages, The']", '2007', ' 6,571,599'] ##['4/6/2008', "[u'Scaphandre et le papillon, Le']", '2007', ' 5,990,075'] ##['4/6/2008', "[u'Run Fatboy Run']", '2007', ' 4,430,583'] ##['4/6/2008', "[u'Persepolis']", '2007', ' 4,200,980'] ##['4/6/2008', "[u'Charlie Bartlett']", '2007', ' 3,928,412'] ##['4/6/2008', "[u'Jodhaa Akbar']", '2008', ' 3,434,629'] ##['4/6/2008', "[u'Fälscher, Die']", '2007', ' 2,903,370'] ##['4/6/2008', "[u'Bikur Ha-Tizmoret']", '2007', ' 2,459,543'] ##['4/6/2008', "[u'Shine a Light']", '2008', ' 1,488,081'] ##['4/6/2008', "[u'Race']", '2008', ' 1,327,606'] ##['4/6/2008', "[u'Funny Games U.S.']", '2007', ' 1,274,055'] ##['4/6/2008', "[u'4 luni, 3 saptamâni si 2 zile']", '2007', ' 1,103,315'] ##['4/6/2008', "[u'Married Life']", '2007', ' 1,002,318'] ##['4/6/2008', "[u'Diary of the Dead']", '2007', ' 893,192'] ##['4/6/2008', "[u'Starting Out in the Evening']", '2007', ' 882,518'] ##['4/6/2008', "[u'Dolphins and Whales 3D: Tribes of the Ocean']", '2008', ' 854,304'] ##['4/6/2008', "[u'Sukkar banat']", '2007', ' 781,954'] ##['4/6/2008', "[u'Bonneville']", '2006', ' 471,679'] ##['4/6/2008', "[u'Flawless']", '2007', ' 390,892'] ##['4/6/2008', "[u'Paranoid Park']", '2007', ' 387,119'] ##['4/6/2008', "[u'Teeth']", '2007', ' 321,732'] ##['4/6/2008', "[u'Hammer, The']", '2007', ' 321,579'] ##['4/6/2008', "[u'Priceless']", '2008', ' 320,131'] ##['4/6/2008', "[u'Steep']", '2007', ' 259,840'] ##['4/6/2008', "[u'Honeydripper']", '2007', ' 259,192'] ##['4/6/2008', "[u'Snow Angels']", '2007', ' 255,147'] ##['4/6/2008', "[u'Taxi to the Dark Side']", '2007', ' 231,743'] ##['4/6/2008', "[u'Cheung Gong 7 hou']", '2008', ' 188,067'] ##['4/6/2008', "[u'Ne touchez pas la hache']", '2007', ' 184,513'] ##['4/6/2008', "[u'Sleepwalking']", '2008', ' 160,715'] ##['4/6/2008', "[u'Chicago 10']", '2007', ' 149,456'] ##['4/6/2008', "[u'Girls Rock!']", '2007', ' 92,636'] ##['4/6/2008', "[u'Beaufort']", '2007', ' 87,339'] ##['4/6/2008', "[u'Shelter']", '2007', ' 85,928'] ##['4/6/2008', "[u'My Blueberry Nights']", '2007', ' 74,146'] ##['4/6/2008', "[u'Témoins, Les']", '2007', ' 71,624'] ##['4/6/2008', "[u'Mépris, Le']", '1963', ' 70,761'] ##['4/6/2008', "[u'Singing Revolution, The']", '2006', ' 66,482'] ##['4/6/2008', "[u'Chop Shop']", '2007', ' 58,858'] ##['4/6/2008', '[u"Chansons d\'amour, Les"]', '2007', ' 58,577'] ##['4/6/2008', "[u'Praying with Lior']", '2007', ' 57,325'] ##['4/6/2008', "[u'Yihe yuan']", '2006', ' 57,155'] ##['4/6/2008', "[u'Casa de Alice, A']", '2007', ' 53,700'] ##['4/6/2008', "[u'Blindsight']", '2006', ' 51,256'] ##['4/6/2008', "[u'Boarding Gate']", '2007', ' 37,107'] ##['4/6/2008', "[u'Voyage du ballon rouge, Le']", '2007', ' 35,222'] ##['4/6/2008', "[u'Bill']", '2007', ' 35,201'] ##['4/6/2008', "[u'Mio fratello è figlio unico']", '2007', ' 34,138'] ##['4/6/2008', "[u'Chapter 27']", '2007', ' 32,602'] ##['4/6/2008', "[u'Meduzot']", '2007', ' 25,352'] ##['4/6/2008', "[u'Shotgun Stories']", '2007', ' 25,346'] ##['4/6/2008', "[u'Sconosciuta, La']", '2006', ' 18,569'] ##['4/6/2008', "[u'Imaginary Witness: Hollywood and the Holocaust']", '2004', ' 18,475'] ##['4/6/2008', "[u'Irina Palm']", '2007', ' 14,214'] ##['4/6/2008', "[u'Naissance des pieuvres']", '2007', ' 7,418'] ##['4/6/2008', "[u'Four Letter Word, A']", '2007', ' 6,017'] ##['4/6/2008', "[u'Tuya de hun shi']", '2006', ' 2,619'] From skanemupp at yahoo.se Sat May 31 10:01:58 2008 From: skanemupp at yahoo.se (globalrev) Date: Sat, 31 May 2008 07:01:58 -0700 (PDT) Subject: SMS sending and receiving from website? References: <6abq0uF36n019U1@mid.individual.net> <5d949166-5112-4a7a-91c3-77ccdd7ca695@j22g2000hsf.googlegroups.com> Message-ID: <2e1e103c-b436-445e-ad23-da735c0d8345@f36g2000hsa.googlegroups.com> On 31 Maj, 14:48, globalrev wrote: > On 31 Maj, 04:04, John Henderson wrote: > > > > > globalrev wrote: > > > can i send and receive messages from a website using python? > > > Absolutely. But I'm not clear what you mean by "from a > > website". Do you mean to use SMPP protocol to lodge and > > receive messages? Or do you want access to your own cellular > > hardware from a web interface? > > > > how would that work with costs? would the mobileowner pay both > > > ways? > > > That depends on the country, the carrier and the offers/plans > > that carrier makes. In most of the civilized world, SMS > > receivers pay nothing. > > > John > > i want to build a service where you can send an SMS with your > cellphone to my website and then the site will collect the data you > asked for and SMS it back. > > so what components would i need for that? also, lets say i want to send a SMS to my own phone from the internet. how would i do that? From gagsl-py2 at yahoo.com.ar Sun May 25 12:05:31 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 25 May 2008 13:05:31 -0300 Subject: which datastructure for fast sorted insert? References: Message-ID: En Sun, 25 May 2008 03:37:00 -0300, escribi?: > im writing a webcrawler. > after visiting a new site i want to store it in alphabetical order. > > so obv i want fast insert. i want to delete duplicates too. > > which datastructure is best for this? Use a list, and the bisect module to keep it sorted: py> import bisect py> def insert_nodupes(slist, item): ... i = bisect.bisect_left(slist, item) ... if i>=len(slist) or slist[i] != item: ... slist.insert(i, item) ... py> items = [] py> insert_nodupes(items, 'link to some site') py> insert_nodupes(items, 'another link') py> insert_nodupes(items, 'third site') py> insert_nodupes(items, 'another link') py> items ['another link', 'link to some site', 'third site'] -- Gabriel Genellina From arnodel at googlemail.com Fri May 2 14:23:54 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Fri, 02 May 2008 19:23:54 +0100 Subject: is +=1 thread safe References: <4819DA2D.3030508@ggmail.com> <67vs9qF2r409aU2@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch writes: > > There are no modern processors with an opcode for incrementing a memory > location!? At least my C64 can do that. ;-) Indeed! I remember a simple use was to make the border change colour very fast, a v. cool effect when you're 12! CLV LOOP: INC $D020 BVC LOOP (from memory, untested!) -- Arnaud From goldspin at gmail.com Sun May 18 15:13:34 2008 From: goldspin at gmail.com (Henry Chang) Date: Sun, 18 May 2008 12:13:34 -0700 Subject: What's the api tat I should use to connect python to a MS Access Db? In-Reply-To: <5dc598e30805181057t30dd2cdau27d7f9264b2be617@mail.gmail.com> References: <5dc598e30805181057t30dd2cdau27d7f9264b2be617@mail.gmail.com> Message-ID: A simple google search: http://bytes.com/forum/thread637384.html On Sun, May 18, 2008 at 10:57 AM, David Anderson wrote: > Please answer me the question of the subject =) > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bignose+hates-spam at benfinney.id.au Tue May 20 23:34:15 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 21 May 2008 13:34:15 +1000 Subject: Code/test ratio wrt static vs dynamic typing References: <1ad1c0c4-c1b5-46aa-b26c-0426c86522b4@a70g2000hsh.googlegroups.com> <57d73312-37b1-4c53-9669-803e84a6901f@p25g2000hsf.googlegroups.com> <263d5498-821f-4705-9e1d-cc9e97a98e07@34g2000hsf.googlegroups.com> <69hi0iF32kli9U1@mid.individual.net> Message-ID: <87bq30gwjs.fsf@benfinney.id.au> greg writes: > Also, I don't think it's valid to equate the size of the tests with > the amount of effort it took to develop them. For instance, the test > suite for Pyrex is currently larger than the Pyrex compiler, but > I've still spent far more time and effort developing the compiler > than writing the tests. Right. The unit test suite should tend to increase: add tests far more often than removing them. The application code, though, should tend to grow less rapidly: refactor duplication, remove redundant code, and add new code. This should tend to result in the unit test suite growing over time faster than the application code does, even if roughly the same effort goes into both. Thus the size of each is not a good indicator of the amount of effort. -- \ "I got a postcard from my best friend, it was a satellite | `\ picture of the entire Earth. On the back he wrote, 'Wish you | _o__) were here'." -- Steven Wright | Ben Finney From mensanator at aol.com Fri May 30 20:59:03 2008 From: mensanator at aol.com (Mensanator) Date: Fri, 30 May 2008 17:59:03 -0700 (PDT) Subject: How to covert ASCII to integer in Python? References: <5C5D68208EBBFD40A9DD9A194E957CCC2798EE@aust-mail.emsaus.com> Message-ID: <30b8b4ff-f0e5-4178-b9f7-513a5e404982@z72g2000hsb.googlegroups.com> On May 30, 6:44?pm, Joshua Kugler wrote: > Skonieczny, Chris wrote: > > YOU SHOULD REMOVE or CORRECT YOUR POST here: > >http://mail.python.org/pipermail/python-list/2007-February/427841.html > > > It is not true - eg. try : > > a='P' ? ? ? ? ? ?# P is ASCII , isn't it ? > > b=int(a) > > and what you will get ? An error !!! > > > Or probably you yourself should - quote : > > "You probably should go through the tutorial ASAP that is located here: > > >http://docs.python.org/tut/" > > int() converts a strings that is a valid intenter. ?What you're looking for > is ord(). Possibly. Perhaps the OP wants the position of 'P' in the alphabet, in which case he wants b=64-ord(a) or b=16. > > In [1]: ord('d') > Out[1]: 100 > > In [2]: a='P' > > In [3]: b=ord(a) > > In [4]: b > Out[4]: 80 > > j From sjmachin at lexicon.net Sat May 17 10:19:56 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 17 May 2008 14:19:56 GMT Subject: Distributing applications that use 3rd party modules In-Reply-To: <8728ad1c-2b4a-47db-aeda-8d2416b6bdc8@i76g2000hsf.googlegroups.com> References: <8728ad1c-2b4a-47db-aeda-8d2416b6bdc8@i76g2000hsf.googlegroups.com> Message-ID: <482ee989@news.mel.dft.com.au> eliben wrote: > Hello, > > I'm getting into Python now after years of Perl, and as part of my > research I must understand how to do some common tasks I need. > > I have a bunch of Windows PCs at work to which I want to distribute an > application I've developed on my PC. All these PCs have Python 2.5 > installed. > > If my application contains only code I've developed, I simply zip its > directory with .py files and send it to everyone, who can then use it > by running the entry-point .py file. However, what if I've installed > some 3rd party modules on my PC, and my application uses them (for > example pyparsing, PiYAML and some others) ? I don't want to manually > install all these packages (there may be dozens of them) on all those > PCs (there may be dozens of those too). What is the best method I can > use ? Naturally, I want all the non-standard packages my app uses to > be detected automatically and collected into some kind of convenient > distributable that is easy to pass around and run. > > I'm aware of py2exe - tried it and it works fine. But it creates huge > executables, and I don't want to distribute those all the time. I much > prefer a zipped directory of .py scripts that takes some 10s of KBs. What do you call "huge"? In my environment the end-users don't have Python installed on their own PCs, but the team does have a networked shared drive; we put py2exe'd applications there. Less complaints about app load time than for things like Word/Excel/Outlook, and no complaints from me about distribution, and no worries about users running old versions. Cheers, John From prudek at bvx.cz Sun May 25 03:26:23 2008 From: prudek at bvx.cz (Milos Prudek) Date: Sun, 25 May 2008 09:26:23 +0200 Subject: module import problem In-Reply-To: References: Message-ID: <200805250926.23422.prudek@bvx.cz> > Reinstall the package "python-gnupginterface" with "sudo aptitude reinstall Your advice helped! Upgrade is running now. Thanks! -- Milos Prudek From kyosohma at gmail.com Fri May 2 15:13:16 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 2 May 2008 12:13:16 -0700 (PDT) Subject: pil:effbot and pythonware offline References: <8a2150b5-dfbf-419b-af10-af88932584ff@8g2000hse.googlegroups.com> Message-ID: <84e9f4c6-4f34-4331-8815-8f69e9fde500@f63g2000hsf.googlegroups.com> On May 1, 5:15 pm, spdegabrielle wrote: > Sorry, I'm new to python and was trying to get imageTK; > this led me to try find PIL, but pythonware and effbot both seem to be > offline. > > I can't find any mention of an outage on python.org, this newsgroup, > or the planet-blogs. > > Is it just me? and does anyone know where I can find ImageTK? > > Cheers, > > stephen They both seem to be up now. Maybe there was some simultaneous server maintenance? Mike From paddy3118 at googlemail.com Thu May 15 01:47:17 2008 From: paddy3118 at googlemail.com (Paddy) Date: Wed, 14 May 2008 22:47:17 -0700 (PDT) Subject: Sanitised Newsgroup Feeds? Message-ID: Hi, Does anyone do a sanitised newsgroup feed? Something like what mail filters do for email? It is getting tedious wading through the ads for 'cracks' & watches; as well as the Xah cross-posted self-promotions, the wx-'its easier to post than read the tutorial' annoyances and the castiro (human/Eliza?) weirdnesses. I guess that many would want to add the same things to their kill file, but it takes me three clicks to add anyone/any thread to it and the c.l.p signal-to-noise is getting lower. I'd like to thank the posters of the weekly summary - it's great and I will continue to read it, but It is more fun reading and posting to Python blog-posts via a Google Reader search, than it is c.l.p Python popularity is a double-edged sword. - Paddy. From miki.tebeka at gmail.com Mon May 26 14:31:09 2008 From: miki.tebeka at gmail.com (Miki) Date: Mon, 26 May 2008 11:31:09 -0700 (PDT) Subject: Using Python to unit test C code References: Message-ID: <451913de-b548-4c42-9b72-b262663e8482@x19g2000prg.googlegroups.com> Hello, > I would like to hear any information about how to unit test C code using Python. I never done it, but you can either generate a Python wrapper (using SWIG, Boost.Python, Pyrex ...) and then test the wrapper, or directly call the C module functions using ctypes. HTH, -- Miki http://pythonwise.blogspot.com From bignose+hates-spam at benfinney.id.au Sat May 3 02:05:41 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 03 May 2008 16:05:41 +1000 Subject: #!/usr/bin/env python vs. #!/usr/bin/python References: <87abj91j8u.fsf@benfinney.id.au> Message-ID: <87r6cjylai.fsf@benfinney.id.au> Ben Finney writes: > The shebang line (the initial line of the file beginning with "#!") > takes advantage of OS kernels that determine how to execute a file > based on the first few bytes of the file. The shebang line tells the > kernel that this file should be executed by passing it as input to a > process started by another command. > > The specified command takes the form of a fully-qualified file path, > and zero or one arguments to the program. That command is then > executed by the kernel, and the Python program file is passed as > input to the resulting process. As was pointed out later in the thread, this description is partially untrue. The program isn't passed as input to the interpreter. Instead, the path to the program is appended as a command-line argument to the interpreter. Thus the kernel starts a command of the form: Examples: filename: /home/foo/bar.py shebang line: #! /usr/bin/python command line invoked: /usr/bin/python /home/foo/bar.py filename: /home/foo/Makefile shebang line: #! /usr/bin/make -f command line invoked: /usr/bin/make -f /home/foo/Makefile For more information on shebang processing, see for a basic description, and for lots of gory detail. -- \ "There's no excuse to be bored. Sad, yes. Angry, yes. | `\ Depressed, yes. Crazy, yes. But there's no excuse for boredom, | _o__) ever." -- Viggo Mortensen | Ben Finney From tarun.kap at gmail.com Fri May 2 14:23:28 2008 From: tarun.kap at gmail.com (TkNeo) Date: Fri, 2 May 2008 11:23:28 -0700 (PDT) Subject: calling variable function name ? References: <57461074-8fd1-4e65-9bc9-2ac916aa1fb5@y21g2000hsf.googlegroups.com> Message-ID: On Apr 30, 11:05 am, Arnaud Delobelle wrote: > TkNeo writes: > > > George - Thanks for your reply but what you suggested is not working: > > > def FA(param1,param2): > > print "FA" + param1 + " " + param2 > > def FA(param1,param2): > > print "FB" + param1 + " " + param2 > > def FA(param1,param2): > > print "FC" + param1 + " " + param2 > > > temp = sys.argv[1] > > > func = globals()["F" + temp] > > func("Hello", "World") > > > I ran the script with first parameter as B and i get the following > > message > > KeyError: 'FB' > > Perhaps if you call your three function FA, FB, FC instead of FA, FA, > FA it'll help? > > -- > Arnaud oh crap. I can't believe I was doing that ! :) Thanks for pointing out. works perfect. From gagsl-py2 at yahoo.com.ar Sat May 24 15:54:08 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 24 May 2008 16:54:08 -0300 Subject: Overloading __getitem__ References: Message-ID: En Thu, 22 May 2008 20:38:39 -0300, Andreas Matthias escribi?: > inhahe at gmail.com wrote: > >> actually i ddin't think about the fact that you're overloading dict, which >> can already take multiple values in getitem > > Oh, I didn't know that. I totally misinterpreted the error message. > > >> so how about >> >> class crazy: pass >> >> and then in your dict class: >> >> def __getitem__(*args): > > Apparently, args already is a tuple, so this should be: > > def __getitem__(self, args): > > Is this documented somewhere? I couldn't find it anywhere. No, that's not correct. First, there is nothing special with the arguments to dict.__getitem__ -- except that the syntax obj[index] provides a delimiter and it allows for obj[a,b] as a shortcut for obj[(a,b)] -> obj.__getitem__((a,b)) You may use the *args notation in any function; it is always a tuple (a singleton, when you call the function with only one argument) py> def foo(*args): print args ... py> foo(1) (1,) py> foo(1,2) (1, 2) py> foo((1,2)) ((1, 2),) Compare with: py> def bar(arg): print arg ... py> bar(1) 1 py> bar(1,2) Traceback (most recent call last): File "", line 1, in TypeError: bar() takes exactly 1 argument (2 given) py> bar((1,2)) (1, 2) -- Gabriel Genellina From tjreedy at udel.edu Thu May 8 20:31:30 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 8 May 2008 20:31:30 -0400 Subject: The Importance of Terminology's Quality References: <5NCdnRlmwIIt5L7VnZ2dnUVZ8sSrnZ2d@plusnet> Message-ID: "Jon Harrop" wrote in message news:5NCdnRlmwIIt5L7VnZ2dnUVZ8sSrnZ2d at plusnet... | Perhaps the best example I can think of to substantiate your original point | is simple comparison because Mathematica allows: | | a < b < c | | I wish other languages did. Python does also. From kay.schluehr at gmx.net Fri May 23 00:54:40 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Thu, 22 May 2008 21:54:40 -0700 (PDT) Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> Message-ID: <2f34b8a9-9334-44f0-bb24-6dba373d643f@z72g2000hsb.googlegroups.com> On 13 Mai, 01:39, Dave Parker wrote: > I've read that one of the design goals of Python was to create an easy- > to-use English-like language. That's also one of the design goals of > Flaming Thunder athttp://www.flamingthunder.com/ , which has proven > easy enough for even elementary school students, even though it is > designed for scientists, mathematicians and engineers. "Why on earth shall kids program and even more serious: why shall I program in a language for kids?" From mathieu.prevot at ens.fr Sat May 24 09:18:47 2008 From: mathieu.prevot at ens.fr (Mathieu Prevot) Date: Sat, 24 May 2008 15:18:47 +0200 Subject: PIPE stderr Message-ID: <3e473cc60805240618v12661458gacb174df7de81cc3@mail.gmail.com> Hi again, I don't have the same ouptput between 1) and 2) ... what's happening ? 1) wget http://www.youtube.com/v/A8bwZf3vXjg -O /dev/null 2> file 2) k = Popen (["wget", "http://www.youtube.com/v/A8bwZf3vXjg", "-O", "/dev/null"], stderr=PIPE) print k.stderr In the case 2) I got: open file '', mode 'rb' at 0x5a608> and I want what I get in file from 1) ... how to do this ? Mathieu From mail at timgolden.me.uk Wed May 7 10:19:31 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 07 May 2008 15:19:31 +0100 Subject: Scanning through Windows registry... In-Reply-To: References: <48216129.5090405@timgolden.me.uk> Message-ID: <4821BA73.7070600@timgolden.me.uk> Mike Driscoll wrote: > On May 7, 4:45 am, Tim Golden wrote: >> In a spirit of being helpful... :) [... snip registry walker ...] > This is pretty cool stuff, Tim. Of course, it would also seriously > screw up some programs if you decided to replace the wrong phrase. > Just a word of warning to the OP: be sure to make a backup of the > registry before doing something like this. Trying to fix a messed up > registry from the command line is not a fun way to spend the > afternoon. Good point, Mike. In a spirit of being even more helpful... the _winreg module includes the functions SaveKey and LoadKey so as a crude backup mechanism, you could do this: import time import _winreg import win32api import win32security # # You need to have SeBackupPrivilege enabled for this to work # priv_flags = win32security.TOKEN_ADJUST_PRIVILEGES | win32security.TOKEN_QUERY hToken = win32security.OpenProcessToken (win32api.GetCurrentProcess (), priv_flags) privilege_id = win32security.LookupPrivilegeValue (None, "SeBackupPrivilege") win32security.AdjustTokenPrivileges (hToken, 0, [(privilege_id, win32security.SE_PRIVILEGE_ENABLED)]) root = _winreg.OpenKey (_winreg.HKEY_LOCAL_MACHINE, r"Software\Python\TEST") # # This will fail if the file already exists so make it uniqueish # _winreg.SaveKey (root, "c:/temp/HKLM_Software_Python-%s.reg" % time.strftime ("%Y%m%d-%H%M%S")) Note that the file which this creates is *not* the same as a .reg file which the File > Export menu option provides from within the registry editor. (In fact, I shouldn't really have called it .reg; call it something else). It can be reloaded by the _winreg.LoadKey function -- which I notice is incorrectly named RegLoadKey in the docs after the underlying API call. The docs note that SeRestorePrivilege is required for this action, the counterpart to SeBackupPrivilege. TJG From jeffrey at fro.man Tue May 6 10:24:08 2008 From: jeffrey at fro.man (Jeffrey Froman) Date: Tue, 06 May 2008 07:24:08 -0700 Subject: Are rank noobs tolerated, here? References: <3zITj.35199$gB5.25251@fe105.usenetserver.com> Message-ID: notbob wrote: > I'm running > vers 2.5.1 on slackware 12. Nice to see another Slackware user around here! > "Here is an example of a user-defined function that has a parameter: > > > def print_twice(bruce): > print bruce, bruce > is this just an example of how the def should be written and it doesn't > really do anthing... yet? That's correct. A function doesn't generally *do* anything until it is called. Here, it is only defined. The only thing this function does when called is to print the value of bruce twice. > I define myfirstfunction in the pyth > editor and give the command print myfirstfuntion and I get back this: > Functions are objects too, and this is a printed representation of that function object. It still hasn't been "called" at this point. > ....when I add the ._doc_, it get this: > Traceback (most recent call last): > File "", line 1, in > AttributeError: 'function' object has no attribute '_doc_' > ....so, there is a no go there, too. The functions docstring is stored in the attribute named "__doc__". Like other python "special" attributes, it starts and ends with TWO underscores. > ok, I try and follow the above, but where is he getting the script? So, I > make a script called chap03.py and put it in ~/pyth/chap03/. You are correct to create this script yourself from scratch. > I then try an do the import thing above, but the pyth ed accepts none of > it. not from: > from ~/pyth/chap03/ import * > from chap03 import * #taken from ~/pyth/ > ....nor from any other configuration I can imagine, so that "from" command > makes no sense. Modules are imported from your PYTHONPATH, which is a search path similar to bash's PATH: It is a list of directories that are searched for *module* names when you attempt an import. You can examine your python path by doing: >>> import sys >>> sys.path Your module files, i.e., chap03.py, should be in one of the directories on that path. "from" modifies a *module* name, not a path component. So "from module import one_function, another_function". This allows you to use one_function without referencing it through the imported module name. In other words, these two are equivalent: >>> import chap03 >>> chap03.print_twice() and: >>> from chap03 import print_twice >>> print_twice() In the above examples, "chap03" is the *module* file, chap03.py. Hope that helps clarifies things a bit, Jeffrey From hans at poltras.com Wed May 28 13:50:05 2008 From: hans at poltras.com (Hans Larsen) Date: Wed, 28 May 2008 13:50:05 -0400 Subject: Problem with subprocess and mkstemp Message-ID: Hello, I'm having this script here: ---- import sys, tempfile, subprocess if len(sys.argv) > 1: i = 0 while i < 1000: print "Hello World" * 500 i = i + 1 exit( 1 ) h,fp = tempfile.mkstemp() print "out: " + fp out = open(fp, "r") proc = subprocess.Popen( [sys.argv[0], "1"], stdout = h ) while proc.poll() is None: o = out.read() if o: print o print out.read() print "The end" ---- This scripts work wonders on Windows (and I've heard Linux is doing well too tyvm - although if one of you could check, I don't have a linux ready), but on OSX it outputs nothing. If I change the stdout of the subprocess for a pipe, it works well. I cannot confirm that the bug comes from Python, but I'm pretty sure this should work normally. Does anyone know of this problem? Is there a workaround? A fix, maybe? We're using temporary files because a pipe hangs out with large output, such as this one. Thanks a lot, Hans Larsen -- My definition of an expert in any field is a person who knows enough about what's really going on to be scared. P. J. Plauger Computer Language, March 1983 -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Fri May 2 14:49:47 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 02 May 2008 15:49:47 -0300 Subject: i want to add a timeout to my code References: <53ffe104-be3b-43e2-b5c8-4ce5886ac60d@b1g2000hsg.googlegroups.com> <1f70ea43-7909-4bd8-b63d-2467e8a0542f@c65g2000hsa.googlegroups.com> <2976bcad-e514-4a33-bf1a-5966997b6d42@1g2000prg.googlegroups.com> Message-ID: En Thu, 01 May 2008 17:06:20 -0300, maehhheeyy escribi?: > On Apr 29, 3:29?pm, John Krukoff wrote: >> On Tue, 2008-04-29 at 14:47 -0700, maehhheeyy wrote: >> > On Apr 17, 4:24 pm, Miki wrote: >> > > On Apr 17, 1:10 pm,maehhheeyy wrote: >> >> > > > I want to add a timeout so that when I pull out my gps from my >> serial >> > > > port, it would wait for a bit then loop and then see if it's >> there. I >> > > > also want to add a print statement saying that there is no GPS >> device >> > > > found. However when I run my code and unplug my serial port, my >> code >> > > > will just hang until I plug it back in. >> > > > This is my code right now: >> >> > > > def GetGPS(): >> > > > ? ? ? data = [] >> > > > ? ? ? #Open com1: 9600,8,N,1 >> > > > ? ? ? fi = serial.Serial(0, timeout = 1) >> > > > ? ? ? print '[gps module] SERIAL PORT OPEN ON COM1:' >> >> > >http://docs.python.org/lib/node545.html >> >> > I tried the code onto my codes but what came out was that in the line >> > signal.signal(signal.SIGSLRM, handler), an attributeError appeared >> > reading that 'module' object has no attribute 'SIGALRM' >> > -- >> Are you writing your program on windows, or some other platform which is >> not unix? >> > Yeah I'm using Windows 2000. signal doesn't work on Windows. The timeout parameter to Serial should suffice... -- Gabriel Genellina From meesters at uni-mainz.de Thu May 29 09:28:20 2008 From: meesters at uni-mainz.de (Christian Meesters) Date: Thu, 29 May 2008 15:28:20 +0200 Subject: seg. fault with Py_BuildValue? Message-ID: Hi I'm having trouble with Py_BuildValue. I was able to pinpoint the following statement as the one causing a seg. fault with my script: static PyObject * funcname(PyObject *self, PyObject *args) { ... return Py_BuildValue("(OO)", x, y); } where x & y are both of type PyObject. Any suggestions here? Do I need to handle the output of Py_BuildValue somehow before returning? How? Need to decref x & y before returning? TIA Christian From wxPythoner at gmail.com Sun May 11 08:54:45 2008 From: wxPythoner at gmail.com (wxPythoner at gmail.com) Date: Sun, 11 May 2008 05:54:45 -0700 (PDT) Subject: Make Python create a tuple with one element in a clean way Message-ID: To create a tuple with one element, you need to do this: >>> my_tuple = (1,) # Note the trailing comma after the value 1 >>> type(my_tuple) But if you do this >>> my_tuple = (1) >>> type(my_tuple) you don't get a tuple. I thought that just putting a value inside ( ) would make a tuple. Apparently that is not the case. I hate ugly code so it would be clean if Python would convert anything put into ( ) to be a tuple, even if just one value was put in (without having to use that ugly looking comma with no value after it). From Joshuajruss at gmail.com Sun May 18 08:18:26 2008 From: Joshuajruss at gmail.com (Sanoski) Date: Sun, 18 May 2008 05:18:26 -0700 (PDT) Subject: secret code? Message-ID: <5bc52ed9-855e-4569-b3bd-a0c1ab6941d7@k37g2000hsf.googlegroups.com> What would you guys says about this secret code? The key was apparently lost. The guy never sent it, and he was never seen again. It must stand for letters in the alphabet, but it almost looks like trajectory tables. I don't know. What do you guys think? http://i243.photobucket.com/albums/ff273/ezname420/code.jpg From wuwei23 at gmail.com Mon May 12 22:57:01 2008 From: wuwei23 at gmail.com (alex23) Date: Mon, 12 May 2008 19:57:01 -0700 (PDT) Subject: Learning Python for no reason References: <0383f3b8$0$27282$c3e8da3@news.astraweb.com> <4ae5beb9-40c4-42d5-b22e-612297c7d014@f36g2000hsa.googlegroups.com> Message-ID: On May 13, 5:50 am, JustMe wrote: > I'm in the same boat. My work seems fixated with .Net but IMHO I think > they would be better off going with Python. Still, who am I to stand > in the way of hundreds of .Net programmers. You could always be the hero who teaches them IronPython :) - alex23 From python at bdurham.com Wed May 14 16:10:24 2008 From: python at bdurham.com (python at bdurham.com) Date: Wed, 14 May 2008 16:10:24 -0400 Subject: enumerate() values starting at 1 vs. 0 In-Reply-To: References: <1210795102.6483.1253187515@webmail.messagingengine.com> Message-ID: <1210795824.8556.1253189577@webmail.messagingengine.com> Arnaud, >> Is there any way to have enumerate() start at 1 vs. 0? >> >> The problem with starting at 0 is that many things in the real world >> begin at 1 - like line numbers or labels in a list. > I suppose you could redefine enumerate to support an optional argument: > > from itertools import izip, count > > def enumerate(iterable, start=0): > return izip(count(start), iterable) > > >>> list(enumerate('spam', 1)) > [(1, 's'), (2, 'p'), (3, 'a'), (4, 'm')] Brilliant!! Thank you, Malcolm From castironpi at gmail.com Wed May 14 11:44:18 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 14 May 2008 08:44:18 -0700 (PDT) Subject: PPyGui emulator References: <482aa2f2$0$22076$6e1ede2f@read.cnntp.org> Message-ID: <64ea7e01-9355-4cf2-ba47-2efab79f912e@i76g2000hsf.googlegroups.com> On May 14, 7:54?am, pyt... at bdurham.com wrote: > Stef, > > Looks great!! > > Malcolm Nice touch on the Spin / Slider / Progress. Wink. From paddy3118 at googlemail.com Sat May 24 18:44:27 2008 From: paddy3118 at googlemail.com (Paddy) Date: Sat, 24 May 2008 15:44:27 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <8763t3by81.fsf@benfinney.id.au> <5ea78616-e955-4ee0-8e60-a22734ec31be@79g2000hsk.googlegroups.com> Message-ID: On May 24, 3:14 pm, Fuzzyman wrote: > On May 24, 2:58 pm, Ben Finney > wrote: > > > Sh4wn writes: > > > first, python is one of my fav languages, and i'll definitely keep > > > developing with it. But, there's 1 one thing what I -really- miss: > > > data hiding. I know member vars are private when you prefix them with > > > 2 underscores, but I hate prefixing my vars, I'd rather add a keyword > > > before it. > > > From whom are you trying to hide your attributes? > > Actually, 'data hiding', although vastly overused by the static crowd > can be a reasonable thing to want. > > For example, at Resolver Systems we expose the spreadsheet object > model to our users. It hasa public, documented, API - plus a host of > undocumented internally used methods. > > We would really *much* rather hide these, because anything our > customers start using (whether documented or not) we will probably > have to continue supporting and maintaining. > > The 'we told you not to use that' approach, when applied to paying > customers doesn't really work... all they see is that you broke their > spreadsheet code by changing your API. "We told you not to use it in the API Docs" "Those names with leading undoerscores means _DO_NOT_USE_IT" "THose methods whose docstrings say DO NOT USE EXTERNALLY" And if they still use them, then they'd be problematic no matter what language was used. Customers ey? Can't live without 'em... ... Actually that's customers Sir! :-) - Paddy. From rsoh.woodhouse at googlemail.com Wed May 28 15:14:44 2008 From: rsoh.woodhouse at googlemail.com (rsoh.woodhouse at googlemail.com) Date: Wed, 28 May 2008 12:14:44 -0700 (PDT) Subject: Threads and import Message-ID: <6d04f375-9cc6-428b-aafb-d5b947d6e915@b1g2000hsg.googlegroups.com> Hi, I'm trying to work out some strange (to me) behaviour that I see when running a python script in two different ways (I've inherited some code that needs to be maintained and integrated with another lump of code). The sample script is: # Sample script, simply create a new thread and run a # regular expression match in it. import re import threading class TestThread(threading.Thread): def run(self): print('start') try: re.search('mmm', 'mmmm') except Exception, e: print e print('finish') tmpThread = TestThread() tmpThread.start() tmpThread.join() import time for i in range(10): time.sleep(0.5) print i # end of sample script Now if I run this using: $ python ThreadTest.py then it behaves as expected, ie an output like: start finish 0 1 2 ... But if I run it as follows (how the inherited code was started): $ python -c "import TestThread" then I just get: start I know how to get around the problem but could someone with more knowledge of how python works explain why this is the case? Thanks, Rowan From fiacre.patrick at gmail.com Fri May 23 03:00:55 2008 From: fiacre.patrick at gmail.com (Andrew Lee) Date: Fri, 23 May 2008 03:00:55 -0400 Subject: Write bits in file In-Reply-To: References: Message-ID: <48366bcb$0$15164$607ed4bc@cv.net> Tim Roberts wrote: > Monica Leko wrote: >> I have a specific format and I need binary representation. Does >> Python have some built-in function which will, for instance, represent >> number 15 in exactly 10 bits? > > For the record, I'd like to point out that even C cannot do this. You need > to use shifting and masking to produce a stream of 8-bit bytes, or to > extract your values from a stream of 8-bit bytes. Hmmmm, bitfields are exactly non-aligned bits in a structure and are part of ANSI C. Although C gives no guarantee of the ordering of fields within machine words ... so bitfieds are of limited use in portable programs unless they are 0-initialized. IIRC, Huffman code uses arbitrary length bit strings and is the basis of many compression algorithms. From martin at v.loewis.de Fri May 2 15:41:48 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 02 May 2008 21:41:48 +0200 Subject: IPv6 and Python In-Reply-To: <39b4d18b-2fa7-4c8f-aee5-8c3522158d1f@j22g2000hsf.googlegroups.com> References: <39b4d18b-2fa7-4c8f-aee5-8c3522158d1f@j22g2000hsf.googlegroups.com> Message-ID: <481B6E7C.2020602@v.loewis.de> > My hosting company provides me a common IPv4 address. > I'd like to set up my workstation (Windows XP or Linux Debian, doesn't > really matter) to temporarily use IPv6 for trying to add such feature > to my library (I work on both Windows XP and Linux). > Could someone point me to some resources describing how could I do > that? Information is spread widely. If you really want resources, I recommend to google for them; there are various IPv6 howtos. Here is how I would do it: On Linux, "modprobe ipv6", then "ifconfig". This should display the loopback adapter, with the address "::1". You should then be able to listen on that address, and connect to it. On Windows (XP SP2), "netsh int ipv6 install". Again, you should be able to use IPv6 loopback afterwards. If you want true connectivity to the global IPv6 internet, I recommend SixXS (http://www.sixxs.net/). You can setup a tunnel to the IPv6 net through your IPv4 POP, using a close IPv6 POP who participates in SixXS. To set up the tunnel, you then use aiccu, which works really well for me (and is packaged conveniently as a Debian package). Regards, Martin From rdm at rcblue.com Sat May 17 22:37:16 2008 From: rdm at rcblue.com (Dick Moores) Date: Sat, 17 May 2008 19:37:16 -0700 Subject: r' question Message-ID: <20080518023835.61FE61E4009@bag.python.org> An HTML attachment was scrubbed... URL: From inhahe at gmail.com Wed May 21 12:05:29 2008 From: inhahe at gmail.com (inhahe) Date: Wed, 21 May 2008 12:05:29 -0400 Subject: C-like assignment expression? References: <68b5d090-9e3b-4e7d-9dda-fc1b099822c2@m73g2000hsh.googlegroups.com> <48340412$0$10773$426a74cc@news.free.fr> <87fxsbzxn4.fsf@mulj.homelinux.net> <7df99fd4-21c9-49a1-ba65-e55794fd4c12@26g2000hsk.googlegroups.com> <06ea8b72-598e-4455-b3f9-e614ddb6ad94@p25g2000hsf.googlegroups.com> Message-ID: wrote in message news:06ea8b72-598e-4455-b3f9-e614ddb6ad94 at p25g2000hsf.googlegroups.com... > On May 21, 4:57 pm, "inhahe" wrote: >> one of the few things i miss from C is being able to use assignment in >> expressions. that's the only thing, really. >> also there's no switch/case, you have to use a dictionary of functions >> instead, although i rarely need that, usually i just use elif. > > One thing I hate from C is the assignment in expressions...Forcing > myself to write > 0 == Something > rather than > Something == 0 interesting trick, i've never thought of that/seen it although if Python implemented it I think it should default to giving warnings when you use = in an expression, that way you don't have to worry. > just to make sure I was mistakenly assigning values in statements is > annoying, it ruins the ease of reading. > > I kind of agree with the select:case, but I think a key issue is how > to implement it. Elif is reasonable for now. > > Diez, true I guess, but then we haven't seen what these expressions > are, and why there has to be three. From bruno.42.desthuilliers at websiteburo.invalid Mon May 5 10:38:58 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 05 May 2008 16:38:58 +0200 Subject: confused about self, why not a reserved word? In-Reply-To: <9c619edb-303b-439b-ad65-995fb76f70d5@y38g2000hsy.googlegroups.com> References: <972f7226-baef-4f94-a8ea-5bec99213540@34g2000hsf.googlegroups.com> <9c619edb-303b-439b-ad65-995fb76f70d5@y38g2000hsy.googlegroups.com> Message-ID: <481f1c02$0$4907$426a74cc@news.free.fr> globalrev a ?crit : > sorry i noticed now a little error, i was playing around a lot and saw > that on the sel-example i had then called foo.hello() instead of > foo.Hello(). > > > but it was an informing error now i egt it. was wondering about self > anyway so thanks for clearing it up. > > > but it still is a bit confusing that u can pass with any word. > wouldnt: > > > class Foo(object): > def Hello(): > print "hi" > > > make more sense? What would make sens in your example would be to either make hello a staticmethod, since it doesn't use any reference to the current instance nor it's class. > the class-thing seems inside out somehow in python. Python's object model is indeed a bit pecular wrt/ most mainstream OOPLs. But once you understand how it works, it happens to be mostly well designed (IMHO) and really powerful. > if im doing > foo.Hello() im already saying that im using the class foo because i > did foo=Foo() Nope. You are saying your using an instance of class Foo. > before and then still when calling Hello() i am > invisibly passing the class itself a s a parameter by default? It's not the class that get passed (unless you use a classmethod, but that's not the case here), but the instance. And you are not "invisibly" passing it, you just pass it another way. In fact, foo.hello() is equivalent to type(foo).hello(foo). > just seems backwards and weird. Each and every OOPL needs to have a way to "inject" the instance a method was called on into the method's local namespace. Python solved this it's own way - by making 'methods' thin wrappers around instance/function couples, these wrappers being in charge of calling the function with the instance as first argument. From the implementation POV, this allow to build methods on existing, more general features - functions and the descriptor protocol - instead of having to special-case them. From the programmer's POV, this allow to define functions outside classes, then dynamically add them as 'methods' either on a per-class or per-instance basis. From gagsl-py2 at yahoo.com.ar Sat May 24 19:05:12 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 24 May 2008 20:05:12 -0300 Subject: for some reason the actual tries figure is not right References: <002301c8bdcc$979ce8c0$1300a8c0@Home> Message-ID: En Sat, 24 May 2008 15:32:56 -0300, garywood escribi?: > can someone explain why the tries displays the wrong number > thanks > orginally i started off with tries = 0 but it was off by 2 How would you count that if you were playing the game "for real"? I'd say that you start (mentally) at 0 and count one more each time the other player says a word. In your code, there are *two* places where the player inputs his guess. A common idiom is to rearrange the code this way: tries = 0 ... while True: guess = raw_input("Your guess: ") tries += 1 # break out of the loop when player guesses if guess==correct: break print "Sorry..." .... print "You guessed it in", tries, "tries." ... (instead of all those if/else, try to use a dictionary to hold the "hint" corresponding to each word - you might even store several hints, as a tuple) -- Gabriel Genellina From lists at cheimes.de Wed May 7 16:47:51 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 07 May 2008 22:47:51 +0200 Subject: subprocess wait() waits forever, but os.system returns In-Reply-To: <84a23679-56e2-41b5-83eb-741a696095da@59g2000hsb.googlegroups.com> References: <84a23679-56e2-41b5-83eb-741a696095da@59g2000hsb.googlegroups.com> Message-ID: <48221577.6030408@cheimes.de> grayaii schrieb: > There are so many threads on this subject, but I ran across a > situation on Windows that I can't figure out. > > I'm trying to run this little command-line exe and when I launch like > this, it hangs: > >>>> import subprocess >>>> command = r'c:\mydir\foo.exe' >>>> run = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stdin=None, stderr=subprocess.PIPE, env=os.environ, universal_newlines=True) >>>> returncode = run.wait() ## HANGS HERE ## The code blocks because you aren't reading from stdout and stderr. Use the communicate() method instead of wait(). Christian From dmitrey.kroshko at scipy.org Fri May 9 06:46:51 2008 From: dmitrey.kroshko at scipy.org (dmitrey) Date: Fri, 9 May 2008 03:46:51 -0700 (PDT) Subject: simple question about Python list References: <7f1db30b-426f-42ca-bdd3-7264d7e095c6@24g2000hsh.googlegroups.com> Message-ID: Hmm... I thought this issue is available from Python2.5 only. I have no other interpreters in my recently installed KUBUNTU 8.04. Thanks all, D. On 9 ???, 13:41, Duncan Booth wrote: > dmitrey wrote: > > On 9 ???, 13:17, Paul Hankin wrote: > >> On May 9, 11:04?am, dmitrey wrote: > > >> > list1 = ['elem0', 'elem1', 'elem2', 'elem3', 'elem4', 'elem5'] > >> > and > >> > list2 = [0, 2, 4] # integer elements > > >> > howto (I mean most simple recipe, of course) form list3 that contains > >> > elements from list1 with indexes from list2, i.e. > > >> list3 = [list1[i] for i in list2] > > > Ok, I use Python 2.5 but I try my code to remain Python 2.4 and > > (preferable) 2.3 compatible. > > Are there other solutions? > > D. > > Did you try Paul's suggestion? > > Python 2.3.5 (#1, Oct 13 2005, 09:17:23) > [GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-52)] on linux2 > Type "help", "copyright", "credits" or "license" for more information.>>> list1 = ['elem0', 'elem1', 'elem2', 'elem3', 'elem4', 'elem5'] > >>> list2 = [0, 2, 4] > >>> list3 = [list1[i] for i in list2] > >>> list3 > > ['elem0', 'elem2', 'elem4'] From kyrie at uh.cu Thu May 15 20:05:51 2008 From: kyrie at uh.cu (Luis Zarrabeitia) Date: Thu, 15 May 2008 20:05:51 -0400 Subject: send yield In-Reply-To: <6a19b5bf-ed71-499c-a348-6e26e2f523eb@m45g2000hsb.googlegroups.com> References: <6a19b5bf-ed71-499c-a348-6e26e2f523eb@m45g2000hsb.googlegroups.com> Message-ID: <200805152005.52062.kyrie@uh.cu> On Thursday 15 May 2008 09:32:37 am castironpi wrote: > Why can't I write this? > -- > http://mail.python.org/mailman/listinfo/python-list yield recieved. Thanks. -- Luis Zarrabeitia (aka Kyrie) Fac. de Matem?tica y Computaci?n, UH. http://profesores.matcom.uh.cu/~kyrie From janzert at janzert.com Tue May 13 22:44:53 2008 From: janzert at janzert.com (Janzert) Date: Tue, 13 May 2008 22:44:53 -0400 Subject: Python and Flaming Thunder In-Reply-To: References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <5b0e3f70-afde-4480-8713-e7113b1250d7@x35g2000hsb.googlegroups.com> <1f537717-00d0-48ee-99b6-7125b96a6133@t12g2000prg.googlegroups.com> <68t4o0F2vaoncU1@mid.uni-berlin.de> <2a32179a-9439-449c-bd07-fff6a4075aee@s50g2000hsb.googlegroups.com> <7ee5dffd-df8f-46f0-bd78-c81ac0418a9a@d77g2000hsb.googlegroups.com> <65ef773e-a1c3-4adb-a18b-e8b8451efe5e@b5g2000pri.googlegroups.com> <68trmmF2vjivnU1@mid.uni-berlin.de> <192840a00805130957t71cbb00ew73f1e10cfb62edcd@mail.gmail.com> Message-ID: D'Arcy J.M. Cain wrote: > On Tue, 13 May 2008 19:57:10 +0300 > "Andrii V. Mishkovskyi" wrote: >> Not everybody has grown in English-speaking community, you know. And >> knowing math quite good, I prefer writing "x = y" instead of "Set x to >> y". > > OMG! It's COBOL. > > Wasn't there an aborted attempt at writing a language based on English > back in the sixties or seventies? I seem to recall that it failed > mainly because it turns out that programmers don't like to speak in > English, even when it is their first language, to describe computer > algorithms. If that wasn't true then pseudocode would look a lot more > like English than it does. In fact, pseudocode tends to look a lot > like Python. > I don't always agree with him but I thought Dave Thomas' recent post[1] about 'natural language like' programming languages was pretty spot on. He is specifically talking about Domain Specific Languages (DSLs) but I think it applies to general programming languages just as well. Janzert 1. http://pragdave.blogs.pragprog.com/pragdave/2008/03/the-language-in.html From Scott.Daniels at Acm.Org Mon May 5 20:44:44 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 05 May 2008 17:44:44 -0700 Subject: Nested os.path.join()'s In-Reply-To: References: Message-ID: Paul Scott wrote: > ... example: > if os.path.exists(os.path.join(basedir,picdir)) == True : > blah blah > > Question is, is there a better way of doing this? The above *works* but > it looks kinda hackish... You've had the joining addressed elsewhere, but note that: if os.path.exists(os.path.join(basedir, picdir)): blah blah is a lot better than comparing to True. --Scott David Daniels Scott.Daniels at Acm.Org From vdv100 at gmail.com Sun May 4 14:20:07 2008 From: vdv100 at gmail.com (Valerio Valerio) Date: Sun, 4 May 2008 19:20:07 +0100 Subject: Image grab in Python In-Reply-To: <18c1e6480805041109p6f2fc98agcd27c9a809fc94d@mail.gmail.com> References: <18c1e6480805040741p8c76a33q2f5464932b6524ff@mail.gmail.com> <18c1e6480805041033v1ae0a3adra3710e1414da0110@mail.gmail.com> <18c1e6480805041109p6f2fc98agcd27c9a809fc94d@mail.gmail.com> Message-ID: 2008/5/4 David : > > What I want is display a window with a image, the user select a region > of > > the image, and the region value is passed to my program, my program > slice > > the image region, and analyze it. > > > > If it's your apps own window, then getting a rectangle selected by the > user is simple. > > 1) Make skeleton x/gtk/wx/qt/etc app > 2) Add code to show an image > 3) Add code to capture mouse events > 4) Add code to show the 'rubber band' rectangle over the mouse selection > area > 5) When the user releases the mouse, then extract the part of the > rectangle between where a mouse button was clicked and where it was > released. > > All this would be in the docs for the Python x/gtk/wx/qt/etc libs. > Where is the difficulty? Right now I don't have any difficulty :) I just asked for a library to do that, if exist I don't have to write all the things from scratch (the selection part), but I am able to do my tasks easily with Xlib or Pygame. Thanks for the help. Cheers, -- Val?rio Val?rio http://www.valeriovalerio.org > > David. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bockman at virgilio.it Wed May 21 08:48:25 2008 From: bockman at virgilio.it (bockman at virgilio.it) Date: Wed, 21 May 2008 05:48:25 -0700 (PDT) Subject: about python modules References: <2fc55c56-7408-4f44-b6e2-64f85f341ac9@i36g2000prf.googlegroups.com> Message-ID: <8586a78d-5614-4700-97aa-37c867fab695@l42g2000hsc.googlegroups.com> On 21 Mag, 14:31, srinivas wrote: > hi friends i am new to python programming. > i am using Python 2.5 and IDLE as editor. > i have developed some functions in python those will be calling > frequently in my main method . > now i want to know how to import my functions folder to python in > sucha way that the functions in functions folder should work like > python library modules . > > i have ?python in folder C:\python25\.. > and functions folder D:\programs\Functions\ > > pls help me friends how to do that. You have two choices: 1. In this way you can import single modules (files) in tour folder import sys sys.path.append(r'D:\programs\Functions\') import my_module_1 import my_module_2 and then use whatever you have in the modules: my_module_1.my_function() print my_module_1.my_variable 2. If you add an empty python module called __init__.py inside the folder D:\programs\Functions\, then python will handle the folder as a package (i.e. a group of modules) and you can import them in this way: sys.path.append(r'D:\programs\') import Functions # I'm not sure this is needed ... from Functions import my_module_1, my_module_2 And then use whatever is in your modules as in case 1. If you put any code in __init__.py, this code will be executed when the import Functions statement is executed. This can be handy in some cases, e.g. if you have subfolders of Function folder and want to extend sys.path to include all them. For more details, read the section 6 of Python tutorial. HTH Ciao ------ FB From bbxx789_05ss at yahoo.com Fri May 16 15:25:34 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Fri, 16 May 2008 12:25:34 -0700 (PDT) Subject: write to specific line in file? References: Message-ID: <104ddf01-e860-4194-87bb-753a5e837ec0@s50g2000hsb.googlegroups.com> globalrev wrote: > i ahve a program that takes certain textsnippets out of one file and > inserts them into another. > > problem is it jsut overwrites the first riow every time. > > i want to insert every new piece of text into the next row. > so: > 1. how do i write to a new line every time i write to the file? > > 2. if i dont want to write to a new line but just want to insert it > after the last token in the file, how do i do then? Generally, you can't "insert" anything into a file. You can either append to the end of a file, or you can rewrite the whole file. It sounds like you probably want to read the file into an array using readlines(). Then manipulate that array however you want--appending and inserting--and when you are done, overwrite the file with your array. However, you should be aware that as soon as you open a file for writing all the data is erased, and if your program should happen to crash right then, the array containing the data will disappear into the ether and your file will be empty--in other words all your data will be gone. To prevent such an occurence, you should write your final data to another file, then delete the original file, and finally change the other file's name to the original file name. From ivan.illarionov at gmail.com Mon May 26 15:45:19 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Mon, 26 May 2008 19:45:19 +0000 (UTC) Subject: Python web development that resembles PHP or classic ASP References: <66a261d8-c31d-4519-beb9-c8913f61a87d@m44g2000hsc.googlegroups.com> Message-ID: On Mon, 26 May 2008 21:26:55 +0200, Sebastian 'lunar' Wiesner wrote: > [ Ivan Illarionov ] > >> If the OP wants PHP-style programming he will get better results with >> PHP because PHP was designed this way. Any Pythonic solution will be an >> overkill. > > Better shoot yourself in the foot with a PHP-like Python-thing, than > committing suicide by shooting yourself into the head with PHP ... :) I can't imagine anything uglier than Python with its significant whitespace wrapped inside HTML. I guess it could be more damaging than PHP which was written exactly for this purpose. From paul at floorball-flamingos.nl Fri May 2 11:40:02 2008 From: paul at floorball-flamingos.nl (Paul Melis) Date: Fri, 02 May 2008 17:40:02 +0200 Subject: Getting started with pyvtk In-Reply-To: References: Message-ID: <481b35eb$0$24406$5fc3050@news.tiscali.nl> Peter Pearson wrote: > On Thu, 01 May 2008 16:45:51 -0500, Robert Kern wrote: >> pyvtk is not the Python interface to VTK. It is for the >> creation of VTK files. The vtk(1) command is a Tcl shell >> with the VTK libraries loaded (I believe). Read the VTK >> documentation for information on the Tcl interface if you >> really want to use it. > > You're right: I don't really want to use it. > >> The Python interface is also included in the VTK sources, >> although it might not have been built on your machine. You >> have to enable it when you build VTK itself. The Python >> interface is essentially the same as the C++ >> interface. There are Python examples in the VTK source >> tree. > > That's the ticket: I don't want to "import pyvtk", I > want to "import vtk" and ape /usr/share/vtk/.../*.py. > > Thanks. I'm not sure you've been helped so far as you seem to already understand about pyvtk not being the official VTK bindings :) So, what would you like to know? Paul From grante at visi.com Mon May 12 10:46:07 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 12 May 2008 09:46:07 -0500 Subject: Is using range() in for loops really Pythonic? References: <482657ca$0$25026$607ed4bc@cv.net> <48275316$0$11629$607ed4bc@cv.net> <3042f24f-f32e-4266-8bf5-41cdb511b78d@m45g2000hsb.googlegroups.com> <873aoo6k8z.fsf@benfinney.id.au> Message-ID: On 2008-05-12, Ben Finney wrote: > Paddy writes: > >> I've used Fortran and C and so would tend to use either i,j,k as the >> unused loop variable above, or, for clarity, call it something >> descriptive like loop_count, if the loop body would be clearer. > > The problem with all of these names is that they also have long > precedent as names of values that *will* be used inside the loop. I guess people who standardize on loop_count never nest loops. :) > Because of the precedent of those names, choosing one of those > names doesn't make it clear to the reader that the value is > never used; they have no indication from you of that until > they look over the code a few times. It's implicit rather than > explicit. And when somebody adds a nested loop things fall apart. -- Grant Edwards grante Yow! BARBARA STANWYCK makes at me nervous!! visi.com From yves at zioup.com Fri May 9 10:57:11 2008 From: yves at zioup.com (Yves Dorfsman) Date: Fri, 09 May 2008 14:57:11 GMT Subject: Grabbing previous iteration in a dict In-Reply-To: <254bd762-aa57-405b-996c-3856743267f6@l17g2000pri.googlegroups.com> References: <25657e4e-45c2-4a1f-948d-26ac64a75cd7@u6g2000prc.googlegroups.com> <7xabizkdui.fsf@ruckus.brouhaha.com> <254bd762-aa57-405b-996c-3856743267f6@l17g2000pri.googlegroups.com> Message-ID: dannywebster at googlemail.com wrote: >> You cannot rely on the elements of a dictionary being in any >> particular order (dicts are internally hash tables), so the above >> is almost certainly ont what you want. > > > Hi - thanks for your reply. How about if I made the dict into a list > (of > which I have done). How would I then reference the previous item? > Can they > be indexed? Yes, I ran in a situation similar to yours, I read the content of a file, and had to both keep the order of the lines in the original file, and create a dictionary from the lines. So I created a class that contained both a dictionary and a tuple containing the keys of the dictionary in the original order. Something like this: class mydict(object): def __init__(self, filename): x = [ e.strip().split() for e in file(filename) ] self.ordered_lines = tuple([ e[0] for e in x ]) self.dictionary = dict( zip(self.ordered_lines, [ e[1:] for e in x]) ) a = mydict('/some/file') a.ordered_lines a.dictionary Yves. http://www.SollerS.ca From celoserpa at gmail.com Thu May 15 22:32:38 2008 From: celoserpa at gmail.com (Marcelo de Moraes Serpa) Date: Thu, 15 May 2008 23:32:38 -0300 Subject: Handling test data that depends on temporal data (that might change while the test runs) In-Reply-To: References: <1e5bcefd0805151021i6306946dre6e54307e91d9c1c@mail.gmail.com> <86ac1b9c0805151812i20a40908l590b342b6f1e9f52@mail.gmail.com> <1e5bcefd0805151844r2fba4141p29a0cf7d37a0a5ef@mail.gmail.com> Message-ID: <1e5bcefd0805151932ie56e5dcx999c5181ce799f27@mail.gmail.com> > > That depends on what you consider "valid". Just duplicating the function > code in the test is absurd and pointless. Yes, the code is duplicated, and now I see your point. Thanks! However, that code would always generate the same string (despite the timestamp). But that was a violation of the DRY principle. And the specs don't really care if it is a md5, only that the string is unique. New mantra: Test to the interfaces (as in program to the interfaces) :) However, I'm curious on how you would test the mathprogram.divide(x,y) function. But in this case I'm not testing the implementation. I don't care how the divide process is done, only that it is done correctly (10/2 = 5). Actually my posted example was meant to be like this: def test_divide divdend = 10 divisor = 2 expected_result = 5 #10/2 should be 5, so let's test if the method gets it right: self.assertEquals(mathprogram.divide(dividend,divisor), expected_result) I'd say they are still unit tests Yes. Now that I think of, they all really only change in **scope**. It's hard to re-wire your brain and break old habits, so, thanks for helping! Marcelo. On Thu, May 15, 2008 at 11:19 PM, Gabriel Genellina wrote: > En Thu, 15 May 2008 22:44:17 -0300, Marcelo de Moraes Serpa < > celoserpa at gmail.com> escribi?: > > @Gabriel: I understand what you are saying. It all depends on what you >> want >> to test. In this case, I wanted to test the algorithm of the method. The >> test_generate_chat_dir_string is meant to do just that: Check if the >> generate_chat_dir_string generated a "valid" (according to the specs) >> string >> for a "chat dir name". >> > > That depends on what you consider "valid". Just duplicating the function > code in the test is absurd and pointless. Of course it will pass now - > you're executing the same code! On the other hand, what if you later want to > replace the algorithm and use SHA1 instead of md5? The test will fail then - > but do you *actually* care whether it actually returns the md5 digest or > something else? > If you *do* care, then you should compute the output by hand (or assume it > is correct *now*) and hard code THAT string in the test, not recompute it > again. > If you *don't* care, then follow the steps I outlined in the previous > message: just ensure that different inputs give different outputs. > > It is not a integration nor a functional "unit" test, but it is a "real" >> unit test in the sense that I created a test for each method and I >> exercised >> the methods the following way: >> >> 1) Got some data to test and... >> 2) ... Generated an output "manually" in the test method that I knew were >> the expected return of the tested method; >> 3) Fed this data to the tested method and compared the manually generated >> result with the return value of the method. >> >> It is like testing a method that does a simple division: >> >> def test_divide >> divdend = 10 >> divisor = 2 >> expected_result = 5 >> self.assertEquals(mathprogram.divide(dividend,divisor),5) >> > > Mmm, no, your posted example was more like this: > > def test_divide > divdend = 10 > divisor = 2 > expected_result = dividend/divisor > self.assertEquals(mathprogram.divide(dividend,divisor), 5) > > You *computed* the expected result using (presumably) the same code as the > tested function. > > The techniques you explained in your message sound more like functional >> testing or integration + functional testing where multiple aspects of a >> single functional unit are being exercised. Or am I wrong? >> > > I'd say they are still unit tests. I'm testing a single function, comparing > the expected output with the actual output. But I only check the *public* > interfase of the function, what their users expect from it (its contract, if > you want); I don't check the internal implementation. > The real value of unit tests comes when you want to modify something, or > reimplement it. You must ensure that you don't break other things. With a > too strict test very tied to the current implementation, you can't change > anything. > > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From znfmail-pythonlang at yahoo.com Mon May 19 10:18:00 2008 From: znfmail-pythonlang at yahoo.com (Poppy) Date: Mon, 19 May 2008 10:18:00 -0400 Subject: addendum Re: working with images (PIL ?) References: Message-ID: Thanks, since posting I figured out how to interpret the histogram results, which seems to be the consensus in responses. I wrote a check image program and have been periodically calling it against a folder where I make a copy of our images used for production. My method right now is to check what we send for errors, but is not preventive. Also I determined whitespace is not the only issue, any color that dominates. I'm considering rewriting this code below to setup bins, so if combined neighboring colors exceeds the threshold then reject the image. I have examples where half the image appears black, but actually varies throughout. Since my image is RGB I'm looping through a 768 element list. Zach- import Image, os def check_image(file): try: im = Image.open(file) except: return "Can't open file %s " % file imData = im.histogram() i = 0 for ea in imData: if ea > ((im.size[0] * im.size[1]) / 4): ## 25% of image size return "bad image %s - %s element num is %s " % (file, ea, str(i)) i = i + 1 return "good image %s, image size is %s" % (file, im.size) def main(dir): data = "" try: files = os.listdir(dir) for ea in files: data = data + str(check_image(os.path.join(dir,ea))) + "\n" except: return "Can't get files in %s" % dir return data print main("\\\\host\\path\\to\\image_folder\\") "Ken Starks" wrote in message news:g0o0h3$jd4$1$8300dec7 at news.demon.co.uk... > As others have said, PIL has the 'histogram' method to do most of the > work. However, as histogram works on each band separately, you have > a bit of preliminary programming first to combine them. > > The ImageChops darker method is one easy-to-understand way (done twice), > but there are lots of alternatives, I am sure. > > > # ------------------------------------ > > import Image > import ImageChops > > Im = Image.open("\\\\server\\vol\\temp\\image.jpg") > R,G,B = Im.split() > > Result=ImageChops.darker(R,G) > Result=ImageChops.darker(Result,B) > > WhiteArea=Result.histogram()[0] > TotalArea=Im.size[0] * Im.size[1] > PercentageWhite = (WhiteArea * 100.0)/TotalArea > > > > > > Poppy wrote: >> I've put together some code to demonstrate what my goal is though looping >> pixel by pixel it's rather slow. >> >> import Image >> >> def check_whitespace(): >> im = Image.open("\\\\server\\vol\\temp\\image.jpg") >> >> size = im.size >> >> i = 0 >> whitePixCount = 0 >> while i in range(size[1]): >> j = 0 >> while j in range(size[0]): >> p1 = im.getpixel((j,i)) >> if p1 == (255, 255, 255): >> whitePixCount = whitePixCount + 1 >> if whitePixCount >= 492804: ## ((image dimensions 1404 x >> 1404) / 4) 25% >> return "image no good" >> j = j + 1 >> i = i + 1 >> >> print whitePixCount >> >> return "image is good" >> >> print check_whitespace() >> >> >> "Poppy" wrote in message news:... >>> I need to write a program to examine images (JPG) and determine how much >>> area is whitespace. We need to throw a returned image out if too much of >>> it is whitespace from the dataset we're working with. I've been >>> examining the Python Image Library and can not determine if it offers >>> the needed functionality. Does anyone have suggestions of other image >>> libraries I should be looking at it, or if PIL can do what I need? >>> >> From castironpi at gmail.com Fri May 16 11:27:21 2008 From: castironpi at gmail.com (castironpi) Date: Fri, 16 May 2008 08:27:21 -0700 (PDT) Subject: Instance of class "object" References: <9dec1377-270f-46d6-bac8-f003e32f9bec@m36g2000hse.googlegroups.com> Message-ID: On May 16, 10:21 am, castironpi wrote: > On May 16, 9:41 am, castironpi wrote: > > > > > > > On May 16, 8:56 am, castironpi wrote: > > > > On May 16, 8:51 am, castironpi wrote: > > > > > On May 16, 4:26 am, Peter Otten <__pete... at web.de> wrote: > > > > > > ?? wrote: > > > > > > I wonder why below does not work. > > > > > > > a = object() > > > > > > a.b = 1 # dynamic bind attribute failed... > > > > > > The implementation of slots depends on that behaviour: > > > > > >http://docs.python.org/ref/slots.html > > > > > > > Does this strange behavior break the LSP (Liskov substitution principle)? > > > > > > Can you expand on that? > > > > > > Peter > > > > > Spirals are important. > > > > I'd be modeling streams, in par. crossing them.- Hide quoted text - > > > > - Show quoted text - > > > Python 3.0a5 (py3k:62932M, May 9 2008 > > win32 > > Type "help", "copyright", "credits" or>>> import parser > > >>> import compiler > > > Traceback (most recent call last): > > File "", line 1, in > > ImportError: No module named compiler > > > Does anyone want to model mic-based soundwaves? My recent project has > > been color progression over time, and talking about compilers.- Hide quoted text - > > > - Show quoted text - > > Can 'compiler' come back in? I want to build a compiler + exec.- Hide quoted text - > > - Show quoted text - I am also talking about Mac. I have this one: def click( self, *_ ): self.degrees+= 180 Looking entirely unapproachable. Bartender? From barisc at bckm.org Tue May 27 05:03:11 2008 From: barisc at bckm.org (Baris-C) Date: Tue, 27 May 2008 02:03:11 -0700 (PDT) Subject: graphical ide?? References: Message-ID: <1d3e7b3c-1767-4c26-ba4c-cba86189f8c7@k30g2000hse.googlegroups.com> On May 27, 2:32?am, Marc Pelletier wrote: > Hello, > > I am just getting started in Python with the intention of tweaking an > opensource wxPython project called Brewsta. I've been reading python > documentation and the code, and its starting to make sense, but there seems > to be an awful lot of boilerplate required to make such an application > work. > > Are there any ides that help out? There seem to be lots of options, and > I've been downloading like crazy, but nothing so far that stands out. Are > there any tips or tutorials specific to doing gui development? > > cheers > > Marc Pelletier i use eric on kde 3.5.9 From deets at nospam.web.de Wed May 14 10:19:45 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 14 May 2008 16:19:45 +0200 Subject: Class Methods Vs Any Other Callable References: <98b4a67c-9ec7-407c-8c80-06488bd48a68@e39g2000hsf.googlegroups.com> Message-ID: <690ap7F2u0ftdU1@mid.uni-berlin.de> > An instance method works on the instance > A Static method is basically a function nested within a class object > A class method is overkill? If anything, a static method is overkill. See it this way: *if* you for some reason put a method into an enclosing context - isn't it worth having a reference to that? > I can call a static or class method through either the class OR any > instance of it. I've never designed a method that took advantage of > the class name except in cases where I needed to extend a super class > *but* even in this case, I didn't use the enclosing class name... > > Whats the deal with class methods, why use them over anything else? > What does a class method accomplish in at least one line shorter than > anything else? Does it help reduce duplication or typing? I am at a > lost for words that can shed at least *one* good reason to use them. > > What is the one greatest reason to use them? A little syntax and > explanation can go a long long way. I am failing to understand them so > any help is really appreciated here! There is not one greatest reason. They have their uses as e.g. factory-methods for instances of the class. Or as e.g. registering functions for notifications amongst instances of the class. In which case writing class Foo: @classmethod def register(cls, listener): cls.LISTENERS.append(listener) is much more robust because you could rename Foo the way you like - register won't be affected. Diez From bruno.42.desthuilliers at websiteburo.invalid Fri May 9 04:32:00 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 09 May 2008 10:32:00 +0200 Subject: "prove" In-Reply-To: References: Message-ID: <48240c00$0$7184$426a74cc@news.free.fr> Lucas Prado Melo a ?crit : > Hello, > How could I "prove" to someone that python accepts this syntax using > the documentation (I couldn't find it anywhere): > classname.functionname(objectname) Why do you need the documentation ? Just fire up your python shell and hack a Q&D example: Python 2.5.1 (r251:54863, May 2 2007, 16:56:35) [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> class Foo(object): ... def bar(self): ... print "in %s bar" % self ... >>> f = Foo() >>> Foo.bar(f) in <__main__.Foo object at 0xb7dccd2c> bar >>> f.bar() in <__main__.Foo object at 0xb7dccd2c> bar >>> From howachen at gmail.com Sun May 25 14:13:07 2008 From: howachen at gmail.com (howa) Date: Sun, 25 May 2008 11:13:07 -0700 (PDT) Subject: Beginner question Message-ID: Hi, Just want to try mod_python but it is more complicated then I expected... I just followed the tutorial on: http://www.modpython.org/live/mod_python-2.7.8/doc-html/inst-testing.html E.g. URL = http://www.example.com/mptest.py It return ImportError: No module named mptest 1. If I removed addHandler mod_python .py and PythonHandler mptest, I can see the SOURCE CODE 2. The PythonHandler mod_python.testhandler seems return correct result, showing I am using python 2.4.3 any idea? Thanks. From castironpi at gmail.com Tue May 13 06:33:58 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 13 May 2008 03:33:58 -0700 (PDT) Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <2b66a86e-5a05-4262-b3c9-4703b0ae3372@d1g2000hsg.googlegroups.com> <5b0e3f70-afde-4480-8713-e7113b1250d7@x35g2000hsb.googlegroups.com> <1f537717-00d0-48ee-99b6-7125b96a6133@t12g2000prg.googlegroups.com> <68t4o0F2vaoncU1@mid.uni-berlin.de> Message-ID: On May 13, 4:52?am, castiro... at gmail.com wrote: > On May 13, 4:18?am, "Diez B. Roggisch" wrote: > > > > > > > Dave Parker wrote: > > > On May 12, 7:20?pm, castiro... at gmail.com wrote: > > >>Yes, I am trying to visualize something. > > > > If it is related to making furniture comfortable for humans, have you > > > considered painting the furniture with thermochromic paint ( > > >http://en.wikipedia.org/wiki/Thermochromism)??It changes color in > > > response to temperature, which in part is determined by how hard a > > > body is pressed against it because close contact tends to trap heat. > > > An evenly distributed color might indicated evenly distributed > > > pressure. > > > Don't let yourself be irritated by castironpi - he's the virtual equivalent > > of a mumbling mad man in this group. Ignorance serves best as remedy - and > > I only see his postings being > > quoted... a huge relief!) > > > Diez > > I hate to ignore work. ?Who is the non-virtual equivalent mumble?- Hide quoted text - However, that's just the sunrise I would be talking about. How are the soft drinks here? Does anyone else have a t.v.? I don't like mine or have one. From zerge69 at gmail.com Tue May 20 23:52:31 2008 From: zerge69 at gmail.com (zerge69 at gmail.com) Date: Tue, 20 May 2008 20:52:31 -0700 (PDT) Subject: Newbie In Python References: <316da0ad-403d-492c-81b1-4aa069da0caa@k10g2000prm.googlegroups.com> Message-ID: <597c5935-6647-4276-81f0-b30693d93ba2@k10g2000prm.googlegroups.com> On May 20, 5:15 am, andrew.smith.... at gmail.com wrote: > I have Heard About "Python" its a OOD Language. i have to Learn it > where from i should start it. > i have python compiler at linux Platform. > anyone can suggest me about it. > > Thanks In advance. I recommend Pyscripter http://code.google.com/p/pyscripter/ It includes all the Python documentation and tutorial From amat at kabsi.at Thu May 22 17:51:26 2008 From: amat at kabsi.at (Andreas Matthias) Date: Thu, 22 May 2008 23:51:26 +0200 Subject: Overloading __getitem__ Message-ID: The following code doesn't run but I hope you get what I am trying to do. class my_dict (dict): def __getitem__ (self, key, crazy = False): if crazy == True: return 5 * self.get(key) else: return self.get(key) foo = my_dict() foo['a'] = 123 print foo['a'] print foo['a', crazy = True] Is it somehow possible to overload __getitem__ with an additional argument? Are there other possibilities to achiev this? Or is the only solution to this to write a normal function call `def my_get (self, key, crazy=False)'? Ciao Andreas From banibrata.dutta at gmail.com Mon May 12 02:52:59 2008 From: banibrata.dutta at gmail.com (Banibrata Dutta) Date: Mon, 12 May 2008 12:22:59 +0530 Subject: Is there no single/uniform RDBMS access API module for Python ? In-Reply-To: <3de8e1f70805112345u672d8ec0ia1aaa10a55e1b048@mail.gmail.com> References: <3de8e1f70805112243u765fc507v32c5461be34d4077@mail.gmail.com> <4827E6B9.3080509@shopzeus.com> <3de8e1f70805112345u672d8ec0ia1aaa10a55e1b048@mail.gmail.com> Message-ID: <3de8e1f70805112352j341a3cd2o34d0964499e86271@mail.gmail.com> Found that SnakeSQL does implement DB2.0 API. However are there such implementations for MySQL ? On 5/12/08, Banibrata Dutta wrote: > > > On 5/12/08, Laszlo Nagy wrote: >> >> Banibrata Dutta ?rta: >> >>> Hi, >>> Again a noob question. >>> Based on this URL http://wiki.python.org/moin/DatabaseInterfaces , is >>> it correct to conclude that there is no RDBMS agnostic, single/uniform DB >>> access API for Python ? >>> Something in the lines of JDBC for Java, DBD for Perl etc. ? >>> How is the RDBMS change handled for solutions which need to work with >>> different RDBMSs ?? >>> >> http://www.python.org/dev/peps/pep-0249/ >> > > > That appears to be only an API specification. Are there any implementations > of that ? > > -- > regards, > Banibrata > http://www.linkedin.com/in/bdutta > http://octapod.wordpress.com > -- regards, Banibrata http://www.linkedin.com/in/bdutta http://octapod.wordpress.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From wgumgfy at gmail.com Fri May 9 01:38:44 2008 From: wgumgfy at gmail.com (Waylen Gumbal) Date: Thu, 8 May 2008 22:38:44 -0700 Subject: The Importance of Terminology's Quality References: Message-ID: <68i6b5F2soauaU1@mid.individual.net> Sherman Pendley wrote: > kodifik at eurogaran.com writes: > > > > > PLEASE DO NOT | :.:\:\:/:/:.: > > > FEED THE TROLLS | :=.' - - '.=: > > > > I don't think Xah is trolling here (contrary to his/her habit) > > but posing an interesting matter of discussion. > > It might be interesting in the abstract, but any such discussion, when > cross-posted to multiple language groups on usenet, will inevitably > devolve into a flamewar as proponents of the various languages argue > about which language better expresses the ideas being talked about. > It's like a law of usenet or something. > > If Xah wanted an interesting discussion, he could have posted this to > one language-neutral group such as comp.programming. He doesn't want > that - he wants the multi-group flamefest. Not everyone follows language-neutral groups (such as comp,programming as you pointed out), so you actually reach more people by cross posting. This is what I don't understand - everyone seems to assume that by cross posting, one intends on start a "flamefest", when in fact most such "flamefests" are started by those who cannot bring themselves to skipping over the topic that they so dislike. -- wg From dReEeMpOeVsEtT1H at IgSmail.com Thu May 29 09:53:51 2008 From: dReEeMpOeVsEtT1H at IgSmail.com (deepest1) Date: Thu, 29 May 2008 15:53:51 +0200 Subject: boost Message-ID: Hi everybody. I'm trying to use boost, but just don't know how to set it up. My os is winXP (installed on disk D). Python is installed in D:\Python25 MigGW compiler is installed in D:\MinGW (i downloaded it because djgpp is making much more errors with bjam) I have downloaded boost_1_35_0.zip and boost-jam-3.1.16-1-ntx86.zip, extracted boost_1_35_0.zip to D:\Program Files (so I have now D:\Program Files\boost_1_35_0), extracted there bjam and used bjam in cmd: bjam --build-dir="D:\Program Files\boost_1_35_0" --toolset=gcc stage I got 12 failures and 8 warnings from this (other few hundrds were ok) I'm now trying to compile World.cpp and use it from python World.cpp: -------------------------- #include "boost/python.hpp" using namespace boost::python; BOOST_PYTHON_MODULE(hello) { class_("World") .def("greet", &World::greet) .def("set", &World::set) ; } struct World { void set(std::string msg) { this->msg = msg; } std::string greet() { return msg; } std::string msg; }; -------------------------- When trying to compile it I get: ---------------------------- E:\Source>g++ World.cpp World.cpp:1:28: boost/python.hpp: No such file or directory World.cpp:2: error: `boost' has not been declared World.cpp:2: error: `python' is not a namespace-name World.cpp:2: error: expected namespace-name before ';' token World.cpp:4: error: expected constructor, destructor, or type conversion before '(' token World.cpp:15: error: `std::string' has not been declared World.cpp:15: error: ISO C++ forbids declaration of `msg' with no type World.cpp:16: error: using-declaration for non-member at class scope World.cpp:16: error: expected `;' before "greet" World.cpp:17: error: expected `;' before "std" World.cpp:17: error: using-declaration for non-member at class scope World.cpp:17: error: expected `;' before "msg" World.cpp: In member function `void World::set(int)': World.cpp:15: error: 'struct World' has no member named 'msg' ---------------------------- What have i done wrong and what should have been done instead? Thank you in advance. :) From kccnospam at glenevin.com Mon May 19 14:56:52 2008 From: kccnospam at glenevin.com (seanacais) Date: Mon, 19 May 2008 11:56:52 -0700 (PDT) Subject: Using StringVars in List of Dictionaries as tkInter variables for Scale and Label widgets References: Message-ID: <12f77d06-3311-4986-8d77-489dfe8172db@w8g2000prd.googlegroups.com> On May 19, 2:11 pm, Peter Otten <__pete... at web.de> wrote: > > There's some magic going on behind the scene which means that you have to > create a Tkinter.Tk instance before you can start churning out StringVars: > > >>> import Tkinter as tk > >>> v = tk.StringVar() > > Traceback (most recent call last): > File "", line 1, in > File "/usr/lib/python2.5/lib-tk/Tkinter.py", line 257, in __init__ > Variable.__init__(self, master, value, name) > File "/usr/lib/python2.5/lib-tk/Tkinter.py", line 188, in __init__ > self._tk = master.tk > AttributeError: 'NoneType' object has no attribute 'tk'>>> root = tk.Tk() > >>> v = tk.StringVar() > >>> v.set(42) > >>> v.get() > > '42' > > Peter I had the Tkinter import as from Tkinter import * but I changed it to import Tkinter as tk and modified the creation of the root object to root=tk.Tk() I then had to change every instance of Menu, Label, Button, and all Tkinter elements to be prefaced by tk. (so Button became tk.Button). That kind of makes sense to me. However even after specifying StringVar is a tk type def initOPValues(self, OPname, dname): OPDefaults = { 'Vval' : 0, 'Ival' : 0, 'Otemp' : 0 } dname = dict((d,tk.StringVar()) for d in OPDefaults) for d in OPDefaults: dname[d].set(OPDefaults[d]) I still get a very similar error message C:\Code\gui>tkinter.py Traceback (most recent call last): File "C:\Code\gui\tkinter.py", line 169, in ps.initOPValues(c, OPValues[c]) File "C:\Code\gui\tkinter.py", line 54, in initOPValues dname = dict((d,tk.StringVar()) for d in OPDefaults) File "C:\Code\gui\tkinter.py", line 54, in dname = dict((d,tk.StringVar()) for d in OPDefaults) File "C:\Python25\lib\lib-tk\Tkinter.py", line 254, in __init__ Variable.__init__(self, master, value, name) File "C:\Python25\lib\lib-tk\Tkinter.py", line 185, in __init__ self._tk = master.tk AttributeError: 'NoneType' object has no attribute 'tk' Exception exceptions.AttributeError: "StringVar instance has no attribute '_tk'" in > ignored Thanks! Kevin From hdante at gmail.com Thu May 22 00:36:15 2008 From: hdante at gmail.com (Henrique Dante de Almeida) Date: Wed, 21 May 2008 21:36:15 -0700 (PDT) Subject: Bug in floating-point addition: is anyone else seeing this? References: <0a9620e9-40f4-4d11-9ddf-9e0f424547b3@x35g2000hsb.googlegroups.com> Message-ID: On May 22, 1:26?am, Henrique Dante de Almeida wrote: > On May 21, 3:38?pm, Mark Dickinson wrote: > > >>> a = 1e16-2. > > >>> a > > 9999999999999998.0 > > >>> a+0.999 ? ? # gives expected result > > 9999999999999998.0 > > >>> a+0.9999 ? # doesn't round correctly. > > > 10000000000000000.0 > > ?Notice that 1e16-1 doesn't exist in IEEE double precision: > ?1e16-2 == 0x1.1c37937e07fffp+53 > ?1e16 == 0x1.1c37937e08p+53 > > ?(that is, the hex representation ends with "7fff", then goes to > "8000"). > > ?So, it's just rounding. It could go up, to 1e16, or down, to 1e16-2. > This is not a bug, it's a feature. I didn't answer your question. :-/ Adding a small number to 1e16-2 should be rounded to nearest (1e16-2) by default. So that's strange. The following code compiled with gcc 4.2 (without optimization) gives the same result: #include int main (void) { double a; while(1) { scanf("%lg", &a); printf("%a\n", a); printf("%a\n", a + 0.999); printf("%a\n", a + 0.9999); } } From fred.sells at adventistcare.org Tue May 20 09:46:16 2008 From: fred.sells at adventistcare.org (Sells, Fred) Date: Tue, 20 May 2008 09:46:16 -0400 Subject: do you fail at FizzBuzz? simple prog test In-Reply-To: Message-ID: <0A53725C4A497848A7B3A0874B259831011B090C@acesxch01.ADVENTISTCORP.NET> or for i in range(1,100): print ('fizz','','')[i%3] + ('buzz','','','','')[i%5] or i > > > > "Write a program that prints the numbers from 1 to 100. But for > > multiples of three print "Fizz" instead of the number and for the > > multiples of five print "Buzz". For numbers which are multiples of > > both three and five print "FizzBuzz". > > > > for i in range(1,101): > > if i%3 == 0 and i%5 != 0: > > print "Fizz" > > elif i%5 == 0 and i%3 != 0: > > print "Buzz" > > elif i%5 == 0 and i%3 == 0: > > print "FizzBuzz" > > else: > > print i > > > > > > is there a better way than my solution? is mine ok? > > From mccredie at gmail.com Thu May 29 17:54:50 2008 From: mccredie at gmail.com (Matimus) Date: Thu, 29 May 2008 14:54:50 -0700 (PDT) Subject: make a string a list References: Message-ID: <2837626a-0f01-456e-9d8f-cc98097d963e@d45g2000hsc.googlegroups.com> On May 29, 2:30 pm, Nikhil wrote: > or a string iterable ? How can I do that. I have lots of '\r\n' > characters in the string which I think can be easier if it were made > into a list and I can easily see if the required value (its a numeral) > is present in it or not after some position or after some characters' > position. > > Thanks, > Nikhil I a little confused by what you are trying to do, but: Strings are iterable. >>> for c in "hello": ... print "look, a letter", c ... look, a letter h look, a letter e look, a letter l look, a letter l look, a letter o And indexable: >>> "hello"[0] 'h' And converting to a list is done like this: >>> list("hello") ['h', 'e', 'l', 'l', 'o'] They also have some pretty nifty methods: >>> "hello\r\nworld\r\nlets\r\nsplit\r\n".split("\r\n") ['hello', 'world', 'lets', 'split', ''] >>> "hello world".index('world') 6 >>> "hello world".index('l') 2 >>> "hello world".index('l', 2+1) 3 >>> "hello world".index('l', 3+1) 9 >>> "hello world".index('l', 9+1) Traceback (most recent call last): File "", line 1, in ValueError: substring not found Hopefully some of that helps. Matt From daveparker at flamingthunder.com Wed May 28 11:09:42 2008 From: daveparker at flamingthunder.com (Dave Parker) Date: Wed, 28 May 2008 08:09:42 -0700 (PDT) Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <20080514215943.14c92f16.johnjsal@NOSPAMgmail.com> <94bac166-d13c-44dd-af84-db19e19488b8@w1g2000prd.googlegroups.com> <8cfd3523-8d16-40bc-b904-94a6a36a414d@p25g2000pri.googlegroups.com> <5c98049e-e62e-4ab1-afed-b0a3e186bd05@w1g2000prd.googlegroups.com> Message-ID: <3dd6fa95-e9fe-4922-a46d-020cf9263469@w4g2000prd.googlegroups.com> > > If catch(set x to y+z.) < 0.1 then go to tinyanswer. > > So what does this do exactly if the set throws an error? I think the catch should catch the error thrown by set, compare it to 0.1, the comparison will not return true because the error is not less than 0.1, and so the go-to to tinyanswer will not be taken. > Is the error > message printed at the top level going to be telling you about the failed > addition or the failed comparison? I don't think there will be an error message at the top in the case above, because I don't think the comparison should fail -- the comparision will return that it is not true that the error is less than 0.1. > Why do you need the catch anyway, if a > statement is just an expression why can't you just put the statement into > parentheses? Statements return values, but statements are not just expressions. Statements are more about control-flow and side-effects; expressions are more about returning values. Putting a statement into parentheses in a context where expressions are also allowed in parentheses is (or can be) both lexically and visually ambiguous. That's why C had to resort to the confusing "=" vs "==" notation -- to disambiguate the two cases. The "catch" keyword unambiguously alerts the reader that the parenthesis contain a statement (or a whole list of statements). > For that matter, is there any way to distinguish between different errors > and only catch particular ones? I think the catch function should catch all of the errors (and the non- error result if no error occured), so I think distinguishing the error would have to come after. Maybe something like: Set result to catch(read x from "input.txt".). If result = dividebyzeroerror then ... else throw result. I'm open to alternate suggestions, though. > You have a great opportunity to avoid making some of the same mistakes that > Python is trying to get out of. I'm sure that I'll make my own new and different errors. :) However, I really appreciate your comments because maybe I'll make fewer errors. Or at least, correct them faster. On May 28, 7:52?am, Duncan Booth wrote: > Dave Parker wrote: > > Catch also gives you a > > single, uniform, syntactically unambiguous way to embed statements (or > > whole statement lists) into expressions -- without causing the > > syntactic problems of = statements in if statements or the obfuscation > > of question mark notation, etc. ?For example: > > > If catch(set x to y+z.) < 0.1 then go to tinyanswer. > > So what does this do exactly if the set throws an error? Is the error > message printed at the top level going to be telling you about the failed > addition or the failed comparison? Why do you need the catch anyway, if a > statement is just an expression why can't you just put the statement into > parentheses? > > For that matter, is there any way to distinguish between different errors > and only catch particular ones? A bare except clause in Python is usually a > signal of bad code: when handling errors you only want the errors you have > anticipated, and want to be sure that any unexpected errors don't get > caught. > > You have a great opportunity to avoid making some of the same mistakes that > Python is trying to get out of. For example as of Python 2.5 > KeyboardInterrupt and SystemExit to longer inherit from Exception. That > means a bare except in Python no longer catches either of those: if you > want to handle either of these exceptions you have to be explicit about it. > > -- > Duncan Boothhttp://kupuguy.blogspot.com From patrickstinson.lists at gmail.com Thu May 22 20:09:17 2008 From: patrickstinson.lists at gmail.com (Patrick Stinson) Date: Thu, 22 May 2008 16:09:17 -0800 Subject: statically linking release build on mac In-Reply-To: <6214d7a20805221113ld148f65nefab1cf62437d889@mail.gmail.com> References: <6214d7a20805221113ld148f65nefab1cf62437d889@mail.gmail.com> Message-ID: <6214d7a20805221709o330b2505mceac97d7267dab73@mail.gmail.com> Here is the error: code 4, error number 0 (Symbol not found: _Py_DebugFlag Referenced from: /Library/Application Support/Digidesign/Plug-Ins/Play.dpm/Contents/MacOS/Play Expected in: /System/Library/Frameworks/AudioUnit.framework/Versions/A/AudioUnit ) On Thu, May 22, 2008 at 10:13 AM, Patrick Stinson < patrickstinson.lists at gmail.com> wrote: > I get an error reporting an unfound symbol using a statically linked > release build of python2.5 on a OSX-Tiger. This works fine on leopard, where > the system default python is version 2.5.1 - the same version that I'm using > to link to. > > Sorry, I'm currently screwing with my configs and don't have a build to run > (my bad :) anymore, but the error is basically this: > > Undefined symbol: _PY_DebugFlag > Referenced From: > Expected in: > > I moved the system python frameworks out of the frameworks path for the > build and run just to make sure that they weren't somehow getting in the > way. I found that that symbol is defined in pydebug.h for both release and > debug builds. Also, I discovered that I can fix the problem with some of my > targets (I have both standalone exe and plugin lib versions of my app code) > by referencing the variable directly like this: int mine = Py_DebugFlag, > which fixes that symbol but then the next symbol in pydebug (PY_VerboseFlag) > is reported as undefined. After some playing with it, I found that the > following code will fix the problem in a basic standalone app: > > int _________mine; > void *__________p = NULL; > _________mine = Py_DebugFlag; > _________mine = Py_VerboseFlag; > _________mine = Py_InteractiveFlag; > _________mine = Py_OptimizeFlag; > _________mine = Py_NoSiteFlag; > _________mine = Py_UseClassExceptionsFlag; > _________mine = Py_FrozenFlag; > _________mine = Py_TabcheckFlag; > _________mine = Py_UnicodeFlag; > _________mine = Py_IgnoreEnvironmentFlag; > _________mine = Py_DivisionWarningFlag; > _________mine = _Py_QnewFlag; > __________p = (void *) _PyOS_ReadlineTState; > __________p = (void *) PyOS_ReadlineFunctionPointer; > > > Woah, don't I feel like the lib is jerking me around a little? Anyway, this > works if I put it in main() for a standalone target, in a semi-random class > constructor for the AudioUnit target, and I still can't find the right place > to put it for the RTAS ( > http://www.digidesign.com/index.cfm?query=developers%20plugin_info%20rtas.cfm&langid=1) > target. It's a little weird that I'm getting this at runtime and not at > link-time since I'm linking statically. > > This is the standalone main() that works, but fails if I remove the above > code: > > #include > > int main(int, char **) > { > int mine = -1; > void *p = NULL; > > mine = Py_DebugFlag; > mine = Py_VerboseFlag; > mine = Py_InteractiveFlag; > mine = Py_OptimizeFlag; > mine = Py_NoSiteFlag; > mine = Py_UseClassExceptionsFlag; > mine = Py_FrozenFlag; > mine = Py_TabcheckFlag; > mine = Py_UnicodeFlag; > mine = Py_IgnoreEnvironmentFlag; > mine = Py_DivisionWarningFlag; > mine = _Py_QnewFlag; > p = (void *) _PyOS_ReadlineTState; > p = (void *) PyOS_ReadlineFunctionPointer; > > Py_Initialize(); > > Py_Finalize(); > } > > > It seems to me like this might have something to do with setting up a > symbol lookup table correctly or something, I don't know. I'm not having any > problems with debug builds. This is the relevant part of my config.status. > > ac_cs_version="\ > > python config.status > 2.5 > > configured by ./configure, generated by GNU Autoconf > 2.59, > > with options \"'--enable-universalsdk' '--disable-shared'\" > > > Help? *whimper*.. Cheers. > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From upton at virginia.edu Mon May 19 14:31:43 2008 From: upton at virginia.edu (Dan Upton) Date: Mon, 19 May 2008 14:31:43 -0400 Subject: How do *you* use Python in non-GUI work? In-Reply-To: <20080518182022.990193bd.johnjsal@NOSPAMgmail.com> References: <20080518182022.990193bd.johnjsal@NOSPAMgmail.com> Message-ID: <5504f9ac0805191131x2d17e11dn36a97d33582caa78@mail.gmail.com> On Sun, May 18, 2008 at 6:20 PM, John Salerno wrote: > Hey all. Just thought I'd ask a general question for my own interest. Every time I think of something I might do in Python, it usually involves creating a GUI interface, so I was wondering what kind of work you all do with Python that does *not* involve any GUI work. This could be any little scripts you write for your own benefit, or what you do at work, if you feel like talking about that! :) > > Thanks. > -- > http://mail.python.org/mailman/listinfo/python-list > I write a lot of job control and process monitoring scripts in Linux. Stuff that forks and execs processes, and then monitors procfs and sysfs to collect periodic data. I actually wouldn't mind doing a GUI for it, but pretty much all of the data display I need from it I can do by taking the data files and running them through gnuplot. (That, and I'm too lazy to figure out how to rewrite my telemetry plotter from Java to Python.) I guess I also write some data conversion programs, mostly the sort of thing where I have a bunch of data that I didn't think far enough in advance how I needed to be able to display it, so I just write something to convert it to where I need it. Incidentally, I used to do that all in Java too, until other people in my research group started making fun of me for it and also for not really knowing a scripting language. From inhahe at gmail.com Thu May 22 14:01:04 2008 From: inhahe at gmail.com (inhahe) Date: Thu, 22 May 2008 14:01:04 -0400 Subject: Returning to 'try' block after catching an exception References: <485f7ddc-8f50-4483-b591-151f1ae560be@k10g2000prm.googlegroups.com> Message-ID: <%viZj.78717$%15.59308@bignews7.bellsouth.net> Might have a stack overflow issue, if it retries too many times? "alex23" wrote in message news:b3680690-73c3-47cb-8693-54a207daafcd at x1g2000prh.googlegroups.com... > On May 22, 6:15 pm, Karlo Lozovina <_karlo_ at _mosor.net_> wrote: >> Because when you expect exception to occur on something like 0.01% of >> cases, and you have 4 or 5 exceptions and the code to test for each >> conditions that cause exceptions is quite long and burried deep inside >> some other code it's much better to do it this way ;). Too bad there's no >> syntactic sugar for doing this kind of try-except loop. > > I'm surprised your unit tests let it get to such a state... ;) > > How about something like this? > > retry, total_fail = False, False > try: > some_function() > except SomeException: > some_function2() > some_function3() > retry = True > finally: > if retry: > try: > some_function() > except SomeException: > total_fail = True > > Using 'finally' seems more explicit about it being part of the > exception handling than using a loop construct. > > Actually, this is even more direct: > > try: > some_function() > except SomeException: > some_function2() > some_function3() > try: > some_function() > except SomeException: > raise SomeError From 1jamgold at gmail.com Mon May 26 15:13:33 2008 From: 1jamgold at gmail.com (JAMGold) Date: Mon, 26 May 2008 12:13:33 -0700 (PDT) Subject: COMPUTER GEEKS AND $UCCE$$ Message-ID: <95eb87bd-b9b3-4e81-b8ed-d8e6f593f7ae@p25g2000pri.googlegroups.com> Let's face it: We love computers, we love to be creative, we love to show off our talents to as many people as will watch, and we love to make money doing it. So why don't more of us excel at the money-making? I know you have looked at the sales page of an internet marketing site and just shaken your head and said to yourself, "I can do better than that!" Perhaps you've come across a couple of good ones - real cornea poppers - that make you wonder "How'd they DO that? Do I have the software and know-how to make stuff like that?" You didn't care what they were selling; you just drooled at the creative possibilities! So, again, why don't more of us excel at money-making? What if I could show you a way to do what you love doing - creating websites, writing innovative code, developing databases, et al - and make more money than your boss? Maybe more than your CEO? (Microsoft employees, ignore that last! Bill's gonna make more than you... sorry.) What I want to do is revolutionize your perception of a much-maligned and hated profession - internet marketing! It's the perfect hand-in-glove fit for us computer geeks! We get to play with automation, with graphics, with programming and web design... All the elements that combine to draw us into the computer world are integral parts of a profession that could make you thousands and thousands of dollars a WEEK! The hard part is getting started. Don't be fooled into thinking that I'm offering you a get-rich-quick scheme. It's a profession. I'm suggesting you invest the time and effort it WILL take to learn a new angle on what you already know how to do. But still, I'm offering you a program that will transform your life - it's THE ideal way to develop and showcase your skills and abilities! The training is live and interactive on the web. The owners and top executives of this company are "in the trenches" with you and are available to help you via live chat rooms, personal phone calls (that's right - you can call the CEO and talk to him on his personal phone! You MS guys, can you do that?) You'll be led by the hand step by step to a kind of financial freedom your current J.O.B. (Just Over Broke) will NEVER provide for you. I want you to take a look at two sites: http://shmyl.com/staqson http://shmyl.com/nebqson As you look at these sites and watch the videos, think about the edge you have on everyone else that's looking into this business. You already know a lot of the principles that make internet marketers successful! You just need to learn how to apply them, and WE WILL SHOW YOU HOW! Seriously, you'll be glad you looked into this. Best regards and I'll see you at the top! Wayne Hamrick 800 708-0069 Wayne at solutionsRus.ws From timr at probo.com Wed May 28 03:36:40 2008 From: timr at probo.com (Tim Roberts) Date: Wed, 28 May 2008 07:36:40 GMT Subject: SocketServer, its offspring, and threads References: Message-ID: eliben wrote: > >I ended up using an ugly hack to make it work for me. Since >handle_request() only blocks until a request is received, the thread >can be unblocked by sending it a real message. So to stop a server, I >opened a XML-RPC client connection (using ServerProxy from xmlrpclib) >and made a request. In the server thread, handle_process() returned >and the thread could see the flag requesting it to stop. > >There must be a better way ! Any ideas ? Well, maybe it is a matter of personal preference, but I don't see anything wrong with this approach. If a thread is blocked waiting for a command, what's wrong with sending it a "please commit suicide" command? -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From Joshuajruss at gmail.com Fri May 30 09:11:31 2008 From: Joshuajruss at gmail.com (Sanoski) Date: Fri, 30 May 2008 06:11:31 -0700 (PDT) Subject: Python 2.5.2 on Ubuntu Hardy Utf-8-Euro error References: Message-ID: <0b040810-4764-4cb8-8a74-6e9b40829dc7@34g2000hsh.googlegroups.com> On May 30, 8:24?am, Josep wrote: > I'm playing with an application framework (or kinda) that's developed > with python, and it throws this error: > > > File "/usr/lib/python2.5/site-packages/Dabo-0.8.3-py2.5.egg/dabo/db/dCursorMixin.py", line 281, in execute > > ? ? sql = unicode(sql, self.Encoding) > > LookupError: unknown encoding: utf_8_euro > > At the application (DABO) mailing list, they have pointed that this has > to be a Python issue. As I'm a totally python newbie, I would ask if > somebody has experimented this kind of error, and if there is any known > solution. I've found no clue searching at Google right now. I've had nothing but problems ever since I upgraded to Hardy. I used to be a die hard Ubuntu fan until recently. Maybe try a better OS > > My Python version is 2.5.2, Ubuntu Hardy .deb package. > > Thanks in advance for your help. > > -- > > Josep S?nchez > [papapep] > ----------------------------------http://extralinux.net > ---------------------------------- > > ?signature.asc > 1KDownload From jonbutler88 at googlemail.com Thu May 22 04:22:35 2008 From: jonbutler88 at googlemail.com (jonbutler88 at googlemail.com) Date: Thu, 22 May 2008 01:22:35 -0700 (PDT) Subject: HTMLParser error References: <628d3bbf-0fd9-4075-9749-6c8c81f887fa@z72g2000hsb.googlegroups.com> <1aecdaeb-76f1-4a57-88d3-2023dd6e00e4@e39g2000hsf.googlegroups.com> <06ba6753-712e-4c1c-8d2f-c1fd075ed0cf@u6g2000prc.googlegroups.com> <10f12f0c-d08e-41e1-ab6f-10488ae51010@p25g2000pri.googlegroups.com> <42323d1c-9a10-4030-8870-75ed2d10a31e@b64g2000hsa.googlegroups.com> Message-ID: On May 22, 2:40?am, alex23 wrote: > On May 22, 8:18 am, jonbutle... at googlemail.com wrote: > > > Sorry, im new to both python and newsgroups, this is all pretty > > confusing. So I need a line in my __init__ function of my class? The > > spider class I made inherits from HTMLParser. Its just using the > > feed() function that produces errors though, the rest seems to work > > fine. > > Let me repeat: it would make this a lot easier if you would paste > actual code. > > As you say, your Spider class inherits from HTMLParser, so you need to > make sure that you set it up correctly so that the HTMLParser > functionality you've inherited will work correctly (or work as you > want it to work). If you've added your own __init__ to Spider, then > the __init__ on HTMLParser is no longer called unless you *explicitly* > call it yourself. > > Unfortunately, my earlier advice wasn't totally correct... HTMLParser > is an old-style object, whereas super() only works for new-style > objects, I believe. (If you don't know about old- v new-style objects, > seehttp://docs.python.org/ref/node33.html). So there are a couple of > approaches that should work for you: > > ? ? class SpiderBroken(HTMLParser): > ? ? ? ? def __init__(self): > ? ? ? ? ? ? pass # don't do any ancestral setup > > ? ? class SpiderOldStyle(HTMLParser): > ? ? ? ? def __init__(self): > ? ? ? ? ? ? HTMLParser.__init__(self) > > ? ? class SpiderNewStyle(HTMLParser, object): > ? ? ? ? def __init__(self): > ? ? ? ? ? ? super(SpiderNewStyle, self).__init__() > > Python 2.5.1 (r251:54863, May ?1 2007, 17:47:05) [MSC v.1310 32 bit > (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information.>>> html = open('temp.html','r').read() > >>> from spider import * > >>> sb = SpiderBroken() > >>> sb.feed(html) > > Traceback (most recent call last): > ? File "", line 1, in > ? File "C:\Python25\lib\HTMLParser.py", line 107, in feed > ? ? self.rawdata = self.rawdata + data > AttributeError: SpiderBroken instance has no attribute 'rawdata' > > >>> so = SpiderOldStyle() > >>> so.feed(html) > >>> sn = SpiderNewStyle() > >>> sn.feed(html) > > The old-style version is probably easiest, so putting this line in > your __init__ should fix your issue: > > ? ? HTMLParser.__init__(self) > > If this still isn't clear, please let me know. > > - alex23 OK, heres what I have so far: #!/usr/bin/env python from HTMLParser import HTMLParser from urllib2 import urlopen, HTTPError class Spider(HTMLParser): def __init__(self): HTMLParser.__init__(self) self.found = [] self.queue = [] def handle_starttag(self, tag, attrs): try: if tag == 'a': if attrs[0][0] == 'href': self.queue.append(attrs[0][1]) except HTMLParseError: print 'Error parsing HTML tags' def parse(self, page): try: self.feed(urlopen('http://' + page).read()) except HTTPError: print 'Error getting page source' def crawl(self, site): self.queue.append(site) while 1: try: url = self.queue.pop(0) self.parse(url) except IndexError: break self.found.append(url) return self.found if __name__ == '__main__': s = Spider() site = raw_input("What site would you like to scan? http://") s.crawl(site) Still getting very odd errors though, this being the latest: Traceback (most recent call last): File "spider.py", line 38, in s.crawl(site) File "spider.py", line 30, in crawl self.parse(url) File "spider.py", line 21, in parse self.feed(urlopen('http://' + page).read()) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/urllib2.py", line 124, in urlopen return _opener.open(url, data) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/urllib2.py", line 381, in open response = self._open(req, data) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/urllib2.py", line 399, in _open '_open', req) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/urllib2.py", line 360, in _call_chain result = func(*args) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/urllib2.py", line 1107, in http_open return self.do_open(httplib.HTTPConnection, req) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/urllib2.py", line 1064, in do_open h = http_class(host) # will parse host:port File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/httplib.py", line 639, in __init__ self._set_hostport(host, port) File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/httplib.py", line 651, in _set_hostport raise InvalidURL("nonnumeric port: '%s'" % host[i+1:]) httplib.InvalidURL: nonnumeric port: '' Also could you explain why I needed to add that HTMLParser.__init__(self) line? Does it matter that I have overwritten the __init__ function of spider? Thanks From deets at nospam.web.de Thu May 8 08:16:03 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 08 May 2008 14:16:03 +0200 Subject: Idea for P3K References: <4821d418$0$932$ba4acef3@news.orange.fr> <4821fea4$0$880$ba4acef3@news.orange.fr> Message-ID: <68g992F2sjmdqU1@mid.uni-berlin.de> M?ta-MCI (MVP) wrote: > Hi! > >> I don't often feel like using this word > > Look at languages like OCAML or F # The point being? Yes, shockingly enough other languages have other syntax & semantics. Diez From python at bdurham.com Sat May 3 18:27:10 2008 From: python at bdurham.com (python at bdurham.com) Date: Sat, 03 May 2008 18:27:10 -0400 Subject: Preventing 'bad' filenames from raising errors in os.path In-Reply-To: <481c9223$0$34540$742ec2ed@news.sonic.net> References: <481c9223$0$34540$742ec2ed@news.sonic.net> Message-ID: <1209853630.17819.1251260483@webmail.messagingengine.com> Matimus and John, Thank you both for your feedback. Matimus: I agree with your analysis. I blame lack of caffeine for my original post :) Regards, Malcolm From notnorwegian at yahoo.se Thu May 22 19:10:21 2008 From: notnorwegian at yahoo.se (notnorwegian at yahoo.se) Date: Thu, 22 May 2008 16:10:21 -0700 (PDT) Subject: serach file for regexp, return if found? Message-ID: <348e4ed3-201c-43b6-ae27-0b921861a461@m36g2000hse.googlegroups.com> i want to search a document for a particular regexp and then store that regexp to a file. but search and match only returns matchobjects(what are those anyway? i dont get what to do with them, do they contain true/false, stringposition etc?) how do i do: for rows in file: print regexp.find ## or something equiavlent From bignose+hates-spam at benfinney.id.au Thu May 1 21:31:15 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 02 May 2008 11:31:15 +1000 Subject: TypeError: unsupported operand type(s) for /: 'NoneType' and 'NoneType' References: Message-ID: <87fxt11ogs.fsf@benfinney.id.au> "Jordan Harry" writes: > I'm trying to write a simple program to calculate permutations. I > created a file called "mod.py" and put the following in it: > > def factorial(n): > a = n > b = n > while a>0 and b>1: > n = (n)*(b-1) > b = b-1 A function that does some calculations internally, but has no 'return' statement and thus implicitly returns 'None'. > def perm(n, r): > a = factorial(n) > b = factorial(n-r) These statements bind the 'None' returned by the 'factorial' function to the names 'a' and 'b'. > q = a / b This attempts to use the '/' operator on 'None' with 'None', which raises the exception you saw. (good sigmonster, have a cookie) -- \ "Pinky, are you pondering what I'm pondering?" "I think so, | `\ Brain, but Zero Mostel times anything will still give you Zero | _o__) Mostel." -- _Pinky and The Brain_ | Ben Finney From hniksic at xemacs.org Fri May 2 04:24:48 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 02 May 2008 10:24:48 +0200 Subject: is +=1 thread safe References: <4819DA2D.3030508@ggmail.com> <7xbq3pjhav.fsf@ruckus.brouhaha.com> Message-ID: <87bq3pglkf.fsf@mulj.homelinux.net> Paul Rubin writes: > AlFire writes: >> But I still can not believe that +=1 is not a thread safe operation. > > In CPython I believe it is thread safe, because of the global > interpreter lock. Thread switches can happen only between bytecode > executions, not in the middle of a bytecode, even though executing a > bytecode can take several machine instructions. It's safe when writing extensions in C (because of the GIL), but not when writing Python code. Python switches threads after a number of bytecode instructions, so Python code behaves somewhat like C multithreaded code on a single CPU -- although there is no true parallelism, you still have context switches at arbitrary places to worry about, and still need locks because of them. Since the += operator is not compiled into a single bytecode instruction, it needs the lock. x+=1 gets compiled into the following bytecode: 3 0 LOAD_GLOBAL 0 (x) 3 LOAD_CONST 1 (1) 6 INPLACE_ADD 7 STORE_GLOBAL 0 (x) If two threads execute that code simultaneously, a thread switch could easily occur some time between LOAD_GLOBAL and STORE_GLOBAL, causing the variable to be incremented by 1 instead of by 2. From skanemupp at yahoo.se Wed May 7 17:47:36 2008 From: skanemupp at yahoo.se (globalrev) Date: Wed, 7 May 2008 14:47:36 -0700 (PDT) Subject: explain this function to me, lambda confusion References: Message-ID: <81addfb5-254f-4a2b-a2bc-044592cee07f@p25g2000hsf.googlegroups.com> and what si the diffrence here: g = lambda x=5:x*x g = lambda x:x*x the first was a mistake to write but it worked and the x=5 seems to be completely ignored. why? it has no effect at all? From stevegill7 at gmail.com Sun May 4 00:33:45 2008 From: stevegill7 at gmail.com (Jetus) Date: Sat, 3 May 2008 21:33:45 -0700 (PDT) Subject: saving a webpage's links to the hard disk Message-ID: <9a4733b4-5320-4a66-b0ce-5dcebc02d9a7@y38g2000hsy.googlegroups.com> Is there a good place to look to see where I can find some code that will help me to save webpage's links to the local drive, after I have used urllib2 to retrieve the page? Many times I have to view these pages when I do not have access to the internet. From istvan.albert at gmail.com Thu May 1 08:46:51 2008 From: istvan.albert at gmail.com (Istvan Albert) Date: Thu, 1 May 2008 05:46:51 -0700 (PDT) Subject: ]ANN[ Vellum 0.16: Lots Of Documentation and Watching References: Message-ID: On Apr 29, 3:51 am, "Zed A. Shaw" wrote: > You can grab the most recent draft of the book at: > > http://zedshaw.com/projects/vellum/manual-final.pdf > However, I'm curious to get other people's thoughts. IMO if you would refrain from using swear words in the manual it would help broadening its reach and acceptance. i. From martin at v.loewis.de Sat May 10 06:21:02 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 10 May 2008 12:21:02 +0200 Subject: Pythonicity of some algorithms In-Reply-To: References: Message-ID: <4825770e$0$25961$9b622d9e@news.freenet.de> > This works for me. But I'd like to know if this is considered > Pythonic, and if there are other, better ways of doing the above in > Python. >From the Python point of view, it's fine. However, it uses busy-wait, which I consider bad style (in any language). > 3) Make a custom thread-safe queue class, with an 'interrupt_get' > method. When your app calls queue.interrupt_get(), all threads > currently locking on a queue.get() will continue, but with a > GetInterrupted exception thrown. That's what I would do. I'd use the existing Queue class as a base class, though, rather than starting from scratch. Regards, Martin From johnjsal at NOSPAMgmail.com Tue May 27 14:08:14 2008 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 27 May 2008 14:08:14 -0400 Subject: Hungarian Notation References: <74d9c37f-807c-4aae-8ad5-db79bb3e2bd2@8g2000hse.googlegroups.com> Message-ID: <483c4f26$0$7278$c3e8da3@news.astraweb.com> "Paul McGuire" wrote in message news:74d9c37f-807c-4aae-8ad5-db79bb3e2bd2 at 8g2000hse.googlegroups.com... On May 27, 12:28 am, "inhahe" wrote: My own knee-jerk reaction was "Hungarian Notation Bad!" and googling about for "python hungarian notation" led me through some like-minded sites. But I also found this entry on Joel Spolky's site (http:// www.joelonsoftware.com/printerFriendly/articles/Wrong.html), that warns against tarring all Hungarian-type notations with the same brush. Wow, that was fascinating. I had no idea Hungarian notation originally didn't mean to prefix the object type! From eckhardt at satorlaser.com Tue May 20 04:54:08 2008 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Tue, 20 May 2008 10:54:08 +0200 Subject: conventions/requirements for 'is' vs '==', 'not vs '!=', etc References: <4dc24f2e-04f5-4ad6-b021-f416ef5c7415@z72g2000hsb.googlegroups.com> <8ebd28f1-887f-45c9-a35f-af9023b062ea@u12g2000prd.googlegroups.com> Message-ID: Asun Friere wrote: > Well you have to be careful in case some smartarse comes back with a > class with something like this in it: > > def __eq__ (self, other) : > if self is other : return False That's pretty paranoid. :) Who said that? (: Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From afilash+python at gmail.com Fri May 30 12:50:15 2008 From: afilash+python at gmail.com (abhilash pp) Date: Fri, 30 May 2008 22:20:15 +0530 Subject: how can i stop script from running on login ? In-Reply-To: References: <9f9d35df0805300544x7a8f3af3t2808445edc55de3f@mail.gmail.com> Message-ID: <9f9d35df0805300950o5fc9767id9ba6400ac5f6a08@mail.gmail.com> thanks Benjamin, i have to try it out On Fri, May 30, 2008 at 6:31 PM, Benjamin Kaplan wrote: > > > On Fri, May 30, 2008 at 8:44 AM, abhilash pp > > wrote: > >> Hi all, >> >> One of my friends played some tricky thing, and now I am in great trouble, >> please help >> Here is the scenario [windows xp ]: >> >> He wrote one login script and put it on the start program folder under >> 'All Users' >> The script is like this it will issue a log off command when we login; due >> to this I am not able to login to my system even he himself not able to >> access the system and solve the problem. The main thing is the script is of >> '.pyw' type so I can't able to close the CMD window to stop this script >> >> How can I remove that script? Any help will be appreciated, thanks in >> advance >> >> Abhilash >> >> > Try running the machine in safe mode, then delete the script. > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From torriem at gmail.com Thu May 1 13:10:57 2008 From: torriem at gmail.com (Michael Torrie) Date: Thu, 01 May 2008 11:10:57 -0600 Subject: Stream I/O to a java applet (os.popen?) In-Reply-To: References: Message-ID: <4819F9A1.1020109@gmail.com> Cody Woolaver wrote: > This is all done at the terminal though and i need to have it done through a python file. I'm aware that i will have to use os.popen but am unfamiliar with how it works. You'll probably want to look at the subprocess module, which replaces the old os.popen stuff. It's also a bit better at running on Windows. There are lots of docs and examples relating to subprocess. Probably some good recipes too, especially for running on windows. I'd begin by looking on google for "python subprocess example windows." Bear in mind interactive control of a subprocess is sometimes fraught with difficulty, as it's easy to deadlock if you're waiting for the subprocess to say something and it's waiting for you to say something. On another track, you might want to consider using Jython, as it will allow your python class file to interact directly with the Java stuff, rather than having to do it via pipes and subprocesses. The only downside to Jython currently is it's stuck at Python 2.2 stuff. But it's a nice integration of Java and Python. From arnodel at googlemail.com Fri May 16 11:42:17 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Fri, 16 May 2008 16:42:17 +0100 Subject: Making Variable Text Output More Pythonic? References: <015e35b2-165c-4693-bf6c-38ad0cce7553@t12g2000prg.googlegroups.com> <781ccceb-2474-484f-b6c8-f4b59b2396b5@27g2000hsf.googlegroups.com> Message-ID: afrobeard writes: > Arnaud's code wont work if self.opt1 is None, an empty list, an empty > tuple, False, etc, because all these evaluate to false. They wont > print the internal state of these variables. [Just an informational > notice, this may be the behavior you expect] ??? My suggestion is to get rid of attributes altogether and does not test any truth values. > Secondly, I'm not sure if you know the variable names from before hand > in which case Casey's approach will work, or you need to know them via > introspection. http://www.ibm.com/developerworks/library/l-pyint.html > [Scroll down to attributes]. > > On May 16, 1:44?am, Arnaud Delobelle wrote: >> Casey writes: >> > Hi, >> >> > I have some classes that print variable outputs depending on their >> > internal state, like so: >> >> > def __str__(self): >> > ? ? out = [] >> > ? ? if self.opt1: out += ['option 1 is %s' % self.opt1'] >> > ? ? if self.opt2: out += ['option 2 is %s' % self.opt2'] >> > ? ? .... >> > ? ? return '\n'.join(out) >> >> > Is there any way to make this cleaner? >> >> Maybe. >> >> Have a dictionary of options rather than individual attributes; >> options not in the dictionary are not set. E.g. >> >> mask = { >> ? ? 'opt1': 'option 1 is %s', >> ? ? 'opt2': 'option 2 is %s', >> ? ? ... >> ? ? } >> >> def __str__(self): >> ? ? return '\n'.join(mask[o] % v for o,v in self.options.iteritems()) >> >> -- >> Arnaud From deets at nospam.web.de Mon May 5 08:37:23 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 05 May 2008 14:37:23 +0200 Subject: confused about self, why not a reserved word? References: <972f7226-baef-4f94-a8ea-5bec99213540@34g2000hsf.googlegroups.com> Message-ID: <688dctF2rnddhU1@mid.uni-berlin.de> globalrev wrote: > class Foo(object): > def Hello(self): > print "hi" > > object is purple, ie some sort of reserved word. It is not. > why is self in black(ie a normal word) when it has special powers. > replacing it with sel for example will cause an error when calling > Hello. That must be some other problem. This is perfectly legal python code and works: class Foo(object): def bar(imafancyobject): print imafancyobject f = Foo() f.bar() Diez From gagsl-py2 at yahoo.com.ar Mon May 26 20:34:51 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 26 May 2008 21:34:51 -0300 Subject: graphical ide?? References: Message-ID: En Mon, 26 May 2008 20:32:58 -0300, Marc Pelletier escribi?: > I am just getting started in Python with the intention of tweaking an > opensource wxPython project called Brewsta. I've been reading python > documentation and the code, and its starting to make sense, but there > seems > to be an awful lot of boilerplate required to make such an application > work. That's strange - usually you don't require "an awful lot of boilerplate" in Python. > Are there any ides that help out? There seem to be lots of options, and > I've been downloading like crazy, but nothing so far that stands out. Are > there any tips or tutorials specific to doing gui development? I'm unsure if you're looking for a development environment like these: http://wiki.python.org/moin/IntegratedDevelopmentEnvironments or an interface designer for wxPython (see the bottom part of http://wiki.python.org/moin/GuiProgramming) -- Gabriel Genellina From pavlovevidence at gmail.com Fri May 23 15:24:41 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 23 May 2008 12:24:41 -0700 (PDT) Subject: Decorator metaclass References: <219a475b-c6e3-4128-98bc-d73fd215ce67@w7g2000hsa.googlegroups.com> <3372d0a4-84c3-44ae-abf6-f431cb5b1164@8g2000hse.googlegroups.com> Message-ID: <3ab520b0-fd25-4026-9749-12bf06bfa6ab@p25g2000hsf.googlegroups.com> On May 23, 11:42 am, Thomas Karolski wrote: > > You will note that Decorator does not define __init__. In fact, > > object.__init__ will be called, which does nothing. If you think that > > all classes with DecoratorType as their metaclass will be a direct > > subclass of Decorator, you can get away with not calling > > Decorator.__init__ at all. > > Now, inside my new version, I have a class which inherits from both > Decorator and Window, out of which the __init__ for Decorator is not > called. Does this prove to be a problem? It sounds like it could create infinite recursion. If your decorated class inherits from Decorator, it should also get the DecorateType metaclass, which should recursively try to create its own decorated class, ad infinitum. Unless I misunderstand what you meant. > > Probably the best piece of advice is "Don't try to use Decorator > > pattern". :) > > Well, I decided on the decorator pattern, because I want to be able to > change the behavior of classes during run-time. I did not really find > any other pattern which would let me do that. Ah. Well it is possible to do that in Python. though there's probably not an official design pattern for it (but then design patterns grew up around less flexible languages, partially as a way to cope with their lack of flexibility). Here are a couple things to think about: If you'd like to change the behavior of individual instances of a class, you can assign functions to individual instances which act just like methods. (Warning: this does not work with operators.) Here is an example: class A(object): def say_hello(self): print "hello, world" a = A() def custom_hello(): print "hello, my name is Inigo Montoya" a.say_hello = custom_hello If you'd like to change the behavior of all instances of the class, then you can assign a new method directly to the class after it was created: def new_default_hello(self): print "hello, children" A.say_hello = new_default_hello Notice that you need to use self when assigning it to the class object, and not to use self when assigning it to an instance of the class. Carl Banks From cjw at ncf.ca Mon May 12 11:04:15 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Mon, 12 May 2008 11:04:15 -0400 Subject: Compiling Python using Microsoft Visual C++ 2008 In-Reply-To: <482855df$0$14196$9b622d9e@news.freenet.de> References: <482855df$0$14196$9b622d9e@news.freenet.de> Message-ID: Martin v. L?wis wrote: >> 1.I have both 2.5 and 2.6 but both appear, under Recent Projects, as >> pcbuild. It would be helpful if the Python Version could be indicated. > > Hover over the link, and it will display the full path, which you can > then infer to reason about the specific copy of Python you are using. Lovely, thanks. It's at the bottom of the screen. > > In any case, compiling Python 2.5 with VS 2008 is not supported. > >> 2.With 2.6, Python compiles and executes OK but various packages are not >> compiled, eg sqlite3. > > See PCbuild/readme.txt. I presume that this is PCbuild8.txt > >> 3.Pythonw compiles OK but not sqlite3. > > So what's the error? > >> 4.Mike Fletcher suggests an approach >> (http://www.vrplumber.com/programming/mstoolkit/) with Visual C for >> Python 2.4. Is this still the recommended way to compile Python 2.6? > > No. Either use the full product, or the express edition. Neither > requires and additional setup. > >> 5.Python 2.5 source refers to an Older Visual C. Automatic conversion >> to Visual C 2008 gives the message ?Some of the properties associated >> with the solution could not be read.? All projects except one had a >> single warning, there were no errors reported. >> 6.After conversion there is no python project, it is flagged ?unavailable?. > > See above. This procedure is not supported; you are on your own. > Get a copy of VS 2003 if you want to follow the official > recommendations. > >> 7.Pythoncore builds with no errors and 6 warnings but there is no >> executable. >> 8.Python 2.5 build _tkinter fails ? tcl.h not found. > > See PCbuild/readme.txt. > > Regards, > Martin Thanks. I'll look at the readme more carefully and seek VS 2003. Now, I would like to remove Python 2.5 from VS 2008 but see no obvious way of getting rid of it. Colin W. From lists at cheimes.de Thu May 1 08:07:53 2008 From: lists at cheimes.de (Christian Heimes) Date: Thu, 01 May 2008 14:07:53 +0200 Subject: Is vs Equality Operator In-Reply-To: <706397.16040.qm@web35903.mail.mud.yahoo.com> References: <706397.16040.qm@web35903.mail.mud.yahoo.com> Message-ID: <4819B299.9090903@cheimes.de> Good Z schrieb: > Hello, > I am having problem in using is. Here is what i am doing. > > x='' > if x is None or x is '': > return 1 > > The above statement does not return value 1. > > If i changed the above check to > if x == None or x == '': > return 1 > Now it works fine. > > Any idea. What is happening here. I am using python 2.4.4 on ubuntu. Never use the identity operator "is" on strings and numbers! In most of the cases it won't do what you are expecting. The behavior can be explained with with a simple analogy. You have a street with a STOP sign on both ends. The stop sign on the near end is equal to the stop sign on the far end. Both have the same form, colors and meaning. The stop signs are also equal to every other stop sign in your town. However the stop signs are NOT identical. They occupy two different places and they are made from two totally different sets of atoms. When you want to know if the stop sign on the near end is a stop sign, you have to use the equality == operator. But if you want to check if you are referring to exactly the one and only stop sign at the near end of your road and no other sign in the universe you have to use 'is'. HTH Christian From marco at sferacarta.com Mon May 12 04:47:49 2008 From: marco at sferacarta.com (Marco Mariani) Date: Mon, 12 May 2008 10:47:49 +0200 Subject: module global variables In-Reply-To: References: Message-ID: pistacchio wrote: > On 12 Mag, 10:01, alex23 wrote: >> On May 12, 5:17 pm, pistacchio wrote: >> >>> hi to all! >>> can i load a module passing to it, automatically and as default, all >>> the caller's global variables to act as module's global variables? Are you positively sure you need this? Modifying imported modules is already quite fragile, but this.. it's basically a reversed(import *) It's quite messy. Where quite equals to "very" From hdante at gmail.com Thu May 22 00:26:32 2008 From: hdante at gmail.com (Henrique Dante de Almeida) Date: Wed, 21 May 2008 21:26:32 -0700 (PDT) Subject: Bug in floating-point addition: is anyone else seeing this? References: Message-ID: <0a9620e9-40f4-4d11-9ddf-9e0f424547b3@x35g2000hsb.googlegroups.com> On May 21, 3:38?pm, Mark Dickinson wrote: >>> a = 1e16-2. > >>> a > 9999999999999998.0 > >>> a+0.999 ? ? # gives expected result > 9999999999999998.0 > >>> a+0.9999 ? # doesn't round correctly. > > 10000000000000000.0 Notice that 1e16-1 doesn't exist in IEEE double precision: 1e16-2 == 0x1.1c37937e07fffp+53 1e16 == 0x1.1c37937e08p+53 (that is, the hex representation ends with "7fff", then goes to "8000"). So, it's just rounding. It could go up, to 1e16, or down, to 1e16-2. This is not a bug, it's a feature. From daraburke78 at gmail.com Tue May 20 06:26:53 2008 From: daraburke78 at gmail.com (dbee) Date: Tue, 20 May 2008 03:26:53 -0700 (PDT) Subject: Report Lab Image Flowable Issue .. Message-ID: I'm try to generate a report that will span multiple pages and have dynamic content using python reportlab. I have no issues with regards to generating images and then using p.drawInlineImage(signup_img, 100,150) to draw them onto the canvas. The problem that i have comes when i try to create flowables so that my layout can span multiple pages. The images themselves never actually show up on the page ... # Import pdf generator from cStringIO import StringIO from reportlab.pdfgen import canvas from reportlab.pdfgen.canvas import Canvas from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib.units import inch from reportlab.platypus import Paragraph, Frame from PIL import Image # Create the HttpResponse object with the appropriate PDF headers. response = HttpResponse(mimetype='application/pdf') response['Content-Disposition'] = 'attachment; filename=somefilename.pdf' buffer = StringIO() styles = getSampleStyleSheet() styleN = styles['Normal'] styleH = styles['Heading1'] story = [] #add some flowables story.append(Paragraph("This is a Heading",styleH)) story.append(Paragraph("""This is a paragraph in style"\ "",styleN)) c = Canvas(buffer) f = Frame(inch, inch, 6*inch, 9*inch, showBoundary=1) f.addFromList(story,c) c.save() # Get the value of the StringIO buffer and write it to the response. pdf = buffer.getvalue() buffer.close() response.write(pdf) This should generate a pdf with the google image in it no ? The pdf gets generated but no image comes out. When I try the other option of using image flowables, I get only an error. The reportlab docs example shows an Image flowable being called like ... Image("lj8100.jpg") .... but when i try to call the object directly i get an error which suggests that i should use Image.new or Image.open to call the object ... # Create image from /tmp im = Image("/tmp/car_dealership.jpg", width=2*inch, height=2*inch) im.hAlign = 'CENTER' #add some flowables story.append(Paragraph("This is a Heading",styleH)) story.append(Image(im)) TypeError: 'module' object is not callable for the im = Image( ....) When i try to feed the image manually ... interest_image = interests_barchart(request) im = Image.open(StringIO(interest_image.content)) #add some flowables story.append(Paragraph("This is a Heading",styleH)) story.append(im) I get ... AttributeError: getSpaceBefore ... which seems to suggest that im isn't a flowable ... Can anyone help pls ? From pavlovevidence at gmail.com Thu May 1 19:32:00 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 1 May 2008 16:32:00 -0700 (PDT) Subject: Best way to store config or preferences in a multi-platform way. References: <790cec6c-b057-4a2d-bc2c-e683630c1127@w7g2000hsa.googlegroups.com> <52a268cc-dae7-4eda-81df-cc82dbcbdcd7@56g2000hsm.googlegroups.com> Message-ID: <071d4536-2b40-4b75-87e1-096a1773f886@f63g2000hsf.googlegroups.com> On May 1, 4:50 pm, Ivan Illarionov wrote: > On Thu, 01 May 2008 11:56:20 -0700, Carl Banks wrote: > > On May 1, 1:30 pm, Ivan Illarionov wrote: > >> On Thu, 01 May 2008 09:45:28 -0700, Carl Banks wrote: > >> > On May 1, 12:11 pm, Jon Ribbens wrote: > >> >> On 2008-05-01, Ivan Illarionov wrote: > > >> >> > IMO .ini-like config files are from the stone age. The modern > >> >> > approach is to use YAML (http://www.yaml.org). > > >> >> You mean YAML isn't a joke!? It's so ludicrously overcomplicated, > >> >> and so comprehensively and completely fails to achieve its stated > >> >> main goal of being "readable by humans", that I had assumed it was > >> >> an April Fool along the lines of Intercal or brainf***. > > >> > YAML, ISTM, took a simple concept that worked for small, > >> > straightforward data, and tried to make into a format that could > >> > anything anywhere, with disastrous results. It's not unlike Perl in > >> > this regard. It's quite ridiculous. > > >> > My recommendation to the OP would be: > > >> > If you intend to write a GUI that completely sets all the options, > >> > use XML. You can bet there are some users who would prefer text > >> > editing options files, and XML, while not the most readable format > >> > available, at least gives users the option. > > >> > If you don't intend to write a GUI to do that, write a simple text > >> > file parser (if the options are simple), use ConfigParser, or use a > >> > Python file that you exec. > > >> > Store the file in $HOME/.appname/config.ext on Unix, $USERDIR/ > >> > ApplicationData/Appname/config.ext on Windows. I don't recommend > >> > using the Windows registry to store options; use it to modify Windows > >> > behavior (like file associations) but keep your own program's options > >> > in your own file. > > >> If you don't like YAML, use JSON or something similar -- XML is > >> overkill and .INI is too limited. > > > I don't think you know the OP's requirements enough to know whether INI > > or XML is suitable. You're welcome to suggest alternatives but what I > > suggested is fine. > > > As for XML being overkill for anything, I highly disagree. XML is > > suitable for the smallest tasks. These days I use XML for almost all my > > data exchange needs: including conf files. Elementtree makes it > > possible to process XML and pull out some typical data in ten or so > > lines of code. What could possibly be overkill about that? > > > Carl Banks > > I used XML for almost everything in the past until I found YAML. > Elementtree makes it easy but not easy enough. I'm honestly very happy for you that you have found the data transfer format that you are happy with, but I'm sorry, that doesn't amount to a blanket invalidation of everything you've ever tried and rejected. > The most powerful thing > about YAML is that it was designed to map directly to native data types > in languages like Python (see another my post in this thread for > example). And this means that simple YAML files will always be easier to > process in Python than XML or INI. And this in turn means that OP with > any requirements will have to write less code to read and write his > config files. I will mention that Python already has, built in, a data transfer format that maps directly to Python types: pickle. And not only that, it's more readable than YAML. I will also add that what you think of as a strength is not always thought of as a strength by everyone. In my early days of Python, I would use pickle for all kinds of things. I've now pretty much switched entirely to XML, because I no longer believe that direct correspondance to Python types is a good thing; at least it isn't for me. There is a very basic reason for this: whenever I write a pair of tools, one to output some XML data, and another further down the chain to read it back in, I hardly ever want the data to have the same structure in memory in both tools. For me, YAML or pickle would not gain me anything; I'd be doing all that reformatting anyway. Of course, the OP wasn't talking about data transfer, he was talking about a freaking config file. Reading in a config file is a ridulously silly thing to try to hyperoptimize. Do you really want him to add an extra dependency just to reduce code used by five lines? Carl Banks From erik.oosterwaal at gmail.com Sun May 25 12:58:55 2008 From: erik.oosterwaal at gmail.com (erik.oosterwaal at gmail.com) Date: Sun, 25 May 2008 09:58:55 -0700 (PDT) Subject: Python web development that resembles PHP or classic ASP Message-ID: <66a261d8-c31d-4519-beb9-c8913f61a87d@m44g2000hsc.googlegroups.com> Hi All, I have been developing websites in classic asp using VB script for a long while now. Due to the fact that I also took a detour to developing ColdFusion, and the fact the companies I work(ed) for never had time or money for courses, I am now in the awkward position that I am -still- developing classic ASP. In it, I have become quite resourceful, I wrote a framework using WSC (windows scripting components) to separate logic from presentation, and my display pages use almost no logic, except for the loops and variables I need to build my pages. I have a three-tier setup and all business logic is in separate WSC files. The framework even uses an ORM for access to the tables of my database. This works like a charm. It makes classic ASP code maintainable, it makes working in classic ASP very pleasant actually and it makes our customers very happy. The problem is that classic asp is now a dead language, I need to modernize and fast! Although the arguments some people make against it are not valid for me (spaghetti code, unmaintainable, slow), I still see that there is little to no support for it anymore. The most logical way to "update" my knowledge to something more modern, would be to dive into ASP.NET. I considered that for a long time, but there are some problems with this: 1. I love the control I have over my html using inline, template-based vbscript. ASP.NET's web forms really sound like a very bad idea, also the approach Microsoft takes in trying to make a stateless web-app seem like a statefull application is IMHO a burden. I think webapps are inherently different than desktop apps, and should be programmed as such. 2. Who says Microsoft isn't going to pull the plug on VB.NET in a while or make a drastic change like they did from asp to asp.net again, some time in the future? 3. I like the rapid development I can do in a dynamic, loosely typed language like vbscript. The performance-bottleneck of a site is mostly in the database-access and the http-calls and I think writing all of the declarations and types for a strong-typed language is overkill for a webapp. So that's when I started looking at other dynamic languages for webdevelopment. I looked at Ruby on Rails and at the different web- frameworks that are available for Python. The biggest problem there for me is that the MVC type frameworks that are currently very popular are also not what I'm looking for. I like having my directory tree conform to the structure of my website, so the "Controller" part of the MVC style of development is something I wouldn't want. What I -would- like is a separation of code and display logic (so being able to include libraries in a page) and being able to intermix code directly into the HTML. As Python would be the language I prefer over Ruby, I thought I'd ask here to see if anyone in the Python community knows if such a development-framework exists in Python. For example, does IronPython also use the same web forms approach as asp.net using VB? The frameworks I looked at (Django, Pylons) seem to be able to use different templating engines, does that mean it's just a question of finding the right one? Also, for Python there is also the problem of meaningful indentation. I'm not even sure if it's possible to use Python directly inside HTML, because indentation would be at the very least tricky to maintain. I'm kind of hoping here that there are some solutions to these problems available in Python. Any help would be greatly appreciated. Kind regards, Erik From efurman at admailinc.com Wed May 14 13:17:00 2008 From: efurman at admailinc.com (Ethan Furman) Date: Wed, 14 May 2008 09:17:00 -0800 Subject: built in list generator? In-Reply-To: <87hcd14vo0.fsf@benfinney.id.au> References: <87hcd14vo0.fsf@benfinney.id.au> Message-ID: <482B1E8C.1010800@admailinc.com> Ben Finney wrote: > Subject: > Re: built in list generator? > From: > Ben Finney > Date: > Wed, 14 May 2008 09:43:43 +1000 > To: > python-list at python.org > > To: > python-list at python.org > Newsgroups: > comp.lang.python > > >"Diez B. Roggisch" writes: > > > >>globalrev schrieb: >> >> >>>if i want a list with all numbers between x and y is there a way to >>>do this with an inbult function. >>> >>>i mean i can always construct a function to do this but is there >>>soemthing like: >>> >>>nbrs = list(range(50,100, 2)) >>> >>> >>range *does* that. use xrange if all you want is to iterate. >> >> > >Until Python 3.0, where 'range' returns an iterable. > > Is there a thread somewhere of the discussion for this change? I'm presuming range is used almost exclusively in loops where a change in the return type would have no negative effect. -- Ethan -------------- next part -------------- An HTML attachment was scrubbed... URL: From ohad.frand at percello.com Mon May 12 13:27:10 2008 From: ohad.frand at percello.com (Ohad Frand) Date: Mon, 12 May 2008 20:27:10 +0300 Subject: question about python statements Message-ID: Hi I am looking for a way to programmically get a list of all python existing statements that I cannot access by __builtins__ or locals() (like ["assert","break","class",...]) Thanks, Ohad -------------- next part -------------- An HTML attachment was scrubbed... URL: From workitharder at gmail.com Wed May 21 20:14:07 2008 From: workitharder at gmail.com (bukzor) Date: Wed, 21 May 2008 17:14:07 -0700 (PDT) Subject: Bug in floating-point addition: is anyone else seeing this? References: <8187c3b6-a772-456f-a54f-0af7babb353e@w34g2000prm.googlegroups.com> <69jlk4F330nmpU1@mid.uni-berlin.de> Message-ID: On May 21, 3:28 pm, Dave Parker wrote: > On May 21, 4:21 pm, "Diez B. Roggisch" wrote: > > > Which is exactly what the python decimal module does. > > Thank you (and Jerry Hill) for pointing that out. If I want to check > Flaming Thunder's results against an independent program, I'll know to > use Python with the decimal module. Utterly shameless. From gagsl-py2 at yahoo.com.ar Mon May 12 06:31:42 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 12 May 2008 07:31:42 -0300 Subject: Import/Create module from buffer References: <09bfaed8-8bf6-4faf-80f9-e0b97aa03127@a70g2000hsh.googlegroups.com> Message-ID: En Mon, 12 May 2008 05:49:22 -0300, Gruik escribi?: > I'm currently working on python embedding with C++. My goal is that > the C++ part handle files writing/reading so that the Python part only > works with buffers. > > I succeeded in buffer exchanges. The problem is that some of the files > I read/write are python files so that, before embedding, I imported > them as modules when I needed them. > > But now that the Python part only receive buffers, I can't do it > anymore. So I wonder : > - is it possible to import module from a buffer instead of files? > - or is it possible to create a module object from my buffer? Yes, first compile the buffer to get a code object, then use PyImport_ExecCodeModule. See how this function is used in import.c -- Gabriel Genellina From bj_666 at gmx.net Sat May 17 00:57:24 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 17 May 2008 04:57:24 GMT Subject: Classmethods are evil References: Message-ID: <6976tkF31cvenU1@mid.uni-berlin.de> On Sat, 17 May 2008 04:01:50 +0000, Ivan Illarionov wrote: > After re-reading "Python is not Java" I finally came to conclusion that > classmethods in Python are a very Bad Thing. > > I can't see any use-case of them that couldn't be re-written more clearly > with methods of metaclass or plain functions. *The* use case IMHO are alternative constructors. They belong to the class, so functions are not as clear and it's possible to have more than one class in a module with class methods of the same name, e.g. `A.from_string()` and `B.from_string()` vs. `create_a_from_string()` and `create_b_from_string()`. And I don't see how functions can be inherited by sub classes like class methods can. Metaclasses are more clear than class methods? You must be joking!? > They have the following issues: > 1. You mix instance-level and class-level functionality in one place > making your code a mess. Writing meta classes just for alternative constructors seems to be more of a mess to me. Too much magic for such a simple case for my taste. Ciao, Marc 'BlackJack' Rintsch From timr at probo.com Wed May 28 02:04:54 2008 From: timr at probo.com (Tim Roberts) Date: Wed, 28 May 2008 06:04:54 GMT Subject: php vs python References: <-t-dnWQ4bZN2MaTVnZ2dnUVZ_qGdnZ2d@comcast.com> <68cb8bb1-4cc5-4a28-8915-46e7d4e316d9@d1g2000hsg.googlegroups.com> <613388153.20080528051020@freemail.ru> Message-ID: <5dtp34thl4a0ipeb5lm550uslud0jhpvua@4ax.com> Ivan Illarionov wrote: >On Wed, 28 May 2008 05:10:20 +0400, AnrDaemon wrote: >> In reply to Your message dated Monday, May 26, 2008, 04:47:00, >> >>>> As I've said before - good programmers can write good code in any >>>> language. >> >>> Yes, they can. But it may be harder to do for them in one language and >>> easier in another. >... >No. Language does matter. A good programmer keeps many tools in his toolbox, and understands which tools provide the best service for the problem at hand. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From castironpi at gmail.com Sat May 10 08:10:13 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 10 May 2008 05:10:13 -0700 (PDT) Subject: People still using Tkinter? References: <68ku74F2sm1usU1@mid.uni-berlin.de> Message-ID: On May 10, 1:38?am, Marc 'BlackJack' Rintsch wrote: > On Sat, 10 May 2008 00:20:33 -0500, Kenneth McDonald wrote: > > Any guesses as to how many people are still using Tkinter? And can ? > > anyone direct me to good, current docs for Tkinter? > > AFAIK `Tkinter` hasn't changed much over time, so "old" documentation is > still current. > > Ciao, > ? ? ? ? Marc 'BlackJack' Rintsch Get synchronizing into wx. CallAfter and CallLater both pull too hard, but I didn't write it for money. How are specs doing on coming down? Window size is important. Does anyone else bounce around resizability either? Ciao. From rajarshi.guha at gmail.com Wed May 14 12:13:09 2008 From: rajarshi.guha at gmail.com (Rajarshi) Date: Wed, 14 May 2008 09:13:09 -0700 (PDT) Subject: usage of python References: Message-ID: On May 13, 6:57 pm, afrobeard wrote: > If I were you, I'd show them actual code and how easy it is to get > things done. Showing them how to implement a GTalk Bot[http:// > code.google.com/p/pygtalkrobot/] or how to build simple arcade games > with PyGame[http://www.pygame.org/news.html] would harbor much more > interest in my opinion because it'll show them their own power. There > may be some people who oppose this approach under the pretext that > students taking introductory programming courses should be taught C > because it incorporates the discipline that is much needed if they > want to become hard core CS researchers. Thanks for the pointers. I agree with your comments - the students are not necessarily going towards CS - there are many from telecom, business etc. That was one of the big reasons for using Python - the ability to get stuff done easily and quickly From wizzardx at gmail.com Sat May 3 20:10:16 2008 From: wizzardx at gmail.com (David) Date: Sun, 4 May 2008 02:10:16 +0200 Subject: Light slices + COW In-Reply-To: References: Message-ID: <18c1e6480805031710r5e332200y8f1a792383f30f5f@mail.gmail.com> > That xpairs() generator is nice, but it's not the best possible code > (but you may disagree with me, and you may think that code better than > the successive D code that uses two slices). Inside it I can't use a > list slicing because it copies subparts of the list, probably becoming > too much slow (for example if len(seq) == 1000). What do you mean by best possible? Most efficient? Most readable? And why don't you use islice? eg: def xpairs(seq): len_seq = len(seq) for i, e1 in enumerate(seq): for e2 in islice(seq, i+1, None): yield e1, e2 Here's a version which makes more use of itertools. It should be more efficient, but it's ugly :-) (this is my first time using itertools). def xpairs(seq): def _subfunc(): for i in xrange(len(seq)): e1 = seq[i] yield izip(repeat(e1), islice(seq, i+1, None)) return chain(*_subfunc()) > That D code is as fast or faster than the code you can back-translate > from Python, this is possible because in D arrays slices are very > light, they are a struct of D compiles to efficient machine code so Python is at a disadvantage even if you use the same syntax (see my first example). You can make the Python version faster, but beware of premature optimization. > I think Python 3.0 too may enjoy a similar strategy of light slices + > COW for strings, lists and arrays (tuples and strings don't need the > COW). What I'dlike to see is a rope[1] module for Python. I'ts in C++'s STL library[2], but I haven't found a Python version yet. [1] http://en.wikipedia.org/wiki/Rope_(computer_science) [2] http://www.sgi.com/tech/stl/Rope.html With a Python rope library you could do things like this: a = '' b = rope(a) # Contains a reference to a c = b[0:100000] # Get a rope object d = b[100000:200000] # Get another rope object e = b + b # Get another rope object print e # Get the string representation of all the re-assembled sub-sections # And so on. In the above code there was only 1 copy of the huge string in memory. The rope objects only contain a tree of sub-operations (slices, concatenations, references to original sequences, etc). This shouldn't be too hard to implement. Does anyone know of an already-existing 'rope' module? David. From workitharder at gmail.com Wed May 21 15:05:17 2008 From: workitharder at gmail.com (bukzor) Date: Wed, 21 May 2008 12:05:17 -0700 (PDT) Subject: Bug in floating-point addition: is anyone else seeing this? References: Message-ID: On May 21, 11:38 am, Mark Dickinson wrote: > On SuSE 10.2/Xeon there seems to be a rounding bug for > floating-point addition: > > dickinsm at weyl:~> python > Python 2.5 (r25:51908, May 25 2007, 16:14:04) > [GCC 4.1.2 20061115 (prerelease) (SUSE Linux)] on linux2 > Type "help", "copyright", "credits" or "license" for more information.>>> a = 1e16-2. > >>> a > 9999999999999998.0 > >>> a+0.999 # gives expected result > 9999999999999998.0 > >>> a+0.9999 # doesn't round correctly. > > 10000000000000000.0 > > The last result here should be 9999999999999998.0, > not 10000000000000000.0. Is anyone else seeing this > bug, or is it just a quirk of my system? > > Mark I see it too From castironpi at gmail.com Tue May 20 14:07:46 2008 From: castironpi at gmail.com (castironpi) Date: Tue, 20 May 2008 11:07:46 -0700 (PDT) Subject: "indexed properties"... References: <7o7r245pb3kqk42odihmf95sifpbbv0rqp@4ax.com> <7sm234hp8u9ia850uaopn3amtq95jqbt5t@4ax.com> <20080519144803.14d3569a@hyperspace> <2la534p1h4g7lke3lq3tji06q6cm32v7b0@4ax.com> <20080520154802.4b5df647@hyperspace> Message-ID: <4233fb45-f144-423d-aae8-e9fa623ea029@j22g2000hsf.googlegroups.com> On May 20, 10:40?am, "David C. Ullrich" wrote: > In article <20080520154802.4b5df647 at hyperspace>, > > > > > > ?pataphor wrote: > > On Tue, 20 May 2008 06:12:01 -0500 > > David C. Ullrich wrote: > > > > Well, ok. Like I said, I never _took_ the position that it _should_ > > > be a list of lists, I just said I didn't see the advantage to using > > > a single list. > > > I'm now thinking about a list of lists containing single element lists. > > > def test(): > > ? ? n = 3 > > ? ? R = range(n) > > ? ? M = [[[i+j*n] for i in R] for j in R] > > ? ? for L in M: > > ? ? ? ? print L > > ? ? row2 = M[1] > > ? ? print > > ? ? print row2 > > ? ? col3 = [L[2] for L in M] > > ? ? print col3 > > ? ? col3[1][0]=9 > > > print col3 > > ? ? print row2 > > ? ? print > > ? ? for L in M: > > ? ? ? ? print L > > > if __name__=='__main__': > > ? ? ? ? test() > > > The idea is to use a single element list as kind of storage facility. > > That enables me to copy a column, then change something in that column > > and make the change turn up in the matrix and even in a previously made > > copy of a row that shared the specific element. > > > > Today's little joke: Long ago I would have solved > > > this by storing the data as a list of rows and _also_ > > > a list of columns, updating each one any time the > > > other changed. Just goes to show you things > > > could always be worse... > > > Well have I ever ... I only thought about this last week and I > > actually thought it was a *good* idea. > > Sorry. If you really want to do this you could keep things > in sync automatically by writing the appropriate __setitem__ > and resolving never to modify the data except through that... > > def whatever.__setitem__(self, (row,col), value): > ? self.rows[row][col] = value > ? self.cols[col][row] = value > > Seems to me like an, um, "untenable" waste of space. And you'd > need to be certain to never set anything except through > self[row,col]; as far as I can see anything like setrow() > would be a loop "for col in range(width): self[row,col] =". > > Hmm. You could keep the data in some object that encapsulates > the two double lists and use some fancy feature (__getattribute__?) > to make certain that the only possible access to the data > was through __getitem__... > > > > > > > I only gave up on it because > > now I would have to keep ?track of how far the two views are out of > > sync, because some operation could use data that was modified by an > > other view. Zipstar transposition is very handy for syncing, but it is > > also very expensive. But probably not for you. > > > > Expressing interest is a big mistake... > > > How so? ;-) > > > > Sometime soon a thread will appear titled something > > > like "indexed attributes" with a stripped-down but > > > functional example of what I have in mind for Matrix > > > I can't wait! Keep up the good work. > > > P. > > -- > David C. Ullrich- Hide quoted text - > > - Show quoted text -- Hide quoted text - > > - Show quoted text - You can use tuples in dictionaries. Example: >>> a= {} >>> a[0,1]= 2 >>> a[2,3]= 7 >>> a[0,1] 2 From _karlo_ at _mosor.net_ Wed May 21 19:13:12 2008 From: _karlo_ at _mosor.net_ (Karlo Lozovina) Date: Wed, 21 May 2008 23:13:12 +0000 (UTC) Subject: Returning to 'try' block after catching an exception Message-ID: I'm not sure if Python can do this, and I can't find it on the web. So, here it goes: try: some_function() except SomeException: some_function2() some_function3() ... # somehow goto 'try' block again In case it's not clear what I meant: after executing some_function() exception SomeExcpetion gets risen. Then, in except block I do something to fix whatever is causing the exception and then I would like to go back to try block, and execute some_function() again. Is that doable? Thanks. -- _______ Karlo Lozovina - Mosor | | |.-----.-----. web: http://www.mosor.net || ICQ#: 10667163 | || _ | _ | Parce mihi domine quia Dalmata sum. |__|_|__||_____|_____| From ivan.illarionov at gmail.com Sat May 10 13:33:26 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Sat, 10 May 2008 10:33:26 -0700 (PDT) Subject: Now what!? References: <68m0i1F2t8265U1@mid.uni-berlin.de> Message-ID: <7363f4c0-1dec-4943-a9f6-7a24c3aff971@e39g2000hsf.googlegroups.com> On 10 ???, 21:22, notbob wrote: > On 2008-05-10, Diez B. Roggisch wrote: > > > notbob schrieb: > >> script the same way ($ ./helloworld) and it works fine. Same shebang, same > >> dir, same permission, etc. > > > I'm pretty sure you misse the correct shebang - > > Sorry. Both exactly the same. I checked 5 times. > > helloworld shebang: #!/usr/bin/python > while shebang: #!/usr/bin/python > > (above yanked from respective scripts) > > nb Shebang is certainly broken, possible causes: 1. Wrong line endings (should be \n) 2. Whitespace before the shebang -- Ivan From __peter__ at web.de Fri May 23 04:12:00 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 23 May 2008 10:12:00 +0200 Subject: pickle error: can't pickle instancemethod objects References: Message-ID: Michele Simionato wrote: > Can somebody explain what's happening with the following script? > def __gestate__(self): # should skip the bound methods attributes Must be __getstate__ ;) Peter From gherron at islandtraining.com Thu May 1 18:33:09 2008 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 01 May 2008 15:33:09 -0700 Subject: is +=1 thread safe In-Reply-To: <4819DA2D.3030508@ggmail.com> References: <4819DA2D.3030508@ggmail.com> Message-ID: <481A4525.6020205@islandtraining.com> AlFire wrote: > Hi, > > I have a piece of software which uses threads in very massive way - > like hundreds of them generated every second. > > there is also a piece of code which maintains the number of > outstanding threads, simply > > counter+=1 is executed when before starting the thread and counter-=1 > after it finishes. > > all is very simple and by the end of the program life I expect the > counter to zero out. > > however I am getting values -1, -2, 1 ,2 ,3 and quite often 0 as > expected. > > I guarded those statement with Lock.{acquire,release} and now it > always returns 0. > > > But I still can not believe that +=1 is not a thread safe operation. > > > Any clue? > Of course it's not thread safe. For the same reason and more basic, even the expression i++ is not thread safe in C++. Any such calculation, on modern processors, requires three operations: retrieve value of i into a register, increment the register write the value into i. If a thread is interrupted anywhere within that sequence, and another thread access i, you have a conflict. (And indeed, hardware interrupts can occur between any two instructions.) Gary Herron From deets at nospam.web.de Thu May 29 09:44:26 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 29 May 2008 15:44:26 +0200 Subject: seg. fault with Py_BuildValue? References: Message-ID: <6a7qarF35bvivU1@mid.uni-berlin.de> Christian Meesters wrote: > Hi > > I'm having trouble with Py_BuildValue. I was able to pinpoint the > following statement as the one causing a seg. fault with my script: > > static PyObject * funcname(PyObject *self, PyObject *args) { > ... > return Py_BuildValue("(OO)", x, y); > } > where x & y are both of type PyObject. > > Any suggestions here? Do I need to handle the output of Py_BuildValue > somehow before returning? How? Need to decref x & y before returning? Just a guess - but according to the docs of Py_BuildValue it will return a tuple already when given a format string of several format units. What happens if you get rid of the ()? Diez From mcknight0219 at gmail.com Mon May 12 23:02:37 2008 From: mcknight0219 at gmail.com (Jimmy) Date: Mon, 12 May 2008 20:02:37 -0700 (PDT) Subject: how to get information of a running prog in python References: <8b571818-25f0-4c5d-8b1c-5b7e73192d15@w5g2000prd.googlegroups.com> Message-ID: <58a5cb5c-5c10-43a3-bff0-58fa3c213a80@i36g2000prf.googlegroups.com> On May 13, 10:36 am, "Dan Upton" wrote: > On Mon, May 12, 2008 at 10:19 PM, Jimmy wrote: > > Well, i know it may be a little non-python thing, however, I can think > > of no place better to post this question :) > > > can anyone tell me, in python, how to obtain some information of a > > running program? > > paticularly, if i am playing some music in audacious or other media > > player, how can i get the the name and some other info of current > > playing song? It seems that audicious doesn't output on run-time > > -- > > http://mail.python.org/mailman/listinfo/python-list > > In most cases, you'll probably need some sort of API, either in the > program itself or through some sort of plugin, that lets external > programs query it. For instance, there are some plugins to WinAmp > that allow external programs (like Last.FM or Mog-O-Matic) to see what > track is currently playing. You may also be able to do something like > get the window title (again, WinAmp's title bar usually includes the > artist and title) and parse it out. I don't really know that there's > anything specific to Python for accessing these though, and it may > vary depending on media player. > > Just my two cents... > > -dan thanks! In linux, I am always obfuscated by sort of APIs. Like how to get title information of a running program? where am I supposed to find these APIs From rocky at panix.com Wed May 28 23:18:15 2008 From: rocky at panix.com (R. Bernstein) Date: Wed, 28 May 2008 23:18:15 -0400 Subject: pydb remote debugging/cmd.Cmd over socket? References: <6a5b8qF35n4hiU1@mid.uni-berlin.de> Message-ID: "Diez B. Roggisch" writes: > Hi, > > I'm fiddling around with pydb. Installation and usage are fine. What I > especially like is the fact that you can attach a signal such that you drop > into debugging mode on demand. > > But this is of limited use to me in situations where a server is written in > python. According to the source, pydb's debugger class Gdb extends cmd.Cmd. > > It passes stdin/stdout-arguments that should be usable to replace the > standard streams. But so far all my experiments simply dropped the process > into debugging mode putting out and getting io over stdin/stdout - not my > self-supplied streams. > > So I wonder (being a bit rusty on my UNIX-piping-skillz): how does one do > that - essentially, create a remote python shell using cmd.Cmd? > > Diez As part of the 2006 Google Summer of Code project Matt Flemming started working on remote debugging in pydb. Alas it wasn't completed and I let the code fall through the cracks. Matt claimed it worked to some degree but I could never get it to work for me. Most definitely the code has atrophied. The user interface was loosely based or reminiscent of gdb. So you'd run pydbserver either as a command inside the debugger or as an option to pydb or call inside Python pdbserver after importing. There is a connection class (file pydb/connection.rb) which was to allow different kinds of protocols, like a socket connection or a serial line connection, or maybe even two FIFO's so that you could connect to a different process on the same computer. And there were some commands on the user-interaction side to attach or detach the Python program you want to debug. If you look in pydb.py.in and gdb.py.in you'll see some code commented out with double hashes which is part of this effort. I invite you or others to try to resurrect this effort. However as I look at the code now, it doesn't make much sense other than the broad outline given above. Another approach and possibly a much simpler one if you are looking for a Python debugger which supports remote debugging is Winpdb http://winpdb.org/ by Nir Aides. From code at pizzashack.org Sat May 3 00:48:49 2008 From: code at pizzashack.org (Derek Martin) Date: Sat, 3 May 2008 00:48:49 -0400 Subject: RegEx for matching brackets In-Reply-To: <4465e4ed-6a37-48a3-ac0d-f3da316301a4@26g2000hsk.googlegroups.com> References: <713f6d61-906d-490f-bcbc-befd19e086e5@d19g2000prm.googlegroups.com> <4465e4ed-6a37-48a3-ac0d-f3da316301a4@26g2000hsk.googlegroups.com> Message-ID: <20080503044849.GH17661@dragontoe.org> On Fri, May 02, 2008 at 03:51:16PM -0700, NevilleDNZ wrote: > Thanx for the link to these parsers. ANTLR looks interesting. > Yoyo: http://www-users.cs.york.ac.uk/~fisher/software/yoyovwg/readme > > I figured out a way to do it in python. [...] > > def check_open_close(str): > try: > eval("".join({"{":"[","}":"],"}[c] for c in re.findall( "([{}])|(?: > [^{}]+)", str) if c)) Ouchie... It may be short, but if I had to maintain this code, and I saw this, your name would be used in sentences with lots of curse words. ;-) That's one hard-to-read line of code... Also this may or may not do what you want it to do -- I think it doesn't... This problem is the classical example of when to use a stack (Last-In, First-Out) data structure. If all you want to do is make sure that the line has the same number of opens and closes in a line, your code does that. But if you actually want to verify the syntax (i.e. make sure that there are the same number of open brackets as close brackets, AND make sure that they occur in the correct order, opens first, closes last, AND that the closes come in the same (reverse) order as the opens), your code does not do that. I changed the tests in your code (specifically the brackets, and nothing else) to demonstrate this: DETECTED: { a test BAD DETECTED: { a test } OK # This should fail, because the closing ] comes before the open [ MISSED: { a test ] [ a test } BAD DETECTED: { a test } { this { a test } is a test } OK # this should fail, for the above reason, and because the order is wrong MISSED: { a test { this { a test ] is a test } missing close [}} BAD DETECTED: { a test { this { a test ] is a test } missing close } BAD # this should also fail for both reasons MISSED: { a test ] this { a test } is a test } missing close [ BAD DETECTED: a test } { this { a test } is a test } BAD DETECTED: { a test } this { a test } is a test } BAD It doesn't detect the brackets in the right order (opens before closes), nor does it detect that they occur in the correct sequence. Clever code isn't always so clever... I think there's something to be said for writing code that's a little bit more lengthy, but easier to understand. This version is only a few lines longer than yours (in total, not counting the comments), but it is a bit clearer and easier to follow. Note that I added angle brackets and mixed the bracket types in the tests. I also didn't use your referee... In my code, the test simply succeeds if the brackets match, and fails if they are unbalanced or out of order. #!/usr/bin/python # define the matching pairs bm = { '}': '{', ']': '[', ')': '(', '>': '<' } def bracket_balance(str): # initialize the stack to an empty list blist = [] for c in str: # If c is an open bracket of any type, place on stack if c in bm.values(): blist.append(c) # If it is a close bracket, pull one off the stack and # see if they are matching open-close pairs. If the stack # is empty, there was no matching open. Return false in that # case, or if they don't match. if c in bm.keys(): try: foo = blist.pop() except IndexError: return False if foo != bm[c]: return False # End of the line: if we still have brackets on the stack, we # didn't have enough close brackets. Return false. if blist != []: return False # If we got here, the stack is empty, and there are no brackets # left unmatched. we're good! return True tests=""" { this is a test BAD < this is a test > OK { this is a test } { this is a test } OK { this is a test } [ this { this is a test } is a test ] OK { this is a test { this { this is a test } is a test } missing close BAD """.splitlines()[1:] for test in tests: print "Testing %s:" % test if bracket_balance(test): print "-> OK" else: print "-> FAILED" Testing with your original set of tests: $ ./brackets.py Testing { this is a test BAD: -> FAILED Testing < this is a test > OK: -> OK Testing { this is a test } { this is a test } OK: -> OK Testing { this is a test } [ this { this is a test } is a test ] OK: -> OK Testing { this is a test { this { this is a test } is a test } missing close BAD: -> FAILED Testing with my modified set of tests: $ ./brackets.py Testing { a test BAD: -> FAILED Testing { a test } OK: -> OK Testing { a test ] [ a test } BAD: -> FAILED Testing { a test } { this { a test } is a test } OK: -> OK Testing { a test { this { a test ] is a test } missing close [}} BAD: -> FAILED Testing { a test { this { a test ] is a test } missing close } BAD: -> FAILED Testing { a test ] this { a test } is a test } missing close [ BAD: -> FAILED Testing a test } { this { a test } is a test } BAD: -> FAILED Testing { a test } this { a test } is a test } BAD: -> FAILED In all cases, this code correctly identifies when the brackets are out of order, or unbalanced. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From bignose+hates-spam at benfinney.id.au Fri May 2 01:50:22 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 02 May 2008 15:50:22 +1000 Subject: #!/usr/bin/env python vs. #!/usr/bin/python References: <87abj91j8u.fsf@benfinney.id.au> Message-ID: <87ve1xz23l.fsf@benfinney.id.au> "D'Arcy J.M. Cain" writes: > On Fri, 02 May 2008 13:24:01 +1000 > Ben Finney wrote: > > I much prefer "#! /usr/bin/python" because I want my Python > > programs to, by default, be run with the default Python, and > > depend on Python being installed by the operating system's package > > manager. On systems that use shebang lines and that actually have > > standardised filesystem locations, the default Python is found at > > '/usr/bin/python'. > > You have lived a sheltered life. Not every packaging system puts the > executible in /usr/bin. Many systems use /usr/local/bin. They use that for the operating-system-installed default Python interpreter? Colour me incredulous. -- \ ?[The RIAA] have the patience to keep stomping. They?re | `\ playing whack-a-mole with an infinite supply of tokens.? | _o__) ?kennon, http://kuro5hin.org/ | Ben Finney From umpsumps at gmail.com Fri May 9 17:19:38 2008 From: umpsumps at gmail.com (umpsumps at gmail.com) Date: Fri, 9 May 2008 14:19:38 -0700 (PDT) Subject: anagram finder / dict mapping question References: <0ebda682-6c99-43b2-b88b-80f6c88e1c98@p25g2000hsf.googlegroups.com> Message-ID: <54f75240-d8ee-482c-baea-d37bf3900b76@i36g2000prf.googlegroups.com> > > What would be the best method to print the top results, the one's that > > had the highest amount of anagrams?? Create a new histogram dict? > > You can use the max() function to find the biggest list of anagrams: > > top_results = max(anagrams.itervalues(), key=len) > > -- > Arnaud That is the biggest list of anagrams, what if I wanted the 3 biggest lists? Is there a way to specific top three w/ a max command?? From jeffrey at fro.man Tue May 6 14:15:04 2008 From: jeffrey at fro.man (Jeffrey Froman) Date: Tue, 06 May 2008 11:15:04 -0700 Subject: Are rank noobs tolerated, here? References: <3zITj.35199$gB5.25251@fe105.usenetserver.com> Message-ID: <9OGdnYcw57m1Pb3VnZ2dnUVZ_vCdnZ2d@cablespeedwa.com> notbob wrote: > Do python scripts require the: > > #!/usr/bin/env python An appropriate shebang is required if you intend to use the module itself as a script, from the command line, like: $ ./my_module.py argument argument ... It is not required merely to import the module into a python program or interpreter. Even without the shebang, the module can be run indirectly with: $ python ./my_module.py argument argument ... or, if the module is somewhere on your sys.path: $ python -m my_module argument argument ... Jeffrey From stef.mientki at gmail.com Sat May 10 15:25:47 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Sat, 10 May 2008 21:25:47 +0200 Subject: how to reference my own module ? Message-ID: <4825F6BB.9090707@gmail.com> hello, I've a library that I import as import ppygui.api as gui the reason for this construct is that I've to use different libraries for different platforms. Now I like to write some examples in the library (activated by if __name__ == '__main__' :) and I would that these examples can be used in the user program just by copy / paste. For calling a function / class in the user program I've to write: sizer = gui.VBox () So also write exactly the same sentence in the library examples, but "gui" is not recognized Any ideas how I can realize the above ? thanks, Stef Mientki From bruno.42.desthuilliers at websiteburo.invalid Fri May 9 10:01:15 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 09 May 2008 16:01:15 +0200 Subject: How to modify meaning of builtin function "not" to "!"? In-Reply-To: References: Message-ID: <4824592a$0$26517$426a74cc@news.free.fr> grbgooglefan a ?crit : > I am creating functions, the return result of which I am using to make > decisions in combined expressions. > In some expressions, I would like to inverse the return result of > function. > > E.g. function contains(source,search) will return true if "search" > string is found in source string. Do you really need a function for this ? if "foo" in "foobar": print "do you really really need a function for this ?" > I want to make reverse of this by putting it as: > if ( ! contains(s1,s2) ): > return 1 which is a convoluted way to write: return s2 not in s1 > I found that "!" is not accepted by Python & compile fails with > "invalid syntax". > Corresponding to this Boolean Operator we've "not" in Python. > > How can I make "not" as "!"? Err... How to say... The boolean negation operator in Python is "not". So the only answer I can provide is : "use 'not' instead of '!'". And while we're at it : drop those useless parens. HTH From dikkie at nospam.org Wed May 28 19:43:18 2008 From: dikkie at nospam.org (Dikkie Dik) Date: Thu, 29 May 2008 01:43:18 +0200 Subject: Python's tail -f implementation for remote files In-Reply-To: <483dda9a$0$11598$607ed4bc@cv.net> References: <483dda9a$0$11598$607ed4bc@cv.net> Message-ID: <483dee16$0$1279$bf4948fe@news.tele2.nl> asdf wrote: > Basically what i want to do is to read a file > that is being constantly appended to but which > is located on a remote server. > I found this for doing BASH's tail -f in python: > > import os > tailoutputfile = os.popen('tail -f syslog') > while 1: > line = tailoutputfile.readline() > if len(line)==0: # change the termination condition > break > process_line(line) > > and it works great. But not sure how to use this with > ssh command to connect to remote machine. > > Any tips? ssh host_address 'tail -f file_name' Should do it (from the command line). Off course, you can put this into popen as well. If you log in with a public key (see ssh-keygen), you do not have to supply a password using the console. Best regards. From notbob at nothome.com Sat May 10 19:22:00 2008 From: notbob at nothome.com (notbob) Date: Sat, 10 May 2008 23:22:00 GMT Subject: Now what!? References: <68m0i1F2t8265U1@mid.uni-berlin.de> <7363f4c0-1dec-4943-a9f6-7a24c3aff971@e39g2000hsf.googlegroups.com> <9GlVj.168$PE5.102@fe087.usenetserver.com> Message-ID: On 2008-05-10, Dennis Lee Bieber wrote: > So... in short, you'd need to have been reading a tutorial specific > to "shell" scripting... I have been. I'm also trying to learn bash shell scripting, not to mention sed/awk, php, etc. I should have started this a long time ago, but I'm lazy and, like I said, I'm not particularly fond of coding. Yes, I have learned basic C and basic , but never beyond intro. Now, I'm doing it because I'm a geezer and I figure my brain needs more exercise then just blabbing on usenet. Besides, I've been cruising while using linux for too long and have remained low end intermediate. Time to get serious. Pass the cheat sheets! nb From tarun.kap at gmail.com Fri May 2 16:35:30 2008 From: tarun.kap at gmail.com (TkNeo) Date: Fri, 2 May 2008 13:35:30 -0700 (PDT) Subject: list.index crashes when the element is not found References: <491f6$481b6455$547@news.teranews.com> <18cd9b76-91e7-4830-af75-cc9c97536347@d45g2000hsc.googlegroups.com> <858f0130-2d19-4429-8f80-346aa5cc7c9f@r66g2000hsg.googlegroups.com> Message-ID: <8667e17a-705c-4984-af05-4ba59d2dd26d@m3g2000hsc.googlegroups.com> On May 2, 3:09 pm, George Sakkis wrote: > On May 2, 3:04 pm, TkNeo wrote: > > > > > On May 2, 1:58 pm, Nick J Chackowsky > > wrote: > > > > TkNeo wrote: > > > > WHAT ? > > > > > This is crazy > > > > Crazy like a fox? > > > > a = [1, 2, 3] > > > try: > > > a.index(99) > > > except: > > > a.append(99) > > > finally: > > > print a.index(99) > > > > MY question: which exception should I actually be catching there? > > > ** Posted fromhttp://www.teranews.com** > > > ofcouse try catch is going to work but in ideality the index function > > should return a -1 and no way in hell crash. > > Please refrain from making such inane comments after an hour or two of > toying with a new language. Read a good tutorial first (e.g.http://diveintopython.org/toc/index.html) and come back if you have a > real question. > > George George - I am not trying to be negative in any way whatsoever. 0 - In my first post in this thread, i was just being sarcastic. 1- I have been using python for more than an year or so. Just not an avid user as probably you are. 2. You suggest me to ask a "REAL" question. Real is a relative word. What is real to you might not be real to lets say Guido van Rossum. I met him a few months ago and he was very humble to all the stupid questions i had. 3 The board does not specify the level of python developers who can post questions. 4 -I have always heard that python community is based on sharing and helping each other. Please keep those spirits up. Thanks for replying and sorry for wasting your time. TK From maehhheeyy at gmail.com Thu May 1 16:06:20 2008 From: maehhheeyy at gmail.com (maehhheeyy) Date: Thu, 1 May 2008 13:06:20 -0700 (PDT) Subject: i want to add a timeout to my code References: <53ffe104-be3b-43e2-b5c8-4ce5886ac60d@b1g2000hsg.googlegroups.com> <1f70ea43-7909-4bd8-b63d-2467e8a0542f@c65g2000hsa.googlegroups.com> Message-ID: <2976bcad-e514-4a33-bf1a-5966997b6d42@1g2000prg.googlegroups.com> On Apr 29, 3:29?pm, John Krukoff wrote: > On Tue, 2008-04-29 at 14:47 -0700, maehhheeyy wrote: > > On Apr 17, 4:24 pm, Miki wrote: > > > On Apr 17, 1:10 pm,maehhheeyy wrote: > > > > > I want to add a timeout so that when I pull out my gps from my serial > > > > port, it would wait for a bit then loop and then see if it's there. I > > > > also want to add a print statement saying that there is no GPS device > > > > found. However when I run my code and unplug my serial port, my code > > > > will just hang until I plug it back in. > > > > This is my code right now: > > > > > def GetGPS(): > > > > ? ? ? data = [] > > > > ? ? ? #Open com1: 9600,8,N,1 > > > > ? ? ? fi = serial.Serial(0, timeout = 1) > > > > ? ? ? print '[gps module] SERIAL PORT OPEN ON COM1:' > > > > > can anyone help me please? Thanks. > > > >http://docs.python.org/lib/node545.html > > > > HTH, > > > -- > > > Miki http://pythonwise.blogspot.com > > > I tried the code onto my codes but what came out was that in the line > > signal.signal(signal.SIGSLRM, handler), an attributeError appeared > > reading that 'module' object has no attribute 'SIGALRM' > > -- > >http://mail.python.org/mailman/listinfo/python-list > > Are you writing your program on windows, or some other platform which is > not unix? > > -- > John Krukoff > Land Title Guarantee Company- Hide quoted text - > > - Show quoted text - Yeah I'm using Windows 2000. From banibrata.dutta at gmail.com Sat May 3 05:28:26 2008 From: banibrata.dutta at gmail.com (Banibrata Dutta) Date: Sat, 3 May 2008 14:58:26 +0530 Subject: Newbie question - probably FAQ (but not exactly answered by regular FAQ) Message-ID: <3de8e1f70805030228y33b081faoa56fd251d48a3ae8@mail.gmail.com> Hi, I've gone through the list of "language differences" between 2.3 / 2.4 & 2.5 of CPython. I've spend around 2 weeks now, learning v2.5 of CPython, and I consider myself still very very newbie. So, unable to take a call as to how-important or desirable the newer language features are -- so whether to write my app for v2.5 of Python, versus, as few others on this list have recommended, i.e. to stick to v2.3 ?? Are the preformance improvements, and memory footprint / leak fix in 2.5 enough to justify moving to it ? What all do I stand to lose (or gain) by writing on v2.3 ?? I've a constraint due to which I might have to also write parts of my app (client side) in Jython (because I want to eventually ship Java -- yet benefit from the rapid development and clarity of Python). Would sticking to v2.3 in such a case be a better idea ? Suggestions with reasoning would be very helpful. -- regards, Banibrata http://www.linkedin.com/in/bdutta From gagsl-py2 at yahoo.com.ar Sat May 17 01:33:13 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 17 May 2008 02:33:13 -0300 Subject: Classmethods are evil References: Message-ID: En Sat, 17 May 2008 01:01:50 -0300, Ivan Illarionov escribi?: > After re-reading "Python is not Java" I finally came to conclusion that > classmethods in Python are a very Bad Thing. > > I can't see any use-case of them that couldn't be re-written more clearly > with methods of metaclass or plain functions. A good use case for class methods are alternate constructors, like dict.from_keys. I don't think an alternate constructor would be more clear being a method of the metaclass - actually it belongs to the class itself, not to its metaclass. Metaclass methods are harder to find; they don't show in dir(instance) nor dir(class). Also the resolution order is harder to grasp for metaclasses - but this may be just lack of usage from my part... > They have the following issues: > 1. You mix instance-level and class-level functionality in one place > making your code a mess. Not necesarily; some classmethods are naturally tied to the class itself, not to the metaclass (like the constructor example above). But yes, *some* classmethods could be written as methods of their metaclass instead - but that doesn't always make sense. > 2. They are slower than metaclass methods or plain functions. Hu? How did you come to that? I've done a small test and a class method wins by a very minuscule but consistent advantage over a metaclass method: class A(object): color = "red" @classmethod def foo(cls, x): return getattr(cls, x) class MetaB(type): def foo(self, x): return getattr(self, x) class B(object): __metaclass__ = MetaB color = "red" C:\TEMP>python -m timeit -s "from meta3 import A,B;a,b=A(),B()" "A.foo('color')" 1000000 loops, best of 3: 1.19 usec per loop C:\TEMP>python -m timeit -s "from meta3 import A,B;a,b=A(),B()" "B.foo('color')" 1000000 loops, best of 3: 1.2 usec per loop -- Gabriel Genellina From george.sakkis at gmail.com Sat May 31 10:40:15 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Sat, 31 May 2008 07:40:15 -0700 (PDT) Subject: How to add function return value References: <28e0c835-4ed7-4571-ab69-a90cec4efc08@f24g2000prh.googlegroups.com> <7d89a189-1ce9-46d3-b200-2ad86858fa45@h1g2000prh.googlegroups.com> Message-ID: On May 30, 10:16?pm, Raymond Hettinger wrote: > On May 30, 6:21?pm, HYRY wrote: > > > Can I write a decorator that it can automately do this conversion > > > def func1() > > ? ? a = 1 > > > ---> > > > def func1(): > > ? ? a = 1 > > ? ? return locals() > > Not sure why you would want to do this, but there are several ways. > > 1. Make bytecode hack decorator that transforms the final "return > None" into "return locals()". ?A recipe that shows the basic technique > is at:http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/277940 > > 2. Retrieve the source using inspect.getsourcelines(f). Then, append a > "return locals()" to the end of the function and run it through exec. > > 3. Try hacking a tracing/debugging utility. > > 4. Run the sourcefile through tokenize, make the appropriate > insertion, and then untokenize. Here's an illustration of (3): import sys import functools def withlocals(f): @functools.wraps(f) def wrapper(*args, **kwds): f_locals = {} def probe(frame, event, arg): if event == 'return': f_locals.update(frame.f_locals) return probe sys.settrace(probe) try: res = f(*args,**kwds) finally: sys.settrace(None) return (res, f_locals) return wrapper # example @withlocals def foo(x, y=0, *args, **kwds): a = max(x,y) b = len(args) c = min(kwds.values()) return a+b+c r,locs = foo(1,2,3,4,a=5,b=6) print locs George From marco_furchi at hotmail.com Tue May 20 03:57:29 2008 From: marco_furchi at hotmail.com (marco furchi) Date: Tue, 20 May 2008 09:57:29 +0200 Subject: fafdasf Message-ID: asdfdg -------------- next part -------------- An HTML attachment was scrubbed... URL: From ivan.illarionov at gmail.com Sat May 17 05:50:19 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Sat, 17 May 2008 09:50:19 +0000 (UTC) Subject: Classmethods are evil References: Message-ID: On Sat, 17 May 2008 02:33:13 -0300, Gabriel Genellina wrote: > En Sat, 17 May 2008 01:01:50 -0300, Ivan Illarionov > escribi?: > >> After re-reading "Python is not Java" I finally came to conclusion that >> classmethods in Python are a very Bad Thing. >> >> I can't see any use-case of them that couldn't be re-written more >> clearly with methods of metaclass or plain functions. > > A good use case for class methods are alternate constructors, like > dict.from_keys. I don't think an alternate constructor would be more > clear being a method of the metaclass - actually it belongs to the class > itself, not to its metaclass. > Metaclass methods are harder to find; they don't show in dir(instance) > nor dir(class). > Also the resolution order is harder to grasp for metaclasses - but this > may be just lack of usage from my part... > >> They have the following issues: >> 1. You mix instance-level and class-level functionality in one place >> making your code a mess. > > Not necesarily; some classmethods are naturally tied to the class > itself, not to the metaclass (like the constructor example above). But > yes, *some* classmethods could be written as methods of their metaclass > instead - but that doesn't always make sense. > >> 2. They are slower than metaclass methods or plain functions. > > Hu? How did you come to that? > I've done a small test and a class method wins by a very minuscule but > consistent advantage over a metaclass method: > > class A(object): > color = "red" > > @classmethod > def foo(cls, x): > return getattr(cls, x) > > class MetaB(type): > def foo(self, x): > return getattr(self, x) > > class B(object): > __metaclass__ = MetaB > color = "red" > > C:\TEMP>python -m timeit -s "from meta3 import A,B;a,b=A(),B()" > "A.foo('color')" > 1000000 loops, best of 3: 1.19 usec per loop > > C:\TEMP>python -m timeit -s "from meta3 import A,B;a,b=A(),B()" > "B.foo('color')" > 1000000 loops, best of 3: 1.2 usec per loop How did I come to this: http://code.djangoproject.com/changeset/7098 I measured this and there was a marginal speed increase when classmethods wher moved to metaclass. -- Ivan From mail at timgolden.me.uk Thu May 22 11:37:45 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 22 May 2008 16:37:45 +0100 Subject: Showing the method's class in expection's traceback In-Reply-To: <15ce3e4e-c98c-4ee6-bb5f-caf2cf0d69cf@i76g2000hsf.googlegroups.com> References: <79c7d6fb-a6b8-481f-9a36-81b980628710@59g2000hsb.googlegroups.com> <69bi20F31j4kdU1@mid.uni-berlin.de> <483406a0$0$10773$426a74cc@news.free.fr> <6a8c7499-7d8c-4d5d-9ea6-a3e1ba2f9565@c58g2000hsc.googlegroups.com> <48353a94$0$12639$426a74cc@news.free.fr> <15ce3e4e-c98c-4ee6-bb5f-caf2cf0d69cf@i76g2000hsf.googlegroups.com> Message-ID: <48359349.3090501@timgolden.me.uk> Agustin Villena wrote: > I don't see things like you, because I'm accustomed to design my > software > though classes and see the code in an "object = software's functional > atom/component" way > I agree that python's dynamic nature make things complicated here, but > for me it its just > an implementation problem derived of the recent OOP support of python (laughs). I do hope you're either joking or wearing a flameproof suit. Python's dynamic nature as an implementation problem. Hmmm.. And what's that about "recent" OOP support of Python? Oh well... TJG From sophacles at gmail.com Mon May 12 13:59:02 2008 From: sophacles at gmail.com (Erich) Date: Mon, 12 May 2008 10:59:02 -0700 (PDT) Subject: Learning Python for no reason References: <0383f3b8$0$27282$c3e8da3@news.astraweb.com> Message-ID: <5c63d29d-a452-4831-aa68-4b8831f9e71d@s50g2000hsb.googlegroups.com> On May 12, 12:27 pm, "John Salerno" wrote: > The *process* of learning is enough fun for me, and every now and then I do > find a small use for Python that really pays off, but for the most part I'm > wondering what people's thoughts are as far as simply learning it for the > sake of learning. Does it seem like a silly endeavor to most people? Did > anyone here learn a programming language when you didn't need to? If so, how > much and in what capacity did you use it after you learned it? > I am of the belief that there is no such thing as "useless learning", or "bad learning"*. I have found that the more I learn about anything, the better I am at everything. I think this is because more knowledge/ understanding does: 1. gives me more 'entry points' for new knowledge, I can relate more bits to something I know, making the whole learning process easier. 2. allows me to better relate to people who I need to communicate with, becuase it is more likely there is a common point of knowledge/ interest to build from 3. gives me personal satisfaction in my life (self-actualization). When I learned python, I was a bartender, and was just learning it for fun. Only later did I become a computer programmer. I was lucky enough to find a job where I get to do a lot of my work in python. * There are times when learning new info set A is more productive than new info set B, depending on other constraints of time, energy, money, etc, B could be classified as "unwise learning" Regards, Erich From maxwell.newlands at gmail.com Thu May 15 16:00:34 2008 From: maxwell.newlands at gmail.com (max) Date: Thu, 15 May 2008 13:00:34 -0700 (PDT) Subject: no inputstream? References: <87lk2ba4b4.fsf@mulj.homelinux.net> Message-ID: <8d566db4-c626-491f-82e4-303308c5b8da@25g2000hsx.googlegroups.com> you're right, my java implementation does indeed parse for Id3v2 (sorry for the confusion). i'm using the getrawid3v2() method of this bitstream class (http://www.javazoom.net/javalayer/docs/docs0.4/ javazoom/jl/decoder/Bitstream.html) to return an inputstream that then i buffer and parse. apologies if i misrepresented my code! back to python, i wonder if i'm misusing the mutagen id3 module. this brief tutorial (http://www.sacredchao.net/quodlibet/wiki/Development/ Mutagen/Tutorial) leads me to believe that something like this might work: from mutagen.mp3 import MP3 id3tags = MP3(urllib2.urlopen(URL)) but this gives me the following TypeError: "coercing to Unicode: need string or buffer, instance found". does this mean i need to convert the "file-like object" that is returned by urlopen() into a unicode object? if so, do i just decode() with 'utf-8', or is this more complex? as of now, doing so gives me mostly "No such file or directory" errors, with a few HTTP 404s. anyway, thanks again.... On May 15, 1:02?pm, Hrvoje Niksic wrote: > "John Krukoff" writes: > > I'd love to know how Java handles all that automatically through a > > generic stream interface, though. > > It could be that their stream interface supports seek(), and that > seek()ing on HTTP connection sends the appropriate range request and, > if it fails, throws an appropriate exception which the client code > interprets as "seeking impossible, read the whole file". > > But that doesn't apply to the InputStream interface described athttp://java.sun.com/j2se/1.5.0/docs/api/java/io/InputStream.html-- no > seeking there. From paul at science.uva.nl Wed May 7 03:29:04 2008 From: paul at science.uva.nl (Paul Melis) Date: Wed, 07 May 2008 09:29:04 +0200 Subject: PEP 370 question Message-ID: In (the recently accepted) PEP 370 it says "Current Python versions don't have a unified way to install packages into the home directory of a user (except for Mac Framework builds). Users are either forced to ask the system administrator to install or update a package for them or to use one of the many workarounds like Virtual Python [1], Working Env [2] or Virtual Env [3]. [...] The feature can't be implemented using the environment variable PYTHONPATH. The env var just inserts a new directory to the beginning of sys.path but it doesn't parse the pth files in the directory. A full blown site-packages path is required for several applications and Python eggs." I'm confused. For years I've been installing packages and extension modules locally using distutils's --prefix option, e.g. using python setup.py install --prefix=$HOME/local Together with adding $HOME/local/lib/python2.4/site-package to my PYTHONPATH this works fine, even if there are packages that require a .pth file to work or that use Eggs (like setuptools and pygments). So what limitation does the quoted paragraph in the PEP refer to? Regards, Paul From vivainio at gmail.com Thu May 15 09:30:51 2008 From: vivainio at gmail.com (Ville M. Vainio) Date: Thu, 15 May 2008 13:30:51 GMT Subject: datamining .txt-files, library? References: <8ab6802f-ac2c-4492-b793-704126567a8e@a1g2000hsb.googlegroups.com> <96f60dc3-fe60-45fa-befe-70d7ae5a330a@d77g2000hsb.googlegroups.com> Message-ID: <87ve1fd78z.fsf@gmail.com> Chris writes: > On May 15, 2:27?pm, globalrev wrote: >> i have a big collection of .txt files that i want to open and parse to >> extract information. >> >> is there a library for this or maybe even built in? > > os.open to open the files and iterate through it and built in string > functions to parse it. Or more probably, regular expression library "re". From max at alcyone.com Tue May 6 05:18:10 2008 From: max at alcyone.com (Erik Max Francis) Date: Tue, 06 May 2008 02:18:10 -0700 Subject: Decimal vs Float comparasion In-Reply-To: References: Message-ID: Dennis Lee Bieber wrote: > On Tue, 6 May 2008 11:52:10 +0800, "Yuan HOng" > declaimed the following in comp.lang.python: > >> It seems to me that rather than allowing this to happen, comparasion >> between the two should either be made correct (by convertion decimal >> to float e.g.) or forbidden, like arithmatic operations between the >> two types. > > Why should decimal be coerced to float? Maybe float should be > coerced to decimal? > > Or... the programmer should explicitly specify what comparison is > wanted -- if any... > > Or... Isn't Python 3.x supposed to forbid mixed type comparisons > unless the types implement suitable handling? Bottom line is that it shouldn't silently return something insane. 99999.0 is surely exactly representable in any modern floating point system, being a floating point representing of an integer, so silently returning a completely invalid comparison is a tremendously bad idea. It's a bug. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis Can I walk with you / 'Till the day that the world stops turning -- India Arie From ankitanand1986 at gmail.com Wed May 28 07:48:53 2008 From: ankitanand1986 at gmail.com (Ankit) Date: Wed, 28 May 2008 04:48:53 -0700 (PDT) Subject: Flash Decoder References: <860bf237-18d3-4949-a26d-97becafb27c8@i36g2000prf.googlegroups.com> <6a4rtbF35ut5sU1@mid.uni-berlin.de> Message-ID: <0c0ea160-89d6-4827-8d54-d0029d064c71@w5g2000prd.googlegroups.com> Thanks for replying guys but could you be a little more specific like in terms of steps i shd follow to make the decoder and also how is ffmpeg/libffmpeg going to help.. Regards Ankit Anand From kar1107 at gmail.com Fri May 2 01:11:09 2008 From: kar1107 at gmail.com (Karthik Gurusamy) Date: Thu, 1 May 2008 22:11:09 -0700 (PDT) Subject: help with list comprehension References: Message-ID: <7d00b02d-fe6b-4684-9197-5e1a7d2f5fef@y18g2000pre.googlegroups.com> On May 1, 8:01 pm, Yves Dorfsman wrote: > In the following script, m1() and m2() work fine. I am assuming m2() is > faster although I haven't checked that (loops through the list twice instead > of once). > > Now what I am trying to do is something like m3(). As currently written it > does not work, and I have tried different ways, but I haven't managed to > make it work. > > Is there a possibility ? Or is m2() the optimum ? > > Thanks. > > #!/usr/bin/python > > l = [ { 'colour': 'black', 'num': 0}, > { 'colour': 'brown', 'num': 1}, > { 'colour': 'red', 'num': 2}, > { 'colour': 'orange', 'num': 3}, > { 'colour': 'yellow', 'num': 4}, > { 'colour': 'green', 'num': 5}, > { 'colour': 'blue', 'num': 6}, > { 'colour': 'violet', 'num': 7}, > { 'colour': 'grey', 'num': 8}, > { 'colour': 'white', 'num': 9} > ] > > def m1(): > colours = [ e['colour'] for e in l ] > nums = [ e['num'] for e in l ] > > def m2(): > colours = [] > nums = [] > for e in l: > colours.append(e['colour']) > nums.append(e['num']) > > #def m3(): > # colours, nums = [ e['colour'], e['num'] for e in l ] > Looks like m1 is the cleanest; if you really want to run list- comprehension once, one possible way: >>> p = [ (e['colour'], e['num']) for e in l ] >>> import operator >>> map(operator.itemgetter(0), p) ['black', 'brown', 'red', 'orange', 'yellow', 'green', 'blue', 'violet', 'grey', 'white'] >>> map(operator.itemgetter(1), p) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> Karthik > -- > Yves.http://www.SollerS.ca From kamhung.soh at gmail.com Fri May 9 18:25:27 2008 From: kamhung.soh at gmail.com (Kam-Hung Soh) Date: Sat, 10 May 2008 08:25:27 +1000 Subject: anagram finder / dict mapping question References: <0ebda682-6c99-43b2-b88b-80f6c88e1c98@p25g2000hsf.googlegroups.com> <54f75240-d8ee-482c-baea-d37bf3900b76@i36g2000prf.googlegroups.com> Message-ID: On Sat, 10 May 2008 07:19:38 +1000, wrote: >> > What would be the best method to print the top results, the one's that >> > had the highest amount of anagrams?? Create a new histogram dict? >> >> You can use the max() function to find the biggest list of anagrams: >> >> top_results = max(anagrams.itervalues(), key=len) >> >> -- >> Arnaud > > That is the biggest list of anagrams, what if I wanted the 3 biggest > lists? Is there a way to specific top three w/ a max command?? > Built-in max() function only returns one result. My solution is to make a sorted list and return last three items: sorted((len(anagrams[key]), key) for key in anagrams.keys())[-3:] -- Kam-Hung Soh Software Salariman From yves at zioup.com Sun May 11 18:32:54 2008 From: yves at zioup.com (Yves Dorfsman) Date: Sun, 11 May 2008 22:32:54 GMT Subject: How to call a file In-Reply-To: References: Message-ID: Gary Herron wrote: > First of all, some terminology: You are not *calling* a file, you are > *opening* it or reading. Wouldn't it be more correct to say that, in python, you either create a file object, or call a method for that object, once the object has been created ? Yves. From wuwei23 at gmail.com Wed May 21 21:40:08 2008 From: wuwei23 at gmail.com (alex23) Date: Wed, 21 May 2008 18:40:08 -0700 (PDT) Subject: HTMLParser error References: <628d3bbf-0fd9-4075-9749-6c8c81f887fa@z72g2000hsb.googlegroups.com> <1aecdaeb-76f1-4a57-88d3-2023dd6e00e4@e39g2000hsf.googlegroups.com> <06ba6753-712e-4c1c-8d2f-c1fd075ed0cf@u6g2000prc.googlegroups.com> <10f12f0c-d08e-41e1-ab6f-10488ae51010@p25g2000pri.googlegroups.com> <42323d1c-9a10-4030-8870-75ed2d10a31e@b64g2000hsa.googlegroups.com> Message-ID: On May 22, 8:18 am, jonbutle... at googlemail.com wrote: > Sorry, im new to both python and newsgroups, this is all pretty > confusing. So I need a line in my __init__ function of my class? The > spider class I made inherits from HTMLParser. Its just using the > feed() function that produces errors though, the rest seems to work > fine. Let me repeat: it would make this a lot easier if you would paste actual code. As you say, your Spider class inherits from HTMLParser, so you need to make sure that you set it up correctly so that the HTMLParser functionality you've inherited will work correctly (or work as you want it to work). If you've added your own __init__ to Spider, then the __init__ on HTMLParser is no longer called unless you *explicitly* call it yourself. Unfortunately, my earlier advice wasn't totally correct... HTMLParser is an old-style object, whereas super() only works for new-style objects, I believe. (If you don't know about old- v new-style objects, see http://docs.python.org/ref/node33.html). So there are a couple of approaches that should work for you: class SpiderBroken(HTMLParser): def __init__(self): pass # don't do any ancestral setup class SpiderOldStyle(HTMLParser): def __init__(self): HTMLParser.__init__(self) class SpiderNewStyle(HTMLParser, object): def __init__(self): super(SpiderNewStyle, self).__init__() Python 2.5.1 (r251:54863, May 1 2007, 17:47:05) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> html = open('temp.html','r').read() >>> from spider import * >>> sb = SpiderBroken() >>> sb.feed(html) Traceback (most recent call last): File "", line 1, in File "C:\Python25\lib\HTMLParser.py", line 107, in feed self.rawdata = self.rawdata + data AttributeError: SpiderBroken instance has no attribute 'rawdata' >>> so = SpiderOldStyle() >>> so.feed(html) >>> sn = SpiderNewStyle() >>> sn.feed(html) >>> The old-style version is probably easiest, so putting this line in your __init__ should fix your issue: HTMLParser.__init__(self) If this still isn't clear, please let me know. - alex23 From dstromberglists at gmail.com Sun May 11 15:44:09 2008 From: dstromberglists at gmail.com (Dan Stromberg) Date: Sun, 11 May 2008 19:44:09 GMT Subject: diffing and uniqing directories References: Message-ID: On Sat, 26 Apr 2008 23:44:17 +0530, Rustom Mody wrote: > Over years Ive collected tgz's of my directories. I would like to diff > and uniq them > > Now I guess it would be quite simple to write a script that does a walk > or find through a pair of directory trees, makes a SHA1 of each file and > then sorts out the files whose SHA1s are the same/different. What is > more difficult for me to do is to write a visual/gui tool to help me do > this. > > I would guess that someone in the python world must have already done it > [The alternative is to use some of the tools that come with version > control systems like git. But if I knew more about that option I would > not be stuck with tgzs in the first place ;-)] > > So if there is such software known please let me know. > > PS Also with the spam flood that has hit the python list I dont know if > this mail is being read at all or Ive fallen off the list! It doesn't have a GUI, but here's a python program I wrote for dividing large collections of files up into identical groups: http://stromberg.dnsalias.org/~strombrg/equivalence-classes.html From tjreedy at udel.edu Mon May 12 19:21:41 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 12 May 2008 19:21:41 -0400 Subject: Is using range() in for loops really Pythonic? References: <482657ca$0$25026$607ed4bc@cv.net><41078222-aec0-4e8b-8a1f-945cdf814498@m73g2000hsh.googlegroups.com><48275446$0$11628$607ed4bc@cv.net> <87mymw8nr0.fsf@benfinney.id.au> <87iqxk6nvs.fsf@benfinney.id.au> <877ie06kdl.fsf@benfinney.id.au> Message-ID: "Ben Finney" wrote in message news:877ie06kdl.fsf at benfinney.id.au... | So, when not using the values that come from the controlling iterator, | it's good to make that explicit. If Python supported it, we might | prefer to use no name at all for something that isn't used, but the | 'for' syntax doesn't allow that. But I presume it could if [target 'in'] were optional. for range(n): It is possible this has been proposed and rejected, but I have no specific memory. tjr From castironpi at gmail.com Thu May 8 19:56:12 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 8 May 2008 16:56:12 -0700 (PDT) Subject: RELEASED Python 2.6a3 and 3.0a5 References: Message-ID: On May 8, 6:50?pm, Barry Warsaw wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > On behalf of the Python development team and the Python community, I ? > am happy to announce the third alpha release of Python 2.6, and the ? > fifth alpha release of Python 3.0. > > Please note that these are alpha releases, and as such are not ? > suitable for production environments. ?We continue to strive for a ? > high degree of quality, but there are still some known problems and ? > the feature sets have not been finalized. ?These alphas are being ? > released to solicit feedback and hopefully discover bugs, as well as ? > allowing you to determine how changes in 2.6 and 3.0 might impact > you. ?If you find things broken or incorrect, please submit a bug ? > report at > > ? ?http://bugs.python.org > > For more information and downloadable distributions, see the Python > 2.6 website: > > ? ?http://www.python.org/download/releases/2.6/ > > and the Python 3.0 web site: > > ? ?http://www.python.org/download/releases/3.0/ > > These are the last planned alphas for both versions. ?If all goes ? > well, next month will see the first beta releases of both, which will ? > also signal feature freeze. ?Two beta releases are planned, with the ? > final releases scheduled for September 3, 2008. > > See PEP 361 for release details: > > ? ? ?http://www.python.org/dev/peps/pep-0361/ > > Enjoy, > - -Barry > > Barry Warsaw > ba... at python.org > Python 2.6/3.0 Release Manager > (on behalf of the entire python-dev team) > > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.8 (Darwin) > > iQCVAwUBSCORrnEjvBPtnXfVAQIK+QQAgEUtAvW7uo0BxMiT1bCAo2E9ZecWJ9xe > DBgd/5IK8moITkqhqGAH5UvfytV6uPkOMgGIS/Uvk4hzhU3jwSopEIDJLFQ5nGtC > lCzOHzkDjSNZ8Q2OOAI9mbSHY8grvVxCMB4X2SVXIEMZ6M/X1AcV2b0utp9O1w/l > T/PEvP8U1uY= > =2Tnb > -----END PGP SIGNATURE----- Does signal freeze signal signal freeze? Or should ideas pend beta? From banibrata.dutta at gmail.com Fri May 9 09:23:26 2008 From: banibrata.dutta at gmail.com (Banibrata Dutta) Date: Fri, 9 May 2008 18:53:26 +0530 Subject: Pythonwin In-Reply-To: <11c8a80e-41bb-4cea-88d6-c9515e1a9d13@j22g2000hsf.googlegroups.com> References: <11c8a80e-41bb-4cea-88d6-c9515e1a9d13@j22g2000hsf.googlegroups.com> Message-ID: <3de8e1f70805090623vbca5677pce3317a1dd39428@mail.gmail.com> if one has installed ActiveState Python 2.5, I think it'd have been Start Menu --> Programs --> ActiveSte ActivePython 2.5 --> and I think it delivers IDLE, not PythonWin. On 5/9/08, Mike Driscoll wrote: > > On May 9, 5:30 am, Clive_S wrote: > > Hi > > > > I am trying to use Python with ArcGIS. > > > > I have installed Python 2.4. I have an icon for IDLE and command line. > > I do not see Python PythonWin. > > > > How do you install or launch pythonwin?? > > > > Thanks > > > > Clive > > I have PythonWin installed in my Start Menu --> Programs --> Python > 2.5. I may have installed the ActiveState version though. Just check > if it's there on your system and if not, you can follow Niklas's > advice. > > Mike > > -- > http://mail.python.org/mailman/listinfo/python-list > -- regards, Banibrata http://www.linkedin.com/in/bdutta http://octapod.wordpress.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From inhahe at gmail.com Sun May 18 03:42:58 2008 From: inhahe at gmail.com (inhahe) Date: Sun, 18 May 2008 03:42:58 -0400 Subject: morning in Python References: <409ea9f1-9774-4bf2-abac-2daf997bc97f@c65g2000hsa.googlegroups.com> Message-ID: What advantages do teams have? in what? over who? when? If they have any use at all, what language is good for them? How do programming teams interact? It sounds fun. I'm not sure I want to get work done so much as talk, but programming is fun. -the advantages of teams in general is the organization of effort. -with 10 people doing 10 things in their own individually chosen -directions, you get 10 little things done. with 10 people doing 10 -things in a team, you get 1 big thing done that's 10 times as large. -(some things that can be done can only be done as big things; i.e -not everything is scalar in a practical sense). and that's not even -including synergy. perhaps i should have said, the "coalition -/coalescence" of effort, as the organization of it is a different -matter. that's a harder animal to tackle. it also applies to -computing itself. why is programming useful? because of its -organization. why is a CPU useful? because of its organization. -why is an organization useful? why are systems effective? is the -universe a system? is it thusly a matter of reciprocality? (as -affected and affecter are two sub-systems of the universe) -a team's advantage is in accomplishing a goal that all members -agree to accomplish. this may involve compromising on their -own goals just enough to do something close but similar that can -actually get done. but it gets more complex than that as a lot of -people join programming teams to make money and put bread on -the table. the economy becomes the team. and then you get into -game theory and realize that sometimes just because a system -falls into a certain order doesn't mean it's the most mutually -beneficial way of doing things. -a programming team wouldn't have an advantage "over" -somebody unless it's a competing company. but then those -companies also have teams so it wouldn't be having a team -per se that gives an advantage "over" them. although teams -of programmers would have advantage over every would-be -single programmer that would want to program a competing -product. but do those people even count? they're not in the -arena. -even with a programming team, what language to use depends on -what the goal is. although it also depends on the preconceptions -of ill-informed higher-ups. i'm not prepared to say, though, that -some programming languages aren't more amenable to -team-work than others. I'd start to discuss state property in appertanance to city property. What are some properties of the state? -what states have more than cities: power. universality. levels of -beaurocracy. global relevance. size. superordination. time. You would have to introduce a computer to a (finite?) way of expressing language, provided it *expresses* at rates over time that do not exceed its input (impression), and limited by the complexity bound of the architecture. Tangent: architecture complexity. -hmm. expression vs. impression rates represents symmetry in flow. -conservation of information. complexity of architecture is static. -so i wonder what dimension that affects. the only thing I can think of -is that regardless of your flow control if your architecture is too -simple then people will realize that it's not sentient. they may realize -that anyway but they'd be less entertained. basically, your computer -would be less effective at achieving its goals in a complex arena. but -not all arenas are complex. (people are, yes.) In order to recreate 'propositional knowledge', you have to tell it. Accumulating could amount to hashing video feed over time. What do you know about what's on the screen? Naturally, as symbols are logical, the video would have to be of something you want from it, even if it's high spirits. -i don't fully understand this logic and i don't fully agree with it so i -won't comment. I am less concerned about the audio, but maybe video is just one way of learning. What information do the mic inputs convey from a spoken voice? (And how do you summarize that?) -it's probably easier to gather information from audio. but then you can -gather more at a time from video (with more holistic requirements). but -then if you're measuring how much you can gather per byte of input -stream (thus putting 'at a time' into the von neuman computing arena or -perhaps bandwidth allowance) then it's hard to say (as video requires -more bytes per sense-time). -to summarize, mic inputs convey a) one's voice (it's part of why people -fall in love..), b) words and sentences; semantic content; formal -(or informal) facts (already in propositional form) (depending on the -the theoretical limits for AI speech recognition), c) intonation and emphasis -of those words (largely requires understanding of the psyche for -interpretation). but i'm not going to say that a computer can necessarily -understand psyche (or one's voice); it's cosmic. -also, words can express facts from anywhere at any time. video -expresses an event or a state at one particular place at one -one particular time. so, even though the facts of words are -compressed (assimilated semiotically, symbolic, serialized), they can -give you a lot more factual context on a global scale with which -to understand the behavior of people everywhere, and moreso their -words, such as the words in this newsgroup, which you like to participate in. And what results are on video summaries are there so far? I would start with difference primitives on video. How does the same work for voice? -i don't understand the last two sentences. -as for video you should understand solidity, classical mechanics and -perspective to get some sort of objectivity in its interpretation. perhaps -color also. (the next higher level of contextual understandig/objectivity -can only come from words and/or the "cross-sum" of countless videos. -try an encyclopedia.) Of course, human understanding may come across the difference in form of artifacts of hardware, but of course, the crossing operation is non- trivial to perform, audio and video. I'm not mentioning smell because crossing it sounds risky. Whaddya know. -risky? interesting. how would you get smell input anyway? Now creation and recreation *decompose* into creation and time, spec. real iteration., but where I'm from, creation and time are known to cross means; if I have inferred correctly so far, you want a computer to recreate. If so, you want creation in act to tell a story. I think it's more fun to make them up than tell computers, and if we're by them, can we tell a story on a newsgroup? Who understands best in the cross-sum of { Newsgroup, Newsgroup + task, Computer }? Who wants to define cross-sum? -you're the only one fusing newsgroups and computers. and i'm the only -one that's paying attention, so i guess the answer is either you, or I. -you're asking /us/ to define cross-sum? suspiciously flippant. ;) --- To those who don't want me to feed the bot, I'm sorry. It's not a bot, and I don't know the policy on having philosophical conversations. From lixinyi.23 at gmail.com Thu May 29 02:47:29 2008 From: lixinyi.23 at gmail.com (lixinyi.23 at gmail.com) Date: Wed, 28 May 2008 23:47:29 -0700 (PDT) Subject: How to get all the variables in a python shell Message-ID: Hi! I'm currently working on a scientific computation software built in python. What I want to implement is a Matlab style command window <-> workspace interaction. For example, you type 'a=1' in the command window, and you see a list item named 'a' in the workspace. You double click the icon of the item, and you see its value. You can modify the value of the list item, 1 -> 100 etc, after which if you go back to the command window and type 'a' and press enter, you see that varable a's value has been changed to 100. So my question is : if you have two DOS command windows running under WINDOWS OS, how can you make them share the same internal variable buffer? Or is there any easier way to implement such kind of interaction? Maybe I could just build a small database to store all the values and access them from both programs, but chances are sometimes I have to deal with big arrays, and they will eat extra memory if I keep them in a database. Is there anyway to access a shell's local memory buffer? I tried to use shell.interp.locals() in wxPython, but there's too many variables in the list which I don't actually need. Come on guys, give me some ideas. Thanks in advance! From duncan.booth at invalid.invalid Fri May 30 03:27:33 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 30 May 2008 07:27:33 GMT Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <94bac166-d13c-44dd-af84-db19e19488b8@w1g2000prd.googlegroups.com> <8cfd3523-8d16-40bc-b904-94a6a36a414d@p25g2000pri.googlegroups.com> <5c98049e-e62e-4ab1-afed-b0a3e186bd05@w1g2000prd.googlegroups.com> <3dd6fa95-e9fe-4922-a46d-020cf9263469@w4g2000prd.googlegroups.com> Message-ID: "D'Arcy J.M. Cain" wrote: > I guess I am still new to this group and don't understand its charter. > I wasn't aware that it was a Flaming Blunder group. Can someone please > point me to a newsgroup or mailing list dedicated to the Python > programming language? > A minor point of netiquette: it's fine to reply by email to a message if you want to make a point off group, but if you are following up to the newsgroup/mailing list please don't CC the original sender: they will see the message in any case on the newsgroup and getting it twice is just likely to annoy. I don't understand your problem: it's just a single thread so killfile or skip it. -- Duncan Booth http://kupuguy.blogspot.com From kapoornir at gmail.com Mon May 5 20:23:07 2008 From: kapoornir at gmail.com (Rakhi) Date: Mon, 5 May 2008 17:23:07 -0700 (PDT) Subject: Python Programmer position available in New York Message-ID: <62503df2-3e7e-43b7-8900-71bea747ee0b@f24g2000prh.googlegroups.com> Title: Python Programmer Location: Orangeburg, NY 10962 6 months position Roles and responsibilities:- ? Designs and codes from specifications, analyzes, evaluates, tests, debugs, documents, and implements moderately complex software applications. Prepares detailed specifications. ? Provide programming skills to augment team capacity. Project consists of coding and deploying new version of in-house web based applications to new production platform. ? Skills required include - substantial object oriented programming knowledge, substantial web based programming experience, solid working knowledge of python programming language, experience with apache web server, web frameworks (e.g. cherry py) , and linux/ unix operating system Experience with telecommunications services or equipment is a plus. ? Candidate will need work with the existing team and interact with the BA/QA personnel. ? Skills: Python, Apache, Linux/ Unix Operating system Please email your resume to the below mentioned email. Regards, Rakhi Kapoor | Direct: 212-381-0614 | Email: rakhi.kapoor at mastech.com | Web: www.mastech.com | 1000 Commerce Drive, Suite 500 | Pittsburgh, PA 15275 | From kyrie at uh.cu Thu May 8 19:14:06 2008 From: kyrie at uh.cu (Luis Zarrabeitia) Date: Thu, 8 May 2008 19:14:06 -0400 Subject: Mathematics in Python are not correct In-Reply-To: <52c855d8-5609-43e0-b98f-9fa87b2808c2@m3g2000hsc.googlegroups.com> References: <52c855d8-5609-43e0-b98f-9fa87b2808c2@m3g2000hsc.googlegroups.com> Message-ID: <200805081914.06459.kyrie@uh.cu> On Thursday 08 May 2008 06:54:42 pm wxPythoner at gmail.com wrote: > The problem is that Python parses -123**0 as -(123**0), not as > (-123)**0. Actually, I've always written it as (-123)**0. At least where I'm from, exponentiation takes precedence even over unary "-". (to get a power of -123, you must write $(-123)^0$ [latex]) Though not an authoritative source, wikipedia also uses the (-x)^y notation: http://en.wikipedia.org/wiki/Exponentiation#Powers_of_minus_one Btw, there seems to be a math problem in python with exponentiation... >>> 0**0 1 That 0^0 should be a nan or exception, I guess, but not 1. [just found out while trying the poster's example] -- Luis Zarrabeitia (aka Kyrie) Fac. de Matem?tica y Computaci?n, UH. http://profesores.matcom.uh.cu/~kyrie From space.captain.face at gmail.com Thu May 29 04:44:53 2008 From: space.captain.face at gmail.com (Kalibr) Date: Thu, 29 May 2008 01:44:53 -0700 (PDT) Subject: Compare 2 files and discard common lines References: <8d55718c-6881-4844-b8d1-bbe1c5929f46@x35g2000hsb.googlegroups.com> Message-ID: <94950542-455f-48d8-8a07-771d3fbe14c3@g16g2000pri.googlegroups.com> On May 29, 6:36 pm, loial wrote: > I have a requirement to compare 2 text files and write to a 3rd file > only those lines that appear in the 2nd file but not in the 1st file. > > Rather than re-invent the wheel I am wondering if anyone has written > anything already? You can use the cmp(x, y) function to tell if a string is similar to another. going cmp('spam', 'eggs') will return 1 (spam is greater than eggs) (have no idea why) swapping the two give -1 and having 'eggs' and 'eggs' gives 0. is that what you were looking for? From deets at nospam.web.de Sat May 24 10:20:26 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 24 May 2008 16:20:26 +0200 Subject: need some help in serving static files inside a wsgi apps In-Reply-To: <6e15240b-520d-4f01-9d21-83f9feeefc2d@x41g2000hsb.googlegroups.com> References: <6e15240b-520d-4f01-9d21-83f9feeefc2d@x41g2000hsb.googlegroups.com> Message-ID: <69qmhcF33pou1U1@mid.uni-berlin.de> Tool69 schrieb: > Hi, > > Until now, I was running my own static site with Python, but I'm in > need of dynamism. > > After reading some cgi tutorials, I saw Joe Gregorio's old article > "Why so many Python web frameworks?" about wsgi apps [http:// > bitworking.org/news/Why_so_many_Python_web_frameworks] and have a > question about it. The code he gave works like a charm (I had to make > a little change because SQLAlchemy has changed since), but how the > hell can I serve static files (css, js, images, etc.) within an wsgi > app, ie inside a '/static' directory ?! There is a wsgi-app out there that is called "static". Use that. And it's the first hit on google "wsgi static"... :) http://lukearno.com/projects/static/ Diez From ivan.illarionov at gmail.com Thu May 22 16:02:13 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Thu, 22 May 2008 20:02:13 +0000 (UTC) Subject: Producing multiple items in a list comprehension References: <5RiZj.165543$ng7.151222@en-nntp-05.dc1.easynews.com> <5PjZj.78772$%15.70394@bignews7.bellsouth.net> Message-ID: On Thu, 22 May 2008 15:29:42 -0400, inhahe wrote: > "Joel Koltner" wrote in message > news:5RiZj.165543$ng7.151222 at en-nntp-05.dc1.easynews.com... >> Is there an easy way to get a list comprehension to produce a flat list >> of, say, [x,2*x] for each input argument? >> >> E.g., I'd like to do something like: >> >> [ [x,2*x] for x in range(4) ] >> >> ...and receive >> >> [ 0,0,1,2,2,4,3,6] >> >> ...but of course you really get a list of lists: >> >> [[0, 0], [1, 2], [2, 4], [3, 6]] >> >> I'm aware I can use any of the standard "flatten" bits of code to turn >> this back into what I want, but I was hoping there's some way to avoid >> the "lists of lists" generation in the first place? >> >> A slightly similar problem: If I want to "merge," say, list1=[1,2,3] >> with list2=[4,5,6] to obtain [1,4,2,5,3,6], is there some clever way >> with "zip" to do so? >> >> Thanks, >> ---Joel >> >> > i figured out a solution > > sum([x,2*x] for x in range(4)],[]) #not tested sum(zip(list1,list2),()) > #not tested > > (you did say you knew of ways to flatten, but i dunno if you knew of > that way or not) > > as an aside, i wish that sum didn't have to take the second parameter. > it's kind of superfluous. it can just use the first item as the initial > value instead of 0 when no initial value is specified. it would be a > little complex to do without putting a conditional in your main loop and > slowing it down, but it could be done. If you don't want the second parameter use reduce(): >>> reduce(operator.add, ([x, x*2] for x in xrange(4))) [0, 0, 1, 2, 2, 4, 3, 6] >>> reduce(operator.add, zip([1,2,3],[4,5,6])) (1, 4, 2, 5, 3, 6) or: >>> reduce(lambda x, y: x.extend(y) or x, ([x, x*2] for x in xrange(4))) [0, 0, 1, 2, 2, 4, 3, 6] -- Ivan From castironpi at gmail.com Wed May 7 16:40:31 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 7 May 2008 13:40:31 -0700 (PDT) Subject: howto print binary number References: 021f52a9-4d18-4e0a-acdd-3a08cca4a4e5@z72g2000hsb.googlegroups.com Message-ID: On May 7, 3:31?pm, Mensanator wrote: > On May 7, 3:13?pm, dmitrey wrote: > > > hi all, > > could you inform how to print binary number? > > I.e. something like > > > print '%b' % my_number > > > it would be nice would it print exactly 8 binary digits (0-1, with > > possible start from 0) > > > Thank you in advance, D > > The gmpy works good. > > >>> import gmpy > >>> print gmpy.digits(66,2).zfill(8) > > 01000010 >>> print '\n'.join( [ ''.join( [ str( a>> i & 1 ) for i in range( 7, -1, -1 ) ] ) for a in range( 10 ) ] ) 00000000 00000001 00000010 00000011 00000100 00000101 00000110 00000111 00001000 00001001 From dgetsman at amirehab.net Wed May 21 12:12:52 2008 From: dgetsman at amirehab.net (Damon Getsman) Date: Wed, 21 May 2008 09:12:52 -0700 (PDT) Subject: issues simply parsing a whitespace-delimited textfile in python script References: Message-ID: Okay, so I manged to kludge around the issue by not using the .readline() in my 'for' statement. Instead, I'm slurping the whole file into a new list that I put in for that purpose, and everything seems to be working just fine. However, I don't know WHY the other method failed and I'm at a loss for why that didn't work and this is working. I'd really like to know the why about this issue so that I don't have to use crappy coding practice and kludge around it the next time I have an issue like this. Any ideas much appreciated. Damon G. From thorsten at thorstenkampe.de Fri May 2 09:51:53 2008 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Fri, 2 May 2008 15:51:53 +0200 Subject: #!/usr/bin/env python vs. #!/usr/bin/python References: <87abj91j8u.fsf@benfinney.id.au> <87k5iczvdy.fsf@benfinney.id.au> Message-ID: * Ben Finney (Fri, 02 May 2008 23:30:01 +1000) > The OP was asking why people prefer on over the other. My answer is > that I prefer specifying "give me the default OS Python" because > anything not installed by the OS is to non-standardised for me to > worry about. > > Others may prefer something different, but then they get to wear > whatever problems occur as a result of that choice. I continue to be > bemused by that preference, and nothing that I've seen so far in this > thread illuminates the issue more. You're missing the point. Apart from the really dubious terms you use ("OS installable package"), using env in the first line has exactly the effect to use the default path of Python (which is the first entry in your path) and not some hard-coded path (which might not even exist). Thorsten From gherron at islandtraining.com Thu May 8 11:17:48 2008 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 08 May 2008 08:17:48 -0700 Subject: Newbie to python --- why should i learn ! In-Reply-To: <9f5ee6c3-86f7-401a-acc8-cd2c9b059fbd@x19g2000prg.googlegroups.com> References: <9f5ee6c3-86f7-401a-acc8-cd2c9b059fbd@x19g2000prg.googlegroups.com> Message-ID: <4823199C.6060308@islandtraining.com> Raxit at MyKavita.com wrote: > Hi, > > i was reading/learning some hello world program in python. > I think its very simillar to Java/C++/C#. What's different (except > syntax) ? > > what can i do easily with python which is not easy in c++/java !? > With Python, you can program with a smile on your face. (Truly, when I found Python, programming became fun again.) Gary Herron > Tnx, > Raxit > www.mykavita.com > -- > http://mail.python.org/mailman/listinfo/python-list > From yves at zioup.com Thu May 1 23:01:10 2008 From: yves at zioup.com (Yves Dorfsman) Date: Fri, 02 May 2008 03:01:10 GMT Subject: help with list comprehension Message-ID: In the following script, m1() and m2() work fine. I am assuming m2() is faster although I haven't checked that (loops through the list twice instead of once). Now what I am trying to do is something like m3(). As currently written it does not work, and I have tried different ways, but I haven't managed to make it work. Is there a possibility ? Or is m2() the optimum ? Thanks. #!/usr/bin/python l = [ { 'colour': 'black', 'num': 0}, { 'colour': 'brown', 'num': 1}, { 'colour': 'red', 'num': 2}, { 'colour': 'orange', 'num': 3}, { 'colour': 'yellow', 'num': 4}, { 'colour': 'green', 'num': 5}, { 'colour': 'blue', 'num': 6}, { 'colour': 'violet', 'num': 7}, { 'colour': 'grey', 'num': 8}, { 'colour': 'white', 'num': 9} ] def m1(): colours = [ e['colour'] for e in l ] nums = [ e['num'] for e in l ] def m2(): colours = [] nums = [] for e in l: colours.append(e['colour']) nums.append(e['num']) #def m3(): # colours, nums = [ e['colour'], e['num'] for e in l ] -- Yves. http://www.SollerS.ca From vijayakumar.subburaj at gmail.com Thu May 8 03:06:06 2008 From: vijayakumar.subburaj at gmail.com (v4vijayakumar) Date: Thu, 8 May 2008 00:06:06 -0700 (PDT) Subject: python newbie: some surprises Message-ID: <67b60370-bed9-4f43-b401-25ce2fd89522@t54g2000hsg.googlegroups.com> When I started coding in python, these two things surprised me. 1. my code is inconsistently indented with the combination of tabs and spaces. Even lines looked intended, but it is not. 2. python requires to pass "self" to all instance methods and I missed ":" often. :) From temmokan at gmail.com Sat May 24 02:45:04 2008 From: temmokan at gmail.com (Sagari) Date: Fri, 23 May 2008 23:45:04 -0700 (PDT) Subject: Calling class method by name passed in variable References: <48366fb1$0$4879$426a74cc@news.free.fr> <4836b62b$0$24427$426a74cc@news.free.fr> Message-ID: <5de30ef7-d9a2-493b-bc43-665339f52cd8@m3g2000hsc.googlegroups.com> Thanks to everyone for the advice. In fact, since all the called methods trap necessary exceptions, I see no big problems with that. With all respect, Konstantin From deets at nospam.web.de Thu May 8 06:48:39 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 08 May 2008 12:48:39 +0200 Subject: pickle problem References: Message-ID: <68g456F2t41nqU1@mid.uni-berlin.de> krustymonkey at gmail.com wrote: > I'm wondering if anyone can help with a workaround for a problem I > currently have. I'm trying to set up a prefork tcp server. > Specifically, I'm setting up a server that forks children and has them > listen on pipes created with os.pipe(). The parent process for the > group starts an inet:tcp server on a given port. In the parent, after > a "socket.accept()", I'm trying to pickle the connection object to > send over an IPC pipe (as stated previously), but I get the following > error: > > File "/usr/lib/python2.4/copy_reg.py", line 76, in _reduce_ex > raise TypeError("a class that defines __slots__ without " > TypeError: a class that defines __slots__ without defining > __getstate__ cannot be pickled > > Does anyone know of a workaround for this? Maybe my approach to this > is wrong? Any help would be appreciated. The error-message is pretty clear I'd say. You use slots - so you are responsible yourself for implementing the pickling-protocol using __getstate__ and __setstate__. Looking at the pickle-docs should give you an idea. But the really easy solution is: do not use slots. They are intended as memory-consumption optimization technique, *not* as "I want to declare my attributes explicitly"-mechanism. So - get rid of them and be a happy pickler. Diez From ivan.illarionov at gmail.com Thu May 1 16:50:32 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Thu, 1 May 2008 20:50:32 +0000 (UTC) Subject: Best way to store config or preferences in a multi-platform way. References: <790cec6c-b057-4a2d-bc2c-e683630c1127@w7g2000hsa.googlegroups.com> <52a268cc-dae7-4eda-81df-cc82dbcbdcd7@56g2000hsm.googlegroups.com> Message-ID: On Thu, 01 May 2008 11:56:20 -0700, Carl Banks wrote: > On May 1, 1:30 pm, Ivan Illarionov wrote: >> On Thu, 01 May 2008 09:45:28 -0700, Carl Banks wrote: >> > On May 1, 12:11 pm, Jon Ribbens wrote: >> >> On 2008-05-01, Ivan Illarionov wrote: >> >> >> > IMO .ini-like config files are from the stone age. The modern >> >> > approach is to use YAML (http://www.yaml.org). >> >> >> You mean YAML isn't a joke!? It's so ludicrously overcomplicated, >> >> and so comprehensively and completely fails to achieve its stated >> >> main goal of being "readable by humans", that I had assumed it was >> >> an April Fool along the lines of Intercal or brainf***. >> >> > YAML, ISTM, took a simple concept that worked for small, >> > straightforward data, and tried to make into a format that could >> > anything anywhere, with disastrous results. It's not unlike Perl in >> > this regard. It's quite ridiculous. >> >> > My recommendation to the OP would be: >> >> > If you intend to write a GUI that completely sets all the options, >> > use XML. You can bet there are some users who would prefer text >> > editing options files, and XML, while not the most readable format >> > available, at least gives users the option. >> >> > If you don't intend to write a GUI to do that, write a simple text >> > file parser (if the options are simple), use ConfigParser, or use a >> > Python file that you exec. >> >> > Store the file in $HOME/.appname/config.ext on Unix, $USERDIR/ >> > ApplicationData/Appname/config.ext on Windows. I don't recommend >> > using the Windows registry to store options; use it to modify Windows >> > behavior (like file associations) but keep your own program's options >> > in your own file. >> >> If you don't like YAML, use JSON or something similar -- XML is >> overkill and .INI is too limited. > > > I don't think you know the OP's requirements enough to know whether INI > or XML is suitable. You're welcome to suggest alternatives but what I > suggested is fine. > > As for XML being overkill for anything, I highly disagree. XML is > suitable for the smallest tasks. These days I use XML for almost all my > data exchange needs: including conf files. Elementtree makes it > possible to process XML and pull out some typical data in ten or so > lines of code. What could possibly be overkill about that? > > > Carl Banks I used XML for almost everything in the past until I found YAML. Elementtree makes it easy but not easy enough. The most powerful thing about YAML is that it was designed to map directly to native data types in languages like Python (see another my post in this thread for example). And this means that simple YAML files will always be easier to process in Python than XML or INI. And this in turn means that OP with any requirements will have to write less code to read and write his config files. -- Ivan From bbxx789_05ss at yahoo.com Sun May 11 15:06:30 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Sun, 11 May 2008 12:06:30 -0700 (PDT) Subject: Problem with custom events in wxpython References: <4efa4dcf-7f3d-4c82-9177-1ee8b25d9e3d@b5g2000pri.googlegroups.com> Message-ID: <223951e8-fb2f-44e8-b416-6cea30cfc66c@24g2000hsh.googlegroups.com> On May 11, 7:23?am, Jimmy wrote: > hi, all > > I'm having a problem with creating custom events in wxpython. > > I have a class A handling some data processing work and another class > B of GUI matter. I need GUI to display information when data in A is > updated. > I know cutom events in wxpython may work. But I found no material > paricularly > helpful :( > > can anyone write me some demo code to show how to do this ... This example works for me: import wx class MyCustomEvent(wx.PyCommandEvent): #or wx.PyEvent def __init__(self, event_type, id): wx.PyCommandEvent.__init__(self, event_type, id) class A(object): #Data Processing class def __init__(self, widget_to_update): self.widget_to_update = widget_to_update #create the custom event: self.my_event_type = wx.NewEventType() self.EVT_MY_CUSTOM_EVENT = wx.PyEventBinder(self.my_event_type, 1) #Note: you need to make EVT_MY_CUSTOM_EVENT persist so that you #can refer to it in a later call to Bind() def process_data(self): #create thread here finished = True if finished: self.update_gui() def update_gui(self): #create a custom event object and enter it in the event queue: my_evt_obj = MyCustomEvent(self.my_event_type, self.widget_to_update.GetId() ) self.widget_to_update.GetEventHandler().ProcessEvent(my_evt_obj) class B(object): #Gui class def __init__(self): frame = wx.Frame(None, -1, "My Window") panel = wx.Panel(frame, -1) button = wx.Button(panel, -1, "Start Data Processing", pos=(100, 10)) button.Bind(wx.EVT_BUTTON, self.onclick) self.text_ctrl = wx.TextCtrl(panel, -1, "Hello World", pos=(100, 50), size=(200, 20)) self.a = A(self.text_ctrl) frame.Bind(self.a.EVT_MY_CUSTOM_EVENT, self.on_my_custom_event) frame.Show() def onclick(self, event): self.a.process_data() def on_my_custom_event(self, event): self.text_ctrl.SetValue("Finished Processing Data") app = wx.PySimpleApp(redirect=False) b = B() app.MainLoop() However, I couldn't get similar code to work when I derived the event class from wx.PyEvent and used Bind() directly on the TextCtrl (command events propagate up the container hierarchy while regular events don't): import wx class MyCustomEvent(wx.PyEvent): #or wx.PyEvent def __init__(self, event_type, id): wx.PyEvent.__init__(self, event_type, id) class A(object): #Data Processing class def __init__(self, widget_to_update): self.widget_to_update = widget_to_update #create the custom event: self.my_event_type = wx.NewEventType() self.EVT_MY_CUSTOM_EVENT = wx.PyEventBinder(self.my_event_type, 1) def process_data(self): #create thread here finished = True if finished: self.update_gui() def update_gui(self): #create a custom event object and enter it in the event queue: my_evt_obj = MyCustomEvent(self.my_event_type, self.widget_to_update.GetId() ) self.widget_to_update.GetEventHandler().ProcessEvent(my_evt_obj) class B(object): #Gui class def __init__(self): frame = wx.Frame(None, -1, "My Window") panel = wx.Panel(frame, -1) button = wx.Button(panel, -1, "Start Data Processing", pos=(100, 10)) button.Bind(wx.EVT_BUTTON, self.onclick) self.text_ctrl = wx.TextCtrl(panel, -1, "Hello World", pos=(100, 50), size=(200, 20)) self.a = A(self.text_ctrl) self.text_ctrl.Bind(self.a.EVT_MY_CUSTOM_EVENT, self.on_my_custom_event) frame.Show() def onclick(self, event): self.a.process_data() def on_my_custom_event(self, event): self.text_ctrl.SetValue("Finished Processing Data") app = wx.PySimpleApp(redirect=False) b = B() app.MainLoop() From jstucklex at attglobal.net Sun May 25 15:07:09 2008 From: jstucklex at attglobal.net (Jerry Stuckle) Date: Sun, 25 May 2008 15:07:09 -0400 Subject: php vs python In-Reply-To: <68cb8bb1-4cc5-4a28-8915-46e7d4e316d9@d1g2000hsg.googlegroups.com> References: <5l%Yj.77$mz3.53@fe101.usenetserver.com> <37b112d8-a3ba-446d-9d2f-d907d93c637b@w8g2000prd.googlegroups.com> <-t-dnWQ4bZN2MaTVnZ2dnUVZ_qGdnZ2d@comcast.com> <68cb8bb1-4cc5-4a28-8915-46e7d4e316d9@d1g2000hsg.googlegroups.com> Message-ID: <1oydnYcMZLpzJaTVnZ2dnUVZ_r-dnZ2d@comcast.com> Ivan Illarionov wrote: > Jerry Stuckle wrote: >> Lie wrote: >>> On May 22, 12:28 pm, NC wrote: >>>> On May 21, 1:10 pm, notbob wrote: >>>>> So, here's my delimna: I want to start a blog. Yeah, who doesn't. >>>>> Yet, I want learn the guts of it instead of just booting up some >>>>> wordwank or whatever. >>>> Here's a simple computation to consider... WordPress' codebase is >>>> approximately a megabyte of PHP code and megabyte of JavaScript code. >>>> Assuming that the average line of that code is 50 characters long, you >>>> are looking at 20,000 lines of code in PHP and as many in JavaScript. >>>> Based on the notion that the average developer out there writes 100 >>>> lines a day, either you're in for a two-year project or your product >>>> is going to have seriously reduced functionality compared to something >>>> that's been freely available for years. What's your choice? >>> Nope, the core functionality of a blogging software could be >>> replicated in just a few lines of PHP codes, in the range of tens to >>> hundreds of lines. If you're creating your own blogging software, you >>> wouldn't seriously think you'd recreate all those things such as >>> pingbacks, commenting system, etc, etc, etc. No, you'd start with some >>> basic core functionalities: a few simple server side includes only. >> As he said - it's either a two man-year project or your product is going >> to have seriously reduced functionality. It looks like you are opting >> for the latter. >> >> Also, you still need to write the server-side includes. But they won't >> do nearly enough for everything WordPress does. > > If the OP wants to learn the guts of the blog or to implement the blog > from scratch, Python/Django would be a better choice than PHP. The > reason is that he can reuse and customize existing high quality > components for all these auth/auth, admin, comments, etc, etc, etc. > Another reason is that Python and Django encourage very clean design > while PHP is too often ends up in "spaghetti SQL wrapped in spaghetti > PHP wrapped in spaghetti HTML". 2 man/year in PHP == 2 man/week in > Python/Django. > You can do the same in PHP. And PHP doesn't create spaghetti code - programmers do. Good programmers write good code in any language. Poor programmers write lousy code - in any language. And I'd love to see you write WordPress in 2 weeks in Python. That's about 2K LOC. Can't be done with the same functionality - unless you have some 50K lines. It's going to be very close to the same 2 man years that PHP takes. > And there are Python/Django blog applications that already do almost > everything (and maybe more) that WordPress does. http://byteflow.su/ > is one of them (IMHO the most promising). > > Ivan > And there are many CMS's written in PHP which do much more than WordPress does. Drupal, Joomla and Mambo come to mind. -- ================== Remove the "x" from my email address Jerry Stuckle JDS Computer Training Corp. jstucklex at attglobal.net ================== From raxitsheth2000 at gmail.com Fri May 16 03:16:47 2008 From: raxitsheth2000 at gmail.com (Raxit@MyKavita.com) Date: Fri, 16 May 2008 00:16:47 -0700 (PDT) Subject: how to set python hosting ! Message-ID: Hi, i do have some basic python know-how. i want to tryout by actually implementing some python generated dynamic page etc. i am having websetup which runs with mysql on linux, and pythong is installed on it. so is there any ref. from where i can know how to configure my webserver for python. -Raxit From pavlovevidence at gmail.com Thu May 29 02:55:46 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 28 May 2008 23:55:46 -0700 (PDT) Subject: Optimization: Picking random keys from a dictionary and mutating values References: Message-ID: <5d7a0971-5b7a-4b52-bd49-484238331c9a@m44g2000hsc.googlegroups.com> On May 28, 7:41 pm, blaine wrote: > Hey everyone, > Just a friendly question about an efficient way to do this. Friendly advance reminder: in many optimization problems, the objective function is far more expensive to calculate than the optimizing procedure. Your time is usually better spent optimizing the objective function, or tuning the optimizer. But what they hey. > I have > a graph with nodes and edges (networkx is am amazing library, check it > out!). I also have a lookup table with weights of each edge. So: > > weights[(edge1, edge2)] = .12 > weights[(edge2, edge5)] = .53 > weights[(edge5, edge1)] = 1.23 > weights[(edge3, edge2)] = -2.34 > etc. > > I would like to take this weight table and subject it to evolutionary > mutations. So given a probability p (mutation rate), mutate edge > weights by some random value. So in effect, if p is .25, choose 25% > random edges, and mutate them some amount. So: > 1. Whats a good way to get the keys? I'm using a loop with > random.choice() at the moment. That's probably the best way. You might be able to squeeze a little more speed out of it by using a partial random shuffle as opposed to removing the item from the list. This will minimize the amount of copying. Here's an example (without error checking): def partial_random_shuffle(lst,nshuffled): for i in xrange(nshuffled): j = random.randrange(i,len(lst)) t = lst[i] lst[i] = lst[j] lst[j] = t The first nshuffled items of lst upon return will be the selected items. Note: This might also be slower than removing items. It should scale better, though. > 2. Any comments on how to get a 'fair' mutation on an existing edge > value? random.normalvariate is usually a good choice for selecting random real-valued increments. val = random.normalvariate(val,sigma) where sigma, the standard deviation, is the amount > I currently am doing something like this, which seems like it leaves > something to be desired. > > import random > weights = generateweights() # generates table like the one above > p = 0.25 > v = random.betavariate(2, 10) > num = int(v*len(weights)) # How many weights should we mutate? > keys = w.keys() > for i in xrange(num): > val = random.choice(keys) # Choose a single random key > w[val] = w[val]*(random.random()*5-1) # Is this a 'good' way to > 'mutate' the value? If you don't remove keys[val], there's a chance you'll mutate the same key twice, which I doubt is what you want. > This is an evolutionary search, so mutate in this sense relates to a > genetic algorithm, perhaps a gradient decent? A gradient descent method is not an evolutionary search and involves no randomness (unless noise is added to the objective, which is a possible way to attack a function with unimportant small scale features, and in that case normalvariate would be the thing used). Carl Banks From dullrich at sprynet.com Sat May 24 07:33:21 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Sat, 24 May 2008 06:33:21 -0500 Subject: WXpython Question References: <5772771b-9b09-4870-8152-397bd93c926c@56g2000hsm.googlegroups.com> <9b765698-4d27-4e10-853e-e2c7e918d751@a1g2000hsb.googlegroups.com> <5196bcc1-e840-456f-ac4d-a3841445362f@y38g2000hsy.googlegroups.com> Message-ID: On Fri, 23 May 2008 06:40:13 -0700 (PDT), Gandalf wrote: >On May 23, 3:29 pm, Mike Driscoll wrote: >> On May 23, 8:24 am, Gandalf wrote: >> >> > I try to reach a specific wx StaticText element's text and to change >> > it by clicking on a button >> >> > now let's say the this is my element: >> >> > wx.StaticText(panel, 15, "Hello" ,(30, 70) , style=wx.ALIGN_CENTRE) >> >> > And this is my EVT_BUTTON bind function : >> >> > def OnClick(event): >> >> > which code shude i enter to change "hello" to "goodbay"? >> >> > thanks >> >> You're probably looking for SetLabel(). So if you do something like >> this to instantiate the StaticText: >> >> self.myText = wx.StaticText(panel, 15, "Hello" ,(30, 70) , >> style=wx.ALIGN_CENTRE) >> >> Then you can change your text by adding this to your OnClick event >> handler: >> >> self.myText.SetLabel("goodbye") >> >> Have fun! And remember, there's a great wxPython mailing list too: >> >> http://www.wxpython.org/maillist.php >> >> Mike > >Thanks! You should also note docs.wxwidgets.org (I tend to find that by googling "wxTreeCtrl" or whatever.) The descriptions of various components there are more complete than in the (excellent!) wxPython book - it's C++ but usually not hard to figure out what the corresponding wxPython should be. David C. Ullrich From buzzard at urubu.freeserve.co.uk Fri May 23 10:25:39 2008 From: buzzard at urubu.freeserve.co.uk (duncan smith) Date: Fri, 23 May 2008 15:25:39 +0100 Subject: Misuse of list comprehensions? In-Reply-To: References: <038e4418$0$27258$c3e8da3@news.astraweb.com> <6359d72c-f937-46cd-b1ce-b7450671b714@i76g2000hsf.googlegroups.com> <5fb0bcfd-0ce0-46cb-b273-7071c7694366@x35g2000hsb.googlegroups.com> <490e72b3-e73b-4047-be64-9880b73a958e@u12g2000prd.googlegroups.com> <48340938$0$10773$426a74cc@news.free.fr> Message-ID: Simon Forman wrote: > On May 21, 4:36 am, Bruno Desthuilliers 42.desthuilli... at websiteburo.invalid> wrote: >> Simon Forman a ?crit : >> >> >> >>> On May 20, 8:58 am, Paul McGuire wrote: >>>> On May 20, 10:50 am, s0s... at gmail.com wrote: >>>>> You don't need all those conditionals. A set differs from a list >>>>> precisely in the fact that each element is unique. And since the >>>>> function is expecting "s" to be an iterable object, it can be >>>>> constructed even without a for loop: >>>>> def compress(s): >>>>> return list(set(s)) >>>>> That does the trick. >>>> Only if order does not need to be maintained. list(set(s)) will not >>>> necessarily keep the unique characters in the order they are seen. >>>> We'll have to check with the OP to see if this is important (I just >>>> assumed that it was because of the use of list comps). >>>> -- Paul >>> If order is important, you can use sorted() instead of list() like so: >>> def compress(s): >>> new = sorted(set(s), key=s.index) >>> return return ''.join(new) >> This won't still preserve the *original* order. > > > I don't understand. > > new will contain each unique item in s, sorted in order of the items' > first occurance in s, right? > There are other ways to do it (other functions that could be passed to > sorted() as the key arg) of course, but this seems like a good value > of "original order", no? :) > > Regards, > ~S But, I think, worst case quadratic performance through generating all the indices. Duncan From Graham.Dumpleton at gmail.com Thu May 1 19:13:57 2008 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Thu, 1 May 2008 16:13:57 -0700 (PDT) Subject: where do I begin with web programming in python? References: <37ea096e-cf3e-4932-8370-306a15a2aebd@25g2000hsx.googlegroups.com> Message-ID: On May 2, 7:45 am, Christian Heimes wrote: > jmDesktop schrieb: > > > I have been to the main python site, but am still confused. I have > > been using .net, so it may be obvious how to do this to everyone > > else. I am aware there are various frameworks (Django, Pylons, etc.), > > but I would like to know how to create web pages without these. If I > > havemod_pythonor fastcgi on apache, where do I start? I don't have > > clue where to begin to create a web page from scratch in python. I am > > sure I will want to access database, etc., all the "normal" stuff, I > > just want to do it myself as opposed to the frameworks, for learning. > > I highly recommend WSGI instead ofmod_pythonor (fast)cgi. I've heard > only bad things aboutmod_pythonover the past years and CGI is totally > old school. > > Check out Python Paste, CherryPy and Django. You can also try the Zope, > Zope3 and Plone world but Zope is usually for larger and complex > applications. > > Most frameworks come with their own little web server for development, too. I'd also suggest avoiding coding anything directly to mod_python and instead base things on WSGI. You can still run it on mod_python with a suitable adapter, but you can also run it with mod_wsgi, mod_fastcgi, or using pure Python web servers such as the one in Paste as well. For a low level nuts and bolts (anti framework) approach I'd suggest looking at: http://dev.pocoo.org/projects/werkzeug/ This gives you all the basic components, but it is really up to you as to how you put them together, which seems to be what you want to be able to do. Graham From bj_666 at gmx.net Tue May 20 02:45:20 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 20 May 2008 06:45:20 GMT Subject: this worked before...' '.join([`x x` for x in range(1, 6)]) References: Message-ID: <69fac0F2uih6aU3@mid.uni-berlin.de> On Mon, 19 May 2008 15:28:48 -0700, notnorwegian wrote: > ' '.join([`x x` for x in range(1, 6)]) > > anyone can tell me what im doing wrong? I doubt that this worked before because that's a syntax error: In [84]: ' '.join([`x x` for x in range(1, 6)]) ------------------------------------------------------------ File "", line 1 ' '.join([`x x` for x in range(1, 6)]) ^ : invalid syntax The backticks are syntactic sugar for the `repr()` function and ``repr(x x)`` isn't legal syntax either. Ciao, Marc 'BlackJack' Rintsch From tjreedy at udel.edu Sun May 11 16:38:11 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 11 May 2008 16:38:11 -0400 Subject: Keeping two lists aligned after processing References: <823470c7-4c15-4653-8c51-7ab83acc9221@m36g2000hse.googlegroups.com> <7xbq3dfj0c.fsf@ruckus.brouhaha.com> Message-ID: "Paul Rubin" <"http://phr.cx"@NOSPAM.invalid> wrote in message news:7xbq3dfj0c.fsf at ruckus.brouhaha.com... | philly_bob writes: | > algs=['AlgA', 'AlgB', 'AlgC', 'AlgD', 'AlgE'] | > accs=[] | > for alg in algs: | > thisacc=getattr(alg.accuracy)() |> # picked this technique on comp.lang.python last month I don't believe that you actually ran this. What you should have picked up for the above was something like globals()[alg].accuracy(). What you probably saw was something like getattr(ob_with_call_attr, 'callable_name')(). But a list of alg objects instead of names, as Paul suggested, is almost always better. | > accs.append(thisacc) | I think what you mean is (untested): | | algs = [AlgA, AlgB, AlgC, AlgD, AlgE] | accs = sorted(((alg.accuracy(), alg.name()) for alg in algs), reverse=True) Use alg.__name__ instead of alg.name(). | for i,(alg_acc, alg_name) in enumerate(accs): | print '%2d %5s %0.2f'% (i, alg_name, alg_acc) | | This assumes a method alg.name() which tells you the name of the algorithm. See above. In 3.0, function names are also .__name__ instead of .func_name, so one can mix callables in a list and get their definitions names uniformly. | I don't understand how you're converting the string 'AlgA' | to an algorithm object in your example above. He was trying to convert name to method with the buggy getattr call. tjr From notnorwegian at yahoo.se Mon May 26 15:02:24 2008 From: notnorwegian at yahoo.se (notnorwegian at yahoo.se) Date: Mon, 26 May 2008 12:02:24 -0700 (PDT) Subject: definition of a highlevel language? References: <2759eed3-956d-45c7-8dfb-9557f74133b3@56g2000hsm.googlegroups.com> <26d0b3d2-01cc-49bd-b284-1a849b0b835f@y38g2000hsy.googlegroups.com> Message-ID: <34dcbdc1-5285-41ec-be06-c88c56bb0372@i76g2000hsf.googlegroups.com> On 26 Maj, 20:57, miller.pau... at gmail.com wrote: > On May 26, 2:34 pm, notnorweg... at yahoo.se wrote: > > I wanted to address some other points I failed to mention in my first > response. > > > so are they fundamentally differently built or is it just a lot of > > lowlevel operations built on top of each other? > > Partly. A high-level language is essentially one that gives you high- > level operations, like "apply the function f to each element of the > sequence seq, and return [f(seq[0]), f(seq[1]), ... f(seq[n])]. > > But, it's more than that. (You use Haskell as your example, but I'll > use Python because I know it roughly a million percent better than > Haskell... hehe.) In Python, you have support from the language to > treat functions as first-class objects; in C, you explicitly cannot do > this -- to map an arbitrary function over a sequence, you're > restricted to accessing the function through a pointer. On the > surface, it's the same operation, but that extra level of indirection > can really bog one's mind down. Think about how difficult it is for a > human to interpret the declaration of a function pointer in C, for > instance. > > > haskell is considered a very highlevellanguage but can you do > > systemsprogramming with it(yes maybe it is very unpractical i dont > > know but can you)? > > is lambda calculus a more abstract and efficient way of modeling a > > computer? > > Lambda calculus doesn't model computers. It models *computation*. > That is, given a Turing machine, there's a set of functions in the > lambda calculus, which, when suitably combined, will yield the exact > same result as the original Turing machine. That doesn't in any way > imply that Turing machines work by interpreting lambda calculus. > > > how did lispmachines work? was the basic system programmed in LISP? > > Yes, the whole kit and kaboodle, all the way down to the microcode was > programmed in LISP. In principle, there's no reason we couldn't have > Haskell machines or Python machines. It's just that nobody's been > crazy enough to do it, that I know of. :-) what is crazy about it? in the same way programming webapps in C would be annoying because you have to do a lot of lowlevel tasks it is dumb to program computer ina highlevellanguage because you dont have direct access to lowlevel tasks meaning you cant program it very efficiently, ie make it fast? From mathieu.prevot at ens.fr Wed May 28 08:11:51 2008 From: mathieu.prevot at ens.fr (Mathieu Prevot) Date: Wed, 28 May 2008 14:11:51 +0200 Subject: Flash Decoder In-Reply-To: <0c0ea160-89d6-4827-8d54-d0029d064c71@w5g2000prd.googlegroups.com> References: <860bf237-18d3-4949-a26d-97becafb27c8@i36g2000prf.googlegroups.com> <6a4rtbF35ut5sU1@mid.uni-berlin.de> <0c0ea160-89d6-4827-8d54-d0029d064c71@w5g2000prd.googlegroups.com> Message-ID: <3e473cc60805280511o6cf0e639lfdfc2d1ea8902300@mail.gmail.com> 2008/5/28 Ankit : > Thanks for replying guys but could you be a little more specific like > in terms of steps i shd follow to make the decoder and also how is > ffmpeg/libffmpeg going to help.. You can start by getting familiar with ffmpeg [1] by playing with it and glance at its libraries (I call them libffmpeg, but they have their specific name) allow you to do. Keep in mind that libraries contain frequently used functions and are written so they can be reused, shared by other/news softwares eg. the one you want. Start by opening a flash video eg one .flv [2] file from youtube with a first python script that use the right component(s) of libffmpeg. Python allows you to use C libraries. Mathieu [1] http://ffmpeg.mplayerhq.hu/documentation.html [2] http://en.wikipedia.org/wiki/Flv From efurman at admailinc.com Tue May 13 12:24:24 2008 From: efurman at admailinc.com (Ethan Furman) Date: Tue, 13 May 2008 08:24:24 -0800 Subject: looking for a pdf module Message-ID: <4829C0B8.9090605@admailinc.com> Greetings! I'm hoping to be able to generate pdf files on the fly -- are there any python modules out there to do that? All help appreciated! -- Ethan -------------- next part -------------- An HTML attachment was scrubbed... URL: From ptmcg at austin.rr.com Wed May 14 23:47:23 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Wed, 14 May 2008 20:47:23 -0700 (PDT) Subject: More fun with PyParsing - almost did it on my own.. References: Message-ID: <150b049c-2c84-481d-a2fa-6af0b7fc8ce1@f63g2000hsf.googlegroups.com> On May 14, 6:07?pm, rh0dium wrote: > Hi all, > > I almost did my first pyparsing without help but here we go again. > Let's start with my code. ?The sample data is listed below. > > > > x = ?cells.parseString(data) > print x[0].asDict() > > reveals > {'pins': ([(['A', 'Input'], {'direction': [('Input', 1)], 'name': > [('A', 0)]}), (['B', 'Input'], {'direction': [('Input', 1)], 'name': > [('B', 0)]}), (['Y', 'Output'], {'direction': [('Output', 1)], 'name': > [('Y', 0)]}), (['VDD', 'Inout', 'Power'], {'direction': [('Inout', > 1)], 'name': [('VDD', 0)], 'signal': [('Power', 2)]}), (['VSS', > 'Inout', 'Ground'], {'direction': [('Inout', 1)], 'name': [('VSS', > 0)], 'signal': [('Ground', 2)]})], {}), 'name': 'AND2X1', 'library': > 'stdcell130'} > > As you can see the Pins is all jacked up and I want is not that. ?I > want the following > > { 'name': 'AND2X1', > ? 'library':'stdcell130' > ? 'pins': [ { 'name': 'VSS', 'direction':'Inout', 'signal':'Ground'}, > ? ? ? ? ? ? ?{ 'name': 'VDD', 'direction':'Inout', 'signal':'Power'}, > ? ? ? ? ? ? ?{ 'name': 'A', 'direction':'Input' }, > ? ? ? ? ? ? ?{ 'name': 'B', 'direction':'Input' }, > ? ? ? ? ? ? ?{ 'name': 'Y', 'direction':'Output' } ] > > } > > What did I do wrong in my code.. > Not a thing! asDict() is just not very good at dumping out lists of subdicts. Look at the output when you iterate over the cells in x, and the pins in each cell: for cell in x: print "Name:", cell["name"] print "Library:", cell["library"] print "Pins:" for pin in cell["pins"]: print pin.asDict() print Prints: Name: AND2X1 Library: stdcell130 Pins: {'direction': 'Input', 'name': 'A'} {'direction': 'Input', 'name': 'B'} {'direction': 'Output', 'name': 'Y'} {'direction': 'Inout', 'name': 'VDD', 'signal': 'Power'} {'direction': 'Inout', 'name': 'VSS', 'signal': 'Ground'} Name: AND2X2 Library: stdcell130 Pins: {'direction': 'Input', 'name': 'A'} {'direction': 'Input', 'name': 'B'} {'direction': 'Output', 'name': 'Y'} {'direction': 'Inout', 'name': 'VDD', 'signal': 'Power'} {'direction': 'Inout', 'name': 'VSS', 'signal': 'Ground'} Now, here is a real trick. Each pin has a unique name, and the collection of pins can be used to define a dict using the pin names as dynamically-defined keys. You've laid all the ground work, all that is needed is to define your sequence of OneOrMore(guts) as a dict using the guts names as keys. The only change needed is to wrap this OneOrMore(guts) in a pyparsing Dict class - that is, change: OneOrMore(guts).setResultsName("pins") to: Dict(OneOrMore(guts)).setResultsName("pins") Now, if you iterate over each cell, you can dump out its structure: for cell in x: print cell.dump() print Prints: ['stdcell130', 'AND2X1', [['A', 'Input'], ['B', 'Input'], ['Y', 'Output'], ['VDD', 'Inout', 'Power'], ['VSS', 'Inout', 'Ground']]] - library: stdcell130 - name: AND2X1 - pins: [['A', 'Input'], ['B', 'Input'], ['Y', 'Output'], ['VDD', 'Inout', 'Power'], ['VSS', 'Inout', 'Ground']] - A: Input - B: Input - VDD: ['Inout', 'Power'] - direction: Inout - name: VDD - signal: Power - VSS: ['Inout', 'Ground'] - direction: Inout - name: VSS - signal: Ground - Y: Output ['stdcell130', 'AND2X2', [['A', 'Input'], ['B', 'Input'], ['Y', 'Output'], ['VDD', 'Inout', 'Power'], ['VSS', 'Inout', 'Ground']]] - library: stdcell130 - name: AND2X2 - pins: [['A', 'Input'], ['B', 'Input'], ['Y', 'Output'], ['VDD', 'Inout', 'Power'], ['VSS', 'Inout', 'Ground']] - A: Input - B: Input - VDD: ['Inout', 'Power'] - direction: Inout - name: VDD - signal: Power - VSS: ['Inout', 'Ground'] - direction: Inout - name: VSS - signal: Ground - Y: Output To flesh out all fields of all pins, I suggest you add a default value for the optional signal entry, and set the results name on the Optional wrapper, not the quoted string. Change: + Optional(quotedString.setParseAction(removeQuotes).setResultsName("signal")) to: + Optional(quotedString.setParseAction(removeQuotes),default="").setResultsName("signal") Now dump() called on each cell prints out: ['stdcell130', 'AND2X1', [['A', 'Input', ''], ['B', 'Input', ''], ['Y', 'Output', ''], ['VDD', 'Inout', 'Power'], ['VSS', 'Inout', 'Ground']]] - library: stdcell130 - name: AND2X1 - pins: [['A', 'Input', ''], ['B', 'Input', ''], ['Y', 'Output', ''], ['VDD', 'Inout', 'Power'], ['VSS', 'Inout', 'Ground']] - A: ['Input', ''] - direction: Input - name: A - signal: - B: ['Input', ''] - direction: Input - name: B - signal: - VDD: ['Inout', 'Power'] - direction: Inout - name: VDD - signal: Power - VSS: ['Inout', 'Ground'] - direction: Inout - name: VSS - signal: Ground - Y: ['Output', ''] - direction: Output - name: Y - signal: Power Input ['stdcell130', 'AND2X2', [['A', 'Input', ''], ['B', 'Input', ''], ['Y', 'Output', ''], ['VDD', 'Inout', 'Power'], ['VSS', 'Inout', 'Ground']]] - library: stdcell130 - name: AND2X2 - pins: [['A', 'Input', ''], ['B', 'Input', ''], ['Y', 'Output', ''], ['VDD', 'Inout', 'Power'], ['VSS', 'Inout', 'Ground']] - A: ['Input', ''] - direction: Input - name: A - signal: - B: ['Input', ''] - direction: Input - name: B - signal: - VDD: ['Inout', 'Power'] - direction: Inout - name: VDD - signal: Power - VSS: ['Inout', 'Ground'] - direction: Inout - name: VSS - signal: Ground - Y: ['Output', ''] - direction: Output - name: Y - signal: You can use the nested names shown in the dump to access individual bits of the parsed results: for cell in x: print cell.name print cell.pins.keys() print cell.pins.VDD.signal print cell.pins.A.direction print prints: AND2X1 ['A', 'Y', 'B', 'VDD', 'VSS'] Power Input AND2X2 ['A', 'Y', 'B', 'VDD', 'VSS'] Power Input -- Paul From ian.g.kelly at gmail.com Tue May 13 20:18:01 2008 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 13 May 2008 18:18:01 -0600 Subject: list.__len__() or len(list) In-Reply-To: References: Message-ID: <3fc761710805131718y448ef0b8r67dcc8cf118bc80a@mail.gmail.com> On Tue, May 13, 2008 at 5:57 PM, Nikhil wrote: > __len__() is a built-in function of the list object and is updated along > with the list object elements and will be useful incase the list is very > huge. > > len() is an external method again, which may require the processing cycles > again. The purpose of obj.__len__() is to implement len(obj), which simply calls it. So obj.__len__() may be faster, but only marginally. The reason to prefer len(obj) is that if you inadvertently pass an object that does not implement __len__, you get the more appropriate TypeError rather than an AttributeError. From gagsl-py2 at yahoo.com.ar Mon May 12 17:21:15 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 12 May 2008 18:21:15 -0300 Subject: Import/Create module from buffer References: <09bfaed8-8bf6-4faf-80f9-e0b97aa03127@a70g2000hsh.googlegroups.com> Message-ID: En Mon, 12 May 2008 08:09:45 -0300, Gruik escribi?: > On May 12, 12:31?pm, "Gabriel Genellina" > wrote: >> En Mon, 12 May 2008 05:49:22 -0300, Gruik escribi?: >> >> > I'm currently working on python embedding with C++. My goal is that >> > the C++ part handle files writing/reading so that the Python part only >> > works with buffers. >> >> > I succeeded in buffer exchanges. The problem is that some of the files >> > I read/write are python files so that, before embedding, I imported >> > them as modules when I needed them. >> >> > But now that the Python part only receive buffers, I can't do it >> > anymore. So I wonder : >> > - is it possible to import module from a buffer instead of files? >> > - or is it possible to create a module object from my buffer? >> >> Yes, first compile the buffer to get a code object, then use PyImport_ExecCodeModule. See how this function is used in import.c >> > > Thanks for your quick answer ! > I think I'll have no problem with that in C++ and I'm going to try it > right after this message. > > But before that 1 question: what if I'm in Python ? > Following your solution, I did that in Python : > > def load_buffer(buffer) : > compiled_buffer = compile(buffer, "module_name", "exec") > exec(compiled_buffer) > > It works great except that I can't have a module object and that it is > as if I did "from module import *" > But I need the module object and not an "import *" behavior. > Any idea about the way to do that? Almost - you have to create a new module and exec the code into its namespace: py> import new py> foo = new.module("foo", "This is the foo module") py> exec "def f(): pass" in foo.__dict__ py> foo py> foo.f py> dir(foo) ['__builtins__', '__doc__', '__name__', 'f'] (replace "def f(): pass" with the compiled buffer) Two differences with a "normal" module: - it has no __file__ attribute - you may want to add it, with the original filename, or leave it off to show that it's not loaded from a file. - it does not exist in sys.modules, so other modules cannot import it. If you want to allow that: sys.modules['foo'] = foo (perhaps one should check previously that there is no module named "foo" before replacing it...) -- Gabriel Genellina From tjreedy at udel.edu Mon May 5 15:00:43 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 5 May 2008 15:00:43 -0400 Subject: confused about self, why not a reserved word? References: <972f7226-baef-4f94-a8ea-5bec99213540@34g2000hsf.googlegroups.com> <9c619edb-303b-439b-ad65-995fb76f70d5@y38g2000hsy.googlegroups.com> Message-ID: "globalrev" wrote in message news:9c619edb-303b-439b-ad65-995fb76f70d5 at y38g2000hsy.googlegroups.com... | sorry i noticed now a little error, i was playing around a lot and saw | that on the sel-example i had then called foo.hello() instead of | foo.Hello(). Lesson: whenever one inquires about an 'error', one should cut and paste the error traceback along with a relevant snippet of code. From dullrich at sprynet.com Fri May 23 11:01:49 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Fri, 23 May 2008 10:01:49 -0500 Subject: Relationship between GUI and logic? References: <48363c34$0$15204$607ed4bc@cv.net> <4836747b$0$15488$426a74cc@news.free.fr> <4836c28e$0$25161$c3e8da3@news.astraweb.com> Message-ID: On Fri, 23 May 2008 09:13:50 -0400, "John Salerno" wrote: >"Bruno Desthuilliers" wrote in >message news:4836747b$0$15488$426a74cc at news.free.fr... >> Ever heard of the "Model/View/Controller" pattern ? > >Yes, I have, but I probably don't understand it well enough yet. For >example, I don't really know what is meant by phrases like "build a model", >"the view registers itself with the model", "interations are sent to the >appropriate controller" -- I may understand them literally, but I get the >feeling that the implementation of these ideas are beyond me. I doubt that. I've done things like this. I ended up with just a Model and a View, no Controller. I assumed that meant I was being Bad - I read once that that often happens, specifically with GUI programs. An example, certainly not meant to be definitive, maybe not even right, probably not "right", but illustrating explicitly what those terms you claim not to understand might mean in an implementation: class Model: """Encapsulates an abstract version of the game: Knows nothing about how the players make moves, the moves are reported to the model via the ProcessMove method. Knows nothing about how the state of the game is displayed to the players; that's handled by the view or views. The model might contain a matrix, where the entry in each cell is None or a certain Piece object. The model knows that if a certain Cell contains a King then it's legal to move that King to this Cell but not to that Cell - that's part of the rules of the game, something the View knows nothing about""" def __init__(self): #set up internal state, for example #self.board = [[None]*8]*8 #and then self.board[0,4] = Queen[WhitePlayer], #etc. Whatever... self.views = [] #or just self.view = None if there's #no reason for multiple views. When I did #something like this once I decided at the #end that I should have allowed multiple #views even though there was only one to start, #because functionality that got added to the view #could have been done more cleanly by creating #a second view (one view being the display and #another being spoken messages) def RegisterView(self, view): self.views.append(view) #or just self.view = view def UpdateViews(self): for view in self.views: view.UpdateDisplay(self) #or UpdateView(self): if self.view: self.view.UpdateDisplay(self) def ProcessMove(self, move): """Model recieves "messages" from View here.""" #modify internal state depending on the #information passed in "move", #for example move might say that the Piece in #a certain Cell was dragged to another Cell. #Here in ProcessMove you decide whether that's #a legal move, and if so what effect it should #have on the state of the game. Update state, then self.UpdateViews() #or there could be more than one "Process" method #if there are various different sorts of things the #players might do class Square: def __init__(self, row, col): self.row = row self.col = col #say a move is a drag from one square to another: class Move: def __init__(self, start, end) self.start = start self.end = end #wrote that out explicitly just to emphasize that #the Move object, which the View passes to the #Model as a message, doesn't know anything #about the details of the display and also doesn't #know anything about the rules of the game... class View: def __init__(self, game): #set up the wxPython stuff self.game = game self.game.RegisterView(self) Bind(self, VariousEvents, VariousHandlers) def VariousHandlers(self, evt) #figure out what the players just did based #on evt. Maybe a player has just dragged a piece #from one square to another. figure out the row #and col of the start and end squares from #information in evt. #Now tell the Model what just happened: self.game.ProcessMove(Move(Square(row1, col1),Square(row2, col2))) def UpdateDisplay(self): #look at self.game to figure out what pieces #go where, then draw them on the screen. wx.This wx.That game = Model() view = View(game) >I think it's >mainly an issue of terminology, so probably I should just read up on MVC. > >> The user interface doesn't need to be graphical. There were games and >> emails clients and text editors before GUIs existed, you know ? > >Of course, but I'm specifically asking about creating a program that has a >GUI, and even more specifically it would be wxPython. > David C. Ullrich From vlastimil.brom at gmail.com Sat May 3 17:31:38 2008 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Sat, 3 May 2008 23:31:38 +0200 Subject: using sqlite3 - execute vs. executemany; committing ... Message-ID: <9fdb569a0805031431r6666e950pc6dbc8aab6e36684@mail.gmail.com> Hi all, I'd like to ask about some (probably elementary) things about the proper usage of sqlite3 in python (2.5.2; win). - Are there any peculiarities with using curs.executemany(...) vs. multiple curs.execute(...) ? I read a notice, sqlite3 does internally some caching, hence both should be similarly fast, but in my case executemany(...) is quite a bit faster (probably due to the function call overhead?). Are there maybe some caveats with using executemany? (the obvious memory consumption for the intermediate list doesn't seem to matter much in my application). Further, I am not quite sure about the standard usage of the cursor object and also the proper commiting the transactions and closing the connection. Should one create a cursor of a connection and call the execute ... methods of the cursor - or is it better to call the shortcut execute etc. methods of the Connection object directly (as suggested in the docs: http://docs.python.org/lib/node351.html(or are there specific use cases for both approaches)? When the transactions should be commited? (creating, altering a table, or also selecting the results ?) There seem to be some implicit handling of the transactions ( http://docs.python.org/lib/sqlite3-Controlling-Transactions.html#sqlite3-Controlling-Transactions); hence I am not sure about the standard usage of these methods; the same is true of connection.close() - or are these calls eventually unnecessary? To give a bit more info about my use case, my (gui) app displays a set texts along with some informations on the currently visible text segments. After starting a gui the texts are read from the source files (also containing a kind of tags) - simultaneously the tags are parsed and the corresponding values are stored in sqlite "in memory" - the column names as well as the corresponding values for given text parts are extracted dynamically from the source files. During the whole run of the program the db should be available in order to retrieve the properties of the given text index. Below is a part of my code dealing with the populating of the db;, I'm sorry, it's a not runable pseudocode, however, my present code works somehow, but I'm quite sure, the implementation isn't really standard, hence I'd like to hear some comments/suggestions. (I asked some time ago about the possibility of a parametrised input of the table and column names, but this seems impossible - therefore I used the string interpolation.) - the variables are defined in other parts of code before; most of the names might be self explanatory; self - custom class managing the text with its properties; text_name - name of the table; index_col_name - a name of the special db column containing the text index; act_db_columns - list of the db columns; question_marks - a string "?, ?, ? ..." (synchronized with the length of act_db_columns); tags_seq - a nested list with the previously retrieved data for the database. conn_tags_DB = sqlite3.connect(':memory:') curs = self.conn_tags_DB.cursor() curs.execute('CREATE TABLE IF NOT EXISTS "%s" ("%s", UNIQUE("%s"))' % (self.text_name, index_col_name, index_col_name)) curs.execute(u'INSERT OR REPLACE INTO "%s"("%s") VALUES (?)' % (self.text_name, index_col_name), (0,)) for new_col in act_db_columns[1:]: # adds the needed columns (except of the first one: index_col_name) curs.execute('ALTER TABLE "%s" ADD "%s" TEXT' % (self.text_name, new_col)) curs.executemany('INSERT OR REPLACE INTO "%s" VALUES (%s)' % (self.text_name, question_marks), tags_seq) self.conn_tags_DB.commit() Are there maybe any comments or hints on a more elegant/efficient solution? Now, what's the usual way to access the database? Is it possible/wise/standard ... to leave the connection open for the subsequent queries during the whole run of the app; could even the cursor eventually be present as a class method, or should it rather be created repeatedly with each call? (After populating, the db shouldn't be modified, but only read.) Many thanks in advance for your help; and apologies for this longer post. Greetings, Vlasta -------------- next part -------------- An HTML attachment was scrubbed... URL: From dfnsonfsduifb at gmx.de Sun May 25 16:04:42 2008 From: dfnsonfsduifb at gmx.de (Johannes Bauer) Date: Sun, 25 May 2008 22:04:42 +0200 Subject: 22.800000 and a 1 on the end!!?? In-Reply-To: References: Message-ID: notnorwegian at yahoo.se schrieb: > ok where does the 1 in the come from? Conversion to floating point values, which have no precise representation for all numbers that have such in the decimal system. Read more on http://en.wikipedia.org/wiki/IEEE_754-1985 Regards, Johannes -- "Wer etwas kritisiert muss es noch lange nicht selber besser k?nnen. Es reicht zu wissen, da? andere es besser k?nnen und andere es auch besser machen um einen Vergleich zu bringen." - Wolfgang Gerber in de.sci.electronics <47fa8447$0$11545$9b622d9e at news.freenet.de> From pavlovevidence at gmail.com Tue May 13 19:52:39 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 13 May 2008 16:52:39 -0700 (PDT) Subject: Purpose of operator package References: Message-ID: <1cd579a7-c5a3-49f2-9071-0eef5e966dab@r66g2000hsg.googlegroups.com> On May 13, 7:46 pm, Carl Banks wrote: > On May 13, 6:09 pm, Eric Anderson wrote: > > > I mainly work in other languages (mostly Ruby lately) but my text > > editor (Scribes) is python. With python being everywhere for dynamic > > scripting I thought I would read the source to learn the language > > better (I've gone through some basic tutorials but I always prefer to > > learn from real source). > > There is one significant drawback of that.... > > > So right from the start I see the following: > > > from operator import truth > > if truth(argv): > > # blah blah blah > > > It is obvious they are testing to see if any command line arguments. > > But curious for why the function is needed. > > It isn't. The above is terrible code. > > 1. You don't even need operator.truth; the built-in bool performs that > job. However, this code could have been written before the advent of > bool, so we'll give it a temporary pass. > 2. bool in unnecessary in this context. > 3. Lest someone claim that truth serves to document that you are > asking for the boolean value of argv (i.e., whether it's not empty), > it's redundnant since the if statement implies that. 4. sys.argv is never false. I presume that that the first item of argv was removed, or argv is a copy of sys.argv without the first element. Either way is bad style IMO. Leave sys.argv alone, and if you copy it without the first element, copy it to a differently-named variable. Carl Banks From bruno.42.desthuilliers at websiteburo.invalid Mon May 26 05:28:13 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 26 May 2008 11:28:13 +0200 Subject: Storing objects in relational database In-Reply-To: <87r6bsvxz7.fsf@gmail.com> References: <03a17198-3eb2-438e-97c9-db18c0c24a80@c65g2000hsa.googlegroups.com> <87r6bsvxz7.fsf@gmail.com> Message-ID: <483a82ad$0$12589$426a74cc@news.free.fr> Ville M. Vainio a ?crit : > "bruno.desthuilliers at gmail.com" writes: > > >> I don't know if you'd label it 'elegant', but as far as I'm >> concerned, storing serialized objects as blobs in a relational >> database is mostly non-sense. If I use a relational database, it's >> because it is a *relational* database. If you want an OODB, then we >> have the ZODB, Durus and a couple others. > > ... not to forget object-relational mappers like SQLAlchemy, SQLObject... Which are more IMHO another way to "bridge" RBDMS with the programming language than a way to persist objects. From jcd at sdf.lonestar.org Wed May 14 06:53:02 2008 From: jcd at sdf.lonestar.org (J. Clifford Dyer) Date: Wed, 14 May 2008 06:53:02 -0400 Subject: Python and Flaming Thunder In-Reply-To: <0bda514d-7e61-45ff-826b-9e64999b18c3@z24g2000prf.googlegroups.com> References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <5b0e3f70-afde-4480-8713-e7113b1250d7@x35g2000hsb.googlegroups.com> <1f537717-00d0-48ee-99b6-7125b96a6133@t12g2000prg.googlegroups.com> <68t4o0F2vaoncU1@mid.uni-berlin.de> <2a32179a-9439-449c-bd07-fff6a4075aee@s50g2000hsb.googlegroups.com> <7ee5dffd-df8f-46f0-bd78-c81ac0418a9a@d77g2000hsb.googlegroups.com> <65ef773e-a1c3-4adb-a18b-e8b8451efe5e@b5g2000pri.googlegroups.com> <68trmmF2vjivnU1@mid.uni-berlin.de> <0bda514d-7e61-45ff-826b-9e64999b18c3@z24g2000prf.googlegroups.com> Message-ID: <1210762382.6465.3.camel@jcd-desktop> On Tue, 2008-05-13 at 10:33 -0700, Dave Parker wrote: > > You sound like a commercial. > > Get Flaming Thunder for only $19.95! It slices, it dices! > > > And while programs and libraries written in assembly may be twice as fast > > as programs and libraries written in C, ... > > It's a myth that they're only twice as fast. An experienced assembly > language programmer can usually get out at least a factor of 5 by > using tricks such as cache-coherence, carry flag tricks, stack > manipulations, etc. > > > ... they're real hell to maintain. > > That's also a myth. For example, if C is easy to maintain, why is > Flaming Thunder the only single-asset 8-by-8 shotgun cross compiler in > the world? There should be lots of single-asset 8-by-8 shotgun cross > compilers written in C, if C is easier to maintain. Not only is it the world's only "single-asset 8-by-8 shotgun cross compiler," but according to google, it's also the world's only "shotgun cross compiler" period. But I guess if you make up your own terminology you're bound to be unique. :) Do you mind if I ask: what exactly is a single-asset 8x8 shotgun cross compiler, and what makes that of any value to me? Cheers, Cliff From iman.darabi at gmail.com Mon May 12 06:37:03 2008 From: iman.darabi at gmail.com (Iman) Date: Mon, 12 May 2008 03:37:03 -0700 (PDT) Subject: artificiall, agent, movement Message-ID: <94c853a6-decd-4524-b549-4f8245f36736@y18g2000pre.googlegroups.com> hi i'm working on some simulation project . i'm going to simulate traffic of a city. this simulation has cars , passengers , non-movable objects and Traffic signals . i've made cars as intelligent agent . it has thinking method , changing states agents ... the main problem is i have problem to move my agents in world . it would be possible to add some method to agent which move agent in random destination . but i'm trying to find some patterns which is designed for this problems . is there any sample source code in python or links, docs to help me ? thanks for your attention . From wizzardx at gmail.com Wed May 7 03:04:57 2008 From: wizzardx at gmail.com (David) Date: Wed, 7 May 2008 09:04:57 +0200 Subject: using sqlite3 - execute vs. executemany; committing ... In-Reply-To: <9fdb569a0805061507j70706aa5ie32ddfeb832ccfa7@mail.gmail.com> References: <9fdb569a0805031431r6666e950pc6dbc8aab6e36684@mail.gmail.com> <18c1e6480805040214m5ecd0b27t9800bfc4a39daec8@mail.gmail.com> <9fdb569a0805041407s75c8ad3bsc08c8bac87fa0d83@mail.gmail.com> <18c1e6480805041536x7287d23ds9d9bfcf6ec73e123@mail.gmail.com> <9fdb569a0805050559q83999d4v6043acb94c9797d0@mail.gmail.com> <18c1e6480805060207k5255414ey6dacef759d17966@mail.gmail.com> <9fdb569a0805061507j70706aa5ie32ddfeb832ccfa7@mail.gmail.com> Message-ID: <18c1e6480805070004t4f067703ka1fcb90a015cce6@mail.gmail.com> Hi Vlasta. > > tags_lookups[tag][item_dict[tag]] = tags_lookups[tag].get(item_dict[tag], > set()) | set([idx]) > > I thought, whether I am not overestimating myself with respect to the future > maintaining of the code ... :-) Here's a suggestion for readability and maintainability: Make a search() method (possibly on the object storing the text), which takes variable args. You'd declare it something like this: def search(self, **kwargs) And call it like this: text.search(line=123, VCC=1, etc) Probably it would return a list of results (line numbers in the original text?). Then inside the function build up the sets etc, and comment the logic liberally so you can understand it later. This approach should be much more readable the equivalent sqllite + SQL. > > The suggested XML structure is actually almost the one, I use to prepare > and control the input data before converting it to the one presented in the > previous mail :-). The main problem is, that I can't seem to make it fully > valid XML without deforming the structure of the text itself - it can't be > easily decided, what CUSTOM_TAG should be in some places - due to the > overlapping etc. I was originally going to suggest an overlapped tag format, similar to this: Bold textBold and italicisedItalicised But I changed my mind. It's seriously malformed :-) I think that for now, your format, where your marker values remain 'active' until changed to another value is the best way way to go. XML's problems with this sort of thing are a know limitation. See this link: http://en.wikipedia.org/wiki/XML#Disadvantages_of_XML "Expressing overlapping (non-hierarchical) node relationships requires extra effort" There is some research into the subject, but no major (ie widely-used) Python libraries as far as I can tell. Google for "overlapping markup" and "python overlapping markup" for more information. Here's one interesting page I found: http://www.wilmott.ca/python/xmlparser.html#OVERLAPPED It discusses the issue in detail, and comes with a Python implementation (I haven't checked it). David. From jcd at sdf.lonestar.org Fri May 23 10:04:52 2008 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Fri, 23 May 2008 10:04:52 -0400 Subject: Why is math.pi slightly wrong? In-Reply-To: <5504f9ac0805221206m452a73f8q1b08e2d15e58cfb2@mail.gmail.com> References: <6b7a57e3-0f0e-4b52-a2e8-246491dd0e7f@x35g2000hsb.googlegroups.com> <5504f9ac0805221206m452a73f8q1b08e2d15e58cfb2@mail.gmail.com> Message-ID: <1211551492.3332.8.camel@aalcdl07.lib.unc.edu> On Thu, 2008-05-22 at 15:06 -0400, Dan Upton wrote: > Who wants to verify that that's correct to that many digits? ;) Verified. I checked it against the million digits on piday.org, by putting each into a string, stripping out spaces and newlines, and doing: >>> piday[:len(clpy)] == clpy False >>> piday[:len(clpy)-1] == clpy[:-1] True >>> print piday[len(clpy)-10:len(clpy)+1] 44893330963 >>> print clpy[-10:] 4489333097 >>> So the last digit doesn't match, even accounting for rounding, but that's probably because it was calculated to the bit, not to the digit. From goldnery at gmail.com Sat May 10 13:20:00 2008 From: goldnery at gmail.com (Gandalf) Date: Sat, 10 May 2008 10:20:00 -0700 (PDT) Subject: Simple question References: <68lj5oF2sudm7U1@mid.individual.net> <205f1f1e-073b-4edc-ad18-59d1d1b065d6@59g2000hsb.googlegroups.com> <4825afc8$0$14350$e4fe514c@news.xs4all.nl> Message-ID: <8825cf75-8b21-4bca-bba2-97b817b11ebe@a23g2000hsc.googlegroups.com> Thanks guys I think you miss understood me. i have been mining to use python to create a none web application. And i found out that i can ran python scripts by calling them from CMD or just raning them from windows From deets at nospam.web.de Sun May 18 10:53:41 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 18 May 2008 16:53:41 +0200 Subject: writing python extensions in assembly In-Reply-To: References: Message-ID: <69au85F31e943U1@mid.uni-berlin.de> > Also, from the gcc manpage, apparently 387 is the default when > compiling for 32 bit architectures, and using sse instructions is > default on x86-64 architectures, but you can use -march=(some > architecture with simd instructions), -msse, -msse2, -msse3, or > -mfpmath=(one of 387, sse, or sse,387) to get the compiler to use > them. > > As long as we're talking about compilers and such... anybody want to > chip in how this works in Python bytecode or what the bytecode > interpreter does? Okay, wait, before anybody says that's > implementation-dependent: does anybody want to chip in what the > CPython implementation does? (or any other implementation they're > familiar with, I guess) There isn't anything in (C)Python aware of these architecture extensions - unless 3rd-party-libs utilize it. The bytecode-interpreter is machine and os-independent. So it's above that level anyway. And AFAIK all mathematical functionality is the one exposed by the OS math-libs. Having said that, there are of course libs like NumPy that do take advantage of these architectures, through the use of e.g. lib atlas. Diez From arnodel at googlemail.com Fri May 9 02:02:47 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Fri, 09 May 2008 07:02:47 +0100 Subject: anagram finder / dict mapping question References: Message-ID: "Kam-Hung Soh" writes: > I avoid creating a temporary variable if it's only used once > immediately, so I would have written: > > newtlist = ''.join(sorted(list(line))) Or ''.join(sorted(line)) as sorted() works with any iterable. -- Arnaud From protected at myshelter.net Sun May 4 05:39:59 2008 From: protected at myshelter.net (Protected) Date: Sun, 4 May 2008 10:39:59 +0100 Subject: Please help - Tkinter not doing anything In-Reply-To: <237aa3894dff4c8976896df85f4d7d23@localhost> References: <20562a9d-200c-40ae-a850-eb0f9a943d3f@l42g2000hsc.googlegroups.com> <237aa3894dff4c8976896df85f4d7d23@localhost> Message-ID: <3ab5d06a0805040239m6cf12d39ufcde4fcc585f81e4@mail.gmail.com> Good thinking. It was indented with spaces, so I replaced them with tabs. Now I'm getting a SyntaxError: invalid syntax in root = Tk(). If I split the code in two parts (with the second one beginning in that line) and run them separately, I get no errors, but still nothing happens. class Application(Frame): def say_hi(self): print "hi there, everyone!" def createWidgets(self): self.QUIT = Button(self) self.QUIT["text"] = "QUIT" self.QUIT["fg"] = "red" self.QUIT["command"] = self.quit self.QUIT.pack({"side": "left"}) self.hi_there = Button(self) self.hi_there["text"] = "Hello", self.hi_there["command"] = self.say_hi self.hi_there.pack({"side": "left"}) def __init__(self, master=None): Frame.__init__(self, master) self.pack() self.createWidgets() var root = Tk() app = Application(master=root) app.mainloop() root.destroy() On Sun, May 4, 2008 at 12:33 PM, Q4 wrote: > On Sun, 4 May 2008 02:23:37 -0700 (PDT), Protected > wrote: > > Hello. I'm a complete newbie trying to learn Python. I decided to try > > some Tkinter examples, including the one from the library reference, > > but they don't seem to do anything! Shouldn't there be, like, a > > dialog? > > > > I'm running Windows XP and using IDLE. You can assume my version of > > Python is the latest. > > -- > > http://mail.python.org/mailman/listinfo/python-list > > If you just copy the code from the python doc the indentation might be > broken. > Send the code and I'll take a look at it. > > Do you get any errors? > > -- > My website: > http://www.riddergarn.dk/koder/ > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Thu May 15 05:48:25 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 15 May 2008 06:48:25 -0300 Subject: "indexed properties"... References: Message-ID: En Wed, 14 May 2008 18:15:41 -0300, David C. Ullrich escribi?: > Having a hard time phrasing this in the form > of a question... > > The other day I saw a thread where someone asked > about overrideable properties and nobody offered > the advice that properties are Bad. So maybe we've > got over that. I suppose properties could have > Bad consequences if a user doesn't know they exist > and think that a certain property of an object is > just an ordinary attribute. But that applies to > almost any aspect of any language. > > If a person comes from, say, Object Pascal (Delphi) > then properties are hard to live without. The > other day I decided I wanted what OP calls an > "indexed property" or "array property". Couldn't > figure out how to make a _property_ behave that way. > So I read a little bit about descriptors, and a > few minutes later I had an indexedproperty thing > that works just like property, except it gives > an indexed property! This is just too cool. > > Why? For example, a Matrix should have a row[n] > property allowing things like > > m.row[0] = m.row[1] + m.row[2] > > Ok, you could do _that_ by just making row > an ordinary list of Row objects. But then > you'd have to say > > m.row[0] = Row([1,2,3]) > > where I want to be able to say > > m.row[0] = [1,2,3] > > and have the Row created automatically. > > _Also_ with these indexed properties my Matrix > can have m.row[j] and m.col[k] that look exactly > the same to a client - we don't want to store a > list of rows internally and also store the same > data in a list of columns. Too cool. > > Hmm, none of that's a valid excuse for a post here. > Um, right, here we go: Anyone see problems or > possible improvements with the implementation > of indexedproperty below? > > """indexed.py: "indexedproperty" works more or less > like "property" except it gives what in Object Pascal > would be an "indexed property". See the > __name__="__main__" section below for a demo > > """ > > class WriteOnlyIP(Exception): > def __str__(self): > return """ > > indexed property is write-only > > """ > > class ReadOnlyIP(Exception): > def __str__(self): > return """ > > indexed property is read-only > > """ > > class indexedproperty(object): > def __init__(self, getitem=None, setitem=None): > self.getitem = getitem > self.setitem = setitem > > def __get__(self, obj, owner): > self.obj = obj > return self > > def __getitem__(self, index): > if self.getitem: > return self.getitem(self.obj, index) > else: > raise WriteOnlyIP > > def __setitem__(self, index, value): > if self.setitem: > self.setitem(self.obj, index, value) > else: > raise ReadOnlyIP > > > if __name__ == "__main__": > > class AClass(object): > def __init__(self): > self.cells = [[0,0], [0,0]] > > def SetCell(self, (row, col), value): > self.cells[row][col] = value > > def GetCell(self, (row, col)): > return self.cells[row][col] > > cell = indexedproperty(GetCell, SetCell) > > C = AClass() > for row in range(2): > for col in range(2): > C.cell[row, col] = "row: %s, col: %s" % (row, col) > > for row in range(2): > for col in range(2): > print C.cell[row, col] > > C.cell[0,0], C.cell[1,1] = C.cell[1,1], C.cell[0,0] > > print "After C.cell[0,0], C.cell[1,1] = C.cell[1,1], C.cell[0,0]:" > > for row in range(2): > for col in range(2): > print C.cell[row, col] > -- Gabriel Genellina From wuwei23 at gmail.com Tue May 13 22:55:50 2008 From: wuwei23 at gmail.com (alex23) Date: Tue, 13 May 2008 19:55:50 -0700 (PDT) Subject: I'm stuck in Python! References: <0563506d-bd36-404d-8961-4c4c5d1cc029@t54g2000hsg.googlegroups.com> Message-ID: On May 14, 5:41 am, "inhahe" wrote: > "George Sakkis" wrote in message > > You must be new here. It is an AS (Artificial Stupidity) trolling bot, > > you can safely ignore its posts. > > How does it generate text? My guess is by inhaling a lot of intoxicants. From mail at timgolden.me.uk Thu May 29 08:00:59 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 29 May 2008 13:00:59 +0100 Subject: [python-win32] How to get all the variables in a python shell In-Reply-To: <483E650B.5060902@timgolden.me.uk> References: <483E650B.5060902@timgolden.me.uk> Message-ID: <483E9AFB.2040402@timgolden.me.uk> <<< No Message Collected >>> From fiacre.patrick at gmail.com Fri May 23 01:46:16 2008 From: fiacre.patrick at gmail.com (Andrew Lee) Date: Fri, 23 May 2008 01:46:16 -0400 Subject: MVC In-Reply-To: <8a269063-ae96-4707-afdc-5d2c9270e0ff@a9g2000prl.googlegroups.com> References: <8a269063-ae96-4707-afdc-5d2c9270e0ff@a9g2000prl.googlegroups.com> Message-ID: <48365a28$0$11628$607ed4bc@cv.net> George Maggessy wrote: > Hi Gurus, > > I'm a Java developer and I'm trying to shift my mindset to start > programming python. So, my first exercise is to build a website. > However I'm always falling back into MVC pattern. I know it's a > standard, but the implementation language affects the use of design > patter. So, here goes my question. Is that OK if I follow this? Should > I create DAOs, View Objects, Controllers and etc? Is there any sort of > best practice / standard to Python? > > Cheers, > George Look at Pylons. From wizzardx at gmail.com Tue May 6 11:04:34 2008 From: wizzardx at gmail.com (David) Date: Tue, 6 May 2008 17:04:34 +0200 Subject: How do you debug memory usage? In-Reply-To: <18c1e6480805060740w13a4a04dl36c5e09aff0cf047@mail.gmail.com> References: <18c1e6480805060627y32aecc65wf9b4874c7f37590@mail.gmail.com> <3de8e1f70805060721n64944a6ep3592a4e2b7f63b2e@mail.gmail.com> <18c1e6480805060740w13a4a04dl36c5e09aff0cf047@mail.gmail.com> Message-ID: <18c1e6480805060804h33b54268o9a3cb5545909926e@mail.gmail.com> > > I'll check a few of those results and post to the list if I find something good. > It looks like Heapy, part of the Guppy project can do this: http://guppy-pe.sourceforge.net/#Heapy David. David. From duncan.booth at invalid.invalid Wed May 14 10:55:45 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 14 May 2008 14:55:45 GMT Subject: [off-topic] Usenet References: <6bafdf82-cf8a-42cd-9f72-d98a39fab5b5@j22g2000hsf.googlegroups.com> Message-ID: hdante wrote: > How can I access Usenet without using Google Groups ? (my ISP doesn't > have a NNTP server). Do you recommend doing so ? Yes, even those ISP's who do have a news server often seem to make a mess of maintaining it. I use news.individual.net which seems to do a pretty good job of filtering out spam messages (or at least I see a lot more messages complaining about spam messages than spam messages themselves). Also, it is a lot cheaper than most third party news servers: 10EUR per year for 25,000 newsgroups. See http://news.individual.net/ > What's your prefered news reader ? XNews, but that's mostly just because I'm used to it. It is getting a bit elderly these days and doesn't handle non-ascii encodings very well. It does have good scorefile support though. I use Hamster to actually retrieve news: Hamster runs as a local newsserver and pulls feeds from as many different news servers as I want to configure presenting them all as though they come from the same server. That means I can use my ISPs server as a backup in case I can't access news.individual.net for any reason (my previous ISP kept 'accidentally' throttling usenet access): Hamster just merges the newsfeeds together and is intelligent enough not to fetch a message twice from different servers. I also recommend Gmane which provides a free news server for most mailing lists: mailing lists are a lot more manageable when gatewayed into a news server. If you just want to access comp.lang.python I think you'll find the mailing list to which it is connected is available for free on Gmane. From wuwei23 at gmail.com Wed May 21 22:48:01 2008 From: wuwei23 at gmail.com (alex23) Date: Wed, 21 May 2008 19:48:01 -0700 (PDT) Subject: Publish a program References: <4833f0ff_2@news.tm.net.my> <48342434_2@news.tm.net.my> Message-ID: <8242bac2-7bbe-472a-8079-cf249e02e4e8@s21g2000prm.googlegroups.com> On May 21, 11:31 pm, TheSaint wrote: > Other idea, I'll apreciate somebody to join and put new views on this > project. Have you thought about putting the full project somewhere like http://code.google.com/ ? Nothing gets comments & criticisms like used code :) From theller at python.net Wed May 21 12:33:35 2008 From: theller at python.net (Thomas Heller) Date: Wed, 21 May 2008 18:33:35 +0200 Subject: [ctypes] convert pointer to string? In-Reply-To: References: Message-ID: <69j16pF33ht4vU1@mid.individual.net> Neal Becker schrieb: > In an earlier post, I was interested in passing a pointer to a structure to > fcntl.ioctl. > > This works: > > c = create_string_buffer (...) > args = struct.pack("iP", len(c), cast (pointer (c), c_void_p).value) > err = fcntl.ioctl(eos_fd, request, args) > > Now to do the same with ctypes, I have one problem. > > class eos_dl_args_t (Structure): > _fields_ = [("length", c_ulong), > ("data", c_void_p)] > ... > args = eos_dl_args_t() > args_p = cast(pointer(args), c_void_ptr).value > fcntl.ioctl(fd, request, args_p) <<< May fail here > > That last may fail, because .value creates a long int, and ioctl needs a > string. > > How can I convert my ctypes structure to a string? It _cannot_ be a c-style > 0-terminate string, because the structure may contain '0' values. > ctypes instances support the buffer interface, and you can convert the buffer contents into a string: >>> from ctypes import * >>> c_int(42) c_long(42) >>> buffer(c_int(42)) >>> buffer(c_int(42))[:] '*\x00\x00\x00' >>> Thomas From Lie.1296 at gmail.com Fri May 30 04:31:03 2008 From: Lie.1296 at gmail.com (Lie) Date: Fri, 30 May 2008 01:31:03 -0700 (PDT) Subject: Hungarian Notation References: Message-ID: <80e11ea2-e107-4dae-8ca8-779e143bbae5@p25g2000pri.googlegroups.com> On May 27, 12:28?pm, "inhahe" wrote: > Does anybody know of a list for canonical prefixes to use for hungarian > notation in Python? ?Not that I plan to name all my variables with hungarian > notation, but just for when it's appropriate. If it was me, I'd use an empty-defined class: class Fake(object): pass data = 'headinfo=trash;headtrash=info' Header = Fake() Header.Str = data Header.Dict = parse(data) it saves name if it's important (alternatively, you may also use a dict or a tuple/list to store the string/dict pair). But using Fake class just like that is difficult to work with if I need to "write" to the data (not read only) and synchronizes the data, in that case, it's easy to extend the Fake Class: class Fake(object): def __init__(self, data): self.data = parse(data) def toStr(self): return str(self.data) def fromStr(self, s): self.data = parse(s) Str = property(toStr, fromStr) def toDict(self): return self.data def fromDict(self, s): self.data = s Dict = property(toDict, fromDict) you might go as far as overriding __str__ and __repr__ as appropriate. From takaurai at gmail.com Thu May 29 03:26:45 2008 From: takaurai at gmail.com (=?ISO-2022-JP?B?GyRCJD8kKxsoQg==?=) Date: Thu, 29 May 2008 00:26:45 -0700 (PDT) Subject: How do I tell "imconplete input" from "valid input"? Message-ID: <52dfcd24-3182-4dc7-9141-4324864783e5@g16g2000pri.googlegroups.com> Hi everyone, I am developing the console which has the embedded Python interactive interpreter. So, I want to judge whether current command is complete or not. Below is good example to solve this problem. // // http://effbot.org/pyfaq/how-do-i-tell-incomplete-input-from-invalid-input.htm // int testcomplete(char *code) /* code should end in \n */ /* return -1 for error, 0 for incomplete, 1 for complete */ { node *n; perrdetail e; n = PyParser_ParseString(code, &_PyParser_Grammar, Py_file_input, &e); if (n == NULL) { if (e.error == E_EOF) return 0; return -1; } PyNode_Free(n); return 1; } But, I think this code has a problem. For example, when argument 'code' has below python command, if x % 2: print "odd" at the current situation, this function returns COMPLETE! But, I think that sometimes users want to type "else" statement. So, I expected to get INCOMPLETE from this function, but I didn't. How should I do it? Thanks, urai From Lie.1296 at gmail.com Sun May 25 14:09:28 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 25 May 2008 11:09:28 -0700 (PDT) Subject: php vs python References: <5l%Yj.77$mz3.53@fe101.usenetserver.com> Message-ID: On May 22, 3:10?am, notbob wrote: > I'm not posting this just to initiate some religious flame war, though it's > the perfect subject to do so. ?No, I actaully want some serious advice about > these two languages and since I think usenet is the best arena to find it, > here ya' go. > > So, here's my delimna: I want to start a blog. ?Yeah, who doesn't. ?Yet, I > want learn the guts of it instead of just booting up some wordwank or > whatever. ?I started to learn python, but heard php was easier or faster or > more like shell scripting or... fill in the blank. ?Anyway, so I change over > to learning php. ?Then I run across that blog, Coding Horror, and start > reading articles like this: > > http://www.codinghorror.com/blog/archives/001119.html > > Now what? ?Go back to python. ?Soldier on with php? ?What do I know? ?Not > much. ?I can setup mysql and apache,, but don't know how to use 'em, really. > I use emacs and run slackware and can fumble my way through bash scripts, > but I can't really write them or do lisp. ?I've taken basic basic and basic > C, but am barely literate in html. ?Sometimes it seems overwhelming, but I > persevere because it's more fun/challenging than video games, which bore me > to tears. ? > > Well, that's my actual question, then. ?Is php really so bad I'm just > wasting my time? ?Or is it really the quickest way to blog functionality? > Would I be better served in the long run learning python, which claims to be > easy as pie to learn/program (still looks hard to me). ?I admit I'm no code > geek. ?But, I'm not completely brain dead, either, and I need something to > keep my geezer brain sparking. ?What say ye? > > nb My advice? Mix a bit of both. PHP's pros is it's tight integration with HTML, it's really easy to slip small, short PHP snippets here and there. Server side includes for example, is a short one-liner, in python it would involve reading the original file, finding where and what to slip, then reading the include file then concatenates the files then send it to the requester, or you could setup an engine for you which might take some time and patience. On the other hand, python is a general-purpose language, and is a better designed language. Writing the blog back-end in Python is probably easier than in PHP while writing the interface-related codes is probably easier in PHP. You might also consider calling python code from the PHP. From semanticist at gmail.com Wed May 7 21:13:27 2008 From: semanticist at gmail.com (Miles) Date: Wed, 7 May 2008 21:13:27 -0400 Subject: slicing lists In-Reply-To: References: Message-ID: On Wed, May 7, 2008 at 7:46 PM, Ivan Illarionov wrote: > On Wed, 07 May 2008 23:29:27 +0000, Yves Dorfsman wrote: > > > Is there a way to do: > > x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] > > x[0,2:6] > > > > That would return: > > [0, 3, 4, 5, 6] > > IMHO this notation is confusing. > > What's wrong with: > [0]+x[2:6] I think Yves meant to return [1, 3, 4, 5, 6], as in Perl's list slicing: my @x = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10); return @x[0, 2..6]; // returns (1, 3, 4, 5, 6) This isn't incredibly efficient, but it does what you want (I think): from itertools import chain class multisliceable(list): def __getitem__(self, slices): if isinstance(slices, (slice, int, long)): return list.__getitem__(self, slices) else: return list(chain(*[list.__getitem__(self, s) if isinstance(s, slice) else [list.__getitem__(self, s)] for s in slices])) p = open('/etc/passwd') q = [multisliceable(e.strip().split(':'))[0,2:] for e in p] -Miles From deets at nospam.web.de Wed May 21 09:39:10 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 21 May 2008 15:39:10 +0200 Subject: C-like assignment expression? References: <68b5d090-9e3b-4e7d-9dda-fc1b099822c2@m73g2000hsh.googlegroups.com> <48340412$0$10773$426a74cc@news.free.fr> <87fxsbzxn4.fsf@mulj.homelinux.net> <7df99fd4-21c9-49a1-ba65-e55794fd4c12@26g2000hsk.googlegroups.com> <75ca6227-435c-46bf-8701-aa326d3533e0@p25g2000hsf.googlegroups.com> Message-ID: <69in0tF33sdj6U2@mid.uni-berlin.de> cokofreedom at gmail.com wrote: > On May 21, 3:12 pm, "boblat... at googlemail.com" > wrote: >> On May 21, 1:47 pm, Hrvoje Niksic wrote: >> >> > Although that solution is pretty, it is not the canonical solution >> > because it doesn't cover the important case of "if" bodies needing to >> > access common variables in the enclosing scope. (This will be easier >> > in Python 3 with 'nonlocal', though.) The snippet posted by Diez is >> > IMHO closer to a canonical solution to this FAQ. >> >> Hello everybody, >> >> thanks for the various answers. I'm actually pretty puzzled because I >> expected to see some obvious solution that I just hadn't found before. >> In general I find Python more elegant and syntactically richer than C >> (that's where I come from), so I didn't expect the solutions to be a >> lot more verbose and/or ugly (no offense) than the original idea which >> would have worked if Python's assignment statement would double as >> expression, as in C. >> >> Thanks again, >> robert >> >> PS: Since I'm testing only three REs, and I only need the match >> results from one of them, I just re-evaluate that one. > > Is it really a lot to change to have it > > if my_re1.match(line): > match = my_re1.match(line) > elseif my_re2.match(line): > match = my_re2.match(line) > elseif my_re3.match(line): > match = my_re3.match(line) > > ? > > That reads clearly to me... And wastes time. regular expressions can become expensive to match - doing it twice might be hurtful. Diez From roy at panix.com Fri May 2 00:16:05 2008 From: roy at panix.com (Roy Smith) Date: Fri, 02 May 2008 00:16:05 -0400 Subject: #!/usr/bin/env python vs. #!/usr/bin/python References: <87abj91j8u.fsf@benfinney.id.au> Message-ID: In article <87abj91j8u.fsf at benfinney.id.au>, Ben Finney wrote: > I've never clearly understood why people want to use "#! /usr/bin/env > python", which is prone to finding a different Python from the one > installed by the operating system. I'd be interested to see what > responses are in favour of it, and what the reasoning is. > > One possible reason is that the programmer is attempting to allow for > systems where Python has been installed, but not from an operating > system package. You've got it exactly. I'm currently using Python to write unit tests as part of a build system. Many of our development boxes don't have python installed in /usr/bin (or perhaps at all). And even if they did, we might want to use a different version of Python on different branches of the code. We've got Python built for all our platforms and the binaries stored in our source control system. When you check out a particular branch, you get the right version of Python for that branch. By having the Python scripts start with #!/usr/bin/env python, I can select the version of Python I want just by changing the environment. Then, of course, I recently ran across a machine where env was installed in /opt/gnu/bin instead of /usr/bin. Sigh. Sometimes you just can't win. From deets at nospam.web.de Mon May 26 12:32:37 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 26 May 2008 18:32:37 +0200 Subject: integration with browser References: <69vmlgF35akucU1@mid.uni-berlin.de> Message-ID: <6a0722F33j3q5U1@mid.uni-berlin.de> nik600 wrote: > Both win and linux if possible i don't have preference for gui. Thanks Qt4 now contains the WebKit html widget. Diez From castironpi at gmail.com Fri May 16 11:21:07 2008 From: castironpi at gmail.com (castironpi) Date: Fri, 16 May 2008 08:21:07 -0700 (PDT) Subject: Instance of class "object" References: <9dec1377-270f-46d6-bac8-f003e32f9bec@m36g2000hse.googlegroups.com> Message-ID: On May 16, 9:41 am, castironpi wrote: > On May 16, 8:56 am, castironpi wrote: > > > > > > > On May 16, 8:51 am, castironpi wrote: > > > > On May 16, 4:26 am, Peter Otten <__pete... at web.de> wrote: > > > > > ?? wrote: > > > > > I wonder why below does not work. > > > > > > a = object() > > > > > a.b = 1 # dynamic bind attribute failed... > > > > > The implementation of slots depends on that behaviour: > > > > >http://docs.python.org/ref/slots.html > > > > > > Does this strange behavior break the LSP (Liskov substitution principle)? > > > > > Can you expand on that? > > > > > Peter > > > > Spirals are important. > > > I'd be modeling streams, in par. crossing them.- Hide quoted text - > > > - Show quoted text - > > Python 3.0a5 (py3k:62932M, May 9 2008 > win32 > Type "help", "copyright", "credits" or>>> import parser > >>> import compiler > > Traceback (most recent call last): > File "", line 1, in > ImportError: No module named compiler > > Does anyone want to model mic-based soundwaves? My recent project has > been color progression over time, and talking about compilers.- Hide quoted text - > > - Show quoted text - Can 'compiler' come back in? I want to build a compiler + exec. From zethex at hotmail.com Thu May 22 00:59:47 2008 From: zethex at hotmail.com (Zethex) Date: Wed, 21 May 2008 21:59:47 -0700 (PDT) Subject: Bit of List replacing trouble (newbie) Message-ID: <17397379.post@talk.nabble.com> At the moment i'm doing a piece of work for school and I'm stuck at the moment. I have a list of words, for example: Sentence = ['A', 'dog', 'walked', 'across', 'the', 'street'] I have another list which I need to use to replace certain words, and its in the form of: synonyms = [ [canine, [dog, puppy, bulldog]], [ road, [street, avenue, court]] ] What the procedure must do is replace dog with canine, and street with road. Therefore if a word is in the sentence and appears on the right side of the list entry, replace it with the left entry. I can't seem to find a help file with what I'm after. I'm just wondering if anyone can help me on the right track on how to start this procedure, maybe not an answer but just a little help on how to get started as I'm complete stuck right now. -- View this message in context: http://www.nabble.com/Bit-of-List-replacing-trouble-%28newbie%29-tp17397379p17397379.html Sent from the Python - python-list mailing list archive at Nabble.com. From maxm at mxm.dk Mon May 26 04:11:22 2008 From: maxm at mxm.dk (Max M) Date: Mon, 26 May 2008 10:11:22 +0200 Subject: php vs python In-Reply-To: References: <5l%Yj.77$mz3.53@fe101.usenetserver.com> <37b112d8-a3ba-446d-9d2f-d907d93c637b@w8g2000prd.googlegroups.com> <-t-dnWQ4bZN2MaTVnZ2dnUVZ_qGdnZ2d@comcast.com> <68cb8bb1-4cc5-4a28-8915-46e7d4e316d9@d1g2000hsg.googlegroups.com> Message-ID: Jerry Stuckle skrev: > Ivan Illarionov wrote: > I repeat. The language has nothing to do with it. Good programmers > write good code. Lousy programmers write bad code. That is simply not true! The languag has a lot to do with what you can do in any given time. You can write good code in a bad language. But it will take lot more time. And so it will not be done. Your argument, if it was true, would mean that I could just as well write a blog in c or even assembler, and still write optimal code. php is a terrible language and I cringe whenever I have to use it. In fact I have turned down many jobs because they were written in php. It is simply to frustrating. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From saluk64007 at gmail.com Sun May 4 20:15:06 2008 From: saluk64007 at gmail.com (Patrick Mullen) Date: Sun, 4 May 2008 17:15:06 -0700 Subject: Are rank noobs tolerated, here? In-Reply-To: References: Message-ID: There is also the python tutor list: http://mail.python.org/mailman/listinfo/tutor Which is more geared toward beginners. Although I am subscribed to both lists, and they are both matched by the same filter for me so I wont know the difference... But there may be people who are not subscribed to both lists and don't care to listen to beginner discussions. I wouldn't know. There is python irc as well: #python on irc.freenode.net. If you just have a quick question you may be better off trying there first. -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Thu May 15 10:06:31 2008 From: castironpi at gmail.com (castironpi) Date: Thu, 15 May 2008 07:06:31 -0700 (PDT) Subject: no inputstream? References: <692sk0F3090hfU1@mid.uni-berlin.de> <46abd84e-f943-48a5-94b9-81f2f47cc887@f63g2000hsf.googlegroups.com> <974fe6b4-7e53-4a5f-bd66-6b40aa718d5d@34g2000hsh.googlegroups.com> Message-ID: <74e109f2-724e-4271-8520-32e62163b843@j22g2000hsf.googlegroups.com> On May 15, 9:02?am, max wrote: > On May 15, 9:51?am, castironpi wrote: > > > > > > > On May 15, 8:37?am, Marc 'BlackJack' Rintsch wrote: > > > > On Thu, 15 May 2008 06:08:35 -0700, max wrote: > > > > i currently have locations of the mp3s in question as strings, which > > > > works for parsing local files, but gives me a "No such file or > > > > directory" error when it tries to process URLs. ?it seems terribly > > > > inefficient to download each mp3 just to get at that small tag data, > > > > and i assume there's a way to do this with file() or open() or > > > > something, i just can't get it to work. > > > > You can use `urllib2.urlopen()` to open URLs as files. ?But if you deal > > > with ID3 V1 tags you'll have to download the file anyway because those are > > > in the last 128 bytes of an MP3 file. > > > > Ciao, > > > ? ? ? ? Marc 'BlackJack' Rintsch > > > Just don't import time. ?What would you do with an autolocking timer, > > such as time.sleep( ) on a thread? ?I am tongue tied in the presence > > of a lady. > > thanks guys. ?i guess i just figured there'd be a way to get at those > id3 bytes at the end without downloading the whole file. ?if java can > do this, seems like i should just stick with that implementation, no?- Hide quoted text - > > - Show quoted text - I can post life1 to this: lifeOne, lifeone, lifea perhaps. From weinhand at unileoben.ac.at Wed May 7 02:03:48 2008 From: weinhand at unileoben.ac.at (Weinhandl Herbert) Date: Wed, 07 May 2008 08:03:48 +0200 Subject: DISLIN 9.3 starting issues In-Reply-To: <9f7035c5-38ad-4e46-85b4-4fb29d791ddb@m44g2000hsc.googlegroups.com> References: <9f7035c5-38ad-4e46-85b4-4fb29d791ddb@m44g2000hsc.googlegroups.com> Message-ID: <48214644$0$11610$3b214f66@aconews.univie.ac.at> adolfo wrote: > I built the following little program: > > from numpy import * > from dislin import * > > def main(): > x = arange (100, typecode=Float32) > plot (x, sin (x/5)) > disfin () > > main() > > *** Here are the problems: > > 1. The "from Numeric import" statement did not work, I replaced with > "from numpy import*" and no complains form the interpreter. > > 2. If I enyter "from dislin import *" I get: > Traceback (most recent call last): > File "", line 1, in > from dislin import * > ImportError: No module named dislin > > I checked the environmental variables paths and it all seems Ok: > c:\dislin > SYSTEM PATH = %SystemRoot%\system32;%SystemRoot%;\System32;\Wbem;C: > \Archivos de programa;\QuickTime;\QTSystem;C:\dislin\win > PYTHON PATH = C:\Archivos de programa\ArcGIS\bin;c:\dislin\python the environment variable is PYTHONPATH and i has to contain the directory where the dislin.pyd module can be found; you should set environment variable DISLIN too (see python.inf, which you can find in the dislin-distribution) depending on your python version (2.4 or 2.5) you need the correct dislin-distribution, because dislin is a fortran/c library with a layer for python access. and try some examples of the distribution (they are importing only dislin and math modules). hth Herbert From netizen at gmx.de Mon May 26 06:30:45 2008 From: netizen at gmx.de (Michael Fesser) Date: Mon, 26 May 2008 12:30:45 +0200 Subject: php vs python References: <5l%Yj.77$mz3.53@fe101.usenetserver.com> <37b112d8-a3ba-446d-9d2f-d907d93c637b@w8g2000prd.googlegroups.com> <-t-dnWQ4bZN2MaTVnZ2dnUVZ_qGdnZ2d@comcast.com> <68cb8bb1-4cc5-4a28-8915-46e7d4e316d9@d1g2000hsg.googlegroups.com> Message-ID: .oO(Ivan Illarionov) >On Sun, 25 May 2008 17:09:43 -0400, Jerry Stuckle wrote: >> Not at all. I do it every day. >> >> And BTW - yes, I write Python, also. But I find I can write better, >> faster code in PHP. > >I find I can write better code in Python. Maybe it's just a matter of >personal preference? Exactly. >> Do you write PHP? >I did. And I hated it very much. See, for me it's the other way round. I really hate Python syntax. I only touch it for scripting Paint Shop Pro or if some third-party Python script lacks proper documentation and I have to wade through the sources to find the informations I need. So where does this leave us? Nowhere. A language is just a tool and a tool is just as good as the one who uses it. This was said often enough. If you hate PHP, that's OK, but it doesn't make PHP a bad or even inferior language. Micha From bj_666 at gmx.net Mon May 19 02:22:08 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 19 May 2008 06:22:08 GMT Subject: Reading Java byte[] data stream over standard input References: <59da4e60-f4ac-4fa0-9c86-5e4a0c7cf423@m73g2000hsh.googlegroups.com> Message-ID: <69ckkgF31kls5U1@mid.uni-berlin.de> On Sun, 18 May 2008 22:11:33 -0700, sapsi wrote: > I am using HadoopStreaming using a BinaryInputStream. What this > basically does is send a stream of bytes ( the java type is : private > byte[] bytes) to my python program. > > I have done a test like this, > while 1: > x=sys.stdin.read(100) > if x: > print x > else: > break > > Now, the incoming data is binary(though mine is actually merely ascii > text) but the output is not what is expected. I expect for e.g > > all/86000/114.310.151.209.60370-121.110.5.176.113\n62485.9718 > 118.010.241.12 60370 128.210.5.176 > > However i get a 1 before all and a 4 just after \n and before the 6. > > My question is : how do i read binary data(Java's byte stream) from > stdin? > Or is this actually what i'm getting? If there's extra data in `x` then it was sent to stdin. Maybe there's some extra information like string length, Java type information, or checksums encoded in that data!? Ciao, Marc 'BlackJack' Rintsch From a.schmolck at gmail.com Sun May 4 09:00:59 2008 From: a.schmolck at gmail.com (Alexander Schmolck) Date: Sun, 04 May 2008 14:00:59 +0100 Subject: is +=1 thread safe References: <4819DA2D.3030508@ggmail.com> <481BD50F.5080608@ggmail.com> <8a0d4152-af47-4c83-bf78-c5ceda7c9fbd@8g2000hse.googlegroups.com> Message-ID: Gary Herron writes: > But... It's not! > > A simple test shows that. I've attached a tiny test program that shows this > extremely clearly. Please run it and watch it fail. In [7]: run ~/tmp/t.py final count: 2000000 should be: 2000000 (I took the liberty to correct your test to actually do what I said, namely use a numpy.array; just replace ``count = 0`` with ``import numpy; count = numpy.array(0)``). 'as p.s. please don't send me copies to on-list replies, at least not without explicitly mentioning the fact -- I've got better things to do then guessing whether something was meant to be off-list or not. From phil at riverbankcomputing.com Sun May 4 11:04:04 2008 From: phil at riverbankcomputing.com (Phil Thompson) Date: Sun, 4 May 2008 16:04:04 +0100 Subject: pyqt4: trouble making custom widget appear in mainwindow In-Reply-To: References: Message-ID: <200805041604.04448.phil@riverbankcomputing.com> On Sunday 04 May 2008, Lance Gamet wrote: > Hi, > about 3 years ago I did a bit of Qt3 and 4 on C++, now I am trying to do > something in python. > > A QMainWindow subclass as my mainwindow. Its basically a frame with no > widgets of its own. > > Several QWidget subclasses each representing a mode of the program, these > widgets should appear in the mainwindow depending on what part of the > program is being used. > > I have made the main window and a couple of widgets with designer-qt4 and > generate a Ui_Whatever.py with pyuic4 and subclass that. > > My problem is I cant get my widgets to appear in the main window. > > My MainWindow.py looks like (imports etc skipped): > > class MainWindow(QMainWindow, Ui_MainWindow): > def __init___(self): > QMainWindow.__init__(self) > self.setupUi(self) > > def newTeamWizardMode(self): > Widget = QWidget() > self.newTeamWizard = CreateNewTeamWizard(Widget) > self.newTeamWizard.setGeometry(QRect(0,0,90, 160)) > self.newTeamWizard.setObjectName("newTeamWizard") > self.newTeamWizard.show() > > My CreateNewTeamWizard is defined like so: > > class CreateNewTeamWizard(QWidget, Ui_CreateNewTeamWizard): > def __init___(self, parent = None): > QWidget.__init__(self, parent) > self.setupUi(self) > > In my main program i make the main window and try and add the widget like > this: > > app = Qt.QApplication(sys.argv) > mainWindow = MainWindow() > app.connect(app, Qt.SIGNAL("lastWindowClosed()"), app, Qt.SLOT("quit > ()")) > mainWindow.newTeamWizardMode() > mainWindow.show() > > One thing i tried was changing the CreateNewTeamWizard in > MainWindow.newTeamWizardMode to CreateNewTeamWizard(Widget, self) to > provide the main window as the parent but I get the following error: > > self.newTeamWizard = CreateNewTeamWizard(Widget, self) > TypeError: argument 2 of QWidget() has an invalid type > > I have looked for examples, but everything I have found is a bit too > simple. Creating a single window or widget, displaying it as the programs > main window and exiting when the window is closed. > > I havent found anything to tell me how to make a widget appear in a > mainwindow how I want. > > Any tips? I think QMainWindow.setCentralWidget() is what you are looking for. > If someone can point me to a nice open source program that uses pyqt4 > that might help. The eric4 IDE probably covers most things you'll ever need. Phil From upton at virginia.edu Thu May 29 18:02:53 2008 From: upton at virginia.edu (Dan Upton) Date: Thu, 29 May 2008 18:02:53 -0400 Subject: Python and Flaming Thunder In-Reply-To: <20080529175745.b3e7a579.darcy@druid.net> References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <5c98049e-e62e-4ab1-afed-b0a3e186bd05@w1g2000prd.googlegroups.com> <3dd6fa95-e9fe-4922-a46d-020cf9263469@w4g2000prd.googlegroups.com> <20080529175745.b3e7a579.darcy@druid.net> Message-ID: <5504f9ac0805291502h2813e004k2e32bf820b190364@mail.gmail.com> On Thu, May 29, 2008 at 5:57 PM, D'Arcy J.M. Cain wrote: > I guess I am still new to this group and don't understand its charter. > I wasn't aware that it was a Flaming Blunder group. Can someone please > point me to a newsgroup or mailing list dedicated to the Python > programming language? > Yeah, but if you look past the "FT is better than Python" propaganda, there's some interesting discussion of language design. From skanemupp at yahoo.se Fri May 30 17:08:35 2008 From: skanemupp at yahoo.se (globalrev) Date: Fri, 30 May 2008 14:08:35 -0700 (PDT) Subject: SMS sending and receiving from website? Message-ID: can i send and receive messages from a website using python? how would that work with costs? would the mobileowner pay both ways? From george.sakkis at gmail.com Tue May 20 23:36:07 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 20 May 2008 20:36:07 -0700 (PDT) Subject: namespaces and eval References: <67508298-e382-436b-99a1-4a7fa4be2487@h1g2000prh.googlegroups.com> Message-ID: On May 16, 5:02?pm, Arnaud Delobelle wrote: > dave.g1... at gmail.com writes: > > Sorry for the repost, didnt' quite finish > > > Suppose I have a function in module X that calls eval e.g, > > > X.py > > _______ > > Def foo(bar): > > ? ? ? ? Eval(bar) > > _______ > > > Now eval will be called using the default eval(bar,globals(),locals()) > > and globals will pull in anything in module X. > > > Now I have module Y that calls bar like so > > Y.py > > ________ > > from x import * > > def biz(): > > ? ? ? ? print "Im a silly example!" > > Foo("biz()") > > _______ > > > Python will complain that it cannot find biz because it's not the X > > module. > > > My question - is there any way to a) get a listing of active namespaes > > search ALL active namespaces for a particular variable > > sys.modules gives you all the live modules. > > > b) get the namespace of the caller withing passing it in (here, Y) > > sys._getframe(1).f_globals (resp. sys._getframe(1).f_locals) gives you > the caller's globals (resp. locals). > > > c) do anything else to get biz without passing > > foo("biz()",locals(),globals()) or hacking biz into the __builtin__ > > namespace(don't know if it's even possible, but it defeats the > > purpose of what I'm trying to do) ? > > Functions in Python are objects like any other, and can be passed as > parameters. ?I.e: > > x.py > ---------- > def foo(bar): > ? ? bar() > > > > > > >>> from x import foo > >>> def biz(): print "Boo!" > >>> foo(biz) > Boo! > > > I realize this is here for a reason, but I'm working on something > > that's kind of a hack already > > > Thanks > > dave > > > More gratuitous context. Long story I'm trying to write a hack for a > > concise way of adding arbitrary methods to objects for JPA/JQuery like > > chaning eg. > > > def foo(self): > > ? ? print "foo" > > ? ? return self; > > > wrap(x).foo().foo().foo().foo() etc.... > > What about a composition function instead? I.e. > > compose(foo, foo, foo, foo)(x) > > Here's one that I made earlier:http://www.marooned.org.uk/~arno/python/compose.html Neat, although the order is counter-intuitive; the callables should better be called in the same order they are given in compose(). Here's yet another take on the composition syntax: DONE = object() class Chainable(object): def __init__(self, val): self.val = val def __or__(self, func): if func is DONE: return self.val self.val = func(self.val) return self # Test def double(x): return 2*x def square(x): return x**2 def succ(x): return x+1 >>> print Composable(2) | float | succ | square | double | DONE 18.0 Admittedly 'DONE' is ugly but it's necessary to denote that the piping ends and the final value (rather than the Composable wrapper) should be returned. The OP's wrap class suffers from the same problem but it masks it by overriding __getattr__ in an old-style class. If the class is changed to new-style, it becomes more obvious that wrap(x).foo().foo().foo().foo() returns the wrap object, not x. George From mail at timgolden.me.uk Wed May 14 11:29:32 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 14 May 2008 16:29:32 +0100 Subject: Rename field in Access DB In-Reply-To: References: Message-ID: <482B055C.5050604@timgolden.me.uk> Iain King wrote: > I'm manipulating an MS Access db via ADODB with win32com.client. I > want to rename a field within a table, but I don't know how to. I > assume there is a line of SQL which will do it, but nothing I've tried > (from searching) has worked. > Basic code: > > import win32com.client > connection = win32com.client.Dispatch(r'ADODB.Connection') > DSN = 'PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=dbfile.mdb;' > connection.Open(DSN) > connection.Execute("ALTER TABLE tablename CHANGE from to") #this sql > doesn't work > connection.Close() import os, sys from win32com.client.gencache import EnsureDispatch as Dispatch DATABASE_FILEPATH = r"c:\temp\test.mdb" CONNECTION_STRING = "Provider=Microsoft.Jet.OLEDB.4.0; data Source=%s" % \ DATABASE_FILEPATH if os.path.exists (DATABASE_FILEPATH): os.remove (DATABASE_FILEPATH) adox = Dispatch ("ADOX.Catalog") adox.Create (CONNECTION_STRING) adox = None db = Dispatch ('ADODB.Connection') db.Open (CONNECTION_STRING) try: db.Execute ('CREATE TABLE dtest (id INT, data INT)') db.Execute ('INSERT INTO dtest (id, data) VALUES (1, 2)') try: db.Execute ('SELECT id, newdata FROM dtest') except: print "FAILED as expected" else: print "SUCCEEDED unexpectedly" try: db.Execute ('SELECT id, data FROM dtest') except: print "FAILED unexpectedly" else: print "SUCCEEDED as expected" adox = Dispatch ("ADOX.Catalog") adox.ActiveConnection = db adox.Tables ("dtest").Columns ("data").Name = "newdata" adox.Tables.Refresh () finally: db.Close () db = Dispatch ('ADODB.Connection') db.Open (CONNECTION_STRING) try: try: db.Execute ('SELECT id, data FROM dtest') except: print "FAILED as expected" else: print "SUCCEEDED unexpectedly" try: db.Execute ('SELECT id, newdata FROM dtest') except: print "FAILED unexpectedly" else: print "SUCCEEDED as expected" finally: db.Close () TJG From daveparker at flamingthunder.com Wed May 21 17:29:26 2008 From: daveparker at flamingthunder.com (Dave Parker) Date: Wed, 21 May 2008 14:29:26 -0700 (PDT) Subject: Bug in floating-point addition: is anyone else seeing this? References: <8187c3b6-a772-456f-a54f-0af7babb353e@w34g2000prm.googlegroups.com> Message-ID: <6e4549da-6493-4be5-9ac0-945dd7cca323@q27g2000prf.googlegroups.com> On May 21, 3:17?pm, "Chris Mellon" wrote: > If you're going to use every post and question about Python as an > opportunity to pimp your own pet language you're going irritate even > more people than you have already. Actually, I've only posted on 2 threads that were questions about Python -- this one, and the one about for-loops where the looping variable wasn't needed. I apologize if that irritates you. But maybe some Python users will be interested in Flaming Thunder if only to check the accuracy of the results that they're getting from Python, like I did on this thread. I think most people will agree that having two independent programs confirm a result is a good thing. From bruno.42.desthuilliers at websiteburo.invalid Wed May 7 03:59:06 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 07 May 2008 09:59:06 +0200 Subject: Am I missing something with Python not having interfaces? In-Reply-To: <29716374-c3b2-407e-ac54-ae2a17ccf081@2g2000hsn.googlegroups.com> References: <45de2f7e-484a-4871-bbaa-bf7eed5dfa40@x35g2000hsb.googlegroups.com> <29716374-c3b2-407e-ac54-ae2a17ccf081@2g2000hsn.googlegroups.com> Message-ID: <4821613f$0$4286$426a74cc@news.free.fr> jmDesktop a ?crit : (snip) > On the dynamic typing, > isn't that the same sort of thing that lots of scripting languages > do? This is not restricted to scripting languages - that is, unless you'd call Smalltalk, Erlang or common lisp "scripting languages". Also and FWIW, static typing in C is mostly here to help the compiler optimizing, and it's very common to use void pointers and typecast to get some genericity (cf the sort() function in C stdlib). And you have the same pattern in Java with "generic" containers storing only "object" instances, then you have to cast your objects back to the appropriate type (which may fails, leading to a runtime error). > VBScript doesn't require you to define your variables, You mean "to declare the type of your variables" ? Neither OCaml nor Haskell require this, and they are both statically and strongly typed. > but I > don't really want to use it for anything Neither do I, but not because of dynamic typing. By experience, dynamic typing works just fine for most applications. And by experience too, static typing doesn't magically make your code bullet-proof. > (used to use it a lot in > Classic ASP.) I believe everyone that Python is great, but some of it > doesn't make sense to me as to why. Quite a lot of Java stopped making sens to me since I learned some other languages. And most of the "OO" (hem) complexity, patterns madness etc you'll typically find in Java code only exists because of the language's arbitrary restrictions and lack of expressivity. Learn Python, learn Ruby or (preferably) Smalltalk, learn common lisp or (preferably) Scheme, learn OCaml or (preferably) Haskell, learn Erlang, and you'll find out that there's much more in programming and languages than can be dreamt of in Java's philosophy !-) From castironpi at gmail.com Fri May 16 18:19:49 2008 From: castironpi at gmail.com (castironpi) Date: Fri, 16 May 2008 15:19:49 -0700 (PDT) Subject: save dictionary for later use? References: <99403e9d-4c67-4e3f-a726-7bb02e72423a@m3g2000hsc.googlegroups.com> <9ec97b27-e4a8-40e0-b8b3-a2cdaeba448e@d77g2000hsb.googlegroups.com> <21eb068b-0c96-43f0-a71f-0bb1c2be6ec9@y38g2000hsy.googlegroups.com> Message-ID: On May 16, 4:29?pm, "bruno.desthuilli... at gmail.com" wrote: > On 16 mai, 22:24, globalrev wrote: > > > > > > > On 16 Maj, 21:22, jay graves wrote: > > > > On May 16, 2:17 pm, globalrev wrote: > > > > > i extract info from one file and put it into a dictionary. > > > > i want to save that dictionary for later use, how do i do that? > > > > might save a list of dictionaries or a list of classobjects too if > > > > there is any difference. > > > > use the 'pickle' module.http://docs.python.org/lib/module-pickle.html > > > > ... > > > Jay Graves > > > pickle.dumps(mg) > > pickle.load(mg) > > > 'dict' object has no attribute 'readline' > > dumps load(well i dont know but i get no complaint but running load > > generates that error) > > What about *READING THAT FUCKING MANUAL* ? > > http://docs.python.org/lib/node316.html > """ > dump(obj, file[, protocol]) > ? ? Write a pickled representation of obj to the open file object > file. This is equivalent to Pickler(file, protocol).dump(obj). > > ? ? If the protocol parameter is omitted, protocol 0 is used. If > protocol is specified as a negative value or HIGHEST_PROTOCOL, the > highest protocol version will be used. > > ? ? Changed in version 2.3: Introduced the protocol parameter. > > ? ? file must have a write() method that accepts a single string > argument. It can thus be a file object opened for writing, a StringIO > object, or any other custom object that meets this interface. > > load(file) > ? ? Read a string from the open file object file and interpret it as a > pickle data stream, reconstructing and returning the original object > hierarchy. This is equivalent to Unpickler(file).load(). > > ? ? file must have two methods, a read() method that takes an integer > argument, and a readline() method that requires no arguments. Both > methods should return a string. Thus file can be a file object opened > for reading, a StringIO object, or any other custom object that meets > this interface. > > ? ? This function automatically determines whether the data stream was > written in binary mode or not. > """ > > Example use: > > > > >>> d = dict(a=1, b=2) > >>> f = open("mydict.dat", "w") > >>> pickle.dump(d, f) > >>> f.close() > >>> f = open("mydict.dat") > >>> d2 = pickle.load(f) > >>> f.close() > >>> d2 == d > True > >>> d2 > {'a': 1, 'b': 2} > > Now : it's not the first time - in a couple days - that you ask a > question that you wouldn't have asked if you had taken a couple > minutes doing the tutorial and/or reading the doc. This newsgroup is > *very* tolerant (in most other places on usenet, you would have get a > raw RTFM on the first question, and a PLONK on the second), but there > are still limits, and as far as I'm concerned you're not far from > them. So do yourself and the world a favour, read this:http://catb.org/~esr/faqs/smart-questions.html > > and then this:http://docs.python.org/tut/tut.html > > and next time someone points you to a specific module, have mercy and > *read* the doc before posting. > > As far as I'm concerned, I won't anwser any of your questions unless > it's obvious that you have followed these advices (but then I'll be > happy to help if I can).- Hide quoted text - > > - Show quoted text - There is 'shelve'. It's just that you have to re-update each entry when you modify, so it's just similarity you'd be saving. From tjreedy at udel.edu Thu May 8 17:04:35 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 8 May 2008 17:04:35 -0400 Subject: anagram finder / dict mapping question References: Message-ID: "Kam-Hung Soh" wrote in message news:op.uatraax1ev04yd at melwxp23... | On Thu, 08 May 2008 15:42:07 +1000, dave | wrote: | Your code is always going to return the same list because every word is an | anagram of itself. | | Tip: Create a list for each dictionary key, then add a word to the list if | that word is not in the list. So: | | mapdic('adem') --> ["edam", "made"] Unless you plan to keep the list in alphabetical order, a set might be slightly better. From bignose+hates-spam at benfinney.id.au Sat May 24 21:39:20 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 25 May 2008 11:39:20 +1000 Subject: Code correctness, and testing strategies References: Message-ID: <87iqx39n7b.fsf@benfinney.id.au> Duncan Booth writes: > You still need human testing and QA, the difference is that with a > good set of unit tests you reduce the number of times code comes > back from QA before it can be passed and make it more likely that > the customer will be happy with the first version. Paradoxically, you also end up writing less code that you would otherwise. Behaviour Driven Development insists that you be lazy in satisfying the tests and implement only the simplest thing that could possibly work (and refactor code whenever the unit test suite passes). This results in never writing code into the application that isn't needed to satisfy some unit test, saving a lot of fruitless coding time. -- \ "...one of the main causes of the fall of the Roman Empire was | `\ that, lacking zero, they had no way to indicate successful | _o__) termination of their C programs." -- Robert Firth | Ben Finney From prisoner_at_war at yahoo.com Mon May 26 05:21:06 2008 From: prisoner_at_war at yahoo.com (Prisoner at War) Date: Mon, 26 May 2008 02:21:06 -0700 (PDT) Subject: Why Turn "Print" into "Print()"???? References: <248a2c45-caae-49bb-b8ff-701af8b86207@p25g2000hsf.googlegroups.com> Message-ID: On May 26, 1:37 am, "Gabriel Genellina" wrote: > > > The differences aren't so fundamental or important: it's not an entirely new language, just some ugly old things are being removed or changed in incompatible ways (at *some* time it was supposed to happen - but could not happen on the 2.x series which has to remain backwards compatible) > Also, Python 3.0 will be released simultaneously with 2.6, and there will be other 2.x releases. Python 2 won't magically disappear from Earth, I don't think Linux distros will come with Python 3.0 by default anytime soon (perhaps not before 3.1). But I'd read that Python 3 is very different in many important ways. I read it right there on the Py3K site! I can't make sense of how, why, even what, exactly, but that's not a misimpression on my part, I certain nonetheless...it's not just cosmetic changes but important ones pertaining to a sort of "linguistic logic" I gather.... > So learning Python with a book targeted to 2.5 isn't a waste of time - not at all. Well, I will be learning Python from the excellent materials available online, to be sure, but a book that I spend money for, well, I have "higher standards" for it, you know, one of which is that it doesn't get superseded so soon! > (This subject has already been discussed several times in this group.) Oops, sorry! Just thinking aloud a logical follow-up question.... > -- > Gabriel Genellina From deets at nospam.web.de Tue May 13 06:19:35 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 13 May 2008 12:19:35 +0200 Subject: array in class References: <3f2b8a18-8f5b-4188-acb7-660d73574027@m44g2000hsc.googlegroups.com> Message-ID: <68t8avF2uftkbU1@mid.uni-berlin.de> alefajnie wrote: > class A: > this_is_original_variable_only_for_one_inctance = 0 > > def __init__(self, v): > self.this_is_original_variable_only_for_one_inctance = v > > > class B: > this_is_common_for_all_instances = [] > > def __init__(self, v): > self.this_is_common_for_all_instances.append(v) > > > ---------------- > now I can create some instances of B, but all of them have the same > array, why > > if I use append for b1.this_is_common_for_all_instances, the b2, b3 > will have been changed that array. > (where bi is instance of B) > but changes on this_is_original_variable_only_for_one_inctance works > fine > > why it does that? > and how create array in class - normal array, "private variable" BOTH are at first class-wide. The difference is that the list is mutable, and thus you alter the one list, whereas a number is not - and instead you rebind a new object under the name now in the instance itself. You need to understand that the way you "declared" the variables above is NOT the way instance variables work in python. It can serve as neat trick to initialize variables to common values - but *only* if you really know the semantics. Instead, the idiom for creating instance-variables (that you wrongly called "private") is this: class Foo(object): def __init__(self, some_value): self.some_var = some_value The reason why the above seems to work is that a lookup of a name in python on an instance is done like this: if hasattr(self, name): return getattr(self, name) else if hasattr(self.__class__, name): return getattr(self.__class__, name) That is the reason why class Foo(object): bar = 10 def __init__(self): print self.bar sees the 10 - it will first lookup on self, fail, and then lookup on Foo, and succedd. However, the assignment is *always* on the instance, or spelled out like this: setattr(self, name, value) Thus self.name = 20 will create a new variable named "name" with the object it points to being 20. There are some minor details here regarding the descriptor protocol and such, but these aren't important for now. So - stop "declaring" variables if you want them to be per-instance. Use the above mentioned idiom of setting them on self inside __init__ Diez From gagsl-py2 at yahoo.com.ar Fri May 16 20:04:31 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 16 May 2008 21:04:31 -0300 Subject: Get all the instances of one class References: <29f39184-2daa-49fc-a7af-7f869fd2d688@h1g2000prh.googlegroups.com> Message-ID: En Fri, 16 May 2008 20:44:00 -0300, Terry escribi?: > Is there a simple way to get all the instances of one class? I mean > without any additional change to the class. Try with gc.get_referrers() py> import gc py> class A(object): pass ... py> a,b,c = A(),A(),A() py> A py> for item in gc.get_referrers(A): print type(item) ... We need to filter that list, keeping only A's instances: py> [item for item in gc.get_referrers(A) if isinstance(item,A)] [<__main__.A object at 0x00A40DC8>, <__main__.A object at 0x00A40DF0>, <__main__.A object at 0x00A40E18>] -- Gabriel Genellina From mmanns at gmx.net Mon May 26 17:11:25 2008 From: mmanns at gmx.net (Martin Manns) Date: Mon, 26 May 2008 23:11:25 +0200 Subject: Getting a set of lambda functions References: <483a1319$0$34516$742ec2ed@news.sonic.net> Message-ID: On Sun, 25 May 2008 18:46:27 -0700 John Nagle wrote: > >>>> func_strings=['x', 'x+1', 'x+2', 'x'] > >>>> funclist = [eval('lambda x:' + func) for func in func_strings] > > What are you actually trying to do, anyway? What's the > application? > > You probably don't want to use "eval" that way. If you want > function objects out, use "compile". I am writing on an application that I call pyspread (http://pyspread.sourceforge.net). It provides a grid (mapped to a numpy.array) into which users can type in strings that contain python expressions. Each expression is transformed into a function object in a second numpy.array of the same size, so that each function can be called by accessing the respective cell of the grid. eval seems to work quite fine and provides nice access to globals, system functions, modules, etc. Therefore, one can do general programming tasks within the grid without worrying about cell precedence. compile returns code objects instead of function objects. I can of course evaluate these code objects. However, when I store the code objects, it is an extra operation each time I want to call the function. So what is the benefit? More specific: Is there any benefit of calling: eval(compile(mystring, '', 'eval')) instead of eval(mystring) ? What are the drawbacks of my approach that I may be missing? Any suggestions? Best Regards Martin From gagsl-py2 at yahoo.com.ar Sun May 18 11:05:41 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 18 May 2008 12:05:41 -0300 Subject: Write bits in file References: Message-ID: En Sun, 18 May 2008 10:36:28 -0300, Monica Leko escribi?: > On May 18, 2:20?pm, Ken Starks wrote: >> You want your file considered as a sequence of bits rather >> than a sequence of 8-bit bytes, do you? > > Yes. > >> is the 10-bit >> bit-pattern to be stored at an arbitrary bit-position in >> the file > > Yes. I need arbitrary, 8bits, than 10 bits for something else, than > sequence of bytes, than 10 bits again, etc. If you really need arbitrary bit sequences that aren't synchonized into bytes, I think there is a BitVector o BitArray package somewhere. But if you mostly have bytes and sparsely a different size, I think the struct module and some gymnastics involving bitwise operations would be enough. -- Gabriel Genellina From CXDALTON at sentara.com Fri May 2 16:45:57 2008 From: CXDALTON at sentara.com (CRAIG DALTON) Date: Fri, 02 May 2008 16:45:57 -0400 Subject: Need help: Compiling Python-Code &In-Reply-To= Message-ID: <20080502205253.EA6C11E4023@bag.python.org> Hi, I'm looking to append several text files in one director and out put the combined files into another director. I'm new to Python and just can't get it to work. So far I've been able to create a file in the desired directory but it isn't pulling any of the data in the originating directory. Could please look at my code and tell me what I'm doing wrong. import os,shutil f=open("c:\\output\\testing1.txt","a+") for r,d,fi in os.walk("c:\\test"): for files in fi: if files.endswith(".txt"): g=open(os.path.join(r+,files)) shutil.copyfileobj(g,f) g.close() f.close() Any help would be great. Thanks, Craig Dalton Business Applications Systems Analyst Sentara Healthcare Systems Information Technology cxdalton at sentara.com From gherron at islandtraining.com Wed May 28 12:30:54 2008 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 28 May 2008 09:30:54 -0700 Subject: accessing class attributes In-Reply-To: <5827888d-4e9b-45bd-9361-108714c9043a@m45g2000hsb.googlegroups.com> References: <5827888d-4e9b-45bd-9361-108714c9043a@m45g2000hsb.googlegroups.com> Message-ID: <483D88BE.9020306@islandtraining.com> eliben wrote: > Hello, > > I have a game class, and the game has a state. Seeing that Python has > no enumeration type, at first I used strings to represent states: > "paused", "running", etc. But such a representation has many > negatives, so I decided to look at the Enum implementation given here: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/413486 > > So, I've defined: > > class Game: > self.GameState = Enum('running', 'paused', 'gameover') > That can't be what you've got. But I think I can guess what you meant to show here.) > def __init__ > ... etc > Several options: Define the Enum outside the class: GameState = Enum('running', 'paused', 'gameover') then later class Game: ... if state == GameState.running: ... Or just simply define some values RUNNING = 0 PAUSED = 1 GAMEOVER = 2 then later: class Game: ... if state == RUNNING: ... Or try this shortcut (for the exact same effect): RUNNING, PAUSED, GAMEOVER = range(3) Gary Herron > Later, each time I want to assign a variable some state, or check for > the state, I must do: > > if state == self.GameState.running: > > This is somewhat long and tiresome to type, outweighing the benefits > of this method over simple strings. > > Is there any better way, to allow for faster access to this type, or > do I always have to go all the way ? What do other Python programmers > usually use for such "enumeration-obvious" types like state ? > > Thanks in advance > Eli > -- > http://mail.python.org/mailman/listinfo/python-list > From carsten.haese at gmail.com Sun May 4 17:37:03 2008 From: carsten.haese at gmail.com (Carsten Haese) Date: Sun, 04 May 2008 17:37:03 -0400 Subject: unicode newbie - printing mixed languages to the terminal In-Reply-To: References: Message-ID: <30qTj.8447$iK6.4206@nlpi069.nbdc.sbc.com> David wrote: > Hi list. > > I've never used unicode in a Python script before, but I need to now. > I'm not sure where to start. I'm hoping that a kind soul can help me > out here. > > My current (almost non-existant) knowledge of unicode: > >>From the docs I know about the unicode string type, and how to declare > string types. What I don't understand yet is what encodings are and > when you'd want/need to use them. What I'd like is to just be able to > print out unicode strings in mixed languages, and they'd appear on the > terminal the same way they get shown in a web browser (when you have > appropriate fonts installed), without any fuss. > > Here is an example of how I'd like my script to work: > > $ ./test.py > > Random hiragana: > Random romaji: kakikukeko > > Is this possible? > >>From my limited knowledge, I *think* I need to do to things: > > 1) In my Python script, run .encode() on my unicode variable before > printing it out (I assume I need to encode into Japanese) > > Question: How does this work when you have multiple languages in a > single unicode string? Do you need to separate them into separate > strings (one per language) and print them separately? > > Or is it the case that you can (unlike a web browser) *only* > display/print one language at a time? (I really want mixed language - > English AND Japanese). > > 2) Setup the terminal to display the output. From various online docs > it looks like I need to set the LANG environment variable to Japanese, > and then start konsole (or gnome-terminal if that will work better). > But again, it looks like this limits me to 1 language. > > If what I want to do is very hard, I'll output html instead and view > it in a web browser. But I'd prefer to use the terminal instead if > possible :-) I suggest you read http://www.amk.ca/python/howto/unicode to demystify what Unicode is and does, and how to use it in Python. Printing text from different languages is possible if and only if the output device (terminal, in this case) supports a character encoding that accommodates all the characters you wish to print. UTF-8 is a fairly ubiquitous candidate that fits that criteria, since it encompasses Unicode in its entirety (as opposed to latin-1, for example, which only includes a very small subset of Unicode). HTH, -- Carsten Haese http://informixdb.sourceforge.net From banibrata.dutta at gmail.com Tue May 6 04:23:08 2008 From: banibrata.dutta at gmail.com (Banibrata Dutta) Date: Tue, 6 May 2008 13:53:08 +0530 Subject: Newbie question - probably FAQ (but not exactly answered by regular FAQ) In-Reply-To: <482010d3$0$12566$426a74cc@news.free.fr> References: <482010d3$0$12566$426a74cc@news.free.fr> Message-ID: <3de8e1f70805060123o13cd0c81k2eac1d14f1d3329d@mail.gmail.com> On 5/6/08, Bruno Desthuilliers wrote: > Nick Craig-Wood a ?crit : > > Banibrata Dutta wrote: > > > > > I've gone through the list of "language differences" between 2.3 / 2.4 > > > & 2.5 of CPython. I've spend around 2 weeks now, learning v2.5 of > > > CPython, and I consider myself still very very newbie. So, unable to > > > take a call as to how-important or desirable the newer language > > > features are -- so whether to write my app for v2.5 of Python, versus, > > > as few others on this list have recommended, i.e. to stick to v2.3 ?? > > > Are the preformance improvements, and memory footprint / leak fix in > > > 2.5 enough to justify moving to it ? What all do I stand to lose (or > > > gain) by writing on v2.3 ?? > > > > > > > If you are writing for 2.3 you are writing for 2.4 and 2.5 also. > > > > There are some nice things in 2.4 and 2.5 but nothing you really need > > IMHO. > > > > There are some nice things in Python but nothing you really need neither - > could have the same result in C or assembly !-) > > > Ok, if you're newbie to programming, the new stuff in 2.4 and 2.5 might not > be that useful to you right now. But the real question is mostly: do you > have any reason to stick to 2.3 ? > Newbie to Python yes, not to programming. But does that change anything -- i.e. to impact my decision ? > > > I've a constraint due to which I might have to also write parts of my > > > app (client side) in Jython (because I want to eventually ship Java -- > > > yet benefit from the rapid development and clarity of Python). Would > > > sticking to v2.3 in such a case be a better idea ? Suggestions with > > > reasoning would be very helpful. > > > > > > > Jython seems to be based off python 2.2 > > > > It is so far. But Sun recently hired Jython's maintainers, so we may have a > much more up to date Jython version in a foreseeable future. Well, I need to start somewhere, and I want that "somewhere" to be a decent-enough point. :-) As such 2.6 & 3.0 are also cooking, but from what I see on the mailing list, some of the features are a bit controversial. So if I start with 2.5 now, unless there are some break-thru preformance gains, or annoying defects fixed, I'd stick to it. If I can do something "well-enough" with 2.5, I'd not refactor for 2.6, for quite some fore-seeable future. From benjamin.fremiot at gmail.com Mon May 12 04:49:22 2008 From: benjamin.fremiot at gmail.com (Gruik) Date: Mon, 12 May 2008 01:49:22 -0700 (PDT) Subject: Import/Create module from buffer Message-ID: <09bfaed8-8bf6-4faf-80f9-e0b97aa03127@a70g2000hsh.googlegroups.com> Hi people, I'm currently working on python embedding with C++. My goal is that the C++ part handle files writing/reading so that the Python part only works with buffers. I succeeded in buffer exchanges. The problem is that some of the files I read/write are python files so that, before embedding, I imported them as modules when I needed them. But now that the Python part only receive buffers, I can't do it anymore. So I wonder : - is it possible to import module from a buffer instead of files? - or is it possible to create a module object from my buffer? I looked on the Internet but didn't find anything about that. Does anyone have an idea? Thanks Benjamin From kenneth.m.mcdonald at sbcglobal.net Sat May 10 14:57:27 2008 From: kenneth.m.mcdonald at sbcglobal.net (Kenneth McDonald) Date: Sat, 10 May 2008 13:57:27 -0500 Subject: People still using Tkinter? In-Reply-To: <4825cd01$0$14982$9b622d9e@news.freenet.de> References: <4825cd01$0$14982$9b622d9e@news.freenet.de> Message-ID: <8E6E31ED-9D5C-4008-86AB-C264ADCF5965@sbcglobal.net> The only trick it that sometimes it isn't obvious how to make the Tcl/ Tk call via Python. Ken On May 10, 2008, at 11:27 AM, Martin v. L?wis wrote: >> I am, but "still" isn't the word, I just started. Good, *complete* >> docs seem to be hard to find, but using a combination of the free >> resources and going back and forth between them seems to work all >> right so far. > > IMO, the trick really is to also have a Tk documentation around. > If you need to find out what option is supported by what widget, > there isn't really much point in duplicating that information in > Tkinter, IMO - the Tk documentation has it all. > > Regards, > Martin > -- > http://mail.python.org/mailman/listinfo/python-list From aisaac at american.edu Fri May 30 16:39:35 2008 From: aisaac at american.edu (Alan G Isaac) Date: Fri, 30 May 2008 16:39:35 -0400 Subject: should I put old or new style classes in my book? In-Reply-To: References: Message-ID: <3t6dnfCz_cCV-93VnZ2dnUVZ_h7inZ2d@rcn.net> > Alan Isaac writes: >> I take it from this thread that in Python 3 the following are >> equivalent: >> class Test: pass >> class Test(object): pass Arnaud Delobelle wrote: > I don't know where it is stated, but how could they *not* be > equivalent? The most obvious way would be that the former became an illegal syntax. But in Python 3 alpha, it is accepted, so I assume that it will continue to be? Cheers, Alan Isaac From google at mrabarnett.plus.com Tue May 20 17:41:48 2008 From: google at mrabarnett.plus.com (MRAB) Date: Tue, 20 May 2008 14:41:48 -0700 (PDT) Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <20080514215943.14c92f16.johnjsal@NOSPAMgmail.com> Message-ID: <94bac166-d13c-44dd-af84-db19e19488b8@w1g2000prd.googlegroups.com> On May 20, 4:33 am, Dave Parker wrote: > On May 14, 7:59 pm, John Salerno wrote: > > > Would it be valid to say: > > > x = "concrete" > > > or to say: > > > if command (is) set to "quit" > > > ?????? > > I like the idea of: > > If command is set to "quit" ... > Or just: If command is "quit" ... > I've added it to my list of things to think about, and possibly > implement. From yves at zioup.com Fri May 2 11:43:35 2008 From: yves at zioup.com (Yves Dorfsman) Date: Fri, 02 May 2008 15:43:35 GMT Subject: help with list comprehension In-Reply-To: References: Message-ID: George Sakkis wrote: > Another alternative is: > > from operator import itemgetter > > def m3(): > colours, nums = zip(*map(itemgetter('colour','num'), l)) > > It's slower than m1() but faster than m2(); it's also the most > concise, especially if you extract more than two keys. Good you guys gave me some ideas, I've made m3() work: def m3() total = [ [e['colour'], e['num'], e['couleur']] for e in l ] c,d,e = zip(*total) return map(list, [c,d,e]) (I have to transform to lists, I need to transform them later on, so tuples won't work). Unfortunately the timing is inconsistant, the first time I run python -m timeit 'import listcomp ; listcomp.m1()' m1 is the fastest. But then if I run the test several times, they all seem to be about the same time ; I'll have to try with a large list. Now here is a question: Is there any way to change my first line there for the list comp. to return a list of lists rather than a list of tuples ? From frikker at gmail.com Wed May 28 19:45:07 2008 From: frikker at gmail.com (blaine) Date: Wed, 28 May 2008 16:45:07 -0700 (PDT) Subject: FW: php vs python References: Message-ID: <1cc9a56b-c1d4-4fad-968b-a87684ccfc12@l64g2000hse.googlegroups.com> On May 28, 4:47 pm, "Phil Runciman" wrote: > -----Original Message----- > From: Jerry Stuckle [mailto:jstuck... at attglobal.net] > Sent: Wednesday, 28 May 2008 1:48 p.m. > To: python-l... at python.org > Subject: Re: php vs python > > Ivan Illarionov wrote: > > On Wed, 28 May 2008 05:10:20 +0400, AnrDaemon wrote: > > >> Greetings, Ivan Illarionov. > >> In reply to Your message dated Monday, May 26, 2008, 04:47:00, > > >>>> As I've said before - good programmers can write good code in any > >>>> language. > >>> Yes, they can. But it may be harder to do for them in one language > and > >>> easier in another. > >> It's obvious lie. If you have clear mind and you know language you're > >> using, there are absolutely NOTHING can deny you to write clear code. > >> Even using forth postfix notation, I have no problem writing good > code, > >> it's as easy as writing bad code. And yes, I do see the difference. > > > No. Language does matter. > > Yes it does matter. > > I have programmed in many assembly and higher level languages. > > In OldenTimes: > In Algol 60 I was productive from the start. > KDF9 Usercode (Assembly) was brilliant. (A bigger HW stack would have > made it even better). > IBM 360 Assembly was poorer but not a disaster. > PL1 was a mess. You could write good code but why bother? > COBOL was fit for purpose and when combined with Jackson structured > programming could be used straight away by rooky programmers in business > systems programming. I am sure it has progressed since ANSI 68. > > The Inuit have 13 terms for snow. Microsoft advocate DSLs. Why have DSLs > if language does not matter? > > My 2c worth. http://www.fukung.net/v/7729/php_vs_python.png :) From inhahe at gmail.com Fri May 16 12:24:23 2008 From: inhahe at gmail.com (inhahe) Date: Fri, 16 May 2008 12:24:23 -0400 Subject: writing python extensions in assembly References: Message-ID: "D'Arcy J.M. Cain" wrote in message news:mailman.1232.1210952591.12834.python-list at python.org... > > 2. Once the code is functioning, benchmark it and find the > bottlenecks. Replace the problem methods with a C extension. Refactor > (and check your unit tests again) if needed to break out the problem > areas into as small a piece as possible. There's probably only 2 or 3 basic algorithms that will need to have all that speed. > > 3. If it is still slow, embed some assembler where it is slowing down. > I won't know if the assembler is faster until I embed it, and if I'm going to do that I might as well use it. Although it's true I'd only have to embed it for one system to see (more or less). > >> For portability, I'd simply write different asm routines for different >> systems. How wide a variety of systems I'd support I don't know. As a >> bare >> minimum, 32-bit x86, 64-bit x86, and one or more of their available forms >> of >> SIMD. > > Even on the same processor you may have different assemblers depending > on the OS. yeah I don't know much about that, I was figuring perhaps I could limit the assembler parts / methodology to something I could write generically enough.. and if all else fails write for the other OS's or only support windows. also I think I should be using SIMD of some sort, and I'm not sure but I highly doubt C++ compilers support SIMD. From python at bdurham.com Tue May 6 09:11:29 2008 From: python at bdurham.com (python at bdurham.com) Date: Tue, 06 May 2008 09:11:29 -0400 Subject: Module to read input from commandline Message-ID: <1210079489.22730.1251666281@webmail.messagingengine.com> James, Check out the optparse module as well. The optparse module supercedes(?) the cmd module and offers a lot more functionality. Malcolm From gandalf at shopzeus.com Mon May 19 05:06:05 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Mon, 19 May 2008 11:06:05 +0200 Subject: TPCServer and xdrlib In-Reply-To: References: Message-ID: <483142FD.4060700@shopzeus.com> > It is possible to change the serialization used by Pyro > > http://pyro.sourceforge.net/manual/9-security.html#pickle > > to the the 'gnosis' XML Pickler. > As I said earlier, I would not use XML. Just an example - I need to be able to transfer image files, word and excel documents. How silly it would be to base64encode a binary file, then put it into an XML. L From deets at nospam.web.de Tue May 6 07:00:14 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 06 May 2008 13:00:14 +0200 Subject: use php in python httpservers References: <36960658-388b-48f9-84d0-38aab3e336f0@s50g2000hsb.googlegroups.com> Message-ID: <68as2qF2r15d8U1@mid.uni-berlin.de> artasis at gmail.com wrote: > Hi, that is my task: > I need to create python webserver-like extension(dll) which will run > php and python scripts as plugins. > I have no problems with dll creating and run python scripts, but I > cannot understand how to run php(CLI is not a solution). > Is there a way to solve this problem? I've thought to implement php to > HTTPServer-like python module, but as I see it's impossible. Solutions > with creating intermediate C-based module is allowed, but better > without them :). > AFAIK, php5ts.dll is that what I must use but how integrate it to > python webserver? that is a question http://www.amazon.com/Extending-Embedding-PHP-Developers-Library/dp/067232704X Might be of help. And maybe the roadsend PHP-compiler. Diez From rupole at hotmail.com Fri May 30 00:06:38 2008 From: rupole at hotmail.com (Roger Upole) Date: Fri, 30 May 2008 00:06:38 -0400 Subject: Finding file details... References: Message-ID: Kalibr wrote: > On May 30, 1:41 am, "Roger Upole" wrote: >> >> You can use the shell COM objects to access media properties >> as shown by Explorer. >> >> import win32com.client >> sh=win32com.client.Dispatch('Shell.Application') >> >> folder= r'M:\Music\Bob Dylan\Highway 61 Revisited' >> ns=sh.NameSpace(folder) >> >> ## the column index for Artist may vary from folder to folder >> for c in range(0,255): >> colname=ns.GetDetailsOf(None, c) >> if colname=='Artists': ## This shows up as just Artist on XP >> for i in ns.Items(): >> artist=ns.GetDetailsOf(i, c) >> if artist: >> print ns.GetDetailsOf(i, 0), artist >> break >> >> Roger > > I shall give that a go. (is the module you reference this one? > http://python.net/crew/mhammond/win32/Downloads.html ) > -- That's the one. Roger From arnodel at googlemail.com Tue May 6 11:29:21 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 06 May 2008 16:29:21 +0100 Subject: Am I missing something with Python not having interfaces? References: <45de2f7e-484a-4871-bbaa-bf7eed5dfa40@x35g2000hsb.googlegroups.com> Message-ID: jmDesktop writes: > Studying OOP and noticed that Python does not have Interfaces. Is > that correct? Is my schooling for nought on these OOP concepts if I > use Python. Am I losing something if I don't use the "typical" oop > constructs found in other languages (Java, C# come to mind.) I'm > afraid that if I never use them I'll lose them and when I need them > for something beside Python, I'll be lost. Thank you. You're not missing anything. An Interface is the Poor Man's Multiple Inheritance. But in truth, even without multiple inheritance, Python wouldn't need java-like interfaces. -- Arnaud From python at hope.cz Sat May 17 11:58:38 2008 From: python at hope.cz (Johny) Date: Sat, 17 May 2008 08:58:38 -0700 (PDT) Subject: Dbase / foxpro files References: Message-ID: <1badfadf-f47f-4502-a7ec-fafd78eb5104@d1g2000hsg.googlegroups.com> Thanks for your reply.Is it possible to delete a record by using the module? Thanks L> From castironpi at gmail.com Mon May 12 21:12:06 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 12 May 2008 18:12:06 -0700 (PDT) Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <2b66a86e-5a05-4262-b3c9-4703b0ae3372@d1g2000hsg.googlegroups.com> Message-ID: On May 12, 7:59?pm, Dave Parker wrote: > On May 12, 6:32?pm, castiro... at gmail.com wrote: > > > Can you render some furniture for me... to try to see some human > > posture to lowest energy levels. > > I couldn't find any furniture created using DPGraph, but the math art > gallery athttp://www.dpgraph.com/math-art.htmlhas a sailboat, an > F15, Tux (the Linux penguin), a lampshade, and lots of other things > that will soon be doable in Flaming Thunder. Mine's been always messing up the color wheel. Do you see anything analytic* / theoretically necessary / a priori / physical / physically induced about that? *Now that's a word from Philosophy Syntax--- pertaining to inherent definitions of words, any and all. From bob at passcal.nmt.edu Thu May 22 13:32:13 2008 From: bob at passcal.nmt.edu (Bob Greschke) Date: Thu, 22 May 2008 11:32:13 -0600 Subject: List of disk drives on Windows? References: <2008052013180816807-bob@passcalnmtedu> Message-ID: <2008052211321316807-bob@passcalnmtedu> On 2008-05-20 13:18:08 -0600, Bob Greschke said: > This MUST have been asked before, but I can't seem to Google the right > thing. ?How can I get a list of drives on a Windows box, like ["C:\", > "D:\"], like I can if I do something like listdir("/Volumes") on a Mac? > > Thanks! > > Bob Thanks for the ideas, guys! It's off to the emacs... From duncan.booth at invalid.invalid Fri May 9 08:40:12 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 9 May 2008 12:40:12 GMT Subject: Function creation (what happened?) References: <199c06d7-601c-49f3-a88c-c28f7283e619@25g2000hsx.googlegroups.com> Message-ID: Viktor wrote: > Can somebody give me an explanation what happened here (or point me to > some docs)? > > Code: > > HMMM = None > > def w(fn): > print 'fn:', id(fn) > HMMM = fn > print 'HMMM:', id(HMMM) > def wrapper(*v, **kw): > fn(*v, **kw) > wrapper.i = fn > print 'wrapper:', id(wrapper) > return wrapper > > class A: > @w > def __init__(self): pass > > print 'A.__init__:', id(A.__init__) > print 'A.__init__.i:', id(A.__init__.i) > print 'HMMM:', id(HMMM) > > > > Output: > > fn: 10404208 > HMMM: 10404208 > wrapper: 10404272 > A.__init__: 10376136 > A.__init__.i: 10404208 > HMMM: 505264624 > > > > Why did HMMM changed his id?! It didn't: global HMMM refers to None both before and after executing the rest of your code. The other HMMM is local to a particular invocation of w. Try the same steps interactively (and try printing the values not just the ids) and it may be more obvious: >>> HMMM = None >>> print 'HMMM:', id(HMMM) HMMM: 505264624 >>> def w(fn): print 'fn:', id(fn) HMMM = fn print 'HMMM:', id(HMMM) def wrapper(*v, **kw): fn(*v, **kw) wrapper.i = fn print 'wrapper:', id(wrapper) return wrapper >>> class A: @w def __init__(self): pass fn: 18299952 HMMM: 18299952 wrapper: 18300016 >>> print 'HMMM:', id(HMMM), HMMM HMMM: 505264624 None >>> From grante at visi.com Mon May 12 10:34:48 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 12 May 2008 09:34:48 -0500 Subject: Is using range() in for loops really Pythonic? References: <482657ca$0$25026$607ed4bc@cv.net> <41078222-aec0-4e8b-8a1f-945cdf814498@m73g2000hsh.googlegroups.com> <48275446$0$11628$607ed4bc@cv.net> <87mymw8nr0.fsf@benfinney.id.au> <87iqxk6nvs.fsf@benfinney.id.au> Message-ID: On 2008-05-12, Ben Finney wrote: >> Maybe my brain works differently, but I find both "dummy" and >> "unused" are extremely confusing names for loop counters. The loop >> begins to look like it doesn't iterate at all if its counter is >> dummy or unused. >> >> If it *counts* it is *used* and it's *not* dummy. > > The value is unused by any of the code inside the block. For the > purposes of that block, it is a dummy value. The value may be unused, but for me it's the name that matters, not the value. The name might be in use by other code, and the careless choice of a "dummy" name that's _supposed_ to be unused has broken code precisely becuase the name was being used (for something else). Requiring that the user pollute a namespace with a useless name is a wart. > That is also regrettably common in Python code. It still > suffers from being unnecessarily ambiguous, since there are > *also* plenty of loops using 'i', 'j', etc. where the loop > counter *is* used. Perhaps I'm the only one who's ever been stupid enough to overwrite an index named "i" (that is being used) with another index named "i" (that isn't being used)... -- Grant Edwards grante Yow! All of life is a blur at of Republicans and meat! visi.com From wuwei23 at gmail.com Fri May 9 00:04:39 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 8 May 2008 21:04:39 -0700 (PDT) Subject: range with variable leading zeros References: <52c13461-f1e6-45f7-9131-8b311bb59ecc@i76g2000hsf.googlegroups.com> Message-ID: On May 9, 1:42 pm, yhvh wrote: > I want to generate a range with variable leading zeros > > x = [0010, 0210] > padding = len(x[1]) > > for j in range(x[0], x[1]): > print (url).join('%0(pad)d(jj)'+'.jpg') %{'pad':padding, 'jj':j} > > This is syntactically incorrect, you can't insert a variable into the > string format options. Any ideas? Concatenate the parts of the pattern string first: pat = '%0' + str(padding) + 'd' From deets at nospam.web.de Tue May 13 05:18:17 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 13 May 2008 11:18:17 +0200 Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <2b66a86e-5a05-4262-b3c9-4703b0ae3372@d1g2000hsg.googlegroups.com> <5b0e3f70-afde-4480-8713-e7113b1250d7@x35g2000hsb.googlegroups.com> <1f537717-00d0-48ee-99b6-7125b96a6133@t12g2000prg.googlegroups.com> Message-ID: <68t4o0F2vaoncU1@mid.uni-berlin.de> Dave Parker wrote: > On May 12, 7:20?pm, castiro... at gmail.com wrote: >>Yes, I am trying to visualize something. > > If it is related to making furniture comfortable for humans, have you > considered painting the furniture with thermochromic paint ( > http://en.wikipedia.org/wiki/Thermochromism )? It changes color in > response to temperature, which in part is determined by how hard a > body is pressed against it because close contact tends to trap heat. > An evenly distributed color might indicated evenly distributed > pressure. Don't let yourself be irritated by castironpi - he's the virtual equivalent of a mumbling mad man in this group. Ignorance serves best as remedy - and getting a filter to work, as I did (so I only see his postings being quoted... a huge relief!) Diez From marc.messina at sbcglobal.net Thu May 8 12:17:51 2008 From: marc.messina at sbcglobal.net (delta2) Date: Thu, 8 May 2008 09:17:51 -0700 (PDT) Subject: Python Math libraries - How to? In-Reply-To: References: Message-ID: <17127534.post@talk.nabble.com> I am also using Zelle's book to teach myself programming and Python. I also had a problem with " import math ", but the alternative of " from math import * " is working for me. I don't know why one works and the other doesn't. Cousin Stanley-3 wrote: > > >> >> Here is the arithmetic program I made that it worked before I added >> the "import math" line. >> >> #volumen.py >> # A program to compute the volume and surface area of a sphere >> import math >> >> .... >> NameError: global name 'pi' is not defined >> .... > >>>> from math import * >>>> >>>> def surface( r ) : > ... return 4 * pi * r ** 2 > ... >>>> def volume( r ) : > ... return ( 4. / 3. ) * pi * r ** 3 > ... >>>> for n in range( 1 , 11 ) : > ... s = surface( n ) > ... v = volume( n ) > ... print ' %2d .... %9.4f .... %9.4f ' % ( n , s , v ) > ... > > > -- > Stanley C. Kitching > Human Being > Phoenix, Arizona > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/Python-Math-libraries---How-to--tp16952032p17127534.html Sent from the Python - python-list mailing list archive at Nabble.com. From pupeno at pupeno.com Sat May 17 13:43:33 2008 From: pupeno at pupeno.com (=?ISO-8859-1?Q?J=2E_Pablo_Fern=E1ndez?=) Date: Sat, 17 May 2008 10:43:33 -0700 (PDT) Subject: Getting elements and text with lxml References: <482EF709.3000604@behnel.de> Message-ID: <8ea36733-c9bb-4193-a309-d14af8f134c9@f63g2000hsf.googlegroups.com> On May 17, 4:17?pm, Stefan Behnel wrote: > J. Pablo Fern?ndez wrote: > > I have an XML file that starts with: > > > > > > > > > ? *-a > > > > > out of it, I'd like to extract something like (I'm just showing one > > structure, any structure as long as all data is there is fine): > > > [("ofc", "*"), "-", ("rad", "a")] > > ? ? >>> root = etree.fromstring(xml) > ? ? >>> l = [] > ? ? >>> for el in root.iter(): ? ?# or root.getiterator() > ? ? ... ? ? l.append((el, el.text)) > ? ? ... ? ? l.append(el.text) > > or maybe this is enough: > > ? ? list(root.itertext()) > > Stefan Hello, My object doesn't have iter() or itertext(), it only has: iterancestors, iterchildren, iterdescendants, itersiblings. Thanks. From zhalbrecht at gmail.com Tue May 20 16:05:53 2008 From: zhalbrecht at gmail.com (Zack) Date: Tue, 20 May 2008 13:05:53 -0700 (PDT) Subject: Accumulating values in dictionary References: <07fbc8ec-924a-4e90-b212-ca4cc66f2b85@i76g2000hsf.googlegroups.com> Message-ID: <7e73581b-6e8f-417c-9d34-0608164d2517@w5g2000prd.googlegroups.com> On May 20, 10:38 am, Thomas Bellman wrote: > Arnaud Delobelle wrote: > > from collections import defaultdict > > d = defaultdict(int) # That means the default value will be 0 > > for person in people: > > d[person.fav_food] += 1 > > Ah! I didn't think of using int as the factory function. If you > use this, then I believe the warning I gave about performance > does not apply; my understanding is that calling built-in functions > (like the int constructor) is fast. > > -- > Thomas Bellman, Lysator Computer Club, Link?ping University, Sweden > "Beware of bugs in the above code; I have ! bellman @ lysator.liu.se > only proved it correct, not tried it." ! Make Love -- Nicht Wahr! Arnaud, that is so badass re: int From sturlamolden at yahoo.no Sat May 3 18:05:31 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 3 May 2008 15:05:31 -0700 (PDT) Subject: Feature suggestion: sum() ought to use a compensated summation algorithm References: <481CB283.107@gmail.com> Message-ID: On May 3, 10:13 pm, hdante wrote: > I believe that moving this to third party could be better. What about > numpy ? Doesn't it already have something similar ? Yes, Kahan summation makes sence for numpy arrays. But the problem with this algorithm is optimizing compilers. The programmer will be forced to use tricks like inline assembly to get around the optimizer. If not, the optimizer would remove the desired features of the algorithm. But then we have a serious portability problem. From martin at marcher.name Tue May 20 17:44:36 2008 From: martin at marcher.name (Martin Marcher) Date: Tue, 20 May 2008 23:44:36 +0200 Subject: preserve history in the interactive python In-Reply-To: References: Message-ID: <5fa6c12e0805201444x55e2660dne2d7973e0724c98e@mail.gmail.com> Hi, On Tue, May 20, 2008 at 8:19 PM, Nikhil wrote: > Nikhil wrote: >> the previous interactive shell. Basically, is there anyway that I can >> preserve the history in the shell? > > I figured it out. This below thing works fine for me. > BTW, I got it from http://docs.python.org/tut/node15.html. A little search Didn't even think of that, now that I have it: I love you - it's great. To the one that implemented this: If you ever come to vienna, drop me a note I'll get you a $FAVORITE_DRINK_HERE /martin -- http://www.xing.com/profile/Martin_Marcher You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. From bignose+hates-spam at benfinney.id.au Mon May 12 03:40:06 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 12 May 2008 17:40:06 +1000 Subject: Is using range() in for loops really Pythonic? References: <482657ca$0$25026$607ed4bc@cv.net> <41078222-aec0-4e8b-8a1f-945cdf814498@m73g2000hsh.googlegroups.com> <48275446$0$11628$607ed4bc@cv.net> <87mymw8nr0.fsf@benfinney.id.au> <87iqxk6nvs.fsf@benfinney.id.au> Message-ID: <877ie06kdl.fsf@benfinney.id.au> Ivan Illarionov writes: > On Mon, 12 May 2008 16:24:23 +1000, Ben Finney wrote: > [...] > > That is also regrettably common in Python code. It still suffers > > from being unnecessarily ambiguous, since there are *also* plenty > > of loops using 'i', 'j', etc. where the loop counter *is* used. > > > > Differentiating these use cases by appropriate naming is, IMO, > > worth the effort of choosing a meaningful name. > > Even if the counter is not used inside the loop's body it's still in > control of the whole loop Not in Python it's not. The values that come out of the iterator aren't "in control of the loop". The state for the loop is in the *iterator*, not the values that come out. Having access to the values that come from the iterator is usually useful, but regardless of whether one uses them or not, they're *not* controlling the loop, and it's confusing to imply that they are. So, when not using the values that come from the controlling iterator, it's good to make that explicit. If Python supported it, we might prefer to use no name at all for something that isn't used, but the 'for' syntax doesn't allow that. In the absence of supporting syntax, the next best thing is to choose a name that *does* make it explicit that the values will not be used. -- \ ?All television is educational television. The question is: | `\ what is it teaching?? ?Nicholas Johnson | _o__) | Ben Finney From smitty1e at gmail.com Fri May 2 22:16:57 2008 From: smitty1e at gmail.com (smitty1e) Date: Fri, 2 May 2008 19:16:57 -0700 (PDT) Subject: unified command line args, environment variables, .conf file settings. Message-ID: Just a fun exercise to unify some of the major input methods for a script into a single dictionary. Here is the output, given a gr.conf file in the same directory with the contents stated below: smitty at localhost ~/proj/mddl4/test $ ./inputs.py {'source_db': '/home/sweet/home.db'} smitty at localhost ~/proj/mddl4/test $ source_db="test_env" ./inputs.py {'source_db': 'test_env'} smitty at localhost ~/proj/mddl4/test $ ./inputs.py -f "test_cli" {'source_db': 'test_cli'} For the file ========= #!/usr/bin/env python #Goal: unification of environment variables, command line, and # configuration file settings. # The .conf file is the specification. # Optional environment variables can override. # Optional command-line inputs trump all. # Example is a file spec for a source database for an application. # .conf has a contents like: #================================ # [CONF] # source_db=/home/sweet/home.db #TODO: # 1. Decide (make an option?) to retain the simple dictionary or build a # class from the options. # 2. Allow for multiple .conf locations, trying to be cool like # xorg.conf from ConfigParser import SafeConfigParser from optparse import OptionParser import os CONF = "CONF" #section in .conf file CONF_FILE = "gr.conf" #name of config file PLACEBO = "placebo" #mindless default that we don't want gconf = {} #all your config are belong to here parser = OptionParser() parser.add_option( "-f" , "--file" , dest = "source_db" , help = "source database" , default = PLACEBO ) (cl_opts, args) = parser.parse_args() config = SafeConfigParser() config.read(CONF_FILE) file_conf = dict(config.items(CONF)) for k in file_conf: gconf[k]=file_conf[k] if os.environ.has_key(k): gconf[k] = os.environ[k] if cl_opts.__dict__.has_key(k): if cl_opts.__dict__[k]!=PLACEBO: gconf[k] = cl_opts.__dict__[k] print gconf From Scott.Daniels at Acm.Org Mon May 12 22:47:28 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 12 May 2008 19:47:28 -0700 Subject: anonymous assignment In-Reply-To: References: <1XNVj.133805$Cj7.33096@pd7urf2no> Message-ID: Yves Dorfsman wrote: > ... Sorry this was a typo (again :-), I meant: > d = time.local() > y = d[0] > d = d[2] Then: y, d = list(time.localtime())[:4:2] --Scott David Daniels Scott.Daniels at Acm.Org From dulipishi at gmail.com Thu May 22 11:55:32 2008 From: dulipishi at gmail.com (duli) Date: Thu, 22 May 2008 08:55:32 -0700 (PDT) Subject: Books for learning how to write "big" programs Message-ID: <219c77ef-dd0c-464b-bb6a-e4f3bee89eae@x41g2000hsb.googlegroups.com> Hi: I would like recommendations for books (in any language, not necessarily C++, C, python) which have walkthroughs for developing a big software project ? So starting from inception, problem definition, design, coding and final delivery on a single theme or application. Most of the code I have written and books that I have read deal with toy programs and I am looking for something a bit more comprehensive. For example, maybe a complete compiler written in C++ for some language, or a complete web server or implementing .net libraries in some language (just a few examples of the scale of things I am interested in learning). Thanks! Duli. From daveparker at flamingthunder.com Wed May 21 15:53:22 2008 From: daveparker at flamingthunder.com (Dave Parker) Date: Wed, 21 May 2008 12:53:22 -0700 (PDT) Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <7ae9cb4f-60bf-4e77-826c-03248cca4027@w4g2000prd.googlegroups.com> Message-ID: <7a2dcc0b-001a-433a-ad1d-0eb3f1254350@q24g2000prf.googlegroups.com> On May 21, 1:29?pm, "Dan Upton" wrote: > ... --somewhat akin to the > guy who a month or so ago wanted to sneakily teach his high school > class programming fundamentals by teaching them game programming. Yep, that's kind of my plan, too. After I get enough "computer languagey" stuff running, I'm going to incorporate the 3D graphics from DPGraph. > Maybe this should be your selling point, and maybe you should be > drawing comparisons to programming in Matlab or Mathematica. That sounds like a good idea. Personally, the first thing I wanted to get running in Flaming Thunder was the ability to cross-compile CGI scripts for Linux under Windows, because some inexpensive web-hosting sites (such as GoDaddy) don't allow shell access, so I couldn't compile the CGI scripts natively. Also, the ability to cross-compile programs for the Mac since Macs often appear in educational settings. Now that those are up and running and Flaming Thunder is released to the public, I'm adding features as prioritized by customer requests. Currently, the highest big things on the list are arrays/matrices and 3D graphics. Next on the list is improved symbolics. From castironpi at gmail.com Fri May 16 10:10:38 2008 From: castironpi at gmail.com (castironpi) Date: Fri, 16 May 2008 07:10:38 -0700 (PDT) Subject: default object comparison considered harmful? References: <482d7cc6$0$10756$426a34cc@news.free.fr> <57aa79de-8e01-44bc-90d3-cfd6b7e9bf3f@x35g2000hsb.googlegroups.com> Message-ID: <52d91619-d8bf-47cb-8a69-5604f71dc45c@e39g2000hsf.googlegroups.com> On May 16, 8:35?am, castironpi wrote: > On May 16, 8:18?am, castironpi wrote: > > > > > > > On May 16, 7:23?am, Bruno Desthuilliers > > 42.desthuilli... at websiteburo.invalid> wrote: > > > Kay Schluehr a ?crit : > > > > > On 16 Mai, 10:03, "A.T.Hofkamp" wrote: > > > >> Hello all, > > > > >> Yesterday we found the cause of a bug that has caused problems for a long time. > > > >> It appeared to be the following: > > > > >> class A(object): > > > >> ? ? pass > > > > >> print min(1.0, A()) > > > > >> which is accepted by Python even though the A() object is not numerical in > > > >> nature. > > > > >> The cause of this behavior seems to be the compare operation of the object > > > >> class. > > > > >> Is there a way to disable this behavior in Python (other than deriving a new > > > >> 'object-like' class that doesn't do comparisons?) > > > > > Are you sure you don't want to use a statically typed language that > > > > captures all type errors just by inspecting your source code? > > > > This is not necessarily a static vs dynamic typing problem. The > > > following code will raise a TypeError for very good reasons: > > > > ? ? print 1.0 + A()- Hide quoted text - > > > > - Show quoted text - > > > I question the real-world examples of coercion, casting, and > > upcasting. ?C insists that defining by operator, which may or may not > > relate to system, is the only legal move. ?I doubt operator+ is well- > > defined on non-ideal structures. ?Rationals are not floats, but system > > got checked. ?Define concurrency.- Hide quoted text - > > > - Show quoted text - > > I would be bouncing localcy and remoticy. ?What word's on the bar?- Hide quoted text - > > - Show quoted text - Can you suffixize words? I have corner, cornercy, lunacy, emphatic, emphasize, a value of Y, orderings, say, remoticy, & cross. Come do graphics. Anybody speak? For verbs, I have: say, speak, see, talk, and stack. Pretty harmless. Still here? From bj_666 at gmx.net Sun May 4 00:08:34 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 4 May 2008 04:08:34 GMT Subject: generator functions in another language References: <831bea0d-ef71-4ede-9065-3111bce5225e@c65g2000hsa.googlegroups.com> Message-ID: <684r62F2rmn3gU2@mid.uni-berlin.de> On Sat, 03 May 2008 16:39:43 -0700, castironpi wrote: > I'm actually curious if there's a way to write a generator function > (not a generator expression) in C, or what the simplest way to do it > is... besides link the Python run-time. The reference implementation of Python is written in C, so obviously there must be a way to write something like generators in C. Ciao, Marc 'BlackJack' Rintsch From vbgunz at gmail.com Wed May 14 12:25:40 2008 From: vbgunz at gmail.com (vbgunz) Date: Wed, 14 May 2008 09:25:40 -0700 (PDT) Subject: Class Methods Vs Any Other Callable References: <98b4a67c-9ec7-407c-8c80-06488bd48a68@e39g2000hsf.googlegroups.com> <690ap7F2u0ftdU1@mid.uni-berlin.de> <690ge0F2vj8fiU1@mid.uni-berlin.de> <0be4edce-1b3f-45bb-b186-de20f8bc9087@e53g2000hsa.googlegroups.com> Message-ID: <1e097d72-95a3-475b-8016-53b48808514f@l64g2000hse.googlegroups.com> > > > Instance methods make the most sense. A static method makes sense too > > > *but* I can see how a class method not only does what a static method > > > does but how a class method *also* gets the cls reference for free. > > > I don't understand the last part - but I certainly agree on the "instance > > methods make the most sense". But *if* you want a hierarchy > > of "sensefulness", > > > method > classmethod > staticmethod Sorry I quoted this earlier and meant to respond to it. What I meant was, might as well use a class method over a static method AND in doing so, cls is free. I sort of repeated the same thing over and over. I think my main concern was trying to make sure I could grasp at least that much. From arnodel at googlemail.com Tue May 20 11:17:12 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 20 May 2008 16:17:12 +0100 Subject: Misuse of list comprehensions? References: <038e4418$0$27258$c3e8da3@news.astraweb.com> <6359d72c-f937-46cd-b1ce-b7450671b714@i76g2000hsf.googlegroups.com> Message-ID: Paul McGuire writes: > On May 20, 8:13?am, "John Salerno" wrote: >> I posted this code last night in response to another thread, and after I >> posted it I got to wondering if I had misused the list comprehension. Here's >> the two examples: >> >> Example 1: >> -------------------- >> def compress(s): >> ? ? new = [] >> >> ? ? for c in s: >> ? ? ? ? if c not in new: >> ? ? ? ? ? ? new.append(c) >> ? ? return ''.join(new) >> ---------------------- >> >> Example 2: >> ------------------------ >> def compress(s): >> ? ? new = [] >> ? ? [new.append(c) for c in s if c not in new] >> ? ? return ''.join(new) >> -------------------------- >> >> In example 1, the intention to make an in-place change is explicit, and it's >> being used as everyone expects it to be used. In example 2, however, I began >> to think this might be an abuse of list comprehensions, because I'm not >> assigning the result to anything (nor am I even using the result in any >> way). >> >> What does everyone think about this? Should list comprehensions be used this >> way, or should they only be used to actually create a new list that will >> then be assigned to a variable/returned/etc.? > > Why not make the list comp the actual list you are trying to build? > > def compress(s): > seen = set() > new = [c for c in s if c not in seen and (seen.add(c) or True)] Isn't c not in seen and (seen.add(c) or True) the same as seen.add(c) or c not in seen ? > return ''.join(new) > (notice I haven't closed the tag!) -- Arnaud From seymour.morris at gmail.com Sat May 3 22:27:59 2008 From: seymour.morris at gmail.com (SFM) Date: Sat, 3 May 2008 19:27:59 -0700 (PDT) Subject: Help - IDLE Debugger Source Checkbox?? Message-ID: <80a1e892-c154-4a06-a211-936fedbd75be@8g2000hse.googlegroups.com> I have been learning the IDLE Debugger and was wondering if I was missing something with the "Source" checkbox setting in the debugger. As I single-step through my program, I have to uncheck and then recheck this box in order to see the current line in the file editing window highlighted. Is there anyway continually see the current line being executed in the file editor, without unchecking and rechecking the source setting in the debugger? Thanks for any insight on this issue. From giraffeboy at gmail.com Wed May 21 13:45:18 2008 From: giraffeboy at gmail.com (giraffeboy at gmail.com) Date: Wed, 21 May 2008 10:45:18 -0700 (PDT) Subject: Database Query Contains Old Data References: <33b13117-0f9f-435d-b8f8-19f1ed3a121a@d77g2000hsb.googlegroups.com> <4f0163cc-d943-4204-87e5-880477d6f7e0@f36g2000hsa.googlegroups.com> Message-ID: On May 21, 3:23 pm, Paul Boddie wrote: > Note that if you have a connection open in your program, especially if > that connection has already been used to select data, it may be the > case that you then have to perform a rollback or commit before > attempting to access newly added data. The reason for this behaviour > is that the DB-API modules will have begun a transaction on your > behalf, and while that transaction is open, changes committed in other > transactions may be unavailable to your own transaction, depending on > the transaction isolation level. Thanks for that Paul, seems to have solved the problem perfectly. I had always just thought querying a database would always give you the most current data, guess it just goes to show that things are never as simple as they first appear! From martin at v.loewis.de Fri May 2 15:44:20 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 02 May 2008 21:44:20 +0200 Subject: portable /dev/null In-Reply-To: <1jkwzhktzddwv.xxl22p30ivrs.dlg@40tude.net> References: <1jkwzhktzddwv.xxl22p30ivrs.dlg@40tude.net> Message-ID: <481b6f14$0$9717$9b622d9e@news.freenet.de> > I have functions that take a file object and write to it. In some cases I > just want to throw out what is written to that file object. I want > something like open('/dev/null', 'w'), but portable. > > It needs to have an underlying file descriptor/file handle, as it will be > passed to non python code. > > Is there a portable /dev/null somewhere in the standard library? The subprocess module should work fine. Pass a pipe to the subprocess, and read and discard anything from the pipe (e.g. in a separate thread). If the non-Python code is inprocess, you are out of luck. Some systems just don't support a null device, so Python can't possibly emulate it. Regards, Martin From duncan.booth at invalid.invalid Wed May 7 06:09:19 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 7 May 2008 10:09:19 GMT Subject: Why don't generators execute until first yield? References: Message-ID: Martin Sand Christensen wrote: > Now to the main point. When a generator function is run, it immediately > returns a generator, and it does not run any code inside the generator. > Not until generator.next() is called is any code inside the generator > executed, giving it traditional lazy evaluation semantics. Why don't > generators follow the usual eager evaluation semantics of Python and > immediately execute up until right before the first yield instead? You mean you expect the semantics of generators to be that when you create them, or every time you call next() they run until they hit yield and then (except for the initial run) return the result that was yielded the time before? It is easy enough to implement that, but could be a bit confusing for the user. >>> def greedy(fn): def greedygenerator(*args, **kw): def delayed(): it = iter(fn(*args, **kw)) try: res = it.next() except StopIteration: yield None return yield None for value in it: yield res res = value yield res it = delayed() it.next() return it return greedygenerator >>> @greedy def mygen(n): for i in range(n): print i yield i >>> x = mygen(3) 0 >>> list(x) 1 2 [0, 1, 2] >>> x = mygen(0) >>> list(x) [] >>> Now try: for command in getCommandsFromUser(): print "the result of that command was", execute(command) where getCommandsFromUser is a greedy generator that reads from stdin, and see why generators don't work that way. From basti.wiesner at gmx.net Fri May 30 18:39:53 2008 From: basti.wiesner at gmx.net (Sebastian 'lunar' Wiesner) Date: Sat, 31 May 2008 00:39:53 +0200 Subject: Help needed in choosing an algorithm for Cryptographic services. References: Message-ID: [ Peter Pearson ] > On Thu, 29 May 2008 20:27:35 -0500, Larry Bates wrote: >> abhishek wrote: >>> Hi group, recently my employer asked me too implement encryption/ >>> decryption for secure data transfer over internet. Problem is that the >>> client application is written using C# and the webserver where i need >>> to store the information is developed using python. >>> >>> My situation of dilemma is which cryptographic method suits me best >>> for this purpose. >>> >>> Help/Suggestions are urgently required > Data security is a complex and difficult problem, and you are likely > to fail in the worst possible way: implementing something that is > weak but that you believe to be strong. Some advice: (1) Use > off-the-shelf products like PGP or GPG; don't write your own. full ack. > (2) Read Bruce Schneier's Applied Cryptography to get a feeling > for the dimensions of the problem. While this book is most certainly worth reading, I doubt, that it is necessary to gain in-depth knowledge of cryptography to make use of it in your code. If you transfer data over SSL-connection, you should rely on them being safe, you don't need to understand the details. You only need to know, what SSL can protect against, and what it can't protect against. -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From vbgunz at gmail.com Sat May 10 12:42:27 2008 From: vbgunz at gmail.com (vbgunz) Date: Sat, 10 May 2008 09:42:27 -0700 (PDT) Subject: Orlando Florida Python Tutor Needed Message-ID: <7ce42a69-8c6b-435b-a125-2a619b3a8603@k13g2000hse.googlegroups.com> I will pay anyone for a face-to-face tutoring in the Orlando Florida area. I will pay $20.00 per hour (minimum 2 hours needed). What I need are lessons in Decorators and Class methods. If I can walk away with at least 5 lessons taught in both subjects I will be happy to offer an additional $20.00. If you are interested in this offer feel free to either reply through email OR here on this thread. There are no string attached, catches, etc. I need to learn and if you can teach well, I will be happy to learn. Best Regards Victor B. Gonzalez From pavlovevidence at gmail.com Thu May 1 20:53:46 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 1 May 2008 17:53:46 -0700 (PDT) Subject: Best way to store config or preferences in a multi-platform way. References: <790cec6c-b057-4a2d-bc2c-e683630c1127@w7g2000hsa.googlegroups.com> <52a268cc-dae7-4eda-81df-cc82dbcbdcd7@56g2000hsm.googlegroups.com> <071d4536-2b40-4b75-87e1-096a1773f886@f63g2000hsf.googlegroups.com> Message-ID: <2209e61f-2799-4c05-a594-31ee6cc54b7e@d1g2000hsg.googlegroups.com> On May 1, 7:54 pm, Ivan Illarionov wrote: > No, all I want is to give the OP a useful alternative Fair enough, I can't argue with that. Carl Banks From python at hope.cz Thu May 15 10:16:08 2008 From: python at hope.cz (Johny) Date: Thu, 15 May 2008 07:16:08 -0700 (PDT) Subject: Dbase / foxpro files Message-ID: Is there a module for reading/modifing db files from Python? Thanks for help B. From deets at nospam.web.de Fri May 23 12:34:49 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 23 May 2008 18:34:49 +0200 Subject: can python do some kernel stuff? In-Reply-To: <3ba0233a-0ed4-4057-bc9c-7e1940968d92@d19g2000prm.googlegroups.com> References: <983ec0f6-1316-40cd-a4d4-ce9b5e272a60@h1g2000prh.googlegroups.com> <48366cfa$0$15168$607ed4bc@cv.net> <28c432f0-657c-4272-8cd4-a9081b013279@w5g2000prd.googlegroups.com> <69nigsF3499pqU2@mid.uni-berlin.de> <8d1f0f0f-8dc4-43df-bbc5-78c05b81d6ca@u12g2000prd.googlegroups.com> <3ba0233a-0ed4-4057-bc9c-7e1940968d92@d19g2000prm.googlegroups.com> Message-ID: <69oa1aF33cfteU1@mid.uni-berlin.de> Jimmy schrieb: > On May 23, 11:14 pm, Jimmy wrote: >> On May 23, 5:53 pm, "Diez B. Roggisch" wrote: >> >> >> >>> Jimmy schrieb: >>>> On May 23, 3:05 pm, Andrew Lee wrote: >>>>> Jimmy wrote: >>>>>> Hi to all >>>>>> python now has grown to a versatile language that can >>>>>> accomplish tasks for many different purposes. However, >>>>>> AFAIK, little is known about its ability of kernel coding. >>>>>> So I am wondering if python can do some kernel coding that >>>>>> used to be the private garden of C/C++. For example, can python >>>>>> intercept the input of keyboard on a system level? someone told me >>>>>> it's a kernel thing, isn't it? >>>>> http://wiki.python.org/moin/elmer >>>> well, straightly speaking, how can I know a key is pressed on a system- >>>> level if >>>> using python? >>> What has that todo with kernel programming? You can use e.g. pygame to >>> get keystrokes. Or under linux, read (if you are root) the keyboard >>> input file - I've done that to support several keyboards attached to a >>> machine. >>> And the original question: no, python can't be used as kernel >>> programming language. Amongst other reasons, performance & the GIL >>> prevent that. >>> Diez >> sorry, my aim is not limited to one particular program. Yes, many >> library can >> permit you to respond to keyboard event, however, what I want is a >> universal >> function. as long as a key is pressed, no matter where, my program can >> repond. >> >> I am quite strange with this topic. But according to my understanding, >> any event, keyboard event >> for example, once triggered, will be dilivered by keyboard driver to X >> system, and then >> any running program can either choose to respond or ignore. So my >> question can be translated to: >> how to make my program respond ? > > maybe I'd better elaborate on my question. Back to my original > question: > intercept keyboard event on a system level. If you are writing program > in > emacs, of course, the keyboard inputs are meant for emacs only. What > I > want is no matter what program you're running, keyboard events can be > anyway caught by my program. > > Am I clear with myself? :) Do you want to intercept the call (prevent that it is passed through to e.g. emacs), or are you merely interested in getting it? If the latter, you can (as root) access the /dev/input keyboard device and get the scan-codes. The former is more complicated - without research I don't know out of my head how to accomplish that. But it must be possible, as e.g. KDE observes global key-shortcuts. Most probably a X-server thing. Diez From andrew.smith.cpp at gmail.com Tue May 20 06:15:22 2008 From: andrew.smith.cpp at gmail.com (andrew.smith.cpp at gmail.com) Date: Tue, 20 May 2008 03:15:22 -0700 (PDT) Subject: Newbie In Python Message-ID: <316da0ad-403d-492c-81b1-4aa069da0caa@k10g2000prm.googlegroups.com> I have Heard About "Python" its a OOD Language. i have to Learn it where from i should start it. i have python compiler at linux Platform. anyone can suggest me about it. Thanks In advance. From james.harris.1 at googlemail.com Wed May 21 08:33:56 2008 From: james.harris.1 at googlemail.com (James Harris) Date: Wed, 21 May 2008 05:33:56 -0700 (PDT) Subject: Running commands on cisco routers using python References: Message-ID: On 19 May, 16:18, SPJ wrote: > Is it possible to run specific commands on cisco router using Python? > I have to run command "show access-list" on few hundred cisco routers and get the dump into a file. Please let me know if it is feasible and the best way to achieve this. Can you access the routers with telnet or do you need to use ssh? I've written loads of Python to access Cisco routers using a wrapper around the standard telnetlib. Telnetlib supplies an excellent expect function which makes this work. It is telnet, though. If I had to use ssh I would probably add it under the same wrapper so that higher level code could work unchanged. There may be a way to route the telnet interractions through openssh or similar externally but I haven't tried that. From wizzardx at gmail.com Sat May 24 08:34:36 2008 From: wizzardx at gmail.com (David) Date: Sat, 24 May 2008 14:34:36 +0200 Subject: Code correctness, and testing strategies Message-ID: <18c1e6480805240534k1da68fc8rfbace233f0de6e40@mail.gmail.com> Hi list. What strategies do you use to ensure correctness of new code? Specifically, if you've just written 100 new lines of Python code, then: 1) How do you test the new code? 2) How do you ensure that the code will work correctly in the future? Short version: For (1) I thoroughly (manually) test code as I write it, before checking in to version control. For (2) I code defensively. Long version: For (2), I have a lot of error checks, similar to contracts (post & pre-conditions, invariants). I've read about Python libs which help formalize this[1][2], but I don't see a great advantage over using regular ifs and asserts (and a few disadvantages, like additional complexity). Simple ifs are good enough for Python built-in libs :-) [1] PEP 316: http://www.python.org/dev/peps/pep-0316/ [2] An implementation: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/436834 An aside: What is the correct situation in which to use assert statements in Python? I'd like to use them for enforcing 'contracts' because they're quick to type, but from the docs: "Assert statements are a convenient way to insert debugging assertions into a program:" So to me it sounds like 'assert' statements are only useful while debugging, and not when an app is live, where you would also (especially!) want it to enforce contracts. Also, asserts can be removed with -O, and you only ever get AssertionError, where ValueError and the like might be more appropriate. As for point 1 (how do you test the new code?): I like the idea of automated unit tests. However, in practice I find they take a long time to write and test, especially if you want to have good coverage (not just lines, but also possible logic branches). So instead, I prefer to thoroughly test new code manually, and only then check in to version control. I feel that if you are disciplined, then unit tests are mainly useful for: 1) Maintenance of legacy code 2) More than 1 person working on a project One recent personal example: My workstation is a Debian Unstable box. I like to upgrade regularly and try out new library & app versions. Usually this doesn't cause major problems. One exception is sqlalchemy. It's API seems to change every few months, causing warnings and breakage in code which used the old API. This happened regularly enough that for one project I spent a day adding unit tests for the ORM-using code, and getting the unit tests up to 100% coverage. These tests should allow me to quickly catch and fix all sqlalchemy API breakages in my app in the future. The breakages also make me want to stop using ORM entirely, but it would take longer to switch to SQL-only code than to keep the unit tests up to date :-) My 'test code thoroughly before checkin' methodology is as follows: 1) Add "raise 'UNTESTED'" lines to the top of every function 2) Run the script 3) Look where the script terminated 4) Add print lines just before the exception to check the variable values 5) Re-run and check that the values have expected values. 6) Remove the print and 'raise "UNTESTED"' lines 7) Add liberal 'raise "UNTESTED"' lines to the body of the function. 8.1) For short funcs, before every line (if it seems necessary) 8.2) For longer funcs, before and after each logic entry/exit point (blocks, exits, returns, throws, etc): eg, before: if A(): B() C() D() E() after: raise 'UNTESTED' if A(): raise 'UNTESTED' B() C() D() raise 'UNTESTED' raise 'UNTESTED' E() 8.2.1) Later I add "raise 'UNTESTED'" lines before each line in the blocks also, if it seems necessary. 9) Repeat steps 2 to 8 until the script stops throwing exceptions 10) Check for 'raise "UNTESTED"' lines still in the script 11) Cause those sections of code to be run also (sometimes I need to temporarily set vars to impossible values inside the script, since the logic will never run otherwise) And here is one of my biggest problem with unit tests. How do you unit test code which almost never runs? The only easy way I can think of is for the code to have 'if or lines'. I know I'm meant to make 'fake' testing classes which return erroneous values, and then pass these objects to the code being tested. But this can take a long time and even then isn't guaranteed to reach all your error-handling code. The above methodology works well for me. It goes fairly quickly, and is much faster than writing and testing elaborate unit tests. So finally, my main questions: 1) Are there any obvious problems with my 'correctness' strategies? 2) Should I (regardless of time it takes initially) still be adding unit tests for everything? I'd like to hear what XP/agile programming advocates have to say on the subject. 3) Are there easy and fast ways to do write and test (complete) unit tests? 4) Any other comments? Thanks for your time. David. From bbrown at speakeasy.net Wed May 28 11:14:28 2008 From: bbrown at speakeasy.net (Robert Brown) Date: Wed, 28 May 2008 11:14:28 -0400 Subject: definition of a highlevel language? References: <2759eed3-956d-45c7-8dfb-9557f74133b3@56g2000hsm.googlegroups.com> <26d0b3d2-01cc-49bd-b284-1a849b0b835f@y38g2000hsy.googlegroups.com> <34dcbdc1-5285-41ec-be06-c88c56bb0372@i76g2000hsf.googlegroups.com> Message-ID: "inhahe" writes: > I like to think of a language that would combine low-level and high-level > features to be used at the programmer's whim. C--, High Level Assembly, and > C++ with in-line assembly are examples, but none of them come as high-level > as Python. Other possible examples might be ctypes, numpy, array.array, and > I heard a rumor that Python 3.0 might have optional type declarations. My > ideal language would be like a version of C++ (including in-line asm), or > C-- with classes, that's compiled, but supports Python abstractions and > features wherever possible (including doing away with {}'s and ;'s). Maybe you should give Common Lisp a try. It combines the high-level features you enjoy in Python with features like optional type declarations, which can be used to create high-performance code. You will also have fun playing around with syntactic abstraction (macros) to define very high-level domain specific languages. From sturlamolden at yahoo.no Sun May 25 22:15:18 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sun, 25 May 2008 19:15:18 -0700 (PDT) Subject: which datastructure for fast sorted insert? References: <4839A607.7070300@behnel.de> Message-ID: On May 25, 8:02 pm, Rodrigo Lazo wrote: > what about heapq for sorting? Heap is the data structure to use for 'fast (nearly) sorted inserts'. But heapq do not support (as far as I know) deletion of duplicates. But a custom heap class coud do that of course. From pistacchio at gmail.com Tue May 13 09:36:48 2008 From: pistacchio at gmail.com (pistacchio) Date: Tue, 13 May 2008 06:36:48 -0700 (PDT) Subject: module global variables References: <9af51496-5840-4f53-ae71-0d9c0da6c2f4@34g2000hsh.googlegroups.com> Message-ID: <598d5d96-4c4a-4f0e-b9f0-a2726ab3e63a@d77g2000hsb.googlegroups.com> On 12 Mag, 11:11, pistacchio wrote: > On 12 Mag, 10:47, Marco Mariani wrote: > > >pistacchiowrote: > > > On 12 Mag, 10:01, alex23 wrote: > > >> On May 12, 5:17 pm,pistacchio wrote: > > > >>> hi to all! > > >>> can i load a module passing to it, automatically and as default, all > > >>> the caller's global variables to act as module's global variables? > > > Are you positively sure you need this? > > > Modifying imported modules is already quite fragile, but this.. it's > > basically a reversed(import *) > > > It's quite messy. Where quite equals to "very" > > well, i'm writing a module called pycatrix. within the module i have > compile / exec statements in a functions that work on global > variables. ( exec compiledTemplate in globals() ). > > now, i don't want to be forced (or force the end user) to import to > call the module's function with a compulsory "globals()" as argument. up From 65563082 at qq.com Mon May 12 11:03:04 2008 From: 65563082 at qq.com (www.globwholesale.com) Date: Mon, 12 May 2008 08:03:04 -0700 (PDT) Subject: Discount, Chanel Prada Coach Women's Sandals, LV D&G Fendi Versace Sunglasses Message-ID: <1b4c5e62-4633-48e1-91d6-e65ae5b00fc1@q27g2000prf.googlegroups.com> Discount Coach Sandals, Dior Sandals, Prada Sandals, Chanel Sandals, Versace Sandals, Crocs Sandals, LV Sandals, ( G U C C I ) Sandals, Women's Sandals Men's Slippers From China Brand Sunglasses Wholesale: Discount, Prada Sunglasses Discount, D&G Sunglasses Discount, Fendi Sunglasses Discount, Burberry Sunglasses Discount, Chanel Sunglasses Discount, LV Sunglasses Discount, Dior Sunglasses Discount, (G U C C I ) Sunglasses Discount, Armani Sunglasses Discount, Versace Sunglasses Discount, A&F Sunglasses Discount, LV Sunglasses Wholesale, Prada Sunglasses Wholesale, D&G Sunglasses Wholesale, Fendi Sunglasses Wholesale, Burberry Sunglasses Wholesale, Chanel Sunglasses Wholesale, LV Sunglasses Wholesale, Dior Sunglasses Wholesale, ( G U C C I ) Sunglasses Wholesale, Armani Sunglasses Wholesale, Versace Sunglasses Wholesale, A&F Sunglasses Wholesale, LV Sunglasses From nik600 at gmail.com Mon May 26 11:36:44 2008 From: nik600 at gmail.com (nik600) Date: Mon, 26 May 2008 17:36:44 +0200 Subject: integration with browser In-Reply-To: <69vmlgF35akucU1@mid.uni-berlin.de> References: <69vmlgF35akucU1@mid.uni-berlin.de> Message-ID: <9469c3170805260836m32e35e70w329259e3a0563b36@mail.gmail.com> Both win and linux if possible i don't have preference for gui. Thanks 2008/5/26, Diez B. Roggisch : > nik600 wrote: > >> Hi to all >> >> i'd like to create a window that integrates a browser control, the >> browser control must support html, javascript and css. >> >> Is possible to include something that uses the same engine of firefox? >> >> Thanks to all in advance > > What OS, what GUI toolkit? > > Diez > -- > http://mail.python.org/mailman/listinfo/python-list > -- /*************/ nik600 https://sourceforge.net/projects/ccmanager https://sourceforge.net/projects/reportmaker https://sourceforge.net/projects/nikstresser From arnodel at googlemail.com Wed May 14 13:45:11 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 14 May 2008 18:45:11 +0100 Subject: Class Methods Vs Any Other Callable References: <98b4a67c-9ec7-407c-8c80-06488bd48a68@e39g2000hsf.googlegroups.com> <690ap7F2u0ftdU1@mid.uni-berlin.de> <238061d6-9423-44c1-90b2-cc09f392db9b@p25g2000hsf.googlegroups.com> Message-ID: George Sakkis writes: > On May 14, 10:19 am, "Diez B. Roggisch" wrote: > >> > An instance method works on the instance >> > A Static method is basically a function nested within a class object >> > A class method is overkill? >> >> If anything, a static method is overkill. See it this way: *if* you for some >> reason put a method into an enclosing context - isn't it worth having a >> reference to that? > > My feeling exactly; these days I almost always use class methods > instead of static. I vaguely remember seeing somewhere an example > where a static method was the only (elegant) solution; neither a class > method nor a plain function would do. I'll post it if I find it unless > someone beats me to it. > > George __new__ is a static method! -- Arnaud From gagsl-py2 at yahoo.com.ar Mon May 12 02:39:47 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 12 May 2008 03:39:47 -0300 Subject: computing with characters References: <474df$48180e0b$541fc2ec$12128@cache1.tilbu1.nb.home.nl> <481813E2.2030302@islandtraining.com> <61f41$48181d87$541fc2ec$29688@cache3.tilbu1.nb.home.nl> <2d6af$48183337$541fc2ec$23598@cache2.tilbu1.nb.home.nl> <87y76vyamr.fsf@physik.rwth-aachen.de> <4820319a_7@news.bluewin.ch> <8f1293e5-26f7-4183-acd4-47fd6eda931a@l42g2000hsc.googlegroups.com> Message-ID: En Tue, 06 May 2008 08:16:55 -0300, escribi?: > I tend to do ", ".join("%s" % e for e in item) > > Is there any difference between this and str()? Use the timeit module to measure performance: C:\TEMP>python -m timeit "for i in xrange(10000): str(i)" 10 loops, best of 3: 81.8 msec per loop C:\TEMP>python -m timeit "for i in xrange(10000): '%s' % i" 10 loops, best of 3: 78.5 msec per loop The %s version consistently wins in my system -2.5.1 on WinXP- for a wide range of inputs. -- Gabriel Genellina From inhahe at gmail.com Tue May 27 01:28:38 2008 From: inhahe at gmail.com (inhahe) Date: Tue, 27 May 2008 01:28:38 -0400 Subject: Hungarian Notation Message-ID: Does anybody know of a list for canonical prefixes to use for hungarian notation in Python? Not that I plan to name all my variables with hungarian notation, but just for when it's appropriate. From kyosohma at gmail.com Thu May 1 17:31:58 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 1 May 2008 14:31:58 -0700 (PDT) Subject: where do I begin with web programming in python? References: <37ea096e-cf3e-4932-8370-306a15a2aebd@25g2000hsx.googlegroups.com> Message-ID: <3832bd90-c219-4bc8-b16b-0c5e0318c83b@f63g2000hsf.googlegroups.com> On May 1, 4:25?pm, jmDesktop wrote: > I have been to the main python site, but am still confused. ?I have > been using .net, so it may be obvious how to do this to everyone > else. ?I am aware there are various frameworks (Django, Pylons, etc.), > but I would like to know how to create web pages without these. ?If I > have mod_python or fastcgi on apache, where do I start? ?I don't have > clue where to begin to create a web page from scratch in python. ?I am > sure I will want to access database, etc., all the "normal" stuff, I > just want to do it myself as opposed to the frameworks, for learning. > > Thank you for any help. The web frameworks make it a lot easier. But you can use the httplib modules. You should check out the wiki: http://wiki.python.org/moin/WebProgramming There's also a couple of books on the topic: "Python Web Programming" by Steve Holden, and "Web Programming in Python" by Thiruvathukal. Check out the cgi-type stuff especially. Hope that helps some. Mike From mmanns at gmx.net Sun May 25 19:55:03 2008 From: mmanns at gmx.net (Martin Manns) Date: Mon, 26 May 2008 01:55:03 +0200 Subject: Getting a set of lambda functions References: <83bb3e45-f32f-4811-831f-d1e31d4fcb1e@d77g2000hsb.googlegroups.com> <59719846-588e-414e-a1b9-cc7b04019501@k37g2000hsf.googlegroups.com> Message-ID: On Sun, 25 May 2008 14:39:28 -0700 (PDT) bearophileHUGS at lycos.com wrote: > This may have some bugs left, but it looks a bit better: [...] > self._hash = hash(self._func.func_code) ^ \ > hash(tuple(signature[0]) + tuple(signature[1:3])) > def __eq__(self, other): > return self._func.func_code == other._func.func_code and \ > getargspec(self._func) == getargspec(other._func) > def __hash__(self): > return self._hash > def __call__(self, *args, **kwargs): > return self._func(*args, **kwargs) > > I haven't put a full hashing of getargspec(self._func) too into the > __init__() because it may contain too much nested unhashable > structures, but the __eq__() is able to tell them apart anyway, with > some collisions. Looking at a function: >>> a=lambda x:x >>> dir(a) ['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__get__', '__getattribute__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name'] Should func_globals and func_name also be taken into account for __eq__()? Best Regards Martin From kyosohma at gmail.com Tue May 13 14:56:23 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 13 May 2008 11:56:23 -0700 (PDT) Subject: Literate programs in Python References: <37e8fb41-8008-45aa-a123-b71455bc7ce5@t54g2000hsg.googlegroups.com> <6bb0ca79-1070-4d42-90a9-a1066b152210@d1g2000hsg.googlegroups.com> Message-ID: On May 13, 1:47?pm, Carl Banks wrote: > On May 13, 1:44 pm, Mike Driscoll wrote: > > > On May 13, 10:28 am, Paul Miller wrote: > > > > Does anyone know of any (preferably largish) examples of literate > > > programs written using Python? ?Alternatively, does anyone know of any > > > literate programming tools which support Python well? ?(I am aware of > > > Leo and I've been to literateprogramming.com, but any additional > > > pointers would be much appreciated!) > > > Check out Zope, bittorrent, or Editra. You should just go to > > SourceForge and do a search for projects done in Python. > > Those aren't examples of literate programming AFAIK. ?(Check Wikipedia > for "literate programming" if you're still confused.) > > It occurs to me that one could get pretty close to literate > programming with Pure Python (if they stick to regular function calls > and not expect code weaving, which would need a preprocessor). ?A > fairly simple script could ?parse docstrings and Python source files > to produce a document from the source. ?In fact, there are tools that > can do that sort of thing already, but I doubt they output documents > according to literate programming expectations. ?Don't know of any > tools specifically for literate programming. > > Carl Banks Sorry...I took the OP's meaning literally... Mike From daveparker at flamingthunder.com Tue May 13 09:32:11 2008 From: daveparker at flamingthunder.com (Dave Parker) Date: Tue, 13 May 2008 06:32:11 -0700 (PDT) Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <2b66a86e-5a05-4262-b3c9-4703b0ae3372@d1g2000hsg.googlegroups.com> <5b0e3f70-afde-4480-8713-e7113b1250d7@x35g2000hsb.googlegroups.com> <1f537717-00d0-48ee-99b6-7125b96a6133@t12g2000prg.googlegroups.com> <68t4o0F2vaoncU1@mid.uni-berlin.de> Message-ID: > Don't let yourself be irritated by castironpi I'm not the sort to get irritated by anyone. There is value in all interaction. Flaming Thunder is itself the averaging of interactions with many computer languages and conversations with many people, so as to create a language that allows people to tell a computer what they want it to do, without having to know very much about how the computer does it. On May 13, 3:18?am, "Diez B. Roggisch" wrote: > Dave Parker wrote: > > On May 12, 7:20?pm, castiro... at gmail.com wrote: > >>Yes, I am trying to visualize something. > > > If it is related to making furniture comfortable for humans, have you > > considered painting the furniture with thermochromic paint ( > >http://en.wikipedia.org/wiki/Thermochromism)? ?It changes color in > > response to temperature, which in part is determined by how hard a > > body is pressed against it because close contact tends to trap heat. > > An evenly distributed color might indicated evenly distributed > > pressure. > > Don't let yourself be irritated by castironpi - he's the virtual equivalent > of a mumbling mad man in this group. Ignorance serves best as remedy - and > getting a filter to work, as I did (so I only see his postings being > quoted... a huge relief!) > > Diez From gagsl-py2 at yahoo.com.ar Sun May 25 13:53:57 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 25 May 2008 14:53:57 -0300 Subject: raising an exception when multiple inheritance involves same baseThank References: <0932331b-126f-494e-b946-9e6471d31dfa@x35g2000hsb.googlegroups.com> Message-ID: En Sun, 25 May 2008 13:32:39 -0300, Paul McGuire escribi?: > Here's a more general version of your testing code, to detect *any* > diamond multiple inheritance (using your sample classes). > > for cls in (A,B,C,D): > seen = set() > try: > bases = cls.__bases__ > for b in bases: > if hasattr(b,"__mro__"): > for m in b.__mro__: > if m in seen: > raise Exception("diamond multiple > inheritance") > seen.add(m) > except Exception, e: > print cls,"has diamond MI" > else: > print cls,"is ok" I think you should exclude the `object` class from the test, because all new-style classes inherit from it and *every* case of multiple inheritance forms a diamond. -- Gabriel Genellina From pavlovevidence at gmail.com Sat May 24 21:15:39 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 24 May 2008 18:15:39 -0700 (PDT) Subject: Assignment and comparison in one statement References: <10f19bee-1e0a-4401-a03b-18c458388297@s50g2000hsb.googlegroups.com> Message-ID: On May 24, 7:12 am, Johannes Bauer wrote: > Carl Banks schrieb: > > > p = myfunction() > > if p: > > print p > > > (I recommend doing it this way in C, too.) > > This is okay for if-clauses, but sucks for while-loops: > > while (fgets(buf, sizeof(buf), f)) { > printf("%s\n", buf); > > } In earlier times, the Python idiom was this: while True: line = f.readline() if not line: break print line Not the prettiest thing ever, but it works fine, is readable, and avoids a temporary variable. In C, given the choice between this or using assignment expression, I'd say use either one. (But don't use the version with a temporary, that's ugly as hell.) More recent versions of Python have obviated the need to use this idiom by making it possible to iterate over the lines of a file directly. First they added xreadlines: for line in xreadlines(f): print line Then they deprecated the xreadline function and made it a method: for line in f.xreadlines(): print line Then they recommended you no longer use that, and just made file objects directly iterable: for line in f: print line The point is, the Python language developers do share your concern about these things. However, they still think assignment epxressions are a very bad idea, so they've sought other solutions to these issues. (But, as I said, they have yet to provide an alternative for elif clauses; you're stuck with workarounds there.) Carl Banks From rocky at panix.com Wed May 14 23:31:04 2008 From: rocky at panix.com (R. Bernstein) Date: Wed, 14 May 2008 23:31:04 -0400 Subject: Running an interactive interpreter inside a python Message-ID: The next release of pydb will have the ability to go into ipython from inside the debugger. Sort of like how in ruby-debug you can go into irb :-) For ipython, this can be done pretty simply; there is an IPShellEmbed method which returns something you can call. But how could one do the same for the stock python interactive shell? To take this out of the realm of debugging. What you want to do is to write a python program that goes into the python interactive shell - without having to write your own a read/eval loop and deal with readline, continuation lines, etc. The solution should also allow - variables/methods in the calling PYthon program to be visible in the shell - variables set in the interactive (sub) shell should persist after the shell terminates, although this is a weaker requirement. POSIX subshells for example *don't* work this way. There has been much written about how to embed Python from C, so I suppose this may offer one way. And at worst, I could write a C extension which follows how C Python does this for itself. But is there a simpler way? Thanks. From arnodel at googlemail.com Tue May 20 05:19:20 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 20 May 2008 10:19:20 +0100 Subject: compressing short strings? References: <7xy7658k8o.fsf_-_@ruckus.brouhaha.com> Message-ID: Paul Rubin writes: > I have a lot of short English strings I'd like to compress in order to > reduce the size of a database. That is, I'd like a compression > function that takes a string like (for example) "George Washington" > and returns a shorter string, with luck maybe 6 bytes or so. One > obvious idea is take the gzip function, compress some large text > corpus with it in streaming mode and throw away the output (but > setting up the internal state to model the statistics of English > text), then put in "George Washington" and treat the additional output > as the compressed string. Obviously to get reasonable speed there > would have to be a way to save the internal state after initializing > from the corpus. > > Anyone know if this has been done and if there's code around for it? > Maybe I'm better off with freezing a dynamic Markov model? I think > there's DMM code around but am not sure where to look. > > Thanks. Out of the blue idea which is probably rubbish: Create a tree of your words, look at it as a Deterministic Finite Automaton (DFA), minimise it, you get what some call a DAWG. That works very well with lots of small words. e.g. Words aabc, babc, bbbc. Minimal DFA: 1 -a-> 2 -a-> 4 -b-> 5 -c-> 6 \ ^ b-> 3 -a-----+ \ / b----+ To compress a word, simply find its position in alphabetical order, call that its 'path'. The 'decompression algorithm' is then (in pseudo-python) def decompress(DFA, path): letters = [] state = DFA.initial_state while not state.is_final(): transitions = state.transitions path, choice = divmod(path, len(transitions)) state = transitions[choice].new_state letters.append(transitions[choice].letter) I'm not too sure about this :) -- Arnaud From wizzardx at gmail.com Sat May 24 15:14:36 2008 From: wizzardx at gmail.com (David) Date: Sat, 24 May 2008 21:14:36 +0200 Subject: Code correctness, and testing strategies In-Reply-To: References: Message-ID: <18c1e6480805241214t6c556e46r31170ea50d0eb1d5@mail.gmail.com> Hi again list. > > As you come up with the corner case, write a test for it and leave the implementation > for later. The hard part of coding is always defining your problem. Once it is > defined (by a test) the solution is just a matter of tidy work. > Is it considered to be cheating if you make a test case which always fails with a "TODO: Make a proper test case" message? While it is possible to describe all problems in docs, it can be very hard to write actual test code. For example: sanity tests. Functions can have tests for situations that can never occur, or are very hard to reproduce. How do you unit test for those? A few examples off the top of my head: * Code which checks for hardware defects (pentium floating point, memory or disk errors, etc). * Code that checks that a file is less than 1 TB large (but you only have 320 GB harddrives in your testing environment). * Code which checks if the machine was rebooted over a year ago. And so on. These I would manually test by temporarily changing variables in the code, then changing them back. To unit test these you would need to write mock functions and arrange for the tested code to call them instead of the python built-ins. Also, there are places where mock objects can't be used that easily. eg 1: A complicated function, which needs to check the consistency of it's local variables at various points. It *is* possible to unit test those consistency checks, but you may have to do a lot of re-organization to enable unit testing. In other cases it might not be appropriate to unit test, because it makes your tests brittle (as mentioned by another poster). eg: You call function MyFunc with argument X, and expect to get result Y. MyFunc calls __private_func1, and __private_func2. You can check in your unit test that MyFunc returns result Y, but you shouldn't check __private_func1 and __private_func2 directly, even if they really should be tested (maybe they sometimes have unwanted side effects unrelated to MyFunc's return value). eg: Resource usage. How do you unit test how much memory, cpu, temporary disk space, etc a function uses? eg: Platforms for which unit tests are hard to setup/run. - embedded programming. You would need to load your test harness into the device, and watch LED patterns or feedback over serial. Assuming it has enough memory and resources :-) - mobile devices (probably the same issues as above) eg: race conditions in multithreaded code: You can't unit test effectively for these. And so on. > > Agreed. There is no good way of reusing your prototype code in TDD. You end > up having to throw your propotype away in order to have a proper tested > implementation in the end. Takes more time up front, but less time over the > lifecycle of the program you are building. > Sounds like you are talking about cases where you have to throw away the prototype *because* you couldn't unit test it properly? (but it was otherwise functioning perfectly well). >>Problem 3: Slows down development in general >> >>Having to write tests for all code takes time. Instead of eg: 10 hours >>coding and say 1/2 an hour manual testing, you spend eg: 2-3 hours >>writing all the tests, and 10 on the code. > > This is incorrect. It speeds up development in general. The debugging phase of > development becomes much shorter because the bugs are fewer and the ones you > have a much shallower. There are so many tests that reduce the scope in which > you have to search for the bug that it usually becomes trivial to find. Depends on the type of bug. If it's a bug which breaks the unit tests, then it can be found quickly. Unit tests won't help with bugs they don't explicitly cover. eg off-by-one, memory leaks, CPU load, side-effects (outside what the unit tests test), and so on. That's another reason why I don't think that unit tests are a silver bullet. You can have code that's totally wrong, but still succeeds in the tests (even if they're very detailed). eg: hardcoding return values expected by the tests, and returning garbage the rest of the time. But once you track down problems like the above you can write more unit tests to catch those exact bugs in the future. This is one case where I do favour unit tests. I guess you could compare unit tests to blacklists or anitivirus software. All of them only catch cases that have been explicitely coded into them. > > I have direct experience from this, getting my company to change to TDD about > 10 months ago. Productivity has improved enormously. I'd say that we have cut > between 25 and 50% in development time. > Going by your figures and other cases I've read on the web, there are definitely cases where TDD is beneficial and can save a lot of time. What I'm not sure of (probably inexperience on my part) is when you should and shouldn't use TDD, and to what extent. I'm sure that factors like this have to come in to play when deciding if and how to use TDD in a given project: - size and age of the project (new, small code is easier to understand than large, old) - complexity & modularity of project - programming language used (dynamic langs need unit tests more than compiled) - importance of project (consequences of bugs) - who the project is for (yourself, inhouse, or for client) - how easy it is to fix problems in deployed software - number of developers - skill & discipline of developers - development style (waterfall/incremental, etc) - consistency checks already built into the software That last one (internal consistency checks) is a big one for me. If software has a lot of internal consistency checks (contracts), then I feel that the need for unit tests is a lot less. >>Problem 4: Can make refactoring difficult. >> >>If you have very complete & detailed tests for your project, but one >>day you need to change the logic fundamentally (maybe change it from >>single-threaded to multi-threaded, or from running on 1 server to >>distributed), then you need to do a large amount of test refactoring >>also. The more tests you have (usually a good thing), the longer it >>will take to update all the tests, write new ones, etc. It's worse if >>you have to do all this first before you can start updating the code. > > No, this is a total misunderstanding. It makes refactoring much easier. > It takes a bit of time to refactor the affected tests for the module, but you > gain so much by having tests that show that your refactoring is not breaking > code that should be unaffected that it saves the extra time spent many times > over. > Makes refactoring easier how? I assume you mean the unchanged tests, which check functionality which should be the same before and after your refactoring. All the other tests need to be replaced. I agree that the unchanged tests can be helpful. It's the extra work of unit test maintenance I have a problem with. In an extreme case you might refactor the same code multiple times, requiring the test cases to also be refactored each time too (more test cases = more work each time). To me it feels like the test cases can be a lot of 'dead weight', slowing down development. Even if you want unit tests for the final version which goes to the customer, you still had to spend time with re-writing unit tests for all the refactored versions inbetween. To me those intermediate unit test versions sound like a complete waste of time. Please correct me if this is also mistaken :-) > Introducing bugs because you missed some aspect in a refactoring is one of the > most common problems in non-TDD code and it is a really nasty quality > concern. I agree here. But I feel that you can get the same quality by good QA and human testing (ie: developer does a lot of testing, then hands it over to testers, then it goes to the customer). Which should be done whether or not you have unit tests. I feel that unit tests are mainly good for catching rare cases which might not be tested by a human. In other words, full-on TDD only becomes really useful when projects grow large (and complicated) and can't be fully tested by humans? Until that point, only using unit tests to catch regressions seems to be more than enough to ensure good quality. (Again, correct me if this is mistaken). >> >>Problem 5: Tests are more important than code >> >>You need to justify the extra time spent on writing test code. Tests >>are nice, and good to have for code maintainability, but they aren't >>an essential feature (unless you're writing critical software for life >>support, etc). Clients, deadlines, etc require actual software, not >>tests for software (that couldn't be completed on time because you >>spent too much time writing tests first ;-)). >> > The tests are as important as the code. As a customer, I don't think I'd buy > software today unless I know that it has been built using TDD. Certainly I am > ahead of the curve in this, but it won't be long before this will be required > by skilled organisations buying software and sooner or later the rest of the > world will follow. How much software is written with TDD? Do companies generally advertise this? I get the idea that most high quality open source software (Apache, linux kernel, GNU, Python, etc) are developed in a non-TDD way. What they do have is intelligent developers, coding conventions, and a very good testing & QA process. Where they do have unit tests it's usually for regressions. Why don't they use TDD if it would make such a big difference? Are you going to stop using open source software (like Python) which isn't written with TDD? > > Getting into a TDD mindset is hard work, but those who succeed produce better > software with less effort. > Thanks for your informative reply. I've learned a bit from this thread and will definitely look more into TDD :-) David. From brad at 16systems.com Thu May 22 18:20:12 2008 From: brad at 16systems.com (Brad) Date: Thu, 22 May 2008 18:20:12 -0400 Subject: Python is slow In-Reply-To: References: Message-ID: cm_gui wrote: > Python is slow. It ain't C++, but it ain't a punch card either... somewhere in between. I find it suitable for lots of stuff. I use C++ when performance really matters tho... right tool for the job. Learn a good interpreted language (Pyhton) and a good compiled language (C or C++) and you'll be just fine. Until then, quit bitching. From mcknight0219 at gmail.com Fri May 23 14:32:26 2008 From: mcknight0219 at gmail.com (Jimmy) Date: Fri, 23 May 2008 11:32:26 -0700 (PDT) Subject: can python do some kernel stuff? References: <983ec0f6-1316-40cd-a4d4-ce9b5e272a60@h1g2000prh.googlegroups.com> <48366cfa$0$15168$607ed4bc@cv.net> <28c432f0-657c-4272-8cd4-a9081b013279@w5g2000prd.googlegroups.com> <69nigsF3499pqU2@mid.uni-berlin.de> <8d1f0f0f-8dc4-43df-bbc5-78c05b81d6ca@u12g2000prd.googlegroups.com> <3ba0233a-0ed4-4057-bc9c-7e1940968d92@d19g2000prm.googlegroups.com> <69oa1aF33cfteU1@mid.uni-berlin.de> Message-ID: <2826a237-a4e7-4aa5-a015-de00ef4ed642@w1g2000prd.googlegroups.com> On May 24, 12:34 am, "Diez B. Roggisch" wrote: > Jimmy schrieb: > > > > > On May 23, 11:14 pm, Jimmy wrote: > >> On May 23, 5:53 pm, "Diez B. Roggisch" wrote: > > >>> Jimmy schrieb: > >>>> On May 23, 3:05 pm, Andrew Lee wrote: > >>>>> Jimmy wrote: > >>>>>> Hi to all > >>>>>> python now has grown to a versatile language that can > >>>>>> accomplish tasks for many different purposes. However, > >>>>>> AFAIK, little is known about its ability of kernel coding. > >>>>>> So I am wondering if python can do some kernel coding that > >>>>>> used to be the private garden of C/C++. For example, can python > >>>>>> intercept the input of keyboard on a system level? someone told me > >>>>>> it's a kernel thing, isn't it? > >>>>>http://wiki.python.org/moin/elmer > >>>> well, straightly speaking, how can I know a key is pressed on a system- > >>>> level if > >>>> using python? > >>> What has that todo with kernel programming? You can use e.g. pygame to > >>> get keystrokes. Or under linux, read (if you are root) the keyboard > >>> input file - I've done that to support several keyboards attached to a > >>> machine. > >>> And the original question: no, python can't be used as kernel > >>> programming language. Amongst other reasons, performance & the GIL > >>> prevent that. > >>> Diez > >> sorry, my aim is not limited to one particular program. Yes, many > >> library can > >> permit you to respond to keyboard event, however, what I want is a > >> universal > >> function. as long as a key is pressed, no matter where, my program can > >> repond. > > >> I am quite strange with this topic. But according to my understanding, > >> any event, keyboard event > >> for example, once triggered, will be dilivered by keyboard driver to X > >> system, and then > >> any running program can either choose to respond or ignore. So my > >> question can be translated to: > >> how to make my program respond ? > > > maybe I'd better elaborate on my question. Back to my original > > question: > > intercept keyboard event on a system level. If you are writing program > > in > > emacs, of course, the keyboard inputs are meant for emacs only. What > > I > > want is no matter what program you're running, keyboard events can be > > anyway caught by my program. > > > Am I clear with myself? :) > > Do you want to intercept the call (prevent that it is passed through to > e.g. emacs), or are you merely interested in getting it? If the latter, > you can (as root) access the /dev/input keyboard device and get the > scan-codes. > > The former is more complicated - without research I don't know out of my > head how to accomplish that. But it must be possible, as e.g. KDE > observes global key-shortcuts. Most probably a X-server thing. > > Diez thanks, right now I am content with just knowing a key is pressed. as you said, I checked /etc/input/event1 which seems the input of keyboard. Then I got some extremely strange code. however, how can I just simply know a key is pressed? From timr at probo.com Tue May 20 00:14:04 2008 From: timr at probo.com (Tim Roberts) Date: Tue, 20 May 2008 04:14:04 GMT Subject: Write bits in file References: Message-ID: Monica Leko wrote: > >I have a specific format and I need binary representation. Does >Python have some built-in function which will, for instance, represent >number 15 in exactly 10 bits? For the record, I'd like to point out that even C cannot do this. You need to use shifting and masking to produce a stream of 8-bit bytes, or to extract your values from a stream of 8-bit bytes. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From gagsl-py2 at yahoo.com.ar Mon May 19 20:16:51 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 19 May 2008 21:16:51 -0300 Subject: Thread killing - I know I know! References: <6fda9c2c-84fe-4339-8ce2-25b6d6b97ba4@t54g2000hsg.googlegroups.com> <8ac3f740-1c21-49c8-85e7-023ebe03d880@x41g2000hsb.googlegroups.com> <7xtzgtyjtx.fsf@ruckus.brouhaha.com> Message-ID: En Mon, 19 May 2008 20:07:06 -0300, Paul Rubin <"http://phr.cx"@NOSPAM.invalid> escribi?: > blaine writes: >> How is it that you recommend killing a pure python thread? Make the thread cooperate. It should periodically check some variable or condition, and cleanly exit when requested. >> And also, >> when i use the 'threading' module am I creating a process, or a (gasp) >> thread? > > A thread. > >> (Is this an obvious question - and if so, how does one create >> a 'process'?) > > os.fork() A more portable answer: using the subprocess module. -- Gabriel Genellina From yves at zioup.com Sun May 11 18:51:09 2008 From: yves at zioup.com (Yves Dorfsman) Date: Sun, 11 May 2008 22:51:09 GMT Subject: Is using range() in for loops really Pythonic? In-Reply-To: <48275446$0$11628$607ed4bc@cv.net> References: <482657ca$0$25026$607ed4bc@cv.net> <41078222-aec0-4e8b-8a1f-945cdf814498@m73g2000hsh.googlegroups.com> <48275446$0$11628$607ed4bc@cv.net> Message-ID: John Salerno wrote: > > To me, the first example is a pure use of the for loop. You are > iterating through an object and *using* the items you are stepping through. > > The second example, however, is simply doing something 10 times, and > what it's doing has nothing to do with 'x' or xrange. So it seems like > an abuse of the for loop. Well, I would say this: myl = ['a', 'b', 'c', 'd'] for i in xrange(len(myl)): print myl[i] As you would see in other languages, is an abuse in python. But in you need to iterate 5 times over something. Do you have a cleaner / python'er alternative ? Do you find the following cleaner: x = 0 while x <= 4: print x x += 1 Yves. http://www.SollerS.ca From collinyeung at shaw.ca Wed May 21 21:06:06 2008 From: collinyeung at shaw.ca (Collin) Date: Thu, 22 May 2008 01:06:06 GMT Subject: Python and Flaming Thunder In-Reply-To: References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> Message-ID: <2G3Zj.285812$pM4.26927@pd7urf1no> Dave Parker wrote: > On May 20, 7:05 pm, Collin wrote: > >> Personally, FT is a bit meh to me. The way you issue your statements I >> always think something is wrong, mainly because when I want to define, >> say, x, in python I'd go: >> >> x = "whatever" >> >> Instantly noting that I defined x. While in Flaming Thunder I'd have to >> type: >> >> Set x to "whatever" >> >> It just feels wrong. > > Actually, it felt wrong to me when I first started working on Flaming > Thunder because I've been programming for decades and have had all of > the programming idioms burned into my brain. > > But after getting input from children and teachers, etc, it started > feeling right. > > For example, consider the two statements: > > x = 8 > x = 10 > > The reaction from most math teachers (and kids) was "one of those is > wrong because x can't equal 2 different things at the same time". > Many computer languages conflate "equality" with "assignment" and then > go to even more confusing measures to disambiguate them (such as using > == for equality, or := for assignment). > > Plus, symbols are more confusing for people to learn about than > words. There are lots of people who are fluent in English, but > dislike math. > > So, I opted for a simple, unambiguous, non-mathematical way of > expressing "assignment" which makes sense even to the non- > mathematically inclined: > > Set x to 8. > > That way, = can be reserved unambiguously and unconfusingly for the > mathematical notion of "equality" -- because it's in their math > classes that people learn what = means: > > Set QuadraticEquation to a*x^2 + b*x + c = 0. Then I guess the elementary school kids will use your FT system while we will use our naturally burned-in sense of syntax from other programming languages, eh? Not saying this as a negative or anything, I'm just saying that most of us have a habit, and it's not necessarily a bad nor good habit, of doing things the way most languages have them done. For example, x = 8 is extremely readable, to, I assume, most of us. Set x to 8, it takes some time getting used to. Why should we switch to a language that will take us time to get used and some more time to understand syntax when we already understand and can efficiently use our current languages? It's like going to the middle of London and screaming: "HEY GUYS GUESS WHAT! I JUST INVENTED A NEW LANGUAGE AND IT'S VERY VERY EASY TO LEARN!" And the people who would try the language would find the way you do everything is very different from English, or their native language, for that matter. Best let sleeping dogs lie. Collin From jcd at sdf.lonestar.org Sun May 18 14:13:57 2008 From: jcd at sdf.lonestar.org (J. Clifford Dyer) Date: Sun, 18 May 2008 14:13:57 -0400 Subject: [jcd@sdf.lonestar.org: Re: Compress a string] Message-ID: <20080518181357.GB14680@sdf.lonestar.org> On Sun, May 18, 2008 at 07:06:10PM +0100, Matt Porter wrote regarding Compress a string: > > Hi guys, > > I'm trying to compress a string. > E.g: > "AAAABBBC" -> "ABC" > > The code I have so far feels like it could be made clearer and more > succinct, but a solution is currently escaping me. > > > def compress_str(str): > new_str = "" > for i, c in enumerate(str): > try: > if c != str[i+1]: > new_str += c > except IndexError: > new_str += c > return new_str > > > Cheers > Matt def compress_str(s): # str is a builtin keyword. Don't overload it. out = [] for c in s: if out and c == out[-1]: out.append(c) # This is faster than new_str += c return ''.join(out) From inhahe at gmail.com Sun May 18 06:44:04 2008 From: inhahe at gmail.com (inhahe) Date: Sun, 18 May 2008 06:44:04 -0400 Subject: morning in Python References: <409ea9f1-9774-4bf2-abac-2daf997bc97f@c65g2000hsa.googlegroups.com> <143b1593-658c-4a1c-9826-72af517b3ad0@m36g2000hse.googlegroups.com> Message-ID: > My ideal language would be a natively compiling cross between C++ and > Python. Objects declared with a type would be statically typed, objects > not declared with a type would be dynamically typed. There would also be > keywords to declare that class names won't be reassigned and class > attributes won't be deleted. Those attributes would be referred to by > offset, not hash table keys. But those attributes would also exist in the hash table because the referer can also use a dynamically created name. From deets at nospam.web.de Tue May 13 13:26:43 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 13 May 2008 19:26:43 +0200 Subject: Python and Flaming Thunder In-Reply-To: <8b9560fa-7f29-4bfe-b312-e3da0e3779b6@z24g2000prf.googlegroups.com> References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <5b0e3f70-afde-4480-8713-e7113b1250d7@x35g2000hsb.googlegroups.com> <1f537717-00d0-48ee-99b6-7125b96a6133@t12g2000prg.googlegroups.com> <68t4o0F2vaoncU1@mid.uni-berlin.de> <2a32179a-9439-449c-bd07-fff6a4075aee@s50g2000hsb.googlegroups.com> <7ee5dffd-df8f-46f0-bd78-c81ac0418a9a@d77g2000hsb.googlegroups.com> <65ef773e-a1c3-4adb-a18b-e8b8451efe5e@b5g2000pri.googlegroups.com> <68trmmF2vjivnU1@mid.uni-berlin.de> <68tuhfF2unducU1@mid.uni-berlin.de> <8b9560fa-7f29-4bfe-b312-e3da0e3779b6@z24g2000prf.googlegroups.com> Message-ID: <68u1avF2ujou9U1@mid.uni-berlin.de> Dave Parker schrieb: >> Who has conducted the research that supports that statement? And since when >> is ^ the better operator for "to the power of" that **? Because latex uses >> it? I need to see the elementary school students who use that... > > All of the calculators and textbooks that elementary school students > use, use "^" for powers. Just like Flaming Thunder does. I haven't > seen "**" for powers since FORTRAN. I haven't seen a power operator in elementary school at all. And even *if* I did see it, it would have been in the raised-text-variant, *not* the caret that is a crutch. Diez From tamim.shahriar at gmail.com Mon May 19 01:27:24 2008 From: tamim.shahriar at gmail.com (subeen) Date: Sun, 18 May 2008 22:27:24 -0700 (PDT) Subject: How do *you* use Python in non-GUI work? References: <20080518182022.990193bd.johnjsal@NOSPAMgmail.com> Message-ID: <9dd32e12-9f4e-49f9-b2eb-cc8c58a60e85@z16g2000prn.googlegroups.com> On May 19, 7:52 am, "Kam-Hung Soh" wrote: > On Mon, 19 May 2008 08:20:22 +1000, John Salerno > > wrote: > > Hey all. Just thought I'd ask a general question for my own interest. > > Every time I think of something I might do in Python, it usually > > involves creating a GUI interface, so I was wondering what kind of work > > you all do with Python that does *not* involve any GUI work. This could > > be any little scripts you write for your own benefit, or what you do at > > work, if you feel like talking about that! :) > > > Thanks. > > -- > >http://mail.python.org/mailman/listinfo/python-list > > - Enhancing existing products by scripting new features. > - Interface between databases, Excel and text files. > - Convert data between flat files and XML. > - Manage files for build processes. > - Automating processes (e.g. checkout, builds, FTP). > > Wish I had some reasons to make a GUI application in Python. > > -- > Kam-Hung Soh Software Salariman I also haven't used GUI in python yet. I basically write web crawlers/ spiders in Python where GUI is not essential. regards, Subeen http://love-python.blogspot.com/ From rolf.oltmans at gmail.com Fri May 2 14:51:42 2008 From: rolf.oltmans at gmail.com (Oltmans) Date: Fri, 2 May 2008 11:51:42 -0700 (PDT) Subject: Searching and replacing text ? Message-ID: <6c06af6c-e068-4569-9a2d-f42df5fe1ff4@k37g2000hsf.googlegroups.com> Hi, I'm new to Python (and admittedly not a very good programmer) and I've come across a scenario where I've to search and replace text in a file. For the sake of an example, I'm searching for every occurence of the text [[http://www.hotmail.com -> Hotmail]] I've to replace it with [http://www.hotmail.com Hotmail] I've come up with following scheme p=re.compile(r'\[\[') q=re.compile(r'->') p.sub('[',txt) q.sub('\b',txt) Give that I don't have very strong RegEX background, this doesn't look very elegant. Is there some other way I can accomplish the same thing? Moreover, please note that I'm using 'p' and 'q' for two regex and then calling 'sub()' on both p and q. Can't I just do that by employing one RegEx and then calling sub() only once? Please enlighten me. Thanks in advance. From kyosohma at gmail.com Tue May 27 12:25:34 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 27 May 2008 09:25:34 -0700 (PDT) Subject: datetime.stdptime help References: Message-ID: <871e60df-fbf7-4fe5-ba45-d409e577f933@2g2000hsn.googlegroups.com> On May 27, 10:34?am, Laszlo Nagy wrote: > ? ? ? ? ? ? def str2datetime(s): > ? ? ? ? ? ? ? ? #28 May 2008 12:38:16 BDT > ? ? ? ? ? ? ? ? return time.strptime(s,"%d %b %Y %H:%M:%S %Z") > > ? ? ? ? ? ? #.... some code here.... > ? ? ? ? ? ? print repr(pd) > ? ? ? ? ? ? print str2datetime(pd) > > Result: > > '24 May 2008 12:38:16 BDT' > Traceback (most recent call last): > ? File "__init__.py", line 40, in > ? ? print ssc.get_order_data('202-9810306-3236320') > ? File > "/usr/local/www/vhosts/zeusd1/fantasy/controller/sites/ControllerBase.py", > line 306, in get_order_data > ? ? print str2datetime(pd) > ? File > "/usr/local/www/vhosts/zeusd1/fantasy/controller/sites/ControllerBase.py", > line 299, in str2datetime > ? ? return time.strptime(s,"%d %b %Y %H:%M:%S %Z") > ? File "/usr/local/lib/python2.5/_strptime.py", line 331, in strptime > ? ? (data_string, format)) > ValueError: time data did not match format: ?data=24 May 2008 12:38:16 > BDT ?fmt=%d %b %Y %H:%M:%S %Z > > I think that the format is correct. What am I doing wrong? > > Thanks, > > ? ?Laszlo I tried taking out components until I got it to work. It seems to be choking on the time zone part of it. If you remove the "BDT" from your string and the "%Z" from your formatter, it works. Unfortunately, I do not know why it doesn't work the other way. Mike From python at bdurham.com Tue May 6 17:43:16 2008 From: python at bdurham.com (python at bdurham.com) Date: Tue, 06 May 2008 17:43:16 -0400 Subject: Generate labels for a multi-level outline Message-ID: <1210110196.17982.1251761433@webmail.messagingengine.com> I need to generate multi-level incrementing labels for an outline/hierarchy where the string for each level of a label is based on an incrementing sequence like 1, 2, 3 or A, B, C, or even I, II, III. For simplicity, assume that each level's label segment is separated by a period ("."). I will pass an integer level (1 ... N) to this function/object so that level specific counters get reset when the level changes. I will use this function/object to generate output like: Label Level I. 1 I.A. 2 I.B. 2 I.C. 2 I.D. 2 I.D.1. 3 I.D.2. 3 I.D.3. 3 I.E. 2 II. 1 Is there a pre-built class for generating label sequences like this? (I'm not sure what I would use as search terms to google for such a class). While this sounds like a simple/fun class to write, I think it could quickly get complicated when one factors in parsing rules for each level's label type, separators, and error checking. If there's an existing, road tested class (with unit tests) that does this, I would rather avoid re-inventing/re-testing the wheel. Thanks, Malcolm From kamhung.soh at gmail.com Thu May 15 00:37:49 2008 From: kamhung.soh at gmail.com (Kam-Hung Soh) Date: Thu, 15 May 2008 14:37:49 +1000 Subject: Accepting text input References: <72QVj.262833$pM4.115744@pd7urf1no> <84QVj.133083$rd2.94188@pd7urf3no> Message-ID: On Thu, 15 May 2008 12:36:29 +1000, Collin wrote: > Kam-Hung Soh wrote: >> On Wed, 14 May 2008 11:02:36 +1000, Collin wrote: >> >>> Gabriel Genellina wrote: >>>> En Mon, 12 May 2008 01:54:28 -0300, Collin >>>> escribi?: >>>> >>>>> Collin wrote: >>>>>> I'm pretty new to Python, but this has really bugged me. I can't >>>>>> find a >>>>>> way around it. >>>>>> >>>>>> >>>>>> The problem is that, when I use raw_input("sajfasjdf") whatever, or >>>>>> input("dsjfadsjfa"), you can only have numerical values as answers. >>>>>> >>>>>> Any help would be appreciated. Thanks. >>>>> >>>>> Oh, wow. I feel so stupid. Please disregard this message. <_< >>>> No need to apologize... >>>> >>>>> I read the error message just now a bit more carefully, and I tried >>>>> something. I tried defining "yes" as some random numerical value. >>>>> Then >>>>> when I did: >>>>> (example code) >>>>> >>>>> yes = 123123983 #some number >>>>> test = input("Test test test ") >>>>> if test == yes: >>>>> print "It worked." >>>>> else: >>>>> print "failed" >>>>> >>>>> (example code off) >>>> The usual way for Python<3.0 is: >>>> answer = raw_input("Test test test ").lower() >>>> if answer == "yes": >>>> ... >>>> The input() function evaluates user input as an expression: if he >>>> types 2+5 the input() function returns the integer 7. I would never >>>> use input() in a program - it's way too unsafe; use always raw_input >>>> instead. >>>> >>> >>> If I use it like that, do I have to import anything to have the >>> .lower() work? And if I do, what does the .lower() signify? >>> -- http://mail.python.org/mailman/listinfo/python-list >>> >> You don't need to import any module to use ".lower()"; it is a method >> of a string. raw_input() returns a string, so you can use methods of a >> string. >> Try the following statement to see what happens: >> "ABCDE".lower() >> > > So the .lower() string method is just to convert the string to lowercase > letters so that you don't have to type a bunch of if - then statements > in both cases, I'm assuming? > -- > http://mail.python.org/mailman/listinfo/python-list > That's right. If you normalize your input to all lower case or upper case, you make it easier to process user input. Regards, -- Kam-Hung Soh Software Salariman From metallourlante at gmail.com Sat May 17 07:08:56 2008 From: metallourlante at gmail.com (Alex) Date: Sat, 17 May 2008 04:08:56 -0700 (PDT) Subject: Help on thread pool Message-ID: <323a8e66-7cc0-4d1f-9d7a-fc70f0c0a442@56g2000hsm.googlegroups.com> Hi all. In order to understand the concept of threading pool in python I'm working on a simple single-site web crawler. I would like to stop the program when the threading pool have downloaded all internal links from a web site, but now my program keep waiting forever even if there are no more links to download. Here's my code, I appreciate any comments, I'm programming just for fun and learning ;-) Thanks in advance. from BeautifulSoup import BeautifulSoup import urllib from pprint import pprint import string from urlparse import urlparse import sys from threading import Thread import time from Queue import Queue #dirty hack: set default encoding to utf-8 reload(sys) sys.setdefaultencoding('utf-8') opener = urllib.FancyURLopener({}) class Crawler: def __init__(self): """ Constructor """ self.missed = 0 self.url_list = [] self.urls_queue = Queue() self.num_threads = 5 self._create_threads() def get_internal_links(self,url): """ Get all internal links from a web page and feed the queue """ self.url = url url_netloc = urlparse(self.url).netloc print "Downloading... ", self.url time.sleep(5) try: p = opener.open(self.url) #print p.info() except IOError: print "error connecting to ", self.url print "wait..." time.sleep(5) print "retry..." try: p = urllib.urlopen(self.url) except IOError: self.missed = self.missed + 1 return None html = p.read() soup = BeautifulSoup(html) anchors = soup.findAll('a') links = [ str(anchor['href']) for anchor in anchors] internal_links = [link for link in links if (urlparse(link).netloc == url_netloc)] for link in internal_links: if link not in self.url_list and link != self.url: self.url_list.append(link) self.urls_queue.put(link) print "Queue size: ", self.urls_queue.qsize() print "List size: ", str(len(self.url_list)) print "Errors: ", str(self.missed) self._queue_consumer() def _queue_consumer(self): """ Consume the queue """ while True: url = self.urls_queue.get() print 'Next url: ', url self.get_internal_links(url) self.urls_queue.task_done() def _create_threads(self): """ Set up some threads to fetch pages """ for i in range(self.num_threads): worker = Thread(target=self._queue_consumer, args=()) worker.setDaemon(True) worker.start() #----------------------------------------------------------------------------- # if __name__ == '__main__': c = Crawler() c.get_internal_links('http://www.thinkpragmatic.net/') From dmitrey.kroshko at scipy.org Sun May 18 14:55:33 2008 From: dmitrey.kroshko at scipy.org (dmitrey) Date: Sun, 18 May 2008 11:55:33 -0700 (PDT) Subject: howto use pylint from Eric IDE? References: Message-ID: <6f8d242c-d7e6-4082-9cb2-e2f719a1a6dc@y21g2000hsf.googlegroups.com> Since I have no project (and willing to create the one), just several py-files, the Project->Check button is disabled. Are there any other methods in v4.1.1 or more recent? Thx, D. On 18 ???, 16:48, Detlev Offenbach wrote: > dmitrey wrote: > > Hi all, > > > I have Eric 4.1.1, pylint and Eric pylint plugin installed, but I > > cannot find how to use pylint from Eric IDE GUI. > > Does anyone know? > > > Thank you in advance, D. > > Project->Check->Run PyLint > > Regards, > Detlev > -- > Detlev Offenbach > det... at die-offenbachs.de From wuwei23 at gmail.com Mon May 26 06:47:36 2008 From: wuwei23 at gmail.com (alex23) Date: Mon, 26 May 2008 03:47:36 -0700 (PDT) Subject: Why Turn "Print" into "Print()"???? References: <248a2c45-caae-49bb-b8ff-701af8b86207@p25g2000hsf.googlegroups.com> Message-ID: On May 26, 7:21 pm, Prisoner at War wrote: > But I'd read that Python 3 is very different in many important ways. > I read it right there on the Py3K site! I can't make sense of how, > why, even what, exactly, but that's not a misimpression on my part, I > certain nonetheless...it's not just cosmetic changes but important > ones pertaining to a sort of "linguistic logic" I gather.... Well, let's see what Guido says about the issue: Q. I want to learn Python. Should I learn Python 2.6 or Python 3.0? A. Definitely learn Python 2.x (the latest version out is 2.5). I expect it'll be two years before you'll need to learn Python 3.0, and the differences aren't that great from a beginner's perspective: most of what you'll learn about 2.x will still hold about 3.0. (from http://www.artima.com/weblogs/viewpost.jsp?thread=211200) From castironpi at gmail.com Sat May 17 23:55:19 2008 From: castironpi at gmail.com (castironpi) Date: Sat, 17 May 2008 20:55:19 -0700 (PDT) Subject: morning in Python References: <409ea9f1-9774-4bf2-abac-2daf997bc97f@c65g2000hsa.googlegroups.com> <143b1593-658c-4a1c-9826-72af517b3ad0@m36g2000hse.googlegroups.com> <91d4cf3b-e71f-4e73-90da-db0735f34035@c65g2000hsa.googlegroups.com> Message-ID: <4a0aa0fb-4c43-4690-b31d-83475357da22@z72g2000hsb.googlegroups.com> On May 17, 9:22?pm, castironpi wrote: > On May 17, 5:35?am, Ivan Illarionov wrote: > > > > > > > On Sat, 17 May 2008 02:57:08 -0700, castironpi wrote: > > > Full day later, I think it, to emphasize state, would prioritize > > > context. ?The reason for the huge ramble was, believe it or not, > > > namespace conflict... as though any other states around here might nose > > > in. ?And thanks to 'inhahe' for coming back with the question. ?...Which > > > would explain next move to 'prioritize context'. Context is a high > > > priority for people. > > > > I'm proposing to start on one on a computer. ?The first things a > > > computer 'knows' are the boot, keyboard, & mouse. ?Yet on another scale, > > > the first things it knows are BIOS, file system, and OS. ?On still > > > another, the only thing it knows are interruptions. ?Knowledge is > > > important to context. ?(The scales are ram on disk on, ram on disk off, > > > and ram off, which may tell of the currency they and their power are > > > bought with. ?Thence, we should be getting different values for lengths > > > of time.) > > > > (Furthermore, we're all on different longitudes -and- latitudes.) > > > > Context comes from motion, perception, and composite perception > > > (reperception e.a.o. memory). ?There is some reason to believe that > > > motion and sight are different senses, perhaps so with stationary sound > > > (gatcha) and mobile sound too. ?Do you go deaf of a tone after prolonged > > > duration? ?That makes computers valuable commodities*: they have a > > > symbolic interface, which no other unlive objects have. ?They have both > > > mouse and keyboard. > > > > *I'm sure there is a precision to wants: what magnitude of what types of > > > action a person wants from a day and for a time-- what energy states > > > they go to and from (note phone on come to and come from.) > > > > Therefore, context should originate in mouse and keyboard. > > > > Humans have symbolic know-how: knowledge of how to convey intent > > > digitally, though it may be there is no interpolation of 'intent per > > > mouse-or-key', even though people are prone to empathize with faces. > > > However, if you start with a 'me' and a 'no', you can get pretty > > > logical. > > > > Intent per mouse-and-key isn't necessarily scalar, three-dimensional, or > > > rationally dimensional (?), though they do have magnitudes per mass and > > > volume. ?The contingent of 'rationally dimensional' is having or > > > beknowing/benouncing an orthonormal basis. ?Incidentally, '''orthography > > > of a language specifies the correct way of using a specific writing > > > system to write the language. .. Orthography is derived from Greek ????? > > > orth?s ("correct") and ??????? gr?phein ("to write").''' - wikipedia. > > > > Further incidentally, context and state may have more important in > > > common than priority and price: privacy and safety are involved ex > > > hypothesi. ?Incidentally = ... > > > > It is not clear that the first (cheapest best) human-computer language > > > is a computer language, though if two were orthonormal in comparison to > > > life, Python's fine. ?Not my first. > > > > In privacy concerns, it is not clear that duals aren't primitives to > > > humans. ?What's a brain primitive? ?Lol: what is a primitive brain? > > > > On May 16, 10:58?am, "inhahe" wrote: > > >> I'm not an expert in this but what does it mean to emphasize state? ?It > > >> seems the opposite of that would be a) functional programming, and b) > > >> passing parameters instead of using global or relatively local > > >> variables. And maybe c) coroutines (generators as implemented in > > >> Python), although perhaps coroutines could be said to emphasize state > > >> inasmuch as they go out of their way to capture, objectify and reuse it > > >> (Stackless' microthreads, even moreso). ?And Python seems to be > > >> well-noted for implementing some functional programming methodology, > > >> and as for passing parameters it's just as object-oriented as the rest > > >> of them. > > > >> But as I said, I'm not an expert, so let me know if I've gone astray.. > > > >> > I have a proposition to ask you all: Python emphasizes state. ?Is it > > >> > true?- Hide quoted text - > > > >> - Show quoted text - > > > Castironpi, > > > I love you! You remind me of all the kittens and puuppies I had when I > > was a child. > > > I #define this. Hope your database could give us something funny again. > > > -- Ivan- Hide quoted text - > > > - Show quoted text - > > I have to talk about crossing threats. ?But talking about threads is > like talking, and people talk about food. ?What are some threats to be > scared of? ?What about threads to be thunder?- Hide quoted text - > > - Show quoted text - I have to question sincerity, which is disappointing for a night. Does anyone live in a city? From sajmikins at gmail.com Wed May 21 13:11:09 2008 From: sajmikins at gmail.com (Simon Forman) Date: Wed, 21 May 2008 10:11:09 -0700 (PDT) Subject: Misuse of list comprehensions? References: <038e4418$0$27258$c3e8da3@news.astraweb.com> <6359d72c-f937-46cd-b1ce-b7450671b714@i76g2000hsf.googlegroups.com> <5fb0bcfd-0ce0-46cb-b273-7071c7694366@x35g2000hsb.googlegroups.com> <490e72b3-e73b-4047-be64-9880b73a958e@u12g2000prd.googlegroups.com> <48340938$0$10773$426a74cc@news.free.fr> Message-ID: On May 21, 4:36 am, Bruno Desthuilliers wrote: > Simon Forman a ?crit : > > > > > On May 20, 8:58 am, Paul McGuire wrote: > >> On May 20, 10:50 am, s0s... at gmail.com wrote: > > >>> You don't need all those conditionals. A set differs from a list > >>> precisely in the fact that each element is unique. And since the > >>> function is expecting "s" to be an iterable object, it can be > >>> constructed even without a for loop: > >>> def compress(s): > >>> return list(set(s)) > >>> That does the trick. > >> Only if order does not need to be maintained. list(set(s)) will not > >> necessarily keep the unique characters in the order they are seen. > >> We'll have to check with the OP to see if this is important (I just > >> assumed that it was because of the use of list comps). > > >> -- Paul > > > If order is important, you can use sorted() instead of list() like so: > > > def compress(s): > > new = sorted(set(s), key=s.index) > > return return ''.join(new) > > This won't still preserve the *original* order. I don't understand. new will contain each unique item in s, sorted in order of the items' first occurance in s, right? There are other ways to do it (other functions that could be passed to sorted() as the key arg) of course, but this seems like a good value of "original order", no? :) Regards, ~S From marco at sferacarta.com Thu May 8 11:51:17 2008 From: marco at sferacarta.com (Marco Mariani) Date: Thu, 08 May 2008 17:51:17 +0200 Subject: How to kill Python interpreter from the command line? In-Reply-To: <10fdb79d-8ac2-4bf3-bbdc-a825ae2c44c8@l42g2000hsc.googlegroups.com> References: <10fdb79d-8ac2-4bf3-bbdc-a825ae2c44c8@l42g2000hsc.googlegroups.com> Message-ID: <_jFUj.36624$o06.17318@tornado.fastwebnet.it> spectrumdt at gmail.com wrote: > The default way of killing the current process on the command line is > Ctrl+C, but that doesn't work with Python. It should work. Do you have a bare except: which intercepts SystemExit as well? If so, be as specific as possible in what you intercept, or at least catch StandardError: In [1]: StandardError ? Type: type Base Class: String Form: Namespace: Python builtin Docstring: Base class for all standard Python exceptions that do not represent interpreter exiting. From castironpi at gmail.com Wed May 14 13:54:40 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 14 May 2008 10:54:40 -0700 (PDT) Subject: Python and Flaming Thunder References: <6908kuF2ud4e1U1@mid.uni-berlin.de> Message-ID: <72a187b2-503e-452c-bae7-c660ae7e8ad2@x35g2000hsb.googlegroups.com> On May 14, 8:43?am, "Diez B. Roggisch" wrote: > >>> That's also a myth. ?For example, if C is easy to maintain, why is > >>> Flaming Thunder the only single-asset 8-by-8 shotgun cross compiler in > >>> the world? ?There should be lots of single-asset 8-by-8 shotgun cross > >>> compilers written in C, if C is easier to maintain. > >>Not only is it the world's only "single-asset 8-by-8 shotgun cross > >>compiler," but according to google, it's also the world's only "shotgun > >>cross compiler" period. ?But I guess if you make up your own terminology > >>you're bound to be unique. ?:) ?Do you mind if I ask: what exactly is a > >>single-asset 8x8 shotgun cross compiler, and what makes that of any > >>value to me? > > > The web page explains. ?It's a compiler that runs on 8 platforms and can > > generate executables for any of them on any of them. ?It's not _totally_ > > clear about what "single-asset" means, but it gives the impression (and > > the term somewhat suggests) that this means there's a single executable > > that does all of this (compare to gcc's design, where support for cross > > compiling to another arch is provided by a separate executable). > > Which isn't too hard if all you have are simple datatypes as a handfull > numerical types + strings. > > Besides, from what I see, the supported platforms all are x86, 32bit & > 64bit. And I bet GCC works pretty unmodified amongst these as well - only > binary formats differ. But let Flaming Thunder grow a library system with > dynamic loading, and I wonder how well his crosscompiler works.. > > Diez- Hide quoted text - > > - Show quoted text - 8x8 is pretty easy to aim for. Turn on 16x16, and you're the laptop to stand on. FxF? From Lie.1296 at gmail.com Wed May 21 14:23:58 2008 From: Lie.1296 at gmail.com (Lie) Date: Wed, 21 May 2008 11:23:58 -0700 (PDT) Subject: conventions/requirements for 'is' vs '==', 'not vs '!=', etc References: Message-ID: On May 20, 2:39?am, destroooooy wrote: > I'm wondering what is the canonical usage of the keywords 'is' and > 'not' when you're writing conditionals and loops. The one I've been > following is completely arbitrary--I use the symbols '==', '!=' for > numerical comparisons and the words 'is', 'not' for everything else. > > Thanks in advance! If we're talking in English, it would be like this: There is a person with a black hair called A There is another person with a black hair called B A has a nickname C All of these statements are true: A.haircolor == B.haircolor A is C but this is NOT true: A is B # is False and this is debatable: A == B whether A is similar enough to B so that they can be said to be equal is debatable and depends on the purpose of the comparison (which is why equality comparison is overridable while identity comparison is not). From alefnula at gmail.com Fri May 9 09:35:45 2008 From: alefnula at gmail.com (Viktor) Date: Fri, 9 May 2008 06:35:45 -0700 (PDT) Subject: Function creation (what happened?) References: <199c06d7-601c-49f3-a88c-c28f7283e619@25g2000hsx.googlegroups.com> <50ea9d09-a315-4342-aaac-f5d8e5c5da15@x41g2000hsb.googlegroups.com> Message-ID: <13f84fe5-e60e-493e-9301-ed178344f6e5@26g2000hsk.googlegroups.com> I figured out the first two solutions, but the third looks like the most cleaner, think I'll use that one... Thank you everyone. :) On May 9, 3:24 pm, George Sakkis wrote: > The decorator does receive the correct function. The problem is that > at this point __init__ is still a plain function, not a method, i.e. > the sequence is: > function -> decorated function -> method > > There are several workarounds if you really want to differentiate > between functions and methods, none of them perfect: > > - Apply the decorator after the class has been built, i.e. after the > functions have been wrapped in (unbound) methods: > A.__init__ = w(A.__init__) > > - (Risky Hack): Guess whether a function is intended to be wrapped in > a method by checking whether its first argument is named "self". > Obviously this is not foolproof and it doesn't work for static/class > methods. > > - Have two different decorators, one intended for plain functions and > one for functions-to-be-methods (e.g. @deco, @decomethod). > > George From bruno.42.desthuilliers at websiteburo.invalid Fri May 9 04:52:22 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 09 May 2008 10:52:22 +0200 Subject: python newbie: some surprises In-Reply-To: References: <67b60370-bed9-4f43-b401-25ce2fd89522@t54g2000hsg.googlegroups.com> <64fb7f0f-c8fa-4324-8a13-f4e99082c470@p25g2000hsf.googlegroups.com> Message-ID: <482410c6$0$5108$426a34cc@news.free.fr> Yves Dorfsman a ?crit : (snip) > I see the point of the OP. Couldn't the new-line be used as an > equivalent of ':', Technically, yes. OTHO, the ':' helps editors doing proper indentation. From znfmail-pythonlang at yahoo.com Wed May 14 11:30:19 2008 From: znfmail-pythonlang at yahoo.com (Poppy) Date: Wed, 14 May 2008 11:30:19 -0400 Subject: working with images (PIL ?) Message-ID: I need to write a program to examine images (JPG) and determine how much area is whitespace. We need to throw a returned image out if too much of it is whitespace from the dataset we're working with. I've been examining the Python Image Library and can not determine if it offers the needed functionality. Does anyone have suggestions of other image libraries I should be looking at it, or if PIL can do what I need? From scott.hafeman at rogers.com Fri May 23 13:14:05 2008 From: scott.hafeman at rogers.com (scott.hafeman at rogers.com) Date: Fri, 23 May 2008 10:14:05 -0700 (PDT) Subject: Shell-independent *nix setup script References: Message-ID: <5c476ba7-1189-465f-b964-61790da9d0e4@w4g2000prd.googlegroups.com> On May 22, 5:29?pm, brad wrote: > scott.hafe... at rogers.com wrote: > > Hi, > > Is it worthwhile maintaining a production application setup script in > > Python as opposed to shell-script? ? > > I do not think so. Perhaps 'in conjunction with', but not 'opposed > to'... sh is the lowest common denominator of shells. Script for sh and > your script will run on most any Unix. Python is gaining acceptance, but > is still not present everywhere by default... Solaris for example. If we consider the approach 'in conjunction with', is the following adequately robust? $ source app_setup.sh #File: app_setup.sh # -. shell-script .- # Assume we can figure out some basic version of a python interpreter: # standalone executable # embedded within another application, providing basic libpython.a features # $PYTHON sniffEnvWithComplexLogic.py 'shCompatibleEnvSettings.txt' source shCompatibleEnvSettings.txt From eduardo.padoan at gmail.com Fri May 16 18:38:52 2008 From: eduardo.padoan at gmail.com (Eduardo O. Padoan) Date: Fri, 16 May 2008 19:38:52 -0300 Subject: can't delete from a dictionary in a loop In-Reply-To: <482DFF63.7020701@islandtraining.com> References: <482DFF63.7020701@islandtraining.com> Message-ID: On Fri, May 16, 2008 at 6:40 PM, Gary Herron wrote: > bruno.desthuilliers at gmail.com wrote: >> >> On 16 mai, 23:28, Hans Nowak wrote: >> >>> >>> Dan Upton wrote: >>> >>>> >>>> for pid in procs_dict: >>>> if procs_dict[pid].poll() != None >>>> # do the counter updates >>>> del procs_dict[pid] >>>> The problem: >>>> RuntimeError: dictionary changed size during iteration >>>> >>> >>> I don't know if the setup with the pids in a dictionary is the best way >>> to >>> manage a pool of processes... I'll leave it others, presumably more >>> knowledgable, to comment on that. :-) But I can tell you how to solve >>> the >>> immediate problem: >>> >>> for pid in procs_dict.keys(): >>> > > No, keys() produces a list (which is what is wanted here). > It's iterkeys() that produces an iterator which would reproduce the OP's > problem. > > And then, in Python3, keys() produces something else altogether (call a view > of the dictionary) which would provoke the same problem, so yet another > solution would have to be found then. In Python 3.0, list(procs_dict.keys()) would have the same effect. > Gary Herron > >> >> I'm afraid this will do the same exact thing. A for loop on a dict >> iterates over the dict keys, so both statements are strictly >> equivalent from a practical POV. >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Eduardo de Oliveira Padoan http://www.advogato.org/person/eopadoan/ http://twitter.com/edcrypt Bookmarks: http://del.icio.us/edcrypt From squareswallower at 1ya2hoo3.net Wed May 7 21:02:12 2008 From: squareswallower at 1ya2hoo3.net (dave) Date: Wed, 7 May 2008 19:02:12 -0600 Subject: anagram finder / dict mapping question Message-ID: Hi All, I wrote a program that takes a string sequence and finds all the words inside a text file (one word per line) and prints them: def anagfind(letters): #find anagrams of these letters fin = open('text.txt') #one word per line file wordbox = [] #this is where the words will go for line in fin: word = line.strip() count = 0 for char in letters: if char not in word: break else: count += 1 if count == len(word): wordbox.append(word) return wordbox Now I'd like to modify the code to naturally find all anagrams inside a wordlist. What would be the best way to do this? Using Hints? Is it possible to iterate over dict keys? How can I make a dict that maps from a set of letters to a list of words that are spelled from those letters? Wouldn't I need to make the set of letters a key in a dict? As always - Thanks for helping someone trying to learn... Dave From max at alcyone.com Fri May 2 14:32:01 2008 From: max at alcyone.com (Erik Max Francis) Date: Fri, 02 May 2008 11:32:01 -0700 Subject: Do you know of a much simpler way of writing a program that writes a program? In-Reply-To: References: Message-ID: mcse jung wrote: > Here is asample program that writes a program and then executes it. > Do you knowof a much simpler way of writing a program that writes a program? It looks like you have a program which is more printed text than program logic. In which case, the usual solution is to use a templating system, where most of the text is unmodified and you only set out the specific areas where you want to insert logic. EmPy is one: http://www.alcyone.com/software/empy/ -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis From castironpi at gmail.com Sun May 4 07:11:35 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 4 May 2008 04:11:35 -0700 (PDT) Subject: generator functions in another language References: <831bea0d-ef71-4ede-9065-3111bce5225e@c65g2000hsa.googlegroups.com> <684r62F2rmn3gU2@mid.uni-berlin.de> Message-ID: On May 4, 12:21?am, "Gabriel Genellina" wrote: > En Sun, 04 May 2008 01:08:34 -0300, Marc 'BlackJack' Rintsch escribi?: > > > On Sat, 03 May 2008 16:39:43 -0700, castironpi wrote: > > >> I'm actually curious if there's a way to write a generator function > >> (not a generator expression) in C, or what the simplest way to do it > >> is... besides link the Python run-time. > > > The reference implementation of Python is written in C, so obviously there > > must be a way to write something like generators in C. > > Yes and no. Generators are tied to frames, and frames execute Python code, not C. There is no simple way to write generators in C, but there are some generator-like examples in the itertools module. > See this threadhttp://groups.google.com/group/comp.lang.python/browse_thread/thread/... > > -- > Gabriel Genellina Gabriel, How did your attempt turn out from last May? At first look, it's outside the scope of Python, but it is not the scope of C necessarily. Generators offer a lot of simplicity (which I haven't read about extensively, but am starting to see) that could gain some reputation for Python. What is the midpoint at which C could meet Python? There is no such thing as a 'frame' per se in C; byte code is integral. As there is no such thing as suspended state without frames, and no such thing as generators without suspended state. It's a hard thing to Google for without knowing the prior terminology for the work that's already been done on them in C. What work is there? Are any devs interested in pursuing it? The frame implementation. http://svn.python.org/projects/python/trunk/Include/frameobject.h http://svn.python.org/projects/python/trunk/Objects/frameobject.c The generator code. http://svn.python.org/projects/python/trunk/Include/genobject.h http://svn.python.org/projects/python/trunk/Objects/genobject.c I used Microsoft's search engine (python frame generator site:svn.python.org , links 3 and 5) to find it. From hdante at gmail.com Fri May 30 10:36:50 2008 From: hdante at gmail.com (Henrique Dante de Almeida) Date: Fri, 30 May 2008 07:36:50 -0700 (PDT) Subject: definition of a highlevel language? References: <2759eed3-956d-45c7-8dfb-9557f74133b3@56g2000hsm.googlegroups.com> <26d0b3d2-01cc-49bd-b284-1a849b0b835f@y38g2000hsy.googlegroups.com> <34dcbdc1-5285-41ec-be06-c88c56bb0372@i76g2000hsf.googlegroups.com> <45f03028-a86c-4357-9aa2-0148f7cc84dc@d45g2000hsc.googlegroups.com> <80531$483b266d$3799@news.teranews.com> Message-ID: On May 26, 6:06?pm, Paul Miller wrote: > On Mon, 26 May 2008 15:49:33 -0400, Dan Upton wrote: > > On Mon, May 26, 2008 at 3:22 PM, ? wrote: > > I don't know if it would necessarily look like the CPython VM, except > > for the decode stage (this being said without any knowledge of the > > CPython implementation, but with more than I ever thought I'd know about > > processor architecture/microarchitecture) > > Out of curiosity, do you know how easy it would be to make a Python chip > using FPGAs? ?I have little to no hardware knowledge, but it sounds like > a fun project in any case. ?Even if it's not likely to have blazing > performance, it'd be cool to load Python bytecode directly into > memory. :-) > > -- > code.py: a blog about Python. ?http://pythonista.wordpress.com > ** Posted fromhttp://www.teranews.com** The python VM is too "high level". :-) I think a python CPU would need to be developed in two layers, one that looks like a typical processor and another that executes complex instructions (microcode ?). The low level part takes some weeks (one week or so if you have the whole architecture figured out) in VHDL. Once I claimed to have done this in an April Fool's day. It was fun. :-D From python-url at phaseit.net Mon May 19 13:49:51 2008 From: python-url at phaseit.net (Gabriel Genellina) Date: Mon, 19 May 2008 17:49:51 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (May 19) Message-ID: QOTW: "IIRC the idea was so that managers could write programs in English. It failed because nobody could write a parser that would handle something like 'The bottom line is that the stakeholder group requires the situation going forward to be such as to facilitate the variable known as x to provide the same outcome when stimulated by dereferencing as the variable known as y'." - John Machin http://groups.google.com/group/comp.lang.python/msg/aefcc0ca19f6d9b3, from his oral history of COBOL A problem with async_chat.push and why it works that way: http://mail.python.org/pipermail/python-list/2008-May/491027.html How to remove dictionary entries when iterating over it: http://mail.python.org/pipermail/python-list/2008-May/491739.html Classmethods: why do they exist, and its behavior compared with metaclass methods: http://mail.python.org/pipermail/python-list/2008-May/491280.html http://mail.python.org/pipermail/python-list/2008-May/491793.html Free PDFs of *Python Magazine* available: http://mail.python.org/pipermail/advocacy/2008-May/000587.html Two problems due to the "all objects are comparable by default" philosophy in Python 2.x: http://mail.python.org/pipermail/python-list/2008-May/491600.html http://mail.python.org/pipermail/python-list/2008-May/491388.html A hundred ways of writing the FizzBuzz test - and whether it is effective or not: http://mail.python.org/pipermail/python-list/2008-May/490584.html Why to learn Python if one doesn't have to: http://mail.python.org/pipermail/python-list/2008-May/490856.html How to create a restricted (safer) Python environment: http://mail.python.org/pipermail/python-list/2008-May/490705.html How to emulate the "indexed property" concept from Object Pascal: http://mail.python.org/pipermail/python-list/2008-May/491354.html ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. Just beginning with Python? This page is a great place to start: http://wiki.python.org/moin/BeginnersGuide/Programmers The Python Papers aims to publish "the efforts of Python enthusiats": http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the "Planet" sites: http://planetpython.org http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Many Python conferences around the world are in preparation. Watch this space for links to them. Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://www.python.org/dev/peps/pep-0042/ The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topic/python/ (requires subscription) http://groups-beta.google.com/groups?q=python-url+group:comp.lang.python*&start=0&scoring=d& http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". Write to the same address to unsubscribe. -- The Python-URL! Team-- Phaseit, Inc. (http://phaseit.net) is pleased to participate in and sponsor the "Python-URL!" project. Watch this space for upcoming news about posting archives. From mcknight0219 at gmail.com Mon May 12 03:25:25 2008 From: mcknight0219 at gmail.com (Jimmy) Date: Mon, 12 May 2008 00:25:25 -0700 (PDT) Subject: Problem with custom events in wxpython References: <4efa4dcf-7f3d-4c82-9177-1ee8b25d9e3d@b5g2000pri.googlegroups.com> Message-ID: <3ab21871-9ac0-489a-ad8a-7db2b9014700@u6g2000prc.googlegroups.com> On May 11, 11:27 pm, "Frank Niessink" wrote: > Hi Jimmy, > > 2008/5/11 Jimmy : > > > hi, all > > > I'm having a problem with creating custom events in wxpython. > > > I have a class A handling some data processing work and another class > > B of GUI matter. I need GUI to display information when data in A is > > updated. > > I know cutom events in wxpython may work. > > You may want to look at the pubsub module. Available as wx.lib.pubsub > in wxPython:http://www.wxpython.org/docs/api/wx.lib.pubsub-module.html, > and also available separately on PyPI:http://pypi.python.org/pypi/PyPubSub/ > > Cheers, Frank hi, thanks it works! however, it seems the message can not be exchanged between processes :( actually what I want to do is let a running process send data to GUI process and display it From arnodel at googlemail.com Tue May 20 14:38:48 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 20 May 2008 19:38:48 +0100 Subject: preserve history in the interactive python References: Message-ID: Nikhil writes: > Nikhil wrote: >> Hi, >> >> I am using python -i, and I find it hard typing/pasting the commands >> from the previous interactive shell. Basically, is there anyway that >> I can preserve the history in the shell? >> I guess but not sure there should be something like ~/.pyrc for >> configuring such but can someone please let me know what is the >> effective environment variable to preserve the history? >> >> Thanks, >> Nikhil > I figured it out. This below thing works fine for me. > BTW, I got it from http://docs.python.org/tut/node15.html. A little > search would not hurt ;-) Or you could use IPython (http://ipython.scipy.org/), "an Enhanced Python Shell". -- Arnaud From castironpi at gmail.com Wed May 7 20:22:31 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 7 May 2008 17:22:31 -0700 (PDT) Subject: slicing lists References: Message-ID: <8e6cc35c-a4a8-46ca-9bbb-798fb193f530@j22g2000hsf.googlegroups.com> On May 7, 6:58?pm, Ivan Illarionov wrote: > On Wed, 07 May 2008 23:46:33 +0000, Ivan Illarionov wrote: > > On Wed, 07 May 2008 23:29:27 +0000, Yves Dorfsman wrote: > > >> Is there a way to do: > >> x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] > >> x[0,2:6] > > >> That would return: > >> [0, 3, 4, 5, 6] > > > IMHO this notation is confusing. > > > What's wrong with: > > [0]+x[2:6] > > >> I am surprised this notation is not supported, it seems intuitive. A > >> concrete example of the sort of thing I want to do: > > >> p = file('/etc/passwd').readlines() > >> q = [ e.strip().split(':')[0,2:] for e in p ] > > >> (getting rid of the password / x field) > > > This works and is clearer: > > [[0] + e.strip().split(':')[2:] for e in open('/etc/passwd')] > > or maybe you wanted to do this: > > >>> [e.split(':')[0] for e in open('/etc/passwd')] > > ['root', 'daemon', 'bin', 'sys', 'sync', ...] > > What are you trying to get from /etc/passwd? > > -- > Ivan- Hide quoted text - > > - Show quoted text - The t. Oughtn't there be a run on Guido's name more often than is? You -could- write: x[ slice(0)+slice(2,6) ] where slice would be an 'autochaining' type under a syntax. Fine for slices, not for logic. x[ b1+And+b2+Or+b3 ] would also register as b1 and b2 or b3, which really quickly rises on the wheel again, er, um, crawls up the spout. Would you be happy with x[ '0,2:6' ], necessarily in quotes? With two punctuation marks you couldn't get much farther in money than Python does today. x[ '0 2:6' ] -> x.__getitem__( x, '0 2:6' ) -> '0 2:6'.split( ) -> x.__getslice__( x, slice( 0 ) ) ... + x.__getslice__( x, slice( 2, 6 ) ) However, it's not clear it's trivial to overwrite a built-in type's __getitem__! From marlin_rowley at hotmail.com Thu May 22 17:24:11 2008 From: marlin_rowley at hotmail.com (Marlin Rowley) Date: Thu, 22 May 2008 16:24:11 -0500 Subject: How do I make a copy of my class object? Message-ID: All: I have a class object which has the usual data members and functions. I'm trying to make a copy of this class (which includes wx.Bitmap objects) but deepcopy() doesn't seem to work. How would I do this? -M _________________________________________________________________ E-mail for the greater good. Join the i?m Initiative from Microsoft. http://im.live.com/Messenger/IM/Join/Default.aspx?source=EML_WL_ GreaterGood -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreas.tawn at ubisoft.com Thu May 15 12:33:21 2008 From: andreas.tawn at ubisoft.com (Andreas Tawn) Date: Thu, 15 May 2008 18:33:21 +0200 Subject: file open/read/name etc, not working In-Reply-To: References: Message-ID: <8AEDA5E3386EA742B8C24C95FF0C75800403F774@PDC-MAIL3.ubisoft.org> >import os > >print os.path.exists('C:/Python25/myPrograms/netflix/test.txt') >d=open('C:/Python25/myPrograms/netflix/flim.txt', 'r') >d.readline() > >returns true in the shell but prints no text even though the document >contains text. > >d.name returns nothing, d.name() raises an error. >-- >http://mail.python.org/mailman/listinfo/python-list Try... import os print os.path.exists('C:/Python25/myPrograms/netflix/test.txt') d=open('C:/Python25/myPrograms/netflix/flim.txt', 'r') for line in d: print line And I'm guessing that's a typo in flim.txt? Cheers, Drea From arnodel at googlemail.com Tue May 27 14:06:51 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 27 May 2008 19:06:51 +0100 Subject: Misuse of list comprehensions? References: <038e4418$0$27258$c3e8da3@news.astraweb.com> <69g2bpF31ttuuU1@mid.uni-berlin.de> <69g605F2v4102U2@mid.uni-berlin.de> <027e0b24$0$26906$c3e8da3@news.astraweb.com> Message-ID: "Ian Kelly" writes: > On Tue, May 20, 2008 at 11:19 AM, John Salerno wrote: >> "Diez B. Roggisch" wrote in message >> news:69g605F2v4102U2 at mid.uni-berlin.de... >>> After being corrected about missing the construction of a None-containing >>> list, one needs of course to think about the waste of resources, as a >>> possible result-list is created in any case. >> >> Yeah, I was already aware of the list of Nones, which is why I asked. Simply >> typing the list comprehension without an assignment just *looked* wrong, >> too. > > It sounds like the wasteful list creation is the biggest objection to > using a list comprehension. I'm curious what people think of this > alternative, which avoids populating the list by using a generator > expression instead (apart from the fact that this is still quadratic, > which I'm aware of). > > def compress(s): > new = [] > filter(None, (new.append(c) for c in s if c not in new)) > return ''.join(new) This is crazy! -- Arnaud From deets at nospam.web.de Fri May 16 08:26:05 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 16 May 2008 14:26:05 +0200 Subject: TPCServer and xdrlib In-Reply-To: <5d56b071-1184-4112-bd82-89c00975b939@m73g2000hsh.googlegroups.com> References: <5d56b071-1184-4112-bd82-89c00975b939@m73g2000hsh.googlegroups.com> Message-ID: <695crbF303jk4U1@mid.uni-berlin.de> > > Did you consider gzipping your XML (or YAML) packets ? Would the > transfer time be acceptable in this case ? That would add even more to the overhead of transcoding the transportlayer. Switching from XMLRPC to a json-based protocol reduced in a project of mine reduced the overhead 10-20fold - mainly because of reduced size and parsing efforts. Diez From ppearson at nowhere.invalid Thu May 1 16:54:08 2008 From: ppearson at nowhere.invalid (Peter Pearson) Date: Thu, 01 May 2008 15:54:08 -0500 Subject: Getting started with pyvtk Message-ID: I'm trying to get started with pyvtk, the Python interface to the Visualization Toolkit, but there's obviously something important that I haven't figured out after an embarrassingly long morning of googling around. When I run sample pyvtk code (example1.py, from http://cens.ioc.ee/cgi-bin/viewcvs.cgi/python/pyvtk/examples/example1.py), nothing graphical happens, but some text files appear named example1.vtk and example1b.vtk. Guessing that I need to feed one of these to vtk, I tried "vtk spamcop, invalid->net. From pavlovevidence at gmail.com Thu May 22 00:22:29 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 21 May 2008 21:22:29 -0700 (PDT) Subject: Bug in floating-point addition: is anyone else seeing this? References: <8187c3b6-a772-456f-a54f-0af7babb353e@w34g2000prm.googlegroups.com> <399b9f4e-3e36-40a5-bf02-ab2b25c1f4ef@d1g2000hsg.googlegroups.com> Message-ID: <39a12039-bfc9-4587-81ab-eb070cd51133@t54g2000hsg.googlegroups.com> On May 21, 11:27 pm, Dave Parker wrote: > On May 21, 7:01 pm, Carl Banks wrote: > > > The crucial thing is not to slow down the calculations with useless > > bells and whistles. > > Are you running your simulations on a system that does or does not > support the "useless bell and whistle" of correct rounding? If not, > how do you prevent regression towards 0? The "useless bell and whistle" is switching to multiprecision. I'm not sure whether our hardware has a rounding bias or not but I doubt it would matter if it did. > For example, one of the things that caused the PS3 to be in 3rd place > behind the Wii and XBox 360 is that to save a cycle or two, the PS3 > cell core does not support rounding of single precision results -- it > truncates them towards 0. That led to horrible single-pixel errors in > the early demos I saw, which in term helped contribute to game release > delays, which has turned into a major disappointment for Sony. And you believe that automatically detecting rounding errors and switching to multi-precision in software would have saved Sony all this? Carl Banks From aisaac at american.edu Thu May 29 18:54:41 2008 From: aisaac at american.edu (Alan Isaac) Date: Thu, 29 May 2008 22:54:41 GMT Subject: code of a function In-Reply-To: References: <8a6035a00805290110v67ed53d0j8ae9c93b3089565c@mail.gmail.com> <483E6B8D.6020307@islandtraining.com> Message-ID: Anand Patil wrote: > If you're using IPython, you can do svd?? . http://www.scipy.org/doc/numpy_api_docs/numpy.linalg.linalg.html hth, Alan Isaac From danb_83 at yahoo.com Tue May 27 19:04:55 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Tue, 27 May 2008 16:04:55 -0700 (PDT) Subject: Hungarian Notation References: Message-ID: <4686e9a0-32bd-4fe6-88b3-bc449bf23206@2g2000hsn.googlegroups.com> On May 27, 12:28?am, "inhahe" wrote: > Does anybody know of a list for canonical prefixes to use for hungarian > notation in Python? ?Not that I plan to name all my variables with hungarian > notation, but just for when it's appropriate. pnWe vUse adjHungarian nNotation prepAt nWork, conjAnd pnI vauxDont vLike pnIt advVery advMuch. conjSo pnI vAvoid pnIt prepIn nPython. From arnodel at googlemail.com Tue May 27 03:00:54 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 27 May 2008 08:00:54 +0100 Subject: set partition question References: <4839c866$0$32633$9b622d9e@news.freenet.de> <3b08539b-d4ba-4616-86df-529fceeeef01@q24g2000prf.googlegroups.com> <98b0a07f-0444-4814-a7a6-6a0a049068a3@w5g2000prd.googlegroups.com> Message-ID: pball.benetech at gmail.com writes: > I used Arnaud's suggestion with a few minor tweaks, as follows: > > #----- > fset = frozenset > s0 = fset([1]) > s1 = fset([1,2]) > s2 = fset([2]) > > # let S be the set of all your sets except s0 (i.e. s1, s2, s3, ...) > S = set([s1,s2]) > > # X is the "domain", C is the set of complements in X of elements of > S > X = set() > for s in S: > X |= s > print "s0 is ", s0 > print "S is ", S > print "X is ", X > > C = set(fset(X - s) for s in S if fset(X-s)) > print "C is ", C > > # Find the "fibers" at each element x of s0. > # A fiber at x is the set of all s in S or C that contain x > from collections import defaultdict > fibers = defaultdict(list) > for s in S | C: > for x in s & s0: > fibers[x].append(s) > print "fibers are ", fibers > > # Find the "seeds" at each x in s0. > # A seed at x is the set of all elements contained in all s in the > fiber at x. > # Intutively, a seed at x is the smallest set containing x that can > be > # built from S > seeds = set() > for F in fibers.itervalues(): > seeds &= set(F) Change this to: seeds = [] for F in fibers.itervalues(): seed = X for f in F: seed &= f seeds.append(seed) And the whole thing should work HTH > print 'seeds are ', seeds > > # Now we know if there is a solution: > sol = set() > for s in seeds: > sol |= s > if sol != s0: > print "No solution" > else: > print "Solution: union(intersection(fibers[x]) for x in s0)" > #----- > > yields this: > > s0 is frozenset([1]) > S is set([frozenset([1, 2]), frozenset([2])]) > X is set([1, 2]) > C is set([frozenset([1])]) > fibers are defaultdict(, {1: [frozenset([1, 2]), > frozenset([1])]}) > seeds are set([]) > No solution > > > I follow your logic up to the point of the "seeds," where I get a bit > confused. Thanks much! for the idea, I'm going to keep thinking about > it. Any other ideas are *most* welcome. -- PB. -- Arnaud From torriem at gmail.com Thu May 1 12:49:41 2008 From: torriem at gmail.com (Michael Torrie) Date: Thu, 01 May 2008 10:49:41 -0600 Subject: Zope/DTML Infuriating... In-Reply-To: <65492d56-de86-4979-a886-b4e6f9b3b42f@2g2000hsn.googlegroups.com> References: <65492d56-de86-4979-a886-b4e6f9b3b42f@2g2000hsn.googlegroups.com> Message-ID: <4819F4A5.4010302@gmail.com> Jens wrote: > - Why is it, when primitive data types seem to be objects (similar to > javascript), that type casting is done through build-in functions > rather than methods, e.g. String.toInt('5') or '5'.toInt() or x = > Integer.fromString('5'). Mainly because it's much cleaner to do it the python way (absolutely explicit), and just as clear or clearer what you are intending to do. Digging a little deeper, you'll find that the built-in function "str," for example, actually calls object.__str__(). This is nice because it allows any object class to define that method and have it work with str() in a manner consistent across python. It preserves some amount of uniformity. The second example, x = Integer.fromString('5') demonstrates a huge weakness in Java. In python, rather than asking an integer object to convert from a limited selection of other objects, python works the other way, asking objects to convert themselves to integers (if they can). We don't worry about the size of integers, since python's integers are auto-sizing. So any object that implements the __int__() method can be used with the classic "int()" built-in function. The same goes for __float__ and float(). Little things like this really make me happy about how python does things generally. I think much of how Java works with Integer and String (as you describe above) is because Java has primitive types (which aren't objects at all) and then boxed objects around the primitive types. Python eliminates this idea, and makes everything, even "simple" types objects. Now sure python could just say always call the "int()" or "float()" or "str()" method on objects to produce those respective conversions. But using a combination of a built-in language function and a specialized, reserved class method name, allows a lot of flexibility without infringing on the programmer's need to use method names like "int, float, or str" if he or she so desired. From mattheww at chiark.greenend.org.uk Wed May 14 12:58:41 2008 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 14 May 2008 17:58:41 +0100 (BST) Subject: Purpose of operator package References: Message-ID: I V wrote: > I hadn't heard of operator.truth before. Does it do anything different > from bool(x) ? Not really. It was occasionally useful before the bool type existed; now it's just a leftover. -M- From anna.k.lawrence at baesystems.com Fri May 9 14:33:31 2008 From: anna.k.lawrence at baesystems.com (Lawrence, Anna K (US SSA)) Date: Fri, 9 May 2008 11:33:31 -0700 Subject: Not able to get utf8 encoded string into a document Message-ID: <4AE25A7D8CBE4E4DA8E87173237DE27E258C51@blums0042.bluelnk.net> Hi all, This is my first post and I'm really at a loss for how to fix my problem, so I really hope someone can help me out. I am working on a web application using Pylons .0.9.6, SQLAlchemy 0.4.4, MySQLdb 1.2.2 and Python 2.4.4. We want to use utf8 encoding throughout and as far as I can see everything is set properly between components and I've got a sitecustomize.py in my site-packages directory of python set to utf8 as well. Everything is stored properly in the database and displays nicely in the app. However, when I try to take a string that is coming out of the database and export it to a Word document, no amount of encoding/decoding will make the Word doc display properly. Since I'm on a Windows machine, my default locale is cp437. Is this the reason? Is there something that needs to be set that I'm missing? Any help would be greatly appreciated. Thanks, Anna -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at v.loewis.de Fri May 23 13:38:07 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 23 May 2008 19:38:07 +0200 Subject: array of 64-bit ints? In-Reply-To: References: Message-ID: <483700FF.1020704@v.loewis.de> > Is it possible to have an array of 64-bit-ints using the standard Python > array module? On my 64-bit architecture (AMD64, MSVC), both "int" and > "long int" are 32 bit integers. To declare 64-bit ints, one needs either > "long long int" or "size_t". However, according to the Python array > documentation, arrays of "size_t" or "long long int" are not available. No, it's not possible. Regards, Martin From deets at nospam.web.de Fri May 23 06:50:42 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 23 May 2008 12:50:42 +0200 Subject: can python do some kernel stuff? In-Reply-To: <4836994e$0$11625$607ed4bc@cv.net> References: <983ec0f6-1316-40cd-a4d4-ce9b5e272a60@h1g2000prh.googlegroups.com> <48366cfa$0$15168$607ed4bc@cv.net> <28c432f0-657c-4272-8cd4-a9081b013279@w5g2000prd.googlegroups.com> <69nigsF3499pqU2@mid.uni-berlin.de> <4836994e$0$11625$607ed4bc@cv.net> Message-ID: <69nls3F344g2cU1@mid.uni-berlin.de> Andrew Lee schrieb: > Diez B. Roggisch wrote: >> Jimmy schrieb: >>> On May 23, 3:05 pm, Andrew Lee wrote: >>>> Jimmy wrote: >>>>> Hi to all >>>>> python now has grown to a versatile language that can >>>>> accomplish tasks for many different purposes. However, >>>>> AFAIK, little is known about its ability of kernel coding. >>>>> So I am wondering if python can do some kernel coding that >>>>> used to be the private garden of C/C++. For example, can python >>>>> intercept the input of keyboard on a system level? someone told me >>>>> it's a kernel thing, isn't it? >>>> http://wiki.python.org/moin/elmer >>> >>> well, straightly speaking, how can I know a key is pressed on a system- >>> level if >>> using python? >> >> What has that todo with kernel programming? You can use e.g. pygame to >> get keystrokes. Or under linux, read (if you are root) the keyboard >> input file - I've done that to support several keyboards attached to a >> machine. >> >> And the original question: no, python can't be used as kernel >> programming language. Amongst other reasons, performance & the GIL >> prevent that. >> >> Diez > > http://www.kernel-panic.it/programming/py-pf/ > > Of course you can code kernel routines in Python -- you are just calling > the underlying C interface. The GIL means you have to manage > threadsafety on your own -- it doesn't imply kernel programming can not > be done. I understood the OP's question as "can one program kernelspace routines in python". Which I don't think is possible. And I don't see how py-pf does that either. Diez From sebastian.noack at googlemail.com Tue May 27 04:51:47 2008 From: sebastian.noack at googlemail.com (sebastian.noack at googlemail.com) Date: Tue, 27 May 2008 01:51:47 -0700 (PDT) Subject: tarfile.open(mode='w:gz'|'w|gz'|..., fileobj=StringIO()) fails. References: <133193d2-a87f-4000-b70c-29fdbb36f6d0@59g2000hsb.googlegroups.com> <35552ee8-4c87-4694-b783-aa4315f3ce18@m73g2000hsh.googlegroups.com> Message-ID: <414185e8-26cb-437f-abc5-70cd547450a8@34g2000hsh.googlegroups.com> I have written a FileWrapper class as workaround, which works for me (see the code below). The FileWrapper object holds an internal file- like object and maps its attributes, but prevents the user (in this case tarfile) from closing the internal file, so I can still access StringIO's content after closing the TarFile object. But this should not be required to create in memory tar files. It is definitely a bug, that TarFile closes external file objects passed to tarfile.open, when closing the TarFile object. The code which opens a file is also responsible for closing it. Regards Sebastian Noack # # File: StringIO-tarfile.py # #!/usr/bin/env python from StringIO import StringIO import tarfile import sys class FileWrapper(object): def __init__(self, fileobj): self.file = fileobj self.closed = fileobj.closed def __getattr__(self, name): # Raise AttributeError, if it isn't a file attribute. if name not in dir(file): raise AttributeError(name) # Get the attribute of the internal file object. value = getattr(self.file, name) # Raise a ValueError, if the attribute is callable (e.g. an instance # method) and the FileWrapper is closed. if callable(value) and self.closed: raise ValueError('I/O operation on closed file') return value def close(self): self.closed = True def create_tar_file(filenames, fileobj, mode): tar_file = tarfile.open(mode=mode, fileobj=fileobj) for f in filenames: tar_file.add(f) tar_file.close() if __name__ == '__main__': files = sys.argv[1:] modes = ['w%s%s' % (x, y) for x in (':', '|') for y in ('', 'gz', 'bz2')] for mode in modes: ext = mode.replace('w|', '-pipe.tar.').replace('w:', '.tar.').rstrip('.') # StringIO test. stream = FileWrapper(StringIO()) create_tar_file(files, stream, mode) fd = open('StringIO%s' % ext, 'w') fd.write(stream.file.getvalue()) stream.file.close() fd.close() # file object test. fd = open('file%s' % ext, 'w') create_tar_file(files, fd, mode) From heikki at osafoundation.org Fri May 2 15:42:33 2008 From: heikki at osafoundation.org (Heikki Toivonen) Date: Fri, 02 May 2008 12:42:33 -0700 Subject: Python and SOAP status In-Reply-To: References: Message-ID: Sorry, suds link should have been https://fedorahosted.org/suds -- Heikki Toivonen From bronger at physik.rwth-aachen.de Thu May 1 02:09:14 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Thu, 01 May 2008 08:09:14 +0200 Subject: relative import broken? References: <9c6ba5f9-d65b-4265-baba-fc5d7936781b@d1g2000hsg.googlegroups.com> <87prs6x1ye.fsf@mulj.homelinux.net> <33782b65-6d6d-4ae7-8539-29f809ae5077@d45g2000hsc.googlegroups.com> <87iqxyboae.fsf@physik.rwth-aachen.de> <6ddbc077-0092-4378-b613-5a5656b0e53e@l42g2000hsc.googlegroups.com> Message-ID: <87abjablo5.fsf@physik.rwth-aachen.de> Hall?chen! Sam writes: >> I didn't look it up myself, but maybe a __init__.py file is missing >> so that it can be recognised as a package. > > No, every single one (S, B, and W) has its own __init__.py > >> >> > in u.py Python gives "ImportError: No module named S". >> >> >> A silly question: is the directory that contains "S" in PYTHONPATH or >> >> in sys.path? >> >> > It's in sys.path. >> >> "S" or its parent directory? > > I added r'C:\Users\Myname\S' to sys.path. Is this the correct usage? Try r'C:\Users\Myname'. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From darcy at druid.net Fri May 2 10:15:08 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Fri, 2 May 2008 10:15:08 -0400 Subject: #!/usr/bin/env python vs. #!/usr/bin/python In-Reply-To: <87k5iczvdy.fsf@benfinney.id.au> References: <87abj91j8u.fsf@benfinney.id.au> <87k5iczvdy.fsf@benfinney.id.au> Message-ID: <20080502101508.a1562849.darcy@druid.net> On Fri, 02 May 2008 23:30:01 +1000 Ben Finney wrote: > The OP was asking why people prefer on over the other. My answer is > that I prefer specifying "give me the default OS Python" because > anything not installed by the OS is to non-standardised for me to > worry about. As someone else pointed out, not all the world is Linux. So your version of Linux (I'm not sure whether it is true for all versions or not) delivers Python as part of the OS. That is simply not true of the whole world. Some OS distributions have an adjunct facility for installing packages but they are not part of the OS. Some systems don't even have that and people must download packages such as Python and install them manually. Even on Linux there are people who won't install binaries and use NetBSD's pkgsrc instead. Clearly that cannot install into /usr/bin since it is not part of the OS. Certainly #! /usr/bin/python is fine if you never expect your software to run outside of your own little corner of the world but you asked why people prefer the env version and the answer is that we want to write software that runs everywhere that Python runs. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From yves at zioup.com Fri May 2 12:10:34 2008 From: yves at zioup.com (Yves Dorfsman) Date: Fri, 02 May 2008 16:10:34 GMT Subject: #!/usr/bin/env python vs. #!/usr/bin/python In-Reply-To: <87fxt0zs92.fsf@benfinney.id.au> References: <87abj91j8u.fsf@benfinney.id.au> <87k5iczvdy.fsf@benfinney.id.au> <87fxt0zs92.fsf@benfinney.id.au> Message-ID: <_1HSj.237347$pM4.42390@pd7urf1no> Thanks everybody, I didn't mean to start a flamewar... I do get it now, it's whatever python is in the path, vs. the specific one you're pointing to. Ben Finney wrote: > > No, because it's quite common for the PATH variable to have > '/usr/local/bin' appear *before* both of '/bin' and '/usr/bin'. > > If the system has a sysadmin-installed '/usr/local/bin/python' > installed as well as the OS-installed '/usr/bin/python', then the two > shebang options the OP raised will behave differently on such a > system. This seems to be quite the point of the discussion. > And I have to admit, I prefer specifying the version (full path) because I have run into too many problem when users have different PATHs and end up running different version of an interpreter. Yves. -- http://www.SollerS.ca From kyosohma at gmail.com Fri May 23 09:29:16 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 23 May 2008 06:29:16 -0700 (PDT) Subject: WXpython Question References: <5772771b-9b09-4870-8152-397bd93c926c@56g2000hsm.googlegroups.com> Message-ID: <9b765698-4d27-4e10-853e-e2c7e918d751@a1g2000hsb.googlegroups.com> On May 23, 8:24?am, Gandalf wrote: > I try to reach a specific wx StaticText element's text and to change > it by clicking on a button > > now let's say the this is my element: > > wx.StaticText(panel, 15, "Hello" ,(30, 70) , style=wx.ALIGN_CENTRE) > > And this is my EVT_BUTTON bind function : > > def OnClick(event): > > which code shude i enter to change "hello" to "goodbay"? > > thanks You're probably looking for SetLabel(). So if you do something like this to instantiate the StaticText: self.myText = wx.StaticText(panel, 15, "Hello" ,(30, 70) , style=wx.ALIGN_CENTRE) Then you can change your text by adding this to your OnClick event handler: self.myText.SetLabel("goodbye") Have fun! And remember, there's a great wxPython mailing list too: http://www.wxpython.org/maillist.php Mike From wizzardx at gmail.com Sun May 4 14:14:50 2008 From: wizzardx at gmail.com (David) Date: Sun, 4 May 2008 20:14:50 +0200 Subject: Real Time Midi File Playback - Reading and Writing midi at the same time In-Reply-To: <4e5b78a7-bc7a-4c1e-8552-b8175a9cbe32@m3g2000hsc.googlegroups.com> References: <4e5b78a7-bc7a-4c1e-8552-b8175a9cbe32@m3g2000hsc.googlegroups.com> Message-ID: <18c1e6480805041114j1b3448dfj2b86fe3144d77f9c@mail.gmail.com> On Sun, May 4, 2008 at 7:11 PM, Gilly wrote: > Hi > I am trying to create an application that uses some form of input to > create a midi file. > I would like for this to be a 'real time' process. In other words, I > want to be able to begin playing the midi file before I finish writing > it, and continue writing as it plays. Have you tried the MIDI libraries listed on this page? http://wiki.python.org/moin/PythonInMusic David. From wizzardx at gmail.com Thu May 8 09:36:31 2008 From: wizzardx at gmail.com (David) Date: Thu, 8 May 2008 15:36:31 +0200 Subject: Parsing Email 'References' header. In-Reply-To: <18c1e6480805080614r14d8d0c4t511a2bb4c0bc378a@mail.gmail.com> References: <4822F7B6.2000403@gmail.com> <18c1e6480805080614r14d8d0c4t511a2bb4c0bc378a@mail.gmail.com> Message-ID: <18c1e6480805080636i590f4a13t2179aac67433e8a1@mail.gmail.com> > > "<.*>(<.*?>)" > Doesn't work if there is only one e-mail address: Here's another one: "<[^<]+>$" From hat at se-162.se.wtb.tue.nl Fri May 16 03:45:37 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Fri, 16 May 2008 09:45:37 +0200 Subject: managing properties/configurations References: <408a6c83-8869-4c76-9acf-48cd42075658@y22g2000prd.googlegroups.com> <9976ee1f-1d37-4252-802a-8dd3c3de7d3d@k1g2000prb.googlegroups.com> Message-ID: On 2008-05-16, Venkatraman.S. wrote: > Or a better example would be: Indeed, this is concrete enough to make some suggestions. > I have the params in a config file and import this module: > myconfig.py > a=10 > b=30 > c=31 > d=40 The big problem imho with coding such stuff directly in Python is that you have no way to extract the data from the code to display it to your users without exposing them to Python code. Why not instead throw this in a ConfigParser file like below, and load the data values from it (each time they have changed?) [score] a=10 b=30 c=31 d=40 By picking better names, the config gets much more readable. The big advantage here is that a config file is something readable and editable without appearing it to be Python. If this is too low level for your users, you can use it as a data exchange format between the processing application and the frontend application where users can change the values. > import myconfig > def checkCutoff(self,up,down): > .............do some processing........ > if (a <= score <= b): > result="Bad" > elif (c <= score <= d): > result="Good" > .............do some processing........ > return result > > Now when i 'manually' make some changes to the value of a,b,c,d then > the the checkCutoff func should refer to the new values. Maybe reload the file each time you run the program? Sincerely, Albert From notnorwegian at yahoo.se Sun May 25 18:49:16 2008 From: notnorwegian at yahoo.se (notnorwegian at yahoo.se) Date: Sun, 25 May 2008 15:49:16 -0700 (PDT) Subject: which datastructure for fast sorted insert? References: <6610cad9-384d-4755-9a2c-c605329be217@8g2000hse.googlegroups.com> <69sj10F34jb08U3@mid.uni-berlin.de> Message-ID: On May 25, 9:32?am, Marc 'BlackJack' Rintsch wrote: > On Sun, 25 May 2008 00:10:45 -0700, notnorwegian wrote: > > sets dont seem to be so good because there is no way to iterate them. > > Err: > > In [82]: for x in set(['a', 'b', 'c']): > ? ?....: ? ? print x > ? ?....: > a > c > b > > Ciao, > ? ? ? ? Marc 'BlackJack' Rintsch i meant like set[pos], not iterate but access a specific position in the set. now i have to do: s = toSet.pop() toSet.add(s) if i want to get the url of the next item in a set, how would i do that? i can do this with a list: def scrapeSitesX(startAddress, toList, listPos): return scrapeSites(toList[listPos], toList, listPos+1) to use recursion with a list. i can work around that but it doesnt get as elegant. From d3vvnull at gmail.com Fri May 23 00:50:27 2008 From: d3vvnull at gmail.com (Michael Mabin) Date: Thu, 22 May 2008 23:50:27 -0500 Subject: php vs python In-Reply-To: References: <5l%Yj.77$mz3.53@fe101.usenetserver.com> Message-ID: <170543c70805222150j14365fc6hc96b3948c339d68a@mail.gmail.com> I used python to generate php code. But that was before I knew what vast troves of python web frameworks there were. :) On Thu, May 22, 2008 at 11:40 PM, inhahe wrote: > > > PHP can do that. There are also a number of templating engines > > available. The nice thing about PHP is you have a choice. > > i just meant that php is sort of invented to combine html and code, so if > you use python instead you should use a templating engine. but i suppose > it's useful for php too. > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- | _ | * | _ | | _ | _ | * | | * | * | * | -------------- next part -------------- An HTML attachment was scrubbed... URL: From byte8bits at gmail.com Thu May 22 11:45:06 2008 From: byte8bits at gmail.com (brad) Date: Thu, 22 May 2008 11:45:06 -0400 Subject: problem boost::python::import In-Reply-To: References: Message-ID: Fr?d?ric Degraeve wrote: > Hello, > > I tried this code with vs7-8 and boost1.34.1-1.35.0 and my python is a > 2.4...... Try the boost users list: To subscribe or unsubscribe via the World Wide Web, visit http://lists.boost.org/mailman/listinfo.cgi/boost-users From castironpi at gmail.com Tue May 13 10:16:27 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 13 May 2008 07:16:27 -0700 (PDT) Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <2b66a86e-5a05-4262-b3c9-4703b0ae3372@d1g2000hsg.googlegroups.com> <5b0e3f70-afde-4480-8713-e7113b1250d7@x35g2000hsb.googlegroups.com> <1f537717-00d0-48ee-99b6-7125b96a6133@t12g2000prg.googlegroups.com> <68t4o0F2vaoncU1@mid.uni-berlin.de> <3d8cb22c-5b5a-49c1-9ee0-9c09ed91106a@k37g2000hsf.googlegroups.com> Message-ID: <2108ecb8-ba27-4c97-8f9f-adfe451e10fb@56g2000hsm.googlegroups.com> On May 13, 9:05?am, Dave Parker wrote: > On May 13, 7:44?am, castiro... at gmail.com wrote: > > > I am not convinced that the colorspace occupies three dimensions necessarily. > > Apparently there are some people -- called tetrachromats -- who can > see color in four dimensions. ?They have extra sets of cones in their > retinas containing a different photopigment. ?So, the dimensions of > color appear to be an artifact of our visual systems, and not inherent > in the colors themselves which are linear (one-dimensional) in > frequency. ?http://en.wikipedia.org/wiki/Tetrachromacy My conspiracy theorists know too much. They would question that mathematical claim of science, that retinas only detect one dimension of one force. Are we asking if something like that is fundamental to life? I have been very sceptical about emperical claims, especially since I just try to render stuff and play Tron. From sturlamolden at yahoo.no Fri May 30 06:21:37 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 30 May 2008 03:21:37 -0700 (PDT) Subject: should I put old or new style classes in my book? References: Message-ID: <63757633-e3d7-4d5b-b1c4-160987913990@34g2000hsh.googlegroups.com> On May 29, 6:07 pm, allendow... at gmail.com wrote: > The current edition of the book presents old style classes. I am > considering > switching to new style classes on the assumption that this should be > the default > choice for new programs. The drawback is that a lot of the online > documentation > still uses old style classes. You should use new-style classes. It is the default in Python 2.6 and the only option in 3.0. These releases will be out before your book is on the market. From alex_fainshtein at netzero.net Fri May 2 17:29:57 2008 From: alex_fainshtein at netzero.net (Alex Fainshtein) Date: Fri, 2 May 2008 14:29:57 -0700 Subject: 'property' builtin does not work for me Message-ID: Question: what I am doing wrong? Here, I am defining class with property member: class Test: def getter(self): print "Getter called." return 'a' def setter(self, val): print "Setter called." prop = property(getter, setter) Then testing it: >>> t = Test() >>> t.prop Getter called. 'a' >>> t.prop = 'b' >>> t.prop 'b' >>> As you see, getter works properly. But when assigning to property, setter is not called, as I would expect. prop is simply replaced with whatever is assigned and ceased being a property. -------------- next part -------------- An HTML attachment was scrubbed... URL: From benjamin.kaplan at case.edu Sat May 24 16:57:39 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sat, 24 May 2008 16:57:39 -0400 Subject: Why does python not have a mechanism for data hiding? In-Reply-To: <5ea78616-e955-4ee0-8e60-a22734ec31be@79g2000hsk.googlegroups.com> References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <8763t3by81.fsf@benfinney.id.au> <5ea78616-e955-4ee0-8e60-a22734ec31be@79g2000hsk.googlegroups.com> Message-ID: On Sat, May 24, 2008 at 10:14 AM, Fuzzyman wrote: > On May 24, 2:58 pm, Ben Finney > > > wrote: > > Sh4wn writes: > > > first, python is one of my fav languages, and i'll definitely keep > > > developing with it. But, there's 1 one thing what I -really- miss: > > > data hiding. I know member vars are private when you prefix them with > > > 2 underscores, but I hate prefixing my vars, I'd rather add a keyword > > > before it. > > > > From whom are you trying to hide your attributes? > > Actually, 'data hiding', although vastly overused by the static crowd > can be a reasonable thing to want. > > For example, at Resolver Systems we expose the spreadsheet object > model to our users. It hasa public, documented, API - plus a host of > undocumented internally used methods. > > We would really *much* rather hide these, because anything our > customers start using (whether documented or not) we will probably > have to continue supporting and maintaining. > > The 'we told you not to use that' approach, when applied to paying > customers doesn't really work... all they see is that you broke their > spreadsheet code by changing your API. > It apparently works for Sun Microsystems. They do that with a whole bunch of packages in Java, and Java does allow data hiding. http://java.sun.com/products/jdk/faq/faq-sun-packages.html > > You can make members truly private by proxying, but it is a bit > ungainly. > > Michael Foord > http://www.ironpythoninaction.com/ > > > > > > In Python, the philosophy "we're all consenting adults here" applies. > > You shouldn't pretend to know, at the time you write it, all the uses > > to which your code will be put. Barriers such as enforced "private" > > attributes will only cause resentment when people, despite your > > anticipations, *need* to access them and are then forced to hack their > > way around them. > > > > If you want the users of your code to know that an attribute should > > not be used as a public API for the code, use the convention of naming > > the attribute with a single leading underscore. This is a string > > signal that the attribute is part of the implementation, not the > > interface. The reader is then on notice that they should not rely on > > that attribute; but they are not *prohibited* from using it if > > necessary to their ends. > > > > > Python advertises himself as a full OOP language, but why does it > > > miss one of the basic principles of OOP? > > > > Who taught you that enforced restrictions on attribute access was a > > "basic principle" of OO? > > > > Perhaps you're confusing the "encapsulation" and "abstraction" > > principles for enforced access restrictions; they're not. > > > > > Will it ever be added to python? > > > > I hope not. > > > > -- > > \ "Why was I with her? She reminds me of you. In fact, she | > > `\ reminds me more of you than you do!" -- Groucho Marx | > > _o__) | > > Ben Finney > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bbxx789_05ss at yahoo.com Sat May 10 22:37:05 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Sat, 10 May 2008 19:37:05 -0700 (PDT) Subject: Is using range() in for loops really Pythonic? References: <482657ca$0$25026$607ed4bc@cv.net> Message-ID: <87c642fa-2a6c-43c5-a812-27924e689889@34g2000hsh.googlegroups.com> On May 10, 8:19?pm, John Salerno wrote: > I know it's popular and very handy, but I'm curious if there are purists > out there who think that using something like: > > for x in range(10): > ? ? #do something 10 times > > is unPythonic. The reason I ask is because the structure of the for loop > seems to be for iterating through a sequence. It seems somewhat > artificial to use the for loop to do something a certain number of > times, like above. > x = range(10) print x --output:-- [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] From arnodel at googlemail.com Thu May 29 15:12:15 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Thu, 29 May 2008 20:12:15 +0100 Subject: should I put old or new style classes in my book? References: Message-ID: Jason writes: > On May 29, 10:07 am, allendow... at gmail.com wrote: >> Hi All, >> >> I am working on a revised edition of How To Think Like a Computer >> Scientist, >> which is going to be called Think Python. It will be published by >> Cambridge >> University Press, but there will still be a free version under the GNU >> FDL. >> >> You can see the latest version at thinkpython.com; I am revising now, >> so >> I welcome all comments, suggestions, corrections, etc. >> >> Anyway, I am posting to ask about the current status of new style >> classes. >> I am planning to present only one style in the book, because the >> differences >> between them don't matter for anything I am doing in the book. >> >> The current edition of the book presents old style classes. I am >> considering >> switching to new style classes on the assumption that this should be >> the default >> choice for new programs. The drawback is that a lot of the online >> documentation >> still uses old style classes. >> >> Thanks for any guidance you can provide. >> >> Cheers, >> Allen > > I've got Python 3.0 alpha 2. In this version, it looks like you can > define classes in either the old style or new style. (I snipped the > top line a bit in the following example): > > Python 3.0a2 (r30a2:59405M, Dec 7 2007, 15:23:28 > Type "help", "copyright", "credits" or "license" >>>> class one(object): pass > ... >>>> class two: pass > ... >>>> two > >>>> one > >>>> type(one) > >>>> type(two) > >>>> Note that you can get the same behaviour in Python 2.2+ by setting the global variable __metaclass__ to type: marigold:~ arno$ python Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:17) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> __metaclass__ = type >>> class Foo: pass ... >>> type(Foo) >>> -- Arnaud From daveparker at flamingthunder.com Wed May 21 17:39:43 2008 From: daveparker at flamingthunder.com (Dave Parker) Date: Wed, 21 May 2008 14:39:43 -0700 (PDT) Subject: Bug in floating-point addition: is anyone else seeing this? References: <8187c3b6-a772-456f-a54f-0af7babb353e@w34g2000prm.googlegroups.com> Message-ID: On May 21, 3:19?pm, "Dan Upton" wrote: > The fact is, sometimes it's better to get it fast and be good enough, > where you can use whatever methods you want to deal with rounding > error accumulation. I agree. I also think that the precision/speed tradeoff should be under user control -- not at the whim of the compiler writer. So, for example, if a user says: Set realdecimaldigits to 10. then it's okay to use hardware double precision, but if they say: Set realdecimaldigits to 100. then it's not. The user should always be able to specify the precision and the rounding mode, and the program should always provide correct results to those specifications. From vivainio at gmail.com Mon May 5 14:41:01 2008 From: vivainio at gmail.com (Ville M. Vainio) Date: Mon, 05 May 2008 18:41:01 GMT Subject: ISBN Barecode reader in Python? References: Message-ID: Max Erickson writes: > The killer application for ISBN lookup on Amazon is checking prices > while in the bookstore. Being able to email a photo from your phone > and then getting an email with the Amazon price in response would be > way easier than typing the isbn into Google or whatever. Yeah, or just create a S60 python app to do it directly. Basically, just put up a web service somewhere that allows pushing an image of the barcode and returns the lowest price for that item, and the PyS60 app will be done in a day. From wizzardx at gmail.com Mon May 5 09:09:49 2008 From: wizzardx at gmail.com (David) Date: Mon, 5 May 2008 15:09:49 +0200 Subject: using sqlite3 - execute vs. executemany; committing ... In-Reply-To: <9fdb569a0805050559q83999d4v6043acb94c9797d0@mail.gmail.com> References: <9fdb569a0805031431r6666e950pc6dbc8aab6e36684@mail.gmail.com> <18c1e6480805040214m5ecd0b27t9800bfc4a39daec8@mail.gmail.com> <9fdb569a0805041407s75c8ad3bsc08c8bac87fa0d83@mail.gmail.com> <18c1e6480805041536x7287d23ds9d9bfcf6ec73e123@mail.gmail.com> <9fdb569a0805050559q83999d4v6043acb94c9797d0@mail.gmail.com> Message-ID: <18c1e6480805050609n7a65d67amdc83c2b89f8f2271@mail.gmail.com> Hi Vlasta. Don't have time to reply to your mail in detail now. Will do so later. Have you tried the eGenix text tagging library? It sounds to me that this is exactly what you need: http://www.egenix.com/products/python/mxBase/mxTextTools/ Disclaimer: I've never actually used this library ;-) David. From mnordhoff at mattnordhoff.com Sun May 25 01:19:49 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Sun, 25 May 2008 05:19:49 +0000 Subject: module import problem In-Reply-To: <200805242359.27995.prudek@bvx.cz> References: <200805242359.27995.prudek@bvx.cz> Message-ID: <4838F6F5.5070409@mattnordhoff.com> Milos Prudek wrote: > I have a Kubuntu upgrade script that fails to run: > > File "/tmp/kde-root//DistUpgradeFetcherCore.py", > line 34, in > import GnuPGInterface > ImportError > No module named GnuPGInterface > > I got a folder /usr/share/python-support/python-gnupginterface with > a "GnuPGInterface.py" but no __init__.py. > > In python command line, print sys.path shows that /usr/share/python-support/ > is not among python paths. > > If I cd into /usr/share/python-support/python-gnupginterface and launch Python > I can "import GnuPGInterface". But when I run DistUpgradeFetcherCore.py in > that folder it always fails with No module named GnuPGInterface. > > I do not know much about setting python path. This doesn't help solve your problem, but /usr/share/python-support doesn't need to be in Python's path because python-support puts symlinks to it in /usr/share/python*/site-packages. -- From bruno.42.desthuilliers at websiteburo.invalid Fri May 16 09:45:38 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 16 May 2008 15:45:38 +0200 Subject: class problem, NoneType obj has no attribute In-Reply-To: <4ee9d5fa-5012-40a5-8bf6-c2624781d855@k37g2000hsf.googlegroups.com> References: <10bbf997-3520-4920-b225-8685b98d9079@59g2000hsb.googlegroups.com> <482d7bbc$0$15491$426a74cc@news.free.fr> <4ee9d5fa-5012-40a5-8bf6-c2624781d855@k37g2000hsf.googlegroups.com> Message-ID: <482d9001$0$24452$426a74cc@news.free.fr> globalrev a ?crit : > On 16 Maj, 14:19, Bruno Desthuilliers 42.desthuilli... at websiteburo.invalid> wrote: >> globalrev a ?crit : (snip) >>> cust1 = customer.__init__('12',['1','435','2332']) >> __init__ is automagically called on instanciation, so you don't have to >> call it yourself. And FWIW, your __init__ returns None. > > what should init return normally? None. Your __init__ is fine, the problem is with the call. To instanciate a class, you call the class object itself, passing it the arguments awaited by __init__, ie: cust1 = Customer('12', ['1', '435', '2332']) From victorsubervi at gmail.com Fri May 2 09:38:34 2008 From: victorsubervi at gmail.com (Victor Subervi) Date: Fri, 2 May 2008 08:38:34 -0500 Subject: Custom Classes? In-Reply-To: <1209729679.6589.23.camel@jcd-desktop> References: <4dc0cfea0804300902o7493dab2m35999b5b59deace4@mail.gmail.com> <1209576920.4990.17.camel@aalcdl07.lib.unc.edu> <4dc0cfea0805011531s4574eb0bk8b6aea6ac010c881@mail.gmail.com> <1209729679.6589.23.camel@jcd-desktop> Message-ID: <4dc0cfea0805020638l59af4bb2o4abdcb12ee88995f@mail.gmail.com> Thank you for your patience. I apologize for so many errors. Also, apparently your email client renders those double-spaces whereas mine does not. Hopefully the below is better: #!/usr/bin/python import MySQLdb import sys,os sys.path.append(os.getcwd()) from login import login user, passwd, db, host = login() pic = "pic1" w = 20 x = 0 d = 6 y = 1 getpic = "getpic" + str(w) + ".py" try: os.remove(getpic) except: pass code = """ #!/usr/local/bin/python import cgitb; cgitb.enable() import MySQLdb import cgi import sys,os sys.path.append(os.getcwd()) from login import login user, passwd, db, host = login() form = cgi.FieldStorage() picid = int(form["id"].value) x = int(form["x"].value) pics = {1:'pic1',2:'pic1_thumb',3:'pic2',4:'pic2_thumb',5:'pic3',6:'pic3_thumb',7:'pic4',8:'pic4_thumb',\ 9:'pic5',10:'pic5_thumb',11:'pic6',12:'pic6_thumb'} pic = pics[x] db = MySQLdb.connect(host, user, passwd, db) cursor= db.cursor() sql = "select %s from products where id='%s';" % (pic, str(picid)) cursor.execute(sql) content = cursor.fetchall()[0][0].tostring() cursor.close() print 'Content-Type: image/jpeg' print print content """ script = open(getpic, "w") script.write(code) # print '' % (str(x), pic) # print '

\n' % (getpic, d, y) print '\n' Now, on those last 3 lines, I am having trouble with this error being thrown that I don?t understand: ValueError: unpack list of wrong size If I surf to the given url, the image appears! So what gives?? Furthermore, the code works just fine from where it was lifted. TIA, Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From arnodel at googlemail.com Mon May 19 17:27:06 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 19 May 2008 22:27:06 +0100 Subject: explain this function to me, lambda confusion References: <5cc7ef7a-dd21-4772-a7e3-765410f810bb@l17g2000pri.googlegroups.com> <081fe61b-820b-4512-80a9-8a0805f3ce55@k13g2000hse.googlegroups.com> <74ce1ffa-0031-4101-8792-5f2ba7f22bca@b64g2000hsa.googlegroups.com> Message-ID: Paul McGuire writes: > On May 19, 11:04?am, Arnaud Delobelle wrote: >> Paul McGuire writes: >> >> [...] >> >> Could you use it as a decoratore instead? >> >> integer = Word("0123456789") >> >> @integer.setParseAction >> def parse_integer(tokens): >> ? ? return int(tokens[0]) >> >> I could make your grammar clearer, because you don't mix it with >> processing code... and no need for lambdas! >> >> -- >> Arnaud > > What a sexy little idiom! You could really apply this to any API > method that accepts a callable as a single argument, and pyparsing > actually has several of these: > > setParseAction > addParseAction > setFailAction > setDebugActions > > (Unfortunately, setDebugActions requires 3 callables for its arguments > - one to be run when an expression is about to be parsed, one to be > run after parsing is complete, and one to be run if the expression > fails to be parsed. So setDebugActions can't be used in this > decorator manner.) > > Using these methods as decorators deviates from the typical decorator > usage model as I understand it - instead of wrapping the provided > function within some enclosing setup/teardown code (like lock/unlock, > or open-file/close-file, or begin-transaction/commit-transaction), and > then returning the created wrapper function, the decorator usage you > propose is one in which the decorator uses the provided function with > some side-effect (such as setting a property), but then just returns > the original function. I humbly think this is a very good use of decorators; it is one that I frequently take advantage of and until I read this I had never thought of it as deviant :). After all, Python is not a functional language, functions have side-effects and that's that. In a way it is more basic than the 'typical' use, i.e. # Typical use; mutates defined function @staticmethod def foo(bar, baz)... is shorthand for def foo(bar, baz)... foo = staticmethod(foo) Whereas # Deviant use; leaves function untouched @register def foo(bar, baz)... is shorthand for def foo(bar, baz)... register(foo) I am not claiming that it should be a common decorator idiom, only that I am comfortable with it and find it useful. > By returning the original function, we could stack decorators so > that multiple expressions could share the same parse action: > > @articleTitle.setParseAction > @movieTitle.setParseAction > @bookTitle.setParseAction > def upcase_title(tokens): > return " ".join( t.title() for t in tokens ) > > Here is where I have something of a hitch, with the way pyparsing > implements most setXXX methods. setParseAction already returns a > value, and the value returned is self. If you have any Smalltalk > background, this will seem familiar to you. (Not that I was ever a > big-time Smalltalk coder, but this was one language idiom that you > learned on Day 0.5 or you were lost forever.) This makes it easy to > chain together a constructor and multiple property setters into a > single expression: > > timestamp = Regex(r"\d\d(\/\d\d\){2} \d\d(:\d\d) > {2}").setParseAction(convertTimeStamp).leaveWhitespace().setDebug() I am not a user of pyparsing (yet!), so my comment is completely uninformed, but I feel that what is gained in brevity by writing it like this, may be lost in clarity because separate notions are put together (parsing, processing, debugging). But if I understand correctly, I would be able to rewrite this as: # Grammar section timestamp = Regex(r"\d\d(\/\d\d\){2} \d\d(:\d\d){2}") # Processing section timestamp.setParseAction(convertTimeStamp) timestamp.leaveWhitespace() # I'm not sure what this does! # Debugging section timestamp.setDebug() OK, now I understand what my problem is: - your existing setXXX methods mutate self and return it, thus breaking the quasi-rule that if you mutate something, don't return it (c.f. list.sort, etc); - your proposed 'decorator-friendly' setXXX methods mutate self and return their argument just to satisfy the decorator-friendliness constraint, but in spirit they return nothing. This is just a train of thought, and I hope that you won't take this the wrong way. I am arguing for the pleasure of it, and I am happy to lose the argument :) > In the case where we have a single parse action shared by multiple > expressions, we have to fall back to: > > def upcase_title(tokens): > return " ".join( t.title() for t in tokens ) > articleTitle.setParseAction(upcase_title) > movieTitle.setParseAction(upcase_title) > bookTitle.setParseAction(upcase_title) > > But, now that I've looked at this for a while, I may fall back on some > other idioms: > - just because you *can* do something doesn't mean you *should* do it > - explicit is better than implicit You're (probably!) the best person to judge the syntactical balance of pyparsing! > Decorator syntax is already a mysterious topic for many newbies, even > when used for its normal application. Using a decorator to perform > the same function as an explicit "set" call invokes cleverness at the > cost of clarity. Using decorators to replace: > > def methodX(a,b,c): > blah > methodX = staticmethod(methodX) > > with > > @staticmethod > def methodX(a,b,c): > blah > > does have some merits, including DRY. But using decorator syntax as > an implicit invocation of a set method? It's just taking advantage of > the incidental implementation of the decorator syntax. It would be > like implementing the logic of a for-loop using a list comprehension - > clever, and yes it can be done, but maybe a bit obscure. I understand your comment about list-comprehensions, but I haven't yet reached the level of Python guru-ness to correlate it to decorators :) There are more things I would have liked to expand on but unfortunately I don't have enough time to put my thoughts together in a communicable manner. -- Arnaud From martin at v.loewis.de Thu May 1 14:03:22 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 01 May 2008 20:03:22 +0200 Subject: Problems with Cheese Shop In-Reply-To: <87zlr9vry8.fsf@physik.rwth-aachen.de> References: <87zlr9vry8.fsf@physik.rwth-aachen.de> Message-ID: <481A05EA.6080508@v.loewis.de> > How can I authorise to the Python Cheese Shop in order to use > setup.py upload? Currently, I get > > Upload failed (401): You must be identified to edit package information You need to add your PyPI password to .pypirc. Regards, Martin From alex.m.gusarov at gmail.com Wed May 28 13:13:01 2008 From: alex.m.gusarov at gmail.com (Alex Gusarov) Date: Thu, 29 May 2008 00:13:01 +0700 Subject: Overloading virtual method of widget without inheriting (PyQt) In-Reply-To: References: <6a53c9ff-d4ce-483e-959f-2505ad107093@a1g2000hsb.googlegroups.com> Message-ID: > I have a feeling that the form produced by Qt Designer, once converted to > code, contains references to QCalendarWidget where you really want to use a > customized calendar widget. If so, you should "promote" the calendar widget > in Qt Designer to use your widget instead, and make sure you import the > module that supplies it in your application. David, thanks for noticing about "promoting" within designer, it helped me. > Anyway, IIRC (it's a long time since I used Qt), QT allows to connect > more than one slot with the same signal, so you should not need to > subclass or to create your own multi-dispatcher. Just doing: > > calendar.paintCell.signal( SOME_SIGNAL_NAME, my_paint_method ) > > should work. I don't know which signal you should connect to, however. > > This link gives you some detail on signal/slots in PyQT: Thanks, but actually, paintCell is not a signal, it's simply a virtual method of caledarwidget. -- Best regards, Alex Gusarov From tjreedy at udel.edu Tue May 13 03:16:41 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 13 May 2008 03:16:41 -0400 Subject: anonymous assignment References: <1XNVj.133805$Cj7.33096@pd7urf2no> Message-ID: "Arnaud Delobelle" wrote in message news:m2lk2eivos.fsf at googlemail.com... | "Terry Reedy" writes: | | > "Arnaud Delobelle" wrote in message | > news:c689625d-b2d2-4268-ae40-15e3c9b78ea2 at x41g2000hsb.googlegroups.com... | > | > here is a very sophisticated implementation :) | > | >>>> def extract(indices, seq): | > ... return tuple(seq[i] for i in indices) | > ... | >>>> y, d = extract((0, 2), time.localtime()) | >>>> y, d | > (2008, 12) | > | > =================== | > Or a generator version: | > | > # 3.0 | > def extract(iterable, indexes): | > # assume indexes are all legal and in order, I wrote once, but seem to have erased in revising (frown) | > enext = enumerate(iterable).__next__ | > i,item = enext() | > for index in indexes: | > while i < index: | > i,item = enext() | > yield item | > | > import time | > print(list(extract(time.localtime(), (0,2)))) | > | > #prints [2008, 12] | | but extract('python', (3, 1)) won't work! From grayaii at gmail.com Wed May 7 17:04:30 2008 From: grayaii at gmail.com (grayaii) Date: Wed, 7 May 2008 14:04:30 -0700 (PDT) Subject: subprocess wait() waits forever, but os.system returns References: <84a23679-56e2-41b5-83eb-741a696095da@59g2000hsb.googlegroups.com> Message-ID: <27830e9e-cfc4-45a3-99da-94cb17bb1720@r66g2000hsg.googlegroups.com> Awesome! That worked! And your comment just led me down another exploration path on why the following doesn't work: --------------------- while(returncode is None): returncode = run.poll() time.sleep(1) out = run.stdout.readlines() err = run.stderr.readlines() --------------------- Nowhere in the loop am I reading stdout or err. I'm only reading it after the loop has finished, and when running the exe, returncode is *always* None. Now I have to figure out a way to read it within the loop without blocking the read... on Windows... Thinking out loud: Perhaps it would be better to put the subprocess commands in a separate thread so if my process hangs, I can kill it after a given time. Various threads in this forum suggested that method, so perhaps I should do it that way... From b0bm00r3 at gmail.com Sun May 11 02:19:04 2008 From: b0bm00r3 at gmail.com (philly_bob) Date: Sat, 10 May 2008 23:19:04 -0700 (PDT) Subject: Keeping two lists aligned after processing Message-ID: <823470c7-4c15-4653-8c51-7ab83acc9221@m36g2000hse.googlegroups.com> """ I have a population of five algorithms. Each Alg has a method, Alg.accuracy(), which calculates its accuracy. Running the accuracy method on each Alg, I end up with a list of accuracies like [0.75, 0.10, 0.45, 0.80, 0.45] Now I want to store the algorithms and associated accuracies in a file, in descending order of accuracy. Here's how I do it now. There must be a better way! This method is inelegant, and does not handle at all the issue of what to do with duplicate accuracies, such as the two different algorithms with 0.45 accuracies in the example above. It merely saves the first of the duplicates -- not what I want at all. I want to end up with a file: 0 AlgD 0.80 1 AlgA 0.75 2 AlgC 0.45 3 AlgE 0.45 4 AlgB 0.10 """ algs=['AlgA', 'AlgB', 'AlgC', 'AlgD', 'AlgE'] accs=[] for alg in algs: thisacc=getattr(alg.accuracy)() # picked this technique on comp.lang.python last month accs.append(thisacc) unsortedaccs=[x for x in accs] # to preserve unsorted accs.sort() accs.reverse() # ending up with sorted list nuorder=[] for ax,acc in enumerate(accs): spot=unsortedaccs.index(acc) nuorder.append(spot) ofn=open('store.alg','w') for ord in nuorder: alg=algs[ord] acc=unsortedlist[ord] ofn.write("%d %s,%s" % (ord,alg,str(acc)) ofn.close() From arnodel at googlemail.com Sun May 11 16:28:15 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 11 May 2008 21:28:15 +0100 Subject: Is using range() in for loops really Pythonic? References: <482657ca$0$25026$607ed4bc@cv.net> <48275316$0$11629$607ed4bc@cv.net> Message-ID: John Salerno writes: > John Salerno wrote: >> I know it's popular and very handy, but I'm curious if there are purists >> out there who think that using something like: >> >> for x in range(10): >> #do something 10 times >> >> is unPythonic. The reason I ask is because the structure of the for loop >> seems to be for iterating through a sequence. It seems somewhat >> artificial to use the for loop to do something a certain number of >> times, like above. >> >> Anyone out there refuse to use it this way, or is it just impossible to >> avoid? > > Ok, I think most people are misunderstanding my question a little. I > probably should have said xrange instead of range, but the point of my > question remains the same: > > Should a for loop be used simply to do something X number of times, or > should it strictly be used to step through an iterable object for the > purpose of processing the items in that object? It makes me feel slightly uncomfortable too, but AFAIK there is no better way in Python. What I sometimes do is make the for loop bind its variable to something useful instead of an unused counter. Contrived example: # Print 'hello' 10 times; x is not used for x in xrange(10): print 'hello' # By changing what is iterated over, no unused variable: from itertools import repeat for msg in repeat('hello', 10): print msg -- Arnaud From wuwei23 at gmail.com Wed May 21 21:05:11 2008 From: wuwei23 at gmail.com (alex23) Date: Wed, 21 May 2008 18:05:11 -0700 (PDT) Subject: Returning to 'try' block after catching an exception References: Message-ID: <485f7ddc-8f50-4483-b591-151f1ae560be@k10g2000prm.googlegroups.com> On May 22, 9:13 am, Karlo Lozovina <_karlo_ at _mosor.net_> wrote: > In case it's not clear what I meant: after executing some_function() > exception SomeExcpetion gets risen. Then, in except block I do something > to fix whatever is causing the exception and then I would like to go back > to try block, and execute some_function() again. Is that doable? If you know what exception to expect, and you know how to "fix" the cause, why not just put tests _before_ some_function() is called to ensure that everything is as it needs to be? From nagle at animats.com Tue May 13 13:20:41 2008 From: nagle at animats.com (John Nagle) Date: Tue, 13 May 2008 10:20:41 -0700 Subject: Is using range() in for loops really Pythonic? In-Reply-To: References: <482657ca$0$25026$607ed4bc@cv.net> Message-ID: <4829cac1$0$34550$742ec2ed@news.sonic.net> Matt Nordhoff wrote: > John Salerno wrote: >> I know it's popular and very handy, but I'm curious if there are purists >> out there who think that using something like: >> >> for x in range(10): >> #do something 10 times >> >> is unPythonic. The reason I ask is because the structure of the for loop >> seems to be for iterating through a sequence. It seems somewhat >> artificial to use the for loop to do something a certain number of >> times, like above. >> >> Anyone out there refuse to use it this way, or is it just impossible to >> avoid? > > Well, you should use "xrange(10)" instead of "range(10)". CPython really is naive. That sort of thing should be a compile-time optimization. John Nagle From Sam.Dutton at itn.co.uk Sun May 25 15:38:57 2008 From: Sam.Dutton at itn.co.uk (Dutton, Sam) Date: Sun, 25 May 2008 20:38:57 +0100 Subject: where do I begin with web programming in python? Message-ID: <3F2A6E37-A9C5-4645-BEDA-A8EABB3034E7@mimectl> This doesn't really answer your question, but you might want to consider Google App Engine. http://code.google.com/appengine/ Sam Dutton SAM DUTTON SENIOR SITE DEVELOPER 200 GRAY'S INN ROAD LONDON WC1X 8XZ UNITED KINGDOM T +44 (0)20 7430 4496 F E Sam.Dutton at itn.co.uk WWW.ITN.CO.UK P Please consider the environment. Do you really need to print this email? Please Note: Any views or opinions are solely those of the author and do not necessarily represent those of Independent Television News Limited unless specifically stated. This email and any files attached are confidential and intended solely for the use of the individual or entity to which they are addressed. If you have received this email in error, please notify postmaster at itn.co.uk Please note that to ensure regulatory compliance and for the protection of our clients and business, we may monitor and read messages sent to and from our systems. Thank You. -------------- next part -------------- An HTML attachment was scrubbed... URL: From inhahe at gmail.com Thu May 22 13:48:29 2008 From: inhahe at gmail.com (inhahe) Date: Thu, 22 May 2008 13:48:29 -0400 Subject: import X vs from x import * References: Message-ID: wrote in message news:c8ca75c3-98ab-4c74-8868-b58fbc12a0b2 at m73g2000hsh.googlegroups.com... > import Tkinter > from Tkinter import * > > i have a program where if i comment out either of those import- > statements i get an error. > > i thought they meant the same thing and from was supposed to be just > to imort just a specific function and the * imports everything in the > module. > but aparently the above statements have diffrent meaning and i cant > figure it out fromt he tutorials. the first statement imports tkinter but everything inside of tkinter in stored in the tkinter namespace, in other words if tkinter has a class tk, then tk would be accessed as tkinter.tk. for example import tkinter blah = tkinter.tk() if you do from tkinter import *, then everything in tkinter is imported at the top level, so it would be from tkinter import * blah = tk() From pistacchio at gmail.com Mon May 12 04:10:33 2008 From: pistacchio at gmail.com (pistacchio) Date: Mon, 12 May 2008 01:10:33 -0700 (PDT) Subject: module global variables References: Message-ID: On 12 Mag, 10:10, pistacchio wrote: > On 12 Mag, 10:01, alex23 wrote: > > > On May 12, 5:17 pm, pistacchio wrote: > > > > hi to all! > > > can i load a module passing to it, automatically and as default, all > > > the caller's global variables to act as module's global variables? > > > thanks > > > module = __import__('module', globals=globals()) > > > I think that's what you're looking for. > > > - alex23 > > hmm, well, maybe yes.. should i ovveride the standard import function > of the module? > say that the module is called "pycatrix", would adding this to the > module solve the problem? > > def __import__('pycatrix', globals=globals()): pardon, this: def __import__('pycatrix', globals=globals()): pass From tinnews at isbd.co.uk Thu May 1 16:09:31 2008 From: tinnews at isbd.co.uk (tinnews at isbd.co.uk) Date: 01 May 2008 20:09:31 GMT Subject: Best way to store config or preferences in a multi-platform way. References: <790cec6c-b057-4a2d-bc2c-e683630c1127@w7g2000hsa.googlegroups.com> Message-ID: <481a237b$0$654$bed64819@news.gradwell.net> Carl Banks wrote: > On May 1, 12:11 pm, Jon Ribbens wrote: > > On 2008-05-01, Ivan Illarionov wrote: > > > > > IMO .ini-like config files are from the stone age. The modern approach is > > > to use YAML (http://www.yaml.org). > > > > You mean YAML isn't a joke!? It's so ludicrously overcomplicated, > > and so comprehensively and completely fails to achieve its stated > > main goal of being "readable by humans", that I had assumed it > > was an April Fool along the lines of Intercal or brainf***. > > > YAML, ISTM, took a simple concept that worked for small, > straightforward data, and tried to make into a format that could > anything anywhere, with disastrous results. It's not unlike Perl in > this regard. It's quite ridiculous. > > > My recommendation to the OP would be: > > If you intend to write a GUI that completely sets all the options, use > XML. You can bet there are some users who would prefer text editing > options files, and XML, while not the most readable format available, > at least gives users the option. > But XML has human unfriendly syntax, is awkward to type, is difficult to read, what's good about it? If there's a GUI between you and the XML then OK, but that wasn't where we were was it? -- Chris Green From inhahe at gmail.com Tue May 6 08:36:28 2008 From: inhahe at gmail.com (inhahe) Date: Tue, 6 May 2008 08:36:28 -0400 Subject: select.poll() and WSAPoll Message-ID: select.poll isn't supported on Windows, because Windows doesn't have such a feature, or at least it didn't until Vista. Vista implements the same thing but called WSAPoll, an article is here http://blogs.msdn.com/wndp/archive/2006/10/26/WSAPoll.aspx I hope that the next edition of Python supports select.poll on Vista, or at least that someone writes a third-party module fo it. As much as I'd love to do it myself, it's probably beyond me.. i've never used poll before nor written a Python extension. also, i don't have Vista. Thanks From danb_83 at yahoo.com Sun May 11 02:35:47 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Sat, 10 May 2008 23:35:47 -0700 (PDT) Subject: Keeping two lists aligned after processing References: <3695ddb4-373f-4702-bdb8-4d067778fa7a@e53g2000hsa.googlegroups.com> Message-ID: <707cec67-1844-499d-95ef-8937bdcf1e1c@v26g2000prm.googlegroups.com> On May 11, 1:22?am, philly_bob wrote: > > I have a population of five algorithms. Each Alg has a method, > Alg.accuracy(), which calculates its accuracy. Running the accuracy > method on each Alg, I end up with a list of accuracies like [0.75, > 0.10, 0.45, 0.80, 0.45] > > Now I want to store the algorithms and associated accuracies in a > file, in descending order of accuracy. > > Here's how I do it now. There must be a better way! This method is > inelegant, and does not handle at all the issue of what to do with > duplicate accuracies, such as the two different algorithms with 0.45 > accuracies in the example above. It merely saves the first of the > duplicates -- not what I want at all. > > I want to end up with a file: > > 0 AlgD 0.80 > 1 AlgA 0.75 > 2 AlgC 0.45 > 3 AlgE 0.45 > 4 AlgB 0.10 algs.sort(key=Alg.accuracy, reverse=True) From george.sakkis at gmail.com Tue May 13 14:19:32 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 13 May 2008 11:19:32 -0700 (PDT) Subject: I'm stuck in Python! References: Message-ID: <0563506d-bd36-404d-8961-4c4c5d1cc029@t54g2000hsg.googlegroups.com> On May 13, 9:46 am, Sanoski wrote: > Any programming that helps you solve a problem is fun and > recreational. At least, that's how I look at it. I suppose it really > depends on why you're doing it, what your objective is, etc. But I'd > say, why not? You must be new here. It is an AS (Artificial Stupidity) trolling bot, you can safely ignore its posts. > > On May 13, 9:02 am, castiro... at gmail.com wrote: From jkrukoff at ltgc.com Thu May 15 19:11:22 2008 From: jkrukoff at ltgc.com (John Krukoff) Date: Thu, 15 May 2008 17:11:22 -0600 Subject: no inputstream? In-Reply-To: References: <87lk2ba4b4.fsf@mulj.homelinux.net> <8d566db4-c626-491f-82e4-303308c5b8da@25g2000hsx.googlegroups.com> Message-ID: <1210893082.3312.2.camel@jmk> On Thu, 2008-05-15 at 15:35 -0700, max wrote: > On May 15, 6:18 pm, MRAB wrote: > > On May 15, 9:00 pm, max wrote: > > > > > you're right, my java implementation does indeed parse for Id3v2 > > > (sorry for the confusion). i'm using the getrawid3v2() method of this > > > bitstream class (http://www.javazoom.net/javalayer/docs/docs0.4/ > > > javazoom/jl/decoder/Bitstream.html) to return an inputstream that then > > > i buffer and parse. apologies if i misrepresented my code! > > > > > back to python, i wonder if i'm misusing the mutagen id3 module. this > > > brief tutorial (http://www.sacredchao.net/quodlibet/wiki/Development/ > > > Mutagen/Tutorial) leads me to believe that something like this might > > > work: > > > > > from mutagen.mp3 import MP3 > > > id3tags = MP3(urllib2.urlopen(URL)) > > > > > but this gives me the following TypeError: "coercing to Unicode: need > > > string or buffer, instance found". does this mean i need to convert > > > the "file-like object" that is returned by urlopen() into a unicode > > > object? if so, do i just decode() with 'utf-8', or is this more > > > complex? as of now, doing so gives me mostly "No such file or > > > directory" errors, with a few HTTP 404s. > > > > [snip] > > I think it's expecting the path of the MP3 but you're giving it the > > contents. > > cool, so how do i give it the path, if not in the form of a URL > string? maybe this is obvious... > -- > http://mail.python.org/mailman/listinfo/python-list It doesn't look like you can, with mutagen. So, time to find a different library that supports arbitrary file objects instead of only file paths. I'd suggest starting here: http://pypi.python.org/pypi?%3Aaction=search&term=id3&submit=search Possibly one with actual documentation, since that would also be a step up from mutagen. -- John Krukoff Land Title Guarantee Company From 42flicks at gmail.com Tue May 13 17:34:38 2008 From: 42flicks at gmail.com (Mike) Date: Wed, 14 May 2008 09:34:38 +1200 Subject: feedparser In-Reply-To: <1a285875-2cfb-49ea-bb5f-2345dc10ccaa@a23g2000hsc.googlegroups.com> References: <2b54d4370805130330m59602387g9f59b3f93097ca3d@mail.gmail.com> <1a285875-2cfb-49ea-bb5f-2345dc10ccaa@a23g2000hsc.googlegroups.com> Message-ID: <2b54d4370805131434i20b84444peee962a8566c0db6@mail.gmail.com> On Tue, May 13, 2008 at 11:16 PM, wrote: > On May 13, 6:06 am, "Gabriel Genellina" > wrote: > > En Tue, 13 May 2008 07:30:44 -0300, Mike <42fli... at gmail.com> escribi?: > > > > > > > > > > > > > I'm trying to use the feedparser module (http://www.feedparser.org/). > > > > > Is it possible to use this without running the setup program? > > > > > I don't see why not, seems like I'm missing something obvious. > > > > > My directory structure is: > > > > > myprogram.py > > > /feedparser > > > /feedparser.py > > > > > I know I can install the module in the modules directory but would > like > > > to > > > avoid this for two reasons: I'm only using it for the one project so > > > would > > > like to keep it seperate, and if I move to a shared host I may not be > > > allowed to install additional modules (not sure if this is correct > > > though). > > > > The easiest way would be to put the single module feedparser.py in the > > same directory as your program (I don't completely get your reasons not > > > to do that). OR put feedparser.py in some other directory that is > already > > listed in sys.path. OR add the directory containing feedparser.py to > > sys.path, just at the beginning of your program. > > > > > I've tried: > > > > > import feedparser > > > > > import feedparser.feedparser > > > > > from feedparser import feedparser > > > > > What am I doing wrong? :) > > > > *IF* the directory 'feedparser' were a package (that is, if it contained > a > > file __init__.py), then that last import statement would be valid. But I > > > don't reccomend doing this; you're changing the module's environment. > > > > -- > > Gabriel Genellina- Hide quoted text - > > > > - Show quoted text - > > > I've overlooked the fact there is no _init_.py, I was expecting it to behave as a package. I'll put the file in my current directory as you suggested. Thanks for the explanation, it was very helpful and much appreciated. -------------- next part -------------- An HTML attachment was scrubbed... URL: From Lie.1296 at gmail.com Sun May 18 02:44:18 2008 From: Lie.1296 at gmail.com (Lie) Date: Sat, 17 May 2008 23:44:18 -0700 (PDT) Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <7ee5dffd-df8f-46f0-bd78-c81ac0418a9a@d77g2000hsb.googlegroups.com> <65ef773e-a1c3-4adb-a18b-e8b8451efe5e@b5g2000pri.googlegroups.com> <68trmmF2vjivnU1@mid.uni-berlin.de> <68tuhfF2unducU1@mid.uni-berlin.de> <68tulsF2unducU2@mid.uni-berlin.de> <68u1lqF2sv8gjU1@mid.uni-berlin.de> <6ed29b01-30c8-455f-b0be-2b5343e506da@p39g2000prm.googlegroups.com> <2f97dd8d-d2a7-4d2c-910b-047e8db29a1c@f63g2000hsf.googlegroups.com> Message-ID: <8c9a70fb-4f2b-46df-91b0-e979e4221108@u6g2000prc.googlegroups.com> On May 16, 3:58?am, "bruno.desthuilli... at gmail.com" wrote: > On 15 mai, 19:30, Lie wrote: > > > > > On May 15, 4:08 am, "bruno.desthuilli... at gmail.com" > > > wrote: > > > On 14 mai, 08:08, Lie wrote: > > > > > On May 14, 12:51 pm, Lie wrote: > > > > > > And your 8 by 8 cross compiler doesn't impress me at all, they're all > > > > > based on x86/IA-32 architecture which is quite similar, no PowerPC, > > > > > SPARC, ARM, no other CISC or RISC architecture. And your compiler is a > > > > > single language compiler instead of three dimensional compiler that > > > > > GCC is (cross platform, cross target platform, cross language). > > > > > And to add, I also need to mention that Python doesn't need to be > > > > compiled at all, > > > > No language needs compilation - it's an implementation problem, not a > > > language problem. Now all the Python's implementations I know do use > > > compilation (to byte-code). > > > > its py and pyo file is architecture independent. > > > > True, but this is not strictly related to being compiled or not. > > > It's true, it's implementation problem whether a language is compiled > > or not, but what I was emphasizing was that Python's code is > > architecture independent at all stages (that is visible to the user > > and the programmer), on the other hand, a compiled code is a compiled > > code is a compiled code, > > Ever wondered what all these .pyc files were ? > > > it cannot be architecture independent without > > packing multiple binaries in the same executable (like in Macintosh's > > universal binary) or using an emulation (with huge overheads) or at > > least using a compatibility layer (which doesn't always work) and all > > this is done in the layer that is visible to user and programmer > > (programmer having to compile against everything and user having to > > download the correct executable) instead of being done in a platform > > independent way that interpreted language like Python have. > > Python is not interpreted, because being interpreted is a feature of > an implementation, not of a language. And so far, no known Python > implementation is (strictly speaking) interpreted - they all compile > to byte-code. "compiled" doesn't necessarily imply "compiled to > platform native binary code", you know. That's beside the point, the point is about platform independentness of the .py file. When I call Python is interpreted, I meant that the CPU doesn't directly interpret python codes (in most Python implementation). > Ok, this may look like a bit on the splitting hairs side. But may I > remind you that to run ever a .pyc file, you do need to have the > Python runtime (VM + quite a lot of libs) installed one way (normal > install) or another (packed in something that looks like an ordinary > "executable" - whatever this means for the target platform) ? OTHO, > it's true that a .pyc file is platform-independant ?- it just requires > the correct versions of quite a lot of platform-dependant binaries. > Wait... Isn't this code some kind of a "visible to the user and > programmer" "compatibilty layer" ? With the same bit on being on the splitting hair side: It's the same with msvcrt in C or msvbvm60 in VB, programming language runtime is invisible to the user, it's visible to the system administrator (which, in many cases is also the user though). It is, however, invisible to both the user and the programmers. From pavlovevidence at gmail.com Fri May 23 04:07:39 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 23 May 2008 01:07:39 -0700 (PDT) Subject: Decorator metaclass References: <219a475b-c6e3-4128-98bc-d73fd215ce67@w7g2000hsa.googlegroups.com> Message-ID: <3372d0a4-84c3-44ae-abf6-f431cb5b1164@8g2000hse.googlegroups.com> On May 22, 10:28 pm, thomas.karol... at googlemail.com wrote: > Hi, > I would like to create a Decorator metaclass, which automatically > turns a class which inherits from the "Decorator" type into a > decorator. > A decorator in this case, is simply a class which has all of its > decorator implementation inside a decorator() method. Every other > attribute access is being proxied to decorator().getParent(). > > Here's my attempt: You got deep stuff going on there, chief, and some of it's wrong. I'll try to point it out. > ------------------------------------------------------- > from new import classobj > > class DecoratorType(type): > def __new__(cls, name, bases, dct): > dct2 = {} > for key, val in dct.iteritems(): > dct2[key] = val First of all, you can just do dct2 = dct.copy(). Second, since you never use dct again, even copying it is unnecessary. > # create a new class which will store all of the implementation > impl = classobj('%sImpl'%name,(),dct2) classobj creates an old-style class, and I'm pretty sure you don't want to do that. To create a new-style class, use type: impl = type('%sImpl'%name,(),dct) > # update the old class to implement this implementation > def __init__(self, *args, **dargs): > object.__setattr__(self, '__impl', impl(*args, **dargs)) As your code stands now, object.__setattr__ isn't necessary here; just using self.__impl = impl(*args,**dargs) should work fine. I'm guessing you intend to override __setattr__ later? If you do use object.__setattr__, I suggest that you might want to call the superclass's __setattr__ instead of object's. I imagine in this case the superclass will rarely want to override __setattr__ itself, but in general it's a good idea. In this particular circumstance, we don't yet have the class object (it doesn't come till after calling type.__new__) but we do have the parent class. So you might consider changing the definition of __init__ to this: basecls = bases[0] if bases else object def __init__(self, *args, **dargs): basecls.__setattr__(self, '__impl', impl(*args, **dargs)) > def decorator(self): > return object.__getattribute__(self,'__impl') Again, consider changing it to def decorator(self): return basecls.__getattribute(self,'__impl') > def __getattribute__(self, attr): > if attr=="decorator": > return object.__getattribute__(self,'decorator') > return getattr(object.__getattribute__(self, 'decorator') > ().getParent(), attr) > dct = {} > dct['__init__'] = __init__ > dct['decorator'] = decorator > dct['__getattribute__'] = __getattribute__ > > return type.__new__(cls, name, bases, dct) > > class Decorator(object): > __metaclass__ = DecoratorType Parenthetical: I don't normally recommend this style, since it obscures the fact that you're using a custom metaclass to the user. That is something the user probably would benefit from knowing, if for no other reason than so they can make a mental note about where to look first if something goes wrong. I prefer to make the user use the __metaclass__ attribute. However, I could see it being desirable for some cases where you're trying to be as transparent as possible, and indeed it looks as if that's your goal here. > class HBar(Decorator): > def __init__(self, number): > Decorator.__init__(self) Ok, at this point you have to ask yourself what you want to do, because the solution you choose will involve trade-offs. You will note that Decorator does not define __init__. In fact, object.__init__ will be called, which does nothing. If you think that all classes with DecoratorType as their metaclass will be a direct subclass of Decorator, you can get away with not calling Decorator.__init__ at all. However, this can cause problems if a user wants to define their own base class with an __init__ that does something (either by using the __metaclass__ attribute, or by subclassing a Decorator subclass). In that case, you will have to make arrangements to pass the decorator object to the superclass instead of the decorated. This can be pretty hairy, and it beyond the scope of this reply. To do it completely transparently, your decorated class will probably have to maintain a reference to its decorator, and will also have to derive from a base class that delegates any method calls to the superclass of the decorator. (Phew.) That won't be as easy as it sounds. > self._number = number > def inc(self): > self._number += 1 > def p(self): > print self._number > > hbar = HBar(10) > for each in dir(hbar.decorator()): > print each > > hbar.decorator().p() > hbar.decorator().inc() > hbar.decorator().p() > ------------------------------------------------------- > Unfortunately this does not work. The newly defined __init__ method > inside __new__, does a call to impl(*args, **dargs). However, since > the HBar.__init__ calls the Decorator.__init__ method, but the > HBar.__init__ method no longer resides inside HBar, but rather inside > HBarImpl (which is no longer a subtype of Decorator), the compiler > complains that Decorator.__init__ is not being called with a Decorator > instance as its first argument (which is true). > I tried changing the definition of impl inside __new__ to have > Decorator as one of its bases, but then for some reason impl(*args, > **dargs) asks for 4 arguments (just like __new__) and I have no clue > as to why that happens. I believe it's happening because you mixed old-style and new-style classes. But it's not the right solution anyway. > Any help on this? Probably the best piece of advice is "Don't try to use Decorator pattern". :) Seriously, you might want to see what other people have done in similar cases. This stuff is tricky to get right, so maybe you should shamelessly ride the coattails of someone who already ran into all the issues. One example I can think of is the ZODB Persistent class (it's a proxy class, so some of the same issues are involved). Perhaps searching Python cookbook for some proxy or decorator class recipes will give you ideas. Carl Banks From upton at virginia.edu Mon May 19 23:59:32 2008 From: upton at virginia.edu (Dan Upton) Date: Mon, 19 May 2008 23:59:32 -0400 Subject: Python and Flaming Thunder In-Reply-To: <3650313b-fe8d-4beb-bfbd-2748757233e2@p25g2000pri.googlegroups.com> References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <5b0e3f70-afde-4480-8713-e7113b1250d7@x35g2000hsb.googlegroups.com> <1f537717-00d0-48ee-99b6-7125b96a6133@t12g2000prg.googlegroups.com> <68t4o0F2vaoncU1@mid.uni-berlin.de> <2a32179a-9439-449c-bd07-fff6a4075aee@s50g2000hsb.googlegroups.com> <7ee5dffd-df8f-46f0-bd78-c81ac0418a9a@d77g2000hsb.googlegroups.com> <65ef773e-a1c3-4adb-a18b-e8b8451efe5e@b5g2000pri.googlegroups.com> <20080514223033.0ec9fff0.johnjsal@NOSPAMgmail.com> <3650313b-fe8d-4beb-bfbd-2748757233e2@p25g2000pri.googlegroups.com> Message-ID: <5504f9ac0805192059j5d14c6c6sbf12984faf5da3ef@mail.gmail.com> On Mon, May 19, 2008 at 11:20 PM, Dave Parker wrote: > > For another example, I've always preferred languages that are English- > like because it's easier to return to your code after several years > and still know what you were doing (and it's easier for someone else > to maintain your code). > Unless of course you use reasonable variable names and have good comments in your code. I don't think figuring out well-documented C code would be any easier if it were in a more English-like syntax--IMO, it's usually the understanding the interfaces or figuring out what's going on in functions that makes reading someone else's code tricky, not the difference between "x=" and "set x to." From ndbecker2 at gmail.com Wed May 21 12:54:32 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Wed, 21 May 2008 12:54:32 -0400 Subject: [ctypes] convert pointer to string? References: <5349ef25-2900-4706-b6ab-f293da263eb9@m3g2000hsc.googlegroups.com> Message-ID: marek.rocki at wp.pl wrote: > Neal Becker napisa?(a): >> In an earlier post, I was interested in passing a pointer to a structure >> to fcntl.ioctl. >> >> This works: >> >> c = create_string_buffer (...) >> args = struct.pack("iP", len(c), cast (pointer (c), c_void_p).value) >> err = fcntl.ioctl(eos_fd, request, args) >> >> Now to do the same with ctypes, I have one problem. >> >> class eos_dl_args_t (Structure): >> _fields_ = [("length", c_ulong), >> ("data", c_void_p)] >> ... >> args = eos_dl_args_t() >> args_p = cast(pointer(args), c_void_ptr).value >> fcntl.ioctl(fd, request, args_p) <<< May fail here >> >> That last may fail, because .value creates a long int, and ioctl needs a >> string. >> >> How can I convert my ctypes structure to a string? It _cannot_ be a >> c-style 0-terminate string, because the structure may contain '0' values. > > Hello. I'm not completely sure what your problem is ("may fail" is not > a good description. Does it fail or does it not?). If you want a > pointer to a structure as the third argument to ioctl, this would be > imho the easiest way to do it with ctypes: > >> class eos_dl_args_t(Structure): >> _fields_ = [("length", c_ulong), ("data", c_void_p)] >> args = eos_dl_args_t() >> fcntl.ioctl(fd, request, byref(args)) > Seems to be a problem with that: ---> 59 err = fcntl.ioctl(eos_fd, request, byref(args)) 60 TypeError: an integer is required From malaclypse2 at gmail.com Wed May 21 16:44:29 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 21 May 2008 16:44:29 -0400 Subject: Bug in floating-point addition: is anyone else seeing this? In-Reply-To: References: Message-ID: <16651e80805211344h3f2a9227n79420dc012d62f06@mail.gmail.com> On Wed, May 21, 2008 at 4:34 PM, Dave Parker wrote: > On May 21, 12:38 pm, Mark Dickinson wrote: > >> >>> a+0.999 # gives expected result >> 9999999999999998.0 >> >>> a+0.9999 # doesn't round correctly. >> >> 10000000000000000.0 > > Shouldn't both of them give 9999999999999999.0? My understand is no, not if you're using IEEE floating point. > I wrote the same program under Flaming Thunder: > > Set a to 10^16-2.0. > Writeline a+0.999. > Writeline a+0.9999. > > and got: > > 9999999999999998.999 > 9999999999999998.9999 You can get the same results by using python's decimal module, like this: >>> from decimal import Decimal >>> a = Decimal("1e16")-2 >>> a Decimal("9999999999999998") >>> a+Decimal("0.999") Decimal("9999999999999998.999") >>> a+Decimal("0.9999") Decimal("9999999999999998.9999") >>> -- Jerry From kyosohma at gmail.com Fri May 9 09:09:37 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 9 May 2008 06:09:37 -0700 (PDT) Subject: Pythonwin References: Message-ID: <11c8a80e-41bb-4cea-88d6-c9515e1a9d13@j22g2000hsf.googlegroups.com> On May 9, 5:30?am, Clive_S wrote: > Hi > > I am trying to use Python with ArcGIS. > > I have installed Python 2.4. I have an icon for IDLE and command line. > I do not see Python PythonWin. > > How do you install or launch pythonwin?? > > Thanks > > Clive I have PythonWin installed in my Start Menu --> Programs --> Python 2.5. I may have installed the ActiveState version though. Just check if it's there on your system and if not, you can follow Niklas's advice. Mike From sturlamolden at yahoo.no Sun May 18 19:19:03 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Sun, 18 May 2008 16:19:03 -0700 (PDT) Subject: How do *you* use Python in non-GUI work? References: <20080518182022.990193bd.johnjsal@NOSPAMgmail.com> Message-ID: On May 19, 12:20 am, John Salerno wrote: > Hey all. Just thought I'd ask a general question for my own interest. Every time I think of something I might do in Python, it usually involves creating a GUI interface, so I was wondering what kind of work you all do with Python that does *not* involve any GUI work. This could be any little scripts you write for your own benefit, or what you do at work, if you feel like talking about that! :) Back in the 'old days' of Unix, programs tended not to be small, could only do one thing, and did it well. They had no gui, and all interaction came from command line options. The programs were invoked from the command line, and input and output were piped from one program to another (input on stdin, output on stdout). Today, it is expected that programs should have a GUI. The majority do not even know how to use a program that does not have one. As a result, programs have become poorer at interacting with other, and become bloated and grown monolithic. Today's programs are monolithic beasts spanning tens or hundreds of megabytes, where the bulk of the code duplicates functionality found in every other program. I prefer that a program has no GUI if it does not need user interaction beyond what can be easily accomplished from the command line. Sometimes I think gui becomes overwhelming, and obfuscates the real functionality in the program. When I write program's for others people, a GUI is usually expected. But when I get requests for adding new functionality to such a program, it tends to be for unimportant GUI stuff rather than real functionality to the program. To answer your question: I only add GUIs when I have to. But because it seems that people are becoming computer illiterate, incapable of using a keyboard, and only comfortable with a certain point-and-click input device, it tends to be most of the time now. From gpanterov at yahoo.com Tue May 13 14:39:27 2008 From: gpanterov at yahoo.com (Georgy Panterov) Date: Tue, 13 May 2008 11:39:27 -0700 (PDT) Subject: list index out of range Message-ID: <46657.69485.qm@web50406.mail.re2.yahoo.com> I am a relatively new python user. I am writing an economic simulation of a card-game. The simulation runs fine for a few iteration but then it gives an error of "list index out of range." The strange thing is that it will sometimes run for 10 iterations sometimes for only a few and sometimes won't run at all (seemingly arbitrary). Here is some of the code: for _ in range(100): handA=deal_hand(DECK) #deals 2 'hole' cards from a DECK handB=deal_hand(DECK) print handA print handB deal_flop(handA,handB,DECK) #appends 3 cards to handA and handB deal_current(handA,handB,DECK) #appends one more card deal_rake(handA,handB,DECK) #appends one more card DECK.extend(list(set(handA+handB))) #returns the cards to the DECK print winner(handA,handB) #returns 0-draw 1 -playerA win, 2-playerB win The error message is : ['08C', '10H'] ['07S', '03C'] -------- ['06C', '02H'] ['04D', '12S'] -------- ['11H', '14S'] ['06S', '04S'] -------- Traceback (most recent call last): File "G:\Other Stuff\POKER4.py", line 267, in handB=deal_hand(DECK) File "G:\Other Stuff\POKER4.py", line 13, in deal_hand HAND.append(deck[i]) IndexError: list index out of range In this case it ran 3 times. It will sometimes run for up to 9-10 times. It seems to be arbitrary but I can't get it to run more than 12 times. Here is the code for the --deal_***-- functions: def deal_hand(deck): HAND=[] for _ in range(2): i=random.randint(0,len(deck)) #produces a random card from the deck HAND.append(deck[i]) # appends the card to the players' hand list deck.remove(deck[i]) #removes the card from the deck return HAND def deal_flop(hand1,hand2,deck): for _ in range(3): i=random.randint(0,len(deck)) hand1.append(deck[i]) hand2.append(deck[i]) deck.remove(deck[i]) I would appreciate any help with this Thanks George Send instant messages to your online friends http://uk.messenger.yahoo.com From arnodel at googlemail.com Tue May 20 03:21:11 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 20 May 2008 08:21:11 +0100 Subject: explain this function to me, lambda confusion References: <5cc7ef7a-dd21-4772-a7e3-765410f810bb@l17g2000pri.googlegroups.com> <081fe61b-820b-4512-80a9-8a0805f3ce55@k13g2000hse.googlegroups.com> <74ce1ffa-0031-4101-8792-5f2ba7f22bca@b64g2000hsa.googlegroups.com> <48327914$0$30041$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers writes: > Paul McGuire a ?crit : >> On May 19, 11:04 am, Arnaud Delobelle wrote: >>> Paul McGuire writes: >>> >>> [...] >>> >>> Could you use it as a decoratore instead? >>> >>> integer = Word("0123456789") >>> >>> @integer.setParseAction >>> def parse_integer(tokens): >>> return int(tokens[0]) >>> >>> I could make your grammar clearer, because you don't mix it with >>> processing code... and no need for lambdas! >> >> What a sexy little idiom! You could really apply this to any API >> method that accepts a callable as a single argument, and pyparsing >> actually has several of these: >> >> setParseAction >> addParseAction >> setFailAction >> setDebugActions >> >> (Unfortunately, setDebugActions requires 3 callables for its arguments >> - one to be run when an expression is about to be parsed, one to be >> run after parsing is complete, and one to be run if the expression >> fails to be parsed. So setDebugActions can't be used in this >> decorator manner.) > > You just have to provide three decorators instead, one for each callback. > >> >> Using these methods as decorators deviates from the typical decorator >> usage model as I understand it - instead of wrapping the provided >> function within some enclosing setup/teardown code (like lock/unlock, >> or open-file/close-file, or begin-transaction/commit-transaction), and >> then returning the created wrapper function, the decorator usage you >> propose is one in which the decorator uses the provided function with >> some side-effect (such as setting a property), but then just returns >> the original function. > > This is already a well-known decorator pattern. It's used in CherryPy > to mark methods that are exposed as request handlers. Actually, IIRC the decorator provided by CherryPy is something like (names are probably wrong, as I haven't looked at CherryPy for a while): def exposed(f): f.is_exposed = True return f So it doesn't mutate anything else than the function that it decorates, but changes slightly how the world sees that function. This is in line with classic decorators such as staticmethod, classmethod, etc. -- Arnaud From bockman at virgilio.it Sun May 4 13:18:42 2008 From: bockman at virgilio.it (Francesco Bochicchio) Date: Sun, 04 May 2008 19:18:42 +0200 Subject: Determine socket family at runtime References: <30bafd19-c822-41b6-8e17-ea004ba30821@t54g2000hsg.googlegroups.com> Message-ID: On Sun, 04 May 2008 08:49:55 -0700, Giampaolo Rodola' wrote: > Hi there, > since the socket.socket.family attribute has been introduced only in > Python 2.5 and I need to have my application to be backward compatible > with Python 2.3 and 2.4 I'd like to know how could I determine the > family of a socket.socket instance which may be AF_INET or AF_INET6. > Is there some kind of getsockopt() directive I could use? > For now I've been able to determine the family by using: > > # self.socket = a connected socket.socket instance > ip, port = self.socket.getsockname()[0:2] > af = socket.getaddrinfo(ip, port)[0][0] > > ...but I'd like to know if some other solution is preferable. > > > > Thanks. > > > --- Giampaolo > http://code.google.com/p/pyftpdlib Ciao, what about wrapping the socket type and adding a 'family' attribute to the base socket class? Something like: class SocketWrapper(socket.socket): def __init__(self, family, type, proto=0): socket.socket.__init__(self, family, type, proto) self.family = family then you have just to create the sockets with SocketWrapper insetead of socket.socket. For the rest of your code it would not matter, and then you are sure to always have a .family attribute. Ciao ---- FB From lew at lewscanon.com Sat May 10 17:39:42 2008 From: lew at lewscanon.com (Lew) Date: Sat, 10 May 2008 17:39:42 -0400 Subject: The Importance of Terminology's Quality In-Reply-To: References: <68i6b5F2soauaU1@mid.individual.net> <68l2piF2sv620U1@mid.individual.net> Message-ID: Sherman Pendley wrote: > Lew writes: > >> You guys are off topic. None of the million groups to which this >> message was posted are about netiquette. > > Netiquette has come up at one point or another in pretty much every > group I've ever read. It's pretty much a universal meta-topic. Good, then please have the courtesy not to include comp.lang.java.programmer in the distribution for this thread any longer. -- Lew From donnyf at gmail.com Thu May 8 21:34:06 2008 From: donnyf at gmail.com (donnyf at gmail.com) Date: Thu, 8 May 2008 18:34:06 -0700 (PDT) Subject: Using Python to verify streaming tv/radio station links References: <2e6baf9b-09d3-430e-9e01-cd56ec6e1a33@t54g2000hsg.googlegroups.com> Message-ID: <8f8eb5ff-f0b4-4123-8185-904f611c3824@m44g2000hsc.googlegroups.com> On Apr 29, 10:11 am, alexel... at gmail.com wrote: > Hey! > > With regards checking feeds, look into urllib (maybe) and the httplib > (definitely). They /could/ offer some sort of information regarding > the activity of your feeds. Without knowing anything about the > streaming protocols I wouldn't suggest my methods to necessarily be > the most helpful. You could, at least [maybe], establish whether a > feed is active if it can return a HTTP 200 response. If that's a > sufficient check I would suggest that httplib is the place to start. > > Alex. Thanks for the reply. I'm not so sure that httplib is going to work as most of these are not http urls. Here's a handful of examples that maybe someone could use to give me an idea of how to accomplish what I'm trying to do. Here's a list of the various types of media links I have in my database (all working): http://www.dradio.de/streaming/dkultur_hq_ogg.m3u http://200.29.92.21/ucvtv http://www.ampmedia.org/asx/marina25.asx http://www.jazz.fm/streaming/JAZZFM91.pls mms://144.122.56.15/ODTU-TV rtsp://200.79.7.137/broadcast/tv.rm The httplib approach may work the http urls, but what about the mms and rsp 'protocols'? Please remember that I only know enough to be dangerous and that I'm much more a hacker than I am a programmer. As always, any help is greatly appreciated! From wizzardx at gmail.com Sun May 4 08:22:46 2008 From: wizzardx at gmail.com (David) Date: Sun, 4 May 2008 14:22:46 +0200 Subject: Script Optimization In-Reply-To: <18c1e6480805040521w2756b4eehef4d456837aa875@mail.gmail.com> References: <6ed749de-1a7d-4db5-a229-d3400da4d24b@f24g2000prh.googlegroups.com> <18c1e6480805040521w2756b4eehef4d456837aa875@mail.gmail.com> Message-ID: <18c1e6480805040522q4dd36701x69bc83f44f5b8cfa@mail.gmail.com> Eh, I forgot the attachment. -------------- next part -------------- A non-text attachment was scrubbed... Name: utils.py Type: text/x-python Size: 5287 bytes Desc: not available URL: From pete.forman at westerngeco.com Tue May 13 05:45:37 2008 From: pete.forman at westerngeco.com (Pete Forman) Date: Tue, 13 May 2008 10:45:37 +0100 Subject: Am I missing something with Python not having interfaces? References: <45de2f7e-484a-4871-bbaa-bf7eed5dfa40@x35g2000hsb.googlegroups.com> <200805080912.29438.onsen-neko@gmx.net> <1210244572.6529.5.camel@jcd-desktop> <200805081911.47081.onsen-neko@gmx.net> <1210267542.8621.16.camel@aalcdl07.lib.unc.edu> Message-ID: I would suggest that using an interface at compile time is not the only approach. Unit tests can be run on classes to check that they do indeed quack. -- Pete Forman -./\.- Disclaimer: This post is originated WesternGeco -./\.- by myself and does not represent pete.forman at westerngeco.com -./\.- the opinion of Schlumberger or http://petef.22web.net -./\.- WesternGeco. From castironpi at gmail.com Thu May 15 10:07:28 2008 From: castironpi at gmail.com (castironpi) Date: Thu, 15 May 2008 07:07:28 -0700 (PDT) Subject: send yield References: <6a19b5bf-ed71-499c-a348-6e26e2f523eb@m45g2000hsb.googlegroups.com> <482c42d9$0$9669$426a34cc@news.free.fr> Message-ID: <1fc6c5b4-f4e6-4a1c-8ab0-b07d7f269a66@l42g2000hsc.googlegroups.com> On May 15, 9:04?am, Bruno Desthuilliers wrote: > castironpi a ?crit : > > > Why can't I write this? > > Because one or more of the "t", "h", "i", "s" keys are missing from your > keyboard ? No; they're all here. From castironpi at gmail.com Tue May 13 09:44:04 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 13 May 2008 06:44:04 -0700 (PDT) Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <2b66a86e-5a05-4262-b3c9-4703b0ae3372@d1g2000hsg.googlegroups.com> <5b0e3f70-afde-4480-8713-e7113b1250d7@x35g2000hsb.googlegroups.com> <1f537717-00d0-48ee-99b6-7125b96a6133@t12g2000prg.googlegroups.com> <68t4o0F2vaoncU1@mid.uni-berlin.de> Message-ID: <3d8cb22c-5b5a-49c1-9ee0-9c09ed91106a@k37g2000hsf.googlegroups.com> On May 13, 8:32?am, Dave Parker wrote: > > Don't let yourself be irritated by castironpi > > I'm not the sort to get irritated by anyone. ?There is value in all > interaction. ?Flaming Thunder is itself the averaging of interactions > with many computer languages and conversations with many people, so as > to create a language that allows people to tell a computer what they > want it to do, without having to know very much about how the computer > does it. > > On May 13, 3:18?am, "Diez B. Roggisch" wrote: > > > > > Dave Parker wrote: > > > On May 12, 7:20?pm, castiro... at gmail.com wrote: > > >>Yes, I am trying to visualize something. > > > > If it is related to making furniture comfortable for humans, have you > > > considered painting the furniture with thermochromic paint ( > > >http://en.wikipedia.org/wiki/Thermochromism)??It changes color in > > > response to temperature, which in part is determined by how hard a > > > body is pressed against it because close contact tends to trap heat. > > > An evenly distributed color might indicated evenly distributed > > > pressure. > > > Don't let yourself be irritated by castironpi - he's the virtual equivalent > > of a mumbling mad man in this group. Ignorance serves best as remedy - and > > getting a filter to work, as I did (so I only see his postings being > > quoted... a huge relief!) > > > Diez- Hide quoted text - > > - Show quoted text - I got hung-up on your sailboat and it took me to coffee. But I return empty-handed, and castironpi does not bother me. All I try to do in life is write video games. I am not convinced that the colorspace occupies three dimensions necessarily. But I do like sailboats and furniture. I am into city planning, roadways, infrastructure, but don't work - too- hard. Furniture can be pretty stock and utility on the micro level--- there's just been runs on the banks before to microize to certain energy/mass/volume/metabolism levels. People like stuff and pull. If I can get a word in, I also like to distribute economy, and microize currency. So long as currency stays current, nobody minds. Do you need something done... or said? From mccredie at gmail.com Fri May 9 19:06:17 2008 From: mccredie at gmail.com (Matimus) Date: Fri, 9 May 2008 16:06:17 -0700 (PDT) Subject: regexp help References: <834d8448-5d6a-4f49-9be6-6501a0b5fd92@k37g2000hsf.googlegroups.com> Message-ID: On May 9, 3:19 pm, globalrev wrote: > i want to a little stringmanipulationa nd im looking into regexps. i > couldnt find out how to do: > s = 'poprorinoncoce' > re.sub('$o$', '$', s) > should result in 'prince' > > $ is obv the wrng character to use bu what i mean the pattern is > "consonant o consonant" and should be replace by just "consonant". > both consonants should be the same too. > so mole would be mole > mom would be m etc >>> import re >>> s = s = 'poprorinoncoce' >>> coc = re.compile(r"(.)o\1") >>> coc.sub(r'\1', s) 'prince' Matt From deets at nospam.web.de Sat May 24 08:43:56 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 24 May 2008 14:43:56 +0200 Subject: Popen: NameError: name 'PIPE' is not defined In-Reply-To: References: Message-ID: <69qgseF31lv3aU1@mid.uni-berlin.de> Mathieu Prevot schrieb: > Hi > > I import subprocess and use Popen, but PIPE is not defined. I used > 2.5.1, 2.5.2, Python 2.6a3+ (trunk:63576, May 24 2008, 12:13:40), it's > always the same. What am I missing ? Without showing code, it's hard to know. A guess is: if you use import subprocess then use subprocess.PIPE Or if using from subprocess import Popen make sure to do from subprocess import Popen, PIPE Diez From mcknight0219 at gmail.com Wed May 14 21:31:20 2008 From: mcknight0219 at gmail.com (Jimmy) Date: Wed, 14 May 2008 18:31:20 -0700 (PDT) Subject: create window on panel Message-ID: Hi, all I have been trying to use wxPython to design a GUI that will be displayed on the panel on the top of desktop. that is when the program starts, it will dwell on the panel to display some dynamic information. can anyone tell me in wxPython how to do this? thanks! From castironpi at gmail.com Thu May 8 20:29:57 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 8 May 2008 17:29:57 -0700 (PDT) Subject: pickle problem References: <68g456F2t41nqU1@mid.uni-berlin.de> <97b9fbd1-3725-4a7d-9ecb-1d2af6f35665@y21g2000hsf.googlegroups.com> <68h7p7F2su97jU3@mid.uni-berlin.de> <8763tofpiv.fsf@mulj.homelinux.net> Message-ID: <875ee438-b682-489e-b284-b22620384a75@m44g2000hsc.googlegroups.com> On May 8, 4:35?pm, Hrvoje Niksic wrote: > Marc 'BlackJack' Rintsch writes: > > > On Thu, 08 May 2008 08:55:35 -0700, krustymonkey wrote: > > >> The thing is, I'm not using slots by choice. ?I'm using the standard > >> lib "socket" class, which apparently uses slots. > > > `socket` objects can't be pickled. ?Not just because of the > > `__slot__`\s but because a substantial part of their state lives in > > the operating system's space. > > Of course, if it makes sense to pickle sockets in the application, one > is can do so by defining __getstate__ and __setstate__: > > class Connection(object): > ? ? def __init__(self, host, port): > ? ? ? ? self.host = host > ? ? ? ? self.port = port > ? ? ? ? self.init_sock() > > ? ? def init_sock(self): > ? ? ? ? self.sock = socket.socket() > ? ? ? ? self.sock.connect((host, port)) > ? ? ? ? ... init communication ... > > ? ? def __getstate__(self): > ? ? ? ? # pickle self as a (host, port) pair > ? ? ? ? return self.host, self.port > > ? ? def __setstate__(self, state): > ? ? ? ? # reinstate self by setting host and port and > ? ? ? ? # recreating the socket > ? ? ? ? self.host, self.port = state > ? ? ? ? self.init_sock() I, local, am mystified that you'd want to pickle a socket. It's a live connection, which flies on a pocket dollar. You don't want it on disk, do you? If you're running a net buoy through a cluster somewhere, do you want to drop a server and reconnect? Is Amazon's EC2 up and running? Certainly no one was talking on the internet. Were you? I don't think you hit anything but banks surfing the web, and the American dollar is notoriously stuffy. Pump a wi-fi to a diner, though, and you're just talking more. Where's Usenet? From inhahe at gmail.com Sun May 18 06:37:30 2008 From: inhahe at gmail.com (inhahe) Date: Sun, 18 May 2008 06:37:30 -0400 Subject: morning in Python Message-ID: "inhahe" wrote in message news:... > >>It is not clear that the first (cheapest best) human->computer language >>is a computer language, though if two were orthonormal >in comparison >>to life, Python's fine. Not my first. > > The utterly dry, closed, logical, definitive, hierarchical, consistent, > determinate nature of a computer language is the only thing that will > facilitate anything useful on something as utterly stupid (and not to > mention logical, definite and determined) as a computer. > > I mean it, computers are /really/ stupid. They're literally > stupider than a bug. We just like things we can control. > > The requisites I have for a computer language are: > > Efficiency (speed) > Elegance of syntax > Powerful (conceptual-wise) abstractions > > Python has delicious abstractions that make doing a lot of things really > easy and fun to think about. > Stackless Python adds even more to that with continuations. > Also Python's dynamic (another aspect of being powerful conceptual-wise) > But most of all, I love its syntax. Guido is the awesome. > (BTW, I won't even use any language that uses := for assignment. I just > refuse. I don't care what the language has.) > > The speed/efficiency issue depends on the task at hand. For most things I > use Python. But assembly isn't out of the question, and it's fun to code > in. I also find C/C++ an elegant language. Most things just don't need > that speed. And Python is 50 times easier to code in than C/C++ and 1000 > times easier to debug in. > > I also like C#. > > My ideal language would be a natively compiling cross between C++ and > Python. Objects declared with a type would be statically typed, objects > not declared with a type would be dynamically typed. There would also be > keywords to declare that class names won't be reassigned and class > attributes won't be deleted. Those attributes would be referred to by > offset, not hast table keys. f hast = hash From bruno.42.desthuilliers at websiteburo.invalid Fri May 16 08:19:08 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 16 May 2008 14:19:08 +0200 Subject: class problem, NoneType obj has no attribute In-Reply-To: <10bbf997-3520-4920-b225-8685b98d9079@59g2000hsb.googlegroups.com> References: <10bbf997-3520-4920-b225-8685b98d9079@59g2000hsb.googlegroups.com> Message-ID: <482d7bbc$0$15491$426a74cc@news.free.fr> globalrev a ?crit : > wassup here? > > > 7 > > Traceback (most recent call last): > File "C:\Python25\myPrograms\netflix\netflix.py", line 22, in > > print cust1.getID() > AttributeError: 'NoneType' object has no attribute 'getID' > > > > class customer: 1/ naming convention : class names should be CamelCased 2/ unless you need compatibility with years old Python versions, use newstyle classes class Customer(object): > def __init__(self, ID, movies): > self.ID = ID > self.movies = movies 3/ naming conventions : ALL_UPPER_NAMES denote (pseudo) constants def __init__(self, id, movies): self.id = id self.movies = movies > def getID(): > return self.ID > > def getMovies(): > return self.movies 4/ Python has support for computed attributes, so you just don't need these getters. > > import os > import customer > import movie > > mv1 = open('C:\\Python25\\myPrograms\\netflix\\mv1exp2.txt', 'r+') > mv1str = mv1.read() > > print mv1str.count(',5,') > > cust1 = customer.__init__('12',['1','435','2332']) __init__ is automagically called on instanciation, so you don't have to call it yourself. And FWIW, your __init__ returns None. cust1 = Customer('12', ['1', '435', '2332']) > print cust1.getID() print cust1.id From irmen.NOSPAM at xs4all.nl Mon May 12 05:00:06 2008 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Mon, 12 May 2008 11:00:06 +0200 Subject: Best technology for agent/web server architecture In-Reply-To: References: <4823268D.1060602@egenix.com> Message-ID: <4828071a$0$14343$e4fe514c@news.xs4all.nl> Gabriel Genellina wrote: >> 2008/5/8 M.-A. Lemburg : >> >>> SOAP would be a good choice if you want to send to data to other >>> servers as well, e.g. Java-based ones. >>> >>> XML-RPC and JSON are better for simple data structures. >>> >>> If you have control over both client and server and don't >>> need to bother with other backends or frontends, Python >>> pickle is the best choice. > > En Fri, 09 May 2008 05:41:07 -0300, Florencio Cano escribi?: > >> I have control over agent and client but I'm not sure how to use >> pickle for this task. Do you suggest to pickle the objects that I want >> to send and send it over a usual socket? I have searched a bit in >> Google and I have seen that Pickle is insecure by default. What do you >> think about this? > > "insecure" means that someone could build a specially crafted pickle able to run arbitrary code on the unpickling environment. One way to avoid that is to only accept pickles from trusted sources: using SSL by example. > While Pyro (http://pyro.sourceforge.net) uses pickle by default, it is well understood that you'll have to deal with a potential security issue if your server is open to untrusted/uncontrolled clients. Pyro provides several things that could help you here: - you can define a connection authenticator that checks client IP and/or passphrases - you can switch to an XML based serialisation protocol (courtesy of gnosis tools) - you can run Pyro over SSL and let SSL deal with authentication/encryption/... Cheers Irmen de Jong From ggpolo at gmail.com Sat May 10 11:25:41 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Sat, 10 May 2008 12:25:41 -0300 Subject: People still using Tkinter? In-Reply-To: References: Message-ID: 2008/5/10 Zentrader : > I like New Mexico Tech's site as well. Also, take a look at the PMW > extension for additional widgets, and TkTable and/or TableListWrapper. > http://infohost.nmt.edu/tcc/help/pubs/tkinter/ There is also Tile, or Ttk since Tk 8.5, if you are interested in extensions too. Apparently there are three Tile wrappers now, two are incomplete (sorry for saying that): http://bruno.thoorens.free.fr/ttk.html -- Missing Treeview, big part of ttk styling, maybe other things and it is not only a ttk wrapper (there are other things besides it) http://bugs.python.org/file10010/Tile.py -- Missing several methods in Treeview, big part of ttk styling and maybe something else. And there is also one I'm doing, that I expect to be complete: http://gpolo.ath.cx:81/projects/ttk_to_tkinter/ Documentation and samples are still lacking, but I'm working on them. And I haven't tested it under Windows, so I invite you all to test it. Regards, -- -- Guilherme H. Polo Goncalves From notbob at nothome.com Thu May 22 12:29:37 2008 From: notbob at nothome.com (notbob) Date: Thu, 22 May 2008 16:29:37 GMT Subject: php vs python References: <5l%Yj.77$mz3.53@fe101.usenetserver.com> <7xwslnwa3s.fsf@ruckus.brouhaha.com> Message-ID: On 2008-05-21, Paul Rubin wrote: > Knowing lots of languages is good for you. php is probably your > quickest route to getting a rudimentary web app running. Python > is a longer term project. Do both. Good advice. Thank you. nb From pavlovevidence at gmail.com Wed May 14 15:35:17 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 14 May 2008 12:35:17 -0700 (PDT) Subject: list.__len__() or len(list) References: <3fc761710805131718y448ef0b8r67dcc8cf118bc80a@mail.gmail.com> Message-ID: <7d28fc5b-4027-448a-bbff-b92b7aa149f2@x41g2000hsb.googlegroups.com> On May 14, 11:07 am, Nikhil wrote: > Christian Heimes wrote: > > Ian Kelly schrieb: > >> The purpose of obj.__len__() is to implement len(obj), which simply > >> calls it. So obj.__len__() may be faster, but only marginally. The > >> reason to prefer len(obj) is that if you inadvertently pass an object > >> that does not implement __len__, you get the more appropriate > >> TypeError rather than an AttributeError. > > > len(obj) is faster than obj.__len__() for several types like str. In > > general len() is as least as fast __len__(). len() also does some extra > > sanity checks. > > > python2.5 -m timeit "'abc'.__len__()" > > 1000000 loops, best of 3: 0.453 usec per loop > > > python2.5 -m timeit "len('abc')" > > 1000000 loops, best of 3: 0.292 usec per loop > > > Common code paths are already highly optimized. Don't try to be clever > > unless you really understand what happens inside the interpreter. The > > __internal__ methods are called magic methods for a reason. ;) > > > Christian > > Thanks for the useful insight. > Then why to have __len__() internal method at all when the built-in > len() is faster? > I heard, in Python3, this internal method is being pruned/renamed to > something else? Can someone please shed light here? My advice is to think of len() as an operator. Like other operators, it can be overloaded using the __opname__ syntax: -x calls x.__neg__ x+2 calls x.__add__ len(x) calls x.__len__ It's not really an operator: it's a regular built-in function, has no special syntax, and no opcodes associated with it, but in sometimes it helps to think of it as one. Carl Banks From conrad at lewscanon.com.invalid Sun May 25 23:28:50 2008 From: conrad at lewscanon.com.invalid (Lew) Date: Sun, 25 May 2008 23:28:50 -0400 Subject: blogs, longbets.org, and education of sociology In-Reply-To: <1c97ba8a-b758-4891-a3c4-20e462361934@z16g2000prn.googlegroups.com> References: <1c97ba8a-b758-4891-a3c4-20e462361934@z16g2000prn.googlegroups.com> Message-ID: xahlee at gmail.com wrote: > For about the past 10 years, i [sic] have been saying things like > ... fart ignorant ..., often in a > irresponsible and carefree way. ... > Some of these beer drinking f**kheads are simply being a asshole, ... > vandalism. (the tech geekers use in-group slang for this: ?troll?.) Actually, it's argot, not slang. The definition is fairly narrow and well understood. more obscenity: > technology. (note: not reading more motherf**king slashdot or > motherf**king groklaw or more great podcasts on your beatific language > or your postmodernistic f**khead idols) And the temerity of: > (One thing you can do, is actually take a course on philosophy, > history, law, economics, in your local community college.) Yeah, those bastions of intellectual elitism. Plonk, plonk, plonk. -- Lew From notnorwegian at yahoo.se Mon May 19 18:28:48 2008 From: notnorwegian at yahoo.se (notnorwegian at yahoo.se) Date: Mon, 19 May 2008 15:28:48 -0700 (PDT) Subject: this worked before...' '.join([`x x` for x in range(1, 6)]) Message-ID: ' '.join([`x x` for x in range(1, 6)]) anyone can tell me what im doing wrong? From gandalf at shopzeus.com Mon May 12 02:42:01 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Mon, 12 May 2008 08:42:01 +0200 Subject: Is there no single/uniform RDBMS access API module for Python ? In-Reply-To: <3de8e1f70805112243u765fc507v32c5461be34d4077@mail.gmail.com> References: <3de8e1f70805112243u765fc507v32c5461be34d4077@mail.gmail.com> Message-ID: <4827E6B9.3080509@shopzeus.com> Banibrata Dutta ?rta: > Hi, > > Again a noob question. > > Based on this URL http://wiki.python.org/moin/DatabaseInterfaces , is > it correct to conclude that there is no RDBMS agnostic, single/uniform > DB access API for Python ? > Something in the lines of JDBC for Java, DBD for Perl etc. ? > > How is the RDBMS change handled for solutions which need to work with > different RDBMSs ?? http://www.python.org/dev/peps/pep-0249/ From skanemupp at yahoo.se Mon May 5 07:09:53 2008 From: skanemupp at yahoo.se (globalrev) Date: Mon, 5 May 2008 04:09:53 -0700 (PDT) Subject: pygame music, cant read mp3? Message-ID: <30fe7c79-dbac-47bb-9e29-bea61b7c3da8@56g2000hsm.googlegroups.com> http://www.pygame.org/docs/ref/mixer.html import pygame #pygame.mixer.init(frequency=22050, size=-16, channels=2, buffer=3072) //it complained abiout words= so i guess its only the nbrs should be there// pygame.mixer.init(22050, -16, 2, 3072) pygame.mixer.music.load("example1.mp3") pygame.mixer.music.play(loops=1, start=0.0) Traceback (most recent call last): File "C:\Python25\myPrograms\pygameProgs\musicexp.py", line 5, in pygame.mixer.music.load("example1.mp3") error: Couldn't read from 'example1.mp3' From gherron at islandtraining.com Sun May 18 14:45:32 2008 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 18 May 2008 11:45:32 -0700 Subject: Compress a string In-Reply-To: References: Message-ID: <4830794C.4030309@islandtraining.com> Matt Porter wrote: > Hi guys, > > I'm trying to compress a string. > E.g: > "AAAABBBC" -> "ABC" > > The code I have so far feels like it could be made clearer and more > succinct, but a solution is currently escaping me. > > > def compress_str(str): > new_str = "" > for i, c in enumerate(str): > try: > if c != str[i+1]: > new_str += c > except IndexError: > new_str += c > return new_str > > > Cheers > Matt This is shorter and perhaps clearer: def compress_str(str): new_str = "" for c in str: if not new_str or c != new_str[-1]: new_str += c return new_str However, successive appends to a string is inefficient (whereas successive appends to a list are ok), so this is probably more efficient: def compress_str(str): r = [] for c in str: if not r or c != r[-1]: r.append(c) # Build a list of characters return ''.join(r)# Join list into a single string And then building a list in a loop is usually more efficient (and perhaps clearer) if done with a list comprehension: new_str = ''.join([c for i,c in enumerate(str) if not i or str[i-1] != c]) or, maybe clearer as two lines: r = [c for i,c in enumerate(str) if not i or str[i-1] != c] new_str = ''.join(r) Gary Herron From gherron at islandtraining.com Fri May 9 10:45:33 2008 From: gherron at islandtraining.com (Gary Herron) Date: Fri, 09 May 2008 07:45:33 -0700 Subject: Grabbing previous iteration in a dict In-Reply-To: <254bd762-aa57-405b-996c-3856743267f6@l17g2000pri.googlegroups.com> References: <25657e4e-45c2-4a1f-948d-26ac64a75cd7@u6g2000prc.googlegroups.com> <7xabizkdui.fsf@ruckus.brouhaha.com> <254bd762-aa57-405b-996c-3856743267f6@l17g2000pri.googlegroups.com> Message-ID: <4824638D.6080302@islandtraining.com> dannywebster at googlemail.com wrote: > On May 9, 10:48 am, Paul Rubin wrote: > >> dannywebs... at googlemail.com writes: >> >>> I have a dictionary of which i'm itervalues'ing through, and i'll be >>> performing some logic on a particular iteration when a condition is >>> met with trusty .startswith('foo'). I need to grab the previous >>> iteration if this condition is met. I can do something with an extra >>> var to hold every iteration while iterating, but this is hacky and not >>> elegant. >>> >> You cannot rely on the elements of a dictionary being in any >> particular order (dicts are internally hash tables), so the above >> is almost certainly ont what you want. >> > > > Hi - thanks for your reply. How about if I made the dict into a list > (of > which I have done). How would I then reference the previous item? > Can they > be indexed? > -- > http://mail.python.org/mailman/listinfo/python-list > Yes: listOfItems = DICT.items() for i in range(len(listOfItems)): k,v = listOfItems[i] # Current key,value pair if whatever: kPrev,vPrev = listOfItems[i-1] # Previous key,value pair Still, since there is no proscribed order in which the items are placed into the list, I wonder how this can be useful. However, this *does* do what you asked. Gary Herron From castironpi at gmail.com Fri May 16 15:04:30 2008 From: castironpi at gmail.com (castironpi) Date: Fri, 16 May 2008 12:04:30 -0700 (PDT) Subject: morning in Python References: <409ea9f1-9774-4bf2-abac-2daf997bc97f@c65g2000hsa.googlegroups.com> Message-ID: On May 16, 10:58?am, "inhahe" wrote: > I'm not an expert in this but what does it mean to emphasize state? ?It > seems the opposite of that would be a) functional programming, and b) > passing parameters instead of using global or relatively local variables. > And maybe c) coroutines (generators as implemented in Python), although > perhaps coroutines could be said to emphasize state inasmuch as they go out > of their way to capture, objectify and reuse it (Stackless' microthreads, > even moreso). ?And Python seems to be well-noted for implementing some > functional programming methodology, and as for passing parameters it's just > as object-oriented as the rest of them. > > But as I said, I'm not an expert, so let me know if I've gone astray.. > > > > > I have a proposition to ask you all: Python emphasizes state. ?Is it > > true?- Hide quoted text - > > - Show quoted text - What advantages do teams have? in what? over who? when? If they have any use at all, what language is good for them? How do programming teams interact? It sounds fun. I'm not sure I want to get work done so much as talk, but programming is fun. I'd start to discuss state property in appertanance to city property. What are some properties of the state? You would have to introduce a computer to a (finite?) way of expressing language, provided it *expresses* at rates over time that do not exceed its input (impression), and limited by the complexity bound of the architecture. Tangent: architecture complexity. In order to recreate 'propositional knowledge', you have to tell it. Accumulating could amount to hashing video feed over time. What do you know about what's on the screen? Naturally, as symbols are logical, the video would have to be of something you want from it, even if it's high spirits. I am less concerned about the audio, but maybe video is just one way of learning. What information do the mic inputs convey from a spoken voice? (And how do you summarize that?) And what results are on video summaries are there so far? I would start with difference primitives on video. How does the same work for voice? Of course, human understanding may come across the difference in form of artifacts of hardware, but of course, the crossing operation is non- trivial to perform, audio and video. I'm not mentioning smell because crossing it sounds risky. Whaddya know. Now creation and recreation *decompose* into creation and time, spec. real iteration., but where I'm from, creation and time are known to cross means; if I have inferred correctly so far, you want a computer to recreate. If so, you want creation in act to tell a story. I think it's more fun to make them up than tell computers, and if we're by them, can we tell a story on a newsgroup? Who understands best in the cross-sum of { Newsgroup, Newsgroup + task, Computer }? Who wants to define cross-sum? From wizzardx at gmail.com Sun May 4 14:09:37 2008 From: wizzardx at gmail.com (David) Date: Sun, 4 May 2008 20:09:37 +0200 Subject: Image grab in Python In-Reply-To: References: <18c1e6480805040741p8c76a33q2f5464932b6524ff@mail.gmail.com> <18c1e6480805041033v1ae0a3adra3710e1414da0110@mail.gmail.com> Message-ID: <18c1e6480805041109p6f2fc98agcd27c9a809fc94d@mail.gmail.com> > What I want is display a window with a image, the user select a region of > the image, and the region value is passed to my program, my program slice > the image region, and analyze it. > If it's your apps own window, then getting a rectangle selected by the user is simple. 1) Make skeleton x/gtk/wx/qt/etc app 2) Add code to show an image 3) Add code to capture mouse events 4) Add code to show the 'rubber band' rectangle over the mouse selection area 5) When the user releases the mouse, then extract the part of the rectangle between where a mouse button was clicked and where it was released. All this would be in the docs for the Python x/gtk/wx/qt/etc libs. Where is the difficulty? David. From mensanator at aol.com Sun May 11 01:48:43 2008 From: mensanator at aol.com (Mensanator) Date: Sat, 10 May 2008 22:48:43 -0700 (PDT) Subject: do you fail at FizzBuzz? simple prog test References: <39709320-66e1-40e9-a351-c769c9a94585@x41g2000hsb.googlegroups.com> Message-ID: On May 11, 12:04?am, John Machin wrote: > On May 11, 1:24 pm, Mensanator wrote: > > > > > > > On May 10, 8:12?pm, globalrev wrote: > > > >http://reddit.com/r/programming/info/18td4/comments > > > > claims people take a lot of time to write a simple program like this: > > > > "Write a program that prints the numbers from 1 to 100. But for > > > multiples of three print "Fizz" instead of the number and for the > > > multiples of five print "Buzz". For numbers which are multiples of > > > both three and five print "FizzBuzz". > > > > for i in range(1,101): > > > ? ? if i%3 == 0 and i%5 != 0: > > > ? ? ? ? print "Fizz" > > > ? ? elif i%5 == 0 and i%3 != 0: > > > ? ? ? ? print "Buzz" > > > ? ? elif i%5 == 0 and i%3 == 0: > > > ? ? ? ? print "FizzBuzz" > > > ? ? else: > > > ? ? ? ? print i > > > > is there a better way than my solution? is mine ok? > > > Define better. > > > >>> f = ['','','Fizz']*100 > > >>> b = ['','','','','Buzz']*100 > > >>> for i in xrange(1,100): > > > ? ? ? ? fb = f[i-1]+b[i-1] > > ? ? ? ? if fb=='': > > ? ? ? ? ? ? ? ? print i > > ? ? ? ? else: > > ? ? ? ? ? ? ? ? print fb > > You seem to have an unfortunate fixation on 100. Consider changing the > above instances to 34, 20, and 101. Ok, I agree with 101, but I wouldn't necessarily say the others were unfortunate. You might be surprised at how often such fixations discover bugs, something that I have a gift for. From bruno.42.desthuilliers at websiteburo.invalid Thu May 22 08:46:42 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 22 May 2008 14:46:42 +0200 Subject: merging the global namespaces of two modules In-Reply-To: References: Message-ID: <48356b20$0$19726$426a74cc@news.free.fr> Fabrizio Pollastri a ?crit : > Hi, > > just an import problem: > a program imports two modules, modA and modB, each module do not known > anything about the other module (i.e. no cross imports in them), both > modules needs to refer to some functions that are defined in the global > namespace of the other module. IOW, you have a circular dependency between modA and modB. > There is a possible solution? The obvious one : extract the relevant functions from modA and modB into modC and import modC in both modA and modB. If not applyable in your case, please provide more informations. From ivan.illarionov at gmail.com Sun May 25 17:30:19 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Sun, 25 May 2008 21:30:19 +0000 (UTC) Subject: php vs python References: <5l%Yj.77$mz3.53@fe101.usenetserver.com> <37b112d8-a3ba-446d-9d2f-d907d93c637b@w8g2000prd.googlegroups.com> <-t-dnWQ4bZN2MaTVnZ2dnUVZ_qGdnZ2d@comcast.com> <68cb8bb1-4cc5-4a28-8915-46e7d4e316d9@d1g2000hsg.googlegroups.com> Message-ID: On Sun, 25 May 2008 17:09:43 -0400, Jerry Stuckle wrote: > Not at all. I do it every day. > > And BTW - yes, I write Python, also. But I find I can write better, > faster code in PHP. I find I can write better code in Python. Maybe it's just a matter of personal preference? > Do you write PHP? I did. And I hated it very much. I hated it so much that even I had few Python scripts that generated PHP for me when it was possible. From arnodel at googlemail.com Mon May 19 12:04:58 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 19 May 2008 17:04:58 +0100 Subject: explain this function to me, lambda confusion References: <5cc7ef7a-dd21-4772-a7e3-765410f810bb@l17g2000pri.googlegroups.com> <081fe61b-820b-4512-80a9-8a0805f3ce55@k13g2000hse.googlegroups.com> Message-ID: Paul McGuire writes: [...] > lambda is handy in defining parse actions in pyparsing. Parse actions > are callbacks to be run when an expression within a larger grammar is > matched. A common use for parse actions is to do some sort of text or > type conversion. The simplest parse actions are called using the list > of matched tokens. Here is a subexpression that will convert numeric > strings found in a larger grammar to ints: > > integer = Word("0123456789").setParseAction(lambda tokens: > int(tokens[0]) ) Could you use it as a decoratore instead? integer = Word("0123456789") @integer.setParseAction def parse_integer(tokens): return int(tokens[0]) I could make your grammar clearer, because you don't mix it with processing code... and no need for lambdas! -- Arnaud From thorsten at thorstenkampe.de Fri May 2 13:55:04 2008 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Fri, 2 May 2008 19:55:04 +0200 Subject: #!/usr/bin/env python vs. #!/usr/bin/python References: <87abj91j8u.fsf@benfinney.id.au> <87k5iczvdy.fsf@benfinney.id.au> <87fxt0zs92.fsf@benfinney.id.au> Message-ID: * Ben Finney (Sat, 03 May 2008 00:37:45 +1000) > Thorsten Kampe writes: > > * Ben Finney (Fri, 02 May 2008 23:30:01 +1000) > > > The OP was asking why people prefer on over the other. My answer > > > is that I prefer specifying "give me the default OS Python" > > > because anything not installed by the OS is to non-standardised > > > for me to worry about. > > > > > > Others may prefer something different, but then they get to wear > > > whatever problems occur as a result of that choice. I continue to > > > be bemused by that preference, and nothing that I've seen so far > > > in this thread illuminates the issue more. > > > > You're missing the point. Apart from the really dubious terms you > > use ("OS installable package"), using env in the first line has > > exactly the effect to use the default path of Python (which is the > > first entry in your path) > > No, because it's quite common for the PATH variable to have > '/usr/local/bin' appear *before* both of '/bin' and '/usr/bin'. > > If the system has a sysadmin-installed '/usr/local/bin/python' > installed as well as the OS-installed '/usr/bin/python', then the two > shebang options the OP raised will behave differently on such a > system. This seems to be quite the point of the discussion. Again you're missing the point. If you or whoever installs Python (or another version of Python) to /usr/local/bin and puts this in the path to front (as it's often done) then /you/ want that Python to be the "default" one. It would just be silly to say "no, I the developer want /usr/bin/python". So in general "#! env" is better while in certain circumstance hardcoding the path to /usr/bin/python can be better. Thorsten From miller.paul.w at gmail.com Mon May 26 15:38:28 2008 From: miller.paul.w at gmail.com (miller.paul.w at gmail.com) Date: Mon, 26 May 2008 12:38:28 -0700 (PDT) Subject: looking for membership management software -- Open Source, written in Python References: Message-ID: I forgot to ask: what's your target platform? I mentioned Organizer's Database, but it only runs on Windows. If you need a Linux or OS X solution, then I can make another suggestion. :-) From aahz at pythoncraft.com Sun May 18 00:37:40 2008 From: aahz at pythoncraft.com (Aahz) Date: 17 May 2008 21:37:40 -0700 Subject: usage of python References: Message-ID: In article , Rajarshi wrote: > >Is there any list with people/groups/companies using Python for >impressive things? > >Any pointers would be appreciated And one more: http://www.pythonology.com/ -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Need a book? Use your library! From celoserpa at gmail.com Fri May 9 10:30:42 2008 From: celoserpa at gmail.com (Marcelo de Moraes Serpa) Date: Fri, 9 May 2008 11:30:42 -0300 Subject: Newbie to python --- why should i learn ! In-Reply-To: <83493f3d-3b40-4001-ae5a-81ac6a537540@m45g2000hsb.googlegroups.com> References: <9f5ee6c3-86f7-401a-acc8-cd2c9b059fbd@x19g2000prg.googlegroups.com> <83493f3d-3b40-4001-ae5a-81ac6a537540@m45g2000hsb.googlegroups.com> Message-ID: <1e5bcefd0805090730i5f5905dcrcd0f0792b2b94f0e@mail.gmail.com> I sincerely think that most languages in existence today have its place. Java has some great libraries and programs that were written in it. Try writing an Eclipse clone in Python, I don't think it would go well. On Fri, May 9, 2008 at 11:08 AM, hdante wrote: > On May 8, 7:25 am, "Ra... at MyKavita.com" > wrote: > > Hi, > > > > i was reading/learning some hello world program in python. > > I think its very simillar to Java/C++/C#. What's different (except > > syntax) ? > > All the languages have similar "power", in a theoretical sense. If > you can solve a problem with one, most of the time you'll be able to > solve it with the other. So we could say that the languages are > "equal". > > However, in practice, the syntax matters a lot. For example, they > will influence on the maintainability and the performance of your > application. > > > > > what can i do easily with python which is not easy in c++/java !? > > Pretty much everything. Python syntax is minimalist, so it requires > much less code. There are many examples in Wikipedia, for example: > > > http://en.wikipedia.org/wiki/User_datagram_protocol#Sample_code_.28Python.29 > http://pt.wikipedia.org/wiki/Radix_sort#C.C3.B3digo_em_Java > http://en.wikipedia.org/wiki/Observer_pattern#Python > > etc. > > > > > Tnx, > > Raxitwww.mykavita.com > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Thu May 15 22:19:08 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 15 May 2008 23:19:08 -0300 Subject: Handling test data that depends on temporal data (that might change while the test runs) References: <1e5bcefd0805151021i6306946dre6e54307e91d9c1c@mail.gmail.com> <86ac1b9c0805151812i20a40908l590b342b6f1e9f52@mail.gmail.com> <1e5bcefd0805151844r2fba4141p29a0cf7d37a0a5ef@mail.gmail.com> Message-ID: En Thu, 15 May 2008 22:44:17 -0300, Marcelo de Moraes Serpa escribi?: > @Gabriel: I understand what you are saying. It all depends on what you > want > to test. In this case, I wanted to test the algorithm of the method. The > test_generate_chat_dir_string is meant to do just that: Check if the > generate_chat_dir_string generated a "valid" (according to the specs) > string > for a "chat dir name". That depends on what you consider "valid". Just duplicating the function code in the test is absurd and pointless. Of course it will pass now - you're executing the same code! On the other hand, what if you later want to replace the algorithm and use SHA1 instead of md5? The test will fail then - but do you *actually* care whether it actually returns the md5 digest or something else? If you *do* care, then you should compute the output by hand (or assume it is correct *now*) and hard code THAT string in the test, not recompute it again. If you *don't* care, then follow the steps I outlined in the previous message: just ensure that different inputs give different outputs. > It is not a integration nor a functional "unit" test, but it is a "real" > unit test in the sense that I created a test for each method and I > exercised > the methods the following way: > > 1) Got some data to test and... > 2) ... Generated an output "manually" in the test method that I knew > were > the expected return of the tested method; > 3) Fed this data to the tested method and compared the manually > generated > result with the return value of the method. > > It is like testing a method that does a simple division: > > def test_divide > divdend = 10 > divisor = 2 > expected_result = 5 > self.assertEquals(mathprogram.divide(dividend,divisor),5) Mmm, no, your posted example was more like this: def test_divide divdend = 10 divisor = 2 expected_result = dividend/divisor self.assertEquals(mathprogram.divide(dividend,divisor), 5) You *computed* the expected result using (presumably) the same code as the tested function. > The techniques you explained in your message sound more like functional > testing or integration + functional testing where multiple aspects of a > single functional unit are being exercised. Or am I wrong? I'd say they are still unit tests. I'm testing a single function, comparing the expected output with the actual output. But I only check the *public* interfase of the function, what their users expect from it (its contract, if you want); I don't check the internal implementation. The real value of unit tests comes when you want to modify something, or reimplement it. You must ensure that you don't break other things. With a too strict test very tied to the current implementation, you can't change anything. -- Gabriel Genellina From mathieu.prevot at ens.fr Wed May 28 09:06:42 2008 From: mathieu.prevot at ens.fr (Mathieu Prevot) Date: Wed, 28 May 2008 15:06:42 +0200 Subject: Flash Decoder In-Reply-To: References: <860bf237-18d3-4949-a26d-97becafb27c8@i36g2000prf.googlegroups.com> <6a4rtbF35ut5sU1@mid.uni-berlin.de> <0c0ea160-89d6-4827-8d54-d0029d064c71@w5g2000prd.googlegroups.com> <3e473cc60805280511o6cf0e639lfdfc2d1ea8902300@mail.gmail.com> Message-ID: <3e473cc60805280606g5661dbddocc23012c64079764@mail.gmail.com> 2008/5/28 ankit anand : > hmm i am more interested in .swf format and more specifically i would like > to have all the pixel values of all the frames can i do that using this > library? Not with ffmpeg. You can check out the code from Gnash [1] or Swfdec [2] or start you swf decoder from scratch using Adobe specification [3] on the swf format. Happy coding ! Mathieu [1] http://en.wikipedia.org/wiki/Gnash [2] http://en.wikipedia.org/wiki/Swfdec [3] http://www.adobe.com/devnet/swf/ From ZeeGeek at gmail.com Sun May 4 11:59:05 2008 From: ZeeGeek at gmail.com (ZeeGeek) Date: Sun, 4 May 2008 08:59:05 -0700 (PDT) Subject: default gettext localedir on windows Message-ID: Hi, what's the default localedir for gettext module on windows? In Linux, it's /usr/share/locale. Where should I put the *.mo file in order to make the translation work? Thanks. From tjreedy at udel.edu Fri May 9 15:35:12 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 9 May 2008 15:35:12 -0400 Subject: Mathematics in Python are not correct References: <52c855d8-5609-43e0-b98f-9fa87b2808c2@m3g2000hsc.googlegroups.com><200805081914.06459.kyrie@uh.cu> Message-ID: "Lou Pecora" wrote in message news:pecora-DFE713.11234209052008 at ra.nrl.navy.mil... | In article , | "Terry Reedy" wrote: | | > "Luis Zarrabeitia" wrote in message | > news:200805081914.06459.kyrie at uh.cu... | > | Btw, there seems to be a math problem in python with exponentiation... | > | >>> 0**0 | > | 1 | > | That 0^0 should be a nan or exception, I guess, but not 1. | > | > a**b is 1 multiplied by a, b times. 1 multiplied by 0 no times is 1. | > But there are unenlighted people who agree with you ;-) | > Wikipedia has a discussion of this. | > | > tjr | | I like that argument better. But... | | I've also heard the very similar a**b is a multiplied by a b-1 times. Me too, in school, but *that* definition is incomplete: it excludes b=0 and hence a**0 for all a. It was the best people could do before 0 was known. But 0 was introduced to Europe just over 800 years ago ;-) In general, sequence reduction work better if the base case is given separately rather that defined as the first member of the sequence (which excludes empty sequences!). ab = [a]*b # b a count a**b = reduce(int.__mul__, ab, 1) # better a**b = reduce(int.__mul__, ab[1:], a) # crashes for b=0 Consider the equivalent pair of definitions for a*b: a*b = 0 incremented by a, b times = reduce(int.__add__, ab, 0) a*b = a incremented by a, b-1 times = reduce(int.__add__, ab[1:] a) Since we have 0, the second, which excludes (crashes on) a*0 , is incomplete. Terry Jan Reedy From deets at nospam.web.de Fri May 23 05:53:32 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 23 May 2008 11:53:32 +0200 Subject: can python do some kernel stuff? In-Reply-To: <28c432f0-657c-4272-8cd4-a9081b013279@w5g2000prd.googlegroups.com> References: <983ec0f6-1316-40cd-a4d4-ce9b5e272a60@h1g2000prh.googlegroups.com> <48366cfa$0$15168$607ed4bc@cv.net> <28c432f0-657c-4272-8cd4-a9081b013279@w5g2000prd.googlegroups.com> Message-ID: <69nigsF3499pqU2@mid.uni-berlin.de> Jimmy schrieb: > On May 23, 3:05 pm, Andrew Lee wrote: >> Jimmy wrote: >>> Hi to all >>> python now has grown to a versatile language that can >>> accomplish tasks for many different purposes. However, >>> AFAIK, little is known about its ability of kernel coding. >>> So I am wondering if python can do some kernel coding that >>> used to be the private garden of C/C++. For example, can python >>> intercept the input of keyboard on a system level? someone told me >>> it's a kernel thing, isn't it? >> http://wiki.python.org/moin/elmer > > well, straightly speaking, how can I know a key is pressed on a system- > level if > using python? What has that todo with kernel programming? You can use e.g. pygame to get keystrokes. Or under linux, read (if you are root) the keyboard input file - I've done that to support several keyboards attached to a machine. And the original question: no, python can't be used as kernel programming language. Amongst other reasons, performance & the GIL prevent that. Diez From jstucklex at attglobal.net Sun May 25 17:09:43 2008 From: jstucklex at attglobal.net (Jerry Stuckle) Date: Sun, 25 May 2008 17:09:43 -0400 Subject: php vs python In-Reply-To: References: <5l%Yj.77$mz3.53@fe101.usenetserver.com> <37b112d8-a3ba-446d-9d2f-d907d93c637b@w8g2000prd.googlegroups.com> <-t-dnWQ4bZN2MaTVnZ2dnUVZ_qGdnZ2d@comcast.com> <68cb8bb1-4cc5-4a28-8915-46e7d4e316d9@d1g2000hsg.googlegroups.com> Message-ID: Ivan Illarionov wrote: > On Sun, 25 May 2008 13:28:25 -0700, NC wrote: > [...] >> A quick look at the revision log: >> >> http://byteflow.su/log/ >> >> reveals that the initial commit of 60 or so files has been done on >> 08/14/07 >> (10 months ago), a second developer came on board 12/01/07 (seven+ >> months ago), >> a third one, on 01/04/08 (six+ months ago), a fourth one, on 01/16/08 >> (also >> six+ months ago). There are at least nine discernible contributors >> overall. >> Say what you will, but it still looks an awful lot like like two man- >> years, >> Django or no Django... > > I bet that if they did this with PHP framework they where far from where > they are now. > Yep, I'd bet they would be much further along. > I didn't say that it's not possible to write good code in PHP, I said > that Python and Django encourage cleaner code more than PHP and PHP > frameworks do. > I repeat. The language has nothing to do with it. Good programmers write good code. Lousy programmers write bad code. > IMHO Python language is better designed and this influences everything > written in it. > A lot of people don't share the opinion that it is "better designed". > Yes, it's possible to write something clean in PHP but it would require a > lot more work. > Not at all. I do it every day. And BTW - yes, I write Python, also. But I find I can write better, faster code in PHP. Do you write PHP? > Ivan > > -- ================== Remove the "x" from my email address Jerry Stuckle JDS Computer Training Corp. jstucklex at attglobal.net ================== From hdante at gmail.com Tue May 6 10:17:15 2008 From: hdante at gmail.com (hdante) Date: Tue, 6 May 2008 07:17:15 -0700 (PDT) Subject: Am I missing something with Python not having interfaces? References: <45de2f7e-484a-4871-bbaa-bf7eed5dfa40@x35g2000hsb.googlegroups.com> Message-ID: <486da6f2-d1be-4637-af5f-01d5924ced04@2g2000hsn.googlegroups.com> On May 6, 10:44?am, jmDesktop wrote: > Studying OOP and noticed that Python does not have Interfaces. ?Is > that correct? ?Is my schooling for nought on these OOP concepts if I > use Python. ?Am I losing something if I don't use the "typical" oop > constructs found in other languages (Java, C# come to mind.) ?I'm > afraid that if I never use them I'll lose them and when I need them > for something beside Python, I'll be lost. ?Thank you. Python supports interfaces. In the example below, "Vehicle" is an interface. class Vehicle: def drive(self, count): raise Exception("I'm only an interface... :-(") def number_of_wheels(self): return 0 def fly(self): pass class Car(Vehicle): def drive(self, count): print "The car walked %d steps" % count def number_of_wheels(self): return 4 As you can see, there are a couple of ways you can tell others "Vehicle" is an interface, like raising exceptions, returning useless values or doing nothing. You could also raise an exception in Vehicle.__init__. From hniksic at xemacs.org Fri May 9 05:38:56 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 09 May 2008 11:38:56 +0200 Subject: pickle problem References: <68g456F2t41nqU1@mid.uni-berlin.de> <97b9fbd1-3725-4a7d-9ecb-1d2af6f35665@y21g2000hsf.googlegroups.com> <68h7p7F2su97jU3@mid.uni-berlin.de> <8763tofpiv.fsf@mulj.homelinux.net> <68i084F2su97jU4@mid.uni-berlin.de> Message-ID: <87y76jx1e7.fsf@mulj.homelinux.net> Marc 'BlackJack' Rintsch writes: >> Of course, if it makes sense to pickle sockets in the application, one >> is can do so by defining __getstate__ and __setstate__: > > When does it make sense!? When recreating the object from on-disk state requires reestablishing the communication, as the example shows. I'm not saying that doing that is always a good idea, only that it can be done if/when needed. > But if you unpickle it while the original connection is still open it > can't connect. Why not? I was thinking "client socket", not "server socket". From ptmcg at austin.rr.com Tue May 20 11:54:39 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 20 May 2008 08:54:39 -0700 (PDT) Subject: Misuse of list comprehensions? References: <038e4418$0$27258$c3e8da3@news.astraweb.com> <6359d72c-f937-46cd-b1ce-b7450671b714@i76g2000hsf.googlegroups.com> Message-ID: <86e5f3b2-d1ae-414f-976e-062e7a293c9b@25g2000hsx.googlegroups.com> On May 20, 10:17?am, Arnaud Delobelle wrote: > Paul McGuire writes: > > On May 20, 8:13?am, "John Salerno" wrote: > >> I posted this code last night in response to another thread, and after I > >> posted it I got to wondering if I had misused the list comprehension. Here's > >> the two examples: > > >> Example 1: > >> -------------------- > >> def compress(s): > >> ? ? new = [] > > >> ? ? for c in s: > >> ? ? ? ? if c not in new: > >> ? ? ? ? ? ? new.append(c) > >> ? ? return ''.join(new) > >> ---------------------- > > >> Example 2: > >> ------------------------ > >> def compress(s): > >> ? ? new = [] > >> ? ? [new.append(c) for c in s if c not in new] > >> ? ? return ''.join(new) > >> -------------------------- > > >> In example 1, the intention to make an in-place change is explicit, and it's > >> being used as everyone expects it to be used. In example 2, however, I began > >> to think this might be an abuse of list comprehensions, because I'm not > >> assigning the result to anything (nor am I even using the result in any > >> way). > > >> What does everyone think about this? Should list comprehensions be used this > >> way, or should they only be used to actually create a new list that will > >> then be assigned to a variable/returned/etc.? > > > Why not make the list comp the actual list you are trying to build? > > > def compress(s): > > ? ? seen = set() > > ? ? new = [c for c in s if c not in seen and (seen.add(c) or True)] > > > Isn't > > ? ? c not in seen and (seen.add(c) or True) > > the same as > > ? ? seen.add(c) or c not in seen > > ? > > > ? ? return ''.join(new) > > (notice I haven't closed the tag!) > > -- > Arnaud- Hide quoted text - > > - Show quoted text - Unfortunately, no. "seen.add(c) or c not in seen" will never return true, since c gets added to seen before testing if c in seen. -- Paul From pavlovevidence at gmail.com Tue May 27 03:03:53 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 27 May 2008 00:03:53 -0700 (PDT) Subject: Hungarian Notation References: Message-ID: <62ed1093-7d90-4fc6-b1b9-0edd3d1e1042@26g2000hsk.googlegroups.com> On May 27, 2:42 am, "inhahe" wrote: > Well, I just need it once in a while. Actually now is the only time I > remember. The last time what I needed was a file name extension. I want a > string called headers, but I want to derive a dict from it, also called > headers. So I figured the string would be called strHeaders, and the dict, > dctHeaders probably, but when a precedent for something like that exists, I > like to use it. I doubt there's anything canonical since Python community, PEP 8, and Python's dynamic typing all discourage its use. I would venture to say that the community would frown upon names such as "strHeaders" since they don't agree with the naming conventions in PEP 8. Instead, use "str_headers" and "dict_headers". Better yet, use "headers_str" and "headers_dict". Put the less important information last. Carl Banks From fc14301589 at icqmail.com Sat May 31 14:48:28 2008 From: fc14301589 at icqmail.com (TheSaint) Date: Sun, 01 Jun 2008 02:48:28 +0800 Subject: File browser in python gui References: <4841353e_1@news.tm.net.my> Message-ID: <48419d7c_2@news.tm.net.my> On 22:39, sabato 31 maggio 2008 Sebastian 'lunar' Wiesner wrote: > What about QtGui.QFileDialog? Yeah! Thank you! So strange that I was looking for all around and it was already in my computer. I'm gonna back to study a little function that will return an existing/new file or None (if Cancel is pressed) -- Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html From stefan_ml at behnel.de Thu May 29 04:54:01 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 29 May 2008 10:54:01 +0200 Subject: Compare 2 files and discard common lines In-Reply-To: <8d55718c-6881-4844-b8d1-bbe1c5929f46@x35g2000hsb.googlegroups.com> References: <8d55718c-6881-4844-b8d1-bbe1c5929f46@x35g2000hsb.googlegroups.com> Message-ID: <483E6F29.8000805@behnel.de> loial wrote: > I have a requirement to compare 2 text files and write to a 3rd file > only those lines that appear in the 2nd file but not in the 1st file. lines_in_file2 = set(open("file2").readlines()) for line in open("file1"): if line not in lines_in_file2: print line Stefan From hdante at gmail.com Wed May 14 21:29:54 2008 From: hdante at gmail.com (Henrique Dante de Almeida) Date: Thu, 15 May 2008 01:29:54 +0000 (UTC) Subject: Usenet References: <6bafdf82-cf8a-42cd-9f72-d98a39fab5b5@j22g2000hsf.googlegroups.com> Message-ID: Em Wed, 14 May 2008 10:01:40 -0700, castironpi escreveu: > On May 14, 11:58?am, "Terry Reedy" wrote: > > Love them opticals. Testing. :-P From wuwei23 at gmail.com Sat May 17 21:08:25 2008 From: wuwei23 at gmail.com (alex23) Date: Sat, 17 May 2008 18:08:25 -0700 (PDT) Subject: multiple databases, what's the best interface ? References: Message-ID: <325c024f-2bc2-40e5-85ac-cefb99a85709@w34g2000prm.googlegroups.com> On May 18, 4:54 am, Stef Mientki wrote: > What's the best interface so I can use the same program for all databases, > and just have to change the database name, if I want to use another > database ? I really like sqlalchemy: http://www.sqlalchemy.org/features.html - alex23 From mnikhil at gmail.com Tue May 20 14:12:13 2008 From: mnikhil at gmail.com (Nikhil) Date: Tue, 20 May 2008 23:42:13 +0530 Subject: preserve history in the interactive python Message-ID: Hi, I am using python -i, and I find it hard typing/pasting the commands from the previous interactive shell. Basically, is there anyway that I can preserve the history in the shell? I guess but not sure there should be something like ~/.pyrc for configuring such but can someone please let me know what is the effective environment variable to preserve the history? Thanks, Nikhil From miller.paul.w at gmail.com Sun May 25 19:19:37 2008 From: miller.paul.w at gmail.com (miller.paul.w at gmail.com) Date: Sun, 25 May 2008 16:19:37 -0700 (PDT) Subject: Performance of Python builtins Message-ID: Is there any place outside the actual C source for Python that has information about the performance of Python's built-in operations? For example, I'd *expect* list.append to be O(1), and I hope that list[i] is O(1), but I don't really know that for sure, since it would depend a lot on the internal implementation. I'm really only asking this for curiosity's sake --- more as a reasonable, non-trollish version of the "Python is slow" post than anything. :-) I've never really had any problems with the performance of Python code that I couldn't solve by either changing my algorithm or, if all else has truly failed, rewriting in C or Pyrex. What I'd like to see is something like http://svn.python.org/projects/python/trunk/Objects/listsort.txt where Python's sorting algorithm is described, except with the focus on other built-in constructs. Thanks! From wxPythoner at gmail.com Sat May 10 16:56:39 2008 From: wxPythoner at gmail.com (wxPythoner at gmail.com) Date: Sat, 10 May 2008 13:56:39 -0700 (PDT) Subject: Python doesn't recognize quote types Message-ID: There's a thing that bugs me in Python. Look at this... >>> print "Testing\" SyntaxError: EOL while scanning single-quoted string Please focus on the part of the error message that states "while scanning single-quoted string". How can Python claim it scanned a single-quoted string when I fed it with a double-quoted string? Is quote type (single quote and double quote) recognition not implemented in Python? From sumon.sadhu at gmail.com Thu May 8 19:44:41 2008 From: sumon.sadhu at gmail.com (Sumon Sadhu) Date: Thu, 8 May 2008 16:44:41 -0700 Subject: Write a python blog/website? In-Reply-To: <880dece00805081556hb7be637l1533cea08e054993@mail.gmail.com> References: <08d22e33-667e-4089-a777-69d5cb9cb95b@59g2000hsb.googlegroups.com> <880dece00805081556hb7be637l1533cea08e054993@mail.gmail.com> Message-ID: <0169FBC4-65FF-4D22-B534-1DB15341EEA0@gmail.com> Hey Dotan, My apologies if this post caused offense. Your assertion is right, maybe i should have emailed everyone individually like i've done with the first 45 sites, but it was never my intention to spam. We're programmers like yourself, trying to build something that provides a lot of benefit. You can see our intentions are genuine (and our python ad server was fun to build) So while i appreciate your response, it was never my attention to be "spammy" Thanks, - Sumon On 8 May 2008, at 15:56, Dotan Cohen wrote: > 2008/5/8 sharpshoot : >> Hi Guys, >> >> I thought this would be really interesting to people who blog who >> might be able to help us. > > Your proposal very well may be interesting to those who might be able > to help you, yet, you dug your own grave by spamming the Python list. > I see that your intentions were honest, but your post was unsolicited > advertising, and off-topic at that. > > I don't 'blog'. I write web content. I have rather impressive traffic > at some sites and your advertising seems to fit at least two or three > medium-traffic sites I maintain. I won't experiment with the > advertising on the large sites until I see results at the smaller ones > first. However, snaptalent.com stands out as a spammer. I most > certainly will not do business with spammers, and I am willing to > sacrifice my bottom line to avoid making spammers richer. That's too > bad, as there are many more effective ways that you could have reached > me and others like me. The two or three fish you will net spamming the > python list will not be worth your bad name, I assure you. > > Dotan Cohen > > http://what-is-what.com > http://gibberish.co.il > ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?- > ?-?-?-?-? > > A: Because it messes up the order in which people normally read text. > Q: Why is top-posting such a bad thing? From mensanator at aol.com Fri May 2 16:47:39 2008 From: mensanator at aol.com (Mensanator) Date: Fri, 2 May 2008 13:47:39 -0700 (PDT) Subject: Finally had to plonk google gorups. References: <966256b2-fe7c-4ec5-900b-90b285311881@k10g2000prm.googlegroups.com> <87abjne42n.fsf@physik.rwth-aachen.de> <2dc0c81b0804300851h63500c54q8570202c9cece332@mail.gmail.com> <87r6cncp4r.fsf@physik.rwth-aachen.de> <2dc0c81b0804301029n5db13d7ej8cb71938f1980f7e@mail.gmail.com> <2dc0c81b0804301030x7858b8b5y14729ba3632c61b9@mail.gmail.com> <9ee1e917-a0c2-4c03-b611-e409e315c071@x41g2000hsb.googlegroups.com> Message-ID: On May 2, 2:26?pm, Arnaud Delobelle wrote: > Mensanator writes: > > On May 2, 1:20?pm, Michael Torrie wrote: > >> Mensanator wrote: > >> > On May 2, 9:53 am, Michael Torrie wrote: > >> >> Shawn Milochik wrote: > >> >>> How does one "plonk" stuff from Google Groups? Specifically, how > >> >>> can this be done in Gmail? > >> >> Set up a filter that looks for some phrase in the mail headers that > >> >> identifies messages originating from google groups. ?Gmail's filters are > >> >> fairly flexible. ?I'd probably just have it look for certain words. > >> >> Look at an e-mail's source (raw view) and particularly check in the > >> >> headers for things to filter by. > > >> > Why don't you just block all messages from Gmail? > > >> Brilliant! ?Seeing as he's asking about doing the filtering in Gmail > >> (implying it's use for his own posting and viewing the list) that would > >> work splendidly for him! ?Or not. > > >> Of course you're not likely to see this message either since I and many > >> folks on here post from gmail. > > >> Spam comes mainly from Google Groups, not as much from Gmail in my > >> experience. > > > I didn't say it was POSTED from gmail, but the spammers often have > > gmail addresses, to wit: > > You're confusing gmail addresses and Google Groups > (groups.google.com), No, I'm not. > which can be used as a web interface to usenet > and mailing lists. ? Read again what I wrote. > Look at the 'Organisation' header of the messages > you quote. > > It seems most of the spam on comp.lang.python is posted from Google > Groups, *including* the one with a 'From' header which is not a gmail > address. To post from Google Groups, don't you need a legitimate e-mail address? Why does Gmail allow spammers to have e-mail accounts? They are as much to blame as Google Groups. > > So it would be more efficient And thus, stupid. > to block messages posted from Google > Groups than the ones from gmail addresses. > > -- > Arnaud- Hide quoted text - > > - Show quoted text - From workitharder at gmail.com Sat May 24 02:15:00 2008 From: workitharder at gmail.com (bukzor) Date: Fri, 23 May 2008 23:15:00 -0700 (PDT) Subject: Reloading function obtained via 'from xxx import yyy' References: <4837225e$0$5507$9b622d9e@news.freenet.de> Message-ID: <0f6bda3c-94c1-483b-893f-988315244a6f@p25g2000pri.googlegroups.com> On May 23, 3:44?pm, "Joel Koltner" wrote: > ""Martin v. L?wis"" wrote in messagenews:4837225e$0$5507$9b622d9e at news.freenet.de... > > > Try all three of them, in sequence: > > Thanks, will do. > > > If you absolutely don't want to import test, write > > I can live with the import, I just don't want to have to type out the full > names all the time. > > ---Joel t = reload(test).testFunc t() From wuwei23 at gmail.com Mon May 12 22:52:45 2008 From: wuwei23 at gmail.com (alex23) Date: Mon, 12 May 2008 19:52:45 -0700 (PDT) Subject: do you fail at FizzBuzz? simple prog test References: <39709320-66e1-40e9-a351-c769c9a94585@x41g2000hsb.googlegroups.com> <688a0f5a-2cdf-45ca-abe7-5bbb89aac32f@s50g2000hsb.googlegroups.com> Message-ID: <968dc79b-f0ae-4505-867e-83801870af2f@z16g2000prn.googlegroups.com> wrote: > I just can't believe someone applying for a programmer position cannot > provide a sensible anwser in 5 or less minutes. Try taking a look at the level of discourse in the Google App Engine group. It's pretty clear that some - let's say "developers" rather than "programmers" - developers are simply interested in acquiring usage patterns for the particular language they're required to develop in. Being able to extend existing patterns or create new solutions is completely outside of their scope of interest or ability. My 'favourite' is the "how do I do x?", "can you show me a working example?", "can you add your example to my code?" sequence, you see a lot of that. I'd honestly expect a lot of the current GAE group posters to fail the FizzBuzz test, especially given that an amazing number of them seem to be constantly griping about not being able to run production code on what is currently only a preview framework. - alex23 From george.sakkis at gmail.com Wed May 28 17:58:54 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 28 May 2008 14:58:54 -0700 (PDT) Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <5c98049e-e62e-4ab1-afed-b0a3e186bd05@w1g2000prd.googlegroups.com> <6a60ioF360u5uU1@mid.uni-berlin.de> Message-ID: On May 28, 5:19 pm, "Diez B. Roggisch" wrote: > > Kind of like how this year's program won't work on next year's > > Python? > > For somebody who has admitted to have only very rudimentary knowledge of > python that's a pretty bold statement, don't you think? > > > Except Flaming Thunder is faster. ;) > > Faster in execution speed for a very limited domain of problems - maybe. > > But unless it grows support for structured data types, arrays and maybe > even an object system - it's nothing but a toy language. I wouldn't even call it a toy language, it seems more like a sandbox for fumbling around in compiler technology and language "design" (loosely speaking). Fun as a research or alpha-stage project but nowhere near production-ready. To be fair, the graphics look cool and the "single-asset 8-by-8 shotgun cross compiler, written entirely in assembly language" sounds impressive from an implementation point of view, in the sense that building Deep Blue with nothing but NAND gates would; utterly impressive and pointless at the same time. Which goes to prove that hardcore hackers don't necessarily make decent language designers. George From fetchinson at googlemail.com Sat May 10 22:35:39 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Sat, 10 May 2008 19:35:39 -0700 Subject: Is using range() in for loops really Pythonic? In-Reply-To: <482657ca$0$25026$607ed4bc@cv.net> References: <482657ca$0$25026$607ed4bc@cv.net> Message-ID: I know it's popular and very handy, but I'm curious if there are purists > out there who think that using something like: > > for x in range(10): > #do something 10 times > > is unPythonic. The reason I ask is because the structure of the for loop > seems to be for iterating through a sequence. It seems somewhat > artificial to use the for loop to do something a certain number of > times, like above. > > Anyone out there refuse to use it this way, or is it just impossible to > avoid? IMHO it's perfectly okay to use it as you describe it. Maybe you can switch to xrange( ) which doesn't return a list but an iterator. Note that in python 3.0 xrange will cease to exist and range( ) will return an iterator instead. Cheers, Daniel -- http://www.cafepress.com/putitdown -------------- next part -------------- An HTML attachment was scrubbed... URL: From fiacre.patrick at gmail.com Fri May 23 06:02:51 2008 From: fiacre.patrick at gmail.com (Andrew Lee) Date: Fri, 23 May 2008 06:02:51 -0400 Subject: can python do some kernel stuff? In-Reply-To: <28c432f0-657c-4272-8cd4-a9081b013279@w5g2000prd.googlegroups.com> References: <983ec0f6-1316-40cd-a4d4-ce9b5e272a60@h1g2000prh.googlegroups.com> <48366cfa$0$15168$607ed4bc@cv.net> <28c432f0-657c-4272-8cd4-a9081b013279@w5g2000prd.googlegroups.com> Message-ID: <4836964c$0$25057$607ed4bc@cv.net> Jimmy wrote: > On May 23, 3:05 pm, Andrew Lee wrote: >> Jimmy wrote: >>> Hi to all >>> python now has grown to a versatile language that can >>> accomplish tasks for many different purposes. However, >>> AFAIK, little is known about its ability of kernel coding. >>> So I am wondering if python can do some kernel coding that >>> used to be the private garden of C/C++. For example, can python >>> intercept the input of keyboard on a system level? someone told me >>> it's a kernel thing, isn't it? >> http://wiki.python.org/moin/elmer > > well, straightly speaking, how can I know a key is pressed on a system- > level if > using python? http://docs.python.org/lib/module-curses.html Unless you are using an ancient piece of hardware -- a terminal is a pseudo terminal and a key stroke isn't a kernel event at all. If you were looking for examples of kernel level functions you might want to consider driver interfaces -- how to program device interfaces -- that, too, can be done in Python -- but, again, you are always calling some underlying C function exposed via SWIG or another cross compilation tool. Python doesn't reinvent system calls! :-) From alan.wright at volubill.com Wed May 21 06:44:48 2008 From: alan.wright at volubill.com (Alan Wright) Date: Wed, 21 May 2008 11:44:48 +0100 Subject: Newbie: Keep TCP socket open References: Message-ID: Same on FC8, sends RST after it sees SYN/ACK "Ghirai" wrote in message news:mailman.1367.1211240706.12834.python-list at python.org... > On Mon, 19 May 2008 23:50:50 +0100 > "Alan Wright" wrote: > >> Ghirai, >> Scapy does the same, only it sends RST and not FIN, so still no help >> >> send(IP(dst="10.1.1.2")/TCP(dport=50000,flags="S")) >> >> Only have windows at the moment sadly. >> >> Alan >> > > Are you sure there's no firewall or something else between you and the > remote host? > > Because i just tried that command with scapy and it didn't send any other > packets > except what it was told (1 packet with SYN flag set). > > I haven't tried on windows though. > > -- > Regards, > Ghirai. From cameronlarue at gmail.com Fri May 30 15:50:43 2008 From: cameronlarue at gmail.com (Cameron) Date: Fri, 30 May 2008 12:50:43 -0700 (PDT) Subject: accumulator generators Message-ID: I was reading this Paul Graham article and he builds an accumuator generator function in the appendix. His looks like this:
def foo(n):
  s = [n]
  def bar(i):
    s[0] += i
    return s[0]
  return bar
Why does that work, but not this:
def foo(n):
  s = n
  def bar(i):
    s += i
    return s
  return bar
From info at thegrantinstitute.com Fri May 16 16:34:58 2008 From: info at thegrantinstitute.com (Anthony Jones) Date: 16 May 2008 13:34:58 -0700 Subject: Professional Grant Proposal Writing Workshop (August 2008: Boston, Massachusetts - University of Phoenix Campus) Message-ID: <20080516133458.D51242FB142EC022@thegrantinstitute.com> An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Sun May 25 12:59:17 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 25 May 2008 12:59:17 -0400 Subject: which datastructure for fast sorted insert? References: Message-ID: "Rares Vernica" wrote in message news:y1r1w3qan3p.fsf at ics.uci.edu... | >>> l=list(s) | >>> l.sort() This can be condensed to l = sorted(s) | >>> l | ['a', 'b', 'c'] From bruno.desthuilliers at gmail.com Mon May 19 16:35:55 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Mon, 19 May 2008 13:35:55 -0700 (PDT) Subject: Using Python for programming algorithms References: <48315082$0$24599$426a74cc@news.free.fr> <62884fc6-6c74-4477-91de-7b7689b5fa75@m44g2000hsc.googlegroups.com> Message-ID: <21d1d960-110c-4d70-99f5-7ce47c184544@k13g2000hse.googlegroups.com> On 19 mai, 18:11, Henrique Dante de Almeida wrote: > On May 19, 7:03 am, Bruno Desthuilliers > > > 42.desthuilli... at websiteburo.invalid> wrote: > > Vicent Giner a ?crit : > > > > Hello. > > > > I am new to Python. It seems a very interesting language to me. Its > > > simplicity is very attractive. > > > > However, it is usually said that Python is not a compiled but > > > interpreted programming language > > > cf my answer to you and Henrique on this. > > > > I am working on my PhD Thesis, which is about Operations Research, > > > heuristic algorithms, etc., and I am considering the possibility of > > > programming all my algorithms in Python. > > > > The usual alternative is C, but I like Python more. > > > Then use it. > > > > The main drawbacks I see to using Python are these: > > > > * As far as I understand, the fact that Python is not a compiled > > > language makes it slower than C, when performing huge amounts of > > > computations within an algorithm or program. > > > In which way is this a problem here ? I thought your thesis was about > > algorithm, not about implementation optimisation ? And if it's the > > later, then even C might sometimes be too high level - you should drop > > to assembly language. > > > > * I don't know how likely it is to find libraries in Python related to > > > my research field. > > > I can't tell but you'd be surprised by the quantity of available Python > > libs. > > > > * I know Python is a "serious" and mature programming language, of > > > course. But I do not know if it is seen as "just funny" in a research > > > context. Is Python considered as a good programming language for > > > implementing Operations Research algorithms, such as heuristics and > > > other soft-computing algorithms? > > > Don't know if this answers your question, but it seems that at least > > some authors consider it a good choice:http://www.oreilly.com/catalog/9780596529321/ > > > All code examples in this books are in Python - very badly written > > Python, alas... > > > > Maybe this is not the right forum, but maybe you can give me some > > > hints or tips... > > > Hem... Obviously, most people here will have a little biased, you know ?-) > > I agree with what most people here said, that the language doesn't > really matter, etc., but that simply does not apply to the specific > case of optimization research. > > The little I know about optimization, even trivial problems may be > hairy problems. Na?ve implementations simply don't finish and the > performance bottlenecks are not necessarily in the numeric computation > algorithms (so numpy doesn't help much here). If the guy is doing > research on that, it possible that he will work with thousands (or > millions) of weird constraints. > > I'm pretty sure about that: when the algorithms take 4 hours to test > a single execution, you value processor time. I'm no expert here, but this sounds like a sensible argument to me. OTHO, if the OP ends up spending more time writing boilerplate code and fighting with gory implementation details than working on the algorithm themselves, he might find than relative difference between two possible algorithms (like one takes 4 hours and the second take 2 1/2 hours, but each took less than one hour to implement) is much more important than having the first one taking 4 minutes, the second 2 1/2 minutes, and each having take 15 days to write and debug... > The situation would be simpler if there were good well-known toolkits > for optimization in python (like numpy for matrix operations), but > that's not the case. There's at least Psyco (if you're willing and able to restrict yourself from using some of the most dynamic parts of Python - which might not be a problem here). One could also mention stuff like Pyrex and Cython. From PurpleServerMonkey at gmail.com Sat May 24 05:38:00 2008 From: PurpleServerMonkey at gmail.com (PurpleServerMonkey) Date: Sat, 24 May 2008 02:38:00 -0700 (PDT) Subject: Python, Daemons and D-Bus Message-ID: <739ea057-0839-4836-bbf9-6f9538f6eeaf@s21g2000prm.googlegroups.com> Seeking feedback from group members on a design I'm looking at using in a project. I've created an XML-RPC server and a number of Daemons, the idea is that the XML-RPC server gets a request from a user interface of some sort and then sends data to the Daemon processes to do work. Daemons will also need to feed back task information to the XML-RPC server. For the communications between the Daemons and XML-RPC server I was thinking of using D-Bus (The project is for Linux and *BSD) but wanted to hear what others thought of the idea? Would you use D-Bus or a more traditional IPC method such as sockets? Although D-Bus is relatively new it looks interesting, just not sure it would work well in this kind of project. Thanks in advance for your thoughts and opinions. From johnjsal at NOSPAMgmail.com Tue May 20 13:22:28 2008 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 20 May 2008 13:22:28 -0400 Subject: Misuse of list comprehensions? References: <038e4418$0$27258$c3e8da3@news.astraweb.com> <6359d72c-f937-46cd-b1ce-b7450671b714@i76g2000hsf.googlegroups.com> <5fb0bcfd-0ce0-46cb-b273-7071c7694366@x35g2000hsb.googlegroups.com> Message-ID: <027e0bd9$0$26878$c3e8da3@news.astraweb.com> "Paul McGuire" wrote in message news:b56a93ee-b177-44fb-927a-1e204f491639 at t54g2000hsg.googlegroups.com... On May 20, 10:50 am, s0s... at gmail.com wrote: > def compress(s): > return list(set(s)) > > That does the trick. Wow, I just *knew* there had to be some built-in function that would make this problem trivial! :) Only if order does not need to be maintained. list(set(s)) will not necessarily keep the unique characters in the order they are seen. We'll have to check with the OP to see if this is important (I just assumed that it was because of the use of list comps). Good point. For me it doesn't matter because it wasn't my problem originally. I just had a question about the list comp. But if order matters, then I guess set doesn't work? From robert.kern at gmail.com Thu May 8 18:22:58 2008 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 08 May 2008 17:22:58 -0500 Subject: python vs. grep In-Reply-To: References: <011f43ea-9bc8-499a-a3fe-dba24b47932e@c58g2000hsc.googlegroups.com> Message-ID: Alan Isaac wrote: > Anton Slesarev wrote: >> I've read great paper about generators: >> http://www.dabeaz.com/generators/index.html Author say that it's easy >> to write analog of common linux tools such as awk,grep etc. He say >> that performance could be even better. But I have some problem with >> writing performance grep analog. > > https://svn.enthought.com/svn/sandbox/grin/trunk/ As the author of grin I can definitively state that it is not at all competitive with grep in terms of speed. grep reads files really fast. awk is probably beatable, though. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From ivan.illarionov at gmail.com Wed May 7 21:15:43 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Thu, 8 May 2008 01:15:43 +0000 (UTC) Subject: slicing lists References: Message-ID: On Wed, 07 May 2008 21:13:27 -0400, Miles wrote: > On Wed, May 7, 2008 at 7:46 PM, Ivan Illarionov > wrote: > > On Wed, 07 May 2008 23:29:27 +0000, Yves Dorfsman wrote: > > > > > Is there a way to do: > > > x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] > > > x[0,2:6] > > > > > > That would return: > > > [0, 3, 4, 5, 6] > > > > IMHO this notation is confusing. > > > > What's wrong with: > > [0]+x[2:6] > > I think Yves meant to return [1, 3, 4, 5, 6], as in Perl's list > slicing: > > my @x = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10); return @x[0, 2..6]; // returns > (1, 3, 4, 5, 6) So it should be x[0] + x[2:6] or x[0].extend(x[2:6]) From rossgk at gmail.com Wed May 28 12:01:01 2008 From: rossgk at gmail.com (RossGK) Date: Wed, 28 May 2008 09:01:01 -0700 (PDT) Subject: Python Threads - stopped vs. gone vs. Alive Message-ID: <1495901c-62c0-4977-8623-46deee092b56@26g2000hsk.googlegroups.com> I'm a newbie to python threads, and playing with some simple client server stuff and lots of print statements. My server thread launched with self.worker = WorkerThread(self) completes an interaction and then if I check on it's status with print "Status:", self.worker I get Status none A client thread behaves differently. Launched as self.clientWorker( = ClientThreadself) when it finishes it's work, I instead get: Status: If I check the isAlive status on each of those, self.worker.isAlive throws an exception, 'cause there is nothing there anymore to check isAlive on. But self.clientWorker comes back as False, since it is a stopped thread and hasn't gone away (which I'd like it to after it finishes its work). So my question is when a thread finishes its work how do I more predictably control whether it is just stopped, or goes away all together? I don't want to do a double nested 'if' statement to check if it exists before I check if it's alive. From skanemupp at yahoo.se Fri May 9 22:58:13 2008 From: skanemupp at yahoo.se (globalrev) Date: Fri, 9 May 2008 19:58:13 -0700 (PDT) Subject: regexp help References: <834d8448-5d6a-4f49-9be6-6501a0b5fd92@k37g2000hsf.googlegroups.com> <4824fcec$1@news.mel.dft.com.au> Message-ID: > The inner pair of () are not necessary. yes they are? ty anyway, got it now. From __peter__ at web.de Sun May 4 03:09:41 2008 From: __peter__ at web.de (Peter Otten) Date: Sun, 04 May 2008 09:09:41 +0200 Subject: word shifts References: Message-ID: dave wrote: > I made a function that takes a word list (one word per line, text file) > and searches for all the words in the list that are 'shifts' of > eachother. ?'abc' shifted 1 is 'bcd' > > Please take a look and tell me if this is a viable solution. > > ?def shift(word, amt): > ????????ans = '' > ????????for letter in word: > ????????????????ans = ans + chr((ord(letter) - ord('a') + amt) % 26 + ord('a')) > ????????return ans > > def fileshift(x): > ????????fin = open(x) > ????????d = {} > ????????for line in fin: > ????????????????d[line.strip()] = [1] > ????????????????for i in range(1, 26): > ????????????????????????ite = shift(line.strip(), i) > ????????????????????????if ite in d: > ????????????????????????????????print ite > > > Any tips/suggestions/critiques greatly appreciated.. I'm trying to > teach myself Python (and still beginning) and would love any helpful > info. My ideas: Move the open() call out of fileshift() and have it working with arbitrary iterables. Store a normalized version of the word in the dictionary. if every word in the dict is guaranteed to start with an "a" you can reduce the number of tests to one. If you have many words you can build a fast shift() function based on str.translate(). Invoke the following script both with and without a filename argument: from string import ascii_lowercase as chars, maketrans tables = [maketrans(chars, chars[i:] + chars[:i]) for i in range(26)] def shift(word, n): return word.translate(tables[n%26]) def normalize(word): a = word[0] return shift(word, ord("a") - ord(a)) def findshifted(words): d = {} for word in words: d.setdefault(normalize(word), []).append(word) return d if __name__ == "__main__": import sys args = sys.argv[1:] if args: words = (line.strip() for line in open(args[0])) else: import random sample = """\ alpha beta gamma delta """.split() words = sample + [shift(random.choice(sample), random.randrange(26)) for _ in range(10)] items = findshifted(words).items() items.sort() for k, v in items: print k, "-->", v Peter From b0bm00r3 at gmail.com Sun May 11 02:22:43 2008 From: b0bm00r3 at gmail.com (philly_bob) Date: Sat, 10 May 2008 23:22:43 -0700 (PDT) Subject: Keeping two lists aligned after processing Message-ID: <3695ddb4-373f-4702-bdb8-4d067778fa7a@e53g2000hsa.googlegroups.com> """ I have a population of five algorithms. Each Alg has a method, Alg.accuracy(), which calculates its accuracy. Running the accuracy method on each Alg, I end up with a list of accuracies like [0.75, 0.10, 0.45, 0.80, 0.45] Now I want to store the algorithms and associated accuracies in a file, in descending order of accuracy. Here's how I do it now. There must be a better way! This method is inelegant, and does not handle at all the issue of what to do with duplicate accuracies, such as the two different algorithms with 0.45 accuracies in the example above. It merely saves the first of the duplicates -- not what I want at all. I want to end up with a file: 0 AlgD 0.80 1 AlgA 0.75 2 AlgC 0.45 3 AlgE 0.45 4 AlgB 0.10 """ algs=['AlgA', 'AlgB', 'AlgC', 'AlgD', 'AlgE'] accs=[] for alg in algs: thisacc=getattr(alg.accuracy)() #comp.lang.python April accs.append(thisacc) unsortedaccs=[x for x in accs] # to preserve unsorted accs.sort() accs.reverse() # ending up with sorted list nuorder=[] for ax,acc in enumerate(accs): spot=unsortedaccs.index(acc) nuorder.append(spot) ofn=open('store.alg','w') for ord in nuorder: alg=algs[ord] acc=unsortedlist[ord] ofn.write("%d %s,%s" % (ord,alg,str(acc)) ofn.close() From mensanator at aol.com Mon May 12 14:47:42 2008 From: mensanator at aol.com (Mensanator) Date: Mon, 12 May 2008 11:47:42 -0700 (PDT) Subject: do you fail at FizzBuzz? simple prog test References: Message-ID: <17db55cb-20ca-4802-9067-f203a580bc21@27g2000hsf.googlegroups.com> On May 11, 7:05?pm, "Delaney, Timothy (Tim)" wrote: > Mensanator wrote: > > Ok, I agree with 101, but I wouldn't necessarily > > say the others were unfortunate. You might be > > surprised at how often such fixations discover > > bugs, something that I have a gift for. > > The discovering, the making, or both? ;) Both, of course. The trick is to catch your errors before anyone gets to see them. Then you get a reputation for being clever. > > Tim Delaney From miller.paul.w at gmail.com Mon May 26 14:57:39 2008 From: miller.paul.w at gmail.com (miller.paul.w at gmail.com) Date: Mon, 26 May 2008 11:57:39 -0700 (PDT) Subject: definition of a highlevel language? References: <2759eed3-956d-45c7-8dfb-9557f74133b3@56g2000hsm.googlegroups.com> Message-ID: <26d0b3d2-01cc-49bd-b284-1a849b0b835f@y38g2000hsy.googlegroups.com> On May 26, 2:34?pm, notnorweg... at yahoo.se wrote: I wanted to address some other points I failed to mention in my first response. > so are they fundamentally differently built or is it just a lot of > lowlevel operations built on top of each other? Partly. A high-level language is essentially one that gives you high- level operations, like "apply the function f to each element of the sequence seq, and return [f(seq[0]), f(seq[1]), ... f(seq[n])]. But, it's more than that. (You use Haskell as your example, but I'll use Python because I know it roughly a million percent better than Haskell... hehe.) In Python, you have support from the language to treat functions as first-class objects; in C, you explicitly cannot do this -- to map an arbitrary function over a sequence, you're restricted to accessing the function through a pointer. On the surface, it's the same operation, but that extra level of indirection can really bog one's mind down. Think about how difficult it is for a human to interpret the declaration of a function pointer in C, for instance. > haskell is considered a very highlevellanguage but can you do > systemsprogramming with it(yes maybe it is very unpractical i dont > know but can you)? > is lambda calculus a more abstract and efficient way of modeling a > computer? Lambda calculus doesn't model computers. It models *computation*. That is, given a Turing machine, there's a set of functions in the lambda calculus, which, when suitably combined, will yield the exact same result as the original Turing machine. That doesn't in any way imply that Turing machines work by interpreting lambda calculus. > how did lispmachines work? was the basic system programmed in LISP? Yes, the whole kit and kaboodle, all the way down to the microcode was programmed in LISP. In principle, there's no reason we couldn't have Haskell machines or Python machines. It's just that nobody's been crazy enough to do it, that I know of. :-) From dReEeMpOeVsEtT1H at IgSmail.com Thu May 29 19:30:05 2008 From: dReEeMpOeVsEtT1H at IgSmail.com (deepest1) Date: Fri, 30 May 2008 01:30:05 +0200 Subject: boost References: <1uv2h5-dii.ln1@satorlaser.homedns.org> Message-ID: Thanks for help. I lost more then 10 hours on boost today, but it finally works, and I'm pleased with it. :) From george.sakkis at gmail.com Wed May 21 18:32:53 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 21 May 2008 15:32:53 -0700 (PDT) Subject: Segmentation fault on updating a BYTEA field [psycopg2] Message-ID: I have a simple DB table that stores md5 signature pairs: Table "public.duplicate" Column | Type | Modifiers ----------+-------+----------- sig | bytea | not null orig_sig | bytea | not null Indexes: "duplicate_pkey" PRIMARY KEY, btree (sig) "ix_duplicate_orig_sig" btree (orig_sig) I use SqlAlchemy to interact with it and inserting works fine; update however crashes hard with a segfault. Sure enough, the crash is reproducible when using the underlying psycopg2 directly: >>> import psycopg2 >>> connect_string = ... >>> conn = psycopg2.connect(connect_string) >>> cur = conn.cursor() >>> cur.execute('SELECT sig,orig_sig from duplicate limit 1') >>> d = cur.fetchone() >>> d (, ) >>> map(str,d) ["\x02#qO\xb0\xcc\xfcx\xb9u\xa5\x83)\xc4'@", '\xa1\xf22\xf6y\xd0\xbc \xea6\xf0Y\xf1"\xc9(\n'] >>> cur.execute('UPDATE duplicate SET orig_sig=%(orig_sig)s WHERE duplicate.sig = %(duplicate_sig)s', ... dict(orig_sig=d[0], duplicate_sig=d[1])) Segmentation fault Am I (and SqlAlchemy) doing something silly or is this a bug in psycopg2 ? George From jorgen.maillist at gmail.com Wed May 21 04:45:21 2008 From: jorgen.maillist at gmail.com (Jorgen Bodde) Date: Wed, 21 May 2008 10:45:21 +0200 Subject: Print HTML from Python Message-ID: <11e49df10805210145g56b4266fjf94eb2c480fd9625@mail.gmail.com> Hi All, I am at a loss. This is slightly OT because it concerns Windows and HTML printing. I would like to print a HTML document from Python, but not showing the printing dialog. After numerous searches and trials I came to the conclusion that ShellExecute with the "print" command and a HTML document simply always shows a print dialog, so that road is a dead end (or unless someone can show me a snippet that does work). I used win32com and I am able to print through he internet explorer interface which seems to work, but quite unreliably. When I execute the scipt too fast, nothing is printed at all. The method isBusy that IE exposes through COM always returns False so there is no way to wait reliably on the progress of the printer. So basically my question is, does someone know a python lib or way to print HTML to the default printer (I can get the printer name so even that is not really needed) without showing the print dialog? With regards, - Jorgen From conradwt at gmail.com Tue May 13 20:29:59 2008 From: conradwt at gmail.com (Con) Date: Tue, 13 May 2008 17:29:59 -0700 (PDT) Subject: Install Python MySQL db module? Message-ID: Hi, how does properly install the Python MySQL db module for Mac OS X? I was only able to locate the Win32 modules. Thanks in advance, -Conrad From castironpi at gmail.com Wed May 14 14:04:43 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 14 May 2008 11:04:43 -0700 (PDT) Subject: named tuple mutability References: Message-ID: On May 14, 12:41?pm, Raymond Hettinger wrote: > >?Should tuples be named? > > Yes. Not clearly should. Sequences ought be. If you're on the right time for both, can't the library hold the B? From mathieu.prevot at gmail.com Sat May 24 08:09:07 2008 From: mathieu.prevot at gmail.com (Mathieu Prevot) Date: Sat, 24 May 2008 14:09:07 +0200 Subject: Popen: NameError: name 'PIPE' is not defined Message-ID: <3e473cc60805240509t207853dcm5240c110f723fad1@mail.gmail.com> Hi I import subprocess and use Popen, but PIPE is not defined. I used 2.5.1, 2.5.2, Python 2.6a3+ (trunk:63576, May 24 2008, 12:13:40), it's always the same. What am I missing ? Thanks Mathieu From gagsl-py2 at yahoo.com.ar Wed May 14 01:22:59 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 14 May 2008 02:22:59 -0300 Subject: Fill memeory with endless loop? References: <252c17a9-01a6-4abe-9515-2507e0e50a20@l64g2000hse.googlegroups.com> Message-ID: En Tue, 13 May 2008 15:18:31 -0300, globalrev escribi?: > On 13 Maj, 18:59, Filip ?t?dronsk? wrote: >> On ?t, kv? 13, 2008 at 06:49:33 +0200, globalrev wrote: >> >> > if i do something like >> > while 1: >> > print "x" >> >> > will the program ever stop because it runs out of memory? >> >> No, there is no reason to run out of memory. This will simply >> make an everlasting x-printer and there is no need to store >> anything [...] > > and when the program get skiled because out of memory all this will be > deleted from the memory? Yes. That's the operating system job. > so there is no way that you can, by accident, fill your whole > harddrive and make it unusable? > > and RAM-memory always get cleaned out when not used i guess? We were talking of RAM, including virtual memory backed by disk space. You *may* fill your whole disk if you keep writing data. If you invoke your example above using: python neverending.py > output the "output" file will grow indefinitely until you kill the program or you get a "disk full" exception. That disk space is not cleared when the program exits - you have to explicitely delete the file. Note that none of this is Python specific. -- Gabriel Genellina From rhamph at gmail.com Sun May 18 12:15:56 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Sun, 18 May 2008 09:15:56 -0700 (PDT) Subject: waiting on an event blocks all signals References: <27553255-72e6-4df6-944b-ac4637a78f3d@m3g2000hsc.googlegroups.com> <69auuoF2uob0sU1@mid.uni-berlin.de> Message-ID: <68e1821b-37e1-4c96-a812-2105ab305561@j33g2000pri.googlegroups.com> On May 18, 9:05 am, "Diez B. Roggisch" wrote: > alan schrieb: > > > This ignores CTRL-C on every platform I've tested: > > > python -c "import threading; threading.Event().wait()" > > ^C^C^C^C > > > It looks to me like all signals are masked before entering wait(). Can > > someone familiar with the internals explain and/or justify this > > behavior? Thanks, > > They aren't masked. Read the docs: > > # Although Python signal handlers are called asynchronously as far as > the Python user is concerned, they can only occur between the ``atomic'' > instructions of the Python interpreter. This means that signals arriving > during long calculations implemented purely in C (such as regular > expression matches on large bodies of text) may be delayed for an > arbitrary amount of time. > > (http://docs.python.org/lib/module-signal.html) > > Which is what is happening here - wait is implemented in C. So the > arriving signal is stored flagged in the interpreter so that the next > bytecode would be the signal-handler set - but the interpreter still > waits for the blocked call. If a signal arrives while the thread is in a syscall it will usually interrupt the syscall. Most code in the interpreter will see the EINTR error code and check if we have a signal to process, which leads to raising a KeyboardInterrupt exception. However, most thread synchronization functions specified in POSIX are not interrupted by signals, so the interpreter never has a chance do anything. Why would we care anyway, as Python doesn't let you intentionally interrupt a non-main thread? From miller.paul.w at gmail.com Mon May 26 15:18:47 2008 From: miller.paul.w at gmail.com (miller.paul.w at gmail.com) Date: Mon, 26 May 2008 12:18:47 -0700 (PDT) Subject: looking for membership management software -- Open Source, written in Python References: Message-ID: <014354fc-991d-4b56-99fb-5bebabd1ec79@59g2000hsb.googlegroups.com> On May 26, 10:36?am, Laura Creighton wrote: > I'm looking for an application that handles the membership of an > organisation -- who's a member, who has paid fees, addressbook and > the odd added field. > > Anybody got one they recommend? > It sounds like you essentially need a specialized database and an app to query the database. If this is a small organization (under 100 people, say), then the simplest solution would probably be a simple spreadsheet. Otherwise, maybe something like Organizers' Database (http://www.organizersdb.org/) would do the trick. I haven't actually used this software, but it looks like it's made to do exactly what you want to do. Hope that helps! From roy at panix.com Sat May 24 18:04:31 2008 From: roy at panix.com (Roy Smith) Date: Sat, 24 May 2008 18:04:31 -0400 Subject: Code correctness, and testing strategies References: Message-ID: David wrote: > Problem 1: You can only code against tests Yup. That's the flavor of Kool-Aide being served at a convenient TDD outlet near you. > Basically, with TDD you write the tests first, then the code which > passes/fails the tests as appropriate. However, as you're writing the > code you will also think of a lot of corner cases you should also > handle. The natural way to do this is to add them to the code first. That's only the natural way if you're haven't drunk the Kool-Aide :-) It takes a while to get used to, but once you get the hang of it, doing it this way becomes very natural. Sure, I think of corner cases when I'm writing code. But, what I do with them is write a test for them first, then write the code which implements it. From bruno.42.desthuilliers at websiteburo.invalid Tue May 20 04:29:45 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 20 May 2008 10:29:45 +0200 Subject: Compress a string In-Reply-To: References: Message-ID: <48328bf3$0$23651$426a34cc@news.free.fr> Matt Porter a ?crit : > Hi guys, > > I'm trying to compress a string. > E.g: > "AAAABBBC" -> "ABC" > > The code I have so far feels like it could be made clearer and more > succinct, but a solution is currently escaping me. > > > def compress_str(str): using 'str' as an indentifier will shadow the builtin str type. > new_str = "" > for i, c in enumerate(str): > try: > if c != str[i+1]: > new_str += c > except IndexError: > new_str += c > return new_str > > Now everyone gave smart solutions, may I suggest the stupidier possible one: def compress_string(astring): compressed = [] for c in astring: if c not in compressed: compressed.append(c) return ''.join(compressed) Not elegant, but at least very clear. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon May 19 15:58:07 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 19 May 2008 21:58:07 +0200 Subject: Compress a string References: Message-ID: <69e4efF31tjn1U2@mid.individual.net> inhahe wrote: > i see lots of neat one-liner solutions but just for the sake of > argument: > > def compress_str(str): > new_str = "" > lc = "" > for c in str: > if c != lc: new_str.append(c) > return new_str Please test before posting. >>> compress_str("AAAABBBBCCCCC") Traceback (most recent call last): File "", line 1, in File "", line 5, in compress_str AttributeError: 'str' object has no attribute 'append' Regards, Bj?rn -- BOFH excuse #48: bad ether in the cables From marlin_rowley at hotmail.com Fri May 16 19:23:03 2008 From: marlin_rowley at hotmail.com (Marlin Rowley) Date: Fri, 16 May 2008 18:23:03 -0500 Subject: More on numpy trickiness. In-Reply-To: References: Message-ID: All: Say I have an array: a = (['rrrrggggbbbbaaaa'],['rrrrggggbbbbaaaa']) How do I make it so that I now have: starting with first element (a[0])new_arr[0] = 'r'new_arr[1] = 'g'new_arr[2] = 'b'new_arr[3] = 'a'new_arr[4] = 'r'..... continuing "through" a[1] with the same new_arrnew_arr[N] = 'r'new_arr[N+1] = 'g'.... -M _________________________________________________________________ E-mail for the greater good. Join the i?m Initiative from Microsoft. http://im.live.com/Messenger/IM/Join/Default.aspx?source=EML_WL_ GreaterGood -------------- next part -------------- An HTML attachment was scrubbed... URL: From giraffeboy at gmail.com Wed May 21 06:30:04 2008 From: giraffeboy at gmail.com (giraffeboy at gmail.com) Date: Wed, 21 May 2008 03:30:04 -0700 (PDT) Subject: Database Query Contains Old Data Message-ID: <33b13117-0f9f-435d-b8f8-19f1ed3a121a@d77g2000hsb.googlegroups.com> Hi there, I'm having a problem with the Python db api, using MySQL. I've written a program with a GUI using wxPython, the GUI is contained in main.py which imports another module - reports.py. There are several reports that are selected using the gui, and each report is a class in the file reports.py. These classes contain a method which is passed data as arguments and produces a report, writing HTML to a file and using matplotlib to create a graph file. The report class methods are called from the GUI using the following code: agentlist = self.getselected() detail = self.cb1.GetValue() if self.getdates() != False: fromdate, todate = self.getdates() app.mainframe.SetStatusText("Generating Report...") if self.reportchoice.GetSelection() == 0: thereport = reports.VehicleRunningCost() thereport.producereport(agentlist, fromdate=fromdate, todate=todate, detail=detail) app.mainframe.SetStatusText("Report Complete") viewerframe = ViewerFrame(None, -1, "Mileage and Fuel Report Viewer") viewerframe.Show(True) The first time you run a report, everything works as expected but if you run it a second time, after modifying data, it seems that the data from before the modification is selected on the second report run. It would be much appreciated if anyone could give me any hints as to why the old data is selected. I haven't posted the full code because it's quite long but will post more if anyone wants to see specific parts. Thanks! Andrew From vinay_sajip at yahoo.co.uk Thu May 29 05:16:19 2008 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Thu, 29 May 2008 02:16:19 -0700 (PDT) Subject: Custom log handler and logging.config.fileConfig() References: Message-ID: <72799b9c-bf89-4c50-9e9a-30f0f5a895dd@i76g2000hsf.googlegroups.com> On May 28, 9:53 pm, "Lowell Alleman" wrote: > Here is the situation: I wrote my own log handler class (derived fromlogging.Handler) and I want to be able to use it from aloggingconfig > file, that is, a config file loaded with thelogging.config.fileConfig() function. > > Let say myloggingclass is called "MyLogHandler" and it's in a module > called "mylogmodule", I want to be able to make an entry something > like this in myloggingconfig file: > > [handler_hand02] > class=mylogmodule.MyLogHandler > level=DEBUG > formatter=form02 > args=('python.log', 10, True) > > I did some digging in the code and documentation, and it doesn't > appear that this question of writing and accessing your own log > handlers is addressed. As per thelogging/config.py code, it looks > like the actual file handler classes are being grabbed using an "eval" > from the "logging" module's namespace, like so: > klass = eval(klass, vars(logging)) > > So this basically means that I have to mess with the "logging" > module's namespace if I want this to work, right? So I've come up > with a couple of options, but I'm trying to figure out what approach > is best: > > Option 1: Require the client (the user of myloggingmodule), first > import my module and then copy it into theloggingmodule's namespace, > before calling fileConfig(). Something like this: > > import mylogmodule > importlogging > logging.mylogmodule = mylogmodule > > Option 2: Have my module make a copy MyLogHandler class into thelogging(orlogging.handlers) module, and then let the client use it > from their directly. They client would still have to load mylogging > class first (which isn't any different they what they would have to do > if they wanted to use the extended log handlers form thelogging.handlers module) > > My module would include: > importlogging > class MyLogHandler(logging.Handler): > ... > logging.MyLogHandler = MyLogHandler > > The config file would simply have: > class=MyLogHandler > > Option 3: Is there an easy (and non-evil) way for me to make my > module available as "logging.mylogmodule" directly? I am using > setuptools, and it seems like what I've read about "namespaces", they > do something close to what I'm looking for, but I think that requires > that all of the "__init__.py"s involved be empty (or have some special > namespace declaration code). The __init__.py for theloggingmodule > is not at all empty, so I suppose that rules out this option? Anyone > have some insights on this? > > Thanks in advance, > > - Lowell Alleman Hi Lowell, I think it's OK to use the logging.handlers namespace to add your custom handlers - after all, the handlers namespace is for holding handlers other than the basic ones included in "logging". So... # -- myhandler.py --- import logging.handlers class MySpecialHandler(logging.handlers.RotatingFileHandler): def __init__(self, fn): logging.handlers.RotatingFileHandler.__init__(self, fn, maxBytes=2000, backupCount=3) # -- logging.ini --- [loggers] keys=root [handlers] keys=hand01 [formatters] keys=form01 [logger_root] level=NOTSET handlers=hand01 [handler_hand01] class=handlers.MySpecialHandler level=NOTSET formatter=form01 args=("rotating.log",) [formatter_form01] format=%(asctime)s %(levelname)s %(message)s datefmt= class=Formatter # -- app.py --- import logging.handlers, logging.config from myhandler import MySpecialHandler logging.handlers.MySpecialHandler = MySpecialHandler logging.config.fileConfig("logging.ini") logger = logging.getLogger("test") for i in xrange(100): logger.debug("Message no. %d", i) should produce the expected results. From squareswallower at invalid.com Sun May 4 01:17:07 2008 From: squareswallower at invalid.com (dave) Date: Sat, 3 May 2008 23:17:07 -0600 Subject: word shifts Message-ID: Hello, I made a function that takes a word list (one word per line, text file) and searches for all the words in the list that are 'shifts' of eachother. 'abc' shifted 1 is 'bcd' Please take a look and tell me if this is a viable solution. def shift(word, amt): ans = '' for letter in word: ans = ans + chr((ord(letter) - ord('a') + amt) % 26 + ord('a')) return ans def fileshift(x): fin = open(x) d = {} for line in fin: d[line.strip()] = [1] for i in range(1, 26): ite = shift(line.strip(), i) if ite in d: print ite Any tips/suggestions/critiques greatly appreciated.. I'm trying to teach myself Python (and still beginning) and would love any helpful info. thanks! From wmcbrine at users.sf.net Sat May 24 20:36:28 2008 From: wmcbrine at users.sf.net (William McBrine) Date: Sun, 25 May 2008 00:36:28 GMT Subject: Assignment and comparison in one statement References: <10f19bee-1e0a-4401-a03b-18c458388297@s50g2000hsb.googlegroups.com> Message-ID: On Sat, 24 May 2008 13:12:13 +0200, Johannes Bauer wrote: > char *tmp; > tmp = fgets(buf, sizeof(buf), f); > while (tmp) { > printf("%s\n", buf); > tmp = fgets(buf, sizeof(buf), f); > } I think a more Pythonic way to write this, in general, would be: while (1) { char *tmp = fgets(buf, sizeof(buf), f); if (!tmp) break; printf("%s\n", buf); } In actual Python, that's: while True: buf = f.readline() if not buf: break print buf Yeah, it's longer than the traditional C way, but you don't need to have duplicate fgets() (or whatever) lines. On the plus side, you're less likely to get '=' and '==' accidentally swapped in Python. For this specific example, it can be cut down much more: for buf in f.readlines(): print buf (BTW, all of the above result in doublespacing the original file, but that's what your C version was doing, so I kept it that way.) -- 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -- pass it on From tjreedy at udel.edu Fri May 9 16:02:58 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 9 May 2008 16:02:58 -0400 Subject: multiple Python versions, but on Windows (how to handle registry updates) References: <3de8e1f70805090358p27796919jb885138406ade6aa@mail.gmail.com> Message-ID: "Gabriel Genellina" wrote in message news:op.uav4dutjx6zn5v at a98gizw.cpe.telecentro.net.ar... En Fri, 09 May 2008 07:58:33 -0300, Banibrata Dutta escribi?: |> I already have Python25, and need to install Python24. I would prefer not to |> remove Python25, but each Python version seems to update the registry, I |> guess (not sure), overwriting each other's entries. Any way to have both |> versions ? |They can coexist peacefully. The last one you install will be the default |version to handle .py files automatically. Since 2.5 at least, the Windows installer gives the option to make the new installation the default or not. One might have to choose 'custom' versus 'auto' (don't remember for Python), but I do the latter always anyway. tjr From justin.mailinglists at gmail.com Tue May 6 21:45:28 2008 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: Tue, 6 May 2008 18:45:28 -0700 (PDT) Subject: how to use subprocess.Popen execute "find" in windows References: <5666ed04-8a2f-4dad-b7bc-3e3c3c084f03@f24g2000prh.googlegroups.com> Message-ID: <708883cd-5cc8-4507-b91e-841dd10d149a@c19g2000prf.googlegroups.com> On May 6, 5:19 pm, clyf... at gmail.com wrote: > In cmd, I can use find like this. > > C:\>netstat -an | find "445" > TCP 0.0.0.0:445 0.0.0.0:0 LISTENING > UDP 0.0.0.0:445 *:* > > C:\> > > And os.system is OK.>>> import os > >>> os.system('netstat -an | find "445"') > > TCP 0.0.0.0:445 0.0.0.0:0 LISTENING > UDP 0.0.0.0:445 *:* > 0 > > > > But I don't know how to use subprocess.Popen to do this. > > from subprocess import Popen, PIPE > > p1 = Popen(['netstat', '-an'], stdout = PIPE) > p2 = Popen(['find', '"445"'], stdin = p1.stdout, stdout = PIPE) > print p2.stdout.read() > > It doesn't work. > Because subprocess.Popen execute "find" like this. > > C:\>find \"445\" > ???? - \ > > C:\> > > It adds a '\' before each '"'. > How to remove the '\'? > Thank you. cannot help with the backslashes but try findstr instead of find From zerty.david at gmail.com Thu May 8 20:28:25 2008 From: zerty.david at gmail.com (David Anderson) Date: Thu, 8 May 2008 21:28:25 -0300 Subject: Cannot import opj Message-ID: <5dc598e30805081728i7d451bber36991f5a547874a7@mail.gmail.com> I'm trying to import the opj module Trying like this: from Main import opj It says it doesn't exists And like this: import os.path.join as opj Raises error. What should I do? -------------- next part -------------- An HTML attachment was scrubbed... URL: From skanemupp at yahoo.se Thu May 1 12:07:58 2008 From: skanemupp at yahoo.se (globalrev) Date: Thu, 1 May 2008 09:07:58 -0700 (PDT) Subject: PyGame, window is not closing, tut not helping References: <2cda1f18-2ebd-49a2-8359-e922d9d1451e@m73g2000hsh.googlegroups.com> Message-ID: <2d4d6a94-cac4-4359-962d-dff23ab42466@y38g2000hsy.googlegroups.com> another program that has the same problem: import sys, pygame pygame.init() size = width, height = 320, 240 speed = [2, 2] black = 0, 0, 0 screen = pygame.display.set_mode(size) ball = pygame.image.load("snake.png") ballrect = ball.get_rect() while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() ballrect = ballrect.move(speed) if ballrect.left < 0 or ballrect.right > width: speed[0] = -speed[0] if ballrect.top < 0 or ballrect.bottom > height: speed[1] = -speed[1] screen.fill(black) screen.blit(ball, ballrect) pygame.display.flip() From bruno.42.desthuilliers at websiteburo.invalid Wed May 21 07:25:33 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 21 May 2008 13:25:33 +0200 Subject: Showing the method's class in expection's traceback In-Reply-To: References: <79c7d6fb-a6b8-481f-9a36-81b980628710@59g2000hsb.googlegroups.com> <69bi20F31j4kdU1@mid.uni-berlin.de> Message-ID: <483406a0$0$10773$426a74cc@news.free.fr> Gabriel Genellina a ?crit : > En Sun, 18 May 2008 17:31:44 -0300, Diez B. Roggisch > escribi?: >> Agustin Villena schrieb: > >>> is there anyway to show the class of a method in an exception's >>> traceback? >>> >>> I want to improve the line File "G:\dev\exceptions\sample.py", >>> line 3, in foo >>> >>> to File "G:\dev\exceptions\sample.py", line 3, in Some.foo >>> >>> Is this improvement feasible >> It should be. You can get a dictionary of the locals of an >> exception stack frame, of which you could extract the >> self-parameter's class. > > That by itself is not enough, the method could be inherited; one > should walk the base classes in the MRO to find the right one. And > deal with classmethods and staticmethods. And decorators that don't > preserve meta information... And monkeypatches. > Hmmm, I think it isn't so trivial as it > seems. And not that useful - why would one care about the function being defined in class X or Y when one have the exact file and line ? From dstanek at dstanek.com Tue May 20 16:16:31 2008 From: dstanek at dstanek.com (David Stanek) Date: Tue, 20 May 2008 16:16:31 -0400 Subject: scaling problems In-Reply-To: References: Message-ID: On Tue, May 20, 2008 at 12:03 AM, James A. Donald wrote: > On Mon, 19 May 2008 21:04:28 -0400, "David Stanek" > wrote: >> What is the difference if you have a process with 10 threads or 10 >> separate processes running in parallel? Apache is a good example of a >> server that may be configured to use multiple processes to handle >> requests. And from what I hear is scales just fine. >> >> I think you are looking at the problem wrong. The fundamentals are the >> same between threads and processes. > > I am not planning to write a web server framework, but to use one. > Doubtless a python framework could be written to have satisfactory > scaling properties, but what are the scaling properties of the ones > that have been written? > Both Django and TurborGears work well for me. When you step back and think about it all of the popular web frameworks would do just fine. The ones that don't do multiprocessing out of the box would be trivial to load balance behind Apache or a real load balancer. Again the problem here is the number of connections to the database, once you get big enough to worry about it. -- David http://www.traceback.org From bignose+hates-spam at benfinney.id.au Thu May 8 18:35:23 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 09 May 2008 08:35:23 +1000 Subject: Surprising difference in behavior between "import blah" and "from blah import thing" References: <874p984o4c.fsf@offby1.atm01.sea.blarg.net> <88edf8eb-c043-46f3-8ccb-653ffac10703@y18g2000pre.googlegroups.com> Message-ID: <87y76ka0gk.fsf@benfinney.id.au> offby1 writes: > Ah. So from the point of view of mut.py, "thing" and "system.thing" > are separate, unrelated variables; No. Thinking of them as "variables" (with all the non-Python terminological baggage that implies) will only exacerbate the confusion. "thing" and "system.thing" are separate *names*, that can be independently bound to different objects or the same object. > the former of which is initialized from the latter when mut says > "from system import thing". Rather, the name "thing" is bound to the same object as the name "system.thing" at the time "from system import thing" is executed. What happens to the name "system.thing" afterward has no effect on the name "thing". -- \ "Listen: we are here on Earth to fart around. Don't let anybody | `\ tell you otherwise." -- _Timequake_, Kurt Vonnegut | _o__) | Ben Finney From martin at v.loewis.de Mon May 12 13:37:48 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 12 May 2008 19:37:48 +0200 Subject: Learning Python for no reason In-Reply-To: <0383f3b8$0$27282$c3e8da3@news.astraweb.com> References: <0383f3b8$0$27282$c3e8da3@news.astraweb.com> Message-ID: <4828806c$0$11583$9b622d9e@news.freenet.de> > Hopefully this question even makes sense! I completely agree that you don't need to spend time on learning a language if you don't plan on using it; I'll leave alone the entire discussion of doing things for fun only (you don't *need* to eat ice cream, either - right?) OTOH: do you plan to do any programming at all, in your life? If yes: consider using Python for every programming task you'll encounter - unless there are outside constraints demanding a different language. Python is flexible enough for *all* you programming needs (I claim); then the acquired knowledge will be useful. To be effective in a language, you need to be fluent in it. This involves both passive reading, as well as active experimentation. HTH, Martin From vdv100 at gmail.com Sun May 4 11:28:54 2008 From: vdv100 at gmail.com (Valerio Valerio) Date: Sun, 4 May 2008 16:28:54 +0100 Subject: Image grab in Python In-Reply-To: <18c1e6480805040741p8c76a33q2f5464932b6524ff@mail.gmail.com> References: <18c1e6480805040741p8c76a33q2f5464932b6524ff@mail.gmail.com> Message-ID: I can grab the image, I need a way of grab the region size with the mouse, a easy way of the user select a region of the image to analyze, something like the "Rectangle selection tool" of gimp. Regards, -- Val?rio Val?rio http://www.valeriovalerio.org 2008/5/4 David : > On Sun, May 4, 2008 at 4:25 PM, Valerio Valerio wrote: > > Hi, > > > > anyone know a Python library to grab the size of a selected image region > > (the selection will be made with the mouse), that work in Linux ? > > You might be able to use this tool: > > http://freshmeat.net/projects/gtkshots/ > > David. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From zer0dyer at verizon.net Mon May 26 20:05:44 2008 From: zer0dyer at verizon.net (Curtis) Date: Tue, 27 May 2008 00:05:44 GMT Subject: php vs python In-Reply-To: References: <5l%Yj.77$mz3.53@fe101.usenetserver.com> <37b112d8-a3ba-446d-9d2f-d907d93c637b@w8g2000prd.googlegroups.com> <-t-dnWQ4bZN2MaTVnZ2dnUVZ_qGdnZ2d@comcast.com> <68cb8bb1-4cc5-4a28-8915-46e7d4e316d9@d1g2000hsg.googlegroups.com> <9IWdnbyQq5GKl6fVnZ2dnUVZ_oGdnZ2d@comcast.com> Message-ID: I V wrote: > On Sun, 25 May 2008 21:41:09 -0400, Jerry Stuckle wrote: >> The the good programmers are able to adapt to the language and make the >> most of whatever language they're using. The result is good code. OTOH, >> poor programmers I have known have found all kinds of excuses - from the >> language itself to lack of requirements, to anything else they can >> blame, except the real root of the problem. > > That's true - but I wonder if there might not be differences at the > margins. Some languages (and, which is not quite the same but not easy to > fully distinguish either, the communities around some languages) may > encourage mediocre programmers to produce slightly more or less mediocre > programs. > > Some features of Python (the one that really stands out for me is not > default-initializing variables on first use; the comparatively clean > standard library might be another), and some features of the Python > community (which, IME, has more members more explicitly committed to > writing clean code) I think do make Python a better environment for us > mediocre programmers. If you set PHP to show notices, it will tell you of such cases. However, the way I learned good programming practice was talking with other programmers, and trying different languages. I think if you have a real desire to write good code, and work at it, you can accomplish your task, regardless of the language. However, there is definitely a prevalent amount of poorly written PHP on the Web, so it can be easy for a newcomer to pick up some bad practices. This isn't a fault of the design of the language, though. > But maybe I'm wrong - I've never been paid to write Python programs, > whereas I have been paid to write PHP, so I might just be projecting my > frustrations with work onto the language. I've also not used PHP5 much in > anger, which does look to be a lot nicer than earlier versions. Yeah, PHP5 is awesome, and PHP4 is dead/dying. -- Curtis From fc14301589 at icqmail.com Wed May 28 06:38:47 2008 From: fc14301589 at icqmail.com (TheSaint) Date: Wed, 28 May 2008 18:38:47 +0800 Subject: graphical ide?? References: <1d3e7b3c-1767-4c26-ba4c-cba86189f8c7@k30g2000hse.googlegroups.com> Message-ID: <483d3639_1@news.tm.net.my> On 19:48, marted? 27 maggio 2008 Alex Gusarov wrote: > I tried Eric (on windows), but then decided in favour of Eclipse + > PyDev. I'm a KDE fan :) and I like Qt design. I've Qt designer installed, but I much like if I can use an IDE which write python code, rather than wrappers. I've just been disappointed by Boa Constructor, it disappeared suddenly while trying some test. Which other SDK write in python code? From kamhung.soh at gmail.com Wed May 28 20:02:29 2008 From: kamhung.soh at gmail.com (Kam-Hung Soh) Date: Thu, 29 May 2008 10:02:29 +1000 Subject: convert string number to real number - ValueError: invalid literal for int() with base 10: '"2"' In-Reply-To: References: <3ca86e1d-a32f-48f2-bc9a-6cb792c0c631@z17g2000hsg.googlegroups.com> <20080228181914.6307257e.darcy@druid.net> <491b0d8f0805270900r4950360bjee559f9c86fb43b9@mail.gmail.com> Message-ID: Matthias Bl?sing wrote: > Am Wed, 28 May 2008 10:41:51 -0700 schrieb davidj411: > >> I like the str2num function approach, but then i get left with a float >> that has more than 2 decimal spaces , i.e. 11.50 becomes >> 11.449999999999999 and round will not fix that. > > Welcome to the wonderful world of floating point numbers. For your usage > you want 10-based numbers. Have a look at the decimal module: > >>>> from decimal import Decimal >>>> a = Decimal("11.45") >>>> a > Decimal("11.45") >>>> str(a) > '11.45' >>>> a + 1 > Decimal("12.45") >>>> a + Decimal("1.55") > Decimal("13.00") > > HTH > > Matthias > -- > http://mail.python.org/mailman/listinfo/python-list > Thanks for the tip, Matthias. I knew that there had to be a way to handle arbitrary precision numbers. -- Kam-Hung Soh Software Salariman From oldmantaggie at gmail.com Wed May 14 14:19:05 2008 From: oldmantaggie at gmail.com (John Chandler) Date: Wed, 14 May 2008 13:19:05 -0500 Subject: Submitting data to HTTPS javascript Message-ID: <8e087c6d0805141119y7637732cr37288492d7601f27@mail.gmail.com> I am trying to write a script to test certain functionality of a website that requires users to login. The login page is simple, a few pictures and two text bars (one for username and one for password). I tried logging in with webbrowser, but that did not work because the page uses javascript. I also tried using win32com though I have no idea what I am doing. Any ideas? -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Tue May 13 11:50:04 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 13 May 2008 17:50:04 +0200 Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <2b66a86e-5a05-4262-b3c9-4703b0ae3372@d1g2000hsg.googlegroups.com> <5b0e3f70-afde-4480-8713-e7113b1250d7@x35g2000hsb.googlegroups.com> <1f537717-00d0-48ee-99b6-7125b96a6133@t12g2000prg.googlegroups.com> <68t4o0F2vaoncU1@mid.uni-berlin.de> <2a32179a-9439-449c-bd07-fff6a4075aee@s50g2000hsb.googlegroups.com> <7ee5dffd-df8f-46f0-bd78-c81ac0418a9a@d77g2000hsb.googlegroups.com> <65ef773e-a1c3-4adb-a18b-e8b8451efe5e@b5g2000pri.googlegroups.com> Message-ID: <68trmmF2vjivnU1@mid.uni-berlin.de> > Also, several users have rewritten their Python programs in Flaming > Thunder, and found that Flaming Thunder was 5 to 10 times faster > (Flaming Thunder compiles to native executables). So again, since > many people value their time at more than $0, I think that many people > will find that Flaming Thunder is worth $19.95 per year. 5-10 times faster for what kind of code? I don't see anything that resembles OO features of python, let alone more advanced concepts like meta-programming, higher-order functions and such. Which save tremendous amounts of time coding. If FT grows these and *still* is 5-10 times faster, I'll salut you. And what is really expensive is brain-cycles, not cpu-cycles. Which above described features save. > Plus, me getting paid to work on Flaming Thunder is far more > motivating than me not getting paid to work on Python. This weekend, > Python users will still be debating how to fix awkwardnesses in the > languages (such as FOR loops where you're just counting the loops and > not referencing the loop variable) -- but Flaming Thunder users will > be getting work done using the REPEAT n TIMES constructs that I'll be > implementing. > > Python has been around about 15 years, yet still has those > awkwardnesses. Flaming Thunder has been out less than 6 months and > those awkwardnesses are already getting fixed. The difference: I > can't afford to ignore users. Oh *please*! Try getting nearly as feature & library complete as python is today - and *then* I'll point to all the akwardness of FT. Let alone it is very much a question of view-point if two different looping constructs or keywords are more awkward than one general looping-concept with only one keyword. It's a matter of taste. Diez From greg at cosc.canterbury.ac.nz Fri May 9 04:56:18 2008 From: greg at cosc.canterbury.ac.nz (greg) Date: Fri, 09 May 2008 20:56:18 +1200 Subject: ANN: Pyrex 0.9.7 Message-ID: Pyrex 0.9.7 is now available: http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/ Highlights of this version: * I have streamlined the integer for-loop syntax. Instead of the loop variable redundantly appearing in two places, it's now just for x < i < y: ... * If you declare a variable as a list or dict, then calls to some of its methods will be compiled into type-specific Python API calls instead of generic ones. * Most built-in constants are referenced directly instead of via dict lookup. * There are two new builtin functions, typecheck() and issubtype(), for checking the types of arguments more safely (since isinstance and issubclass can be fooled). What is Pyrex? -------------- Pyrex is a language for writing Python extension modules. It lets you freely mix operations on Python and C data, with all Python reference counting and error checking handled automatically. From offby1 at blarg.net Thu May 8 15:00:51 2008 From: offby1 at blarg.net (Eric Hanchrow) Date: Thu, 08 May 2008 12:00:51 -0700 Subject: Surprising difference in behavior between "import blah" and "from blah import thing" Message-ID: <874p984o4c.fsf@offby1.atm01.sea.blarg.net> (This is with Python 2.5.2, on Ubuntu Hardy, if it matters.) This seems so basic that I'm surprised that I didn't find anything about it in the FAQ. (Yes, I am fairly new to Python.) Here are three tiny files: ==== mut.py ==== import system from system import thing def doit(): print " thing is", thing def do_it_slightly_differently(): print "system.thing is", system.thing ==== system.py ==== thing = "I am the original thing!!" ==== test.py ==== import mut mut.doit() mut.do_it_slightly_differently() import system system.thing = "The new improved thing" mut.doit() mut.do_it_slightly_differently() When I run "python test.py", I see thing is I am the original thing!! system.thing is I am the original thing!! thing is I am the original thing!! system.thing is The new improved thing What surprises me is that the assignment to "system.thing" in test.py only seems to affect the use of "system.thing" in mut.py, and not affect the use of just plain "thing" in that same file. I would have expected my assignment to have affected both, or perhaps neither. I have no idea why these two differ. Can someone explain? -- Rarely do we find men who willingly engage in hard, solid thinking. There is an almost universal quest for easy answers and half-baked solutions. Nothing pains some people more than having to think. -- Martin Luther King, Jr. from "Strength to Love," 1963. From simon at brunningonline.net Fri May 23 08:29:24 2008 From: simon at brunningonline.net (Simon Brunning) Date: Fri, 23 May 2008 13:29:24 +0100 Subject: Books for learning how to write "big" programs In-Reply-To: <219c77ef-dd0c-464b-bb6a-e4f3bee89eae@x41g2000hsb.googlegroups.com> References: <219c77ef-dd0c-464b-bb6a-e4f3bee89eae@x41g2000hsb.googlegroups.com> Message-ID: <8c7f10c60805230529v490577dfg3727591192c71537@mail.gmail.com> On Thu, May 22, 2008 at 4:55 PM, duli wrote: > Hi: > I would like recommendations for books (in any language, not > necessarily C++, C, python) which have walkthroughs for developing > a big software project ? So starting from inception, problem > definition, design, coding and final delivery on a single theme > or application. With regard to the arcitecture of systems rather than process, there are some good boos liked to from here: . Patterns of Enterprise Application Architecture in particular is a bit of a classic. -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues | Twitter: brunns From larzluv at hotmail.com Sun May 11 00:41:33 2008 From: larzluv at hotmail.com (Larry Hale) Date: Sat, 10 May 2008 21:41:33 -0700 (PDT) Subject: Module python-magic on/for Windows? Message-ID: I've heard tell of a Python binding for libmagic (file(1) *nixy command; see http://darwinsys.com/file/). Generally, has anybody built this and worked with it under Windows? The only thing I've been able to find is the python-magic module at http://hupp.org/adam/hg/python-magic/. [1] Is this "THE" python-magic module. (It seems to be to me, but obviously I don't know. :) [2] Has anybody been able to build THIS version under Windows? I've gotten as far as completing the "setup.py install" process. (After many troubles; I'll post the top-to-bottom HowTo-like info if/ when I ever get it to work. :) At this point, there -is- a "magic" module that can be imported (attempted-to, that is), but it fails. If I go to a cmd window, run the Py interpreter, and do "import magic" I get: [1] an error pop-up (Windows window, which is blocking [as opposed to "non-blocking", not "obscuring", though it does that, too] the cmd window): (X) This application has failed to start because magic1.dll was not found. Re-installing the application may fix this problem. [OK] [2] then, within the interpreter, I get: Traceback (most recent call last): File "", line 1, in File "build\bdist.win32\egg\magic.py", line 2, in File "build\bdist.win32\egg\cmagic.py", line 7, in File "build\bdist.win32\egg\_cmagic.py", line 7, in File "build\bdist.win32\egg\_cmagic.py", line 6, in __bootstrap__ ImportError: DLL load failed: The specified module could not be found. I'm using Python 2.5 on Windows XP Pro. I've got CYGWIN installed (more info can be provided if necessary) for a copy of file.exe (and libmagic.a @ 357KB and libmagic.dll.a @ 25KB in C:\cygwin\lib). I also have GNUWin32, also for file.exe alternatively (and libmagic.dll.a @ ~ 8KB in C:\Program Files\GnuWin32\lib). magic.py in C:\Program Files\Python25\Lib\site-packages\magic-0.1- py2.5-win32.egg imports cmagic.py (also in this egg), which imports _cmagic.py, which has the following: def __bootstrap__(): global __bootstrap__, __loader__, __file__ import sys, pkg_resources, imp __file__ = pkg_resources.resource_filename(__name__,'_cmagic.pyd') del __bootstrap__, __loader__ imp.load_dynamic(__name__,__file__) __bootstrap__() Now I *presume* my problem (at this point) is that I need to have libmagic named as "magic1.dll" -wherever- this module is looking for it. I'm just not sure, let alone if this is true, WHERE Python/ modules expect to find such things. Also, which version(s)/file(s) should be placed where, or...?? Thanks for any/all help/pointers. I apologize up-front if I left out any pertinent info; I'm paranoid about putting in too much (and some that may be worthless) already... :) Cheers, Larry Hale From eliben at gmail.com Sat May 17 14:35:32 2008 From: eliben at gmail.com (eliben) Date: Sat, 17 May 2008 11:35:32 -0700 (PDT) Subject: Distributing applications that use 3rd party modules References: <8728ad1c-2b4a-47db-aeda-8d2416b6bdc8@i76g2000hsf.googlegroups.com> Message-ID: On May 17, 8:54 pm, "Terry Reedy" wrote: > "eliben" wrote in message > > news:b439e7f0-685b-46b6-b0ea-3161cc548868 at m45g2000hsb.googlegroups.com... > | Is there a simple way to find out which packages are used by my > | script ? > > Ggrep for import statements? This isn't very comprehensive :-) > (But that only only gives direct dependencies.) > Does py2exe have an option to output the list it collects?| > I think people have mentioned such here. Digging around the standard library documentation, I came upon the 'modulefinder' module, which seems to be able to do what I want, at least in terms of finding all the modules used. I wonder how difficult it should be to wrap something around modulefinder that copies all the relevant modules into a local directory and modifies sys.path accordingly. Eli From sarenius at sun3.oulu.fi Sun May 25 23:09:07 2008 From: sarenius at sun3.oulu.fi (Vesa-Matti Sarenius) Date: Mon, 26 May 2008 03:09:07 +0000 (UTC) Subject: UTF problem? References: Message-ID: In article , Dennis Lee Bieber wrote: >(Vesa-Matti Sarenius) declaimed the following in comp.lang.python: > And what reported the file not found -- some line of the Python >script, or a spawned shell (since the line you point out is just >creating a command to be executed a subprocess of some sort) I think that would be the gsprint.exe. > The other matter would be: is the shell that command is passed off >to using the same encoding? That would be the windows shell (command prompt) and I know so little of windows so I would not know... -- Vesa-Matti Sarenius, M.Sc. * * * * * * * * * * * * * * * * * mailto:sarenius at koivu.oulu.fi * Music seems to help the pain * Lecturer, mathematics education * R.I.P. Syd, my hero * University of Oulu, Finland * * * * * * * * * * * * * * * * * From exarkun at divmod.com Thu May 8 11:50:42 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 8 May 2008 11:50:42 -0400 Subject: How to kill Python interpreter from the command line? In-Reply-To: <10fdb79d-8ac2-4bf3-bbdc-a825ae2c44c8@l42g2000hsc.googlegroups.com> Message-ID: <20080508155042.6859.1822443718.divmod.quotient.60559@ohm> On Thu, 8 May 2008 08:29:33 -0700 (PDT), spectrumdt at gmail.com wrote: >Hello. > >I am running Fedora Linux and KDE, using the Konsole command line. > >When coding Python, I regularly make a bug causing my program to not >terminate. But how do I kill the non-terminating Python interpreter >without killing the entire Konsole? > >The default way of killing the current process on the command line is >Ctrl+C, but that doesn't work with Python. Neither do the "terminate >task", "suspend task" or "interrupt task" commands (available from >right-click in Konsole). Ctrl+C often works with Python, but as with any language, it's possible to write a program which will not respond to it. You can use Ctrl+\ instead (Ctrl+C sends SIGINT which can be masked or otherwise ignored, Ctrl+\ sends SIGQUIT which typically isn't) or you can use the kill command. You can either use it in another terminal or you can suspend the Python process (Ctrl+Z which sends SIGSTOP and _cannot_ be masked or otherwise ignored) and then use kill in that terminal. You need to know the PID or jobspec in order to use kill. In bash (and probably elsewhere), jobspecs are easy. When you hit Ctrl+Z, the jobspec will be written to your terminal in the form "[N]+ Stopped python". "N" is the jobspec and you can kill it with "kill %N". You may need to use SIGKILL to end the process, in which case use "kill -KILL %N". You can then resume the Python process with the "fg" command, it will immediately end since it has be killed. This is more a Linux/bash/etc question than a Python question, so followups might be directed to a more appropriate forum (eg, the man page for your shell, or a bash user group, etc). Jean-Paul From jstucklex at attglobal.net Fri May 23 07:42:39 2008 From: jstucklex at attglobal.net (Jerry Stuckle) Date: Fri, 23 May 2008 07:42:39 -0400 Subject: php vs python In-Reply-To: <48369413$0$25059$607ed4bc@cv.net> References: <5l%Yj.77$mz3.53@fe101.usenetserver.com> <48369413$0$25059$607ed4bc@cv.net> Message-ID: Andrew Lee wrote: > notbob wrote: >> I'm not posting this just to initiate some religious flame war, though >> it's >> the perfect subject to do so. No, I actaully want some serious advice >> about >> these two languages and since I think usenet is the best arena to find >> it, >> here ya' go. >> >> So, here's my delimna: I want to start a blog. Yeah, who doesn't. >> Yet, I >> want learn the guts of it instead of just booting up some wordwank or >> whatever. I started to learn python, but heard php was easier or >> faster or >> more like shell scripting or... fill in the blank. Anyway, so I >> change over >> to learning php. Then I run across that blog, Coding Horror, and start >> reading articles like this: >> >> http://www.codinghorror.com/blog/archives/001119.html >> >> Now what? Go back to python. Soldier on with php? What do I know? Not >> much. I can setup mysql and apache,, but don't know how to use 'em, >> really. >> I use emacs and run slackware and can fumble my way through bash scripts, >> but I can't really write them or do lisp. I've taken basic basic and >> basic >> C, but am barely literate in html. Sometimes it seems overwhelming, >> but I >> persevere because it's more fun/challenging than video games, which >> bore me >> to tears. >> Well, that's my actual question, then. Is php really so bad I'm just >> wasting my time? Or is it really the quickest way to blog functionality? >> Would I be better served in the long run learning python, which claims >> to be >> easy as pie to learn/program (still looks hard to me). I admit I'm no >> code >> geek. But, I'm not completely brain dead, either, and I need >> something to >> keep my geezer brain sparking. What say ye? >> >> nb > > Personally, I believe PHP would get you more productive more quickly for > a blog, but it is a potentially brain damaging language in terms of > really getting your juices flowing with programming. It is not a > general purpose language and suffers from all the limitations of of a > tool designed for one job. If you are interested in programming and the > blog is your path to that, stick with Python! In particular, immerse > yourself in mod_python or look at a framework like Django or Pylons -- > the learning curve is steep for any of these technologies but they are a > full meal compared to saltine cracker and water of PHP. And what job is that? I have a lot of batch scripts written in PHP, for instance. -- ================== Remove the "x" from my email address Jerry Stuckle JDS Computer Training Corp. jstucklex at attglobal.net ================== From tjreedy at udel.edu Thu May 8 16:31:31 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 8 May 2008 16:31:31 -0400 Subject: Running a python code periodically References: Message-ID: "Maryam Saeedi" wrote in message news:ee9cd3be0805080902g48e641bxbcf1d5578620defe at mail.gmail.com... |I was wondering if you know how can I run a python code once every five | minutes for a period of time either using python or some other program like | a bash script. I expect the following should work. from time import sleep while True: #or # for i in range(nunber_of_cycles): do_whatever() sleep(600) assuming do_whatever() is quick and you do not need exactly 5 minute intervals. | I have asked this question before and some of you answered me but I still | have problem. Most of the answers was to use cron and crontab which works on | my computer but not if I want to do it on department's computer since I do | not have permission to change those files. Is there any other way which does | not need administrator permission? From darcy at druid.net Fri May 16 10:52:00 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Fri, 16 May 2008 10:52:00 -0400 Subject: writing python extensions in assembly In-Reply-To: References: Message-ID: <20080516105200.eeafe010.darcy@druid.net> On Fri, 16 May 2008 10:13:04 -0400 "inhahe" wrote: > Can anyone give me pointers/instructions/a template for writing a Python > extension in assembly (or better, HLA)? I am trying to imagine the requirements document for your project. - Must be error prone and hard to debug - Must take an order of magnitude longer to write - Must be unportable to other systems Really, why don't you write your etension in C? Do you really think you will improve your code by writing it in assembler? Even embedding assembler in C code make it unportable and I find it hard to imagine anything that you want to do in a Python context that can't be done at least as well in C if not pure Python. Just curious is all. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From Sizer at nospam.com Thu May 8 05:25:02 2008 From: Sizer at nospam.com (Sizer) Date: 8 May 2008 04:25:02 -0500 Subject: Can't drag and drop onto .py in Windows XP? References: Message-ID: "Roger Upole" wrote in news:mailman.703.1210165759.12834.python-list at python.org: > Sizer wrote: >> It's just a little weird that I >> can't just drag and drop file names onto .pyw or .py files. Am I >> missing something here? >> >> Thanks for any help. > > You can register a DropHandler for the Python file class. > Put this in a .reg file and merge it into the registry: > > REGEDIT4 > > [HKEY_CLASSES_ROOT\Python.File\shellex\DropHandler] > @="{86C86720-42A0-1069-A2E8-08002B30309D}" Sir, you rock! I found that it actually worked a little better if I used a generic wsh drop handler instead of the .exe handler, but I would never have known where to start looking without your suggestion. I ended up with the following .reg file, and now I can drag and drop files onto my .py, .pyw, and .pyc files and off they go as you'd expect. It kind of seems like this should be the default installer behavior unless there's a good reason not to do it. Thanks again for your help. REGEDIT4 [HKEY_CLASSES_ROOT\Python.File\shellex\DropHandler] @="{60254CA5-953B-11CF-8C96-00AA00B8708C}" [HKEY_CLASSES_ROOT\Python.NoConFile\shellex\DropHandler] @="{60254CA5-953B-11CF-8C96-00AA00B8708C}" [HKEY_CLASSES_ROOT\Python.CompiledFile\shellex\DropHandler] @="{60254CA5-953B-11CF-8C96-00AA00B8708C}" From james at reggieband.com Tue May 6 09:26:42 2008 From: james at reggieband.com (james at reggieband.com) Date: Tue, 6 May 2008 06:26:42 -0700 (PDT) Subject: Module to read input from commandline References: Message-ID: On May 6, 2:11?pm, pyt... at bdurham.com wrote: > Check out the optparse module as well. The optparse module supercedes(?) > the cmd module and offers a lot more functionality. Hi Malcom, Doesn't the optparse module work by parsing the arguments that are passed to the script when it is invoked? What I was looking for was a commandline read loop that executes within a script that is already running ... or can optparse be used in this context as well? Thanks, James. From jgardner at jonathangardner.net Wed May 21 13:48:28 2008 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Wed, 21 May 2008 10:48:28 -0700 (PDT) Subject: What replaces `` in py3k? References: Message-ID: <0ef180ba-6c67-425d-84c3-0b697cde27ea@v26g2000prm.googlegroups.com> On May 21, 10:45?am, bukzor wrote: > What are backticks going to be translated into? repr From gabriel.rossetti at arimaz.com Mon May 26 08:32:32 2008 From: gabriel.rossetti at arimaz.com (Gabriel Rossetti) Date: Mon, 26 May 2008 14:32:32 +0200 Subject: b64encode and unicode problem In-Reply-To: References: Message-ID: <483AADE0.9020708@arimaz.com> Peter Otten wrote: > Gabriel Rossetti wrote: > > >> Hello everyone, >> >> I am trying to encode a string using b4encode and I get the following >> error : >> >> >>> b64encode(u"Salut Pierre, comment ?a va?") >> Traceback (most recent call last): >> File "", line 1, in >> File "/usr/lib/python2.5/base64.py", line 53, in b64encode >> encoded = binascii.b2a_base64(s)[:-1] >> UnicodeEncodeError: 'ascii' codec can't encode character u'\xe7' in >> position 22: ordinal not in range(128) >> >> If I remove the "u" infront of the string, it works. The problem is that >> I in my program, the string is given to me un unicode/utf-8. I tried >> several things, but I still get it, How can I get it to work, anybody >> have any idea? >> > > >>>> base64.b64encode(u"Salut Pierre, comment ?a va?".encode("utf8")) >>>> > 'U2FsdXQgUGllcnJlLCBjb21tZW50IMOnYSB2YT8=' > > unicode is a sequence of codepoints with no predetermined representation as > a byte sequence. Therefore whenever you go from unicode to str you have to > decide upon an encoding. If you don't make that decision python assumes > ascii which will of course fail for non-ascii characters. > > Peter > > Ok, I get it better now, thanks! Gabriel From giuott at gmail.com Tue May 13 09:17:40 2008 From: giuott at gmail.com (Giuseppe Ottaviano) Date: Tue, 13 May 2008 15:17:40 +0200 Subject: Best way to delimit a list? In-Reply-To: <57129f75-b496-40fc-8b2d-d93ba544d4c5@u6g2000prc.googlegroups.com> References: <57129f75-b496-40fc-8b2d-d93ba544d4c5@u6g2000prc.googlegroups.com> Message-ID: <579012D4-7B2B-4482-9B20-8B5C404ABCC5@gmail.com> On May 13, 2008, at 12:28 PM, dannywebster at googlemail.com wrote: > Hi - I have a list returned from popen/readlines, and am wondering how > to go about iterating over each item which was returned (rather than > currently having the whole lot returned). > > so far: > >>>> f=os.open("./get_hostnames").readlines > > returns ['host1 host2 host3 ... hostN\n]' > > i'd like to be in a position to iterate through these, grabbing each > host. I have played with transmuting to a str, and using split, and > this works, but I get the subscript brackets from the list output as > expected, as the list output is now a string literal, and this is not > what I want - and I think it's a bit long-winded to do a search 'n > replace on it - hence why I ask in the subject what's the best way. > >>>> f=str(f) >>>> f.split() > ["['host1","host2", ... ,"hostN\n']"] If the file is really big, you may want not to construct an actual list with all the words, but instead use an iterator. If you define the function def ichain(seq): for s in seq: for x in s: yield x (which is often useful and I don't think it has been included in itertools) you can iterate lazily on the file: hosts = ichain(s.split() for s in f) for host in hosts: # ... HTH, Giuseppe From bignose+hates-spam at benfinney.id.au Wed May 21 21:54:42 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 22 May 2008 11:54:42 +1000 Subject: backport of 'set' to python 2.3? References: Message-ID: <871w3vdrx9.fsf@benfinney.id.au> "Daniel Fetchinson" writes: > Does anyone have a pure python implementation of the builtin 'set' > object so that I could use that in python 2.3? Yes. You have one in Python 2.3 already , it's just not a builtin. > If this would be the case that would be really great as I wouldn't > have to change my code that runs happily on 2.5 You will, but it's as simple as: try: set() except NameError: from sets import Set as set You then know that 'set' refers to the set type from that point on (or you're not on a version of Python that has a 'set' type at all). -- \ "I have a large seashell collection, which I keep scattered on | `\ the beaches all over the world. Maybe you've seen it." -- | _o__) Steven Wright | Ben Finney From gagsl-py2 at yahoo.com.ar Mon May 19 20:26:18 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 19 May 2008 21:26:18 -0300 Subject: conventions/requirements for 'is' vs '==', 'not vs '!=', etc References: <4dc24f2e-04f5-4ad6-b021-f416ef5c7415@z72g2000hsb.googlegroups.com> Message-ID: En Mon, 19 May 2008 17:58:48 -0300, bruno.desthuilliers at gmail.com escribi?: > On 19 mai, 22:29, Luis Zarrabeitia wrote: > (snip) >> The main >> concept here: identity [usually] implies equality, > > I really enjoyed the "usually" disclaimer !-) In some *rare* cases, identity does not imply equality: py> inf = 1e300*1e300 py> nan = inf-inf py> nan -1.#IND py> nan is nan True py> nan == nan False -- Gabriel Genellina From castironpi at gmail.com Fri May 9 16:17:57 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Fri, 9 May 2008 13:17:57 -0700 (PDT) Subject: slicing lists References: Message-ID: <1c8a388a-4d04-4152-9b6e-3d64d96ec7f0@24g2000hsh.googlegroups.com> On May 9, 10:11?am, Yves Dorfsman wrote: > castiro... at gmail.com wrote: > > The only thing is, is there is another natural meaning to [a,b:c]. > > > Counting grids on the diagonals, the rational set is well defined: > > > 0: 0, 0 > > 1: 1, 0 > > 2: 0, 1 > > 3: 2, 0 > > 4: 1, 1 > > 5: 0, 2 > > 6: 3, 0 > > 7: 2, 1 > > ... > > > Thencefore ( 2, 0 ) : ( 3, 0 ) is well defined. ?Thencefore, > > > a,b:c,d > > > is not; x[a,b:c,d]= x[a]+ x[b:c]+ x[d]. > > I'm not sure what you mean here. Could you give me a simple piece of code to > show an example ? > > Yves.http://www.SollerS.ca- Hide quoted text - > > - Show quoted text - Yves, sadly, simple piece of code is not the writer's forte. I was merely advising against leaping in to syntax additions, changes even. The point was, even though a,b:c,d is shown ill-defined, a,b:c may not be. From p.selvaraj2008 at gmail.com Wed May 14 01:50:10 2008 From: p.selvaraj2008 at gmail.com (p.selvaraj2008 at gmail.com) Date: Tue, 13 May 2008 22:50:10 -0700 (PDT) Subject: hai friend Message-ID: <30014ac9-4022-40c5-965c-87a3eef85c16@l28g2000prd.googlegroups.com> hai friend how are you i wish to all of your successfull works and learn more money www.yourambition.blogspot.com From mikael at isy.liu.se Tue May 13 03:12:54 2008 From: mikael at isy.liu.se (Mikael Olofsson) Date: Tue, 13 May 2008 09:12:54 +0200 Subject: passing *args "recursively" In-Reply-To: References: Message-ID: Guillermo wrote: > This must be very basic, but how'd you pass the same *args several > levels deep? > > def func2(*args) > print args # ((1, 2, 3),) > # i want this to output (1, 2, 3) as func1! > # there must be some better way than args[0]? > > def func1(*args): > print args # (1, 2, 3) > func2(args) > > func1(1,2,3) func2(*args) Thats all. See http://docs.python.org/tut/node6.html#SECTION006740000000000000000 /MiO From xahlee at gmail.com Sun May 25 19:25:33 2008 From: xahlee at gmail.com (xahlee at gmail.com) Date: Sun, 25 May 2008 16:25:33 -0700 (PDT) Subject: blogs, longbets.org, and education of sociology Message-ID: <1c97ba8a-b758-4891-a3c4-20e462361934@z16g2000prn.googlegroups.com> For about the past 10 years, i have been concerned in the programing community's level of education in social issues. I have found that recently, a news that would be of interest to programers. There was a bet at longbets.org (run by Long Now Foundation) regarding the importance of blogs. The bet was made in 2002. The prediction has a resolution date in 2007. In 2008, the bet is resolved. See ?Decision: Blogs vs. New York Times? (2008-02-01) by Alexander Rose http://blog.longnow.org/2008/02/01/decision-blogs-vs-new-york-times/ I'd like encourage, for many of you, who have lots of opinions on technical issues or social issues surrounding software, to make use of longbets.org. It can help shape your thoughts from blog fart to something more refined. In any case, your money will benefit society. here's some examples you could try: ? I bet that Java will be out of the top 10 programing languages by 2020. ? I bet that the top 10 programing languages in 2015 (as determined by requirement from job search engine), the majority will be those characterized as dynamic languages (e.g. php, perl, python, javascript, tcl, lisp. (as opposed to: C, Java, C++, C#, F#, Haskell)). ? You bet that Linux as a desktop system will or will not have a market share of such and such by the year xyz. (I'm not sure the above ?predictions? are candidates on longbets.org, since one of their rule is that the ?predictions? should be socially important. Looking at existing entries on their site, the social importance of the above items pale in comparison. (however, many of their existing ?predictions? are somewhat fringe)) * * * Note, in almost all online forums where tech geekers gather (e.g. newsgroups, slashdot, irc, etc), often they are anonymous, each fart ignorant cries and gripes and heated arguments, often in a irresponsible and carefree way. One of the longbets.org's goal is to foster RESPONSIBILITY. In recent years, i have often made claims that the Python's documentation, it's writing quality and its documentation quality in whole, is one of the worst. Among all the wild claims in our modern world, from the sciences to social or political issues, my claim about Python's technical writing quality or its whole quality as a technical documentation, is actualy trivial to verify by any standards. When presented to intellectuals of the world at large, the claim's verifiability is trivial, almost as a matter of fact checking (which are done by interns or newbie grads of communinication/journalism/literature majors, working for journalism houses). However, when i voiced my opinion on Python doc among programing geekers online, it is often met with a bunch of wild cries. Some of these beer drinking fuckheads are simply being a asshole, which are expected by the nature of online tech geeking communities (a significance percentage are bored young males). However, many others, many with many years of programing experience as a professional, sincerely tried to say something to the effect of ?in my opinion it's good?, or voice other stupid remarks to the effect of ?why don't you fix it?, and in fact find my claim, and its tone too fantastical, to the point thinking i'm a youngling who are bent on to do nothing but vandalism. (the tech geekers use in-group slang for this: ?troll?.) The case of the Python doc is just one example. I have also, in the past decade, in _appropriate_ online communties (e.g. newsgroups, mailing lists), voiced opinions on Perl's doc, emacs's doc, criticism on lisp nested syntax, ?software engineering? issues (e.g. OOP), various issues of jargons and naming (e.g. currying, lisp1 vs lisp2, tail recursion, closure), emacs's user interface issues, criticism on the phenomenon of Open Source community's fervor for bug reporting, criticism on IT industry celebrities such as Larry Wall and Guido von Rossum, opinions on cross-posting, ... and others. Some of my claims are indeed controversial by nature. By that i mean that there is no consensus on the subject among its experts, and the issue is complex, and has political implications. However, many trivially verifiable, or even simple facts, are wildly debated or raised a ruckus, because the programers are utterly ignorant of basic social knowledge, or due to their political banding (e.g. a language faction, Open Source) or current trends and fashions (e.g. OOP, Java, ?Patterns?, ?eXtreme Programing?, ... , OpenSource and ?Free? software movement, ...). I think, the founding of Long Now Foundation with its longbets.org, shares a concern i have on the tech geeking communities. In particular, tech geekers need to have a broader education on social sciences, needs to think in long term, and needs to foster personal responsibility, when they act or voice opinions on their love of technology. (note: not reading more motherfucking slashdot or motherfucking groklaw or more great podcasts on your beatific language or your postmodernistic fuckhead idols) (One thing you can do, is actually take a course on philosophy, history, law, economics, in your local community college.) Disclaimer: I have no affiliation with Long Now Foundation. * * * See also: ?Responsible Software Licensing? (2003-07) by Xah Lee http://xahlee.org/UnixResource_dir/writ/responsible_license.html ?On Microsoft Hatred? (2002-02-23) Xah Lee http://xahlee.org/UnixResource_dir/writ/mshatred155.html Xah xah at xahlee.org ? http://xahlee.org/ ? From deets at nospam.web.de Fri May 16 10:18:15 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 16 May 2008 16:18:15 +0200 Subject: writing python extensions in assembly In-Reply-To: References: Message-ID: <695jdlF30fp0gU1@mid.uni-berlin.de> inhahe schrieb: > Can anyone give me pointers/instructions/a template for writing a Python > extension in assembly (or better, HLA)? You could write a C-extension and embed assembly. See the docs for how to write one. If you know how to implement a C-callingconvention-based shared library in assembly (being an assembler guru you sure know how that works), you could mimic a C-extension. Diez From james at reggieband.com Tue May 6 08:41:30 2008 From: james at reggieband.com (james at reggieband.com) Date: Tue, 6 May 2008 05:41:30 -0700 (PDT) Subject: Module to read input from commandline References: <2e04b64c-9a12-4e20-8d5a-546a0ec4ac7f@m36g2000hse.googlegroups.com> Message-ID: On Apr 13, 9:05?pm, ja... at reggieband.com wrote: > On Apr 13, 7:44 pm, thashoo... at farifluset.mailexpire.com wrote: > > > What you're looking for is no module, it is included in the standard > > python namespace. > > > raw_input > > Thanks for the response GL. > > What I am looking for is a module to wrap raw_input so it can handle > some of the validation. Looks like I found the module after-all: http://blog.doughellmann.com/2008/05/pymotw-cmd.html http://docs.python.org/lib/module-cmd.html The cmd module does what I want and more. Just wanted to post this in-case someone finds this through a search. cheers, James From gnewsg at gmail.com Sun May 4 14:38:06 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Sun, 4 May 2008 11:38:06 -0700 (PDT) Subject: Determine socket family at runtime References: <30bafd19-c822-41b6-8e17-ea004ba30821@t54g2000hsg.googlegroups.com> Message-ID: <43a969df-0098-4fab-a736-fb92d5b75aca@26g2000hsk.googlegroups.com> On 4 Mag, 19:18, Francesco Bochicchio wrote: > On Sun, 04 May 2008 08:49:55 -0700, Giampaolo Rodola' wrote: > > Hi there, > > since the socket.socket.family attribute has been introduced only in > > Python 2.5 and I need to have my application to be backward compatible > > with Python 2.3 and 2.4 I'd like to know how could I determine the > > family of a socket.socket instance which may be AF_INET or AF_INET6. > > Is there some kind of getsockopt() directive I could use? > > For now I've been able to determine the family by using: > > > # self.socket = a connected socket.socket instance > > ip, port = self.socket.getsockname()[0:2] > > af = socket.getaddrinfo(ip, port)[0][0] > > > ...but I'd like to know if some other solution is preferable. > > > Thanks. > > > --- Giampaolo > >http://code.google.com/p/pyftpdlib > > Ciao, > > what about wrapping the socket type and ?adding a 'family' attribute > to the base socket class? Something like: > > class SocketWrapper(socket.socket): ? ?def __init__(self, family, type, proto=0): ? ? ? ? ? ? socket.socket.__init__(self, family, type, proto) ? ? ? ? ? ? ?self.family = family > > then you have just to create the sockets with SocketWrapper insetead of > socket.socket. For the rest of your code it would not matter, and then you > are sure to always have a .family attribute. > > Ciao > ---- > FB- Nascondi testo tra virgolette - > > - Mostra testo tra virgolette - Ciao, I don't think that it would be possible since the socket I'm talking about is returned by socket.socket.accept(). --- Giampaolo http://code.google.com/p/pyftpdlib From jcd at sdf.lonestar.org Fri May 16 10:15:33 2008 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Fri, 16 May 2008 10:15:33 -0400 Subject: class problem, NoneType obj has no attribute In-Reply-To: <9355f9ed-032c-44e1-bf8d-183092e5b201@e53g2000hsa.googlegroups.com> References: <10bbf997-3520-4920-b225-8685b98d9079@59g2000hsb.googlegroups.com> <9355f9ed-032c-44e1-bf8d-183092e5b201@e53g2000hsa.googlegroups.com> Message-ID: <1210947333.3766.9.camel@aalcdl07.lib.unc.edu> On Fri, 2008-05-16 at 06:04 -0700, globalrev wrote: > On 16 Maj, 13:54, Peter Otten <__pete... at web.de> wrote: > > Christian Heimes wrote: > > > globalrev schrieb: > > >> cust1 = customer.__init__('12',['1','435','2332']) > > > > > cust1 = customer('12',['1','435','2332']) > > > > ... and before that > > > > from customer import customer > > > > Peter > > why do i have to write that? > > if i do import customer im importing everything no? > Not exactly. That's how perl and PHP tend to do it, but python's import system is much more conservative (and far superior because of it). When you import a name you get that name and nothing else. You can still call your class without doing from customer import customer, but you have to include the module in the class name like this: cust1 = customer.customer('12',['1','435','2332']) Everything stays hidden behind the name customer. That way, if customer defines a class that has the same name that you already have in your namespace, it won't get overwritten. Say you define a class Purchase in your customer module, and then in the interpreter, you write py>>> import customer py>>> Purchase = 4 py>>> bread = customer.Purchase('bread') py>>> Purchase 4 py>>> bread py>>> Purchase and customer.Purchase can live happily side by side. In perl or PHP, the default behavior causes errors which are hard to debug because you can't see what names are being pulled into your namespace. > but youre right it doesnt work unless i do, i just dont get why. > -- > http://mail.python.org/mailman/listinfo/python-list > From workitharder at gmail.com Wed May 21 13:45:58 2008 From: workitharder at gmail.com (bukzor) Date: Wed, 21 May 2008 10:45:58 -0700 (PDT) Subject: What replaces `` in py3k? Message-ID: In Python 3, backticks (``) are being removed. The plan is to create an automatic way to port python2 programs to python3, so my question is: What are backticks going to be translated into? I tried looking at the 2to3 fixer source code, but as far as I can tell they haven't written that part yet. http://svn.python.org/view/sandbox/trunk/2to3/lib2to3/fixes/ From bj_666 at gmx.net Fri May 30 02:02:42 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 30 May 2008 06:02:42 GMT Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <94bac166-d13c-44dd-af84-db19e19488b8@w1g2000prd.googlegroups.com> <8cfd3523-8d16-40bc-b904-94a6a36a414d@p25g2000pri.googlegroups.com> <5c98049e-e62e-4ab1-afed-b0a3e186bd05@w1g2000prd.googlegroups.com> <3dd6fa95-e9fe-4922-a46d-020cf9263469@w4g2000prd.googlegroups.com> Message-ID: <6a9jk2F364dj7U1@mid.uni-berlin.de> On Thu, 29 May 2008 17:57:45 -0400, D'Arcy J.M. Cain wrote: > I guess I am still new to this group and don't understand its charter. > I wasn't aware that it was a Flaming Blunder group. Can someone please > point me to a newsgroup or mailing list dedicated to the Python > programming language? By discussing language design of FT compared to other languages you can learn about Python. We all know that Python is brilliant -- here's the opportunity to think about why it is. :-) And it's basically only this very long thread, so it's easy to filter and ignore in a decent news reader. Ciao, Marc 'BlackJack' Rintsch From matthieu.brucher at gmail.com Sun May 11 18:17:34 2008 From: matthieu.brucher at gmail.com (Matthieu Brucher) Date: Mon, 12 May 2008 00:17:34 +0200 Subject: Some error messages in Python are ugly In-Reply-To: <1af83e8f-8083-4b5d-95e1-534193d059e5@24g2000hsh.googlegroups.com> References: <1af83e8f-8083-4b5d-95e1-534193d059e5@24g2000hsh.googlegroups.com> Message-ID: Please, really please, stop asking question and go read some books about/get some courses on Linux shell and then finally Python. Before you do that, the only thing will have is upset people telling you to _think_ (clearly that's something you are n,ot used to do, but you will have to start at some point) before sending a mail. Matthieu 2008/5/11 : > This really looks ugly for an error message: > > [1]+ Stopped python > > > Please explain to me the role of the '+' sign. And why is there such a > gap between 'Stopped' and 'python'? > -- > http://mail.python.org/mailman/listinfo/python-list > -- French PhD student Website : http://matthieu-brucher.developpez.com/ Blogs : http://matt.eifelle.com and http://blog.developpez.com/?blog=92 LinkedIn : http://www.linkedin.com/in/matthieubrucher -------------- next part -------------- An HTML attachment was scrubbed... URL: From basti.wiesner at gmx.net Sat May 31 10:39:21 2008 From: basti.wiesner at gmx.net (Sebastian 'lunar' Wiesner) Date: Sat, 31 May 2008 16:39:21 +0200 Subject: File browser in python gui References: <4841353e_1@news.tm.net.my> Message-ID: [ TheSaint ] > I've started to build a GUI for my Mailsweeper by the help of QT4 > Designer. I came across the problem that there isn't any prebuild file > browser like Kdialog. > I know some other sample, but PyGTK builded. I'm not happy to use a > different widget set or to have to design my own file browser with QT4 > widgets. It's almost thousand times people need to use such browser, I > wonder why I couldn't find one on the entire day searching on web site. > A QT XML file (.ui extension) should do fine, if someone would help :) What about QtGui.QFileDialog? -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From deets at nospam.web.de Tue May 6 06:37:39 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 06 May 2008 12:37:39 +0200 Subject: Cannot install Pypvm (Python Parallel Virtual Machine) References: Message-ID: <68aqoeF2rue80U1@mid.uni-berlin.de> spectrumdt at gmail.com wrote: > Hello. > > I am trying to install Pypvm (http://pypvm.sourceforge.net/), the > Python interface to PVM ("Parallel Virtual Machine"). Unfortunately, > installation fails. I am hoping someone can help me fix it. > > I am running Fedora Core 8 Linux. > > The official Pypvm documentation is very helpful (or something), > providing the following: > > > > To build Pypvm, cross your fingers and try: > > make -f Makefile.pre.in boot > make > > Or alternatively, try > python setup.py build > python setup.py install > > > > For me, the "make -f Makefile.pre.in boot" seems to run fine, but the > "make" fails, giving (among other things) the following: > > > > [ore at localhost pypvm-0.94]$ make > gcc -pthread -fPIC -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 > -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m32 - > march=i386 > -mtune=generic -fasynchronous-unwind-tables -D_GNU_SOURCE -fPIC > -I/usr/include/python2.5 -I/usr/lib/python2.5/config -c > ././pypvm_coremodule.c -o ./pypvm_coremodule.o > ././pypvm_coremodule.c:2:18: error: pvm3.h: No such file or directory > ././pypvm_coremodule.c: In function ?was_error?: > ././pypvm_coremodule.c:81: error: ?PvmOk? undeclared (first use in > this function) > ././pypvm_coremodule.c:81: error: (Each undeclared identifier is > reported only once > ././pypvm_coremodule.c:81: error: for each function it appears in.) > ././pypvm_coremodule.c:85: error: ?PvmBadParam? undeclared (first use > in this function) > ././pypvm_coremodule.c:85: error: ?PvmMismatch? undeclared (first use > in this function) > [...] > ././pypvm_coremodule.c:1889: error: ?PvmDupEntry? undeclared (first > use in this function) > ././pypvm_coremodule.c:1767: warning: unused variable ?optModule? > ././pypvm_coremodule.c:1766: warning: unused variable ?resultModule? > ././pypvm_coremodule.c:1765: warning: unused variable ?notifyModule? > ././pypvm_coremodule.c:1764: warning: unused variable ?spawnModule? > ././pypvm_coremodule.c:1763: warning: unused variable ?dataModule? > ././pypvm_coremodule.c:1762: warning: unused variable > ?exceptionModule? > make: *** [pypvm_coremodule.o] Error 1 > [ore at localhost pypvm-0.94]$ > > > > In in alternate version, "python setup.py build" similarly fails: > > > > [ore at localhost pypvm-0.94]$ python setup.py build > running build > running build_py > running build_ext > building 'pypvm_core' extension > gcc -pthread -fno-strict-aliasing -DNDEBUG -O2 -g -pipe -Wall -Wp,- > D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer- > size=4 -m32 -march=i386 -mtune=generic -fasynchronous-unwind-tables - > D_GNU_SOURCE -fPIC -fPIC -I/usr/include -I/usr/include/python2.5 -c > pypvm_coremodule.c -o build/temp.linux-i686-2.5/pypvm_coremodule.o > pypvm_coremodule.c:2:18: error: pvm3.h: No such file or directory > pypvm_coremodule.c: In function ?was_error?: > pypvm_coremodule.c:81: error: ?PvmOk? undeclared (first use in this > function) > pypvm_coremodule.c:81: error: (Each undeclared identifier is reported > only once > pypvm_coremodule.c:81: error: for each function it appears in.) > pypvm_coremodule.c:85: error: ?PvmBadParam? undeclared (first use in > this function) > [...] > pypvm_coremodule.c:1889: error: ?PvmDupEntry? undeclared (first use in > this function) > pypvm_coremodule.c:1767: warning: unused variable ?optModule? > pypvm_coremodule.c:1766: warning: unused variable ?resultModule? > pypvm_coremodule.c:1765: warning: unused variable ?notifyModule? > pypvm_coremodule.c:1764: warning: unused variable ?spawnModule? > pypvm_coremodule.c:1763: warning: unused variable ?dataModule? > pypvm_coremodule.c:1762: warning: unused variable ?exceptionModule? > error: command 'gcc' failed with exit status 1 > [ore at localhost pypvm-0.94]$ > > > > Can anyone help me get it to work? You need to check which package provides the "pvm3.h"-include-file and install that. Usually, these are *-dev(el)?-packages. Diez From __peter__ at web.de Thu May 22 02:11:11 2008 From: __peter__ at web.de (Peter Otten) Date: Thu, 22 May 2008 08:11:11 +0200 Subject: Bit of List replacing trouble (newbie) References: Message-ID: Zethex wrote: > At the moment i'm doing a piece of work for school and I'm stuck at the > moment. > > I have a list of words, for example: > > Sentence = ['A', 'dog', 'walked', 'across', 'the', 'street'] > > I have another list which I need to use to replace certain words, and its > in the form of: > > synonyms = [ > [canine, [dog, puppy, bulldog]], > [ road, [street, avenue, court]] > ] > What the procedure must do is replace dog with canine, and street with > road. Therefore if a word is in the sentence and appears on the right side > of the list entry, replace it with the left entry. > > I can't seem to find a help file with what I'm after. I'm just wondering > if anyone can help me on the right track on how to start this procedure, > maybe not an answer but just a little help on how to get started as I'm > complete stuck right now. See if you can put the synonyms in a dict: syndict = {"dog": "canine", "puppy": "canine", ..., "court": "road"} The code to achieve that should consist of two nested loops. You can then look up a word easily with word = syndict.get(word, word) Put that into another loop iterating over the words of the original sentence and build the new sentence by appending to a fresh list. Peter From gagsl-py2 at yahoo.com.ar Fri May 2 12:35:44 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 02 May 2008 13:35:44 -0300 Subject: Python 2.6 and wrapping C libraries on Windows References: <_X8Sj.3499$XI1.3261@edtnps91> <9a4cc17e-deb2-4219-a093-bff5c1a20d5e@s33g2000pri.googlegroups.com> <4819B2F1.9030100@cheimes.de> Message-ID: En Thu, 01 May 2008 09:09:21 -0300, Christian Heimes escribi?: > illume schrieb: >> Has anyone tested the new python binaries that link to msvcr90.dll on >> win9x machines? > > It doesn't matter to use because Python 2.6 and 3.0 require at least > Windows 2000 SP4. The 9x, ME and NT series aren't supported any more. That should be menctioned in the What's new? document - I could not find any reference. -- Gabriel Genellina From svetoslav.agafonkin at gmail.com Sat May 3 07:52:01 2008 From: svetoslav.agafonkin at gmail.com (svetoslav.agafonkin at gmail.com) Date: Sat, 3 May 2008 04:52:01 -0700 (PDT) Subject: How to use a parameter in a class References: <4923419b-4de0-4739-b02d-753636ef0220@y21g2000hsf.googlegroups.com> Message-ID: <9ea30fa0-7c79-46a7-a4af-d0a5e73bcf73@e53g2000hsa.googlegroups.com> On May 3, 1:05?pm, Decebal wrote: > I have the following class: > ##### > class Dummy(): > ? ? value = 0 > ? ? def __init__(self, thisValue): > ? ? ? ? print thisValue > ? ? ? ? self.value = thisValue > ? ? ? ? value = thisValue > > ? ? def testing(self): > ? ? ? ? print 'In test: %d' % self.value > > ? ? def returnValue(self): > ? ? ? ? return self.value > > ? ? result = someFuntion(default = value) > ##### > > But the last line does not work. > I would like to do a call like: > ? ? dummy = Dummy(thisValue = 12) > > And that someFunction gets a default value of 12. How can I do that? The line > result = someFuntion(default = value) is executed when the whole 'class' compound statement is executed, i.e. before the line that creates the 'dummy' instance. Moreover, this happens only once and not every time you create a new instance of the class. If you want 'result' to be a class attribute that is set every time you create a new instance move the line > result = someFuntion(default = value) in the __init__ constructor (you also have to assign some value to it before, just like the 'value' attribute and preffix it with Dummy. otherwise it'll be considered as local name of __init__): class Dummy(): value = 0 result = 0 def __init__(self, thisValue): print thisValue self.value = thisValue Dummy.value = thisValue Dummy.result = someFuntion(default = Dummy.value) def testing(self): ... From workitharder at gmail.com Fri May 23 02:26:59 2008 From: workitharder at gmail.com (bukzor) Date: Thu, 22 May 2008 23:26:59 -0700 (PDT) Subject: call f(a, *b) with f(*a, **b) ? References: <55bc8846-107e-461a-89de-25c83cbcfa27@2g2000hsn.googlegroups.com> <5coZj.13951$hv2.4218@bignews5.bellsouth.net> Message-ID: <9e688dbd-43fb-43ca-8c60-8dd2aaa66aa1@x1g2000prh.googlegroups.com> On May 22, 5:29?pm, "inhahe" wrote: > "bukzor" wrote in message > > news:55bc8846-107e-461a-89de-25c83cbcfa27 at 2g2000hsn.googlegroups.com... > > > This question seems easy but I can't figure it out. > > Lets say there's a function: > > > def f(a, *args): > > ? ?print a > > ? ?for b in args: print b > > > and elsewhere in your program you have a list and a dict like this: > > args = [2, 3] > > kwargs = {'a':1} > > > I'd like to get f() to print something like the following, but I can't > > figure out how. > > 1 > > 2 > > I think there's no 'standard' way to do this. but: > > import inspect > f(*map(kwargs.get, inspect.getargspec(f)[0])+args) > > i don't know if it works because i'm afraid to try it. ?if it doesn't the > solution is something similar to that. That does, in fact work. Thanks! I'm a little sad that there's no builtin way to do it, owell. >>> def f(a, *args): ... print a ... for b in args: print b ... >>> import inspect >>> a = [2,3] >>> b = {'a':1} >>> inspect.getargspec(f) (['a'], 'args', None, None) >>> map(b.get, inspect.getargspec(f)[0]) [1] >>> map(b.get, inspect.getargspec(f)[0]) + a [1, 2, 3] >>> f(*map(b.get, inspect.getargspec(f)[0]) + a) 1 2 3 From ppearson at nowhere.invalid Fri May 30 10:50:36 2008 From: ppearson at nowhere.invalid (Peter Pearson) Date: Fri, 30 May 2008 09:50:36 -0500 Subject: Help needed in choosing an algorithm for Cryptographic services. References: Message-ID: On Thu, 29 May 2008 20:27:35 -0500, Larry Bates wrote: > abhishek wrote: >> Hi group, recently my employer asked me too implement encryption/ >> decryption for secure data transfer over internet. Problem is that the >> client application is written using C# and the webserver where i need >> to store the information is developed using python. >> >> My situation of dilemma is which cryptographic method suits me best >> for this purpose. >> >> Help/Suggestions are urgently required The proper newsgroup for this question is sci.crypt. Data security is a complex and difficult problem, and you are likely to fail in the worst possible way: implementing something that is weak but that you believe to be strong. Some advice: (1) Use off-the-shelf products like PGP or GPG; don't write your own. (2) Read Bruce Schneier's Applied Cryptography to get a feeling for the dimensions of the problem. (3) Start by composing a clear statement of what you need, avoiding vague terms like "security". If you don't know where you're going, you can't tell whether you've arrived. -- To email me, substitute nowhere->spamcop, invalid->net. From jcd at sdf.lonestar.org Fri May 9 12:08:17 2008 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Fri, 09 May 2008 12:08:17 -0400 Subject: A question about python and xml In-Reply-To: <0507ffd8-6842-4546-a635-414fabf481fb@y21g2000hsf.googlegroups.com> References: <0507ffd8-6842-4546-a635-414fabf481fb@y21g2000hsf.googlegroups.com> Message-ID: <1210349297.3332.53.camel@aalcdl07.lib.unc.edu> On Fri, 2008-05-09 at 08:39 -0700, Holden wrote: > Hello everyone I heard this was a good community to go too for help > and advice. I want to make a web site that uses the python programming > language which I am VERY new at. This website would store simple data > such as names in a form. At first I wanted to use mysql to store the > data but I want to export the data using xml. > > So say if a user logged in they would be able to store there basic > information in an xml file and download it whenever. Is that possible > using XML and Python. I am sorry if this post doesn't make much sense > but any advice would be greatly appreciated. You can also e-mail me if > you need further information or clarification. > > Thanks > > Holden > -- > http://mail.python.org/mailman/listinfo/python-list > A general question will only get you a general answer, but yes, it's very possible. You'll want to look into the cgi module (in the standard library)for basic, ground level server/browser communication. You might also be interested in using a web framework, for keeping your site design clean and manageable. I recommend Django from my own experience, but you might also look into turbogears, pylons, webpy, or any of a number of other well-regarded options. The downside to using a framework is that it's another set of things to learn, which, if you're just starting out with python, might be a bit much to chew, but they can be very helpful with maintenance down the line. For XML processing, lxml.etree or ElementTree should suit your needs. ElementTree is included in the standard library of recent versions of python, though lxml is easily downloadable, and adds a couple bells and whistles. There are other options available, but those are straightforward to use, and well designed. Good luck with your site. Cheers, Cliff From bruno.42.desthuilliers at websiteburo.invalid Thu May 15 03:25:47 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 15 May 2008 09:25:47 +0200 Subject: [x for x in <> while <>]? In-Reply-To: References: Message-ID: <482be56f$0$10798$426a34cc@news.free.fr> urikaluzhny a ?crit : > It seems that I rather frequently need a list or iterator of the form > [x for x in <> while <>] > And there is no one like this. > May be there is another short way to write it (not as a loop). Is > there? The answer is very probably in the itertools module. From jym at cornsoft.com Sun May 4 10:58:42 2008 From: jym at cornsoft.com (jym) Date: Sun, 4 May 2008 09:58:42 -0500 Subject: Writing a aiff audio file problem? Message-ID: <5078ba20805040758m3d5a5a00p9e7394b0e635e300@mail.gmail.com> Hi all I can not creat a usable audio file in the aiff format. The example code below creates a wav file that I can listen to just fine. However, I just get noise when I listen to the resulting aiff file. Is this a byte order problem? I am using Python 2.5.2 on Windows XP. Any guidance on this issue would be appreciated. Thanks jym import pyaudio import wave import sys import aifc chunk = 1024 FORMAT = pyaudio.paInt16 CHANNELS = 1 RATE = 8000 RECORD_SECONDS = 5 WAVE_OUTPUT_FILENAME = "output" p = pyaudio.PyAudio() stream = p.open(format = FORMAT, channels = CHANNELS, rate = RATE, input = True, frames_per_buffer = chunk) print "* recording" all = [] for i in range(0, RATE / chunk * RECORD_SECONDS): data = stream.read(chunk) all.append(data) print "* done recording" stream.close() p.terminate() #write data to AIFF file data = ''.join(all) af = aifc.open(WAVE_OUTPUT_FILENAME + ".aiff", 'wb') af.setnchannels(CHANNELS) af.setsampwidth(p.get_sample_size(FORMAT)) af.setframerate(RATE) af.writeframes(data) af.close() # write data to WAVE file wf = wave.open(WAVE_OUTPUT_FILENAME + ".wav", 'wb') wf.setnchannels(CHANNELS) wf.setsampwidth(p.get_sample_size(FORMAT)) wf.setframerate(RATE) wf.writeframes(data) wf.close() -------------- next part -------------- An HTML attachment was scrubbed... URL: From prisoner_at_war at yahoo.com Mon May 26 01:06:02 2008 From: prisoner_at_war at yahoo.com (Prisoner at War) Date: Sun, 25 May 2008 22:06:02 -0700 (PDT) Subject: Why Turn "Print" into "Print()"???? References: Message-ID: <248a2c45-caae-49bb-b8ff-701af8b86207@p25g2000hsf.googlegroups.com> On May 25, 8:37 pm, "drobi... at gmail.com" wrote: > > > See http://www.python.org/dev/peps/pep-3105/ > That should answer all your questions. Hey, thanks, I missed that one! Not that I understand the rationale given (iman00b), but oh well, so it looks like a real function now. Might you have any idea, BTW, whether the upcoming "Head First Programming" from O'Reilly, coming in August, will cover Python 3?? Unlikely, right? Unless maybe if that guy Vern Ceder (the author) is active in the Python development community?? I'd already pre-ordered the book...but it makes no sense to get a book on "old" Python 2.x if it's just going to get deprecated in like a year or two! Then again, current Python programs would still work, right? I mean, once it's been done up as an executable...PySol or something should still work, right? (Sorry, iman00b, I don't really know how this stuff works....) From kyosohma at gmail.com Mon May 26 20:36:49 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 26 May 2008 17:36:49 -0700 (PDT) Subject: Keyboard Events References: <14d057b1-3b62-4efb-bdb2-c20394c7268c@r66g2000hsg.googlegroups.com> <1e920a06-3741-4154-94a1-73b90f659e1b@z72g2000hsb.googlegroups.com> <4d26372a-c07d-4a41-992f-4c158f0c40c3@56g2000hsm.googlegroups.com> Message-ID: On May 26, 5:38?pm, Ivan Illarionov wrote: > On Mon, 26 May 2008 15:26:50 -0700, Gandalf wrote: > > On May 27, 12:18 am, Gandalf wrote: > >> On May 27, 12:00 am, Ivan Illarionov wrote: > > >> > On Mon, 26 May 2008 14:40:18 -0700, Gandalf wrote: > >> > > Thanks! > >> > > Anyone know which library should i learn then? > > >> > Looks like you need to dive into Win32 > >> > APIhttp://msdn.microsoft.com/en-us/library/ms697544 > > (VS.85).aspxhttp://ms... > > >> > and others > >> > combined with ctypes. > > >> > Ivan > > >> well, that seems extremely valuable but how can i implement those > >> functions with python? > > > You know what I'm sorry, I will try to understand the ctypes lib before > > bothering you. > > > thank you all! > > No need to sorry. I have actually found very valuable information athttp://www.brunningonline.net/simon/blog/archives/000652.html > while googling to answer your question. I didn't know that such things > are really possible with Python/Win32! It'll help me a lot. Thank you! > > Ivan If you guys are going to go digging into the PyWin32 modules, make sure you check this site out: http://aspn.activestate.com/ASPN/docs/ActivePython/2.5/pywin32/PyWin32.html It has the docs for the distro and a link to the user's group too. Bot have been very helpful to me. Mike From rocky at panix.com Thu May 15 15:07:18 2008 From: rocky at panix.com (R. Bernstein) Date: Thu, 15 May 2008 15:07:18 -0400 Subject: Running an interactive interpreter inside a python References: <16f79f5a-ef95-41ce-a58d-3b513e201d35@56g2000hsm.googlegroups.com> Message-ID: castironpi writes: > On May 15, 6:26?am, ro... at panix.com (R. Bernstein) wrote: >> "Alan J. Salmoni" writes: >> >> > I'm not sure if this is exactly what you're after, but try looking >> > into the 'code' module. >> >> > It's fairly easy to make an interactive interpreter that runs within >> > your program. If you import your programs variables into >> > __main__.__dict__, you can have access to them which can be funky. You >> > can even override the showtraceback method to catch various exceptions >> > and do daft things like adding new methods to strings. I guess it >> > would even be possible to have the commands compared to a list of >> > commands and keywords to build a restricted interpreter, though how >> > secure this would be against a determined attack is another matter. >> >> > Alan >> >> I think this (largely) does the trick. Thanks! >> >> I'm not sure about how to deal with globals yet which should come from >> a stackframe f_globals. It might be possible to save and restore >> __main__.__dict__ before and after the call to interact(). Probably >> would have been cooler to design interact() to take a globals >> parameter, same as eval does. >> >> >> >> >> >> > On May 15, 11:31 am, ro... at panix.com (R. Bernstein) wrote: >> >> The next release of pydb will have the ability to go into ipython from >> >> inside the debugger. Sort of like how in ruby-debug you can go into >> >> irb :-) >> >> >> For ipython, this can be done pretty simply; there is an IPShellEmbed >> >> method which returns something you can call. But how could one do the >> >> same for the stock python interactive shell? >> >> >> To take this out of the realm of debugging. What you want to do is to >> >> write a python program that goes into the python interactive shell - >> >> without having to write your own a read/eval loop and deal with >> >> readline, continuation lines, etc. >> >> >> The solution should also allow >> >> ?- variables/methods in the calling PYthon program to be visible >> >> ? ?in the shell >> >> ?- variables set in the interactive (sub) shell should persist after the shell >> >> ? ?terminates, although this is a weaker requirement. POSIX subshells >> >> ? ?for example *don't* work this way. >> >> >> There has been much written about how to embed Python from C, so I >> >> suppose this may offer one way. And at worst, I could write >> >> a C extension which follows how C Python does this for itself. >> >> >> But is there a simpler way? >> >> >> Thanks.- Hide quoted text - >> >> - Show quoted text - > > One threat is malicious code; sorry for this. This is a little too cryptic for me. But then if we're talking security, maybe obfuscation is in order. :-) If this was meant as an explanation for why interact() only takes a local parameter and none for global, security concerns are in fact why you'd want to *add* that parameter: so that the caller could more easily decide what interact sees as global. I haven't tried implementing a __main__.__dict__ save, modify and restore around the interact(), but I'll assume that this could be made to work. If instead this was about the evils of writing a program that uses code and calls interact, in general, debuggers and security are at odds. In a highly secure environment, you probably want to disallow any trace hook. I think Ruby uses the global variable $SAFE with a particular level setting for this purpose. From cwitts at gmail.com Wed May 7 06:14:55 2008 From: cwitts at gmail.com (Chris) Date: Wed, 7 May 2008 03:14:55 -0700 (PDT) Subject: open filename with spaces in path References: Message-ID: <3166ab25-5859-4b92-aeaf-6531bcf06382@x41g2000hsb.googlegroups.com> On May 7, 1:09?am, "Kam-Hung Soh" wrote: > On Wed, 07 May 2008 08:36:35 +1000, Michael Robertson ? > > wrote: > > I'm having trouble opening a file in linux, whose path has spaces in it. > > > $ mkdir my\ test > > $ echo test > my\ test/test.txt > > $ python > > > ?>>> open('./my test/test.txt') > > Exception > > ?>>> open('./my\\ test/test.txt') > > Exception > > Try a string literal by prefixing your path string with "r": > > open(r'./my test/test.txt') > > Seehttp://docs.python.org/ref/strings.html > > > but yet... > > > ?>>> import os > > ?>>> os.chdir('./my test') > > ?>>> open('./test') > > > works just fine. > > Couldn't test on Linux, but in Windows ... > > >>> os.chdir('C:\temp\my test') > > Traceback (most recent call last): > ? ?File "", line 1, in > WindowsError: [Error 123] The filename, directory name, or volume label ? > syntax is incorrect: 'C:\temp\\my test' > > -- > Kam-Hung Soh Software Salariman >>> os.chdir('C:/') >>> os.getcwd() 'C:\\' >>> os.chdir('C:\temp\my test') Traceback (most recent call last): File "", line 1, in WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect: 'C:\temp\\my test' >>> os.chdir('C:/temp/my test') >>> os.getcwd() 'C:\\temp\\my test' Windoze works fine if you hand it forward slashes. >>> os.chdir('C:/') >>> os.chdir(os.path.join('C:','temp','my test')) >>> os.getcwd() 'C:\\temp\\my test' And joining your target with os.path.join works to. From bhawsar.vaibhav at gmail.com Mon May 5 07:26:45 2008 From: bhawsar.vaibhav at gmail.com (Vaibhav.bhawsar) Date: Mon, 5 May 2008 07:26:45 -0400 Subject: threading: getting latest elements from list/dict In-Reply-To: <17d58cc40805050412l2cc0340cs2b84916d0af0760c@mail.gmail.com> References: <17d58cc40805050412l2cc0340cs2b84916d0af0760c@mail.gmail.com> Message-ID: <17d58cc40805050426w3282bb3eyc9c1831d1d37d705@mail.gmail.com> Hello I have a thread updating a dictionary with new elements. How can I check for new elements as they are inserted into the dictionary by the thread? In general is it safe to read a dictionary or a list while it is being updated by a running thread? Does the dictionary or list have to be locked while reading? many questions! :) vaibhav -------------- next part -------------- An HTML attachment was scrubbed... URL: From Scott.Daniels at Acm.Org Sat May 24 09:49:20 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 24 May 2008 06:49:20 -0700 Subject: Unhandled exceptions checking In-Reply-To: <5bc79d5b-d22b-49a4-bab4-424230465818@y21g2000hsf.googlegroups.com> References: <5bc79d5b-d22b-49a4-bab4-424230465818@y21g2000hsf.googlegroups.com> Message-ID: Yosifov Pavel wrote: > Does somebody know existent tool for checking unhandled exceptions? > Like in Java when method throws exception but in code using this > method, try...catch is missed. May be something like PyChecker? I've seen this a number of places. Apparently there are a number of programmers who find exceptions to be a problem to suppressed, rather than an indicator of a deeper bug. Your goal should be to handle anticipatable problems where you can, and reveal the others, not to make sure you cannot raise an exception. Exceptions are valuable in that they reveal "thinko"s, embrace what they tell you, and don't look for mechanical ways to avoid them; test them out. --Scott David Daniels Scott.Daniels at Acm.Org From max at alcyone.com Sat May 3 17:14:23 2008 From: max at alcyone.com (Erik Max Francis) Date: Sat, 03 May 2008 14:14:23 -0700 Subject: list.index crashes when the element is not found In-Reply-To: <6ac548f4-0c96-4bd4-a6e1-9332f3093ad6@y38g2000hsy.googlegroups.com> References: <491f6$481b6455$547@news.teranews.com> <18cd9b76-91e7-4830-af75-cc9c97536347@d45g2000hsc.googlegroups.com> <6ac548f4-0c96-4bd4-a6e1-9332f3093ad6@y38g2000hsy.googlegroups.com> Message-ID: <8oudnccY4MgvSIHVnZ2dnUVZ_rzinZ2d@speakeasy.net> Jeff wrote: > The generally used idiom for that is: > > lst = ['a', 'b', 'c'] > if 'a' in lst: > foo = lst.index('a') It's not a very good idiom, since it iterates over the list twice unnecessarily: first, to see if the object is in the list; then, to find the index of that object. That's pointless wasteful. The Pythonic idiom is to catch the exception and then deal with it as desired. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis From arnodel at googlemail.com Mon May 12 11:15:31 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 12 May 2008 08:15:31 -0700 (PDT) Subject: Mathematics in Python are not correct References: <52c855d8-5609-43e0-b98f-9fa87b2808c2@m3g2000hsc.googlegroups.com><200805081914.06459.kyrie@uh.cu> <6b64d8f4-3f61-4295-9298-4633214d1e94@m73g2000hsh.googlegroups.com> <03166a24-ba2d-40bf-98c8-5344382e9b76@b64g2000hsa.googlegroups.com> Message-ID: On 12 May, 15:21, Mark Dickinson wrote: > On May 12, 2:09?am, "Terry Reedy" wrote: > > > Then it seems equally dubious that 0.**y, y>0, should be well-defined. > > It seems to me that lim as x goes to 0. exp(y*log(x)) is equally well > > defined whether y is 0 or not, even though there is a discontinuity in the > > limit. > > Well, there's a difference: ?the limit of exp(y*log(x)) as (x, y) -> > (0, a) exists for all finite nonzero a. ?The limit as (x, y) -> > (0, 0) doesn't. But exp(y*log(x)) -> 1 as (x, y) -> (0, 0) along any analytic curve which is not the x=0 axis (I think at least - it seems easy to prove that given f and g analytic over R, f(x)*ln g(x) -> 0 as x -> 0 if f(0)=g(0)=0 and g(x)>0 in the neighbourhood of 0). This should cover most practical uses? -- Arnaud From mark.deverter at dads.state.tx.us Tue May 20 15:32:32 2008 From: mark.deverter at dads.state.tx.us (Deverter,Mark) Date: Tue, 20 May 2008 14:32:32 -0500 Subject: subscribe Message-ID: -------------- next part -------------- An HTML attachment was scrubbed... URL: From rdahlstrom at directedge.com Thu May 29 07:03:40 2008 From: rdahlstrom at directedge.com (Dahlstrom, Roger) Date: Thu, 29 May 2008 07:03:40 -0400 Subject: [python-win32] How to get all the variables in a python shell References: <483E650B.5060902@timgolden.me.uk> Message-ID: -----Original Message----- > From: python-win32-bounces at python.org [mailto:python-win32-bounces at python.org] On Behalf Of Tim Golden > Sent: Thursday, May 29, 2008 4:11 AM > To: Python-Win32 List; python-list at python.org > Cc: Python-Win32 List > Subject: Re: [python-win32] How to get all the variables in a python shell > > lixinyi.23 at gmail.com wrote: > > I'm currently working on a scientific computation software built in > > python. > > What I want to implement is a Matlab style command window <-> > > workspace interaction. > > > > For example, you type 'a=1' in the command window, and you see a list > > item named 'a' in the workspace. > > You double click the icon of the item, and you see its value. You can > > modify the value of the list item, > > 1 -> 100 etc, after which if you go back to the command window and > > type 'a' and press enter, you see that > > varable a's value has been changed to 100. > > > > So my question is : if you have two DOS command windows running under > > WINDOWS OS, how can you make them share the same internal variable > > buffer? Or is there any easier way to implement such kind of > > interaction? > > I stronly suggest you look at IPython [1]. To do what I think > you're describing, you'd need to hack or reimplement the interpreter. > And that's what they've done. ISTR that they even have a branch > which is dealing with parallel instances. > > TJG > > [1] http://ipython.scipy.org/moin/ > _______________________________________________ > python-win32 mailing list > python-win32 at python.org > http://mail.python.org/mailman/listinfo/python-win32 I'd try looking at memcached (http://www.danga.com/memcached/apis.html). No hacking or reimplementation of the interpreter would be necessary, and there's a Python api available. I haven't used it for anything production related, but I have played with it a bit, and it's fast and stable. DISCLAIMER: This e-mail, and any attachments thereto, is intended only for use by the addressee(s) named herein and may contain legally privileged and/or confidential information. If you are not the intended recipient of this e-mail, you are hereby notified that any dissemination, distribution or copying of this e-mail, and any attachments thereto, is strictly prohibited. If you have received this in error, please immediately notify me and permanently delete the original and any copy of any e-mail and any printout thereof. E-mail transmission cannot be guaranteed to be secure or error-free. The sender therefore does not accept liability for any errors or omissions in the contents of this message which arise as a result of e-mail transmission. NOTICE REGARDING PRIVACY AND CONFIDENTIALITY Direct Edge ECN LLC may, at its discretion, monitor and review the content of all e-mail communications. www.directedge.com From bearophileHUGS at lycos.com Sun May 25 17:39:28 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sun, 25 May 2008 14:39:28 -0700 (PDT) Subject: Getting a set of lambda functions References: <83bb3e45-f32f-4811-831f-d1e31d4fcb1e@d77g2000hsb.googlegroups.com> Message-ID: <59719846-588e-414e-a1b9-cc7b04019501@k37g2000hsf.googlegroups.com> This may have some bugs left, but it looks a bit better: from inspect import getargspec class HashableFunction(object): """Class that can be used to wrap functions, to allow their hashing, for example to create a set of unique functions. >>> func_strings = ['x', 'x+1', 'x+2', 'x'] >>> func_list1 = [eval('lambda x:' + func) for func in func_strings] >>> func_set = set(HashableFunction(f) for f in func_list1) >>> len(func_set) 3 >>> set(f(10) for f in func_set) == set([10, 11, 12]) True >>> func_list2 = [lambda x=1: x, lambda x: x] >>> len(set(HashableFunction(f) for f in func_list2)) 2 >>> class Foo: ... def __eq__(self, other): raise NotImplementedError >>> func_list3 = [lambda x=Foo(): x, lambda x=Foo(): x] >>> set(HashableFunction(f) for f in func_list3) Traceback (most recent call last): ... NotImplementedError """ # Original code by I V , 25 May 2008, # http://groups.google.com/group/comp.lang.python/browse_thread/thread/a973de8f3562675c # modified by bearophile def __init__(self, func): self._func = func signature = getargspec(func) self._hash = hash(self._func.func_code) ^ \ hash(tuple(signature[0]) + tuple(signature[1:3])) def __eq__(self, other): return self._func.func_code == other._func.func_code and \ getargspec(self._func) == getargspec(other._func) def __hash__(self): return self._hash def __call__(self, *args, **kwargs): return self._func(*args, **kwargs) I haven't put a full hashing of getargspec(self._func) too into the __init__() because it may contain too much nested unhashable structures, but the __eq__() is able to tell them apart anyway, with some collisions. Bye, bearophile From bruno.desthuilliers at gmail.com Fri May 16 17:34:58 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Fri, 16 May 2008 14:34:58 -0700 (PDT) Subject: can't delete from a dictionary in a loop References: Message-ID: On 16 mai, 23:28, Hans Nowak wrote: > Dan Upton wrote: > > for pid in procs_dict: > > if procs_dict[pid].poll() != None > > # do the counter updates > > del procs_dict[pid] > > > The problem: > > > RuntimeError: dictionary changed size during iteration > > I don't know if the setup with the pids in a dictionary is the best way to > manage a pool of processes... I'll leave it others, presumably more > knowledgable, to comment on that. :-) But I can tell you how to solve the > immediate problem: > > for pid in procs_dict.keys(): I'm afraid this will do the same exact thing. A for loop on a dict iterates over the dict keys, so both statements are strictly equivalent from a practical POV. From deets at nospam.web.de Thu May 22 06:57:19 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 22 May 2008 12:57:19 +0200 Subject: Bug in floating-point addition: is anyone else seeing this? References: <8187c3b6-a772-456f-a54f-0af7babb353e@w34g2000prm.googlegroups.com> <6e4549da-6493-4be5-9ac0-945dd7cca323@q27g2000prf.googlegroups.com> Message-ID: <69l1teF33eaduU1@mid.uni-berlin.de> > > This person who started this thread posted the calculations showing > that Python was doing the wrong thing, and filed a bug report on it. > > If someone pointed out a similar problem in Flaming Thunder, I would > agree that Flaming Thunder was doing the wrong thing. > > I would fix the problem a lot faster, though, within hours if > possible. Apparently this particular bug has been lurking on Bugzilla > since 2003: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=323 I wonder how you would accomplish that, given that there is no fix. http://hal.archives-ouvertes.fr/hal-00128124 Diez From cjw at ncf.ca Thu May 8 09:51:26 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Thu, 08 May 2008 09:51:26 -0400 Subject: PCBuild.sin - Attempt to compile Python using Visual Studio 2008 In-Reply-To: References: Message-ID: <4823055E.9090207@ncf.ca> Gabriel Genellina wrote: > En Thu, 08 May 2008 09:55:36 -0300, Colin J. Williams escribi?: > >> The readme.txt has: >> >> All you need to do is open the workspace >> "pcbuild.sln" in Visual Studio, >> select the desired combination of >> configuration and platform and eventually >> build the solution. Unless you are going >> to debug a problem in the core or >> you are going to create an optimized >> build you want to select "Release" as >> configuration. >> >> Unfortunately, the Express Edition >> (Free) doesn't handle "solution" files. > > Yes, it does. You get a warning saying that solution *folders* aren't supported; that just means that you won't see those 26 projects nicely grouped, only as a long list, that's all... Python builds fine with Visual C++ Express Edition. > Select Release, Win32 from the dropdown lists, press F7, and wait for compilation to complete... > Many thanks. Yes, you are right. Colin W. From bruno.42.desthuilliers at websiteburo.invalid Fri May 9 04:37:01 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 09 May 2008 10:37:01 +0200 Subject: Newbie to python --- why should i learn ! In-Reply-To: <9f5ee6c3-86f7-401a-acc8-cd2c9b059fbd@x19g2000prg.googlegroups.com> References: <9f5ee6c3-86f7-401a-acc8-cd2c9b059fbd@x19g2000prg.googlegroups.com> Message-ID: <48240d2d$0$30967$426a34cc@news.free.fr> Raxit at MyKavita.com a ?crit : > Hi, > > i was reading/learning some hello world program in python. > I think its very simillar to Java/C++/C#. Err... You saw a Python helloworld and a Java helloworld and you found them "very similar" ??? > What's different (except > syntax) ? dynamism (and not only wrt/ the type system), higher order functions, closures, lazy evaluation... and fun. > what can i do easily with python which is not easy in c++/java !? Enjoy writing a working app focusing on the problem to solve instead of wasting time writing boilerplate code and going thru hoops just to satisfy the compiler. From alan.wright at volubill.com Wed May 21 06:47:59 2008 From: alan.wright at volubill.com (Alan Wright) Date: Wed, 21 May 2008 11:47:59 +0100 Subject: Newbie: Keep TCP socket open References: Message-ID: Thanks Roy Any ideas how to code this child process stuff, as I said I am newbie and not from a coding background to be honest ideally yes, i'd get 50K, but if i can get above 30K that would be OK Alan "Roy Smith" wrote in message news:roy-27A881.20583919052008 at 70-1-84-166.area1.spcsdns.net... > In article , > "Alan Wright" wrote: > >> Thanks for the feedback. >> >> Using the socket in a list is great >> >> However, as i imagined, I now get a limit of around 1500 conns before the >> system crashes out, also i have noticed, that the ports loop back to 1025 >> when they hit 5000. >> >> Any ideas on how to make the list/socket get to around 50K > > Yikes. Not on any box I know of. A given process is limited in how many > descriptors it can have open at once. I don't know of any that will allow > anywhere near 50k. Somewhere in the 1-2000 range would be more typical. > The 1500 you report is not at all surprising. > > You might try creating a bunch of child processes with os.system() or > something of that ilk. Create 50 processes and have each one open 1000 > sockets. > > The next thing you have to worry about is whether the OS can handle 50k > file descriptors open per-system. Or 50k sockets, or TCP connections. I > wouldn't be too surprised if many systems couldn't. The address space > (TCP > port numbers) is 16-bit (unsigned), or about 65k, but you may well run > into > some other system limit long before you exhaust the theoretically > available > ports. > > Something like Scapy, recommended by others, may indeed be able to > generate > all those SYN packets you want, but that doesn't mean you'll get all the > open connections you seek. You send a SYN packet to the remote host, and > it sends back a SYN/ACK. The local kernel now sees a SYN/ACK packet for a > port it doesn't know about. I'm not sure what the RFCs say about that, > but > I wouldn't be surprised if the kernel ends up sending a RST or maybe a FIN > or something like that. The kernel owns the ports; it's not nice to try > and mess with them on your own. From castironpi at gmail.com Sun May 11 00:27:18 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 10 May 2008 21:27:18 -0700 (PDT) Subject: Now what!? References: <68m0i1F2t8265U1@mid.uni-berlin.de> <7363f4c0-1dec-4943-a9f6-7a24c3aff971@e39g2000hsf.googlegroups.com> <9GlVj.168$PE5.102@fe087.usenetserver.com> <8eb3fdfb-b8ae-4a1f-a2f3-fde46206b637@d77g2000hsb.googlegroups.com> Message-ID: On May 10, 10:05?pm, hdante wrote: > On May 10, 8:22?pm, notbob wrote: > > > On 2008-05-10, Dennis Lee Bieber wrote: > > > > ? ?So... in short, you'd need to have been reading a tutorial specific > > > to "shell" scripting... > > > I have been. ?I'm also trying to learn bash shell scripting, not to mention > > sed/awk, php, etc. ?I should have started this a long time ago, but I'm lazy > > ?Throw all of this away and learn just python. That will be much > simpler for you. > > > and, like I said, I'm not particularly fond of coding. ?Yes, I have learned > > basic C and basic , but never beyond intro. ?Now, I'm doing it because I'm a > > ?Forget basic and learn python. Later you can learn C. Fiscally speaking, C and Python may well be just as economical. So long as you've spent time learning a computer language, hold you can get your needs met*. * Even if money isn't a measure of value, a true measure of value, or measure of true value. In light of the actual writing of Python, if you make it, like to. In sight of competitors, argue that Python is at least a locus, node, nodepoint, or to-central of something about free and software. Hold that Python is an end in itself, and/or that writing it is, and/ or is writing an implementation. (Can you talk about languages like they're people?) Distinguish further between languages, programs, libraries, and the standards. Then evaluate Python for population assortment characteristics, such as population, overcrowding, undercrowding, and various sense criteria. In the Windows world, we are asking, how many keystrokes per thought, mouse motions per error, and cross. If your boss sucks but Python rules, it remains unclear that either is any better. It is not clear that Python has a will, or computers have. If they have minds, whether absent will or not, perhaps it wouldn't pay to like it too much. What diversity can you find on a newsgroup? > > > > > geezer and I figure my brain needs more exercise then just blabbing on > > usenet. ?Besides, I've been cruising while using linux for too long and have > > remained low end intermediate. ?Time to get serious. ?Pass the cheat sheets! > > > nb- Hide quoted text - > > - Show quoted text - From bruno.desthuilliers at gmail.com Fri May 23 17:36:37 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Fri, 23 May 2008 14:36:37 -0700 (PDT) Subject: Storing objects in relational database References: <03a17198-3eb2-438e-97c9-db18c0c24a80@c65g2000hsa.googlegroups.com> Message-ID: On 23 mai, 23:14, nayden wrote: > and then I try to restore the object with the following code > > def success(rv): > print "success" > str = cStringIO.StringIO(libpq.PgUnQuoteBytea(rv[0][0])) > i = cPickle.load(str) > i.toString() > > the execution fails just after the print statement, and I am not quite > sure why is that. Please reread the doc for pickle.dump, pickle.dumps, pickle.load and pickle.loads. You just don't need StringIO here, just use the 's versions of the functions. > I would love to find out what people are using when they need to do > something similar > perhaps I am trying to do it the perl way, while there is an elegant > python solution. I don't know if you'd label it 'elegant', but as far as I'm concerned, storing serialized objects as blobs in a relational database is mostly non-sense. If I use a relational database, it's because it is a *relational* database. If you want an OODB, then we have the ZODB, Durus and a couple others. From gagsl-py2 at yahoo.com.ar Thu May 15 22:31:55 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 15 May 2008 23:31:55 -0300 Subject: Handling test data that depends on temporal data (that might change while the test runs) References: <1e5bcefd0805151021i6306946dre6e54307e91d9c1c@mail.gmail.com> <1e5bcefd0805151850r899c923m3da14c089973beab@mail.gmail.com> Message-ID: En Thu, 15 May 2008 22:50:21 -0300, Marcelo de Moraes Serpa escribi?: > Hmm.. I re-read your message and I think I'm approaching testing in a > mechanical way, indeed. > > You're right, my test is kind of pointless, given the objective of the > function, which is to generate a differnt directory name each time it is > called. I also found it kind of strange to repeat the implementation in > the > test method. However, something keeps telling me that it still has to be > "unit" tested, sonehow (the algorith used). Again, that depends on the actual purpose of such function. If all you want is a unique directory name, you might consider the set of users and time as "hints" only; a completely random directory name would be OK. You might not even require that the same input generates always the same output. The less restrictions you put on the required behavior, the easiest is to replace the current implementation. Of course, if you *do* require some invariant or some condition, you have to test for it. -- Gabriel Genellina From mde at MicahElliott.com Thu May 1 14:17:47 2008 From: mde at MicahElliott.com (Micah Elliott) Date: Thu, 01 May 2008 11:17:47 -0700 Subject: Best way to store config or preferences in a multi-platform way. In-Reply-To: <790cec6c-b057-4a2d-bc2c-e683630c1127@w7g2000hsa.googlegroups.com> References: <790cec6c-b057-4a2d-bc2c-e683630c1127@w7g2000hsa.googlegroups.com> Message-ID: <20080501181747.GA6567@micahelliott.com> On 2008-05-01 Carl Banks wrote: > If you don't intend to write a GUI to do that, write a simple > text file parser (if the options are simple), use ConfigParser, > or use a Python file that you exec. INI is great for so many things. It is also extremely commonplace, regardless of platform. The biggest challenge might be choosing which one to adopt: http://wiki.python.org/moin/ConfigParserShootout -- Micah Elliott | mde at MicahElliott.com | http://MicahElliott.blogspot.com -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From space.captain.face at gmail.com Thu May 29 04:23:45 2008 From: space.captain.face at gmail.com (Kalibr) Date: Thu, 29 May 2008 01:23:45 -0700 (PDT) Subject: Finding file details... Message-ID: I've been trying to figure out how to find the details of files (specifically music for now) for a little sorting script I'm making, My aim is to get details on the artist, album, and genre for mp3 and wma files (possibly more in the future). My closest match was when I stumbled accross PyMedia, but it only supports up to 2.4 (I have 2.5). Now I see a bit mentioned on GetFileVersionInfo, but that doesn't seem to help (and most of it went over my head). Is there any module I can use to find this sort of data? I'm trying to not make it specialised in music, because I may want to extend this to picture, movie, text etc. files in the future. Any ideas how I could go about this? From cmpython at gmail.com Sat May 10 03:58:12 2008 From: cmpython at gmail.com (CM) Date: Sat, 10 May 2008 00:58:12 -0700 (PDT) Subject: firefox add-on to grab python code handily? Message-ID: <93e5303c-d19e-4037-9b39-368df4325c76@c65g2000hsa.googlegroups.com> I encounter a fair number of small Python scripts online, and usually try them out by copying them to the clipboard, pasting into Notepad, saving them, and either running them directly or opening them in IDLE. And so I was wondering if anyone knew of an extension/add-on/script for Firefox which would allow a way to do something like this: user highlights Python code on a webpage right clicks selects a menu item, "Save as Python code" FF pops up a filename dialog or popup for filename (and, though I don't know if this is possible, runs Python code) Not an important thing by any means, but it would be a nice convenience. I know there are similar add-ons in FF for grabbing highlighted text and saving, but they are not good, as they don't seem to preserve line breaks properly or append the .py extension, etc. I've Googled for this and so far it seems it doesn't exist. Anyone know? From bruno.42.desthuilliers at websiteburo.invalid Fri May 16 04:12:45 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 16 May 2008 10:12:45 +0200 Subject: default object comparison considered harmful? In-Reply-To: References: Message-ID: <482d41eb$0$23030$426a74cc@news.free.fr> A.T.Hofkamp a ?crit : > Hello all, > > Yesterday we found the cause of a bug that has caused problems for a long time. > It appeared to be the following: > > class A(object): > pass > > print min(1.0, A()) > > which is accepted by Python even though the A() object is not numerical in > nature. > > The cause of this behavior seems to be the compare operation of the object > class. > > > Is there a way to disable this behavior in Python (other than deriving a new > 'object-like' class that doesn't do comparisons?) Other than implementing a custom __cmp__ function ? Not AFAIK. FWIW, you don't necessarily need to fiddle with inheritance - you can also monkeypatch your classes (nb : for new-style objects, you cannot monkeypatch __magic__ methods on a per-object basis). Also, IIRC, this behaviour has changed in Python 3. From aaron.watters at gmail.com Fri May 2 16:05:43 2008 From: aaron.watters at gmail.com (Aaron Watters) Date: Fri, 2 May 2008 13:05:43 -0700 (PDT) Subject: Why is None <= 0 References: <481226f9$0$20866$9b622d9e@news.freenet.de> Message-ID: <769285d3-d774-4690-9062-d03c8fb1a93f@24g2000hsh.googlegroups.com> On Apr 25, 8:17 pm, Jon Ribbens wrote: > On 2008-04-25, Martin v. L?wis wrote: > > > None is smaller than anything. > > According to Tim Peters, this is not true. > > See http://bugs.python.org/issue1673405 This is unfortunate. I would advocate something like ordering "incomparable objects" by the name of their type or something similar. When building indexing structures it can be very nice to be able to construct a list of heterogeneous tuples and sort them without getting an exception. Implementing this using L.sort(cmp) where cmp is implemented in Python can result in a significant speed penalty. What's up with Tim Peters anyway? I haven't seen much from him for a while. -- Aaron Watters === http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=quote+tim+peters From gandalf at shopzeus.com Wed May 21 10:35:11 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Wed, 21 May 2008 16:35:11 +0200 Subject: problem with import / namespace In-Reply-To: <483427BF.6030805@shopzeus.com> References: <483427BF.6030805@shopzeus.com> Message-ID: <4834331F.2000606@shopzeus.com> > > When you try to import a module, python starts to search for it. The > was it does the search is very well defined. It mostly depends on the > current directory and sys.path. You can read more about this here: "The was it" -> "The way it" > - inside your app.py file either make sure that the current dir is > /app, or insert /app in the first place in sys.path Example: import os,sys mydir = os.split(os.abspath(__file__)[0] os.chdir(mydir) # Option 1 - chdir to dir. containing your app sys.path.insert(0,mydir) # Option 2 - add to your sys.path Good things to know: - In Python, it is recommended not to use upper case module/package names. It is a convention. However, some 3rd party packages (like wxPython or PIL) break this rule. - Obviously, you should not use numbers, reserved words for module or package names. The name should tell what is it for. - It is good to know the standard library, and avoid overwriting names from the standard lib. For example, you can create your own 'os.py' module but it would be very silly. I personally tend to use absolute package names for libraries that are not tied to a specific project but it does not need to be that way. You can find many threads in python-list about how applications and packages should be constructed. Best, Laszlo From aahz at pythoncraft.com Fri May 30 16:00:32 2008 From: aahz at pythoncraft.com (Aahz) Date: 30 May 2008 13:00:32 -0700 Subject: should I put old or new style classes in my book? References: Message-ID: In article , wrote: > >Anyway, I am posting to ask about the current status of new style >classes. I am planning to present only one style in the book, because >the differences between them don't matter for anything I am doing in >the book. You've got a tough use-case. When is your book supposed to be done? To what extent to you want to make your book work with 3.x? Overall, I'm generally in favor of presenting both (I'm opposed to new-style-only), but in your case it sounds like just new-style would be better. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Need a book? Use your library! From terry.yinzhe at gmail.com Fri May 16 19:44:00 2008 From: terry.yinzhe at gmail.com (Terry) Date: Fri, 16 May 2008 16:44:00 -0700 (PDT) Subject: Get all the instances of one class Message-ID: <29f39184-2daa-49fc-a7af-7f869fd2d688@h1g2000prh.googlegroups.com> Hi, Is there a simple way to get all the instances of one class? I mean without any additional change to the class. br, Terry From maxm at mxm.dk Tue May 27 13:24:11 2008 From: maxm at mxm.dk (Max M) Date: Tue, 27 May 2008 19:24:11 +0200 Subject: New chairman In-Reply-To: References: <3720fb99-ac37-469b-b8ce-ece3ed27b8e5@m36g2000hse.googlegroups.com> Message-ID: Sverker Nilsson skrev: > I was talking about Guido van Rossum > > The one who decides, so far when people agree I have been using Python since the nineties. I cannot remember when I have had to rewrite old code because of changes in the language. At the same time I have been feeling as if I was sitting in a time machine watching other languages whoosh by at breakneck speed. Entire technologies have been developed to make programming as practical and easy as it has been in Python the entire time. So I find it hard to see exactly what it is that Guido is doing wrong? -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From eckhardt at satorlaser.com Wed May 21 06:14:22 2008 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Wed, 21 May 2008 12:14:22 +0200 Subject: C-like assignment expression? References: <68b5d090-9e3b-4e7d-9dda-fc1b099822c2@m73g2000hsh.googlegroups.com> Message-ID: <099dg5-r6j.ln1@satorlaser.homedns.org> boblatest at googlemail.com wrote: > I have an if-elif chain in which I'd like to match a string against > several regular expressions. Also I'd like to use the match groups > within the respective elif... block. The C-like idiom that I would > like to use is this: > > if (match = my_re1.match(line): > # use match > elsif (match = my_re2.match(line)): > # use match > elsif (match = my_re3.match(line)) > # use match > > ...buy this is illegal in python. The other way is to open up an else: > block in each level, do the assignment and then the test. This > unneccessarily leads to deeper and deeper nesting levels which I find > ugly. How about this (untested) code: for re in (re1, re2, re3): match = re.match(line) if match: # use it This requires that "use it" means the same for each regular expression though... Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From krumblebunk at gmail.com Tue May 6 11:29:59 2008 From: krumblebunk at gmail.com (krumblebunk at gmail.com) Date: Tue, 6 May 2008 08:29:59 -0700 (PDT) Subject: Reversing a dict? References: <6e3fdb8c-687f-42b6-b544-19c88950cc00@q1g2000prf.googlegroups.com> Message-ID: Thanks all!! kb. From kirk at daycos.com Fri May 30 14:53:55 2008 From: kirk at daycos.com (Kirk Strauser) Date: Fri, 30 May 2008 13:53:55 -0500 Subject: Calling instance methods from a decorator References: <87d4n3n1z7.fsf@internal.daycos.com> <6aasg8F35t0j9U1@mid.uni-berlin.de> Message-ID: <871w3jmxmk.fsf@internal.daycos.com> At 2008-05-30T17:40:17Z, "Diez B. Roggisch" writes: > Of course you can get the self - just use the first paramter, because it > *is* self. Self is just a parameter - nothing special. If I blame it on being a long week, can I keep my geek card? -- Kirk Strauser The Day Companies From mccredie at gmail.com Thu May 1 14:52:48 2008 From: mccredie at gmail.com (Matimus) Date: Thu, 1 May 2008 11:52:48 -0700 (PDT) Subject: Best way to store config or preferences in a multi-platform way. References: Message-ID: <006ba21e-8510-4dd1-992c-3da3f7997bec@v26g2000prm.googlegroups.com> On May 1, 4:37 am, Lance Gamet wrote: > Hi, python beginner starting a new project here. > > This project will store most of its actual data in a shared-database, but > I have a small amount of user specific data that I need to be stored like > configuration or preferences for example, the list of databases that the > program should connect to. > > On Unix this might be a .file, on windows this could be in the registry, > or an ini file or an xml file in ProgramData or AppData or something. > > Is there a pythony way to store such config data, perhaps there is > already a standard python package for such a purpose? > > My app uses Qt, and Qt has its method of doing it (QSettings), but for > architectural reasons I don't want to use it. > > Could sqlite be an option perhaps? I am still undecided if the ability > for the user to edit the file independently of the program is a good or > bad thing. > > Thanks a lot. > Lance sqlite is a wonderful option, if the user doesn't need to directly edit it. Alternatively, you might consider just using python code. Something like this: [config_file.py] class Config: optiona = 1 optionb = 2 [/end file] Then, in your code you can just: >>> import imp >>> m = imp.load_source("config_file", "./config_file.py") # use appropriate path (of course) >>> m.Config.optiona 1 >>> m.Config.optionb 2 Like any other solution, this option has advantages and disadvantages, but I think it is worth exploring. The class method in the above code is just an example, choose whatever format is appropriate. As for generating the contents of the file, tripple quoted strings and `%r` are your friends. Matt From torriem at chem.byu.edu Thu May 1 12:51:58 2008 From: torriem at chem.byu.edu (Michael L Torrie) Date: Thu, 01 May 2008 10:51:58 -0600 Subject: Zope/DTML Infuriating... In-Reply-To: <4819F4A5.4010302@gmail.com> References: <65492d56-de86-4979-a886-b4e6f9b3b42f@2g2000hsn.googlegroups.com> <4819F4A5.4010302@gmail.com> Message-ID: <4819F52E.8080100@chem.byu.edu> Michael Torrie wrote: > The second example, x = Integer.fromString('5') demonstrates a huge > weakness in Java. Ahem. Javascript. Sorry. -- Michael Torrie Assistant CSR, System Administrator Chemistry and Biochemistry Department Brigham Young University Provo, UT 84602 +1.801.422.5771 A: Because it messes up the order in which people normally read text. Q: Why is top-posting such a bad thing? From gherron at islandtraining.com Fri May 16 17:33:28 2008 From: gherron at islandtraining.com (Gary Herron) Date: Fri, 16 May 2008 14:33:28 -0700 Subject: can't delete from a dictionary in a loop In-Reply-To: <5504f9ac0805161422r31f3a0d6sbe4e49914ade7383@mail.gmail.com> References: <5504f9ac0805161422r31f3a0d6sbe4e49914ade7383@mail.gmail.com> Message-ID: <482DFDA8.3040305@islandtraining.com> Dan Upton wrote: > This might be more information than necessary, but it's the best way I > can think of to describe the question without being too vague. > > The task: > > I have a list of processes (well, strings to execute said processes) > and I want to, roughly, keep some number N running at a time. If one > terminates, I want to start the next one in the list, or otherwise, > just wait. > > The attempted solution: > > Using subprocess, I Popen the next executable in the list, and store > it in a dictionary, with keyed on the pid: > (outside the loop) > procs_dict={} > > (inside a while loop) > process = Popen(benchmark_exstring[num_started], shell=true) > procs_dict[process.pid]=process > > Then I sleep for a while, then loop through the dictionary to see > what's terminated. For each one that has terminated, I decrement a > counter so I know how many to start next time, and then try to remove > the record from the dictionary (since there's no reason to keep > polling it since I know it's terminated). Roughly: > > for pid in procs_dict: > if procs_dict[pid].poll() != None > # do the counter updates > del procs_dict[pid] > > The problem: > > RuntimeError: dictionary changed size during iteration > > So, the question is: is there a way around this? Yes. Create a list of keys, and loop through it: pids = procs_dict.keys() for pid in pids: if procs_dict[pid].poll() != None # do the counter updates del procs_dict[pid] Then the diction delete operation won't trip up the loop and its internal counter. OR: Create a list of things to delete while you are in the loop, and do the delete afterwards deleteme = [] for pid in procs_dict: if procs_dict[pid].poll() != None # do the counter updates deleteme.append(pid) for pid in deleteme: del procs_dict[pid] OR: shred and rebuild the dictionary each time: new_dict = {} for pid,value in procs_dict.items(): if value.poll() != None: # do the counter updates pass else: new_dict[pid] = value procs_dict = new_dict Gary Herron > I know that I can > just /not/ delete from the dictionary and keep polling each time > around, but that seems sloppy and like it could keep lots of memory > around that I don't need, since presumably the dictionary holding a > reference to the Popen object means the garbage collector could never > reclaim it. Is the only reasonable solution to do something like > append all of those pids to a list, and then after I've iterated over > the dictionary, iterate over the list of pids to delete? > > (Also, from the implementation side, is there a reason the dictionary > iterator can't deal with that? If I was deleting from in front of the > iterator, maybe, but since I'm deleting from behind it...) > -- > http://mail.python.org/mailman/listinfo/python-list > From gagsl-py2 at yahoo.com.ar Thu May 8 09:28:13 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 08 May 2008 10:28:13 -0300 Subject: PCBuild.sin - Attempt to compile Python using Visual Studio 2008 References: Message-ID: En Thu, 08 May 2008 09:55:36 -0300, Colin J. Williams escribi?: > The readme.txt has: > > All you need to do is open the workspace > "pcbuild.sln" in Visual Studio, > select the desired combination of > configuration and platform and eventually > build the solution. Unless you are going > to debug a problem in the core or > you are going to create an optimized > build you want to select "Release" as > configuration. > > Unfortunately, the Express Edition > (Free) doesn't handle "solution" files. Yes, it does. You get a warning saying that solution *folders* aren't supported; that just means that you won't see those 26 projects nicely grouped, only as a long list, that's all... Python builds fine with Visual C++ Express Edition. Select Release, Win32 from the dropdown lists, press F7, and wait for compilation to complete... -- Gabriel Genellina From mal at egenix.com Tue May 13 06:52:32 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Tue, 13 May 2008 12:52:32 +0200 Subject: Is there no single/uniform RDBMS access API module for Python ? In-Reply-To: <3de8e1f70805112243u765fc507v32c5461be34d4077@mail.gmail.com> References: <3de8e1f70805112243u765fc507v32c5461be34d4077@mail.gmail.com> Message-ID: <482972F0.2090101@egenix.com> On 2008-05-12 07:43, Banibrata Dutta wrote: > Hi, > > Again a noob question. > > Based on this URL http://wiki.python.org/moin/DatabaseInterfaces , is it > correct to conclude that there is no RDBMS agnostic, single/uniform DB > access API for Python ? > Something in the lines of JDBC for Java, DBD for Perl etc. ? > > How is the RDBMS change handled for solutions which need to work with > different RDBMSs ?? Most Python database modules adhere to the Python Database API specification (DB-API). The current version 2 is available in the PEP format as: http://www.python.org/dev/peps/pep-0249/ The spec was created and is maintained by the Python DB-SIG: http://www.python.org/community/sigs/ If you are looking for a generic Python database interface, then I'd suggest you have a look at our mxODBC: http://www.egenix.com/products/python/mxODBC/ It works on all common Python platforms (e.g. Windows, Linux x86/x64, Macs, Solaris, etc.) and provides the same API on these, so apart from changing the ODBC driver configuration, you don't need to make any major changes to your application if you want to switch from one platform to another. Note: mxODBC is a commercial add-on to our eGenix mx Base OSS distribution. It's maintained by eGenix and has been around since 1997. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, May 13 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From russblau at hotmail.com Thu May 22 17:52:02 2008 From: russblau at hotmail.com (Russell Blau) Date: Thu, 22 May 2008 17:52:02 -0400 Subject: How do I make a copy of my class object? References: Message-ID: "Marlin Rowley" wrote in message news:BAY135-W134E8CAB38A2ACB2F5933F9FC60 at phx.gbl... > I have a class object which has the usual data members and functions. > I'm trying to make a copy of this class (which includes wx.Bitmap objects) > but deepcopy() doesn't seem to work. How would I do this? Are you trying to make a copy of the "class object" or of a class instance? What error message are you getting when you call deepcopy() on this object? From bronger at physik.rwth-aachen.de Thu May 1 19:21:38 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Fri, 02 May 2008 01:21:38 +0200 Subject: Best way to store config or preferences in a multi-platform way. References: <878wytvis5.fsf@physik.rwth-aachen.de> Message-ID: <874p9hvce5.fsf@physik.rwth-aachen.de> Hall?chen! Ivan Illarionov writes: > [...] > > For me it looks more like an old-school/new-school thing than > use-case thing. I may be wrong, but I see more and more new > projects use things like reST and YAML/JSON and it feels like they > are gradually replacing traditional old-school solutions. > > And I've got very strong impression that YAML is a the future of > configuration files when Google released their App Engine. In contrast to many other areas of software, configuration files needn't be compatible with anything except the user's brain. So even if the rest of the world uses config format X, you can safely stick with config format Y. I mean, YAML is not really a complex thing, yet it was conceived not before 2001. The reason is that traditional config files do a good job. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From sven.siegmund at gmail.com Sun May 11 18:27:51 2008 From: sven.siegmund at gmail.com (Sven Siegmund) Date: Sun, 11 May 2008 15:27:51 -0700 (PDT) Subject: IDLE 3.0a5 has problems with Unicode Message-ID: <13b7e4cc-031b-4c57-8212-9fe186d97324@e39g2000hsf.googlegroups.com> Hello, I am testing Python 3.0a5's handling of unicode strings. Since SPE is not yet for Python 3.0, I have begun to write in IDLE 3.0a5. I have a source code which IDLE 3.0a5 cannot parse, but Python 3.0a5 can: #!/usr/bin/python # -*- coding: utf-8 -*- def na?tiSlovn?k(zdroj='slovn?k.txt'): soubor = open(zdroj, mode='r', encoding='utf_8') ??dky = soubor.readlines() for ??dek in ??dky: print(??dek, end='') na?tiSlovn?k() # End of source code I have set up Default Source Encoding to UTF-8 in IDLE's general configuration. Still, when I open that source code and try to run it, IDLE complains about "invalid character in identifier" and highlights "zdroj" red in the first line (sic!). However, when I run the source code from command line (by "python "), it gets executed well and does what it shall do. I should probably add, that I have installed py3k:62932M, May 9 2008, 16:23:11 [MSC v.1500 32 bit (Intel)] on win32. I use Windows XP SP 3. Is this a known bug if IDLE 3.0a5 which will be fixed in the final release? Greetings, S. From victorsubervi at gmail.com Thu May 8 11:33:55 2008 From: victorsubervi at gmail.com (Victor Subervi) Date: Thu, 8 May 2008 10:33:55 -0500 Subject: Custom Classes? In-Reply-To: <4dc0cfea0805020638l59af4bb2o4abdcb12ee88995f@mail.gmail.com> References: <4dc0cfea0804300902o7493dab2m35999b5b59deace4@mail.gmail.com> <1209576920.4990.17.camel@aalcdl07.lib.unc.edu> <4dc0cfea0805011531s4574eb0bk8b6aea6ac010c881@mail.gmail.com> <1209729679.6589.23.camel@jcd-desktop> <4dc0cfea0805020638l59af4bb2o4abdcb12ee88995f@mail.gmail.com> Message-ID: <4dc0cfea0805080833l7fc8c711t92fdad94e2014551@mail.gmail.com> Okay, trying this again with everything working and no ValueError or any other errors, here we go: Load this code. Unless you use a similar login() script, you will want to edit your own values into the user, passwd, db and host: #!/usr/bin/python import MySQLdb import sys,os sys.path.append(os.getcwd()) from login import login user, passwd, db, host = login() pic = "pic1" w = 20 x = 0 d = 6 y = 1 getpic = "getpic" + str(w) + ".py" try: os.remove(getpic) except: pass code = """ #!/usr/local/bin/python import cgitb; cgitb.enable() import MySQLdb import cgi import sys,os sys.path.append(os.getcwd()) from login import login user, passwd, db, host = login() form = cgi.FieldStorage() picid = int(form["id"].value) x = int(form["x"].value) pics = {1:'pic1',2:'pic1_thumb',3:'pic2',4:'pic2_thumb',5:'pic3',6:'pic3_thumb',7:'pic4',8:'pic4_thumb',\ 9:'pic5',10:'pic5_thumb',11:'pic6',12:'pic6_thumb'} pic = pics[x] db = MySQLdb.connect(host, user, passwd, db) cursor= db.cursor() sql = "select %s from products where id='%s';" % (pic, str(picid)) cursor.execute(sql) content = cursor.fetchall()[0][0].tostring() cursor.close() print 'Content-Type: image/jpeg' print print content """ script = open(getpic, "w") script.write(code) script.close() and then surf to: http://whatever.url/getpic20.py?id=6&x=1 Also, please re-send the link on how to post good questions to the list. I cannot find it. TIA, Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From jpthing at online.no Thu May 8 04:05:36 2008 From: jpthing at online.no (John Thingstad) Date: Thu, 08 May 2008 10:05:36 +0200 Subject: The Importance of Terminology's Quality References: Message-ID: P? Thu, 08 May 2008 04:14:35 +0200, skrev Kyle McGivney : >> ? Module, Block, in Mathematica is in lisp's various ?let*?. The >> lisp's keywords ?let?, is based on the English word ?let?. That word >> is one of the English word with multitudes of meanings. If you look up >> its definition in a dictionary, you'll see that it means many >> disparate things. One of them, as in ?let's go?, has the meaning of >> ?permit; to cause to; allow?. This meaning is rather vague from a >> mathematical sense. Mathematica's choice of Module, Block, is based on >> the idea that it builds a self-contained segment of code. (however, >> the choice of Block as keyword here isn't perfect, since the word also >> has meanings like ?obstruct; jam?) > > If the purpose of let is to introduce one or more variable bindings, > then I don't see how changing to block or module would improve > anything. I've always found it fairly intuitive to parse (let ((x > 5)) ...) to "let x be five". Additionally, replacing let with the > synonyms you provided would approximately yield "permit x to be five" > or "allow x to be five". In my mind you have constructed an argument > in favor of let here (obviously it's better than block, because > nobody's going to come along and be confused about whether let will > "obstruct" or "jam" them :) How about bind? (bind ((v f (mod i)) ((a b) list) (t (rem q))) 1. is a multiple-value-bind 2. is a destructuring-bind 3. is a let http://common-lisp.net/project/metabang-bind/ To me this is a example of where the ANSI group could have spent more time on naming. -------------- John Thingstad From deets at nospam.web.de Sun May 4 12:38:42 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 04 May 2008 18:38:42 +0200 Subject: Weird import problem In-Reply-To: References: Message-ID: <68674mF2rjrt5U1@mid.uni-berlin.de> Anton81 schrieb: > I have a directory structure like > > NS/dir1/file1.py > NS/dir2/file2.py This *must* be wrong or at least not the full directory listing - please read http://docs.python.org/tut/node8.html > if in the python shell I type > > import NS.dir1.file1 > > it works, however typing > > import NS.dir2.file2 > > fails with > > ImportError: No module named dir2.file2 > > Any ideas what could go wrong? > Directory permissions seem to be OK. Missing __init__.py in the dir2? Diez From tarun.kap at gmail.com Fri May 2 14:25:13 2008 From: tarun.kap at gmail.com (TkNeo) Date: Fri, 2 May 2008 11:25:13 -0700 (PDT) Subject: list.index crashes when the element is not found Message-ID: WHAT ? This is crazy From castironpi at gmail.com Tue May 20 17:19:12 2008 From: castironpi at gmail.com (castironpi) Date: Tue, 20 May 2008 14:19:12 -0700 (PDT) Subject: conventions/requirements for 'is' vs '==', 'not vs '!=', etc References: <4dc24f2e-04f5-4ad6-b021-f416ef5c7415@z72g2000hsb.googlegroups.com> <8ebd28f1-887f-45c9-a35f-af9023b062ea@u12g2000prd.googlegroups.com> <3629843a-ebcb-4f15-82f1-899500f7b91f@t54g2000hsg.googlegroups.com> <20080519234214.beae9314.johnjsal@NOSPAMgmail.com> <720e75d1-806e-4fb1-94f5-a1a9c6cae8c1@x41g2000hsb.googlegroups.com> Message-ID: <111a4113-d453-4c2c-9997-0c27d8fcea8b@a32g2000prf.googlegroups.com> On May 20, 11:49?am, s0s... at gmail.com wrote: > On May 20, 9:04 am, castironpi wrote: > > > > > > > On May 20, 5:04 am, Duncan Booth wrote: > > > > John Salerno wrote: > > > >>>> a = 'this is longer' > > > >>>> b = 'this is longer' > > > >>>> a == b > > > > True > > > >>>> a is b > > > > False > > > > > In the above example, Python has created only one string called > > > > 'hello' and both x and y reference it. However, 'this is longer' is > > > > two completely different objects. > > > > That is true when run interactively, but the behaviour changes again if you > > > run it as a script: > > > > C:\Temp>type t.py > > > a = 'this is longer' > > > b = 'this is longer' > > > print a is b > > > > C:\Temp>t > > > True > > > > In short, two equal strings may or may not be identical and any code which > > > makes assumptions based on observed behaviour is broken. If you want to be > > > able to test identity on strings safely then use the 'intern()' builtin to > > > get repeatable behaviour. > > > > -- > > > Duncan Boothhttp://kupuguy.blogspot.com > > > There is no such thing as real true equals. > > That's quite some dark deep philosophy. Fortunately, computers are not > as complicated as real life. I would argue that, programatically, > there *is* such thing as "real true equals". I would also argue that > that view is most certainly not shared by everyone.- Hide quoted text - > > - Show quoted text - Mean as it sounds, bits are pigeonholes: 5+V or 0. As such, computers are able to simulate numerical identity, but, don't forget, all your inputs are discretized (pigeonholed). Symbolic (mathematical) identity (equality) is defined as a reflexive, symmetric, transitive relation, and partitions its domain into equivalence classes (membership in which is binary). Symbols are outside of cause. Ma: Symbolic identity is a mathematical relation Mb: Symbols are acausal m: Matter is causal C: Symbolic identity is not defined on matter. Further, conclude computers are symbolic only. Now, what can a hoard of people do with some symbols? But, I defer on the practical sense. From amit.uttam at gmail.com Fri May 16 20:12:10 2008 From: amit.uttam at gmail.com (amit.uttam at gmail.com) Date: Fri, 16 May 2008 17:12:10 -0700 (PDT) Subject: SImple python print question References: <47054b9b-fb5e-4601-9e2d-75bfe61e9cb8@w1g2000prd.googlegroups.com> Message-ID: On May 16, 4:02 pm, Hans Nowak wrote: > amit.ut... at gmail.com wrote: > > Hey there, > > > I have a simple question about python print statement. Take the > > following code snippet for example... > > > 1 print "-#- executing: %s" % section, > > 2 tests[section] = test.testcase(name=config.get(section,'name')) > > 3 tests[section].runTest() > > 4 printStatus(tests[section]) > > > Now the problem is that line 1 does not get printed until line 4. What > > I thought would happen is that line 1 gets executed and the user sees > > that the statement that the test case is executing. Then after the > > test case executes a "PASS" or "FAIL" appears on the same line as the > > "-#- executing: 0053" statement. > > > e.g. > > -#- executing: 0053 FAIL > > > Some tests take a long time to finish thus the screen is blank until > > the entire test finishes and the above statement is outputted. > > > Thanks for any help. > > 'print' sends its output to sys.stdout, which is buffered, and may not be > displayed immediately (because it's held in the buffer). To force the output to > be displayed, use flush(): > > print "-#- executing: %s" % section, > sys.stdout.flush() > ...tests here... > > Hope this helps! > > --Hans Thanks a lot! This worked beautifully! From python at bdurham.com Wed May 21 10:32:08 2008 From: python at bdurham.com (python at bdurham.com) Date: Wed, 21 May 2008 10:32:08 -0400 Subject: Publish a program In-Reply-To: <48342434_2@news.tm.net.my> References: <4833f0ff_2@news.tm.net.my> <48342434_2@news.tm.net.my> Message-ID: <1211380328.14783.1254358753@webmail.messagingengine.com> > appreciate somebody to join and put new views on this project Send us a link to one of the sites with your code, eg. http://python.pastebin.com Malcolm From castironpi at gmail.com Fri May 16 18:36:47 2008 From: castironpi at gmail.com (castironpi) Date: Fri, 16 May 2008 15:36:47 -0700 (PDT) Subject: save dictionary for later use? References: <99403e9d-4c67-4e3f-a726-7bb02e72423a@m3g2000hsc.googlegroups.com> <9ec97b27-e4a8-40e0-b8b3-a2cdaeba448e@d77g2000hsb.googlegroups.com> <21eb068b-0c96-43f0-a71f-0bb1c2be6ec9@y38g2000hsy.googlegroups.com> Message-ID: On May 16, 5:19?pm, castironpi wrote: > On May 16, 4:29?pm, "bruno.desthuilli... at gmail.com" > > > > > > wrote: > > On 16 mai, 22:24, globalrev wrote: > > > > On 16 Maj, 21:22, jay graves wrote: > > > > > On May 16, 2:17 pm, globalrev wrote: > > > > > > i extract info from one file and put it into a dictionary. > > > > > i want to save that dictionary for later use, how do i do that? > > > > > might save a list of dictionaries or a list of classobjects too if > > > > > there is any difference. > > > > > use the 'pickle' module.http://docs.python.org/lib/module-pickle.html > > > > > ... > > > > Jay Graves > > > > pickle.dumps(mg) > > > pickle.load(mg) > > > > 'dict' object has no attribute 'readline' > > > dumps load(well i dont know but i get no complaint but running load > > > generates that error) > > > What about *READING THAT FUCKING MANUAL* ? > > >http://docs.python.org/lib/node316.html > > """ > > dump(obj, file[, protocol]) > > ? ? Write a pickled representation of obj to the open file object > > file. This is equivalent to Pickler(file, protocol).dump(obj). > > > ? ? If the protocol parameter is omitted, protocol 0 is used. If > > protocol is specified as a negative value or HIGHEST_PROTOCOL, the > > highest protocol version will be used. > > > ? ? Changed in version 2.3: Introduced the protocol parameter. > > > ? ? file must have a write() method that accepts a single string > > argument. It can thus be a file object opened for writing, a StringIO > > object, or any other custom object that meets this interface. > > > load(file) > > ? ? Read a string from the open file object file and interpret it as a > > pickle data stream, reconstructing and returning the original object > > hierarchy. This is equivalent to Unpickler(file).load(). > > > ? ? file must have two methods, a read() method that takes an integer > > argument, and a readline() method that requires no arguments. Both > > methods should return a string. Thus file can be a file object opened > > for reading, a StringIO object, or any other custom object that meets > > this interface. > > > ? ? This function automatically determines whether the data stream was > > written in binary mode or not. > > """ > > > Example use: > > > >>> d = dict(a=1, b=2) > > >>> f = open("mydict.dat", "w") > > >>> pickle.dump(d, f) > > >>> f.close() > > >>> f = open("mydict.dat") > > >>> d2 = pickle.load(f) > > >>> f.close() > > >>> d2 == d > > True > > >>> d2 > > {'a': 1, 'b': 2} > > > Now : it's not the first time - in a couple days - that you ask a > > question that you wouldn't have asked if you had taken a couple > > minutes doing the tutorial and/or reading the doc. This newsgroup is > > *very* tolerant (in most other places on usenet, you would have get a > > raw RTFM on the first question, and a PLONK on the second), but there > > are still limits, and as far as I'm concerned you're not far from > > them. So do yourself and the world a favour, read this:http://catb.org/~esr/faqs/smart-questions.html > > > and then this:http://docs.python.org/tut/tut.html > > > and next time someone points you to a specific module, have mercy and > > *read* the doc before posting. > > > As far as I'm concerned, I won't anwser any of your questions unless > > it's obvious that you have followed these advices (but then I'll be > > happy to help if I can).- Hide quoted text - > > > - Show quoted text - > > There is 'shelve'. ?It's just that you have to re-update each entry > when you modify, so it's just similarity you'd be saving.- Hide quoted text - > > - Show quoted text - Now a shelf of filenames could be valuable. From n00m at narod.ru Mon May 5 10:58:26 2008 From: n00m at narod.ru (n00m) Date: Mon, 5 May 2008 07:58:26 -0700 (PDT) Subject: How to pass a multiline arg to exec('some.exe arg')? References: <7b6965a2-193d-42cf-8fad-2ad97c8de27b@i76g2000hsf.googlegroups.com> <95445d33-218f-42de-9412-067229c20830@d45g2000hsc.googlegroups.com> Message-ID: <8f56fd78-05fa-481a-982e-feb03d66a52e@c65g2000hsa.googlegroups.com> it can be done like this: osql=popen2.popen2('osql -E -S(local) -dpubs -c"GO" -n - w800') osql[1].write(query+'\nGO\n') osql[1].close() res=osql[0].readlines() osql[0].close() res=join(res,'') btw, is it necessarily to close() osql[1] in order to get res? without close() the script seems is waiting for smth. I'd like to get "res" in a loop: write() read() write() read() ... is it possible? From pataphor at gmail.com Tue May 20 09:48:02 2008 From: pataphor at gmail.com (pataphor) Date: Tue, 20 May 2008 15:48:02 +0200 Subject: "indexed properties"... References: <7o7r245pb3kqk42odihmf95sifpbbv0rqp@4ax.com> <7sm234hp8u9ia850uaopn3amtq95jqbt5t@4ax.com> <20080519144803.14d3569a@hyperspace> <2la534p1h4g7lke3lq3tji06q6cm32v7b0@4ax.com> Message-ID: <20080520154802.4b5df647@hyperspace> On Tue, 20 May 2008 06:12:01 -0500 David C. Ullrich wrote: > Well, ok. Like I said, I never _took_ the position that it _should_ > be a list of lists, I just said I didn't see the advantage to using > a single list. I'm now thinking about a list of lists containing single element lists. def test(): n = 3 R = range(n) M = [[[i+j*n] for i in R] for j in R] for L in M: print L row2 = M[1] print print row2 col3 = [L[2] for L in M] print col3 col3[1][0]=9 print col3 print row2 print for L in M: print L if __name__=='__main__': test() The idea is to use a single element list as kind of storage facility. That enables me to copy a column, then change something in that column and make the change turn up in the matrix and even in a previously made copy of a row that shared the specific element. > Today's little joke: Long ago I would have solved > this by storing the data as a list of rows and _also_ > a list of columns, updating each one any time the > other changed. Just goes to show you things > could always be worse... Well have I ever ... I only thought about this last week and I actually thought it was a *good* idea. I only gave up on it because now I would have to keep track of how far the two views are out of sync, because some operation could use data that was modified by an other view. Zipstar transposition is very handy for syncing, but it is also very expensive. But probably not for you. > Expressing interest is a big mistake... How so? ;-) > Sometime soon a thread will appear titled something > like "indexed attributes" with a stripped-down but > functional example of what I have in mind for Matrix I can't wait! Keep up the good work. P. From rustompmody at gmail.com Mon May 19 06:52:25 2008 From: rustompmody at gmail.com (Rustom Mody) Date: Mon, 19 May 2008 16:22:25 +0530 Subject: pickle internals Message-ID: I am trying to understand pickle internals. This involves: -- the algorithm(s) used for traversal arbitrary structures -- the pickle format -- the use if any of introspection I'll be thankful for any pointers PS Should this question be put on some other list?/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Tue May 6 05:10:34 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 06 May 2008 11:10:34 +0200 Subject: read line References: <240aafd8-17b7-431a-a529-fdf617703093@c65g2000hsa.googlegroups.com> Message-ID: <68all5F2sj3e0U1@mid.uni-berlin.de> moustafa.elmihy at gmail.com wrote: > hi every body, > > I'm a new python user and I'm making a program to run useing Abaqus > and there is something I can't do, > > if i have a text file that has a line like this " 10 20 30 40 > 50" and I wana do the coding to put every number of these like 10 or > 20 in a separate variable .. any suggestions ?? Look up on the file-objects in the documentation, as well as string-methods such as split and the int-function. Diez From n00m at narod.ru Mon May 5 05:25:15 2008 From: n00m at narod.ru (n00m) Date: Mon, 5 May 2008 02:25:15 -0700 (PDT) Subject: How to pass a multiline arg to exec('some.exe arg')? Message-ID: <7b6965a2-193d-42cf-8fad-2ad97c8de27b@i76g2000hsf.googlegroups.com> os:windows ml = 'line1 \n line2 \n line3 \n' exec('some.exe "' + ml + '"') and some.exe get only 'line1'... From pydecker at gmail.com Mon May 12 10:40:26 2008 From: pydecker at gmail.com (Peter Decker) Date: Mon, 12 May 2008 09:40:26 -0500 Subject: Is there no single/uniform RDBMS access API module for Python ? In-Reply-To: <3de8e1f70805112345u672d8ec0ia1aaa10a55e1b048@mail.gmail.com> References: <3de8e1f70805112243u765fc507v32c5461be34d4077@mail.gmail.com> <4827E6B9.3080509@shopzeus.com> <3de8e1f70805112345u672d8ec0ia1aaa10a55e1b048@mail.gmail.com> Message-ID: On Mon, May 12, 2008 at 1:45 AM, Banibrata Dutta wrote: > > > Based on this URL http://wiki.python.org/moin/DatabaseInterfaces , is > it correct to conclude that there is no RDBMS agnostic, single/uniform DB > access API for Python ? > > > Something in the lines of JDBC for Java, DBD for Perl etc. ? > > > How is the RDBMS change handled for solutions which need to work with > different RDBMSs ?? > > > > > > > http://www.python.org/dev/peps/pep-0249/ > > > > That appears to be only an API specification. Are there any implementations > of that ? You might want to take a look at Dabo (http://dabodev.com). They have a backend-agnostic interface for working with different databases. I don't do database apps myself, so I can't comment on how well it works, but based on the comments of others on the Dabo email lists, it seems as though it works well enough. -- # p.d. From joe.p.cool at googlemail.com Thu May 8 17:10:57 2008 From: joe.p.cool at googlemail.com (Joe P. Cool) Date: Thu, 8 May 2008 14:10:57 -0700 (PDT) Subject: Python GUIs and custom controls Message-ID: <049d1607-c578-48dc-83f3-42cf562449b4@p25g2000hsf.googlegroups.com> So far I have a little experience with Tkinter and wxPython. I wonder which of the numerous Python GUI kits would be the best choice for a multi platform application that makes heavy use of custom controls, 3D views and the like? Thanks in advance for your hints and advice. Joe From gabriel.rossetti at arimaz.com Mon May 26 06:14:55 2008 From: gabriel.rossetti at arimaz.com (Gabriel Rossetti) Date: Mon, 26 May 2008 12:14:55 +0200 Subject: b64encode and unicode problem Message-ID: <483A8D9F.3080104@arimaz.com> Hello everyone, I am trying to encode a string using b4encode and I get the following error : >>> b64encode(u"Salut Pierre, comment ?a va?") Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.5/base64.py", line 53, in b64encode encoded = binascii.b2a_base64(s)[:-1] UnicodeEncodeError: 'ascii' codec can't encode character u'\xe7' in position 22: ordinal not in range(128) If I remove the "u" infront of the string, it works. The problem is that I in my program, the string is given to me un unicode/utf-8. I tried several things, but I still get it, How can I get it to work, anybody have any idea? Thanks, Gabriel From http Sun May 25 19:35:23 2008 From: http (Paul Rubin) Date: 25 May 2008 16:35:23 -0700 Subject: Performance of Python builtins References: Message-ID: <7xskw69cuc.fsf@ruckus.brouhaha.com> miller.paul.w at gmail.com writes: > Is there any place outside the actual C source for Python that has > information about the performance of Python's built-in operations? Really, just the source code and the general culture. It's not in the docs; that would be a pretty rare thing. > For example, I'd *expect* list.append to be O(1), and I hope that > list[i] is O(1), but I don't really know that for sure, since it > would depend a lot on the internal implementation. list[i] is O(1). list.append is amortized O(1) but on some calls can take much longer. Basically list.append preallocates some extra space for further appends but when you use up the extra space there is some copying. > I'm really only asking this for curiosity's sake --- more as a > reasonable, non-trollish version of the "Python is slow" post than > anything. :-) I've never really had any problems with the performance > of Python code that I couldn't solve by either changing my algorithm > or, if all else has truly failed, rewriting in C or Pyrex. "You can fix your Python program's performance problems by rewriting it in C" is not that convincing an answer to a concern that Python is slow ;-). From __peter__ at web.de Mon May 5 06:53:26 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 05 May 2008 12:53:26 +0200 Subject: How to pass a multiline arg to exec('some.exe arg')? References: <7b6965a2-193d-42cf-8fad-2ad97c8de27b@i76g2000hsf.googlegroups.com> Message-ID: n00m wrote: > os:windows > ml = 'line1 \n line2 \n line3 \n' > exec('some.exe "' + ml + '"') > > and some.exe get only 'line1'... My crystall ball says you want subprocess.call(["some.exe", ml]) exec is a python statement that executes python code. Peter From castironpi at gmail.com Tue May 13 10:23:01 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 13 May 2008 07:23:01 -0700 (PDT) Subject: I'm stuck in Python! References: <6c34f3a3-88fa-4519-b624-34a4589d2424@c65g2000hsa.googlegroups.com> Message-ID: <3b6ac749-be8a-4d7d-91eb-d357554c6a24@b1g2000hsg.googlegroups.com> On May 13, 9:01?am, castiro... at gmail.com wrote: > On May 13, 8:46?am, Sanoski wrote: > > > > > > > Any programming that helps you solve a problem is fun and > > recreational. At least, that's how I look at it. I suppose it really > > depends on why you're doing it, what your objective is, etc. But I'd > > say, why not? > > > Tron! That's one I haven't seen in awhile. I'll have to take a mental > > note to rent the movie again someday. I always thought a game based on > > the movie hackers would be cool. Actually not based on the movie > > itself, but on that 3D computer world they kept breaking into. Ah man, > > it's so funny looking back on that film. Gibson, that's what they > > called it. It was like a 3D database. That in itself wouldn't make a > > very good game, but I suppose one could easily be created around that > > idea. Perhaps it could be combined with Lawnmower-man. You're somehow > > trapped in this 80's looking 3D world that has access to all the > > world's information. More stuff could be thrown in to make it more > > interesting. And of course, there would have to be hidden references > > or parodies to whatever movies inspired it. > > > Good luck with your project > > > Sincerely, > > Joshua > > > On May 13, 9:02?am, castiro... at gmail.com wrote: > > > > Hi all. > > > > I am trying to write to the Python newsgroup. ?I doubt (aha, but > > > doubt) that I have come to the right place. ?(Incoming "this"!) ?Is > > > this the Python newsgroup? ?I heard it was called comp.lang.python. > > > Now to repeat the subject line. ?I'm stuck in Python. > > > > Now that was fun. ?I will also try to enumerate simple screen savers > > > (graphicals, graphiclizers). ?It may be profitable on some non-bank- > > > breaking scale to compile the results. ?Shall I proceed? ?The risk is > > > "overunity", such that one person can't be at liberty to live, which > > > in some technical political arenas would be an "anarchy", but there > > > are sufficiently many of those that I will too. > > > > Does anyone want such a list, or if not, is it at least fun and > > > recreational to make it? ?The dollar would come along the lines of > > > PowerPoint (name (tm)), so it may be free to do it, very entertaining, > > > and peaceable. ?(As the above would show, you would be free to > > > approach me to -buy-; I won't oversell.) ?I like programming. ?(And is > > > Guido getting his fair share? ?I am prepared to share with him.) > > > Check in his name. > > > > I want to try to ally with other programmers and make cool games, like > > > Tron, that one party can make games for on a console, such as live > > > obstacles, incl. tear-down, and certain people have to play from time > > > to time. ?But you can't charge to do it, so it's a guaranteed game. > > > (That in virtue of that I'm typing.) ?Advantages include microspacing > > > of time. ?Very summer. > > > > Resemblances would include Dungeons & Dragons with multi-host, or > > > multi-ref small-shooter sport-likers. ?The real-time is definitely > > > attractive (duh). ?As for voice, it's not clear it's the most > > > entertaining, but I just don't have a mic. > > > > However, forseeing, I return with sailing, but that's in 3-space and > > > not even in code, as though we'd construct the Royal Navy and battle. > > > But I think we can keep it well. > > > > Thing is, someone has to play it to keep a synch (keep from falling), > > > and tap-outs would have to live. > > > > Side note: In political theory, this is known as the problem of > > > nominating a successor. ?Would it stay afloat, even for long enough to > > > make it worth the negatives, yes which do include tear-down and fall, > > > invasion of privacy, and rights infrigement? > > > > I code in Python (get the callbacks), but configurable servers could > > > spread the work out, using relays to put each person on each's own > > > turf to be a ref. ?If you feed the roles, it could get really fun, and > > > c-l-py is the appropriate place to start such a thing, both and ask if > > > it's been done before.- Hide quoted text - > > > - Show quoted text - > > My bot just tries to take control and lead. ?(The bot that I'm > writing!) ?However, it is amusingly unsuccessful. ?We see in lines, so > the game would be pretty primitive, but I'm not sure that everything > else isn't merely too exciting, such that Tron wouldn't be monkey-in- > the-middle, or king of the hill, of fun. ?I'm just not on a hill, so > someone else would have to try to play it with me online!- Hide quoted text - > > - Show quoted text - But, since, I'm just Tron, I will try short and repeated attempts to sophisticate, at quantifiable levels, as I would be more than one. From dullrich at sprynet.com Tue May 20 11:40:17 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Tue, 20 May 2008 10:40:17 -0500 Subject: "indexed properties"... References: <7o7r245pb3kqk42odihmf95sifpbbv0rqp@4ax.com> <7sm234hp8u9ia850uaopn3amtq95jqbt5t@4ax.com> <20080519144803.14d3569a@hyperspace> <2la534p1h4g7lke3lq3tji06q6cm32v7b0@4ax.com> <20080520154802.4b5df647@hyperspace> Message-ID: In article <20080520154802.4b5df647 at hyperspace>, pataphor wrote: > On Tue, 20 May 2008 06:12:01 -0500 > David C. Ullrich wrote: > > > Well, ok. Like I said, I never _took_ the position that it _should_ > > be a list of lists, I just said I didn't see the advantage to using > > a single list. > > I'm now thinking about a list of lists containing single element lists. > > def test(): > n = 3 > R = range(n) > M = [[[i+j*n] for i in R] for j in R] > for L in M: > print L > row2 = M[1] > print > print row2 > col3 = [L[2] for L in M] > print col3 > col3[1][0]=9 > > print col3 > print row2 > print > for L in M: > print L > > if __name__=='__main__': > test() > > The idea is to use a single element list as kind of storage facility. > That enables me to copy a column, then change something in that column > and make the change turn up in the matrix and even in a previously made > copy of a row that shared the specific element. > > > Today's little joke: Long ago I would have solved > > this by storing the data as a list of rows and _also_ > > a list of columns, updating each one any time the > > other changed. Just goes to show you things > > could always be worse... > > Well have I ever ... I only thought about this last week and I > actually thought it was a *good* idea. Sorry. If you really want to do this you could keep things in sync automatically by writing the appropriate __setitem__ and resolving never to modify the data except through that... def whatever.__setitem__(self, (row,col), value): self.rows[row][col] = value self.cols[col][row] = value Seems to me like an, um, "untenable" waste of space. And you'd need to be certain to never set anything except through self[row,col]; as far as I can see anything like setrow() would be a loop "for col in range(width): self[row,col] =". Hmm. You could keep the data in some object that encapsulates the two double lists and use some fancy feature (__getattribute__?) to make certain that the only possible access to the data was through __getitem__... > I only gave up on it because > now I would have to keep track of how far the two views are out of > sync, because some operation could use data that was modified by an > other view. Zipstar transposition is very handy for syncing, but it is > also very expensive. But probably not for you. > > > Expressing interest is a big mistake... > > How so? ;-) > > > Sometime soon a thread will appear titled something > > like "indexed attributes" with a stripped-down but > > functional example of what I have in mind for Matrix > > I can't wait! Keep up the good work. > > P. -- David C. Ullrich From castironpi at gmail.com Tue May 13 11:35:53 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 13 May 2008 08:35:53 -0700 (PDT) Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <2b66a86e-5a05-4262-b3c9-4703b0ae3372@d1g2000hsg.googlegroups.com> <5b0e3f70-afde-4480-8713-e7113b1250d7@x35g2000hsb.googlegroups.com> <1f537717-00d0-48ee-99b6-7125b96a6133@t12g2000prg.googlegroups.com> <68t4o0F2vaoncU1@mid.uni-berlin.de> <2a32179a-9439-449c-bd07-fff6a4075aee@s50g2000hsb.googlegroups.com> <7ee5dffd-df8f-46f0-bd78-c81ac0418a9a@d77g2000hsb.googlegroups.com> <65ef773e-a1c3-4adb-a18b-e8b8451efe5e@b5g2000pri.googlegroups.com> Message-ID: <7803a03b-c626-4573-b859-6611229cb622@a70g2000hsh.googlegroups.com> On May 13, 10:24?am, Dave Parker wrote: > > ?The "Flaming Thunder" looks promising, but without being free > > software, it's unlikely it will create a large developer community, > > specially considering both free general purpose and scientific > > programming languages. > > Perhaps. ?Flaming Thunder is only $19.95 per year for an individual > (and even less per individual for site licenses), which is less than > the cost of just one book on Python. > > I think that many people will find that Flaming Thunder is easier to > use and understand than Python -- so for many people the amount of > time they save will be worth more than the cost of Flaming Thunder > (unless, of course, their time is worth $0). > > Also, several users have rewritten their Python programs in Flaming > Thunder, and found that Flaming Thunder was 5 to 10 times faster > (Flaming Thunder compiles to native executables). ?So again, since > many people value their time at more than $0, I think that many people > will find that Flaming Thunder is worth $19.95 per year. > > Plus, me getting paid to work on Flaming Thunder is far more > motivating than me not getting paid to work on Python. ?This weekend, > Python users will still be debating how to fix awkwardnesses in the > languages (such as FOR loops where you're just counting the loops and > not referencing the loop variable) -- but Flaming Thunder users will > be getting work done using the REPEAT n TIMES constructs that I'll be > implementing. > > Python has been around about 15 years, yet still has those > awkwardnesses. ?Flaming Thunder has been out less than 6 months and > those awkwardnesses are already getting fixed. ?The difference: I > can't afford to ignore users. > > But the future is one of the hardest things to predict, so we'll see. > > On May 13, 8:34?am, hdante wrote: > > > > > On May 13, 10:58?am, Paul McGuire wrote: > > > > On May 13, 8:32?am, Dave Parker wrote: > > > > > > Don't let yourself be irritated by castironpi > > > > > I'm not the sort to get irritated by anyone. ?There is value in all > > > > interaction. > > > > Not this interaction, I'm afraid. ?What irritates *me* about > > > castironpi is that he uses a chatterbot to clutter up the threads > > > here. ?If you go back to his postings from a year ago (and selected > > > ones since), his comments are coherent and sensible. ?These rambling > > > stream-of-consciousness rants about t.v.'s and coffee are (I guess) > > > his idea of a joke. ?But they are certainly not worth your time in > > > trying to respond to them. > > > > -- Paul > > > ?I don't think castironpi so annoying that I should filter its > > messages. It would be enough if he were better tuned. He is much > > smarter than the emacs shrink, for example. :-P > > > ?The "Flaming Thunder" looks promising, but without being free > > software, it's unlikely it will create a large developer community, > > specially considering both free general purpose and scientific > > programming languages.- Hide quoted text - > > > - Show quoted text -- Hide quoted text - > > - Show quoted text - Flaming Thunder, the lightning one, looked like [ 255, 210, 255 ], but the next thing I thought was -40 on green. From bborcic at gmail.com Tue May 6 06:43:12 2008 From: bborcic at gmail.com (Boris Borcic) Date: Tue, 06 May 2008 12:43:12 +0200 Subject: parameters to lambda's executed at run time. In-Reply-To: References: Message-ID: <48203672$1_4@news.bluewin.ch> One way : >>> from functools import partial >>> def func(item) : print item >>> llist = [partial(func,item) for item in range(5)] >>> for thing in llist : thing() 0 1 2 3 4 wyleu wrote: > I'm trying to supply parameters to a function that is called at a > later time as in the code below: > > llist = [] > > for item in range(5): > llist.append(lambda: func(item)) > > def func(item): > print item > > for thing in llist: > thing() > > which produces the result > > IDLE 1.2.1 >>>> ================================ RESTART ================================ >>>> > at 0xb716356c> > at 0xb71635a4> > at 0xb71635dc> > at 0xb7163614> > at 0xb716364c> >>>> ================================ RESTART ================================ >>>> > 4 > 4 > 4 > 4 > 4 > > How can one allocate a different parameter to each instance of the > function rather than all of them getting the final value of the loop? > From mishok13 at gmail.com Tue May 27 11:13:02 2008 From: mishok13 at gmail.com (Andrii V. Mishkovskyi) Date: Tue, 27 May 2008 18:13:02 +0300 Subject: decorators when? In-Reply-To: References: <3m0o34hbb0c6rpr6ec0qh3hlkaagt8pfi5@4ax.com> <6a2edeF356g4eU1@mid.uni-berlin.de> Message-ID: <192840a00805270813i3bfc6fccja42034f87eac5634@mail.gmail.com> 2008/5/27 David C. Ullrich : > On Tue, 27 May 2008 14:50:23 +0200, "Diez B. Roggisch" > wrote: > >>David C. Ullrich wrote: >> >>> What version added decorators (using the >>> @decorator syntax)? >>> >>> (Is there a general way I could have found out the answer myself?) >>> >>> Is there a somthing such that "from __future__ import something" >>> will make decorators work in 2.5.2? >> >>They do work. They were introduced in python2.4 > > That's more or less what I thought, but... > > Oh. Never mind the details, let's just say that having 2.3 and > 2.5 installed on the same machine can lead to confusion > about exactly which one you're running a script under. > Duh. > > Sorry. Thanks. I don't suppose that decorators are available > from __future__ somehow in 2.3? > Nope, they don't. Anyway, decorators are just a syntactic sugar, why would you need this feature in 2.3? > >>Diez > > David C. Ullrich > -- > http://mail.python.org/mailman/listinfo/python-list > -- Wbr, Andrii Mishkovskyi. He's got a heart of a little child, and he keeps it in a jar on his desk. From zerty.david at gmail.com Thu May 8 21:47:59 2008 From: zerty.david at gmail.com (David Anderson) Date: Thu, 8 May 2008 22:47:59 -0300 Subject: Weird bug with an integer In-Reply-To: <5dc598e30805081844n834a776v812be9afd61e496@mail.gmail.com> References: <5dc598e30805081844n834a776v812be9afd61e496@mail.gmail.com> Message-ID: <5dc598e30805081847n5e2ed2a5jeb8e8da6263dd11c@mail.gmail.com> Ps: When I go to shell and type:rowN = int(0) rows = [["1223", "11/23/08", "Purchase", "To be shipped", "Gallery Name", "Art Title[22 of 300]", "$10,000"],#1st row ["1223", "11/23/08", "Purchase", "To be shipped", "Gallery Name", "Art Title[22 of 300]", "$10,000"],#2nd row ["1223", "11/23/08", "Purchase", "To be shipped", "Gallery Name", "Art Title[22 of 300]", "$10,000"],#etc, obviouslly these info will be fetched from the db ["1223", "11/23/08", "Purchase", "To be shipped", "Gallery Name", "Art Title[22 of 300]", "$10,000"] ] for row in rows: colN = int(0) for col in row: print str(colN) + "," + str(rowN) + " - " + col It works and print everything correctly Oo On Thu, May 8, 2008 at 10:44 PM, David Anderson wrote: > Look this slice of code: > > rowN = int(0) > for row in rows: > success = self.resultGrid.AppendRows(); > colN = int(0) > for col in row: > self.resultGrid.SetReadOnly(self.resultGrid.GetNumberRows() > - 1,colN,isReadOnly = True) > print rowN > self.resultGrid.SetCellValue(int(rowN),int(colN),col) > > I am getting this output: > 0 > 0 > 0 > 0 > 0 > 0 > 0 > (1,) > Traceback (most recent call last): > in populateGrid > self.resultGrid.SetCellValue(int(rowN),int(colN),col) > TypeError: int() argument must be a string or a number, not 'tuple' > > > Why is this happening? > -------------- next part -------------- An HTML attachment was scrubbed... URL: From upton at virginia.edu Fri May 16 14:54:31 2008 From: upton at virginia.edu (Dan Upton) Date: Fri, 16 May 2008 14:54:31 -0400 Subject: morning in Python In-Reply-To: <28kXj.142759$Er2.39732@bignews6.bellsouth.net> References: <409ea9f1-9774-4bf2-abac-2daf997bc97f@c65g2000hsa.googlegroups.com> <19286799-53b1-4ba9-bb16-e3f963da7dc6@m3g2000hsc.googlegroups.com> <28kXj.142759$Er2.39732@bignews6.bellsouth.net> Message-ID: <5504f9ac0805161154k1fec9250y9763e6d6c31715d@mail.gmail.com> On Fri, May 16, 2008 at 2:12 PM, inhahe wrote: > > "George Sakkis" wrote in message > news:19286799-53b1-4ba9-bb16-e3f963da7dc6 at m3g2000hsc.googlegroups.com... > On May 16, 11:58 am, "inhahe" wrote: >> I'm not an expert in this but what does it mean to emphasize state? It >> seems the opposite of that would be a) functional programming, and b) >> passing parameters instead of using global or relatively local variables. >> And maybe c) coroutines (generators as implemented in Python), although >> perhaps coroutines could be said to emphasize state inasmuch as they go >> out >> of their way to capture, objectify and reuse it (Stackless' microthreads, >> even moreso). And Python seems to be well-noted for implementing some >> functional programming methodology, and as for passing parameters it's >> just >> as object-oriented as the rest of them. >> >> But as I said, I'm not an expert, so let me know if I've gone astray.. >> >> > I have a proposition to ask you all: Python emphasizes state. Is it >> > true? > > Please don't feed the bots. > > -- > > > I figured the question was interesting enough to warrant discussion whether > it was a bot or not. But i'm not an avid forum user, so maybe I'm wrong. > > Also, if it's a bot I'm floored and the man who wrote it could probably > solve cancer and world hunger with five lines of asm. > Yeah... when he/she/it first appeared the replies were at least mostly lucid, if not necessarily helpful, and spawned a few interesting discussions. Recently it's gone downhill... Could be some sort of bot that was trying to learn 'speech' patterns and it overloaded its database. (I've seen that happen on at least one chatbot...) From alex.gaynor at gmail.com Tue May 13 20:06:57 2008 From: alex.gaynor at gmail.com (alex.gaynor at gmail.com) Date: Tue, 13 May 2008 17:06:57 -0700 (PDT) Subject: list.__len__() or len(list) References: Message-ID: On May 13, 6:57?pm, Nikhil wrote: > which one is better? and why? > > __len__() is a built-in function of the list object and is updated along > with the list object elements and will be useful incase the list is very > huge. > > len() is an external method again, which may require the processing > cycles again. > > Is it right? len() is the correct way to do it, methods that begin with __ are meant to be more internal. From nick at craig-wood.com Mon May 19 06:30:03 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 19 May 2008 05:30:03 -0500 Subject: Get all the instances of one class References: <29f39184-2daa-49fc-a7af-7f869fd2d688@h1g2000prh.googlegroups.com> <2C2F5120-5EE5-4F04-9A8F-F37DA85FCD9E@comhem.se> Message-ID: Matt Nordhoff wrote: > Tommy Nordgren wrote: > > class MyClass : a_base_class > > memberlist=[] > > > > # Insert object in memberlist when created; > > # note: objects won't be garbage collected until removed from memberlist. > > Just to say, if you wanted to go about it that way, you could avoid the > garbage collection problem by using weakrefs: > > Eg... from weakref import WeakKeyDictionary class Test(object): _instances = WeakKeyDictionary() def __init__(self): self._instances[self] = True # your normal init stuff here @classmethod def instances(cls): return cls._instances.keys() print Test.instances() a = Test() b = Test() print Test.instances() del a print Test.instances() del b print Test.instances() .... Which prints [] [<__main__.Test object at 0xb7d4eb6c>, <__main__.Test object at 0xb7d4eb4c>] [<__main__.Test object at 0xb7d4eb6c>] [] -- Nick Craig-Wood -- http://www.craig-wood.com/nick From dave.g1234 at gmail.com Fri May 16 18:05:59 2008 From: dave.g1234 at gmail.com (dave.g1234 at gmail.com) Date: Fri, 16 May 2008 15:05:59 -0700 (PDT) Subject: namespaces and eval References: <31750f1d-910b-4fcc-90c0-0df9634f2c73@l28g2000prd.googlegroups.com> Message-ID: <7268f446-17b8-41bb-9d8e-e828f1e74053@c19g2000prf.googlegroups.com> On May 16, 2:47 pm, "bruno.desthuilli... at gmail.com" wrote: > On 16 mai, 23:23, dave.g1... at gmail.com wrote: > > > Thanks for the responses. I'm well aware that the function can be > > passed in the parameters, passing in the functino as an arg defeats > > the purpose of what I'm going after. > > Why so ? > > @ Arnaud - Nice. I'm not sure what the performance of mine vs. yours, > > but a perfunctory glance looks like we're doing the close to the same > > thing. Maybe one advanage to doing it wrap(x).foo().... is that you > > can pass in other parameters to foo. > > I may be wrong (if so please pardon my lack of intelligence and/or > provide a couple use case), but it looks like you're trying to > reinvent partial application. > > from functools import partial > def foo(x, y): > return x + y > > pfoo = partial(foo, 2) > print pfoo(42) > > Don't know if this helps... Ok, so that solves the issue of the aforementioned compose function. We could do compose( partialfoo,....) ) etc (although I might say I prefer wrap(x).foo(23).foo(16 ..etc ) The original idea was to provide wrapper around an object that lets you call abritrary functions on that object with it as a parameter - i.e., as if it were a method in a class. The partial function was only a component of the code I posted earlier. Or am I missing something you're saying? best dave From matthieu.brucher at gmail.com Wed May 21 17:17:12 2008 From: matthieu.brucher at gmail.com (Matthieu Brucher) Date: Wed, 21 May 2008 23:17:12 +0200 Subject: Bug in floating-point addition: is anyone else seeing this? In-Reply-To: <8187c3b6-a772-456f-a54f-0af7babb353e@w34g2000prm.googlegroups.com> References: <8187c3b6-a772-456f-a54f-0af7babb353e@w34g2000prm.googlegroups.com> Message-ID: 2008/5/21 Dave Parker : > On May 21, 2:44 pm, "Jerry Hill" wrote: > > > My understand is no, not if you're using IEEE floating point. > > Yes, that would explain it. I assumed that Python automatically > switched from hardware floating point to multi-precision floating > point so that the user is guaranteed to always get correctly rounded > results for +, -, *, and /, like Flaming Thunder gives. Correct > rounding and accurate results are fairly crucial to mathematical and > scientific programming, in my opinion. > -- > http://mail.python.org/mailman/listinfo/python-list > That's why there is the Decimal module. That's why the IEEE standard exists as well, because it is not possible to always use what you call multi-precision floating point with decent speed. That's why numerical analysis exists. Matthieu -- French PhD student Website : http://matthieu-brucher.developpez.com/ Blogs : http://matt.eifelle.com and http://blog.developpez.com/?blog=92 LinkedIn : http://www.linkedin.com/in/matthieubrucher -------------- next part -------------- An HTML attachment was scrubbed... URL: From bruno.desthuilliers at gmail.com Mon May 19 16:46:26 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Mon, 19 May 2008 13:46:26 -0700 (PDT) Subject: Using Python for programming algorithms References: <98fa5fa3-45ae-4df1-9fd3-1a227641244f@p25g2000hsf.googlegroups.com> <48314dd0$0$32138$426a34cc@news.free.fr> Message-ID: <92857241-ef7c-482f-a7cb-8ee81edd8317@e53g2000hsa.googlegroups.com> On 19 mai, 17:53, Henrique Dante de Almeida wrote: (snip) > Yes, I was actually referring to statically typed JIT-compiled > languages. Sorry about that, blame the beers that entered my digestive > system that night. :-P for beer in beers: if beer.entered_henrique_digestive_system_last_night: beer.blame() !-) From s0suk3 at gmail.com Mon May 19 02:08:11 2008 From: s0suk3 at gmail.com (s0suk3 at gmail.com) Date: Sun, 18 May 2008 23:08:11 -0700 (PDT) Subject: How do *you* use Python in non-GUI work? References: <20080518182022.990193bd.johnjsal@NOSPAMgmail.com> <6fb308f2-a5be-4641-aa04-561b1782c6bb@z72g2000hsb.googlegroups.com> <20080518202516.e858910c.johnjsal@NOSPAMgmail.com> Message-ID: <3b0ba35b-c2b9-4ab2-8e7c-fecebce465c2@d77g2000hsb.googlegroups.com> On May 18, 7:25 pm, John Salerno wrote: > On Sun, 18 May 2008 16:17:55 -0700 (PDT) > > Mensanator wrote: > > I see no need for GUI in any of these applications. > > Yeah, I try to find little projects to write in Python that don't involve a GUI. It's quicker, for one thing, and I also find that there is much more of a focus on the actual problem rather than wasting time trying to get a button positioned just right. :) > > Even back when I was using Windows 3.1 and 95, I enjoyed doing stuff in DOS because it made me feel like I was actually getting work done. :) I do mostly Internet protocol server/proxy-side applications. One of the fun things about those kinds of programs is that you get away from the whole "user interface design" concept, because you normally don't have to do any kind of user interface (neither command-line-based, GUI- based, web-based, nor anything), since you're not designing something to serve an end user, but to work as a lonely daemon and serve some kind of Internet service. So I think that'd be a good alternative for you. Every now and then, however, I do build some interface (mostly GUI), such as a monitor, notification mechanism, etc. But I never feel like I'm losing focus on the actual problem; maybe because I develop the core program first and the think about a possible and optional interface. Maybe a good suggestion is to put the GUI stuff on another module or package, and make interface functions or methods to handle the needed GUI controls, so that the GUI stuff shows up as little as possible in the core part of the program. From nagle at animats.com Sun May 25 21:46:27 2008 From: nagle at animats.com (John Nagle) Date: Sun, 25 May 2008 18:46:27 -0700 Subject: Getting a set of lambda functions In-Reply-To: References: Message-ID: <483a1319$0$34516$742ec2ed@news.sonic.net> Martin Manns wrote: > Hi, > > I try to get a set of lambda functions that allows me executing each > function code exactly once. Therefore, I would like to modify the set > function to compare the func_code properties (or the lambda > functions to use this property for comparison). > > (The reason is that the real function list is quite large (> 1E5), there > are only few functions with non-equal code and the order of execution > is not important.) > > How can I achieve this? > >>>> func_strings=['x', 'x+1', 'x+2', 'x'] >>>> funclist = [eval('lambda x:' + func) for func in func_strings] What are you actually trying to do, anyway? What's the application? You probably don't want to use "eval" that way. If you want function objects out, use "compile". John Nagle From goldnery at gmail.com Fri May 23 11:45:11 2008 From: goldnery at gmail.com (Gandalf) Date: Fri, 23 May 2008 08:45:11 -0700 (PDT) Subject: Another Question Message-ID: How can i bind function that handle the mouse clicking window X event or clicking alt+F4 thanks From bockman at virgilio.it Mon May 5 13:22:32 2008 From: bockman at virgilio.it (Francesco Bochicchio) Date: Mon, 05 May 2008 19:22:32 +0200 Subject: config files in python References: <44f9662d-a88d-418c-a11d-b7b472b01fc3@j33g2000pri.googlegroups.com> Message-ID: On Mon, 05 May 2008 00:35:51 -0700, sandipm wrote: > Hi, > In my application, I have some configurable information which is used > by different processes. currently I have stored configration in a > conf.py file as name=value pairs, and I am importing conf.py file to > use this variable. it works well > > import conf > print conf.SomeVariable > > but if I need to change some configuration parameteres, it would need > me to restart processes. > > I want to store this data in some conf file (txt) and would like to > use it same way as I am using these variables as defined in py > files. > > one solution I can think of is writing data as a dictionary into conf > file. and then by reading data, apply eval on that data. and update > local dict? but this is not a good solution.... > > any pointers? > > Sandip The 'simple but relatively dangerous way', already suggested, is to reload() the module. A safer way - but requiring more work - could be to build something around the Configparser module in the standard library ... Ciao ----- FB From castironpi at gmail.com Fri May 16 11:43:52 2008 From: castironpi at gmail.com (castironpi) Date: Fri, 16 May 2008 08:43:52 -0700 (PDT) Subject: Pyparsing Question References: Message-ID: <90c5b91a-06a5-4e2e-b166-dda83e899366@m36g2000hse.googlegroups.com> On May 16, 6:43?am, Ant wrote: > Hi all, > > I have a question on PyParsing. I am trying to create a parser for a > hierarchical todo list format, but have hit a stumbling block. I have > parsers for the header of the list (title and description), and the body > (recursive descent on todo items). > > Individually they are working fine, combined they throw an exception. > The code follows: > > #!/usr/bin/python > # parser.py > import pyparsing as pp > > def grammar(): > ? ? ?underline = pp.Word("=").suppress() > ? ? ?dotnum = pp.Combine(pp.Word(pp.nums) + ".") > ? ? ?textline = pp.Combine(pp.Group(pp.Word(pp.alphas, pp.printables) + > pp.restOfLine)) > ? ? ?number = pp.Group(pp.OneOrMore(dotnum)) > > ? ? ?headtitle = textline > ? ? ?headdescription = pp.ZeroOrMore(textline) > ? ? ?head = pp.Group(headtitle + underline + headdescription) > > ? ? ?taskname = pp.OneOrMore(dotnum) + textline > ? ? ?task = pp.Forward() > ? ? ?subtask = pp.Group(dotnum + task) > ? ? ?task << (taskname + pp.ZeroOrMore(subtask)) > ? ? ?maintask = pp.Group(pp.LineStart() + task) > > ? ? ?parser = pp.OneOrMore(maintask) > > ? ? ?return head, parser > > text = """ > > My Title > ======== > > Text on a longer line of several words. > More test > and more. > > """ > > text2 = """ > > 1. Task 1 > ? ? ?1.1. Subtask > ? ? ? ? ?1.1.1. More tasks. > ? ? ?1.2. Another subtask > 2. Task 2 > ? ? ?2.1. Subtask again""" > > head, parser = grammar() > > print head.parseString(text) > print parser.parseString(text2) > > comb = head + pp.OneOrMore(pp.LineStart() + pp.restOfLine) + parser > print comb.parseString(text + text2) > > #=================================================================== > > Now the first two print statements output the parse tree as I would > expect, but the combined parser fails with an exception: > > Traceback (most recent call last): > ? ?File "parser.py", line 50, in ? > ? ? ?print comb.parseString(text + text2) > . > . [Stacktrace snipped] > . > ? ? ?raise exc > pyparsing.ParseException: Expected start of line (at char 81), (line:9, > col:1) > > Any help appreciated! > > Cheers, > > -- > Ant. I hold that the + operator should be overloaded for strings to include newlines. Python 3.0 print has parentheses around it; wouldn't it make sense to take them out? From michele.simionato at gmail.com Thu May 29 07:19:12 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Thu, 29 May 2008 04:19:12 -0700 (PDT) Subject: cmd.Cmd bug or at least docu-bug References: <6a7b72F3467inU1@mid.uni-berlin.de> Message-ID: <78925615-83f4-4197-a922-6e34287774e9@34g2000hsf.googlegroups.com> On May 29, 11:26?am, "Diez B. Roggisch" wrote: > Hi, > > I'm fiddling around with module cmd. I tried to pass my own streams as > replacements for stdin and stdout. However, stdin wasn't working. After a > look into the sourcecode I discovered that there is an class-variable > called > > use_rawinput > > that prevents using the passed stdin. I then read the docs again - and found > it described. However, I think it should be mentioned on the first page > where the constructor is described that without setting use_rawinput to > False, stdin will be ignored. > > Or even better either make use_rawinput set to false in case stdin is passed > anything but None or at least make it a keyword argument. > > Any thoughts about this? > > Diez I run into the same issue and I solved it by using a custom subclass of Cmd, but I agree that the cmd module could be improved. I even wrote a cmd2 module that I should publish one day or another. +1 to submit a bug report. Michele Simionato From upton at virginia.edu Thu May 22 00:59:44 2008 From: upton at virginia.edu (Dan Upton) Date: Thu, 22 May 2008 00:59:44 -0400 Subject: related to python In-Reply-To: References: Message-ID: <5504f9ac0805212159u174437ccs4409d83381c6a804@mail.gmail.com> This looks like a homework assignment, but... On Wed, May 21, 2008 at 10:34 PM, salil_reeves wrote: > develop a function called standardise_phrase to convert > the user's input to a standard form for subsequent processing. This > involves: > 1. removing all inter-word punctuation, which for our purposes is > assumed to > consist only of commas (`,'), full stops (`.'), exclamation marks > (`!') or > question marks (`?'); I think a question similar to this was answered on the list today or yesterday, for removing spaces and hyphens. > 2. stripping away any leading and trailing blank spaces; and If your solution for part 1 can't be extended to cover this... you might have to find another way to "strip" the the spaces ;) > 3. replacing words in the user's input with ELIZA's preferred > vocabulary. Assuming you have some sort of dictionary mapping words to ELIZA words, you should be able to iterate through all of the words in the input and, using that dictionary, swap the key for the value in your input string. There, I think those are sufficiently vague as to not do your homework for you, but maybe get you started... From daveparker at flamingthunder.com Wed May 21 11:34:15 2008 From: daveparker at flamingthunder.com (Dave Parker) Date: Wed, 21 May 2008 08:34:15 -0700 (PDT) Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> Message-ID: On May 20, 7:05?pm, Collin wrote: > Personally, FT is a bit meh to me. The way you issue your statements I > always think something is wrong, mainly because when I want to define, > say, x, in python I'd go: > > x = "whatever" > > Instantly noting that I defined x. While in Flaming Thunder I'd have to > type: > > Set x to "whatever" > > It just feels wrong. Actually, it felt wrong to me when I first started working on Flaming Thunder because I've been programming for decades and have had all of the programming idioms burned into my brain. But after getting input from children and teachers, etc, it started feeling right. For example, consider the two statements: x = 8 x = 10 The reaction from most math teachers (and kids) was "one of those is wrong because x can't equal 2 different things at the same time". Many computer languages conflate "equality" with "assignment" and then go to even more confusing measures to disambiguate them (such as using == for equality, or := for assignment). Plus, symbols are more confusing for people to learn about than words. There are lots of people who are fluent in English, but dislike math. So, I opted for a simple, unambiguous, non-mathematical way of expressing "assignment" which makes sense even to the non- mathematically inclined: Set x to 8. That way, = can be reserved unambiguously and unconfusingly for the mathematical notion of "equality" -- because it's in their math classes that people learn what = means: Set QuadraticEquation to a*x^2 + b*x + c = 0. From bruno.42.desthuilliers at websiteburo.invalid Tue May 20 03:17:02 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 20 May 2008 09:17:02 +0200 Subject: conventions/requirements for 'is' vs '==', 'not vs '!=', etc In-Reply-To: <3629843a-ebcb-4f15-82f1-899500f7b91f@t54g2000hsg.googlegroups.com> References: <4dc24f2e-04f5-4ad6-b021-f416ef5c7415@z72g2000hsb.googlegroups.com> <8ebd28f1-887f-45c9-a35f-af9023b062ea@u12g2000prd.googlegroups.com> <3629843a-ebcb-4f15-82f1-899500f7b91f@t54g2000hsg.googlegroups.com> Message-ID: <48327ae9$0$15299$426a74cc@news.free.fr> notnorwegian at yahoo.se a ?crit : > i am confused. > > x=5 > y=5 > > x==y -> True > x is y -> True > > shouldnt x is y return False since they shouldnt(dont?) point to the > same place in memory, they just store an equal value? Python's "variable" do not "store values", they are name to object bindings. x = 5 is a shortand for globals()['x'] = int(5), which means "create an int instance with value 5 and bind it to the name 'x' in the global namespace'. wrt/ the identity test yielding true, it's the result of a CPython specific optimisation for small integer objects, that are cached and reused. Since Python integers are immutable, they can safely be shared. Now since it's an implementation specific thing, you should by no mean rely on it. From __peter__ at web.de Fri May 23 04:48:16 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 23 May 2008 10:48:16 +0200 Subject: KeyError in pickle References: <6eb38a0e-1ecc-46f7-92b7-1dd816efe206@8g2000hse.googlegroups.com> Message-ID: christof wrote: > I am using pickle/unpickle to let my program save its documents to > disk. While this it worked stable for a long time, one of my users now > complained, that he had a file which can't be loaded. > > The traceback is: > > File "pickle.pyo", line 1374, in loads > File "pickle.pyo", line 858, in load > KeyError: 'A' > > > Does anybody know this problem. How this can happen and how can I > avoid it? Is this reproducible? How? If not I would guess that the file is corrupted. Peter From afrobeard at gmail.com Tue May 13 18:39:25 2008 From: afrobeard at gmail.com (afrobeard) Date: Tue, 13 May 2008 15:39:25 -0700 (PDT) Subject: What is self.file = file for? References: Message-ID: If you are familiar to C++ or a similar language, the concept of the this pointer might not be alien to you. self in this context is basically a reference to the class itself. Hence self.file is creating a class member and setting to the input from file. As Gary pointed out, during initialization, only the latter parameter i.e. file is being passed to __init__ You can get a brief tutorial from http://docs.python.org/tut/node11.html about classes in python. On May 14, 3:08?am, wxPytho... at gmail.com wrote: > Hello! > > I have trouble understanding something in this code snippet: > > class TextReader: > ? ? """Print and number lines in a text file.""" > ? ? def __init__(self, file): > ? ? ? ? self.file = file > ? ? ? ? . > ? ? ? ? . > ? ? ? ? . > > When would you do a thing like ?self.file = file ?? I really don't > find an answer on this. Please help me understand this. From mensanator at aol.com Thu May 1 14:34:44 2008 From: mensanator at aol.com (Mensanator) Date: Thu, 1 May 2008 11:34:44 -0700 (PDT) Subject: DO U WANT TO KNOW ABOUT SCIENTOLOGY? References: <7fe132fe-8a8a-4abc-9d8e-f1c27d00cc48@z24g2000prf.googlegroups.com> Message-ID: <72c27738-3d8a-4a9d-8250-17e4d4f8cad3@a70g2000hsh.googlegroups.com> On May 1, 8:11?am, prabain... at gmail.com wrote: > ? ? ? ? ? ? ? ? ? ? HELLO FRIEND IAM SHALINI, > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? DO U WANT TO KNOW ABOUT > SCIENTOLOGY? Do I need to know about wiping my ass with a rock? Oh, wait...that's Islam, isn't it? Sorry, I often get those two confused. Scientology and ass wiping. > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?PLS LOOK AT THE BELOW > WEBSITE. > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?www.bigconcern3.blogspot.com From wizzardx at gmail.com Sat May 3 15:54:55 2008 From: wizzardx at gmail.com (David) Date: Sat, 3 May 2008 21:54:55 +0200 Subject: State machine Example in Python In-Reply-To: References: Message-ID: <18c1e6480805031254j7647d5a4rfa4aeb4b5613298f@mail.gmail.com> On Sat, May 3, 2008 at 6:26 PM, Alok Kumar wrote: > Can someone please redirect me for a state machine example or design pattern > used in Python. > Google for it, eg: http://www.google.com/search?q=python+state+machine There's plenty of results. Be more specific if you can't get what you want from Google. David. From rschroev_nospam_ml at fastmail.fm Tue May 20 15:27:55 2008 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Tue, 20 May 2008 21:27:55 +0200 Subject: Using Python for programming algorithms In-Reply-To: <4d44955c-4eee-42bd-ae7f-a3cf511869c2@27g2000hsf.googlegroups.com> References: <98fa5fa3-45ae-4df1-9fd3-1a227641244f@p25g2000hsf.googlegroups.com> <48314dd0$0$32138$426a34cc@news.free.fr> <4d44955c-4eee-42bd-ae7f-a3cf511869c2@27g2000hsf.googlegroups.com> Message-ID: <0DFYj.28609$ie5.21801@newsfe05.ams2> Wow this resulted in far more reactions than I had expected ... bruno.desthuilliers at gmail.com schreef: > On 19 mai, 15:30, Roel Schroeven > wrote: >> Bruno Desthuilliers schreef: >> >>> 1/ being interpreted or compiled (for whatever definition of these >>> terms) is not a property of a language, but a property of an >>> implementation of a language. >>> 2/ actually, all known Python implementations compile to byte-code. >> You keep saying that, and in theory you're right. > > "In theory" ??? Heck, both points above are mere facts. Well, I may > accept that the 2nd one is a bit overgeneralized, since IIRC there's > an experimental Python to javascript "compiler" in Pypy, but... > >> But I'm still inclined to disagree with it, since the practical reality is different. > > Do you mean that how source code written in a language (that is : a > grammar + a syntax) finally become a set of instructions executed by > a CPU depends on the language (I repeat : a grammer + a syntax), and > not on a piece of software turning the source code into something that > can actually be executed by the CPU ? No, that's not what I said; what I said is that some languages where designed with in the back of the head the idea that they were going to be compiled to native code, others to be interpreted, and others to be compiled to byte code. Wikipedia says about C that "its design goals were for it to be compiled using a relatively straightforward compiler, provide low-level access to memory, provide language constructs that map efficiently to machine instructions, and require minimal run-time support". To me, that very strongly suggests that it was meant to be compiled to native code. It's called "portable assembly" for a reason. You *can* make it work in another way, and I suppose that it *is* done, but those implementations are far in the minority. As for Python, until the advent of PyPy all implementations I known used a virtual machine (CPython, Jython, IronPython). And PyPy is still experimental as far as I know. So yes, the transformation method from source code to something that the CPU understands depends on your tools. But if you want to get work done, the most common method by far for C is to use a toolchain that compiles to native code and for Python a byte code compiler + virtual machine. With possibly a JIT compiler, that's true. >> Python is >> indeed compiled to byte code, but if you compare that byte code with >> assembly code you'll see that there's a whole world of difference >> between the two, > > Obviously, yes - at least for all assembly language I've seen so far. > But whoever said otherwise ? Whenever someone says that Python is interpreted, you respond saying that that's not true, since it's compiled to byte code. Correct of course, but somehow it appears to me that you imply that that makes Python closer to a C-like language than to an interpreted language, and that's not correct (IMO). If that's just a misinterpretation by me, I apologize. >> largely because of the dynamical nature of Python. Fact >> is that Python was designed from the start to run on a virtual machine, >> not on the native hardware. > > Nope. The facts are that > 1/ Python (the language) has *not* been designed with ease of > implementation of an optimizing native-code compiler in mind, and > 2/ CPython (the first and reference implementation) has been designed > to use a byte-code + VM scheme Isn't that more or less the same as what I said? Maybe I don't make enough distinction between Python the language and CPython the implementation, but Python development does happen on the CPython implementation (Python 3.0 alpha releases are CPython releases, for example). > >> C OTOH was designed to be compiled to assembly code (or directly to >> machine code) > > Note quite. C has been designed to make it as easy as possible to > write either a C to assembly or C to native binary code compiler. I find it hard to believe that during the development of C Dennis Ritchie was considering any other mode of operation than compilation to assembly or machine code. I might be wrong of course. >> and as a result there are no (or virtually) no >> implementations that interpret C or compile it to bytecode. > > There's at least one (possibly incomplete) C interpreter. I'd like to call that the exception that confirms the rule. > There's a very naive belief we saw every here and then here, which is > that "Python would be faster if it was compiled to native code". The > point is that, given Python's (as a language) extrem dynamism, > compiling it to native code wouldn't buy you much in terms of raw > performances. The problem is not with writing a native-code > compiler[1}, but with writing an *optimising* native-code compiler. I admit I'm guilty of that belief. I know it's true what you say, but I do have the more-or-less unconscious reflex 'compiled to native code == fast'. > I'm just getting fed up with > this "Python is an interpreted and therefore slow language" non- > sense. Python is a language, and as such is neither slow nor fast nor > interpreted nor compiled nor here>. And while CPython is not blazingly fast for computation-heavy > stuff, it's not because it is "interpreted" - which it is not for a > strict definition of "interpreted", but anyway... - but because > *optimizing* execution of an highly dynamic language is nothing, > well, err, trivial. So you are saying that CPython is relatively slow because Python is a highly dynamic language. I know that CPython is not Python and Python is not CPython, but there is a very strong association between the two and therefore I think it's not really that much wrong to simplify that to 'Python is slow because it is a highly dynamic language (until proven wrong by PyPy or another fast implementation'. -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From kyosohma at gmail.com Tue May 13 13:44:16 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 13 May 2008 10:44:16 -0700 (PDT) Subject: Literate programs in Python References: <37e8fb41-8008-45aa-a123-b71455bc7ce5@t54g2000hsg.googlegroups.com> Message-ID: On May 13, 10:28?am, Paul Miller wrote: > Does anyone know of any (preferably largish) examples of literate > programs written using Python? ?Alternatively, does anyone know of any > literate programming tools which support Python well? ?(I am aware of > Leo and I've been to literateprogramming.com, but any additional > pointers would be much appreciated!) > > Thanks, > > Paul Check out Zope, bittorrent, or Editra. You should just go to SourceForge and do a search for projects done in Python. Mike From johnjsal at NOSPAMgmail.com Tue May 20 00:09:14 2008 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 20 May 2008 00:09:14 -0400 Subject: Compress a string References: Message-ID: <20080520000914.24b6c12e.johnjsal@NOSPAMgmail.com> On Sun, 18 May 2008 19:06:10 +0100 "Matt Porter" wrote: > Hi guys, > > I'm trying to compress a string. > E.g: > "AAAABBBC" -> "ABC" Not that you need help anymore, but I decided to give it a try. Not as elegant as the one- and two-liners, but somewhat concise I guess. def compress(s): new = [s[:1]] for c in s[1:]: if c not in new: new.append(c) return ''.join(new) From tarundevnani at gmail.com Wed May 7 08:25:12 2008 From: tarundevnani at gmail.com (tarun) Date: Wed, 7 May 2008 17:55:12 +0530 Subject: Some issue with right click in TreeCtrl Message-ID: Hello All, Please find the code for a simple wx.TreeCtrl code. Whenever I right click on any item in the Tree, I see the function, 'OnSelChanged' gets called twice. What I've just done is that I've associated the function 'OnRightClick' with wx.EVT_TREE_ITEM_RIGHT_CLICK. And in this function, I say self.tree.SelectItem(evt.GetItem(),True) to select the item and then so some action for right click. Can any one help. Thanks & Regards, Tarun *Please find the code in the attachment and also below:-* import wx tests = ["All Tests", ["Suite1", "test01", "test02", ["suite2","test03","test04"], "test05", ], ["Suite3", "test06", "test07" ], ["Suite4", "test08", "test09" ], "test10", "test11", ] class TestFrame(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, title="Simple Tree", size=(400,500)) # Create the tree self.tree = wx.TreeCtrl(self) # Add a root node root = self.tree.AddRoot(tests[0]) # Add nodes from our data set self.AddTreeNodes(root, tests, 0) # Bind some interesting events self.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelChanged, self.tree) self.Bind(wx.EVT_TREE_ITEM_RIGHT_CLICK, self.OnRightClick, self.tree) # Expand the first level self.tree.Expand(root) def AddTreeNodes(self, father, aTestList,count): if type(aTestList) == type([]): l = len(aTestList) i = 0 while i < l: if i == 0: if count ==1: father = self.tree.AppendItem(father, aTestList[i]) else: self.AddTreeNodes(father, aTestList[i], 1) i = i + 1 if type(aTestList) == type(""): self.tree.AppendItem(father, aTestList) def OnRightClick(self, evt): self.tree.SelectItem(evt.GetItem(),True) print 'In OnRightClick Function...',self.GetItemText(evt.GetItem()) def GetItemText(self, item): if item: return self.tree.GetItemText(item) else: return "" def OnSelChanged(self, evt): print "OnSelChanged: ", self.GetItemText(evt.GetItem()) app = wx.PySimpleApp(redirect=True) frame = TestFrame() frame.Show() app.MainLoop() -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: my_test.py URL: From python at bc90021.net Sun May 11 16:12:38 2008 From: python at bc90021.net (bc90021) Date: Sun, 11 May 2008 20:12:38 GMT Subject: File Creation Not Working In A Thread Class? References: <7qGVj.32505$KJ1.18416@newsfe19.lga> Message-ID: On Sun, 11 May 2008 19:55:31 +0000, Duncan Booth wrote: > 7stud wrote: > > >> ? ? ? ? ? ? ? ? ? ? ? ? ? ? tempfileName = "\"proctemp\\" >> ? ? ? ? ? ? ? ? ? ? ? ? ? ? + >> self.matrix[c][0] + "_other.txt\"" > > It wouldn't exactly result in either of the error messages you posted, > but I expect the spurious quote marks round the filename will be giving > you problems. > > Surely you want the filename to be something like > 'proctemp\fred_other.txt' rather than '"proctemp\fred_other.txt"' with > the spurious double quotes? Yup, that's what it was. I figured it out two seconds before this post. However, it will be interesting to see how it handles files with spaces in the name... Thanks for your help! From zerty.david at gmail.com Thu May 1 20:31:01 2008 From: zerty.david at gmail.com (David Anderson) Date: Thu, 1 May 2008 21:31:01 -0300 Subject: Problems with psycopg2 Message-ID: <5dc598e30805011731g1022de5bq750f890a284e5880@mail.gmail.com> Hi all I have this function: def checkName(self, name): cur = self.conn.cursor() sql = "SELECT * from patient WHERE fn_pat = '" + name + "'" cur.execute(sql) rows = cur.fetchall() if rows == "[]": self.insert() It seems to work fine, But I'm getting this exception: psycopg2.ProgrammingError: current transaction is aborted, commands ignored until end of transaction block at: cur.execute(sql) What's the problem? thx ps: fn_pat is the column of the db, name is the string passed in the function parameter -------------- next part -------------- An HTML attachment was scrubbed... URL: From sn at sncs.se Fri May 23 11:30:36 2008 From: sn at sncs.se (Sverker Nilsson) Date: Fri, 23 May 2008 08:30:36 -0700 (PDT) Subject: How to print a sorted list as a multi-column table Message-ID: <0628a0f6-d5a5-4629-ae93-3a3bff93eec3@x41g2000hsb.googlegroups.com> Hi all, I would like to ask about opinions about the best way to format sorted tables of items for interactive use. I have begun to add interactive help to Guppy/Heapy (http://guppy-pe.sourceforge.net) because it lacks the usual ways for introspection (see for example http://www.pkgcore.org/trac/pkgcore/doc/dev-notes/heapy.rst) which is due to Heapy's use of dynamic things like __getattr__ and to some extent properties. There seems to be no (good or otherwise) way to hook into the standard help() (?) (At least not before 2.6 where I recall seeing a __dir__ magic method may be introduced, but I want it to be backwards compatible to at least 2.4, preferably to 2.3.) So I am about to roll my own help system. It will be based on having the API objects supplying a standardized '.help' attribute which can be used interactively, and will limit the output it prints to say 15 or 20 rows at a time. That's for a background. Now what I was stumbling on which pumped up enough adrenalin to make me begin to write this --- Why are tables formatted like the following, when sorted? (Both in linux eg ls, ftp help, and in Python help() when listing (eg) modules)) (1) a g m s b h n t c i o u d j p v e k q f l r Wouldn't it be more natural to just sort them like this: (2) a b c d e f g h i j k l m n o p q r s t u v What's the rationale for the choice of (1)? In a pager, if you want to limit the number of lines output at a time, then yo'd see with (1) (if artifically limiting output to 2 lines): a g m s b h n t So to see the f item you would have to scroll down all the way. The number of times you would have to scroll down is in completely unrelated to the item's position in sort order. That seems to defeat the purpose of sorting in the first place. It feels strange, to me at least. Anybody had the same feeling? Well, what's the rationale (if any) for using the layout (1)? Wouldn't layout (2) be better? And/or would it be confusing / non-pythonic / non-unlixonic if a program used the (2) layout instead? Have a (:nice:) weekend :-) Sverker From mail at timgolden.me.uk Wed May 7 03:58:33 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 07 May 2008 08:58:33 +0100 Subject: Scanning through Windows registry... In-Reply-To: References: Message-ID: <48216129.5090405@timgolden.me.uk> Unknown Hero wrote: > Tim Golden wrote: [... snip long example ...] > Correct me if I'm wrong (which I just might be), but doesn't the above > code go through the keys behind HKEY_LOCAL_MACHINE\Software\Timsoft\ ? > > Is it possible to use an empty value in: > > hTimSoft = _winreg.OpenKey (HKLM, r"Software\TimSoft") > > like: > > hTimSoft = _winreg.OpenKey (HKLM, "") > > so it would go all subkeys behind the "root" (in this case, > HKEY_LOCAL_MACHINE)? Yes. (Well, you can try it and find out for yourself!). As I said, this was code to illustrate some other poster's difficulty. I assume that you're capable of twisting it to suit your own purposes :) > The code is supposed to work even if I don't know all possible subkeys > under HKEY_LOCAL_MACHINE. Creating dozens or hundreds of handles like > the above is a bit... unappealing. > > Can I also use HKLM in the place of hTimSoft when I want to determine > the amount of subkeys it has, like you did over here: Yes. You can put any key handle you like in place of my hTimSoft of the predefined _winreg.HKEY_LOCAL_MACHINE. They're just keys. I assume you'll want some kind of recursive function which combines calls to EnumKeys and EnumValues. > Anyway, the above code seems interesting. I'll try a few tweaks here > and there and see what happens. I wasn't sure just how experienced you were with programming; although you said you were new to Python I thought you might have experience elsewhere which would help you out here. If you're really stuck, post back and I (or someone else) can try to knock up a more pertinent example. The main thing is for you to get hold of the _winreg docs -- which I know you mentioned before -- and to grasp what the concepts are and how the API calls work. It's a low-level module, simply exposing the raw API calls, which is why there are several wrapper modules around it, but it's worth getting to understand what's going on under the covers. TJG From s0suk3 at gmail.com Mon May 19 11:48:42 2008 From: s0suk3 at gmail.com (s0suk3 at gmail.com) Date: Mon, 19 May 2008 08:48:42 -0700 (PDT) Subject: Newbie: Keep TCP socket open References: Message-ID: On May 19, 10:25 am, "Alan Wright" wrote: > Hi Folks, > I am newbie to Python, but have successfully created a simple client and > server setup, I have one issue though. > > I am trying to test a box by sending many TCP conns (WHILE loop) but not > closing them with a FIN/RST. However, no matter what i do, i cannot get the > loop to stop sending FIN from the client. > > Any clues? > > Here is my current script > > #!/usr/bin/python > > import socket,sys > from numpy import * > num1=0 > > while (num1<=10) : > > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > s.settimeout(10.0) > s.connect(("10.1.1.69", 50008)) # SMTP > print s.recv(1024) + '\n', > num1=num1+1 > #s.close() > > sys.exit(1) socket.socket instances do an implicit close() on the socket when the object is destructed (in this case, it's destructed when it is garbage- collected). What's happening is that on each iteration, the variable "s", which references the socket.socket instance, is assigned to a new socket.socket instance, therefore the instance of the previous iteration is no longer referenced by "s", and since it's no longer referenced by anything, the instance is garbage-collected, automatically imposing an implicit close() on that instance. A simple solution could be to create a list and append the socket.socket instance of each iteration to that list, that way the instances would remain referenced in the list and not be garbage-collected; though you might be able to find a more elegant solution. Sebastian From python at bc90021.net Sun May 11 13:59:13 2008 From: python at bc90021.net (bc90021) Date: Sun, 11 May 2008 17:59:13 GMT Subject: File Creation Not Working In A Thread Class? References: Message-ID: On Sun, 11 May 2008 10:51:34 -0700, Gary Herron wrote: > bc90021 wrote: >> Hi All, >> >> Thanks in advance for any and all help! >> >> I have this code: >> >> g = open(fileName, 'a') >> >> > I don't believe you. I think you have something like > > g = open('fileName', 'a') > > instead of (as you claim) > > g = open(fileName, 'a') > > Do you see the difference? > > Develop the skill of reading the error messages *very* carefully. Your > error says there is no file named "fileName", and if you think about > what's on your disk, I'll bet you won't find a file whose name is > "fileName". > > > Gary Herron > Gary, I can assure you that that's not the case. (Of course, you're free to believe me or not believe me at your convenience.) You are right that I don't have that file on the disk - it is supposed to be created with the "open" line! It works *perfectly* outside the class the inherits from threading.Thread; inside the threading.Thread class it does NOT create the file, whether I use g = open(fileName, 'a') or g = open (fileName, 'w'). Hence my obvious confusion. From victorsubervi at gmail.com Thu May 1 18:31:25 2008 From: victorsubervi at gmail.com (Victor Subervi) Date: Thu, 1 May 2008 17:31:25 -0500 Subject: Custom Classes? In-Reply-To: <1209576920.4990.17.camel@aalcdl07.lib.unc.edu> References: <4dc0cfea0804300902o7493dab2m35999b5b59deace4@mail.gmail.com> <1209576920.4990.17.camel@aalcdl07.lib.unc.edu> Message-ID: <4dc0cfea0805011531s4574eb0bk8b6aea6ac010c881@mail.gmail.com> On Wed, Apr 30, 2008 at 12:35 PM, J. Cliff Dyer wrote: > Post working code, and I'll answer your actual question. Good grief! The code is *not* double spaced! Take a look. Click to the end of the first line and hit the right arrow key, and see for yourself. As for not initializing w, well, I did in my code and just forgot to cut and paste that. Same with the except. Sorry on those. And yes, I pull out try clauses when I need to look at stacks. Here: w = 0 try: w += 1 getpic = "getpic" + str(w) + ".py" try: os.remove(getpic) except: pass code = """ #!/usr/local/bin/python import cgitb; cgitb.enable() import MySQLdb import cgi import sys,os sys.path.append(os.getcwd()) from login import login user, passwd, db, host = login() form = cgi.FieldStorage() picid = int(form["id"].value) x = int(form["x"].value) pics = {1:'pic1',2:'pic1_thumb',3:'pic2',4:'pic2_thumb',5:'pic3',6:'pic3_thumb',7:'pic4',8:'pic4_thumb',\ 9:'pic5',10:'pic5_thumb',11:'pic6',12:'pic6_thumb'} pic = pics[x] print 'Content-Type: text/html' db = MySQLdb.connect(host=host, user=user, passwd=passwd, db=db) cursor= db.cursor() sql = "select " + pic + " from products where id='" + str(picid) + "';" cursor.execute(sql) content = cursor.fetchall()[0][0].tostring() cursor.close() print 'Content-Type: image/jpeg' print print content """ script = open(getpic, "w") script.write(code) print '' % pic print '

\n' % (getpic, d, y) except: pass TIA, Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From zxo102 at gmail.com Sat May 24 18:59:55 2008 From: zxo102 at gmail.com (zxo102) Date: Sat, 24 May 2008 15:59:55 -0700 (PDT) Subject: Hexadecimal: how to convert 'ED6F3C01' to "\xED\x6F\x3C\x01" in python coding? References: Message-ID: But this is not "\xED\x6F\x3C\x01". I need it for struct.unpack('f',"\xED\x6F\x3C\x01") to calculate the decimal value (IEEE 754). Any other suggestions? ouyang On 5?25?, ??6?46?, Sebastian 'lunar' Wiesner wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > [ zxo102 ] > > > how to change the hexadecimal 'ED6F3C01' (or 'ED 6F 3C 01') to > > "\xED\x6F\x3C\x01" in python coding? > > When I take 'ED6F3C01' as a string and insert '\x' into it, I just got > > the error information : invalid \x escape. > > [1]--> 'ED6F3C01'.decode('hex') > Out[1]: '\xedo<\x01' > > - -- > Freedom is always the freedom of dissenters. > (Rosa Luxemburg) > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v2.0.9 (GNU/Linux) > > iEYEARECAAYFAkg4mtEACgkQn3IEGILecb7W6ACeNwr/vavkaXluvc0zeSa4cy1N > YFIAoJjMsrRcLhqAPRxKktUqt7miMTrs > =jxll > -----END PGP SIGNATURE----- From notnorwegian at yahoo.se Sun May 25 03:10:45 2008 From: notnorwegian at yahoo.se (notnorwegian at yahoo.se) Date: Sun, 25 May 2008 00:10:45 -0700 (PDT) Subject: which datastructure for fast sorted insert? References: Message-ID: <6610cad9-384d-4755-9a2c-c605329be217@8g2000hse.googlegroups.com> On 25 Maj, 08:56, Rares Vernica wrote: > use a set to store them: > > >>> s=set() > >>> s.add('a') > >>> s.add('b') > >>> s > set(['a', 'b']) > >>> s.add('a') > >>> s > set(['a', 'b']) > >>> s.add('c') > >>> s > > set(['a', 'c', 'b']) > > > > it does remove duplicates, but is it not ordered. to order it you can > use: > > >>> l=list(s) > >>> l.sort() > >>> l > > ['a', 'b', 'c'] > > hth, > Rares sets dont seem to be so good because there is no way to iterate them. s.pop() remove and return an arbitrary element from s; raises KeyError if empty i dont want to remove i just want to get the string that is stored there. From stefan_ml at behnel.de Sat May 24 02:18:37 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sat, 24 May 2008 08:18:37 +0200 Subject: simple url regexp In-Reply-To: <545f4025-ff39-4eaa-871d-7aa4cca722a7@k13g2000hse.googlegroups.com> References: <545f4025-ff39-4eaa-871d-7aa4cca722a7@k13g2000hse.googlegroups.com> Message-ID: <4837B33D.4080007@behnel.de> notnorwegian at yahoo.se wrote: > url = re.compile(r"((http|ftp|https)\:\/\/)(www)?([a-zA-Z]{1}([\w\-]+ > \.)+([\w]{2,5}))(:[\d]{1,5})?((/?\w+/)+|/?)(\w+ > \.[\w]{3,4})?((\?\w+=\w+)?(&\w+=\w+)*)?") > > damn i hate these things. > > i want it to only match http://www.name.any/etc > > not http://wiki.x etc Why don't you use urlparse and check the result yourself? Stefan From notnorwegian at yahoo.se Sat May 24 01:18:58 2008 From: notnorwegian at yahoo.se (notnorwegian at yahoo.se) Date: Fri, 23 May 2008 22:18:58 -0700 (PDT) Subject: why is com-prompt faster and how do i start at cprompt at mydir/ ? References: <878wy0cqg6.fsf@benfinney.id.au> <8e5e9da7-4255-4f38-b32b-04723be46b9a@y38g2000hsy.googlegroups.com> <87mymgb8hn.fsf@benfinney.id.au> Message-ID: <5def9628-1332-4c18-b123-e5eef1a810d1@t54g2000hsg.googlegroups.com> On 24 Maj, 07:01, Ben Finney wrote: > notnorweg... at yahoo.se writes: > > On 24 Maj, 05:48, Ben Finney > > wrote: > > > Can you tell us exactly which programs you mean when you say "the > > > shell" and "the commandprompt"? > > > commandprompt = windows dos-windows > > > shell = standard python interactive prompt > > Thanks. > > Be aware that referring to "the shell" without further qualification > is usually understood to mean "the operating system shell", i.e. the > command shell provided for running operating system commands. > > So, you're asking about the difference in behaviour between "the > Windows command shell" versus "the Python interactive shell". > > -- > \ ?I cannot conceive that anybody will require multiplications | > `\ at the rate of 40,000 or even 4,000 per hour ...? ?F. H. | > _o__) Wales, 1936 | > Ben Finney yes From mail at timgolden.me.uk Thu May 15 12:09:19 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 15 May 2008 17:09:19 +0100 Subject: exists=false, but no complaint when i open it!? In-Reply-To: <285e0ce6-1371-4ab7-9281-ad1d664a480f@a23g2000hsc.googlegroups.com> References: <285e0ce6-1371-4ab7-9281-ad1d664a480f@a23g2000hsc.googlegroups.com> Message-ID: <482C602F.4070203@timgolden.me.uk> globalrev wrote: > print os.path.exists('C:\Users\saftarn\Desktop\NetFlixDataSet > \trainingsetunzipped\training_set\mv_0000001.txt') > > d=open('C:/Python25/myPrograms/mapexperiments/maps/provinces-of- > sweden.gif') > d.close() Ummm. These are not the same files (unless you've got some bizarre NTFS linking going on). > exists returns false but when i open it doesnt complain. how come? Also, in general, you're prone to race conditions if you do this kind of thing, altho' on a local C: drive that's less likely. But still possible. Probably better to wrap the open in a try-except and handle an IOError. TJG From ptmcg at austin.rr.com Fri May 9 18:54:21 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Fri, 9 May 2008 15:54:21 -0700 (PDT) Subject: regexp help References: <834d8448-5d6a-4f49-9be6-6501a0b5fd92@k37g2000hsf.googlegroups.com> Message-ID: <1cd897aa-0027-4c5b-8bf2-f7c5781df93e@24g2000hsh.googlegroups.com> On May 9, 5:19?pm, globalrev wrote: > i want to a little stringmanipulationa nd im looking into regexps. i > couldnt find out how to do: > s = 'poprorinoncoce' > re.sub('$o$', '$', s) > should result in 'prince' > > $ is obv the wrng character to use bu what i mean the pattern is > "consonant o consonant" and should be replace by just "consonant". > both consonants should be the same too. > so mole would be mole > mom would be m etc from re import * vowels = "aAeEiIoOuU" cons = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ" encodeRe = re.compile(r"([%s])[%s]\1" % (cons,vowels)) print encodeRe.sub(r"\1",s) This is actually a little more complex than you asked - it will search for any consonant-vowel-same_consonant triple, and replace it with the leading consonant. To meet your original request, change to: from re import * cons = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ" encodeRe = re.compile(r"([%s])o\1" % cons) print encodeRe.sub(r"\1",s) Both print "prince". -- Paul (I have a pyparsing solution too, but I just used it to prototype up the solution, then coverted it to regex.) From bj_666 at gmx.net Sat May 24 07:35:49 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 24 May 2008 11:35:49 GMT Subject: Assignment and comparison in one statement References: <10f19bee-1e0a-4401-a03b-18c458388297@s50g2000hsb.googlegroups.com> Message-ID: <69qcslF33dagrU5@mid.uni-berlin.de> On Sat, 24 May 2008 13:12:13 +0200, Johannes Bauer wrote: > Carl Banks schrieb: > >> p = myfunction() >> if p: >> print p >> >> (I recommend doing it this way in C, too.) > > This is okay for if-clauses, but sucks for while-loops: > > while (fgets(buf, sizeof(buf), f)) { > printf("%s\n", buf); > } > > is much shorter than > > char *tmp; > tmp = fgets(buf, sizeof(buf), f); > while (tmp) { > printf("%s\n", buf); > tmp = fgets(buf, sizeof(buf), f); > } Can be written in Python as: from functools import partial # ... for buf in iter(partial(f.read, buf_size), ''): print '%s\n' % buf Ciao, Marc 'BlackJack' Rintsch From banibrata.dutta at gmail.com Tue May 6 09:51:05 2008 From: banibrata.dutta at gmail.com (Banibrata Dutta) Date: Tue, 6 May 2008 19:21:05 +0530 Subject: Module to read input from commandline In-Reply-To: References: Message-ID: <3de8e1f70805060651r70767637wb6820fc156411a32@mail.gmail.com> something like "curses" but w/o the fancy window decorations perhaps ? if so, then following link might help ( http://www.amk.ca/python/howto/curses/). thanks & regards, banibrata On Tue, May 6, 2008 at 6:56 PM, wrote: > On May 6, 2:11 pm, pyt... at bdurham.com wrote: > > > Check out the optparse module as well. The optparse module supercedes(?) > > the cmd module and offers a lot more functionality. > > Hi Malcom, > > Doesn't the optparse module work by parsing the arguments that are > passed to the script when it is invoked? > > What I was looking for was a commandline read loop that executes > within a script that is already running ... or can optparse be used in > this context as well? > > Thanks, > James. > -- > http://mail.python.org/mailman/listinfo/python-list > -- regards, Banibrata http://www.linkedin.com/in/bdutta -------------- next part -------------- An HTML attachment was scrubbed... URL: From spectrumdt at gmail.com Fri May 9 06:16:57 2008 From: spectrumdt at gmail.com (spectrumdt at gmail.com) Date: Fri, 9 May 2008 03:16:57 -0700 (PDT) Subject: How to kill Python interpreter from the command line? References: Message-ID: <637ecc42-63f2-4ab0-b126-83059634f099@s50g2000hsb.googlegroups.com> Thanks for all the replies. On May 8, 5:50?pm, Jean-Paul Calderone wrote: > Ctrl+C often works with Python, but as with any language, it's possible > to write a program which will not respond to it. ?You can use Ctrl+\ > instead (Ctrl+C sends SIGINT which can be masked or otherwise ignored, > Ctrl+\ sends SIGQUIT which typically isn't) Yes, thank you, this seems to work. :) I did some more testing and found out that the problem seems to be thread-related. If I have a single-threaded program, then Ctrl+C usually works, but if I have threads, it is usually ignored. For instance, the below program does not respond to Ctrl+C (but it does die when issued Ctrl+\): import threading def loop(): while True: pass threading.Thread(target=loop,args=()).start() From duncan.booth at invalid.invalid Mon May 19 03:56:33 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 19 May 2008 07:56:33 GMT Subject: Classmethods are evil References: Message-ID: Hans Nowak wrote: > The way I see it, a class method is really just sugar for a function > operating on the class, living in the class namespace. As such, they > are basically redundant, and as you point out, they can always be > replaced by a function outside the class (and in fact, this was what > people did before they came along in 2.2). Personally, I don't use > them... but some people like them. Different strokes, and all that... > In exactly the same way you could claim that a method is just sugar for a function operating on the instance living in the instance namespace. As such, you might think that they too are basically redundant, but they aren't: with instance methods you get the ability to override the method in a subclass without the caller needing to know whether they are calling the original method or an overridden version. With class methods you also get the ability to override the method in a subclass, and again the caller doesn't need to know or care which variant when they call it. Say you have a class hierarchy with a from_keys() class method. If you want to construct a new Foo you might call Foo.from_keys() without caring whether the method is the original one defined in one of Foo's base classes or a modified version specific to a Foo. If you were using functions then you would need to define a new from_keys() function for every class in a hierarchy, or at least for every different implementation in the hierarchy and the caller would need to be careful to call the correct one. So we end up with functions from_keys_Foo_or_Baz(cls) and from_keys_Bar() which is an unmaintainable mess. -- Duncan Booth http://kupuguy.blogspot.com From zondo42 at googlemail.com Sun May 4 21:20:10 2008 From: zondo42 at googlemail.com (Glenn Hutchings) Date: Mon, 05 May 2008 02:20:10 +0100 Subject: Numpy not found References: <9d1d26d4-6351-4557-9834-fd51669858df@34g2000hsf.googlegroups.com> Message-ID: adolfo writes: > I downloaded and installed Phyton 2.52 (it works), numpy-1.0.4.win32- > py2.5, and scipy-0.6.0.win32-py2.5 > > I can?t get Numpy to show up at Python?s IDLE, or command line. If I > do: > >>>>> import Numeric > # I get >>>>> Traceback (most recent call last): > File "", line 1, in > import Numeric > ImportError: No module named Numeric Try 'import numpy' instead. Numeric is an earlier incarnation of numpy -- it has (mostly) the same interface, but is a different package. (Just to confuse things even further, there's also another old one, called numarray). > And if I do: >>>>> import Numeric * > # I get > SyntaxError: invalid syntax The proper syntax for that is (assuming you want numpy instead) 'from numpy import *'. Glenn From greg.ewing at canterbury.ac.nz Sun May 18 07:25:45 2008 From: greg.ewing at canterbury.ac.nz (Greg Ewing) Date: Sun, 18 May 2008 23:25:45 +1200 Subject: ANN: Pyrex 0.9.8.2 Message-ID: Pyrex 0.9.8.2 is now available: http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/ A block of external functions can now be declared nogil at once. cdef extern from "somewhere.h" nogil: ... Also some minor nogil-related bugs have been fixed. What is Pyrex? -------------- Pyrex is a language for writing Python extension modules. It lets you freely mix operations on Python and C data, with all Python reference counting and error checking handled automatically. From thomas.karolski at googlemail.com Thu May 22 22:28:22 2008 From: thomas.karolski at googlemail.com (thomas.karolski at googlemail.com) Date: Thu, 22 May 2008 19:28:22 -0700 (PDT) Subject: Decorator metaclass Message-ID: <219a475b-c6e3-4128-98bc-d73fd215ce67@w7g2000hsa.googlegroups.com> Hi, I would like to create a Decorator metaclass, which automatically turns a class which inherits from the "Decorator" type into a decorator. A decorator in this case, is simply a class which has all of its decorator implementation inside a decorator() method. Every other attribute access is being proxied to decorator().getParent(). Here's my attempt: ------------------------------------------------------- from new import classobj class DecoratorType(type): def __new__(cls, name, bases, dct): dct2 = {} for key, val in dct.iteritems(): dct2[key] = val # create a new class which will store all of the implementation impl = classobj('%sImpl'%name,(),dct2) # update the old class to implement this implementation def __init__(self, *args, **dargs): object.__setattr__(self, '__impl', impl(*args, **dargs)) def decorator(self): return object.__getattribute__(self,'__impl') def __getattribute__(self, attr): if attr=="decorator": return object.__getattribute__(self,'decorator') return getattr(object.__getattribute__(self, 'decorator') ().getParent(), attr) dct = {} dct['__init__'] = __init__ dct['decorator'] = decorator dct['__getattribute__'] = __getattribute__ return type.__new__(cls, name, bases, dct) class Decorator(object): __metaclass__ = DecoratorType class HBar(Decorator): def __init__(self, number): Decorator.__init__(self) self._number = number def inc(self): self._number += 1 def p(self): print self._number hbar = HBar(10) for each in dir(hbar.decorator()): print each hbar.decorator().p() hbar.decorator().inc() hbar.decorator().p() ------------------------------------------------------- Unfortunately this does not work. The newly defined __init__ method inside __new__, does a call to impl(*args, **dargs). However, since the HBar.__init__ calls the Decorator.__init__ method, but the HBar.__init__ method no longer resides inside HBar, but rather inside HBarImpl (which is no longer a subtype of Decorator), the compiler complains that Decorator.__init__ is not being called with a Decorator instance as its first argument (which is true). I tried changing the definition of impl inside __new__ to have Decorator as one of its bases, but then for some reason impl(*args, **dargs) asks for 4 arguments (just like __new__) and I have no clue as to why that happens. Any help on this? Regards, Thomas K. From jr9445 at ATT.COM Thu May 15 12:11:27 2008 From: jr9445 at ATT.COM (Reedick, Andrew) Date: Thu, 15 May 2008 11:11:27 -0500 Subject: exists=false, but no complaint when i open it!? In-Reply-To: <285e0ce6-1371-4ab7-9281-ad1d664a480f@a23g2000hsc.googlegroups.com> References: <285e0ce6-1371-4ab7-9281-ad1d664a480f@a23g2000hsc.googlegroups.com> Message-ID: > -----Original Message----- > From: python-list-bounces+jr9445=att.com at python.org [mailto:python- > list-bounces+jr9445=att.com at python.org] On Behalf Of globalrev > Sent: Thursday, May 15, 2008 12:04 PM > To: python-list at python.org > Subject: exists=false, but no complaint when i open it!? > > print os.path.exists('C:\Users\saftarn\Desktop\NetFlixDataSet > \trainingsetunzipped\training_set\mv_0000001.txt') > > d=open('C:/Python25/myPrograms/mapexperiments/maps/provinces-of- > sweden.gif') > d.close() > > exists returns false but when i open it doesnt complain. how come? > > another file that exists returned false for complained when i tried to > open it. > -- You're falling victim to string interpolation because of the backslashes. (\n == newline, \N == N). Try using a raw string r'filename', instead of 'filename': print os.path.exists(r'C:\Users\saftarn\Desktop\NetFlixDataSet\trainingsetunzi pped\training_set\mv_0000001.txt') ***** The information transmitted is intended only for the person or entity to which it is addressed and may contain confidential, proprietary, and/or privileged material. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon this information by persons or entities other than the intended recipient is prohibited. If you received this in error, please contact the sender and delete the material from all computers. GA621 From sjmachin at lexicon.net Fri May 9 21:39:59 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 10 May 2008 01:39:59 GMT Subject: regexp help In-Reply-To: References: <834d8448-5d6a-4f49-9be6-6501a0b5fd92@k37g2000hsf.googlegroups.com> Message-ID: <4824fcec$1@news.mel.dft.com.au> globalrev wrote: > ty. that was the decrypt function. i am slo writing an encrypt > function. > > def encrypt(phrase): > pattern = > re.compile(r"([bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ])") The inner pair of () are not necessary. > return pattern.sub(r"1\o\1", phrase) > > doesnt work though, h becomes 1\\oh. To be precise, "h" becomes "1\\oh", which is the same as r"1\oh". There is only one backslash in the result. It's doing exactly what you told it to do: replace each consonant by (1) the character '1' (2) a backslash (3) the character 'o' (4) the consonant > > > def encrypt(phrase): > pattern = > re.compile(r"([bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ])") > return pattern.sub(r"o\1", phrase) > > returns oh. It's doing exactly what you told it to do: replace each consonant by (1) the character 'o' (2) the consonant > i want hoh. So tell it to do that: return pattern.sub(r"\1o\1", phrase) > i dont quite get it.why cant i delimit pattern with \ Perhaps you could explain what you mean by "delimit pattern with \". From paul at boddie.org.uk Wed May 21 07:30:14 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 21 May 2008 04:30:14 -0700 (PDT) Subject: Minimal Python installation? References: Message-ID: On 21 Mai, 12:07, Thomas Troeger wrote: > > I'd like to put the python library and interpreter on a small embedded > Linux x86 compatible device where disk space is an issue. I played > around with the minimal Python interpreters, but was not entirely happy > with them, so my question is, is there an (preferably easy) way to put > the interpreter and a cut-down version of the python library/modules > that ship with regular Python into a new archive that I can safely copy > and use? Perhaps there are some projects on the following pages which may help in some way: http://wiki.python.org/moin/EmbeddedPython http://wiki.python.org/moin/Tiny_Python [...] > Let's say I want a complete Python install, but without all the batteries :-) I think there's an overlap between "installer" tools and some of the projects mentioned on the above pages, especially where retaining only the critical libraries in the resulting distribution is concerned. Paul From bcb at undisclosedlocation.net Wed May 7 19:53:42 2008 From: bcb at undisclosedlocation.net (Bruce C. Baker) Date: Wed, 7 May 2008 18:53:42 -0500 Subject: The Importance of Terminology's Quality References: Message-ID: <5irUj.71335$y05.1766@newsfe22.lga> wrote in message news:f4abdb41-be28-4628-a2ad-7fb6cea6ed65 at u12g2000prd.googlegroups.com... [...] (for example, Perl's naming heavily relies on unix culture (grep, pipe, hash...), ... "hash" + "pipe"? Ahhhhh, /no wonder/ Perl is the syntactic mishmash it is! ;-) From tjreedy at udel.edu Sat May 10 20:00:30 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 10 May 2008 20:00:30 -0400 Subject: Mathematics in Python are not correct References: <52c855d8-5609-43e0-b98f-9fa87b2808c2@m3g2000hsc.googlegroups.com><200805081914.06459.kyrie@uh.cu> Message-ID: wrote in message news:f6743b81-9324-46dd-bbd3-ef8812e28197 at d77g2000hsb.googlegroups.com... |I am stunned that this simple misunderstanding of mine ended in a | mathematical clash of a sort. :) You guys really blew me away wih | your mathematical knowledge. And also the 0**0 is a thing I've never | thought about trying, until now that is. Anyone who defines a function should think about 'edge' and 'corner' cases. Recursive definitions often help, since such cases are typically the base cases. When learning a (computer) function, I often test such cases since they are a common place to mess up. tjr From __peter__ at web.de Sun May 18 08:11:34 2008 From: __peter__ at web.de (Peter Otten) Date: Sun, 18 May 2008 14:11:34 +0200 Subject: Error when calling superclass __init__ method References: Message-ID: Maese Fernando wrote: > I'm getting an odd error while trying to call the __init__ method of a > super class: > > BaseField.__init__(self) > TypeError: unbound method __init__() must be called with BaseField > instance as first argument (got nothing instead) > > > This is the code: No, it isn't. Please provide the actual code or, better, a minimal example. Don't forget to run it to verify it shows the behaviour described above before you post it. > What am I doing wrong? My bets are on BaseField.__init__() # no self Peter From mr.edel at gmx.at Wed May 28 09:42:22 2008 From: mr.edel at gmx.at (Matt) Date: Wed, 28 May 2008 13:42:22 +0000 Subject: ctypes, function pointers and a lot of trouble Message-ID: Hi friends, Okay so well, I have quite a problem right now with a file stream. What I am doing is to use the Cannon SDK dlls to get control over my old Cannon A60 Camera for some surveillance useage. By using ctypes it all worked well until now. I am able to load the dlls, use a lot of functions, am able to connect to the camera, read out some params, send commands etc... but now I am stuck with reading the picture data. In C the code looks as follows (found in an supplemental *.h SDK file: ------------------------------CODE----------------------------------------- #define cdSTDCALL __stdcall typedef void cdSTDCALL cdSOpen(cdContext contextH, cdPermission, cdError* err); typedef void cdSTDCALL cdSClose(cdContext contextH, cdError* err); typedef void cdSTDCALL cdSRead(cdContext contextH, void* buf, cdUInt32* bufsize, cdError* err); typedef void cdSTDCALL cdSWrite(cdContext contextH, const void *buf, cdUInt32* bufsize, cdError *err); typedef void cdSTDCALL cdSSeek(cdContext contextH, cdWhence, cdInt32 offset, cdError* err); typedef cdInt32 cdSTDCALL cdSTell(cdContext contextH, cdError* err); typedef void cdSTDCALL cdSProgress(cdContext contextH, cdUInt16 percentDone, cdError* err); /* cdStream */ typedef struct { cdContext contextH; /* stream I/O function pointers */ cdSOpen* open; cdSClose* close; cdSRead* read; cdSWrite* write; cdSSeek* seek; cdSTell* tell; } cdStream; /* cdStgMedium */ typedef struct { cdMemType Type; /* Type of the medium (u). */ union { cdChar* lpszFileName; cdStream* pStream; #ifdef macintosh cdFSSpec* pFSSpec; #endif }u; /* Union of all transfer medium */ } cdStgMedium; ------------------------------\CODE---------------------------------------- and this is the function definition that should give me access to the data stream (available via DLL): ------------------------------CODE----------------------------------------- cdCAPI CDGetReleasedData( cdHSource hSource, cdProgressCallbackFunction * pCallbackFunc, cdContext Context, cdProgressOption ProgressOption, cdReleaseImageInfo* pInfo, cdStgMedium* pStgMedium ); ------------------------------\CODE---------------------------------------- So, since I'm no C-Professional, I can only guess what that code does. With some previous commands I tell the camera to make a picture. This picture is then automatically moved to the PCs RAM and with the function above (CDGetReleasedData) I should be able to access this stream. Now I havn't accessed any stream with ctypes yet so I have only a rough idea how it could work. The following are the relevant parts of my code that don't work: ------------------------------CODE----------------------------------------- # Definitions: class cdReleaseImageInfo(Structure): _fields_ = [("SequenceID", c_uint), ("DataType", c_uint), ("Format", c_ubyte), ("DataSize", c_uint), ("Filename", c_char * 2)] class cdStream(Structure): _fields_ = [("contextH", c_uint), ("open", c_uint), ("close", c_uint), ("read", c_uint), ("write", c_uint), ("seek", c_uint), ("tell", c_uint)] class memunion(Union): _fields_ = [("lpszFileName", c_char), ("pStream", cdStream)] class cdStgMedium(Structure): _fields_ = [("Type", c_uint), ("u", memunion)] # command: datainfo = cdReleaseImageInfo() data = cdStgMedium() errorcode = cdsdk.CDGetReleasedData(devicehandle, byref(cbfunct), c_uint(1), c_uint(1), byref(datainfo), byref(data)) ------------------------------\CODE---------------------------------------- The function "cdsdk.CDGetReleasedData" itself gets executed correctly, but returns an "Invalid Parameter" errorcode. there's also no useful data whereas datainfo gets written correctly. I know that my cdStream can't work, facing the C-code, but what'd be the right cdStream class? What can I do? Any ideas? Best regards and thanks, Matt From kyosohma at gmail.com Fri May 23 16:47:21 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 23 May 2008 13:47:21 -0700 (PDT) Subject: Another Question References: <5c2e7570-6bb1-46d8-8dd5-b1a257431b31@p25g2000hsf.googlegroups.com> <57c4cdf6-4920-46f9-986e-e2859de7de8b@27g2000hsf.googlegroups.com> Message-ID: On May 23, 1:44?pm, Gandalf wrote: > you've been very helpful but still i have only one problem. I wont the > window not to be close after clicking the X button. > I wont the program to stay on the toolbar > > thanks! Well then, in your event handler, just don't do anything. def onClose(self, event): pass or maybe you want to hide the frame? def onClose(self, event): self.frame.Hide() Just make sure you give the user some other way to close it and in that handler, you'll need to call self.frame.Destroy(). Alternatively, you can just tell the frame not to create the "X" button: self.frame = wx.Frame(None, -1, title="My Frame", style=wx.SYSTEM_MENU) However, that makes it pretty annoying to close. Mike From yves at zioup.com Fri May 23 01:29:28 2008 From: yves at zioup.com (Yves Dorfsman) Date: Fri, 23 May 2008 05:29:28 GMT Subject: serach file for regexp, return if found? References: <348e4ed3-201c-43b6-ae27-0b921861a461@m36g2000hse.googlegroups.com> Message-ID: notnorwegian at yahoo.se wrote: > i want to search a document for a particular regexp and then store > that regexp to a file. > but search and match only returns matchobjects(what are those anyway? > i dont get what to do with them, do they contain true/false, > stringposition etc?) > how do i do: > for rows in file: > print regexp.find ## or something equiavlent Is this what you are trying to do: for row in file('/etc/services'): if re.match('^ssh', row): print row Yves. http://www.SollerS.ca From claird at lairds.us Mon May 26 13:49:40 2008 From: claird at lairds.us (Cameron Laird) Date: Mon, 26 May 2008 17:49:40 +0000 Subject: Python needn't apologize (was: Using Python for programming algorithms) References: <7ENXj.6906$255.106@bignews8.bellsouth.net> <71dc01f3-0084-4878-a4f0-5792e2648f77@y21g2000hsf.googlegroups.com> Message-ID: In article <71dc01f3-0084-4878-a4f0-5792e2648f77 at y21g2000hsf.googlegroups.com>, sturlamolden wrote: >On May 18, 5:46 am, "inhahe" wrote: > >> The numbers I heard are that Python is 10-100 times slower than C. > >Only true if you use Python as if it was a dialect of Visual Basic. If >you use the right tool, like NumPy, Python can be fast enough. Also >note that Python is not slower than any other language (including C) >if the code is i/o bound. As it turns out, most code is i/o bound, >even many scientific programs. > >In scientific research, CPU time is cheap and time spent programming >is expensive. Instead of optimizing code that runs too slowly, it is >often less expensive to use fancier hardware, like parallell >computers. For Python, we e.g. have mpi4py which gives us access to >MPI. It can be a good advice to write scientific software >parallelizable from the start. . [more of same] . . I can hardly overemphasize how often it happens not just that Python is more than 1% as fast as C, not just that Python is fast enough, but that real-world programs written in Python are FASTER then their homologs coded in C. From sarenius at sun3.oulu.fi Sun May 25 15:25:26 2008 From: sarenius at sun3.oulu.fi (Vesa-Matti Sarenius) Date: Sun, 25 May 2008 19:25:26 +0000 (UTC) Subject: UTF problem? References: Message-ID: In article , Tim Golden wrote: >so it's just possible that one of your filenames has >a non-ascii char in it without your noticing? (Altho' >I'd find that an odd character to include in a filename). There is somewhere since printing worked when I changed the filename completely. >To get round the problem in the immediate term, change >both print lines to something like: > >print repr (full_filename) This did not work. Neither did commenting all print lines. The problem is somewhere else. Strange... The bash script that copies-renames the file for dirwatch.py is here: http://justin.yackoski.name/winp/winp I cannot see where they put a non ascii character there. Can you? -- Vesa-Matti Sarenius, M.Sc. * * * * * * * * * * * * * * * * * mailto:sarenius at koivu.oulu.fi * Music seems to help the pain * Lecturer, mathematics education * R.I.P. Syd, my hero * University of Oulu, Finland * * * * * * * * * * * * * * * * * From google at mrabarnett.plus.com Thu May 8 14:04:29 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 8 May 2008 11:04:29 -0700 (PDT) Subject: slicing lists References: Message-ID: <9cbadcb0-d452-419b-b04e-4142a055435b@p25g2000hsf.googlegroups.com> On May 8, 4:34 am, Yves Dorfsman wrote: > Miles wrote: > > On Wed, May 7, 2008 at 7:46 PM, Ivan Illarionov > > > > Is there a way to do: > > > > x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] > > > > x[0,2:6] > > > > > That would return: > > > > [0, 3, 4, 5, 6] > > Arg... Yes, this is a typo, I meant: > [1, 3, 4, 5, 6] > > > I think Yves meant to return [1, 3, 4, 5, 6], as in Perl's list slicing: > > > my @x = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10); > > return @x[0, 2..6]; // returns (1, 3, 4, 5, 6) > > Yes, exactly. > > > > > This isn't incredibly efficient, but it does what you want (I think): > > > from itertools import chain > > > class multisliceable(list): > > def __getitem__(self, slices): > > if isinstance(slices, (slice, int, long)): > > return list.__getitem__(self, slices) > > else: > > return list(chain(*[list.__getitem__(self, s) if isinstance(s, slice) > > else [list.__getitem__(self, s)] for s in slices])) > > > p = open('/etc/passwd') > > q = [multisliceable(e.strip().split(':'))[0,2:] for e in p] > > So would it be a worthy addition to python, to add it right in the core of > the language, and hopefully in an efficient manner ? > > That would certainly help some type of list comprehensions, making them more > readable, and hopefully more readable (running split once instead of twice, > or how many number of time you need it). The passwd example is just one > example I ran into, but I can see running in this problem a lot with more > complex cases. Right now I solve the passwd pb with: > > p = file('/etc/passwd').readlines() > r = [ e.strip().split(':') for e in p ] > s = [ e[0:1] + e[2:] for e in r ] > > Or: > > p = file('/etc/passwd').readlines() > s = [ e.strip().split(':')[0:1] + e.strip().split(':')[2:] for e in p ] > > In the first case we're looping twice (two list comprehension), in the > second case we're running the split twice on every element of p. > You should've read the thread entitled "Why don't generators execute until first yield?"! :-) Michael Torrie gave the URL http://www.dabeaz.com/generators/Generators.pdf. Your example can be rewritten as follows: p = file('/etc/passwd') # No need for readlines() because file's iterator yields the lines. r = ( e.strip().split(':') for e in p ) # A generator expression instead of a list comprehension. s = [ e[0:1] + e[2:] for e in r ] From deets at nospam.web.de Sun May 25 07:42:59 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 25 May 2008 13:42:59 +0200 Subject: need some help in serving static files inside a wsgi apps In-Reply-To: References: <6e15240b-520d-4f01-9d21-83f9feeefc2d@x41g2000hsb.googlegroups.com> <69qmhcF33pou1U1@mid.uni-berlin.de> <48382917$0$20800$426a74cc@news.free.fr> <69r113F34rbeeU1@mid.uni-berlin.de> Message-ID: <69t1m5F33b3ncU2@mid.uni-berlin.de> Sebastian 'lunar' Wiesner schrieb: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > [ Diez B. Roggisch ] >>> I finally managed to work with static files with a little hack, but it's >>> ugly because I'm reading each static file per request. >> How else should that work? Apache does that the same way. > > I guess, Apache does some kind of memory caching for files, which are often > requested and small enough to fit into the system memory. May be, that's > what the OP is referring to ... I'm not aware of that, and I even more seriously doubt it. Because caching is a complicated, domain-dependend subject that would *immediately* cry for configuration - e.g. caching strategies and such. And a common idiom for apache & caching is to use Squid as reverse proxy. Which wouldn't be the case would apache cache by itself. Diez From daveparker at flamingthunder.com Thu May 29 19:11:07 2008 From: daveparker at flamingthunder.com (Dave Parker) Date: Thu, 29 May 2008 16:11:07 -0700 (PDT) Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <94bac166-d13c-44dd-af84-db19e19488b8@w1g2000prd.googlegroups.com> <8cfd3523-8d16-40bc-b904-94a6a36a414d@p25g2000pri.googlegroups.com> <5c98049e-e62e-4ab1-afed-b0a3e186bd05@w1g2000prd.googlegroups.com> <3dd6fa95-e9fe-4922-a46d-020cf9263469@w4g2000prd.googlegroups.com> Message-ID: Dan Upton wrote: > I just think if you're shooting for an easily understandable > language, overloading error handling requires more thought on the > programmer's part, not less, because they have to reason about all > outcomes Duncan Booth wrote: > Maybe FT should do something similar: > Writeline value of (set x to "hello world". Result is x.). I like the "value of" syntax. You guys have convinced me to reconsider overloading the error handling. Thank you both. From malaclypse2 at gmail.com Thu May 8 22:31:06 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Thu, 8 May 2008 22:31:06 -0400 Subject: anagram finder / dict mapping question In-Reply-To: <16651e80805081930o6a240199q69dd1c3e469d45c1@mail.gmail.com> References: <16651e80805081930o6a240199q69dd1c3e469d45c1@mail.gmail.com> Message-ID: <16651e80805081931i7fd43798t47bc8fe977b23a67@mail.gmail.com> On Thu, May 8, 2008 at 7:52 PM, dave wrote: > I got it! Thanks for all your help!!! Please tell me what you think: Here's yet another version of the same thing, using defaultdicts and sets. This way we don't have to test for membership in either the dictionary or the collection of anagrams. The code is shorter, but no less readable in my opinion. from collections import defaultdict def anafind(words): """ Given a sequence of words, return a dictionary with groups of letters as keys and sets of anagrams as values """ anagrams = defaultdict(set) for word in words: key = ''.join(sorted(word)) anagrams[key].add(word) return anagrams if __name__ == "__main__": wordlist = ['live', 'evil', 'one', 'nose', 'vile', 'neo'] anagrams = anafind(wordlist) for letters, words in anagrams.items(): print "%s: %s" % (letters, words) -- Jerry From flossy at bobbsey_twins.com Sat May 10 23:23:53 2008 From: flossy at bobbsey_twins.com (MooJoo) Date: Sat, 10 May 2008 20:23:53 -0700 Subject: Prettyprinting SQL statements Message-ID: I'm building a Python app that will be making queries to a MySQL server using the MySQLdb module. The app will need to create SQL statements on the fly which, in addition to going to the server, will occasionally need to be displayed to the user. While these queries are not too complex, they still can be difficult to decipher without doing some formatting. I've done the requisite Googling to see if a library to format SQL can be found but, other than commericial Windows apps and some on-line formatters, I've not found anything remotely usable. Before trying to write my own parser/formatter, I was hoping somebody might know of a package to perform this function. Anybody? Ferris? Anybody at all? Thanks. From ptmcg at austin.rr.com Wed May 28 09:45:19 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Wed, 28 May 2008 06:45:19 -0700 (PDT) Subject: multi dimensional dictionary References: Message-ID: On May 28, 3:11?am, Peter Otten <__pete... at web.de> wrote: > Gary Herron wrote: > > Alok Kumar wrote: > >> Dear All, > > >> I am using dictionary for filling my xpath parsed data. > > >> I wanted to use in the following manner. > > >> mydict[index] ["key1"] ["key2"] ? ?#Can someone help me with right > >> declaration. > > >> So that I can fill my XML xpath parsed data > > >> mydict[0] ["person"] ["setTime"] = "12:09:30" > >> mydict[0] ["person"] ["clrTime"] = "22:09:30" > > [I didn't see the original post] > > >>> from collections import defaultdict > >>> def make_inner(): > > ... ? ? return defaultdict(lambda: defaultdict(make_inner)) > ...>>> mydict = make_inner() > >>> mydict[0]["person"]["setTime"] = "12:09:30" > >>> mydict[0]["person"]["shoes"]["color"] = "bright yellow" > >>> mydict > When this has come up in previous threads, I think this was the best solution that was proposed: from collections import defaultdict class recursivedefaultdict(defaultdict): def __init__(self): self.default_factory = type(self) Here is this recursivedefaultdict in action: data = [ ('A','B','Z',1), ('A','C','Y',2), ('A','C','X',3), ('B','A','W',4), ('B','B','V',5), ('B','B','U',6), ('B','D','T',7), ] table = recursivedefaultdict() for k1,k2,k3,v in data: table[k1][k2][k3] = v for kk in sorted(table.keys()): print "-",kk for jj in sorted(table[kk].keys()): print " -",jj for ii in sorted(table[kk][jj].keys()): print " -",ii,table[kk][jj][ii] Prints: - A - B - Z 1 - C - X 3 - Y 2 - B - A - W 4 - B - U 6 - V 5 - D - T 7 -- Paul From n00m at narod.ru Mon May 5 07:34:18 2008 From: n00m at narod.ru (n00m) Date: Mon, 5 May 2008 04:34:18 -0700 (PDT) Subject: How to pass a multiline arg to exec('some.exe arg')? References: <7b6965a2-193d-42cf-8fad-2ad97c8de27b@i76g2000hsf.googlegroups.com> Message-ID: <95445d33-218f-42de-9412-067229c20830@d45g2000hsc.googlegroups.com> actually, it's this doesn't work (again, in VBS the "same" construction works properly): f = os.popen('osql -E -S(local) -dpubs -w800 -Q"' + query + '"', 'r') res=f.readlines() ======= here "query" is a multiline string like: select getdate() select 555*666 select getdate() From larzluv at hotmail.com Mon May 12 02:34:08 2008 From: larzluv at hotmail.com (Larry Hale) Date: Sun, 11 May 2008 23:34:08 -0700 (PDT) Subject: Module python-magic on/for Windows? References: <3a66adfe-3fd6-4f23-a6e8-4b219db1a3cd@x41g2000hsb.googlegroups.com> Message-ID: <2eb6f620-4aca-469e-9cdd-d6b0174da41e@8g2000hse.googlegroups.com> On May 11, 11:42 pm, Larry Hale wrote: > THANKS, AGAIN, for the reply! :) > > Okay, now I -really- feel silly... :> > > So, when I was going to try what you'd suggested, I noticed something > peculiar: I hadn't "changed" anything on my system, but now, when I > tried to "import magic" I got a missing DLL error. For a DIFFERENT > DLL! This got me to thinking... > > Turns out, when I was having "success" earlier, I was -in- the C: > \Program Files\GnuWin32\bin directory (where file.exe and related .dll > files are). > > So I added C:\Program Files\GnuWin32\bin to the (system/Windows) > PATH. Everything worked. I removed all the copious copies of the > DLL, the magic files, etc., littering my hard drive in every other > location. Still worked. > > 'Course, I don't honestly know why it didn't work with the files > copied to other locales contained in the sys/Py paths... perhaps it > was, as you mentioned, wanting the tree-structure to be the same? (I > haven't the heart to check this out fully right now... *maybe* at a > later time... ;) ) > > Yeah, I know. But HONESTLY! I could have -sworn- I'd already tried > THAT... you know, all the "obvious"/"I've been programming/working in > computers (albeit 'Windows' until lately) for ~25 years; yeah, I'm a > 'hacker'..." stuff. I -swear-! > > [EGG ON FACE] > > [SIGH] Well, I'd say "live and learn", but I'm still scratching my > head. But, 'nough of that. Thanks for your replies, Michael, and I'm > off to work _with_ the module now, then work-up my HowTo (and > experiment with making an "egg"?? ;) )... > > Caio! > -Larry :P :) > > On May 11, 11:09 pm, Michael Torrie wrote: > > > Larry Hale wrote: > > > ALSO: I've even tried putting the 4 "magic" files INTO the .egg > > > file... still no-go. :/ > > > It's often the custom of programs ported from unix to windows to use the > > dll location as a key to find the other files that are typically in > > share, or etc. GTK, for example uses ../share and ../etc from the > > location where the dlls are stored (if the dlls are in a folder called bin). > > > In this case I'd try making a folder in the Python25 folder called > > "share" and put the contents of the gnuwin32 share/file stuff in there. > > Should look something like this: > > > c:/python25/share/file/magic.mime.mgc > > c:/python25/share/file/magic > > c:/python25/share/file/magic.mgc > > c:/python25/share/file/magic.mime > > > Or, judging by a string I found in the dll itself, you might have to put > > the files here: > > > c:/progra~1/File/share/file/magic > > > Although if such a path really is hardcoded into the dll, this is > > certainly a bug, since it will fail on certain non-english windows systems. > > > Anyway, who knows. Give these options a try. UPDATE: HOORAY!!! Well, actually, was about two steps forward, one back. But I've gotten it all sorted out now! :) I added C:\Program Files\GnuWin32\bin to the system/Windows PATH. This takes care of the various required DLLs/libs. The file source (previously linked from http://hupp.org/adam/hg/python-magic/) has the man pages. I'd overlooked these as they were only modified as necessary; the "BSD" part made me think they'd be the same as the same online versions I'd already read (that were *nix specific). Obviously, I was wrong. These had the default paths to the magic* files listed; C:\Program Files\File\share\file\. If one creates said directory structure and moves/copies/unpacks the magic ("database") files THERE, then one may do: >>> import magic >>> test = magic.Magic() # <-- New Magic class instance >>> test.from_file( 'C:\\startrek.exe' ) # <-- Yeah, I have an old Star Trek game file here to test with... :) 'MS-DOS executable, MZ for MS-DOS' # <-- This is what's returned... Alternately, if one wishes to leave/place the magic files elsewhere, do like: >>> test = magic.Magic( magic_file = 'C:\\Program Files\\GnuWin32\ \share\\file\\magic' ) # <-- spec where/what the file is NOTE: Even if the "magic_file" location *is* specified, "mime = True" still works fine. (Haven't checked, but I presume the source simply tacks ".mime" to the filename automagically.) Obviously/also, one needn't specify the argument names if one uses proper argument order: magic.Magic( mime, magic_file ) :) THANKS SO MUCH, Michael, for your answers and helping me alone the way... :) Cheers, -Larry From martin at v.loewis.de Sat May 10 15:23:24 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 10 May 2008 21:23:24 +0200 Subject: Is there a PyPI API? In-Reply-To: <7acaec98-73ca-436c-b153-4d34599a5f0c@8g2000hse.googlegroups.com> References: <7acaec98-73ca-436c-b153-4d34599a5f0c@8g2000hse.googlegroups.com> Message-ID: <4825F62C.9050407@v.loewis.de> > I just can't figure out how to get the metadata, I guess. See http://wiki.python.org/moin/PyPiXmlRpc Regards, Martin From mwolffedu at gmail.com Fri May 16 16:16:24 2008 From: mwolffedu at gmail.com (lampshade) Date: Fri, 16 May 2008 13:16:24 -0700 (PDT) Subject: Arch problems--how do I build PIL to be 64 bit so it plays nicely on OS X? Message-ID: Hello, I'm using python + django to do some web design and I would really like to use the python image library as part of this. There seems to be a problem, however, with apache and mod_python being 64 bit while my python image library(PIL) is only 32 bit. Does anyone have experience with building the correct architectures so that OS X 10.5 plays nicely? I think, when it comes down to it, I just need PIL at this point to be x86_64 so that it plays with apache and mod_python. Any advice, hand-holding, or sage wisdom? From marlin_rowley at hotmail.com Fri May 16 19:21:37 2008 From: marlin_rowley at hotmail.com (Marlin Rowley) Date: Fri, 16 May 2008 18:21:37 -0500 Subject: Rearranging elements (cont..) In-Reply-To: References: Message-ID: All: Say I have an array: a = (['rrrrggggbbbbaaaa'],['rrrrggggbbbbaaaa']) How do I make it so that I now have: starting with first element (a[0]) new_arr[0] = 'r' new_arr[1] = 'g' new_arr[2] = 'b' new_arr[3] = 'a' new_arr[4] = 'r' ..... continuing "through" a[1] with the same new_arr new_arr[N] = 'r' new_arr[N+1] = 'g' .... -M _________________________________________________________________ Keep your kids safer online with Windows Live Family Safety. http://www.windowslive.com/family_safety/overview.html?ocid=TXT_TAGLM_WL_Refresh_family_safety_052008 -------------- next part -------------- An HTML attachment was scrubbed... URL: From badmuthahubbard at gmail.com Tue May 20 09:19:17 2008 From: badmuthahubbard at gmail.com (Chuckk Hubbard) Date: Tue, 20 May 2008 16:19:17 +0300 Subject: What is wrong with my Python threading? Message-ID: <8200bab70805200619o21f8b971ob6d3bb359f9080aa@mail.gmail.com> #!/usr/bin/python #why doesn't this run both threads simultaneously? #Thanks for any help. #Chuckk import threading import time def printesc(thrd): for i in range(10): time.sleep(1) print thrd, i def master(): thd1 = threading.Thread(target=printesc, args=(1,)) thd2 = threading.Thread(target=printesc, args=(2,)) thd1.run() thd2.run() master() From gagsl-py2 at yahoo.com.ar Tue May 27 22:08:07 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 27 May 2008 23:08:07 -0300 Subject: Misuse of list comprehensions? References: <038e4418$0$27258$c3e8da3@news.astraweb.com> <69g2bpF31ttuuU1@mid.uni-berlin.de> <69g605F2v4102U2@mid.uni-berlin.de> <027e0b24$0$26906$c3e8da3@news.astraweb.com> <3fc761710805271043k2305b96bs125e794c26fcd036@mail.gmail.com> Message-ID: En Tue, 27 May 2008 14:43:52 -0300, Ian Kelly escribi?: > It sounds like the wasteful list creation is the biggest objection to > using a list comprehension. I'm curious what people think of this > alternative, which avoids populating the list by using a generator > expression instead (apart from the fact that this is still quadratic, > which I'm aware of). > > def compress(s): > new = [] > filter(None, (new.append(c) for c in s if c not in new)) > return ''.join(new) filter returns a newly created list, so this code is as wasteful as a list comprehension (and harder to read). -- Gabriel Genellina From castironpi at gmail.com Wed May 14 14:07:37 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 14 May 2008 11:07:37 -0700 (PDT) Subject: I'm stuck in Python! References: <0563506d-bd36-404d-8961-4c4c5d1cc029@t54g2000hsg.googlegroups.com> <6a0167c3-bd87-4ddc-a161-249b7bf933c2@s50g2000hsb.googlegroups.com> <1f6bc3b5-da44-42a2-82f1-4aec5a6d31b1@c58g2000hsc.googlegroups.com> <499bc2af-6c7d-4ff4-abba-db06f4122cf9@x41g2000hsb.googlegroups.com> <0a3717f4-5992-484d-a39c-04f0d2cfec3a@m45g2000hsb.googlegroups.com> Message-ID: <4559b920-f42f-4fdb-afc7-fc6bfc1b9ff1@r66g2000hsg.googlegroups.com> On May 14, 1:06?pm, castiro... at gmail.com wrote: > On May 14, 1:02?pm, castiro... at gmail.com wrote: > > > > > > > On May 14, 12:51?pm, castiro... at gmail.com wrote: > > > > On May 14, 5:25?am, castiro... at gmail.com wrote: > > > > > On May 14, 4:32?am, castiro... at gmail.com wrote: > > > > > > On May 13, 9:55?pm, alex23 wrote: > > > > > > > On May 14, 5:41 am, "inhahe" wrote: > > > > > > > > "George Sakkis" wrote in message > > > > > > > > You must be new here. It is an AS (Artificial Stupidity) trolling bot, > > > > > > > > you can safely ignore its posts. > > > > > > > > How does it generate text? > > > > > > > My guess is by inhaling a lot of intoxicants. > > > > > > However you know what would be helpful? ?If I could go to the right > > > > > place to start the ring. > > > > > I have a slightly sinister role on stage. ?Does anyone want to play? > > > > I'd stay on mutability for the world domination factor. ?Fluent > > > currency is buoyant currency; turn on a local clock, and someone gets > > > some cubic verticals. > > > > Now if sense-reference is trading on the BDFL, I'm still holding Tron > > > can pretty well win work.- Hide quoted text - > > > > - Show quoted text - > > > I have a self-referential on Pygame: it's a Hand Tool object. > > Currently, it decays over time. ?You said 'flip' in the newsgroup, and > > 'check', 'cross', and 'mate'. ?Now who jumps who?- Hide quoted text - > > > - Show quoted text - > > If Python can plot in to chess, and Tron rings live, then why not > group it knew?- Hide quoted text - > > - Show quoted text - That would be know. Plot and split in too. From dickinsm at gmail.com Thu May 22 11:23:43 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Thu, 22 May 2008 08:23:43 -0700 (PDT) Subject: Bug in floating-point addition: is anyone else seeing this? References: <8fc0d94d-19bd-483a-8a57-8c03e47d2035@m45g2000hsb.googlegroups.com> Message-ID: <0afa8161-cc8e-4f2a-b4fb-7f2cea997fb7@59g2000hsb.googlegroups.com> On May 22, 5:09?am, Ross Ridge wrote: > Henrique Dante de Almeida ? wrote: > > > Finally (and the answer is obvious). 387 breaks the standards and > >doesn't use IEEE double precision when requested to do so. > > Actually, the 80387 and the '87 FPU in all other IA-32 processors > do use IEEE 745 double-precision arithmetic when requested to do so. > The problem is that GCC doesn't request that it do so. ?It's a long > standing problem with GCC that will probably never be fixed. ?You can > work around this problem the way the Microsoft C/C++ compiler does > by requesting that the FPU always use double-precision arithmetic. Even this isn't a perfect solution, though: for one thing, you can only change the precision used for rounding, but not the exponent range, which remains the same as for extended precision. Which means you still don't get strict IEEE 754 compliance when working with very large or very small numbers. In practice, I guess it's fairly easy to avoid the extremes of the exponent range, so this seems like a workable fix. More seriously, it looks as though libm (and hence the Python math module) might need the extended precision: on my machine there's a line in /usr/include/fpu_control.h that says #define _FPU_EXTENDED 0x300 /* libm requires double extended precision. */ Mark From benjamin.fremiot at gmail.com Mon May 12 09:13:25 2008 From: benjamin.fremiot at gmail.com (Gruik) Date: Mon, 12 May 2008 06:13:25 -0700 (PDT) Subject: Import/Create module from buffer References: <09bfaed8-8bf6-4faf-80f9-e0b97aa03127@a70g2000hsh.googlegroups.com> <48282e92$0$14346$e4fe514c@news.xs4all.nl> Message-ID: On May 12, 1:48?pm, Irmen de Jong wrote: > Gruik wrote: > > But before that 1 question: what if I'm in Python ? > > Following your solution, I did that in Python : > > > ? ? def load_buffer(buffer) : > > ? ? ? ? compiled_buffer = compile(buffer, "module_name", "exec") > > ? ? ? ? exec(compiled_buffer) > > > It works great except that I can't have a module object and that it is > > as if I did "from module import *" > > But I need the module object and not an "import *" behavior. > > Any idea about the way to do that? > > Something along the lines of: > > import new > mymodule = new.module("mymodule") > exec <<>> in mymodule.__dict__ > > --irmen Yeah it works ! exec(compiled_module, globals(), mymodule.__dict__) Just to add mymodule to sys.modules and it's good! Thanks again Benjamin From wxPythoner at gmail.com Thu May 8 18:54:42 2008 From: wxPythoner at gmail.com (wxPythoner at gmail.com) Date: Thu, 8 May 2008 15:54:42 -0700 (PDT) Subject: Mathematics in Python are not correct Message-ID: <52c855d8-5609-43e0-b98f-9fa87b2808c2@m3g2000hsc.googlegroups.com> Have a look at this: >>> -123**0 -1 The result is not correct, because every number (positive or negative) raised to the power of 0 is ALWAYS 1 (a positive number 1 that is). The problem is that Python parses -123**0 as -(123**0), not as (-123)**0. I suggest making the Python parser omit the negative sign if a negative number is raised to the power of 0. That way the result will always be a positive 1, which is the mathematically correct result. This is a rare case when the parser is fooled, but it must be fixed in order to produce the correct mathematical result. From ivan.illarionov at gmail.com Sat May 3 20:08:17 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Sun, 4 May 2008 00:08:17 +0000 (UTC) Subject: PIL JPEG mis-step References: <3e422e1b-5720-4bbd-a707-d6be51f06532@u12g2000prd.googlegroups.com> Message-ID: On Sat, 03 May 2008 17:01:44 -0700, darkblueB wrote: > On May 3, 4:52?pm, Ivan Illarionov wrote: >> Try run 'python setup.py build_ext -f' to force setup.py to rebuild >> everything with JPEG. And 'sudo python setup.py install' should install >> PIL with JPEG support. > > yes, that works > > (the self test still gives misleading results ?) but running some sample > program works fine > > thanks You're welcome. To make self test inside source directory work you probably should rebuild it inplace too. python setup.py build_ext -f -i From gagsl-py2 at yahoo.com.ar Tue May 27 11:32:26 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 27 May 2008 12:32:26 -0300 Subject: tarfile.open(mode='w:gz'|'w|gz'|..., fileobj=StringIO()) fails. References: <133193d2-a87f-4000-b70c-29fdbb36f6d0@59g2000hsb.googlegroups.com> <35552ee8-4c87-4694-b783-aa4315f3ce18@m73g2000hsh.googlegroups.com> Message-ID: En Tue, 27 May 2008 02:43:53 -0300, sebastian.noack at googlemail.com escribi?: > On May 27, 2:17 am, "Gabriel Genellina" > wrote: >> It's not a bug, you must extract the StringIO contents *after* closing >> tar_file, else you won't get the last blocks pending to be written. > > I looked at tarfile's source code last night after I wrote this > message and figured it out. But the problem is that TarFile's close > method closes the underlying file object after the last block is > written and when you close StringIO you can not get its content > anymore. Wtf does it close the underlying file? There is absolute no > reason for doing this. Are you still sure this isn't a bug? Ouch, sorry, I only tried with gzip (and worked fine), not bz2 (which is buggy). -- Gabriel Genellina From hdante at gmail.com Tue May 6 14:00:16 2008 From: hdante at gmail.com (hdante) Date: Tue, 6 May 2008 11:00:16 -0700 (PDT) Subject: generator functions in another language References: <831bea0d-ef71-4ede-9065-3111bce5225e@c65g2000hsa.googlegroups.com> <684r62F2rmn3gU2@mid.uni-berlin.de> <2e3fe05e-2918-4eeb-b67f-94d808afe0d5@d77g2000hsb.googlegroups.com> Message-ID: <2523ca17-c534-44b9-8db7-543a794dc213@e39g2000hsf.googlegroups.com> On May 6, 12:28?am, castiro... at gmail.com wrote: > > There's a process decorator to functions in a module. > > [supposes] > > @process > def datafile( processdict ): > ? ?processdict.modify( ) > ? ?op= yield > ? ?op.call( ) in processdict > ? ?# op.call( ) in namespace > > More simply: > > @process > def datafile( processdict ): > ? ?processdict.modify( ) > ? ?interaction_object= yield > ? ?invoke( interaction_object, processdict ) > ? ?#or interaction_object.invoke( **processdict ) > ? ?processdict.commit( ) > > Making each execution of process a self-modifying disk file. > Interaction_object could be binary or text. ?If text, we'd have a > cross-language executable, but I'm suspicious it wouldn't be vacuous > as a Python of Python composition: would other languages pass other > than Python programs? > > I think relational databases are the only in there. ?In other words, I > think Python would make a wholly better stored procedure and query > language than those of databases. ?Certainly I'm suspicious that's > naivete speaking up; I question, would it? ?Is there more risk of or > opportunity for malicious execution? ?Simply put, can we get > primitives in to databases? ?What's an example of a [optionally real] > operation on the primitives that doesn't map pretty well into SQL? > How do you want to write base-case scenarios if they're going to be > literals? Datafiles could be implemented with SQL. Consider SQL: SELECT * FROM process_dict where id = 1 . SELECT * FROM process_dict where id = 1 Obviously, this is all a supposition, I'm not claiming the code is perfect (or am I ?). If datafiles could be implemented with SQL and storing text requires datafiles, then I can store text with datafiles (haha !). Would you consider doing this ? One could even store python decorated serialized code using SQL [supposition]. But would it be useful [haha !] ? I don't know. From littlesweetmelon at gmail.com Fri May 16 04:46:40 2008 From: littlesweetmelon at gmail.com (=?GB2312?B?zPC5zw==?=) Date: Fri, 16 May 2008 16:46:40 +0800 Subject: Instance of class "object" Message-ID: Howdy, I wonder why below does not work. a = object() a.b = 1 # dynamic bind attribute failed... To make it correct, we have to create a new class: class MyClass(object): pass a = MyClass() a.b = 1 # OK Does this strange behavior break the LSP (Liskov substitution principle)? Regards, -- ShenLei From wuwei23 at gmail.com Tue May 27 04:15:40 2008 From: wuwei23 at gmail.com (alex23) Date: Tue, 27 May 2008 01:15:40 -0700 (PDT) Subject: Why Turn "Print" into "Print()"???? References: <248a2c45-caae-49bb-b8ff-701af8b86207@p25g2000hsf.googlegroups.com> <7927276a-6d1a-4c33-a918-aaa47b1dd32f@e53g2000hsa.googlegroups.com> Message-ID: <31d9adb0-7a0e-4e02-bc22-f6e49c4f2d17@y22g2000prd.googlegroups.com> On May 27, 5:47 pm, Sverker Nilsson wrote: > Dont make they functions. Or is this just to throw us out? Have you even bothered to read the reasoning for this change since the last time you got your knickers twisted over it? http://www.python.org/dev/peps/pep-3105/#rationale I don't see "piss everyone off" listed there anywhere. Personally, I believe if you're writing code of any serious length, you generally shouldn't be using 'print' anyway, using the logging module allows for a lot more flexibility. If you're bothered by having to type the parentheses while in the interpreter, try using IPython with it's autocall mode turned on. From daveparker at flamingthunder.com Wed May 21 15:34:36 2008 From: daveparker at flamingthunder.com (Dave Parker) Date: Wed, 21 May 2008 12:34:36 -0700 (PDT) Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <20080514215943.14c92f16.johnjsal@NOSPAMgmail.com> <94bac166-d13c-44dd-af84-db19e19488b8@w1g2000prd.googlegroups.com> <8cfd3523-8d16-40bc-b904-94a6a36a414d@p25g2000pri.googlegroups.com> <471aa7ed-3241-466c-b599-e91c38db62fa@e39g2000hsf.googlegroups.com> Message-ID: On May 21, 1:14?pm, MRAB wrote: > I wonder whether "is" could be used both for "x is value" and "x is a > type" without causing a problem: > > If command is a string ... > > If command is "quit" ... I think you are right. I like "If command is "quit" ...". For a user who wasn't mathemetically inclined and was doing mainly string manipulation, I think it might be easier to read than the equivalent "If command = "quit" ...". By making them exactly equivalent, I can't think of any confusion that might induce bugs. If you think of any drawbacks, please let me know. Otherwise, I'll put it in the next time I update the parser (probably this weekend). Thank you again for your suggestions. From giraffeboy at gmail.com Wed May 21 09:22:02 2008 From: giraffeboy at gmail.com (giraffeboy at gmail.com) Date: Wed, 21 May 2008 06:22:02 -0700 (PDT) Subject: Database Query Contains Old Data References: <33b13117-0f9f-435d-b8f8-19f1ed3a121a@d77g2000hsb.googlegroups.com> Message-ID: <4f0163cc-d943-4204-87e5-880477d6f7e0@f36g2000hsa.googlegroups.com> On May 21, 1:49 pm, "Jerry Hill" wrote: > Did you remember to commit your changes before re-running the report? > Python's DB API requires that any auto-commit feature of the > underlying database be turned off by default, so you are required to > commit changes yourself. If you're used to having auto-commit turned > on, this can be confusing. I did and I confirmed this by modifying the data, selecting it from the mysql command line client to verify the changes, then running the report again. If I exit the application and then start it again, everything works as expected until the second instance of the report is run. I have a feeling it has something to do with there already being an instance of the report class, but I can't work out how to destroy it and aren't really sure how to remove the references to it either. I added a print statement to the code and it displays a row that doesn't exist any more. Code, output of print statement and result from the mysql client shown below. Andrew Code: #Get all the mileages and add them together for the month: curs.execute('SELECT date, mileage, name FROM mileage, agents WHERE mileage.agent = agent.rowid AND date >= CAST(%s AS DATE) AND date < CAST(%s AS DATE) AND mileage.agent=%s ORDER BY date', (fromdate, todate, agentid)) for row in curs: month = str(row[0])[:7] print row[1], month Output: 100.0 2008-03 MySQL Output just prior to running the report: mysql> select * from mileage; +-------+------------+---------+---------+-------+ | rowid | date | mileage | vehicle | agent | +-------+------------+---------+---------+-------+ | 1 | 2008-04-28 | 875.63 | 3 | 3 | | 2 | 2008-04-28 | 1188.13 | 6 | 6 | | 3 | 2008-04-28 | 676.88 | 4 | 4 | | 4 | 2008-04-21 | 1111.25 | 6 | 6 | | 5 | 2008-04-21 | 1126.88 | 3 | 3 | | 6 | 2008-04-28 | 1029.38 | 7 | 8 | | 7 | 2008-04-21 | 953.13 | 7 | 8 | | 8 | 2008-04-21 | 675.63 | 4 | 4 | | 9 | 2008-04-14 | 891.88 | 3 | 3 | +-------+------------+---------+---------+-------+ 9 rows in set (0.00 sec) As you can see there's no row with a mileage of 100 with the correct month. From terry.yinzhe at gmail.com Sun May 18 19:42:05 2008 From: terry.yinzhe at gmail.com (Terry) Date: Sun, 18 May 2008 16:42:05 -0700 (PDT) Subject: Get all the instances of one class References: <29f39184-2daa-49fc-a7af-7f869fd2d688@h1g2000prh.googlegroups.com> <24267a4f-1406-42c2-bffc-f1ccd64f0218@w34g2000prm.googlegroups.com> <69b0mlF31f0kbU1@mid.uni-berlin.de> Message-ID: <507f43ce-1513-490b-b4a3-6c501e1a0169@v26g2000prm.googlegroups.com> On May 18, 11:35 pm, "Diez B. Roggisch" wrote: > Terry schrieb: > > > > > On May 17, 8:04 am, "Gabriel Genellina" > > wrote: > >> En Fri, 16 May 2008 20:44:00 -0300, Terry > >> escribi?: > > >>> Is there a simple way to get all the instances of one class? I mean > >>> without any additional change to the class. > >> Try with gc.get_referrers() > > >> py> import gc > >> py> class A(object): pass > >> ... > >> py> a,b,c = A(),A(),A() > >> py> A > >> > >> py> for item in gc.get_referrers(A): print type(item) > >> ... > >> > >> > >> > >> > >> > >> > >> > >> > > >> We need to filter that list, keeping only A's instances: > > >> py> [item for item in gc.get_referrers(A) if isinstance(item,A)] > >> [<__main__.A object at 0x00A40DC8>, <__main__.A object at 0x00A40DF0>, > >> <__main__.A object at 0x00A40E18>] > > >> -- > >> Gabriel Genellina > > > But I saw in the help that we should "Avoid using get_referrers() for > > any purpose other than debugging. " > > Yes, because using it do is very resource-consuming and shouldn't be > done. Why don't you tell us what you are after here & then we might come > up with a better solution? > > Diez I'm developing a message/state_machine based python program (I'm not using stackless, plan to move to it later). I want to collect all the state_machines (threads) and send them 'tick' message or 'quit' message. Now I'm using a static member to collect the machines, just wonderring if python already provide something like this. From deets at nospam.web.de Mon May 5 11:25:14 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 05 May 2008 17:25:14 +0200 Subject: pygame music, cant read mp3? References: <30fe7c79-dbac-47bb-9e29-bea61b7c3da8@56g2000hsm.googlegroups.com> <688af0F2pc3jjU1@mid.uni-berlin.de> <5e52e1b5-8698-4ba1-8fc2-180ba20491cb@m73g2000hsh.googlegroups.com> <0038dede-85c0-4d4d-a347-a4d23cab23ad@d45g2000hsc.googlegroups.com> Message-ID: <688n7kF2onffkU1@mid.uni-berlin.de> > directory = ['C:','Python25','myPrograms','pygameProgs','dront.mp3'] > os.path.join(directory) > > Then python can worry about the gritty details, and you don't have to. Or somewhat neater IMHO: os.path.join('C:','Python25','myPrograms','pygameProgs','dront.mp3') Diez From exarkun at divmod.com Wed May 14 06:20:05 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Wed, 14 May 2008 06:20:05 -0400 Subject: asynchat sends data on async_chat.push and .push_with_producer In-Reply-To: <575bc914-c702-42c1-a6e5-e911e68187b9@c65g2000hsa.googlegroups.com> Message-ID: <20080514102005.6859.835877135.divmod.quotient.63329@ohm> On Tue, 13 May 2008 18:20:29 -0700 (PDT), Giampaolo Rodola' wrote: >On 14 Mag, 02:56, Jean-Paul Calderone wrote: > >> Why? Isn't this why subtraction exists? If there is a call scheduled to >> happen at T1 and the current time is T2, then I know that after (T1 - T2) >> elapses, it will be time to run the call. Why do I have to do any checks >> at all? I just tell select() to wait that long. Presumably this is just >> what someone will do if they want to use asyncore with timed calls. Call >> asyncore.loop() in a loop, always passing (T1 - T2) as the timeout value. > >That doesn't work if I decide to schedule one or more calls AFTER the >loop has started (see: "I already told select what timeout use"). >As far as I've understood by reading the Twisted core what happens is >that there's a heap of scheduled calls and a loop that keeps calling >time.time() to check the scheduled functions due to expire soonest. >I've also proposed a patch for asyncore using the same approach: >http://bugs.python.org/issue1641 This isn't how it works. You're misreading the Twisted implementation. I don't know how to explain it any more clearly. Jean-Paul From regnarg at seznam.cz Sun May 11 09:17:35 2008 From: regnarg at seznam.cz (Filip =?utf-8?B?xaB0xJtkcm9uc2vDvQ==?=) Date: Sun, 11 May 2008 15:17:35 +0200 Subject: Make Python create a tuple with one element in a clean way In-Reply-To: References: Message-ID: <20080511131735.GA31145@sirius> Hello, > so it would be clean if Python would convert anything put into ( ) to > be a tuple, even if just one value was put in (without having to use > that ugly looking comma with no value after it). if it worked that way, it will absolutely mess up Python syntax, because we mathematicians are used to use parentheses to force explicit operator precedence, to group expressions, etc. Should (1+1)*2 yield 4 or (2,2) ? From ivlenin at gmail.com Sun May 25 19:30:49 2008 From: ivlenin at gmail.com (I V) Date: Sun, 25 May 2008 23:30:49 GMT Subject: which datastructure for fast sorted insert? References: <6610cad9-384d-4755-9a2c-c605329be217@8g2000hse.googlegroups.com> <69sj10F34jb08U3@mid.uni-berlin.de> Message-ID: On Sun, 25 May 2008 15:49:16 -0700, notnorwegian wrote: > i meant like set[pos], not iterate but access a specific position in the > set. If you need to access arbitrary elements, use a list instead of a set (but you'll get slower inserts). OTOH, if you just need to be able to get the next item from the set, you can use an iterator: > now i have to do: > s = toSet.pop() > toSet.add(s) i = iter(toSet) s = i.next() > if i want to get the url of the next item in a set, how would i do that? > i can do this with a list: > > def scrapeSitesX(startAddress, toList, listPos): return > scrapeSites(toList[listPos], toList, listPos+1) to use recursion with a > list. > i can work around that but it doesnt get as elegant. Do you have to use recursion here? Why not: for site in toList: scrape(site) From gagsl-py2 at yahoo.com.ar Fri May 9 01:56:12 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 09 May 2008 02:56:12 -0300 Subject: Custom Classes? References: <4dc0cfea0804300902o7493dab2m35999b5b59deace4@mail.gmail.com> <1209576920.4990.17.camel@aalcdl07.lib.unc.edu> <4dc0cfea0805011531s4574eb0bk8b6aea6ac010c881@mail.gmail.com> <1209729679.6589.23.camel@jcd-desktop> <4dc0cfea0805020638l59af4bb2o4abdcb12ee88995f@mail.gmail.com> <4dc0cfea0805080833l7fc8c711t92fdad94e2014551@mail.gmail.com> Message-ID: En Thu, 08 May 2008 12:33:55 -0300, Victor Subervi escribi?: > Okay, trying this again with everything working and no ValueError or any > other errors, here we go: > getpic = "getpic" + str(w) + ".py" Why do you *generate* the getpicNN.py? It contains always the same code, why don't you just use a single getpic.py? > and then surf to: > http://whatever.url/getpic20.py?id=6&x=1 Why don't you post the error you get instead...? Including the complete exception report. > Also, please re-send the link on how to post good questions to the list. > I cannot find it. Uhm, I don't think there is something specific for this list. There is an article from E.S.Raymond "How to ask questions the smart way?" that you can find with Google -- Gabriel Genellina From maxerickson at gmail.com Mon May 12 09:23:13 2008 From: maxerickson at gmail.com (Max Erickson) Date: Mon, 12 May 2008 13:23:13 +0000 (UTC) Subject: do you fail at FizzBuzz? simple prog test References: <39709320-66e1-40e9-a351-c769c9a94585@x41g2000hsb.googlegroups.com> <48283881@news.mel.dft.com.au> Message-ID: Arnaud Delobelle wrote: > On May 12, 1:30?pm, John Machin wrote: >> Duncan Booth wrote: > [...] >> > I think the variant I came up with is a bit clearer: >> >> > for i in range(1,101): >> > ? ?print '%s%s' % ('' if i%3 else 'Fizz', '' if i%5 else >> > 'Buzz') or > i >> >> More than a bit clearer, IMO. How about >> ? ? ?print ('' if i%3 else 'Fizz') + ('' if i%5 else 'Buzz') or >> i (or perhaps >> ? ? ?print (('' if i%3 else 'Fizz') + ('' if i%5 else 'Buzz')) >> or i to save looking up the precedence rules) ? > > Stuff clarity! How about > > for i in xrange(1, 101): > print 'FizzBuzz'[4*(i%3>0):4+4*(i%5<1)] or i > > -- > Arnaud > > -- > http://mail.python.org/mailman/listinfo/python-list > > With no loop: i=1 exec"print'FizzBuzz'[4*(i%3>0):4+4*(i%5<1)]or i;i+=1;"*100 max From kuratkull at kuratkull.com Mon May 19 05:54:14 2008 From: kuratkull at kuratkull.com (kuratkull at kuratkull.com) Date: Mon, 19 May 2008 02:54:14 -0700 (PDT) Subject: "Disabling" raw string to print newlines Message-ID: <7f63b5e9-e0d6-4505-9707-b13b70fe61c0@27g2000hsf.googlegroups.com> Hello, *************** import urllib2 import re import string import sys url = "http://www.macgyver.com/" request = urllib2.Request(url) opener = urllib2.build_opener() html = opener.open(request).read() match = re.compile("
(.+)
", re.DOTALL) out = match.findall(html) print out ************** I would like to print out string with formatting, but as I read, the string is made into a raw string when using re. How could I disable or bypass this? I googled for an hour and couldn't find a solution. Thank you in advance. From Randy.Galbraith at gmail.com Sat May 10 23:41:00 2008 From: Randy.Galbraith at gmail.com (Randy Galbraith) Date: Sat, 10 May 2008 20:41:00 -0700 (PDT) Subject: Compiling Python 2.5.2 on AIX 5.2 References: <0b73e8e5-c301-4823-ac94-42f757456cf1@x19g2000prg.googlegroups.com> <48059DA9.5080900@v.loewis.de> <480c2364$0$26788$9b622d9e@news.freenet.de> <480e2bbc$0$24477$9b622d9e@news.freenet.de> Message-ID: <9140d58c-9034-4a67-9d93-9a0b09089898@s33g2000pri.googlegroups.com> On Apr 22, 11:17 am, "Martin v. L?wis" wrote: > > test test_mmap crashed -- : [Errno > > 22] Invalid argument > > You should run this with -v. This is too little detail to know what > exactly failed. Sorry it took so long to get back to you. At this point, I'm going to attempt to use python on AIX 5.2 even with the mmap and wait4 failures. My main requirement running Mercurial SCM, so hopefully the python binary I have will do the job. Nonetheless, I wanted to quickly dump out the expanded results you suggested might help. Running this: ./python Lib/test/test_mmap.py -v Resulted in this: --results-- Position of foo: 1.0 pages Length of file: 2.0 pages Contents of byte 0: '\x00' Contents of first 3 bytes: '\x00\x00\x00' Modifying file's content... Contents of byte 0: '3' Contents of first 3 bytes: '3\x00\x00' Contents of second page: '\x00foobar\x00' Regex match on mmap (page start, length of match): 1.0 6 Seek to zeroth byte Seek to 42nd byte Seek to last byte Try to seek to negative position... Try to seek beyond end of mmap... Try to seek to negative position... Attempting resize() Creating 10 byte test data file. Opening mmap with access=ACCESS_READ Ensuring that readonly mmap can't be slice assigned. Ensuring that readonly mmap can't be item assigned. Ensuring that readonly mmap can't be write() to. Ensuring that readonly mmap can't be write_byte() to. Ensuring that readonly mmap can't be resized. Opening mmap with size too big Opening mmap with access=ACCESS_WRITE Modifying write-through memory map. Opening mmap with access=ACCESS_COPY Modifying copy-on-write memory map. Traceback (most recent call last): File "Lib/test/test_mmap.py", line 393, in test_both() File "Lib/test/test_mmap.py", line 247, in test_both m.flush() EnvironmentError: [Errno 22] Invalid argument --end results-- btw I'm not sure if -v was required in this direct run. Running w/o - v gave the same results. Now, over to wait4. Your comment was: > That suggests a bug in wait4: apparently, it fails to correctly return > the PID. Could be an OS bug, but more likely, it's a type problem in > Modules/posixmodule.c. Running this: ./python Lib/test/test_wait4.py Resulted in this: --results-- test_wait (__main__.Wait4Test) ... FAIL ====================================================================== FAIL: test_wait (__main__.Wait4Test) ---------------------------------------------------------------------- Traceback (most recent call last): File "/..../Python-2.5.2/Lib/test/fork_wait.py", line 75, in test_wait self.wait_impl(cpid) File "Lib/test/test_wait4.py", line 28, in wait_impl self.assertEqual(spid, cpid) AssertionError: 0 != 8417358 ---------------------------------------------------------------------- Ran 1 test in 12.066s FAILED (failures=1) Traceback (most recent call last): File "Lib/test/test_wait4.py", line 37, in test_main() File "Lib/test/test_wait4.py", line 33, in test_main run_unittest(Wait4Test) File "/..../Python-2.5.2/Lib/test/test_support.py", line 451, in run_unittest run_suite(suite, testclass) File "/..../Python-2.5.2/Lib/test/test_support.py", line 436, in run_suite raise TestFailed(err) test.test_support.TestFailed: Traceback (most recent call last): File "/..../Python-2.5.2/Lib/test/fork_wait.py", line 75, in test_wait self.wait_impl(cpid) File "Lib/test/test_wait4.py", line 28, in wait_impl self.assertEqual(spid, cpid) AssertionError: 0 != 8417358 --end results-- Thanks for taking your time to respond. It is truly appreciated at this end. Kind regards, -Randy Galbraith From jeffober at gmail.com Thu May 1 15:31:20 2008 From: jeffober at gmail.com (Jeff) Date: Thu, 1 May 2008 12:31:20 -0700 (PDT) Subject: data manipulation References: <083cef9c-6bfe-4a1f-afc0-7384c043dc6d@u12g2000prd.googlegroups.com> Message-ID: <6cb58c7d-33cb-4969-a8f5-55d285688306@k37g2000hsf.googlegroups.com> The function expects an excel file. It cannot read a plain text file. You would need to figure out a way to convert the text file data into an excel format and save it to a new file first. The proper way to handle this is to make your data processing functions expect a defined format. Then, you write importer functions for various types of files that convert the data in each file to the defined format. That way, you can support various file formats and reuse your processing functions on all of them. From aspersieman at gmail.com Thu May 8 08:53:10 2008 From: aspersieman at gmail.com (Aspersieman) Date: Thu, 08 May 2008 14:53:10 +0200 Subject: Parsing Email 'References' header. Message-ID: <4822F7B6.2000403@gmail.com> Hi I have a python script that parses email headers to extract information from them. I need to get the _last_ messageid in the 'References' field (http://cr.yp.to/immhf/thread.html) to create a threaded view of these emails (these messageid's are stored in a database). Now, I can easily access the 'References' field using the python 'email' module, but I need a regular expression to get the last messageid in the 'References' field. Here's what I have so far: rx_lastmesgid = re.compile(r"(<.+>$)") lastmesgid = "".join( filter( rx_lastmesgid.match, parentid ) ) # parentid's value is eg:"<1 at mail.gmail.com><2 at mail.gmail.com><3 at mail.gmail.com><4 at mail.gmail.com><5 at mail.gmail.com>" lastmesgid = "".join( filter( rx_lastmesgid.match, parentid ) ) I need it to return "<5 at mail.gmail.com>" Can anyone help? Thanks Nicol -- The three things to remember about Llamas: 1) They are harmless 2) They are deadly 3) They are made of lava, and thus nice to cuddle. From andre.roberge at gmail.com Sat May 24 09:22:27 2008 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Sat, 24 May 2008 06:22:27 -0700 (PDT) Subject: unittest: Calling tests in liner number order References: <84ff733a-e364-437d-9b5d-d8bb14cc692d@m73g2000hsh.googlegroups.com> Message-ID: <3300da64-ff6b-4c00-9bb4-339d44c9b204@f36g2000hsa.googlegroups.com> On May 24, 10:12 am, Roy Smith wrote: > In article > <84ff733a-e364-437d-9b5d-d8bb14cc6... at m73g2000hsh.googlegroups.com>, > John Roth wrote: > > > > Does the following patch has a chance of being introduced in the > > > standard python distribution? > > > I certainly hope not! > > I think you're being overly negative here. Antoon went to the trouble to > read the sources and post a diff. At the very least, he deserves a more > polite response. > > But, more than that, I think Antoon's idea has some merit. I understand > that the mantra in unit testing is that the tests should be able to be run > in any order. Still, it's the job of a library package to make it easy to > do things, not to enforce policy. If somebody (for whatever reason) has a > need to run their tests in a certain order, why is it our job to make it > hard for them to do that? > > In fact, unittest.defaultTestLoader *already* sorts the tests into > alphabetical order by their name. So, if somebody wanted to get the tests > run in order, they could just name their tests "test0001", "test0002", etc. > In fact, I've done that in the past when I had some (long forgotten) reason > why I wanted to run a bunch of things in order. Allowing the tests to be > sorted by line number order instead of by name just makes it a little > easier to do the same thing. > > If somebody wants that functionality, and is willing to put in the effort > to write the code to do it, and contribute that back to the community, I > don't see any reason why it shouldn't be considered. It would have to be > done in a way that doesn't change the current behavior (perhaps by shipping > a subclass of TestLoader which users could use instead of the default). > I'm not saying that we *need* to include it, just that it's not such a bad > idea that it deserves responses like "I certainly hope not!" I totally agree. I can't relate to anyone that want to oppose a change that would give more freedom to a programmer. Andr? From lists at cheimes.de Tue May 6 18:54:25 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 07 May 2008 00:54:25 +0200 Subject: open filename with spaces in path In-Reply-To: References: Message-ID: <4820E1A1.6050406@cheimes.de> Michael Robertson schrieb: > I'm having trouble opening a file in linux, whose path has spaces in it. > > $ mkdir my\ test > $ echo test > my\ test/test.txt > $ python > >>>> open('./my test/test.txt') > Exception Works for me >>> open('./my test/test.txt') Christian From bignose+hates-spam at benfinney.id.au Thu May 15 06:04:16 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 15 May 2008 20:04:16 +1000 Subject: named tuple mutability References: <844dc74c-1812-4599-934e-8fb63878b5cf@p25g2000hsf.googlegroups.com> <873aokzgs9.fsf@benfinney.id.au> <482be615$0$10798$426a34cc@news.free.fr> Message-ID: <87zlqrx4rj.fsf@benfinney.id.au> Bruno Desthuilliers writes: > May we agree to disagree here - unless we don't ? Absolutely not, except where not applicable. -- \ "I always wanted to be somebody. I see now that I should have | `\ been more specific." -- Lily Tomlin | _o__) | Ben Finney From szrRE at szromanMO.comVE Sat May 31 14:36:54 2008 From: szrRE at szromanMO.comVE (szr) Date: Sat, 31 May 2008 11:36:54 -0700 Subject: The Importance of Terminology's Quality References: <4840ab73$0$90274$14726298@news.sunsite.dk> Message-ID: J?rgen Exner wrote: > "szr" wrote: >> I would rather have the OP comment about that, as he started the >> thread. > > The OP is a very well-known troll who has the habit of spitting out a > borderline OT article to a bunch of loosly related NGs ever so often > and then sits back and enjoys the complaints and counter-complaints > of the regulars. While I agree cross-posting should be chosen more carefully, it seemed like a harmless article to me. I did not get the impression he was just trolling. There are people who like to post articles they come across and maybe want to start a discussion on. Like I said, this may have been better to put in a more general programming group, and that yes, it is kind of OT for specific language groups, but I really saw no harm in it (and I saw no one try to redirect the discussion to a more general group), and you and anyone else are free to ignore the thread. All I ask is you allow people to make up their own minds. -- szr From rhamph at gmail.com Tue May 20 14:37:42 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Tue, 20 May 2008 11:37:42 -0700 (PDT) Subject: conventions/requirements for 'is' vs '==', 'not vs '!=', etc References: <4dc24f2e-04f5-4ad6-b021-f416ef5c7415@z72g2000hsb.googlegroups.com><8ebd28f1-887f-45c9-a35f-af9023b062ea@u12g2000prd.googlegroups.com><3629843a-ebcb-4f15-82f1-899500f7b91f@t54g2000hsg.googlegroups.com><20080519234214.beae9314.johnjsal@NOSPAMgmail.com> Message-ID: On May 20, 12:09 pm, "Terry Reedy" wrote: > Intern() is gone in 3.0 But not gone far: >>> import sys >>> sys.intern From grante at visi.com Sat May 10 23:36:36 2008 From: grante at visi.com (Grant Edwards) Date: Sat, 10 May 2008 22:36:36 -0500 Subject: do you fail at FizzBuzz? simple prog test References: <39709320-66e1-40e9-a351-c769c9a94585@x41g2000hsb.googlegroups.com> <482650a5$1@news.mel.dft.com.au> Message-ID: On 2008-05-11, John Machin wrote: >> "Write a program that prints the numbers from 1 to 100. But for >> multiples of three print "Fizz" instead of the number and for the >> multiples of five print "Buzz". For numbers which are multiples of >> both three and five print "FizzBuzz". >> >> for i in range(1,101): >> if i%3 == 0 and i%5 != 0: >> print "Fizz" >> elif i%5 == 0 and i%3 != 0: >> print "Buzz" >> elif i%5 == 0 and i%3 == 0: >> print "FizzBuzz" >> else: >> print i >> >> >> is there a better way than my solution? is mine ok? > > Try doing it using %3 and %5 only once each. for i in xrange(101): print (("","Fizz")[i%3==0] + ("","Buzz")[i%5==0]) or str(i) His is better though, since it's more obvious what's intended. Here's one that's less opaque for i in xrange(101): s = "" if i%3 == 0: s += "Fizz" if i%5 == 0: s += "Buzz" if s: print s else: print i There are dozens of other ways to do it. -- Grant Edwards grante Yow! ... or were you at driving the PONTIAC that visi.com HONKED at me in MIAMI last Tuesday? From pDOTpagel at helmholtz-muenchen.de Fri May 30 11:03:40 2008 From: pDOTpagel at helmholtz-muenchen.de (Philipp Pagel) Date: Fri, 30 May 2008 15:03:40 +0000 (UTC) Subject: How to covert ASCII to integer in Python? References: Message-ID: Skonieczny, Chris wrote: > YOU SHOULD REMOVE or CORRECT YOUR POST here: > http://mail.python.org/pipermail/python-list/2007-February/427841.html > > It is not true - eg. try : > a='P' # P is ASCII , isn't it ? > b=int(a) > and what you will get ? An error !!! 'P' is obviously not an ASCII representation of a number. What did you expect? The closest number by visual appearance? cu Philipp -- Dr. Philipp Pagel Lehrstuhl f. Genomorientierte Bioinformatik Technische Universit?t M?nchen http://mips.gsf.de/staff/pagel From martin at v.loewis.de Fri May 9 19:37:07 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 10 May 2008 01:37:07 +0200 Subject: PyXml In-Reply-To: References: Message-ID: <4824E023.1060803@v.loewis.de> > What's the story with PyXml? Is it stable/complete or has effort moved > elsewhere? Large parts of PyXML are now part of the standard library. When I stepped back as a maintainer, nobody volunteered to take over. > Can anyone recommend a Python validating parser that validates vs Xml > Schema? The libxml bindings for Python can do that. Regards, Martin From deets at nospam.web.de Tue May 6 06:17:54 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 06 May 2008 12:17:54 +0200 Subject: parameters to lambda's executed at run time. References: Message-ID: <68apjeF2r9b93U2@mid.uni-berlin.de> wyleu wrote: > I'm trying to supply parameters to a function that is called at a > later time as in the code below: > > llist = [] > > for item in range(5): > llist.append(lambda: func(item)) > > def func(item): > print item > > for thing in llist: > thing() > > which produces the result > > IDLE 1.2.1 >>>> ================================ RESTART >>>> ================================ >>>> > at 0xb716356c> > at 0xb71635a4> > at 0xb71635dc> > at 0xb7163614> > at 0xb716364c> >>>> ================================ RESTART >>>> ================================ >>>> > 4 > 4 > 4 > 4 > 4 >>>> > > How can one allocate a different parameter to each instance of the > function rather than all of them getting the final value of the loop? That's a FAQ. Python creates a closure for you that will retain the last value bound. To prevent that, you need to create a named paramter like this: lambda item=item: func(item) That will bind the current item value at the lambda creation time. Diez From info at thegrantinstitute.com Fri May 16 01:38:53 2008 From: info at thegrantinstitute.com (Anthony Jones) Date: 15 May 2008 22:38:53 -0700 Subject: Professional Grant Proposal Writing Workshop (August 2008: Boston, Massachusetts - University of Phoenix Campus) Message-ID: <20080515223853.D27E5C5D92CAB5F9@thegrantinstitute.com> An HTML attachment was scrubbed... URL: From manuhack at gmail.com Fri May 16 18:37:11 2008 From: manuhack at gmail.com (Manu Hack) Date: Fri, 16 May 2008 18:37:11 -0400 Subject: Rpy Module In-Reply-To: <4cbbf8ef-f123-47cd-b265-4d91925efa10@e39g2000hsf.googlegroups.com> References: <4cbbf8ef-f123-47cd-b265-4d91925efa10@e39g2000hsf.googlegroups.com> Message-ID: <50af02ed0805161537q26c9ae52oa9c778263d5d5fa1@mail.gmail.com> On Fri, May 16, 2008 at 6:14 PM, Mike P wrote: > Hi experts, > > I've just seen there is an R module, what i can't see easily is if you > can / how to import other modules for R into the Rpy module > > Can anyone advise on this? Say if you want to use Hmisc within rpy, import rpy rpy.r.library('Hmisc') Manu -------------- next part -------------- An HTML attachment was scrubbed... URL: From devphyl at gmail.com Tue May 13 06:04:06 2008 From: devphyl at gmail.com (alefajnie) Date: Tue, 13 May 2008 03:04:06 -0700 (PDT) Subject: array in class Message-ID: <3f2b8a18-8f5b-4188-acb7-660d73574027@m44g2000hsc.googlegroups.com> class A: this_is_original_variable_only_for_one_inctance = 0 def __init__(self, v): self.this_is_original_variable_only_for_one_inctance = v class B: this_is_common_for_all_instances = [] def __init__(self, v): self.this_is_common_for_all_instances.append(v) ---------------- now I can create some instances of B, but all of them have the same array, why if I use append for b1.this_is_common_for_all_instances, the b2, b3 will have been changed that array. (where bi is instance of B) but changes on this_is_original_variable_only_for_one_inctance works fine why it does that? and how create array in class - normal array, "private variable" From johnjsal at NOSPAMgmail.com Mon May 12 23:38:52 2008 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: 13 May 2008 03:38:52 GMT Subject: Learning Python for no reason References: <0383f3b8$0$27282$c3e8da3@news.astraweb.com> Message-ID: <48290d4c$0$11631$607ed4bc@cv.net> Matthew Woodcraft wrote: > I can't tell from what you wrote whether you feel you won't have any > reason to do any programming, or whether you already know several other > programming languages and you feel you won't have any reason to use > Python in particular. Definitely the former. I've loved programming since I was in high school, but I've never really had much of a consistent use for it. But you're right, when there's something to be done that could benefit from a simple script, it's so much fun to turn to Python to do it. I think I might try to get involved in helping write the Python documentation too, so that will keep me involved. From tjreedy at udel.edu Thu May 8 13:47:45 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 8 May 2008 13:47:45 -0400 Subject: The del statement References: <02860f2a-cd1d-4b1d-ad49-08b13032ba21@2g2000hsn.googlegroups.com> Message-ID: "George Sakkis" wrote in message news:02860f2a-cd1d-4b1d-ad49-08b13032ba21 at 2g2000hsn.googlegroups.com... | One of the few Python constructs that feels less elegant than | necessary to me is the del statement. For one thing, it is overloaded | to mean three different things: | (1) del x: Remove x from the current namespace | (2) del x[i]: Equivalent to x.__delitem__(i) | (3) del x.a: Equivalent to x.__delattr__('a') (or delattr(x,'a')) Since I see del x.a as deleting a from the attribute namespace of x, I see this as the same meaning. A namespace is a specialized association (keys are identifier strings). A dict is more generalized (keys merely hashable). So ditto for del dic[key]. The only different meaning is del somelist[i]. The implicit association between counts in range(n=len(somelist)) *is* broken, but unless i == n-1, items are 'shifted down' so that some other item become associated with i, and j's for i < j < n-1 get new associations and n-1 is left with none. One could imagine del somelist[i] as simple leaving a void in the list. (Which is not to say that that would be terribly useful.) tjr From thomas.troeger.ext at siemens.com Wed May 21 06:07:12 2008 From: thomas.troeger.ext at siemens.com (Thomas Troeger) Date: Wed, 21 May 2008 12:07:12 +0200 Subject: Minimal Python installation? Message-ID: Hi, I'd like to put the python library and interpreter on a small embedded Linux x86 compatible device where disk space is an issue. I played around with the minimal Python interpreters, but was not entirely happy with them, so my question is, is there an (preferably easy) way to put the interpreter and a cut-down version of the python library/modules that ship with regular Python into a new archive that I can safely copy and use? My current method is to copy the python interpreter and the python shared library to the device. Then I create a tar archive with all startup files from the site package directory to my archive using the following one-liner: strace -f -eopen python -c 'pass' 2>&1 | grep -v ENO | grep '\.py' | awk 'BEGIN { FS="\"" } { print $2 }' | tar cvf x.tar -T - This effectively packs all python library files that are accessed upon startup into a tar archive. But I figure this method is not what I want because there surely are files I am missing here (for example which are accessed when starting a script), and what I really want is a minimal environment that works. Let's say I want a complete Python install, but without all the batteries :-) Any pointers? Regards, Thomas. From bignose+hates-spam at benfinney.id.au Mon May 5 01:16:43 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 05 May 2008 15:16:43 +1000 Subject: Truncate beginning of a file References: <1bc92095-41ab-404a-a697-088545cdddec@27g2000hsf.googlegroups.com> Message-ID: <87zlr5e3es.fsf@benfinney.id.au> s0suk3 at gmail.com writes: > file.truncate(X) will truncate the file to at most X bytes (i.e. > leave the first X bytes of the file and throw away the rest). Yes, by (IIRC) asking the filesystem to do this in a simple operation. Most (all?) filesystems support this operation either directly or with little effort. > Is there a way to throw away, say, the first X bytes of the file, > and leave the rest? (Without opening the same file for reading, > reading and processing, overwriting the file with the new processed > data, etc.) I don't know of any filesystem that supports this operation without reading the file data. The built-in 'file' type doesn't support it. -- \ "It's easy to play any musical instrument: all you have to do | `\ is touch the right key at the right time and the instrument | _o__) will play itself." -- Johann Sebastian Bach | Ben Finney From deets at nospam.web.de Tue May 20 18:13:44 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 21 May 2008 00:13:44 +0200 Subject: Processing in Python In-Reply-To: <483345f5$0$902$ba4acef3@news.orange.fr> References: <483345f5$0$902$ba4acef3@news.orange.fr> Message-ID: <69h0p9F327mqgU1@mid.uni-berlin.de> Salvatore DI DI0 schrieb: > Hello, > > The Processing Graphics language has been implemented in Javascript. No, it hasn't. Processing is written in Java. > Does anybody tried to make this in Python ? There are similar projects, yet maybe not to the same level of integration. However, pygame + PyOpenGL give you pretty much the same, and even avoid some of the limitations of processing. Diez From mal at egenix.com Fri May 30 16:48:39 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Fri, 30 May 2008 22:48:39 +0200 Subject: Python 2.5.2 on Ubuntu Hardy Utf-8-Euro error In-Reply-To: <4840657A.2000904@egenix.com> References: <4840657A.2000904@egenix.com> Message-ID: <48406827.10203@egenix.com> On 2008-05-30 22:37, M.-A. Lemburg wrote: > On 2008-05-30 17:41, Peter Otten wrote: >> Josep wrote: >> >>> I'm playing with an application framework (or kinda) that's developed >>> with python, and it throws this error: >>> >>> >>>> File >>>> "/usr/lib/python2.5/site-packages/Dabo-0.8.3-py2.5.egg/dabo/db/dCursorMixin.py", >>>> >>>> line 281, in execute >>>> sql = unicode(sql, self.Encoding) >>>> LookupError: unknown encoding: utf_8_euro >>> At the application (DABO) mailing list, they have pointed that this has >>> to be a Python issue. As I'm a totally python newbie, I would ask if >>> somebody has experimented this kind of error, and if there is any known >>> solution. I've found no clue searching at Google right now. >>> >>> My Python version is 2.5.2, Ubuntu Hardy .deb package. >> >> Python might get confused by an @EURO suffix in the locale: > > Right, that's what's happening. > > The locale module uses a locale aliasing table that help map environment > locale settings to C local names. > > That table was last updated in 2004 and since then a lot more > locale variable strings have made their way into the Linux > distros. > > I guess we need to update the table... I've opened ticket http://bugs.python.org/issue3011 for this. >> $ LANG=de_DE.UTF-8 at EURO >> $ python -c"import locale; print locale.getdefaultlocale()" >> ('de_DE', 'utf_8_euro') >> >> Try setting the LANG environment variable to something like >> >> $ LANG=de_DE.UTF-8 >> $ python -c"import locale; print locale.getdefaultlocale()" >> ('de_DE', 'UTF8') >> >> before you run your program (use ca_ES or whatever you need instead of >> de_DE). >> >> Peter >> -- >> http://mail.python.org/mailman/listinfo/python-list > -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, May 30 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From castironpi at gmail.com Sat May 17 04:33:44 2008 From: castironpi at gmail.com (castironpi) Date: Sat, 17 May 2008 01:33:44 -0700 (PDT) Subject: can't delete from a dictionary in a loop References: <95294ce6-38a0-44cd-8b0f-2bce0642886d@27g2000hsf.googlegroups.com> Message-ID: <69100481-9da1-460f-ac75-6d71e0241f9d@b1g2000hsg.googlegroups.com> On May 17, 3:06?am, George Sakkis wrote: > On May 16, 5:22?pm, "Dan Upton" wrote: > > > > > > > This might be more information than necessary, but it's the best way I > > can think of to describe the question without being too vague. > > > The task: > > > I have a list of processes (well, strings to execute said processes) > > and I want to, roughly, keep some number N running at a time. ?If one > > terminates, I want to start the next one in the list, or otherwise, > > just wait. > > > The attempted solution: > > > Using subprocess, I Popen the next executable in the list, and store > > it in a dictionary, with keyed on the pid: > > (outside the loop) > > procs_dict={} > > > (inside a while loop) > > process = Popen(benchmark_exstring[num_started], shell=true) > > procs_dict[process.pid]=process > > > Then I sleep for a while, then loop through the dictionary to see > > what's terminated. ?For each one that has terminated, I decrement a > > counter so I know how many to start next time, and then try to remove > > the record from the dictionary (since there's no reason to keep > > polling it since I know it's terminated). ?Roughly: > > > for pid in procs_dict: > > ? if procs_dict[pid].poll() != None > > ? ?# do the counter updates > > ? ?del procs_dict[pid] > > Since you don't look up processes by pid, you don't need a dictionary > here. A cleaner and efficient solution is use a deque to pop processes > from one end and push them to the other if still alive, something like > this: > > from collections import deque > > processes = deque() > # start processes and put them in the queue > > while processes: > ? ? for i in xrange(len(processes)): > ? ? ? ? p = processes.pop() > ? ? ? ? if p.poll() is None: # not finished yet > ? ? ? ? ? ? processes.append_left(p) > ? ? time.sleep(5) > > HTH, > George- Hide quoted text - > > - Show quoted text - No underscore in appendleft. From maxm at mxm.dk Sun May 11 07:39:21 2008 From: maxm at mxm.dk (Max M) Date: Sun, 11 May 2008 13:39:21 +0200 Subject: Mathematics in Python are not correct In-Reply-To: References: <52c855d8-5609-43e0-b98f-9fa87b2808c2@m3g2000hsc.googlegroups.com><200805081914.06459.kyrie@uh.cu> Message-ID: wxPythoner at gmail.com skrev: > I have two another interesting things to discuss about, for which I'll > open new posts on this group. Look for "Python doesn't recognize quote > types" and "Python, are you ill?". You have a tendency to form your questions as complaints about Python being broken. You will probably get better responses if you just state that there are things you do not understand, and ask why it works that way. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From mbelzile at softimage.com Thu May 15 16:32:12 2008 From: mbelzile at softimage.com (=?iso-8859-1?Q?Marc-Andr=E9_Belzile?=) Date: Thu, 15 May 2008 16:32:12 -0400 Subject: Building python 2.5 fails on linux 64 In-Reply-To: <0BCB4AE868D8934A8B3DCE3A58126A8902151190@tewk-mbpf3> References: <0BCB4AE868D8934A8B3DCE3A58126A8902151190@tewk-mbpf3> Message-ID: <0BCB4AE868D8934A8B3DCE3A58126A89021513B3@tewk-mbpf3> So I tried with 2.6a3 and 3.0 and I ended up with the same error, but python 2.5.2 works though. Seems like something is missing from the build instructions for the newer versions I guess. -mab ________________________________ From: python-list-bounces+mbelzile=softimage.com at python.org [mailto:python-list-bounces+mbelzile=softimage.com at python.org] On Behalf Of Marc-Andr? Belzile Sent: May-15-08 10:58 AM To: python-list at python.org Subject: Building python 2.5 fails on linux 64 Hi, I have the following error when building python 2.5 (revision 63261) ./Parser/asdl_c.py -c ./Python ./Parser/Python.asdl 'import site' failed; use -v for traceback Traceback (most recent call last): File "./Parser/asdl_c.py", line 7, in ? import os, sys, traceback ImportError: No module named os make: *** [Python/Python-ast.c] Error 1 I'm using gcc version 4.1.1 on Red Hat Enterprise Linux WS release 4 (Nahant Update 4) What could be the problem ? Thanks for helping. -mab -------------- next part -------------- An HTML attachment was scrubbed... URL: From ivarnelispam at gmail.com Mon May 19 01:28:20 2008 From: ivarnelispam at gmail.com (ivarnelispam at gmail.com) Date: Sun, 18 May 2008 22:28:20 -0700 (PDT) Subject: Organizing a Python project Message-ID: <960da03c-1edf-4fa4-b434-6656e8a8884f@e39g2000hsf.googlegroups.com> Hello all, I'm starting work on what is going to become a fairly substantial Python project, and I'm trying to find the best way to organize everything. The project will consist of: - A few applications - Several small scripts and utilities - Unit tests and small interactive test programs - A number of custom libraries and modules that may be shared and referenced among all of the above I have the following general structure in mind: myproject/ app1/ main.py file1.py file2.py tests/ test_abc.py test_xyz.py app2/ ... scripts/ script1.py script2.py shared/ mylib1/ file1.py file2.py tests/ test_foo.py test_bar.py mylib2/ ... The files that you might want to execute directly are: - Any of the "main.py" files under app*/ - Any of the files under shared/ - Any of the files under app*/tests or shared/mylib*/tests So, my questions: First of all, does this look like a reasonable overall structure, or are there better alternatives? Second (and the thing I'm primarily interested in), what is the best way to deal with importing the shared modules in the applications, scripts, test programs, and possibly other shared modules? I think the most obvious solution is to add /path/to/myproject to PYTHONPATH. However, this seems like an annoying little dependency that you are likely to forget whenever you move your workspace to a new path, open up a branch of the project in a different directory, or download and work on the project using a different computer. Is there a way to set this up that is a bit more self contained? For example, at first I was somewhat hopeful that Python could ascend parent directories until it reached a directory that did not include an __init__.py file, and it could use this as a root for referring to packages and modules from any file contained within. (e.g. in the example project above, any file could refer to myproject.shared.mylib1 so long as 'myproject' and all subdirectories contained an __init__.py, and the parent of 'myproject' didn't contain such a file). Evidently this is not the case, but it seems like it could be a useful feature in these situations. Anyway, I'm sure this is not an unusual situation, so I'm curious to hear how other people have handled it. (Note - don't remove 'spam' from my e-mail address when replying. The address is correct as listed) Thanks! Kevin From hniksic at xemacs.org Wed May 14 03:01:47 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Wed, 14 May 2008 09:01:47 +0200 Subject: list.__len__() or len(list) References: Message-ID: <87r6c5s71g.fsf@mulj.homelinux.net> "Ian Kelly" writes: > On Tue, May 13, 2008 at 5:57 PM, Nikhil wrote: >> __len__() is a built-in function of the list object and is updated along >> with the list object elements and will be useful incase the list is very >> huge. >> >> len() is an external method again, which may require the processing cycles >> again. > > The purpose of obj.__len__() is to implement len(obj), which simply > calls it. So obj.__len__() may be faster, but only marginally. Have you tried it? __len__ is in fact marginally slower because it involves a dict lookup, whereas the built-in len() knows how to cheat and invoke __len__ through a slot in the C type struct very efficiently. $ python -m timeit -s 'l=[1, 2, 3]' 'len(l)' 1000000 loops, best of 3: 0.24 usec per loop $ python -m timeit -s 'l=[1, 2, 3]' 'l.__len__()' 1000000 loops, best of 3: 0.347 usec per loop From arnodel at googlemail.com Sat May 3 13:40:20 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sat, 03 May 2008 18:40:20 +0100 Subject: Feature suggestion: sum() ought to use a compensated summation algorithm References: Message-ID: Szabolcs Horv?t writes: [...] > A little research shows that Mathematica uses a "compensated > summation" algorithm. Indeed, using the algorithm described at > http://en.wikipedia.org/wiki/Kahan_summation_algorithm > gives us a result around ~ 10^-17: > > def compSum(arr): > s = 0.0 > c = 0.0 > for x in arr: > y = x-c > t = s+y > c = (t-s) - y > s = t > return s > > mean = compSum(data)/len(data) > print compSum(x - mean for x in data)/len(data) > > > I thought that it would be very nice if the built-in sum() function > used this algorithm by default. Has this been brought up before? > Would this have any disadvantages (apart from a slight performance > impact, but Python is a high-level language anyway ...)? > > Szabolcs Horv?t sum() works for any sequence of objects with an __add__ method, not just floats! Your algorithm is specific to floats. -- Arnaud From larry.bates at websafe.com` Tue May 20 19:51:29 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Tue, 20 May 2008 18:51:29 -0500 Subject: Misuse of list comprehensions? In-Reply-To: <038e4418$0$27258$c3e8da3@news.astraweb.com> References: <038e4418$0$27258$c3e8da3@news.astraweb.com> Message-ID: John Salerno wrote: > I posted this code last night in response to another thread, and after I > posted it I got to wondering if I had misused the list comprehension. Here's > the two examples: > > Example 1: > -------------------- > def compress(s): > new = [] > > for c in s: > if c not in new: > new.append(c) > return ''.join(new) > ---------------------- > > Example 2: > ------------------------ > def compress(s): > new = [] > [new.append(c) for c in s if c not in new] > return ''.join(new) > -------------------------- > > In example 1, the intention to make an in-place change is explicit, and it's > being used as everyone expects it to be used. In example 2, however, I began > to think this might be an abuse of list comprehensions, because I'm not > assigning the result to anything (nor am I even using the result in any > way). > > What does everyone think about this? Should list comprehensions be used this > way, or should they only be used to actually create a new list that will > then be assigned to a variable/returned/etc.? > > You might use this: def compress(s) return ''.join([ u for u in s if u not in locals()['_[1]'] ]) From tjreedy at udel.edu Mon May 19 00:22:24 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 19 May 2008 00:22:24 -0400 Subject: explain this function to me, lambda confusion References: <5cc7ef7a-dd21-4772-a7e3-765410f810bb@l17g2000pri.googlegroups.com> Message-ID: "Arnaud Delobelle" wrote in message news:m2ve1b7msb.fsf at googlemail.com... | Lie writes: | | > Lambda can actually be safely removed from python and no other | > features would be missing. It is always possible to create a def | > version of any lambda, so lambda is useless. It is just a convenience | > for the times where we're just too lazy to invent a name and find a | > place to place the def, instead just inlining the function. | | Note that the same thing can be said about generator expressions, | which are nothing more than anonymous, non-reusable, generator | functions. Right. So if someone posted on genexp confusion, I would suggest 'write a full generator function'. | Instead these were _added_ to the language! As a convenience. Actually, if one uses more that one for-clause in a generator expression, there is a potential gotcha in relation to name capture. So if that bites, the genexp is not so much a convenience, and one might better write the full function. tjr From mail at timgolden.me.uk Thu May 29 08:00:59 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 29 May 2008 13:00:59 +0100 Subject: [python-win32] How to get all the variables in a python shell In-Reply-To: <483E650B.5060902@timgolden.me.uk> References: <483E650B.5060902@timgolden.me.uk> Message-ID: <483E9AFB.2040402@timgolden.me.uk> Tim Golden wrote: > lixinyi.23 at gmail.com wrote: >> I'm currently working on a scientific computation software built in >> python. >> What I want to implement is a Matlab style command window <-> >> workspace interaction. >> >> For example, you type 'a=1' in the command window, and you see a list >> item named 'a' in the workspace. >> You double click the icon of the item, and you see its value. You can >> modify the value of the list item, >> 1 -> 100 etc, after which if you go back to the command window and >> type 'a' and press enter, you see that >> varable a's value has been changed to 100. >> >> So my question is : if you have two DOS command windows running under >> WINDOWS OS, how can you make them share the same internal variable >> buffer? Or is there any easier way to implement such kind of >> interaction? > > I stronly suggest you look at IPython [1]. To do what I think > you're describing, you'd need to hack or reimplement the interpreter. > And that's what they've done. ISTR that they even have a branch > which is dealing with parallel instances. Sorry, having seen Roger D's memcached suggestion, I realise I may have misinterpreted your requirement. I thought that you wanted a Python interpreter session to share its objects to another window, hence my IPython suggestion. If you're writing your own console app and want to share stuff, then there's any number of IPC possibilities. Roger's already mentioned memcached which I've no more than a passing knowledge of. But Pyro [1] is often a good bet for these things, and the pyprocessing [2] module is gaining a fair bit of traction at the moment. (To name just two out of many). TJG [1] http://pyro.sf.net [2] http://pyprocessing.berlios.de/ From lists at cheimes.de Fri May 2 17:51:13 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 02 May 2008 23:51:13 +0200 Subject: 'property' builtin does not work for me In-Reply-To: References: Message-ID: <481B8CD1.1010001@cheimes.de> Alex Fainshtein schrieb: > As you see, getter works properly. But when assigning to property, setter is > not called, as I would expect. prop is simply replaced with whatever is > assigned and ceased being a property. properties work only for new style classes. You have to subclass your class from object in order to get a new style class: class Test(object): def getter(self): print "Getter called." return 'a' def setter(self, val): print "Setter called." prop = property(getter, setter) Christian From bruno.42.desthuilliers at websiteburo.invalid Wed May 14 06:33:34 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 14 May 2008 12:33:34 +0200 Subject: Python and Flaming Thunder In-Reply-To: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> Message-ID: <482abff7$0$11008$426a74cc@news.free.fr> Dave Parker a ?crit : (snip spam) Please stop spamming here trying to sell your dumbass proprietary basic. From basti.wiesner at gmx.net Sat May 24 18:42:00 2008 From: basti.wiesner at gmx.net (Sebastian 'lunar' Wiesner) Date: Sun, 25 May 2008 00:42:00 +0200 Subject: module import problem References: Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 [ Milos Prudek ] > If I cd into /usr/share/python-support/python-gnupginterface and launch > Python I can "import GnuPGInterface". But when I run > DistUpgradeFetcherCore.py in that folder it always fails with No module > named GnuPGInterface. > > I do not know much about setting python path. Reinstall the package "python-gnupginterface" with "sudo aptitude reinstall python-gnupginterface". This should fix the problem, unless your package management is broken. - -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) -----BEGIN PGP SIGNATURE----- Version: GnuPG v2.0.9 (GNU/Linux) iEYEARECAAYFAkg4mb0ACgkQn3IEGILecb6jpACfc80saFQz/Q6F5lYbuCUQxJt2 Z+8AoKkB+5hqm0tMmK/d1s1IjsSSCqAz =Z6/t -----END PGP SIGNATURE----- From gagsl-py2 at yahoo.com.ar Tue May 20 18:50:06 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 20 May 2008 19:50:06 -0300 Subject: python script to windows exe References: <4541e631-d38a-4047-b578-bd9afdde0af8@s50g2000hsb.googlegroups.com> <9951d859-330f-4a7a-a869-df73cdce5f67@m44g2000hsc.googlegroups.com> <1ff3349csta3dvmoau6meadkrrt239ujfv@4ax.com> <2598173e-356e-49b8-8875-00556f5cfe98@j33g2000pri.googlegroups.com> Message-ID: En Tue, 20 May 2008 04:04:13 -0300, sandeep escribi?: > thanks for ur replies. i have a bit closer look at my code and i am > able to fix the problem.now my exe is working fine.the code is bit > more cleaner now as i removed lot of unused function from it and try > to document it also. Glad to see it worked finally. Just a few comments: > #function which will initialise outlook and return its reference > def getAppRef(): > temp=win32com.client.Dispatch("OutLook.Application") > return temp.GetNamespace("MAPI") Instead of a comment, use a docstring def getAppRef(): """Initialise outlook and return its reference.""" ... > abc=os.path.isdir(os.getcwd()+'\email') > if(abc==True): > print 'directory exists' > else: > os.mkdir(os.getcwd()+'\email') > path=os.path.abspath(os.getcwd()+'\email') > atmt.SaveAsFile(path+"\\"+atmt.DisplayName) Use '\\email' instead, or r'\email'. \ is the escape character, '\temp' actually isn't what you may think. The rules: Anyway, it's much better to use os.path.join to build a path: email_dir = os.path.abspath(os.path.join(os.getcwd(), 'email')) abc = os.path.isdir(email_dir) if abc: print 'directory exists' else: os.mkdir(email_dir) atmt.SaveAsFile(os.path.join(email_dir, atmt.DisplayName)) > # function to check whether the character encoding is ascii or smthing > else > def checkStringType(a): > if isinstance(a,str): > b='not a unicode string' > else: > a.encode('utf-8') > #print 'unicode type' > return a This function does not perform what the comment says. The b='...' is useless, and the a.encode(...) line *returns* a string (which is immediately discarded) - it does not modify `a`, strings in Python are immutable. -- Gabriel Genellina From skanemupp at yahoo.se Fri May 16 15:17:50 2008 From: skanemupp at yahoo.se (globalrev) Date: Fri, 16 May 2008 12:17:50 -0700 (PDT) Subject: save dictionary for later use? Message-ID: <99403e9d-4c67-4e3f-a726-7bb02e72423a@m3g2000hsc.googlegroups.com> i extract info from one file and put it into a dictionary. i want to save that dictionary for later use, how do i do that? might save a list of dictionaries or a list of classobjects too if there is any difference. From rajarshi.guha at gmail.com Tue May 13 13:10:23 2008 From: rajarshi.guha at gmail.com (Rajarshi) Date: Tue, 13 May 2008 10:10:23 -0700 (PDT) Subject: usage of python Message-ID: Hi, I teach an introductory programming course in Python. As part of the introduction I'd like to highlight the usage of Python in industry. The idea is to show that there are big players using Python for a variety of tasks. Given that the students come from a variety of backgrounds and are not necessarily 'hackers', I'm trying to look for examples with a bit of wow-factor. Is there any list with people/groups/companies using Python for impressive things? Any pointers would be appreciated Thanks, Rajarshi From lists at cheimes.de Mon May 5 15:46:20 2008 From: lists at cheimes.de (Christian Heimes) Date: Mon, 05 May 2008 21:46:20 +0200 Subject: Visual Studio 6 compile of 2.5.2 fails with missing db.h In-Reply-To: <1f1a09ff-5800-4ecb-ac9f-f2604454edfb@q1g2000prf.googlegroups.com> References: <1f1a09ff-5800-4ecb-ac9f-f2604454edfb@q1g2000prf.googlegroups.com> Message-ID: brucoder schrieb: > Any pointers? A prerequisite that I might be missing? The source is > the Python-2.5.2.tar.gz from the Python.org site. The tar.gz doesn't contain the dependencies like the bsddb files or sqlite3, bzip2 and more. You have to download and unpack the correct versions into the correct folder. Please read PCbuild/readme.txt Christian From bbxx789_05ss at yahoo.com Sun May 11 16:30:02 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Sun, 11 May 2008 13:30:02 -0700 (PDT) Subject: File Creation Not Working In A Thread Class? References: <7qGVj.32505$KJ1.18416@newsfe19.lga> Message-ID: <8878fece-434c-44e0-9386-dc79d376819b@z72g2000hsb.googlegroups.com> On May 11, 2:11?pm, bc90021 wrote: > [CUT] > > > I have in no way assumed that you are stupid. ?I have tried to help you > > formulate your problem better so that people on the list can help you. > > I believe I have done so respectfully, with the aim of introducing you > > to the modus operandi of this group. > > I appreciate your help. ?However, the comments I got from other people > that "I'm sure you have quotes here..." type comments are incredibly > insulting. ?To tell someone that you're sure that they have quotes around > something when they don't is the height of arrogance and rudeness. > The best way to get help is to post a simple example that demonstrates your problem and that anyone can run and get the same error you are getting. That means you need take your real code and you start hacking out the bits that are irrelevant to the problem. With judicious use of print statements you should be able to narrow the problem down. Your first post was about as far away from that as it could be. Your first post was essentially equivalent to asking: > Why does this line: >print name >display "Jack" and not "Jill". When you post a question like that, then you are either going to be met with silence or people will attempt to debug your imaginary code and guess at the problem, which sometimes works and sometimes doesn't. If you find the guesses insulting, then post a better model of your problem. The fact that you found these guesses insulting, even though they were respectfully given and they were the obvious answers in light of how little information you gave, means you are probably going to have problems on any newsgroup you post to. The python community has some real jerks in it, but you didn't meet any of them in this thread. > >> (I really must say that so far the help I am getting in the Python > >> community is a big let down. ?Whether it's on IRC or here, everyone has > >> an arrogance that I don't find anywhere else in the open source > >> community, and it seriously makes me question the choice of language > >> that I've made.) > > > Don't judge too quickly. ?I think this newsgroup is on the whole > > extremely helpful. ?I have learnt a lot from it. ?But you have to get > > used to its ways, and until you are familiar with them, approach it with > > humility. > > Unfortunately, this is not my first interaction with the Python IRC > communities or Python newsgroups. ?I had tried working with this language > a while back (around 2000) and the answers I got were unhelpful and > usually rude. ?I decided to give it another shot for the program I'm > writing, and I'm regretting that. ?It's possible that I'm to blame - I'm > the common factor in both instances, but at the same time, when you ask a > question in #python and NO ONE ANSWERS at all, and they all just sit > there not talking at all, what's the point of having the IRC channel? ?If > newbies can't go there for help, what's the point? ?When there are 70 > people in a channel, and no one even acknowledges your question has been > asked, where does one go for help? ?It's like talking to yourself. > > >> The error message was at the top of the thread (am I incapable of > >> posting it, or are you incapable of following a thread?), but here it > >> is again: > > >> IOError: [Errno 2] no such file u'tempfileName' > > > This is different from the error message that you posted in your > > original message. > > > Anyway, what is useful to us is a full traceback, no just an error > > message. > > It is not "different" except that I posted the full name the second > time. ?(tempfileName instead of the previously simplified fileName) ?The > code itself is actually irrelevant, in my humble opinion. ?In one place a > file creation line does not work; in the second place it does. ?How can > the same line of code do two different things in two places? ?Either it > creates a file or it doesn't. ?It should create the file in either place, > regardless of where it's being called. > > Either way, I figured it out. From skanemupp at yahoo.se Thu May 15 12:57:50 2008 From: skanemupp at yahoo.se (globalrev) Date: Thu, 15 May 2008 09:57:50 -0700 (PDT) Subject: exists=false, but no complaint when i open it!? References: <285e0ce6-1371-4ab7-9281-ad1d664a480f@a23g2000hsc.googlegroups.com> Message-ID: yeah i was unclear but i tested different stuff at the same time. and flim is not misspelled i just created it and jolted osmething down and it became flim... print os.path.exists('C:/Python25/myPrograms/netflix/flim.txt') d=open('C:/Python25/myPrograms/netflix/flim.txt', 'r') #print d.readline() print d.read() d.close() #not necessary? print os.path.exists('C:\Users\saftarn\Desktop\NetFlixDataSet \training_set') i can read flim and exists returns true. however print os.path.exists('C:\Users\saftarn\Desktop\NetFlixDataSet') returns True but print os.path.exists('C:\Users\saftarn\Desktop\NetFlixDataSet \training_set') returns False... i have thourogly checked the filename to be correct and if we assume it is what could this mean then? i had a problem one other time when i had renamed a file but windows didnt rename it compeltely apparently. From jonbutler88 at googlemail.com Wed May 21 05:02:22 2008 From: jonbutler88 at googlemail.com (jonbutler88 at googlemail.com) Date: Wed, 21 May 2008 02:02:22 -0700 (PDT) Subject: Typeerror References: Message-ID: <9dee15ca-1b7c-4884-b3dd-189c84688e07@2g2000hsn.googlegroups.com> On May 21, 9:58?am, Freaky Chris wrote: > This is a simple error, you are passing the variable res as an interger to > use for a slice when what ever you are storing in res isn't an integer. > > Chris > > > > Beema shafreen wrote: > > > Hi all, > > I getting the following error when i run my scirpt , > > can somebody help me regarding this to solve the type error problem > > > Traceback (most recent call last): > > ? File "get_one_prt_pep.py", line 59, in ? > > ? ? if len(data[res])<=1: > > TypeError: string indices must be integers > > > -- > > Beema Shafreen > > > -- > >http://mail.python.org/mailman/listinfo/python-list > > -- > View this message in context:http://www.nabble.com/Typeerror-tp17358659p17358932.html > Sent from the Python - python-list mailing list archive at Nabble.com. If it is an integer, but stored as a string you can use: if len(data[int(res)])<=1 its not pretty but it should sort out the type errors From darcy at druid.net Thu May 29 17:57:45 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Thu, 29 May 2008 17:57:45 -0400 Subject: Python and Flaming Thunder In-Reply-To: References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <94bac166-d13c-44dd-af84-db19e19488b8@w1g2000prd.googlegroups.com> <8cfd3523-8d16-40bc-b904-94a6a36a414d@p25g2000pri.googlegroups.com> <5c98049e-e62e-4ab1-afed-b0a3e186bd05@w1g2000prd.googlegroups.com> <3dd6fa95-e9fe-4922-a46d-020cf9263469@w4g2000prd.googlegroups.com> Message-ID: <20080529175745.b3e7a579.darcy@druid.net> I guess I am still new to this group and don't understand its charter. I wasn't aware that it was a Flaming Blunder group. Can someone please point me to a newsgroup or mailing list dedicated to the Python programming language? -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From Matthew.Moorland at gmail.com Mon May 5 15:09:47 2008 From: Matthew.Moorland at gmail.com (ETP) Date: Mon, 5 May 2008 12:09:47 -0700 (PDT) Subject: USB HID documentation? References: <6885g8F2s6gaeU1@mid.uni-berlin.de> Message-ID: <61e2bf8f-d2e4-48dc-a488-1c8c38cbcd0d@w34g2000prm.googlegroups.com> I don't doubt I misunderstand since most programming jargon goes over my head. That said, I'm sure you can guess my OS is Windows and I don't know what an API is. After a quick search it looks like windows uses something called DirectInput for gaming devices. Is anyone familiar with DirectInput? Is it implementable in Python? Here's my source: http://msdn.microsoft.com/en-us/library/bb219802(VS.85).aspx Actually, I found this, too: http://directpython.sourceforge.net/ Sounds like it is very straight forward. i would definitely still appreciate any comments or suggestions on the best way to implement a game controller. Thanks again. From deets at nospam.web.de Tue May 6 07:33:42 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 06 May 2008 13:33:42 +0200 Subject: how to use subprocess.Popen execute "find" in windows References: <5666ed04-8a2f-4dad-b7bc-3e3c3c084f03@f24g2000prh.googlegroups.com> Message-ID: <68au1hF2qevdkU1@mid.uni-berlin.de> clyfish at gmail.com wrote: > In cmd, I can use find like this. > > C:\>netstat -an | find "445" > TCP 0.0.0.0:445 0.0.0.0:0 LISTENING > UDP 0.0.0.0:445 *:* > > C:\> > > And os.system is OK. >>>> import os >>>> os.system('netstat -an | find "445"') > TCP 0.0.0.0:445 0.0.0.0:0 LISTENING > UDP 0.0.0.0:445 *:* > 0 >>>> > > But I don't know how to use subprocess.Popen to do this. While there certainly are valid usecases for piping with subprocess in Python - this ain't one I'd say. Just read the output of netstat yourself, and filter for lines that contain the desired pattern. Diez From basti.wiesner at gmx.net Sat May 24 15:23:58 2008 From: basti.wiesner at gmx.net (Sebastian 'lunar' Wiesner) Date: Sat, 24 May 2008 21:23:58 +0200 Subject: need some help in serving static files inside a wsgi apps References: <6e15240b-520d-4f01-9d21-83f9feeefc2d@x41g2000hsb.googlegroups.com> <69qmhcF33pou1U1@mid.uni-berlin.de> <48382917$0$20800$426a74cc@news.free.fr> <69r113F34rbeeU1@mid.uni-berlin.de> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 [ Diez B. Roggisch ] >> I finally managed to work with static files with a little hack, but it's >> ugly because I'm reading each static file per request. > > How else should that work? Apache does that the same way. I guess, Apache does some kind of memory caching for files, which are often requested and small enough to fit into the system memory. May be, that's what the OP is referring to ... - -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) -----BEGIN PGP SIGNATURE----- Version: GnuPG v2.0.9 (GNU/Linux) iEYEARECAAYFAkg4a1QACgkQn3IEGILecb5ibACgoYyLaOc+q51D0g+SuudnqHab dYYAnjH3E0/e2y0owJ1PuWMk13i9YVA/ =7C8x -----END PGP SIGNATURE----- From gnewsg at gmail.com Wed May 21 23:35:53 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Wed, 21 May 2008 20:35:53 -0700 (PDT) Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <2G3Zj.285812$pM4.26927@pd7urf1no> Message-ID: <20d322a6-3132-4482-83fa-210397fefc8c@27g2000hsf.googlegroups.com> On 21 Mag, 17:34, Dave Parker wrote: > [...] symbols are more confusing for people to learn about than > words. There are lots of people who are fluent in English, but > dislike math. > > So, I opted for a simple, unambiguous, non-mathematical way of > expressing "assignment" which makes sense even to the non- > mathematically inclined: > > Set x to 8. Sorry but... are you really trying to tell us that a person which is not able to understand "x = 5" should use a programming language? Such a person shouldn't even use a computer and I strongly doubt that your syntax solution would make ring a bell in his head! Besides that what makes you think that: Set n to 1 Factorial is a function(n) doing if n = 0 then return 1 else return n*factorial(n-1). ...is more clear/intuitive than: n = 1 def factorial(n): "this is a function doing:" return 1 if n == 0 else n * factorial(n-1) ...? IMHO, it seems to me that you've just tried to mix "comments" and "code" into a single thing for no other reason than to be different. I'd be curious to see some code samples solving some - real world - problems instead of showing hot to calculate factorials, printing hello worlds or read from a file, which are the only code samples I've seen in the homepage and in the documentation. --- Giampaolo http://code.google.com/p/pyftpdlib From rhamph at gmail.com Tue May 20 00:55:27 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Mon, 19 May 2008 21:55:27 -0700 (PDT) Subject: Thread killing - I know I know! References: <6fda9c2c-84fe-4339-8ce2-25b6d6b97ba4@t54g2000hsg.googlegroups.com> Message-ID: <58a61ace-5b19-4427-a311-9a0671779fa1@t12g2000prg.googlegroups.com> On May 19, 11:31 am, "Chris Mellon" wrote: > On Mon, May 19, 2008 at 11:36 AM, Roger Heathcote > > Fair point, but for sub processes that need to be in close contact with the > > original app, or very small functions that you'd like 100s or 1000s of it > > seems like a kludge having to spawn whole new processes build in socket > > communications and kill via explicit OS calls. I can't see that approach > > scaling particularly well but I guess there's no choice. > > It's not a kludge - the whole reason why killing a thread is undefined > and a "cardinal sin" is because it's in your own address space and you > can't guarantee anything about how it left things when you killed it. > You simply can't have it both ways. If you want to be able to safely > and sanely kill an uncooperative thread (*especially* third party code > you don't control) you have to isolate it from your address space, and > this means a process. This is a fundamental problem with the entire > idea of shared-state concurrency. For the record, you can't use 1000s > of threads either - if you really need 1000s of concurrent things > running you need to re-think your concurrency model and possibly your > choice of languages and environment. Strictly speaking, you CAN use 1000s of threads, but it requires some special effort. It's not a good idea though, at least for the near future. If you want to kill a thread you have to do it cooperatively, and for the effort required to get that right you might as well make the whole thing event-driven. > The messiness of the real world is *why* you should use processes, not > a reason to avoid them. > > > Does anyone think it likely that the threading module (and threading in > > general) will be improved and augmented with features like timeouts and > > arbitrary threadicide in the next year or two? Seems there's little scope > > for tapping the power of the current generation of multiple cores with the > > current pythons, tho I appreciate breakneck speed has never been a design > > objective it looks like multicore is set to be the next generation PC > > architecture. > > They absolutely should not be. Adding an API which can't work in the > general case and is dangerous even when it can work does not do anyone > any favors. I agree, if it's not safe there's no point adding it. However, if you change the parameters a little bit.. it's quite possible to redefine many blocking functions as cooperative cancellation points. This is the approach I take with python- safethread, and it should satisfy most purposes. From gherron at islandtraining.com Thu May 15 19:00:03 2008 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 15 May 2008 16:00:03 -0700 Subject: How do I use the unpack function? In-Reply-To: References: <482C6E59.3020503@islandtraining.com> <482CA10E.1040602@islandtraining.com> Message-ID: <482CC073.20402@islandtraining.com> Marlin Rowley wrote: > Hey Gary! Please keep such discussions on the public python-list -- not personal e-mail. Scroll down for an answer to your latest question. > > Here's what I have that renders fine but I see some optimization that > can be done (as you mentioned): > > # Tile Generation > # This is where all the drawing to the client window > # will happen. > def generateTile( txl, tyl, tileWidth, tileHeight, clientWindow ): > # make rgba (8-bit) data structure and zero it out. > rgb = zeros( tileWidth*tileHeight*3, UnsignedInt8 ) > alpha = zeros( tileWidth*tileHeight*3, UnsignedInt8 ) > > #print 'tileWidth: %s' % tileWidth > #print 'tileHeight: %s' % tileHeight > # for each pixel in the tile > # we must invert the rendering of each > # tile for wxPython's Bitmap support. > for y in range( (tileHeight-1),-1,-1 ): > for color in range(4): > > # read per scanline > pixelComp = clientWindow.fileIO.read(4*tileWidth) <<<< > HERE'S YOUR OPTIMIZATION!! > > for x in range(tileWidth): > # mental ray streams RGBA components across the width > # of every tile. so it first does all the r's, > # then all the g's, then all the b's, etc.. across > # the width.. Then it streams the second row, etc.. > # However, wxPython Bitmap class accepts an array of > # tuples or just a byte order of RGBARGBARGBA, etc.. > # so we convert, keeping track of an offset. > if color < 3: > index = (3*(y*tileWidth+x))+color > else: > index = (3*(y*tileWidth+x)) > > > # RGBA_FP > if clientWindow.pixelCode == 13: > > # unpack the pixel > #fourbytes = pixelComp[:4] > #pixelComp = pixelComp[4:] > buffer = unpack("!f", pixelComp[4*x:4*x+4]) > <<<<<<<<<<<<<<<<<< YOUR OPTIMIZATION!! > > # convert from 32-bit to 8-bit precision > gamma = clientWindow.gamma > if gamma == 1.0: > pixel = int(255 * buffer[0] + 0.5) > pixel = clamp(pixel,0,255) > if color == 3: > alpha[index+0] = alpha[index+1] = > alpha[index+2] = pixel > else: > rgb[index] = pixel > else: > pixel = int(buffer[0] * GAMMA_BIT_PRECISION + 0.5) > pixel = clamp(pixel,0,GAMMA_BIT_PRECISION-1) > # set the color and alpha > if color == 3: > alpha[index+0] = alpha[index+1] = > alpha[index+2] = clientWindow.frame.gammaTable[pixel] > else: > rgb[index] = > clientWindow.frame.gammaTable[pixel] > > > # ... > > # create an empty rgb and alpha tile > tileRGB = wx.BitmapFromBuffer( tileWidth, tileHeight, rgb ) > tileAlpha = wx.BitmapFromBuffer( tileWidth, tileHeight, alpha ) > > # set up main device to render to the current > # buffers > dc = wx.BufferedDC( None,clientWindow.colorBuffer ) > dca = wx.BufferedDC( None,clientWindow.alphaBuffer ) > > # draw tiles > dc.DrawBitmap( tileRGB, txl, (clientWindow.height-tileHeight)-tyl ) > dca.DrawBitmap( tileAlpha, txl, (clientWindow.height-tileHeight)-tyl ) > > > I'm no python expert (as you can tell), but I'm trying.. :) > > I started to re-write this function but I'm confused on how to do: > > > Reshape the array into a 3D array (i.e., a rectangular array of RGBA > > values) > > this without using a for loop. Yes, easily. No Python loops (although plenty of C-level loops.) (I think you are using Numeric -- a ancient predecessor of numpy. However, I think these operations work in Numeric.) Again I create a small test case. The values will be in the order rrrrggggbbbb to start with, and rgbrgbrgbrgb afterwards. Create a test array and examine it: >>> a = numpy.frombuffer('rrrrggggbbbb', dtype='S1') >>> a array(['r', 'r', 'r', 'r', 'g', 'g', 'g', 'g', 'b', 'b', 'b', 'b'], dtype='|S1') Isolate each color component (here height*width = 4) >>> a.shape = (3,4) >>> a array([['r', 'r', 'r', 'r'], ['g', 'g', 'g', 'g'], ['b', 'b', 'b', 'b']], dtype='|S1') Transpose it. (This creates a new array by copying efficiently.) >>> b = a.transpose() >>> b array([['r', 'g', 'b'], ['r', 'g', 'b'], ['r', 'g', 'b'], ['r', 'g', 'b']], dtype='|S1') Reset it's shape to be a width*height array of rgb's. >>> b.shape = (2,2,3) >>> b array([[['r', 'g', 'b'], ['r', 'g', 'b']], [['r', 'g', 'b'], ['r', 'g', 'b']]], dtype='|S1') Put it out in byte array form: >>> b.tostring() 'rgbrgbrgbrgb' Done. Gary Herron > > -M > > > > Date: Thu, 15 May 2008 13:46:06 -0700 > > From: gherron at islandtraining.com > > CC: python-list at python.org > > Subject: Re: How do I use the unpack function? > > > > Marlin Rowley wrote: > > > Gary, > > > > > > I'm getting streaming tile data from a renderer in order to allow the > > > user to see the rendering of tiles in real-time to create the total > > > image. I'm NOT reading an entire image scanline-by-scanline. The > > > renderer streams in a series of floats (for each tile) and I build > > > this tile up from each individual color component passed in. I then > > > convert it to a small bitmap and blit() it to the window that will > > > eventually make up my entire image. I'm just wanting to make the > > > process as fast as the renderer can render the tiles. I've noticed on > > > scenes that aren't very complex for the renderer that my python > script > > > is spending most of it's time drawing while the renderer is already > > > done. What you've given me has sped up the drawing a lot, but I'm > > > hungry for more optimization! > > > > > > There is no file format to be read. The data is raw bytes and can be > > > any format. > > > > You are misinterpreting what I mean by a format. All data is a string > > of bytes, and interpreting that string of bytes to have some particular > > form is applying a format to it. Your particular format is: each 4 > > bytes represents a float, and a string of such floats give the RGBA > > values for a rectangle (of some size) of pixels. I doubt that you are > > the first ever to use that particular format to encode an image, but I > > also don't believe it matches any of the standard image formats. > > > > So... There is still hope to use already written tools to decode your > > format. > > > > Here's a hint on how to use numpy for decoding a byte string into an > > array of floats. My example byte string is a hand coded string of just > > 12 bytes -- you should replace that with a whole row or better yet, a > > whole tile's worth of bytes. > > > > >>> import numpy > > >>> byteString = '\x00\x00\x80?\x00\x00\x00@\x00\x00@@' > > >>> b = numpy.frombuffer(byteString, dtype=numpy.float32) > > >>> b > > array([ 1., 2., 3.], dtype=float32) > > > > > > If you want to use the array module instead: > > > > >>> import array > > >>> a = array.array('f') > > >>> a.fromstring(byteString) > > >>> a > > array('f', [1.0, 2.0, 3.0]) > > > > > > In either case ANY number of bytes can be decoded into an array of > > floats, in one highly efficient call from Python. > > > > What you do with that array of float afterwards is up to you.... > > > > If I read your note correctly, here's what I'd do to turn the array of > > bytes into an image of a tile to be displayed on the screen. > > > > Get the whole tile's worth of bytes with one read into a single string. > > Decode that string into an array of floats (as above). > > Reshape the array into a 3D array (i.e., a rectangular array of RGBA > > values) > > Convert that array of floats into an array of 8-bit integers (scaling > > all by 255). > > Extract (via tostring) that array into a string of bytes. > > Send that string of bytes to the graphics system as an RGBA array of > > pixels. > > > > Each of these calls is one Python call into a highly efficient library. > > This is using Python as a, so called, glue language. > > > > Gary Herron > > > > > > > > > > > > > > > > > > > > > Date: Thu, 15 May 2008 10:09:45 -0700 > > > > From: gherron at islandtraining.com > > > > CC: python-list at python.org > > > > Subject: Re: How do I use the unpack function? > > > > > > > > John Machin wrote: > > > > > On May 16, 2:11 am, Gary Herron > wrote: > > > > > > > > > >> Marlin Rowley wrote: > > > > >> > > > > >>> All: > > > > >>> > > > > >>> I've got a script that runs really slow because I'm reading > from a > > > > >>> stream a byte at a time: > > > > >>> > > > > >>> // TERRIBLE > > > > >>> for y in range( height ): > > > > >>> for color in range(4): > > > > >>> for x in range( width ): > > > > >>> pixelComponent = fileIO.read(4) > > > > >>> buffer = unpack("!f",pixelComponent) << unpacks ONE > > > > >>> > > > > > > > > > > [snip] > > > > > Perhaps the OP might be able to use the Python Imaging Library > (PIL) > > > > > instead of reinventing an image-file handler. > > > > > > > > > > > > > Indeed. That's why my original answer included the line: > > > > There are probably better ways overall, but this directly answers > > > > your question. > > > > > > > > Other possibilities. > > > > > > > > I don't recognize the file format being read in here, but if it is a > > > > standard image format, the PIL suggestion is a good way to go. > > > > > > > > Or, if it is an image of not too enormous size, read the *whole* > thing > > > > in at once. > > > > > > > > Or rather than manipulate the array by carving off 4 bytes at a > time, > > > > just index through it in 4 byte chunks: > > > > for i in range(width): > > > > buffer = unpack("!f", pixelComponent[4*i:4*i+4]) > > > > > > > > Or > > > > for i in range(0,4*width,4): > > > > buffer = unpack("!f", pixelComponent[i:i+4]) > > > > > > > > Or > > > > Use numpy. Create an array of floats, and initialize it with the > byte > > > > string, making sure to take endianess int account. (I'm quite > sure this > > > > could be made to work, and then the whole operation is > enormously fast > > > > with only several lines of Python code and *no* Python loops. > > > > > > > > Or > > > > ...? > > > > > > > > Gary Herron > > > > > > > > > -- > > > > > http://mail.python.org/mailman/listinfo/python-list > > > > > > > > > > > > > -- > > > > http://mail.python.org/mailman/listinfo/python-list > > > > > > > ------------------------------------------------------------------------ > > > Windows Live SkyDrive lets you share files with faraway friends. > Start > > > sharing. > > > > > > > > > > > > ------------------------------------------------------------------------ > > > > > > -- > > > http://mail.python.org/mailman/listinfo/python-list > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > ------------------------------------------------------------------------ > Get Free (PRODUCT) RED? Emoticons, Winks and Display Pics. Check it > out! > From george.sakkis at gmail.com Wed May 14 10:30:04 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 14 May 2008 07:30:04 -0700 (PDT) Subject: Class Methods Vs Any Other Callable References: <98b4a67c-9ec7-407c-8c80-06488bd48a68@e39g2000hsf.googlegroups.com> <690ap7F2u0ftdU1@mid.uni-berlin.de> Message-ID: <238061d6-9423-44c1-90b2-cc09f392db9b@p25g2000hsf.googlegroups.com> On May 14, 10:19 am, "Diez B. Roggisch" wrote: > > An instance method works on the instance > > A Static method is basically a function nested within a class object > > A class method is overkill? > > If anything, a static method is overkill. See it this way: *if* you for some > reason put a method into an enclosing context - isn't it worth having a > reference to that? My feeling exactly; these days I almost always use class methods instead of static. I vaguely remember seeing somewhere an example where a static method was the only (elegant) solution; neither a class method nor a plain function would do. I'll post it if I find it unless someone beats me to it. George From banibrata.dutta at gmail.com Sun May 11 00:17:22 2008 From: banibrata.dutta at gmail.com (Banibrata Dutta) Date: Sun, 11 May 2008 09:47:22 +0530 Subject: multiple Python versions, but on Windows (how to handle registry updates) In-Reply-To: <3de8e1f70805102115j5f0bf985w3952facf49a66d79@mail.gmail.com> References: <3de8e1f70805090358p27796919jb885138406ade6aa@mail.gmail.com> <3de8e1f70805092138y4ca414ck2be6b5246afa664b@mail.gmail.com> <3de8e1f70805102115j5f0bf985w3952facf49a66d79@mail.gmail.com> Message-ID: <3de8e1f70805102117p584e5920hb4a99166488c6448@mail.gmail.com> I realized that my query was not making much sense, or a bit convoluted. A simler form of the question: For packages which do contain .dlls & .pyd's (not pure Python) their latest version may be compatible with -- say Python 2.5, whereas I need the version compatible for Python2.2. Is this a completely manual exercise ? On 5/11/08, Banibrata Dutta wrote: > > Thanks Gabriel & Terry. Those explanations make perfect sense. > > What is the recommended way, to find the "compatible" packages that include > .dll's / .pyd's or dependencies that are Python release specific ? For > example, is there a 'yum' or other automatic dependency checking mechanism > which works accross OS's (Windows & Linux), which will allow me to find the > other (s.a. 3rd party) packages, which would work with say Python2.2 ? Is it > a completely manual exercise, where I read the README or Package Notes or > Release Notes, and figure out the required version of package ? > > > On 5/11/08, Gabriel Genellina wrote: >> >> En Sat, 10 May 2008 01:38:24 -0300, Banibrata Dutta < >> banibrata.dutta at gmail.com> escribi?: >> >> > given that I already have Python2.5 installed & will install Python2.4, >> will >> > copying the ../Lib/site-packages/ from 2.5 into 2.4's, work ? >> > i think the answer is "no", but still asking. is it package specific ? >> > >> > does it matter if the packages were egg drops ? >> >> Packages containing only .py modules ("pure" packages) are OK; packages >> using C extensions (.dll, .pyd) have to be rebuilt (or you have to download >> the binaries for the other Python version). >> >> -- >> Gabriel Genellina >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > > > -- > regards, > Banibrata > http://www.linkedin.com/in/bdutta > http://octapod.wordpress.com > -- regards, Banibrata http://www.linkedin.com/in/bdutta http://octapod.wordpress.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From cjw at ncf.ca Sat May 17 20:00:48 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Sat, 17 May 2008 20:00:48 -0400 Subject: Using Python for programming algorithms In-Reply-To: References: Message-ID: <482F71B0.3050808@ncf.ca> Vicent Giner wrote: > Hello. > > I am new to Python. It seems a very interesting language to me. Its > simplicity is very attractive. > > However, it is usually said that Python is not a compiled but > interpreted programming language ?I mean, it is not like C, in that > sense. > > I am working on my PhD Thesis, which is about Operations Research, > heuristic algorithms, etc., and I am considering the possibility of > programming all my algorithms in Python. > > The usual alternative is C, but I like Python more. > > The main drawbacks I see to using Python are these: > > * As far as I understand, the fact that Python is not a compiled > language makes it slower than C, when performing huge amounts of > computations within an algorithm or program. The usual answer is that development time is more important than running time. Since you are likely to be using arrays, you might look at numpy, where the number crunching is using compiled C code. > > * I don't know how likely it is to find libraries in Python related to > my research field. > > * I know Python is a "serious" and mature programming language, of > course. But I do not know if it is seen as "just funny" in a research > context. Is Python considered as a good programming language for > implementing Operations Research algorithms, such as heuristics and > other soft-computing algorithms? Try Google with Python and your area of interest. You could well find Python-based packages which meet your needs. > > Maybe this is not the right forum, but maybe you can give me some > hints or tips... > > Thank you in advance. Good luck. Colin W. From stefan_ml at behnel.de Sun May 4 01:46:40 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 04 May 2008 07:46:40 +0200 Subject: Error handling in SAX In-Reply-To: <55e65c5e-1dd9-41d2-ab1c-7340cd4db558@25g2000hsx.googlegroups.com> References: <55e65c5e-1dd9-41d2-ab1c-7340cd4db558@25g2000hsx.googlegroups.com> Message-ID: <481D4DC0.9060709@behnel.de> mrkafk at gmail.com wrote: > (this is a repost, for it's been a while since I posted this text via > Google Groups and it plain didn't appear on c.l.py - if it did appear > anyway, apols) It did, although some people have added google groups to their kill file. > So I set out to learn handling three-letter-acronym files in Python, > and SAX worked nicely until I encountered badly formed XMLs, like with > bad characters in it (well Unicode supposed to handle it all but > apparently doesn't), If it's not well-formed, it's not XML. XML parsers are required to reject non well-formed input. In case it actually is well-formed XML and the problem is somewhere in your code but you can't see it through the SAX haze, try lxml. It also allows you to pass the expected encoding to the parser to override broken document encodings. http://codespeak.net/lxml/ Stefan From otaeris at o2.pl Thu May 29 11:14:46 2008 From: otaeris at o2.pl (otaeris at o2.pl) Date: Thu, 29 May 2008 17:14:46 +0200 Subject: =?UTF-8?Q?Writing_Empty_folders_into_ZipFile?= Message-ID: Hello. I'm having situation writing folders structure into a zip file. Folders contain no files. Is it possible to do in python ? Regards, Bartek From jschroed at gmail.com Thu May 8 22:34:59 2008 From: jschroed at gmail.com (John Schroeder) Date: Thu, 8 May 2008 19:34:59 -0700 Subject: How can I add spaces where ever I have capital letters? In-Reply-To: <92da89760805081904v2927bf73tc28c55415c405a4d@mail.gmail.com> References: <4878ad7b0805081812l2a3412abh185a832866be2878@mail.gmail.com> <92da89760805081904v2927bf73tc28c55415c405a4d@mail.gmail.com> Message-ID: <4878ad7b0805081934j383998b5rd88baa57927c0ce5@mail.gmail.com> Thanks guys. That upper() function reminded me to use the isupper() function. I got this going in a single pass: def a(name): self_name = name # Increment this value every time we add a space offset = 0 for i in xrange(len(name)): if i != 0 and name[i].isupper(): self_name = self_name[:i + offset] + ' ' + self_name[i + offset:] offset += 1 return self_name name = "GeneralPacketMeToo" print a(name) >>> General Packet Me Too >>> On Thu, May 8, 2008 at 7:04 PM, Eric Wertman wrote: > Something like this. I'm sure there are other ways to do it. > > import re > > def addspace(m) : > return ' ' + m.group(0) > > strng = "ModeCommand" > > newstr = re.sub('[A-Z]',addspace,strng) > > print newstr.strip() > > > > On Thu, May 8, 2008 at 9:12 PM, John Schroeder wrote: > > I have a string (which I got from the names of my classes) and I would > like > > to print out my CamelCase classes as titles. > > > > I would like it to do this: > > > >>>> my_class_name = "ModeCommand" > > ## Do some magic here > >>>> my_class_name > > 'Mode Command' > > > > Anyone know any easy way to do this? Thanks. > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mnikhil at gmail.com Wed May 14 14:52:53 2008 From: mnikhil at gmail.com (Nikhil) Date: Thu, 15 May 2008 00:22:53 +0530 Subject: readlines with line number support? References: Message-ID: Arnaud Delobelle wrote: > Nikhil writes: > >> Hi, >> >> I am reading a file with readlines method of the filepointer object >> returned by the open function. Along with reading the lines, I also >> need to know which line number of the file is read in the loop >> everytime. >> I am sure, the line should have the property/attribute which will say >> the line number of the file. >> >> If there is none, do I have to end up using the counter in the loop? >> >> fp = open("file", "r") >> lineno = 0 >> for line in fp.readlines(): >> print "line number: " + lineno + ": " + line.rstrip() >> lineno = lineno + 1 > > The standard Python way is using enumerate() > > for i, line in enumerate(fp): > print "line number: " + lineno + ": " + line.rstrip() > Oh I did not know enumerate can be used. Thanks Paul and Arnaud. I will try this. From daveparker at flamingthunder.com Tue May 13 13:33:01 2008 From: daveparker at flamingthunder.com (Dave Parker) Date: Tue, 13 May 2008 10:33:01 -0700 (PDT) Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <5b0e3f70-afde-4480-8713-e7113b1250d7@x35g2000hsb.googlegroups.com> <1f537717-00d0-48ee-99b6-7125b96a6133@t12g2000prg.googlegroups.com> <68t4o0F2vaoncU1@mid.uni-berlin.de> <2a32179a-9439-449c-bd07-fff6a4075aee@s50g2000hsb.googlegroups.com> <7ee5dffd-df8f-46f0-bd78-c81ac0418a9a@d77g2000hsb.googlegroups.com> <65ef773e-a1c3-4adb-a18b-e8b8451efe5e@b5g2000pri.googlegroups.com> <68trmmF2vjivnU1@mid.uni-berlin.de> Message-ID: <0bda514d-7e61-45ff-826b-9e64999b18c3@z24g2000prf.googlegroups.com> > You sound like a commercial. Get Flaming Thunder for only $19.95! It slices, it dices! > And while programs and libraries written in assembly may be twice as fast > as programs and libraries written in C, ... It's a myth that they're only twice as fast. An experienced assembly language programmer can usually get out at least a factor of 5 by using tricks such as cache-coherence, carry flag tricks, stack manipulations, etc. > ... they're real hell to maintain. That's also a myth. For example, if C is easy to maintain, why is Flaming Thunder the only single-asset 8-by-8 shotgun cross compiler in the world? There should be lots of single-asset 8-by-8 shotgun cross compilers written in C, if C is easier to maintain. Here's one of the tricks I use: I wrote an assembly language preprocessor that takes 1 assembly language source file and generates the library code for the 8 different target platforms. That's much easier than maintaining quirky C code across 8 different platforms -- which is why GCC's support for cross-compilation is often so broken. On May 13, 10:57?am, "Andrii V. Mishkovskyi" wrote: > You sound like a commercial. Is this your way of attracting costumers of FT? > > 2008/5/13 Dave Parker : > > > > 5-10 times faster for what kind of code? > > > ?Mostly numerical analysis and CGI scripting. ?All of Flaming Thunder's > > ?library code is in assembly language, and Flaming Thunder creates > > ?statically-linked pure syscall CGI scripts. > > > ?> I don't see anything that resembles OO features of python, ... > > > ?True. ?But in Python, you don't see statically-linked pure-syscall CGI > > ?scripts being cross-compiled under Windows for ftp'ing up to a Linux > > ?server. ?And you don't see the speed of pure assembly language > > ?libraries. > > I see your assembly language libraries and raise you C language libraries. :) > Python libraries have the speed of pure C language libraries. And > while programs and libraries written in assembly may be twice as fast > as programs and libraries written in C, they're real hell to maintain. > But that doesn't stop you from telling us, that: > > > ?And I'll be willing to bet that Flaming Thunder will have > > ?OO features similar to Python before Python has the features that > > ?Flaming Thunder already does. > > Well, we'll see. But, IMHO, this is highly unlikely. > > > ?For many people, being 5 to 10 times faster at numerical analysis and > > ?CGI scripting is reason enough to pay $19 per year. ?But maybe for > > ?other people, having slow, inefficient programs and websites is > > ?acceptable. > > Yeah, right, Python is sooooo slow. :) Show us some sites and programs > that were written in FT. > > > > > ?> And what is really expensive is brain-cycles, not cpu-cycles. > > > ?Depends on whether you're the programmer, or the customer. ?I've found > > ?that customers prefer products that are 5 to 10 times faster, instead > > ?of products that were easy for the developer. > > If I'm customer, than why should I care about FT? > If I'm a programmer, I'd better care about brain-cycles. > > > > > ?And I disagree that Flaming Thunder requires more brain-cycles. > > ?Because it's based on leveraging existing English and math fluency > > ?(which was one of the original goals of Python, was it not?), I think > > ?that Flaming Thunder requires fewer brain-cycles because fewer brains > > ?cells have to be devoted to memorizing language peculiarities. > > Not everybody has grown in English-speaking community, you know. And > knowing math quite good, I prefer writing "x = y" instead of "Set x to > y". > > > > > > > > > ?> Let alone it is > > ?> very much a question of view-point if two different looping constructs or > > ?> keywords are more awkward than one general looping-concept with only one > > ?> keyword. It's a matter of taste. > > > ?Perhaps. ?But if elementary school students can easily understand why > > ?one programming language gives the answer 100 (Flaming Thunder): > > > ? Write 10^2. > > > ?but can't understand why another programming language gives the answer > > ?8 (Python): > > > ? Print 10^2 > > > ?then I think the comparison moves beyond a matter of taste into the > > ?realm of measurable ease-of-use. > > '^' is a bitwise XOR. Python uses "x**y" for raising x to power of y. > What's your point here? > > > > > > > > > ?On May 13, 9:50 am, "Diez B. Roggisch" wrote: > > ?> > Also, several users have rewritten their Python programs in Flaming > > ?> > Thunder, and found that Flaming Thunder was 5 to 10 times faster > > ?> > (Flaming Thunder compiles to native executables). ?So again, since > > ?> > many people value their time at more than $0, I think that many people > > ?> > will find that Flaming Thunder is worth $19.95 per year. > > > ?> 5-10 times faster for what kind of code? I don't see anything that resembles > > ?> OO features of python, let alone more advanced concepts like > > ?> meta-programming, higher-order functions and such. Which save tremendous > > ?> amounts of time coding. If FT grows these and *still* is 5-10 times faster, > > ?> I'll salut you. > > > ?> And what is really expensive is brain-cycles, not cpu-cycles. Which above > > ?> described features save. > > > ?> > Plus, me getting paid to work on Flaming Thunder is far more > > ?> > motivating than me not getting paid to work on Python. ?This weekend, > > ?> > Python users will still be debating how to fix awkwardnesses in the > > ?> > languages (such as FOR loops where you're just counting the loops and > > ?> > not referencing the loop variable) -- but Flaming Thunder users will > > ?> > be getting work done using the REPEAT n TIMES constructs that I'll be > > ?> > implementing. > > > ?> > Python has been around about 15 years, yet still has those > > ?> > awkwardnesses. ?Flaming Thunder has been out less than 6 months and > > ?> > those awkwardnesses are already getting fixed. ?The difference: I > > ?> > can't afford to ignore users. > > > ?> Oh *please*! Try getting nearly as feature & library complete as python is > > ?> today - and *then* I'll point to all the akwardness of FT. Let alone it is > > ?> very much a question of view-point if two different looping constructs or > > ?> keywords are more awkward than one general looping-concept with only one > > ?> keyword. It's a matter of taste. > > > ?> Diez > > > ?-- > > ?http://mail.python.org/mailman/listinfo/python-list > > -- > Wbr, Andrii Mishkovskyi. > > He's got a heart of a little child, and he keeps it in a jar on his desk.- Hide quoted text - > > - Show quoted text -- Hide quoted text - > > - Show quoted text - From deets at nospam.web.de Tue May 27 12:08:05 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 27 May 2008 18:08:05 +0200 Subject: New chairman References: <3720fb99-ac37-469b-b8ce-ece3ed27b8e5@m36g2000hse.googlegroups.com> <6a2ndjF35q29pU1@mid.uni-berlin.de> <0b18caad-4fbf-46e8-887f-ce29963e24a0@m3g2000hsc.googlegroups.com> Message-ID: <6a2q04F35ab70U1@mid.uni-berlin.de> > Good luck to you to. Its just that it .. well it has never been easy > for me to introduce Python at work. This py3k, if I like it or not, is > not making it easier. And creating a fork makes it easier? > Praktical, pragmatic, you know --- as I said, its not broken so lets > brake it Again - creating a fork makes that better? > I just try to get things to work. And with some style too. Their > connected. I think a 6 cylinder engine is one of the most stylist > things there are. And when I was at a museum in Stocholm, I saw Henry > Fords original enginge and was amazed, it looks just like the one in > dads car. This is a castironpi-esque metaphor. Guess what, I have an ever older one: the wheels used by roman circus race wagons essentially look the same as on a formula one car. Round, with a hub in the middle. Now how about you throw that computers of your out of the window because it is technology not available in ancient rome, and as change is bad according to your view- away with it! > Its not about changing and yes I dislike py3k, till somebody can > convince me otherwise > > Guido just seems to not care to post here anyways, so we can try to > make our own branch/business Again: how is that going to help? You argue that a *fork* is what helps mitigating the problems *a fork called Py3K* introduces (in your opinion). Now why do you think your company is more likely to adopt the language "Sverker Nilsson his own fork of Python that no one else cares about and that won't be supported" - short SNHOFOPTNOECAATWBS? If you don't like change - stick to python 2.5. Or whatever suits you. For the umpteenth time: how is that going to help you with your "don't change" issues? Diez From inhahe at gmail.com Mon May 26 15:43:36 2008 From: inhahe at gmail.com (inhahe) Date: Mon, 26 May 2008 15:43:36 -0400 Subject: definition of a highlevel language? References: <2759eed3-956d-45c7-8dfb-9557f74133b3@56g2000hsm.googlegroups.com> <26d0b3d2-01cc-49bd-b284-1a849b0b835f@y38g2000hsy.googlegroups.com> <34dcbdc1-5285-41ec-be06-c88c56bb0372@i76g2000hsf.googlegroups.com> Message-ID: I like to think of a language that would combine low-level and high-level features to be used at the programmer's whim. C--, High Level Assembly, and C++ with in-line assembly are examples, but none of them come as high-level as Python. Other possible examples might be ctypes, numpy, array.array, and I heard a rumor that Python 3.0 might have optional type declarations. My ideal language would be like a version of C++ (including in-line asm), or C-- with classes, that's compiled, but supports Python abstractions and features wherever possible (including doing away with {}'s and ;'s). > > what is crazy about it? > > in the same way programming webapps in C would be annoying because you > have to do a lot of lowlevel tasks it is dumb to program computer ina > highlevellanguage because you dont have direct access to lowlevel > tasks meaning you cant program it very efficiently, ie make it fast? From http Sun May 25 18:14:23 2008 From: http (Paul Rubin) Date: 25 May 2008 15:14:23 -0700 Subject: Code correctness, and testing strategies References: Message-ID: <7xy75ym3pc.fsf@ruckus.brouhaha.com> aahz at pythoncraft.com (Aahz) writes: > You must have poor project management/tracking. You WILL pay the cost > of testing, the only question is when. The when does have an impact on > other aspects of the development process. Well, let's say you used TDD and your program has 5000 tests. One might reasonably ask: why 5000 test? Why not 10000? Why not 20000? No number of tests can give you mathematical certainty that your code is error-free. The only sensible answer I can think of to "why 5000" is that 5000 empirically seemed to be enough to make the program reliable in practice. Maybe if you used a more error-prone coding process, or wrote in assembly language instead of Python, you would have needed 10000 or 20000 tests instead of 5000 to get reliable code. But then one might reasonably ask again: why 5000 tests? Why not 2000 or 1000? Was there something wrong with the coding process, that couldn't produce reliable code with fewer tests? So, I think you have to consider the total development cycle and not treat test development as if it were free. I also haven't yet seem an example of a real program written in this test-driven style that people keep touting. I use doctest when writing purely computational code, and maybe it helps some, but for more typical code involving (e.g.) network operations, writing automatic tests (with "mock objects" and all that nonsense) is a heck of a lot more work than testing manually in the interactive shell, and doesn't seem to help reliability much. I'd be interested in seeing examples of complex, interactive or network-intensive programs with automatic tests. From deets at nospam.web.de Mon May 26 07:52:51 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 26 May 2008 13:52:51 +0200 Subject: integration with browser References: Message-ID: <69vmlgF35akucU1@mid.uni-berlin.de> nik600 wrote: > Hi to all > > i'd like to create a window that integrates a browser control, the > browser control must support html, javascript and css. > > Is possible to include something that uses the same engine of firefox? > > Thanks to all in advance What OS, what GUI toolkit? Diez From bronger at physik.rwth-aachen.de Fri May 2 10:26:51 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Fri, 02 May 2008 16:26:51 +0200 Subject: #!/usr/bin/env python vs. #!/usr/bin/python References: <87abj91j8u.fsf@benfinney.id.au> <87k5iczvdy.fsf@benfinney.id.au> Message-ID: <87y76ssrx0.fsf@physik.rwth-aachen.de> Hall?chen! D'Arcy J.M. Cain writes: > On Fri, 02 May 2008 23:30:01 +1000 > Ben Finney wrote: > >> The OP was asking why people prefer on over the other. My answer >> is that I prefer specifying "give me the default OS Python" >> because anything not installed by the OS is to non-standardised >> for me to worry about. > > [...] > > Certainly #! /usr/bin/python is fine if you never expect your > software to run outside of your own little corner of the world but > you asked why people prefer the env version and the answer is that > we want to write software that runs everywhere that Python runs. Granted, but you must draw the line somewhere anyway. I cannot pollute my program with hundreds of if clauses just to make it work on every quirky system. It's the *systems* where the streamlining must happen, not the programs. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From wxPythoner at gmail.com Sun May 11 04:10:19 2008 From: wxPythoner at gmail.com (wxPythoner at gmail.com) Date: Sun, 11 May 2008 01:10:19 -0700 (PDT) Subject: Some error messages in Python are ugly Message-ID: <1af83e8f-8083-4b5d-95e1-534193d059e5@24g2000hsh.googlegroups.com> This really looks ugly for an error message: [1]+ Stopped python Please explain to me the role of the '+' sign. And why is there such a gap between 'Stopped' and 'python'? From mcknight0219 at gmail.com Fri May 23 02:29:43 2008 From: mcknight0219 at gmail.com (Jimmy) Date: Thu, 22 May 2008 23:29:43 -0700 (PDT) Subject: can python do some kernel stuff? Message-ID: <983ec0f6-1316-40cd-a4d4-ce9b5e272a60@h1g2000prh.googlegroups.com> Hi to all python now has grown to a versatile language that can accomplish tasks for many different purposes. However, AFAIK, little is known about its ability of kernel coding. So I am wondering if python can do some kernel coding that used to be the private garden of C/C++. For example, can python intercept the input of keyboard on a system level? someone told me it's a kernel thing, isn't it? From inhahe at gmail.com Tue May 20 17:49:43 2008 From: inhahe at gmail.com (inhahe) Date: Tue, 20 May 2008 17:49:43 -0400 Subject: persistent deque References: <29451c2a-cb0a-43a6-b140-6c16e3cb46ac@c65g2000hsa.googlegroups.com> Message-ID: def __init__(self, filename, initial): should be def __init__(self, filename, initial=[]): (that was the whole reason i put the filename first.) sorry. From pavlovevidence at gmail.com Tue May 27 03:23:58 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 27 May 2008 00:23:58 -0700 (PDT) Subject: Hungarian Notation References: <74d9c37f-807c-4aae-8ad5-db79bb3e2bd2@8g2000hse.googlegroups.com> Message-ID: On May 27, 2:37 am, Paul McGuire wrote: > On May 27, 12:28 am, "inhahe" wrote: > > > Does anybody know of a list for canonical prefixes to use for hungarian > > notation in Python? Not that I plan to name all my variables with hungarian notation, but just for when it's appropriate. > > You are likely to get some links to PEP 8 for coding style and naming > conventions, but it turns out PEP 8 doesn't really say yay or nay on > the Hungarian notation topic. > > My own knee-jerk reaction was "Hungarian Notation Bad!" and googling > about for "python hungarian notation" led me through some like-minded > sites. But I also found this entry on Joel Spolky's site (http://www.joelonsoftware.com/printerFriendly/articles/Wrong.html), that > warns against tarring all Hungarian-type notations with the same > brush. The name of a variable is a valuable resource. There are all kinds of things you can encode in it, but you have to choose only one or two. The most important information is what it is (e.g., box), or what it's archetype is (i, for a counter variable). Pretty much all names should contain one of these two. Second most important are discriminators such as a description (red_box), usage (shoebox), or circumstance (next_box). But sometimes other things are important enough to warrant addition to the name. Type usually isn't one of them, but there are times when it's helpful to know. But then, I'm not sure I would call it "Hungarian notation" to add ad hoc type information to a few of names here and there. One convention I have for myself is to use x for elements when I'm using ElementTree, but the reason is pragmatic: I'm creating objects that have the same name as the elements. > So with that article in mind, I'd have to ask, what do you mean by > "appropriate"? It seems like OP wanted to disambiguate two objects based on type, which seems reasonable to me. Sometimes you want to have side-by-side represenations of something where type is the main difference, in which case there's no reason type shouldn't be added to the name. Carl Banks From msh at blisses.org Fri May 16 11:31:16 2008 From: msh at blisses.org (Matt Herzog) Date: Fri, 16 May 2008 10:31:16 -0500 Subject: Python book question Message-ID: <20080516153116.GF13079@chicago.blisses.org> People keep telling me I need a course in "Data Structures and Algorithms." Since Python is the only language that doesn't give me headaches I thought this book might be good. Has anyone read it or can anyone recommend the author? Can anyone recommend a better Data Structures and Algorithms book? The book: http://www.fbeedle.com/053-9.html -- Matt H. -- "Outside of a dog, a book is a man's best friend. Inside of a dog, it is too dark to read." -- Groucho Marx From jldunn2000 at googlemail.com Thu May 29 04:36:44 2008 From: jldunn2000 at googlemail.com (loial) Date: Thu, 29 May 2008 01:36:44 -0700 (PDT) Subject: Compare 2 files and discard common lines Message-ID: <8d55718c-6881-4844-b8d1-bbe1c5929f46@x35g2000hsb.googlegroups.com> I have a requirement to compare 2 text files and write to a 3rd file only those lines that appear in the 2nd file but not in the 1st file. Rather than re-invent the wheel I am wondering if anyone has written anything already? From skanemupp at yahoo.se Fri May 16 14:41:29 2008 From: skanemupp at yahoo.se (globalrev) Date: Fri, 16 May 2008 11:41:29 -0700 (PDT) Subject: write to specific line in file? Message-ID: i ahve a program that takes certain textsnippets out of one file and inserts them into another. problem is it jsut overwrites the first riow every time. i want to insert every new piece of text into the next row. so: 1. how do i write to a new line every time i write to the file? 2. if i dont want to write to a new line but just want to insert it after the last token in the file, how do i do then? From M8R-yfto6h at mailinator.com Wed May 14 21:54:31 2008 From: M8R-yfto6h at mailinator.com (Mark Tolonen) Date: Wed, 14 May 2008 18:54:31 -0700 Subject: Using the indent method References: Message-ID: <-eWdnTt5ip1PCrbVnZ2dnUVZWhednZ2d@comcast.com> "dj" wrote in message news:ffbc75e3-612b-4195-b9c1-11df9e66d286 at f63g2000hsf.googlegroups.com... > Hello All, > > I am using elementtree to write an XML document and I am having a hard > time adding the correct indentation. > I have tried using the indent method, but I can not figure out how to > use it. Any suggestions. Using the version of indent() found on http://effbot.org/zone/element-lib.htm: >>> from xml.etree import ElementTree as ET >>> x='stuff' >>> e=ET.fromstring(x) >>> ET.dump(e) stuff >>> indent(e) >>> ET.dump(e) stuff -Mark From s0suk3 at gmail.com Sun May 4 22:54:09 2008 From: s0suk3 at gmail.com (s0suk3 at gmail.com) Date: Sun, 4 May 2008 19:54:09 -0700 (PDT) Subject: Please help - Tkinter not doing anything References: <20562a9d-200c-40ae-a850-eb0f9a943d3f@l42g2000hsc.googlegroups.com> <237aa3894dff4c8976896df85f4d7d23@localhost> <3ab5d06a0805040239m6cf12d39ufcde4fcc585f81e4@mail.gmail.com> <05343da9-b929-4d86-a2b0-80984af9c25c@l64g2000hse.googlegroups.com> Message-ID: <07c6e440-18fb-4a97-83b8-e9751bf9e56c@y38g2000hsy.googlegroups.com> On May 4, 6:59 am, Protected wrote: > On May 4, 12:18 pm, s0s... at gmail.com wrote: > > > > > On May 4, 5:22 am, Protected wrote: > > > > I had previously ran the import line. I prepended it to the example > > > code I'm trying to run every time but it did not help, still nothing > > > happens. With or without var before 'root'. I'm pasting the code in > > > IDLE and using Windows XP as written in the first post. > > > Tkinter doesn't work if you type the statements in IDLE. I don't > > remember the specifics of it, but essentially it doesn't work because > > IDLE is itself a Tkinter app. You have to type it at the Python > > command line or save it in a file. BTW, if you're on Windows, you > > should definitely check wxPython. I used to work with Tkinter, > > struggling with it all the time only to get a lame result most of the > > time. Then I switched to wxPython, and in the same week I was learning > > it I did a better GUI than I ever did in Tkinter (with months of > > work!). I feel it makes it easier to make your program have a better > > structure and design, and thus lets you focus on the actual task of > > the program, rather than in the GUI itself. Plus, on Windows, you'll > > get the widgets to look more natively, like any good quality > > application there is on Windows. > > Ah, but is it cross platform? > > (Thanks for letting me know about IDLE.) Of course. I forgot to say about that. It is cross platform, like most things in Python. I'd say it's actually more cross platform than Tkinter, because of the looks of both in different platforms. In Tkinter, you can get all the widgets to work in all the platforms it supports, but the widgets look so different on different platforms, that at the end you end up modifying the code anyway so that the controls look better on the platform that you port the program to. With what I've done with wxPython, the controls look great on any of the platforms I've tried my programs in. Another thing: wxPython is a port of the wxWidgets toolkit which is for C++. It has also been ported to a bunch of other languages like Ruby, Perl, C#, etc; so if you learn any of the languages which wxWidgets has been ported to, you can use the toolkit in the same way that you've been doing with Python, except that with the syntax of the other language. From wuwei23 at gmail.com Fri May 23 22:39:19 2008 From: wuwei23 at gmail.com (alex23) Date: Fri, 23 May 2008 19:39:19 -0700 (PDT) Subject: webspider, regexp not working, why? References: <8c900277-4e80-441c-bbc5-6db7eec4c9ad@f36g2000hsa.googlegroups.com> Message-ID: <4f7add9e-fbcc-4418-a0f0-ef5a542e8fce@q24g2000prf.googlegroups.com> On May 24, 3:26 am, "Reedick, Andrew" wrote: > c) If you're going to parse html/xml then bite the bullet and learn one > of the libraries specifically designed to parse html/xml. Many other > regex gurus have learned this lesson. Myself included. =) Agreed. The BeautifulSoup approach is particularly nice (although not part of stdlib): >>> import urllib >>> from BeautifulSoup import BeautifulSoup >>> html = urllib.urlopen('http://www.python.org/').read() >>> soup = BeautifulSoup(html) >>> links = [link['href'] for link in soup('link')] >>> links[0] u'http://www.python.org/channews.rdf' - alex23 From mail at timgolden.me.uk Mon May 19 06:04:50 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 19 May 2008 11:04:50 +0100 Subject: Using Python for programming algorithms In-Reply-To: <48314dd0$0$32138$426a34cc@news.free.fr> References: <98fa5fa3-45ae-4df1-9fd3-1a227641244f@p25g2000hsf.googlegroups.com> <48314dd0$0$32138$426a34cc@news.free.fr> Message-ID: <483150C2.3080700@timgolden.me.uk> Bruno Desthuilliers wrote: > 2/ actually, all known Python implementations compile to byte-code. In curiosity, did your "actually" mean, in the French sense, "at the moment" or, in the English sense, "in contrast to something stated earlier"? Or maybe both? TJG From george.sakkis at gmail.com Fri May 2 04:24:50 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 2 May 2008 01:24:50 -0700 (PDT) Subject: help with list comprehension References: <7917a0b4-7af2-46f0-adec-33d3b191eb17@y22g2000prd.googlegroups.com> Message-ID: <423509ff-f32a-4e63-b9be-80271e70aef6@25g2000hsx.googlegroups.com> On May 2, 2:17?am, Matimus wrote: > On May 1, 10:50 pm, George Sakkis wrote: > > > > > On May 1, 11:46 pm, Carsten Haese wrote: > > > > Yves Dorfsman wrote: > > > > > In the following script, m1() and m2() work fine. I am assuming m2() is > > > > faster although I haven't checked that (loops through the list twice > > > > instead of once). > > > > Well, let's check it: > > > > $ python -m timeit -s "import x" "x.m1()" > > > 100000 loops, best of 3: 6.43 usec per loop > > > > $ python -m timeit -s "import x" "x.m2()" > > > 100000 loops, best of 3: 8.34 usec per loop > > > > As it turns out, m1 is faster than m2. The reason is that list > > > comprehensions do the loop in C, whereas the for-append pattern does the > > > loop on the Python level. > > > > > Now what I am trying to do is something like m3(). As currently written > > > > it does not work, and I have tried different ways, but I haven't managed > > > > to make it work. > > > > > Is there a possibility ? Or is m2() the optimum ? > > > > > [...] > > > > def m1(): > > > > ? colours = [ e['colour'] for e in l ] > > > > ? nums ? ?= [ e['num'] ? ?for e in l ] > > > > > def m2(): > > > > ? colours = [] > > > > ? nums ? ?= [] > > > > ? for e in l: > > > > ? ? colours.append(e['colour']) > > > > ? ? nums.append(e['num']) > > > > > #def m3(): > > > > # ?colours, nums = [ e['colour'], e['num'] for e in l ] > > > > m3 doesn't work because you're building a list of 10 color/number pairs > > > that you're trying to unpack that into just two names. The working > > > "derivative" of m3 is m1, which is the most natural, fastest and > > > clearest solution to your problem. > > > Another alternative is: > > > from operator import itemgetter > > > def m3(): > > ? ? colours, nums = zip(*map(itemgetter('colour','num'), l)) > > > It's slower than m1() but faster than m2(); it's also the most > > concise, especially if you extract more than two keys. > > > George > > Why deal with zip and unpacking? DRY [1]. This seems more obvious to me: > > colours, nums = map(itemgetter('colour'), l), map(itemgetter('num'), > l) Maybe, but now extend it to three keys. And then four. And then... you see my point. George [1] http://en.wikipedia.org/wiki/Don%27t_repeat_yourself From bignose+hates-spam at benfinney.id.au Mon May 12 03:42:52 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 12 May 2008 17:42:52 +1000 Subject: Is using range() in for loops really Pythonic? References: <482657ca$0$25026$607ed4bc@cv.net> <48275316$0$11629$607ed4bc@cv.net> <3042f24f-f32e-4266-8bf5-41cdb511b78d@m45g2000hsb.googlegroups.com> Message-ID: <873aoo6k8z.fsf@benfinney.id.au> Paddy writes: > I've used Fortran and C and so would tend to use either i,j,k as the > unused loop variable above, or, for clarity, call it something > descriptive like loop_count, if the loop body would be clearer. The problem with all of these names is that they also have long precedent as names of values that *will* be used inside the loop. Because of the precedent of those names, choosing one of those names doesn't make it clear to the reader that the value is never used; they have no indication from you of that until they look over the code a few times. It's implicit rather than explicit. -- \ "As I bit into the nectarine, it had a crisp juiciness about it | `\ that was very pleasurable - until I realized it wasn't a | _o__) nectarine at all, but A HUMAN HEAD!!" -- Jack Handey | Ben Finney From castironpi at gmail.com Wed May 14 19:54:56 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 14 May 2008 16:54:56 -0700 (PDT) Subject: Using file objects with elementtree References: <5dca8f2f-ba08-4cf6-9d45-da2b2e532af8@x35g2000hsb.googlegroups.com> <69184aF2tsmnaU1@mid.uni-berlin.de> Message-ID: On May 14, 5:41?pm, "Diez B. Roggisch" wrote: > dj schrieb: > > > Hello, > > > Rather then holding my XML document in memory before writing it to > > disk, I want to create a file object that elementtree will write each > > element to has it is created. Does any one know how to do that ? > > > Here is my code so, far: > > > fd = open("page.xml", "w") > > tree.write( fd, encoding="iso-8859-1") > > > I know there's something I am doing wrong, but I just do not know > > what. > > This isn't possible. How should ET handle the case that you add a > child-node to a node that has been rendered already? > > What you could try is to serialize subtrees that are closed to a stream. > > Diez What do we render? From ivan.illarionov at gmail.com Thu May 1 10:43:30 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Thu, 1 May 2008 14:43:30 +0000 (UTC) Subject: Best way to store config or preferences in a multi-platform way. References: Message-ID: On Thu, 01 May 2008 08:30:03 -0500, Nick Craig-Wood wrote: > Lance Gamet wrote: >> This project will store most of its actual data in a shared-database, >> but I have a small amount of user specific data that I need to be >> stored like configuration or preferences for example, the list of >> databases that the program should connect to. >> >> On Unix this might be a .file, on windows this could be in the >> registry, or an ini file or an xml file in ProgramData or AppData or >> something. >> >> Is there a pythony way to store such config data, perhaps there is >> already a standard python package for such a purpose? > > I've found > > http://docs.python.org/lib/module-ConfigParser.html > > To be easy to use and built in. It makes human readable / editable .ini > - like files. IMO .ini-like config files are from the stone age. The modern approach is to use YAML (http://www.yaml.org). It has a lot of advantages over .ini and xml, YAML syntax was designed to be easily mapped to Python data types and is very similar to Python. More at http://en.wikipedia.org/wiki/YAML As for where to store it, I completely agree with Nick Craig-Wood. -- Ivan From lowell at allemansonline.com Thu May 29 10:53:50 2008 From: lowell at allemansonline.com (Lowell Alleman) Date: Thu, 29 May 2008 10:53:50 -0400 Subject: Custom log handler and logging.config.fileConfig() In-Reply-To: <72799b9c-bf89-4c50-9e9a-30f0f5a895dd@i76g2000hsf.googlegroups.com> References: <72799b9c-bf89-4c50-9e9a-30f0f5a895dd@i76g2000hsf.googlegroups.com> Message-ID: <839ec5810805290753o5a1c83a2ie29bb481838589cf@mail.gmail.com> Is there any reason not to do this assignment in the "myhandler.py" directly? This would save a step for each application that needs to use it. Starting from your example, it would now look like this: # -- myhandler.py --- import logging.handlers class MySpecialHandler(logging.handlers.RotatingFileHandler): def __init__(self, fn): logging.handlers.RotatingFileHandler.__init__(self, fn, maxBytes=2000, backupCount=3) # Register handler in the "logging.handlers" namespace logging.handlers.MySpecialHandler = MySpecialHandler # -- app.py --- import logging.handlers, logging.config import myhandler logging.config.fileConfig("logging.ini") ... > Hi Lowell, > > I think it's OK to use the logging.handlers namespace to add your > custom handlers - after all, the handlers namespace is for holding > handlers other than the basic ones included in "logging". So... > > # -- myhandler.py --- > import logging.handlers > > class MySpecialHandler(logging.handlers.RotatingFileHandler): > def __init__(self, fn): > logging.handlers.RotatingFileHandler.__init__(self, fn, > maxBytes=2000, backupCount=3) > > > # -- logging.ini --- > [loggers] > keys=root > > [handlers] > keys=hand01 > > [formatters] > keys=form01 > > [logger_root] > level=NOTSET > handlers=hand01 > > [handler_hand01] > class=handlers.MySpecialHandler > level=NOTSET > formatter=form01 > args=("rotating.log",) > > [formatter_form01] > format=%(asctime)s %(levelname)s %(message)s > datefmt= > class=Formatter > > # -- app.py --- > import logging.handlers, logging.config > from myhandler import MySpecialHandler > > logging.handlers.MySpecialHandler = MySpecialHandler > > logging.config.fileConfig("logging.ini") > > logger = logging.getLogger("test") > > for i in xrange(100): > logger.debug("Message no. %d", i) > > > should produce the expected results. > -- > http://mail.python.org/mailman/listinfo/python-list From marco at sferacarta.com Mon May 12 09:27:07 2008 From: marco at sferacarta.com (Marco Mariani) Date: Mon, 12 May 2008 15:27:07 +0200 Subject: Now what!? In-Reply-To: <9GlVj.168$PE5.102@fe087.usenetserver.com> References: <68m0i1F2t8265U1@mid.uni-berlin.de> <7363f4c0-1dec-4943-a9f6-7a24c3aff971@e39g2000hsf.googlegroups.com> <9GlVj.168$PE5.102@fe087.usenetserver.com> Message-ID: notbob wrote: > frustrated and give up on learning programming, not really caring much for > coding, anyway. But, dammit, I'm gonna stick with it this time. I'll learn > python if it kills me! No, it won't kill you but make you stronger ;) From http Sun May 11 01:38:55 2008 From: http (Paul Rubin) Date: 10 May 2008 22:38:55 -0700 Subject: Is using range() in for loops really Pythonic? References: <482657ca$0$25026$607ed4bc@cv.net> Message-ID: <7xabix2yds.fsf@ruckus.brouhaha.com> John Salerno writes: > for x in range(10): > #do something 10 times > > is unPythonic. The reason I ask is because the structure of the for loop > seems to be for iterating through a sequence. It seems somewhat > artificial to use the for loop to do something a certain number of > times, like above. It is pretty natural in imperative-style code. The one thing I'd do differently is use xrange instead of range, to avoid creating a 10-element list in memory before starting the loop. From boblatest at googlemail.com Wed May 21 05:38:10 2008 From: boblatest at googlemail.com (boblatest at googlemail.com) Date: Wed, 21 May 2008 02:38:10 -0700 (PDT) Subject: C-like assignment expression? Message-ID: <68b5d090-9e3b-4e7d-9dda-fc1b099822c2@m73g2000hsh.googlegroups.com> Hello, I have an if-elif chain in which I'd like to match a string against several regular expressions. Also I'd like to use the match groups within the respective elif... block. The C-like idiom that I would like to use is this: if (match = my_re1.match(line): # use match elsif (match = my_re2.match(line)): # use match elsif (match = my_re3.match(line)) # use match ...buy this is illegal in python. The other way is to open up an else: block in each level, do the assignment and then the test. This unneccessarily leads to deeper and deeper nesting levels which I find ugly. Just as ugly as first testing against the RE in the elif: clause and then, if it matches, to re-evaluate the RE to access the match groups. Thanks, robert From grante at visi.com Thu May 22 17:00:02 2008 From: grante at visi.com (Grant Edwards) Date: Thu, 22 May 2008 16:00:02 -0500 Subject: Bug in ssl-object library reference page or in ssl-object code? Message-ID: According to http://docs.python.org/lib/ssl-objects.html 17.2.2 SSL Objects SSL objects have the following methods. read([n]) If n is provided, read n bytes from the SSL connection, otherwise read until EOF. The return value is a string of the bytes read. The behavior I observer when n is not provided doesn't agree with the description. When I call read(), it appears that I get whatever data is currently available. It does not read until EOF. This seems to agree with the comment on the "example" page: http://docs.python.org/lib/socket-example.html # Read a chunk of data. Will not necessarily # read all the data returned by the server. data = ssl_sock.read() If read() did indeed read until EOF, then it would always read all of the data returned by the server. Is this a bug in the doc or in the code? -- Grant Edwards grante Yow! How do I get HOME? at visi.com From landofdreams at gmail.com Thu May 1 01:46:24 2008 From: landofdreams at gmail.com (Sam) Date: Wed, 30 Apr 2008 22:46:24 -0700 (PDT) Subject: relative import broken? References: <9c6ba5f9-d65b-4265-baba-fc5d7936781b@d1g2000hsg.googlegroups.com> <87prs6x1ye.fsf@mulj.homelinux.net> <33782b65-6d6d-4ae7-8539-29f809ae5077@d45g2000hsc.googlegroups.com> <87iqxyboae.fsf@physik.rwth-aachen.de> Message-ID: <6ddbc077-0092-4378-b613-5a5656b0e53e@l42g2000hsc.googlegroups.com> > I didn't look it up myself, but maybe a __init__.py file is missing > so that it can be recognised as a package. No, every single one (S, B, and W) has its own __init__.py > >> > in u.py Python gives "ImportError: No module named S". > > >> A silly question: is the directory that contains "S" in PYTHONPATH or > >> in sys.path? > > > It's in sys.path. > > "S" or its parent directory? I added r'C:\Users\Myname\S' to sys.path. Is this the correct usage? Sam From sjdevnull at yahoo.com Wed May 21 15:23:14 2008 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: Wed, 21 May 2008 12:23:14 -0700 (PDT) Subject: Struct usage and varying sizes of h, l, etc References: <48335269.2000809@admailinc.com> Message-ID: <3139388e-f453-437e-bbc3-abb10fa2d94c@2g2000hsn.googlegroups.com> On May 21, 10:04 am, Grant Edwards wrote: > Yes, C defines "char" to be one byte, but it doesn't define the > size of a "byte" other than it's at least big enough to hold > one character (or something like that). In practice, a byte is > pretty much guaranteed to be at least 8 bits. If you're discussing standard C, you can omit "in practice" and "pretty much". CHAR_BITS is required to be at least 8 by the ANSI/ISO C Standard. > But, on some targets a "byte" is 16 bits, and on others a byte > is 32 bits. Yep, or 9 bits or 36 bits, or anything >= 8. From martin at v.loewis.de Sun May 25 16:13:26 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 25 May 2008 22:13:26 +0200 Subject: set partition question In-Reply-To: References: Message-ID: <4839c866$0$32633$9b622d9e@news.freenet.de> > s0 = set([1]) > s1 = set([1,2]) > s2 = set([2]) > S = set([s0,s1,s2]) > one answer we're searching for is s0 = s1 - s2 > > There may be arbitrarily many set elements (denoted by integers > 1,2,3,...) and arbitrarily many combinations of the elements composing > the sets s_i (s0, s1, ...). We can use any operation or function which > takes and returns sets. In that case, there is always a trivial answer. As I can use any function which takes and returns sets, and as I shall come up with a function that returns s0, I just use the following function def f(s): return s0 To compute s0, just invoke f with any other of the sets, and you will - get s0. > I think this problem is related to integer partitioning, but it's not > quite the same. I think the problem is significantly underspecified. It would be a more interesting problem if there was a restriction to a few selected set operations, e.g. union, intersection, difference, and combinations thereof. Regards, Martin From corvettecraz92 at gmail.com Sat May 31 15:28:33 2008 From: corvettecraz92 at gmail.com (corvettecraz92 at gmail.com) Date: Sat, 31 May 2008 12:28:33 -0700 (PDT) Subject: Question about files? References: <3a260685-b285-43ef-9e2c-c42cfbd4c497@y38g2000hsy.googlegroups.com> Message-ID: On May 31, 3:25?pm, Dennis Lee Bieber wrote: > On Sat, 31 May 2008 11:44:14 -0700 (PDT), corvettecra... at gmail.com > declaimed the following in comp.lang.python: > > > I want to create a program where a user can type what ever they want > > to, have it saved to a file, and the be able to re-open it and read > > it. How would I do this? Thanks! > > import os > os.system("edit") ? ? # may be Windows specific > > ? ? ? ? Start with:http://www.catb.org/~esr/faqs/smart-questions.html > > (or, to expand on it... Exactly what part of the task are you having > problems with? Opening files for read/write/update? Designing a command > set for an editor? Designing a GUI for a text editor; what toolkit, does > it have a generic text edit widget already? Do you really need to write > another text editor when there are so many available that come with most > operating systems (Windows: edit, notepad, maybe even wordpad; > UNIX/Linux type systems: vi, vim, gvim, emacs) or can be downloaded > (SciTE) ) > > -- > ? ? ? ? Wulfraed ? ? ? ?Dennis Lee Bieber ? ? ? ? ? ? ? KD6MOG > ? ? ? ? wlfr... at ix.netcom.com ? ? ? ? ? ? ?wulfr... at bestiaria.com > ? ? ? ? ? ? ? ? HTTP://wlfraed.home.netcom.com/ > ? ? ? ? (Bestiaria Support Staff: ? ? ? ? ? ? ? web-a... at bestiaria.com) > ? ? ? ? ? ? ? ? HTTP://www.bestiaria.com/ No, what I mean is for the user to input text directly into the python program, then the program would save it to a file and display it after it is created. From saluk64007 at gmail.com Fri May 9 11:44:21 2008 From: saluk64007 at gmail.com (Patrick Mullen) Date: Fri, 9 May 2008 08:44:21 -0700 Subject: Free Memory In-Reply-To: References: <8a6035a00805081730g2a18b97cxc32ae6568fb10b81@mail.gmail.com> Message-ID: I had some very interesting results with this code to do what is asked: for key in globals().keys(): del globals()[key] for key in locals().keys(): del locals()[key] It might be better to reverse the two steps, I didn't give it much thought. Anyway, when this is done, all of the builtins spill into globals and locals (since __builtin__ was deleted). I thought that was interesting. It did have the effect that is asked for, although there may be more unintended consequences. Also if any objects are attached to any of the builtins I expect they will still be around. -------------- next part -------------- An HTML attachment was scrubbed... URL: From timr at probo.com Sun May 11 19:26:07 2008 From: timr at probo.com (Tim Roberts) Date: Sun, 11 May 2008 23:26:07 GMT Subject: Python, are you ill? References: <893925d6-a4f8-4446-9bf3-475302dbaa04@j22g2000hsf.googlegroups.com> Message-ID: wxPythoner at gmail.com wrote: > >If you are in the interactive prompt of the Python interpreter and you >do this > >print """Testing\""" or print '''Testing\''' > >you get three dots [...] as if Python expects a code block. ...which it does. >If you >press Enter, you get three dots again, and again, and again... You >can't get out of the code block with pressing the Enter key; you have >to press Ctrl+Z (if you're in Linux) in order to get out of that code >block, No, you don't. You can also enter """ or ''' to properly close the quote. >If you do > >print "Testing\" or print 'Testing\' > >you get an error, but not of you use the triple quotes. Is that a bug >in the interpreter perhaps? As a general rule, when you are just beginning to learn some product, it is safe to assume that anything you see as a bug in the product is almost certainly a flaw in your understanding of the product. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From vadim.pestovnikov at gmail.com Thu May 1 10:07:28 2008 From: vadim.pestovnikov at gmail.com (idev) Date: Thu, 1 May 2008 07:07:28 -0700 (PDT) Subject: Please help me with linking libraries on Solaris 10 sparc Message-ID: <89620267-578c-4d06-9afd-0684b5d646f5@c58g2000hsc.googlegroups.com> Hi all, Please help me with my stuff. I downloaded python 2.5.1 package from http://blastwave.org it was compiled using Sun Studio 11 for Solaris 8 sparc. My system is Solaris 10 sparc and I compiled using SunStudio 11 psycopg2 python binding for PostgreSQL 8.3.1. Compilation was OK, but when I am trying to import psycopg2 I am getting this error: $ python Python 2.5.1 (r251:54863, Nov 3 2007, 02:54:52) [C] on sunos5 Type "help", "copyright", "credits" or "license" for more information. >>> import psycopg2 Traceback (most recent call last): File "", line 1, in File "/opt/csw/lib/python/site-packages/psycopg2/__init__.py", line 60, in from _psycopg import BINARY, NUMBER, STRING, DATETIME, ROWID ImportError: ld.so.1: python: fatal: relocation error: file /opt/csw/ lib/python/site-packages/psycopg2/_psycopg.so: symbol round: referenced symbol not found Any suggestions or help will be appreciated. From castironpi at gmail.com Tue May 13 10:08:35 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 13 May 2008 07:08:35 -0700 (PDT) Subject: Best way to delimit a list? References: <57129f75-b496-40fc-8b2d-d93ba544d4c5@u6g2000prc.googlegroups.com> Message-ID: On May 13, 8:32?am, Peter Otten <__pete... at web.de> wrote: > Giuseppe Ottaviano wrote: > > def ichain(seq): > > ????????for s in seq: > > ????????????????for x in s: yield x > > > (which is often useful and I don't think it has been included in ? > > itertools) you can iterate lazily on the file: > > Python 2.6 includes itertools.chain.from_iterable() with that functionality. > > Peter Can you color the help manual with very fine shades of off-white to ease reading? I was thinking a few pixels shy of red of white to accentuate what are the class methods and which are not. I also have an argument that net readability would decrease, but the sample sizes on that kind of metric are a little brinky with privacy fears around where I'm from. I just try to make Tron rings. From mcknight0219 at gmail.com Fri May 23 04:38:06 2008 From: mcknight0219 at gmail.com (Jimmy) Date: Fri, 23 May 2008 01:38:06 -0700 (PDT) Subject: can python do some kernel stuff? References: <983ec0f6-1316-40cd-a4d4-ce9b5e272a60@h1g2000prh.googlegroups.com> <48366cfa$0$15168$607ed4bc@cv.net> Message-ID: <28c432f0-657c-4272-8cd4-a9081b013279@w5g2000prd.googlegroups.com> On May 23, 3:05 pm, Andrew Lee wrote: > Jimmy wrote: > > Hi to all > > > python now has grown to a versatile language that can > > accomplish tasks for many different purposes. However, > > AFAIK, little is known about its ability of kernel coding. > > > So I am wondering if python can do some kernel coding that > > used to be the private garden of C/C++. For example, can python > > intercept the input of keyboard on a system level? someone told me > > it's a kernel thing, isn't it? > > http://wiki.python.org/moin/elmer well, straightly speaking, how can I know a key is pressed on a system- level if using python? From ptmcg at austin.rr.com Tue May 27 02:37:17 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 26 May 2008 23:37:17 -0700 (PDT) Subject: Hungarian Notation References: Message-ID: <74d9c37f-807c-4aae-8ad5-db79bb3e2bd2@8g2000hse.googlegroups.com> On May 27, 12:28?am, "inhahe" wrote: > Does anybody know of a list for canonical prefixes to use for hungarian > notation in Python? ?Not that I plan to name all my variables with hungarian notation, but just for when it's appropriate. You are likely to get some links to PEP 8 for coding style and naming conventions, but it turns out PEP 8 doesn't really say yay or nay on the Hungarian notation topic. My own knee-jerk reaction was "Hungarian Notation Bad!" and googling about for "python hungarian notation" led me through some like-minded sites. But I also found this entry on Joel Spolky's site (http:// www.joelonsoftware.com/printerFriendly/articles/Wrong.html), that warns against tarring all Hungarian-type notations with the same brush. So with that article in mind, I'd have to ask, what do you mean by "appropriate"? -- Paul From xahlee at gmail.com Sat May 10 01:52:30 2008 From: xahlee at gmail.com (xahlee at gmail.com) Date: Fri, 9 May 2008 22:52:30 -0700 (PDT) Subject: implementation for Parsing Expression Grammar? Message-ID: In the past weeks i've been thinking over the problem on the practical problems of regex in its matching power. For example, often it can't be used to match anything of nested nature, even the most simple nesting. It can't be used to match any simple grammar expressed by BNF. Some rather very regular and simple languages such as XML, or even url, email address, are not specified as a regex. (there exist regex that are pages long that tried to match email address though) I wrote out a more elaborate account of my thoughts here: http://xahlee.org/cmaci/notation/pattern_matching_vs_pattern_spec.html ---------------- After days of researching this problem, looking into parsers and its theories etc, today i found the answer!! What i was looking for is called Parsing Expression Grammar (PEG). See http://en.wikipedia.org/wiki/Parsing_expression_grammar It seems to me it's already in Perl6, and there's also a implementation in Haskell. Is the perl6 PEG is in a usable state? Thanks. Xah xah at xahlee.org ? http://xahlee.org/ ? From vbgunz at gmail.com Tue May 13 00:05:29 2008 From: vbgunz at gmail.com (vbgunz) Date: Mon, 12 May 2008 21:05:29 -0700 (PDT) Subject: Orlando Florida Python Tutor Needed References: <7ce42a69-8c6b-435b-a125-2a619b3a8603@k13g2000hse.googlegroups.com> Message-ID: <269346bf-b025-4d73-8a4a-8446946e956d@j22g2000hsf.googlegroups.com> > I know you're looking for "one-on-one" help, direction, and/or > tutelage, but since you've not received an answer (yet), here's some > general info... > For Decorators, have a gander at: > ? ?http://www.ddj.com/web-development/184406073;jsessionid=QCNTPTSNXZP2W... > ? ?http://www.ibm.com/developerworks/linux/library/l-cpdecor.html I found the first link to decorators a while back. I didn't think much of it and said to myself, I'd find it again. My googlefu wasn't on my side this time so I thank you for bringing it to my attention again. Very very good article. Cleared up some confusion on decorators and I am much better and sharper at them. I think what makes the *idea* of a decorator so hard is how *simple* it really is. From my learning them so far, I know for a fact, I've encountered situations in which decorators would have saved me from headache and grief. Now, an excellent piece of ammo for the arsenal. Lets see if I could explain a decorator in my own words. a decorator is just a pattern e.g., nothing magical about them except for the syntactical sugar '@'. The @func sugar is nothing more than a hook that embeds the following function into the @func first argument (similar to self or cls) AND then Python *implicitly* reassigns the original function name to that of the decorator which enclosed it. From this point out it's pretty much a closure or the wider known factory function but the real essence of a decorator that can make it a better closure is how *unobtrusive* it is at modifying a function *without* actually manually rewriting the original function. Also, the decorator hook '@' reduces duplication and makes explicit the idea that a function is to be *decorated*. I may have some terminology wrong but think I am actually getting the hang of decorators. very very useful indeed. I have some stuff working without a hitch though still a bit foggy on passing *args, **etc. Well, not that I plan on using them for everything but I've already experienced cases in which I know a decorator would have saved my ass. Am so glad I took the time out to learn them. I'll learn them again tomorrow and go over all the links you provided to me. Larry, thank you for the links, I really appreciate them. If you or anyone have any tips or more links on some good articles regarding them, I would surely enjoy seeing them. Now, class methods. What is one powerful common use case for them? What is one thing they can do in which could perhaps be the sole reason for their existence? heh. I'll get them too :) From workitharder at gmail.com Wed May 21 20:21:09 2008 From: workitharder at gmail.com (bukzor) Date: Wed, 21 May 2008 17:21:09 -0700 (PDT) Subject: simple way to touch a file if it does not exist References: Message-ID: <68629786-1cef-4dc5-99d9-4967ebecd10f@r66g2000hsg.googlegroups.com> On May 21, 5:10 pm, "Giampaolo Rodola'" wrote: > On 22 Mag, 01:15, Nikhil wrote: > > > what are the simple ways? > > I could think of os.open(), os.exec(touch file) > > > are there any simpler methods? > > Just use os.path.exists to check for file existence and open() as > replacement for touch. > > >>> import os > >>> if not os.path.exists('file'): > > ... open('file', 'w').close() > ... > > > > --- Giampaolohttp://code.google.com/p/pyftpdlib/ As simple as it gets is a single builtin function call: open("somefile.txt", "a") Leave out the ,"a" if you don't mind blanking a pre-existing file. From papapep at gmail.com Fri May 30 08:24:57 2008 From: papapep at gmail.com (Josep) Date: Fri, 30 May 2008 14:24:57 +0200 Subject: Python 2.5.2 on Ubuntu Hardy Utf-8-Euro error Message-ID: <1212150297.18549.5.camel@awacs> I'm playing with an application framework (or kinda) that's developed with python, and it throws this error: > File "/usr/lib/python2.5/site-packages/Dabo-0.8.3-py2.5.egg/dabo/db/dCursorMixin.py", line 281, in execute > sql = unicode(sql, self.Encoding) > LookupError: unknown encoding: utf_8_euro At the application (DABO) mailing list, they have pointed that this has to be a Python issue. As I'm a totally python newbie, I would ask if somebody has experimented this kind of error, and if there is any known solution. I've found no clue searching at Google right now. My Python version is 2.5.2, Ubuntu Hardy .deb package. Thanks in advance for your help. -- Josep S?nchez [papapep] ---------------------------------- http://extralinux.net ---------------------------------- -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Aix? ?s una part d'un missatge signada digitalment URL: From bruno.desthuilliers at gmail.com Wed May 7 18:12:26 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Wed, 7 May 2008 15:12:26 -0700 (PDT) Subject: Am I missing something with Python not having interfaces? References: <45de2f7e-484a-4871-bbaa-bf7eed5dfa40@x35g2000hsb.googlegroups.com> <74f98740-6f44-44da-b546-dc1cb1bb9006@a23g2000hsc.googlegroups.com> Message-ID: <40145aba-c389-4aa4-bb6a-faf2e7de12c8@s50g2000hsb.googlegroups.com> On 7 mai, 21:19, Daniel Marcel Eichler wrote: > Am Dienstag 06 Mai 2008 16:07:01 schrieb Mike Driscoll: > > > If so, then it looks like an Interface is a generic class with method > > stubs. You can do that with Python just as easily by creating empty > > methods with just the "pass" keyword. > > Well, no. It's a litte different. Interfaces force to implement methods. > Simple inheritance with method-stubs can't garantee that a specific > method is reimplementat in a sub-class. And Java's "Interface" wart can't garantee that a specific method is *appropriately* implemented. One often sees do-nothing methods in Java code - useless boilerplate code that's only here to satisfy the compiler. It's just like Java's "checked exception" mechanism : one very often sees do-nothing catch-all try/catch blocks in Java - which is way worse than just letting the exception propagate. I find all this totally pointless, because there's just no way for a compiler to check if your code is logically correct. > Interfaces work at > compile-time, while method-stubs raise at their first call, so in worst > case, never. And then ? If it's never called, why bother implementing it ? Here again, I don't see the point of compile-time checking. RuntimeError is a well-known Java exception, so the fact is that Java forces you into either rigid designs or overly complex workarounds (best knowns as "design patterns"), without even being able to garantee anything wrt/ correctness nor even safety. Not that static typing by itself is necessarily bad - as usual, there's a balance between somewhat conflicting goals -, but Java's type system definitivly is (bad). (snip) > That's the point. Interfaces garantee that a duck is a duck, an not only > a chicken that quack. Who cares if it's a chicken as long as it quacks when you ask her to ? Now *This* is the whole point of chicken^Mduck typing, isn't it ?-) From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon May 19 15:53:18 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 19 May 2008 21:53:18 +0200 Subject: Thread output with ncurses References: Message-ID: <69e45eF31tjn1U1@mid.individual.net> blaine wrote: > The idea would be that the application simply has three 'windows' > or 'pads' and each thread would output to their respective one. I don't know much about ncurses, but I suggest you better use multiple processes (subprocess module). Regards, Bj?rn -- BOFH excuse #434: Please state the nature of the technical emergency From arnodel at googlemail.com Wed May 14 16:44:51 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 14 May 2008 21:44:51 +0100 Subject: Class Methods Vs Any Other Callable References: <98b4a67c-9ec7-407c-8c80-06488bd48a68@e39g2000hsf.googlegroups.com> <690ap7F2u0ftdU1@mid.uni-berlin.de> <238061d6-9423-44c1-90b2-cc09f392db9b@p25g2000hsf.googlegroups.com> <2851a281-d3f2-46c5-8afe-a5dcd6fa31a6@59g2000hsb.googlegroups.com> Message-ID: "bruno.desthuilliers at gmail.com" writes: > On 14 mai, 19:45, Arnaud Delobelle wrote: >> __new__ is a static method! > > __new__ is a special-cased staticmethod that 1/ must not be declared > as such and 2/ takes the class object as first args. As far as I'm > concerned, it's semantically a classmethod. It's a static method! -- Arnaud From castironpi at gmail.com Tue May 13 11:28:26 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 13 May 2008 08:28:26 -0700 (PDT) Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <2b66a86e-5a05-4262-b3c9-4703b0ae3372@d1g2000hsg.googlegroups.com> <5b0e3f70-afde-4480-8713-e7113b1250d7@x35g2000hsb.googlegroups.com> <1f537717-00d0-48ee-99b6-7125b96a6133@t12g2000prg.googlegroups.com> <68t4o0F2vaoncU1@mid.uni-berlin.de> <2a32179a-9439-449c-bd07-fff6a4075aee@s50g2000hsb.googlegroups.com> <7ee5dffd-df8f-46f0-bd78-c81ac0418a9a@d77g2000hsb.googlegroups.com> <65ef773e-a1c3-4adb-a18b-e8b8451efe5e@b5g2000pri.googlegroups.com> Message-ID: <8fb7373c-e8ee-4eeb-9549-d17ac25a1ec6@c65g2000hsa.googlegroups.com> On May 13, 10:24?am, Dave Parker wrote: > > ?The "Flaming Thunder" looks promising, but without being free > > software, it's unlikely it will create a large developer community, > > specially considering both free general purpose and scientific > > programming languages. > > Perhaps. ?Flaming Thunder is only $19.95 per year for an individual > (and even less per individual for site licenses), which is less than > the cost of just one book on Python. > > I think that many people will find that Flaming Thunder is easier to > use and understand than Python -- so for many people the amount of > time they save will be worth more than the cost of Flaming Thunder > (unless, of course, their time is worth $0). > > Also, several users have rewritten their Python programs in Flaming > Thunder, and found that Flaming Thunder was 5 to 10 times faster > (Flaming Thunder compiles to native executables). ?So again, since > many people value their time at more than $0, I think that many people > will find that Flaming Thunder is worth $19.95 per year. > > Plus, me getting paid to work on Flaming Thunder is far more > motivating than me not getting paid to work on Python. ?This weekend, > Python users will still be debating how to fix awkwardnesses in the > languages (such as FOR loops where you're just counting the loops and > not referencing the loop variable) -- but Flaming Thunder users will > be getting work done using the REPEAT n TIMES constructs that I'll be > implementing. > > Python has been around about 15 years, yet still has those > awkwardnesses. ?Flaming Thunder has been out less than 6 months and > those awkwardnesses are already getting fixed. ?The difference: I > can't afford to ignore users. > > But the future is one of the hardest things to predict, so we'll see. > > On May 13, 8:34?am, hdante wrote: > > > > > On May 13, 10:58?am, Paul McGuire wrote: > > > > On May 13, 8:32?am, Dave Parker wrote: > > > > > > Don't let yourself be irritated by castironpi > > > > > I'm not the sort to get irritated by anyone. ?There is value in all > > > > interaction. > > > > Not this interaction, I'm afraid. ?What irritates *me* about > > > castironpi is that he uses a chatterbot to clutter up the threads > > > here. ?If you go back to his postings from a year ago (and selected > > > ones since), his comments are coherent and sensible. ?These rambling > > > stream-of-consciousness rants about t.v.'s and coffee are (I guess) > > > his idea of a joke. ?But they are certainly not worth your time in > > > trying to respond to them. > > > > -- Paul > > > ?I don't think castironpi so annoying that I should filter its > > messages. It would be enough if he were better tuned. He is much > > smarter than the emacs shrink, for example. :-P > > > ?The "Flaming Thunder" looks promising, but without being free > > software, it's unlikely it will create a large developer community, > > specially considering both free general purpose and scientific > > programming languages.- Hide quoted text - > > > - Show quoted text -- Hide quoted text - > > - Show quoted text - How come no one said lightning? From sjmachin at lexicon.net Tue May 13 16:57:09 2008 From: sjmachin at lexicon.net (John Machin) Date: Tue, 13 May 2008 20:57:09 GMT Subject: do you fail at FizzBuzz? simple prog test In-Reply-To: References: <39709320-66e1-40e9-a351-c769c9a94585@x41g2000hsb.googlegroups.com> <688a0f5a-2cdf-45ca-abe7-5bbb89aac32f@s50g2000hsb.googlegroups.com> Message-ID: <482a00a2@news.mel.dft.com.au> Matthew Woodcraft wrote: > Gabriel Genellina wrote: >> I would like to write a similar problem without this non-programming >> distracting issues (that is, a problem simple enough to be answered in a >> few minutes, that requires only programming skills to be solved, and >> leaving out any domain-specific knowledge). > > Another reason not to like the FizzBuzz example is that it's quite > closely balanced between two reasonable approaches (whether to just > special-case multiples of 15 and say 'FizzBuzz', or whether to somehow > add the Fizz and the Buzz together in that case). The interviewee might > reasonably guess that this distinction is what's being tested, and get > unnecessarily stressed about it. > For such a trivial problem, fifteen minutes is more than enough to present alternative answers. Perhaps the intention is to weed out those who do become unnecessarily stressed in such circumstances. Employers like to play tricks to see how interviewees respond e.g. hand over two pages of a listing of code in language X, announce that there are 10 syntax errors, and ask the interviewee to find and circle all the syntax errors. Correct answer: 11 circles. From stefan_ml at behnel.de Sat May 17 11:17:29 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sat, 17 May 2008 17:17:29 +0200 Subject: Getting elements and text with lxml In-Reply-To: References: Message-ID: <482EF709.3000604@behnel.de> J. Pablo Fern?ndez wrote: > I have an XML file that starts with: > > > > > *-a > > > out of it, I'd like to extract something like (I'm just showing one > structure, any structure as long as all data is there is fine): > > [("ofc", "*"), "-", ("rad", "a")] >>> root = etree.fromstring(xml) >>> l = [] >>> for el in root.iter(): # or root.getiterator() ... l.append((el, el.text)) ... l.append(el.text) or maybe this is enough: list(root.itertext()) Stefan From ma.saeedi at gmail.com Thu May 8 12:12:57 2008 From: ma.saeedi at gmail.com (Maryam Saeedi) Date: Thu, 8 May 2008 11:12:57 -0500 Subject: Running a python code periodically In-Reply-To: <237596740805080907x3546ea8q72cf49a80b6ae18e@mail.gmail.com> References: <237596740805080907x3546ea8q72cf49a80b6ae18e@mail.gmail.com> Message-ID: Can you please explain it a little more? I do not have that much experience! I really appreciate it if you can share a sample code if you have one. Thanks On Thu, May 8, 2008 at 11:07 AM, Amitabh Saikia wrote: > write a bash script(to run your program at intervals) and run the bash > script with nohup > > - saikia at unspokenmind.net > > On Thu, May 8, 2008 at 9:02 AM, Maryam Saeedi wrote: > >> I was wondering if you know how can I run a python code once every five >> minutes for a period of time either using python or some other program like >> a bash script. >> >> I have asked this question before and some of you answered me but I still >> have problem. Most of the answers was to use cron and crontab which works on >> my computer but not if I want to do it on department's computer since I do >> not have permission to change those files. Is there any other way which does >> not need administrator permission? >> >> Thanks a lot, >> >> Maryam >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > -- Maryam Saeedi PhD student Economics Department University of Minnesota -------------- next part -------------- An HTML attachment was scrubbed... URL: From straton at lampsacos.demon.co.uk Sat May 10 08:14:03 2008 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Sat, 10 May 2008 13:14:03 +0100 Subject: Authoring SOAP and WSDL Message-ID: I would like to write SOAP services in python, and have an environment that will then generate a matching WSDL for me automatically. Does such a thing exist in python? Thanks in advance. Ken. From caca at mailinator.com Sat May 31 07:56:17 2008 From: caca at mailinator.com (caca at mailinator.com) Date: Sat, 31 May 2008 04:56:17 -0700 (PDT) Subject: How to get all the variables in a python shell References: Message-ID: I meant it prints 4, which means the value of test is modified by the access to the dict > test=5 > __IPYTHON__.user_ns['test']=4 > print test #prints 4 > From wuwei23 at gmail.com Sun May 11 09:50:13 2008 From: wuwei23 at gmail.com (alex23) Date: Sun, 11 May 2008 06:50:13 -0700 (PDT) Subject: Make Python create a tuple with one element in a clean way References: Message-ID: On May 11, 10:54 pm, wxPytho... at gmail.com wrote: > I thought that just putting a value inside ( ) > would make a tuple. Apparently that is not the case. It's not the case at all. Check out the Tuples & Sequences section in the python docs at http://docs.python.org/tut/node7: "A tuple consists of a number of values separated by commas" So it's not the parentheses that define it as a tuple, but the comma. >>> my_tuple = 1, >>> my_tuple (1,) >>> type(my_tuple) Hope this helps. - alex23 From yves at zioup.com Wed May 7 19:40:26 2008 From: yves at zioup.com (Yves Dorfsman) Date: Wed, 07 May 2008 23:40:26 GMT Subject: class definition Message-ID: Does it make a difference if you put subclass object or not ? What is the difference between c1 and c2 here: class c1: pass class c2(object): pass Thanks, Yves. http://www.SollerS.ca From alangrow at gmail.com Sat May 17 15:32:44 2008 From: alangrow at gmail.com (alan) Date: Sat, 17 May 2008 12:32:44 -0700 (PDT) Subject: waiting on an event blocks all signals Message-ID: <27553255-72e6-4df6-944b-ac4637a78f3d@m3g2000hsc.googlegroups.com> This ignores CTRL-C on every platform I've tested: python -c "import threading; threading.Event().wait()" ^C^C^C^C It looks to me like all signals are masked before entering wait(). Can someone familiar with the internals explain and/or justify this behavior? Thanks, -Alan From arnodel at googlemail.com Sun May 4 03:10:40 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 04 May 2008 08:10:40 +0100 Subject: word shifts References: Message-ID: dave writes: > Hello, > > I made a function that takes a word list (one word per line, text > file) and searches for all the words in the list that are 'shifts' of > eachother. 'abc' shifted 1 is 'bcd' > > Please take a look and tell me if this is a viable solution. > > def shift(word, amt): > ans = '' > for letter in word: > ans = ans + chr((ord(letter) - ord('a') + amt) % 26 + ord('a')) > return ans In Python, if you want to build a string from lots of parts you can use ''.join(parts). I think it is considered more efficient. > > def fileshift(x): > fin = open(x) > d = {} > for line in fin: > d[line.strip()] = [1] > for i in range(1, 26): > ite = shift(line.strip(), i) > if ite in d: > print ite > You could write: line = line.strip() after your for line in fin: statement, rather than strip the line twice. Let me suggest a different solution base on the str.translate() method from string import lowercase, maketrans shifted_lowercase = lowercase[1:] +lowercase[0] table = string.maketrans(lowercase, shifted_lowercase) def shift1(line): return line.translate(table) def fileshift(path): lines = set() for line in open(path): lines.add(line) for i in xrange(25): line = shift1(line) if line in lines: print line (untested) -- Arnaud From ivan.illarionov at gmail.com Sat May 3 14:04:50 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Sat, 3 May 2008 18:04:50 +0000 (UTC) Subject: Feature suggestion: sum() ought to use a compensated summation algorithm References: Message-ID: On Sat, 03 May 2008 18:50:34 +0200, Szabolcs Horv?t wrote: > I did the following calculation: Generated a list of a million random > numbers between 0 and 1, constructed a new list by subtracting the mean > value from each number, and then calculated the mean again. > > The result should be 0, but of course it will differ from 0 slightly > because of rounding errors. > > However, I noticed that the simple Python program below gives a result > of ~ 10^-14, while an equivalent Mathematica program (also using double > precision) gives a result of ~ 10^-17, i.e. three orders of magnitude > more precise. > > Here's the program (pardon my style, I'm a newbie/occasional user): > > from random import random > > data = [random() for x in xrange(1000000)] > > mean = sum(data)/len(data) > print sum(x - mean for x in data)/len(data) > > A little research shows that Mathematica uses a "compensated summation" > algorithm. Indeed, using the algorithm described at > http://en.wikipedia.org/wiki/Kahan_summation_algorithm gives us a result > around ~ 10^-17: > > def compSum(arr): > s = 0.0 > c = 0.0 > for x in arr: > y = x-c > t = s+y > c = (t-s) - y > s = t > return s > > mean = compSum(data)/len(data) > print compSum(x - mean for x in data)/len(data) > > > I thought that it would be very nice if the built-in sum() function used > this algorithm by default. Has this been brought up before? Would this > have any disadvantages (apart from a slight performance impact, but > Python is a high-level language anyway ...)? > > Szabolcs Horv?t Built-in sum should work with everything, not just floats. I think it would be useful addition to standard math module. If you know C you could write a patch to mathmodule.c and submit it to Python devs. -- Ivan From kyosohma at gmail.com Mon May 26 17:18:16 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 26 May 2008 14:18:16 -0700 (PDT) Subject: Keyboard Events References: <14d057b1-3b62-4efb-bdb2-c20394c7268c@r66g2000hsg.googlegroups.com> Message-ID: <0c2af756-7edb-4cd1-9972-2250090c65ad@m73g2000hsh.googlegroups.com> On May 26, 2:06?pm, Gandalf wrote: > I use WX on windows XP and I try to generate an event when the user is > clicking the keyboard while the application frame is not in focus. > All I manged to do were while the application frame is in focus > Can someone please show me how to do it? > > Thanks ! You can only catch the keyboard events for whichever widget is in focus. So, if you have a text control, you'll need to bind to that. The events you're likely need are EVT_KEYDOWN or EVT_CHAR. You cannot catch keyboard events with wx if you are using MS Word. For that sort of thing,you'll have to hook in at the OS level. Mike From tjreedy at udel.edu Tue May 27 02:28:25 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 27 May 2008 02:28:25 -0400 Subject: Why Turn "Print" into "Print()"???? References: <248a2c45-caae-49bb-b8ff-701af8b86207@p25g2000hsf.googlegroups.com> Message-ID: "alex23" wrote in message news:b38b30a9-dbe1-4a78-ba14-7fc36ae20bf9 at z16g2000prn.googlegroups.com... | On May 26, 7:21 pm, Prisoner at War wrote: | > But I'd read that Python 3 is very different in many important ways. | > I read it right there on the Py3K site! I can't make sense of how, | > why, even what, exactly, but that's not a misimpression on my part, I | > certain nonetheless...it's not just cosmetic changes but important | > ones pertaining to a sort of "linguistic logic" I gather.... One important different for beginners is the elimination of old ways that no longer need be learned. Another is that a few inconsistencies have be ironed out. | Well, let's see what Guido says about the issue: | | Q. I want to learn Python. Should I learn Python 2.6 or Python 3.0? | | A. Definitely learn Python 2.x (the latest version out is 2.5). I | expect it'll be two years before you'll need to learn Python 3.0, and | the differences aren't that great from a beginner's perspective: most | of what you'll learn about 2.x will still hold about 3.0. | | (from http://www.artima.com/weblogs/viewpost.jsp?thread=211200) My personal view is a little different. Learn 3.0 unless you have a reason to learn 2.x (and there are many possible ;-). Guido wrote the above nearly a year ago, before either existed to be learned. As it turned out, a decision was made to backport most of the new features of 3.0 into 2.6 to ease the transition. Consequently, 2.6 is in some sense the union of 2.5 and 3.0, so that there is more to learn. This is not a problem for Guido, but I can easily imagine that the extra duplication of function might be for a new learner, let alone someone like me who liked Python for its relative smallness. I personally have no perceived need and hence no plans to ever touch 2.6. So, depending on circumstances, again, I might suggest 2.5 instead of 2.6. tjr From dotancohen at gmail.com Thu May 8 18:56:52 2008 From: dotancohen at gmail.com (Dotan Cohen) Date: Fri, 9 May 2008 01:56:52 +0300 Subject: Write a python blog/website? In-Reply-To: <08d22e33-667e-4089-a777-69d5cb9cb95b@59g2000hsb.googlegroups.com> References: <08d22e33-667e-4089-a777-69d5cb9cb95b@59g2000hsb.googlegroups.com> Message-ID: <880dece00805081556hb7be637l1533cea08e054993@mail.gmail.com> 2008/5/8 sharpshoot : > Hi Guys, > > I thought this would be really interesting to people who blog who > might be able to help us. Your proposal very well may be interesting to those who might be able to help you, yet, you dug your own grave by spamming the Python list. I see that your intentions were honest, but your post was unsolicited advertising, and off-topic at that. I don't 'blog'. I write web content. I have rather impressive traffic at some sites and your advertising seems to fit at least two or three medium-traffic sites I maintain. I won't experiment with the advertising on the large sites until I see results at the smaller ones first. However, snaptalent.com stands out as a spammer. I most certainly will not do business with spammers, and I am willing to sacrifice my bottom line to avoid making spammers richer. That's too bad, as there are many more effective ways that you could have reached me and others like me. The two or three fish you will net spamming the python list will not be worth your bad name, I assure you. Dotan Cohen http://what-is-what.com http://gibberish.co.il ?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-?-? A: Because it messes up the order in which people normally read text. Q: Why is top-posting such a bad thing? From bignose+hates-spam at benfinney.id.au Sat May 24 01:01:56 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 24 May 2008 15:01:56 +1000 Subject: why is com-prompt faster and how do i start at cprompt at mydir/ ? References: <878wy0cqg6.fsf@benfinney.id.au> <8e5e9da7-4255-4f38-b32b-04723be46b9a@y38g2000hsy.googlegroups.com> Message-ID: <87mymgb8hn.fsf@benfinney.id.au> notnorwegian at yahoo.se writes: > On 24 Maj, 05:48, Ben Finney > wrote: > > Can you tell us exactly which programs you mean when you say "the > > shell" and "the commandprompt"? > > commandprompt = windows dos-windows > > shell = standard python interactive prompt Thanks. Be aware that referring to "the shell" without further qualification is usually understood to mean "the operating system shell", i.e. the command shell provided for running operating system commands. So, you're asking about the difference in behaviour between "the Windows command shell" versus "the Python interactive shell". -- \ ?I cannot conceive that anybody will require multiplications | `\ at the rate of 40,000 or even 4,000 per hour ...? ?F. H. | _o__) Wales, 1936 | Ben Finney From wizzardx at gmail.com Sun May 4 08:21:47 2008 From: wizzardx at gmail.com (David) Date: Sun, 4 May 2008 14:21:47 +0200 Subject: Script Optimization In-Reply-To: <6ed749de-1a7d-4db5-a229-d3400da4d24b@f24g2000prh.googlegroups.com> References: <6ed749de-1a7d-4db5-a229-d3400da4d24b@f24g2000prh.googlegroups.com> Message-ID: <18c1e6480805040521w2756b4eehef4d456837aa875@mail.gmail.com> On Sun, May 4, 2008 at 4:43 AM, lev wrote: > Can anyone provide some advice/suggestions to make a script more > precise/efficient/concise, etc.? Hi, I started tidying up the script a bit, but there are some parts I don't understand or look buggy. So I'm forwarding you the version I have so far. Look for the comments with my e-mail address in them for more information. If I have time I'll tidy up the script some more when I have more info about those issues. Here are the changes I made to your version: * Remove newlines introduced by email * Move imports to start of file * Change indentation from 8 spaces to 4 * Move main() to bottom of script * Remove useless "pass" and "return" lines * Temporarily change broken "chdir" line * Split lines so they fit into 80 chars * Add spaces after commas * Use path.join instead of string interpolation * rename rename() to rename_md5() because rename() shadows a function imported from os. * Rename vars shadowing imported names * Improve logic for checking when to print help * Create emtpy md5 listing file if one doesn't exist * Add a comment for a dodgy-looking section David. From info at thegrantinstitute.com Mon May 19 04:23:07 2008 From: info at thegrantinstitute.com (Anthony Jones) Date: 19 May 2008 01:23:07 -0700 Subject: Professional Grant Proposal Writing Workshop (August 2008: Manchester, New Hampshire) Message-ID: <20080519012307.C192D0F458864B79@thegrantinstitute.com> An HTML attachment was scrubbed... URL: From castironpi at gmail.com Tue May 13 10:01:08 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 13 May 2008 07:01:08 -0700 (PDT) Subject: I'm stuck in Python! References: Message-ID: <6c34f3a3-88fa-4519-b624-34a4589d2424@c65g2000hsa.googlegroups.com> On May 13, 8:46?am, Sanoski wrote: > Any programming that helps you solve a problem is fun and > recreational. At least, that's how I look at it. I suppose it really > depends on why you're doing it, what your objective is, etc. But I'd > say, why not? > > Tron! That's one I haven't seen in awhile. I'll have to take a mental > note to rent the movie again someday. I always thought a game based on > the movie hackers would be cool. Actually not based on the movie > itself, but on that 3D computer world they kept breaking into. Ah man, > it's so funny looking back on that film. Gibson, that's what they > called it. It was like a 3D database. That in itself wouldn't make a > very good game, but I suppose one could easily be created around that > idea. Perhaps it could be combined with Lawnmower-man. You're somehow > trapped in this 80's looking 3D world that has access to all the > world's information. More stuff could be thrown in to make it more > interesting. And of course, there would have to be hidden references > or parodies to whatever movies inspired it. > > Good luck with your project > > Sincerely, > Joshua > > On May 13, 9:02?am, castiro... at gmail.com wrote: > > > > > Hi all. > > > I am trying to write to the Python newsgroup. ?I doubt (aha, but > > doubt) that I have come to the right place. ?(Incoming "this"!) ?Is > > this the Python newsgroup? ?I heard it was called comp.lang.python. > > Now to repeat the subject line. ?I'm stuck in Python. > > > Now that was fun. ?I will also try to enumerate simple screen savers > > (graphicals, graphiclizers). ?It may be profitable on some non-bank- > > breaking scale to compile the results. ?Shall I proceed? ?The risk is > > "overunity", such that one person can't be at liberty to live, which > > in some technical political arenas would be an "anarchy", but there > > are sufficiently many of those that I will too. > > > Does anyone want such a list, or if not, is it at least fun and > > recreational to make it? ?The dollar would come along the lines of > > PowerPoint (name (tm)), so it may be free to do it, very entertaining, > > and peaceable. ?(As the above would show, you would be free to > > approach me to -buy-; I won't oversell.) ?I like programming. ?(And is > > Guido getting his fair share? ?I am prepared to share with him.) > > Check in his name. > > > I want to try to ally with other programmers and make cool games, like > > Tron, that one party can make games for on a console, such as live > > obstacles, incl. tear-down, and certain people have to play from time > > to time. ?But you can't charge to do it, so it's a guaranteed game. > > (That in virtue of that I'm typing.) ?Advantages include microspacing > > of time. ?Very summer. > > > Resemblances would include Dungeons & Dragons with multi-host, or > > multi-ref small-shooter sport-likers. ?The real-time is definitely > > attractive (duh). ?As for voice, it's not clear it's the most > > entertaining, but I just don't have a mic. > > > However, forseeing, I return with sailing, but that's in 3-space and > > not even in code, as though we'd construct the Royal Navy and battle. > > But I think we can keep it well. > > > Thing is, someone has to play it to keep a synch (keep from falling), > > and tap-outs would have to live. > > > Side note: In political theory, this is known as the problem of > > nominating a successor. ?Would it stay afloat, even for long enough to > > make it worth the negatives, yes which do include tear-down and fall, > > invasion of privacy, and rights infrigement? > > > I code in Python (get the callbacks), but configurable servers could > > spread the work out, using relays to put each person on each's own > > turf to be a ref. ?If you feed the roles, it could get really fun, and > > c-l-py is the appropriate place to start such a thing, both and ask if > > it's been done before.- Hide quoted text - > > - Show quoted text - My bot just tries to take control and lead. (The bot that I'm writing!) However, it is amusingly unsuccessful. We see in lines, so the game would be pretty primitive, but I'm not sure that everything else isn't merely too exciting, such that Tron wouldn't be monkey-in- the-middle, or king of the hill, of fun. I'm just not on a hill, so someone else would have to try to play it with me online! From jamesd at echeque.com Mon May 19 23:57:26 2008 From: jamesd at echeque.com (James A. Donald) Date: Tue, 20 May 2008 13:57:26 +1000 Subject: scaling problems References: <87y765hitf.fsf@benfinney.id.au> Message-ID: > > 1. Looks to me that python will not scale to very large programs, > > partly because of the lack of static typing, but mostly because there > > is no distinction between creating a new variable and utilizing an > > existing variable, Ben Finney > This seems quite a non sequitur. How do you see a connection between > these properties and "will not scale to large programs"? The larger the program, the greater the likelihood of inadvertent name collisions creating rare and irreproducible interactions between different and supposedly independent parts of the program that each work fine on their own, and supposedly cannot possibly interact. > These errors are a small subset of possible errors. If writing a large > program, an automated testing suite is essential, and can catch far > more errors than the compiler can hope to catch. If you run a static > code analyser, you'll be notified of unused names and other simple > errors that are often caught by static-declaration compilers. That is handy, but the larger the program, the bigger the problem with names that are over used, rather than unused. -- ---------------------- We have the right to defend ourselves and our property, because of the kind of animals that we are. True law derives from this right, not from the arbitrary power of the omnipotent state. http://www.jim.com/ James A. Donald From darcy at druid.net Fri May 16 11:52:14 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Fri, 16 May 2008 11:52:14 -0400 Subject: Python book question In-Reply-To: <20080516153116.GF13079@chicago.blisses.org> References: <20080516153116.GF13079@chicago.blisses.org> Message-ID: <20080516115214.b166eac5.darcy@druid.net> On Fri, 16 May 2008 10:31:16 -0500 Matt Herzog wrote: > Since Python is the only language that doesn't give me headaches I thought this book might be good. Has anyone read it or can anyone recommend the author? Can anyone recommend a better Data Structures and Algorithms book? > > The book: http://www.fbeedle.com/053-9.html I'm not familiar with the book but I poked my head in and looked at the first example: def squareroot(n): root = n/2 for k in range(20): root = (1.0/2)*(root + (n / root)) return root Looks fine and works but I wonder about the "root = n/2" line. Since the behaviour of this operation changes in 3.0, shouldn't it be specific about whether it is doing int or float division? -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From arnodel at googlemail.com Wed May 14 14:45:26 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 14 May 2008 19:45:26 +0100 Subject: readlines with line number support? References: Message-ID: Nikhil writes: > Hi, > > I am reading a file with readlines method of the filepointer object > returned by the open function. Along with reading the lines, I also > need to know which line number of the file is read in the loop > everytime. > I am sure, the line should have the property/attribute which will say > the line number of the file. > > If there is none, do I have to end up using the counter in the loop? > > fp = open("file", "r") > lineno = 0 > for line in fp.readlines(): > print "line number: " + lineno + ": " + line.rstrip() > lineno = lineno + 1 The standard Python way is using enumerate() for i, line in enumerate(fp): print "line number: " + lineno + ": " + line.rstrip() -- Arnaud From duncan.booth at invalid.invalid Fri May 2 03:54:04 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 2 May 2008 07:54:04 GMT Subject: #!/usr/bin/env python vs. #!/usr/bin/python References: Message-ID: Yves Dorfsman wrote: > On UNIX, some people use > #!/usr/bin/env python > > While other use > #!/usr/bin/python > > Why is one preferred over the other one ? > I don't think the answers so far have communicated what I believe to be the important point: it isn't that one is always better than the other, it depends on what you are trying to achieve. The first one runs the Python found from the environment. This means you can write a script and expect it to run on systems configured differently. You might prefer in some cases to specify a particular version of Python: #!/usr/bin/env python2.5 The second one runs a specific copy of Python (and here it is even more likely that you'll want to specify a particular version). This is important if your program is being run as a service or some other background situation where the environment isn't set up. For example Subversion hooks all run with an empty environment, and cron jobs run with a default environment which may not include python (e.g. if it is in /usr/local/bin). From johnjsal at NOSPAMgmail.com Wed May 14 21:59:43 2008 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 14 May 2008 21:59:43 -0400 Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> Message-ID: <20080514215943.14c92f16.johnjsal@NOSPAMgmail.com> On Mon, 12 May 2008 16:39:25 -0700 (PDT) Dave Parker wrote: > I've read that one of the design goals of Python was to create an easy- > to-use English-like language. That's also one of the design goals of > Flaming Thunder at http://www.flamingthunder.com/ , which has proven > easy enough for even elementary school students, even though it is > designed for scientists, mathematicians and engineers. What an interesting and weird language! :) But I have a question concerning something like this, from the website: ---------------------------------------------------- Flaming Thunder uses set statements for assignment: Set x to "concrete". Flaming Thunder does not abbreviate or cojoin common English words. For example, go and to are separate words: Read commmand. If command = "quit" then go to end. ----------------------------------------------------- There doesn't seem to be any consistency here. Why say: set x to "concrete" and then say: if command = "quit" Why are you using the "set...to..." terminology instead of the "=" for assignments, but then in an if test statement, you *do* use the "="??? Would it be valid to say: x = "concrete" or to say: if command (is) set to "quit" ?????? From ark at acm.org Thu May 8 12:33:19 2008 From: ark at acm.org (Andrew Koenig) Date: Thu, 08 May 2008 16:33:19 GMT Subject: Given a string - execute a function by the same name References: Message-ID: wrote in message news:mailman.291.1209400412.12834.python-list at python.org... > I'm parsing a simple file and given a line's keyword, would like to call > the equivalently named function. No, actually, you woudn't :-) Doing so means that if your programs input specification ever changes, you have to rename all of the relevant functions. Moreover, it leaves open the possibility that you might wind up calling a function you didn't intend. The right way to solve this kind of problem is to list all the functions you wish to be able to call in this way, and then explicitly define a mapping from keywords to the appropriate functions. Which is exactly what you're doing in > 3. Place all my functions in dictionary and lookup the function to be > called From squareswallower at y1a2hoo3.com Sat May 3 16:29:10 2008 From: squareswallower at y1a2hoo3.com (dave) Date: Sat, 3 May 2008 14:29:10 -0600 Subject: dict invert - learning question Message-ID: Hello, here is a piece of code I wrote to check the frequency of values and switch them around to keys in a new dictionary. Just to measure how many times a certain key occurs: def invert(d): inv = {} for key in d: val = d[key] if val not in inv: inv.setdefault(val, [key]) else: inv[val].append(key) return inv Using the methods above (I'm just a beginner) could I have written it more concisely? Any criticism/critique in the code would be greatly appreciated. Many Thanks, dave From yguan08 at gmail.com Tue May 13 17:06:13 2008 From: yguan08 at gmail.com (yguan08 at gmail.com) Date: Tue, 13 May 2008 14:06:13 -0700 (PDT) Subject: help with file path exceeding 255 characters References: <411ca062-faa9-4635-8d69-90e69f465729@z72g2000hsb.googlegroups.com> Message-ID: On May 13, 3:49?pm, Arnaud Delobelle wrote: > ygua... at gmail.com writes: > > I have trouble of obtaining the file size of a file because the > > fullpath exceeds 255 characters. I get this message with > > os.path.getsize(fullpath). > > > fullpath = r"\\LOSSSFS002\NWE_TECHNICAL\05. UK\Schiehallion (204_25a) > > \Amos&Burke_P559\07. Technical (Subsurface)\06. Well Planning\Amos > > \Daily Reports\Wireline\final_204_25a_8z\204_25a_8z\Run_1A > > \HRLA_SP_DSI_PEX_HNGS_ECRD\ANCILLARY\Amos_204_25a-8Z_GR_to_surface_3- > > Mar-2008_DSI_HRLA_TLD_MCFL_047PUC.las" > > > fsize = os.path.getsize(fullpath) > > > WindowsError: [Error 206] The filename or extension is too long: > > > The same thing with os.stat(fullpath). > > > I tried using the relative path, but it does not work with the message > > fname not found. > > > dir = os.path.dirname(fullpath) > > fname = os.path.basename(fullpath) > > os.chdir(dir) > > filesize = os.path.getsize(fname) > > > Is there a walk around of this? > > Disclaimer: I am not a Windows user > > Might this help? ?http://forum.altap.cz/viewtopic.php?p=2353 > > Alternately, use a better OS :-) > > -- > Arnaud- Hide quoted text - > > - Show quoted text - I tried, but still the same error: WindowsError: [Error 206] The filename or extension is too long: '\\\\? \\UNC\\LOSSSFS002\\NWE_TECHNICAL\\05. UK\\Schiehallion (204_25a)\ \Amos&Burke_P559\\07. Technical (Subsurface)\\06. Well Planning\\Amos\ \Daily Reports\\Wireline\\final_204_25a_8z\\204_25a_8z\\Run_1A\ \HRLA_SP_DSI_PEX_HNGS_ECRD\\ANCILLARY\\Amos_204_25a-8Z_GR_to_surface_3- Mar-2008_DSI_HRLA_TLD_MCFL_047PUC.las' From tjreedy at udel.edu Tue May 27 19:10:59 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 27 May 2008 19:10:59 -0400 Subject: Weird exception in my, um, exception class constructor References: Message-ID: "Joel Koltner" wrote in message news:Kq__j.177027$ng7.15947 at en-nntp-05.dc1.easynews.com... | Sounds good to me. I take it that, if I don't inherit from Exception, various | expected behaviors will break? (This is what Beazley suggests...) All builtin exceptions have been in the builtin namespace for a while. The duplicate exceptions module is gone in 3.0, In 3.0, if not before, all exceptions must subclass from one of the builtin exceptions. Exception is the usual choice. tjr From denis.kasak2718281828 at gmail.com Sun May 25 19:28:52 2008 From: denis.kasak2718281828 at gmail.com (Denis Kasak) Date: Mon, 26 May 2008 01:28:52 +0200 Subject: Getting a set of lambda functions References: <39e19a010805250611r6e27aafbha4f1a9d79b830626@mail.gmail.com> Message-ID: Scott David Daniels wrote: > Denis Kasak wrote: > ... >>>>> spam = [] >>>>> for i in range(10): >> ... spam.append(lambda: i) >>>>> spam[0]() >> 9 >>>>> spam[1]() >> 9 >> >> Manually creating the lambdas and appending them to a list works as >> expected, naturally; I don't see a good reason why it wouldn't work >> with a loop. Am I missing something? > > Yes, you are missing something: binding time. your anonymous function > returns the value of "i" in the enclosing scope _at_the_time_of_ > _the function's_execution_. If you follow your previous example with > 'del i' and then execute any of your spam functions, you'll get an > "NameError: global name 'i' is not defined". Ah, the problem was in the subtle misunderstanding of the semantics of lambda functions on my part. It's much clearer now. Thanks. > There are a couple of ways to slve your problem: > (1) use default args to do the binding at the function definition time. > for i in range(10): > spam.append(lambda arg=i: arg) > The lambda expression is normally spelled "lambda i=i: i)", but if you > don't know the idiom, I find the "i=i" part confuses people. Indeed. It hasn't occured to me that lambdas could bind the variables inside them by name. I guess my lambdas are still a little shaky. :-) -- Denis Kasak From myshoesbiz89 at yahoo.com.cn Sat May 3 01:56:36 2008 From: myshoesbiz89 at yahoo.com.cn (myshoesbiz89 at yahoo.com.cn) Date: Fri, 2 May 2008 22:56:36 -0700 (PDT) Subject: CHINA WHOLESALE GUCCI DIOR CHANEL HANDBAGS FROM CHINA SUPPLIERS Message-ID: Thenikeshoes DOT net If you are interested in any of our products, please contact our salesman and they will respond in 24 hours after hearing from you. If you cannot find the shoes you are seeking for in the list, please also contact with us and send us your photos, we will do our best to find the shoes from our partners and satisfy you with our best service. Our main customers are from Europe and North America and we know well about the requirements for those markets, such as style number, sticker and box details. We sincerely hope to establish beneficial partnership with your valued company From irmen.NOSPAM at xs4all.nl Sun May 18 20:52:10 2008 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Mon, 19 May 2008 02:52:10 +0200 Subject: How do *you* use Python in non-GUI work? In-Reply-To: <20080518182022.990193bd.johnjsal@NOSPAMgmail.com> References: <20080518182022.990193bd.johnjsal@NOSPAMgmail.com> Message-ID: <4830cf3b$0$14348$e4fe514c@news.xs4all.nl> John Salerno wrote: > Hey all. Just thought I'd ask a general question for my own interest. Every time I > think of something I might do in Python, it usually involves creating a GUI > interface, so I was wondering what kind of work you all do with Python that does > *not* involve any GUI work. This could be any little scripts you write for your own > benefit, or what you do at work, if you feel like talking about that! :) > > Thanks. - web server/blog/wiki. This doesn't have a gui if you don't consider HTML pages a gui - various scripts to help me during software deployment and testing (for instance log file analyzers, automated web clients) - network communications library that tries hard to just get out of your way ;-) - file processing scripts to do more sophisticated stuff than basic search/replace - most recent script is a little tool that downloads the latest version of some World-Of-Warcraft addon, extracts it to the game folder after deleting the old one first, and then copies a backup to a network drive. I just doubleclick the .py file and it dumps the results in a console window that closes after a few seconds. Who needs a gui for that? Also, I often find myself opening a Python prompt to just execute simple tasks that I see other people needing big tools or even online services for: - base-64 encoding/decoding - md5/sha hashing - simple string or regular expression operations - simple math - unicode decoding/encoding - etc etc. --irmen de jong From n00m at narod.ru Mon May 5 06:46:33 2008 From: n00m at narod.ru (n00m) Date: Mon, 5 May 2008 03:46:33 -0700 (PDT) Subject: How to pass a multiline arg to exec('some.exe arg')? References: <7b6965a2-193d-42cf-8fad-2ad97c8de27b@i76g2000hsf.googlegroups.com> Message-ID: Hint: for some reason in VBScript it works fine. What makes it different, with Python? I tried all possible ways to combine quotes, ' and ", with no avail From zzvladimir at gmail.com Wed May 21 03:14:22 2008 From: zzvladimir at gmail.com (Vladimir Kropylev) Date: Wed, 21 May 2008 11:14:22 +0400 Subject: xpath with big files Message-ID: Hi, I've encountered a problem when trying to use lxml.etree.xpath with big (63Mb) file. It returns empty list on any request. Is there any restriction on file size for lxml.etree.xpath? This is what I do: f=open(filename) tree = etree.parse(f) f.close() r = tree.xpath('//image') print(r) it prints: [] What is wrong here? From exarkun at divmod.com Mon May 12 13:16:29 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 12 May 2008 13:16:29 -0400 Subject: Socket and cycle problem In-Reply-To: Message-ID: <20080512171629.6859.799802490.divmod.quotient.62544@ohm> On Mon, 12 May 2008 09:19:48 -0700 (PDT), petr.poupa at gmail.com wrote: > > [snip] >> >> >Where is the mistake? I dont know. >> >> You cannot reconnect a socket. You need to create a new one for each >> connection. It's also almost certainly the case that the way you are >> receiving data is incorrect. There is no guarantee that you will get >> 2048 bytes from socket.recv(2048). It isn't even guaranteed that all >> the bytes written to the socket by the peer will be returned by such >> a call. Instead, you need a framing protocol to determine when all >> data has been received. For example, you might length prefix the >> data, or you might insert a delimiter (or a terminator) at the end. Or >> if there is exactly one message to receive, then you should just read >> until the recv call returns '', indicating EOF. >> >> Jean-Paul > >ok thanks, but I am true greenhorn, so you think that the best way is >write new script? >Could you send me code if it isnt long, becase I have no idea and >unfortunately time as well. > I'm not sure what you want to happen, so I can't write it for you. I suggest you start with Twisted instead of the socket module, though, as Twisted provides a higher-level interface to network programming. You can find some introductory documentation about writing clients here: http://twistedmatrix.com/projects/core/documentation/howto/clients.html Jean-Paul From giles_brown at hotmail.com Tue May 6 11:44:36 2008 From: giles_brown at hotmail.com (Giles Brown) Date: Tue, 6 May 2008 08:44:36 -0700 (PDT) Subject: select.poll() and WSAPoll References: Message-ID: On 6 May, 14:18, Jean-Paul Calderone wrote: > On Tue, 6 May 2008 08:36:28 -0400, inhahe wrote: > >select.poll isn't supported on Windows, because Windows doesn't have such a > >feature, or at least it didn't until Vista. Vista implements the same thing > >but called WSAPoll, an article is here > >http://blogs.msdn.com/wndp/archive/2006/10/26/WSAPoll.aspx > >I hope that the next edition of Python supports select.poll on Vista, or at > >least that someone writes a third-party module fo it. As much as I'd love to > >do it myself, it's probably beyond me.. i've never used poll before nor > >written a Python extension. also, i don't have Vista. > >Thanks > > If you use Twisted, then you can use I/O Completion Ports, which are even > better than WSAPoll, and your code will also work with KQueue on BSD or > EPoll on Linux without any changes. :) > > Jean-Paul The current docs describe the I/O Completion Ports reactor as "extremely experimental". http://twistedmatrix.com/projects/core/documentation/howto/choosing-reactor.html#auto8 Is that overly conservative or is it as bleeding edge as it sounds? (IIRC there have been caveats like this on the Windows reactors for a while) Giles From zerge69 at gmail.com Sun May 25 20:21:14 2008 From: zerge69 at gmail.com (Zerge) Date: Sun, 25 May 2008 17:21:14 -0700 (PDT) Subject: Pinging a machine from python References: Message-ID: <0abad6b7-87bc-42d2-88ee-1f2ed40aa07f@w1g2000prd.googlegroups.com> On May 25, 11:13 am, Prasanth wrote: > I tried pinging a machine from python using socket programming but > could not do it. Is there any module which we can use to ping the > machine < like net::ping in perl> or can you give me simple program. Import OS ip=192.168.1.1 pingtext="ping "+ip+" -n 1" pingresult=os.popen(pingtext).readlines() "OS" gives you access to the command line of the operating system. From nick at craig-wood.com Fri May 23 16:30:09 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Fri, 23 May 2008 15:30:09 -0500 Subject: Advice from senior Members References: <36962062-07d4-4ede-a882-d04ad1fa8e69@b1g2000hsg.googlegroups.com> Message-ID: flit wrote: > I am looking for some experience from the senior members. > Now I am doing a simple desktop application, this application will > have 3 main functions: > > 1- Read information about the desktop system; > 2- Interact with the user; > 3- Send information to a server. > > The first part, reading information about the desktop system, is > already done. And now I am starting to make the gui for the user, > that is when the question appear: "What is the best way to make it? > divide in files? by classes or functions?" I have now one big file > with all functions to get the desktop information. Should I make > one file for the visual functions (wxpython)? another for the > server? Is productive to divide in files? what is the best way? I would divide it into 3 files, one for the desktop info, one for the server interaction and one for the GUI. Subdivide the files if they start getting unmanageably long My wx programs tend to be full of lots of little classes. I make every object (pane, window, widget etc) its own class and glue them all together in other classes. I'd make your read the information file into probably a single class, with each function a method. You can then either read all the information on __init__ or as methods whichever seems best to you. Your gui classes will then query this as appropriate (this is the MVC as discussed by another poster). You can write another text mode interface for the desktop info module which prints things out in text format for testing. Once you've divided your program up, you can start thinking about unit tests. You can certainly unit test your desktop info gathering, and your server interaction. It is hard to write tests for wx GUIs though (but not impossible). When you've finished you'll have 3 files full of classes. You may have a few utility functions too. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From ian at excess.org Mon May 19 09:50:49 2008 From: ian at excess.org (Ian Ward) Date: Mon, 19 May 2008 09:50:49 -0400 Subject: ANN: Urwid 0.9.8.2 - Console UI Library Message-ID: <483185B9.9030307@excess.org> Announcing Urwid 0.9.8.2 ------------------------ Urwid home page: http://excess.org/urwid/ Tarball: http://excess.org/urwid/urwid-0.9.8.2.tar.gz RSS: http://excess.org/feeds/tag/urwid/ About this release: =================== This is a maintenance release that fixes a number of bugs that have been found in 0.9.8.1. New in this release: ==================== * Fixed incompatibilities with Python 2.3 * Fixed Pile cursor pref_col bug, WidgetWrap rows caching bug, Button mouse_event with no callback bug, Filler body bug triggered by the tutorial and a LineBox lline parameter typo. About Urwid =========== Urwid is a console UI library for Python. It features fluid interface resizing, UTF-8 support, multiple text layouts, simple attribute markup, powerful scrolling list boxes and flexible interface design. Urwid is released under the GNU LGPL. From arnodel at googlemail.com Wed May 7 14:27:29 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 07 May 2008 19:27:29 +0100 Subject: letter frequency counter / your thoughts.. References: <5a9a4a7e-a4a3-4a59-a80f-01d44bc69a86@w1g2000prd.googlegroups.com> Message-ID: umpsumps at gmail.com writes: > Hello, > > Here is my code for a letter frequency counter. It seems bloated to > me and any suggestions of what would be a better way (keep in my mind > I'm a beginner) would be greatly appreciated.. > > def valsort(x): > res = [] > for key, value in x.items(): > res.append((value, key)) > return res > > def mostfreq(strng): > dic = {} > for letter in strng: > if letter not in dic: > dic.setdefault(letter, 1) > else: > dic[letter] += 1 > newd = dic.items() > getvals = valsort(newd) > getvals.sort() > length = len(getvals) > return getvals[length - 3 : length] > > thanks much!! I won't comment on the algorithm, but I think you should try to find better names for your variables. In the snippet above you have x, res, dic, newd, length, getvals which don't give much of a clue as to what they are used for. e.g. * dic = {} We know it's a dict, but a dict of what? * newd = dic.items() Sounds like 'new dictionary', but obviously isn'tas it is a list of key,value pairs. * length = len(getvals) Again, we know it's a length, but the length of what? HTH -- Arnaud From castironpi at gmail.com Tue May 13 09:55:41 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 13 May 2008 06:55:41 -0700 (PDT) Subject: where to get McMillan Installer? References: <74f142de-6485-4773-bae8-2a274be19b80@w7g2000hsa.googlegroups.com> <537c541a-4e96-404b-81c3-68ffa9a025b8@b64g2000hsa.googlegroups.com> <3ef2200e-5520-4fcf-9f2c-8667fc1733c4@s50g2000hsb.googlegroups.com> Message-ID: <529f1c1f-9ab6-41a4-88f8-7f54d8528f00@d1g2000hsg.googlegroups.com> On May 13, 8:23?am, gsal wrote: > hhhmmm...py2exe...I tried it earlier and it couldn't handle some of > the packages I was using because they were in the "egg" form. ?I was > hoping Installer could...then again, I don't know how long ago > Installer was written and whether eggs came along after that... > > Regarding the word 'copy'...will you please enlighten me? were you > serious? is it really banned (around here)? I mean, I thought we were > talking about an open application which, for as long as you pass along > the (GNU,GPL) license, you are allowed to provide it to other people. > > So, then, allow me to ask the real question: ?how do I go about > deploying a Python application to somebody who has nothing (python nor > related modules) where my application uses modules from Lib/site- > packages that are in "egg" form? > > Regards, > > gsal Funny you should ask that way; this is strictly speaking, real aside. If people like to share, but don't know what enough is, (or when,) real world problems can sometimes arise. And it's not as easy as asking an authority to see for yourself. There are all kinds of power structures and big sleeping men lying about. They're big and sleeping, just men. Plagiarism (sp.) is a form of copying-- my professors have always resented and penalized quoting right from the book. I continue, if the book's wording is the best way to say certain things (which would be so popular as to be indistinguishable from analytic/necessary, i.e. math), the study is rote, and the creation lies about. But is math in creation? I might hold so. One test even emphasizes, "in your own words." But the power structures are men, and men are living; what does life want? What will man try to do in and over time? What are the universe's poles/attractors/pulls? What has he done before? Is there any money in any logical, cross-sectional isolation of them? As it's my belief that man can have too much money, what if you succeed in trying to make it in the foregoing way? From mmanns at gmx.net Tue May 13 14:31:45 2008 From: mmanns at gmx.net (Martin Manns) Date: Tue, 13 May 2008 20:31:45 +0200 Subject: ANN: pyspread 0.0.6 References: Message-ID: On Tue, 13 May 2008 00:23:12 +0200 Martin Manns wrote: pyspread 0.0.5 has been released. It is a bugfix release for Mac and Windows. > -- > > About: > pyspread is a spreadsheet that accepts a pure python expression in > each cell. > > -- > > Highlights: > + No non-python syntax add-ons > + Access to python modules from cells > + 3D grid > + Numpy object array for representation of string entry into grid cell > + Numpy object array for representation of eval function array > + Cell access via slicing of numpy function array > + X, Y, and Z yield current cell location for relative reference > > Requires: Python >=2.4, Numpy 1.0.4, and wxPython 2.8.7.1. > License: GPL > > Project page: http://pyspread.sourceforge.net Best Regards Martin From larzluv at hotmail.com Mon May 12 00:42:55 2008 From: larzluv at hotmail.com (Larry Hale) Date: Sun, 11 May 2008 21:42:55 -0700 (PDT) Subject: Module python-magic on/for Windows? References: <3a66adfe-3fd6-4f23-a6e8-4b219db1a3cd@x41g2000hsb.googlegroups.com> Message-ID: THANKS, AGAIN, for the reply! :) Okay, now I -really- feel silly... :> So, when I was going to try what you'd suggested, I noticed something peculiar: I hadn't "changed" anything on my system, but now, when I tried to "import magic" I got a missing DLL error. For a DIFFERENT DLL! This got me to thinking... Turns out, when I was having "success" earlier, I was -in- the C: \Program Files\GnuWin32\bin directory (where file.exe and related .dll files are). So I added C:\Program Files\GnuWin32\bin to the (system/Windows) PATH. Everything worked. I removed all the copious copies of the DLL, the magic files, etc., littering my hard drive in every other location. Still worked. 'Course, I don't honestly know why it didn't work with the files copied to other locales contained in the sys/Py paths... perhaps it was, as you mentioned, wanting the tree-structure to be the same? (I haven't the heart to check this out fully right now... *maybe* at a later time... ;) ) Yeah, I know. But HONESTLY! I could have -sworn- I'd already tried THAT... you know, all the "obvious"/"I've been programming/working in computers (albeit 'Windows' until lately) for ~25 years; yeah, I'm a 'hacker'..." stuff. I -swear-! [EGG ON FACE] [SIGH] Well, I'd say "live and learn", but I'm still scratching my head. But, 'nough of that. Thanks for your replies, Michael, and I'm off to work _with_ the module now, then work-up my HowTo (and experiment with making an "egg"?? ;) )... Caio! -Larry :P :) On May 11, 11:09 pm, Michael Torrie wrote: > Larry Hale wrote: > > ALSO: I've even tried putting the 4 "magic" files INTO the .egg > > file... still no-go. :/ > > It's often the custom of programs ported from unix to windows to use the > dll location as a key to find the other files that are typically in > share, or etc. GTK, for example uses ../share and ../etc from the > location where the dlls are stored (if the dlls are in a folder called bin). > > In this case I'd try making a folder in the Python25 folder called > "share" and put the contents of the gnuwin32 share/file stuff in there. > Should look something like this: > > c:/python25/share/file/magic.mime.mgc > c:/python25/share/file/magic > c:/python25/share/file/magic.mgc > c:/python25/share/file/magic.mime > > Or, judging by a string I found in the dll itself, you might have to put > the files here: > > c:/progra~1/File/share/file/magic > > Although if such a path really is hardcoded into the dll, this is > certainly a bug, since it will fail on certain non-english windows systems. > > Anyway, who knows. Give these options a try. From prabaindra at gmail.com Thu May 1 09:11:47 2008 From: prabaindra at gmail.com (prabaindra at gmail.com) Date: Thu, 1 May 2008 06:11:47 -0700 (PDT) Subject: DO U WANT TO KNOW ABOUT SCIENTOLOGY? Message-ID: <7fe132fe-8a8a-4abc-9d8e-f1c27d00cc48@z24g2000prf.googlegroups.com> HELLO FRIEND IAM SHALINI, DO U WANT TO KNOW ABOUT SCIENTOLOGY? PLS LOOK AT THE BELOW WEBSITE. www.bigconcern3.blogspot.com From torriem at gmail.com Mon May 12 08:48:12 2008 From: torriem at gmail.com (Michael Torrie) Date: Mon, 12 May 2008 06:48:12 -0600 Subject: Module python-magic on/for Windows? In-Reply-To: <4827C2E7.2040703@gmail.com> References: <3a66adfe-3fd6-4f23-a6e8-4b219db1a3cd@x41g2000hsb.googlegroups.com> <4827C2E7.2040703@gmail.com> Message-ID: <48283C8C.9040804@gmail.com> Michael Torrie wrote: > In this case I'd try making a folder in the Python25 folder called > "share" and put the contents of the gnuwin32 share/file stuff in there. > Should look something like this: > > c:/python25/share/file/magic.mime.mgc > c:/python25/share/file/magic > c:/python25/share/file/magic.mgc > c:/python25/share/file/magic.mime I used linux's strace command to trace the file calls of file.exe via wine (fun!) and verified that magic1.dll indeed will first in c:/progra~1/File/share/file/magic and then in ../share/file From ivo.talvet at gmail.com Mon May 12 07:07:04 2008 From: ivo.talvet at gmail.com (ivo talvet) Date: Mon, 12 May 2008 13:07:04 +0200 Subject: python without while and other "explosive" statements In-Reply-To: <4827A364.9040507@mattnordhoff.com> References: <3dd0b1a30805111639n2d6db827v166104f28825a29c@mail.gmail.com> <4827A364.9040507@mattnordhoff.com> Message-ID: <3dd0b1a30805120407w407c9bbdr6439f4a89bc4df84@mail.gmail.com> thanks for the tips, pam limits and http://codepad.org/ are both interesting tracks. Ivo 2008/5/12 Matt Nordhoff : > > ivo talvet wrote: > > Hello, > > > > Is it possible to have a python which not handle the execution of > > "while", "for", and other loop statements ? I would like to allow > > remote execution of python on a public irc channel, so i'm looking for > > techniques which would do so people won't be able to crash my computer > > (while 1: os.fork(1)), or at least won't won't freeze my python in a > > infinite loop, make it unresponsive. Is there a compiling option (or > > better, something i can get with apt-get cos i think compiling myself > > and handle all the metastuff myself is somehow dirty) for have a > > "secure python" (you can guess what i mean by "secure" in my case) or > > must i touch myself the source disable some code lines ? If last > > solution, which modifications in which files should i do ? (sorry for > > my bad english) > > > > Thanks. > > > > Ivo > > is a pastebin-like website that lets people upload > code in a dozen different languages, and it runs it. They have info up > about how it's secure at . > > I'm pretty sure there's another similar website that's specific to > Python, but I can't remember it. Anyway, it was similar, using virtual > machines, a firewall, and killing stuff that ran for longer than 20 > seconds, IIRC. > > (Thanks for the link to codepad, habnabit.) > -- > From gneuner2/ at /comcast.net Thu May 8 21:32:58 2008 From: gneuner2/ at /comcast.net (George Neuner) Date: Thu, 08 May 2008 21:32:58 -0400 Subject: The Importance of Terminology's Quality References: Message-ID: On Thu, 08 May 2008 03:25:54 -0700, usenet1.3.CalRobert at SpamGourmet.Com (Robert Maas, http://tinyurl.com/uh3t) wrote: >> From: "xah... at gmail.com" >> the importance of naming of functions. > >> ... [take] a keyword and ask a wide >> audience, who doesn't know about the language or even unfamiliar of >> computer programing, to guess what it means. This is a dumb idea ... >Better would be to reverse the question: Ask >random people on the street what they would like to call these >concepts: ... and this one is even dumber. Terms don't exist in a vacuum - they exist to facilitate communication within a particular knowledge or skill domain. For example, English is only meaningful to those who speak English. The opinions of random people who have no relevant domain knowledge are worthless. Such a survey could only be meaningful if the survey population already possessed some knowledge of programming, but were not already aware of the particular terminology being surveyed. George -- for email reply remove "/" from address From boblatest at googlemail.com Wed May 21 09:12:13 2008 From: boblatest at googlemail.com (boblatest at googlemail.com) Date: Wed, 21 May 2008 06:12:13 -0700 (PDT) Subject: C-like assignment expression? References: <68b5d090-9e3b-4e7d-9dda-fc1b099822c2@m73g2000hsh.googlegroups.com> <48340412$0$10773$426a74cc@news.free.fr> <87fxsbzxn4.fsf@mulj.homelinux.net> Message-ID: <7df99fd4-21c9-49a1-ba65-e55794fd4c12@26g2000hsk.googlegroups.com> On May 21, 1:47 pm, Hrvoje Niksic wrote: > Although that solution is pretty, it is not the canonical solution > because it doesn't cover the important case of "if" bodies needing to > access common variables in the enclosing scope. (This will be easier > in Python 3 with 'nonlocal', though.) The snippet posted by Diez is > IMHO closer to a canonical solution to this FAQ. Hello everybody, thanks for the various answers. I'm actually pretty puzzled because I expected to see some obvious solution that I just hadn't found before. In general I find Python more elegant and syntactically richer than C (that's where I come from), so I didn't expect the solutions to be a lot more verbose and/or ugly (no offense) than the original idea which would have worked if Python's assignment statement would double as expression, as in C. Thanks again, robert PS: Since I'm testing only three REs, and I only need the match results from one of them, I just re-evaluate that one. From pavlovevidence at gmail.com Mon May 12 14:23:07 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 12 May 2008 11:23:07 -0700 (PDT) Subject: Is using range() in for loops really Pythonic? References: <482657ca$0$25026$607ed4bc@cv.net> <48275316$0$11629$607ed4bc@cv.net> <3042f24f-f32e-4266-8bf5-41cdb511b78d@m45g2000hsb.googlegroups.com> <873aoo6k8z.fsf@benfinney.id.au> Message-ID: On May 12, 3:42 am, Ben Finney wrote: > Because of the precedent of those names, choosing one of those names > doesn't make it clear to the reader that the value is never used; Why is it even necessary to document this? This is the thing that baffles me the most about this thread. Think about all the various aspect of a varibale: * is it some common usage archetype * value it represents * scope * (expected) type * physical units of measure * software package it belongs to * whether it's used in the program or not * scalar, structure, or array * mutable or constant * and so on You cannot possibly document all of this pertinent information in the name alone. A variable's name is a very limited resource: one can only document a tiny number of things, so one must prioritize. IMHO, whether a varibale is used or not has got to be one of the least important things of all (in no small part because it's easily discernable from nearby code). In fact, I'd say it's so irrelevant I probably wouldn't have listed it if it wasn't the topic of discussion. The first two items I listed are the most important to me. If a variable fills the archetypal role of counter, then it ought to be named like a counter; this usually trumps all other concerns. (Never mind that the varibale here isn't really a counter, it still fills the archetypal role of one, which is more important. The name of a variable is for the reader's benefit.) So I would have to agree with Ivan Illarionov. Having said that, if you do think it's most important to document whether something is used, I would suggest not using "_" (because it's conflicts with gettext conventions) or "dummy" (because it's misleading) for it. Carl Banks From gherron at islandtraining.com Sun May 11 13:51:34 2008 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 11 May 2008 10:51:34 -0700 Subject: File Creation Not Working In A Thread Class? In-Reply-To: References: Message-ID: <48273226.8060405@islandtraining.com> bc90021 wrote: > Hi All, > > Thanks in advance for any and all help! > > I have this code: > > g = open(fileName, 'a') > I don't believe you. I think you have something like g = open('fileName', 'a') instead of (as you claim) g = open(fileName, 'a') Do you see the difference? Develop the skill of reading the error messages *very* carefully. Your error says there is no file named "fileName", and if you think about what's on your disk, I'll bet you won't find a file whose name is "fileName". Gary Herron > where fileName is defined before the line it's used in. It works fine > when I use it outside a thread class. > > When I put the same line in a thread class, it no longer works, and I get > an error: > > IOError: [Errno 2] no such file u'fileName' > > Are threads not allowed to create files? > -- > http://mail.python.org/mailman/listinfo/python-list > From wizzardx at gmail.com Sun May 4 09:18:50 2008 From: wizzardx at gmail.com (David) Date: Sun, 4 May 2008 15:18:50 +0200 Subject: please remove me from this list In-Reply-To: References: Message-ID: <18c1e6480805040618p14c27164r362584d0ad5f2259@mail.gmail.com> On Sun, May 4, 2008 at 2:48 PM, Vladimir Kropylev wrote: > please remove me from this list, thanks > -- > http://mail.python.org/mailman/listinfo/python-list > Follow that link (http://mail.python.org/mailman/listinfo/python-list) and see the "Python-list Subscribers" section. David. From matthieu.brucher at gmail.com Wed May 21 08:32:47 2008 From: matthieu.brucher at gmail.com (Matthieu Brucher) Date: Wed, 21 May 2008 14:32:47 +0200 Subject: Struct usage and varying sizes of h, l, etc In-Reply-To: <48340df7$1@news.mel.dft.com.au> References: <48335269.2000809@admailinc.com> <48340df7$1@news.mel.dft.com.au> Message-ID: > > This is all true if you want to operate in "native" mode; however in > "standard" mode the sizes are fixed -- otherwise there'd be no easy way of > reading/writing the fixed-size fields in many common file formats. > > As the manual says: > """ > Native size and alignment are determined using the C compiler's sizeof > expression. This is always combined with native byte order. > > Standard size and alignment are as follows: no alignment is required for > any type (so you have to use pad bytes); short is 2 bytes; int and long are > 4 bytes; long long (__int64 on Windows) is 8 bytes; float and double are > 32-bit and 64-bit IEEE floating point numbers, respectively. > """ > > If, as I suspect, Ethan's purpose is be able to read/write files in a > long-established PC file format, he will need to '<' for littleendian order, > and an appropriate selection from bBhHiI and d will do what he needs. > > HTH, > John On an Ubuntu 64 box : >>> struct.calcsize('l') 8 not 4. Matthieu -- French PhD student Website : http://matthieu-brucher.developpez.com/ Blogs : http://matt.eifelle.com and http://blog.developpez.com/?blog=92 LinkedIn : http://www.linkedin.com/in/matthieubrucher -------------- next part -------------- An HTML attachment was scrubbed... URL: From pecora at anvil.nrl.navy.mil Fri May 9 11:23:42 2008 From: pecora at anvil.nrl.navy.mil (Lou Pecora) Date: Fri, 09 May 2008 11:23:42 -0400 Subject: Mathematics in Python are not correct References: <52c855d8-5609-43e0-b98f-9fa87b2808c2@m3g2000hsc.googlegroups.com> <200805081914.06459.kyrie@uh.cu> Message-ID: In article , "Terry Reedy" wrote: > "Luis Zarrabeitia" wrote in message > news:200805081914.06459.kyrie at uh.cu... > | Btw, there seems to be a math problem in python with exponentiation... > | >>> 0**0 > | 1 > | That 0^0 should be a nan or exception, I guess, but not 1. > > a**b is 1 multiplied by a, b times. 1 multiplied by 0 no times is 1. > But there are unenlighted people who agree with you ;-) > Wikipedia has a discussion of this. > > tjr I like that argument better. But... I've also heard the very similar a**b is a multiplied by a b-1 times. That gives 0**0=0*(1/0). Uh, Oh! If you want consistency with the treatment of exponents that might cause problems. Tough situation when you have a "discontinuity" at 0 for x^x. -- -- Lou Pecora From castironpi at gmail.com Wed May 14 14:06:31 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 14 May 2008 11:06:31 -0700 (PDT) Subject: I'm stuck in Python! References: <0563506d-bd36-404d-8961-4c4c5d1cc029@t54g2000hsg.googlegroups.com> <6a0167c3-bd87-4ddc-a161-249b7bf933c2@s50g2000hsb.googlegroups.com> <1f6bc3b5-da44-42a2-82f1-4aec5a6d31b1@c58g2000hsc.googlegroups.com> <499bc2af-6c7d-4ff4-abba-db06f4122cf9@x41g2000hsb.googlegroups.com> Message-ID: <0a3717f4-5992-484d-a39c-04f0d2cfec3a@m45g2000hsb.googlegroups.com> On May 14, 1:02?pm, castiro... at gmail.com wrote: > On May 14, 12:51?pm, castiro... at gmail.com wrote: > > > > > > > On May 14, 5:25?am, castiro... at gmail.com wrote: > > > > On May 14, 4:32?am, castiro... at gmail.com wrote: > > > > > On May 13, 9:55?pm, alex23 wrote: > > > > > > On May 14, 5:41 am, "inhahe" wrote: > > > > > > > "George Sakkis" wrote in message > > > > > > > You must be new here. It is an AS (Artificial Stupidity) trolling bot, > > > > > > > you can safely ignore its posts. > > > > > > > How does it generate text? > > > > > > My guess is by inhaling a lot of intoxicants. > > > > > However you know what would be helpful? ?If I could go to the right > > > > place to start the ring. > > > > I have a slightly sinister role on stage. ?Does anyone want to play? > > > I'd stay on mutability for the world domination factor. ?Fluent > > currency is buoyant currency; turn on a local clock, and someone gets > > some cubic verticals. > > > Now if sense-reference is trading on the BDFL, I'm still holding Tron > > can pretty well win work.- Hide quoted text - > > > - Show quoted text - > > I have a self-referential on Pygame: it's a Hand Tool object. > Currently, it decays over time. ?You said 'flip' in the newsgroup, and > 'check', 'cross', and 'mate'. ?Now who jumps who?- Hide quoted text - > > - Show quoted text - If Python can plot in to chess, and Tron rings live, then why not group it knew? From collinyeung at shaw.ca Mon May 12 00:54:28 2008 From: collinyeung at shaw.ca (Collin) Date: Mon, 12 May 2008 04:54:28 GMT Subject: Accepting text input In-Reply-To: <72QVj.262833$pM4.115744@pd7urf1no> References: <72QVj.262833$pM4.115744@pd7urf1no> Message-ID: <84QVj.133083$rd2.94188@pd7urf3no> Collin wrote: > I'm pretty new to Python, but this has really bugged me. I can't find a > way around it. > > > The problem is that, when I use raw_input("sajfasjdf") whatever, or > input("dsjfadsjfa"), you can only have numerical values as answers. > > Any help would be appreciated. Thanks. Oh, wow. I feel so stupid. Please disregard this message. <_< I read the error message just now a bit more carefully, and I tried something. I tried defining "yes" as some random numerical value. Then when I did: (example code) yes = 123123983 #some number test = input("Test test test ") if test == yes: print "It worked." else: print "failed" (example code off) Collin From banibrata.dutta at gmail.com Tue May 6 10:21:15 2008 From: banibrata.dutta at gmail.com (Banibrata Dutta) Date: Tue, 6 May 2008 19:51:15 +0530 Subject: How do you debug memory usage? In-Reply-To: <18c1e6480805060627y32aecc65wf9b4874c7f37590@mail.gmail.com> References: <18c1e6480805060627y32aecc65wf9b4874c7f37590@mail.gmail.com> Message-ID: <3de8e1f70805060721n64944a6ep3592a4e2b7f63b2e@mail.gmail.com> Many not be the most intuitive and elegant solution (I'm just a Python newbie), but if your Python code is constrained to the usage of Python 2.2 language features, you could use Jython, and then (I'm hoping, since I've not tried this myself), use the Java Memory usage profiling/debugging tools. Would be really interested to know the answer to the question, i.e. if there are any CPython solutions. On Tue, May 6, 2008 at 6:57 PM, David wrote: > Hi list. > > I've tried Googling for this and I checked the Python docs, but to no > avail. > > What is the best way to debug memory usage in a Python script? > > I'd like to see what objects are using the most memory. Ideally this > would be aware of references too. So if I have a small list that > contains (references rather) some large variables, then I could see > that the global list variable was responsible for X MB that couldn't > be collected by the garbage collector. > > It would be nice if it could be used in a similar way to the 'du' > Linux command. eg: > > eg output: > > >>> mem_debugger.pretty_print() > A (type: list): 8 bytes, 10MB > - a (type: string): 6 MB, 0 bytes > - b (type: string): 4 MB, 0 bytes > B (type: dict): 8 bytes, 5 MB > - d (type: string): 3 MB, 0 bytes > - c (type: string): 2 MB, 0 bytes > > In the output above, the 1st size is the memory used by the object > itself, and the 2nd size is the memory used by objects it refers to. A > & B are global vars (a string and a dict), a,b,c, and d are strings > that were added to A & B at some point in the past, and aren't refered > to by anything else. Also, the output is in descending order of size. > > Are there any tools/modules/etc I can use like this? > > David. > -- > http://mail.python.org/mailman/listinfo/python-list > -- regards, Banibrata http://www.linkedin.com/in/bdutta -------------- next part -------------- An HTML attachment was scrubbed... URL: From ivan.illarionov at gmail.com Sat May 3 17:37:25 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Sat, 3 May 2008 21:37:25 +0000 (UTC) Subject: Feature suggestion: sum() ought to use a compensated summation algorithm References: <481CB283.107@gmail.com> Message-ID: On Sat, 03 May 2008 20:44:19 +0200, Szabolcs Horv?t wrote: > Arnaud Delobelle wrote: >> >> sum() works for any sequence of objects with an __add__ method, not >> just floats! Your algorithm is specific to floats. > > This occurred to me also, but then I tried > > sum(['abc', 'efg'], '') Interesting, I always thought that sum is like shortcut of reduce(operator.add, ...), but I was mistaken. reduce() is more forgiving: reduce(operator.add, ['abc', 'efg'], '' ) # it works 'abcefg' -- Ivan From castironpi at gmail.com Fri May 16 10:41:34 2008 From: castironpi at gmail.com (castironpi) Date: Fri, 16 May 2008 07:41:34 -0700 (PDT) Subject: Instance of class "object" References: Message-ID: <9dec1377-270f-46d6-bac8-f003e32f9bec@m36g2000hse.googlegroups.com> On May 16, 8:56 am, castironpi wrote: > On May 16, 8:51 am, castironpi wrote: > > > > > > > On May 16, 4:26 am, Peter Otten <__pete... at web.de> wrote: > > > > ?? wrote: > > > > I wonder why below does not work. > > > > > a = object() > > > > a.b = 1 # dynamic bind attribute failed... > > > > The implementation of slots depends on that behaviour: > > > >http://docs.python.org/ref/slots.html > > > > > Does this strange behavior break the LSP (Liskov substitution principle)? > > > > Can you expand on that? > > > > Peter > > > Spirals are important. > > I'd be modeling streams, in par. crossing them.- Hide quoted text - > > - Show quoted text - Python 3.0a5 (py3k:62932M, May 9 2008 win32 Type "help", "copyright", "credits" or >>> import parser >>> import compiler Traceback (most recent call last): File "", line 1, in ImportError: No module named compiler Does anyone want to model mic-based soundwaves? My recent project has been color progression over time, and talking about compilers. From timr at probo.com Thu May 8 03:09:02 2008 From: timr at probo.com (Tim Roberts) Date: Thu, 08 May 2008 07:09:02 GMT Subject: strftime() argument 1 must be str, not unicode References: <48215537.100@promsoft.ru> Message-ID: <3j952491dh15h5g09lcn0j5g47nkssr8i5@4ax.com> "Andrii V. Mishkovskyi" wrote: >2008/5/7 Alexandr N Zamaraev : >> Subj is bag? >> >> Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit >> (Intel)] on win32 >> Type "help", "copyright", "credits" or "license" for more information. >> >>> from datetime import datetime >> >>> datetime.today().strftime('%Y_%m_%d %H_%M_%S.csv') >> '2008_05_07 12_30_22.csv' >> >>> datetime.today().strftime(u'%Y_%m_%d %H_%M_%S.csv') >> Traceback (most recent call last): >> File "", line 1, in >> TypeError: strftime() argument 1 must be str, not unicode > >Unicode and str objects are not the same. Why do you think that this >is a bug? I think that's a perfectly reasonable thing to expect. At the risk of over-generalization, there is no good reason why, by this point in time, all of the standard library routines that accept strings shouldn't also accept Unicode strings. It's the duck typing principle. Unicode strings look, walk, and talk like regular strings. An error like this is not intuitive. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From python at rcn.com Mon May 19 19:11:10 2008 From: python at rcn.com (Raymond Hettinger) Date: Mon, 19 May 2008 16:11:10 -0700 (PDT) Subject: Classmethods are evil References: Message-ID: <50f0dc9e-6c5a-4862-b23c-14be473c531d@d19g2000prm.googlegroups.com> On May 16, 9:01?pm, Ivan Illarionov wrote: > After re-reading "Python is not Java" I finally came to conclusion that > classmethods in Python are a very Bad Thing. Sounds like a serious case of mis-learning. Class methods are the preferred way to implement alternate constructors. For good examples, see dict.fromkeys() or any of the various datetime constructors. Raymond From gizmohackers at gmail.com Thu May 1 19:43:56 2008 From: gizmohackers at gmail.com (gizmohackers at gmail.com) Date: Thu, 1 May 2008 16:43:56 -0700 (PDT) Subject: Up to the minute gizmo and gadget news and reviews! Message-ID: <17ffbd1d-ec9b-4cd8-a515-ca274613fb4e@w5g2000prd.googlegroups.com> Come check out this new site on the latest news and reviews on gizmos and gadgets! http://gizmohacker.com/ From basti.wiesner at gmx.net Mon May 26 15:26:55 2008 From: basti.wiesner at gmx.net (Sebastian 'lunar' Wiesner) Date: Mon, 26 May 2008 21:26:55 +0200 Subject: Python web development that resembles PHP or classic ASP References: <66a261d8-c31d-4519-beb9-c8913f61a87d@m44g2000hsc.googlegroups.com> Message-ID: [ Ivan Illarionov ] > If the OP wants PHP-style programming he will get better results with PHP > because PHP was designed this way. Any Pythonic solution will be an > overkill. Better shoot yourself in the foot with a PHP-like Python-thing, than committing suicide by shooting yourself into the head with PHP ... -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From fetchinson at googlemail.com Wed May 21 22:02:45 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Wed, 21 May 2008 19:02:45 -0700 Subject: backport of 'set' to python 2.3? In-Reply-To: <871w3vdrx9.fsf@benfinney.id.au> References: <871w3vdrx9.fsf@benfinney.id.au> Message-ID: >> Does anyone have a pure python implementation of the builtin 'set' >> object so that I could use that in python 2.3? > > Yes. You have one in Python 2.3 already > , it's just > not a builtin. > >> If this would be the case that would be really great as I wouldn't >> have to change my code that runs happily on 2.5 > > You will, but it's as simple as: > > try: > set() > except NameError: > from sets import Set as set > > You then know that 'set' refers to the set type from that point on (or > you're not on a version of Python that has a 'set' type at all). Thanks Ben! I should have checked the docs........ Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From lists at cheimes.de Thu May 29 06:05:55 2008 From: lists at cheimes.de (Christian Heimes) Date: Thu, 29 May 2008 12:05:55 +0200 Subject: code of a function In-Reply-To: <8a6035a00805290110v67ed53d0j8ae9c93b3089565c@mail.gmail.com> References: <8a6035a00805290110v67ed53d0j8ae9c93b3089565c@mail.gmail.com> Message-ID: Dark Wind schrieb: > Hi, > > Is there any command in Python which gives the code for a function like just > typing the name of a function (say svd) in R returns its code. Yes, it's posible to retrieve the source code IFF the function is implemented in Python and the .py file is available, too. >>> print inspect.getsource(inspect.getsource) def getsource(object): """Return the text of the source code for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a single string. An IOError is raised if the source code cannot be retrieved.""" lines, lnum = getsourcelines(object) return string.join(lines, '') From deets at nospam.web.de Tue May 13 12:45:51 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 13 May 2008 18:45:51 +0200 Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <2b66a86e-5a05-4262-b3c9-4703b0ae3372@d1g2000hsg.googlegroups.com> <5b0e3f70-afde-4480-8713-e7113b1250d7@x35g2000hsb.googlegroups.com> <1f537717-00d0-48ee-99b6-7125b96a6133@t12g2000prg.googlegroups.com> <68t4o0F2vaoncU1@mid.uni-berlin.de> <2a32179a-9439-449c-bd07-fff6a4075aee@s50g2000hsb.googlegroups.com> <7ee5dffd-df8f-46f0-bd78-c81ac0418a9a@d77g2000hsb.googlegroups.com> <65ef773e-a1c3-4adb-a18b-e8b8451efe5e@b5g2000pri.googlegroups.com> <68trmmF2vjivnU1@mid.uni-berlin.de> Message-ID: <68tuv6F2qbm5nU1@mid.uni-berlin.de> > then I think the comparison moves beyond a matter of taste into the > realm of measurable ease-of-use. Oh, would you please additionally comment on the ease of use of FT in the domain of string-manipulation, regular expressions, collection datatypes? I'm keen to know which 5-10 times faster FT-driven site out there deals with user-input without these.... Diez From ian.g.kelly at gmail.com Fri May 9 02:23:10 2008 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 9 May 2008 00:23:10 -0600 Subject: slicing lists In-Reply-To: References: Message-ID: <3fc761710805082323s3e392b8av2605b9be8240c53f@mail.gmail.com> On Wed, May 7, 2008 at 5:29 PM, Yves Dorfsman wrote: > Is there a way to do: > x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] > x[0,2:6] > > That would return: > [0, 3, 4, 5, 6] > > I am surprised this notation is not supported, it seems intuitive. > A concrete example of the sort of thing I want to do: > > p = file('/etc/passwd').readlines() > q = [ e.strip().split(':')[0,2:] for e in p ] > > (getting rid of the password / x field) Have a look at the itemgetter function from the operator module. g = itemgetter( 0, *range(2, 6) ) p = file("/etc/passwd").readlines() q = [ g( e.strip().split(':') ) for e in p ] From george.sakkis at gmail.com Fri May 23 14:00:42 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 23 May 2008 11:00:42 -0700 (PDT) Subject: Segmentation fault on updating a BYTEA field [psycopg2] References: Message-ID: <79a4662f-3402-49e7-a0ed-0d7a3fdb3172@r66g2000hsg.googlegroups.com> On May 21, 6:32 pm, George Sakkis wrote: > I have a simple DB table that stores md5 signature pairs: > > Table "public.duplicate" > Column | Type | Modifiers > ----------+-------+----------- > sig | bytea | not null > orig_sig | bytea | not null > Indexes: > "duplicate_pkey" PRIMARY KEY, btree (sig) > "ix_duplicate_orig_sig" btree (orig_sig) > > I use SqlAlchemy to interact with it and inserting works fine; update > however crashes hard with a segfault. Sure enough, the crash is > reproducible when using the underlying psycopg2 directly: > > >>> import psycopg2 > >>> connect_string = ... > >>> conn = psycopg2.connect(connect_string) > >>> cur = conn.cursor() > >>> cur.execute('SELECT sig,orig_sig from duplicate limit 1') > >>> d = cur.fetchone() > >>> d > > (, > )>>> map(str,d) > > ["\x02#qO\xb0\xcc\xfcx\xb9u\xa5\x83)\xc4'@", '\xa1\xf22\xf6y\xd0\xbc > \xea6\xf0Y\xf1"\xc9(\n']>>> cur.execute('UPDATE duplicate SET orig_sig=%(orig_sig)s WHERE duplicate.sig = %(duplicate_sig)s', > > ... dict(orig_sig=d[0], duplicate_sig=d[1])) > Segmentation fault > > Am I (and SqlAlchemy) doing something silly or is this a bug in > psycopg2 ? > > George I installed the latest release (psycopg2-2.0.7) and it seems the problem is gone. Sorry for the noise. George From cjw at ncf.ca Sat May 10 18:20:04 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Sat, 10 May 2008 18:20:04 -0400 Subject: test Message-ID: <48261F94.6060608@ncf.ca> test From notnorwegian at yahoo.se Wed May 21 15:19:16 2008 From: notnorwegian at yahoo.se (notnorwegian at yahoo.se) Date: Wed, 21 May 2008 12:19:16 -0700 (PDT) Subject: Psyche (scheme in python), how to run on vista? Message-ID: <01afbef9-6225-487d-9468-cbdf9b03c64b@b1g2000hsg.googlegroups.com> anyone using psyche? how do you run it on Vista? what file do you click? there is no obvious file like psyche.py... From pistacchio at gmail.com Thu May 8 09:49:01 2008 From: pistacchio at gmail.com (pistacchio) Date: Thu, 08 May 2008 15:49:01 +0200 Subject: Newbie to python --- why should i learn ! References: <9f5ee6c3-86f7-401a-acc8-cd2c9b059fbd@x19g2000prg.googlegroups.com> <68gcn4F2su97jU1@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch ha scritto: > On Thu, 08 May 2008 04:17:01 -0700, s0suk3 wrote: > >> Are you a newbie to Python, or to programming in general? I'll assume >> you are a newbie to programming in general because of that last >> question you asked. Things in Python are easier than in almost any >> other programming language. Here are three Hello World programs: > > Counterexamples for quite short "greetings" in other programming languages: > > (Free)BASIC:: > > Print "Hello World!" freebasic is another language i'd point out to a newbie, even if it is not as multiplatform as python if. it has a decent community and a large amount of libraries. it doesn't let you explore functional or, worse, object oriented programming nor you can write server side programs with it. The others are examples of easy "hello world" languages, but, passed that, i think they don't have the same capabilities of python on terms of support, kind of programs you can write and even overall complexity (haskell forces you to functional programming, io is really a minor language, ocalm forces you to di OOP and, if writing hello world is simple, on the other hand ir may have lines of code that read like: | [] -> [] and that negatively compesate the easy way you can write "hello world" > OCaml:: > > print_string "Hello World!" ;; > > Io:: > > "Hello World!" linePrint > > Haskell:: > > main = putStrLn "Hello World!" > > Ciao, > Marc 'BlackJack' Rintsch From holdenpage at gmail.com Fri May 9 11:39:29 2008 From: holdenpage at gmail.com (Holden) Date: Fri, 9 May 2008 08:39:29 -0700 (PDT) Subject: A question about python and xml Message-ID: <0507ffd8-6842-4546-a635-414fabf481fb@y21g2000hsf.googlegroups.com> Hello everyone I heard this was a good community to go too for help and advice. I want to make a web site that uses the python programming language which I am VERY new at. This website would store simple data such as names in a form. At first I wanted to use mysql to store the data but I want to export the data using xml. So say if a user logged in they would be able to store there basic information in an xml file and download it whenever. Is that possible using XML and Python. I am sorry if this post doesn't make much sense but any advice would be greatly appreciated. You can also e-mail me if you need further information or clarification. Thanks Holden From meesters at uni-mainz.de Thu May 29 10:11:46 2008 From: meesters at uni-mainz.de (Christian Meesters) Date: Thu, 29 May 2008 16:11:46 +0200 Subject: seg. fault with Py_BuildValue? References: <6a7qarF35bvivU1@mid.uni-berlin.de> Message-ID: > What happens if you get rid of the ()? Can't see any difference. From ptmcg at austin.rr.com Mon May 19 09:40:31 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 19 May 2008 06:40:31 -0700 (PDT) Subject: explain this function to me, lambda confusion References: <5cc7ef7a-dd21-4772-a7e3-765410f810bb@l17g2000pri.googlegroups.com> Message-ID: <081fe61b-820b-4512-80a9-8a0805f3ce55@k13g2000hse.googlegroups.com> On May 18, 10:41?am, "inhahe" wrote: > > Both the responses offer lambda free alternatives. That's fine, and > > given the terse documentation and problems that I had understanding > > them, I would agree. So what applications are lambdas suited to? I > > think the parameterised function model is one. > > What else? > > i've hardly ever used lambdas since map() and filter() were replaced by list > comprehension. ?two other uses I can think of for it are: using it as a > sorting key (which takes a function and lambdas are perfect for that when a > direct function isn't available. for example, lambda x: x.myName), and I > made an irc bot once that certain events had a list of fuctions that would > be called after that event. ?it was like being able to dynamically add and > remove event handlers. ?for example what if you asked the user a question > and you wanted to know for the next input whether it was from that user and > was an answer to that question. ?sometimes the function to add would be very > simple, so writing a def for it would just be ugly. lambda is handy in defining parse actions in pyparsing. Parse actions are callbacks to be run when an expression within a larger grammar is matched. A common use for parse actions is to do some sort of text or type conversion. The simplest parse actions are called using the list of matched tokens. Here is a subexpression that will convert numeric strings found in a larger grammar to ints: integer = Word("0123456789").setParseAction(lambda tokens: int(tokens[0]) ) Since this returns an actual int, there is no need to junk up the post- parsing code with calls to int(), float(), etc. for these simple conversions. Here is an example parse action that just converts a set of matched words to title case: title = OneOrMore(Word(alphas)).setParseAction(lambda tokens: " ".join([ t.title() for t in tokens ]) ) print title.parseString("the sun also rises")[0] prints: The Sun Also Rises This second example is about as complex as I'd like to get in a lambda, though. Anything more elaborate than that, and I'd go with a separately defined function. -- Paul From _karlo_ at _mosor.net_ Thu May 22 04:15:52 2008 From: _karlo_ at _mosor.net_ (Karlo Lozovina) Date: Thu, 22 May 2008 08:15:52 +0000 (UTC) Subject: Returning to 'try' block after catching an exception References: <485f7ddc-8f50-4483-b591-151f1ae560be@k10g2000prm.googlegroups.com> Message-ID: alex23 wrote in news:485f7ddc-8f50-4483-b591-151f1ae560be at k10g2000prm.googlegroups.com: > If you know what exception to expect, and you know how to "fix" the > cause, why not just put tests _before_ some_function() is called to > ensure that everything is as it needs to be? Because when you expect exception to occur on something like 0.01% of cases, and you have 4 or 5 exceptions and the code to test for each conditions that cause exceptions is quite long and burried deep inside some other code it's much better to do it this way ;). Too bad there's no syntactic sugar for doing this kind of try-except loop. -- _______ Karlo Lozovina - Mosor | | |.-----.-----. web: http://www.mosor.net || ICQ#: 10667163 | || _ | _ | Parce mihi domine quia Dalmata sum. |__|_|__||_____|_____| From zxo102 at gmail.com Sat May 24 19:05:42 2008 From: zxo102 at gmail.com (zxo102) Date: Sat, 24 May 2008 16:05:42 -0700 (PDT) Subject: Hexadecimal: how to convert 'ED6F3C01' to "\xED\x6F\x3C\x01" in python coding? References: Message-ID: <7890f3bd-0d66-4bdd-871e-516344a39f3d@i36g2000prf.googlegroups.com> On 5?25?, ??6?59?, zxo102 wrote: > But this is not "\xED\x6F\x3C\x01". I need it for > struct.unpack('f',"\xED\x6F\x3C\x01") to calculate the decimal value > (IEEE 754). > Any other suggestions? > > ouyang > > On 5?25?, ??6?46?, Sebastian 'lunar' Wiesner > wrote: > > > > > -----BEGIN PGP SIGNED MESSAGE----- > > Hash: SHA1 > > > [ zxo102 ] > > > > how to change the hexadecimal 'ED6F3C01' (or 'ED 6F 3C 01') to > > > "\xED\x6F\x3C\x01" in python coding? > > > When I take 'ED6F3C01' as a string and insert '\x' into it, I just got > > > the error information : invalid \x escape. > > > [1]--> 'ED6F3C01'.decode('hex') > > Out[1]: '\xedo<\x01' > > > - -- > > Freedom is always the freedom of dissenters. > > (Rosa Luxemburg) > > -----BEGIN PGP SIGNATURE----- > > Version: GnuPG v2.0.9 (GNU/Linux) > > > iEYEARECAAYFAkg4mtEACgkQn3IEGILecb7W6ACeNwr/vavkaXluvc0zeSa4cy1N > > YFIAoJjMsrRcLhqAPRxKktUqt7miMTrs > > =jxll > > -----END PGP SIGNATURE------ ??????? - > > - ??????? - Hash: SHA1 I got it. Just simply use it like struct.unpack('f',"ED6F3C01".decode('hex')). It works now. Thank you very much. ouyang From varshinirs at gmail.com Sun May 11 21:05:54 2008 From: varshinirs at gmail.com (surana) Date: Sun, 11 May 2008 18:05:54 -0700 (PDT) Subject: A site for all your programming language needs Message-ID: <40f72ace-ede1-4b92-a9af-e77cf511d9cf@p25g2000pri.googlegroups.com> A complete tutorial for all your programming language needs such as Java, .Net and many more. A one shop site for all your programming language needs and find details on latest updates on sqlserver 2008 http://www.computenetwork.blogspot.com http://www.sqlserversoftware.blogspot.com From krustymonkey at gmail.com Thu May 8 00:02:48 2008 From: krustymonkey at gmail.com (krustymonkey at gmail.com) Date: Wed, 7 May 2008 21:02:48 -0700 (PDT) Subject: pickle problem Message-ID: I'm wondering if anyone can help with a workaround for a problem I currently have. I'm trying to set up a prefork tcp server. Specifically, I'm setting up a server that forks children and has them listen on pipes created with os.pipe(). The parent process for the group starts an inet:tcp server on a given port. In the parent, after a "socket.accept()", I'm trying to pickle the connection object to send over an IPC pipe (as stated previously), but I get the following error: File "/usr/lib/python2.4/copy_reg.py", line 76, in _reduce_ex raise TypeError("a class that defines __slots__ without " TypeError: a class that defines __slots__ without defining __getstate__ cannot be pickled Does anyone know of a workaround for this? Maybe my approach to this is wrong? Any help would be appreciated. Jay From yves at zioup.com Sun May 11 22:28:13 2008 From: yves at zioup.com (Yves Dorfsman) Date: Mon, 12 May 2008 02:28:13 GMT Subject: anonymous assignment Message-ID: <1XNVj.133805$Cj7.33096@pd7urf2no> Is there anyway to tell python I don't care about a value ? Say I want today's year and day, I'd like to do something like: import time y, None, d, None, None, None, None = time.localtime() I know you can't assign anything to None, but I'm sure you get what I mean, a special keyword that means I don't care about this value. In this particular case, there's got to be a better way than: d = time.local() y = d[0] d = d[1] Thanks. Yves. http://www.SollerS.ca From berlin.brown at gmail.com Tue May 6 10:40:10 2008 From: berlin.brown at gmail.com (Berlin Brown) Date: Tue, 6 May 2008 07:40:10 -0700 (PDT) Subject: Cygwin and path issues Message-ID: <941c7834-3120-471f-aae9-d6dd7b412b82@a1g2000hsb.googlegroups.com> I am trying to run some basic unit tests, but I can't get the paths setup in python/cygwin to pick up my modules. This code works fine in linux and I installed python through cygwin not as part of the win32 install. DIR_PATH = os.path.abspath(os.path.dirname(os.path.realpath(__file__))) PROJECT_HOME = os.path.join(DIR_PATH, '..', '..', '..') print("INFO: project_home=%s" % PROJECT_HOME) EXTRA_PATHS = [ DIR_PATH, os.path.join(PROJECT_HOME, 'projects', 'ghostnet'), os.path.join(PROJECT_HOME, 'google_appengine'), os.path.join(PROJECT_HOME, 'google_appengine', 'lib', 'webob'), os.path.join(PROJECT_HOME, 'google_appengine', 'lib', 'yaml', 'lib') ] sys.path = EXTRA_PATHS + sys.path print sys.path --------------- in my ~/.bash_profile I also included the following. export PYTHONPATH=/cygdrive/c/projects/projects_ecl/botlist:/cygdrive/ c/projects Basically, I tried to add the module directory locations in my code; also I tried to add the absolute path to my PYTHONPATH. None of these approaches work. I get the following error, which I dont get on the linux side: Traceback (most recent call last): File "run_all_tests.py", line 108, in from django.conf import settings ImportError: No module named django.conf From kyosohma at gmail.com Wed May 7 09:07:25 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 7 May 2008 06:07:25 -0700 (PDT) Subject: loading folder list from my mailbox in python References: Message-ID: On May 7, 1:15?am, ris... at students.iiit.ac.in wrote: > Hey everyone, > I want to print the folder list of my mailbox using python (IMAP4), and > with hierarchy, i.e. it should print all the names of the folders of my > mailbox and the folders within them. > Can anyone please help me with this. Without knowing the backend, it's mostly a shot in the dark. Oh well. I did some Google-Fu (which you would be wise to learn) and found the following: http://www.devshed.com/c/a/Python/Python-Email-Libraries-part-2-IMAP/ http://www.example-code.com/python/imap.asp http://pypi.python.org/pypi/imap-utils/0.3 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52299 I think at least one of those will get you started. If you're talking about communicating with Exchange, then you may have to use some win32 or ctypes methods. Mike From wizzardx at gmail.com Sat May 24 11:51:23 2008 From: wizzardx at gmail.com (David) Date: Sat, 24 May 2008 17:51:23 +0200 Subject: Code correctness, and testing strategies In-Reply-To: References: Message-ID: <18c1e6480805240851t9aa79b4u6f1056a37e011afa@mail.gmail.com> > I work in small increments, writing one test at a time, then some code, > then another test, then some more code, etc. In fact, I take this to what > many people might call an extreme. Thanks for the replies. I've read about the TDD (and similar) approaches. Maybe I need to try it and get used to it, but there are a few things I don't like about it on a gut level. I'll try to enumerate my concerns here. Problem 1: You can only code against tests Basically, with TDD you write the tests first, then the code which passes/fails the tests as appropriate. However, as you're writing the code you will also think of a lot of corner cases you should also handle. The natural way to do this is to add them to the code first. But with TDD you have to first write a test for the corner case, even if setting up test code for it is very complicated. So, you have these options: - Take as much time as needed to put a complicated test case in place. - Don't add corner case to your code because you can't (don't have time to) write a test for it. - Add the corner case handling to the code first, and try to add a test later if you have time for it. Problem 2: Slows down prototyping In order to get a new system working, it's nice to be able to throw together a set of modules quickly, and if that doesn't work, scrap it and try something else. There's a rule (forget where) that your first system will always be a prototype, regardless of intent. With TDD, you have to first write the tests for the first version. Then when that first version doesn't work out, you end up scrapping the tests and the code. The time spent writing the tests was wasted. Problem 3: Slows down development in general Having to write tests for all code takes time. Instead of eg: 10 hours coding and say 1/2 an hour manual testing, you spend eg: 2-3 hours writing all the tests, and 10 on the code. Problem 4: Can make refactoring difficult. If you have very complete & detailed tests for your project, but one day you need to change the logic fundamentally (maybe change it from single-threaded to multi-threaded, or from running on 1 server to distributed), then you need to do a large amount of test refactoring also. The more tests you have (usually a good thing), the longer it will take to update all the tests, write new ones, etc. It's worse if you have to do all this first before you can start updating the code. Problem 5: Tests are more important than code You need to justify the extra time spent on writing test code. Tests are nice, and good to have for code maintainability, but they aren't an essential feature (unless you're writing critical software for life support, etc). Clients, deadlines, etc require actual software, not tests for software (that couldn't be completed on time because you spent too much time writing tests first ;-)). Problems like the above sum up why I'm not comfortable with the idea of TDD. I think that automated tests can be very valuable for maintainability, making sure that you or other devs don't break something down the line. But these benefits must be worth the time (and general inconvenience) spent on adding/maintaining the tests. If I did start doing some kind of TDD, it would be more of the 'smoke test' variety. Call all of the functions with various parameters, test some common scenarios, all the 'low hanging fruit'. But don't spend a lot of time trying to test all possible scenarios and corner cases, 100% coverage, etc, unless I have enough time for it. I'm going to read more on the subject (thanks to Ben for the link). Maybe I have some misconceptions. David. From tjreedy at udel.edu Sat May 24 21:28:26 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 24 May 2008 21:28:26 -0400 Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com><8763t3by81.fsf@benfinney.id.au><5ea78616-e955-4ee0-8e60-a22734ec31be@79g2000hsk.googlegroups.com> Message-ID: "Benjamin Kaplan" wrote in message news:ec96e1390805241357i6e481e3enf12b4d213e887008 at mail.gmail.com... | On Sat, May 24, 2008 at 10:14 AM, Fuzzyman wrote: || > For example, at Resolver Systems we expose the spreadsheet object | > model to our users. It hasa public, documented, API - plus a host of | > undocumented internally used methods. | > | > We would really *much* rather hide these, because anything our | > customers start using (whether documented or not) we will probably | > have to continue supporting and maintaining. | > | > The 'we told you not to use that' approach, when applied to paying | > customers doesn't really work... all they see is that you broke their | > spreadsheet code by changing your API. Python was not really written with 'difficult' customers in mind ;-) One could largely hide private vars with a program that substituted random names for single _ names, and removed the doc strings for functions, classes, and methods with such names. Such a program could even put such names in a separate module imported as '_private_do_not_use_'. From Sengly.Heng at gmail.com Sat May 3 04:36:02 2008 From: Sengly.Heng at gmail.com (Sengly) Date: Sat, 3 May 2008 01:36:02 -0700 (PDT) Subject: image matching algorithms References: Message-ID: <1cf07f3f-a9bb-4242-bb64-a663845981be@s33g2000pri.googlegroups.com> On Mar 14, 10:59?am, "Daniel Fetchinson" wrote: > > > Since you seem to know quite a bit about this topic, what is your > > > opinion on the apparently 'generic' algorithm described here: > > >http://grail.cs.washington.edu/projects/query/? > > > So far it seems to me that it does what I'm asking for, it does even > > > more because it can take a hand drawn sample image and query the > > > database for similar photos. > > > > There is even a python implementation for it here: > > >http://members.tripod.com/~edcjones/pycode.html > > > > On the histogram method I agree that it won't work partly because of > > > what you say and partly because it is terribly slow since it's > > > comparing every single pixel. > > > I'm hardly the expert and can't answer authoritatively, but here's my 2c. > > > I can't comment as to the actual accuracy of the algorithm, since it > > will depend on your specific data set (set of photos). The algorithm is > > sensitive to spatial and luminance information (because of the YIQ > > colorspace), so there are simple ways in which it will fail. > > > The histogram method uses only color, but has a lot of numbers to > > compare. You may find the histogram method insensitive to spatial > > relations (a landscape with the mountain on the left and one with the > > mountain on the right) compared to the wavelet approach. > > > This is a relatively old paper, and I've seen other more recent image > > retrieval research using wavelets (some cases using only the > > high-frequency wavelets for "texture" information instead of the > > low-frequency ones used by this paper for "shape") and other information > > retrieval-related research using lossy compressed data as the features. > > If you have time, you may want to look at other research that cite this > > particular paper. > > > And just a thought: Instead of merely cutting off at m largest-wavelets, > > why not apply a quantization matrix to all the values? > > I'm not at all an expert, just started to look into image matching, so > I'm not quite sure what you mean. What's a quantization matrix in this > context? Hello, I am also looking for the solution to the same problem. Could you let me know if you have found something useful so far? I appreciate your response. Thanks a lot. Sengly From ulrich at dorda.net Sun May 25 08:56:37 2008 From: ulrich at dorda.net (ulrich at dorda.net) Date: Sun, 25 May 2008 05:56:37 -0700 (PDT) Subject: access interactive namespace from module (shared namespace?) References: Message-ID: <79478cee-4bc6-426f-9e64-04841aee1f3d@k37g2000hsf.googlegroups.com> Thanks a lot to all! Apart from obtaining the solution I was searching for, I learned a lot by studying your answers! Cheers, Ulrich From bignose+hates-spam at benfinney.id.au Fri May 2 23:29:23 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 03 May 2008 13:29:23 +1000 Subject: unified command line args, environment variables, .conf file settings. References: Message-ID: <87ve1wxdyk.fsf@benfinney.id.au> smitty1e writes: > Just a fun exercise to unify some of the major input methods for a > script into a single dictionary. > Here is the output, given a gr.conf file in the same directory with > the contents stated below: > > smitty at localhost ~/proj/mddl4/test $ ./inputs.py > {'source_db': '/home/sweet/home.db'} > smitty at localhost ~/proj/mddl4/test $ source_db="test_env" ./inputs.py > {'source_db': 'test_env'} > smitty at localhost ~/proj/mddl4/test $ ./inputs.py -f "test_cli" > {'source_db': 'test_cli'} A good start. However, you need to account for two conventions with configuration of programs via environment variables: * Environment variables that will be inherited by subprocesses are conventionally distinguished from variables that will not be inherited by using an UPPER_CASE name for variables (like process config variables) that will be inherited, and a lower_case name for variables (like local state variables) that will not be inherited. * The process environment is a flat namespace, so config environment variables need to be named to reduce the risk of namespace collision with variables used by other programs. This is often done by prefixing the name with the name of the program or system that will consume it. e.g. The search path for Python imports is configured via an attribute named 'path', but in the environment by a variable named 'PYTHONPATH' (yes, I know that's not exactly equivalent, but it's a good example). Neither of these distinctions need to be made in a program-specific configuration file, so these conventions don't apply there and would be inappropriate. So you then need to deal with a configuration setting being named one way in the environment, and another way in the configuration file and elsewhere in the program. This is probably best done by a mapping specifically for the environment variable names: config_env_names = { 'source_db': 'GR_SOURCE_DB', } and then referencing that dictionary when inspecting the environment: for key in config.keys(): # ... environ_name = config_env_names[key] environ_value = os.environ.get(environ_name) if environ_value is not None: config[key] = environ_value #... -- \ "Pinky, are you pondering what I'm pondering?" "I think so, | `\ Brain, but how will we get a pair of Abe Vigoda's pants?" -- | _o__) _Pinky and The Brain_ | Ben Finney From budcrandall at hotmail.com Fri May 30 23:32:47 2008 From: budcrandall at hotmail.com (budcrandall at hotmail.com) Date: Fri, 30 May 2008 20:32:47 -0700 (PDT) Subject: compatability Message-ID: <62e2b0c6-dc81-494a-b2bd-c6455049ff77@d1g2000hsg.googlegroups.com> I'm currently using 3ds Max Design 2009 and Maya. Will Python and Plone be compatible with my systems? I would really like to incorporate this software. Thank You Bud budcrandall at hotmail.com. From kyosohma at gmail.com Fri May 16 17:19:41 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 16 May 2008 14:19:41 -0700 (PDT) Subject: encoding problem References: Message-ID: On May 16, 3:31?pm, Luis Zarrabeitia wrote: > Hi, guys. > I'm trying to read an xml file and output some of the nodes. For that, I'm > doing a > print node.toprettyxml() > > However, I get this exception: > > === > ? ? out.write(tag.toxml()) > UnicodeEncodeError: 'ascii' codec can't encode character u'\xba' in position > 190: ordinal not in range(128) > === > > That happens if I "print" it, or send it to stdout, or send it to a file. > > How can I fix it? > cat file works perfectly, and I'm using an utf8 terminal. > > I'm particularly puzzled that it won't work even if I write to a file opened > in "b" mode. Worst thing is... I don't really need that character, just a > general idea of how the document looks like. > > -- > Luis Zarrabeitia (aka Kyrie) > Fac. de Matem?tica y Computaci?n, UH.http://profesores.matcom.uh.cu/~kyrie I recommend studying up on Python's Unicode methods and the codecs module. This site actually talks about your specific issue though and gives pointers: http://evanjones.ca/python-utf8.html HTH Mike From paul.melis at gmail.com Thu May 1 17:01:42 2008 From: paul.melis at gmail.com (Paul Melis) Date: Thu, 1 May 2008 14:01:42 -0700 (PDT) Subject: Getting started with pyvtk References: Message-ID: On 1 mei, 22:54, Peter Pearson wrote: > I'm trying to get started with pyvtk, the Python interface > to the Visualization Toolkit, It looks like you're using this package: http://cens.ioc.ee/projects/pyvtk/ These are not the official Python bindings to VTK, but seem to be an add-on that allow you to manipulate VTK _files_ from Python. The official bindings are included in the VTK distribution and can be enabled at build-time (assuming you build VTK yourself). For a simple example that will open a window and show some 3D object, see for example the example code the vtkConeSource class: http://public.kitware.com/cgi-bin/viewcvs.cgi/*checkout*/Examples/Tutorial/Step1/Python/Cone.py?root=VTK&content-type=text/plain > Simply running "vtk" (apparently 4.0) VTK 4.0 is really really old. Consider switching to 5.0 at least or use the CVS version if you feel adventurous. Hope this helps, Paul From jaywgraves at gmail.com Sun May 18 13:42:50 2008 From: jaywgraves at gmail.com (jay graves) Date: Sun, 18 May 2008 10:42:50 -0700 (PDT) Subject: Python library for clustering from distance vector References: <101cfef8-ecd2-409a-8701-905780a7862e@q24g2000prf.googlegroups.com> Message-ID: On May 17, 11:49 pm, Sengly wrote: > I am looking for a python library which can cluster similar objects > into their respective groups given their similarity score of each two > of them. I have searched the group but I couldn't find any helpful > information yet. How about google? Searching for the terms python and cluster gave some results for me. http://www.google.com/search?q=python+cluster > Any suggestion is appreciated. Also, if you know any specific group > that I should post this message, please also suggest. The book, "Programming Collective Intelligence" by Toby Segaran is great and has examples of clustering algorithms written in Python. http://www.amazon.com/Programming-Collective-Intelligence-Building-Applications/dp/0596529325/ ... Jay Graves From gagsl-py2 at yahoo.com.ar Tue May 13 04:41:35 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 13 May 2008 05:41:35 -0300 Subject: how to get information of a running prog in python References: <8b571818-25f0-4c5d-8b1c-5b7e73192d15@w5g2000prd.googlegroups.com> <58a5cb5c-5c10-43a3-bff0-58fa3c213a80@i36g2000prf.googlegroups.com> Message-ID: En Tue, 13 May 2008 01:22:52 -0300, Ivan Illarionov escribi?: > On Mon, 12 May 2008 20:29:46 -0700, George Sakkis wrote: >>> > On Mon, May 12, 2008 at 10:19 PM, Jimmy >>> > wrote: >>> >>> > > ?can anyone tell me, in python, how to obtain some information of >>> > > ?a running program? >>> > > ?paticularly, if i am playing some music in audacious or other >>> > > ?media player, how can i get the the name and some other info of >>> > > ?current playing song? It seems that audicious doesn't output on >>> > > ?run-time -- >>> >> Your best bet is if the *specific* program you're interested in (e.g. >> audacious) exposes this information programmatically in some way. It's >> up to the developers of this application if and how they choose to do >> it. Even if they do it, there's no requirement that the same API will >> work for any other program of the same category, unless there is some >> popular industry standard that most applications implement. > > George, have you read my post in this thread? What OP wants is actually > possible and it's quite easy. X server is the "superprogram" that knows > the names of all GUI window titles. That relies on the fact that audacious (or whatever player used) actually includes the song name as part of its window title. As G. Sakkis said, this depends on the specific program used. And what about "some other info of?current playing song"? -- Gabriel Genellina From __peter__ at web.de Mon May 26 06:34:33 2008 From: __peter__ at web.de (Peter Otten) Date: Mon, 26 May 2008 12:34:33 +0200 Subject: b64encode and unicode problem References: Message-ID: Gabriel Rossetti wrote: > Hello everyone, > > I am trying to encode a string using b4encode and I get the following > error : > > >>> b64encode(u"Salut Pierre, comment ?a va?") > Traceback (most recent call last): > File "", line 1, in > File "/usr/lib/python2.5/base64.py", line 53, in b64encode > encoded = binascii.b2a_base64(s)[:-1] > UnicodeEncodeError: 'ascii' codec can't encode character u'\xe7' in > position 22: ordinal not in range(128) > > If I remove the "u" infront of the string, it works. The problem is that > I in my program, the string is given to me un unicode/utf-8. I tried > several things, but I still get it, How can I get it to work, anybody > have any idea? >>> base64.b64encode(u"Salut Pierre, comment ?a va?".encode("utf8")) 'U2FsdXQgUGllcnJlLCBjb21tZW50IMOnYSB2YT8=' unicode is a sequence of codepoints with no predetermined representation as a byte sequence. Therefore whenever you go from unicode to str you have to decide upon an encoding. If you don't make that decision python assumes ascii which will of course fail for non-ascii characters. Peter From swapsun at gmail.com Wed May 7 08:25:25 2008 From: swapsun at gmail.com (swapsun at gmail.com) Date: Wed, 7 May 2008 05:25:25 -0700 (PDT) Subject: Learning question... Message-ID: Any idea why the following program does not work? I was learning IO on Python and the following generates a TypeError: range() integer end argument expected, got str. I am a beginner. ################################ # print input name (str k), j times using raw_input def hello(): j=raw_input("Please type in the number of times you want to print ") k=raw_input("Please type in your name ") printname(j,k) def printname(j,k): for i in range(j): print ("Hello %s" % k) ################################ From martin at marcher.name Tue May 20 17:11:35 2008 From: martin at marcher.name (Martin Marcher) Date: Tue, 20 May 2008 23:11:35 +0200 Subject: self.var hmm? In-Reply-To: <4f28a341-8f27-4e07-8940-57ae2d09c0df@q27g2000prf.googlegroups.com> References: <4f28a341-8f27-4e07-8940-57ae2d09c0df@q27g2000prf.googlegroups.com> Message-ID: <5fa6c12e0805201411y290ba5xd43caf5b78d5a14c@mail.gmail.com> Hi, that's because self.group is not the same as TaskGroup.group quickish: class TaskGroup group = [] def __init__(self): """ ## note that all TaskGroup instances now use the the same self.group """ self.group = TaskGroup.group def addTask(self, task): self.group.append(task) hth martin On Tue, May 20, 2008 at 10:58 PM, wrote: > class TaskGroup: > def __init__(self): > self.group = [] > > def addTask(self, task): > self.group.append(task) > > > is this wrong? i have a program thats too big to post but should i > just do group.append in addTask? > > reason is when later doing TaskGroup.group i get None > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.xing.com/profile/Martin_Marcher You are not free to read this message, by doing so, you have violated my licence and are required to urinate publicly. Thank you. From upton at virginia.edu Thu May 29 10:49:07 2008 From: upton at virginia.edu (Dan Upton) Date: Thu, 29 May 2008 10:49:07 -0400 Subject: Python and Flaming Thunder In-Reply-To: References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <94bac166-d13c-44dd-af84-db19e19488b8@w1g2000prd.googlegroups.com> <8cfd3523-8d16-40bc-b904-94a6a36a414d@p25g2000pri.googlegroups.com> <5c98049e-e62e-4ab1-afed-b0a3e186bd05@w1g2000prd.googlegroups.com> <3dd6fa95-e9fe-4922-a46d-020cf9263469@w4g2000prd.googlegroups.com> Message-ID: <5504f9ac0805290749w420259a3n13a65406c69f1bd@mail.gmail.com> On Thu, May 29, 2008 at 3:36 AM, Duncan Booth wrote: > Dave Parker wrote: > >> Catch doesn't return just error types or numbers, it can return any >> object returned by the statements that are being caught; catch doesn't >> care what type they are. For example: >> >> Writeline catch(set x to "hello world".). >> >> will write "hello world". > > I really don't get this. Surely the point about an error being thrown to a > catch statement is that the error path is separate from the normal > execution path? What you are doing here is ensuring that unexpected errors > have no chance at all of propagating up to the top level: they are > invariably going to get caught by some other handler that was installed > just because someone was too lazy to write a set statement followed by a > writeline. It also looks like an overloading of catch, semantically similar to the C: int retcode; if( retcode = doSomethingThatReturns0or1() ) printf("Hello world"); Again, I don't think you want to start overloading your exception-handling mechanism. If you want a set expression to be equal to the l-value at the end, that's fine, but there's no reason that catch should evaluate to an object or an integral- or real-valued exception in error cases, or of the last statement of the block if there's no error. (Evaluating a block to be equal to its last statement is okay, I guess; I know at least that there's a call in Scheme that lets you do a more imperative programming style in the functional language--whether that's a good thing is probably a holy war.) I just think if you're shooting for an easily understandable language, overloading error handling requires more thought on the programmer's part, not less, because they have to reason about all outcomes. From unknown_hero007 at hotmail.com Fri May 9 05:51:13 2008 From: unknown_hero007 at hotmail.com (Unknown Hero) Date: Fri, 9 May 2008 02:51:13 -0700 (PDT) Subject: Scanning through Windows registry... References: <48216129.5090405@timgolden.me.uk> Message-ID: <2f0e3ef0-c33d-4dc3-819e-1c78e5bccb31@8g2000hse.googlegroups.com> On 7 touko, 14:25, Unknown Hero wrote: > I'll post my code here once I have time to write it, currently I'm > rather busy. That is merely for optimization suggestions and for > others who might need the same sort of code I did. > > Thank you once again. Finally managed to get it to work (heh, I was pretty darn lost even though I had the best help) but as promised, I'll post my code here for those who might be interested in it. The biggest of thanks to Tim Golden, who basically walked me step-by-step through this. Most of the code is copied from his examples above. #Goes through all keys and subkeys in the selected hive (defined as root) and replaces the value 'old' with the value 'new' # #IMPORTANT! You should always back up the registry before attempting to modify it. #The author of this script CANNOT BE HELD RESPONSIVE for any damage caused by running this script. # #To customize the script to your liking, you can alter the values old, new, root. # #old and new can be any string value #root has to be one of the following: # # _winreg.HKEY_LOCAL_MACHINE # _winreg.HKEY_CURRENT_USER # _winreg.HKEY_CLASSES_ROOT # _winreg.HKEY_USERS # _winreg.HKEY_CURRENT_CONFIG import _winreg HIVES = { "HKEY_LOCAL_MACHINE" : _winreg.HKEY_LOCAL_MACHINE, "HKEY_CURRENT_USER" : _winreg.HKEY_CURRENT_USER, "HKEY_CLASSES_ROOT" : _winreg.HKEY_CLASSES_ROOT, "HKEY_USERS" : _winreg.HKEY_USERS, "HKEY_CURRENT_CONFIG" : _winreg.HKEY_CURRENT_CONFIG } old = "This was value before" new = "This is new value" start = "HKEY_LOCAL_MACHINE\\" startHandle = _winreg.HKEY_LOCAL_MACHINE #Values for start and startHandle are: HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER, HKEY_CLASSES_ROOT, HKEY_USERS, HKEY_CURRENT_CONFIG class RegKey: def __init__ (self, name, key): self.name = name self.key = key def __str__ (self): return self.name def walk (top): """walk the registry starting from the key represented by top in the form HIVE\\key\\subkey\\..\\subkey and generating key, subkey_names, values at each level. key is a lightly wrapped registry key, including the name and the HKEY object. subkey_names are simply names of the subkeys of that key values are 3-tuples containing (name, data, data-type). See the documentation for _winreg.EnumValue for more details. """ try: if "\\" not in top: top += "\\" root, subkey = top.split ("\\", 1) # print "KEY:", root + "\\" + subkey key = _winreg.OpenKey (HIVES[root], subkey, 0, _winreg.KEY_READ | _winreg.KEY_SET_VALUE) subkeys = [] i = 0 while True: try: subkeys.append (_winreg.EnumKey (key, i)) i += 1 except EnvironmentError: break values = [] i = 0 while True: try: values.append (_winreg.EnumValue (key, i)) i += 1 except EnvironmentError: break yield RegKey (top, key), subkeys, values for subkey in subkeys: for result in walk (top + "\\" + subkey): yield result except WindowsError: # print 'Could not open key', root + "\\" + subkey + "\n" pass basickeys = [] i = 0 while True: try: basickeys.append (_winreg.EnumKey (startHandle, i)) i += 1 except EnvironmentError: print i, 'subkeys found!' break for x in range(len(basickeys)): for key, subkey_names, values in walk (start + basickeys[x]): # print key for (name, data, type) in values: # print " ", name, "=>", data if type == _winreg.REG_SZ and old in data: _winreg.SetValueEx (key.key, name, 0, type, data.replace (old, new)) Not the most effecient code, I'm sure, but it does what I want it to do :D Thank you once more, Tim. Also, thank you, Mike, for your advice on saving the registry. I would have forgotten to note backing up the registry in the beginning if it wasn't for you bringing that up. :D From stefan_ml at behnel.de Sun May 25 13:46:47 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 25 May 2008 19:46:47 +0200 Subject: which datastructure for fast sorted insert? In-Reply-To: References: Message-ID: <4839A607.7070300@behnel.de> notnorwegian at yahoo.se wrote: > im writing a webcrawler. > after visiting a new site i want to store it in alphabetical order. > > so obv i want fast insert. i want to delete duplicates too. > > which datastructure is best for this? Keep the data redundantly in two data structures. Use collections.deque() to append and remove as in a queue, and set() to find duplicates. Again, no ordering, but very fast insert/delete/dup-check. Stefan From Sam.Dutton at itn.co.uk Fri May 23 02:04:09 2008 From: Sam.Dutton at itn.co.uk (Dutton, Sam) Date: Fri, 23 May 2008 07:04:09 +0100 Subject: Why is math.pi slightly wrong? References: <6b7a57e3-0f0e-4b52-a2e8-246491dd0e7f@x35g2000hsb.googlegroups.com> <483659b1$0$11621$607ed4bc@cv.net> Message-ID: Thanks for all the answers and comments. >math.pi is exactly equal to 884279719003555/281474976710656, which is the closest C double to the actual value of pi So much for poor old 22/7... Sam SAM DUTTON SENIOR SITE DEVELOPER 200 GRAY'S INN ROAD LONDON WC1X 8XZ UNITED KINGDOM T +44 (0)20 7430 4496 F E Sam.Dutton at itn.co.uk WWW.ITN.CO.UK P Please consider the environment. Do you really need to print this email? Please Note: Any views or opinions are solely those of the author and do not necessarily represent those of Independent Television News Limited unless specifically stated. This email and any files attached are confidential and intended solely for the use of the individual or entity to which they are addressed. If you have received this email in error, please notify postmaster at itn.co.uk Please note that to ensure regulatory compliance and for the protection of our clients and business, we may monitor and read messages sent to and from our systems. Thank You. From yves at zioup.com Wed May 7 19:29:27 2008 From: yves at zioup.com (Yves Dorfsman) Date: Wed, 07 May 2008 23:29:27 GMT Subject: slicing lists Message-ID: Is there a way to do: x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] x[0,2:6] That would return: [0, 3, 4, 5, 6] I am surprised this notation is not supported, it seems intuitive. A concrete example of the sort of thing I want to do: p = file('/etc/passwd').readlines() q = [ e.strip().split(':')[0,2:] for e in p ] (getting rid of the password / x field) Thanks. Yves. http://www.SollerS.ca From itskrithika at gmail.com Fri May 2 13:26:08 2008 From: itskrithika at gmail.com (terry) Date: Fri, 2 May 2008 10:26:08 -0700 (PDT) Subject: Pyserial - send and receive characters through linux serial port References: Message-ID: <6bb77eb0-9707-4a72-a385-881cb0365b41@r9g2000prd.googlegroups.com> On Apr 26, 8:21?am, Grant Edwards wrote: > On 2008-04-25, terry wrote: > > > I am trying to send a character to '/dev/ttyS0' and expect the > > same character and upon receipt I want to send another > > character. I tired withPyserialbut in vain. > > Pyserialworks. ?I've been using it almost daily for many > years. ?Either your program is broken, your serial port is > broken, or the device connected to the serial port is broken. > > > Test Set up: > > > 1. Send '%' to serial port and make sure it reached the serial port. > > 2. Once confirmed, send another character. > > > I tried with write and read methods inPyserialbut no luck. > > > Can you help? > > Ah yes, the problem is in line 89 of your program. > > We've no way to help if you don't provide details. If you > really want help, write as small a program as possible that > exhibits the problem. ?I'd like to emphasize _small_. The > larger the program the less likely people are to look at it, > and the less likely they are to find the problem if they do > look at it. > > Much of the time the exercise of writing a small demo program > will lead you to the answer. ?If not, then post it, along with > the output from the program that shows the problem. > > Then we can tell you what you did wrong. > > -- > Grant Edwards ? ? ? ? ? ? ? ? ? grante ? ? ? ? ? ? Yow! I'm also against > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? at ? ? ? ? ? ? ? BODY-SURFING!! > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?visi.com ? ? ? ? ? ? Here is the code. """Open serial connection""" def openSerialConnection(self,serpt): try: s1 = serial.Serial(serpt,timeout=10) except: self.print_u("Failed to open serial port %s. " %serpt) def enterThroughSerialPort(self,serpt): s1 = serial.Serial(serpt,timeout=10) self.print_u('Sending !!!!..') while True: s1.write('*') c = s1.read(1) if c: self.print_u('Found "*" ') break print c s1.write('enter\r') s1.read('login') if __name__ == '__main__': serpt = '/dev/ttyS0' x.openSerialConnection(serpt) # funtion to reboot the device goes here ---# x.enterThroughSerialPort(serpt) After opening the serial connection, the device is rebooted followed by sending '*' to serial port and reading back the same. I seem to have problem while trying to read '*' back from serial port. First of all I am not sure if serial port received the '*'. Thanks! From arnodel at googlemail.com Sun May 4 07:56:48 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 04 May 2008 12:56:48 +0100 Subject: word shifts References: <7b142d7f-a9f6-4739-8b6f-1eca581b0517@j22g2000hsf.googlegroups.com> Message-ID: bearophileHUGS at lycos.com writes: > George Sakkis: >> A faster algorithm is to create a 'key' for each word, defined as the >> tuple of ord differences (modulo 26) of consecutive characters. > > Very nice solution, it uses the same strategy used to find anagrams, > where keys are > "".join(sorted(word)) > Such general strategy to look for a possible invariant key for the > subsets of the required solutions is quite useful. Or even: def get_key(word): initial = ord(word[0]) return tuple((ord(x) - initial) % 26 for x in word[1:]) -- Arnaud From hdante at gmail.com Thu May 22 13:34:32 2008 From: hdante at gmail.com (Henrique Dante de Almeida) Date: Thu, 22 May 2008 10:34:32 -0700 (PDT) Subject: Bug in floating-point addition: is anyone else seeing this? References: <8fc0d94d-19bd-483a-8a57-8c03e47d2035@m45g2000hsb.googlegroups.com> Message-ID: <664aa0c1-07ab-4603-8eea-1dabc4daba54@59g2000hsb.googlegroups.com> On May 22, 6:09?am, Ross Ridge wrote: > Henrique Dante de Almeida ? wrote: > > > Finally (and the answer is obvious). 387 breaks the standards and > >doesn't use IEEE double precision when requested to do so. > > Actually, the 80387 and the '87 FPU in all other IA-32 processors > do use IEEE 745 double-precision arithmetic when requested to do so. True. :-/ It seems that it uses a flag to control the precision. So, a conformant implementation would require saving/restoring the flag between calls. No wonder why gcc doesn't try to do this. There are two possible options for python, in that case: - Leave it as it is. The python language states that floating point operations are based on the underlying C implementation. Also, the relative error in this case is around 1e-16, which is smaller than the expected error for IEEE doubles (~2e-16), so the result is non- standard, but acceptable (in the general case, I believe the rounding error could be marginally bigger than the expected error in extreme cases, though). - Use long doubles for archictectures that don't support SSE2 and use SSE2 IEEE doubles for architectures that support it. A third option would be for python to set the x87 precision to double and switch it back to extended precision when calling C code (that would be too much work for nothing). From space.captain.face at gmail.com Thu May 29 06:26:27 2008 From: space.captain.face at gmail.com (Kalibr) Date: Thu, 29 May 2008 03:26:27 -0700 (PDT) Subject: Finding file details... References: Message-ID: <2a7d4ada-8c81-4cb5-8f0c-842b9406fbd8@z16g2000prn.googlegroups.com> On May 29, 7:55 pm, Tim Golden wrote: > > You don't say, but I assume you're on Windows since you mention > GetFileVersionInfo (which doesn't have anything to do with media > files, by the way) and WMA. There may be packages out there > to do all this already but if not you'll need to pull in a few disparate > modules and mix'n'match. > > While ID3 readers (which determine the metadata for MP3) are reasonably > common few of them come ready-compiled for Windows. I've used Ned > Batchelder's id3reader [1] successfully for simple tasks so you might try > that. On the WMA side, you can automate Windows Media Player to get > metadata. (And it might work for .mp3; I've not tried). > > > import win32com.client > > player = win32com.client.gencache.EnsureDispatch ("WMPlayer.OCX") > wmedia = player.mediaCollection.add (r"c:\temp\bells.mp3") > try: > artist = wmedia.getItemInfo ("Artist") > finally: > player.mediaCollection.remove (wmedia, False) > > print "bells.mp3 has artist", artist > > > > You're going to have to dig around for docs on this one. And it's not > pretty. Try starting from: > > http://msdn.microsoft.com/en-us/library/bb249009(VS.85).aspx > > TJG > > [1]http://nedbatchelder.com/code/modules/id3reader.html Hmm, thanks for the info. Yes, I am using Winders (Vista to be exact) and I just assumed that there must be a way to programmatically get the stuff you get from choosing properties in the right click menu. But I guess there isn't (hard to believe, because I can't see MS hard- coding each and every file format's metadata into it's OS). I might have to learn more about the command prompt ( I hear there is a module for fiddling with it) and work from there. Cheers for the links though, I will be checking them out :) From http Wed May 7 02:39:57 2008 From: http (Paul Rubin) Date: 06 May 2008 23:39:57 -0700 Subject: License selection for free software References: <3a8e0a8f-3bd1-4650-9104-5c273f14b097@w7g2000hsa.googlegroups.com> <1w4gs9bk.fsf@gmail.com> <87ve1se6q5.fsf_-_@benfinney.id.au> <8763tr5ov1.fsf@gmail.com> Message-ID: <7xbq3iaa82.fsf@ruckus.brouhaha.com> vivainio at gmail.com (Ville M. Vainio) writes: > In practice, the probability of hijacking of source code by an evil > corporation is very low for most projects. And even when it did > happen, the evil corporation would likely submit patches. If they're going to submit patches then they shouldn't have any problem with the GPL. > The more users an open source project has, the better. That is simply not a valid premise, as others have explained. The priorities of any particular project might give weight to the number of users or might emphasize something else altogether. And some projects are just plain bad (think of malware or spamming tools), so it's better for the world in general if they fail and have no users regardless of the developers' wishes. From lars at gustaebel.de Tue May 27 08:47:40 2008 From: lars at gustaebel.de (Lars =?iso-8859-1?Q?Gust=E4bel?=) Date: Tue, 27 May 2008 14:47:40 +0200 Subject: tarfile.open(mode='w:gz'|'w|gz'|..., fileobj=StringIO()) fails. In-Reply-To: <414185e8-26cb-437f-abc5-70cd547450a8@34g2000hsh.googlegroups.com> References: <133193d2-a87f-4000-b70c-29fdbb36f6d0@59g2000hsb.googlegroups.com> <35552ee8-4c87-4694-b783-aa4315f3ce18@m73g2000hsh.googlegroups.com> <414185e8-26cb-437f-abc5-70cd547450a8@34g2000hsh.googlegroups.com> Message-ID: <20080527124740.GA23226@axis.g33x.de> On Tue, May 27, 2008 at 01:51:47AM -0700, sebastian.noack at googlemail.com wrote: > I have written a FileWrapper class as workaround, which works for me > (see the code below). The FileWrapper object holds an internal file- > like object and maps its attributes, but prevents the user (in this > case tarfile) from closing the internal file, so I can still access > StringIO's content after closing the TarFile object. > > But this should not be required to create in memory tar files. It is > definitely a bug, that TarFile closes external file objects passed to > tarfile.open, when closing the TarFile object. The code which opens a > file is also responsible for closing it. You're right, _BZ2Proxy.close() calls the wrapped file object's close() method and that is definitely not the desired behaviour. So, if you can do without 'bz2' modes for now, you're problem is gone, all other modes work fine. I fixed it (r63744), so the next beta release will work as expected. Your test script helped a lot, thanks. Regards, -- Lars Gust?bel lars at gustaebel.de A casual stroll through a lunatic asylum shows that faith does not prove anything. (Friedrich Nietzsche) From yves at zioup.com Mon May 12 23:23:30 2008 From: yves at zioup.com (Yves Dorfsman) Date: Tue, 13 May 2008 03:23:30 GMT Subject: anonymous assignment In-Reply-To: References: <1XNVj.133805$Cj7.33096@pd7urf2no> Message-ID: Scott David Daniels wrote: > Yves Dorfsman wrote: >> ... Sorry this was a typo (again :-), I meant: >> d = time.local() >> y = d[0] >> d = d[2] > Then: > y, d = list(time.localtime())[:4:2] > What is this ? Could you point me to a document on this syntax ? I've tried it, it works, but I don't understand how. Thanks. Yves. From tarun.kap at gmail.com Fri May 2 15:04:04 2008 From: tarun.kap at gmail.com (TkNeo) Date: Fri, 2 May 2008 12:04:04 -0700 (PDT) Subject: list.index crashes when the element is not found References: <491f6$481b6455$547@news.teranews.com> Message-ID: <18cd9b76-91e7-4830-af75-cc9c97536347@d45g2000hsc.googlegroups.com> On May 2, 1:58 pm, Nick J Chackowsky wrote: > TkNeo wrote: > > WHAT ? > > > This is crazy > > Crazy like a fox? > > a = [1, 2, 3] > try: > a.index(99) > except: > a.append(99) > finally: > print a.index(99) > > MY question: which exception should I actually be catching there? > ** Posted fromhttp://www.teranews.com** ofcouse try catch is going to work but in ideality the index function should return a -1 and no way in hell crash. From bruno.desthuilliers at gmail.com Thu May 15 17:28:05 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Thu, 15 May 2008 14:28:05 -0700 (PDT) Subject: send yield References: <6a19b5bf-ed71-499c-a348-6e26e2f523eb@m45g2000hsb.googlegroups.com> <60bc3c8e-b084-47ce-a8d7-16359f17bcbc@a70g2000hsh.googlegroups.com> Message-ID: <7d37c335-1bac-4318-a3b0-bb0fd67a7a10@8g2000hse.googlegroups.com> On 15 mai, 16:40, castironpi wrote: > On May 15, 9:26 am, "Dan Upton" wrote: > > > On Thu, May 15, 2008 at 9:32 AM, castironpi wrote: > > > Why can't I write this? > > > -- > > > Because your antecedent is undefined? > > Of the two ways to play, just to say #define this per se would be a > bad move, but that's one that comes from the wrong group. #define is > a big scary macro, that python hasn't been using; it's the one-line > typo. Instance: > > #define life1 Tron( drive.SIZE[ 0 ]/ 2, drive.SIZE[ 1 ]/ 2 ) > > Use it to render planes in solids. > > Back about 'this', I honestly hadn't remembered 'til this time, when I > got a chance to reread the subject. Plus I keep ditching my radio. > Jesus H. Christ. This really sounds like my mother in law. Scary, definitively. From wuwei23 at gmail.com Wed May 21 06:15:54 2008 From: wuwei23 at gmail.com (alex23) Date: Wed, 21 May 2008 03:15:54 -0700 (PDT) Subject: Publish a program References: <4833f0ff_2@news.tm.net.my> Message-ID: On May 21, 7:52 pm, TheSaint wrote: > Hello, > > I'm not a master of python :) If I would publish my program for reviewing, > where should I upload it? For simple "look at my code" I like http://paste.turbogears.org/ Sample: http://paste.turbogears.org/paste/2697 There's also http://python.pastebin.com, which lets you create a new paste by modifying an existing one, and keeps them linked for easy diff'ing. Sample: http://python.pastebin.com/d3964b241 From notontheweb at noisp.com Thu May 8 16:29:42 2008 From: notontheweb at noisp.com (Jive Dadson) Date: Thu, 08 May 2008 20:29:42 GMT Subject: web client in Python Q In-Reply-To: References: Message-ID: Jerry Hill wrote: > On Wed, May 7, 2008 at 11:22 PM, Jive Dadson wrote: >> I wonder why it does not work with >> >> http://stockcharts.com/webcgi/wb.exe?Data.web+SLW > > It looks like that is a subscription site. That makes things more > complicated, because it means you'll need to figure out how to log in, > then probably store cookies related to your session and offer them > back up to the web server on subsequent requests. Python has modules > that help with these things (mostly in the urllib2 module if i recall > correctly), but it's not quite as straightforward as just fetching a > URL. > > I don't have time to dig up an example at the moment, but if you're > still having trouble with it, I can try to pull something together > this weekend. > Thanks for the help, Jerry. I do subscribe to that service, but tapping the data via Python may be more trouble than it's worth. I can get all the info for stocks and ETF's from finance.google. All I am missing is indexes. I can probably live without those. But if you want a challenge, have at it. It would be appreciated. Jive From gagsl-py2 at yahoo.com.ar Sun May 4 19:01:02 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 04 May 2008 20:01:02 -0300 Subject: word shifts References: <7b142d7f-a9f6-4739-8b6f-1eca581b0517@j22g2000hsf.googlegroups.com> Message-ID: En Sun, 04 May 2008 03:35:05 -0300, George Sakkis escribi?: > On May 4, 2:04?am, "Gabriel Genellina" wrote: >> En Sun, 04 May 2008 02:17:07 -0300, dave escribi?: >> >> > I made a function that takes a word list (one word per line, text file) >> > and searches for all the words in the list that are 'shifts' of >> > eachother. ?'abc' shifted 1 is 'bcd' >> >> But I'd use a different algorithm. Instead of generating all posible shifts for a given word, I'd substract the newly read word from each previous words (here, "substract two words" means substract the character code for corresponding positions, modulo 26). Shifted words, when substracted, have the same number on all positions. > > A faster algorithm is to create a 'key' for each word, defined as the > tuple of ord differences (modulo 26) of consecutive characters. E.g. > the key of 'acf' is (2,3); 'c' is 2 positions after 'a' and 'f' 3 > positions after 'c'. Shifted words (and only these) have the same key. Much better! I like it. -- Gabriel Genellina From ivlenin at gmail.com Sun May 25 14:27:22 2008 From: ivlenin at gmail.com (I V) Date: Sun, 25 May 2008 18:27:22 GMT Subject: Getting a set of lambda functions References: Message-ID: On Sun, 25 May 2008 13:43:15 +0200, Martin Manns wrote: > I try to get a set of lambda functions that allows me executing each > function code exactly once. Therefore, I would like to modify the set > function to compare the func_code properties (or the lambda functions to > use this property for comparison). With Ivan's approach, you lose access to the actual lambdas, so you need to create a new function and then modify its code object to actually call the code; this seems a little clunky to me. You might instead want to wrap the lambdas in an object that will do the comparison you want: class Code(object): def __init__(self, func): self._func = func def __cmp__(self, other): return cmp(self._func.func_code, other._func.func_code) def __call__(self, *args, **kwargs): return self._func(*args, **kwargs) func_set = set(Code(f) for f in funclist) From clabepa at gmail.com Wed May 14 04:29:38 2008 From: clabepa at gmail.com (clabepa) Date: Wed, 14 May 2008 10:29:38 +0200 Subject: [ANN] PPyGui emulator In-Reply-To: References: Message-ID: <482aa2f2$0$22076$6e1ede2f@read.cnntp.org> Stef Mientki wrote: > I've ran the first real world application through PPyGui-emulator, > so I think it's time to release the first version. > There's lot of room for improvements and a more beautiful layout. > > PPyGui-emulator is build upon wxPython and released under BSD license. > > For remarks, screen shots and downloads, see > http://oase.uci.kun.nl/~mientki/data_www/pylab_works/pp_intro.html Wow! wonderful. I was searching for it for debugging and easy development purposes, screenshots sounds promising. but the api.py link is broken. > have fun, > > Stef Mientki Many thanks Claudio From vivainio at gmail.com Wed May 7 06:46:23 2008 From: vivainio at gmail.com (Ville Vainio) Date: Wed, 7 May 2008 03:46:23 -0700 (PDT) Subject: python vs. grep References: <011f43ea-9bc8-499a-a3fe-dba24b47932e@c58g2000hsc.googlegroups.com> Message-ID: <8dbb25a6-1306-4670-b835-6fbf999413de@k13g2000hse.googlegroups.com> On May 6, 10:42 pm, Anton Slesarev wrote: > flines = (line for line in f if pat.search(line)) What about re.findall() / re.finditer() for the whole file contents? From brechmos at gmail.com Sat May 31 15:12:47 2008 From: brechmos at gmail.com (brechmos) Date: Sat, 31 May 2008 12:12:47 -0700 (PDT) Subject: parse dates Message-ID: <0f58a4f7-ba18-4f83-9291-12bc844a37a0@p25g2000hsf.googlegroups.com> Hi, I have been using PHP the last while and in particular strtotime. What I want to replicate is finding the second or fourth Monday of the next month. In PHP with strtotime it is easy (strtotime("second Monday", strtotime("next month"), but I can't find an easy way to do it in Python. I have seen DateUtil, but it seems to be able to do only the simpler parsing (could be wrong). Any other ideas? From johnjsal at NOSPAMgmail.com Sun May 11 23:46:42 2008 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: 12 May 2008 03:46:42 GMT Subject: Is using range() in for loops really Pythonic? References: <482657ca$0$25026$607ed4bc@cv.net> <41078222-aec0-4e8b-8a1f-945cdf814498@m73g2000hsh.googlegroups.com> <48275446$0$11628$607ed4bc@cv.net> <87mymw8nr0.fsf@benfinney.id.au> Message-ID: <4827bda2$0$11606$607ed4bc@cv.net> Ben Finney wrote: > John Salerno writes: > >> num = 33 >> >> for x in xrange(10): >> print num += 1 > > Which is better done by 'num += 10'. > > Can you come up with an example that isn't trivially replaced with > clearer code? That might make it clearer what your concern is. ::sigh:: No, unfortunately I don't have a strong enough grasp of Python to give a really in-depth example. I understand what you're asking though. Perhaps people don't use this idiom as much as I think they do, so to give a trivial example to support my point isn't helpful. As far as I know, though, I think this is used often enough, so I thought I'd just ask if there are purists out there who don't like this use of the loop and feel it's an abuse of the syntax. From deets at nospam.web.de Wed May 14 11:56:11 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 14 May 2008 17:56:11 +0200 Subject: Class Methods Vs Any Other Callable References: <98b4a67c-9ec7-407c-8c80-06488bd48a68@e39g2000hsf.googlegroups.com> <690ap7F2u0ftdU1@mid.uni-berlin.de> Message-ID: <690ge0F2vj8fiU1@mid.uni-berlin.de> > When I learned about static methods, I learned they're a way to > tightly couple some functionality with a class without tying the > functionality to any of the instances. I see them as nothing more than > a design decision. To me they make some sense. Which you can say exactly about classmethods - because there is *no* instance. > Other than a methods signature (classmethod(cls, l) and a > staticmethod(l)) a class method does anything that a static method > does and gets the CLS reference for FREE? Yes. > Is this why a static method > is considered to be overkill? In other words, either one can be called > from either the class or the instance and both work pretty much the > same *but* only the class method includes the class for reference and > the static method does not? Yes. > The only real difference I see between an instance and either a class > or static method is the whole bound/unbound thing. Otherwise, even an > instance can do what the others do *just* the instance method can only > make those calls through an instance and not the class. Which is a pretty heavy distinction. > Instance methods make the most sense. A static method makes sense too > *but* I can see how a class method not only does what a static method > does but how a class method *also* gets the cls reference for free. I don't understand the last part - but I certainly agree on the "instance methods make the most sense". But *if* you want a hierarchy of "sensefulness", method > classmethod > staticmethod is the ordering to apply I'd say. Again: classmethods get *more* context than staticmethods *without* needing an instance. More is better :) Diez From gnewsg at gmail.com Wed May 28 20:26:38 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Wed, 28 May 2008 17:26:38 -0700 (PDT) Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <5c98049e-e62e-4ab1-afed-b0a3e186bd05@w1g2000prd.googlegroups.com> Message-ID: <0f0801ab-4fcb-4262-a6d6-fc19401efeb1@m3g2000hsc.googlegroups.com> On 28 Mag, 23:13, Dave Parker wrote: > On May 28, 12:09 pm, Luis Zarrabeitia wrote: > > > Following your posts in this thread, I see that > > you 'plan to add soon' every cool feature that every other language seems to > > have. > > I've already added a lot of them. ?For example, loops that don't need > looping variables: > > For 1000 times do ... > > Explicit infinite loops: > > For forever do ... > > I don't those are features that every other language seems to have, > not even Python. > > Plus, by this weekend, built-in compiled fullscreen 3D graphics will > be in, too. > > > With no certainty whatsoever that today's program will work on > > tomorrow's FT. > > Kind of like how this year's program won't work on next year's > Python? ?Except Flaming Thunder is faster. ;) On 28 Mag, 23:13, Dave Parker wrote: > On May 28, 12:09 pm, Luis Zarrabeitia wrote: > > > Following your posts in this thread, I see that > > you 'plan to add soon' every cool feature that every other language seems to > > have. > > I've already added a lot of them. For example, loops that don't need > looping variables: > > For 1000 times do ... > > Explicit infinite loops: > > For forever do ... > > I don't those are features that every other language seems to have, > not even Python. > > Plus, by this weekend, built-in compiled fullscreen 3D graphics will > be in, too. > > > With no certainty whatsoever that today's program will work on > > tomorrow's FT. > > Kind of like how this year's program won't work on next year's > Python? Except Flaming Thunder is faster. ;) This is nonsense. Python 2.x is around since... what is it? Almost 10 years? It lasted that long maintaining retro-compatibility between the various versions. It's very funny that you point your finger at Python's compatibility as a factor of weakness when your FT breaks it *every week*. Before trying to convince whoever that your FT is better than Python you should first decide what to do with your own product by starting to implement all that *basic* features which are common to all modern languages (arrays, OOP, error handling, data structures, Unicode support, etc...). Once you do that, ask yourself if the way you did it was good/ reliable, ask users what they think about it, and apply changes as necessary. At that point you'll be ready to start publicizing FT as an alternative in respect to other languages. Currenlty you're trying to push something which is not even a "pre- alpha" over something else (Python) which has been around since about 20 years and it is known to be one of the cleanest and more elegant languages around. --- Giampaolo http://code.google.com/p/pyftpdlib From pavlovevidence at gmail.com Fri May 16 19:03:15 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 16 May 2008 16:03:15 -0700 (PDT) Subject: SImple python print question References: <47054b9b-fb5e-4601-9e2d-75bfe61e9cb8@w1g2000prd.googlegroups.com> Message-ID: <6330d8bf-f164-4ae6-8bfb-76c742a72ad2@2g2000hsn.googlegroups.com> On May 16, 6:38 pm, amit.ut... at gmail.com wrote: > Hey there, > > I have a simple question about python print statement. Take the > following code snippet for example... > > 1 print "-#- executing: %s" % section, > 2 tests[section] = test.testcase(name=config.get(section,'name')) > 3 tests[section].runTest() > 4 printStatus(tests[section]) > > Now the problem is that line 1 does not get printed until line 4. What > I thought would happen is that line 1 gets executed and the user sees > that the statement that the test case is executing. Then after the > test case executes a "PASS" or "FAIL" appears on the same line as the > "-#- executing: 0053" statement. > > e.g. > -#- executing: 0053 FAIL > > Some tests take a long time to finish thus the screen is blank until > the entire test finishes and the above statement is outputted. Your standard output uses line-buffering, which means that the underlying I/O code stores all the output in memory until it gets a newline, only then does it send the output to the terminal (or console, or whatever). Workarounds to this are as follows: 1. Explicity flush the buffer after any print statements that end with a comma: print "whatever", sys.stdout.flush() 2. Run Python in unbuffered mode, by using the -u switch: python -u yourscript.py Carl Banks From notnorwegian at yahoo.se Thu May 22 20:02:35 2008 From: notnorwegian at yahoo.se (notnorwegian at yahoo.se) Date: Thu, 22 May 2008 17:02:35 -0700 (PDT) Subject: spider, why isnt it finding the url? Message-ID: <08c10a3d-8cb8-433f-9831-cecf8fb7095b@y21g2000hsf.googlegroups.com> this program doesnt produce any output, however i know from testing that the url-regexp matches urls... import urllib import re site = urllib.urlopen("http://www.python.org") email = re.compile(r'[\w\-][\w\-\.]+@[\w\-][\w\-\.]+[a-zA-Z]{1,4}') url = re.compile("^((ht|f)tp(s?)\:\/\/|~/|/)?([\w]+:\w+@)?([a-zA-Z]{1} ([\w\-]+\.)+([\w]{2,5}))(:[\d]{1,5})?((/?\w+/)+|/?)(\w+\.[\w]{3,4})? ((\?\w+=\w+)?(&\w+=\w+)*)?") for row in site: obj = url.search(row) if obj != None: print obj.group() From guibog at gmail.com Sat May 17 23:14:19 2008 From: guibog at gmail.com (Guillaume Bog) Date: Sun, 18 May 2008 11:14:19 +0800 Subject: Shelve or pickle module Message-ID: Hello, I read and re-read "Python in a Nutshell" written by Alex Martelli, who knows what he is talking about. I'm a bit new to python and I'm going to start doing persistence side on a project. Martelli's book seems to tell me that I should use shelve module, but any code I browsed is using pickle instead. Is there any reason to prefer pickle over shelve? Thanks, From banibrata.dutta at gmail.com Sat May 10 00:38:24 2008 From: banibrata.dutta at gmail.com (Banibrata Dutta) Date: Sat, 10 May 2008 10:08:24 +0530 Subject: multiple Python versions, but on Windows (how to handle registry updates) In-Reply-To: References: <3de8e1f70805090358p27796919jb885138406ade6aa@mail.gmail.com> Message-ID: <3de8e1f70805092138y4ca414ck2be6b5246afa664b@mail.gmail.com> Thanks, Gabriel and Terry, for your responses. Another somewhat realted, but very noob'ish question -- given that I already have Python2.5 installed & will install Python2.4, will copying the ../Lib/site-packages/ from 2.5 into 2.4's, work ? i think the answer is "no", but still asking. is it package specific ? does it matter if the packages were egg drops ? On 5/10/08, Terry Reedy wrote: > > "Gabriel Genellina" wrote in message > news:op.uav4dutjx6zn5v at a98gizw.cpe.telecentro.net.ar... > En Fri, 09 May 2008 07:58:33 -0300, Banibrata Dutta > escribi?: > > |> I already have Python25, and need to install Python24. I would prefer > not to > |> remove Python25, but each Python version seems to update the registry, I > |> guess (not sure), overwriting each other's entries. Any way to have both > |> versions ? > > |They can coexist peacefully. The last one you install will be the default > |version to handle .py files automatically. > > Since 2.5 at least, the Windows installer gives the option to make the new > installation the default or not. One might have to choose 'custom' versus > 'auto' (don't remember for Python), but I do the latter always anyway. > > tjr > > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- regards, Banibrata http://www.linkedin.com/in/bdutta http://octapod.wordpress.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From arne at vajhoej.dk Sat May 31 20:30:45 2008 From: arne at vajhoej.dk (=?ISO-8859-1?Q?Arne_Vajh=F8j?=) Date: Sat, 31 May 2008 20:30:45 -0400 Subject: The Importance of Terminology's Quality In-Reply-To: References: <4840ab73$0$90274$14726298@news.sunsite.dk> Message-ID: <4841edb4$0$90265$14726298@news.sunsite.dk> szr wrote: > Arne Vajh?j wrote: >> Stephan Bour wrote: >>> Lew wrote: >>> } John Thingstad wrote: >>> } > Perl is solidly based in the UNIX world on awk, sed, bash and C. >>> } > I don't like the style, but many do. >>> } >>> } Please exclude the Java newsgroups from this discussion. >>> >>> Did it ever occur to you that you don't speak for entire news groups? >> Did it occur to you that there are nothing about Java in the above ? > > Looking at the original post, it doesn't appear to be about any specific > language. That does not make it on topic in the Java group. And the subthread Lew commented on most certainly is not. Arne From nayden at gmail.com Mon May 26 12:13:27 2008 From: nayden at gmail.com (nayden) Date: Mon, 26 May 2008 09:13:27 -0700 (PDT) Subject: Storing objects in relational database References: <03a17198-3eb2-438e-97c9-db18c0c24a80@c65g2000hsa.googlegroups.com> Message-ID: <56acb43d-071e-4416-b8af-6b210d1c8b2f@56g2000hsm.googlegroups.com> Thanks everyone for the helpful suggestions. From roy at panix.com Sun May 25 10:39:06 2008 From: roy at panix.com (Roy Smith) Date: Sun, 25 May 2008 10:39:06 -0400 Subject: unittest: Calling tests in liner number order References: <69t0qlF356llmU1@mid.uni-berlin.de> Message-ID: "Diez B. Roggisch" wrote: > > I agree that tests should not depend on each other, but sometimes it's > > still useful to have the tests run in a certain order for reporting > > purposes. > > Then sort your report. Seriously. A test-outpt shoud be in a way that > delimits individual testresults in a way that makes them easily > extractable. Then if you want them to be ordered for e.g. diff'ing - > sort them. > > Diez Here's an example of why *running* tests in order can make sense. You could have a bunch of tests of increasing complexity. The first bunch of tests all run in a few seconds and test some basic functionality. From experience, you also know that these are the tests that are most likely to fail as you port to a new environment. There's also some tests which take a long time to run. If the basic stuff that's being tested by the earlier tests doesn't work, there's no way these tests could pass, but they still take a long time to fail. It's really handy to have the simple tests RUN first. If you see they fail, you can cancel the rest of the test run and get on with fixing your code faster. It's a good thing to make it easy to do things the right way, and difficult to do things the wrong way. The danger is when you let your pre-conceived notions of right and wrong trick you into making it difficult to do things any way but YOUR way. So far, the strongest argument I've seen against the OP's idea is that it's not portable to Iron Python. That's a legitimate argument. All the rest of the "You're not supposed to do it that way" arguments are just religion. From johnroth1 at gmail.com Wed May 7 17:20:59 2008 From: johnroth1 at gmail.com (John Roth) Date: Wed, 7 May 2008 14:20:59 -0700 (PDT) Subject: Idea for P3K References: <4821d418$0$932$ba4acef3@news.orange.fr> <4821fea4$0$880$ba4acef3@news.orange.fr> Message-ID: <387351b2-cea5-4206-874d-6dfb94fda94b@8g2000hse.googlegroups.com> On May 7, 3:03 pm, "bruno.desthuilli... at gmail.com" wrote: > On 7 mai, 21:41, Gary Herron wrote: > > > M?ta-MCI (MVP) wrote: > > > Hi! > > > >> I don't often feel like using this word > > > > Look at languages like OCAML or F # > > > > @-salutations > > > Well of course, we're all well aware of other languages that allow > > variables to be bound in the middle of an expression. It's just that > > Python was purposely created without that (mis)feature because it's so > > unclear, and easy to abuse. > > This is the same argument that has been used to justify the lack of MI > and operator overloading in Java. > > Not that I would support having assignment as expressions in Python > (wouldn't fit the whole design IMHO), but this is still a somewhat > arbitrary design choice, not necessarily a GoodThing(tm) by itself - > well designed expression-based languages have their strength too. Clearly this leaves C and C++ out [grin]. After all, a significant problem in those languages is confusing = and ==. I wouldn't mind seeing a way of assigning in the middle of an expression because it comes up fairly frequently when one needs to do a test and save the result at the same time. However I absolutely do not want to see the operator be =. However, if it's not =, then it opens another can of worms, that is, what to call it, and where it fits into the precedence structure. <-- might work. John Roth From notnorwegian at yahoo.se Sat May 24 22:34:26 2008 From: notnorwegian at yahoo.se (notnorwegian at yahoo.se) Date: Sat, 24 May 2008 19:34:26 -0700 (PDT) Subject: class-oriented rather than object-oriented? Message-ID: <92e76dc7-60b2-4ecd-89fc-ec6bf654fc47@y21g2000hsf.googlegroups.com> i have some confusion over this. sure a class is basically a classification, like for example an animal or flower. and an object/instance of that class is then for example a cat. an object is an instance of a class. that i know, i also know how to program with classes etc. i am just confused about the term object-oriented. wouldnt class-oriented be more fitting? at least for java since what you do is divide everything into classes. in python i dont or at leats not as much. does object-oriented refer to that everything(strings, ints etc) are all objects? so there is a class string somewhere in the implementation rather than a primitive or somehing? are python functions objects? can a functional language be object-oriented or an objectoriented language be functional? one definition of OO is a language that passes messages between objects. but not necessarily that is has to pass message sbetween classes? From bj_666 at gmx.net Sat May 3 13:34:29 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 3 May 2008 17:34:29 GMT Subject: pygame: rect moveto? References: <7360a3b3-61b8-4cb9-b4d7-177c532bc880@b1g2000hsg.googlegroups.com> Message-ID: <683m15F2rmn3gU1@mid.uni-berlin.de> On Sat, 03 May 2008 09:51:06 -0700, globalrev wrote: > http://www.pygame.org/docs/ref/rect.html#Rect.move > > well i need to put my rect ina specific place and i donw know from > where i will move it so i need a function rect.moveTo(x,y). > > how do i do that? No need for a function or method:: rect.topleft = (x, y) Ciao, Marc 'BlackJack' Rintsch From jgodoy at gmail.com Sun May 4 07:08:09 2008 From: jgodoy at gmail.com (Jorge Godoy) Date: Sun, 04 May 2008 08:08:09 -0300 Subject: about bsddb module References: <22b79613-2346-4eb0-afb3-46542940c2ad@b5g2000pri.googlegroups.com> Message-ID: cocobear wrote: > On 5?3?, ??7?17?, cocobear wrote: >> How to deal with multiple databases in an file. I want to get the >> content of several databases. (...) > Anybody can help me? I believe you can only have one database per file with the Python abstraction... But you can try this (straight from Google for "sleepycat multiple databases" and sleepycat came from the docs for bsddb): http://www.nextgen6.net/docs/db4.1.25/api_java/db_open.html and pay attention to the details here: http://forums.oracle.com/forums/thread.jspa?threadID=581528&tstart=15 From eckhardt at satorlaser.com Wed May 28 06:25:23 2008 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Wed, 28 May 2008 12:25:23 +0200 Subject: UTF-8 and stdin/stdout? References: <6c543325-b5bf-409a-adf7-eeb8b02582c8@b1g2000hsg.googlegroups.com> Message-ID: Chris wrote: > On May 28, 11:08?am, dave_140... at hotmail.com wrote: >> Say I have a file, utf8_input, that contains a single character, ?, >> coded as UTF-8: >> >> $ hexdump -C utf8_input >> 00000000 ?c3 a9 >> 00000002 [...] > weird thing is 'c3 a9' is ?? on my side... and copy/pasting the ? > gives me 'e9' with the first script giving a result of zero and second > script gives me 1 Don't worry, it can be that those are equivalent. The point is that some characters exist more than once and some exist in a composite form (e with accent) and separately (e and combining accent). Looking at http://unicode.org/charts I see that the letter above should have codepoint 0xe9 (combined character) or 0x61 (e) and 0x301 (accent). 0xe9 = 1110 1001 (codepoint) 0xc3 0xa9 = 1100 0011 1010 1001 (UTF-8) Anyhow, further looking at this shows that your editor simply doesn't interpret the two bytes as UTF-8 but as Latin-1 or similar encoding, where they represent the capital A with tilde and the copyrigth sign. Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From skanemupp at yahoo.se Tue May 13 14:18:31 2008 From: skanemupp at yahoo.se (globalrev) Date: Tue, 13 May 2008 11:18:31 -0700 (PDT) Subject: Fill memeory with endless loop? References: <252c17a9-01a6-4abe-9515-2507e0e50a20@l64g2000hse.googlegroups.com> Message-ID: On 13 Maj, 18:59, Filip ?t?dronsk? wrote: > On ?t, kv? 13, 2008 at 06:49:33 +0200, globalrev wrote: > > > if i do something like > > while 1: > > print "x" > > > will the program ever stop because it runs out of memory? > > No, there is no reason to run out of memory. This will simply > make an everlasting x-printer and there is no need to store > anything (except output buffers, terminal scrollback, etc., > but all of this is temporary and of limited size). In case of > adding elements to a list, the memory usage can, of course, > grow unlimitedly. On linux, if the process eats up too much > memory, it gets killed. I do not know about windows, but > they would probably crash with a BSOD or something of that > sort. and when the program get skiled because out of memory all this will be deleted from the memory? so there is no way that you can, by accident, fill your whole harddrive and make it unusable? and RAM-memory always get cleaned out when not used i guess? From gherron at islandtraining.com Tue May 13 17:12:57 2008 From: gherron at islandtraining.com (Gary Herron) Date: Tue, 13 May 2008 14:12:57 -0700 Subject: variable scope question? In-Reply-To: <0b0ffc2e-4a41-4399-b1bf-68b80ea00605@k13g2000hse.googlegroups.com> References: <0b0ffc2e-4a41-4399-b1bf-68b80ea00605@k13g2000hse.googlegroups.com> Message-ID: <482A0459.5000503@islandtraining.com> globalrev wrote: > http://mail.python.org/pipermail/python-list/2003-October/233435.html > > why isnt it printing a in the second(second here, last one in OP) > example before complaining? > > def run(): > a = 1 > def run2(b): > a = b > print a > run2(2) > print a > run() > > def run(): > a = 1 > def run2(b): > print a > a = b > run2(2) > print a > run() > -- > http://mail.python.org/mailman/listinfo/python-list > If you had told us what error you got, I would have answered you hours ago. But without that information I ignored you until is was convenient to run it myself. Now that I see no one has answered, and I have time to run your examples, I see the error produced is Traceback (most recent call last): File "", line 1, in File "", line 6, in run File "", line 4, in run2 UnboundLocalError: local variable 'a' referenced before assignment and its obvious what the problem is. In run2 (of the second example), The assignment to a in the line "a=b" implies that a *must* be a local variable. Python's scoping rules say that if "a" is a local variable anywhere in a function, it is a local variable for *all* uses in that function. Then it's clear that "print a" is trying to access the local variable before the assignment gives it a value. You were expecting that the "print a" pickups it the outer scope "a" and the assignment later creates a local scope "a", but Python explicitly refuses to do that. Gary Herron From kay.schluehr at gmx.net Fri May 16 08:07:32 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Fri, 16 May 2008 05:07:32 -0700 (PDT) Subject: default object comparison considered harmful? References: Message-ID: On 16 Mai, 10:03, "A.T.Hofkamp" wrote: > Hello all, > > Yesterday we found the cause of a bug that has caused problems for a long time. > It appeared to be the following: > > class A(object): > pass > > print min(1.0, A()) > > which is accepted by Python even though the A() object is not numerical in > nature. > > The cause of this behavior seems to be the compare operation of the object > class. > > Is there a way to disable this behavior in Python (other than deriving a new > 'object-like' class that doesn't do comparisons?) > > Sincerely, > Albert Are you sure you don't want to use a statically typed language that captures all type errors just by inspecting your source code? From maxwell.newlands at gmail.com Fri May 16 07:50:40 2008 From: maxwell.newlands at gmail.com (max) Date: Fri, 16 May 2008 04:50:40 -0700 (PDT) Subject: no inputstream? References: <87lk2ba4b4.fsf@mulj.homelinux.net> <8d566db4-c626-491f-82e4-303308c5b8da@25g2000hsx.googlegroups.com> <1210893082.3312.2.camel@jmk> <1210894364.3312.10.camel@jmk> <24ab8bf8-7fac-408c-b8c7-0f027a9f3454@m36g2000hse.googlegroups.com> <325be043-d911-4cce-9c3b-56209033cd68@d45g2000hsc.googlegroups.com> Message-ID: On May 15, 10:31?pm, castironpi wrote: > On May 15, 6:49?pm, castironpi wrote: > > > > > On May 15, 6:42?pm, John Krukoff wrote: > > > > On Thu, 2008-05-15 at 17:32 -0600, John Krukoff wrote: > > > > On Thu, 2008-05-15 at 17:11 -0600, John Krukoff wrote: > > > > > On Thu, 2008-05-15 at 15:35 -0700, max wrote: > > > > > > On May 15, 6:18 pm, MRAB wrote: > > > > > > > On May 15, 9:00 pm, max wrote: > > > > > > > > > you're right, my java implementation does indeed parse for Id3v2 > > > > > > > > (sorry for the confusion). ?i'm using the getrawid3v2() method of this > > > > > > > > bitstream class (http://www.javazoom.net/javalayer/docs/docs0.4/ > > > > > > > > javazoom/jl/decoder/Bitstream.html) to return an inputstream that then > > > > > > > > i buffer and parse. ?apologies if i misrepresented my code! > > > > > > > > > back to python, i wonder if i'm misusing the mutagen id3 module. ?this > > > > > > > > brief tutorial (http://www.sacredchao.net/quodlibet/wiki/Development/ > > > > > > > > Mutagen/Tutorial) leads me to believe that something like this might > > > > > > > > work: > > > > > > > > > from mutagen.mp3 import MP3 > > > > > > > > id3tags = MP3(urllib2.urlopen(URL)) > > > > > > > > > but this gives me the following TypeError: "coercing to Unicode: need > > > > > > > > string or buffer, instance found". ?does this mean i need to convert > > > > > > > > the "file-like object" that is returned by urlopen() into a unicode > > > > > > > > object? ?if so, do i just decode() with 'utf-8', or is this more > > > > > > > > complex? ?as of now, doing so gives me mostly "No such file or > > > > > > > > directory" errors, with a few HTTP 404s. > > > > > > > > [snip] > > > > > > > I think it's expecting the path of the MP3 but you're giving it the > > > > > > > contents. > > > > > > > cool, so how do i give it the path, if not in the form of a URL > > > > > > string? ?maybe this is obvious... > > > > > > -- > > > > > >http://mail.python.org/mailman/listinfo/python-list > > > > > > It doesn't look like you can, with mutagen. So, time to find a different > > > > > library that supports arbitrary file objects instead of only file paths. > > > > > I'd suggest starting here: > > > > >http://pypi.python.org/pypi?%3Aaction=search&term=id3&submit=search > > > > > > Possibly one with actual documentation, since that would also be a step > > > > > up from mutagen. > > > > > After a bit of time looking around, looks like nearly all the python id3 > > > > modules expect to work with filenames, instead of file objects. > > > > > I can't vouch for it, and the documentation still looks sparse, but this > > > > module at least looks capable of accepting a file object: > > > >http://pypi.python.org/pypi/tagpy > > > > > Looks like it'd be a challenge to build if you're on windows, since it > > > > depends on an external library. > > > > > Alternately, you could probably create a subclass of the mutagen stuff > > > > that used an existing file object instead of opening a new one. No idea > > > > what that might break, but seems like it would be worth a try. > > > > > As last ditch option, could write the first few kb of the file out to a > > > > temp file and see if mutagen will load the partial file. > > > > Okay, now I'm officially spending too much time looking through this > > > stuff. > > > > However, looks like the "load" method of the MP3 class is what you'd > > > want to override to change mutagen's file loading behavior. Probably > > > pass the URL as the filename, and take a cut & paste version of the > > > default load method from ID3FileType and change it to use urllib2 to > > > open it instead of a local file open. > > > > Might work. Might not. No warranty express or implied. > > > -- > > > John Krukoff > > > Land Title Guarantee Company- Hide quoted text - > > > > - Show quoted text - > > > I'm supposed to question "time.toomuch.spend". ?NAMERS!- Hide quoted text - > > > - Show quoted text - > > Is there a way 'time.toomuch.spend' can be scanned for in code? ?If > not, let's play! really, really appreciate your help, john. gonna have to ponder my next move here... From aahz at pythoncraft.com Sun May 4 16:19:05 2008 From: aahz at pythoncraft.com (Aahz) Date: 4 May 2008 13:19:05 -0700 Subject: is +=1 thread safe References: <4819DA2D.3030508@ggmail.com> <035b047f-20fb-4bb0-b76a-61405077976a@d1g2000hsg.googlegroups.com> Message-ID: In article , Gary Herron wrote: > >However, the upshot of all of this is that one must maintain extreme >skepticism. Unless you know both your Python code and any extension >modules you call, and you know them at a level necessary to find such >details, you must conclude that any operation, no matter how atomic it >my look, may in fact not be atomic. Absolutely. Note that your statement is insufficiently encompassing: any Python library code might easily use classes that define special methods that cause GIL release. This is why those of us who champion correct use of threads say that the only easy way to create working threaded programs is to pass objects around in Queues and never never never use an object in multiple threads. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Help a hearing-impaired person: http://rule6.info/hearing.html From arnodel at googlemail.com Sun May 18 14:44:56 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 18 May 2008 19:44:56 +0100 Subject: Compress a string References: Message-ID: "Matt Porter" writes: > Hi guys, > > I'm trying to compress a string. > E.g: > "AAAABBBC" -> "ABC" > > The code I have so far feels like it could be made clearer and more > succinct, but a solution is currently escaping me. > > > def compress_str(str): > new_str = "" > for i, c in enumerate(str): > try: > if c != str[i+1]: > new_str += c > except IndexError: > new_str += c > return new_str > > > Cheers > Matt > -- > -- >>> string = 'sssssssssspppppppaaaaaaam' >>> ''.join(x for x, y in zip(string, '\0'+string) if x != y) 'spam' HTH PS: I keep seeing problems on this list whose solution seems to involve 'window' iterating over a sequence. E.g. >>> list(window('eggs', 2)) [('e', 'g'), ('g', 'g'), ('g', 's')] -- Arnaud From caca at mailinator.com Sat May 31 08:09:32 2008 From: caca at mailinator.com (caca at mailinator.com) Date: Sat, 31 May 2008 05:09:32 -0700 (PDT) Subject: How to get all the variables in a python shell References: Message-ID: <645bddab-3ab9-472a-b162-4ef466af5abf@26g2000hsk.googlegroups.com> Have you seen this page? http://matplotlib.sourceforge.net/screenshots.html On watching this, I wouldn't say matplotlib is inferior to matlab plotting. Also, I don't know what they use in sage, but they have 3D plots of surfaces that you can rotate with the mouse. Do as you like, but if you want to "intergrate as many exsiting computation libraries as possible" you may end up doing something too similar to sage. I wouldn't want to go on such a trip alone, so even if sage is not exactly what I would do, I will probably work with them. Their client-server approach should make it easy to work on a cool interface without messing too much with their code. It's true, you'll have to carry with you a lot of symbolic computation tools that may be you don't need as an engineer, but is it that important? The client-server approach has other advantages: if you have a very lightweight computer (like EEE), you can place the server at home and the lightweight computer is enough to have a full scientific environment outdoors. And yes, I'm pretty sure you can call any library from within sage the same way you'd do it from python. Regards Pablo From gnewsg at gmail.com Tue May 13 14:52:03 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Tue, 13 May 2008 11:52:03 -0700 (PDT) Subject: asynchat sends data on async_chat.push and .push_with_producer References: <0c0e20cb-a81b-4f8b-ada8-d4a8d2ac9938@34g2000hsf.googlegroups.com> <8234c478-5d70-46d7-b794-8d18c26fcb10@l28g2000prd.googlegroups.com> Message-ID: <211ce0e0-4196-49ab-af35-17877ca78568@w7g2000hsa.googlegroups.com> On 13 Mag, 18:35, "ludvig.eric... at gmail.com" wrote: > Anyway, I went for a subclassing way of dealing with it, and it works > fine. As Josiah already stated pay attention to the changes that will be applied to asyncore internals in Python 2.6 and 3.0 (in detail you could take a look at how things will be changed by taking a look at the patch provided in bug #1736190). Your subclass could not work on all implementations. --- Giampaolo http://code.google.com/p/pyftpdlib From hniksic at xemacs.org Thu May 8 17:35:04 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Thu, 08 May 2008 23:35:04 +0200 Subject: pickle problem References: <68g456F2t41nqU1@mid.uni-berlin.de> <97b9fbd1-3725-4a7d-9ecb-1d2af6f35665@y21g2000hsf.googlegroups.com> <68h7p7F2su97jU3@mid.uni-berlin.de> Message-ID: <8763tofpiv.fsf@mulj.homelinux.net> Marc 'BlackJack' Rintsch writes: > On Thu, 08 May 2008 08:55:35 -0700, krustymonkey wrote: > >> The thing is, I'm not using slots by choice. I'm using the standard >> lib "socket" class, which apparently uses slots. > > `socket` objects can't be pickled. Not just because of the > `__slot__`\s but because a substantial part of their state lives in > the operating system's space. Of course, if it makes sense to pickle sockets in the application, one is can do so by defining __getstate__ and __setstate__: class Connection(object): def __init__(self, host, port): self.host = host self.port = port self.init_sock() def init_sock(self): self.sock = socket.socket() self.sock.connect((host, port)) ... init communication ... def __getstate__(self): # pickle self as a (host, port) pair return self.host, self.port def __setstate__(self, state): # reinstate self by setting host and port and # recreating the socket self.host, self.port = state self.init_sock() From yves at zioup.com Wed May 7 22:53:31 2008 From: yves at zioup.com (Yves Dorfsman) Date: Thu, 08 May 2008 02:53:31 GMT Subject: class definition In-Reply-To: References: Message-ID: Miles wrote: > In Python 2.2, classes and types were unified. If a class inherits > from object (or any other built-in), it is considered a "new-style" > class; otherwise, it is an old-style (or classic) class. There are > some differences in their behavior; most notably, descriptors > (computer properties) will not work with old-style classes. Old-style > classes will go away in Python 3 (I think), and all classes will have > object as a base. > > An introduction to new-style classes: > http://www.cafepy.com/article/python_types_and_objects/python_types_and_objects.html > A guide to descriptors: > http://users.rcn.com/python/download/Descriptor.htm > The reference manual on the distinction: > http://docs.python.org/ref/node33.html > The technical explanation: > http://www.python.org/download/releases/2.2.3/descrintro/ Thanks Miles, I've started to go though those links, that should keep me busy for a while ! Yves. http://www.SollerS.ca From bronger at physik.rwth-aachen.de Fri May 30 03:39:44 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Fri, 30 May 2008 09:39:44 +0200 Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <94bac166-d13c-44dd-af84-db19e19488b8@w1g2000prd.googlegroups.com> <8cfd3523-8d16-40bc-b904-94a6a36a414d@p25g2000pri.googlegroups.com> <5c98049e-e62e-4ab1-afed-b0a3e186bd05@w1g2000prd.googlegroups.com> <3dd6fa95-e9fe-4922-a46d-020cf9263469@w4g2000prd.googlegroups.com> Message-ID: <87skw0s0jj.fsf@physik.rwth-aachen.de> Hall?chen! Duncan Booth writes: > [...] > > I don't understand your problem: it's just a single thread so > killfile or skip it. Although I agree with you that there is no problem, *this* is not a good justification for this thread. One should stay on topic in *every* thread. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From cocobear.cn at gmail.com Sun May 4 01:06:59 2008 From: cocobear.cn at gmail.com (cocobear) Date: Sat, 3 May 2008 22:06:59 -0700 (PDT) Subject: about bsddb module References: Message-ID: <22b79613-2346-4eb0-afb3-46542940c2ad@b5g2000pri.googlegroups.com> On 5?3?, ??7?17?, cocobear wrote: > How to deal with multiple databases in an file. I want to get the > content of several databases. > > it's the code I wrote: > > [cocobear at cocobear ~]$ python > Python 2.5.1 (r251:54863, Oct 30 2007, 13:54:11) > [GCC 4.1.2 20070925 (Red Hat 4.1.2-33)] on linux2 > Type "help", "copyright", "credits" or "license" for more information.>>> importbsddb > >>> import os > >>> import time > > >>> db_file = 'native.db' > >>> db =bsddb.db.DB() > >>> db.open(db_file,bsddb.db.DB_UNKNOWN,bsddb.db.DB_RDONLY) > >>> dbs = db.keys() > >>> db.open(db_file,dbs[0],bsddb.db.DB_UNKNOWN,bsddb.db.DB_RDONLY) > >>> db.keys() > > ['\x01\x00\x00\x00', '\x02\x00\x00\x00', '\x03\x00\x00\x00', > '\x04\x00\x00\x00', '\x05\x00\x00\x00'] > > >>> db.open(db_file,dbs[1],bsddb.db.DB_UNKNOWN,bsddb.db.DB_RDONLY) > > the program stop here. Anybody can help me? From wuwei23 at gmail.com Tue May 13 22:54:14 2008 From: wuwei23 at gmail.com (alex23) Date: Tue, 13 May 2008 19:54:14 -0700 (PDT) Subject: 2004 example, passing function error References: <3a70d3c9-41b9-4dfa-9127-ed6d1a8abda5@s50g2000hsb.googlegroups.com> Message-ID: <44816313-c296-4730-8f7c-15f0c24604a0@z16g2000prn.googlegroups.com> On May 14, 11:40 am, globalrev wrote: > so just a mistake on his part? but it looks like he just copied his > shell...has there been a change since 2004 inr egards to how you can > pass functions as arguments to functions?? Adding the value argument (x) to the compose function really limits its usefulness as well. Given the author was talking about functions as first class objects, it makes more sense for compose to return a function, rather than to perform several function calls and return a value. Here, compose creates a new function that performs first 'f' then 'g' on a value: >>> def compose(f, g): ... def _compose(x): ... return f(g(x)) ... return _compose ... >>> compose(sqr, cube) >>> compose(sqr, cube)(2) 64 The advantage being you can easily create function chains this way: >>> sqrcube = compose(sqr, cube) >>> sqrcube(2) 64 And because they're functions, you can use them with compose to construct more complex functions: >>> cubesqrcube = compose(cube, sqrcube) >>> cubesqrcube(2) 262144 Just to show they're functionally the same: >>> cubesqrcube(2) == cube(sqrcube(2)) == cube(sqr(cube(2))) True I like this approach because it separates the function composition from its execution. But you can also achieve much the same by using functools.partial (in 2.5+): >>> def compose(f, g, x): return f(g(x)) ... >>> compose(sqr, cube, 2) 64 >>> from functools import partial >>> sqrcube = partial(compose, sqr, cube) >>> sqrcube(2) 64 >>> cubesqrcube = partial(compose, cube, sqrcube) >>> cubesqrcube(2) 262144 Hope this helps. - alex23 From ohad911 at gmail.com Wed May 21 07:51:56 2008 From: ohad911 at gmail.com (ohad frand) Date: Wed, 21 May 2008 14:51:56 +0300 Subject: problem with import / namespace Message-ID: Hi I have a problem that the solution to it must be very simple but i couldnt fint it's answer in the internet so far (i searched for couple of days) the problme is as follows: i have two directories e.g. "\\1" and "\\2" in each directory i have two files with the same names e.g. "tmp1.py" and "tmp2.py" each tmp2.py file imports tmp1 from its same directory (import tmp1) - thats the problem if i execute one file (\\1\tmp2.py) than the execution is ok but when i try after that to execute the second file (\\2\tmp2.py) than the tmp1 file from the wrong directory ( - directory 1 in this case) is imported instead. i tried many things to try to solve it, i removed the previous path from sys.path and added the new one, i tried to change current working directory with os.chdir() I tried to delete from locals and from globals the name tmp1 before running the second file but nothing worked. please help Thanks, Ohad -------------- next part -------------- An HTML attachment was scrubbed... URL: From aztnat at 163.com Tue May 13 10:09:51 2008 From: aztnat at 163.com (aztnat at 163.com) Date: Tue, 13 May 2008 07:09:51 -0700 (PDT) Subject: Threader Earrings -- A Fashion Jewelry Success Story Message-ID: <3933d207-7ef3-4a68-887e-7486e6b8f5f7@c19g2000prf.googlegroups.com> New jewelry fashions need several factors going for them if they are to succeed. These include aesthetics, price, timing, and maybe even just sheer, plain luck. Threader earrings seem to have all these qualities in abundance. Also known as earthreads or ear strings, threader earrings have a very large following, especially among the young set, who think that they are and cool. Threader earrings are exactly what they sound like: a length of a thin chain that the wearer threads through one or more ear piercings. The chain is attached to a small metal bar ? called a lead -- on one end, and the other end is adorned with decorative materials such as gems, beads, or crystals. The wearer first inserts the lead, slides the chain through the piercing and then just lets the earring dangle. Threader earrings are especially attractive in individuals with two or more earlobe piercings because they can mix and match designs, and even knot or weave the chains of the threader earrings together to create a funky effect. The chains used are very thin, delicate and light. They usually measure from three to five inches and are often made from metals such as gold vermeil and sterling silver. Influenced by the decorative ornaments used, the themes of threader earrings? designs range from the playful to the sophisticated. Pearl embellishments impart a sense of elegance, while multicolored vintage crystals or flashy glass beads make threader earrings perfect for casual wear. Young celebrities, or those counting themselves as members of the X and http://users6.nofeehost.com/jecky/html/Bothsexes/20061002/47598.html From wizzardx at gmail.com Sun May 25 16:54:05 2008 From: wizzardx at gmail.com (David) Date: Sun, 25 May 2008 22:54:05 +0200 Subject: Code correctness, and testing strategies In-Reply-To: References: Message-ID: <18c1e6480805251354h3f306866jef4229a1b3b060d@mail.gmail.com> > > You must have poor project management/tracking. You WILL pay the cost > of testing, the only question is when. The when does have an impact on > other aspects of the development process. > > Speaking as someone who started in my current job four years ago as the > third developer in a five-person company, I believe that your claim about > the differences between small companies and large companies is specious. > -- Might be a difference in project size/complexity then, rather than company size. Most of my works projects are fairly small (a few thousand lines each), very modular, and each is usually written and maintained by one developer. A lot of the programs will be installed together on a single server, but their boundaries are very clearly defined. Personally I've had to do very little bug fixing and maintenance. Thorough testing of all my changes before they go into production means that I've caught 99% of the problems, and there is very little to fix later. That's why I'm surprised to hear that such a huge amount of time is spent on testing maintenance, and why the other posters make such a big deal about unit tests. I'm not a genius programmer, so it must be that I'm lucky to work on smaller projects most of the time. David. From petr.poupa at gmail.com Tue May 13 13:41:43 2008 From: petr.poupa at gmail.com (petr.poupa at gmail.com) Date: Tue, 13 May 2008 10:41:43 -0700 (PDT) Subject: Socket and cycle problem References: Message-ID: <1ac03741-176a-4e70-a220-b854098fdec4@t54g2000hsg.googlegroups.com> On 12 Kv?, 21:06, Jean-Paul Calderone wrote: > On Mon, 12 May 2008 11:16:08 -0700 (PDT), petr.po... at gmail.com wrote: > > [snip] > > >My script send me via 3883 port (VRPN) data, but only once. I need > >listening this port countinously. > >So I need make some loop to print data from 3883 port permanent. > >Data that I recevied looks liek this: > > >receive data from server: 'vrpn: ver. 07.13 0\x00\xe8\x0b\x00\x00' > > I'm not sure if you need to write a server or a client. In your > original code, you had a client which repeatedly established out- > bound connections. Here, you say you need to listen on a port. > > > > >Do you think its necessary to use Twisted? Do you have any ideas how > >to do it with socket modul? > > The basic version is pretty easy either way. However, with Twisted, > you get cross-platform error handling without any extra effort, and > you don't have to think about the boring low-level details of BSD > sockets. > > Here's a Twisted server that listens on port 3883 forever and prints > the data it receives from each connection after the remote side drops > the connection: > > from twisted.internet import reactor > from twisted.internet.protocol import ServerFactory, Protocol > > class PrintingProtocol(Protocol): > def connectionMade(self): > """ > When the connection is first established, create a list > into which to buffer all received data. > """ > self.received = [] > > def dataReceived(self, data): > """ > Whenever any data is received on this connection, add it > to the buffer. > """ > self.received.append(data) > > def connectionLost(self, reason): > """ > When the connection is lost, print out the contents of > the receive buffer. > """ > print repr("".join(self.received)) > > # Create a factory which will use our protocol to handle incoming > # connections. > factory = ServerFactory() > factory.protocol = PrintingProtocol > > # Listen with it on port 3883 > reactor.listenTCP(3883, factory) > > # Start the reactor. Nothing in this program will ever stop the > # reactor, so it will run and accept connections forever. > reactor.run() > > If you were to use the socket module, then it would look something like this: > > from socket import socket > from errno import EINTR > > port = socket() > port.bind(('', 3883)) > port.listen(5) > while True: > try: > server, clientAddr = port.accept() > except socket.error, e: > print "Error accepting client connection", e > else: > received = [] > while True: > try: > bytes = server.recv(1024 * 16) > except socket.error, e: > if e.errno == EINTR: > continue > else: > break > if not bytes: > break > received.append(bytes) > print repr("".join(received)) > > Hope this helps, > > Jean-Paul Thanks for code. I am trying both of them, but I am crash to another problem. For socket modul example python report: Traceback (most recent call last): File "C:\Documents and Settings\poupa\Plocha\listen2.py", line 5, in port.bind(('', 3883)) File "", line 1, in bind error: (10048, 'Address already in use') and for twisted example pythod report: Traceback (most recent call last): File "C:\Documents and Settings\poupa\Plocha\listen2twisted.py", line 8, in -toplevel- class PrintingProtocol(Protocol): File "C:\Documents and Settings\poupa\Plocha\listen2twisted.py", line 28, in PrintingProtocol print repr("".join(self.received)) NameError: name 'self' is not defined How can I solve this errors? (for twisted I instal zope for python, pywin32 and twisted. all for python 2.4) From deets at nospam.web.de Wed May 28 11:15:07 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 28 May 2008 17:15:07 +0200 Subject: pydb remote debugging/cmd.Cmd over socket? Message-ID: <6a5b8qF35n4hiU1@mid.uni-berlin.de> Hi, I'm fiddling around with pydb. Installation and usage are fine. What I especially like is the fact that you can attach a signal such that you drop into debugging mode on demand. But this is of limited use to me in situations where a server is written in python. According to the source, pydb's debugger class Gdb extends cmd.Cmd. It passes stdin/stdout-arguments that should be usable to replace the standard streams. But so far all my experiments simply dropped the process into debugging mode putting out and getting io over stdin/stdout - not my self-supplied streams. So I wonder (being a bit rusty on my UNIX-piping-skillz): how does one do that - essentially, create a remote python shell using cmd.Cmd? Diez From dave.g1234 at gmail.com Tue May 20 16:39:20 2008 From: dave.g1234 at gmail.com (dave) Date: Tue, 20 May 2008 13:39:20 -0700 (PDT) Subject: namespaces and eval References: <31750f1d-910b-4fcc-90c0-0df9634f2c73@l28g2000prd.googlegroups.com> <7268f446-17b8-41bb-9d8e-e828f1e74053@c19g2000prf.googlegroups.com> Message-ID: <51ebd8fa-3719-46ae-99b2-1a46ff847a8c@w5g2000prd.googlegroups.com> On May 17, 12:20 am, Arnaud Delobelle wrote: > dave.g1... at gmail.com writes: > > On May 16, 2:47 pm, "bruno.desthuilli... at gmail.com" > > wrote: > >> On 16 mai, 23:23, dave.g1... at gmail.com wrote: > > >> > Thanks for the responses. I'm well aware that the function can be > >> > passed in the parameters, passing in the functino as an arg defeats > >> > the purpose of what I'm going after. > > >> Why so ? > >> > @ Arnaud - Nice. I'm not sure what the performance of mine vs. yours, > >> > but a perfunctory glance looks like we're doing the close to the same > >> > thing. Maybe one advanage to doing it wrap(x).foo().... is that you > >> > can pass in other parameters to foo. > > >> I may be wrong (if so please pardon my lack of intelligence and/or > >> provide a couple use case), but it looks like you're trying to > >> reinvent partial application. > > >> from functools import partial > >> def foo(x, y): > >> return x + y > > >> pfoo = partial(foo, 2) > >> print pfoo(42) > > >> Don't know if this helps... > > > Ok, so that solves the issue of the aforementioned compose function. > > We could do compose( partialfoo,....) ) etc (although I might say I > > prefer wrap(x).foo(23).foo(16 ..etc ) The original idea was to > > provide wrapper around an object that lets you call abritrary > > functions on that object with it as a parameter - i.e., as if it were > > a method in a class. The partial function was only a component of the > > code I posted earlier. Or am I missing something you're saying? > > Ok so you want to do > > wrap(x).foo(42).bar('spam')... > > What is the advantage over > > foo(x, 42) > bar(x, 'spam') > ... > > ? > > -- > Arnaud *shrug*, just syntactic preference I guess. In jquery, for example, you are working over sets of DOM elements and it's convenient to chain those statements into a single line of x.foo().bar().biz() etc. IMO it's a little cleaner to do that as an 'atomic' line, but it's not really that different. Ideally the classes you are using would support this without 'wrap' but I was just tinkering with a hack to do it that way. Thanks for the help dave From upton at virginia.edu Mon May 26 15:49:33 2008 From: upton at virginia.edu (Dan Upton) Date: Mon, 26 May 2008 15:49:33 -0400 Subject: definition of a highlevel language? In-Reply-To: <45f03028-a86c-4357-9aa2-0148f7cc84dc@d45g2000hsc.googlegroups.com> References: <2759eed3-956d-45c7-8dfb-9557f74133b3@56g2000hsm.googlegroups.com> <26d0b3d2-01cc-49bd-b284-1a849b0b835f@y38g2000hsy.googlegroups.com> <34dcbdc1-5285-41ec-be06-c88c56bb0372@i76g2000hsf.googlegroups.com> <45f03028-a86c-4357-9aa2-0148f7cc84dc@d45g2000hsc.googlegroups.com> Message-ID: <5504f9ac0805261249r7eafa4d0k15e068e8cae9b60f@mail.gmail.com> On Mon, May 26, 2008 at 3:22 PM, wrote: > On May 26, 3:02 pm, notnorweg... at yahoo.se wrote: > >> what is crazy about it? > > To make, say, a Python machine fast, you'd have to optimize the hell > out of the architecture, probably all the way down to the microcode > level. Thus, a hypothetical hardware-based Python machine would look > very little like other, more conventional chips like x86 or ARM, for > instance. In fact, I suspect it'd look a lot like the CPython virtual > machine on an instruction level. I don't know if it would necessarily look like the CPython VM, except for the decode stage (this being said without any knowledge of the CPython implementation, but with more than I ever thought I'd know about processor architecture/microarchitecture)--I guess it depends on if you'd have to treat Python bytecode instructions as CISC and then would want to convert them to micro-ops to execute. I don't know about the LISP machine, but I know that many if not all of the attempted implementations of Java machines really just ran Java bytecode as its native instruction set. (I assume they did some optimizations though to actually use registers rather than treating it as a stack machine, or maybe they just had a register stack.) The point about them looking very little like x86/ARM/etc chips is the important part though--IIRC, part of the failure of Java machines was lousy support for preexisting code, due to the optimizations for Java bytecode, and I expect the same would be true of a Python bytecode-optimized processor. From pavlovevidence at gmail.com Wed May 7 13:09:43 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 7 May 2008 10:09:43 -0700 (PDT) Subject: License selection for free software References: <3a8e0a8f-3bd1-4650-9104-5c273f14b097@w7g2000hsa.googlegroups.com> <1w4gs9bk.fsf@gmail.com> <87ve1se6q5.fsf_-_@benfinney.id.au> <8763tr5ov1.fsf@gmail.com> <7xbq3iaa82.fsf@ruckus.brouhaha.com> <15eb97d1-4318-4648-9120-d7d27d7dc435@b64g2000hsa.googlegroups.com> <7x8wyma6w8.fsf@ruckus.brouhaha.com> Message-ID: <1997187c-0347-4aca-a7eb-c884f37df73c@s50g2000hsb.googlegroups.com> On May 7, 3:51 am, Paul Rubin wrote: > Carl Banks writes: > > Nonsense. They could be more than willing to contribute their > > patches, but aren't willing to accept the GPL's limitation to being > > used only in open source packages. > > Oh, I see what you mean--I'm considering any derived work to be a > patch, which is maybe an overbroad use of that term. If they are > willing to contribute their patches in that sense, the GPL shouldn't > be a problem. If they want to just send back small scraps of > improvement while incorporating the GPL'd program into a closed > program, the GPL is doing its job if it prevents that. I think what I said is applicable to derived works, if the idea is to derive another non-open-source work in turn. I.e., someone might be motived to create a derived work of some code with the expectation of using it in their non-open-source project, but if it's GPLed they can't do that, so they probably wouldn't bother. Carl Banks From bearophileHUGS at lycos.com Tue May 20 09:05:04 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 20 May 2008 06:05:04 -0700 (PDT) Subject: compressing short strings? References: <7xy7658k8o.fsf_-_@ruckus.brouhaha.com> <69fn92F329s6vU2@mid.dfncis.de> Message-ID: <3216e39c-3228-4584-bb1f-916350a23538@i76g2000hsf.googlegroups.com> Helmut Jarausch: > I'd ask in comp.compression where the specialists are listening and who are > very helpful. Asking in comp.compression is a good starting point. My suggestions (sorry if they look a bit unsorted): it depends on what language you want to use, how much you want to compress the strings, if they are ASCII or unicode, how much quickly you want to compress/ decompress them, and how much time you have to write the encoder/ decoder. You can use Python or a C/D extension, if you use C you will need more time to develop it, but you will be quite more free to use any algorithm you want (well, you are free with Python too, but the code may be slower if it performs low level things), so D may be an acceptable compromise. Generally it's better to start with the simplest solution, and go on from there looking for more complex ones if the first one isn't enough. In Python the simplest thing to try is to compress the strings with zip: "George Washington".encode("zip") Probably the result is longer than the original (25 bytes output for this string). With "bz2" the results are probably worse (56 bytes for this string). A possible alternative it to compress many (10-30) strings at a time, using an external table of their starting points (you can put the table at the beginning), or you can separate those strings with a separator char that's never present in the strings; and then you can zip that group. If you have 1 million strings you can divide them into such little groups, but the indexing in the DB becomes complex, and I don't like this solution much. A bit less simple python solution is to keep a fixed corpus of text and compress it with and without the little string you want to add (like you say), but compressing/decompressing everything each time (if the corpus is small enough this isn't that slow), for example: >>> s2 = a 2488 bytes long text >>> len(s2) 2488 >>> z1 = (s2).encode("zip") >>> len(z1) 1321 >>> s = 'George Washington' >>> len((s).encode("zip")) 25 >>> len(s.encode("bz2")) 56 >>> z2 = (s2+s).encode("zip") >>> len(z2) 1332 >>> len(z2) - len(z1) 11 So you need to store only this 11 byte long string to be able to decompress it. A bigger corpus (s2) allows you a bit more compression, but it requires more time for compression/decompression: >>> len(s3) # s3 is a longer English text 10811 >>> z3 = s3.encode("zip") >>> len(z3) 4971 >>> z4 = (s3+s).encode("zip") >>> len(z4) 4980 >>> len(z4) - len(z3) 9 One of the simpler ways to compress short ASCII English texts is to see that the most frequent chars are very few, so you can encode the 15 most common English chars with 1 nibble, and the other ones with 3 nibbles (first nibble is an escape, and the two following are the whole byte), if you use a low level language you can encode this with few lines of code, it's very fast and it may shave off 25-33% of your bytes. It means that your "George Washington" (17 chars long) may become about 12-13 chars long. I have implemented this with Python too, it's easy. Another possible solution is to use a Huffman compression with fixed symbol frequencies. In Python there are ways to write such compressor/ decompressor in just 10-15 lines code. You can use the heapq to speed up the processing. This may lead to more compression, but I presume not much than less than 4-5 bpc. But if you want to compress/ decompress a LOT of strings you may need to write (or look for the code) in C/D. This is one implementation that doesn't use heapq yet: from operator import itemgetter def clean_tree(obj): if isinstance(obj, tuple): return obj[0] else: return [clean_tree(obj[0][0]), clean_tree(obj[0][1])] def huffman_generate(freqsl): while len(freqsl) > 2: freqsl.sort(key=itemgetter(1)) freqsl = [ [freqsl[0:2], freqsl[0][1] + freqsl[1][1]] ] + freqsl[2:] return [freqsl, -1] def tree2dict(tree): def encode(tree, out=""): if isinstance(tree, list): encode(tree[0], out+"0") encode(tree[1], out+"1") else: dic[tree[0]] = out return dic dic = {} return encode(tree) freqs = [('a', 45), ('b', 13), ('c', 12), ('d', 16), ('e', 9), ('f', 5)] print tree2dict(clean_tree(huffman_generate(freqs))) If you want to use a Huffman you can use the usual tricks to increase compression: use 2-char symbols, or even use whole words as symbols (but you can use whole words only if you are sure your language is English with few strange words). If you want more compression, like a 6 bytes (2.8 bpc) output you will need more complex algorithms. On long English texts the best compressors need less than 0.9 bpc, but they are surely useless for you. I don't think you will be able to go down to 6 bytes for that string, unless you are ready to pay lot of computational time :-) Bye, bearophile From inhahe at gmail.com Tue May 20 23:07:03 2008 From: inhahe at gmail.com (inhahe) Date: Tue, 20 May 2008 23:07:03 -0400 Subject: persistent deque References: <29451c2a-cb0a-43a6-b140-6c16e3cb46ac@c65g2000hsa.googlegroups.com> <0uednUCD-McN-a7VnZ2dnUVZ_tzinZ2d@comcast.com> Message-ID: oh yeah! thanks for pointing it out, i should have thought of that, i *just* read about it today, or was it yesterday. so what's the problem with pickle? i have a feeling, maybe i read it, that when you pickle a derived class it pickles it as a member of the base class, is that it? i don't know how i would get around the problem, though, because i'd have to know how to access the deque object that my class stores when i do deque.__init__ in my constructor, so that i could pickle it and my class variables separately. "Larry Bates" wrote in message news:0uednUCD-McN-a7VnZ2dnUVZ_tzinZ2d at comcast.com... > inhahe wrote: >> def __init__(self, filename, initial): >> >> should be >> >> def __init__(self, filename, initial=[]): >> >> (that was the whole reason i put the filename first.) >> >> sorry. >> >> >> > Defaulting initial to empty list this way is asking for trouble. You > should > default it to None and check for None and reset to empty list. > > -Larry From nagle at animats.com Sun May 25 03:41:02 2008 From: nagle at animats.com (John Nagle) Date: Sun, 25 May 2008 00:41:02 -0700 Subject: webspider getting stuck In-Reply-To: References: Message-ID: <483914b3$0$34506$742ec2ed@news.sonic.net> notnorwegian at yahoo.se wrote: > i am writing a simple webspider . > > how do i avoid getting stuck at something like this: > Enter username for W3CACL at www.w3.org: > > ? It's a silly feature of urllib. See http://docs.python.org/lib/module-urllib.html where it says: "Note: When performing basic authentication, a FancyURLopener instance calls its prompt_user_passwd() method. The default implementation asks the users for the required information on the controlling terminal. A subclass may override this method to support more appropriate behavior if needed." Yes, the default behavior when faced with a site that wants authentication is to to ask for a user name and password on standard input. This is seldom what you want. So subclass and overrride. John Nagle From exarkun at divmod.com Mon May 5 10:16:51 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 5 May 2008 10:16:51 -0400 Subject: How to convert unicode string to unsigned char * In-Reply-To: <725404980805050705t24557608v9de541d1bcea546d@mail.gmail.com> Message-ID: <20080505141651.6859.554247783.divmod.quotient.59048@ohm> On Mon, 5 May 2008 16:05:08 +0200, Simon Posnjak wrote: >On Mon, May 5, 2008 at 3:48 PM, Jean-Paul Calderone wrote: >> On Mon, 5 May 2008 15:41:08 +0200, Simon Posnjak wrote: >> >> > Hi! >> > >> > I have a C module for which I created a wrapper with swig. The function >> def is: >> > >> > C: >> > >> > int some_thing(unsigned char * the_str); >> > >> > eg: >> > >> > Python: >> > >> > some_module.some_thing (the_str) >> > >> > Now I would like to feed it with a UTF-8 formatted string: >> > >> > test = u'Make \u0633\u0644\u0627\u0645, not war.' >> > >> >> `test? is not a UTF-8 encoded string. It's a unicode string. >> >> To get a UTF-8 encoded string from a unicode string, use the `encode? >> method: >> >> some_module.some_thing(test.encode('utf-8')) > >Yes you are correct. It is unicode string. But still if I use encode I >get the same error: > >TypeError with message: in method 'some_thing', argument 1 of type >'unsigned char *' > >So I am looking for a way to "cast" unicode string to unsigned char *. > You need to provide some more information about `some_module.some_thing?. How is it implemented? What Python type does it expect? If it doesn't take a unicode string and it doesn't take a byte string, I don't know what kind of string it does take. Jean-Paul From qgallet at gmail.com Fri May 23 11:15:02 2008 From: qgallet at gmail.com (Quentin Gallet-Gilles) Date: Fri, 23 May 2008 17:15:02 +0200 Subject: unittest: Calling tests in liner number order In-Reply-To: References: Message-ID: <8b943f2b0805230815l3f9963bav69c7d589a01cd386@mail.gmail.com> I personally don't see any benefit in this approach. By definition, unittests should be independent, so the order argument suggests a deeper issue. What's your use case ? Quentin On Fri, May 23, 2008 at 11:36 AM, Antoon Pardon wrote: > Some time ago I asked whether is would be possible that unittest would > perform the test in order of appearence in the file. > > The answers seemed to be negative. Since I really would like this > behaviour I took the trouble of looking throught the source and > I think I found a minor way to get this behaviour. > > Now my questions are: > > Are other people interrested in this behaviour? > Does the following patch has a chance of being introduced in the > standard python distribution? > > *** /usr/lib/python2.5/unittest.py 2008-04-17 16:26:37.000000000 +0200 > --- unittest.py 2008-05-23 11:19:57.000000000 +0200 > *************** > *** 570,575 **** > --- 570,577 ---- > """ > def isTestMethod(attrname, testCaseClass=testCaseClass, > prefix=self.testMethodPrefix): > return attrname.startswith(prefix) and > callable(getattr(testCaseClass, attrname)) > + def getlinenr(name): > + return getattr(testCaseClass, > name).im_func.func_code.co_firstlineno > testFnNames = filter(isTestMethod, dir(testCaseClass)) > for baseclass in testCaseClass.__bases__: > for testFnName in self.getTestCaseNames(baseclass): > *************** > *** 577,582 **** > --- 579,586 ---- > testFnNames.append(testFnName) > if self.sortTestMethodsUsing: > testFnNames.sort(self.sortTestMethodsUsing) > + else: > + testFnNames.sort(key=getlinenr) > return testFnNames > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From wojtek.gminick.walczak at gmail.com Tue May 6 02:46:07 2008 From: wojtek.gminick.walczak at gmail.com (Wojciech Walczak) Date: Tue, 6 May 2008 08:46:07 +0200 Subject: Decimal vs Float comparasion In-Reply-To: <2c3c21060805052332r6261d8cbt59817603a2d37e00@mail.gmail.com> References: <91320d220805052052r56b61880v2cfb46ff89e605be@mail.gmail.com> <2c3c21060805052332r6261d8cbt59817603a2d37e00@mail.gmail.com> Message-ID: <2c3c21060805052346x23752828x8d587b7bacf3303d@mail.gmail.com> 2008/5/6, Wojciech Walczak : > a > 99999.0 returns True because NotImplemented > 99999.0 returns True. > a < 99999.0 returns False because NotImplemented < 99999.0 returns False. Sorry, it should rather be: Decimal('0.5') > 9.0 returns True because: Decimal('0.5') > NotImplemented returns True and: Decimal('0.5') < 9.0 returns False because: Decimal('0.5') < NotImplemented returns False -- Regards, Wojtek Walczak http://www.stud.umk.pl/~wojtekwa/ From BrianVanderburg2 at aim.com Thu May 1 08:24:01 2008 From: BrianVanderburg2 at aim.com (Brian Vanderburg II) Date: Thu, 01 May 2008 08:24:01 -0400 Subject: Signals/Slots support in Python Message-ID: <4819B661.7080103@aim.com> I don't know if any such support is already built in, so I ended up making my own simple signals/slots like mechanism. If anyone is interested then here it is, along with a simple test. It can connect to normal functions as well as instance methods. It also supports weak connections where when an object is gone, the slot is gone as well, the slot just holds a weak reference to the object. Brian Vanderburg II -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: sigslot.py URL: From waldemar.osuch at gmail.com Wed May 7 04:12:04 2008 From: waldemar.osuch at gmail.com (Waldemar Osuch) Date: Wed, 07 May 2008 08:12:04 GMT Subject: Problem parsing SOAP envelope with ElementTree In-Reply-To: References: Message-ID: Zvi wrote: > Hi All, > > Can someone tell me why id the following not working? snip not working code > > What am I doing wrong? Here is working code. 8<----------------------------- from xml.etree import ElementTree as ET data = """ ]]> """ env = ET.fromstring(data) result = env.find('*//{http://tempuri.org/}Get2Result') response = ET.fromstring(result.text) for elm in response.getiterator(): print elm 8<----------------------------------------- In the future please paste complete examples. It helps me to help you. They were two things that I found to be wrong: - searching using wrong path. You missed *// in front of the tag - parsing only once. There are two xml sources here. The first parse got you the representation of the Envelope. You have to parse the Get2Result payload to get at the interesting part Waldemar From miller.paul.w at gmail.com Tue May 13 23:32:40 2008 From: miller.paul.w at gmail.com (miller.paul.w at gmail.com) Date: Tue, 13 May 2008 20:32:40 -0700 (PDT) Subject: Python isn't English -- and that's a good thing! References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <5b0e3f70-afde-4480-8713-e7113b1250d7@x35g2000hsb.googlegroups.com> <1f537717-00d0-48ee-99b6-7125b96a6133@t12g2000prg.googlegroups.com> <68t4o0F2vaoncU1@mid.uni-berlin.de> <2a32179a-9439-449c-bd07-fff6a4075aee@s50g2000hsb.googlegroups.com> <7ee5dffd-df8f-46f0-bd78-c81ac0418a9a@d77g2000hsb.googlegroups.com> <65ef773e-a1c3-4adb-a18b-e8b8451efe5e@b5g2000pri.googlegroups.com> <68trmmF2vjivnU1@mid.uni-berlin.de> <192840a00805130957t71cbb00ew73f1e10cfb62edcd@mail.gmail.com> <919416e2-590d-48ad-9d75-80a1a4c04732@b1g2000hsg.googlegroups.com> Message-ID: <6552cdf2-5a9e-4081-affa-6e43506ae8d7@34g2000hsh.googlegroups.com> On May 13, 6:14 pm, MRAB wrote: > On May 13, 6:32 pm, "D'Arcy J.M. Cain" wrote: > I once had to do a bit of scripting in AppleScript. The problem I > found was that AppleScript tries to be so much like natural English > that I never got a clear idea of whether something would be valid! You have a great point here. I recently read a blog posting that noted the same thing about Inform 7 (a specialized language used to write interactive fiction games) and its English-like syntax. I've read completed games in Inform 7, and they're very easy to understand, indeed. It does tend to read like English, though somewhat stilted/formal/artificial. Writing it, on the other hand (at least according to to said blog post), is a bit more difficult. Because the syntax is *so* English- like, one tends to want to write things that would be natural in English. However, because the compiler doesn't actually understand natural English, this frequently doesn't work. Python, OTOH, definitely *doesn't* have this sort of impedance mismatch for me. Python code looks like *code*, to be sure, but the language allows you to forget about most of the nitty-gritty details and just get stuff done. That's what I like about it -- *not* that it's "English-like," in any way. From gagsl-py2 at yahoo.com.ar Tue May 20 19:13:49 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 20 May 2008 20:13:49 -0300 Subject: Embedding Python question. References: Message-ID: En Tue, 20 May 2008 06:35:23 -0300, Thomas Troeger escribi?: > I've successfully embedded the Python interpreter into a set of C/C++ > application programs that use a larger library project with information > from http://docs.python.org/api/api.html and > http://docs.python.org/ext/ext.html. Now I want to wrap classes and > functions from the associated libraries so that I can write new > applications completely in Python, but I'm not entirely sure how to > start because I have some problems understanding which is the best way. > It would be nice if someone could answer the following questions and > clarify this matter: > > - until now I've used the approach as documented in > http://docs.python.org/ext/extending-with-embedding.html to extend the > embedded interpreter and that works pretty well. I'd like to use a > similar approach for other C applications. Can I write a C library that > implements this technique and link it into all C applications that need > Python support, or is there a better, more elegant way? (I don't get what you mean by "this technique" and how would you write a library) > - in the documentation, there's an example that illustrates the creation > of a python module for pure extending of a python script (the Noddy > stuff). Do I have to make a separate module for each library I want to > wrap? If yes, how can I manage the case where two libraries can access > each other? Normally, yes, you'd write a wrapping module for each library. If both access each other - well, you'd manage it the same way as you would do it in C; you're just providing an interfase for calling the functions from Python. (Hmm, maybe I have an "imagination crisis" today?) > - if I write an extension module, how can I handle the case where the C > wrapper methods want to call back into the same Python interpreter > instance? I think there is no problem - unless your program is multithreaded, then you should not release the GIL when calling into your extension if there is a chance the C code may call Python code. -- Gabriel Genellina From arnodel at googlemail.com Tue May 6 11:44:06 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 06 May 2008 16:44:06 +0100 Subject: Am I missing something with Python not having interfaces? References: <45de2f7e-484a-4871-bbaa-bf7eed5dfa40@x35g2000hsb.googlegroups.com> <29716374-c3b2-407e-ac54-ae2a17ccf081@2g2000hsn.googlegroups.com> <4dbd4d59-c4e5-4910-bcfd-7e0b2b3bbcef@59g2000hsb.googlegroups.com> Message-ID: cokofreedom at gmail.com writes: [...] > Python is built to be easy to read, And also very easy to *write*. I rarely hear this, but it is the main reason why I like Python so much. I can't really explain why though. [...] (cokofreedom, I found your explanation of the virtues of Python was excellent!) -- Arnaud From Graham.Dumpleton at gmail.com Tue May 13 21:18:34 2008 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Tue, 13 May 2008 18:18:34 -0700 (PDT) Subject: Install Python MySQL db module? References: <3ca0d360-5d71-42e9-a06f-8edf26388ff2@y38g2000hsy.googlegroups.com> Message-ID: On May 14, 10:58?am, Rick Dooling wrote: > On May 13, 7:29 pm, Con wrote: > > > Hi, how does properly install the Python MySQL db module for Mac OS > > X? ?I was only able to locate the Win32 modules. > > > Thanks in advance, > > > -Conrad > > I tried this a couple of weeks ago using macports and had problems. > > See, for example: > > http://www.davidcramer.net/code/57/mysqldb-on-leopard.html > > I read about several people who went in and edited the source files to > work out the bugs on Leopard, but instead I just changed my Python > code to use SQLite for the moment until someone fixes MySQLdb. There's > a nice Perl script that will convert your MySQL db to an SQLite db if > you're interested. > > RD Because Python executable on Leopard has been stripped of 64 bit architectures and thus runs as a 32 bit process, the 64 bit problems only come up when trying to use the MySQLdb module under mod_wsgi or mod_python with Apache (presuming you got mod_python to build as 64 bit). If you are really stuck and can't get MySQLdb module to build as 64 bit capable, then you can force Apache to run as a 32 bit process and avoid the problems. For more details, see section 'Thinning The Apache Executable' of: http://code.google.com/p/modwsgi/wiki/InstallationOnMacOSX Also see contributed comments to the page, which explains a way of making Apache run as 32 bit by changing plist files rather than thinning the Apache executable. Graham From bronger at physik.rwth-aachen.de Thu May 1 13:58:12 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Thu, 01 May 2008 19:58:12 +0200 Subject: Problems with Cheese Shop References: <87zlr9vry8.fsf@physik.rwth-aachen.de> Message-ID: <87ve1xvrd7.fsf@physik.rwth-aachen.de> Hall?chen! Christian Heimes writes: > Torsten Bronger schrieb: > >> How can I authorise to the Python Cheese Shop in order to use >> setup.py upload? Currently, I get >> >> Upload failed (401): You must be identified to edit package >> information > > Try "python setup.py register sdist upload" I forgot to say that the package itself is already there, just not the current release. Is "register" still the way to go? Thank you! Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From mmanns at gmx.net Sun May 18 16:31:55 2008 From: mmanns at gmx.net (Martin Manns) Date: Sun, 18 May 2008 22:31:55 +0200 Subject: distutils directory problem Message-ID: Hi, I have the following problem with the distutils package: (I have now spent hours reading and searching the manuals and tutorials, and I am still stuck.) I have a working directory ~/pyspread in which my libraries are situated and two icons directories ~/pyspread/icons and ~/pyspread/icons/actions Now I would like to create a setup.py file inside my ~/pyspread directory that installs my .py modules in .../site-packages/pyspread and the icons in appropriate sub-folders and adds pyspread.pth to .../site-packages so that .../site-packages/pyspread is in the PYTHONPATH. However, my setup.py puts everything (including .pyc files) into site-packages *and* into the sub-folders. What am I doing wrong? I am looking for a platform-independent solution. Currently, I am using python 2.5 on Linux. Here my setup.py #!/usr/bin/env python from distutils.core import setup setup(name='pyspread', version='0.0.7', description='A spreadsheet that accepts a pure python expression in each cell.', license='GPL v3 :: GNU General Public License', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: End Users/Desktop', ], author='Martin Manns', author_email='mmanns at gmx.net', url='http://sourceforge.net/projects/pyspread/', packages=['pyspread'], package_dir={'pyspread': '.'}, scripts=['pyspread.py'], py_modules=['pyspread.mainapp', 'pyspread.pysgrid', 'pyspread.mygrid','pyspread.icontheme'], package_data={'pyspread': ['icons/*.png', 'icons/actions/*.png' ,\ 'test.pys', 'test.csv', 'test2.csv', \ 'README', 'COPYING']}, ) Thanks in advance Martin From sjmachin at lexicon.net Sat May 24 19:53:39 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 24 May 2008 23:53:39 GMT Subject: Hexadecimal: how to convert 'ED6F3C01' to "\xED\x6F\x3C\x01" in python coding? In-Reply-To: References: Message-ID: <4838aa79$1@news.mel.dft.com.au> Sebastian 'lunar' Wiesner wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > [ zxo102 ] > >> how to change the hexadecimal 'ED6F3C01' (or 'ED 6F 3C 01') to >> "\xED\x6F\x3C\x01" in python coding? >> When I take 'ED6F3C01' as a string and insert '\x' into it, I just got >> the error information : invalid \x escape. > > [1]--> 'ED6F3C01'.decode('hex') > Out[1]: '\xedo<\x01' > FWIW the 'hex' codec is just a big fat Python-coded wrapper around the routines in the C-coded binascii module; here's the evidence: >>> '123'.decode('hex') Traceback (most recent call last): File "", line 1, in File "c:\python25\lib\encodings\hex_codec.py", line 42, in hex_decode output = binascii.a2b_hex(input) TypeError: Odd-length string From alan.wright at volubill.com Mon May 19 18:50:50 2008 From: alan.wright at volubill.com (Alan Wright) Date: Mon, 19 May 2008 23:50:50 +0100 Subject: Newbie: Keep TCP socket open References: Message-ID: Ghirai, Scapy does the same, only it sends RST and not FIN, so still no help send(IP(dst="10.1.1.2")/TCP(dport=50000,flags="S")) Only have windows at the moment sadly. Alan "Ghirai" wrote in message news:mailman.1364.1211234091.12834.python-list at python.org... > On Mon, 19 May 2008 20:25:57 +0100 > "Alan Wright" wrote: > >> Thanks for the feedback. >> >> Using the socket in a list is great >> >> However, as i imagined, I now get a limit of around 1500 conns before >> the system crashes out, also i have noticed, that the ports loop back >> to 1025 when they hit 5000. >> >> Any ideas on how to make the list/socket get to around 50K >> >> TIA >> > > Try to use scapy to send raw empty packets with S flag set. > Also use Linux/BSD if you're trying this on Windows. > > -- > Regards, > Ghirai. From pavlovevidence at gmail.com Sat May 24 07:05:29 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 24 May 2008 04:05:29 -0700 (PDT) Subject: Python is slow References: <2aa4c986-57d8-41dd-9f18-911625965620@z72g2000hsb.googlegroups.com> <5ccb8e61-ad53-48aa-b6ac-a6034907c36c@a32g2000prf.googlegroups.com> Message-ID: <569506e1-b5b2-45f3-9888-5f207284493f@w7g2000hsa.googlegroups.com> On May 24, 1:56 am, cm_gui wrote: > i'm not trying to 'troll' here. Maybe you're not trying, but you're succeeding. If you want to criticize be constructive about it, otherwise get out. Carl Banks From geonomica at gmail.com Tue May 13 18:35:01 2008 From: geonomica at gmail.com (gianluca) Date: Tue, 13 May 2008 15:35:01 -0700 (PDT) Subject: python/swig Message-ID: <186486b1-c3ef-4bbd-9742-bcaed67138b7@k13g2000hse.googlegroups.com> Hy, I need help indeed, about python/swig C wrapper. Exactly, I've built a python library from C library and it seem works. Unfortunatly, a gruop of function that requred pointer to pointer parmeters give me a exception like this: "TypeError: in method 'BestRules', argument 1 of type 'value_type **'" I've tryed to use cpointer.i to obtain a pointer to use in function but this don't work. Could you help me? thanks in advace. Gianluca Massei PS. this is my interface.i file: " %module pyRSL %include "cpointer.i" %{ #include "rough.h" #include "raccess.h" #include "rbasic.h" #include "rclass.h" #include "rcore.h" #include "reduct1.h" #include "reduct2.h" #include "rerror.h" #include "rset.h" #include "rsystem.h" #include "rule1.h" #include "rule2.h" %} %include "rough.h" %include "raccess.h" %include "rbasic.h" %include "rclass.h" %include "rcore.h" %include "reduct1.h" %include "reduct2.h" %include "rerror.h" %include "rset.h" %include "rsystem.h" %include "rule1.h" %include "rule2.h" " From p.wallstedt at gmail.com Mon May 26 17:54:19 2008 From: p.wallstedt at gmail.com (Peter) Date: Mon, 26 May 2008 14:54:19 -0700 (PDT) Subject: pyserial and file open conflict? References: <21c8f220-aa3c-40b8-b1de-3aa35472e2dc@26g2000hsk.googlegroups.com> <88948db2-aade-4f20-a6ba-bc14c2b4c657@d77g2000hsb.googlegroups.com> <8bmdnUdysIKPTKvVnZ2dnUVZ_vqdnZ2d@posted.visi> Message-ID: On 23 Maj, 16:13, Grant Edwards wrote: > On 2008-05-23, Peter wrote: > > > > > On 15 Maj, 19:37, Grant Edwards wrote: > >> On 2008-05-15, p.wallst... at gmail.com wrote: > > >> > I have a small but rather annoying problem withpyserial. I want to > >> > open a file on disk for reading and then open a com-port, write lines > >> > from the file to the port and then read something back and compare it > >> > to the next line in the file. Should be simple. And it is, apart from > >> > the fact that the file seems to be doubled ...? Or it loops through > >> > the file twice. > > >> > If I exclude the "import serial" it works. > > >> > Any ideas? > > >> Your problem is in line 117 of your program. > > > Do you have to much time? > > "Do you have a sense of irony?" he asked, already knowing the answer. > > -- > Grant Grant - "Do you have a sence of appropriateness"? he asked, already knowing the answer. I had no idea this is a comedy club. I might argue that my reply was also some sort of humor, but you clearly didn't see it that way. Maybe you should try living according to the rules you make for others? Diez - Did you mean the section which covers Asperger's Syndrome? I'm just being a hacker here guys ... according to the guidelines. It's amazing how such a simple question gets derailed immediately. Without any light on the subject whatsoever. From benjamin.kaplan at case.edu Thu May 8 12:34:50 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Thu, 8 May 2008 12:34:50 -0400 Subject: Newbie to python --- why should i learn ! In-Reply-To: <9f5ee6c3-86f7-401a-acc8-cd2c9b059fbd@x19g2000prg.googlegroups.com> References: <9f5ee6c3-86f7-401a-acc8-cd2c9b059fbd@x19g2000prg.googlegroups.com> Message-ID: On Thu, May 8, 2008 at 6:25 AM, Raxit at MyKavita.com wrote: > Hi, > > i was reading/learning some hello world program in python. > I think its very simillar to Java/C++/C#. What's different (except > syntax) ? > > what can i do easily with python which is not easy in c++/java !? > Python compared to C++: You don't have to worry about memory management, which means you don't get core dumps and destroy your computer. Python compared to Java: You don't have the strictly enforced type checking and object-oriented programming, which is sometimes not needed. Also, Java was meant to be blind to the platform, so you will have trouble accessing anything outside your program. Python has the os, shutil, and subprocess modules that let you run command line programs and scripts, and you can directly access the win32 API if you are only programming for Windows. Also, Java requires the JVM to run. With python, you can run the program through the regular python interpreter, on the JVM (Jython), natively in Windows (IronPython or freeze it with py2exe), and just about anywhere else you want, so people who use your software won't have to install Python themselves. > > Tnx, > Raxit > www.mykavita.com > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From duncan.booth at invalid.invalid Fri May 9 04:40:15 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 9 May 2008 08:40:15 GMT Subject: "prove" References: Message-ID: "Lucas Prado Melo" wrote: > Hello, > How could I "prove" to someone that python accepts this syntax using > the documentation (I couldn't find it anywhere): > classname.functionname(objectname) Language reference, mostly section 5.3 Primaries call ::= primary "(" [argument_list [","] | expression genexpr_for] ")" primary ::= atom | attributeref | subscription | slicing | call attributeref ::= primary "." identifier atom ::= identifier | literal | enclosure That shows fairly well how the classname.functioname bit works (it is an attributeref which is a primary which forms the first part of a call), but you'll have to wade through a fair bit of the grammar to show that argument_list can be an identifier. argument_list ::= positional_arguments ["," keyword_arguments] ["," "*" expression] ["," "**" expression] | keyword_arguments ["," "*" expression] ["," "**" expression] | "*" expression ["," "**" expression] | "**" expression positional_arguments ::= expression ("," expression)* ... and so on ... From andre.roberge at gmail.com Sat May 31 21:24:35 2008 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Sat, 31 May 2008 18:24:35 -0700 (PDT) Subject: disappearing interpreter References: Message-ID: <8ae1d4e2-3166-49b3-addb-b5b352c09558@2g2000hsn.googlegroups.com> On May 31, 8:59 pm, oregon skip wrote: > I am a new Python programmer, using Windows XP, IDLE and the > interpreter. Everything is > OK except that when I double check a name.py file it runs on the > interpreter, but the > window disappears before I can see what happened. Any suggestions? This is because the entire program runs ... and ends quickly. Try to add the following line: raw_input("Done. Press the enter key to quit.") Andr? From anton.hartl at gmail.com Tue May 20 18:19:26 2008 From: anton.hartl at gmail.com (Anton Hartl) Date: Tue, 20 May 2008 22:19:26 +0000 (UTC) Subject: Processing in Python References: <483345f5$0$902$ba4acef3@news.orange.fr> <69h0p9F327mqgU1@mid.uni-berlin.de> Message-ID: On 2008-05-20, Diez B. Roggisch wrote: > Salvatore DI DI0 schrieb: >> Hello, >> >> The Processing Graphics language has been implemented in Javascript. > > No, it hasn't. Processing is written in Java. Yes, it really has been implemented in Javascript: http://ejohn.org/blog/processingjs/ -Anton From straton at lampsacos.demon.co.uk Sun May 18 11:08:49 2008 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Sun, 18 May 2008 16:08:49 +0100 Subject: Write bits in file In-Reply-To: References: Message-ID: I admit that I was mostly just interested in getting your question clarified, rather than having any great experise. But a bit of Googling took me to the 'Bit vector' module, [I googled: 'python ("bit array" OR "bit vector")'] which might be what you are after. I have no experience with it, myself: http://cobweb.ecn.purdue.edu/~kak/dist/BitVector-1.4.1.html Monica Leko wrote: > On May 18, 2:20 pm, Ken Starks wrote: >> You want your file considered as a sequence of bits rather >> than a sequence of 8-bit bytes, do you? > > Yes. > >> is the 10-bit >> bit-pattern to be stored at an arbitrary bit-position in >> the file > > Yes. I need arbitrary, 8bits, than 10 bits for something else, than > sequence of bytes, than 10 bits again, etc. > > From yves at zioup.com Fri May 9 11:08:51 2008 From: yves at zioup.com (Yves Dorfsman) Date: Fri, 09 May 2008 15:08:51 GMT Subject: python newbie: some surprises In-Reply-To: References: <67b60370-bed9-4f43-b401-25ce2fd89522@t54g2000hsg.googlegroups.com> <64fb7f0f-c8fa-4324-8a13-f4e99082c470@p25g2000hsf.googlegroups.com> Message-ID: <7OZUj.125622$rd2.29080@pd7urf3no> Gabriel Genellina wrote: >> I see the point of the OP. Couldn't the new-line be used as an >> equivalent of ':', for example, do you find this difficult to read: >> >> if a == 3 >> do_something() >> >> >> if a == 3: do_something() > > Yes, it could be done, there are no technical reasons to always force to > use ":". But AFAIK the main reasons to keep ":" are internal consistency > (an inner block always starts with ":"; incidentally, that's easier to > handle for editors) and legibility (the ":" stands for itself and has a > meaning) Legibility ? But one could make the same argument for curly brackets, and we seem to be doing fine without them ! I have become so used to the power of indenting in python that I keep forgetting the colon, and this is getting worse as I do more python, not better. Maybe I'll write myself a "pre-compiler" that add the colons where the compiler needs them :-) Yves. http://www.SollerS.ca From hdante at gmail.com Fri May 16 08:20:19 2008 From: hdante at gmail.com (Henrique Dante de Almeida) Date: Fri, 16 May 2008 05:20:19 -0700 (PDT) Subject: TPCServer and xdrlib References: Message-ID: <5d56b071-1184-4112-bd82-89c00975b939@m73g2000hsh.googlegroups.com> On May 16, 7:16?am, Laszlo Nagy wrote: > ? Hi All, Hello, :-) > > I'm trying to write a multi threaded TPC server. I have used xmlrpc How exactly did you come to the conclusion that your server must be multi threaded ? > - I have to send larger amounts of data, the overhead of converting to > XML and parsing XML back would be too much pain - What's the expected amount of data you have to transfer ? - What's the expected network bandwidth ? - What's the expected acceptable transfer time ? - How many users are expected to be transfering data at the same time ? > I have looked at various solutions including: > > - PyOrbit - too heavy weight > - Pyro - uses pickle, I do not trust it Did you consider gzipping your XML (or YAML) packets ? Would the transfer time be acceptable in this case ? > > BTW I do not care about the clients - they must trust the server side. Oh, he said he _doesn't care about the clients_ ! ;-) > In contrast, the server should not receive anything from the clients > that is dangerous. I would like to use something that is fast, and can > only transfer data, not code. For this reason I think I cannot use the > marshal module because it is able to marshal code objects. I think I'm > going to implement my own "pickler" over xdrlib, that will only > pack/unpack data, NOT code. (It would also have the advantage that > others could write clients in different languages.) In general I would avoid that. Try to better estimate the speed requirements, to see if you really need do to this. > > Before I start re-inventing the wheel: > > - Is there another (already existing) higher level framework that I can > try? It should be safe and fast, that is the only restriction. There's "Twisted". http://twistedmatrix.com/projects/core/documentation/howto/servers.html > - Do you think that it is a good idea to use xdrlib? I haven't seen > projects using it directly. For me it is like the rotor module was - it It's probably the best way to send binary stuff over the network. But, again, I would avoid doing so. > was there but almost nobody used it. There might be a better lower level > library which I don't know of. > > Thank you, > > ? ?Laszlo From Scott.Daniels at Acm.Org Tue May 20 00:12:45 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 19 May 2008 21:12:45 -0700 Subject: test mult vars to same value, how to shorten expr? In-Reply-To: References: Message-ID: notnorwegian at yahoo.se wrote: > if i want o test: > if a == 5 and b ==5 and c==5 ... z==5 > > is there some synctactic suagr for this? > > rather than maiking one of my own i mean, something built-in like: > if a,b,c... z == 5: How about: if 5 == a == b == c == ... z: ... --Scott David Daniels Scott.Daniels at Acm.Org From grante at visi.com Fri May 2 10:40:10 2008 From: grante at visi.com (Grant Edwards) Date: Fri, 02 May 2008 09:40:10 -0500 Subject: #!/usr/bin/env python vs. #!/usr/bin/python References: <87abj91j8u.fsf@benfinney.id.au> Message-ID: On 2008-05-02, Ben Finney wrote: > The specified command takes the form of a fully-qualified file > path, and zero or one arguments to the program. That command > is then executed by the kernel, and the Python program file is > passed as input to the resulting process. Just to clarify that a bit a little, the name of the file (as it was given to the "exec" system call) containing the "shebang line" is passed to the resulting process as a command-line parameter. >> Why is one preferred over the other one ? > > I've never clearly understood why people want to use "#! /usr/bin/env > python", which is prone to finding a different Python from the one > installed by the operating system. I'd be interested to see what > responses are in favour of it, and what the reasoning is. > > One possible reason is that the programmer is attempting to allow for > systems where Python has been installed, but not from an operating > system package. Exactly. the "env" approach works as long as python is installed somewhere on the PATH. "#!/usr/bin/python" will fail if python is installed in /usr/local/bin/python. -- Grant From __peter__ at web.de Tue May 13 05:01:09 2008 From: __peter__ at web.de (Peter Otten) Date: Tue, 13 May 2008 11:01:09 +0200 Subject: Sparse Matrix Multiplications References: Message-ID: Peter Otten wrote: > # use at your own risk > import numpy > > N = 10**4 # I get a MemoryError for a bigger exponent > b = numpy.array(range(N)) > a = numpy.zeros((N, N)) + b > a *= a.transpose() > a[0,0] = (b*b).sum() > print a Sorry, this is nonsense. From mattheww at chiark.greenend.org.uk Mon May 12 16:48:17 2008 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 12 May 2008 21:48:17 +0100 (BST) Subject: Learning Python for no reason References: <0383f3b8$0$27282$c3e8da3@news.astraweb.com> Message-ID: John Salerno wrote: > Just something that crosses my mind every time I delve into "Learning > Python" each night. Does anyone see any value in learning Python when you > don't need to for school, work, or any other reason? I mean, sure, there's > value in learning anything at any time, but for something like a programming > language, I can't help but feel that I will be mostly unable to use what I > learn simply because I have no reason to use it. > The *process* of learning is enough fun for me, and every now and then I do > find a small use for Python that really pays off, but for the most part I'm > wondering what people's thoughts are as far as simply learning it for the > sake of learning. Does it seem like a silly endeavor to most people? Did > anyone here learn a programming language when you didn't need to? If so, how > much and in what capacity did you use it after you learned it? I can't tell from what you wrote whether you feel you won't have any reason to do any programming, or whether you already know several other programming languages and you feel you won't have any reason to use Python in particular. If it's the former, I don't think you need to worry. If you ever find yourself doing a repetitive task using a computer, or find that you're using a program which does nearly-but-not-quite what you want, there are good chances that there'll be a way to write a program to help. -M- From paul at boddie.org.uk Mon May 26 05:14:19 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Mon, 26 May 2008 02:14:19 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <8763t3by81.fsf@benfinney.id.au> <09847cfc-eaec-4adc-8cbf-1e2ebbf940c4@m44g2000hsc.googlegroups.com> Message-ID: So much to respond to here, so let's get it over with in one post... On May 25, 2:32 pm, "Joe P. Cool" wrote: > > On 24 Mai, 15:58, Ben Finney > > wrote: > > > From whom are you trying to hide your attributes? > > > I saw this "don't need it" pattern in discussions about the ternary > > "if..else" expression and about "except/finally on the same block > > level". Now Python has both. Well, there was no need to exclude try...except...finally in the first place - Guido doubted the semantics of such a thing until he saw it in Java, apparently. This is arguably one of the few features that has incurred little cost with its addition, in contrast to many other changes made to Python these days. Which brings us to the ternary expression - something which will presumably see unprecedented usage by those who jump on every new piece of syntax and "wear it out" in short order. Interestingly, Python did have an "access" keyword at some point (before 1.4, I believe), so it isn't as if no-one had thought about this before. [...] > > > Who taught you that enforced restrictions on attribute access was a > > > "basic principle" of OO? > > > Nearly every introduction to OOP? Please don't tell me that > > encapsulation > > does not mean "enforced restriction". If the language has no syntactic > > support for encapsulation then it does not have encapsulation. Similar > > argument applies to Java where programmers sometimes claim that Java > > "has" properties because of setCrap/getCrap. But is "enforced restriction" essential in OOP? Note that languages like C++ provide such features in order to satisfy constraints which are not directly relevant to Python. [...] On May 26, 6:49 am, "Russ P." wrote: > > I've always considered the underscore conventions in Python an ugly > hack in an otherwise elegant language. I often avoid them even when > they technically belong just because I don't like the way they make my > code look. To be honest, I don't really like putting double underscores before names just to make sure that instances of subclasses won't start trashing attributes of a class I've written. (I actually don't care about people accessing attributes directly from outside instances because I've seen enough "if only they hadn't made that private/ protected, I could do my work" situations in languages like Java.) Indeed, I experienced a situation only yesterday where I found that I had been using an instance attribute defined in a superclass (which was arguably designed for subclassing), but was the author really expected to prefix everything with double underscores? Of course, by not enforcing the private nature of attributes, Python does permit things like mix-in classes very easily, however. If anything, Python lacks convenient facilities (besides informal documentation) for describing the instance attributes provided by the code of a class and of superclasses. Of course, the dynamic possibilities in Python makes trivial implementations of such facilities difficult, but having access to such details would make errors like those described above less likely. I imagine that pylint probably helps out in this regard, too. [...] > I am also bothered a bit by the seeming inconsistency of the rules for > the single underscore. When used at file scope, they make the variable > or function invisible outside the module, but when used at class > scope, the "underscored" variables or functions are still fully > visible. For those who claim that the client should be left to decide > what to use, why is the client prohibited from using underscored > variables at file scope? I don't remember why this is. I'll leave you to track down the rationale for this particular behaviour. ;-) > I may be full of beans here, but I would like to make a suggestion. > Why not add a keyword such as "private," and let it be the equivalent > of "protected" in C++? That would make member variables and functions > visible in inherited classes. The encapsulation wouldn't be as > airtight as "private" in C++, so clients could still get access if > they really need it in a pinch, but they would know they are bending > the rules slightly. I realize that single underscores do that already, > but they are just unsightly. If anything, I'd prefer having private attributes than some kind of protected attributes which don't actually offer useful protection (from accidental naming collisions). Paul From inhahe at gmail.com Sun May 18 17:38:17 2008 From: inhahe at gmail.com (inhahe) Date: Sun, 18 May 2008 17:38:17 -0400 Subject: Compress a string Message-ID: I forgot a line that says, "lc = c" i should really test my stuff. "inhahe" wrote in message news:... >i see lots of neat one-liner solutions but just for the sake of argument: > > def compress_str(str): > new_str = "" > lc = "" > for c in str: > if c != lc: new_str.append(c) > return new_str > > > "Matt Porter" wrote in message > news:mailman.1315.1211133997.12834.python-list at python.org... >> Hi guys, >> >> I'm trying to compress a string. >> E.g: >> "AAAABBBC" -> "ABC" >> >> The code I have so far feels like it could be made clearer and more >> succinct, but a solution is currently escaping me. >> >> >> >> >> Cheers >> Matt >> -- >> -- >> > > From hdante at gmail.com Sat May 17 23:25:18 2008 From: hdante at gmail.com (Henrique Dante de Almeida) Date: Sat, 17 May 2008 20:25:18 -0700 (PDT) Subject: Using Python for programming algorithms References: Message-ID: <98fa5fa3-45ae-4df1-9fd3-1a227641244f@p25g2000hsf.googlegroups.com> On May 17, 7:32?pm, Vicent Giner wrote: > Hello. > > I am new to Python. It seems a very interesting language to me. Its > simplicity is very attractive. > > However, it is usually said that Python is not a compiled but > interpreted programming language ?I mean, it is not like C, in that > sense. > > I am working on my PhD Thesis, which is about Operations Research, > heuristic algorithms, etc., and I am considering the possibility of > programming all my algorithms in Python. > > The usual alternative is C, but I like Python more. > > The main drawbacks I see to using Python are these: > > * As far as I understand, the fact that Python is not a compiled > language makes it slower than C, when performing huge amounts of > computations within an algorithm or program. > > * I don't know how likely it is to find libraries in Python related to > my research field. > > * I know Python is a "serious" and mature programming language, of > course. But I do not know if it is seen as "just funny" in a research > context. Is Python considered as a good programming language for > implementing Operations Research algorithms, such as heuristics and > other soft-computing algorithms? > > Maybe this is not the right forum, but maybe you can give me some > hints or tips... > > Thank you in advance. I guess that python is not a good language for that. Algorithms implemented in plain python are many times slower than C ones (hundreds ?). In practice, algorithms are written in C and wrapped in python. I have near zero experience in operations research, but once I looked for linear programming toolkits for python and IIRC, I only could find a trivial wrapper for glpk (called pulp). My opinion: choose compiled or byte compiled languages. Choose the language paradigm that best suit the algorithms. From iainking at gmail.com Thu May 15 04:31:17 2008 From: iainking at gmail.com (Iain King) Date: Thu, 15 May 2008 01:31:17 -0700 (PDT) Subject: Rename field in Access DB References: Message-ID: On May 14, 4:29 pm, Tim Golden wrote: > Iain King wrote: > > I'm manipulating an MS Access db via ADODB with win32com.client. I > > want to rename a field within a table, but I don't know how to. I > > assume there is a line of SQL which will do it, but nothing I've tried > > (from searching) has worked. > > Basic code: > > > import win32com.client > > connection = win32com.client.Dispatch(r'ADODB.Connection') > > DSN = 'PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=dbfile.mdb;' > > connection.Open(DSN) > > connection.Execute("ALTER TABLE tablename CHANGE from to") #this sql > > doesn't work > > connection.Close() > > > import os, sys > from win32com.client.gencache import EnsureDispatch as Dispatch > > DATABASE_FILEPATH = r"c:\temp\test.mdb" > CONNECTION_STRING = "Provider=Microsoft.Jet.OLEDB.4.0; data Source=%s" % \ > DATABASE_FILEPATH > > if os.path.exists (DATABASE_FILEPATH): > os.remove (DATABASE_FILEPATH) > > adox = Dispatch ("ADOX.Catalog") > adox.Create (CONNECTION_STRING) > adox = None > > db = Dispatch ('ADODB.Connection') > db.Open (CONNECTION_STRING) > try: > db.Execute ('CREATE TABLE dtest (id INT, data INT)') > db.Execute ('INSERT INTO dtest (id, data) VALUES (1, 2)') > > try: > db.Execute ('SELECT id, newdata FROM dtest') > except: > print "FAILED as expected" > else: > print "SUCCEEDED unexpectedly" > > try: > db.Execute ('SELECT id, data FROM dtest') > except: > print "FAILED unexpectedly" > else: > print "SUCCEEDED as expected" > > adox = Dispatch ("ADOX.Catalog") > adox.ActiveConnection = db > adox.Tables ("dtest").Columns ("data").Name = "newdata" > adox.Tables.Refresh () > finally: > db.Close () > > db = Dispatch ('ADODB.Connection') > db.Open (CONNECTION_STRING) > try: > > try: > db.Execute ('SELECT id, data FROM dtest') > except: > print "FAILED as expected" > else: > print "SUCCEEDED unexpectedly" > > try: > db.Execute ('SELECT id, newdata FROM dtest') > except: > print "FAILED unexpectedly" > else: > print "SUCCEEDED as expected" > > finally: > db.Close () > > > > TJG Excellent, many thanks. Iain From maxinbjohn at gmail.com Thu May 8 07:38:12 2008 From: maxinbjohn at gmail.com (maxinbjohn) Date: Thu, 8 May 2008 04:38:12 -0700 (PDT) Subject: Newbie to python --- why should i learn ! References: <9f5ee6c3-86f7-401a-acc8-cd2c9b059fbd@x19g2000prg.googlegroups.com> Message-ID: <12b0b227-0a6c-4653-973b-8f13f2e5b3c1@v26g2000prm.googlegroups.com> Hi Raxit, One of the the tempting features of Python is that it is fun to code in Python. If you are really trying to learn python, you should read Adventures with Neko (http://gnuvision.com/books/pybook/) . It is an introductory book on Python programming for school children by Mr. Pramode CE. It is fun for children (when I tried it, me too liked it) to do programming with Neko, the cat. I am sure that it will be a fun filled learning experience for you. Regards, Maxin B. John pistacchio wrote: > Raxit at MyKavita.com ha scritto: > > Hi, > > > > i was reading/learning some hello world program in python. > > I think its very simillar to Java/C++/C#. What's different (except > > syntax) ? > > > > well, it's similar in the sense that it is a programming language. So > you can say that assembly is similar to BASIC, but that both are > different from finnish, but from a programmer's point of view, they're > all rather different languages. > > > what can i do easily with python which is not easy in c++/java !? > > > > generally speaking python is said to be easier to pick up for a pletora > of reasons. technically speaking, it is not, for example, strongly > typed, nor it forces you to use a programming paradigm like object > oriented programming. > This means that if you just want to see your name printed on the screen > you can simply write: > > print "raxit" > > and get the work done. to understand it you just have to understand some > basics like what is a string and what is a statement. > > in java, for example, it would look like: > > public class HelloWorld { > public static void main(String[] args) { > System.out.println("raxit"); > } > } > > in short, to obtain the same result (limited to this case) you have to > write 650% more code and you're forced to know what is a class, what > namespace means, what is a function (and arguments) and what are methods > and the dot notation and an array. not that you won't encounter all of > them learning python, but you're presented with all of them, all at > once, in the moment where you just want to write the simplest program. > that's why a typical java beginner's guide starts with ditto examples > and adds: "ignore everything for the moment". i hate when i have to > ignore things of a code that i'm writing! > > the same applies to C# and, to a certain extend, C++ that is a much > older language and present different learning problems. > Now, what can you do with python? Virtually everything (network > programming, game programming, server side scripting). In most cases, it > would run slower than it would do with the other languages (even slower > than the slow java). You won't do drivers or kernels in python, but you > won't even code them in java or C#. > the programs you'll write will mostly run on a number of different > platform, like java programs. porting a c++ is a bit tougher. at the > moment there is project (mono) that is porting the .net platform (where > c# runs) to multiple platforms, but basically, if you write a c# program > you're programming for windows. > hope it helps > > > > > Tnx, > > Raxit > > www.mykavita.com From upton at virginia.edu Wed May 21 12:00:44 2008 From: upton at virginia.edu (Dan Upton) Date: Wed, 21 May 2008 12:00:44 -0400 Subject: Python and Flaming Thunder In-Reply-To: References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> Message-ID: <5504f9ac0805210900w47ad3a81mc7b433d18b7a6059@mail.gmail.com> On Wed, May 21, 2008 at 11:34 AM, Dave Parker wrote: > For example, consider the two statements: > > x = 8 > x = 10 > > The reaction from most math teachers (and kids) was "one of those is > wrong because x can't equal 2 different things at the same time". Sounds to me like the teacher is being difficult, and IIRC, you've talked about having elementary school kids write in FT -- I don't think asking "does this make sense to you" of elementary school kids is necessarily the best metric for PL syntax/semantics. > Many computer languages conflate "equality" with "assignment" and then > go to even more confusing measures to disambiguate them (such as using > == for equality, or := for assignment). > > Plus, symbols are more confusing for people to learn about than > words. There are lots of people who are fluent in English, but > dislike math. If you can't do, or don't like, math, you probably shouldn't be programming. If you don't have any symbolic reasoning skills, you're largely limited to "Hello, World." > That way, = can be reserved unambiguously and unconfusingly for the > mathematical notion of "equality" -- because it's in their math > classes that people learn what = means: > > Set QuadraticEquation to a*x^2 + b*x + c = 0. You keep trotting out this quadratic equation example, but does FT actually have any kind of useful equation solver in it? Or does it just allow you to do something like Set QuadraticEquation to a*x^2 + b*x + c = 0. Set a to 1. Set b to 0. Set c to -25. Set x to 5. If QuadraticEquation is True then do .... From mblume at socha.net Wed May 28 13:19:27 2008 From: mblume at socha.net (mblume) Date: 28 May 2008 17:19:27 GMT Subject: datetime.stdptime help References: <871e60df-fbf7-4fe5-ba45-d409e577f933@2g2000hsn.googlegroups.com> Message-ID: <483d941f$0$9032$5402220f@news.sunrise.ch> Am Tue, 27 May 2008 12:37:34 -0700 schrieb Dennis Lee Bieber: > > From the library reference: > """ > Support for the %Z directive is based on the values contained in tzname > and whether daylight is true. Because of this, it is platform-specific > except for recognizing UTC and GMT which are always known (and are > considered to be non-daylight savings timezones). """ > > The only value that passed for me was UTC (I didn't try GMT) but... > For me, only UTC, GMT, CET and CEST (Central European [Summer] Time) work. My time.tzname is ('CET', 'CEST'). I think the documentation must be read that ***only*** UTC,GMT,time.tzname work. Also, time zone names are not unique: EST can be Eastern Summer Time (US) as well as Eastern Summer Time (Australia). For working with time zones, I think that a module like pytz http://pytz.sourceforge.net/ may be better suited. My 0.02c. Martin From cbhoem at gmail.com Thu May 1 09:02:35 2008 From: cbhoem at gmail.com (cbhoem at gmail.com) Date: Thu, 1 May 2008 06:02:35 -0700 (PDT) Subject: Cookie Confusion - How to Set a Cookie References: <588d6a6c-0080-48a4-b768-e2c5ef551790@s50g2000hsb.googlegroups.com> <94d81004-fc6d-4ff9-9500-143864a6d7a7@f63g2000hsf.googlegroups.com> Message-ID: On Apr 29, 3:35 pm, Aaron Watters wrote: > > Thanks for the code, Aaron. I will give it a try. > > > I've been reading some more about cookielib and am not sure whether I > > should use Cookie or cookielib. This is what I want to do: a user is > > going to login. Upon a successful login, I want to write their name > > and date/time of visit to a cookie file. Which is the correct python > > module to use? > > Cookie does parsing and generation of cookie strings > for server-side applications like your CGI script. > > The cookielib module > is designed for either implementing a client like a web browser > or emulating a client/browser (for web scraping, for example). > > I think you want to use Cookie. > The distinction could be made clearer in > the docs, imho. > > Also, when you say "write the cookie file" I think you mean > "store the cookie to the client browser". This should happen > automatically when you send the cookie header to the client > correctly (if the client is configured to cooperate). > > -- Aaron Watters > > ===http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=default+does+n... Sorry for the slow replies. I've been in & out with a sick child. I'm used to my javascript cookies. They are automatically written to a cookie.txt file in a .mozilla dir under my user. When I say to 'write the cookie file' this is what I was referring to. I was expecting my python cookie to automatically get written to the same file. I have't seen this happen yet. From alex.m.gusarov at gmail.com Tue May 27 07:20:24 2008 From: alex.m.gusarov at gmail.com (Alex Gusarov) Date: Tue, 27 May 2008 18:20:24 +0700 Subject: Overloading virtual method of widget without inheriting (PyQt) In-Reply-To: References: <6a53c9ff-d4ce-483e-959f-2505ad107093@a1g2000hsb.googlegroups.com> Message-ID: > class MultiHandler(object): > def __init__(self, owner, *initial_handlers): > ... > ... > ... > calendar = Calendar() > calendar.on_paint = MultiHandler(calendar, Calendar.on_paint) > > calendar.on_paint() > calendar.on_paint += handler1 > calendar.on_paint() > calendar.on_paint += handler2 > calendar.on_paint() Marek, this seems exactly what I want, thanks, I will try it. Thanks everybody. Yes, I'm newbie, so may be it was a dumb question, don't judge me. -- Best regards, Alex Gusarov From sposnjak at gmail.com Mon May 5 09:41:08 2008 From: sposnjak at gmail.com (Simon Posnjak) Date: Mon, 5 May 2008 15:41:08 +0200 Subject: How to convert unicode string to unsigned char * Message-ID: <725404980805050641s52cac3b8mf238ff29883c6dba@mail.gmail.com> Hi! I have a C module for which I created a wrapper with swig. The function def is: C: int some_thing(unsigned char * the_str); eg: Python: some_module.some_thing (the_str) Now I would like to feed it with a UTF-8 formatted string: test = u'Make \u0633\u0644\u0627\u0645, not war.' If I try: some_module.some_thing (test) I get: TypeError with message: in method 'some_thing', argument 1 of type 'unsigned char *' I also tried to pack the string into array or struct but I can not get it to work. What would be the best solution for this problem? [I am working on Windows] Regards Simon From pavlovevidence at gmail.com Wed May 28 22:38:27 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 28 May 2008 19:38:27 -0700 (PDT) Subject: FW: php vs python References: <1cc9a56b-c1d4-4fad-968b-a87684ccfc12@l64g2000hse.googlegroups.com> Message-ID: On May 28, 7:45 pm, blaine wrote: > On May 28, 4:47 pm, "Phil Runciman" > wrote: > > > > > -----Original Message----- > > From: Jerry Stuckle [mailto:jstuck... at attglobal.net] > > Sent: Wednesday, 28 May 2008 1:48 p.m. > > To: python-l... at python.org > > Subject: Re: php vs python > > > Ivan Illarionov wrote: > > > On Wed, 28 May 2008 05:10:20 +0400, AnrDaemon wrote: > > > >> Greetings, Ivan Illarionov. > > >> In reply to Your message dated Monday, May 26, 2008, 04:47:00, > > > >>>> As I've said before - good programmers can write good code in any > > >>>> language. > > >>> Yes, they can. But it may be harder to do for them in one language > > and > > >>> easier in another. > > >> It's obvious lie. If you have clear mind and you know language you're > > >> using, there are absolutely NOTHING can deny you to write clear code. > > >> Even using forth postfix notation, I have no problem writing good > > code, > > >> it's as easy as writing bad code. And yes, I do see the difference. > > > > No. Language does matter. > > > Yes it does matter. > > > I have programmed in many assembly and higher level languages. > > > In OldenTimes: > > In Algol 60 I was productive from the start. > > KDF9 Usercode (Assembly) was brilliant. (A bigger HW stack would have > > made it even better). > > IBM 360 Assembly was poorer but not a disaster. > > PL1 was a mess. You could write good code but why bother? > > COBOL was fit for purpose and when combined with Jackson structured > > programming could be used straight away by rooky programmers in business > > systems programming. I am sure it has progressed since ANSI 68. > > > The Inuit have 13 terms for snow. Microsoft advocate DSLs. Why have DSLs > > if language does not matter? > > > My 2c worth. > > http://www.fukung.net/v/7729/php_vs_python.png > :) Ha ha. Took me a second. Carl Banks From mensanator at aol.com Thu May 15 15:24:59 2008 From: mensanator at aol.com (Mensanator) Date: Thu, 15 May 2008 12:24:59 -0700 (PDT) Subject: Computer References: Message-ID: On May 15, 1:14?pm, gaojihuiyuan wrote: > Plastic Coat Your Cedar with EPL > EPL is a clear thin polymer coat that will maintain the bright cedar > wood look. Buy online today.http://www.healthhuman.com.cn/Computer.htm > > Cedar Wood > Find Deals on Cedar Wood and other Home & Garden Products at DealTime. > Choose from millions of deals. Save time and money every time you > shop.http://www.healthhuman.com.cn/Computer.htm > > Cedar Wood - Bargain Prices > Shop fast, Buy smart, Shopzilla for Wood Outdoor Furniture and other > Furniture and Outdoor Decor. Every product from every store means you > get a Bargain Price. Don't just shop, Shopzilla.http://www.healthhuman.com.cn/Computer.htm I'll keep that in mind the next time I buy a wooden computer. From http Wed May 7 02:02:11 2008 From: http (Paul Rubin) Date: 06 May 2008 23:02:11 -0700 Subject: ]ANN[ Vellum 0.16: Lots Of Documentation and Watching References: <3a8e0a8f-3bd1-4650-9104-5c273f14b097@w7g2000hsa.googlegroups.com> <1w4gs9bk.fsf@gmail.com> Message-ID: <7x3aouejoc.fsf@ruckus.brouhaha.com> vivainio at gmail.com (Ville M. Vainio) writes: > if the idea is to maximize the popularity, GPL is a worse bet. That is not a valid inference. Look at the popularity of Linux vs BSD, for example. From wizzardx at gmail.com Thu May 8 08:49:37 2008 From: wizzardx at gmail.com (David) Date: Thu, 8 May 2008 14:49:37 +0200 Subject: python equivalent to perl's inplace edit mechanism In-Reply-To: <170543c70805080511o348f38fam5c56c71fce4a6f37@mail.gmail.com> References: <170543c70805080511o348f38fam5c56c71fce4a6f37@mail.gmail.com> Message-ID: <18c1e6480805080549h70885464r8d8a177741ffcabd@mail.gmail.com> On Thu, May 8, 2008 at 2:11 PM, Michael Mabin wrote: > Does python have an equivalent to Perl's inplace-edit variable $^I? > I misread your question. No, Python eschews magic characters and symbols. They make code ugly and harder to read and maintain. The first 3 lines of the Zen of Python: Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. You might find a variable like that in Ruby, which has strong Perl influences. David. From wojtek.gminick.walczak at gmail.com Mon May 5 08:17:37 2008 From: wojtek.gminick.walczak at gmail.com (Wojciech Walczak) Date: Mon, 5 May 2008 14:17:37 +0200 Subject: pygame music, cant read mp3? In-Reply-To: <5e52e1b5-8698-4ba1-8fc2-180ba20491cb@m73g2000hsh.googlegroups.com> References: <30fe7c79-dbac-47bb-9e29-bea61b7c3da8@56g2000hsm.googlegroups.com> <688af0F2pc3jjU1@mid.uni-berlin.de> <5e52e1b5-8698-4ba1-8fc2-180ba20491cb@m73g2000hsh.googlegroups.com> Message-ID: <2c3c21060805050517j49f84ac1u52e288d18db11aea@mail.gmail.com> 2008/5/5, globalrev : > pygame.mixer.music.load('C:/Python25/myPrograms/pygameProgs/example1.mp3') Are you sure that: os.path.exists('C:/Python25/myPrograms/pygameProgs/example1.mp3') == True? Check it with python. -- Regards, Wojtek Walczak http://www.stud.umk.pl/~wojtekwa/ From skunkwerk at gmail.com Mon May 12 15:29:16 2008 From: skunkwerk at gmail.com (skunkwerk) Date: Mon, 12 May 2008 12:29:16 -0700 (PDT) Subject: threading - race condition? References: <4823f61e$0$34533$742ec2ed@news.sonic.net> <7bbbb71e-d163-4978-ab90-b96652598757@u6g2000prc.googlegroups.com> <07d4f574-ffda-4c7f-9561-b3be424b141f@y18g2000pre.googlegroups.com> Message-ID: On May 11, 1:55 pm, Dennis Lee Bieber wrote: > On Sun, 11 May 2008 09:16:25 -0700 (PDT),skunkwerk > declaimed the following in comp.lang.python: > > > > > the only issue i have now is that it takes a long time for 100 threads > > to initialize that connection (>5 minutes) - and as i'm doing this on > > a webserver any time i update the code i have to restart all those > > threads, which i'm doing right now in a for loop. is there any way I > > can keep the thread stuff separate from the rest of the code for this > > file, yet allow access? It wouldn't help having a .pyc or using > > psycho, correct, as the time is being spent in the runtime? something > > along the lines of 'start a new thread every minute until you get to a > > 100' without blocking the execution of the rest of the code in that > > file? or maybe any time i need to do a search, start a new thread if > > the #threads is <100? > > Is this running as part of the server process, or as a client > accessing the server? > > Alternative question: Have you tried measuring the performance using > /fewer/ threads... 25 or less? I believe I'd mentioned prior that you > seem to have a lot of overhead code for what may be a short query. > > If the .get_item() code is doing a full sequence of: connect to > database; format&submit query; fetch results; disconnect from > database... I'd recommend putting the connect/disconnect outside of the > thread while loop (though you may then need to put sentinel values into > the feed queue -- one per thread -- so they can cleanly exit and > disconnect rather than relying on daemonization for exit). > > thread: > dbcon = ... > while True: > query = Q.get() > if query == SENTINEL: break > result = get_item(dbcon, query) > ... > dbcon.close() > > Third alternative: Find some way to combine the database queries. > Rather than 100 threads each doing a single lookup (from your code, it > appears that only 1 result is expected per search term), run 10 threads > each looking up 10 items at once... > > thread: > dbcon = ... > terms = [] > terminate = False > while not terminate: > while len(terms) < 10: > query = Q.get_nowait() > if not query: break > if query == SENTINEL: > terminate = True > break > terms.append(query) > results = get_item(dbcon, terms) > terms = [] > #however you are returning items; match the query term to the > #key item in the list of returned data? > dbcon.close() > > where the final select statement looks something like: > > SQL = """select key, title, scraped from *** > where key in ( %s )""" % ", ".join("?" for x in terms) > #assumes database adapter uses ? for placeholder > dbcur.execute(SQL, terms) > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfr... at ix.netcom.com wulfr... at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-a... at bestiaria.com) > HTTP://www.bestiaria.com/ thanks again Dennis, i chose 100 threads so i could do 10 simultaneous searches (where each search contains 10 terms - using 10 threads). the .get_item() code is not doing the database connection - rather the intialization is done in the initialization of each thread. so basically once a thread starts the database connection is persistent and .get_item queries are very fast. this is running as a server process (using django). cheers From irmen.NOSPAM at xs4all.nl Sat May 10 10:22:52 2008 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Sat, 10 May 2008 16:22:52 +0200 Subject: Simple question In-Reply-To: <205f1f1e-073b-4edc-ad18-59d1d1b065d6@59g2000hsb.googlegroups.com> References: <68lj5oF2sudm7U1@mid.individual.net> <205f1f1e-073b-4edc-ad18-59d1d1b065d6@59g2000hsb.googlegroups.com> Message-ID: <4825afc8$0$14350$e4fe514c@news.xs4all.nl> Gandalf wrote: > On May 10, 2:36 pm, Bjoern Schliessmann mail-0306.20.chr0n... at spamgourmet.com> wrote: >> Gandalf wrote: >>> how can i ran script with python >> It depends on your web server configuration. To get your web server >> execute Python code, there are several alternatives like >> >> * CGI >> * FastCGI >> * mod_python >> >> Regards, >> >> Bj?rn >> >> -- >> BOFH excuse #93: >> >> Feature not yet implemented > > my server is my computer and all i did way to install python on it. You might want to read a bit more about Python and how it can be used for web programming. Because your question is not easily answered. I suggest the following at least: http://wiki.python.org/moin/PythonVsPhp (especially the "Compared as Web Development Frameworks" section) http://wiki.python.org/moin/WebProgramming Good luck. --irmen From inhahe at gmail.com Mon May 26 15:52:23 2008 From: inhahe at gmail.com (inhahe) Date: Mon, 26 May 2008 15:52:23 -0400 Subject: Question about wsgi.input References: <6a0htmF35sj8eU1@mid.uni-berlin.de> Message-ID: That's what I would have thought, just seems strange since it seems to imply that if I use StringIO or cStringIO, then whenever i write to it i have to save the position, seek to the end, write, and then seek to the position i saved. Are there any other classes that are more suitable for pipes, but qualify as 'file-like objects'? "Diez B. Roggisch" wrote in message news:6a0htmF35sj8eU1 at mid.uni-berlin.de... > inhahe schrieb: >> I'm sorry if this is off-topic, i couldn't find a mailing list OR forum >> for WSGI (and #wsgi wasn't very helpful). >> >> i played around with StringIO, and apparently if you write to a stringio >> the position gets set to the end of the write, so if you read from it >> again, without using seek, you won't read what comes next, you'll skip to >> the end of the write. and if you write without seeking to the end first, >> you'll overwrite part of the string if the reading hasn't caught up. >> >> WSGI says that wsgi.input should block if there's more data to be read >> from the socket, until that data is available. so when the server writes >> to the file object, what happens to the file position? if i were writing >> a WSGI app, i would just seek() to the last place my read ended at just >> to make sure. but i'm making a server, so i need to know whether i >> should leave the position at the end of the write, when it blocks (or for >> that matter, if i'm writing while it's still reading), or at the end of >> the previous read? > > I'm not sure exactly about what you are talking here - but generally, > wsgi.input should be considerd being a pipe. One (the server) simply > writes into it. The WSGI-app just reads. No seek. > > Diez From johnroth1 at gmail.com Sun May 25 09:17:58 2008 From: johnroth1 at gmail.com (John Roth) Date: Sun, 25 May 2008 06:17:58 -0700 (PDT) Subject: unittest: Calling tests in liner number order References: <84ff733a-e364-437d-9b5d-d8bb14cc692d@m73g2000hsh.googlegroups.com> <3300da64-ff6b-4c00-9bb4-339d44c9b204@f36g2000hsa.googlegroups.com> Message-ID: On May 24, 7:22 am, Andr? wrote: > > I can't relate to anyone that want to oppose a change that would give > more freedom to a programmer. > > Andr? Well, you can already do that. Or anything else you want. It's not all that difficult to change the algorithms in the unittest package _without_ patching the code. How to do it could be better documented, granted. For my major project (Python FIT) I've got my own test case extraction mechanism that doesn't depend on patching the code. It lets me use any name I want - that is, it doesn't depend on any kind of pattern match. (It also avoids looking in subclasses for tests.) I find the naming freedom to be quite useful in thinking about the test case. I really don't care what the OP does in his own projects. My objection is that, if it goes into the standard library, is that it passes a signal that it's good practice to allow dependencies between tests. It most definitely is _not_ good practice. I like the technique of looking at the line numbers to get the declaration order; it ought to be documented somewhere. The proper place for this is either a recipe ( http://aspn.activestate.com/ASPN/Cookbook/Python/ ) or a note in the documentation with a caveat that it's not good practice, but it may be useful in some circumstances. John Roth From kyosohma at gmail.com Tue May 20 17:16:20 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 20 May 2008 14:16:20 -0700 (PDT) Subject: List of disk drives on Windows? References: <2008052013180816807-bob@passcalnmtedu> Message-ID: <83b42c06-22e3-4818-af47-6aa419336ed2@l28g2000prd.googlegroups.com> On May 20, 3:43?pm, Christian Heimes wrote: > Mike Driscoll schrieb: > > > > > On May 20, 2:45 pm, Tim Golden wrote: > >> Bob Greschke wrote: > >>> This MUST have been asked before, but I can't seem to Google the right > >>> thing. ?How can I get a list of drives on a Windows box, like ["C:\", > >>> "D:\"], like I can if I do something like listdir("/Volumes") on a Mac? > >> A couple of options to get the ball rolling: > > >> 1) win32api.GetLogicalDriveStrings() > > > I gave this a go to see how it worked and ti gave me this: > > > 'A:\\\x00C:\\\x00D:\\\x00G:\\\x00I:\\\x00L:\\\x00P:\\\x00Q:\\\x00R:\\ > > \x00U:\\\x00X:\\\x00Y:\\\x00Z:\\\x00' > > > Not exactly what I expected. Do I have to parse out the "\\\x00" > > myself or is there an information level switch I should add? > > The data is separated by NUL bytes. Split it with \x00 and you'll get a > list of drives: > > "A:\\\x00C:\\\x00D:\\\x00G:\\\x00I:\\\x00L:\\\x00P:\\\x00Q:\\\x00R:\\\x00U:\\\x00X:\\\x00Y:\\\x00Z:\\\x00".split("\x00") > ['A:\\', 'C:\\', 'D:\\', 'G:\\', 'I:\\', 'L:\\', 'P:\\', 'Q:\\', 'R:\\', > 'U:\\', 'X:\\', 'Y:\\', 'Z:\\', ''] > > Christian Yeah, I noticed that. I just thought that was a weird piece of info for the call to return. Mike From jaywgraves at gmail.com Fri May 16 17:21:57 2008 From: jaywgraves at gmail.com (jay graves) Date: Fri, 16 May 2008 14:21:57 -0700 (PDT) Subject: save dictionary for later use? References: <99403e9d-4c67-4e3f-a726-7bb02e72423a@m3g2000hsc.googlegroups.com> <9ec97b27-e4a8-40e0-b8b3-a2cdaeba448e@d77g2000hsb.googlegroups.com> Message-ID: <8f70d02b-2626-4d50-8d2e-7656b925987e@d1g2000hsg.googlegroups.com> On May 16, 3:24 pm, globalrev wrote: > On 16 Maj, 21:22, jay graves wrote: > > On May 16, 2:17 pm, globalrev wrote: > > > i extract info from one file and put it into a dictionary. > > > i want to save that dictionary for later use, how do i do that? > > > might save a list of dictionaries or a list of classobjects too if > > > there is any difference. > > use the 'pickle' module.http://docs.python.org/lib/module-pickle.html > pickle.dumps(mg) > pickle.load(mg) > > 'dict' object has no attribute 'readline' > dumps load(well i dont know but i get no complaint but running load > generates that error) It's best to post a minimal set of code that exhibits your error. You aren't saving the output of pickle.dumps and you are using pickle.load instead of pickle.loads. Sample loading to and from a string which you can tuck away in a file. >>> import pickle >>> test = {'a':1,'b':2} >>> picklestr = pickle.dumps(test) >>> test2 = pickle.loads(picklestr) >>> test == test2 True >>> Sample using an open file. >>> import pickle >>> test = {'a':1,'b':2} >>> pfile = open('pickletest','wb') >>> pickle.dump(test,pfile) >>> pfile.close() >>> pfile = open('pickletest','rb') >>> test2 = pickle.load(pfile) >>> pfile.close() >>> test == test2 True >>> ... Jay Graves From kw at codebykevin.com Sat May 10 11:31:37 2008 From: kw at codebykevin.com (Kevin Walzer) Date: Sat, 10 May 2008 11:31:37 -0400 Subject: People still using Tkinter? In-Reply-To: References: Message-ID: <4825BFD9.7020600@codebykevin.com> Kenneth McDonald wrote: > Any guesses as to how many people are still using Tkinter? And can > anyone direct me to good, current docs for Tkinter? > > Thanks, > Ken I develop Tk applications commercially on Mac OS X, using Tcl and Python. Here's a screenshot of my Python app: http://www.codebykevin.com/phynchronicity-running.png This app is built on Python 2.5.1 and Tk 8.5.0. Tk 8.5 has a huge number of improvements over older versions of Tk: http://www.tkdocs.com/resources/backgrounder.html Most importantly, Tk 8.5 has a themed widget set that allows for platform-native appearance on Windows and Mac (not emulated, but hooking into system API's). The themed widget set also adds a lot of new widgets, such as combobox, tree, and others. The older widget set is still available as well and they can be freely matched. Tk also has a lot of lightweight, script-level widget libraries that can also enhance the appearance and usability of your app. My own app uses widgets from Tk's traditional set, the new Tile/ttk set, the Tabelist widget, and the BWidget widget library. It uses the following Python wrappers for these widgets: http://tkinter.unpy.net/wiki/TileWrapper http://tkinter.unpy.net/wiki/TableListTileWrapper http://tkinter.unpythonic.net/bwidget/ It also uses a few private wrappers/custom widgets. In addition to the Python-specifc resources that others have provided, here's a new site that documents the latest-and-greatest Tk techniques, including Tile/ttk: http://www.tkdocs.com/ The developer of this site is mainly interest in Tcl and Ruby, so examples of those are provided--I may provide some Python examples at some point. But there should be enough code snippets there for you to get started, especially if you already have some experience with Tk/Tkinter. Tk still has some limitations, including a lack of cross-platform printing support (the canvas widget generates postscript, but that's not enough anymore) and an incomplete cross-platform drag-and-drop mechanism (works fine on Windows, it's buggy on *NIx because Xdnd is so inconsistent, and it was never developed for OS X). If you absolutely need these features, look at wxPython or PyQt. But coming to Python from a Tcl background, I'm very comfortable with Tk--it is lightweight, extremely flexible, and (as I hope you can see from my screenshot) it's possible to do sophisticated user interfaces with it. It fits my brain much better than wxPython, for instance. And the long effort by Tk's developers to modernize its appearance has finally paid off, I think. Hope that helps, Kevin -- Kevin Walzer Code by Kevin http://www.codebykevin.com From mail at timgolden.me.uk Thu May 8 15:50:36 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 08 May 2008 20:50:36 +0100 Subject: How to gather information about the system hardware? In-Reply-To: References: Message-ID: <4823598C.8010606@timgolden.me.uk> Florencio Cano wrote: > Hi, > I'm looking for a method of gathering information about the system > hardware and software installed using Python. I would like to do it in > UNIX and in Windows. I think that it would be good in Windows to look > in the registry and be able to parse and search it. Any pointer to > information would be appreciated. For Windows WMI is probably a good bet. TJG From nick at craig-wood.com Sat May 3 14:30:03 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Sat, 03 May 2008 13:30:03 -0500 Subject: Feature suggestion: sum() ought to use a compensated summation algorithm References: Message-ID: Szabolcs Horv?t wrote: > I did the following calculation: Generated a list of a million random > numbers between 0 and 1, constructed a new list by subtracting the mean > value from each number, and then calculated the mean again. > > The result should be 0, but of course it will differ from 0 slightly > because of rounding errors. > > However, I noticed that the simple Python program below gives a result > of ~ 10^-14, while an equivalent Mathematica program (also using double > precision) gives a result of ~ 10^-17, i.e. three orders of magnitude > more precise. > > Here's the program (pardon my style, I'm a newbie/occasional user): > > from random import random > > data = [random() for x in xrange(1000000)] > > mean = sum(data)/len(data) > print sum(x - mean for x in data)/len(data) > > A little research shows that Mathematica uses a "compensated summation" > algorithm. Indeed, using the algorithm described at > http://en.wikipedia.org/wiki/Kahan_summation_algorithm > gives us a result around ~ 10^-17: I was taught in my numerical methods course (about 20 years ago now!) that the way to do this sum with most accuracy is to sum from the smallest magnitude to the largest magnitude. Eg >>> from random import random >>> data = [random() for x in xrange(1000000)] >>> mean = sum(data)/len(data) >>> print sum(x - mean for x in data)/len(data) 1.64152134108e-14 >>> mean = sum(sorted(data))/len(data) >>> print sum(x - mean for x in data)/len(data) 5.86725534824e-15 >>> It isn't as good as the compensated sum but it is easy! > I thought that it would be very nice if the built-in sum() function used > this algorithm by default. Has this been brought up before? Would this > have any disadvantages (apart from a slight performance impact, but > Python is a high-level language anyway ...)? sum() gets used for any numerical types not just floats... -- Nick Craig-Wood -- http://www.craig-wood.com/nick From jcd at sdf.lonestar.org Tue May 20 11:50:17 2008 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Tue, 20 May 2008 11:50:17 -0400 Subject: Help with character encodings In-Reply-To: <4832EE29.5020700@islandtraining.com> References: <62d8a7af-4e63-4bb5-9440-4232282d6649@d45g2000hsc.googlegroups.com> <4832EE29.5020700@islandtraining.com> Message-ID: <1211298617.30679.9.camel@aalcdl07.lib.unc.edu> On Tue, 2008-05-20 at 08:28 -0700, Gary Herron wrote: > A_H wrote: > > Help! > > > > I've scraped a PDF file for text and all the minus signs come back as > > u'\xad'. > > > > Is there any easy way I can change them all to plain old ASCII '-' ??? > > > > str.replace complained about a missing codec. > > > > > > > > Hints? > > > > Encoding it into a 'latin1' encoded string seems to work: > > >>> print u'\xad'.encode('latin1') > - > > Here's what I've found: >>> x = u'\xad' >>> x.replace('\xad','-') Traceback (most recent call last): File "", line 1, in ? UnicodeDecodeError: 'ascii' codec can't decode byte 0xad in position 0: ordinal not in range(128) >>> x.replace(u'\xad','-') u'-' If you replace the *string* '\xad' in the first argument to replace with the *unicode object* u'\xad', python won't complain anymore. (Mind you, you weren't using str.replace. You were using unicode.replace. Slight difference, but important.) If you do the replace on a plain string, it doesn't have to convert anything, so you don't get a UnicodeDecodeError. >>> x = x.encode('latin1') >>> x '\xad' >>> # Note the lack of a u before the ' above. >>> x.replace('\xad','-') '-' >>> Cheers, Cliff From agustin.villena at gmail.com Thu May 22 11:28:13 2008 From: agustin.villena at gmail.com (Agustin Villena) Date: Thu, 22 May 2008 08:28:13 -0700 (PDT) Subject: Showing the method's class in expection's traceback References: <79c7d6fb-a6b8-481f-9a36-81b980628710@59g2000hsb.googlegroups.com> <69bi20F31j4kdU1@mid.uni-berlin.de> <483406a0$0$10773$426a74cc@news.free.fr> <6a8c7499-7d8c-4d5d-9ea6-a3e1ba2f9565@c58g2000hsc.googlegroups.com> <48353a94$0$12639$426a74cc@news.free.fr> Message-ID: <15ce3e4e-c98c-4ee6-bb5f-caf2cf0d69cf@i76g2000hsf.googlegroups.com> On May 22, 5:19 am, Bruno Desthuilliers wrote: > Agustin Villena a ?crit : > > >> And not that useful - why would one care about the function being > >> defined in class X or Y when one have the exact file and line ? > > > I have 3 reasons: > > > 1) My developing time is expended running unit tests and browsing > > tracebacks to find which is the real problem. Knowing the offender > > class (instead of the method alone) makes me understand more quickly > > which component of my software is failing. > > This is only true when there is an obvious, one-to-one, unambiguous > relationship between the physical location of the error (file, line) and > the class of the object the method has been called on. Which is not > necessarily the case (inheritance, method decoration and monkeypatching > comes to mind here...). > > Also, your above statement seems to imply that component==class, which > is not the case in Python. > > > 2) There are some ocassions where I only have the traceback (e.g. when > > analyzing an app's log) and no inmediate access to teh source code > > Ok. But the above still apply... > > > 3) And finally, for completeness: If a function is really a method, if > > the traceback show only its name and not the class that defines it, > > for me its a bug, because the method name has no sense out of its > > class. > > I'm not sure you really grasp what "methods" are in Python. What you > define (using the def statement) within a class is function, not a > method. It only becomes a method when it's looked up on an instance or > class object, and this 'method' is only a thin wrapper around the > instance, class and function objects. And FWIW, you don't need to define > the function within the class to make it a method: > > # bar.py > def bar(obj): > print "function bar.bar called on obj %s" % obj > > # foo.py > > class Foo(object): pass > > # baaz.py > from foo import Foo > import bar > > Foo.baaz = bar.bar > > def guux(obj): > print "function baaz.guux called on obj %s" % obj > > # main.py > from baaz import Foo > f = Foo() > f.bar() > > f.gnix = baae.guux.__get__(f, type(f)) > f.gnix() > > Not to say that your concerns are pointless, and that things cannot be > improved somehow, but this is not that trivial, and there may be > ambuiguities in some not so rare cases. Well, the solution given in an early response is good enough for me. I don't see things like you, because I'm accustomed to design my software though classes and see the code in an "object = software's functional atom/component" way I agree that python's dynamic nature make things complicated here, but for me it its just an implementation problem derived of the recent OOP support of python From __peter__ at web.de Wed May 28 04:11:19 2008 From: __peter__ at web.de (Peter Otten) Date: Wed, 28 May 2008 10:11:19 +0200 Subject: multi dimensional dictionary References: Message-ID: Gary Herron wrote: > Alok Kumar wrote: >> Dear All, >> >> I am using dictionary for filling my xpath parsed data. >> >> I wanted to use in the following manner. >> >> mydict[index] ["key1"] ["key2"] #Can someone help me with right >> declaration. >> >> So that I can fill my XML xpath parsed data >> >> mydict[0] ["person"] ["setTime"] = "12:09:30" >> mydict[0] ["person"] ["clrTime"] = "22:09:30" [I didn't see the original post] >>> from collections import defaultdict >>> def make_inner(): ... return defaultdict(lambda: defaultdict(make_inner)) ... >>> mydict = make_inner() >>> mydict[0]["person"]["setTime"] = "12:09:30" >>> mydict[0]["person"]["shoes"]["color"] = "bright yellow" >>> mydict defaultdict( at 0x2b7afd0025f0>, {0: defaultdict(, {'person': defaultdict( at 0x2b7afd002668>, {'setTime': '12:09:30', 'shoes': defaultdict(, {'color': 'bright yellow'})})})}) If that looks too messy, try a subclass: >>> class Dict(defaultdict): ... def __init__(self): ... defaultdict.__init__(self, Dict) ... def __repr__(self): ... return dict.__repr__(self) ... >>> mydict = Dict() >>> mydict[0]["person"]["setTime"] = "12:09:30" >>> mydict {0: {'person': {'setTime': '12:09:30'}}} >>> mydict[0]["person"]["shoes"]["color"] = "bright yellow" >>> mydict {0: {'person': {'setTime': '12:09:30', 'shoes': {'color': 'bright yellow'}}}} Peter From bblais at bryant.edu Fri May 23 11:44:11 2008 From: bblais at bryant.edu (Brian Blais) Date: Fri, 23 May 2008 11:44:11 -0400 Subject: Python is slow In-Reply-To: <8bmdnURysILjTavVnZ2dnUVZ_vqdnZ2d@posted.visi> References: <3J6dnbQZld6PZKjVnZ2dnUVZ_sDinZ2d@comcast.com> <8bmdnURysILjTavVnZ2dnUVZ_vqdnZ2d@posted.visi> Message-ID: <3C750143-6BC0-4626-98A6-44FFA16FE142@bryant.edu> On May 23, 2008, at May 23:10:11 AM, Grant Edwards wrote: > On 2008-05-23, RPM1 wrote: >> Larry Bates wrote: >>> If your Python program is slow, you have almost assuredly >>> approached it with a wrong method or algorithm. >> >> I agree for most applications. There are however times where >> Python just isn't fast enough, and that's usually when people >> write extension modules. > > Writing an extension modules is probably pretty far down the > list. What usually happens is people I think that really depends on what you are doing. For me, it is exactly as Larry said. I prototype in Python, then profile to figure out the slowest piece(s), and write an extension module. Personally, I use Cython which makes the transition pretty trivial. It is this solution (cython, that is) that convinced me to use Python over Ruby, or some other language, when I was moving code from Matlab. I haven't regretted it since. bb -- Brian Blais bblais at bryant.edu http://web.bryant.edu/~bblais -------------- next part -------------- An HTML attachment was scrubbed... URL: From mabbikeel at gmail.com Tue May 27 17:52:35 2008 From: mabbikeel at gmail.com (mabbikeel) Date: Tue, 27 May 2008 14:52:35 -0700 (PDT) Subject: Books for learning how to write "big" programs References: <219c77ef-dd0c-464b-bb6a-e4f3bee89eae@x41g2000hsb.googlegroups.com> Message-ID: <3279f21e-a101-405a-ada9-ecb25bf9e067@x35g2000hsb.googlegroups.com> On May 27, 9:58?pm, c james wrote: > duli wrote: > > Hi: > > I would like recommendations for books (in any language, not > > necessarily C++, C, python) which have walkthroughs for developing > > a big software project ? So starting from inception, problem > > definition, design, coding and final delivery on a single theme > > or application. I'm not sure, but perhaps Code Complete would be one to check out. I found it a good read on general design and implementation details, and has some bits on managing complexity. From inhahe at gmail.com Mon May 26 15:21:19 2008 From: inhahe at gmail.com (inhahe) Date: Mon, 26 May 2008 15:21:19 -0400 Subject: Question about wsgi.input Message-ID: I'm sorry if this is off-topic, i couldn't find a mailing list OR forum for WSGI (and #wsgi wasn't very helpful). i played around with StringIO, and apparently if you write to a stringio the position gets set to the end of the write, so if you read from it again, without using seek, you won't read what comes next, you'll skip to the end of the write. and if you write without seeking to the end first, you'll overwrite part of the string if the reading hasn't caught up. WSGI says that wsgi.input should block if there's more data to be read from the socket, until that data is available. so when the server writes to the file object, what happens to the file position? if i were writing a WSGI app, i would just seek() to the last place my read ended at just to make sure. but i'm making a server, so i need to know whether i should leave the position at the end of the write, when it blocks (or for that matter, if i'm writing while it's still reading), or at the end of the previous read? thanks for any help. From stefan_ml at behnel.de Wed May 28 16:04:23 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Wed, 28 May 2008 22:04:23 +0200 Subject: BeautifulSoup: problems with parsing a website In-Reply-To: <06ae8eb8-6879-4f12-9366-a7e938baa87f@a1g2000hsb.googlegroups.com> References: <06ae8eb8-6879-4f12-9366-a7e938baa87f@a1g2000hsb.googlegroups.com> Message-ID: <483DBAC7.1050900@behnel.de> Marco Hornung wrote: > Hy guys, ... and girls? > I'm using the python-framework BeautifulSoup(BS) to parse some > information out of a german soccer-website. consider using lxml. http://codespeak.net/lxml >>> from lxml import html > I want to parse the article shown on the website. >>> tree = html.parse("http://www.bundesliga.de/de/liga/news/ 2007/index.php?f=94820.php") > To do so I want to > use the Tag "
" as a starting-point. >>> div = tree.xpath('//div[@class = "txt_fliesstext"]') > When > I have found the Tag I somehow want to get all following "br"-Tags Following? Meaning: after the div? >>> br_list = diff.xpath("following-sibling::br") Or within the div? >>> br_list = diff.xpath(".//br") > until there is a new CSS-Class Style is coming up. Ok, that's different. >>> for el in div.iter(): # or div.itersiblings(): ... if el.tag == "br": ... print el.text # or whatever ... elif el.tag == "span" or el.get("class"): ... break Hope it helps. Stefan From kyosohma at gmail.com Fri May 23 13:21:47 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 23 May 2008 10:21:47 -0700 (PDT) Subject: Another Question References: <5c2e7570-6bb1-46d8-8dd5-b1a257431b31@p25g2000hsf.googlegroups.com> Message-ID: On May 23, 12:02?pm, Gandalf wrote: > On May 23, 6:25 pm, Mike Driscoll wrote: > > > > > On May 23, 10:45 am, Gandalf wrote: > > > > How can i bind function that handle the mouse clicking ?window X event > > > or clicking alt+F4 > > > > thanks > > > You really need to learn to ask good questions. Unless people dive > > into your previous posts, they won't know what Python GUI toolkit you > > are using, which version of said toolkit, which Python or which OS. > > > Here's a good place to read about events in general: > > >http://wiki.wxpython.org/EventPropagation > > > If you use Google, you can look for the close event, which gives you > > this: > > >http://www.wxpython.org/docs/api/wx.CloseEvent-class.html > > > So you'll want to bind your frame to EVT_CLOSE. You can disable the > > "X" in your frame's window by using non-standard style parameters. > > > Mike > > OK you right. I use WX on windows XP. > I didn't understood how to use this wx.CloseEvent function. > > i really struggle with my poor english to understand this language, so > your help is crucial for my progress and i appreciate it > > Thanks No problem. It just makes it much harder to help if we don't know what you're doing. I forget to mention stuff when I post too. Just in case you still don't get it, here's some generic code: self.frame.Bind(wx.EVT_CLOSE, self.onClose) def onClose(self, event): self.frame.Destroy() Note that I called the frame's Destroy() method instead of its Close() method. If you call Close() then the EVT_CLOSE event gets fired again and you basically end up in a loop. Mike From jason.scheirer at gmail.com Thu May 22 13:41:15 2008 From: jason.scheirer at gmail.com (Jason Scheirer) Date: Thu, 22 May 2008 10:41:15 -0700 (PDT) Subject: Python is slow References: Message-ID: On May 22, 9:14?am, cm_gui wrote: > Python is slow. ? ?Almost all of the web applications written in > Python are slow. ? Zope/Plone is slow, sloow, so very slooow. ?Even > Google Apps is not faster. ? Neither is Youtube. > Facebook and Wikipedia (Mediawiki), written in PHP, are so much faster > than Python. > Okay, they probably use caching or some code compilation -- but Google > Apps and those Zope sites probably also use caching. > > I've yet to see a web application written in Python which is really > fast. This post is a troll written by someone who has already made up their mind. I really don't recommend trying to argue here. I've written plenty of fast, fast Python and there are countless Python processes on servers out there that is not only fast but transparently so. From byte8bits at gmail.com Tue May 20 09:37:19 2008 From: byte8bits at gmail.com (brad) Date: Tue, 20 May 2008 09:37:19 -0400 Subject: Using Python for programming algorithms In-Reply-To: <482F71B0.3050808@ncf.ca> References: <482F71B0.3050808@ncf.ca> Message-ID: > Vicent Giner wrote: > The usual answer is that development time is more important than running time. This depends. Run time is not important until you are asked to scale to millions or billions of users or computations or large data sets. I've seen this first hand. Getting results back the same day or sooner may be important. In cases such as this, I use C or C++... nothing else will do. Nothing else is as fast. Although I always keep a py version around for testing and for smaller tasks. Don't get me wrong, I love Python, but there are times when nothing, but pure, hard speed will do. From deets at nospam.web.de Fri May 16 12:08:55 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 16 May 2008 18:08:55 +0200 Subject: writing python extensions in assembly In-Reply-To: <5giXj.4881$Kk3.2633@bignews9.bellsouth.net> References: <695jdlF30fp0gU1@mid.uni-berlin.de> <695ni3F30u8tgU2@mid.uni-berlin.de> <5giXj.4881$Kk3.2633@bignews9.bellsouth.net> Message-ID: <695pt5F30ah0iU1@mid.uni-berlin.de> inhahe schrieb: > I like to learn what I need, but I have done assembly before, I wrote a > terminal program in assembly for example, with ansi and avatar support. I'm > just not fluent in much other than the language itself, per se. > > Perhaps C would be as fast as my asm would, but C would not allow me to use > SIMD, which seems like it would improve my speed a lot, I think my goals are > pretty much what SIMD was made for. That is not true. I've used the altivec-extensions myself on OSX and inside C. Besides, the parts of your program that are really *worth* optimizing are astonishly few. Don't bother using assembler until you need to. Diez From gherron at islandtraining.com Fri May 16 20:08:20 2008 From: gherron at islandtraining.com (Gary Herron) Date: Fri, 16 May 2008 17:08:20 -0700 Subject: numpy.frombuffer != unpack() ?? In-Reply-To: References: Message-ID: <482E21F4.1090809@islandtraining.com> Marlin Rowley wrote: > All: > > Say I have an array: > > a = (['rrrrggggbbbbaaaa'],['rrrrggggbbbbaaaa']) > > How do I make it so that I now have: > > starting with first element (a[0]) > new_arr[0] = 'r' > new_arr[1] = 'g' > new_arr[2] = 'b' > new_arr[3] = 'a' > new_arr[4] = 'r' > ..... > > continuing "through" a[1] with the same new_arr > new_arr[N] = 'r' > new_arr[N+1] = 'g' > .... > > -M Numpy can do this for you. First, do you really mean the array to contain lists of one string each? If so: >>> import numpy >>> a = (['rrrrggggbbbbaaaa'],['rrrrggggbbbbaaaa']) >>> b = numpy.frombuffer(''.join(sum(a,[])),dtype='S1') # Kind of a kludge here >>> b array(['r', 'r', 'r', 'r', 'g', 'g', 'g', 'g', 'b', 'b', 'b', 'b', 'a', 'a', 'a', 'a', 'r', 'r', 'r', 'r', 'g', 'g', 'g', 'g', 'b', 'b', 'b', 'b', 'a', 'a', 'a', 'a'], dtype='|S1') >>> b.shape=(2,4,4) >>> b array([[['r', 'r', 'r', 'r'], ['g', 'g', 'g', 'g'], ['b', 'b', 'b', 'b'], ['a', 'a', 'a', 'a']], [['r', 'r', 'r', 'r'], ['g', 'g', 'g', 'g'], ['b', 'b', 'b', 'b'], ['a', 'a', 'a', 'a']]], dtype='|S1') >>> c = b.transpose((2,0,1)) >>> c array([[['r', 'g', 'b', 'a'], ['r', 'g', 'b', 'a']], [['r', 'g', 'b', 'a'], ['r', 'g', 'b', 'a']], [['r', 'g', 'b', 'a'], ['r', 'g', 'b', 'a']], [['r', 'g', 'b', 'a'], ['r', 'g', 'b', 'a']]], dtype='|S1') >>> d=c.copy() # To make it contiguous >>> d.shape = (32,) >>> d array(['r', 'g', 'b', 'a', 'r', 'g', 'b', 'a', 'r', 'g', 'b', 'a', 'r', 'g', 'b', 'a', 'r', 'g', 'b', 'a', 'r', 'g', 'b', 'a', 'r', 'g', 'b', 'a', 'r', 'g', 'b', 'a'], dtype='|S1') Done. Cool no? Gary Herron > > > > > ------------------------------------------------------------------------ > From: marlin_rowley at hotmail.com > To: robert.kern at gmail.com; python-list at python.org > Subject: RE: numpy.frombuffer != unpack() ?? > Date: Fri, 16 May 2008 17:31:30 -0500 > > Thank you! That solved it! > > -M > > > ------------------------------------------------------------------------ > > > To: python-list at python.org > > From: robert.kern at gmail.com > > Subject: Re: numpy.frombuffer != unpack() ?? > > Date: Fri, 16 May 2008 17:25:00 -0500 > > > > Marlin Rowley wrote: > > > All: > > > > > > I'm getting different floating point values when I use numpy > vs. unpack(). > > > > > > frgba = numpy.frombuffer(, dtype=float32) > > > buffer = unpack("!f", byte) > > > > > > frgba[0] != buffer[0] > > > > > > why? This is forcing me use the unpack() function since it's > giving me > > > the correct values. What am I doing wrong? > > > > Endianness, perhaps? '!' specifies big-endian data (an alias for > '>'). Most > > likely, you are on a little-endian platform. All of the dtypes > in numpy default > > to the native-endianness unless specified. If you want to read > big-endian data > > using numpy, do this: > > > > frgba = numpy.frombuffer(, dtype='>f') > > > > If you have any more problems with numpy, please join us on the > numpy mailing > > list. When reporting problems, please try to provide a small but > complete > > snippet of self-contained code, the output that you got, and > explain the output > > that you expected to get. Thank you. > > > > http://www.scipy.org/Mailing_Lists > > > > -- > > Robert Kern > > > > "I have come to believe that the whole world is an enigma, a > harmless enigma > > that is made terrible by our own mad attempt to interpret it as > though it had > > an underlying truth." > > -- Umberto Eco > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > ------------------------------------------------------------------------ > E-mail for the greater good. Join the i?m Initiative from > Microsoft. > > > > > ------------------------------------------------------------------------ > E-mail for the greater good. Join the i?m Initiative from Microsoft. > > > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list From bignose+hates-spam at benfinney.id.au Sat May 24 21:46:00 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 25 May 2008 11:46:00 +1000 Subject: Code correctness, and testing strategies References: <18c1e6480805241214t6c556e46r31170ea50d0eb1d5@mail.gmail.com> Message-ID: <87abif9mw7.fsf@benfinney.id.au> "D'Arcy J.M. Cain" writes: > Yes! One of the biggest advantages to unit testing is that you never > ever deliver the same bug to the client twice. More specifically, this is a benefit of putting all unit tests into an automated test suite, and running that test suite all the time during development so it's immediately clear when any of them fails due to a code change. It's not enough to *have* the unit tests, nor is it enough to only run them at certain times. They need to run after every change, so the feedback is immediate and local to the change that was made. (good sigmonster, have a cookie) -- \ "Program testing can be a very effective way to show the | `\ presence of bugs, but is hopelessly inadequate for showing | _o__) their absence." -- Edsger Dijkstra | Ben Finney From goodz158 at yahoo.com Thu May 1 02:58:03 2008 From: goodz158 at yahoo.com (Good Z) Date: Wed, 30 Apr 2008 23:58:03 -0700 (PDT) Subject: Is vs Equality Operator Message-ID: <706397.16040.qm@web35903.mail.mud.yahoo.com> Hello, I am having problem in using is. Here is what i am doing. x='' if x is None or x is '': return 1 The above statement does not return value 1. If i changed the above check to if x == None or x == '': return 1 Now it works fine. Any idea. What is happening here. I am using python 2.4.4 on ubuntu. Mike ____________________________________________________________________________________ Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try it now. http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ -------------- next part -------------- An HTML attachment was scrubbed... URL: From tarun.kap at gmail.com Thu May 22 15:56:23 2008 From: tarun.kap at gmail.com (TkNeo) Date: Thu, 22 May 2008 12:56:23 -0700 (PDT) Subject: 2 different versions of python compiling files. References: <22196543-5198-4424-a4e9-db83894b0385@a70g2000hsh.googlegroups.com> Message-ID: On May 22, 2:44 pm, Hans Nowak wrote: > TkNeo wrote: > > I am trying to upgrade from python 2.3 to 2.4 but not all machines can > > be upgraded. Can you guys tell me if this scenario is possible. > > > 1. Any machine that uses .py files that use libraries that require 2.4 > > will have 2.4 on it. > > 2. rest of the machines will have 2.3 > > > now there is a shared drive. lets say i write a new library called > > testlib.py and put it on the shared drive .. when a script uses it > > from a 2.4 based machine, it will generate a testlib.pyc and leave it > > on the shared drive. going forward that .pyc is used until the > > original lib is changed. now lets say a 2.3 based machine is trying to > > use that lib. it will try to use that pyc file which was compiled by > > py2.4. will it work or crash ? > > It should work, as long as the original .py file is still there. Each Python > version will check for a .pyc file *corresponding to that version* (e.g. Python > 2.4 will look for a .pyc file compiled with 2.4), and create one if it doesn't > exist, overwriting any existing .pyc file in the process. > > If the original .py file is *not* there, it will most likely not work. If you > try to import a .pyc file with the wrong version number, you get something like > this: > > >>> import foo > Traceback (most recent call last): > File "", line 1, in ? > ImportError: Bad magic number in foo.pyc > > I'm not sure what would happen if multiple Pythons try to write a .pyc file at > the same time, though... > > -- > Hans Nowak (zephyrfalcon at gmail dot org)http://4.flowsnake.org/ The original .py will always be there but you know what, multiple python versions from different computers do access that one library at the same time. Anyone know a possible solution ? From kyosohma at gmail.com Mon May 5 16:54:59 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 5 May 2008 13:54:59 -0700 (PDT) Subject: Browser + local Python-based web server vs. wxPython References: Message-ID: On May 5, 9:22?am, pyt... at bdurham.com wrote: > I'm looking at rewriting some legacy VB applications and am pondering > which of the following techniques to use: > > 1. Browser based GUI with local web server (Browser + > wsgiref.simple_server) (I'm assuming that simple_server is class I want > to build from for a local web server) > > -OR- > > 2. wxPython based GUI > > My thought is that a browser/local web server setup may be more portable > to mobile environments than wxPython and may offer a way to scale a > single user offline application to a multi-user online application using > a remote vs. local web server. Some groups of users may feel more > comfortable with a browser based interface as well. > > I'm looking for feedback from anyone that has pondered the same question > as well as any pros/cons or tips from anyone that has chosen the > browser/lcoal web server route. > > Thanks, > > Malcolm wxPython is great for desktop applications on Linux, Windows and Mac. However, there isn't much support for it on mobile platforms at the moment. If you're thinking your application will be mostly for mobile environments, then you'll probably want to look at Python web frameworks, Jython or Silverlight + IronPython (if you want to use Python on the web). The most popular Python web frameworks seem to be TurboGears, Django, Pylons, CherryPy and mod_python. I know you can run TurboGears, Django and CherryPy locally as well as with Apache, so they might garner more of your attention. Mike From bj_666 at gmx.net Sat May 24 07:38:58 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 24 May 2008 11:38:58 GMT Subject: Assignment and comparison in one statement References: <4r9lg5xvm8.ln2@joeserver.homelan.net> Message-ID: <69qd2iF33dagrU6@mid.uni-berlin.de> On Sat, 24 May 2008 13:13:08 +0200, Johannes Bauer wrote: > George Sakkis schrieb: > >>> However, this "assignment and comparison" is not working. What's the >>> "Python way" of doing this kind of thing? >> >> The most obvious and readable of course: use two statements, as one >> should do regardless of the language, instead of resorting to error- >> prone hacks. > > As I said in the reply to Carl, this might be okay for if-clauses, but > is bothering me with while-loops. Then try to write the ``while`` loop as ``for`` loop and move the comparison into a generator function, or use the two argument variant of `iter()`, or `itertools.takewhile()`. Ciao, Marc 'BlackJack' Rintsch From marco at sferacarta.com Tue May 6 10:59:42 2008 From: marco at sferacarta.com (Marco Mariani) Date: Tue, 06 May 2008 16:59:42 +0200 Subject: sed to python: replace Q In-Reply-To: <4820714b$0$34544$742ec2ed@news.sonic.net> References: <48180348$0$34534$742ec2ed@news.sonic.net> <4820714b$0$34544$742ec2ed@news.sonic.net> Message-ID: Raymond wrote: > Aren't sed, awk, grep, and perl the reference implementations of search > and replace? I don't know about "reference implementations", but I daresay they are a mess w.r.t. usability. From wolfgang.grafen at ericsson.com Tue May 13 07:44:27 2008 From: wolfgang.grafen at ericsson.com (Wolfgang Grafen) Date: Tue, 13 May 2008 13:44:27 +0200 Subject: Best way to delimit a list? In-Reply-To: <57129f75-b496-40fc-8b2d-d93ba544d4c5@u6g2000prc.googlegroups.com> References: <57129f75-b496-40fc-8b2d-d93ba544d4c5@u6g2000prc.googlegroups.com> Message-ID: dannywebster at googlemail.com schrieb: > Hi - I have a list returned from popen/readlines, and am wondering how > to go about iterating over each item which was returned (rather than > currently having the whole lot returned). > > so far: > >>>> f=os.open("./get_hostnames").readlines > > returns ['host1 host2 host3 ... hostN\n]' > > i'd like to be in a position to iterate through these, grabbing each > host. I have played with transmuting to a str, and using split, and > this works, but I get the subscript brackets from the list output as > expected, as the list output is now a string literal, and this is not > what I want - and I think it's a bit long-winded to do a search 'n > replace on it - hence why I ask in the subject what's the best way. > >>>> f=str(f) >>>> f.split() > ["['host1","host2", ... ,"hostN\n']"] > > > Any help is highly appreciated > untested: f=" ".join(f) f.split() Best regards Wolfgang From chris.hulan at gmail.com Thu May 22 17:45:17 2008 From: chris.hulan at gmail.com (Chris Hulan) Date: Thu, 22 May 2008 14:45:17 -0700 (PDT) Subject: Using os.walk to return files in subdirectories References: <25f9ae68-e6c3-4c50-a43b-eda5c17f36bd@e39g2000hsf.googlegroups.com> Message-ID: On May 22, 5:24 pm, dj wrote: ...snip... > for d in dir: > if end == d: dir is the list of subdirs of the current dir, and the current dir is NOT a subdir of itself so end == dir is never true Are you trying to get a list per subdir? cheers From castironpi at gmail.com Sat May 17 22:22:39 2008 From: castironpi at gmail.com (castironpi) Date: Sat, 17 May 2008 19:22:39 -0700 (PDT) Subject: morning in Python References: <409ea9f1-9774-4bf2-abac-2daf997bc97f@c65g2000hsa.googlegroups.com> <143b1593-658c-4a1c-9826-72af517b3ad0@m36g2000hse.googlegroups.com> Message-ID: <91d4cf3b-e71f-4e73-90da-db0735f34035@c65g2000hsa.googlegroups.com> On May 17, 5:35?am, Ivan Illarionov wrote: > On Sat, 17 May 2008 02:57:08 -0700, castironpi wrote: > > Full day later, I think it, to emphasize state, would prioritize > > context. ?The reason for the huge ramble was, believe it or not, > > namespace conflict... as though any other states around here might nose > > in. ?And thanks to 'inhahe' for coming back with the question. ?...Which > > would explain next move to 'prioritize context'. Context is a high > > priority for people. > > > I'm proposing to start on one on a computer. ?The first things a > > computer 'knows' are the boot, keyboard, & mouse. ?Yet on another scale, > > the first things it knows are BIOS, file system, and OS. ?On still > > another, the only thing it knows are interruptions. ?Knowledge is > > important to context. ?(The scales are ram on disk on, ram on disk off, > > and ram off, which may tell of the currency they and their power are > > bought with. ?Thence, we should be getting different values for lengths > > of time.) > > > (Furthermore, we're all on different longitudes -and- latitudes.) > > > Context comes from motion, perception, and composite perception > > (reperception e.a.o. memory). ?There is some reason to believe that > > motion and sight are different senses, perhaps so with stationary sound > > (gatcha) and mobile sound too. ?Do you go deaf of a tone after prolonged > > duration? ?That makes computers valuable commodities*: they have a > > symbolic interface, which no other unlive objects have. ?They have both > > mouse and keyboard. > > > *I'm sure there is a precision to wants: what magnitude of what types of > > action a person wants from a day and for a time-- what energy states > > they go to and from (note phone on come to and come from.) > > > Therefore, context should originate in mouse and keyboard. > > > Humans have symbolic know-how: knowledge of how to convey intent > > digitally, though it may be there is no interpolation of 'intent per > > mouse-or-key', even though people are prone to empathize with faces. > > However, if you start with a 'me' and a 'no', you can get pretty > > logical. > > > Intent per mouse-and-key isn't necessarily scalar, three-dimensional, or > > rationally dimensional (?), though they do have magnitudes per mass and > > volume. ?The contingent of 'rationally dimensional' is having or > > beknowing/benouncing an orthonormal basis. ?Incidentally, '''orthography > > of a language specifies the correct way of using a specific writing > > system to write the language. .. Orthography is derived from Greek ????? > > orth?s ("correct") and ??????? gr?phein ("to write").''' - wikipedia. > > > Further incidentally, context and state may have more important in > > common than priority and price: privacy and safety are involved ex > > hypothesi. ?Incidentally = ... > > > It is not clear that the first (cheapest best) human-computer language > > is a computer language, though if two were orthonormal in comparison to > > life, Python's fine. ?Not my first. > > > In privacy concerns, it is not clear that duals aren't primitives to > > humans. ?What's a brain primitive? ?Lol: what is a primitive brain? > > > On May 16, 10:58?am, "inhahe" wrote: > >> I'm not an expert in this but what does it mean to emphasize state? ?It > >> seems the opposite of that would be a) functional programming, and b) > >> passing parameters instead of using global or relatively local > >> variables. And maybe c) coroutines (generators as implemented in > >> Python), although perhaps coroutines could be said to emphasize state > >> inasmuch as they go out of their way to capture, objectify and reuse it > >> (Stackless' microthreads, even moreso). ?And Python seems to be > >> well-noted for implementing some functional programming methodology, > >> and as for passing parameters it's just as object-oriented as the rest > >> of them. > > >> But as I said, I'm not an expert, so let me know if I've gone astray.. > > >> > I have a proposition to ask you all: Python emphasizes state. ?Is it > >> > true?- Hide quoted text - > > >> - Show quoted text - > > Castironpi, > > I love you! You remind me of all the kittens and puuppies I had when I > was a child. > > I #define this. Hope your database could give us something funny again. > > -- Ivan- Hide quoted text - > > - Show quoted text - I have to talk about crossing threats. But talking about threads is like talking, and people talk about food. What are some threats to be scared of? What about threads to be thunder? From anand.prabhakar.patil at gmail.com Thu May 29 04:44:13 2008 From: anand.prabhakar.patil at gmail.com (Anand Patil) Date: Thu, 29 May 2008 09:44:13 +0100 Subject: code of a function In-Reply-To: <483E6B8D.6020307@islandtraining.com> References: <8a6035a00805290110v67ed53d0j8ae9c93b3089565c@mail.gmail.com> <483E6B8D.6020307@islandtraining.com> Message-ID: On May 29, 2008, at 9:38 AM, Gary Herron wrote: > Dark Wind wrote: >> Hi, >> >> Is there any command in Python which gives the code for a function >> like just typing the name of a function (say svd) in R returns its >> code. >> >> Thank you > > Nope. If you're using IPython, you can do svd?? . From java.oke at gmail.com Thu May 8 17:39:19 2008 From: java.oke at gmail.com (j.oke) Date: Thu, 8 May 2008 14:39:19 -0700 (PDT) Subject: The Importance of Terminology's Quality References: Message-ID: <0c3c6e48-32cf-4fdd-883e-348f4436a309@y38g2000hsy.googlegroups.com> xahlee at gmail.com ha scritto: > [bli bla blo, blu blu bum bum bam bam bim bim bim...] don't know Y, by your arty-phycial excerptions always seem chinese me... -JO From cwitts at gmail.com Thu May 15 08:30:57 2008 From: cwitts at gmail.com (Chris) Date: Thu, 15 May 2008 05:30:57 -0700 (PDT) Subject: datamining .txt-files, library? References: <8ab6802f-ac2c-4492-b793-704126567a8e@a1g2000hsb.googlegroups.com> Message-ID: <96f60dc3-fe60-45fa-befe-70d7ae5a330a@d77g2000hsb.googlegroups.com> On May 15, 2:27?pm, globalrev wrote: > i have a big collection of .txt files that i want to open and parse to > extract information. > > is there a library for this or maybe even built in? os.open to open the files and iterate through it and built in string functions to parse it. From gandalf at shopzeus.com Mon May 19 09:28:36 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Mon, 19 May 2008 15:28:36 +0200 Subject: TPCServer and xdrlib In-Reply-To: <5d56b071-1184-4112-bd82-89c00975b939@m73g2000hsh.googlegroups.com> References: <5d56b071-1184-4112-bd82-89c00975b939@m73g2000hsh.googlegroups.com> Message-ID: <48318084.5040208@shopzeus.com> >> I'm trying to write a multi threaded TPC server. I have used xmlrpc >> > > How exactly did you come to the conclusion that your server must be > multi threaded ? > I don't think that it is important. But if you are interested: - yes, the server will probably be I/O bound, not CPU bound - I'm have experience with thread programming, but not with twisted >> - I have to send larger amounts of data, the overhead of converting to >> XML and parsing XML back would be too much pain >> > > - What's the expected amount of data you have to transfer ? > I cannot predict. But I will be trasferring image files which would be silly to do with XML. > - What's the expected network bandwidth ? > It cannot be determined in advance. > - What's the expected acceptable transfer time ? > Not known. > - How many users are expected to be transfering data at the same time ? > The server should be scaleable up to hundreds of users. (I'm just trying to answer your questions, if that helps to answer mine.) > Did you consider gzipping your XML (or YAML) packets ? Would the > transfer time be acceptable in this case ? > No. "Image binary data -> base64encode -> XML -> gzip" - looks very silly. It cannot be efficient. Do you have better ideas? >> BTW I do not care about the clients - they must trust the server side. >> > > Oh, he said he _doesn't care about the clients_ ! ;-) > I meant *safety* here: clients are going to download program updates from the server. So if they do not trust the server then they should not use it. The server is different: it must be safe against external attacks. Maybe it was my bad English? Sorry for the misunderstanding. > In general I would avoid that. Try to better estimate the speed > requirements, to see if you really need do to this. > I cannot predict "acceptable speed" requirements, but I can tell that there will be some clients downloading 100MB report files from the server, so I presume that I will need a progress bar. I think that I need to develop my own protocol for this, and probably the underlying layer should use binary representation. >> Before I start re-inventing the wheel: >> >> - Is there another (already existing) higher level framework that I can >> try? It should be safe and fast, that is the only restriction. >> > > There's "Twisted". > http://twistedmatrix.com/projects/core/documentation/howto/servers.html > Yes, I tried twisted before and I did not like it. It forces me to things that I do not want to do. (I cannot tell what it was - it was two years ago.) >> - Do you think that it is a good idea to use xdrlib? I haven't seen >> projects using it directly. For me it is like the rotor module was - it >> > > It's probably the best way to send binary stuff over the network. > But, again, I would avoid doing so. > It is NOT the best way. Just to tell one example: big endian / little endian integers. Definitely I need some encoding. (But if you are right and this is the best way, why would you avoid?) L From goldnery at gmail.com Thu May 29 20:37:53 2008 From: goldnery at gmail.com (Gandalf) Date: Thu, 29 May 2008 17:37:53 -0700 (PDT) Subject: As I promised couple of day a go Message-ID: <2b5359a8-1e3a-46ef-bf24-0162126cc201@26g2000hsk.googlegroups.com> When we discuss a global window events. and i wanted to generate event when the user click on a key out of my application. I promised that if will found how to do it i'l show you. I found this article which explain very simply how to hook py width pyHook lib http://mindtrove.info/articles/monitoring-global-input-with-pyhook/ now the following code combine between wxpython and phHook. I know this code probably looks not efficient and unorganized. I'm really new width this stuff, but it works fine. before you try it you better install the pyHook from the following link http://mindtrove.info/articles/monitoring-global-input-with-pyhook/ *note theirs an image url you would have to edit in order for it to be work #!/usr/bin/python # menu1.py import wx import wx.html as html import pythoncom, pyHook class MyFrame(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, wx.Size(400, 400)) self.SetBackgroundColour('#fef9d8') panel= wx.Panel(self, -1, style=wx.SIMPLE_BORDER, size=(400, 100)); aaa= html.HtmlWindow(panel, -1, style=wx.SIMPLE_BORDER, size=(250, 60)) aaa.LoadPage('aa.html') cnrl=wx.TextCtrl(aaa, 11, '', (20, 20), (120, 20)) wx.Button(aaa, 12, "Translate", (160, 19)) self.Bind(wx.EVT_BUTTON, self.OnClick, id=12) quite = wx.BitmapButton(panel, 20, wx.Bitmap('py/x.gif'),(370, 0), (20, 20), style=wx.ALIGN_RIGHT ) self.Bind(wx.EVT_BUTTON, self.Yehuda, id=20) self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown) self.SetFocus() font1= wx.Font(12, wx.NORMAL, wx.NORMAL, wx.BOLD) font2=wx.Font(10, wx.NORMAL, wx.NORMAL, wx.NORMAL) text1=wx.StaticText(panel, 15, "Hello" ,(30, 70) , style=wx.ALIGN_CENTRE) text1.SetFont(font1) text2=wx.StaticText(panel, -1, "Peace, By, Good by", (30, 100), style=wx.ALIGN_CENTRE ) text2.SetFont(font2) self.Show() self.Centre() def Yehuda(self, event): self.Hide() def OnKeyDown(self, event): keycode = event.GetKeyCode() if keycode == wx.WXK_ESCAPE: ret = wx.MessageBox('Are you sure to quit?', 'Question', wx.YES_NO | wx.NO_DEFAULT, self) if ret == wx.YES: self.Close() event.Skip() def OnClick(self,event): text1.SetLabel(cnrl.GetValue()) def OnPaint(self, event): dc = wx.PaintDC(frame) dc.DrawBitmap(frame.bitmap, 20, 20) class MyTaskBarIcon(wx.TaskBarIcon): def __init__(self, frame): wx.TaskBarIcon.__init__(self) self.frame = frame self.SetIcon(wx.Icon('menu1.png', wx.BITMAP_TYPE_PNG)) self.Bind(wx.EVT_MENU, self.OnTaskBarActivate, id=1) self.Bind(wx.EVT_MENU, self.OnTaskBarDeactivate, id=2) self.Bind(wx.EVT_MENU, self.OnTaskBarClose, id=3) #self.frame.Bind(wx.EVT_CLOSE, self.OnClose) def CreatePopupMenu(self): menu = wx.Menu() menu.Append(1, 'Show') menu.Append(2, 'Hide') menu.Append(3, 'Close') return menu def OnTaskBarClose(self, event): self.frame.Close() def OnTaskBarActivate(self, event): if not self.frame.IsShown(): self.frame.Show() def OnTaskBarDeactivate(self, event): if self.frame.IsShown(): self.frame.Hide() def OnKeyboardEvent(event): global x, frame, frame2 if event.KeyID == 162: if x==1: frame.Close() frame2= MyFrame(None, -1, 'frame') x=0 else: frame2.Close() frame= MyFrame(None, -1, 'frame2') x=1 x=1 app = wx.App() frame = MyFrame(None, -1, 'Babylon') frame.tskic = MyTaskBarIcon(frame) frame.Show(True) app.SetTopWindow(frame) hm = pyHook.HookManager() hm.KeyDown = OnKeyboardEvent hm.HookKeyboard() pythoncom.PumpMessages() app.MainLoop() From george.sakkis at gmail.com Sat May 31 10:54:56 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Sat, 31 May 2008 07:54:56 -0700 (PDT) Subject: accumulator generators References: Message-ID: <7a41e745-956b-4582-bd61-eac699f1d892@34g2000hsf.googlegroups.com> On May 31, 4:19?am, Arnaud Delobelle wrote: > Cameron writes: > > I was reading this Paul > > Graham article and he builds an accumuator generator function in > > the appendix. His looks like this: > > >
> > def foo(n):
> > ? s = [n]
> > ? def bar(i):
> > ? ? s[0] += i
> > ? ? return s[0]
> > ? return bar
> > 
> > > Why does that work, but not this: > > >
> > def foo(n):
> > ? s = n
> > ? def bar(i):
> > ? ? s += i
> > ? ? return s
> > ? return bar
> > 
> > Others have explained why, but this looks like "pythonized LISP" to > me. ?I would rather use a generator function: > > def foo(n): > ? ? while True: > ? ? ? ? n += yield n > > Although the problem is that you can't send it values the first time > round! > > >>> bar = foo('s') > >>> bar.next() > 's' > >>> bar.send('p') > 'sp' > >>> bar.send('am') > > 'spam' > > But: > > >>> bar = foo(3) > >>> bar.send(2) > > Traceback (most recent call last): > ? File "", line 1, in > TypeError: can't send non-None value to a just-started generator I find the "pythonized LISP" solution more understandable, even without the initial next() requirement. YMMV George From http Thu May 29 20:17:58 2008 From: http (Paul Rubin) Date: 29 May 2008 17:17:58 -0700 Subject: UNIX credential passing References: Message-ID: <7xlk1sbq6h.fsf@ruckus.brouhaha.com> Kris Kennaway writes: > I want to make use of UNIX credential passing on a local domain socket > to verify the identity of a user connecting to a privileged > service. However it looks like the socket module doesn't implement > sendmsg/recvmsg wrappers, and I can't find another module that does > this either. Is there something I have missed? There is a patch for it attached to an RFE in the python bug tracker, I forget which one. Try searching for sendmsg or ancillary messages or SCM_RIGHTS in the tracker. From wuwei23 at gmail.com Thu May 29 19:20:49 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 29 May 2008 16:20:49 -0700 (PDT) Subject: code of a function References: <8a6035a00805290110v67ed53d0j8ae9c93b3089565c@mail.gmail.com> <483E6B8D.6020307@islandtraining.com> Message-ID: <873d04c4-c902-4ed5-8c57-8af8c037f094@c19g2000prf.googlegroups.com> On May 30, 8:54 am, Alan Isaac wrote: > Anand Patil wrote: > > If you're using IPython, you can do svd?? . > > http://www.scipy.org/doc/numpy_api_docs/numpy.linalg.linalg.html > > hth, > Alan Isaac That wasn't a question :) In IPython, '?' is roughly equivalent to 'help()', whereas '??' displays the code, if possible: IPython 0.8.2 -- An enhanced Interactive Python. ? -> Introduction and overview of IPython's features. %quickref -> Quick reference. help -> Python's own help system. object? -> Details about 'object'. ?object also works, ?? prints more. In [1]: from functools import wraps In [2]: wraps?? Type: function Base Class: String Form: Namespace: Interactive File: c:\python25\lib\functools.py Definition: wraps(wrapped, assigned=('__module__', '__name__', '__doc__'), updated=('__dict__',)) Source: def wraps(wrapped, assigned = WRAPPER_ASSIGNMENTS, updated = WRAPPER_UPDATES): """Decorator factory to apply update_wrapper() to a wrapper function Returns a decorator that invokes update_wrapper() with the decorated function as the wrapper argument and the arguments to wraps() as the remaining arguments. Default arguments are as for update_wrapper(). This is a convenience function to simplify applying partial() to update_wrapper(). """ return partial(update_wrapper, wrapped=wrapped, assigned=assigned, updated=updated) Which is very handy, like most of IPython. From tjreedy at udel.edu Sun May 11 16:14:29 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 11 May 2008 16:14:29 -0400 Subject: Is using range() in for loops really Pythonic? References: <482657ca$0$25026$607ed4bc@cv.net> <41078222-aec0-4e8b-8a1f-945cdf814498@m73g2000hsh.googlegroups.com> Message-ID: "XLiIV" wrote in message news:41078222-aec0-4e8b-8a1f-945cdf814498 at m73g2000hsh.googlegroups.com... On May 11, 4:19 am, John Salerno wrote: > I know it's popular and very handy, but I'm curious if there are purists > out there who think that using something like: > > for x in range(10): > #do something 10 times > > is unPythonic. The reason I ask is because the structure of the for loop > seems to be for iterating through a sequence. It seems somewhat > artificial to use the for loop to do something a certain number of > times, like above. > > Anyone out there refuse to use it this way, or is it just impossible to > avoid? |The range() function returns a list and list is a sequence, isn't? yes, for loops iterate thru any iterable From skanemupp at yahoo.se Fri May 2 13:03:47 2008 From: skanemupp at yahoo.se (globalrev) Date: Fri, 2 May 2008 10:03:47 -0700 (PDT) Subject: pygame.key.get_pressed[K_a], K_a is not defined!? References: <680su7F2q6qo2U1@mid.uni-berlin.de> Message-ID: <8f3fead6-895a-4ee4-9fff-2190775da3e9@w7g2000hsa.googlegroups.com> print pygame.K_a displays 97 btw. what does that mean? i though it would return true or false or 0 or 1. From deets at nospam.web.de Fri May 30 12:03:54 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 30 May 2008 18:03:54 +0200 Subject: running on WinPC + comunication via USB In-Reply-To: <746283b7-5ce8-47ba-aff9-47fe197762fb@e53g2000hsa.googlegroups.com> References: <746283b7-5ce8-47ba-aff9-47fe197762fb@e53g2000hsa.googlegroups.com> Message-ID: <6aamrhF16ulv6U1@mid.uni-berlin.de> martin.nkm at googlemail.com schrieb: > Hello, I have two questions. > 1/ If I want to use Python and let my WinPC communicate via RS-232 > with external embedded computer I know there is a pyserial module, > which I can use it. But what will happen if I want to replace RS-232 > by USB? I know I can have virtual COM port, but all the configuration > parameters basically refer to RS-232 parameters - baudrate, bits, > stopbits, parity. In case of USB that's a nonsense I think. Does > anybody know? Depending on the setup - no, it's the exact same thing. If e.g. the usb-device is a usb2serial converter or otherwise offers it's serveces as a serial-like device, it should work. Additionally, there is libusb + a python-wrapping for that. > 2/ Second is a basic question. Do I need also cygwin running on my > Windows PC to get running Python scripts? Or is that Python > interpreter (Win executable) self efficient? Thanks. No cygwin needed. In fact you need to be careful *not* to mix python and cygwin-python. They can happily co-exist - but installing 3rd-party-packages for one doesn't imply they are available for the other. Diez From castironpi at gmail.com Wed May 14 11:31:14 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 14 May 2008 08:31:14 -0700 (PDT) Subject: pretty generic question Message-ID: <3561bbab-6335-4074-9cd3-c3e3b05df195@34g2000hsf.googlegroups.com> I have to talk about coding. I'm thinking about traffic, freight, scheduling, microcontrols, and acoustics. I have pretty basics understandings of the controls of computers. My knowledge is a little contrary or rare; I specialize in information interfaces, but they're not very expensive to copy, i.e. to look at again. I am capable of drawing marginal distinctions from the world in to code. My specialty does provide a resource for library design for further information systems. From python at bc90021.net Sun May 11 13:10:14 2008 From: python at bc90021.net (bc90021) Date: Sun, 11 May 2008 17:10:14 GMT Subject: File Creation Not Working In A Thread Class? Message-ID: Hi All, Thanks in advance for any and all help! I have this code: g = open(fileName, 'a') where fileName is defined before the line it's used in. It works fine when I use it outside a thread class. When I put the same line in a thread class, it no longer works, and I get an error: IOError: [Errno 2] no such file u'fileName' Are threads not allowed to create files? From d3vvnull at gmail.com Thu May 22 23:13:54 2008 From: d3vvnull at gmail.com (Michael Mabin) Date: Thu, 22 May 2008 22:13:54 -0500 Subject: MVC In-Reply-To: <8a269063-ae96-4707-afdc-5d2c9270e0ff@a9g2000prl.googlegroups.com> References: <8a269063-ae96-4707-afdc-5d2c9270e0ff@a9g2000prl.googlegroups.com> Message-ID: <170543c70805222013x3fad3096q5bca73874ee6631e@mail.gmail.com> In fact, the Pylons web framework is geared toward the MVC approach. http://pylonshq.com/ On Thu, May 22, 2008 at 7:48 PM, George Maggessy wrote: > Hi Gurus, > > I'm a Java developer and I'm trying to shift my mindset to start > programming python. So, my first exercise is to build a website. > However I'm always falling back into MVC pattern. I know it's a > standard, but the implementation language affects the use of design > patter. So, here goes my question. Is that OK if I follow this? Should > I create DAOs, View Objects, Controllers and etc? Is there any sort of > best practice / standard to Python? > > Cheers, > George > -- > http://mail.python.org/mailman/listinfo/python-list > -- | _ | * | _ | | _ | _ | * | | * | * | * | -------------- next part -------------- An HTML attachment was scrubbed... URL: From vivainio at gmail.com Sun May 11 16:28:57 2008 From: vivainio at gmail.com (Ville M. Vainio) Date: Sun, 11 May 2008 20:28:57 GMT Subject: File Creation Not Working In A Thread Class? References: <7qGVj.32505$KJ1.18416@newsfe19.lga> Message-ID: <87iqxkwpo4.fsf@gmail.com> bc90021 writes: > The error message was at the top of the thread (am I incapable of posting > it, or are you incapable of following a thread?), but here it is again: > > IOError: [Errno 2] no such file u'tempfileName' Typically, when you report an error message, it helps to paste the whole traceback. For example, it may be that you are seeing an error from an old version of the file that has quotes around tempfileName, or the error is coming from somewhere else. But to answer your original question: no, there are no problems with threading and files, and this is just simple human mistake somewhere. From larry.bates at websafe.com` Thu May 22 19:14:35 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Thu, 22 May 2008 18:14:35 -0500 Subject: ctypes help In-Reply-To: <6a3247f6-3ea2-4c8c-b66b-43f31878fb01@z72g2000hsb.googlegroups.com> References: <6a3247f6-3ea2-4c8c-b66b-43f31878fb01@z72g2000hsb.googlegroups.com> Message-ID: gianluca wrote: > Hy, > I need help about use dll with ctypes. I've compiled my dll C library > and I copied it in c:\windows\system32. When I load it with > "myDLL=cdll.LoadLibrary(find_library("myDLL.dll"))" It seem all OK but > python don't see the dll function. with dir(myDLL) I've only this: > ['_FuncPtr', '__class__', '__delattr__', '__dict__', '__doc__', > '__getattr__', '__getattribute__', '__getitem__', '__hash__', > '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', > '__repr__', '__setattr__', '__str__', '__weakref__', '_handle', > '_name'] > > Could anybody help me > > Thanks > > Gianluca Since it isn't python, dir can'd do much introspection on the object to produce the type of output you desire. You have to know the functions (methods) that you want to call in your dll and call them. -Larry Bates From vlastimil.brom at gmail.com Mon May 5 08:59:30 2008 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Mon, 5 May 2008 14:59:30 +0200 Subject: using sqlite3 - execute vs. executemany; committing ... In-Reply-To: <18c1e6480805041536x7287d23ds9d9bfcf6ec73e123@mail.gmail.com> References: <9fdb569a0805031431r6666e950pc6dbc8aab6e36684@mail.gmail.com> <18c1e6480805040214m5ecd0b27t9800bfc4a39daec8@mail.gmail.com> <9fdb569a0805041407s75c8ad3bsc08c8bac87fa0d83@mail.gmail.com> <18c1e6480805041536x7287d23ds9d9bfcf6ec73e123@mail.gmail.com> Message-ID: <9fdb569a0805050559q83999d4v6043acb94c9797d0@mail.gmail.com> > > > Thanks for further comments David, You are right, the choice of an appropriate data structure isn't easy; I described the requirements in an earlier post: http://mail.python.org/pipermail/python-list/2007-December/469506.html Here is a slightly modified sample of the text source I currently use in my present (ad hoc and quite dirty) code: Wi den L...n m...k gein den Pragern. Wen dy her czu T... vf dy vient wern gesampt czu hertin strit, dez m...s vs gein obint W... stunt s...t. Doch gar Sthir czu em kam, h...g W... sich ken em nom. Ez irgink ubil den L...: S... slug W...um daz houbt ab vil gern. Den Pragern mochtin dy L...ner nit intken, si slugin si, das si plutis hin runnen. Wi dem Stracka geschach, du er do heim sin husfrowin sach. Aus allin L...tern einer hin quom, der waz S...raka gnant mit dem nom. Em ein vetil den rat gab, ... ======================================== The corresponding data stored as a dict look like the following dict (here sorted, at least on the highest level): (, , ... are ignored here, these are used for the text formatting for the gui and aren't retrieved any more) {0: {u'KC': u'12', u'VCC': u'0', u'KNJ': u'13', u'FN': u'21rb', u'VN': u'rn_1_vers_1'}, 13: {u'KC': u'12', u'VCC': u'0', u'KNJ': u'13', u'VN': u'rn_2_vers_1', u'FN': u'21rb'}, 39: {u'KC': u'12', u'VCC': u'1', u'KNJ': u'13', u'VN': u'1', u'VNJ': u'1', u'FN': u'21rb'}, 71: {u'KC': u'12', u'VCC': u'2', u'KNJ': u'13', u'FN': u'21rb', u'VNJ': u'2', u'VN': u'2'}, 102: {u'KC': u'12', u'VCC': u'2', u'KNJ': u'13', u'FN': u'21rb', u'VNJ': u'3', u'VN': u'3'}, 126: {u'KC': u'12', u'VCC': u'3', u'KNJ': u'13', u'VN': u'4', u'VNJ': u'4', u'FN': u'21rb'}, 144: {u'KC': u'12', u'VCC': u'3', u'KNJ': u'13', u'FN': u'21rb', u'VNJ': u'5', u'VN': u'5'}, 171: {u'KC': u'12', u'VCC': u'5', u'KNJ': u'13', u'VN': u'6', u'VNJ': u'6', u'FN': u'21rb'}, 199: {u'KC': u'12', u'VCC': u'6', u'KNJ': u'13', u'FN': u'21rb', u'VNJ': u'7', u'VN': u'7'}, 224: {u'KC': u'12', u'VCC': u'7', u'KNJ': u'13', u'VN': u'8', u'VNJ': u'8', u'FN': u'21rb'}, 264: {u'KC': u'12', u'VCC': u'7', u'KNJ': u'13', u'VN': u'9', u'VNJ': u'9', u'FN': u'21rb'}, 307: {u'KC': u'12', u'VCC': u'8', u'KNJ': u'13', u'FN': u'21rb', u'VNJ': u'10', u'VN': u'10'}, 348: {u'KC': u'12', u'VCC': u'9', u'KNJ': u'13', u'VN': u'_rn_1_vers_11', u'VNJ': u'00', u'FN': u'21rb'}, 373: {u'KC': u'12', u'VCC': u'9', u'KNJ': u'13', u'FN': u'21rb', u'VNJ': u'00', u'VN': u'rn_2_vers_11'}, 409: {u'KC': u'12', u'VCC': u'9', u'KNJ': u'13', u'VN': u'11', u'VNJ': u'11', u'FN': u'21rb'}, 444: {u'KC': u'12', u'VCC': u'10', u'KNJ': u'13', u'VN': u'12', u'VNJ': u'12', u'FN': u'21va'}, 480: {u'KC': u'12', u'VCC': u'11', u'KNJ': u'13', u'FN': u'21va', u'VNJ': u'13', u'VN': u'13'}} The keys are indices of the places in text, where the value of some tag/property ... changes; also the not changing values are copied in the inner dicts, hence after determining the index of the first such "boundary" preceeding the given text position (using bisect), the complete parameters can be retrieved with a single dict lookup. The other way seems much more complicated with this dict structure. I.e. it should be possible to find the index/or all indices/or the lowest index given some combinations of tag values - e.g. with the input: u'FN': u'21va' >> 444 should be found (as the lowest index with this value) for u'KC': u'12' AND u'VN': u'3' >> 102 (there are of course several other combinations to search for) I couldn't find an effective way to lookup the specific values of the inner dict (other than nested loops), probably using a set of tuples instead the inner dict would allow the checks for intersection with the input data, but this also seems quite expensive, as it requires the loop with checks over the entire data ... the same would probably be true for multiple reversed dicts keyed on the tags and containing the indices and the corresponding values (but I actually haven't tested the latter two approaches). The approach with sqlite I'm testing now simply contains columns for all relevant "tags" plus a column for text index; this way I find it quite easy to query the needed information in both directions (index >> tags; tag(s) >> index/indices) with the db selects - even as a beginner with SQL. The exact set of tags will be complete with the availability of all texts, then the gui will be adapted to make the user selections available (comboboxes). The searches are restricted to the predefined "properties", they are not manually queried. With the dynamic building of the db I just tried, not to hardcode all the tags, but it would be later possible to create the database tables and columns also in a controlled "static" way. Comparing the two versions I have, the dictionary approach really seems quite a bit more complicated (the data as well as the functions for the retrieval), than the sqlite3 version. For this app I really actually don't need a persistent db, nor should it be shared etc. The only used thing are the efficient lookup possibilities, which seemed to do what I needed (simply using intersect selects). Are there any ways how to implements this efficiently using the python builtin types? Greetings, Vlasta -------------- next part -------------- An HTML attachment was scrubbed... URL: From mensanator at aol.com Wed May 7 16:31:06 2008 From: mensanator at aol.com (Mensanator) Date: Wed, 7 May 2008 13:31:06 -0700 (PDT) Subject: howto print binary number References: Message-ID: <021f52a9-4d18-4e0a-acdd-3a08cca4a4e5@z72g2000hsb.googlegroups.com> On May 7, 3:13?pm, dmitrey wrote: > hi all, > could you inform how to print binary number? > I.e. something like > > print '%b' % my_number > > it would be nice would it print exactly 8 binary digits (0-1, with > possible start from 0) > > Thank you in advance, D The gmpy works good. >>> import gmpy >>> print gmpy.digits(66,2).zfill(8) 01000010 From bellman at lysator.liu.se Tue May 20 07:04:58 2008 From: bellman at lysator.liu.se (Thomas Bellman) Date: Tue, 20 May 2008 11:04:58 +0000 (UTC) Subject: Misuse of list comprehensions? References: <038e4418$0$27258$c3e8da3@news.astraweb.com> <7aa231e6-2f9c-4e90-8cd1-e839dc6940f2@x35g2000hsb.googlegroups.com> <69g3bmF31ttuuU3@mid.uni-berlin.de> Message-ID: "Diez B. Roggisch" writes: > bearophileHUGS at lycos.com wrote: >> The Example 2 builds a list, that is then thrown away. It's just a >> waste of memory (and time). > No, it doesn't. It uses append because it refers to itself in the > if-expression. So the append(c) is needed - and thus the assignment > possible but essentially useless. Yes it does. A list comprehension *always* creates a list. In this case it will be a list of None, since that is what list.append() returns. See this: >>> new=[] >>> s="This is a foolish use of list comprehensions" >>> [ new.append(c) for c in s if c not in new ] [None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None] Yes, you do get a correct result in 'new', but you *also* create a 17 long list with all elements set to None, that is immediately thrown away. -- Thomas Bellman, Lysator Computer Club, Link??ping University, Sweden "I refuse to have a battle of wits with an ! bellman @ lysator.liu.se unarmed person." ! Make Love -- Nicht Wahr! From gagsl-py2 at yahoo.com.ar Tue May 13 07:06:00 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 13 May 2008 08:06:00 -0300 Subject: feedparser References: <2b54d4370805130330m59602387g9f59b3f93097ca3d@mail.gmail.com> Message-ID: En Tue, 13 May 2008 07:30:44 -0300, Mike <42flicks at gmail.com> escribi?: > I'm trying to use the feedparser module (http://www.feedparser.org/). > > Is it possible to use this without running the setup program? > > I don't see why not, seems like I'm missing something obvious. > > My directory structure is: > > myprogram.py > /feedparser > /feedparser.py > > I know I can install the module in the modules directory but would like > to > avoid this for two reasons: I'm only using it for the one project so > would > like to keep it seperate, and if I move to a shared host I may not be > allowed to install additional modules (not sure if this is correct > though). The easiest way would be to put the single module feedparser.py in the same directory as your program (I don't completely get your reasons not to do that). OR put feedparser.py in some other directory that is already listed in sys.path. OR add the directory containing feedparser.py to sys.path, just at the beginning of your program. > I've tried: > > import feedparser > > import feedparser.feedparser > > from feedparser import feedparser > > What am I doing wrong? :) *IF* the directory 'feedparser' were a package (that is, if it contained a file __init__.py), then that last import statement would be valid. But I don't reccomend doing this; you're changing the module's environment. -- Gabriel Genellina From bruno.42.desthuilliers at websiteburo.invalid Fri May 23 03:50:30 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 23 May 2008 09:50:30 +0200 Subject: Python is slow In-Reply-To: References: Message-ID: <4836772e$0$6097$426a74cc@news.free.fr> Brad a ?crit : > cm_gui wrote: >> Python is slow. > > It ain't C++, but it ain't a punch card either... somewhere in between. > I find it suitable for lots of stuff. I use C++ when performance really > matters tho... right tool for the job. Learn a good interpreted language > (Pyhton) and a good compiled language (C or C++) LordHaveMercy(tm). Could you guys please learn what you're talking about? 1/ being interpreted or compiled (for whatever definition of these terms) is not a property of a language, but a property of an implementation of a language. 2/ actually, all known Python implementations compile to byte-code. > and you'll be just > fine. Until then, quit bitching. From mail at timgolden.me.uk Thu May 29 04:10:51 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 29 May 2008 09:10:51 +0100 Subject: How to get all the variables in a python shell In-Reply-To: References: Message-ID: <483E650B.5060902@timgolden.me.uk> lixinyi.23 at gmail.com wrote: > I'm currently working on a scientific computation software built in > python. > What I want to implement is a Matlab style command window <-> > workspace interaction. > > For example, you type 'a=1' in the command window, and you see a list > item named 'a' in the workspace. > You double click the icon of the item, and you see its value. You can > modify the value of the list item, > 1 -> 100 etc, after which if you go back to the command window and > type 'a' and press enter, you see that > varable a's value has been changed to 100. > > So my question is : if you have two DOS command windows running under > WINDOWS OS, how can you make them share the same internal variable > buffer? Or is there any easier way to implement such kind of > interaction? I stronly suggest you look at IPython [1]. To do what I think you're describing, you'd need to hack or reimplement the interpreter. And that's what they've done. ISTR that they even have a branch which is dealing with parallel instances. TJG [1] http://ipython.scipy.org/moin/ From detlev at die-offenbachs.de Sun May 18 09:48:33 2008 From: detlev at die-offenbachs.de (Detlev Offenbach) Date: Sun, 18 May 2008 15:48:33 +0200 Subject: howto use pylint from Eric IDE? References: Message-ID: dmitrey wrote: > Hi all, > > I have Eric 4.1.1, pylint and Eric pylint plugin installed, but I > cannot find how to use pylint from Eric IDE GUI. > Does anyone know? > > Thank you in advance, D. Project->Check->Run PyLint Regards, Detlev -- Detlev Offenbach detlev at die-offenbachs.de From miller.paul.w at gmail.com Sun May 25 19:56:58 2008 From: miller.paul.w at gmail.com (miller.paul.w at gmail.com) Date: Sun, 25 May 2008 16:56:58 -0700 (PDT) Subject: Performance of Python builtins References: <7xskw69cuc.fsf@ruckus.brouhaha.com> Message-ID: On May 25, 7:35?pm, Paul Rubin wrote: > miller.pau... at gmail.com writes: Thanks for your reply. I guess I'll have to go source diving to truly answer the question. > "You can fix your Python program's performance problems by rewriting > it in C" is not that convincing an answer to a concern that Python is > slow ;-). Wasn't meant to be. But, it is a credit to Guido that, beyond the pain inherent in coding in C, there's relatively little pain involved in writing an extension module. From pavlovevidence at gmail.com Sun May 4 14:25:36 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 4 May 2008 11:25:36 -0700 (PDT) Subject: is +=1 thread safe References: <4819DA2D.3030508@ggmail.com> <481BD50F.5080608@ggmail.com> <8a0d4152-af47-4c83-bf78-c5ceda7c9fbd@8g2000hse.googlegroups.com> <035b047f-20fb-4bb0-b76a-61405077976a@d1g2000hsg.googlegroups.com> Message-ID: On May 4, 2:13 pm, Carl Banks wrote: > However, what I said was not wholly untrue: code in C extensions is > protected by the GIL and thus not interruptable, unless it either > releases the GIL, or calls back into Python code (which is apparently > what numpy scalars do). And, because I know that someone will be nitpicky: yes, technically it is interruptable at that point, but other Python threads trying to execute the same piece of code are not allowed to run. > print 'final count:', count This should be "int(count)". Carl Banks From bruno.42.desthuilliers at websiteburo.invalid Fri May 9 04:41:34 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 09 May 2008 10:41:34 +0200 Subject: Newbie to python --- why should i learn ! In-Reply-To: References: <9f5ee6c3-86f7-401a-acc8-cd2c9b059fbd@x19g2000prg.googlegroups.com> Message-ID: <48240e3e$0$30967$426a34cc@news.free.fr> pistacchio a ?crit : (snip) > Technically speaking, it (Python) is not, for example, strongly > typed, You're confusing "strong" typing with static typing. Somewhat orthogonal issues. From s0suk3 at gmail.com Mon May 5 01:06:42 2008 From: s0suk3 at gmail.com (s0suk3 at gmail.com) Date: Sun, 4 May 2008 22:06:42 -0700 (PDT) Subject: Truncate beginning of a file Message-ID: <1bc92095-41ab-404a-a697-088545cdddec@27g2000hsf.googlegroups.com> file.truncate(X) will truncate the file to at most X bytes (i.e. leave the first X bytes of the file and throw away the rest). Is there a way to throw away, say, the first X bytes of the file, and leave the rest? (Without opening the same file for reading, reading and processing, overwriting the file with the new processed data, etc.) From Lie.1296 at gmail.com Sun May 25 13:37:01 2008 From: Lie.1296 at gmail.com (Lie) Date: Sun, 25 May 2008 10:37:01 -0700 (PDT) Subject: php vs python References: <5l%Yj.77$mz3.53@fe101.usenetserver.com> Message-ID: <37b112d8-a3ba-446d-9d2f-d907d93c637b@w8g2000prd.googlegroups.com> On May 22, 12:28?pm, NC wrote: > On May 21, 1:10 pm, notbob wrote: > > > > > So, here's my delimna: I want to start a blog. ?Yeah, who doesn't. > > Yet, I want learn the guts of it instead of just booting up some > > wordwank or whatever. > > Here's a simple computation to consider... ?WordPress' codebase is > approximately a megabyte of PHP code and megabyte of JavaScript code. > Assuming that the average line of that code is 50 characters long, you > are looking at 20,000 lines of code in PHP and as many in JavaScript. > Based on the notion that the average developer out there writes 100 > lines a day, either you're in for a two-year project or your product > is going to have seriously reduced functionality compared to something > that's been freely available for years. ?What's your choice? Nope, the core functionality of a blogging software could be replicated in just a few lines of PHP codes, in the range of tens to hundreds of lines. If you're creating your own blogging software, you wouldn't seriously think you'd recreate all those things such as pingbacks, commenting system, etc, etc, etc. No, you'd start with some basic core functionalities: a few simple server side includes only. From bruno.42.desthuilliers at websiteburo.invalid Tue May 6 03:36:36 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 06 May 2008 09:36:36 +0200 Subject: Bad form to access a *private variable* like _foo? In-Reply-To: References: Message-ID: <48200a7f$0$23642$426a74cc@news.free.fr> seberino at spawar.navy.mil a ?crit : > Bad form to access a *private variable* like _foo? In this case, this would be spelled "protected" - or even better "implementation". And the contract is: nothing prevent you to access implementation attributes, but then you're on your own if anything breaks. > The reason I'm asking is that TurboGears/SQLObject mobel objects have > an attribute called "_connection" that must be used to manually commit > database stuff.... > > e.g. MyObject._connection.commit() > > It bugs me. I don't know if it is a stylistic faux pas or not. > > Is it? The way you wrote it here, yes. If there's no official way to do the same operation and you have a real use case for it - in which case you may want to add a commit() method to SQLObject's model base class and submit the patch to SQLObject's maintainer. But I strongly suspect there's a better way to handle this case in SQLObject's API. From basti.wiesner at gmx.net Sat May 31 15:40:46 2008 From: basti.wiesner at gmx.net (Sebastian 'lunar' Wiesner) Date: Sat, 31 May 2008 21:40:46 +0200 Subject: parse dates References: <0f58a4f7-ba18-4f83-9291-12bc844a37a0@p25g2000hsf.googlegroups.com> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 [ brechmos ] > Hi, > > I have been using PHP the last while and in particular strtotime. > What I want to replicate is finding the second or fourth Monday of the > next month. In PHP with strtotime it is easy (strtotime("second > Monday", strtotime("next month"), but I can't find an easy way to do > it in Python. I have seen DateUtil, but it seems to be able to do > only the simpler parsing (could be wrong). > > Any other ideas? If parsing is not required, dateutil is just fine: from datetime import datetime from dateutil import relativedelta # second monday datetime.now() + relativedelta.relativedelta(day=1, weekday=relativedelta.MO(+2)) # next month datetime.now() + relativedelta.relativedelta(months=+1) - -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) -----BEGIN PGP SIGNATURE----- Version: GnuPG v2.0.9 (GNU/Linux) iEYEARECAAYFAkhBqcMACgkQn3IEGILecb7FXgCgg1X7vrP/uzTaPa5W3e2WsDFV e5kAnizMQUDLfz07Z/d1hVehlCmoJuKl =yi9t -----END PGP SIGNATURE----- From inhahe at gmail.com Fri May 16 11:21:39 2008 From: inhahe at gmail.com (inhahe) Date: Fri, 16 May 2008 11:21:39 -0400 Subject: writing python extensions in assembly References: Message-ID: You could be right, but here are my reasons. I need to make something that's very CPU-intensive and as fast as possible. The faster, the better, and if it's not fast enough it won't even work. They say that the C++ optimizer can usually optimize better than a person coding in assembler by hand can, but I just can't believe that, at least for me, because when I code in assembler, I feel like I can see the best way to do it and I just can't imagine AI would even be smart enough to do it that way... For portability, I'd simply write different asm routines for different systems. How wide a variety of systems I'd support I don't know. As a bare minimum, 32-bit x86, 64-bit x86, and one or more of their available forms of SIMD. "D'Arcy J.M. Cain" wrote in message news:mailman.1229.1210949533.12834.python-list at python.org... > On Fri, 16 May 2008 10:13:04 -0400 > "inhahe" wrote: >> Can anyone give me pointers/instructions/a template for writing a Python >> extension in assembly (or better, HLA)? > > I am trying to imagine the requirements document for your project. > > - Must be error prone and hard to debug > - Must take an order of magnitude longer to write > - Must be unportable to other systems > > Really, why don't you write your etension in C? Do you really think > you will improve your code by writing it in assembler? Even embedding > assembler in C code make it unportable and I find it hard to imagine > anything that you want to do in a Python context that can't be done at > least as well in C if not pure Python. > > Just curious is all. > > -- > D'Arcy J.M. Cain | Democracy is three wolves > http://www.druid.net/darcy/ | and a sheep voting on > +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From mnikhil at gmail.com Wed May 21 20:37:49 2008 From: mnikhil at gmail.com (Nikhil) Date: Thu, 22 May 2008 06:07:49 +0530 Subject: simple way to touch a file if it does not exist References: <68629786-1cef-4dc5-99d9-4967ebecd10f@r66g2000hsg.googlegroups.com> Message-ID: <4834C05D.6020608@gmail.com> bukzor wrote: > On May 21, 5:10 pm, "Giampaolo Rodola'" wrote: >> On 22 Mag, 01:15, Nikhil wrote: >> >>> what are the simple ways? >>> I could think of os.open(), os.exec(touch file) >>> are there any simpler methods? >> Just use os.path.exists to check for file existence and open() as >> replacement for touch. >> >>>>> import os >>>>> if not os.path.exists('file'): >> ... open('file', 'w').close() >> ... >> >> >> >> --- Giampaolohttp://code.google.com/p/pyftpdlib/ > > As simple as it gets is a single builtin function call: > > open("somefile.txt", "a") > > Leave out the ,"a" if you don't mind blanking a pre-existing file. Thanks :-) That reminds me to check if I could quickly nullify a file if it exists if os.path.exists('file'): open('file', 'w').close() Right? From yves at zioup.com Fri May 23 01:07:57 2008 From: yves at zioup.com (Yves Dorfsman) Date: Fri, 23 May 2008 05:07:57 GMT Subject: Producing multiple items in a list comprehension References: <5RiZj.165543$ng7.151222@en-nntp-05.dc1.easynews.com> Message-ID: Peter Otten <__peter__ at web.de> wrote: > > A slightly similar problem: If I want to "merge," say, list1=[1,2,3] with > > list2=[4,5,6] to obtain [1,4,2,5,3,6], is there some clever way with "zip" > > to do so? > >>> items = [None] * 6 > >>> items[::2] = 1,2,3 > >>> items[1::2] = 4,5,6 > >>> items > [1, 4, 2, 5, 3, 6] My problem with this solution is that you depend on knowing how many elements you have in each list ahead of time. Assuming that both list are of the same length, then, I find the following more elegant: list1=[1,2,3] list2=[4,5,6] reduce(lambda x, y: x+y, zip(list1, list2)) of course, zip creates tuples, so you end up with a tuple, therefore if you need for your solution to be a list: list(reduce(lambda x, y: x+y, zip(list1, list2))) of reduce(lambda x, y: x+y, list(zip(list1, list2)) ) Yves. http://www.SollerS.ca From kyosohma at gmail.com Fri May 23 12:25:28 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 23 May 2008 09:25:28 -0700 (PDT) Subject: Another Question References: Message-ID: <5c2e7570-6bb1-46d8-8dd5-b1a257431b31@p25g2000hsf.googlegroups.com> On May 23, 10:45?am, Gandalf wrote: > How can i bind function that handle the mouse clicking ?window X event > or clicking alt+F4 > > thanks You really need to learn to ask good questions. Unless people dive into your previous posts, they won't know what Python GUI toolkit you are using, which version of said toolkit, which Python or which OS. Here's a good place to read about events in general: http://wiki.wxpython.org/EventPropagation If you use Google, you can look for the close event, which gives you this: http://www.wxpython.org/docs/api/wx.CloseEvent-class.html So you'll want to bind your frame to EVT_CLOSE. You can disable the "X" in your frame's window by using non-standard style parameters. Mike From rocky at panix.com Wed May 21 11:39:01 2008 From: rocky at panix.com (R. Bernstein) Date: Wed, 21 May 2008 11:39:01 -0400 Subject: Possibly pydb 1.23 release around May 30 Message-ID: A release of pydb (1.23) is currently scheduled for around May 30th. If you can and want to help make sure the release is okay, you can try out what is currently in CVS: http://sourceforge.net/cvs/?group_id=61395 I've put an interim tar at http://bashdb.sf.net/pydb-1.23cvs.tar.gz Changes in the upgoming release: * Show parameters on call * Some doc fixes. * add ipython and python commands to go into an ipython or a python shell * add "save" command to save the current breakpoints and/or most settings to a file. (Suggested at a NYC Python group meeting) * add set/show "deftrace" to allow stopping at a def (method creation) statement. * pseudo gdb-like "annotate" set/show commands and option. * Better emacs interactivion via above annotate * bug when "info local" is run inside a "with" statement Fixes for last three items based patches by Alberto Griggio From castironpi at gmail.com Thu May 15 22:43:04 2008 From: castironpi at gmail.com (castironpi) Date: Thu, 15 May 2008 19:43:04 -0700 (PDT) Subject: call tree tool? References: <3k1Xj.3430$7k7.2352@flpi150.ffdc.sbc.com> <13666537-1237-4165-8f61-780a752a2842@59g2000hsb.googlegroups.com> <37761a22-23db-455e-b23c-6b89a1ae77b2@b1g2000hsg.googlegroups.com> Message-ID: <223ab3fc-cb1f-4765-8f27-50f1487c19a3@b1g2000hsg.googlegroups.com> On May 15, 9:30?pm, castironpi wrote: > On May 15, 9:27?pm, castironpi wrote: > > > > > > > On May 15, 6:53?pm, castironpi wrote: > > > > On May 15, 4:26?pm, "Dan Upton" wrote: > > > > > On Thu, May 15, 2008 at 5:19 PM, jay graves wrote: > > > > > On May 15, 3:47 pm, m... at pixar.com wrote: > > > > >> I'm cleaning up some old code, and want to see what orphan > > > > >> functions might be sitting around. > > > > > >> Is there a static call tree analyzer for python? > > > > > > How about > > > > >http://pycallgraph.slowchop.com/ > > > > > > ... > > > > > Jay Graves > > > > > -- > > > > >http://mail.python.org/mailman/listinfo/python-list > > > > > Have you checked to see if PyChecker or pylint can help you? > > > > Apparently they can find unused variables at least, I don't know > > > > whether they do functions or not. > > > > I think of dynamic programming and dynamic code, but voice. ?Does that > > > mean sing about it?- Hide quoted text - > > > > - Show quoted text - > > > I have to write a song. ?Somebody?- Hide quoted text - > > > - Show quoted text - > > Sorry for the frequent posts: I think I have to write a noise about > train cars crossing rail, putting numbers on frequencies, and send > code. ?Train whistles are pretty good too. ?I believe those are the > ones that start to go on keystrokes. ?I'd try to compare differences > between those and bowling pins. ?A couple others are coins clinking > and poker chips. ?Generally speaking, tapping metals and glass.- Hide quoted text - > > - Show quoted text - I also have to apologize for my manners. This had nothing to do with 'call tree tool', which I neglected to consider. It sounds teriffic but I think something about Python makes it unfeasible or inadvisable to visualize them. It's naturally possible it has something to do with the fact that the screen's in two dimensions relative to time, which incidentally some rel. dbs. could use in expressiveness, it's just that it has to come on the dollar since 'is' is often relative to, and comes with verbs. In per Python, you'd have to be wanting to visualize that breadth of information to be wanting to spiral call trees on to screen. From wolfgang.lipp at gmail.com Sat May 24 06:04:14 2008 From: wolfgang.lipp at gmail.com (_wolf) Date: Sat, 24 May 2008 03:04:14 -0700 (PDT) Subject: image scaling in cairo, python Message-ID: [also posted to: cairo at cairographics.org] hi all, i've heard cairo has become the image scling library for firefox3. is that true? wonderful, i want to do that in python. there's a python interface for cairo, right? i've used it before to do simple vector stuff. seems to work. however, i haven't been able to find relevant pointers via google. so do you have any pointers on how to resize a raster image with python using cairo? i've been jumping through hoops for a while now, and i believe it should be easier. cheers and ~flow ps. related (long) posts: http://groups.google.com/group/pyglet-users/browse_frm/thread/44253ad01d809da5/cd051e6bced271e1#cd051e6bced271e1 http://groups.google.com/group/comp.lang.python/browse_frm/thread/5df65d99cff0d7bb# From yves at zioup.com Mon May 12 23:18:32 2008 From: yves at zioup.com (Yves Dorfsman) Date: Tue, 13 May 2008 03:18:32 GMT Subject: anonymous assignment In-Reply-To: References: <1XNVj.133805$Cj7.33096@pd7urf2no> <9e0c171a-6156-46fc-b9db-a8aba01c1472@m44g2000hsc.googlegroups.com> Message-ID: Gabriel Genellina wrote: >> Uses Python 2.6! ;) >> > > No need of 2.6 - the above code works since Python 2.2 at least: > > Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. >>>> import time >>>> t=time.localtime() >>>> type(t) > >>>> t.tm_year > 2008 > > (but struct_time objects were printed as regular tuples) > And not well documented ! Nice one ! Thanks. From iainking at gmail.com Wed May 14 11:08:51 2008 From: iainking at gmail.com (Iain King) Date: Wed, 14 May 2008 08:08:51 -0700 (PDT) Subject: Rename field in Access DB Message-ID: I'm manipulating an MS Access db via ADODB with win32com.client. I want to rename a field within a table, but I don't know how to. I assume there is a line of SQL which will do it, but nothing I've tried (from searching) has worked. Basic code: import win32com.client connection = win32com.client.Dispatch(r'ADODB.Connection') DSN = 'PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=dbfile.mdb;' connection.Open(DSN) connection.Execute("ALTER TABLE tablename CHANGE from to") #this sql doesn't work connection.Close() Anyone know how to get this to work? Iain From castironpi at gmail.com Fri May 16 14:01:16 2008 From: castironpi at gmail.com (castironpi) Date: Fri, 16 May 2008 11:01:16 -0700 (PDT) Subject: Pyparsing Question References: Message-ID: On May 16, 10:45?am, Ant wrote: > Hi Paul, > > > LineStart *really* wants to be parsed at the beginning of a line. > > Your textline reads up to but not including the LineEnd. ?Try making > > these changes. > > > 1. Change textline to: > > > ? ? ?textline = pp.Combine( > > ? ? ? ? pp.Group(pp.Word(pp.alphas, pp.printables) + pp.restOfLine)) + > > \ > > ? ? ? ? pp.LineEnd().suppress() > > Ah - so restOfLine excludes the actual line ending does it? > > > 2. Change comb to: > > > ? ? comb = head + parser > > Yes - I'd got this originally. I added the garbage to try to fix the > problem and forgot to take it back out! Thanks for the advice - it works > ? fine now, and will provide a base for extending the list format. > > Thanks, > > Ant... There is a possibility that spirals can come from doubles, which could be non-trivially useful, in par. in the Java library. I won't see a cent. Can anyone start a thread to spin letters, and see what the team looks like? I want to animate spinners. It's across dimensions. (per something.) Swipe a cross in a fluid. I'm draw crosses. Animate cubes to draw crosses. I.e. swipe them. From lac at openend.se Tue May 27 09:08:42 2008 From: lac at openend.se (Laura Creighton) Date: Tue, 27 May 2008 15:08:42 +0200 Subject: looking for membership management software -- Open Source, written in Python In-Reply-To: Message from miller.paul.w@gmail.com of "Mon, 26 May 2008 12:18:47 PDT." <014354fc-991d-4b56-99fb-5bebabd1ec79@59g2000hsb.googlegroups.com> References: <014354fc-991d-4b56-99fb-5bebabd1ec79@59g2000hsb.googlegroups.com> Message-ID: <200805271308.m4RD8gXP018239@theraft.openend.se> In a message of Mon, 26 May 2008 12:18:47 PDT, miller.paul.w at gmail.com writes: >On May 26, 10:36?am, Laura Creighton wrote: >> I'm looking for an application that handles the membership of an >> organisation -- who's a member, who has paid fees, addressbook and >> the odd added field. >> >> Anybody got one they recommend? >> > >It sounds like you essentially need a specialized database and an app >to query the database. If this is a small organization (under 100 >people, say), then the simplest solution would probably be a simple >spreadsheet. Otherwise, maybe something like Organizers' Database >(http://www.organizersdb.org/) would do the trick. We're bigger than this, and are very much in the 'we are way too big to be a spreadsheet any more' phase. >I haven't actually used this software, but it looks like it's made to >do exactly what you want to do. Indeed, but being powered by Drupal makes it a PHP system, and I don't think I can get our security guys to go for that. And it only runs on windows; they're not going to be happy about that either. >Hope that helps! Yes, it did. Thank you very much, Laura > >-- >http://mail.python.org/mailman/listinfo/python-list From marko.srepfler at gmail.com Fri May 23 04:40:26 2008 From: marko.srepfler at gmail.com (x40) Date: Fri, 23 May 2008 01:40:26 -0700 (PDT) Subject: Google Treasure solution in python - first time python user, help whats wrong Message-ID: <44de619e-14f3-49d2-b336-a14e5dca12cd@e39g2000hsf.googlegroups.com> I try to learn python thru solving some interisting problem, found google trasure hunt, write first program ( but cant find whats wrong). # Unzip the archive, then process the resulting files to obtain a numeric result. You'll be taking the sum of lines from files matching a certain description, and multiplying those sums together to obtain a final result. Note that files have many different extensions, like '.pdf' and '.js', but all are plain text files containing a small number of lines of text. # #Sum of line 5 for all files with path or name containing abc and ending in .js #Sum of line 5 for all files with path or name containing HIJ and ending in .js #Hint: If the requested line does not exist, do not increment the sum. # #Multiply all the above sums together and enter the product below. #(Note: Answer must be an exact, decimal representation of the number.) import fnmatch import os def zbrojipl(pattern): rootPath = '' sum1=0 for root, dirs, files in os.walk(rootPath): for filename in files: path=os.path.join(root, filename) if fnmatch.fnmatch(path, pattern): #print path f=open(path) redovi=f.readlines() #print len(redovi),redovi if len(redovi)>=5: #print redovi[4] # index od 0 kao C sum1=sum1+int(redovi[4]) return sum1 print zbrojipl('*[abc]*.js')*zbrojipl('*[HIJ]*.js') From BrianVanderburg2 at aim.com Thu May 8 07:31:17 2008 From: BrianVanderburg2 at aim.com (Brian Vanderburg II) Date: Thu, 08 May 2008 07:31:17 -0400 Subject: #!/usr/bin/env python vs. #!/usr/bin/python In-Reply-To: <1ab5792a-6dab-4b80-a404-9c197469716e@v26g2000prm.googlegroups.com> References: <87bq3ozs09.fsf@benfinney.id.au> <20080502110755.85e2ea4e.darcy@druid.net> <956b3035-4f82-4391-8d1e-7f88875f8d21@w1g2000prd.googlegroups.com> <3de8e1f70805060135h5b5078fpe12fe5348d24a421@mail.gmail.com> <874p9belo6.fsf@benfinney.id.au> <1ab5792a-6dab-4b80-a404-9c197469716e@v26g2000prm.googlegroups.com> Message-ID: <4822E485.4040107@aim.com> This is sort of related, but I'm wondering what is different between "#!/usr/bin/env python" and "#!python". Wouldn't the second do the same thing, since an absolute path is not specified, find 'python' from the PATH environment, I don't really know. Brian Vanderburg II From ggpolo at gmail.com Sat May 10 11:48:30 2008 From: ggpolo at gmail.com (Guilherme Polo) Date: Sat, 10 May 2008 12:48:30 -0300 Subject: People still using Tkinter? In-Reply-To: <4825C265.90106@codebykevin.com> References: <4825C265.90106@codebykevin.com> Message-ID: 2008/5/10 Kevin Walzer : > Guilherme Polo wrote: >> >> 2008/5/10 Zentrader : >>> >>> I like New Mexico Tech's site as well. Also, take a look at the PMW >>> extension for additional widgets, and TkTable and/or TableListWrapper. >>> http://infohost.nmt.edu/tcc/help/pubs/tkinter/ >> >> There is also Tile, or Ttk since Tk 8.5, if you are interested in >> extensions too. >> Apparently there are three Tile wrappers now, two are incomplete >> (sorry for saying that): >> >> http://bruno.thoorens.free.fr/ttk.html -- Missing Treeview, big part >> of ttk styling, maybe other things and it is not only a ttk wrapper >> (there are other things besides it) >> http://bugs.python.org/file10010/Tile.py -- Missing several methods in >> Treeview, big part of ttk styling and maybe something else. >> >> And there is also one I'm doing, that I expect to be complete: >> >> http://gpolo.ath.cx:81/projects/ttk_to_tkinter/ >> >> Documentation and samples are still lacking, but I'm working on them. >> And I haven't tested it under Windows, so I invite you all to test it. >> >> Regards, >> > I'm the maintainer of Tile.py. It may well be incomplete, as it was first > developed by Martin Franklin a couple of years ago and I've been modifying > it as my own needs require. > > So you're doing your own implementation of ttk in Tkinter as a Google Summer > of Code Project? Wonderful! Are you planning on submitting it for including > in Tkinter's core, as I did? Thanks ;) And, yes Kevin, I'm planning to submit it for inclusion into Tkinter's core. > If yours proves to be the better implementation > I'll gladly withdraw mine, as I'm not sure I have time to overhaul it > extensively. > > I'll follow your progress with interest! Thanks for support it, and sorry for saying yours was incomplete. I wasn't trying to sell my version by doing that, was just trying to say there were some point on doing another wrapper. I also noticed that there is some problem in getting Martin Franklin to fill the contributors agreement, that was the second point on doing this wrapper. > > --Kevin > > -- > Kevin Walzer > Code by Kevin > http://www.codebykevin.com > Regards, -- -- Guilherme H. Polo Goncalves From mccredie at gmail.com Fri May 2 13:21:03 2008 From: mccredie at gmail.com (Matimus) Date: Fri, 2 May 2008 10:21:03 -0700 (PDT) Subject: Preventing 'bad' filenames from raising errors in os.path References: Message-ID: <31980dcf-871f-43d7-bc12-52efb081779a@d19g2000prm.googlegroups.com> On May 2, 9:40 am, pyt... at bdurham.com wrote: > Bad file names, i.e. filenames the OS considers illegal, will cause > functions in the os.path module to raise an error. > > Example: > > import os.path > print os.path.getsize( 'c:/pytest/*.py' ) > > On Windows XP using Python 2.5.2 I get the following traceback: > > Traceback (most recent call last): > File "", line 74, in run_nodebug > File "", line 3, in > File "C:\Python\lib\ntpath.py", line 228, in getsize > return os.stat(filename).st_size > WindowsError: [Error 123] The filename, directory name, or volume label > syntax is incorrect: 'c:/pytest/*.py' > > Since there are many places a user can enter a path name (interactively, > via config files, etc) in most applications, is there an os sensitive > function that can be used to detect bad file names? > > As a matter of best practice, how do you wrap your use of file and path > names to prevent unexpected failures? (There has to be a better > alternative than try/except blocks around each use of an os.path > function in one's code?) > > Thanks, > Malcolm What do you find troubling about try/except? Compare: import os.path path = raw_input("enter a path:") if isvalidpath(path): # this is a made up name print os.path.getsize(path) else: # Do something else To: import os.path path = raw_input("enter a path:") try: print os.path.getsize(path) except WindowsError: # Do something else Now, I can understand if you don't like the "WindowsError" as that is obviously platform specific. The try/except pattern however is the way errors are handled in python and the best and most appropriate way to deal with it. The above example just shows that at the very least there isn't a significant difference in code size between the two methods. I don't know what the equivalent error is called in *nix but assume it is PosixError (it isn't), then it would just be written this way: import os.path path = raw_input("enter a path:") try: print os.path.getsize(path) except (WindowsError, PosixError): # Do something else You don't _always_ need to wrap os.path functions with try/except. You only need to wrap where there is reason to expect that the input might be prone to error. In those cases the alternative is what? wrapping it in a if/else instead? How is that better? Matt From lowell at allemansonline.com Wed May 28 16:53:56 2008 From: lowell at allemansonline.com (Lowell Alleman) Date: Wed, 28 May 2008 16:53:56 -0400 Subject: Custom log handler and logging.config.fileConfig() Message-ID: <839ec5810805281353w637e3e9yadf1f582f6d8c780@mail.gmail.com> Here is the situation: I wrote my own log handler class (derived from logging.Handler) and I want to be able to use it from a logging config file, that is, a config file loaded with the logging.config.fileConfig() function. Let say my logging class is called "MyLogHandler" and it's in a module called "mylogmodule", I want to be able to make an entry something like this in my logging config file: [handler_hand02] class=mylogmodule.MyLogHandler level=DEBUG formatter=form02 args=('python.log', 10, True) I did some digging in the code and documentation, and it doesn't appear that this question of writing and accessing your own log handlers is addressed. As per the logging/config.py code, it looks like the actual file handler classes are being grabbed using an "eval" from the "logging" module's namespace, like so: klass = eval(klass, vars(logging)) So this basically means that I have to mess with the "logging" module's namespace if I want this to work, right? So I've come up with a couple of options, but I'm trying to figure out what approach is best: Option 1: Require the client (the user of my logging module), first import my module and then copy it into the logging module's namespace, before calling fileConfig(). Something like this: import mylogmodule import logging logging.mylogmodule = mylogmodule Option 2: Have my module make a copy MyLogHandler class into the logging (or logging.handlers) module, and then let the client use it from their directly. They client would still have to load my logging class first (which isn't any different they what they would have to do if they wanted to use the extended log handlers form the logging.handlers module) My module would include: import logging class MyLogHandler(logging.Handler): ... logging.MyLogHandler = MyLogHandler The config file would simply have: class=MyLogHandler Option 3: Is there an easy (and non-evil) way for me to make my module available as "logging.mylogmodule" directly? I am using setuptools, and it seems like what I've read about "namespaces", they do something close to what I'm looking for, but I think that requires that all of the "__init__.py"s involved be empty (or have some special namespace declaration code). The __init__.py for the logging module is not at all empty, so I suppose that rules out this option? Anyone have some insights on this? Thanks in advance, - Lowell Alleman From clabepa at gmail.com Thu May 15 02:51:48 2008 From: clabepa at gmail.com (Claudio Driussi) Date: Thu, 15 May 2008 08:51:48 +0200 Subject: [ANN] PPyGui emulator In-Reply-To: References: <482aa2f2$0$22076$6e1ede2f@read.cnntp.org> Message-ID: <482bdd7f$0$22075$6e1ede2f@read.cnntp.org> Stef Mientki wrote: >>> I've ran the first real world application through PPyGui-emulator, >>> so I think it's time to release the first version. >>> There's lot of room for improvements and a more beautiful layout. >>> >>> PPyGui-emulator is build upon wxPython and released under BSD license. >>> >>> For remarks, screen shots and downloads, see >>> http://oase.uci.kun.nl/~mientki/data_www/pylab_works/pp_intro.html >> >> Wow! wonderful. >> I was searching for it for debugging and easy development purposes, >> screenshots sounds promising. >> >> but the api.py link is broken. > Well the file is correctly at the server, > and indeed it downloads as nonsense ??? > Is it not possible to just put a py-file on the server ?? > > Anyway, I've changed it into a zip file, and now everything works (at > least at my place) Yea, tried, it works like a charm even into winpdb debugger. Very nice, many thanks Claudio From alokkat at gmail.com Sat May 3 12:26:43 2008 From: alokkat at gmail.com (Alok Kumar) Date: Sat, 3 May 2008 12:26:43 -0400 Subject: State machine Example in Python Message-ID: Can someone please redirect me for a state machine example or design pattern used in Python. Regards Alok -------------- next part -------------- An HTML attachment was scrubbed... URL: From marco at sferacarta.com Tue May 13 06:20:12 2008 From: marco at sferacarta.com (Marco Mariani) Date: Tue, 13 May 2008 12:20:12 +0200 Subject: array in class In-Reply-To: <3f2b8a18-8f5b-4188-acb7-660d73574027@m44g2000hsc.googlegroups.com> References: <3f2b8a18-8f5b-4188-acb7-660d73574027@m44g2000hsc.googlegroups.com> Message-ID: alefajnie wrote: > class B: > this_is_common_for_all_instances = [] > > def __init__(self, v): > self.this_is_common_for_all_instances.append(v) > > > ---------------- > now I can create some instances of B, but all of them have the same > array, why Because you didn't reassign the attribute 'this_is_common_for_all_instances', but appended to it. > and how create array in class - normal array, "private variable" 1) it's called a list, not an array 2) you do that in the __init__ method: self.blabla = [] 3) still, it won't be a "private" attribute, just an instance attribute From mensanator at aol.com Sun May 18 19:17:55 2008 From: mensanator at aol.com (Mensanator) Date: Sun, 18 May 2008 16:17:55 -0700 (PDT) Subject: How do *you* use Python in non-GUI work? References: <20080518182022.990193bd.johnjsal@NOSPAMgmail.com> Message-ID: <6fb308f2-a5be-4641-aa04-561b1782c6bb@z72g2000hsb.googlegroups.com> On May 18, 5:20?pm, John Salerno wrote: > Hey all. Just thought I'd ask a general question for my own interest. Every time I think of something I might do in Python, it usually involves creating a GUI interface, so I was wondering what kind of work you all do with Python that does *not* involve any GUI work. This could be any little scripts you write for your own benefit, or what you do at work, if you feel like talking about that! :) > > Thanks. Odd, I've been using Python since ver 2.2 and I've NEVER needed a GUI. I do things like (looking at the last 6 months of my Python directory): - how to scrape movie receipt data from IMDB and insert them into an MS-Access database - how to scrape .jpgs from a web page (simple file transfer, no display needed) - how to do a Cartesian Product in SQLlite3 - how to creat a polynomial from a sequence of numbers using Newton's Forward Differences method - how to calculate the date of Easter - how to construct arbitrary length cycles in the Collatz Conjecture - how to find the Ultimate Cycle (also in Collatz Conjecture) - efficient cycle detection comparing Brent's and Sedgewick's cycle detection algorithms - finding the cycles of 3n+C systems - partioning W marbles into D ordered bins with the constraint that each bin contain a minimum of 1 - partioning W marbles into D ordered bins with the constraint that each bin contain a minimum of 1 and that no bin exceeds M - a Python Cartesian Product that in addition to Permutaions with Replacement, also gives the subsets Permutations without Replacement, Combinations with Replacement and Combinations without Replacement - demonstrating the fallacy of Peter Scorer's "proof" of the Collatz Conjecture - demonstrating the fallacy of Alan Tyte's "proof" of the Collatz Conjecture - demonstrating the fallacy of Ken Conrow's "proof" of the Collatz Conjecture - how to identify which members of the infinite solutions to a given Sequnce Vector of a 3n+C system are located on the trivial graph component - developing a novel factoring algorithm based on the Collatz Conjecture I see no need for GUI in any of these applications. From dickinsm at gmail.com Wed May 21 16:20:38 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Wed, 21 May 2008 13:20:38 -0700 (PDT) Subject: Bug in floating-point addition: is anyone else seeing this? References: Message-ID: <5f27111e-942c-48c1-81c1-fe1567e887bb@c58g2000hsc.googlegroups.com> On May 21, 3:22?pm, Marc Christiansen wrote: > On my system, it works: > > ?Python 2.5.2 (r252:60911, May 21 2008, 18:49:26) > ?[GCC 4.1.2 (Gentoo 4.1.2 p1.0.2)] on linux2 > ?Type "help", "copyright", "credits" or "license" for more information. > ?>>> a = 1e16 - 2.; a > ?9999999999999998.0 > ?>>> a + 0.9999 > ?9999999999999998.0 > > Marc Thanks for all the replies! It's good to know that it's not just me. :-) After a bit (well, quite a lot) of Googling, it looks as though this might be known problem with gcc on older Intel processors: those using an x87-style FPU instead of SSE2 for floating-point. This gcc 'bug' looks relevant: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=323 Now that I've got confirmation I'll open a Python bug report: it's not clear how to fix this, or whether it's worth fixing, but it seems like something that should be documented somewhere... Thanks again, everyone! Mark From n00m at narod.ru Thu May 1 05:21:22 2008 From: n00m at narod.ru (n00m) Date: Thu, 1 May 2008 02:21:22 -0700 (PDT) Subject: A bug in difflib module? (find_longest_match) References: <8054bd25-5a14-446d-a775-6efca1d5a2a0@m3g2000hsc.googlegroups.com> Message-ID: <7292bae2-993e-41cc-8f0e-8d1339ecebdf@25g2000hsx.googlegroups.com> Gabriel Genellina: > En Thu, 01 May 2008 04:35:17 -0300, n00m escribi?: > > > from random import randint > > > > s1 = '' > > s2 = '' > > > > for i in xrange(1000): > > s1 += chr(randint(97,122)) > > s2 += chr(randint(97,122)) > > > > print s1[:25] > > print s2[:25] > > > > import difflib > > > > s = difflib.SequenceMatcher(None, s1, s2) > > > > print s.find_longest_match(0, len(s1), 0, len(s2)) > > > > > > > >>>> ============== RESTART ==================== > >>>> > > yymgzldocfaafcborxbpqyade > > urvwtnkwfmcduybjqmrleflqx > > (0, 0, 0) > >>>> > > > > I think it's line #314 in difflib "who's to blame" -- > > Me too. Could you think of some alternative? Simply disabling that > "popularity check" would slow down the algorithm, according to the > comments. > > -- > Gabriel Genellina No idea :) From skanemupp at yahoo.se Sat May 3 12:51:06 2008 From: skanemupp at yahoo.se (globalrev) Date: Sat, 3 May 2008 09:51:06 -0700 (PDT) Subject: pygame: rect moveto? Message-ID: <7360a3b3-61b8-4cb9-b4d7-177c532bc880@b1g2000hsg.googlegroups.com> http://www.pygame.org/docs/ref/rect.html#Rect.move well i need to put my rect ina specific place and i donw know from where i will move it so i need a function rect.moveTo(x,y). how do i do that? From daveparker at flamingthunder.com Mon May 12 21:36:20 2008 From: daveparker at flamingthunder.com (Dave Parker) Date: Mon, 12 May 2008 18:36:20 -0700 (PDT) Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <2b66a86e-5a05-4262-b3c9-4703b0ae3372@d1g2000hsg.googlegroups.com> <5b0e3f70-afde-4480-8713-e7113b1250d7@x35g2000hsb.googlegroups.com> Message-ID: <1f537717-00d0-48ee-99b6-7125b96a6133@t12g2000prg.googlegroups.com> On May 12, 7:20?pm, castiro... at gmail.com wrote: >?Yes, I am trying to visualize something. If it is related to making furniture comfortable for humans, have you considered painting the furniture with thermochromic paint ( http://en.wikipedia.org/wiki/Thermochromism )? It changes color in response to temperature, which in part is determined by how hard a body is pressed against it because close contact tends to trap heat. An evenly distributed color might indicated evenly distributed pressure. From metawilm at gmail.com Mon May 5 14:55:38 2008 From: metawilm at gmail.com (metawilm at gmail.com) Date: Mon, 5 May 2008 11:55:38 -0700 (PDT) Subject: generator functions in another language References: <831bea0d-ef71-4ede-9065-3111bce5225e@c65g2000hsa.googlegroups.com> <684r62F2rmn3gU2@mid.uni-berlin.de> Message-ID: On May 4, 1:11 pm, castiro... at gmail.com wrote: > There is no such thing as a 'frame' per se in C; byte code is > integral. As there is no such thing as suspended state without > frames, and no such thing as generators without suspended state. Well, for implementing generators there are alternatives to using frames + byte code. In CLPython generators are implemented with closures. (Which does not help much when it comes to reimplementing generators in C, alas.) - Willem From goldnery at gmail.com Fri May 30 13:11:40 2008 From: goldnery at gmail.com (Gandalf) Date: Fri, 30 May 2008 10:11:40 -0700 (PDT) Subject: Generating event from event References: <37f8a6a1-dc98-4985-a84d-f74ead1ec2b7@z72g2000hsb.googlegroups.com> <6aanqgF36mnldU1@mid.uni-berlin.de> Message-ID: <2980f056-a68f-4d8e-9104-642ef5911fcf@k37g2000hsf.googlegroups.com> Hi Diez, I can't see how it matter which GUI-Toolkit i uses because I can combine libraries. I think all that matter is that i work with windows XP. if you ever done something like that or you familiar with article which can show me how to implement what I asked it would help me Thank you very much From jaywgraves at gmail.com Fri May 16 15:22:43 2008 From: jaywgraves at gmail.com (jay graves) Date: Fri, 16 May 2008 12:22:43 -0700 (PDT) Subject: save dictionary for later use? References: <99403e9d-4c67-4e3f-a726-7bb02e72423a@m3g2000hsc.googlegroups.com> Message-ID: <9ec97b27-e4a8-40e0-b8b3-a2cdaeba448e@d77g2000hsb.googlegroups.com> On May 16, 2:17 pm, globalrev wrote: > i extract info from one file and put it into a dictionary. > i want to save that dictionary for later use, how do i do that? > might save a list of dictionaries or a list of classobjects too if > there is any difference. use the 'pickle' module. http://docs.python.org/lib/module-pickle.html ... Jay Graves From unknown_hero007 at hotmail.com Wed May 7 07:25:44 2008 From: unknown_hero007 at hotmail.com (Unknown Hero) Date: Wed, 7 May 2008 04:25:44 -0700 (PDT) Subject: Scanning through Windows registry... References: <48216129.5090405@timgolden.me.uk> Message-ID: Thank you, I think I can manage now. It's nice that you could spare some time to help me in this, Tim. People like you make the world a better place :) I'll post my code here once I have time to write it, currently I'm rather busy. That is merely for optimization suggestions and for others who might need the same sort of code I did. Thank you once again. From hat at se-162.se.wtb.tue.nl Tue May 6 09:23:35 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Tue, 06 May 2008 15:23:35 +0200 Subject: Comparing strings - akin to Perl's "=~" References: Message-ID: On 2008-05-06, krumblebunk at gmail.com wrote: > Hello gurus, Hello fellow-guru, > I am grabbing the output from a SQL statement (using PyGreSQL 'pg' > module), and when it returns the result, I am pulling it out as such: > > try: > sc=pg.connect(dbname='mydb',host='dbhost',user='ppp') > except pg.InternalError: > print "Failed to execute SQL: %s" % sql > exit > > for foo in sc.query(sql).dictresult(): <- this returns a dict of the > result I am sure the above is very good. However, as I never program a data base, I absolutely have no clue what data structure you assume here. A literal value in Python syntax or so would be quite useful. > f=dict(foo) f becomes a dict here. Not sure why you do this, as you stated above that you already had a dict. > for k in f.iteritems() k becomes here all key/value pairs of f, ie it is a tuple example: f = {1:'a', 2:'b'} for k in f.iteritems(): print k will print something like (1, 'a') (2, 'b') A more useful statement could be for k,v in f.iteritems(): ... here a multi-assignment is done (the tuple is broken and each part is assigned to a seperate variable), k becomes the key-part, and v becomes the value-part > if k == '^Hostname': <-- need this sort of > behaviour - match a partial string. This will break in two ways. Firstly, k was a tuple, so you cannot compare it with a string. Secondly, this is not the way to match partial strings. The first problem can be solved with the multi-assignment, or by indexing on the tuple (ie k[0] or k[1]). For the second problem, have a look at the string methods: http://docs.python.org/lib/string-methods.html#l2h-233 In this particular case, you can use if k.startswith('Hostname'): or if k[:8] == 'Hostname': # Slice the first 8 chars of the string For more powerful regular expressions, read the 're' module documentation. > print "%s" % f[3] <-- ..and if true, need to pull > out the 4th column on that line. f is a dict. That means indexing is on its keys. Unless you have the integer key 3 in your dictionary, this will not work. f = {3:'q'} print f[3] # prints 'q' However, a dict has no order, so the '4th column' has no meaning. On the other hand, if f is a list, like [10,20,30,40,50], then f[3] is 50, because you can use integers to index in a list (indexing is just a simple form of slicing). > This breaks spectacularly - Ah, segmentation fault? (that would be spectacular at least). It would also help if you tell us at what line it breaks and with what error. > any ideas? Without a explicit Python value of what comes out of the sql query, I can only guess. As example, assume the following data: f = { 1: ['Hostname', 'blabla', 'person', 'john'], 2: ['MachineName', 'blabla', 'company', 'something']} ie a dictionary of column number to rows. Here you are only interested in the value part, and the code becomes. for v in f.itervalues(): if v[0].startswith('Hostname'): print v[3] From kenneth.m.mcdonald at sbcglobal.net Sat May 10 15:39:32 2008 From: kenneth.m.mcdonald at sbcglobal.net (Kenneth McDonald) Date: Sat, 10 May 2008 14:39:32 -0500 Subject: Any other UI kits with text widget similar to that in Tk? Message-ID: <6FB1E771-8D66-46FD-9E08-0E32C5E85936@sbcglobal.net> I'm wondering if any of the other GUI kits have a text widget that is similar in power to the one in Tk. wxWindows, from what I can tell, doesn't offer nearly the options the Tk widget does. I'm less familiar with Qt. Any feedback would be most appreciated. Thanks, Ken From gagsl-py2 at yahoo.com.ar Sun May 18 05:04:03 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 18 May 2008 06:04:03 -0300 Subject: r' question References: <20080518023835.61FE61E4009@bag.python.org> <20080518054915.9555B1E4007@bag.python.org> Message-ID: En Sun, 18 May 2008 02:49:03 -0300, Dick Moores escribi?: > However, (please refer back to my original post) > I want to keep the fstr, ultimately to be the > string entered by the user who knows a bit about > regex, but not how to use r' ' . Or > alternatively, not assume any knowledge of regex, > but build in some options, such as ignoring/not > ignoring case, searching on just a string, or on > a word. So I want to know how to build the user's > fstr into regex. I apologize for not making this clear. Ok, supose the user enters "joe (home)" and you want to build a regular expression to find that words surrounded by space: fstr = "joe (work)" regex = r"\s" + fstr + r"\s" This doesn't work exactly as expected, because "(" and ")" have a special meaning in a regular expression; use re.escape: regex = r"\s" + re.escape(fstr) + r"\s" You may use "\\s" instead of r"\s", it's the *same* string. The r prefix is just a signal, it says how to interpret the source code, not part of the string. -- Gabriel Genellina From eliben at gmail.com Wed May 28 12:09:14 2008 From: eliben at gmail.com (eliben) Date: Wed, 28 May 2008 09:09:14 -0700 (PDT) Subject: accessing class attributes Message-ID: <5827888d-4e9b-45bd-9361-108714c9043a@m45g2000hsb.googlegroups.com> Hello, I have a game class, and the game has a state. Seeing that Python has no enumeration type, at first I used strings to represent states: "paused", "running", etc. But such a representation has many negatives, so I decided to look at the Enum implementation given here: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/413486 So, I've defined: class Game: self.GameState = Enum('running', 'paused', 'gameover') def __init__ ... etc Later, each time I want to assign a variable some state, or check for the state, I must do: if state == self.GameState.running: This is somewhat long and tiresome to type, outweighing the benefits of this method over simple strings. Is there any better way, to allow for faster access to this type, or do I always have to go all the way ? What do other Python programmers usually use for such "enumeration-obvious" types like state ? Thanks in advance Eli From ppearson at nowhere.invalid Sat May 3 13:48:32 2008 From: ppearson at nowhere.invalid (Peter Pearson) Date: Sat, 03 May 2008 12:48:32 -0500 Subject: Getting started with pyvtk References: <481b35eb$0$24406$5fc3050@news.tiscali.nl> Message-ID: On Fri, 02 May 2008 17:40:02 +0200, Paul Melis wrote: > > I'm not sure you've been helped so far as you seem to already understand > about pyvtk not being the official VTK bindings :) > > So, what would you like to know? Thanks, I think I'm set. For the benefit of the next instance of me googling around trying to get started driving VTK from Python, here's what I wanted to find: - Ignore pyvtk. - Import vtk. - To see how to drive VTK from Python, run all the files of the form /usr/share/vtk/.../*.py and see which ones do something like what you want to do. -- To email me, substitute nowhere->spamcop, invalid->net. From d3vvnull at gmail.com Thu May 8 10:28:37 2008 From: d3vvnull at gmail.com (Michael Mabin) Date: Thu, 8 May 2008 09:28:37 -0500 Subject: python equivalent to perl's inplace edit mechanism In-Reply-To: <18c1e6480805080549h70885464r8d8a177741ffcabd@mail.gmail.com> References: <170543c70805080511o348f38fam5c56c71fce4a6f37@mail.gmail.com> <18c1e6480805080549h70885464r8d8a177741ffcabd@mail.gmail.com> Message-ID: <170543c70805080728y4d81f0b5o9b76cbe170bc55e5@mail.gmail.com> I miswrote my question. But I still completely understand. What I really wanted to know was whether there was something equivalent to how perl can perform inplace edits of a file with something like the magic $^I variable. I see from Gabriel that you can use the fileinput module to achieve this. Very cool. And yeah, I think ruby is very perl-like, in that like perl, which looks like someone duct-taped shell, sed, awk and c into a scripting language, ruby duct-taped perl, Smalltalk and Python together. On Thu, May 8, 2008 at 7:49 AM, David wrote: > On Thu, May 8, 2008 at 2:11 PM, Michael Mabin wrote: > > Does python have an equivalent to Perl's inplace-edit variable $^I? > > > > I misread your question. > > No, Python eschews magic characters and symbols. They make code ugly > and harder to read and maintain. > > The first 3 lines of the Zen of Python: > > Beautiful is better than ugly. > Explicit is better than implicit. > Simple is better than complex. > > You might find a variable like that in Ruby, which has strong Perl > influences. > > David. > -- | _ | * | _ | | _ | _ | * | | * | * | * | -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Mon May 5 01:28:30 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 05 May 2008 02:28:30 -0300 Subject: generator functions in another language References: <831bea0d-ef71-4ede-9065-3111bce5225e@c65g2000hsa.googlegroups.com> <684r62F2rmn3gU2@mid.uni-berlin.de> <8987552e-f462-4465-8338-d856017a4020@b1g2000hsg.googlegroups.com> Message-ID: En Mon, 05 May 2008 00:09:02 -0300, hdante escribi?: > Isn't this guy a bot ? :-) It's learning fast. I believe there is a > "frame" in C, composed of its stack and globals. For generators in C, > you may look for "coroutines". For example, see: > > http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html > > A sample code follows: > > #define crBegin static int state=0; switch(state) { case 0: > #define crReturn(i,x) do { state=i; return x; case i:; } while (0) > #define crFinish } > int function(void) { > static int i; > crBegin; > for (i = 0; i < 10; i++) > crReturn(1, i); > crFinish; > } > > The "suspended state" is saved in the static variable. It's not > necessary to save the complete "frame", only the suspended state. Quoting the author himself, "this is the worst piece of C hackery ever seen" -- Gabriel Genellina From alokkat at gmail.com Tue May 13 21:17:10 2008 From: alokkat at gmail.com (Alok Kumar) Date: Tue, 13 May 2008 21:17:10 -0400 Subject: libxml2 Installation for Python 2.4 Message-ID: Hi, Can someone point me how to install libxml2 for python. It works fine on my Redhat 4.0 linux Box, but when I am trying to run my script on ARM target , it throws import error for libxml2. I am using xpath in my script and in header trying to import libxml2. Thanks in advance. Alok -------------- next part -------------- An HTML attachment was scrubbed... URL: From pavlovevidence at gmail.com Thu May 22 19:32:07 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 22 May 2008 16:32:07 -0700 (PDT) Subject: Python is slow References: Message-ID: <0c6091d2-4658-49f2-8f5d-9553d4aa3685@a70g2000hsh.googlegroups.com> On May 22, 12:14 pm, cm_gui wrote: > Python is slow. Almost all of the web applications written in > Python are slow. Zope/Plone is slow, sloow, so very slooow. Even > Google Apps is not faster. Neither is Youtube. > Facebook and Wikipedia (Mediawiki), written in PHP, are so much faster > than Python. > Okay, they probably use caching or some code compilation -- but Google > Apps and those Zope sites probably also use caching. > > I've yet to see a web application written in Python which is really > fast. I expect Dave Parker here any minute to tell us how Flaming Thunder isn't slow. Carl Banks From ukaluzhny at nds.com Thu May 15 02:41:51 2008 From: ukaluzhny at nds.com (urikaluzhny) Date: Wed, 14 May 2008 23:41:51 -0700 (PDT) Subject: [x for x in <> while <>]? Message-ID: It seems that I rather frequently need a list or iterator of the form [x for x in <> while <>] And there is no one like this. May be there is another short way to write it (not as a loop). Is there? Thanks From notnorwegian at yahoo.se Sun May 25 02:37:00 2008 From: notnorwegian at yahoo.se (notnorwegian at yahoo.se) Date: Sat, 24 May 2008 23:37:00 -0700 (PDT) Subject: which datastructure for fast sorted insert? Message-ID: im writing a webcrawler. after visiting a new site i want to store it in alphabetical order. so obv i want fast insert. i want to delete duplicates too. which datastructure is best for this? From ptbremer at gmail.com Mon May 19 19:28:06 2008 From: ptbremer at gmail.com (Timo) Date: Mon, 19 May 2008 16:28:06 -0700 (PDT) Subject: Mac OS distultils probelm Message-ID: <543d2586-941d-4a9c-ae91-d5c752979034@p25g2000pri.googlegroups.com> Hello there, I'm working on a python extension module that I'm trying to install using the distutils setup tools and I am running into a strange linker problem. Here is the situation: I have a bunch of code (swig-wrapped C+ + in this instance) that I want to compile into a module. The compilation itself works just fine and so does the initial linking. The linker command that distutils spits out looks somewhat like this g++ -bundle -undefined dynamic_lookup mymodule_wrap.o -o _mymodule.so -framework Carbon -framework Cocoa -framework ApplicationServices -framework AGL -framework OpenGL -framework GLUT - framework Cocoa /usr/lib/libz.dylib However, when I load the module in python a whole bunch of system symbols are undefined starting in this case with aglSwapBuffers ImportError: dlopen(_mymodule.so, 2): Symbol not found: _aglSwapBuffers Referenced from: _mymodule.so Expected in: dynamic lookup My understanding is that the _mymodule.so file should "know" that this symbol came out of the AGL framework and thus look for it there. I could understand if python wouldn't find the framework because of a DYLD_LIBRARY_PATH issue or the like but here the problem seems to be that the information from where the symbol came from is lost. If I do a "more" on the _mymodule.so file that seems to be indeed what happens. I see links to "/usr/lib/libz.dylib" and the system libraries in there but none to the frameworks. However, now comes the really interesting part. If I execute the *identical* command line from the same shell I called "python setup.py install" from I get a different library which *does* include the links to the frameworks. If I install that file instead of the original everything works as expected. So there seems to be a strange problem inside distutils. I looked at that source code but couldn't make any sense out of it. Any idea of what could cause this and how this could be fixed would be greatly appreciated Thanks Timo From kay.schluehr at gmx.net Thu May 22 00:25:11 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Wed, 21 May 2008 21:25:11 -0700 (PDT) Subject: C-like assignment expression? References: <68b5d090-9e3b-4e7d-9dda-fc1b099822c2@m73g2000hsh.googlegroups.com> Message-ID: <62e09b0a-468a-40b4-8202-e6c6a325a383@b1g2000hsg.googlegroups.com> On 21 Mai, 19:56, sturlamolden wrote: > On May 21, 11:38 am, boblat... at googlemail.com wrote: > > > if (match = my_re1.match(line): > > # use match > > elsif (match = my_re2.match(line)): > > # use match > > elsif (match = my_re3.match(line)) > > # use match > > > ...buy this is illegal in python. > > Assignment expressions is disallowed in Python to protect against a > very common bug in C/C++ programs, the (accidental) confusion of > > if (match = my_re1.match(line)) > > with > > if (match == my_re1.match(line)) > > or vice versa. This is just a syntactical issue. But what is the *value* of an assigment? In Python it is always None: assigments are statements, not expressions. However Guido and team have found a *pragmatic* solution for this at another place: with open("myFile") as f: BLOCK Compare this with a possible syntactical form of an if-statement: if EXPR as NAME: BLOCK This isn't ugly syntax-wise. It's just a bit harder to understand the semantics of an if-statement. It might read like this: "Evaluate EXPR and compute bool(EXPR). If this value is True assign EXPR to NAME and execute BLOCK. Otherwise refuse both assigment and BLOCK execution." Maybe assignment can be performed unconditionally as in the C case. I'm not sure about this. From mensanator at aol.com Fri May 2 15:04:54 2008 From: mensanator at aol.com (Mensanator) Date: Fri, 2 May 2008 12:04:54 -0700 (PDT) Subject: Finally had to plonk google gorups. References: <966256b2-fe7c-4ec5-900b-90b285311881@k10g2000prm.googlegroups.com> <87abjne42n.fsf@physik.rwth-aachen.de> <2dc0c81b0804300851h63500c54q8570202c9cece332@mail.gmail.com> <87r6cncp4r.fsf@physik.rwth-aachen.de> <2dc0c81b0804301029n5db13d7ej8cb71938f1980f7e@mail.gmail.com> <2dc0c81b0804301030x7858b8b5y14729ba3632c61b9@mail.gmail.com> Message-ID: <9ee1e917-a0c2-4c03-b611-e409e315c071@x41g2000hsb.googlegroups.com> On May 2, 1:20?pm, Michael Torrie wrote: > Mensanator wrote: > > On May 2, 9:53 am, Michael Torrie wrote: > >> Shawn Milochik wrote: > >>> How does one "plonk" stuff from Google Groups? Specifically, how > >>> can this be done in Gmail? > >> Set up a filter that looks for some phrase in the mail headers that > >> identifies messages originating from google groups. ?Gmail's filters are > >> fairly flexible. ?I'd probably just have it look for certain words. > >> Look at an e-mail's source (raw view) and particularly check in the > >> headers for things to filter by. > > > Why don't you just block all messages from Gmail? > > Brilliant! ?Seeing as he's asking about doing the filtering in Gmail > (implying it's use for his own posting and viewing the list) that would > work splendidly for him! ?Or not. > > Of course you're not likely to see this message either since I and many > folks on here post from gmail. > > Spam comes mainly from Google Groups, not as much from Gmail in my > experience. I didn't say it was POSTED from gmail, but the spammers often have gmail addresses, to wit: age of empires 3 crack serial 1 soray6034... at gmail.com (1 author) Apr 30 microsoft office word 2007 keygen download 1 soray6034... at gmail.com (1 author) Apr 30 ulead video studio 8 serial crack 1 soray6034... at gmail.com (1 author) Apr 30 daylight savings time patch 1 soray6034... at gmail.com (1 author) Apr 30 the sims 2 crack 1 soray6034... at gmail.com (1 author) Apr 30 fifa manager 08 crack 1 meisnernel73... at gmail.com (1 author) Apr 30 autocad 2005 cracks and cheats 1 meisnernel73... at gmail.com (1 author) Apr 30 rar password crack 2 meisnernel73... at gmail.com (1 author) Apr 30 crack rock cooking 1 meisnernel73... at gmail.com (1 author) Apr 30 vws crack 2 meisnernel73... at gmail.com (1 author) Apr 30 Why aren't you blaming gmail for it's contribution to the problem? From pistacchio at gmail.com Thu May 8 07:23:59 2008 From: pistacchio at gmail.com (pistacchio) Date: Thu, 08 May 2008 13:23:59 +0200 Subject: Newbie to python --- why should i learn ! References: <9f5ee6c3-86f7-401a-acc8-cd2c9b059fbd@x19g2000prg.googlegroups.com> Message-ID: Raxit at MyKavita.com ha scritto: > Hi, > > i was reading/learning some hello world program in python. > I think its very simillar to Java/C++/C#. What's different (except > syntax) ? > well, it's similar in the sense that it is a programming language. So you can say that assembly is similar to BASIC, but that both are different from finnish, but from a programmer's point of view, they're all rather different languages. > what can i do easily with python which is not easy in c++/java !? > generally speaking python is said to be easier to pick up for a pletora of reasons. technically speaking, it is not, for example, strongly typed, nor it forces you to use a programming paradigm like object oriented programming. This means that if you just want to see your name printed on the screen you can simply write: print "raxit" and get the work done. to understand it you just have to understand some basics like what is a string and what is a statement. in java, for example, it would look like: public class HelloWorld { public static void main(String[] args) { System.out.println("raxit"); } } in short, to obtain the same result (limited to this case) you have to write 650% more code and you're forced to know what is a class, what namespace means, what is a function (and arguments) and what are methods and the dot notation and an array. not that you won't encounter all of them learning python, but you're presented with all of them, all at once, in the moment where you just want to write the simplest program. that's why a typical java beginner's guide starts with ditto examples and adds: "ignore everything for the moment". i hate when i have to ignore things of a code that i'm writing! the same applies to C# and, to a certain extend, C++ that is a much older language and present different learning problems. Now, what can you do with python? Virtually everything (network programming, game programming, server side scripting). In most cases, it would run slower than it would do with the other languages (even slower than the slow java). You won't do drivers or kernels in python, but you won't even code them in java or C#. the programs you'll write will mostly run on a number of different platform, like java programs. porting a c++ is a bit tougher. at the moment there is project (mono) that is porting the .net platform (where c# runs) to multiple platforms, but basically, if you write a c# program you're programming for windows. hope it helps > Tnx, > Raxit > www.mykavita.com From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun May 11 17:35:59 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sun, 11 May 2008 23:35:59 +0200 Subject: Simple question References: <68lj5oF2sudm7U1@mid.individual.net> <205f1f1e-073b-4edc-ad18-59d1d1b065d6@59g2000hsb.googlegroups.com> Message-ID: <68p75vF2ubdpbU1@mid.individual.net> Gandalf wrote: > On May 10, 2:36 pm, Bjoern Schliessmann > It depends on your web server configuration. To get your web >> server execute Python code, there are several alternatives like >> >> * CGI >> * FastCGI >> * mod_python > > my server is my computer I didn't mean which server hardware you use, but which web server application. You need a web server application to use your "WWW directory" in such a way. > and all i did way to install python on it. Nah, you probably have at least an operating system beneath Python. Regards, Bj?rn -- BOFH excuse #264: Your modem doesn't speak English. From turian at gmail.com Sat May 10 02:38:16 2008 From: turian at gmail.com (Joseph Turian) Date: Fri, 9 May 2008 23:38:16 -0700 (PDT) Subject: Find more than one error at once Message-ID: Is it possible to coax python to find more than one error at once? Thanks, Joseph From dfnsonfsduifb at gmx.de Sat May 24 07:12:13 2008 From: dfnsonfsduifb at gmx.de (Johannes Bauer) Date: Sat, 24 May 2008 13:12:13 +0200 Subject: Assignment and comparison in one statement In-Reply-To: <10f19bee-1e0a-4401-a03b-18c458388297@s50g2000hsb.googlegroups.com> References: <10f19bee-1e0a-4401-a03b-18c458388297@s50g2000hsb.googlegroups.com> Message-ID: Carl Banks schrieb: > p = myfunction() > if p: > print p > > (I recommend doing it this way in C, too.) This is okay for if-clauses, but sucks for while-loops: while (fgets(buf, sizeof(buf), f)) { printf("%s\n", buf); } is much shorter than char *tmp; tmp = fgets(buf, sizeof(buf), f); while (tmp) { printf("%s\n", buf); tmp = fgets(buf, sizeof(buf), f); } > For the case where you want to do this in an elif-clause, look for the > recent thread "C-like assignment expression?" which list some > workarounds. Or just Google this newsgroup for "assignment > expression". It's one of few minor irritating things in Python > syntax. Alright, I will. Thanks. Regards, Johannes -- "Wer etwas kritisiert muss es noch lange nicht selber besser k?nnen. Es reicht zu wissen, da? andere es besser k?nnen und andere es auch besser machen um einen Vergleich zu bringen." - Wolfgang Gerber in de.sci.electronics <47fa8447$0$11545$9b622d9e at news.freenet.de> From hat at se-162.se.wtb.tue.nl Fri May 16 08:01:08 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Fri, 16 May 2008 14:01:08 +0200 Subject: managing properties/configurations References: <408a6c83-8869-4c76-9acf-48cd42075658@y22g2000prd.googlegroups.com> <9976ee1f-1d37-4252-802a-8dd3c3de7d3d@k1g2000prb.googlegroups.com> <1ff9bbaa-ae04-495a-a9a3-d2f7741e6cc5@k10g2000prm.googlegroups.com> Message-ID: On 2008-05-16, Venkatraman.S. wrote: > The problem being, if i change the config file, then the configobj has > to reload this file again. I do not want to 'refresh' the config obj > per transaction but only when the config params change. If you have trustable time stamps at your file system, you could check the time stamp before loading. > I was thinking along the terms of an Interrupt driven program, which > when getting a custom interrupts reloads the file - any potential > loopholes/falls that anyone can anticipate? Many unix deamons use SIGHUP signal to reload configs. Maybe that would be an option? Sincerely, Albert From paul at rudin.co.uk Fri May 23 04:30:42 2008 From: paul at rudin.co.uk (Paul Rudin) Date: Fri, 23 May 2008 09:30:42 +0100 Subject: Ploneboard - grouping forums and setting up on disk Message-ID: <87tzgpzakt.fsf@rudin.co.uk> I'm investigating using ploneboard and have a couple of questions. First of all I don't quite get what the global view/local view distinction is - perhaps someone could be good enough to explain what it's for. If it possible to group forums so that permissions can be applied to each set so - for example - we have a set of public forums viewable by everyone and a set of member's forums viewable only by logged in members. I understand that permission can be set for each forum individially, but it would be nice to have a grouping so that a new forum can be added to a group and it automatically gets the appropriate permissions for that group. Finally - is it possible to configure the available forums and permission on disk, so that a given forum structure can easily be setup in a new plone instance without having to redo it through the web each time? TIA. From bj_666 at gmx.net Sat May 10 02:38:28 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 10 May 2008 06:38:28 GMT Subject: People still using Tkinter? References: Message-ID: <68ku74F2sm1usU1@mid.uni-berlin.de> On Sat, 10 May 2008 00:20:33 -0500, Kenneth McDonald wrote: > Any guesses as to how many people are still using Tkinter? And can > anyone direct me to good, current docs for Tkinter? AFAIK `Tkinter` hasn't changed much over time, so "old" documentation is still current. Ciao, Marc 'BlackJack' Rintsch From toddw at activestate.com Mon May 5 16:59:55 2008 From: toddw at activestate.com (Todd Whiteman) Date: Mon, 05 May 2008 13:59:55 -0700 Subject: SSL through python. possible ? In-Reply-To: <715b8048-8b88-44cd-a40a-722650125f19@e53g2000hsa.googlegroups.com> References: <6ca74a29-1121-4b53-abb9-6bcecf33272a@m3g2000hsc.googlegroups.com> <715b8048-8b88-44cd-a40a-722650125f19@e53g2000hsa.googlegroups.com> Message-ID: <481F754B.8060505@activestate.com> TkNeo wrote: > ok i have tried around a lot but no luck. I think M2Crypto is my best > option except it requires a minimum of python 2.4 which i don't have. > > What i am trying to do is to do an FTP transfer that uses SSL > (username, password authentication) and not a certificate file. The > few example i have found of the Openssl module use a certificate for > authentication unlike what i want to do. Komodo uses ssl to provide FTPS support (FTP over SSL), using the Python ssl socket library. From memory, I think there were problems trying to get FTPS to work on earlier versions of python (earlier than Python 2.4) and also a few problems working with Python 2.4 itself. This code might provide some help (you can search for FTPS): http://svn.openkomodo.com/openkomodo/view/openkomodo/trunk/src/components/koFTP.py Cheers, Todd From jj.renes at hccnet.nl Sun May 4 10:56:14 2008 From: jj.renes at hccnet.nl (joop renes) Date: Sun, 04 May 2008 16:56:14 +0200 Subject: multirhreading&boost.python Message-ID: <1209912974.11364.10.camel@van-dattum> hi, i hope this is the right list for the following question of a c++ hacker,python newbie. i have a library in c++ to which i want to add a python GUI and other python stuff.The library has multithreading components, while python uses a reference counted memory model. Usually mixing reference counting with multithreading is frowned upon, at least in the c++ world. what am i to expect in the python world, if i bring multithreading c++ into it? just performance penalty or total disaster? best regards joop renes. From certo at comeno.it Mon May 26 14:09:31 2008 From: certo at comeno.it (imho) Date: Mon, 26 May 2008 18:09:31 GMT Subject: About Michele Simionato's "classinitializer" decorator In-Reply-To: <5c215286-6a18-4c13-9ca4-bf9fa9f5679e@m73g2000hsh.googlegroups.com> References: <5c215286-6a18-4c13-9ca4-bf9fa9f5679e@m73g2000hsh.googlegroups.com> Message-ID: Michele Simionato ha scritto: > On May 26, 7:10 pm, imho wrote: >> Hi all. >> I just send this post as a comment to the third part of Michele >> Simionato's article about metaprogramming techniques at: >> >> http://www.ibm.com/developerworks/linux/library/l-pymeta3.html?S_TACT... >> >> I found extremely useful the classinitializer "trick". > > I never use it. Too clever. I am waiting for class decorators > in Python 2.6. Uhm... I suspected that :-) >> I was thinking >> over the caveat not to call a class initializer after the _metaclass_ >> hook (an exception being raised in that case). >> Am I wrong if I state there's a plain solution to this ? > > I think your solution is fine. Still, consider waiting for > class decorators ;) > > Michele Simionato Of course, I stand waiting here :-) Thanks, Diego. From mal at egenix.com Tue May 6 05:38:11 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Tue, 06 May 2008 11:38:11 +0200 Subject: config files in python In-Reply-To: <32822fe60805060207w46752243tdb0e4cad19ffa78b@mail.gmail.com> References: <44f9662d-a88d-418c-a11d-b7b472b01fc3@j33g2000pri.googlegroups.com> <87332548-4f15-49c3-8c92-4aa20e355747@n1g2000prb.googlegroups.com> <482017EA.40706@egenix.com> <32822fe60805060207w46752243tdb0e4cad19ffa78b@mail.gmail.com> Message-ID: <48202703.2020800@egenix.com> On 2008-05-06 11:07, Jorge Vargas wrote: > On Tue, May 6, 2008 at 4:33 AM, M.-A. Lemburg wrote: >> On 2008-05-06 01:16, Matimus wrote: >> >>> On May 4, 11:35 pm, sandipm wrote: >>> >>>> Hi, >>>> In my application, I have some configurable information which is used >>>> by different processes. currently I have stored configration in a >>>> conf.py file as name=value pairs, and I am importing conf.py file to >>>> use this variable. it works well >>>> >>>> import conf >>>> print conf.SomeVariable >>>> >>>> but if I need to change some configuration parameteres, it would need >>>> me to restart processes. >>>> >>>> I want to store this data in some conf file (txt) and would like to >>>> use it same way as I am using these variables as defined in py >>>> files. >>>> >>>> one solution I can think of is writing data as a dictionary into conf >>>> file. and then by reading data, apply eval on that data. and update >>>> local dict? but this is not a good solution.... >>>> >>>> any pointers? >>>> >>>> Sandip >>>> >>> I would load the configuration file using `imp.load_source'. This >>> allows you to load the config file by filename, and gets away from the >>> issue of accidentally importing a file somewhere else in pythons >>> search path. Also, calling imp.load_source will reload the module when >>> called a second time. >>> >> > >> >>> http://docs.python.org/lib/module-imp.html >>> >> Why not just use execfile() ? >> >> http://www.python.org/doc/2.2.3/lib/built-in-funcs.html >> > that is very bad for this case, from what he is suggesting this is a > server install so you are basically giving a vector of remote code > execution (same with the first approach) but then execfile has the > issue that it goes into your current namespace possibly creating a > namespace crash which is even worst because an attacker can shallow > say your auth module with something that will just return. Not really: you can pass in the globals and locals dictionary to execfile(), just like you can with __import__(), but you can't with imp.load_source(), so execfile() is safer than using import directly or via the imp module. I don't see a problem with remote code execution - there's nothing "remote" in loading a local config :-) Also, you can pretty prevent all code execution that goes beyond simple evals by restricting the globals, e.g. globals = {'__builtins__':{}} execfile('config.py', globals) Doing so will prevent imports and doesn't expose the builtins either, so there's little left for a user of the server to manipulate - besides doing so by just inserting his own os.py or similar common Python module would be far easier anyway ;-) >>> [conf.py] >>> a = 1 >>> b = 2 >>> class c: >>> a = "hello" >>> b = "world" >>> [/end conf.py] >>> >>> >>>>>> conf = imp.load_source("conf", "./conf.py") >>>>>> conf.a >>>>>> >>> 1 >>> >>>>>> conf.b >>>>>> >>> 2 >>> >>>>>> conf.c.a >>>>>> >>> 'hello' >>> >>>>>> conf.c.b >>>>>> >>> 'world' >>> >>> >>> >>> There are so many ways potential solutions to your problem that, >>> without any more details, it is hard to suggest anything. >>> >>> Here are some potential solutions: >>> >>> ConfigParser - module for handling ini files >>> xml - several built-in modules for handling XML files >>> sqlite3 - a `lite' SQL database built-in in python 2.5 + (can be used >>> for config data) >>> windows registry - _winreg module >>> pickle - serialize python objects >>> marshal - similar to pickle, only works for simple objects >>> >>> Those are just the built-in solutions. If you wanna look at 3rd party >>> solutions, prepare for overload. The number of alternative INI parsers >>> alone is staggering. >>> >>> Also, there are many ways to organize your data and use a solution >>> similar to what you are already using. >>> >>> I guess what I'm trying to say is... don't roll your own, it would be >>> a waste of time, this problem has been solved 100s of times. That is, >>> unless you want to do it for fun. >>> >>> Matt >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >> -- >> Marc-Andre Lemburg >> eGenix.com >> >> Professional Python Services directly from the Source (#1, May 06 2008) >> >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >> >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >> >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ >> ________________________________________________________________________ >> >> :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: >> >> >> eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 >> D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg >> Registered at Amtsgericht Duesseldorf: HRB 46611 >> >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, May 06 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From andreas.tawn at ubisoft.com Thu May 15 13:20:58 2008 From: andreas.tawn at ubisoft.com (Andreas Tawn) Date: Thu, 15 May 2008 19:20:58 +0200 Subject: exists=false, but no complaint when i open it!? In-Reply-To: References: <285e0ce6-1371-4ab7-9281-ad1d664a480f@a23g2000hsc.googlegroups.com> Message-ID: <8AEDA5E3386EA742B8C24C95FF0C75800403F7BC@PDC-MAIL3.ubisoft.org> >print os.path.exists('C:\Users\saftarn\Desktop\NetFlixDataSet >\training_set') returns False... > >i have thourogly checked the filename to be correct and if we assume >it is what could this mean then? >i had a problem one other time when i had renamed a file but windows >didnt rename it compeltely apparently. It's escape characters again. You're asking for 'C:\Users\saftarn\Desktop\NetFlixDataSet\training_set', but Python interprets that as 'C:\Users\saftarn\Desktop\NetFlixDataSet raining_set', which probably doesn't exist. The first example works by accident because backslash plus the first letter of each folder in your path happens to not match any of Python's string formatting characters. Use forward slashes or double up the backslashes to stop this happening. Cheers, Drea From asmodai at in-nomine.org Thu May 8 07:19:34 2008 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Thu, 8 May 2008 13:19:34 +0200 Subject: PHP + TinyButStrong Python replacement In-Reply-To: References: Message-ID: <20080508111934.GB1016@nexus.in-nomine.org> -On [20080507 15:06], Mike Driscoll (kyosohma at gmail.com) wrote: >http://genshi.edgewall.org/ >http://www.kid-templating.org/ >http://www.cheetahtemplate.org/ >http://turbogears.org/ Add the following to that list: http://jinja.pocoo.org/ http://www.makotemplates.org/ I think Jinja and Mako are currently two of the fastest around. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ | GPG: 2EAC625B If Winter comes, can Spring be far behind..? From mensanator at aol.com Fri May 9 00:58:42 2008 From: mensanator at aol.com (Mensanator) Date: Thu, 8 May 2008 21:58:42 -0700 (PDT) Subject: python newbie: some surprises References: <67b60370-bed9-4f43-b401-25ce2fd89522@t54g2000hsg.googlegroups.com> <64fb7f0f-c8fa-4324-8a13-f4e99082c470@p25g2000hsf.googlegroups.com> Message-ID: <98967816-e310-4b59-a444-26fe0b37d550@a23g2000hsc.googlegroups.com> On May 8, 11:47?pm, Yves Dorfsman wrote: > Mensanator wrote: > >> 2. python requires to pass "self" to all instance methods > > > Who uses methods? > > Is this a joke ? Yes. > What are the alternatives ? > > > > >> and I missed ":" often. :) > > > Try using something like Seed7, where you have to use "then" with > > "if" and "do" with "while" and "end" in every block. Maybe you'll > > come to appreciate significant whitespace and ":". > > I see the point of the OP. Couldn't the new-line be used as an equivalent of > ? ':', for example, do you find this difficult to read: > > if a == 3 > ? ?do_something() > > if a == 3: do_something() > > And surely, it should be easy to parse by the compiler. If they were to chane it, I wouldn't complain. I just think it doesn't deserve complaints when compared to other systems. > > Yves.http://www.SollerS.ca From denis.kasak2718281828 at gmail.com Sun May 25 18:36:49 2008 From: denis.kasak2718281828 at gmail.com (Denis Kasak) Date: Mon, 26 May 2008 00:36:49 +0200 Subject: Getting a set of lambda functions References: Message-ID: On Sun, May 25, 2008 at 1:43 PM, Martin Manns wrote: > Hi, > > I try to get a set of lambda functions that allows me executing each > function code exactly once. Therefore, I would like to modify the set > function to compare the func_code properties (or the lambda > functions to use this property for comparison). > > (The reason is that the real function list is quite large (> 1E5), there > are only few functions with non-equal code and the order of execution > is not important.) > > How can I achieve this? > > >>> func_strings=['x', 'x+1', 'x+2', 'x'] > >>> funclist = [eval('lambda x:' + func) for func in func_strings] > >>> len(funclist) > 4 > >>> len(set(funclist)) > 4 > >>> funclist[0].func_code == funclist[3].func_code > True > >>> funclist[0] == funclist[3] > False Isn't this a bug? Shouldn't it be possible to create a set of different lambda functions via a loop? At first I thought it was just a quirk of list comprehensions, but the following example also yields incorrect (or at least unintuitive) results: >>> spam = [] >>> for i in range(10): ... spam.append(lambda: i) >>> spam[0]() 9 >>> spam[1]() 9 Manually creating the lambdas and appending them to a list works as expected, naturally; I don't see a good reason why it wouldn't work with a loop. Am I missing something? -- Denis Kasak From h.goebel at goebel-consult.de Sat May 17 13:48:42 2008 From: h.goebel at goebel-consult.de (Hartmut Goebel) Date: Sat, 17 May 2008 19:48:42 +0200 Subject: rst2mediawiki? Message-ID: <482f1a7a$0$6552$9b4e6d93@newsspool3.arcor-online.net> Hello, I'm looking for a rst2mediawiki writer. Unfortunatly mediawiki is quite widespread, but I prefere to sty with rst. Any hint? -- Sch?nen Gru? - Regards Hartmut Goebel Goebel Consult Spezialist f?r IT-Sicherheit in komplexen Umgebungen http://www.goebel-consult.de From arkanes at gmail.com Wed May 21 17:17:59 2008 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 21 May 2008 16:17:59 -0500 Subject: Bug in floating-point addition: is anyone else seeing this? In-Reply-To: <8187c3b6-a772-456f-a54f-0af7babb353e@w34g2000prm.googlegroups.com> References: <8187c3b6-a772-456f-a54f-0af7babb353e@w34g2000prm.googlegroups.com> Message-ID: <4866bea60805211417l3e6197e4ue83b27d27b6a0277@mail.gmail.com> On Wed, May 21, 2008 at 3:56 PM, Dave Parker wrote: > On May 21, 2:44 pm, "Jerry Hill" wrote: > >> My understand is no, not if you're using IEEE floating point. > > Yes, that would explain it. I assumed that Python automatically > switched from hardware floating point to multi-precision floating > point so that the user is guaranteed to always get correctly rounded > results for +, -, *, and /, like Flaming Thunder gives. Correct > rounding and accurate results are fairly crucial to mathematical and > scientific programming, in my opinion. > -- If you're going to use every post and question about Python as an opportunity to pimp your own pet language you're going irritate even more people than you have already. From notbob at nothome.com Mon May 5 14:43:11 2008 From: notbob at nothome.com (notbob) Date: Mon, 05 May 2008 18:43:11 GMT Subject: Are rank noobs tolerated, here? References: Message-ID: <3zITj.35199$gB5.25251@fe105.usenetserver.com> On 2008-05-04, notbob wrote: > I'm trying to learn how to program. I'm using: > > How to Think Like a Computer Scientist > > Learning with Python > 2nd Edition http://openbookproject.net//thinkCSpy/index.xhtml OK then, using the above, I get everything up till chap 3 and functions and then it all falls apart. I try using his code and nothing. I'm running vers 2.5.1 on slackware 12. Here's what I don't get: ---------- "Here is an example of a user-defined function that has a parameter: def print_twice(bruce): print bruce, bruce This function takes a single argument and assigns it to the parameter named bruce. The value of the parameter (at this point we have no idea what it will be) is printed twice, followed by a newline. The name bruce was chosen to suggest that the name you give a parameter is up to you, but in general, you want to choose something more illustrative than bruce. ****ME**** is this just an example of how the def should be written and it doesn't really do anthing... yet? I read another newb explanation here: http://www.codepedia.com/1/BeginnersGuideToPython_Functions ...and it doesn't work, either. I define myfirstfunction in the pyth editor and give the command print myfirstfuntion and I get back this: ....when I add the ._doc_, it get this: Traceback (most recent call last): File "", line 1, in AttributeError: 'function' object has no attribute '_doc_' ....so, there is a no go there, too. ****ME**** The interactive Python shell provides us with a convenient way to test our functions. We can use the import statement to bring the functions we have defined in a script into the interpreter session. To see how this works, assume the print_twice function is defined in a script named chap03.py. We can now test it interactively by importing it into our Python shell session: ****ME**** ok, I try and follow the above, but where is he getting the script? So, I make a script called chap03.py and put it in ~/pyth/chap03/. ****ME**** >>> from chap03 import * >>> print_twice('Spam') Spam Spam >>> print_twice(5) 5 5 >>> print_twice(3.14159) 3.14159 3.14159 ****ME**** I then try an do the import thing above, but the pyth ed accepts none of it. not from: from ~/pyth/chap03/ import * from chap03 import * #taken from ~/pyth/ ....nor from any other configuration I can imagine, so that "from" command makes no sense. ****ME**** In a function call, the value of the argument is assigned to the corresponding parameter in the function definition. In effect, it is if bruce = 'Spam' is executed when print_twice('Spam') is called, bruce = 5 in print_twice(5), and bruce = 3.14159 in print_twice(3.14159)." ****ME**** OK, I'm totally lost. Neither the above or the other link works or make any sense at all. Is the above print_twice(5), etc, supposed to work like the original print_twice(bruce) function (which still doesn't!), just with a different parameter? Call me stupid, but I'd sure like to get past this. How am I supposed to get the original def to work? I've yet to figure out how to get plain ol': bruce bruce Yes, I've indented 4 spaces where I should. ****ME**** ---------- I feel dumber'n a bag 0' hammers and in need of clarification. Thank you nb From sjmachin at lexicon.net Fri May 9 19:52:50 2008 From: sjmachin at lexicon.net (John Machin) Date: Fri, 09 May 2008 23:52:50 GMT Subject: regexp help In-Reply-To: <1cd897aa-0027-4c5b-8bf2-f7c5781df93e@24g2000hsh.googlegroups.com> References: <834d8448-5d6a-4f49-9be6-6501a0b5fd92@k37g2000hsf.googlegroups.com> <1cd897aa-0027-4c5b-8bf2-f7c5781df93e@24g2000hsh.googlegroups.com> Message-ID: <4824e3ce$1@news.mel.dft.com.au> Paul McGuire wrote: > from re import * Perhaps you intended "import re". > vowels = "aAeEiIoOuU" > cons = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ" > encodeRe = re.compile(r"([%s])[%s]\1" % (cons,vowels)) > print encodeRe.sub(r"\1",s) > > This is actually a little more complex than you asked - it will search > for any consonant-vowel-same_consonant triple, and replace it with the > leading consonant. To meet your original request, change to: > > from re import * And again. > cons = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ" > encodeRe = re.compile(r"([%s])o\1" % cons) > print encodeRe.sub(r"\1",s) > > Both print "prince". > No they don't. The result is "NameError: name 're' is not defined". From gnewsg at gmail.com Sat May 31 15:40:15 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Sat, 31 May 2008 12:40:15 -0700 (PDT) Subject: ThreadPoolingMixIn References: <3d9dac72-ce4d-4ce5-9213-4bb17aff2f9e@r66g2000hsg.googlegroups.com> Message-ID: On 30 Mag, 22:40, pavel.uva... at gmail.com wrote: > Hi, everybody! > > I wrote a useful class ThreadPoolingMixIn which can be used to create > fast thread-based servers. This mix-in works much faster than > ThreadingMixIn because it doesn't create a new thread on each request. > > Is it worth including in SocketServer.py? > > from __future__ import with_statement > from SocketServer import ThreadingMixIn > import threading > import Queue > class ThreadPoolingMixIn(ThreadingMixIn): > ? ? """Mix-in class to handle requests in a thread > pool. > > ? ? The pool grows and thrinks depending on > load. > > ? ? For instance, a threading UDP server class is created as > follows: > > ? ? class ThreadPoolingUDPServer(ThreadPoolingMixIn, UDPServer): > pass > > ? ? """ > ? ? __author__ = 'Pavel Uvarov ' > > ? ? def init_thread_pool(self, min_workers = 5, > ? ? ? ? ? ? ? ? ? ? ? ? ?max_workers = 100, min_spare_workers = 5): > ? ? ? ? """Initialize thread pool.""" > ? ? ? ? self.q = Queue.Queue() > ? ? ? ? self.min_workers = min_workers > ? ? ? ? self.max_workers = max_workers > ? ? ? ? self.min_spare_workers = min_spare_workers > ? ? ? ? self.num_workers = 0 > ? ? ? ? self.num_busy_workers = 0 > ? ? ? ? self.workers_mutex = threading.Lock() > ? ? ? ? self.start_workers(self.min_workers) > > ? ? def start_workers(self, n): > ? ? ? ? """Start n workers.""" > ? ? ? ? for i in xrange(n): > ? ? ? ? ? ? t = threading.Thread(target = self.worker) > ? ? ? ? ? ? t.setDaemon(True) > ? ? ? ? ? ? t.start() > > ? ? def worker(self): > ? ? ? ? """A function of a working > thread. > > ? ? ? ? It gets a request from queue (blocking if > there > ? ? ? ? are no requests) and processes > it. > > ? ? ? ? After processing it checks how many spare > workers > ? ? ? ? are there now and if this value is greater > than > ? ? ? ? self.min_spare_workers then the worker > exits. > ? ? ? ? Otherwise it loops > infinitely. > > ? ? ? ? """ > ? ? ? ? with self.workers_mutex: > ? ? ? ? ? ? self.num_workers += 1 > ? ? ? ? while True: > ? ? ? ? ? ? (request, client_address) = self.q.get() > ? ? ? ? ? ? with self.workers_mutex: > ? ? ? ? ? ? ? ? self.num_busy_workers += 1 > ? ? ? ? ? ? self.process_request_thread(request, client_address) > ? ? ? ? ? ? self.q.task_done() > ? ? ? ? ? ? with self.workers_mutex: > ? ? ? ? ? ? ? ? self.num_busy_workers -= 1 > ? ? ? ? ? ? ? ? if self.num_workers - self.num_busy_workers > \ > ? ? ? ? ? ? ? ? ? ? ? ? self.min_spare_workers: > ? ? ? ? ? ? ? ? ? ? self.num_workers -= 1 > ? ? ? ? ? ? ? ? ? ? return > > ? ? def process_request(self, request, client_address): > ? ? ? ? """Puts a request into > queue. > > ? ? ? ? If the queue size is too large, it adds extra > worker. > > ? ? ? ? """ > ? ? ? ? self.q.put((request, client_address)) > ? ? ? ? with self.workers_mutex: > ? ? ? ? ? ? if self.q.qsize() > 3 and self.num_workers < > self.max_workers: > ? ? ? ? ? ? ? ? self.start_workers(1) > > ? ? def join(self): > ? ? ? ? """Wait for all busy threads""" > ? ? ? ? self.q.join() This is not the right place to discuss about such a thing. Post this same message on python-dev ml or, even better, open a new ticket on the bug tracker attaching the patch and, most important, a benchmark demonstrating the speed improvement. --- Giampaolo http://code.google.com/p/pyftpdlib/ From miller.paul.w at gmail.com Mon May 26 01:41:10 2008 From: miller.paul.w at gmail.com (miller.paul.w at gmail.com) Date: Sun, 25 May 2008 22:41:10 -0700 (PDT) Subject: set partition question References: <7b64328e-d4e0-4ec1-8918-3cab94e2f815@e39g2000hsf.googlegroups.com> <3cf66f61-5a7e-44a2-8cc4-b879269fd98b@y22g2000prd.googlegroups.com> Message-ID: <3a550801-6e43-4c81-9749-7cb157446668@y21g2000hsf.googlegroups.com> On May 25, 11:40?pm, pball.benet... at gmail.com wrote: > This is a problem in statistical estimation. Given n records made up > of k variables, define a cell as the point in the cartesian product of > v_1 * v_2 * ... * v_k. I want to apply an estimator on the data in > each cell. So, basically, V = (v_1, v_2, ... , v_{k-1}, v_k) can be regarded as an abstract, k-dimensional vector, right? If I understand your revised problem statement correctly, what you really want to do is build a graph of these vectors, where graph adjacency is equivalent to adjacency in your sense. That is, imagine you have V_1, V_2, ... , V_n all sitting out in front of you, represented abstractly as simple points. Draw a line between V_i and V_j if they are "adjacent" in your sense of the word. What you have then is a graph structure where your version of adjacency exactly corresponds to graph adjacency. Then, in your language, a stratum is simply a path in this graph, and finding those is easy. That is, unless I've got this all wrong. :-) From vlastimil.brom at gmail.com Wed May 7 08:29:04 2008 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Wed, 7 May 2008 14:29:04 +0200 Subject: mxTexTools (Re: using sqlite3 - execute vs. executemany; committing ...) In-Reply-To: <48217560.9070707@egenix.com> References: <9fdb569a0805031431r6666e950pc6dbc8aab6e36684@mail.gmail.com> <18c1e6480805040214m5ecd0b27t9800bfc4a39daec8@mail.gmail.com> <9fdb569a0805041407s75c8ad3bsc08c8bac87fa0d83@mail.gmail.com> <18c1e6480805041536x7287d23ds9d9bfcf6ec73e123@mail.gmail.com> <9fdb569a0805050559q83999d4v6043acb94c9797d0@mail.gmail.com> <18c1e6480805060207k5255414ey6dacef759d17966@mail.gmail.com> <9fdb569a0805061507j70706aa5ie32ddfeb832ccfa7@mail.gmail.com> <48217560.9070707@egenix.com> Message-ID: <9fdb569a0805070529v67412125s98874723179bc309@mail.gmail.com> 2008/5/7, M.-A. Lemburg : > > On 2008-05-07 00:07, Vlastimil Brom wrote: > > > Thanks for reminding me about > > the mxTextTools; I looked at this package very quickly several months > > ago and it seemed quite > > complex and heavy-weight, but maybe I will reconsider this after some > > investigation ... > > > > mxTextTools gives you almost full C speed while still being programmable > in Python and without a compiler. > > It is a low level parsing engine. Here's talk I gave on mxTextTools > last year: > > > http://www.egenix.com/library/presentations/EuroPython2007-Parsing-Languages-with-mxTextTools/ > > If you're looking for ways to hide the complexity, you could try > SimpleParse (which uses mxTextTools for the parsing, but provides a > grammar based front-end). > > -- > Marc-Andre Lemburg > eGenix.com > > Professional Python Services directly from the Source (#1, May 07 2008) > >>> Python/Zope Consulting and Support ... http://www.egenix.com/ > >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ > >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ > ________________________________________________________________________ > > :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: > > > eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 > D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg > Registered at Amtsgericht Duesseldorf: HRB 46611 > Thank you very much for the info and for the helpful references, Marc-Andre, I'll definitely have to take a closer look at mxTextTools, thanks for making it available. Greetings, Vlasta -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Fri May 9 10:41:42 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 09 May 2008 11:41:42 -0300 Subject: Function creation (what happened?) References: <199c06d7-601c-49f3-a88c-c28f7283e619@25g2000hsx.googlegroups.com> Message-ID: En Fri, 09 May 2008 10:02:01 -0300, Viktor escribi?: > This completely slipped of my mind... :) > > I'm trying to change the: > http://wordaligned.org/svn/etc/echo/echo.py > > So if the function is method it prints ClassName.MethodName instead of > MethodName(self|klass|cls=<... ClassName>). > > But it turned out that in the decorator, the wrapped function is > always just a TypeFunction (I cannot find out if the function is > method, classmethod, staticmethod or just a plain function - tried > with inspect also)... And what is most interesting, when I do: The decorator receives the original, plain function (unless you chain decorators) and whatever it returns is used instead of the original function. > def w(fn): > print 'fn:', id(fn) > return fn > > class A: > @w > def __init__(self): pass > > print 'A.__init__:', id(A.__init__) > > It turns out that the function I receive in the wrapper (even when I > return the same function) is not the function which will finally be > attached to the class... > Is there a way to find out in the decorator "what will the decorated > function be"? Whatever you return from the decorator. But the decorator returns a *function* and A.__init__ is a *method*, an instance method in fact. The function can be found as A.__dict__['__init__']. Try this: m = A.__init__ print m, type(m), id(m) f = A.__dict__['__init__'] print f, type(f), id(f) A method combines a function with an instance that becomes the "self" argument. In your case you're building an "unbound" method because it's not tied to a particular instance, but even such unbound method is not the same thing as a plain function (it must ensure that its first argument, when called, is an A instance and not any other object). The "magic" that converts a simple function into an instance method, for old-style classes like yours, was in the Class type itself. For new style classes, the descriptor protocol is used. See http://www.python.org/doc/newstyle/ -- Gabriel Genellina From bignose+hates-spam at benfinney.id.au Fri May 2 10:43:02 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 03 May 2008 00:43:02 +1000 Subject: #!/usr/bin/env python vs. #!/usr/bin/python References: <87abj91j8u.fsf@benfinney.id.au> <871w4l1cjj.fsf@benfinney.id.au> <87r6ckzvyv.fsf@benfinney.id.au> Message-ID: <87bq3ozs09.fsf@benfinney.id.au> Roy Smith writes: > In article <87r6ckzvyv.fsf at benfinney.id.au>, > Ben Finney wrote: > > > Whereas if Python is *not* installed from an OS package, it's up > > to the sys admin to ensure that it works -- not up to my program. > > So I don't see the point in making it work by default, when what I > > want for my program is that it works *with the default Python*, > > not with some non-default installation. > > Ben, > > Have you ever shipped software to a customer? Yes, and all parties have been quite happy with the results. > Imagine the following conversation: > > Customer: "Your product is broken. It says it can't find python, and > I know I have it installed". > > Vendor: "Where do you have it installed?" > > Customer: "In /opt/bin/python" > > Vendor: "Oh, that's your problem, it HAS to be in /usr/bin/python". At this point the vendor isn't me, because this statement isn't true. See below. > Customer: "I can't install it there because reason the customer has>. If you can't make your product work > without requiring me to install python in /usr/bin, I'm afraid I > can't buy your product". At this point they have the simple option of running the program with 'python /path/to/the/program'. It's certainly not a case of "can't make the product work". It is, however, a case of "can't automatically account for every local customisation sysadmins choose to make on their systems". Perfectly willing to work with them to get their specific environment working, but as a matter of simple economics it's not worth my time to attempt to make such corner cases work automatically. > If you want to hard-code /usr/bin/python into your application, > that's your decision. If you would like to take on the task of > convincing every sysadmin in the world to do things the way you > think they should be done, have fun. If they've already chosen to install Python to some unpredictable location, they know what they're doing enough to invoke the program in a specific way to get it working. -- \ Rommel: "Don't move, or I'll turn the key on this can of Spam!" | `\ -- The Goon Show, _Rommel's Treasure_ | _o__) | Ben Finney From terry.yinzhe at gmail.com Sun May 18 11:29:17 2008 From: terry.yinzhe at gmail.com (Terry) Date: Sun, 18 May 2008 08:29:17 -0700 (PDT) Subject: Get all the instances of one class References: <29f39184-2daa-49fc-a7af-7f869fd2d688@h1g2000prh.googlegroups.com> Message-ID: <8c40793e-55bc-48de-96fa-47ebb89b9a88@u36g2000prf.googlegroups.com> On May 17, 8:04 am, "Gabriel Genellina" wrote: > En Fri, 16 May 2008 20:44:00 -0300, Terry > escribi?: > > > Is there a simple way to get all the instances of one class? I mean > > without any additional change to the class. > > Try with gc.get_referrers() > > py> import gc > py> class A(object): pass > ... > py> a,b,c = A(),A(),A() > py> A > > py> for item in gc.get_referrers(A): print type(item) > ... > > > > > > > > > > We need to filter that list, keeping only A's instances: > > py> [item for item in gc.get_referrers(A) if isinstance(item,A)] > [<__main__.A object at 0x00A40DC8>, <__main__.A object at 0x00A40DF0>, > <__main__.A object at 0x00A40E18>] > > -- > Gabriel Genellina Thanks! This is what I'm looking for. From bruno.desthuilliers at gmail.com Mon May 26 14:42:08 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Mon, 26 May 2008 11:42:08 -0700 (PDT) Subject: Storing objects in relational database References: <03a17198-3eb2-438e-97c9-db18c0c24a80@c65g2000hsa.googlegroups.com> Message-ID: On 24 mai, 13:01, Piotr Chamera wrote: > bruno.desthuilli... at gmail.com pisze: > > > I don't know if you'd label it 'elegant', but as far as I'm concerned, > > storing serialized objects as blobs in a relational database is mostly > > non-sense. If I use a relational database, it's because it is a > > *relational* database. If you want an OODB, then we have the ZODB, > > Durus and a couple others. > > It is sometimes convenient to store objects in mature relational > database backend (reliability, stability, support, tools, > replication, etc.). See latst efforts with RelStorage backend > for ZODB (http://wiki.zope.org/ZODB/RelStorage) - it stores > pickled Python objects in Oracle, PostgreSQL or MySQL) You mean a SQL database backend here - the conveniences that you mention have nothing to do with being relational or not. And that's my point: pickling objects, you loose of the convenience of a *relational* database. From martin.laloux at gmail.com Thu May 15 03:06:19 2008 From: martin.laloux at gmail.com (martin.laloux at gmail.com) Date: Thu, 15 May 2008 00:06:19 -0700 (PDT) Subject: Install Python MySQL db module? References: <3ca0d360-5d71-42e9-a06f-8edf26388ff2@y38g2000hsy.googlegroups.com> Message-ID: <125b0b18-7d29-434a-8d8e-6d3fb67ff55f@y21g2000hsf.googlegroups.com> search, search, it is a recurrent question.... for example http://groups.google.be/group/comp.lang.python/browse_thread/thread/7bef767753fe40f1/a3fd7c2dd7a50bef?hl=fr&lnk=gst&q=mysqldb+mac#a3fd7c2dd7a50bef From inhahe at gmail.com Sat May 17 23:46:50 2008 From: inhahe at gmail.com (inhahe) Date: Sat, 17 May 2008 23:46:50 -0400 Subject: Using Python for programming algorithms References: Message-ID: <7ENXj.6906$255.106@bignews8.bellsouth.net> what little I know: The numbers I heard are that Python is 10-100 times slower than C. So use Python if you can wait 10-100 times longer. Although it won't really be that slow using numpy and/or psyco. Python seems to have a really extensive reportoire of modules available for it. Although I don't know about things in the math field. If what you want is obscure enough, then you might find it for C/C++ and not Python. You might find out in a few seconds by googling. The advantage to Python (other than production time), is that it would be a lot simpler and more readable simply as a syntax for conveying algorithms. It would be like pseudo-code... but runnable. ;) From cwitts at gmail.com Fri May 16 02:51:07 2008 From: cwitts at gmail.com (Chris) Date: Thu, 15 May 2008 23:51:07 -0700 (PDT) Subject: Problem creating a shorcut References: <2715b502-d636-4541-ac0e-05697f02b2ae@m44g2000hsc.googlegroups.com> Message-ID: <322a200a-ed9a-44d2-b5ea-5f059884b53a@27g2000hsf.googlegroups.com> On May 15, 5:13?pm, Mike Driscoll wrote: > Hi, > > I've had this niggling issue from time to time. I want to create a > shortcut on the user's desktop to a website that specifically loads > Firefox even if Firefox is not the default browser. > > I usually use COM as it allows very specific settings of the shortcut, > such as the Working Directory and the Target Path. However, the > following will not work for some reason: > > > > import win32com.client > import winshell > > shell = win32com.client.Dispatch('WScript.Shell') > userDesktop = winshell.desktop() > > shortcut = shell.CreateShortCut(userDesktop + '\\MyShortcut.lnk') > shortcut.Targetpath = r'"C:\Program Files\Mozilla Firefox\firefox.exe" > https:\www.myCompanyWebsite.com\auth\preauth.php' > shortcut.WorkingDirectory = r'C:\Program Files\Mozilla > Firefox' > shortcut.save() > > > > This creates the following target path (which doesn't work): > > "C:\"C:\Program Files\Mozilla Firefox\firefox.exe" https: > \www.myCompanyWebsite.com\auth\preauth.php" > > If I leave the website off, it works. If I leave the path to Firefox > out, it works too. Is there another method I can use other than > creating the shortcut by hand and using the shutil module? > > Thank you for any ideas. > > Mike Don't set arguments in the path. shortcut = shell.CreateShortCut(userDesktop + '\\MyShortcut.lnk') shortcut.TargetPath = r'Program Files\Mozilla Firefox\firefox.exe' shortcut.Arguments = r'https:\www.myCompanyWebsite.com\auth \preauth.php' shortcut.WorkingDirectory = r'C:\Program Files\Mozilla Firefox' shortcut.save() From deets at nospam.web.de Wed May 21 05:46:48 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 21 May 2008 11:46:48 +0200 Subject: C-like assignment expression? References: <68b5d090-9e3b-4e7d-9dda-fc1b099822c2@m73g2000hsh.googlegroups.com> Message-ID: <69i9d8F2ubi9dU1@mid.uni-berlin.de> boblatest at googlemail.com wrote: > Hello, > > I have an if-elif chain in which I'd like to match a string against > several regular expressions. Also I'd like to use the match groups > within the respective elif... block. The C-like idiom that I would > like to use is this: > > if (match = my_re1.match(line): > # use match > elsif (match = my_re2.match(line)): > # use match > elsif (match = my_re3.match(line)) > # use match > > ...buy this is illegal in python. The other way is to open up an else: > block in each level, do the assignment and then the test. This > unneccessarily leads to deeper and deeper nesting levels which I find > ugly. Just as ugly as first testing against the RE in the elif: clause > and then, if it matches, to re-evaluate the RE to access the match > groups. This might help: ----------- s = "foo" class Tester(object): def __call__(self, pattern): self.m = re.match(pattern, s) return self.m is not None def __getattr__(self, name): return getattr(self.m, name) test = Tester() if test("bar"): print "wrong" elif test("foo"): print "right" ------------- Diez From mail at timgolden.me.uk Thu May 29 04:30:33 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 29 May 2008 09:30:33 +0100 Subject: run a script in vista In-Reply-To: <483e67e8$0$30464$afc38c87@news.optusnet.com.au> References: <483e67e8$0$30464$afc38c87@news.optusnet.com.au> Message-ID: <483E69A9.70005@timgolden.me.uk> Graham Feeley wrote: > Hi, I have a script which runs in xp, however now I have upgraded to > vista this script now does'nt work > Can someone help with this problem please ? > this is the start of the script > > import cPAMIE > import cModalPopUp > import winGuiAuto as wga > import time, datetime > import os, sys, re > import mx.ODBC.Windows as odbc You're not helping very much here: what does "now doesn't work" mean? It doesn't even start? It runs but gives an error? If so, what's the traceback? etc. etc. TJG From inhahe at gmail.com Thu May 22 18:36:15 2008 From: inhahe at gmail.com (inhahe) Date: Thu, 22 May 2008 18:36:15 -0400 Subject: Overloading __getitem__ References: Message-ID: it seems like you can't do it exactly the way you're trying but you could do this def __getitem__(*args): if len(args) > 1 and args[1]: return self.get(args[0]) * 5 return self.get(args[0]) then you would use it like print foo['a'] print foo['a',True] or even print foo['a',"crazy"] if you wanted. or crazy = True print foo['a',crazy] "Andreas Matthias" wrote in message news:uf6hg5-ca9.ln1 at buckbeak.hogwarts... > The following code doesn't run but I hope you get what I > am trying to do. > > > class my_dict (dict): > > def __getitem__ (self, key, crazy = False): > if crazy == True: > return 5 * self.get(key) > else: > return self.get(key) > > > foo = my_dict() > foo['a'] = 123 > > print foo['a'] > print foo['a', crazy = True] > > > Is it somehow possible to overload __getitem__ with an additional > argument? Are there other possibilities to achiev this? Or is > the only solution to this to write a normal function call > `def my_get (self, key, crazy=False)'? > > > Ciao > Andreas From kyosohma at gmail.com Tue May 20 15:58:40 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 20 May 2008 12:58:40 -0700 (PDT) Subject: List of disk drives on Windows? References: <2008052013180816807-bob@passcalnmtedu> Message-ID: On May 20, 2:45?pm, Tim Golden wrote: > Bob Greschke wrote: > > This MUST have been asked before, but I can't seem to Google the right > > thing. ?How can I get a list of drives on a Windows box, like ["C:\", > > "D:\"], like I can if I do something like listdir("/Volumes") on a Mac? > > A couple of options to get the ball rolling: > > 1) win32api.GetLogicalDriveStrings() I gave this a go to see how it worked and ti gave me this: 'A:\\\x00C:\\\x00D:\\\x00G:\\\x00I:\\\x00L:\\\x00P:\\\x00Q:\\\x00R:\\ \x00U:\\\x00X:\\\x00Y:\\\x00Z:\\\x00' Not exactly what I expected. Do I have to parse out the "\\\x00" myself or is there an information level switch I should add? > > 2)http://timgolden.me.uk/python/wmi_cookbook.html#find-drive-types This works as advertised. I was actually going to post that, but you beat me to it. :) > > TJG Mike From hdante at gmail.com Thu May 15 19:42:24 2008 From: hdante at gmail.com (Henrique Dante de Almeida) Date: Thu, 15 May 2008 23:42:24 +0000 (UTC) Subject: exists=false, but no complaint when i open it!? References: <285e0ce6-1371-4ab7-9281-ad1d664a480f@a23g2000hsc.googlegroups.com> <8AEDA5E3386EA742B8C24C95FF0C75800403F7BC@PDC-MAIL3.ubisoft.org> Message-ID: Em Thu, 15 May 2008 19:20:58 +0200, Andreas Tawn escreveu: >>print os.path.exists('C:\Users\saftarn\Desktop\NetFlixDataSet >>\training_set') returns False... >> >>i have thourogly checked the filename to be correct and if we assume it >>is what could this mean then? >>i had a problem one other time when i had renamed a file but windows >>didnt rename it compeltely apparently. > > It's escape characters again. > > You're asking for > 'C:\Users\saftarn\Desktop\NetFlixDataSet\training_set', but Python > interprets that as 'C:\Users\saftarn\Desktop\NetFlixDataSet > raining_set', which probably doesn't exist. > > The first example works by accident because backslash plus the first > letter of each folder in your path happens to not match any of Python's > string formatting characters. > > Use forward slashes or double up the backslashes to stop this happening. > > Cheers, > > Drea Hint: standardize the way you write paths in python: import os.path def _p(*x): return os.path.normpath(os.path.expanduser(os.path.join(*x))) (in my system) In [10]: print _p('abcd.txt') abcd.txt In [11]: print _p('~/abcd.txt') /home/hdante/abcd.txt In [12]: print _p('~/abcd/efgh.txt') /home/hdante/abcd/efgh.txt In [13]: print _p('~', 'abcd', 'efgh.txt') /home/hdante/abcd/efgh.txt From dullrich at sprynet.com Tue May 27 08:49:00 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Tue, 27 May 2008 07:49:00 -0500 Subject: decorators when? Message-ID: <3m0o34hbb0c6rpr6ec0qh3hlkaagt8pfi5@4ax.com> What version added decorators (using the @decorator syntax)? (Is there a general way I could have found out the answer myself?) Is there a somthing such that "from __future__ import something" will make decorators work in 2.5.2? David C. Ullrich From gandalf at shopzeus.com Wed May 14 16:36:07 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Wed, 14 May 2008 22:36:07 +0200 Subject: Submitting data to HTTPS javascript In-Reply-To: <8e087c6d0805141119y7637732cr37288492d7601f27@mail.gmail.com> References: <8e087c6d0805141119y7637732cr37288492d7601f27@mail.gmail.com> Message-ID: <482B4D37.9080100@shopzeus.com> John Chandler wrote: > I am trying to write a script to test certain functionality of a > website that requires users to login. The login page is simple, a few > pictures and two text bars (one for username and one for password). I > tried logging in with webbrowser, but that did not work because the > page uses javascript. I also tried using win32com though I have no > idea what I am doing. Any ideas? - Use firefox :-) - Install "LiveHTTPHeaders" http://livehttpheaders.mozdev.org/ - Open the plugin in one window and the website in another - Enable "capture" in livehttpheaders (default) - Login to the website - Disable "capture" in livehttpheaders (default) - Check the GET and POST requests in the capture log - Try to send the same GET and POST requests from Python. - Don't forget that most sites will also need cookies - you have to extract and send back cookies as needed You do not need any GUI component for this job. Other good things to have: - Good knowledge of the "re" standard module, and regular expression syntax - BeautifulSoup (especially ICanBelieveItIsBeautifulSoup...) You might also check the "mechanoid" project. (I have never used it but it is said to be an automatized, controllable web browser???) If anyone is interested, I can put up a python recipe that shows how to emulate a browser easily. Best, Laszlo From castironpi at gmail.com Wed May 14 13:51:43 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 14 May 2008 10:51:43 -0700 (PDT) Subject: I'm stuck in Python! References: <0563506d-bd36-404d-8961-4c4c5d1cc029@t54g2000hsg.googlegroups.com> <6a0167c3-bd87-4ddc-a161-249b7bf933c2@s50g2000hsb.googlegroups.com> <1f6bc3b5-da44-42a2-82f1-4aec5a6d31b1@c58g2000hsc.googlegroups.com> Message-ID: <499bc2af-6c7d-4ff4-abba-db06f4122cf9@x41g2000hsb.googlegroups.com> On May 14, 5:25?am, castiro... at gmail.com wrote: > On May 14, 4:32?am, castiro... at gmail.com wrote: > > > On May 13, 9:55?pm, alex23 wrote: > > > > On May 14, 5:41 am, "inhahe" wrote: > > > > > "George Sakkis" wrote in message > > > > > You must be new here. It is an AS (Artificial Stupidity) trolling bot, > > > > > you can safely ignore its posts. > > > > > How does it generate text? > > > > My guess is by inhaling a lot of intoxicants. > > > However you know what would be helpful? ?If I could go to the right > > place to start the ring. > > I have a slightly sinister role on stage. ?Does anyone want to play? I'd stay on mutability for the world domination factor. Fluent currency is buoyant currency; turn on a local clock, and someone gets some cubic verticals. Now if sense-reference is trading on the BDFL, I'm still holding Tron can pretty well win work. From eric at pixelwareinc.com Tue May 13 18:09:17 2008 From: eric at pixelwareinc.com (Eric Anderson) Date: Tue, 13 May 2008 15:09:17 -0700 (PDT) Subject: Purpose of operator package Message-ID: I mainly work in other languages (mostly Ruby lately) but my text editor (Scribes) is python. With python being everywhere for dynamic scripting I thought I would read the source to learn the language better (I've gone through some basic tutorials but I always prefer to learn from real source). So right from the start I see the following: from operator import truth if truth(argv): # blah blah blah It is obvious they are testing to see if any command line arguments. But curious for why the function is needed. So I look up the operator package and fine it provides functions that are equivalent to the native operators. So my question is why would someone right the above instead of just if argv: # blah blah blah Seems like unnecessary code but obviously I know nothing about Python. Thanks for any pointers! From fuzzyman at gmail.com Sat May 24 10:10:15 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Sat, 24 May 2008 07:10:15 -0700 (PDT) Subject: unittest: Calling tests in liner number order References: Message-ID: On May 24, 2:44 pm, Roy Smith wrote: > In article > , > > Fuzzyman wrote: > > Also, like others, I have had wonderful experiences of trying to track > > down test failures that depend on the order that tests run in. Having > > interdependencies between tests is a recipe for madness... > > I agree that tests should not depend on each other, but sometimes it's > still useful to have the tests run in a certain order for reporting > purposes. > > If you're doing requirements tracking, it's nice to have the tests execute > in the same order as the requirements are listed. It makes interpreting > the output easier. Sure, you could give the test cases names like > "test_fr17.3a" and write your own getTestCaseNames(), but just putting them > into the file in the order you want them to run is easier. And making > things easy is what this is all about. Whilst I understand your point, I think the danger is that you end up with hidden dependencies on the test order - which you're not aware of and that the tests never expose. Certainly layout your tests in a logical order within the file, but I think you risk potential problems by controlling the order they are run in. Other frameworks specifically provide test order randomizers for this very reason. A worthwhile question for the OP - your patch seems fairly simple. Is it easy for you to extend unittest for your own testing needs by subclassing? Unittest should definitely be easy for people who *want* this to add it to their own testing environment. All the best, Michael Foord http://www.ironpythoninaction.com/ From s0suk3 at gmail.com Wed May 28 03:58:32 2008 From: s0suk3 at gmail.com (s0suk3 at gmail.com) Date: Wed, 28 May 2008 00:58:32 -0700 (PDT) Subject: Does this path exist? Message-ID: <2c6739d1-1128-469c-92b0-ee0263ec25d1@m36g2000hse.googlegroups.com> I wanted to ask for ways to test whether a path exists. I usually use os.path.exists(), which does a stat call on the path and returns True if it succeeds, or False if it fails (catches os.error). But stat calls don't fail only when a path doesn't exist. I see that, at least on Windows, the instance of the exception has an attribute 'errno' set to 2 when it fails because the path doesn't exist. Is it a portable solution to rely on this (haven't tried it on Linux)? Are there other ways of testing whether a path exists? Thanks, Sebastian From daniel.a.esch at gmail.com Tue May 13 17:59:24 2008 From: daniel.a.esch at gmail.com (Dan Esch) Date: Tue, 13 May 2008 17:59:24 -0400 Subject: Learning Python and the Zen of the Mailing List Message-ID: I decided to learn Python. I decided to learn Python because I hate visual basic for applications and I can feel my brain shrink everytime I invoke that freaking macro editor. It's bad enough that Mwfdg Q%$#@%soft had to eliminate the original simple keystroke macro tools that were enough for us knuckle-dragging accounting types - oh no! - they had to replace that tool - that we understood - with the most brain dead, useless, overwrought piece of crap abuse of programming language. This forced me to learn how to program. As I learned how to program, I learned that Visual Basic wasn't as bad as I thought - it was far, far, far worse.... I went to Dartmouth, and, Bill, you harvard dropout, I'd like to inform you that President Kemeny is spinning in his grave for the perversions you have inflicted upon his undergraduate-teaching-tool toy-language. So I write little toy programs and try to wrap my head around real object-oriented programming and and real algorithms and data structures and design my scratch-my-own-itch application in my head while I study. In the mean time, I lurk on this mailing list - I don't have any real questions yet - but reading the questions and answers has been a great way of tapping into the pythonic Zen - I don't know if anyone is a similar situation to me, but I recommend just randomly browsing the mailing list as a means of getting in tune with the rhythm and esthetics of the language Dan -------------- next part -------------- An HTML attachment was scrubbed... URL: From bruno.desthuilliers at gmail.com Mon May 19 16:53:31 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Mon, 19 May 2008 13:53:31 -0700 (PDT) Subject: Classmethods are evil References: Message-ID: <10393839-0a29-4233-8ff2-fab9c7c92a75@i76g2000hsf.googlegroups.com> On 17 mai, 11:50, Ivan Illarionov wrote: > On Sat, 17 May 2008 02:33:13 -0300, Gabriel Genellina wrote: > > En Sat, 17 May 2008 01:01:50 -0300, Ivan Illarionov > > escribi?: > > >> After re-reading "Python is not Java" I finally came to conclusion that > >> classmethods in Python are a very Bad Thing. > > >> I can't see any use-case of them that couldn't be re-written more > >> clearly with methods of metaclass or plain functions. > > > A good use case for class methods are alternate constructors, like > > dict.from_keys. I don't think an alternate constructor would be more > > clear being a method of the metaclass - actually it belongs to the class > > itself, not to its metaclass. > > Metaclass methods are harder to find; they don't show in dir(instance) > > nor dir(class). > > Also the resolution order is harder to grasp for metaclasses - but this > > may be just lack of usage from my part... > > >> They have the following issues: > >> 1. You mix instance-level and class-level functionality in one place > >> making your code a mess. > > > Not necesarily; some classmethods are naturally tied to the class > > itself, not to the metaclass (like the constructor example above). But > > yes, *some* classmethods could be written as methods of their metaclass > > instead - but that doesn't always make sense. > > >> 2. They are slower than metaclass methods or plain functions. > > > Hu? How did you come to that? > > I've done a small test and a class method wins by a very minuscule but > > consistent advantage over a metaclass method: > > > class A(object): > > color = "red" > > > @classmethod > > def foo(cls, x): > > return getattr(cls, x) > > > class MetaB(type): > > def foo(self, x): > > return getattr(self, x) > > > class B(object): > > __metaclass__ = MetaB > > color = "red" > > > C:\TEMP>python -m timeit -s "from meta3 import A,B;a,b=A(),B()" > > "A.foo('color')" > > 1000000 loops, best of 3: 1.19 usec per loop > > > C:\TEMP>python -m timeit -s "from meta3 import A,B;a,b=A(),B()" > > "B.foo('color')" > > 1000000 loops, best of 3: 1.2 usec per loop > > How did I come to this:http://code.djangoproject.com/changeset/7098 > > I measured this and there was a marginal speed increase when classmethods > wher moved to metaclass. IIRC (please correct me if I'm wrong), this part of code is only called when the class is created - in which case it makes sense to move it where it belongs, ie to the metaclass. This is by no mean a use case for classmethods. From gherron at islandtraining.com Sun May 11 19:50:17 2008 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 11 May 2008 16:50:17 -0700 Subject: File Creation Not Working In A Thread Class? In-Reply-To: <48275A1F.5080606@bc90021.net> References: <7qGVj.32505$KJ1.18416@newsfe19.lga> <48275955.4000106@islandtraining.com> <48275A1F.5080606@bc90021.net> Message-ID: <48278639.9090701@islandtraining.com> bc90021 wrote: > You are a perfect example of exactly what I was talking about, and why > the Python community is such a poor one. I though you were treated quite fairly all things considered. (You started the personal attacks, the whining about the group, the accusations of arrogance, and the refusal to believe we all *knew* the error was in your file name calculation and not in Python threads.) This group is widely acknowledged as one of the more friendly groups around, and in fact we keep it that way by coming down rather hard on those who abuse either the members of the group or the purpose of the group. And you've done both and been reprimanded for it. Now, either go away, or change your attitude and join the group. (You would be welcome if the attitude changed.) Either way, this group will be it's usual friendly self. Gary Herron > > Gary Herron wrote: >> bc90021 wrote: >>>> ...and the exact error message was? >>>> >>>> Here is a tip: if you want people to help you, then you have to help >>>> them to help you. Personally, I wouldn't respond to anymore of your >>>> questions because you seem incapable of posting the information >>>> that was >>>> requested. >>>> >>> >>> So far, the people who have answered this post have gone on the >>> assumption that I'm stupid. I'm not. I took perfectly working >>> code, cut it from one class, and put it in another. It stopped >>> working in the second class. I've spent days on this and trust me, >>> given what I've experienced of the Python community so far, if I >>> didn't have to ask, I wouldn't. >>> >>> (I really must say that so far the help I am getting in the Python >>> community is a big let down. Whether it's on IRC or here, everyone >>> has an arrogance that I don't find anywhere else in the open source >>> community, and it seriously makes me question the choice of language >>> that I've made.) >>> >> >> Sorry, the arrogance is yours. >> Expecting us to help with only partial information. >> >> Expecting us to help when your posts of the error message changes >> from one post to the next. >> >> Expecting us to help when you refuse to post the traceback. >> >> Expecting us to believe that it has anything to do with threads. >> (No one believes that for a moment.) >> >> >> While acknowledging that any piece of code may have bugs, Python's >> threading included, the problem here looks to be some simple mistake >> in the computation of the name of the file to be opened. Then I >> look at the convoluted quoting surrounding your computation of the >> file name, and my confidence in that as an explanation sky-rockets. >> Then someone in another post has found an extra set of quotes >> embedded in your filename you compute, and it's clear that we are on >> the right track. >> >> >> >>> The error message was at the top of the thread (am I incapable of >>> posting it, or are you incapable of following a thread?), but here >>> it is again: >>> >>> IOError: [Errno 2] no such file u'tempfileName' >>> >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >> >> >> > From castironpi at gmail.com Sat May 10 07:53:52 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 10 May 2008 04:53:52 -0700 (PDT) Subject: Pythonicity of some algorithms References: <4825770e$0$25961$9b622d9e@news.freenet.de> Message-ID: <47927ab3-186e-4a9f-901d-3d15b69c165b@b64g2000hsa.googlegroups.com> On May 10, 5:21?am, "Martin v. L?wis" wrote: > > This works for me. But I'd like to know if this is considered > > Pythonic, and if there are other, better ways of doing the above in > > Python. > > From the Python point of view, it's fine. However, it uses busy-wait, > which I consider bad style (in any language). > > > 3) Make a custom thread-safe queue class, with an 'interrupt_get' > > method. When your app calls queue.interrupt_get(), all threads > > currently locking on a queue.get() will continue, but with a > > GetInterrupted exception thrown. > > That's what I would do. I'd use the existing Queue class as a base > class, though, rather than starting from scratch. > > Regards, > Martin Did you follow the links to Dev-C++? It rules house. I have drizzle.c compiling in Windows GDI and SDL. I'm poised to double-time Dev-C++ and Windows GDI, if double-tasking is on the market. Credit up... what's standard? From george.maggessy at gmail.com Thu May 22 20:48:57 2008 From: george.maggessy at gmail.com (George Maggessy) Date: Thu, 22 May 2008 17:48:57 -0700 (PDT) Subject: MVC Message-ID: <8a269063-ae96-4707-afdc-5d2c9270e0ff@a9g2000prl.googlegroups.com> Hi Gurus, I'm a Java developer and I'm trying to shift my mindset to start programming python. So, my first exercise is to build a website. However I'm always falling back into MVC pattern. I know it's a standard, but the implementation language affects the use of design patter. So, here goes my question. Is that OK if I follow this? Should I create DAOs, View Objects, Controllers and etc? Is there any sort of best practice / standard to Python? Cheers, George From rpdooling at gmail.com Tue May 13 20:58:59 2008 From: rpdooling at gmail.com (Rick Dooling) Date: Tue, 13 May 2008 17:58:59 -0700 (PDT) Subject: Install Python MySQL db module? References: Message-ID: <3ca0d360-5d71-42e9-a06f-8edf26388ff2@y38g2000hsy.googlegroups.com> On May 13, 7:29 pm, Con wrote: > Hi, how does properly install the Python MySQL db module for Mac OS > X? I was only able to locate the Win32 modules. > > Thanks in advance, > > -Conrad I tried this a couple of weeks ago using macports and had problems. See, for example: http://www.davidcramer.net/code/57/mysqldb-on-leopard.html I read about several people who went in and edited the source files to work out the bugs on Leopard, but instead I just changed my Python code to use SQLite for the moment until someone fixes MySQLdb. There's a nice Perl script that will convert your MySQL db to an SQLite db if you're interested. RD From eduardo.padoan at gmail.com Tue May 20 19:56:59 2008 From: eduardo.padoan at gmail.com (Eduardo O. Padoan) Date: Tue, 20 May 2008 20:56:59 -0300 Subject: What is wrong with my Python threading? In-Reply-To: References: <37ac2e29-2ccb-471d-95a5-7afdb49823fa@34g2000hsf.googlegroups.com> Message-ID: On Tue, May 20, 2008 at 8:24 PM, Gabriel Genellina wrote: > En Tue, 20 May 2008 10:28:51 -0300, castironpi > escribi?: > >> You meant 'thd1.start( )' and 'thd2.start( )'. > > Wow! A message with a high S/N ratio coming from you! > And it's not the first I've seen - whatever pills you're taking, they're > good for you... This is why I shouldn't be so eager adding people to the killfile. -- Eduardo de Oliveira Padoan http://www.advogato.org/person/eopadoan/ http://twitter.com/edcrypt Bookmarks: http://del.icio.us/edcrypt From gagsl-py2 at yahoo.com.ar Wed May 14 02:26:41 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 14 May 2008 03:26:41 -0300 Subject: threads problem in python References: <48296275.9090602@al.com.au> <482A286B.3090504@al.com.au> Message-ID: En Tue, 13 May 2008 20:46:51 -0300, Astan Chee escribi?: > Sorry, I mean functions not classes. Well, actually, one is a class and > another is a function. So when the script (its a free game btw) runs, it > instantiates the first class and somewhere in the middle of processing > the first class, I need to call a function as a separate thread, I also > want to wait for the function to complete and I was wondering how python > handles the thread of this function? Does it die when the function > completes? Anyway, I know it sounds silly to have 2 threads when I can > do it with one, but Im using wx to render opengl objects using pygame. > So it has to be a separate thread, otherwise wx wont play nice. Is there > a simple example of how I can do this? That's why I asked about the GUI library used. For wx see http://wiki.wxpython.org/LongRunningTasks -- Gabriel Genellina From google at mrabarnett.plus.com Wed May 21 21:49:37 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 21 May 2008 18:49:37 -0700 (PDT) Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <20080514215943.14c92f16.johnjsal@NOSPAMgmail.com> <94bac166-d13c-44dd-af84-db19e19488b8@w1g2000prd.googlegroups.com> <8cfd3523-8d16-40bc-b904-94a6a36a414d@p25g2000pri.googlegroups.com> <471aa7ed-3241-466c-b599-e91c38db62fa@e39g2000hsf.googlegroups.com> Message-ID: <12071a08-5c5d-4541-bc34-ed1f1ac4e96f@8g2000hse.googlegroups.com> On May 21, 8:34 pm, Dave Parker wrote: > On May 21, 1:14 pm, MRAB wrote: > > > I wonder whether "is" could be used both for "x is value" and "x is a > > type" without causing a problem: > > > If command is a string ... > > > If command is "quit" ... > > I think you are right. I like "If command is "quit" ...". For a user > who wasn't mathemetically inclined and was doing mainly string > manipulation, I think it might be easier to read than the equivalent > "If command = "quit" ...". By making them exactly equivalent, I can't > think of any confusion that might induce bugs. If you think of any > drawbacks, please let me know. > I've thought of one possible drawback: "a" and "an" can be used as variables, so the "is a" part might cause a problem. You'd need to check the parser to find out... > Otherwise, I'll put it in the next > time I update the parser (probably this weekend). Thank you again for > your suggestions. From bronger at physik.rwth-aachen.de Thu May 1 01:12:41 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Thu, 01 May 2008 07:12:41 +0200 Subject: relative import broken? References: <9c6ba5f9-d65b-4265-baba-fc5d7936781b@d1g2000hsg.googlegroups.com> <87prs6x1ye.fsf@mulj.homelinux.net> <33782b65-6d6d-4ae7-8539-29f809ae5077@d45g2000hsc.googlegroups.com> Message-ID: <87iqxyboae.fsf@physik.rwth-aachen.de> Hall?chen! Sam writes: > On Apr 30, 9:11 pm, Hrvoje Niksic wrote: >> Sam writes: >> > I also have a problem with relative import; I can't for the life of me >> > figure out how to use the damn thing. I think the main problem is with >> > getting Python to recognize the existence of a package. I have >> >> > S/ >> > p.py >> > B/ >> > b.py >> > W/ >> > pyw/ >> > u.py >> > ws.py >> >> > and I'd like to get u.py to import all the other 3 programs. I put >> > empty __init__.py files in all of the above directories (is this >> > necessary?), and even manually added the pathway (r'C:\Myname\S') to >> > sys.path, but when I execute >> >> > from S import p >> >> > in u.py Python gives "ImportError: No module named S". >> >> A silly question: is the directory that contains "S" in PYTHONPATH or >> in sys.path? > > It's in sys.path. "S" or its parent directory? Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From hat at se-162.se.wtb.tue.nl Tue May 6 12:10:01 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Tue, 06 May 2008 18:10:01 +0200 Subject: Am I missing something with Python not having interfaces? References: <45de2f7e-484a-4871-bbaa-bf7eed5dfa40@x35g2000hsb.googlegroups.com> <29716374-c3b2-407e-ac54-ae2a17ccf081@2g2000hsn.googlegroups.com> Message-ID: On 2008-05-06, jmDesktop wrote: > > I would imagine this is why I haven't found any schools teaching > Python in their basic programming classes too. On the dynamic typing, I don't understand your reasoning. What part does 'this' refer to? Also, you are wrong. We teach 2nd year Bachelor students about programming (the process of solving a problem by making a computer program, which is not the same as coding) with Python. > isn't that the same sort of thing that lots of scripting languages > do? VBScript doesn't require you to define your variables, but I > don't really want to use it for anything (used to use it a lot in VB was not designed well in that case. I believe that VB is popular becomes it comes from the same firm that also sells the OS and the word processor of all school computers. Also, many teachers make a choice based on what others do or what they know, rather than what the best possible prog language is for students. Also, industry wants to have graduates that know the language they use. It is very easy to give in to that desire, although it is not very useful, since industry changes its programming language every so many years. > Classic ASP.) I believe everyone that Python is great, but some of it > doesn't make sense to me as to why. Thanks. That's normal (and healthy, probably). The thing that should really scare you however is your idea that everything done in the Java/C# way does make sense (ie you are trying to push Python in the 'yet another hammer' concept rather than treating it as a shiny newly invented tool used by many others already). Unlike what you think, all languages including Java and C# have their weaknesses. However, you can only see weak points from outside the Java/C# world (by knowing other languages that handle the same problems in a better way). (sorry if I offended you with the last bit, I did not intend to attack you personally, just trying to provoke you enough to make you wonder about your implicit assumptions.) Sincerely, Albert From daveparker at flamingthunder.com Tue May 13 11:24:35 2008 From: daveparker at flamingthunder.com (Dave Parker) Date: Tue, 13 May 2008 08:24:35 -0700 (PDT) Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <2b66a86e-5a05-4262-b3c9-4703b0ae3372@d1g2000hsg.googlegroups.com> <5b0e3f70-afde-4480-8713-e7113b1250d7@x35g2000hsb.googlegroups.com> <1f537717-00d0-48ee-99b6-7125b96a6133@t12g2000prg.googlegroups.com> <68t4o0F2vaoncU1@mid.uni-berlin.de> <2a32179a-9439-449c-bd07-fff6a4075aee@s50g2000hsb.googlegroups.com> <7ee5dffd-df8f-46f0-bd78-c81ac0418a9a@d77g2000hsb.googlegroups.com> Message-ID: <65ef773e-a1c3-4adb-a18b-e8b8451efe5e@b5g2000pri.googlegroups.com> > The "Flaming Thunder" looks promising, but without being free > software, it's unlikely it will create a large developer community, > specially considering both free general purpose and scientific > programming languages. Perhaps. Flaming Thunder is only $19.95 per year for an individual (and even less per individual for site licenses), which is less than the cost of just one book on Python. I think that many people will find that Flaming Thunder is easier to use and understand than Python -- so for many people the amount of time they save will be worth more than the cost of Flaming Thunder (unless, of course, their time is worth $0). Also, several users have rewritten their Python programs in Flaming Thunder, and found that Flaming Thunder was 5 to 10 times faster (Flaming Thunder compiles to native executables). So again, since many people value their time at more than $0, I think that many people will find that Flaming Thunder is worth $19.95 per year. Plus, me getting paid to work on Flaming Thunder is far more motivating than me not getting paid to work on Python. This weekend, Python users will still be debating how to fix awkwardnesses in the languages (such as FOR loops where you're just counting the loops and not referencing the loop variable) -- but Flaming Thunder users will be getting work done using the REPEAT n TIMES constructs that I'll be implementing. Python has been around about 15 years, yet still has those awkwardnesses. Flaming Thunder has been out less than 6 months and those awkwardnesses are already getting fixed. The difference: I can't afford to ignore users. But the future is one of the hardest things to predict, so we'll see. On May 13, 8:34?am, hdante wrote: > On May 13, 10:58?am, Paul McGuire wrote: > > > > > > > On May 13, 8:32?am, Dave Parker wrote: > > > > > Don't let yourself be irritated by castironpi > > > > I'm not the sort to get irritated by anyone. ?There is value in all > > > interaction. > > > Not this interaction, I'm afraid. ?What irritates *me* about > > castironpi is that he uses a chatterbot to clutter up the threads > > here. ?If you go back to his postings from a year ago (and selected > > ones since), his comments are coherent and sensible. ?These rambling > > stream-of-consciousness rants about t.v.'s and coffee are (I guess) > > his idea of a joke. ?But they are certainly not worth your time in > > trying to respond to them. > > > -- Paul > > ?I don't think castironpi so annoying that I should filter its > messages. It would be enough if he were better tuned. He is much > smarter than the emacs shrink, for example. :-P > > ?The "Flaming Thunder" looks promising, but without being free > software, it's unlikely it will create a large developer community, > specially considering both free general purpose and scientific > programming languages.- Hide quoted text - > > - Show quoted text - From bearophileHUGS at lycos.com Thu May 15 13:46:30 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Thu, 15 May 2008 10:46:30 -0700 (PDT) Subject: Fast Mersenne Twister Message-ID: <8750298b-b4c9-4089-b01c-d00f2453ee69@k13g2000hse.googlegroups.com> This may be interesting for Python developers of the random module, "SIMD-oriented Fast Mersenne Twister (SFMT): twice faster than Mersenne Twister": http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/SFMT/ One function may be useful to generate integers (randint, randrange, choice, shuffle, etc), the other for floating point values (random) faster than the current Mersenne Twister used in the random module. Bye, bearophile From iainking at gmail.com Fri May 23 04:24:39 2008 From: iainking at gmail.com (Iain King) Date: Fri, 23 May 2008 01:24:39 -0700 (PDT) Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> Message-ID: On May 23, 3:35 am, Charles Hixson wrote: > On Thursday 22 May 2008 13:30:07 Nick Craig-Wood wrote: > > > ... > > >From Armstrong's book: The expression Pattern = Expression causes > > > Expression to be evaluated and the result matched against Pattern. The > > match either succeeds or fails. If the match succeeds any variables > > occurring in Pattern become bound. > > > It is a very powerful idea and one which (along with the concurrency > > and message passing from Erlang) has been implemented for python :- > > > http://candygram.sourceforge.net/ > > > I've been reading the Erlang book and I have to say it has given me a > > lot of insight into python... > > Although when comparing Candygram with Erlang it's worth noting that Candygram > is bound to one processor, where Erlang can operate on multiple processors. > (I'd been planning on using Candygram for a project at one point, but this > made it unusable.) lol, nice name. Also surprisingly relevant to the thread: candygrammar: n. A programming-language grammar that is mostly syntactic sugar; the term is also a play on ?candygram?. COBOL, Apple's Hypertalk language, and a lot of the so-called ?4GL? database languages share this property. The usual intent of such designs is that they be as English- like as possible, on the theory that they will then be easier for unskilled people to program. This intention comes to grief on the reality that syntax isn't what makes programming hard; it's the mental effort and organization required to specify an algorithm precisely that costs. Thus the invariable result is that ?candygrammar? languages are just as difficult to program in as terser ones, and far more painful for the experienced hacker. From detlev at die-offenbachs.de Sun May 4 04:58:29 2008 From: detlev at die-offenbachs.de (Detlev Offenbach) Date: Sun, 04 May 2008 10:58:29 +0200 Subject: ANN: eric 4.1.3 released Message-ID: Hi, I'd like to inform everybody about the immediate availability of eric v4.1.3. This is a bug fix release. It is available via http://www.die-offenbachs.de/eric/index.html. What is eric? ------------- eric is a Python IDE written using PyQt4 and QScintilla2. It comes with all batteries included. For details please see the above link. Regards, Detlev -- Detlev Offenbach detlev at die-offenbachs.de From zentraders at gmail.com Mon May 26 14:50:43 2008 From: zentraders at gmail.com (Zentrader) Date: Mon, 26 May 2008 11:50:43 -0700 (PDT) Subject: definition of a highlevel language? References: <2759eed3-956d-45c7-8dfb-9557f74133b3@56g2000hsm.googlegroups.com> Message-ID: On May 26, 11:34 am, notnorweg... at yahoo.se wrote: > what is the definition of a highlevel-language? It is relative. A low-level language is lower/closer to the computer's binary code. C/C++ is a high-level language compared to assembly. Python is high-level vs. C/C++. Python is low-level compared to "spreadsheet programming", although some spreadsheets like Gnumeric can use Python extensions. From wuwei23 at gmail.com Fri May 23 22:00:20 2008 From: wuwei23 at gmail.com (alex23) Date: Fri, 23 May 2008 19:00:20 -0700 (PDT) Subject: Storing objects in relational database References: <03a17198-3eb2-438e-97c9-db18c0c24a80@c65g2000hsa.googlegroups.com> Message-ID: On May 24, 7:14 am, nayden wrote: > the execution fails just after the print statement, and I am not quite > sure why is that. It's often helpful to include the traceback, or at the very least the last 3-4 lines of it, as it helps everyone work out the issue you're having. If you're not sure which line in a function is causing the issue, try commenting out all but the first, run-and-test, re-add the next, run- and-test etc But the error is most likely this line: > i = cPickle.load(str) cPickle.load unpickles from a file, but here you're handing it a string. You want cPickle.loads. At the interpreter, you can always quickly check these out by looking up the docstring via 'help(cPickle.loads)' (or 'cPickle.loads?' if you're using iPythhon). - alex23 From benjamin.kaplan at case.edu Fri May 30 18:49:14 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Fri, 30 May 2008 18:49:14 -0400 Subject: SMS sending and receiving from website? In-Reply-To: References: Message-ID: On Fri, May 30, 2008 at 5:08 PM, globalrev wrote: > can i send and receive messages from a website using python? > > how would that work with costs? would the mobileowner pay both ways? > -- > http://mail.python.org/mailman/listinfo/python-list > I believe that there is a way to use Django to send messages, but I've never used it myself and I don't know about recieving messages. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rsoh.woodhouse at googlemail.com Wed May 28 17:19:40 2008 From: rsoh.woodhouse at googlemail.com (rsoh.woodhouse at googlemail.com) Date: Wed, 28 May 2008 14:19:40 -0700 (PDT) Subject: Threads and import References: <6d04f375-9cc6-428b-aafb-d5b947d6e915@b1g2000hsg.googlegroups.com> <6a5pulF36888qU1@mid.uni-berlin.de> <0d96c6da-d239-4b15-8456-70e2d9e67fa2@59g2000hsb.googlegroups.com> <6a5rfvF36c899U1@mid.uni-berlin.de> Message-ID: On May 28, 8:52 pm, "Diez B. Roggisch" wrote: > rsoh.woodho... at googlemail.com schrieb: > > > > > On May 28, 8:26 pm, "Diez B. Roggisch" wrote: > >> rsoh.woodho... at googlemail.com schrieb: > > >>> Hi, > >>> I'm trying to work out some strange (to me) behaviour that I see when > >>> running a python script in two different ways (I've inherited some > >>> code that needs to be maintained and integrated with another lump of > >>> code). The sample script is: > >>> # Sample script, simply create a new thread and run a > >>> # regular expression match in it. > >>> import re > >>> import threading > >>> class TestThread(threading.Thread): > >>> def run(self): > >>> print('start') > >>> try: > >>> re.search('mmm', 'mmmm') > >>> except Exception, e: > >>> print e > >>> print('finish') > >>> tmpThread = TestThread() > >>> tmpThread.start() > >>> tmpThread.join() > >>> import time > >>> for i in range(10): > >>> time.sleep(0.5) > >>> print i > >>> # end of sample script > >>> Now if I run this using: > >>> $ python ThreadTest.py > >>> then it behaves as expected, ie an output like: > >>> start > >>> finish > >>> 0 > >>> 1 > >>> 2 > >>> ... > >>> But if I run it as follows (how the inherited code was started): > >>> $ python -c "import TestThread" > >>> then I just get: > >>> start > >>> I know how to get around the problem but could someone with more > >>> knowledge of how python works explain why this is the case? > >> Works for me. And I don't see any reason why it shouldn't for you - > >> unless you didn't show us the actual code. > > >> Diez > > > Strange. That is the code exactly as I run it using python 2.4.4 2.5.1 > > on Ubuntu 7.10. Which version of python/what platform were you using? > > mac-dir:/tmp deets$ python > Python 2.5.1 (r251:54869, Apr 18 2007, 22:08:04) > [GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin > Type "help", "copyright", "credits" or "license" for more information. > Welcome to rlcompleter2 0.96 > for nice experiences hit multiple times > >>> > > But I doubt this changes anything. > > Diez Hmm. Just tested it again on OS X Python 2.4.4 and custom build of Python 2.4.5 on Debian and get the same results as I had before. Thanks, Rowan From tinnews at isbd.co.uk Fri May 23 14:59:39 2008 From: tinnews at isbd.co.uk (tinnews at isbd.co.uk) Date: 23 May 2008 18:59:39 GMT Subject: Python database 'frontends', what's available? Message-ID: <4837141b$0$658$bed64819@news.gradwell.net> I'm desperately trying to move a Microsoft Access database application (a simple accounts system I wrote myself) to Linux. Python is one of my preferred programming laguages so I wonder if there are any good Python 'frameworks' for writing database applications, in particular I need good reporting and forms writing facilities. The basic database and logic/arithmetic seem fairly simple to me. -- Chris Green From bignose+hates-spam at benfinney.id.au Tue May 27 19:04:52 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 28 May 2008 09:04:52 +1000 Subject: When was feature FOO added to Python? (was: decorators when?) References: <3m0o34hbb0c6rpr6ec0qh3hlkaagt8pfi5@4ax.com> Message-ID: <87zlqbs60b.fsf@benfinney.id.au> David C. Ullrich writes: > What version added decorators (using the @decorator syntax)? > > (Is there a general way I could have found out the answer myself?) For standard library features, the documentation for a module usually says "(New in 2.4)" or "(Changed in 2.4)" or the like for features that appeared in a particular version. I think this is manually done by the documentation maintainers, though. For features of the language (like decorators), the language reference is the place that *describes* the features; but I don't see any similar "(New in 2.4)" annotations, so e.g. doesn't mention when the decorator syntax appeared in the language. Any documentation maintainers reading: Please consider updating the documents to give this useful "(New in 2.x)" or "(Changed in 2.x)" annotation for just such a situation. You can get closer to the answer by browsing the "What's New in Python" documents by version. From lists at cheimes.de Thu May 29 10:31:03 2008 From: lists at cheimes.de (Christian Heimes) Date: Thu, 29 May 2008 16:31:03 +0200 Subject: seg. fault with Py_BuildValue? In-Reply-To: References: Message-ID: Christian Meesters schrieb: > Hi > > I'm having trouble with Py_BuildValue. I was able to pinpoint the following > statement as the one causing a seg. fault with my script: > > static PyObject * funcname(PyObject *self, PyObject *args) { > .... > return Py_BuildValue("(OO)", x, y); > } > where x & y are both of type PyObject. > > Any suggestions here? Do I need to handle the output of Py_BuildValue > somehow before returning? How? Need to decref x & y before returning? Check if either x or y are NULL. Christian From miller.paul.w at gmail.com Mon May 26 15:22:24 2008 From: miller.paul.w at gmail.com (miller.paul.w at gmail.com) Date: Mon, 26 May 2008 12:22:24 -0700 (PDT) Subject: definition of a highlevel language? References: <2759eed3-956d-45c7-8dfb-9557f74133b3@56g2000hsm.googlegroups.com> <26d0b3d2-01cc-49bd-b284-1a849b0b835f@y38g2000hsy.googlegroups.com> <34dcbdc1-5285-41ec-be06-c88c56bb0372@i76g2000hsf.googlegroups.com> Message-ID: <45f03028-a86c-4357-9aa2-0148f7cc84dc@d45g2000hsc.googlegroups.com> On May 26, 3:02?pm, notnorweg... at yahoo.se wrote: > what is crazy about it? To make, say, a Python machine fast, you'd have to optimize the hell out of the architecture, probably all the way down to the microcode level. Thus, a hypothetical hardware-based Python machine would look very little like other, more conventional chips like x86 or ARM, for instance. In fact, I suspect it'd look a lot like the CPython virtual machine on an instruction level. From bruno.42.desthuilliers at websiteburo.invalid Thu May 15 10:03:05 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 15 May 2008 16:03:05 +0200 Subject: Class Methods Vs Any Other Callable In-Reply-To: <10cce8be-657c-4c40-9705-baebaf90301b@a70g2000hsh.googlegroups.com> References: <98b4a67c-9ec7-407c-8c80-06488bd48a68@e39g2000hsf.googlegroups.com> <690ap7F2u0ftdU1@mid.uni-berlin.de> <238061d6-9423-44c1-90b2-cc09f392db9b@p25g2000hsf.googlegroups.com> <2851a281-d3f2-46c5-8afe-a5dcd6fa31a6@59g2000hsb.googlegroups.com> <10cce8be-657c-4c40-9705-baebaf90301b@a70g2000hsh.googlegroups.com> Message-ID: <482c428c$0$9669$426a34cc@news.free.fr> Arnaud Delobelle a ?crit : > > bruno.desthuilliers at gmail.com wrote: >> On 14 mai, 22:44, Arnaud Delobelle wrote: >>> "bruno.desthuilli... at gmail.com" writes: >>>> On 14 mai, 19:45, Arnaud Delobelle wrote: >>>>> __new__ is a static method! >>>> __new__ is a special-cased staticmethod that 1/ must not be declared >>>> as such and 2/ takes the class object as first args. As far as I'm >>>> concerned, it's semantically a classmethod. >>> It's a static method! > > OK then let me reply pedantically: > >> Sorry Arnaud, I probably didn't made it clear enough : I do know it is >> a staticmethod object. What I say is that >> 1/ it's special-cased since you don't *explicitely* declare it as a >> staticmethod > > In some cases you have to: > > class Foo(object): pass > > # Later on I want to redefine Foo.__new__ > > @staticmethod > def Foo__new__(cls): > print "new Foo!" > return object.__new__(cls) > > Foo.__new__ = Foo__new__ > >>>> Foo() > New Foo! >>>> # Without the @staticmethod we would get a TypeError Point taken. But you'll admit that monkeypatching the __new__ method is somewhat uncommon !-) >> 2/ it behaves Poor word choice here I'm afraid - of course a staticmethod doesn't "behave" like a classmethod object. But you of course __knew__ what I meant !-) >> just like a classmethod, since it takes the class as >> first argument. > > When you invoke it implicitely maybe, but not when you do so > explicitely! I'm not talking about how you invoke it (FWIW, direct invocation of __new__ is pretty rare, parent call excepted - and then, well, it mostly mirrors a direct parent call within an overridden instance method). It's about having __new__ taking the class as first argument. FWIW, I wonder why the BDFL choosed to implement __new__ as a staticmethod - there are probably some pretty good reasons, but not knowing them, it looks like __new__ would have been a perfect candidate for a classmethod. So far, the only reason I can think of is that making it a classmethod would have required the use of super(Parent, cls) to call the parent's class __new__, which may (or may not - never had the case) be problematic (any guru on this ?) >> IOW, I'm talking about semantic, not implementation. > > I understand what you mean, and from that point of view you can argue > against my example above It's somehow difficult to argue against something that's just the plain and naked truth. My one and only argument is about __new__ being semantically close enough to a classmethod to wonder why it isn't one. > (after all, my example is code, not pure > concept) but for me it is simpler to think of __new__ as a > staticmethod (which it is!), plain and simple. I could by no mean hold it against you !-) From jschroed at gmail.com Thu May 8 12:53:36 2008 From: jschroed at gmail.com (John Schroeder) Date: Thu, 8 May 2008 09:53:36 -0700 Subject: Troubles with 'self' In-Reply-To: <467304.16209.qm@web81401.mail.mud.yahoo.com> References: <467304.16209.qm@web81401.mail.mud.yahoo.com> Message-ID: <4878ad7b0805080953l30aec474s65ee9e6dfeed93a@mail.gmail.com> I think you need to make an instance of your class. Try this: my_class_instance = DataAnalysis() LogFile = my_class_instance.BasicSummary ( ) On Thu, May 8, 2008 at 7:07 AM, Richard Speaker < richard.speaker at sbcglobal.net> wrote: > I'm somewhat new to Python... and programming in general. I know enough to > be dangerous for sure. I have a feeling the solution to this is simple. I'm > having trouble getting 'self' to initialize or work in a class application. > I keep getting the message: > > LogFile = self.BasicSummary ( ) > NameError: name 'self' is not defined > > Code looks like this: > > from data_decode import * > class DataAnalysis: > > def PainInTheArse ( self , i , InvI ): > """This is a filter I made to overcome > some problems I was having with sine wave > analysis""" > TemporaryData = [ ] > for a in range ( int ( InvI [ i ] ) , len ( InvI ) ): > if a < 0: > a = 0 > b = a + 1 > try: > TemporaryData.append ( InvI [ a + i ] ) > if ( InvI [ b + i ] < 0 and InvI [ b + i + > 1 ] > 0 ): > TemporaryData.append ( InvI [ a + i > + 1 ] ) > break > except IndexError: > continue > return TemporaryData > def GetTheInvIData ( self , InvI ): > """"Function determines zero-crossing, and then > calculates the +/- peaks to get an average """ > CurrentMaxList = [ ] > CurrentMinList = [ ] > for i in range ( 0 , len ( InvI ) ): > try: > if ( InvI [ i ] <= 0 and InvI [ i + 1 ] > 0 > ): > TemporaryData = self. PainInTheArse > ( i , InvI ) > BetterData = self.FilterTheBS ( > TemporaryData ) > CurrentMaxList.append ( max ( > BetterData ) ) > CurrentMinList.append ( min ( > BetterData ) ) > except IndexError: > continue > MeanCurrentMax = sum ( CurrentMaxList ) / len ( > CurrentMaxList ) > MeanCurrentMin = sum ( CurrentMinList ) / len ( > CurrentMinList ) > InvIPeakToPeak = MeanCurrentMax - MeanCurrentMin > EstPeak = InvIPeakToPeak / 2 > return EstPeak > > def FilterTheBS ( self , TemporaryData ): > """This is another filter I made to overcome > some problems I was having with sine wave > analysis""" > BetterData = [ ] > UselessData = [ ] > for i in range ( 0 , len ( TemporaryData ) ): > try: > if TemporaryData [ i ] == TemporaryData [ i > + 1 ]: > UselessData.append ( TemporaryData > [ i ] ) > else: > BetterData.append ( TemporaryData [ > i ] ) > except IndexError: > BetterData.append ( TemporaryData [ i ] ) > continue > return BetterData > def BasicSummary ( self ): > > DDC = DecodeData( ) > try: > MeanCurrent_A = float ( ( self.GetTheInvIData ( > DDC.InvIa ) ) ) > MeanCurrent_B = float ( ( self.GetTheInvIData ( > DDC.InvIb ) ) ) > MeanCurrent_C = float ( ( self.GetTheInvIData ( > DDC.InvIc ) ) ) > except ValueError: > print'KaFlewie!' > LogFile = [] > LogFile.append ('DEVICE CURRENT SUMMARY:\n') > LogFile.append ( '\tPHASE A: AVG Current = +/- %.2f A' % ( > MeanCurrent_A ) ) > LogFile.append ( '\tPHASE A: AVG Current = +/- %.2f A' % ( > MeanCurrent_B ) ) > > return LogFile > > LogFile = self.BasicSummary ( ) > for a in LogFile: > print a > > > any and all advice is welcome > > Rick > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From cwitts at gmail.com Wed May 28 07:16:57 2008 From: cwitts at gmail.com (Chris) Date: Wed, 28 May 2008 04:16:57 -0700 (PDT) Subject: A quick question References: Message-ID: On May 28, 12:25?pm, "James" wrote: > Hey everyone, > > I just started using python and cant figure this out, I'm trying to > make a program where someone types in a word and the program gives it > back backwards. ?For example if the person puts in "cat" I want the > program to give it back as "tac" and what it does is prints out 3,2,1. ? > How can I get these integers to print as letters? ?This is what I have, > > word = raw_input("Type a word:") > start = len(word) > > for letter in range(start, 0, -1): > ? ? print letter ? word = raw_input("Type a word:") print 'Reversed : %s' % word[::-1] From jschroed at gmail.com Thu May 8 12:48:15 2008 From: jschroed at gmail.com (John Schroeder) Date: Thu, 8 May 2008 09:48:15 -0700 Subject: Given a string - execute a function by the same name In-Reply-To: References: Message-ID: <4878ad7b0805080948q36b97c05j713de0e6c010ad84@mail.gmail.com> You can do it with a class using the __getattr__ function. There might be a way to do it without a class but I don't how to do it that way. class AllMyFunctions(object): def a(self): print "Hello. I am a." def b(self): print "Hey. I'm b." x = raw_input("Enter a function to call: ") if x not in AllMyFunctions().__dict__: print "That's not a function that I have." else: getattr(AllMyFunctions(), x)() On Thu, May 8, 2008 at 9:33 AM, Andrew Koenig wrote: > wrote in message > news:mailman.291.1209400412.12834.python-list at python.org... > > > I'm parsing a simple file and given a line's keyword, would like to call > > the equivalently named function. > > No, actually, you woudn't :-) Doing so means that if your programs input > specification ever changes, you have to rename all of the relevant > functions. Moreover, it leaves open the possibility that you might wind up > calling a function you didn't intend. > > The right way to solve this kind of problem is to list all the functions > you > wish to be able to call in this way, and then explicitly define a mapping > from keywords to the appropriate functions. Which is exactly what you're > doing in > > > 3. Place all my functions in dictionary and lookup the function to be > > called > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Tue May 20 10:07:57 2008 From: castironpi at gmail.com (castironpi) Date: Tue, 20 May 2008 07:07:57 -0700 (PDT) Subject: persistent deque Message-ID: <29451c2a-cb0a-43a6-b140-6c16e3cb46ac@c65g2000hsa.googlegroups.com> I'd like a persistent deque, such that the instance operations all commit atomicly to file system. From tjreedy at udel.edu Tue May 20 14:09:31 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 20 May 2008 14:09:31 -0400 Subject: conventions/requirements for 'is' vs '==', 'not vs '!=', etc References: <4dc24f2e-04f5-4ad6-b021-f416ef5c7415@z72g2000hsb.googlegroups.com><8ebd28f1-887f-45c9-a35f-af9023b062ea@u12g2000prd.googlegroups.com><3629843a-ebcb-4f15-82f1-899500f7b91f@t54g2000hsg.googlegroups.com><20080519234214.beae9314.johnjsal@NOSPAMgmail.com> Message-ID: "Duncan Booth" wrote in message news:Xns9AA470833CCA8duncanbooth at 127.0.0.1... | In short, two equal strings may or may not be identical and any code which | makes assumptions based on observed behaviour is broken. If you want to be | able to test identity on strings safely then use the 'intern()' builtin to | get repeatable behaviour. Intern() is gone in 3.0 From bruno.42.desthuilliers at websiteburo.invalid Mon May 19 06:07:40 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 19 May 2008 12:07:40 +0200 Subject: How do *you* use Python in non-GUI work? In-Reply-To: <20080518182022.990193bd.johnjsal@NOSPAMgmail.com> References: <20080518182022.990193bd.johnjsal@NOSPAMgmail.com> Message-ID: <4831516b$0$24599$426a74cc@news.free.fr> John Salerno a ?crit : > Hey all. Just thought I'd ask a general question for my own interest. > Every time I think of something I might do in Python, it usually > involves creating a GUI interface, so I was wondering what kind of > work you all do with Python that does *not* involve any GUI work. > This could be any little scripts you write for your own benefit, or > what you do at work, if you feel like talking about that! :) web apps, command line utilities, and of course libraries. From arnodel at googlemail.com Mon May 26 04:06:46 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 26 May 2008 09:06:46 +0100 Subject: set partition question References: <4839c866$0$32633$9b622d9e@news.freenet.de> <3b08539b-d4ba-4616-86df-529fceeeef01@q24g2000prf.googlegroups.com> Message-ID: Arnaud Delobelle writes: > pball.benetech at gmail.com writes: > >> On May 25, 1:13?pm, "Martin v. L?wis" wrote: >>> > We can use any operation or function which >>> > takes and returns sets. >>> >>> I think the problem is significantly underspecified. It would be a more >>> interesting problem if there was a restriction to a few selected set >>> operations, e.g. union, intersection, difference, and combinations >>> thereof. >> >> Ok, that's quite right -- when I just tried to define "any function," >> I found that all the solutions I came up with were combinations of the >> set operations defined for immutable sets. Let me improve the spec as >> the following: >> >> There may be arbitrarily many set elements (denoted by integers >> 1,2,3,...), arbitrarily many combinations of the elements composing >> the sets s_i (s0, s1, ...). We can use any of python's set operations >> or combination of those operations. > > OK then, if you only allow union, intersection, difference, symmetric > difference then I think it would be easy to prove (I haven't done it!) > that if there is a solution to you problem, then the method below > yields a solution: > > *** warning: all this is untested AND written in a rush *** > > let S be the set of all your sets except s0 (i.e. s1, s2, s3, ...) > > > # X is the "domain", C is the set of complements in X of elements of S > > X = reduce(set.union, S) > C = set(X - s for s in S) > > > # Find the "fibers" at each element x of s0. A fiber at x is the set > # of all s in S or C that contain x > > from collections import defaultdict > fibers = defaultdict(list) > > for s in S | C: > for x in s & s0: > fibers[x].append(s) > > > # Find the "seeds" at each x in s0. A seed at x is the set of all > # elements contained in all s in the fiber at x. > > # Intutively, a seed at x is the smallest set containing x that can be > # built from S > > seeds = [reduce(set.intersection, F) for F in fibers.itervalues()] > > > # Now we know if there is a solution: > > sol = reduce(set.union, seeds) > > if sol != s0: > print "No solution" > else: > print "Solution: union(intersection(fibers[x]) for x in s0)" > > > I think this solution will be found in O(m*n**2) time, where: > > * n is the size of X (i.e. the total number of elements) > * m is the size of S (i.e. the total number of sets) > > and assuming that set operations are linear. I forgot to add, using reduce() is probably not a great idea but it allowed me to write down my idea quickly! -- Arnaud From castironpi at gmail.com Sun May 11 04:09:21 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 11 May 2008 01:09:21 -0700 (PDT) Subject: Is using range() in for loops really Pythonic? References: <482657ca$0$25026$607ed4bc@cv.net> <7xabix2yds.fsf@ruckus.brouhaha.com> Message-ID: <76cd3ea7-58e1-4167-a8b4-8108dc6e7bc1@z72g2000hsb.googlegroups.com> On May 11, 12:38?am, Paul Rubin wrote: > John Salerno writes: > > for x in range(10): > > ? ? #do something 10 times > > > is unPythonic. The reason I ask is because the structure of the for loop > > seems to be for iterating through a sequence. It seems somewhat > > artificial to use the for loop to do something a certain number of > > times, like above. > > It is pretty natural in imperative-style code. ?The one thing I'd do > differently is use xrange instead of range, to avoid creating a > 10-element list in memory before starting the loop. If you give extras to memory, can Python live? From gagsl-py2 at yahoo.com.ar Thu May 8 08:44:34 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 08 May 2008 09:44:34 -0300 Subject: python equivalent to perl's inplace edit mechanism References: <170543c70805080511o348f38fam5c56c71fce4a6f37@mail.gmail.com> Message-ID: En Thu, 08 May 2008 09:11:56 -0300, Michael Mabin escribi?: > Does python have an equivalent to Perl's inplace-edit variable $^I? > For example, the following perl code below changes mike to dave in a file > that is passed as an argument. > > #!/usr/bin/env perl > #chgit script > $^I = ''; > while(<>) { > s/mike/dave/g; > print; > } > > The script would be used as below: > chgit somefile > > Afterward, all instances of mike are changed to dave. Like this? import sys,fileinput for line in fileinput.input(inplace=True): sys.stdout.write(line.replace('mike','dave')) Sample session: C:\TEMP>type foo.txt this line tells about mike and john this second line says nothing goodbye mike! C:\TEMP>python chgit.py foo.txt C:\TEMP>type foo.txt this line tells about dave and john this second line says nothing goodbye dave! -- Gabriel Genellina From Lie.1296 at gmail.com Tue May 13 10:20:14 2008 From: Lie.1296 at gmail.com (Lie) Date: Tue, 13 May 2008 07:20:14 -0700 (PDT) Subject: Is using range() in for loops really Pythonic? References: <482657ca$0$25026$607ed4bc@cv.net> <41078222-aec0-4e8b-8a1f-945cdf814498@m73g2000hsh.googlegroups.com> <48275446$0$11628$607ed4bc@cv.net> <87mymw8nr0.fsf@benfinney.id.au> <4827bda2$0$11606$607ed4bc@cv.net> <87od7c6qua.fsf@benfinney.id.au> <482912b7$0$11641$607ed4bc@cv.net> Message-ID: On May 13, 11:01?am, John Salerno wrote: > Ben Finney wrote: > > I think that the idiom > > > ? ? for unused in xrange(10): > > ? ? ? ? # do stuff with no reference to 'unused' > > > is quite common. Is that what you're asking about? > > Yes. I was more or less asking about the specific situation of using a > for loop to do something X number of times, but I think the more > generalized problem that everyone is talking about -- using a counter > variable that is never referenced in the loop -- probably puts the point > I was trying to make in a better light. > > The reason I even brought this up is because I remember someone saying a > while back (probably here on the newsgroup) that the true use of a for > loop was to iterate through a sequence (for the purpose of using that > sequence), not to do something X number of times. Once they made this > comment, I suddenly saw the for loop in a new (and I believe purer) > light. That was the first time I realized what it was really meant > to do. > > Using something like: > > for unused in xrange(10): > ? ? # do stuff 10 times > > suddenly seemed to me like a hackish way to replace > > for (int i=0; i<10; i++) { > ? ? // do stuff 10 times; > > } > > Not that I think the above code (C#) looks all that elegant either. But > in C# there is a distinction between the above, and this: > > foreach (int i in sequence) > ? ? // do something; > > which is more closely related to the Python for loop. > > Now, you could easily make the argument that the Python for loop is a > much simpler tool to accomplish *both* of the above, and I suppose that > makes sense. Seems a little silly to have two separate for loops to do > these things. I just wasn't sure if the "counter" version of the Python > for loop was considered slightly unpythonic. What was unPythonic, I think, as most people would agree, is to use for like this: -- for i in xrange(len(lst)): pass -- In VB, my language before Python, I've never used For Each even for a sequence (Array, in VB), it seems too messy back then. Now, with Python that only allowed a foreach statement, I realized that I never really needed a for i in range(10) at all. Most of the time the places where I need to do that is where the code is just a test code that loops a certain number of times (with randomized input data), almost never (probably never) met that in a real program code. And even in some of those cases, the variables are usually used too (as a test argument to the function being tested) or for logging purpose. On May 13, 8:25 pm, Larry Bates wrote: (snip) > I use it quite often, especially if I want to implement a fixed number of > retries on a communications channel. > > -Larry That still have semantic meaning: 'tries'. If it was me, I'll go to the trouble of giving names, since I would use it for logging or informational purpose ('first try' 'second try' 'third try' 'no more try'). I've never really met a real "do something n times" case, where the variable doesn't hold any semantic meaning that I don't want to use and is not a test case. For me, a _ (or any other dummy variable[1]) is good enough and it's easy to change if later I realized that I actually need to use the variable. I agree though, that i, j, k for unused name is a bad choice because single letter names is in common usage in mathematics. [1] PEP 8 is useless if a certain code base has other agreed convention, as long as the name used for a unused name in certain code base is consistent (and probably documented), it never becomes a problem. From daveparker at flamingthunder.com Wed May 21 12:11:13 2008 From: daveparker at flamingthunder.com (Dave Parker) Date: Wed, 21 May 2008 09:11:13 -0700 (PDT) Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> Message-ID: <7ae9cb4f-60bf-4e77-826c-03248cca4027@w4g2000prd.googlegroups.com> On May 21, 10:00?am, "Dan Upton" wrote: > Sounds to me like the teacher is being difficult, ... No, proof-by-contradiction is a common technique in math. If you can show that x=8 and x=10, then you have shown that your assumptions were incorrect. > If you can't do, or don't like, math, you probably shouldn't be > programming. Why not? Recipes are programs. I prefer to look at it the other way: an easy-to-use programming language might encourage more people to like math. > You keep trotting out this quadratic equation example, but does FT > actually have any kind of useful equation solver in it? Not yet, but it will. Probably around July. From inhahe at gmail.com Fri May 16 12:59:01 2008 From: inhahe at gmail.com (inhahe) Date: Fri, 16 May 2008 12:59:01 -0400 Subject: Thread killing - I know I know! References: Message-ID: I'm not sure it's possible to kill a thread in Python that's in the middle of a C function. I know you can't do it with signals, for example. Or can you? I'm on Windows and signals isn't fully implemented. I had to do just this, btw, so I wrote another Python program that communicates with the main one over a socket and then if it misbehaves I can kill it using an OS command because it's a process and there's an OS command for killing processes, and then I'd restart it. The problem is that, sometimes the OS kill command would work, sometimes it wouldn't, and I never did figure what makes the difference. "Roger Heathcote" wrote in message news:DZSdnYx_IraeNrDVnZ2dneKdnZydnZ2d at bt.com... > Hello everyone, this is my first post so hello & please be gentle! > > Despite many peoples insistence that allowing for the arbitrary killing of > threads is a cardinal sin and although I have no particular threading > problem to crack right now I remain interest in the taboo that is thread > killing. The real world and it's data are messy and imperfect and I can > think of several scenarios where it could be useful to be able to bump off > a naughty thread, especially when using/testing unstable 3rd party modules > and other code that is an unknown quantity. > > With this in mind I am experimenting with a set of threading subclasses > that would permit timeouts and the manual killing of threads. I'm trying > to evaluate how robust such a scheme can be made and what the limitations > would be in practice. > > So far I can seemingly murder/timeout pure python threads that are stuck > blocking for input and stuck in infinite loops but I'm guessing there are > many more awkward cases. What I'm looking for are examples of code/modules > that can get stuck in dead ends or might otherwise be problematic to > terminate. > > In particular I'd be interested to see if I could kill a non-returning c > module. Of course naturally no one wants to be publishing buggy modules > and the like so I am having trouble finding examples of misbehaving c code > to explore further. I figure I could learn how to write c modules for > python but, while it's something I'd like to know someday, I'm guessing > that will be too long to fit into the immediate future :/ Consequently if > anyone has detailed knowledge of what is and isn't fundamentally possible > in the world of thread culling, or if you can point me to some > gnarly/non-returning thread code to test with I would be forever grateful. > > Oh yes, I'm working primarily with 2.5 on XP however I have access to > linux & OSX boxen and I'd be interested to learn about problematic thread > code for either of those platforms as well. > > Thanks for reading, > > Roger Heathcote - www.technicalbloke.com From mccredie at gmail.com Wed May 28 21:08:35 2008 From: mccredie at gmail.com (Matimus) Date: Wed, 28 May 2008 18:08:35 -0700 (PDT) Subject: accessing class attributes References: <5827888d-4e9b-45bd-9361-108714c9043a@m45g2000hsb.googlegroups.com> Message-ID: > I have a game class, and the game has a state. Seeing that Python has > no enumeration type, at first I used strings to represent states: > "paused", "running", etc. But such a representation has many > negatives, so I decided to look at the Enum implementation given here:http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/413486 I frequently use strings in place of enumeration in python. I have found it to be very useful. I'm curious about the _many negatives_ you have found? For example, I wrote a module and one of the parameters to a function was `mode`. Two of the modes were ALL_MODE and ONE_MODE. At first I enumerated the modes: MODES = ALL_MODE, ONE_MODE = 0, 1 And code using the mode tended to look something like this: from package import module module.foo(mode=module.ALL_MODE) Of course, the following would also work, but isn't self descriptive: module.foo(mode=0) Then, after some user feedback I changed it to this: MODES = ALL_MODE, ONE_MODE = "all one".split() This maintained backwards compatabilty, but users could use the much more concise (but still readable) version: module.foo(mode="all") Since then, I have adopted using strings in place of enum types as a best practice. Matt From bj_666 at gmx.net Sat May 3 02:16:13 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 3 May 2008 06:16:13 GMT Subject: is +=1 thread safe References: <4819DA2D.3030508@ggmail.com> <67vs9qF2r409aU2@mid.uni-berlin.de> Message-ID: <682e9cF2qodffU1@mid.uni-berlin.de> On Fri, 02 May 2008 19:23:54 +0100, Arnaud Delobelle wrote: > Marc 'BlackJack' Rintsch writes: > >> >> There are no modern processors with an opcode for incrementing a memory >> location!? At least my C64 can do that. ;-) > > Indeed! I remember a simple use was to make the border change colour > very fast, a v. cool effect when you're 12! > > CLV > LOOP: INC $D020 > BVC LOOP > > (from memory, untested!) That works but I think LOOP: INC $D020 JMP LOOP is a bit more straight forward. Shorter in opcodes, equal in bytes, the loop is as fast but you save the two cycles of the CLV. :-) Ciao, Marc 'BlackJack' Rintsch From paddy3118 at googlemail.com Wed May 21 01:39:30 2008 From: paddy3118 at googlemail.com (Paddy) Date: Tue, 20 May 2008 22:39:30 -0700 (PDT) Subject: Using Python for programming algorithms References: Message-ID: <451986c6-ba24-4060-917b-97fedcba13d7@x35g2000hsb.googlegroups.com> On May 17, 11:32 pm, Vicent Giner wrote: > Hello. > > I am new to Python. It seems a very interesting language to me. Its > simplicity is very attractive. > > However, it is usually said that Python is not a compiled but > interpreted programming language ?I mean, it is not like C, in that > sense. > > I am working on my PhD Thesis, which is about Operations Research, > heuristic algorithms, etc., and I am considering the possibility of > programming all my algorithms in Python. > > The usual alternative is C, but I like Python more. Using Python doesn't mean you give up on C! Many of the best algorithms written in other languages such as C, C++ and Fortran are pre-wrapped in Python or can be wrapped in a Python interface to enhance usability, without having to pay Matlab-type prices. You then make your resulting work easier to reproduce by lowering the cost to other researchers. Python is a scripting language. Despite what some may think, it is a boon, as it means that Pythons designers value its ability to work well with other languages and systems. Nothing stops you from exploring algorithm space in Python then re- implementing in a language closer to assembler - and this may well be the quicker way to your goal. - Paddy. From gandalf at shopzeus.com Fri May 16 07:33:04 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Fri, 16 May 2008 13:33:04 +0200 Subject: ply yacc lineno not working? Message-ID: <482D70F0.9070202@shopzeus.com> This is a fragment from my yacc file: import ply.yacc as yacc from lex import tokens from ast import * def p_msd(p): r"""msd : SCHEMA WORD LBRACE defs RBRACE """ p[0] = MSDSchema(p[2]) print p.lineno(5) # Line number of the right brace p[0].items = p[4] Here is a test input: """ schema TestSchema { field name : varchar { required; size 100; } } """ My program prints out 1. No matter what I do, YaccProduction.lineno(n) returns 1 for every possible n between 0 and 5. What am I doing wrong? Can it be a problem if I use this in my lexer: # Whitespace is mostly ignored, except inside quoted words. def t_ws(t): r'[\n\r\t ]+' # We do not return anything so this will be ignored. If so, how can I easily ignore newlines while preserving the line number for yacc.parse ? Thanks, Laszlo From deets at nospam.web.de Thu May 1 11:18:47 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 01 May 2008 17:18:47 +0200 Subject: is +=1 thread safe In-Reply-To: <4819DA2D.3030508@ggmail.com> References: <4819DA2D.3030508@ggmail.com> Message-ID: <67u5aqF2qfrq9U1@mid.uni-berlin.de> AlFire schrieb: > Hi, > > I have a piece of software which uses threads in very massive way - like > hundreds of them generated every second. > > there is also a piece of code which maintains the number of outstanding > threads, simply > > counter+=1 is executed when before starting the thread and counter-=1 > after it finishes. > > all is very simple and by the end of the program life I expect the > counter to zero out. > > however I am getting values -1, -2, 1 ,2 ,3 and quite often 0 as expected. > > I guarded those statement with Lock.{acquire,release} and now it always > returns 0. > > > But I still can not believe that +=1 is not a thread safe operation. don't confuse augmented assignment with incrementation as it is offered by C (if your data-type actually fits into a single addressable memory spot, that is) python's += works like this a += b <=> a = a.__iadd__(b) Thus you actually get a situation where the expression on the right is evaluated but not yet assigned - and then another thread can take over control, computing with the old value of a. Diez From george.sakkis at gmail.com Tue May 27 15:16:41 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 27 May 2008 12:16:41 -0700 (PDT) Subject: Hungarian Notation References: <6382bf6f-3478-4a88-8f43-3b38c20d3b85@l64g2000hse.googlegroups.com> Message-ID: <3c7d20b4-50ee-4397-b3ba-3f22245b1420@x41g2000hsb.googlegroups.com> On May 27, 3:43 am, Paddy wrote: > On May 27, 7:42 am, "inhahe" wrote: > > > Well, I just need it once in a while. Actually now is the only time I > > remember. The last time what I needed was a file name extension. I want a > > string called headers, but I want to derive a dict from it, also called > > headers. So I figured the string would be called strHeaders, and the dict, > > dctHeaders probably, but when a precedent for something like that exists, I > > like to use it. > > > "Kam-Hung Soh" wrote in message > > I have a my own sometime used convention od using dict names that > mirror > what is being mapped to what, so a dict mapping headers to body might > be called head2body, in general a mapping from x to y I might call > x2y. I use the same convention, though it's less than ideal if x or y consist of more than one word (typically joined with underscore), e.g. "value2row_id" or if the values are also dicts ("category2value2instances"). George From nick at craig-wood.com Fri May 23 16:30:09 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Fri, 23 May 2008 15:30:09 -0500 Subject: array of 64-bit ints? References: <483700FF.1020704@v.loewis.de> Message-ID: Martin v. L?wis wrote: > > Is it possible to have an array of 64-bit-ints using the standard Python > > array module? On my 64-bit architecture (AMD64, MSVC), both "int" and > > "long int" are 32 bit integers. To declare 64-bit ints, one needs either > > "long long int" or "size_t". However, according to the Python array > > documentation, arrays of "size_t" or "long long int" are not available. > > No, it's not possible. You could do it with ctypes like this... from ctypes import * Array = c_int64 * 100 a = Array() for i in range(100): a[i] = 2**63 - i for i in range(100): print a[i] prints -9223372036854775808 9223372036854775807 9223372036854775806 [snip] 9223372036854775710 9223372036854775709 ctypes arrays are fixed length once created though. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From gherron at islandtraining.com Fri May 16 17:40:51 2008 From: gherron at islandtraining.com (Gary Herron) Date: Fri, 16 May 2008 14:40:51 -0700 Subject: can't delete from a dictionary in a loop In-Reply-To: References: Message-ID: <482DFF63.7020701@islandtraining.com> bruno.desthuilliers at gmail.com wrote: > On 16 mai, 23:28, Hans Nowak wrote: > >> Dan Upton wrote: >> >>> for pid in procs_dict: >>> if procs_dict[pid].poll() != None >>> # do the counter updates >>> del procs_dict[pid] >>> >>> The problem: >>> >>> RuntimeError: dictionary changed size during iteration >>> >> I don't know if the setup with the pids in a dictionary is the best way to >> manage a pool of processes... I'll leave it others, presumably more >> knowledgable, to comment on that. :-) But I can tell you how to solve the >> immediate problem: >> >> for pid in procs_dict.keys(): >> No, keys() produces a list (which is what is wanted here). It's iterkeys() that produces an iterator which would reproduce the OP's problem. And then, in Python3, keys() produces something else altogether (call a view of the dictionary) which would provoke the same problem, so yet another solution would have to be found then. Gary Herron > > I'm afraid this will do the same exact thing. A for loop on a dict > iterates over the dict keys, so both statements are strictly > equivalent from a practical POV. > -- > http://mail.python.org/mailman/listinfo/python-list > From notbob at nothome.com Sat May 10 23:45:38 2008 From: notbob at nothome.com (notbob) Date: Sun, 11 May 2008 03:45:38 GMT Subject: Now what!? References: <68m0i1F2t8265U1@mid.uni-berlin.de> <7363f4c0-1dec-4943-a9f6-7a24c3aff971@e39g2000hsf.googlegroups.com> <9GlVj.168$PE5.102@fe087.usenetserver.com> Message-ID: On 2008-05-11, Dennis Lee Bieber wrote: > on the Amiga, it could be any of those applications). ahhh.... the Amiga, the demise of which was one of the great calamaties of our cyber time. (sniff) nb From inhahe at gmail.com Wed May 21 10:57:32 2008 From: inhahe at gmail.com (inhahe) Date: Wed, 21 May 2008 10:57:32 -0400 Subject: C-like assignment expression? References: <68b5d090-9e3b-4e7d-9dda-fc1b099822c2@m73g2000hsh.googlegroups.com> <48340412$0$10773$426a74cc@news.free.fr> <87fxsbzxn4.fsf@mulj.homelinux.net> <7df99fd4-21c9-49a1-ba65-e55794fd4c12@26g2000hsk.googlegroups.com> Message-ID: one of the few things i miss from C is being able to use assignment in expressions. that's the only thing, really. also there's no switch/case, you have to use a dictionary of functions instead, although i rarely need that, usually i just use elif. wrote in message news:7df99fd4-21c9-49a1-ba65-e55794fd4c12 at 26g2000hsk.googlegroups.com... > On May 21, 1:47 pm, Hrvoje Niksic wrote: > >> Although that solution is pretty, it is not the canonical solution >> because it doesn't cover the important case of "if" bodies needing to >> access common variables in the enclosing scope. (This will be easier >> in Python 3 with 'nonlocal', though.) The snippet posted by Diez is >> IMHO closer to a canonical solution to this FAQ. > > Hello everybody, > > thanks for the various answers. I'm actually pretty puzzled because I > expected to see some obvious solution that I just hadn't found before. > In general I find Python more elegant and syntactically richer than C > (that's where I come from), so I didn't expect the solutions to be a > lot more verbose and/or ugly (no offense) than the original idea which > would have worked if Python's assignment statement would double as > expression, as in C. > > Thanks again, > robert > > PS: Since I'm testing only three REs, and I only need the match > results from one of them, I just re-evaluate that one. From hdante at gmail.com Thu May 15 12:43:15 2008 From: hdante at gmail.com (Henrique Dante de Almeida) Date: Thu, 15 May 2008 16:43:15 +0000 (UTC) Subject: pyserial and file open conflict? References: <21c8f220-aa3c-40b8-b1de-3aa35472e2dc@26g2000hsk.googlegroups.com> Message-ID: Em Thu, 15 May 2008 08:03:40 -0700, p.wallstedt escreveu: > Hi all! > > I have a small but rather annoying problem with pyserial. I want to open > a file on disk for reading and then open a com-port, write lines from > the file to the port and then read something back and compare it to the > next line in the file. Should be simple. And it is, apart from the fact > that the file seems to be doubled ...? Or it loops through the file > twice. > > If I exclude the "import serial" it works. > > Any ideas? > > thanks > Peter Are you sure you need to reinvent the wheel ? For example, pppd has the "chat" application: http://www.hmug.org/man/8/chat.php From krumblebunk at gmail.com Tue May 6 08:27:26 2008 From: krumblebunk at gmail.com (krumblebunk at gmail.com) Date: Tue, 6 May 2008 05:27:26 -0700 (PDT) Subject: Comparing strings - akin to Perl's "=~" Message-ID: Hello gurus, I am learning Python to take the place of Perl in my toolbox of bits and bobs, and writing something pretty simple in theory, but having a hard time in Python with it - I am using a 3rd party module, and I am sure the etiquette of this channel states that this is pure Python questions only, but please bare with me in light of this, as my question does indeed relate to Python only. I am grabbing the output from a SQL statement (using PyGreSQL 'pg' module), and when it returns the result, I am pulling it out as such: try: sc=pg.connect(dbname='mydb',host='dbhost',user='ppp') except pg.InternalError: print "Failed to execute SQL: %s" % sql exit for foo in sc.query(sql).dictresult(): <- this returns a dict of the result f=dict(foo) for k in f.iteritems() if k == '^Hostname': <-- need this sort of behaviour - match a partial string. print "%s" % f[3] <-- ..and if true, need to pull out the 4th column on that line. This breaks spectacularly - any ideas? thanks! kb. From carsten.haese at gmail.com Tue May 13 21:49:14 2008 From: carsten.haese at gmail.com (Carsten Haese) Date: Tue, 13 May 2008 21:49:14 -0400 Subject: 2004 example, passing function error In-Reply-To: <3a70d3c9-41b9-4dfa-9127-ed6d1a8abda5@s50g2000hsb.googlegroups.com> References: <3a70d3c9-41b9-4dfa-9127-ed6d1a8abda5@s50g2000hsb.googlegroups.com> Message-ID: globalrev wrote: > but it looks like he just copied his > shell...has there been a change since 2004 inr egards to how you can > pass functions as arguments to functions?? It looks like it's copy/pasted from a shell, but it's not. No past or present Python interpreter could produce an interactive session like that under any circumstances. My guess is that instead of copy/pasting, the author simply retyped the session and made a mistake in doing so. -- Carsten Haese http://informixdb.sourceforge.net From roy at panix.com Sat May 24 10:57:29 2008 From: roy at panix.com (Roy Smith) Date: Sat, 24 May 2008 10:57:29 -0400 Subject: unittest: Calling tests in liner number order References: Message-ID: In article , Fuzzyman wrote: > Whilst I understand your point, I think the danger is that you end up > with hidden dependencies on the test order - which you're not aware of > and that the tests never expose. Well, yes. But, this is no worse than the current situation, where the tests are run in alphabetical order by default. You could still have hidden dependencies and not realize it. From casey.mcginty at gmail.com Sun May 25 18:46:50 2008 From: casey.mcginty at gmail.com (Casey McGinty) Date: Sun, 25 May 2008 12:46:50 -1000 Subject: Organizing a Python project In-Reply-To: References: <960da03c-1edf-4fa4-b434-6656e8a8884f@e39g2000hsf.googlegroups.com> Message-ID: On Sat, May 24, 2008 at 2:11 PM, Gabriel Genellina wrote: > > 2. In the top of your package directory it is typical to have a module > name > > '_package.py'. This is ideally where the main command line entry point > for > > the package code should be placed. > > Why the underscore? And I usually don't put executable scripts inside a > package - I consider them just libraries, to be imported by other parts of > the application. > It's easier to test too when your tests *and* the application code are > external to the package itself. > Ok, guess using the '_package' name is not very common. I saw it used by the dbus module. My whole concern here is that using a script will fragment your application code across the file system. I would prefer to have it all in a single spot. So I still like they idea of keeping most of application code (argument parsing, help output, initialization) inside of the package. The '_' should indicate that any other modules using your package should import that module. - Casey -------------- next part -------------- An HTML attachment was scrubbed... URL: From mathieu.prevot at ens.fr Sat May 24 08:56:30 2008 From: mathieu.prevot at ens.fr (Mathieu Prevot) Date: Sat, 24 May 2008 14:56:30 +0200 Subject: Popen: NameError: name 'PIPE' is not defined In-Reply-To: <69qgseF31lv3aU1@mid.uni-berlin.de> References: <69qgseF31lv3aU1@mid.uni-berlin.de> Message-ID: <3e473cc60805240556t26019274x3e028ffe9196f46@mail.gmail.com> 2008/5/24 Diez B. Roggisch : > Mathieu Prevot schrieb: >> >> Hi >> >> I import subprocess and use Popen, but PIPE is not defined. I used >> 2.5.1, 2.5.2, Python 2.6a3+ (trunk:63576, May 24 2008, 12:13:40), it's >> always the same. What am I missing ? > > Without showing code, it's hard to know. A guess is: if you use > > import subprocess > > > then use > > > subprocess.PIPE > > Or if using > > from subprocess import Popen > > make sure to do > > from subprocess import Popen, PIPE > > Diez Indeed... thank you ! Mathieu From mcknight0219 at gmail.com Mon May 12 22:19:05 2008 From: mcknight0219 at gmail.com (Jimmy) Date: Mon, 12 May 2008 19:19:05 -0700 (PDT) Subject: how to get information of a running prog in python Message-ID: <8b571818-25f0-4c5d-8b1c-5b7e73192d15@w5g2000prd.googlegroups.com> Well, i know it may be a little non-python thing, however, I can think of no place better to post this question :) can anyone tell me, in python, how to obtain some information of a running program? paticularly, if i am playing some music in audacious or other media player, how can i get the the name and some other info of current playing song? It seems that audicious doesn't output on run-time From joe.p.cool at googlemail.com Sun May 11 17:10:39 2008 From: joe.p.cool at googlemail.com (Joe P. Cool) Date: Sun, 11 May 2008 14:10:39 -0700 (PDT) Subject: Python GUIs and custom controls References: <049d1607-c578-48dc-83f3-42cf562449b4@p25g2000hsf.googlegroups.com> <68ifekF2sqbg2U1@mid.uni-berlin.de> Message-ID: On 9 Mai, 10:14, "Diez B. Roggisch" wrote: > If you can work with the license (GPL), I suggest Qt4 Thanks for your helpful hints, guys. -- Joe P. Cool From pDOTpagel at helmholtz-muenchen.de Sat May 31 11:15:12 2008 From: pDOTpagel at helmholtz-muenchen.de (Philipp Pagel) Date: Sat, 31 May 2008 15:15:12 +0000 (UTC) Subject: How to covert ASCII to integer in Python? References: <45f694b7-8c2c-4548-b6e8-42a12e96e0d4@d77g2000hsb.googlegroups.com> Message-ID: Mensanator wrote: > On May 30, 10:03???am, Philipp Pagel > wrote: > > 'P' is obviously not an ASCII representation of a number. > It is in base 36. Sure, but if that was the OP's intent he would most likely have mentioned it... As others have already guessed, it's most likely somethink like ord() he was after. cu Philipp -- Dr. Philipp Pagel Lehrstuhl f. Genomorientierte Bioinformatik Technische Universit?t M?nchen http://mips.gsf.de/staff/pagel From ptmcg at austin.rr.com Tue May 20 10:58:00 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 20 May 2008 07:58:00 -0700 (PDT) Subject: Misuse of list comprehensions? References: <038e4418$0$27258$c3e8da3@news.astraweb.com> Message-ID: <6359d72c-f937-46cd-b1ce-b7450671b714@i76g2000hsf.googlegroups.com> On May 20, 8:13?am, "John Salerno" wrote: > I posted this code last night in response to another thread, and after I > posted it I got to wondering if I had misused the list comprehension. Here's > the two examples: > > Example 1: > -------------------- > def compress(s): > ? ? new = [] > > ? ? for c in s: > ? ? ? ? if c not in new: > ? ? ? ? ? ? new.append(c) > ? ? return ''.join(new) > ---------------------- > > Example 2: > ------------------------ > def compress(s): > ? ? new = [] > ? ? [new.append(c) for c in s if c not in new] > ? ? return ''.join(new) > -------------------------- > > In example 1, the intention to make an in-place change is explicit, and it's > being used as everyone expects it to be used. In example 2, however, I began > to think this might be an abuse of list comprehensions, because I'm not > assigning the result to anything (nor am I even using the result in any > way). > > What does everyone think about this? Should list comprehensions be used this > way, or should they only be used to actually create a new list that will > then be assigned to a variable/returned/etc.? Why not make the list comp the actual list you are trying to build? def compress(s): seen = set() new = [c for c in s if c not in seen and (seen.add(c) or True)] return ''.join(new) or just: def compress(s): seen = set() return ''.join(c for c in s if c not in seen and (seen.add(c) or True)) Using the set also gets rid of that nasty quadratic performance thingy. -- Paul From kay.schluehr at gmx.net Fri May 23 01:00:17 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Thu, 22 May 2008 22:00:17 -0700 (PDT) Subject: Python is slow References: <3J6dnbQZld6PZKjVnZ2dnUVZ_sDinZ2d@comcast.com> Message-ID: On 23 Mai, 00:51, Larry Bates wrote: > > I've yet to see a web application written in Python which is really > > fast. > > You are just dead wrong about this. No, he can demand whatever he wants and we can be stupid enough to respond. From spamgrinder.trylater at ggmail.com Sun May 4 00:18:47 2008 From: spamgrinder.trylater at ggmail.com (AlFire) Date: Sat, 03 May 2008 23:18:47 -0500 Subject: is +=1 thread safe In-Reply-To: References: <4819DA2D.3030508@ggmail.com> <481BD50F.5080608@ggmail.com> Message-ID: <481D3927.4050509@ggmail.com> Alexander Schmolck wrote: > AlFire writes: > >>> The threading module already has a function to return the number of Thread >>> objects currently alive. >> I have threads within threads - so it does not suit me :-(. > > How about using a scalar numpy array? They are mutable, so I assume that x += > 1 should be atomic. > I ended up with following: counter=[] counter=0 counter.append(None) counter+=1 counter.pop() counter-=1 len(counter) counter A. From meesters at uni-mainz.de Fri May 30 09:05:47 2008 From: meesters at uni-mainz.de (Christian Meesters) Date: Fri, 30 May 2008 15:05:47 +0200 Subject: seg. fault with Py_BuildValue? References: Message-ID: Ok now, I know where the error is: "y" actually contained refcounts. This, of course, is complete nonsense and causes the interpreter to crash at some point. Thanks to all of you: You helped at least to track down the problem. Christian From mnikhil at gmail.com Wed May 14 14:25:51 2008 From: mnikhil at gmail.com (Nikhil) Date: Wed, 14 May 2008 23:55:51 +0530 Subject: readlines with line number support? Message-ID: Hi, I am reading a file with readlines method of the filepointer object returned by the open function. Along with reading the lines, I also need to know which line number of the file is read in the loop everytime. I am sure, the line should have the property/attribute which will say the line number of the file. If there is none, do I have to end up using the counter in the loop? fp = open("file", "r") lineno = 0 for line in fp.readlines(): print "line number: " + lineno + ": " + line.rstrip() lineno = lineno + 1 -- Thanks, Nikhil From roy at panix.com Wed May 21 15:13:18 2008 From: roy at panix.com (Roy Smith) Date: Wed, 21 May 2008 15:13:18 -0400 Subject: best way to check if pid is dead? References: <90ecca29-c4d8-4e89-908a-93850d7de1bf@i76g2000hsf.googlegroups.com> Message-ID: In article <90ecca29-c4d8-4e89-908a-93850d7de1bf at i76g2000hsf.googlegroups.com>, bukzor wrote: > Does anyone have a pythonic way to check if a process is dead, given > the pid? > > This is the function I'm using is quite OS dependent. A good candidate > might be "try: kill(pid)", since it throws an exception if the pid is > dead, but that sends a signal which might interfere with the process. > > Thanks. > --Buck The canonical way is to do kill(pid, 0). If it doesn't throw, the process exists. No actual signal is sent to the process either way. Of course, the process could exit immediately after the kill() call, so by the time you find out it's alive, it's dead. Such is life. From inhahe at gmail.com Fri May 16 10:27:45 2008 From: inhahe at gmail.com (inhahe) Date: Fri, 16 May 2008 10:27:45 -0400 Subject: Variable by label References: Message-ID: <_PgXj.4838$Kk3.4214@bignews9.bellsouth.net> >>> a = 1 >>> b = eval("a") >>> b 1 >>> a =1 >>> b = globals()["a"] >>> b 1 >>> a =1 >>> b = locals()["a"] >>> b 1 wrote in message news:aec6cdd8-3bde-4d68-ad93-d9ece9567886 at b1g2000hsg.googlegroups.com... > Is there any function which will return a variable by passing to it > the string containing the variable's name? Something like this for > instance: > > foo = some_function("foo") > > or perhaps it's a dictionary. I don't know, but I would really like to > find out how it can be done. I guess it is achievable. > > Thank you. From kyosohma at gmail.com Wed May 7 08:57:43 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 7 May 2008 05:57:43 -0700 (PDT) Subject: Scanning through Windows registry... References: <48216129.5090405@timgolden.me.uk> Message-ID: On May 7, 4:45?am, Tim Golden wrote: > In a spirit of being helpful... :) > > The code below (which I imagine every Windows programmer writes > sometime in their Python life) mimics the os.walk functionality, yielding > the key, subkeys, and values under a particular starting point in the > registry. The "if __name__ == '__main__'" test run at the bottom does > more-or-less what you were asking for originally, I think, converting > some name to some other name wherever it appears. > > > import _winreg > > HIVES = { > ? "HKEY_LOCAL_MACHINE" : _winreg.HKEY_LOCAL_MACHINE, > ? "HKEY_CURRENT_USER" : _winreg.HKEY_CURRENT_USER, > ? "HKEY_CLASSES_ROOT" : _winreg.HKEY_CLASSES_ROOT, > ? "HKEY_USERS" : _winreg.HKEY_USERS, > ? "HKEY_CURRENT_CONFIG" : _winreg.HKEY_CURRENT_CONFIG > > } > > class RegKey: > > ? def __init__ (self, name, key): > ? ? ?self.name = name > ? ? ?self.key = key > > ? def __str__ (self): > ? ? return self.name > > def walk (top): > ? """walk the registry starting from the key represented by > ? top in the form HIVE\\key\\subkey\\..\\subkey and generating > ? key, subkey_names, values at each level. > > ? key is a lightly wrapped registry key, including the name > ? and the HKEY object. > ? subkey_names are simply names of the subkeys of that key > ? values are 3-tuples containing (name, data, data-type). > ? See the documentation for _winreg.EnumValue for more details. > ? """ > ? if "\\" not in top: top += "\\" > ? root, subkey = top.split ("\\", 1) > ? key = _winreg.OpenKey (HIVES[root], subkey, 0, _winreg.KEY_READ | _winreg.KEY_SET_VALUE) > > ? subkeys = [] > ? i = 0 > ? while True: > ? ? try: > ? ? ? subkeys.append (_winreg.EnumKey (key, i)) > ? ? ? i += 1 > ? ? except EnvironmentError: > ? ? ? break > > ? values = [] > ? i = 0 > ? while True: > ? ? try: > ? ? ? values.append (_winreg.EnumValue (key, i)) > ? ? ? i += 1 > ? ? except EnvironmentError: > ? ? ? break > > ? yield RegKey (top, key), subkeys, values > > ? for subkey in subkeys: > ? ? for result in walk (top + "\\" + subkey): > ? ? ? yield result > > if __name__ == '__main__': > ? for key, subkey_names, values in walk ("HKEY_LOCAL_MACHINE\\Software\\Python"): > ? ? print key > ? ? for (name, data, type) in values: > ? ? ? print " ?", name, "=>", data > ? ? ? if type == _winreg.REG_SZ and "TJG" in data: > ? ? ? ? _winreg.SetValueEx (key.key, name, 0, type, data.replace ("TJG", "XYZ")) > > > > TJG This is pretty cool stuff, Tim. Of course, it would also seriously screw up some programs if you decided to replace the wrong phrase. Just a word of warning to the OP: be sure to make a backup of the registry before doing something like this. Trying to fix a messed up registry from the command line is not a fun way to spend the afternoon. Mike From hdante at gmail.com Mon May 26 21:14:23 2008 From: hdante at gmail.com (Henrique Dante de Almeida) Date: Mon, 26 May 2008 18:14:23 -0700 (PDT) Subject: pyserial and file open conflict? References: <21c8f220-aa3c-40b8-b1de-3aa35472e2dc@26g2000hsk.googlegroups.com> <88948db2-aade-4f20-a6ba-bc14c2b4c657@d77g2000hsb.googlegroups.com> <8bmdnUdysIKPTKvVnZ2dnUVZ_vqdnZ2d@posted.visi> Message-ID: On May 26, 6:54?pm, Peter wrote: > On 23 Maj, 16:13, Grant Edwards wrote: > > > > > On 2008-05-23, Peter wrote: > > > > On 15 Maj, 19:37, Grant Edwards wrote: > > >> On 2008-05-15, p.wallst... at gmail.com wrote: > > > >> > I have a small but rather annoying problem withpyserial. I want to > > >> > open a file on disk for reading and then open a com-port, write lines > > >> > from the file to the port and then read something back and compare it > > >> > to the next line in the file. Should be simple. And it is, apart from > > >> > the fact that the file seems to be doubled ...? Or it loops through > > >> > the file twice. > > > >> > If I exclude the "import serial" it works. > > > >> > Any ideas? > > > >> Your problem is in line 117 of your program. > > > > Do you have to much time? > > > "Do you have a sense of irony?" he asked, already knowing the answer. > > > -- > > Grant > > Grant - "Do you have a sence of appropriateness"? he asked, already > knowing the answer. I had no idea this is a comedy club. I might argue > that my reply was also some sort of humor, but you clearly didn't see > it that way. Maybe you should try living according to the rules you > make for others? > > Diez - Did you mean the section which covers Asperger's Syndrome? > > I'm just being a hacker here guys ... according to the guidelines. > > It's amazing how such a simple question gets derailed immediately. > Without any light on the subject ? whatsoever. Try asking about your problem again. Think before writing. Read your text after you write it. Tell what you are trying to do, how you are trying to do and what's the buggy behaviour. Copy the relevant part of your source code here. From maric at aristote.info Fri May 23 01:39:29 2008 From: maric at aristote.info (Maric Michaud) Date: Fri, 23 May 2008 07:39:29 +0200 Subject: Decorator metaclass In-Reply-To: <219a475b-c6e3-4128-98bc-d73fd215ce67@w7g2000hsa.googlegroups.com> References: <219a475b-c6e3-4128-98bc-d73fd215ce67@w7g2000hsa.googlegroups.com> Message-ID: <200805230739.29745.maric@aristote.info> Le Friday 23 May 2008 04:28:22 thomas.karolski at googlemail.com, vous avez ?crit?: > Hi, > I would like to create a Decorator metaclass, which automatically > turns a class which inherits from the "Decorator" type into a > decorator. > A decorator in this case, is simply a class which has all of its > decorator implementation inside a decorator() method. Every other > attribute access is being proxied to decorator().getParent(). > > ... > > ------------------------------------------------------- > Unfortunately this does not work. The newly defined __init__ method > inside __new__, does a call to impl(*args, **dargs). However, since > the HBar.__init__ calls the Decorator.__init__ method, but the > HBar.__init__ method no longer resides inside HBar, but rather inside > HBarImpl (which is no longer a subtype of Decorator), the compiler > complains that Decorator.__init__ is not being called with a Decorator > instance as its first argument (which is true). > I tried changing the definition of impl inside __new__ to have > Decorator as one of its bases, but then for some reason impl(*args, > **dargs) asks for 4 arguments (just like __new__) and I have no clue > as to why that happens. > > Any help on this? > The problem with kind of design is that you must break the rules of class inheritance, and it seems like a strange idea to implement decorators by inheritance. Of course you could do all sort of magic with python, but what is your goal ? In your example, should the implementation types inherit from each other ? In that case, do you want to preserve the same semantic for __init__ as in standard python class (this could be a hard job) ? This quick fix seems to work with your example, but add extra magic to automatically call the super __init__ of the parent implementation, this could be a bad idea, use with caution ! (I still think it's a bad design, using composition and proxy classes is much more simple and clear) class DecoratorType(type): def __new__(cls, name, bases, dct): # create a new class which will store all of the implementation parent_impl_type = bases[0] is object and object \ or bases[0]._impl_type impl = type('%sImpl'%name,(parent_impl_type,),dict(dct)) dectype = type.__new__(cls, name, bases, {'_impl_type' : impl }) # update the old class to implement this implementation def __init__(self, *args, **dargs): print args, dargs new_impl = impl(*args, **dargs) super(dectype._impl_type, new_impl).__init__(*args, **dargs) object.__setattr__(self, '_impl', new_impl) def decorator(self): return object.__getattribute__(self,'_impl') def __getattribute__(self, attr): if attr=="decorator": return object.__getattribute__(self,'decorator') return getattr(object.__getattribute__( self, 'decorator')(), attr) dectype.__init__ = __init__ dectype.decorator = decorator dectype.__getattribute__ = __getattribute__ return dectype class Decorator(object): __metaclass__ = DecoratorType class HBar(Decorator): def __init__(self, number): print 'hb:', number self._number = number def inc(self): self._number += 1 def p(self): print self._number class HBar2(HBar) : def __init__(self, number): print 'hb2:', number self._hb2 = number def inc2(self): self._hb2 += 1 def p2(self): print self._hb2 hbar = HBar(10) for each in dir(hbar.decorator()): print each hbar.decorator().p() hbar.decorator().inc() hbar.decorator().p() hb2 = HBar2(5) hb2.p() hb2.p2() hb2.inc() hb2.p() hb2.p2() hb2.inc2() hb2.p() hb2.p2() -- _____________ Maric Michaud _____________ From jstucklex at attglobal.net Sun May 25 20:12:32 2008 From: jstucklex at attglobal.net (Jerry Stuckle) Date: Sun, 25 May 2008 20:12:32 -0400 Subject: php vs python In-Reply-To: References: <5l%Yj.77$mz3.53@fe101.usenetserver.com> <37b112d8-a3ba-446d-9d2f-d907d93c637b@w8g2000prd.googlegroups.com> <-t-dnWQ4bZN2MaTVnZ2dnUVZ_qGdnZ2d@comcast.com> <68cb8bb1-4cc5-4a28-8915-46e7d4e316d9@d1g2000hsg.googlegroups.com> Message-ID: Ivan Illarionov wrote: > On Sun, 25 May 2008 17:09:43 -0400, Jerry Stuckle wrote: >> Not at all. I do it every day. >> >> And BTW - yes, I write Python, also. But I find I can write better, >> faster code in PHP. > > I find I can write better code in Python. Maybe it's just a matter of > personal preference? > >> Do you write PHP? > I did. And I hated it very much. I hated it so much that even I had few > Python scripts that generated PHP for me when it was possible. > So you really don't write PHP. Enough said. -- ================== Remove the "x" from my email address Jerry Stuckle JDS Computer Training Corp. jstucklex at attglobal.net ================== From steven.p.clark at gmail.com Mon May 19 10:38:18 2008 From: steven.p.clark at gmail.com (Steven Clark) Date: Mon, 19 May 2008 10:38:18 -0400 Subject: scope of optional arguments In-Reply-To: References: Message-ID: <663744510805190738q9431258kb30c8d8f3656ee68@mail.gmail.com> http://www.ferg.org/projects/python_gotchas.html#contents_item_6 On Mon, May 19, 2008 at 10:30 AM, cseja wrote: > If I call > > print walk([1,2,3], []) > print walk([5,6,7]) > > I get > > [1, 2, 3] > [4, 5, 6] > > but when I call > > print walk([1,2,3]) > print walk([5,6,7]) > > I get > > [1, 2, 3] > [1, 2, 3, 4, 5, 6] > > at stdout, where > > def walk(seq, result = []): > for item in seq: > result.append(item) > return result > > Does that mean that the scope of optional arguments is global if they aren't > used and local if they are (or am I missing something here)? > > Regards, > CS > > > -- > http://mail.python.org/mailman/listinfo/python-list > From dgetsman at amirehab.net Wed May 21 11:59:57 2008 From: dgetsman at amirehab.net (Damon Getsman) Date: Wed, 21 May 2008 08:59:57 -0700 (PDT) Subject: issues simply parsing a whitespace-delimited textfile in python script Message-ID: Okay so I'm writing a script in python right now as a dirty fix for a problem we're having at work.. Unfortunately this is the first really non-trivial script that I've had to work with in python and the book that I have on it really kind of sucks. I'm having an issue parsing lines of 'last' output that I have stored in a /tmp file. The first time it does a .readline() I get the full line of output, which I'm then able to split() and work with the individual fields of without any problem. Unfortunately, the second time that I do a .readline() on the file, I am only receiving the first character of the first field. Looking through the /tmp file shows that it's not corrupted from the format that it should be in at all... Here's the relevant script: ---- #parse Lastdump = open('/tmp/esd_tmp', 'r') #find out what the last day entry is in the wtmp cur_rec = Lastdump.readline() work = cur_rec.split() if debug == 1: print work print " is our split record line from /tmp/esd_tmp\n" startday = work[3] if debug == 1: print startday + " is the starting day\n" print days print " is our dictionary of days\n" print days[startday] + " is our ending day\n" for cur_rec in Lastdump.readline(): work = cur_rec.split() if debug == 1: print "Starting table building pass . . .\n" print work print " is the contents of our split record line now\n" print cur_rec + " is the contents of cur_rec\n" #only go back 2 days while work[0] != days[startday]: tmp = work[1] if table.has_key(work[0]): continue elif tmp[0] != ':': #don't keep it if it isn't a SunRay terminal identifier continue else: #now we keep it table[work[0]] = tmp ---- the first and second sets of debugging output show everything as they should be... the third shows that the next working line (in cur_rec), and thus 'work', as well, only hold the first character of the line. Here's the output: ---- Debugging run Building table . . . ['dgetsman', 'pts/3', ':0.0', 'Wed', 'May', '21', '10:21', 'still', 'logged', 'in'] is our split record line from /tmp/esd_tmp Wed is the starting day {'Wed': 'Mon', 'Sun': 'Fri', 'Fri': 'Wed', 'Thurs': 'Tues', 'Tues': 'Sun', 'Mon': 'Sat', 'Sat': 'Thurs'} is our dictionary of days Mon is our ending day Starting table building pass . . . ['d'] is the contents of our split record line now d is the contents of cur_rec ---- And thus everything fails when I try to work with the different fields in subsequent script afterwards. Does anybody have an idea as to why this would be happening? Oh, and if relevant, here's the datafile's first few lines: ---- dgetsman pts/3 :0.0 Wed May 21 10:21 still logged in dgetsman pts/2 :0.0 Wed May 21 09:04 still logged in dgetsman pts/1 :0.0 Wed May 21 08:56 - 10:21 (01:24) dgetsman pts/0 :0.0 Wed May 21 08:56 still logged in I would really appreciate any pointers or suggestions you can give. *Damon Getsman Linux/Solaris System Administrator From johnjsal at gmailNOSPAM.com Thu May 22 23:37:45 2008 From: johnjsal at gmailNOSPAM.com (John Salerno) Date: Thu, 22 May 2008 23:37:45 -0400 Subject: Relationship between GUI and logic? Message-ID: <48363c34$0$15204$607ed4bc@cv.net> I know that it is good programming practice to keep GUI and logic code physically separate, by using XRC for example, but I'm wondering if it's also good practice (and even possible) to keep them separate from an implementation standpoint as well. Basically what I mean is, should it be possible to write, for example, the logic for a strategy game without even knowing what the graphics will look like or how they will work? To be more specific, let's say I want to create a simple, 2D strategy game. It will have a board layout like chess or checkers and the player will move around the board. Let's say this is all I know, and perhaps I don't even know *this* for sure either. Is it possible to write the logic for such a game at this point? Let's say I want to write a "move" function (or perhaps it would be a method of a "Character" class) for moving the player around. Could you really write this function without 1) knowing what the interface will look like, and 2) integrating GUI code with the logic? Another example could be printing messages to the player. If I need to say "You killed the monster!", is there a general way to write this, or do I need to specifically refer to GUI widgets and methods, etc. in order for it to be displayed properly? Basically, the question is this: can you write the logic behind a program (whether it be a game, an email client, a text editor, etc.) without having any idea of how you will implement the GUI? Thanks! From tjreedy at udel.edu Sat May 10 18:46:13 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 10 May 2008 18:46:13 -0400 Subject: how to reference my own module ? References: <4825F6BB.9090707@gmail.com> Message-ID: "Stef Mientki" wrote in message news:4825F6BB.9090707 at gmail.com... | hello, | | I've a library that I import as | | import ppygui.api as gui | | the reason for this construct is that I've to use different libraries | for different platforms. | | Now I like to write some examples in the library (activated by if | __name__ == '__main__' :) | and I would that these examples can be used in the user program just by | copy / paste. | | For calling a function / class in the user program I've to write: | | sizer = gui.VBox () | | So also write exactly the same sentence in the library examples, | but "gui" is not recognized | | Any ideas how I can realize the above ? Put the import statement in the example so 'gui' *is* recognized ;-) If I understand what you meant ... xploro/test/begin.py ----------------------------- def start(): print('hello') if __name__ == '__main__': import xploro.test.begin as etb etb.start() ---------------------------- prints 'hello'| Import is a name-binding statement that also creates a module when it does not exist already. Modules can be bound to multiple names just like any other object. Terry Jan Reedy From mcknight0219 at gmail.com Fri May 23 11:14:00 2008 From: mcknight0219 at gmail.com (Jimmy) Date: Fri, 23 May 2008 08:14:00 -0700 (PDT) Subject: can python do some kernel stuff? References: <983ec0f6-1316-40cd-a4d4-ce9b5e272a60@h1g2000prh.googlegroups.com> <48366cfa$0$15168$607ed4bc@cv.net> <28c432f0-657c-4272-8cd4-a9081b013279@w5g2000prd.googlegroups.com> <69nigsF3499pqU2@mid.uni-berlin.de> Message-ID: <8d1f0f0f-8dc4-43df-bbc5-78c05b81d6ca@u12g2000prd.googlegroups.com> On May 23, 5:53 pm, "Diez B. Roggisch" wrote: > Jimmy schrieb: > > > On May 23, 3:05 pm, Andrew Lee wrote: > >> Jimmy wrote: > >>> Hi to all > >>> python now has grown to a versatile language that can > >>> accomplish tasks for many different purposes. However, > >>> AFAIK, little is known about its ability of kernel coding. > >>> So I am wondering if python can do some kernel coding that > >>> used to be the private garden of C/C++. For example, can python > >>> intercept the input of keyboard on a system level? someone told me > >>> it's a kernel thing, isn't it? > >>http://wiki.python.org/moin/elmer > > > well, straightly speaking, how can I know a key is pressed on a system- > > level if > > using python? > > What has that todo with kernel programming? You can use e.g. pygame to > get keystrokes. Or under linux, read (if you are root) the keyboard > input file - I've done that to support several keyboards attached to a > machine. > > And the original question: no, python can't be used as kernel > programming language. Amongst other reasons, performance & the GIL > prevent that. > > Diez sorry, my aim is not limited to one particular program. Yes, many library can permit you to respond to keyboard event, however, what I want is a universal function. as long as a key is pressed, no matter where, my program can repond. I am quite strange with this topic. But according to my understanding, any event, keyboard event for example, once triggered, will be dilivered by keyboard driver to X system, and then any running program can either choose to respond or ignore. So my question can be translated to: how to make my program respond ? From szrRE at szromanMO.comVE Sat May 31 12:27:11 2008 From: szrRE at szromanMO.comVE (szr) Date: Sat, 31 May 2008 09:27:11 -0700 Subject: The Importance of Terminology's Quality References: <4840ab73$0$90274$14726298@news.sunsite.dk> Message-ID: Peter Duniho wrote: > On Fri, 30 May 2008 22:40:03 -0700, szr wrote: > >> Arne Vajh?j wrote: >>> Stephan Bour wrote: >>>> Lew wrote: >>>> } John Thingstad wrote: >>>> } > Perl is solidly based in the UNIX world on awk, sed, } > bash >>>> and C. I don't like the style, but many do. >>>> } >>>> } Please exclude the Java newsgroups from this discussion. >>>> >>>> Did it ever occur to you that you don't speak for entire news >>>> groups? >>> >>> Did it occur to you that there are nothing about Java in the above ? >> >> Looking at the original post, it doesn't appear to be about any >> specific language. > > Indeed. That suggests it's probably off-topic in most, if not all, > of the newsgroups to which it was posted, inasmuch as they exist for > topics specific to a given programming language. Perhaps - comp.programming might of been a better place, but not all people who follow groups for specific languages follow a general group like that - but let me ask you something. What is it you really have against discussing topics with people of neighboring groups? Keep in mind you don't have to read anything you do not want to read. [1] > Regardless, unless you are actually reading this thread from the > c.l.j.p newsgroup, I'm not sure I see the point in questioning > someone who _is_ about whether the thread belongs there or not. I would rather have the OP comment about that, as he started the thread. But what gets me is why you are against that specific group being included but not others? What is so special about the Java group and why are you so sure people there don't want to read this thread? [1] What right do you or I or anyone have to make decisions for everyone in a news group? Isn't this why most news readers allow one to block a thread? > And if it's a vote you want, mark me down as the third person reading > c.l.j.p that doesn't feel this thread belongs. I don't know whether > Lew speaks for the entire newsgroup, but based on comments so far, > it's pretty clear that there unanimous agreement among those who have > expressed an opinion. Ok, so, perhaps 3 people out of what might be several hundred, if not thousand (there is no way to really know, but there are certainly a lot of people who read that group, and as with any group, there are far more readers than there are people posting, so, again, just because you or two other people or so don't want to read a topic or dislike it, you feel you can decide for EVERYONE they mustn't read it? Again, this is why readers allow you to ignore threads. Please don't force your views on others; let them decide for themselves. [1] [1] I do not mean this topic specifically, but in general, if one dislikes a thread, they are free to ignore it. I find it rather inconsiderate to attempt to force a decision for everyone, when one has the ability to simply ignore the thread entirely. -- szr From duncan.booth at invalid.invalid Tue May 20 10:16:56 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 20 May 2008 14:16:56 GMT Subject: Using Python for programming algorithms References: <98fa5fa3-45ae-4df1-9fd3-1a227641244f@p25g2000hsf.googlegroups.com> <48314dd0$0$32138$426a34cc@news.free.fr> Message-ID: Roel Schroeven wrote: > C OTOH was designed to be compiled to assembly code (or directly to > machine code) and as a result there are no (or virtually) no > implementations that interpret C or compile it to bytecode. Have you considered Microsoft's C/C++ compiler targetted at .Net. That compiles to a bytecode known as MSIL which is then interpreted and/or JIT compiled to machine code. > I love Python, but IMHO it's a bit silly to maintain that the fact that > Python compiles to byte code instead of assembly code/machine code is > purely a matter of implementation; on the contrary, I believe it's a > result of its design. I also think that there's a large difference > between byte code and machine code (in Python's case; I haven't looked > at other languages), and that it's a bit silly to try to trivialize that > difference. And then there's IronPython which is targetted at .Net. That compiles to a bytecode known as MSIL which is then interpreted and/or JIT compiled to machine code. -- Duncan Booth http://kupuguy.blogspot.com From gagsl-py2 at yahoo.com.ar Wed May 7 18:50:44 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 07 May 2008 19:50:44 -0300 Subject: explain this function to me, lambda confusion References: Message-ID: En Wed, 07 May 2008 18:38:15 -0300, globalrev escribi?: > i have a rough understanding of lambda but so far only have found use > for it once(in tkinter when passing lambda as an argument i could > circumvent some tricky stuff). > what is the point of the following function? > > def addn(n): > return lambda x,inc=n: x+inc lambda is just a shortcut for defining a function without a name. The above code is the same as: def addn(n): def inner(x, inc=n): return x+inc return inner It should be clear now that addn returns a function. addn is a "function factory": builds functions by request. You ask it "give me a function that adds 5" and addn returns that function. > if i do addn(5) it returns > >>>> addn(5) > at 0x01D81830> If you try the other version, you would get: It's the same thing, except that lambda has no name. > ok? so what do i write to make it actually do something. adder5 = addn(5) adder5(3) -> 8 > and is the > inc=n necessary i cant do x+n? Yes, you can, but there is a subtle difference that's hard to explain, and in this case it's absolutely irrelevant. Using inc=n "does the right thing" as it's a bit more efficient too. -- Gabriel Genellina From deets at nospam.web.de Tue May 6 06:27:08 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 06 May 2008 12:27:08 +0200 Subject: Bad form to access a *private variable* like _foo? References: <48200a7f$0$23642$426a74cc@news.free.fr> Message-ID: <68aq4nF2r9b93U4@mid.uni-berlin.de> > The way you wrote it here, yes. If there's no official way to do the > same operation and you have a real use case for it - in which case you > may want to add a commit() method to SQLObject's model base class and > submit the patch to SQLObject's maintainer. But I strongly suspect > there's a better way to handle this case in SQLObject's API. There are other ways. For example, sqlobject.sqlhub.threadingLocal.connection if your system is using multiple threads correctly. Generally speaking, sqlhub could/should be used. Diez From zerty.david at gmail.com Thu May 15 16:31:00 2008 From: zerty.david at gmail.com (David Anderson) Date: Thu, 15 May 2008 17:31:00 -0300 Subject: How to make an Activation Issue? Message-ID: <5dc598e30805151331h7d40ea7dt8c2cc4ef38385d2c@mail.gmail.com> Hi, How can I make something like this... The final user installs the app The app Runs and the User has to authenticate the app, which will be by acessing a remote file on a Server, If he user dont authenticate the program will run only for 3 days, after that it will be blocked until the user authenticates it... How can I do this? Cya =) -------------- next part -------------- An HTML attachment was scrubbed... URL: From salmoni at gmail.com Sat May 31 10:27:48 2008 From: salmoni at gmail.com (Alan J. Salmoni) Date: Sat, 31 May 2008 07:27:48 -0700 (PDT) Subject: How to get all the variables in a python shell References: Message-ID: <238d3920-1b9d-4caa-b667-139f290e9d67@i18g2000prn.googlegroups.com> I'm not certain if this is what you want but try this for the first window: import __main__ localvars = __main__.__dict__ dir(localvars) # lists names of all objects available to the interpreter. And then you can pass localvars anywhere in the program - so after a command is entered in one window, you can import the all locals into the other by putting this function in the second window: def SetWindow2Locals(localvars): __main__.__dict__ = localvars and do the reverse by sending the updated localvars from window 2 to window 1. Setting up an object between the 2 windows should be enough: # window 1, must be created first import __main__ localvars = __main__.__dict__ # create second window (say, win2) win2.SetLocals(localvars) in win2 after creation, there is a method/function: SetLocals(localvars): __main__.__dict__ = localvars If you want to store the object in something like a DB, you can store this localvars dictionary rather than the actual objects. This should be efficient because it stores the object name and ID only but not the objects themselves. However, if the objects are deleted, after saving and before re-loading, you may get some odd results but I'm not sure. I would be very careful of using this in the wild. You can also add objects singly to the dictionary by hand with a function: def importobject(obj): __main__.__dict__[obj.__name__] = obj Which should make them available in the other window easily. If a new object is added to the __main__.__dict__, just grab it and send it to this function. Make sure that you send the object and not just its name because the name is only a string. Sorry if this is not what you were after. Alan On May 29, 2:47 pm, lixinyi... at gmail.com wrote: > Hi! > > I'm currently working on a scientific computation software built in > python. > What I want to implement is a Matlab style command window <-> > workspace interaction. > > For example, you type 'a=1' in the command window, and you see a list > item named 'a' in the workspace. > You double click the icon of the item, and you see its value. You can > modify the value of the list item, > 1 -> 100 etc, after which if you go back to the command window and > type 'a' and press enter, you see that > varable a's value has been changed to 100. > > So my question is : if you have two DOS command windows running under > WINDOWS OS, how can you make them share the same internal variable > buffer? Or is there any easier way to implement such kind of > interaction? > > Maybe I could just build a small database to store all the values and > access them from both programs, but chances are sometimes I have to > deal with big arrays, and they will eat extra memory if I keep them in > a database. Is there anyway to access a shell's local memory buffer? > I tried to use shell.interp.locals() in wxPython, but there's too many > variables in the list which I don't actually need. > > Come on guys, give me some ideas. Thanks in advance! From Magnus.Moraberg at gmail.com Tue May 27 05:05:23 2008 From: Magnus.Moraberg at gmail.com (Magnus.Moraberg at gmail.com) Date: Tue, 27 May 2008 02:05:23 -0700 (PDT) Subject: HTTPError sometimes when using urllib2.urlopen References: <5978cac5-27e1-40cd-9abe-9e7536395468@d45g2000hsc.googlegroups.com> Message-ID: <7311fb13-b4bb-4605-ac5e-c434e54cd0f1@8g2000hse.googlegroups.com> On 27 Maj, 11:03, Magnus.Morab... at gmail.com wrote: > Hi, > > I have the following code - > > import urllib2 > from BeautifulSoup import BeautifulSoup > > proxy_support = urllib2.ProxyHandler({"http":"http:// > 999.999.999.999:8080"}) > opener = urllib2.build_opener(proxy_support) > urllib2.install_opener(opener) > > page = urllib2.urlopen('http://www.cornish-language.org/CORNISH/ > membership.asp') > soup = BeautifulSoup(page) > > pageText = soup.findAll(text=True) > print pageText > > Sometimes when I run this code I get the exception - > > HTTPError: HTTP Error 407 Proxy authentication required > > I seem to get this error repeatidly for a while, then I go a surf for > a moment and when I run the code again the exception might have gone > away. No idea why... > > I have no problems with firefox which uses the same proxy. The proxy > requires no authentication... > > What might the issue be? > > Thanks, > > Barry. I'm running with Python 2.5 with PythonWin Heres the full exception - Traceback (most recent call last): File "C:\Python25\Lib\site-packages\pythonwin\pywin\framework \scriptutils.py", line 409, in ImportFile reload(sys.modules[modName]) File "C:\Documents and Settings\konbgn\Desktop\parse.py", line 8, in page = urllib2.urlopen('http://www.cornish-language.org/CORNISH/ membership.asp') File "C:\Python25\lib\urllib2.py", line 121, in urlopen return _opener.open(url, data) File "C:\Python25\lib\urllib2.py", line 380, in open response = meth(req, response) File "C:\Python25\lib\urllib2.py", line 491, in http_response 'http', request, response, code, msg, hdrs) File "C:\Python25\lib\urllib2.py", line 418, in error return self._call_chain(*args) File "C:\Python25\lib\urllib2.py", line 353, in _call_chain result = func(*args) File "C:\Python25\lib\urllib2.py", line 499, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) HTTPError: HTTP Error 407: Proxy Authentication Required From wolfgang.grafen at ericsson.com Tue May 20 07:57:55 2008 From: wolfgang.grafen at ericsson.com (Wolfgang Grafen) Date: Tue, 20 May 2008 13:57:55 +0200 Subject: do you fail at FizzBuzz? simple prog test In-Reply-To: <39709320-66e1-40e9-a351-c769c9a94585@x41g2000hsb.googlegroups.com> References: <39709320-66e1-40e9-a351-c769c9a94585@x41g2000hsb.googlegroups.com> Message-ID: globalrev schrieb: > http://reddit.com/r/programming/info/18td4/comments > > claims people take a lot of time to write a simple program like this: > > > "Write a program that prints the numbers from 1 to 100. But for > multiples of three print "Fizz" instead of the number and for the > multiples of five print "Buzz". For numbers which are multiples of > both three and five print "FizzBuzz". > > for i in range(1,101): > if i%3 == 0 and i%5 != 0: > print "Fizz" > elif i%5 == 0 and i%3 != 0: > print "Buzz" > elif i%5 == 0 and i%3 == 0: > print "FizzBuzz" > else: > print i > > > is there a better way than my solution? is mine ok? Your example is comprehensive compared to many other suggestions which is an advantage IMO. I minimised it further for i in range(start, stop, step): if not i%15: print "FizzBuzz" elif not i%3: print "Fizz" elif not i%5: print "Buzz" else: print i Best regards Wolfgang From deets at nospam.web.de Tue May 27 08:07:04 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 27 May 2008 14:07:04 +0200 Subject: integration with browser References: <69vmlgF35akucU1@mid.uni-berlin.de> <6a0722F33j3q5U1@mid.uni-berlin.de> Message-ID: <6a2bs6F35a5cmU1@mid.uni-berlin.de> > Web developers usually check only 3 browser > IE > FF > Opera > > I know that using an external engine limits the portability of the > solutions, but i need something that works exaclty as the browser. You know that Webkit is the engine behind Safari? And one of the more compliant implementations out there - millions of mac-users only use Safari. Diez From thomas.troeger.ext at siemens.com Tue May 20 06:20:59 2008 From: thomas.troeger.ext at siemens.com (Thomas Troeger) Date: Tue, 20 May 2008 12:20:59 +0200 Subject: Newbie In Python References: <316da0ad-403d-492c-81b1-4aa069da0caa@k10g2000prm.googlegroups.com> Message-ID: andrew.smith.cpp at gmail.com wrote: > I have Heard About "Python" its a OOD Language. i have to Learn it > where from i should start it. > i have python compiler at linux Platform. > anyone can suggest me about it. > > Thanks In advance. How about http://docs.python.org/tut/tut.html? From jstucklex at attglobal.net Sun May 25 20:15:40 2008 From: jstucklex at attglobal.net (Jerry Stuckle) Date: Sun, 25 May 2008 20:15:40 -0400 Subject: php vs python In-Reply-To: References: <5l%Yj.77$mz3.53@fe101.usenetserver.com> <37b112d8-a3ba-446d-9d2f-d907d93c637b@w8g2000prd.googlegroups.com> <-t-dnWQ4bZN2MaTVnZ2dnUVZ_qGdnZ2d@comcast.com> <68cb8bb1-4cc5-4a28-8915-46e7d4e316d9@d1g2000hsg.googlegroups.com> Message-ID: Ivan Illarionov wrote: > On Sun, 25 May 2008 16:23:12 -0700, NC wrote: > >>> I didn't say that it's not possible to write good code in PHP, >> Indeed you didn't. You did, however, say that development in Python/ >> Django is inherently faster than development in PHP (your exact words >> were, "2 man/year in PHP == 2 man/week in Python/Django", implying a >> 50-fold difference). This claim has just been obliterated using the >> example you (not I) provided; my estimate of two man-years for >> developing WordPress turns out to be fairly close to what has actually >> gone into the development of Byteflow. In other words, so far we have >> discovered no evidence of Python's (or PHP's, to be fair) superiority in >> terms of developer's productivity. > > In this case (excellent blogging tool), yes, I agree. > >>> IMHO Python language is better designed >> That is indeed a matter of opinion. You like (among other things) >> immutable strings, the off-side rule, the idea that everything is an >> object, and the fine distinction between mutable lists and immutable >> tuples, and I have no problem with you liking these features, as long as >> you agree that other people may have reasons to like the alternatives >> better. > > I agree. We like different things and it's good. > >>> Yes, it's possible to write something clean in PHP but it would require >>> a lot more work. >> In my opinion, it wouldn't, and in my experience, it doesn't. All you >> need is to actually put a designer in charge of design. Additionally, >> there are situations (rapid prototyping, for example) when >> maintainability (the requirement behind the "clean code") is simply not >> a concern. > > It's hard to me to write good PHP. I feel happy programming in Python and > I felt very unhappy when I had to program in PHP. I'm glad that you have > a different experience. > > Ivan > It's very easy for me to write good code in PHP. I can say the same for a number of other good programmers I know. As I've said before - good programmers can write good code in any language. -- ================== Remove the "x" from my email address Jerry Stuckle JDS Computer Training Corp. jstucklex at attglobal.net ================== From caca at mailinator.com Fri May 30 08:54:39 2008 From: caca at mailinator.com (caca at mailinator.com) Date: Fri, 30 May 2008 05:54:39 -0700 (PDT) Subject: How to get all the variables in a python shell References: Message-ID: Your project interests me. Actually I was thinking about doing the same. I hadn't worked on it at all, but I though about it and had the idea about reading the session namespace directly, which I though would be stored in the __dict__ attribute of something. After reading your post, I have been trying a little bit, and I have found a way to do it with ipython. If you open an ipython console, press _ then hit TAB, you'll see it stores some useful information, including all input, all output, and after some searching, a dictionary matching all variables to its values. __IPYTHON__.user_ns There is a little extra stuff in there that you don't want, but that can be easily filtered (the extra stuff is either 'In', 'Out', 'help' or starts with '_'). I've tried it, and you can change the value in that dict to alter the value of the real variable. Say you have a variable 'test': test=5 __IPYTHON__.user_ns['test']=4 print test #prints 5 If I get it right, python is a dynamic language, and you won't break things by messing around with its inner stuff like this, but you better check it. Is this what you had in mind? From stefan_ml at behnel.de Fri May 9 06:37:13 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 09 May 2008 12:37:13 +0200 Subject: source beautifier In-Reply-To: <8nEUj.36510$o06.32727@tornado.fastwebnet.it> References: <8nEUj.36510$o06.32727@tornado.fastwebnet.it> Message-ID: <48242959.3030405@behnel.de> Marco Mariani wrote: > Is there a program (free, payware, whatever) like polystyle for > linux/python? > > http://www.polystyle.com/features/python-beautifier.jsp > > I've never used it, but the example is quite clear. I tend to believe that running these tools on some average Python code would not even change whitespace. ;) > I just need it for python -- but it should not force me to use PEP8. IMHO, a tool that automatically corrects code to comply with PEP-8 would actually be more helpful, but I guess that's pretty far reached. Stefan From spectrumdt at gmail.com Tue May 6 06:31:28 2008 From: spectrumdt at gmail.com (spectrumdt at gmail.com) Date: Tue, 6 May 2008 03:31:28 -0700 (PDT) Subject: Cannot install Pypvm (Python Parallel Virtual Machine) Message-ID: Hello. I am trying to install Pypvm (http://pypvm.sourceforge.net/), the Python interface to PVM ("Parallel Virtual Machine"). Unfortunately, installation fails. I am hoping someone can help me fix it. I am running Fedora Core 8 Linux. The official Pypvm documentation is very helpful (or something), providing the following: To build Pypvm, cross your fingers and try: make -f Makefile.pre.in boot make Or alternatively, try python setup.py build python setup.py install For me, the "make -f Makefile.pre.in boot" seems to run fine, but the "make" fails, giving (among other things) the following: [ore at localhost pypvm-0.94]$ make gcc -pthread -fPIC -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m32 - march=i386 -mtune=generic -fasynchronous-unwind-tables -D_GNU_SOURCE -fPIC -I/usr/include/python2.5 -I/usr/lib/python2.5/config -c ././pypvm_coremodule.c -o ./pypvm_coremodule.o ././pypvm_coremodule.c:2:18: error: pvm3.h: No such file or directory ././pypvm_coremodule.c: In function ?was_error?: ././pypvm_coremodule.c:81: error: ?PvmOk? undeclared (first use in this function) ././pypvm_coremodule.c:81: error: (Each undeclared identifier is reported only once ././pypvm_coremodule.c:81: error: for each function it appears in.) ././pypvm_coremodule.c:85: error: ?PvmBadParam? undeclared (first use in this function) ././pypvm_coremodule.c:85: error: ?PvmMismatch? undeclared (first use in this function) [...] ././pypvm_coremodule.c:1889: error: ?PvmDupEntry? undeclared (first use in this function) ././pypvm_coremodule.c:1767: warning: unused variable ?optModule? ././pypvm_coremodule.c:1766: warning: unused variable ?resultModule? ././pypvm_coremodule.c:1765: warning: unused variable ?notifyModule? ././pypvm_coremodule.c:1764: warning: unused variable ?spawnModule? ././pypvm_coremodule.c:1763: warning: unused variable ?dataModule? ././pypvm_coremodule.c:1762: warning: unused variable ?exceptionModule? make: *** [pypvm_coremodule.o] Error 1 [ore at localhost pypvm-0.94]$ In in alternate version, "python setup.py build" similarly fails: [ore at localhost pypvm-0.94]$ python setup.py build running build running build_py running build_ext building 'pypvm_core' extension gcc -pthread -fno-strict-aliasing -DNDEBUG -O2 -g -pipe -Wall -Wp,- D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer- size=4 -m32 -march=i386 -mtune=generic -fasynchronous-unwind-tables - D_GNU_SOURCE -fPIC -fPIC -I/usr/include -I/usr/include/python2.5 -c pypvm_coremodule.c -o build/temp.linux-i686-2.5/pypvm_coremodule.o pypvm_coremodule.c:2:18: error: pvm3.h: No such file or directory pypvm_coremodule.c: In function ?was_error?: pypvm_coremodule.c:81: error: ?PvmOk? undeclared (first use in this function) pypvm_coremodule.c:81: error: (Each undeclared identifier is reported only once pypvm_coremodule.c:81: error: for each function it appears in.) pypvm_coremodule.c:85: error: ?PvmBadParam? undeclared (first use in this function) [...] pypvm_coremodule.c:1889: error: ?PvmDupEntry? undeclared (first use in this function) pypvm_coremodule.c:1767: warning: unused variable ?optModule? pypvm_coremodule.c:1766: warning: unused variable ?resultModule? pypvm_coremodule.c:1765: warning: unused variable ?notifyModule? pypvm_coremodule.c:1764: warning: unused variable ?spawnModule? pypvm_coremodule.c:1763: warning: unused variable ?dataModule? pypvm_coremodule.c:1762: warning: unused variable ?exceptionModule? error: command 'gcc' failed with exit status 1 [ore at localhost pypvm-0.94]$ Can anyone help me get it to work? Thanks in advance. - Claus Appel From castironpi at gmail.com Thu May 15 22:39:55 2008 From: castironpi at gmail.com (castironpi) Date: Thu, 15 May 2008 19:39:55 -0700 (PDT) Subject: send yield References: <6a19b5bf-ed71-499c-a348-6e26e2f523eb@m45g2000hsb.googlegroups.com> <200805152005.52062.kyrie@uh.cu> Message-ID: <715d305d-c99f-431a-945b-d79d49bf382a@k37g2000hsf.googlegroups.com> On May 15, 7:40?pm, castironpi wrote: > On May 15, 7:07?pm, "Dan Upton" wrote: > > > On Thu, May 15, 2008 at 8:05 PM, Luis Zarrabeitia wrote: > > > On Thursday 15 May 2008 09:32:37 am castironpi wrote: > > >> Why can't I write this? > > >> -- > > >>http://mail.python.org/mailman/listinfo/python-list > > > > yield recieved. > > > > Thanks. > > > Should that be > > > ack yield > > > ? > > I'd be putting parachutes on people's screens, but on a newsgroup. ?I > might have time-parachutes too: something that lands softer. Does anyone want furniture put in a room? From max at alcyone.com Thu May 8 21:15:54 2008 From: max at alcyone.com (Erik Max Francis) Date: Thu, 08 May 2008 18:15:54 -0700 Subject: Mathematics in Python are not correct In-Reply-To: <52c855d8-5609-43e0-b98f-9fa87b2808c2@m3g2000hsc.googlegroups.com> References: <52c855d8-5609-43e0-b98f-9fa87b2808c2@m3g2000hsc.googlegroups.com> Message-ID: wxPythoner at gmail.com wrote: > Have a look at this: > >>>> -123**0 > -1 > > > The result is not correct, because every number (positive or negative) > raised to the power of 0 is ALWAYS 1 (a positive number 1 that is). > > The problem is that Python parses -123**0 as -(123**0), not as > (-123)**0. > > I suggest making the Python parser omit the negative sign if a > negative number is raised to the power of 0. That way the result will > always be a positive 1, which is the mathematically correct result. > > This is a rare case when the parser is fooled, but it must be fixed in > order to produce the correct mathematical result. Others have pointed out why this is not a parse error, as it's parsed as -(123**0), not (-123)**0, which is apparently what you meant. Note, however, that even normal mathematical conventions follow this same rule. If you were to write 2 -x as part of a mathematical equation, this means (translated to Python) -(x**2), not (-x)**2. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis I sleep and dream that life is / All beauty -- Lamya From ganeshborse at gmail.com Fri May 9 09:41:00 2008 From: ganeshborse at gmail.com (grbgooglefan) Date: Fri, 9 May 2008 06:41:00 -0700 (PDT) Subject: How to modify meaning of builtin function "not" to "!"? Message-ID: I am creating functions, the return result of which I am using to make decisions in combined expressions. In some expressions, I would like to inverse the return result of function. E.g. function contains(source,search) will return true if "search" string is found in source string. I want to make reverse of this by putting it as: if ( ! contains(s1,s2) ): return 1 I found that "!" is not accepted by Python & compile fails with "invalid syntax". Corresponding to this Boolean Operator we've "not" in Python. How can I make "not" as "!"? From grante at visi.com Fri May 23 10:13:38 2008 From: grante at visi.com (Grant Edwards) Date: Fri, 23 May 2008 09:13:38 -0500 Subject: pyserial and file open conflict? References: <21c8f220-aa3c-40b8-b1de-3aa35472e2dc@26g2000hsk.googlegroups.com> <88948db2-aade-4f20-a6ba-bc14c2b4c657@d77g2000hsb.googlegroups.com> Message-ID: <8bmdnUdysIKPTKvVnZ2dnUVZ_vqdnZ2d@posted.visi> On 2008-05-23, Peter wrote: > On 15 Maj, 19:37, Grant Edwards wrote: >> On 2008-05-15, p.wallst... at gmail.com wrote: >> >> > I have a small but rather annoying problem withpyserial. I want to >> > open a file on disk for reading and then open a com-port, write lines >> > from the file to the port and then read something back and compare it >> > to the next line in the file. Should be simple. And it is, apart from >> > the fact that the file seems to be doubled ...? Or it loops through >> > the file twice. >> >> > If I exclude the "import serial" it works. >> >> > Any ideas? >> >> Your problem is in line 117 of your program. > > Do you have to much time? "Do you have a sense of irony?" he asked, already knowing the answer. -- Grant From ian.g.kelly at gmail.com Tue May 6 12:01:04 2008 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 6 May 2008 10:01:04 -0600 Subject: Reversing a dict? In-Reply-To: References: <6e3fdb8c-687f-42b6-b544-19c88950cc00@q1g2000prf.googlegroups.com> Message-ID: <3fc761710805060901y436174ecw536c70f8a00ddaa0@mail.gmail.com> On Tue, May 6, 2008 at 9:26 AM, Jeremy Sanders wrote: > krumblebunk at gmail.com wrote: > > > Hi - further to my earlier query regarding partial matches (which with > > all your replies enabled me to advance my understanding, thanks), I > > now need to reverse a dict. > > There is no guaranteed order to the items stored in a dictionary. They can > and will move around as the dict is modified. Have a look at > diveintopython: > > http://www.diveintopython.org/getting_to_know_python/dictionaries.html > > You'll have to store your keys in a list or tuple to keep them ordered. You might also take a look at the odict[1] or ordereddict[2] modules. [1] http://www.voidspace.org.uk/python/odict.html [2] http://www.xs4all.nl/~anthon/Python/ordereddict/ From kamhung.soh at gmail.com Wed May 28 02:22:00 2008 From: kamhung.soh at gmail.com (Kam-Hung Soh) Date: Wed, 28 May 2008 16:22:00 +1000 Subject: convert string number to real number - ValueError: invalid literal for int() with base 10: '"2"' In-Reply-To: <491b0d8f0805270900r4950360bjee559f9c86fb43b9@mail.gmail.com> References: <3ca86e1d-a32f-48f2-bc9a-6cb792c0c631@z17g2000hsg.googlegroups.com> <20080228181914.6307257e.darcy@druid.net> <491b0d8f0805270900r4950360bjee559f9c86fb43b9@mail.gmail.com> Message-ID: David Jackson wrote: > i used the csv module and saved its contents to a list. > > ['Date', 'No.', 'Description', 'Debit', 'Credit'] > ['3/17/2006', '5678', 'ELECTRONIC PAYMENT', '', '11.45'] > ['3/04/2007', '5678', 'THE HOME DEPOT 263 SomeCity FL', '', '25.40'] > > > the credit/debit fields are strings. > what should i have done within the CSV module to make numbers appear as > numbers? > how can i remove the quotes to make them numbers? i realize i posted a > solution to this once before (same posting thread) but i am thinking > there is a better method. There doesn't seem to be a way to describe how specific columns should be processed in the csv module. You could define a conversion function that "guesses" the best conversion, for example: def str2num(datum): try: return int(datum) except: try: return float(datum) except: return datum for row in csv.reader(file(r'Transaction.csv')): [str2num(cell) for cell in row] ['Date', 'No.', 'Description', 'Debit', 'Credit'] ['3/17/2006', 5678, 'ELECTRONIC PAYMENT', '', 11.449999999999999] ['3/04/2007', 5678, 'THE HOME DEPOT 263 SomeCity FL', '', 25.399999999999999] -- Kam-Hung Soh Software Salariman From quentel.pierre at wanadoo.fr Tue May 27 11:30:22 2008 From: quentel.pierre at wanadoo.fr (Pierre Quentel) Date: Tue, 27 May 2008 08:30:22 -0700 (PDT) Subject: Python web development that resembles PHP or classic ASP References: <66a261d8-c31d-4519-beb9-c8913f61a87d@m44g2000hsc.googlegroups.com> Message-ID: <973b4193-0d0a-4800-9e5c-3bcb0115bace@56g2000hsm.googlegroups.com> On 25 mai, 18:58, erik.oosterw... at gmail.com wrote: > Hi All, > > I have been developing websites in classic asp using VB script for a > long while now. Due to the fact that I also took a detour to > developing ColdFusion, and the fact the companies I work(ed) for never > had time or money for courses, I am now in the awkward position that I > am -still- developing classic ASP. > > In it, I have become quite resourceful, I wrote a framework using WSC > (windows scripting components) to separate logic from presentation, > and my display pages use almost no logic, except for the loops and > variables I need to build my pages. I have a three-tier setup and all > business logic is in separate WSC files. The framework even uses an > ORM for access to the tables of my database. This works like a charm. > It makes classic ASP code maintainable, it makes working in classic > ASP very pleasant actually and it makes our customers very happy. > > The problem is that classic asp is now a dead language, I need to > modernize and fast! Although the arguments some people make against it > are not valid for me (spaghetti code, unmaintainable, slow), I still > see that there is little to no support for it anymore. > > The most logical way to "update" my knowledge to something more > modern, would be to dive into ASP.NET. I considered that for a long > time, but there are some problems with this: > > 1. I love the control I have over my html using inline, template-based > vbscript. ASP.NET's web forms really sound like a very bad idea, also > the approach Microsoft takes in trying to make a stateless web-app > seem like a statefull application is IMHO a burden. I think webapps > are inherently different than desktop apps, and should be programmed > as such. > > 2. Who says Microsoft isn't going to pull the plug on VB.NET in a > while or make a drastic change like they did from asp to asp.net > again, some time in the future? > > 3. I like the rapid development I can do in a dynamic, loosely typed > language like vbscript. The performance-bottleneck of a site is mostly > in the database-access and the http-calls and I think writing all of > the declarations and types for a strong-typed language is overkill for > a webapp. > > So that's when I started looking at other dynamic languages for > webdevelopment. I looked at Ruby on Rails and at the different web- > frameworks that are available for Python. The biggest problem there > for me is that the MVC type frameworks that are currently very popular > are also not what I'm looking for. > > I like having my directory tree conform to the structure of my > website, so the "Controller" part of the MVC style of development is > something I wouldn't want. What I -would- like is a separation of code > and display logic (so being able to include libraries in a page) and > being able to intermix code directly into the HTML. > > As Python would be the language I prefer over Ruby, I thought I'd ask > here to see if anyone in the Python community knows if such a > development-framework exists in Python. For example, does IronPython > also use the same web forms approach as asp.net using VB? The > frameworks I looked at (Django, Pylons) seem to be able to use > different templating engines, does that mean it's just a question of > finding the right one? > > Also, for Python there is also the problem of meaningful indentation. > I'm not even sure if it's possible to use Python directly inside HTML, > because indentation would be at the very least tricky to maintain. I'm > kind of hoping here that there are some solutions to these problems > available in Python. > > ?Any help would be greatly appreciated. > > Kind regards, > > Erik Hi, You can take a look at Karrigell (http://karrigell.sourceforge.net). It's very simple to install, stable (the first version was published in 2002) and among the programming styles provided you will find "Python Inside HTML" which is as close as you can get to PHP or ASP ===================

Squares

<% for i in range(10): print "%s :%s" %(i,i*i) %> =================== Regards, Pierre From jcd at sdf.lonestar.org Mon May 5 13:44:43 2008 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Mon, 05 May 2008 13:44:43 -0400 Subject: generator functions in another language In-Reply-To: References: <831bea0d-ef71-4ede-9065-3111bce5225e@c65g2000hsa.googlegroups.com> <684r62F2rmn3gU2@mid.uni-berlin.de> <8987552e-f462-4465-8338-d856017a4020@b1g2000hsg.googlegroups.com> Message-ID: <1210009483.25126.4.camel@aalcdl07.lib.unc.edu> On Mon, 2008-05-05 at 10:08 -0700, castironpi at gmail.com wrote: > At some point, code goes "on" and "off" the processor, which knowledge > I do owe to spending money. Thus, if the group news is a localcy > (other dimension of currency), that's bounce check the house dollar. > What do [second person plural] spend on [vernacular]? Sometimes I'm not sure whether castironpi is a bot or a really good troll who wants us to think he or she is a bot. At any rate, somebody's having a chuckle. From dullrich at sprynet.com Tue May 20 06:29:45 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Tue, 20 May 2008 05:29:45 -0500 Subject: How do *you* use Python in non-GUI work? References: <20080518182022.990193bd.johnjsal@NOSPAMgmail.com> Message-ID: On Sun, 18 May 2008 18:20:22 -0400, John Salerno wrote: >Hey all. Just thought I'd ask a general question for my own interest. Every time I think of something I might do in Python, it usually involves creating a GUI interface, so I was wondering what kind of work you all do with Python that does *not* involve any GUI work. This could be any little scripts you write for your own benefit, or what you do at work, if you feel like talking about that! :) You might get a keyboard with an Enter key, btw. Anyway: I'm a math professor, not a programmer. I use Python probably every day to do all sorts of things, for example: (i) Calculating grades. (Ok, this could be done in Excel. But if you know Python anyway you don't need to figure out how to do various things in Excel. Quick: In Excel how do you take all the quiz scores, drop the lowest _two_ of them and average the rest? Stumps people sometimes - if you're doing it by hand in Python it's no problem, you just do it.) (ii) Every semester I get a lot of emails asking about grades. Used to be tedious typing the same replies over and over, looking up the relevant numbers. A littls Python script takes the student's name, looks up the numbers and generates a reply automatically, including a summary of the scores and an explanation of how the grade was calculated.) (iii) Taking various data from various places and making it into HTML to post on the department web site. (Please don't look - a lot of that stuff is currently broken due to improvements on the server introduced by other faculty. These things happen when nobody's in charge so things get done by whoever's willing to do them...) (iv) Say I want to display the following system of equations on a quiz: 3x + 2y + z = 3 x - z = 1. Writing TeX to get the variables to line up properly can be tedious. A little Python thingie takes lists of variable names and coefficients and automatically produces TeX that displays the equations exactly right. I could go on and on - I use computers for a lot of things, and any time I want to do something but it's not obvious how to do it in the relevant big program Python gets pulled out to do the job. A meta-example: I'm about to publish a book on [never mind, the topic is still secret.] Python has been incredibly useful in writing that book, in many different ways. For example: (v) Making modifications to the text itself. For example, the other day I finally figured out how to make a certain aspect of the thing look right. So I wanted to replace every "$$[w]\qed" in the text (where [w] denotes any amount of white space) with "\QED$$". Took about a minute to make a Python script to go through the entire book and make the change. (vi) There are a lot of figures. Some fairly complicated, illustrating fairly complicated mathematical things. The figures are eps files that were generated by Python scripts. The simple ones could just have easily been done in Adobe Illustrator or Corel Whatever, but there's no way you're going to use a mouse-based program like that to draw the complicated figures and have everything in exactly the right place. I have Python do the calculations and then write the corresponding eps file, done. (vii) Many magical things were done with a combination of TeX macros and Python scripts. For example, index entries: If I say \index{Some Theorem} in the text and it turns out that that's on page 37 then "Some Theorem p.37" appears in the index; now if something gets revised so the \index{Some Theorem} is now on page 38 then the index entry is automatically revised to page 38. Or: The first page of Chapter n+1 is supposed to be the smallest odd number larger than the last page of Chapter n. A Python script typesets ("texs") each chapter; after typesetting Chapter n it looks and sees what the last page is, figures out what the first page of Chapter n+1 should be, and modifies the code for Chapter n+1 to start on the page before typesetting it. If I wrote this tomorrow the list of examples would be different. Just now over on comp.text.tex I showed someone a Python solution to a problem he had. I don't know if he's going to use it - he _would_ need to learn a _little_ Python first. But it's what I'd use if _I_ wanted to solve the problem! Other people suggested various programs available that would solve his problem for him - writing a little Python to give the solution took less time than downloading one of those programs would have. >Thanks. David C. Ullrich From afilash+python at gmail.com Thu May 22 08:57:40 2008 From: afilash+python at gmail.com (abhilash pp) Date: Thu, 22 May 2008 18:27:40 +0530 Subject: can someone with guessing a number In-Reply-To: <5504f9ac0805211005p678df2d0r3ee19071b758090f@mail.gmail.com> References: <005101c8bb61$b78fb710$1300a8c0@Home> <9f9d35df0805210954g5b2bb7bye48cf835b413069f@mail.gmail.com> <9f9d35df0805210955r2a00a3f6hfd71fe560a2760e6@mail.gmail.com> <5504f9ac0805211005p678df2d0r3ee19071b758090f@mail.gmail.com> Message-ID: <9f9d35df0805220557xfc858a7md4e6063ff9287c06@mail.gmail.com> Gary, There is a problem in using this sys.exit() if you are working in windows IDLE, then it will ask you for an 'exit altogether' so either change your 'while' clause or restructure your whole program to fit your idea :-) to avoid failed and success messages together cheers , abhilash On Wed, May 21, 2008 at 10:35 PM, Dan Upton wrote: > On Wed, May 21, 2008 at 12:55 PM, abhilash pp > > wrote: > >> On Wed, May 21, 2008 at 10:12 PM, garywood wrote: > >>> > >>> I would just like the program to exit after guessing the amount of > >>> numbers wrong > >>> > >>> # Guess My Number > >>> import random > >>> the_number = random.randrange(100) + 1 > >>> tries = 1 > >>> # guessing loop > >>> while (guess != the_number): > >>> if (guess > the_number): > >>> print "Lower..." > >>> else: > >>> print "Higher..." > >>> > >>> guess = int(raw_input("Take a guess: ")) > >>> tries += 1 > >>> if tries > 10: > >>> print 'you failed- give up' > >>> > >>> print "You guessed it! The number was", the_number > >>> print "And it only took you", tries, "tries!\n" > >>> > >>> raw_input("\n\nPress the enter key to exit.") > >>> > >>> many Thanks > >>> -- > >>> http://mail.python.org/mailman/listinfo/python-list > >> > > if tries > 10: > > print 'you failed- give up' > > break > > <------------------- use this > > > > That won't work as written, because it'll print "you failed," then > break, then print "You guessed it!"... > > As an alternative to what I suggested before, if you really just want > to end the program, you could also do > > from sys import exit > > > > if tries > 10: > print 'you failed- give up' > exit() > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From duncan.booth at invalid.invalid Tue May 20 10:04:56 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 20 May 2008 14:04:56 GMT Subject: scaling problems References: <69fbjvF2uih6aU6@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch wrote: > On Tue, 20 May 2008 10:47:50 +1000, James A. Donald wrote: > >> 2. It is not clear to me how a python web application scales. > > Ask YouTube. :-) Or look at Google appengine where unlike normal Python you really are prevented from making good use of threading. Google App Engine takes an interesting approach by forcing the programmer to consider scalability right from the start: state is stored in a distributed database which cannot do all the hard to scale things that SQL databases do. This means that you have to work as though your application were spread on servers all round the world from day 1 instead of waiting until the structure that was 'good enough' is threatening to kill your business before you address them. It also puts strict limits on how much a single web request can do, so again you have to work from day 1 to make sure that page requests are as efficient as possible. In return you get an application which should scale well. There is nothing Python specific about the techniques, it is just that Python is the first (and so far only) language supported on the platform. -- Duncan Booth http://kupuguy.blogspot.com From Sam.Dutton at itn.co.uk Sun May 25 04:41:55 2008 From: Sam.Dutton at itn.co.uk (Dutton, Sam) Date: Sun, 25 May 2008 09:41:55 +0100 Subject: finding icons for Apps Message-ID: http://tango.freedesktop.org/ ..as used by OpenOffice, Gimp, Pidgin (Gaim), etc. However, if you only need a few basics (Save, Print, etc.) just use the 'standard' for the platform. Whatever you do, don't mix different styles of icon. Note that for Windows the application icon (the thing you see on the Desktop or in a folder) is done as an .ico file, which has multiple sizes in the same file. You'll need to create this in an editor such as Visual Studio. Sam Dutton SAM DUTTON SENIOR SITE DEVELOPER 200 GRAY'S INN ROAD LONDON WC1X 8XZ UNITED KINGDOM T +44 (0)20 7430 4496 F E Sam.Dutton at itn.co.uk WWW.ITN.CO.UK P Please consider the environment. Do you really need to print this email? Please Note: Any views or opinions are solely those of the author and do not necessarily represent those of Independent Television News Limited unless specifically stated. This email and any files attached are confidential and intended solely for the use of the individual or entity to which they are addressed. If you have received this email in error, please notify postmaster at itn.co.uk Please note that to ensure regulatory compliance and for the protection of our clients and business, we may monitor and read messages sent to and from our systems. Thank You. -------------- next part -------------- An HTML attachment was scrubbed... URL: From wuwei23 at gmail.com Thu May 29 09:32:29 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 29 May 2008 06:32:29 -0700 (PDT) Subject: Tuple of coordinates References: Message-ID: On May 29, 10:16 pm, "victor.hera... at gmail.com" wrote: > Hi, > > i am using a software which uses python as its scripting language. I > want to generate a list of coordinates more or less this way: > > for i in (beg, end, step): > for j in (beg, end, step): > for k in (beg, end, step): > ......... > > Coords = ((i1,j1,k1), (i2,j2,k2), ...,(in,jn.kn)) > > Can anyone give me some advice on how to achieve this ? I got a little > idea, but still need to keep working til i get it. Thanks in advance, > > Victor >>> coords = [(x,y,z) for x in range(0,10) for y in range(0,10) for z in range(0,10)] From stefan_ml at behnel.de Fri May 23 03:22:06 2008 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 23 May 2008 09:22:06 +0200 Subject: where is the Write method of ElementTree?? In-Reply-To: <1e111b83-ad85-4e3e-baed-0ddee1255faa@d77g2000hsb.googlegroups.com> References: <1e111b83-ad85-4e3e-baed-0ddee1255faa@d77g2000hsb.googlegroups.com> Message-ID: <4836709E.6000003@behnel.de> gray.bowman at gmail.com wrote: > I'm messing around with trying to write an xml file using > xml.etree.ElementTree. All the examples on the internet show the use > of ElementTree.write(), although when I try to use it it's not > available, gives me ... > > ElementTree(sectionElement).write("section.xml") > TypeError: 'module' object is not callable I guess you did from xml.etree import ElementTree Then you should do this: ElementTree.ElementTree(sectionElement).write("section.xml") sadly, the module names in ET are upper case and look like classes... Stefan From ivan.illarionov at gmail.com Thu May 1 13:07:28 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Thu, 1 May 2008 17:07:28 +0000 (UTC) Subject: Best way to store config or preferences in a multi-platform way. References: Message-ID: On Thu, 01 May 2008 11:11:29 -0500, Jon Ribbens wrote: > On 2008-05-01, Ivan Illarionov wrote: >> IMO .ini-like config files are from the stone age. The modern approach >> is to use YAML (http://www.yaml.org). > > You mean YAML isn't a joke!? It's so ludicrously overcomplicated, and so > comprehensively and completely fails to achieve its stated main goal of > being "readable by humans", that I had assumed it was an April Fool > along the lines of Intercal or brainf***. > > I certainly wouldn't recommend it as being suitable for, well, anything > at all. > > Or were you trolling and I missed the joke? ;-) No, it isn't. I acually find it usefull and readable. I don't think that programmers at Google would use something that is a joke. I used XML files before for this purpose and found YAML much easier and better suitable for the task. Please explain why don't like YANL so much? PS. Your reply remind me of early days of Python when Perl programmers said exacly the same thing about Python. -- Ivan From tonal at promsoft.ru Thu May 15 23:46:33 2008 From: tonal at promsoft.ru (Alexandr N Zamaraev) Date: Fri, 16 May 2008 10:46:33 +0700 Subject: ? In-Reply-To: <51e0f25d-474a-450a-ad00-92f70c893c6c@m44g2000hsc.googlegroups.com> References: <51e0f25d-474a-450a-ad00-92f70c893c6c@m44g2000hsc.googlegroups.com> Message-ID: <482D0399.5090804@promsoft.ru> urikaluzhny wrote: >> | It seems that I rather frequently need a list or iterator of the form >> | [x for x in <> while <>] >> I can think of two ways to interpret that. > I mean like [x for x in if ], only that it breaks the loop when > the expression is false. How do you plan to modify B during iteration? May be [x for x in itertools.takewhile(, )] when function accept element and return True or False From tjreedy at udel.edu Mon May 12 22:38:10 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 12 May 2008 22:38:10 -0400 Subject: question about python statements References: Message-ID: "George Sakkis" wrote in message news:e0ea51fe-7279-434b-9e21-c15554624003 at 2g2000hsn.googlegroups.com... On May 12, 7:35 pm, "Terry Reedy" wrote: > "Ohad Frand" wrote in message > > news:B9E129828E47994B9B95E1BAABC8868C0B8F06 at percello-sbs.percello.local... > | I am looking for a way to programmically get a list of all python > | existing statements that I cannot access by __builtins__ or locals() > | (like ["assert","break","class",...]) > > You appear to want the keywords that begin statements. Look at the > keyword > list in the language reference and pick those you want. Then build that > list into your program. Someone already did it: import keyword print keyword.kwlist ========================= I forgot about that. However, I got the impression that the OP wants a subset, and if so, *that* will require hand selection. From kris at FreeBSD.org Thu May 29 18:10:22 2008 From: kris at FreeBSD.org (Kris Kennaway) Date: Fri, 30 May 2008 00:10:22 +0200 Subject: UNIX credential passing Message-ID: <483F29CE.7060104@FreeBSD.org> I want to make use of UNIX credential passing on a local domain socket to verify the identity of a user connecting to a privileged service. However it looks like the socket module doesn't implement sendmsg/recvmsg wrappers, and I can't find another module that does this either. Is there something I have missed? Kris From castironpi at gmail.com Tue May 13 10:45:32 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 13 May 2008 07:45:32 -0700 (PDT) Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <2b66a86e-5a05-4262-b3c9-4703b0ae3372@d1g2000hsg.googlegroups.com> <5b0e3f70-afde-4480-8713-e7113b1250d7@x35g2000hsb.googlegroups.com> <1f537717-00d0-48ee-99b6-7125b96a6133@t12g2000prg.googlegroups.com> <68t4o0F2vaoncU1@mid.uni-berlin.de> <2a32179a-9439-449c-bd07-fff6a4075aee@s50g2000hsb.googlegroups.com> <7ee5dffd-df8f-46f0-bd78-c81ac0418a9a@d77g2000hsb.googlegroups.com> Message-ID: On May 13, 9:34?am, hdante wrote: > On May 13, 10:58?am, Paul McGuire wrote: > > > > > > > On May 13, 8:32?am, Dave Parker wrote: > > > > > Don't let yourself be irritated by castironpi > > > > I'm not the sort to get irritated by anyone. ?There is value in all > > > interaction. > > > Not this interaction, I'm afraid. ?What irritates *me* about > > castironpi is that he uses a chatterbot to clutter up the threads > > here. ?If you go back to his postings from a year ago (and selected > > ones since), his comments are coherent and sensible. ?These rambling > > stream-of-consciousness rants about t.v.'s and coffee are (I guess) > > his idea of a joke. ?But they are certainly not worth your time in > > trying to respond to them. > > > -- Paul > > ?I don't think castironpi so annoying that I should filter its > messages. It would be enough if he were better tuned. He is much > smarter than the emacs shrink, for example. :-P > > ?The "Flaming Thunder" looks promising, but without being free > software, it's unlikely it will create a large developer community, > specially considering both free general purpose and scientific > programming languages.- Hide quoted text - > > - Show quoted text - What is a tank a tank of? Even if it does, developer communities are willing to sustain it. That's a pretty colinear judgement, that I find the community sustainable. Does anyone commute to out of control? What is to out? No jumping down thrown. Tut tut. From martin at v.loewis.de Sat May 10 02:55:59 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 10 May 2008 08:55:59 +0200 Subject: RELEASED Python 2.6a3 and 3.0a5 In-Reply-To: <90cdf44a-f189-4264-9add-03d094ba48ab@e39g2000hsf.googlegroups.com> References: <90cdf44a-f189-4264-9add-03d094ba48ab@e39g2000hsf.googlegroups.com> Message-ID: <482546ff$0$14157$9b622d9e@news.freenet.de> > I'm trying to install on the latest Ubuntu (8.04) and the following > extension modules fail: > > _bsddb, _curses, _curse_panel, _hashlib, _sqlite3, _ssl, _tkinter, > bz2, dbm, gdbm, readline, zlib > > All of them except for _tkinter are included in the preinstalled > Python 2.5.2, so I guess the dependencies must be somewhere there. > Does Ubuntu have any non-standard lib dir ? You need to manually install the -dev packages (through aptitude) before building Python. Regards, Martin From bellman at lysator.liu.se Tue May 20 10:38:01 2008 From: bellman at lysator.liu.se (Thomas Bellman) Date: Tue, 20 May 2008 14:38:01 +0000 (UTC) Subject: Accumulating values in dictionary References: <07fbc8ec-924a-4e90-b212-ca4cc66f2b85@i76g2000hsf.googlegroups.com> Message-ID: Arnaud Delobelle wrote: > from collections import defaultdict > d = defaultdict(int) # That means the default value will be 0 > for person in people: > d[person.fav_food] += 1 Ah! I didn't think of using int as the factory function. If you use this, then I believe the warning I gave about performance does not apply; my understanding is that calling built-in functions (like the int constructor) is fast. -- Thomas Bellman, Lysator Computer Club, Link??ping University, Sweden "Beware of bugs in the above code; I have ! bellman @ lysator.liu.se only proved it correct, not tried it." ! Make Love -- Nicht Wahr! From bj_666 at gmx.net Fri May 2 02:48:06 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 2 May 2008 06:48:06 GMT Subject: no cleanup on TERM signal References: Message-ID: <67vrp6F2r409aU1@mid.uni-berlin.de> On Fri, 02 May 2008 04:36:06 +0000, Yves Dorfsman wrote: > x.del() gets executed if: > -I del x, then run gc.collect() > -simply exit the script > -get the script to abort on an exception > > But if I kill it with the default signal TERM, the script dies, but I don't > get the message, so I am assuming that python isn't taking the time to > cleanup, even though that is (was) what TERM was intended for. > > Has this been discussed before ? Is worth a suggestion (PEP) ? There is the docs for `__del__()` saying this method is not guaranteed to be called at all. Don't use it if you *need* that method to be called. Just like `finalize()` in Java, it can't be used for deterministic destruction, so it's not that useful after all. Ciao, Marc 'BlackJack' Rintsch From wuwei23 at gmail.com Tue May 27 00:32:04 2008 From: wuwei23 at gmail.com (alex23) Date: Mon, 26 May 2008 21:32:04 -0700 (PDT) Subject: sort list doesnt work, key=str still doesnt work References: Message-ID: <13c751dd-6a86-4e53-a389-9515b9e95494@x19g2000prg.googlegroups.com> On May 27, 12:46 pm, notnorweg... at yahoo.se wrote: > what do i need to do? Ideally, you need to read some introductory material and stop offloading whatever the hell it is you're doing to this group. From castironpi at gmail.com Sun May 4 07:22:31 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sun, 4 May 2008 04:22:31 -0700 (PDT) Subject: saving a webpage's links to the hard disk References: <9a4733b4-5320-4a66-b0ce-5dcebc02d9a7@y38g2000hsy.googlegroups.com> Message-ID: <7ccc9c7b-002c-4385-9832-aaa0981638da@2g2000hsn.googlegroups.com> On May 4, 12:33?am, "Gabriel Genellina" wrote: > En Sun, 04 May 2008 01:33:45 -0300, Jetus escribi?: > > > Is there a good place to look to see where I can find some code that > > will help me to save webpage's links to the local drive, after I have > > used urllib2 to retrieve the page? > > Many times I have to view these pages when I do not have access to the > > internet. > > Don't reinvent the wheel and use wgethttp://en.wikipedia.org/wiki/Wget > > -- > Gabriel Genellina A lot of the functionality is already present. import urllib urllib.urlretrieve( 'http://python.org/', 'main.htm' ) from htmllib import HTMLParser from formatter import NullFormatter parser= HTMLParser( NullFormatter( ) ) parser.feed( open( 'main.htm' ).read( ) ) import urlparse for a in parser.anchorlist: print urlparse.urljoin( 'http://python.org/', a ) Output snipped: ... http://python.org/psf/ http://python.org/dev/ http://python.org/links/ http://python.org/download/releases/2.5.2 http://docs.python.org/ http://python.org/ftp/python/2.5.2/python-2.5.2.msi ... From duncan.booth at invalid.invalid Fri May 16 10:14:47 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 16 May 2008 14:14:47 GMT Subject: Variable by label References: Message-ID: rocco.rossi at gmail.com wrote: > Is there any function which will return a variable by passing to it > the string containing the variable's name? Something like this for > instance: > > foo = some_function("foo") > > or perhaps it's a dictionary. I don't know, but I would really like to > find out how it can be done. I guess it is achievable. > > Thank you. > vars()["foo"] but if you are doing this you are almost certainly making your life harder than it needs to be. Usually you really just want to keep the values in a dict. -- Duncan Booth http://kupuguy.blogspot.com From gneuner2/ at /comcast.net Fri May 2 05:03:59 2008 From: gneuner2/ at /comcast.net (George Neuner) Date: Fri, 02 May 2008 05:03:59 -0400 Subject: Python's doc problems: sort References: <929d5ce9-9063-4e6c-98aa-89526f89fba3@y18g2000pre.googlegroups.com> <9pof14t22rpq24219q0an2748i5f054qr4@4ax.com> <88273bc8-5152-4dfd-9f96-1d6ee2b83f99@e53g2000hsa.googlegroups.com> Message-ID: On Wed, 30 Apr 2008 12:35:10 +0200, "John Thingstad" wrote: >P? Wed, 30 Apr 2008 06:26:31 +0200, skrev George Sakkis >: > >> >> \|||/ >> (o o) >> ,----ooO--(_)-------. >> | Please | >> | don't feed the | >> | TROLL's ! | >> '--------------Ooo--' >> |__|__| >> || || >> ooO Ooo > >Doesn't copying Rainer Joswig's troll warning constitute a copywright >infrigment :) It's not an exact copy of Rainer's so it may be arguable whether it violates his copyright. Might have more luck with a trademark argument - distorted marks may still infringe. George -- for email reply remove "/" from address From jkugler at bigfoot.com Fri May 16 16:08:24 2008 From: jkugler at bigfoot.com (Joshua Kugler) Date: Fri, 16 May 2008 12:08:24 -0800 Subject: IDE for Python References: Message-ID: Jonathan Barbero wrote: > I?m newbie with Python and to learn it better I want to use a good IDE to > concentrate on Python power. There is any IDE like Eclipse for Java for > Python? If not, what is the best Python?s IDE for you? This is an EFAQ (extremely frequently asked question). http://www.google.com/search?hl=en&q=python+ide+site%3Amail.python.org%2Fpipermail%2Fpython-list%2F&btnG=Google+Search j From aspersieman at gmail.com Mon May 26 12:42:12 2008 From: aspersieman at gmail.com (Aspersieman) Date: Mon, 26 May 2008 18:42:12 +0200 Subject: IOError in windows service In-Reply-To: References: <483A85C6.20803@gmail.com> Message-ID: <483AE864.3000708@gmail.com> An HTML attachment was scrubbed... URL: From workitharder at gmail.com Fri May 23 16:17:28 2008 From: workitharder at gmail.com (bukzor) Date: Fri, 23 May 2008 13:17:28 -0700 (PDT) Subject: call f(a, *b) with f(*a, **b) ? References: <55bc8846-107e-461a-89de-25c83cbcfa27@2g2000hsn.googlegroups.com> <5coZj.13951$hv2.4218@bignews5.bellsouth.net> <9e688dbd-43fb-43ca-8c60-8dd2aaa66aa1@x1g2000prh.googlegroups.com> <69670280-f9e7-43f8-9750-09374f907332@j33g2000pri.googlegroups.com> Message-ID: On May 23, 12:35 pm, "inhahe" wrote: > " > I wish this worked:>>> def main(a,b,*argv): pass > >>> options['argv'] = argv > >>> main(**options) > > TypeError: main() got an unexpected keyword argument 'argv' > " > ----- > I was thinking about that exact same thing actually. Except that I was > thinking you might want it like this, otherwise it could be ambiguous: > > >>> def main(a,b,*argv): pass > >>> options['*argv'] = argv > >>> main(**options) > > Weird I know, to put the * operator inside the string. I suppose the > necessity of doing that just shows why it wasn't implemented in the first > place. But still, it would be neat... > > Also, of course, you could then do > main(*argv=[2,3]) > > or rather > > main(*argv=[3,4],a=1,b=2) #in random order Yes I think something like that would be an improvement. I wonder if anyone would help me write a PEP... It might not be too hard to pass since it would be compatible with all existing code. I'd be willing to produce a patch against python2 or py3k. I don't see that leaving off the * makes it ambiguous, since there can only be one argument with that name: def f(args, *args): pass SyntaxError: duplicate argument 'args' in function definition From jeffober at gmail.com Fri May 2 15:50:51 2008 From: jeffober at gmail.com (Jeff) Date: Fri, 2 May 2008 12:50:51 -0700 (PDT) Subject: Do you know of a much simpler way of writing a program that writes a program? References: <481B27D9.3000107@behnel.de> Message-ID: <286490d5-01ce-40c5-8965-9e3da4fea1c9@w74g2000hsh.googlegroups.com> Use lisp? From gherron at islandtraining.com Tue May 13 04:10:59 2008 From: gherron at islandtraining.com (Gary Herron) Date: Tue, 13 May 2008 01:10:59 -0700 Subject: question about python statements In-Reply-To: References: Message-ID: <48294D13.4020600@islandtraining.com> Ohad Frand wrote: > Hi Gary > > Sorry that I was not clear, I hope that this time I will explain myself > better. > > I can get list of all builtin functions in python by dir(__builtins__). > This return a list of string with most known names to python language > such as: > [... 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'long', > 'map', 'max', 'min', 'object', 'oct', 'open', 'ord', 'pow', 'property', > 'quit', 'range', 'raw_input', 'reduce', 'reload'...] > > But I don't know how to generate the next list of builtin python > statements: > ['assert','break','class','continue','def','del','elif','else','except', > 'exec','finally','for','from','global', > 'if','import','pass','print','raise','return','try','while','yield'] > There is no way you can consider 'elif', 'else', 'except', and 'from' statements. However, as someone pointed out, the kwlist from the keyword module is the closest thing we can think of to the list you are asking for. On the other hand, what's wrong with constructing the list as you did in your example above? Just out of curiosity, *why* do you want this list. Perhaps is we knew that, we could think of a programmatic way to construct the list you want. The biggest challenge at the moment is that we have no idea what you mean by statement, but it is certainly not what Python considers statements. Gary Herron > Thanks, > Ohad Frand > > -----Original Message----- > From: Gary Herron [mailto:gherron at islandtraining.com] > Sent: Monday, May 12, 2008 10:41 PM > To: Ohad Frand > Cc: python-list at python.org > Subject: Re: question about python statements > > Ohad Frand wrote: > >> Hi >> >> I am looking for a way to programmically get a list of all python >> existing statements that I cannot access by __builtins__ or locals() >> >> (like ["assert","break","class",...]) >> >> Thanks, >> >> Ohad >> >> >> > ------------------------------------------------------------------------ > >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > Sorry, I've no idea what you mean here. Perhaps you could help us by > defining what you mean by > "statements that I cannot access by __builtins__ or locals()" > > Is there any statement that you *can* access in such a way? > > What does it even mean to "access a statement"? > > Do you even have a list of "statements" from which we are to work? > Python is a little unusual in what it considers statements. > > Gary Herron > > > > > From casey.mcginty at gmail.com Fri May 30 02:01:29 2008 From: casey.mcginty at gmail.com (Casey McGinty) Date: Thu, 29 May 2008 20:01:29 -1000 Subject: Code execution in imported modules In-Reply-To: <92da89760805291743p4f88b15ao14c9f990c1c50162@mail.gmail.com> References: <92da89760805291743p4f88b15ao14c9f990c1c50162@mail.gmail.com> Message-ID: On Thu, May 29, 2008 at 2:43 PM, Eric Wertman wrote: > So I'm working on some file parsing and building up a stack of regular > expressions that I need to use. I was thinking of dropping them in an > external module. I was wondering.. if I put them in a file called > regex.py like so : > > import re > > re1 = ".. > re2 = ".. > > and then do: > > rgx1 = re.compile(re1) > rgx2 = re.compile(re2) > > > and, in my script, parse.py py I do: > > from regex import * > > text = "bunch of stuff......." > > m = rgx1.search(text) > > > Does the re get compiled when I import it, or every time I call it? > Since I'm calling it often, I'd like to compile it once. > > Thanks! > -- > http://mail.python.org/mailman/listinfo/python-list > Please correct me if I am wrong ... but I believe this should work, and rgx's will only be compiled on the first import. You could also place them in a class and get the same effect when you instantiate the class. class MyRegEx( object ): re1 = ".. re2 = ".. rgx1 = re.compile(re1) rgx2 = re.compile(re2) -------------- next part -------------- An HTML attachment was scrubbed... URL: From ivan.illarionov at gmail.com Wed May 14 02:01:02 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Tue, 13 May 2008 23:01:02 -0700 (PDT) Subject: usage of python References: Message-ID: <8bf1efe4-4165-4cee-ae77-cd25a6f36c1e@w7g2000hsa.googlegroups.com> On 13 ???, 21:10, Rajarshi wrote: > Hi, I teach an introductory programming course in Python. As part of > the introduction I'd like to highlight the usage of Python in > industry. The idea is to show that there are big players using Python > for a variety of tasks. Given that the students come from a variety of > backgrounds and are not necessarily 'hackers', I'm trying to look for > examples with a bit of wow-factor. > > Is there any list with people/groups/companies using Python for > impressive things? > > Any pointers would be appreciated > > Thanks, > Rajarshi Hi, Rajarshi, Besides the above comments, I want to highlight Django and other Python web frameworks and their ability to build simple dynamic web sites extremely fast. http://www.djangoproject.com/ -- Ivan From fiacre.patrick at gmail.com Fri May 23 01:26:30 2008 From: fiacre.patrick at gmail.com (Andrew Lee) Date: Fri, 23 May 2008 01:26:30 -0400 Subject: Python is slow In-Reply-To: References: Message-ID: <48365587$0$11637$607ed4bc@cv.net> cm_gui wrote: > Python is slow. Almost all of the web applications written in > Python are slow. Zope/Plone is slow, sloow, so very slooow. Even > Google Apps is not faster. Neither is Youtube. > Facebook and Wikipedia (Mediawiki), written in PHP, are so much faster > than Python. > Okay, they probably use caching or some code compilation -- but Google > Apps and those Zope sites probably also use caching. > > I've yet to see a web application written in Python which is really > fast. So --- don't use Google * shrug * Personally I find PHP to be a hideous language -- it has only one use. It is Perl for people who can be bothered to learn a general purpose programming language and just write web applications. Python is a general purpose programming language ... it does web nicely (Django and pylons!), it supports real OOP and OOD, it's extensible, it has a smart set of libraries, intelligent and coherent interfaces, it sails across platforms, it has at least one great ORM (SQLAlchemy) and I keep discovering new cool things about the language as a recent convert that make me wonder why I would ever write another large application in Perl or Java. I find Zope to be a mess and it gives me a headache ... but it Zope is an *application framework*, not a *programming language*. So, I think you are barking up the wrong straw man (if I may mix metaphors). But that's just my $0.02. From saluk64007 at gmail.com Mon May 26 01:40:33 2008 From: saluk64007 at gmail.com (Patrick Mullen) Date: Sun, 25 May 2008 22:40:33 -0700 Subject: Why does python not have a mechanism for data hiding? In-Reply-To: References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <8763t3by81.fsf@benfinney.id.au> <09847cfc-eaec-4adc-8cbf-1e2ebbf940c4@m44g2000hsc.googlegroups.com> Message-ID: Here is a quick, ugly way you can easily hide data, although persistent clients can still bypass it. x.__dict__ is ugly, though not any uglier than x.__Ugly__Internal__Variable__Do__Not__Set Another option would be to use another structure, such as a dictionary or list, and store variables in there proxying to it from get/set functions (or __getattr__ __setattr__). Or just don't document this. class HideTest(object): def __init__(self): self.__dict__["beans"] = 5 def __setattr__(self,key,val): if key == "beans": raise Exception("Cannot set this attribute") return super(HideTest,self).__setattr__(key,val) b = HideTest() print "b.beans is",b.beans try: b.beans = 5 except: print "Cannot set" Also the point of underscore rules have never been to keep clients from accessing variables. Read about them in PEP8: http://www.python.org/dev/peps/pep-0008/ They are primarily to handle specific name conflict situations, and secondarily to inform users when they might be mucking about with something at a lower level. Using a keyword could work I suppose for the module-level convention, as well as for the name mangling. Implementation wise it seems a bit tricky to use keywords for this. For the purposes of informing users however, keywords versus underscore is a terrible idea. dir() as is makes it clear, with underscores, which variables are safe to use and which are potentially dangerous. Rewriting dir() to print extra information about names seems incredibly problematic as well. I really like the idea of having variables that may be unsafe to use but I can still use them if I want to, and the underscore rules are the most clean way I can see for this purpose (not to mention all of the history). I agree that they do look ugly of course. I also tend not to use them in my code as well. This has been brought up so many times before, and turned down again and again. Working around it as best you can is your best bet, especially since a major change like this could never happen until well after python 3.0. (Who knows how long it will take before 3.0 is fully adopted enough to move on from that) -------------- next part -------------- An HTML attachment was scrubbed... URL: From s0suk3 at gmail.com Sun May 4 07:18:22 2008 From: s0suk3 at gmail.com (s0suk3 at gmail.com) Date: Sun, 4 May 2008 04:18:22 -0700 (PDT) Subject: Please help - Tkinter not doing anything References: <20562a9d-200c-40ae-a850-eb0f9a943d3f@l42g2000hsc.googlegroups.com> <237aa3894dff4c8976896df85f4d7d23@localhost> <3ab5d06a0805040239m6cf12d39ufcde4fcc585f81e4@mail.gmail.com> Message-ID: On May 4, 5:22 am, Protected wrote: > I had previously ran the import line. I prepended it to the example > code I'm trying to run every time but it did not help, still nothing > happens. With or without var before 'root'. I'm pasting the code in > IDLE and using Windows XP as written in the first post. > Tkinter doesn't work if you type the statements in IDLE. I don't remember the specifics of it, but essentially it doesn't work because IDLE is itself a Tkinter app. You have to type it at the Python command line or save it in a file. BTW, if you're on Windows, you should definitely check wxPython. I used to work with Tkinter, struggling with it all the time only to get a lame result most of the time. Then I switched to wxPython, and in the same week I was learning it I did a better GUI than I ever did in Tkinter (with months of work!). I feel it makes it easier to make your program have a better structure and design, and thus lets you focus on the actual task of the program, rather than in the GUI itself. Plus, on Windows, you'll get the widgets to look more natively, like any good quality application there is on Windows. From timr at probo.com Wed May 14 02:17:56 2008 From: timr at probo.com (Tim Roberts) Date: Wed, 14 May 2008 06:17:56 GMT Subject: Fill memeory with endless loop? References: <252c17a9-01a6-4abe-9515-2507e0e50a20@l64g2000hse.googlegroups.com> Message-ID: globalrev wrote: > >and when the program get skiled because out of memory all this will be >deleted from the memory? Yes. When a process is killed, all of the memory it was using is released. >so there is no way that you can, by accident, fill your whole >harddrive and make it unusable? Of course not. Where do you see a connection between memory and your hard drive? Now, you can certainly fill your hard drive by running your little infinite loop application and storing the results in a file: python looper.py > saveme.txt but I hope it is clear to you that this can't damage any of the data you already have. >and RAM-memory always get cleaned out when not used i guess? It gets released so that it can be re-used. I don't know what you mean by "cleaned out". Remember that most of the systems where Python runs are virtual memory systems, so even if one application is using a couple of gigabytes of memory, other applications are still able to run. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From gagsl-py2 at yahoo.com.ar Fri May 9 02:24:06 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 09 May 2008 03:24:06 -0300 Subject: Python script freezed on Window DOS terminal References: <95455e980805082142w7891868fy89da4c0be6659246@mail.gmail.com> Message-ID: En Fri, 09 May 2008 01:42:21 -0300, hce escribi?: > I am running Python and a script on XP DOS terminal, the script > build.py printed out messages on the Terminal, then asked for an input > of numbers. But, I pressed a key, nothing came in DOS terminal, > Eventually, no key active and seem the DOS terminal is freezed. I > could not even terminate the terminal by Ctrl-C or Ctrl-D. The same > script was running fine on linux or Cygwin terminals. Any thoughts > what was the problem? Next time try with Ctrl-Break. It's hard to say what's wrong without seeing the script. -- Gabriel Genellina From arnodel at googlemail.com Sat May 3 16:57:29 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sat, 03 May 2008 21:57:29 +0100 Subject: dict invert - learning question References: Message-ID: dave writes: > Hello, > > here is a piece of code I wrote to check the frequency of values and > switch them around to keys in a new dictionary. Just to measure how > many times a certain key occurs: > > def invert(d): > inv = {} > for key in d: > val = d[key] > if val not in inv: > inv.setdefault(val, [key]) You can simply write: inv[val] = [key] > else: > inv[val].append(key) > return inv > > > Using the methods above (I'm just a beginner) could I have written it > more concisely? Any criticism/critique in the code would be greatly > appreciated. Apart from the unnecessary use of setdefault, it looks good to me. * You could change if 'val not in inv:' to 'if val in inv:' (and swap the if and else clauses of course) in order to have a positive condition rather than a negative one * If you want to use setdefault, you can replace the if .. else construct by: inv.setdefault(val, []).append(key) * You can also iterate over keys and values using the items() or iteritems() method of dictionaries: def invert(d): inv = {} for key, val in d.iteritems(): inv.setdefault(val, []).append(key) return inv -- Arnaud From torriem at gmail.com Thu May 1 12:52:33 2008 From: torriem at gmail.com (Michael Torrie) Date: Thu, 01 May 2008 10:52:33 -0600 Subject: Zope/DTML Infuriating... In-Reply-To: <4819F4A5.4010302@gmail.com> References: <65492d56-de86-4979-a886-b4e6f9b3b42f@2g2000hsn.googlegroups.com> <4819F4A5.4010302@gmail.com> Message-ID: <4819F551.4080501@gmail.com> Michael Torrie wrote: > The second example, x = Integer.fromString('5') demonstrates a huge > weakness in Java. Ahem. Javascript. Sorry. From phil at freehackers.org Tue May 6 10:38:06 2008 From: phil at freehackers.org (BlueBird) Date: Tue, 6 May 2008 07:38:06 -0700 (PDT) Subject: How to generate binary python? References: <5dc598e30805051543g243ed4daw119c7579f3ae4095@mail.gmail.com> Message-ID: <65aa8695-ec87-44a5-9ee1-e4c58000a66c@m73g2000hsh.googlegroups.com> On May 6, 6:29 am, "Gabriel Genellina" wrote: > En Mon, 05 May 2008 19:43:24 -0300, David Anderson > escribi?: > > > Hi, i'm comingo from Java and I'm wanting to know what in Python is the > > equivalent to the file.class in java, I am producing some apps that ar > > not > > open source, so I would like to share only the binaries, Both for Windows > > and for Linux, Can you suggest me anything? > > .class files map roughly to .pyc files > Note that Python generates and writes .pyc files automatically when you > import a module, but not for the main script being executed. > The standard way to generate a binary distribution is using distutils, see > the Python wiki at > You can have a look at the following page for a very very short comparison of the different solutions available today: http://www.freehackers.org/Packaging_a_python_program From parag_paul at hotmail.com Thu May 8 03:30:53 2008 From: parag_paul at hotmail.com (parag_paul at hotmail.com) Date: Thu, 8 May 2008 00:30:53 -0700 (PDT) Subject: What is the purpose of ptyhon in Windows References: Message-ID: <2d7d65f9-9f3e-4ed4-be32-b3c3c21d58a7@b1g2000hsg.googlegroups.com> On May 7, 9:35?pm, Max Erickson wrote: > WolfgangZ wrote: > > parag_p... at hotmail.com schrieb: > >> hi All, > >>http://mail.python.org/mailman/listinfo/python-list > > > At least I'm living in a free country and nobody forces me to > > learn python. So I don't fully understand why you HAVE TO learn > > it. When your problems can be solved in a different programming > > language than you should be free to use whatever you like. And > > also why should it be forbidden to create a new programming > > language? Diversity and competition is usually not bad. > > > -- > >http://mail.python.org/mailman/listinfo/python-list > > I imagine that there is some English as a second language getting > involved and the intent of the question was more like "What is > python useful for on Windows?", which has pretty much the same > meaning but is open to a slightly friendlier interpretation(i.e., > tell me how I can use python instead of tell me why I should use > python). > > The other question might be more like "I already know VBS, what do I > gain by learning python?". > > (the answers could be "lots of things, including full applications" > and "among other things, you can use it on other platforms, and you > might prefer the syntax".) > > max thanks to all, Can you all forward me some sites where there may examples of work done on Python and that which I amy bring into some application From python at rcn.com Fri May 30 22:16:08 2008 From: python at rcn.com (Raymond Hettinger) Date: Fri, 30 May 2008 19:16:08 -0700 (PDT) Subject: How to add function return value References: <28e0c835-4ed7-4571-ab69-a90cec4efc08@f24g2000prh.googlegroups.com> Message-ID: <7d89a189-1ce9-46d3-b200-2ad86858fa45@h1g2000prh.googlegroups.com> On May 30, 6:21?pm, HYRY wrote: > Can I write a decorator that it can automately do this conversion > > def func1() > ? ? a = 1 > > ---> > > def func1(): > ? ? a = 1 > ? ? return locals() Not sure why you would want to do this, but there are several ways. 1. Make bytecode hack decorator that transforms the final "return None" into "return locals()". A recipe that shows the basic technique is at: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/277940 2. Retrieve the source using inspect.getsourcelines(f). Then, append a "return locals()" to the end of the function and run it through exec. 3. Try hacking a tracing/debugging utility. 4. Run the sourcefile through tokenize, make the appropriate insertion, and then untokenize. . . . Raymond From castironpi at gmail.com Fri May 16 18:57:52 2008 From: castironpi at gmail.com (castironpi) Date: Fri, 16 May 2008 15:57:52 -0700 (PDT) Subject: write to specific line in file? References: <104ddf01-e860-4194-87bb-753a5e837ec0@s50g2000hsb.googlegroups.com> <29b9fb36-17bb-4449-aab9-e10361d0b0e4@b1g2000hsg.googlegroups.com> Message-ID: <2c673602-8b32-43cf-be47-2e981b971973@b64g2000hsa.googlegroups.com> On May 16, 5:22?pm, castironpi wrote: > On May 16, 2:25?pm, 7stud wrote: > > > > > > > globalrev wrote: > > > i ahve a program that takes certain textsnippets out of one file and > > > inserts them into another. > > > > problem is it jsut overwrites the first riow every time. > > > > i want to insert every new piece of text into the next row. > > > so: > > > 1. how do i write to a new line every time i write to the file? > > > > 2. if i dont want to write to a new line but just want to insert it > > > after the last token in the file, how do i do then? > > > Generally, you can't "insert" anything into a file. ?You can either > > append to the end of a file, or you can rewrite the whole file. ?It > > sounds like you probably want to read the file into an array using > > readlines(). ?Then manipulate that array however you want--appending > > and inserting--and when you are done, overwrite the file with your > > array. > > > However, you should be aware that as soon as you open a file for > > writing all the data is erased, and if your program should happen to > > crash right then, the array containing the data will disappear into > > the ether and your file will be empty--in other words all your data > > will be gone. ?To prevent such an occurence, you should write your > > final data to another file, then delete the original file, and finally > > change the other file's name to the original file name. > > Some options: > > 1. ?Limit line length. ?Then offset is ( line* length ). > 2. ?Name your relation. > 3. ?Hijack the operating system. ?Remember: > > abc > def > > on disk looks like > abc\ndef > > where > > abcd > def > > looks like > abcd\ndef > > So, if you want line 2, you have to scan line 1.- Hide quoted text - > > - Show quoted text - You also have f.seek( X ) f.write( 'abc' ) which writes 'abc' in the middle, at offset X. f.seek( 0, SEEK_END ) takes you to the back, and don't forget f.flush( ). Say you have: File: abc def ghi Symbols: 0-3 1-3 2-3 abcdefghi and you want to make abc abC. Then f.seek( 2 ) f.write( 'C' ) does work. If you want to make abc ab, then you change a different file table.seek( 0 ) table.write( chr( 2 ) ) ( or bytes( [ 2 ] ) in 3.0 ). If you want to make abc abcd, then you change both. f.seek( 9 ) f.write( 'd' ) table.seek( 0 ) table.write( chr( 4 ) ) But. Now you have item 0 in two places. 'abc' somewhere and 'd' somewhere else, at 0 and at 9 respectively. I think the file system overallocates room for String 1. You would read: 0- 2- [ 3, 1 ] for 'abc'+'d' and 1- 1- [ 3 ] 2- 1- [ 3 ] for 'def' and 'ghi', where actual representations would be: 0- 2- [ 0/3, 9/1, 0, 0, 0, 0, 0, 0 ] 1- 1- [ 3/3, 0, 0, 0, 0, 0, 0, 0 ] 2- 1- [ 6/3, 0, 0, 0, 0, 0, 0, 0 ] As your chains start to grow, leave table 8xN, and just copy strings to new sectors when they become long: 0- 1- [ 9/4, 0, 0, 0, 0, 0, 0, 0 ] 1- 1- [ 3/3, 0, 0, 0, 0, 0, 0, 0 ] 2- 1- [ 6/3, 0, 0, 0, 0, 0, 0, 0 ] You can insort in linear time when you're looking for available slots. 'jklm' can't fit at 0. 0- 1- [ 9/4, 0, 0, 0, 0, 0, 0, 0 ] 1- 1- [ 3/3, 0, 0, 0, 0, 0, 0, 0 ] 2- 1- [ 6/3, 0, 0, 0, 0, 0, 0, 0 ] 3- 1- [ 13/4, 0, 0, 0, 0, 0, 0, 0 ] but 'nop' can. 0- 1- [ 9/4, 0, 0, 0, 0, 0, 0, 0 ] 1- 1- [ 3/3, 0, 0, 0, 0, 0, 0, 0 ] 2- 1- [ 6/3, 0, 0, 0, 0, 0, 0, 0 ] 3- 1- [ 13/4, 0, 0, 0, 0, 0, 0, 0 ] 4- 1- [ 0/3, 0, 0, 0, 0, 0, 0, 0 ] 'jklm' could've with a split: 0- 1- [ 9/4, 0, 0, 0, 0, 0, 0, 0 ] 1- 1- [ 3/3, 0, 0, 0, 0, 0, 0, 0 ] 2- 1- [ 6/3, 0, 0, 0, 0, 0, 0, 0 ] 3- 2- [ 0/3, 13/1, 0, 0, 0, 0, 0, 0 ] and with 'nop': 0- 1- [ 9/4, 0, 0, 0, 0, 0, 0, 0 ] 1- 1- [ 3/3, 0, 0, 0, 0, 0, 0, 0 ] 2- 1- [ 6/3, 0, 0, 0, 0, 0, 0, 0 ] 3- 2- [ 0/3, 13/1, 0, 0, 0, 0, 0, 0 ] 4- 1- [ 14/3, 0, 0, 0, 0, 0, 0, 0 ] There's an easy chance you can beat DbfilenameShelf for your application. From alefnula at gmail.com Fri May 9 08:25:57 2008 From: alefnula at gmail.com (Viktor) Date: Fri, 9 May 2008 05:25:57 -0700 (PDT) Subject: Function creation (what happened?) Message-ID: <199c06d7-601c-49f3-a88c-c28f7283e619@25g2000hsx.googlegroups.com> Can somebody give me an explanation what happened here (or point me to some docs)? Code: HMMM = None def w(fn): print 'fn:', id(fn) HMMM = fn print 'HMMM:', id(HMMM) def wrapper(*v, **kw): fn(*v, **kw) wrapper.i = fn print 'wrapper:', id(wrapper) return wrapper class A: @w def __init__(self): pass print 'A.__init__:', id(A.__init__) print 'A.__init__.i:', id(A.__init__.i) print 'HMMM:', id(HMMM) Output: fn: 10404208 HMMM: 10404208 wrapper: 10404272 A.__init__: 10376136 A.__init__.i: 10404208 HMMM: 505264624 Why did HMMM changed his id?! From gherron at islandtraining.com Fri May 23 02:57:56 2008 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 22 May 2008 23:57:56 -0700 Subject: Calling class method by name passed in variable In-Reply-To: References: Message-ID: <48366AF4.7030106@islandtraining.com> Sagari wrote: > Greetings, > > Can someone suggest an efficient way of calling method whose name is > passed in a variable? > > Given something like: > > class X: > #... > def a(self): > # ... > > def b(self): > # ... > > #... > > x = X() > #... > v = 'a' > > How do I call the method of x whose name is stored in v? > Use getattr (stands for get attribute) to do this. fn = getattr(x, v) # Get the method named by v fn(...) # Call it Or in one line: getattr(x,v)(...) Gary Herron > PHP code for this would be: > > class X { > function a() { > } > } > > $x = new X(); > $v = 'a'; > $x->$v(); > > I need a solution for Python. Could you suggest anything? > > The task it to call a function whose name is taken from user-supplied > input. > > Thanks. > -- > http://mail.python.org/mailman/listinfo/python-list > From notbob at nothome.com Thu May 8 13:30:34 2008 From: notbob at nothome.com (notbob) Date: Thu, 08 May 2008 17:30:34 GMT Subject: How to kill Python interpreter from the command line? References: <10fdb79d-8ac2-4bf3-bbdc-a825ae2c44c8@l42g2000hsc.googlegroups.com> Message-ID: <_MGUj.53425$kl6.21975@fe103.usenetserver.com> On 2008-05-08, spectrumdt at gmail.com wrote: > I am running Fedora Linux and KDE, using the Konsole command line. I also run python from Konsole. > When coding Python, I regularly make a bug causing my program to not > terminate. But how do I kill the non-terminating Python interpreter > without killing the entire Konsole? Are you refering to the python editor? If so, try cntrl-d. > The default way of killing the current process on the command line is > Ctrl+C, but that doesn't work with Python. Neither do the "terminate > task", "suspend task" or "interrupt task" commands (available from > right-click in Konsole). If you want to completely kill python, open another Konsole session and kill it from there. There are several ways. The simplist is: killall python ....which will kill python without killing the Konsole session. This will find the python pid number and kill it with -15 which cleans everything up nicely before killing. If that doesn't work, you may need to use kill -9, which is kill with extreme prejudice and leaves all the bodies lying around to crap up the works. To do that, try: ps aux | grep python .....which will give you the pid number and then you plug it into: kill -9 pid_number If all that doesn't work, change to Slackware! ;) nb From nick at craig-wood.com Sat May 3 05:30:03 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Sat, 03 May 2008 04:30:03 -0500 Subject: Help with pyserial and sending binary data? References: Message-ID: Rich wrote: > I am working on a python library for sending and receiving data > from a Subaru's ECU (the fuel injection computer) via the OBD-II > port and an OBD to USB cable, with the Subaru Select Monitor > protocol. [snip] > So I've been messing with it, and in as few lines as possible, this > should in theory, send the init command to the ECU (0x80 0x10 0xF0 > 0x01 0xBF 0x40), and the ECU should return its ID to let you know > that you can now chat (something like 0x80 0xF0 0x10 0x39 0xFF 0xA2 > 0x10 0x0F 0x1B 0x14 0x40 0x05 0x05 0x73 0xFA 0xEB ......): > > #-------------------------- > import serial, string > output = " " > ser = serial.Serial('/dev/ttyUSB0', 4800, 8, 'N', 1, timeout=1) > ser.write(chr(0x80)+chr(0x10)+chr(0xF0)+chr(0x01)+chr(0xBF)+chr(0x40)) > while output != "": > output = ser.read() > print hex(ord(output)) > #-------------------------- The code looks OK. With a constructor which takes as many arguments as Serial does I tend to name them to avoid mistakes, eg serial.Serial("/dev/ttyUSB0", baudrate=4800, bytesize=8, parity='N', stopbits=1, timeout=1) 8N1 is documented as the default so you could then reduce it to the following if you wanted serial.Serial("/dev/ttyUSB0", baudrate=4800, timeout=1) > The only problem is that when I send the ECU init command, it just > echos back the data I sent it, which, from my understanding, means > that I sent an invalid request packet. My experience with these sort of protocols is that if you make a packet error (wrong address, wrong checksum, wrong start byte) you'll get no reply at all. If you make a command error (use a command that isn't understood in a valid packet) you'll get a properly formatted reply with an error message in. This should start 0x80 0xF0 0x10 .... (from and to reversed). I'd suspect that if you are just receiving the data back then you have got your serial cable wrong and have somehow looped tx and rx. Did you try your cable with the other programs? Or possibly you are using the wrong serial port - are you sure you haven't any other USB serials? ls /dev/ttyUSB* on a udev system will show you. lsusb (as root) is useful as is dmesg immediately after plugging the port in. I do a lot of this sort of thing at work (not with cars though with satellite equipment) and it is always the first packet and the first response which is the hard part. After that it is usually plain sailing! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From mnikhil at gmail.com Wed May 14 14:52:35 2008 From: mnikhil at gmail.com (Nikhil) Date: Thu, 15 May 2008 00:22:35 +0530 Subject: readlines with line number support? References: Message-ID: <482B34F3.20705@gmail.com> Arnaud Delobelle wrote: > Nikhil writes: > >> Hi, >> >> I am reading a file with readlines method of the filepointer object >> returned by the open function. Along with reading the lines, I also >> need to know which line number of the file is read in the loop >> everytime. >> I am sure, the line should have the property/attribute which will say >> the line number of the file. >> >> If there is none, do I have to end up using the counter in the loop? >> >> fp = open("file", "r") >> lineno = 0 >> for line in fp.readlines(): >> print "line number: " + lineno + ": " + line.rstrip() >> lineno = lineno + 1 > > The standard Python way is using enumerate() > > for i, line in enumerate(fp): > print "line number: " + lineno + ": " + line.rstrip() > Oh I did not know enumerate can be used. Thanks Paul and Arnaud. I will try this. From bronger at physik.rwth-aachen.de Wed May 21 12:59:34 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Wed, 21 May 2008 18:59:34 +0200 Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <20080514215943.14c92f16.johnjsal@NOSPAMgmail.com> <94bac166-d13c-44dd-af84-db19e19488b8@w1g2000prd.googlegroups.com> <8cfd3523-8d16-40bc-b904-94a6a36a414d@p25g2000pri.googlegroups.com> <48343e56$0$5866$426a74cc@news.free.fr> Message-ID: <87ej7voao9.fsf@physik.rwth-aachen.de> Hall?chen! Daniel Fetchinson writes: >>>> Or just: >>>> >>>> If command is "quit" ... >>> >>> Hmmm. In Flaming Thunder, I'm using "is" (and "is an", "is a", etc) >>> for assigning and checking types. For example, to read data from a >>> file and check for errors: >>> >>> Read data from "input.txt". >>> If data is an error then go to ... >> >> Arf ! A goto ! > > You are surely aware of the fact that the C source of python also uses > goto at tons of places. Is that Arf! too? In the hands of a skilled person who really knows what he/she does, it can be a useful statement. But this collides with the goals of FT, which claims to be simple to use. Besides, the above use case for a goto is definitively awful. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From deets at nospam.web.de Sun May 4 18:12:13 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 05 May 2008 00:12:13 +0200 Subject: Can I install Python 2.4 and 2.5 ? In-Reply-To: References: Message-ID: <686qm2F2ri0t9U1@mid.uni-berlin.de> adolfo schrieb: > I am reviewing various visualization programs (Scipy, PYGNL, etc) and > IDE?s. Some run on Python 2.4 others in 2.5. > > Can I have both installed at the same time if I don?t run them > concurrently? > > Now in Windows XP soon on Ubuntu 8 > > Appreciating your help, Yes you can. However you need to install 3rd-party-modules separately for each version - e.g. scipy - if you want to use them with both. Diez From mensanator at aol.com Thu May 8 13:24:40 2008 From: mensanator at aol.com (Mensanator) Date: Thu, 8 May 2008 10:24:40 -0700 (PDT) Subject: python newbie: some surprises References: <67b60370-bed9-4f43-b401-25ce2fd89522@t54g2000hsg.googlegroups.com> Message-ID: <64fb7f0f-c8fa-4324-8a13-f4e99082c470@p25g2000hsf.googlegroups.com> On May 8, 2:06?am, v4vijayakumar wrote: > When I started coding in python, these two things surprised me. > > 1. my code is inconsistently indented with the combination of tabs and > spaces. Even lines looked intended, but it is not. You must type inconsistently. I never had such a problem even when I used to use Notepad. > > 2. python requires to pass "self" to all instance methods Who uses methods? > > and I missed ":" often. :) Try using something like Seed7, where you have to use "then" with "if" and "do" with "while" and "end" in every block. Maybe you'll come to appreciate significant whitespace and ":". From thorsten at thorstenkampe.de Tue May 20 14:31:13 2008 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Tue, 20 May 2008 20:31:13 +0200 Subject: default gettext localedir on windows References: <6e4b1599-bdbd-4bb1-a104-1f2e8c66b33e@t12g2000prg.googlegroups.com> <0e7b13f0-649d-442d-ae6e-1df5d88663cd@b5g2000pri.googlegroups.com> Message-ID: * ZeeGeek (Tue, 20 May 2008 09:31:27 -0700 (PDT)) > On May 17, 8:39?pm, Thorsten Kampe wrote: > > * ZeeGeek (Sun, 4 May 2008 10:56:52 -0700 (PDT)) > > > On May 5, 1:16?am, Thorsten Kampe wrote: > > > > * ZeeGeek (Sun, 4 May 2008 08:59:05 -0700 (PDT)) > > > > > Hi, what's the default localedir for gettext module on windows? In > > > > > Linux, it's /usr/share/locale. Where should I put the *.mo file in > > > > > order to make the translation work? > > > > > > %PYTHONHOME%\share\locale > > > > > I tried moving the *.mo file into %PYTHONHOME%\share\locale\zh_CN > > > \LC_MESSAGES, but still no luck. The following is the code snippet I > > > use: > > > > > import gettext > > > gettext.install('testprogram', unicode = True) > > > > The syntax is correct. Is the test program localised under Linux or > > Cygwin? If not then the error is somewhere in your application. > > Yes, it's localized under linux. > > > How did you try to set the language on Windows? It works for me on Vista > > with "set LANG=de" or "set LANGUAGE=de" while I think under XP it had to > > be "set LANG=de_DE" (LANGUAGE or de alone did not work if I remember > > correctly). > > I'm using Simplified Chinese Windows, so I didn't set anything > specifically before firing up the program. I found that if I use > gettext.GNUTranslations to read in the .mo file, then it's localized. > But gettext.install doesn't work. Well, then why don't you set the environment variable for testing!? T. From pataphor at gmail.com Thu May 22 08:58:41 2008 From: pataphor at gmail.com (pataphor) Date: Thu, 22 May 2008 14:58:41 +0200 Subject: "indexed properties"... References: <7sm234hp8u9ia850uaopn3amtq95jqbt5t@4ax.com> <20080519144803.14d3569a@hyperspace> <2la534p1h4g7lke3lq3tji06q6cm32v7b0@4ax.com> <20080520154802.4b5df647@hyperspace> <20080521124744.17546846@outerspace> <7sla341agcpd1729k5pa0e0hern05qtv22@4ax.com> Message-ID: <20080522145841.7c9e8133@hyperspace> On Thu, 22 May 2008 06:26:41 -0500 David C. Ullrich wrote: > On Wed, 21 May 2008 12:47:44 +0200, pataphor > wrote: > >Using the trick of encapsulating the values inside single-element > >lists one can make a transposition of the matrix and get > >synchronicity for the little price of doubling the number of > >instances. Since the views share the data this is a lot less > >expensive than one would think. One can use the row view or the > >column view to alter data and the changes will automatically be > >visible in the other view, since the views update the same lists. > > Oh - that's different. This is not what I thought you had in mind > (it's not what I had in mind in the thing I called a joke.) The idea has two parts, the first part is to create two views and the second part is to somehow synchronize the data. To make both views update the same data is just not a very lazy synchronization procedure. Does it even have to be a list? Let's see ... No, this works as well: class Shared(object): def __init__(self,value=None): self.value = value class Storage(ListMixin): def __init__(self, seq=[]): self.L = map(Shared,seq) def _constructor(self, iterable): return Storage(iterable) def __len__(self): return len(self.L) def _get_element(self, i): assert 0 <= i < len(self) return self.L[i].value def _set_element(self, i, x): assert 0 <= i < len(self) self.L[i].value = x def _resize_region(self, start, end, new_size): assert 0 <= start <= len(self) assert 0 <= end <= len(self) assert start <= end self.L[start:end] = [Shared() for i in range(new_size)] > > def _constructor(self, iterable): > > return Storage(iterable) > > Probably I'm just being dense. Why does > _constructor exist? (Oh - looking at things > below, I imagine it's something to do with > ListMixin.) I just filled in the example class. It was very handy, one can make changes very quickly because all the functionality is in a few lines of code. P. From jcd at sdf.lonestar.org Thu May 22 14:30:06 2008 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Thu, 22 May 2008 14:30:06 -0400 Subject: import X vs from x import * In-Reply-To: References: Message-ID: <1211481006.12177.7.camel@aalcdl07.lib.unc.edu> On Thu, 2008-05-22 at 10:44 -0700, notnorwegian at yahoo.se wrote: > import Tkinter > from Tkinter import * > > i have a program where if i comment out either of those import- > statements i get an error. > > i thought they meant the same thing and from was supposed to be just > to imort just a specific function and the * imports everything in the > module. > but aparently the above statements have diffrent meaning and i cant > figure it out fromt he tutorials. > -- > http://mail.python.org/mailman/listinfo/python-list > Others have explained what one statement does as opposed to the other. In general, you do not want to use from x import *. Your namespace gets polluted with all sorts of variables, and you don't know if you're going to overwrite something important. It's much better to specify which names you want to import (for the sake of those reading your code later, and for the sake of future-proofing your code against new variables finding their way into the module being imported from), or just to import the package (and optionally assign it to a shorter alias) import Tkinter as tk tk.function() That said, there are occasional packages where it is common practice to import *. Tkinter might be one of those. I don't have any experience with it. But don't make a habit of it. :) Cheers, Cliff From fuzzyman at gmail.com Sun May 18 17:25:38 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Sun, 18 May 2008 14:25:38 -0700 (PDT) Subject: about python References: Message-ID: On Apr 23, 3:50?am, mran... at varshyl.com wrote: > How can python execute in browser? > > Mukul The best way of running Python code in the browser is with the Silverlight browser plugin. Silverlight 2 (currently working with IE, Safari and Firefoxon Windows and Mac OS X - but Silveright 2 for Linux, called Moonlight, made major steps in the last few days). You can run IronPython code inside Silverlight, with the choice of the WPF based user interface or interacting with the browser DOM and Javascript. See the following for more details: http://www.voidspace.org.uk/ironpython/silverlight/ Michael Foord http://www.ironpythoninaction.com/ From gagsl-py2 at yahoo.com.ar Tue May 20 18:12:19 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 20 May 2008 19:12:19 -0300 Subject: What's wrong with that comment? References: Message-ID: En Tue, 20 May 2008 16:22:10 -0300, Joe P. Cool escribi?: > Ludwig Miniatur wrote: >> For example: >> #!/usr/bin/env python >> >> from parser import suite, ast2list >> fh = file(__file__) >> s = fh.read() >> fh.close() >> ast = suite(s) >> >> while False: >> print "hello world" >> # comment >> >> Looks like a little bug in parser; but what I don't understand is that >> I thought parser was build with the current syntax of python. > > I didn't read the grammar but I assume that Python grammar requires a > comment to have the form #.*. >> >> So, why can python run the script (an it can if you comment out the >> line "ast = suite(s)") but parser can't? > > The interpreter probably appends a newline after the input stream as a > friendly service :) Something like that. The last line of source *must* end in a newline (be it a comment or not); this is a known limitation. See py_compile.py for an example. -- Gabriel Genellina From mensanator at aol.com Fri May 30 11:41:16 2008 From: mensanator at aol.com (Mensanator) Date: Fri, 30 May 2008 08:41:16 -0700 (PDT) Subject: How to covert ASCII to integer in Python? References: Message-ID: <45f694b7-8c2c-4548-b6e8-42a12e96e0d4@d77g2000hsb.googlegroups.com> On May 30, 10:03?am, Philipp Pagel wrote: > Skonieczny, Chris wrote: > > YOU SHOULD REMOVE or CORRECT YOUR POST here: > >http://mail.python.org/pipermail/python-list/2007-February/427841.html? > > > It is not true - eg. try : > > a='P' ? ? ? ? ? ?# P is ASCII , isn't it ? > > b=int(a) > > and what you will get ? An error !!! > > 'P' is obviously not an ASCII representation of a number. It is in base 36. >>> a='P' >>> b=int(a,36) >>> b 25 > What did you expect? The closest number by visual appearance? > > cu > ? ? ? ? Philipp > > -- > Dr. Philipp Pagel > Lehrstuhl f. Genomorientierte Bioinformatik > Technische Universit?t M?nchenhttp://mips.gsf.de/staff/pagel From upton at virginia.edu Wed May 21 19:30:27 2008 From: upton at virginia.edu (Dan Upton) Date: Wed, 21 May 2008 19:30:27 -0400 Subject: Python and Flaming Thunder In-Reply-To: References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <7ee5dffd-df8f-46f0-bd78-c81ac0418a9a@d77g2000hsb.googlegroups.com> <65ef773e-a1c3-4adb-a18b-e8b8451efe5e@b5g2000pri.googlegroups.com> <68trmmF2vjivnU1@mid.uni-berlin.de> <68tuhfF2unducU1@mid.uni-berlin.de> <8b9560fa-7f29-4bfe-b312-e3da0e3779b6@z24g2000prf.googlegroups.com> <68u1avF2ujou9U1@mid.uni-berlin.de> Message-ID: <5504f9ac0805211630i1475aa16i340394ffd5c7f700@mail.gmail.com> On Wed, May 21, 2008 at 5:27 PM, Fuzzyman wrote: > On May 14, 10:30 pm, "bruno.desthuilli... at gmail.com" > wrote: >> > Dave Parker schrieb: >> > > All of the calculators and textbooks that elementary school students >> > > use, use "^" for powers. >> >> I've never seen this symbol in textbooks. In textbooks, powers are >> written using superscript. >> >> >> Just like Flaming Thunder does. I haven't >> > > seen "**" for powers since FORTRAN. >> >> I haven't seen any language using '^' as the power operator so far - >> but I've seen quite a lot of them using it as the bitwise XOR operator. > > > Excel uses the caret as the power operator. Arguably the worlds most > widely used programming environment... > I think BASIC did, too. I know I used to use it in some language and was confused when I first tried to use it in Java and didn't get what I was expecting. ("Some language" must be in the set (BASIC, C, Logo).) From alex.m.gusarov at gmail.com Thu May 29 03:50:19 2008 From: alex.m.gusarov at gmail.com (Alex Gusarov) Date: Thu, 29 May 2008 14:50:19 +0700 Subject: Struct usages in Python In-Reply-To: References: <1211985562.3335.18.camel@aalcdl07.lib.unc.edu> Message-ID: > Yes. That is the somewhat unfortunate difference between new-style and old-style classes. > Use new-style if you can, and that means that "object" must be part of the inheritance graph. ... > You are wrong for Python 2.X, but right for Python 3 where old-style > > classes are gone for good. Thanks, I don't knew it before and it's a sensitive information for me. -- Best regards, Alex Gusarov From kyosohma at gmail.com Tue May 27 10:05:32 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 27 May 2008 07:05:32 -0700 (PDT) Subject: Problems with Python IDLE References: <2fc399e1-3cf3-43fa-ad95-55bc06b62ea1@e53g2000hsa.googlegroups.com> Message-ID: On May 27, 3:54?am, Giraffe wrote: > I have the followong class in a file: > -------------------------------------------- > class someClass: > ? ?def __init__ (self): > ? ? ? self.someVar = 10 > > ? ?def getSomeVar (self): > ? ? ? return self.someVar > -------------------------------------------- > > In another file a do the following: > -------------------------------------------- > tmp = someClass () > tmp.getSomeVar () > -------------------------------------------- > > I run the second file in the IDLE environment and everything seems to > be working fine until I start to modify in the first file: > -------------------------------------------- > class someClass: > ? ?def __init__ (self): > ? ? ? self.someVar = 10 > > ? ?def getSomeVar (self): > ? ? ? print "Modified class!" > ? ? ? return self.someVar > ------------------------------------------- > > When I now try to run the second file in the IDLE environment again, I > DO NOT get the newly added printout. I have saved and compiled (run) > both files but there is still no change. What have I missed? You might also look into the reload(module) function, documented here: http://docs.python.org/lib/built-in-funcs.html It's made for that sort of thing. Mike From stanc at al.com.au Fri May 2 05:40:15 2008 From: stanc at al.com.au (Astan Chee) Date: Fri, 02 May 2008 19:40:15 +1000 Subject: get number that is raised to the power of In-Reply-To: <97C60C67-80CC-4AF6-A7EF-2B98F618A870@rgbaz.eu> References: <481ADC8B.20000@al.com.au> <97C60C67-80CC-4AF6-A7EF-2B98F618A870@rgbaz.eu> Message-ID: <481AE17F.7070503@al.com.au> Python.Arno wrote: > the "reverse" of a power to is logarithm > so v = 10**n <=> math.log(v,10) = n > > Arno > Im so ashamed of myself for not thinking in logs. I must be dreaming again. Thanks for the help. -- "Formulations of number theory: Complete, Consistent, Non-trivial. Choose two." Animal Logic http://www.animallogic.com Please think of the environment before printing this email. This email and any attachments may be confidential and/or privileged. If you are not the intended recipient of this email, you must not disclose or use the information contained in it. Please notify the sender immediately and delete this document if you have received it in error. We do not guarantee this email is error or virus free. From arnodel at googlemail.com Thu May 15 07:09:53 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Thu, 15 May 2008 04:09:53 -0700 (PDT) Subject: Class Methods Vs Any Other Callable References: <98b4a67c-9ec7-407c-8c80-06488bd48a68@e39g2000hsf.googlegroups.com> <690ap7F2u0ftdU1@mid.uni-berlin.de> <238061d6-9423-44c1-90b2-cc09f392db9b@p25g2000hsf.googlegroups.com> <2851a281-d3f2-46c5-8afe-a5dcd6fa31a6@59g2000hsb.googlegroups.com> Message-ID: <10cce8be-657c-4c40-9705-baebaf90301b@a70g2000hsh.googlegroups.com> bruno.desthuilliers at gmail.com wrote: > On 14 mai, 22:44, Arnaud Delobelle wrote: > > "bruno.desthuilli... at gmail.com" writes: > > > On 14 mai, 19:45, Arnaud Delobelle wrote: > > >> __new__ is a static method! > > > > > __new__ is a special-cased staticmethod that 1/ must not be declared > > > as such and 2/ takes the class object as first args. As far as I'm > > > concerned, it's semantically a classmethod. > > > > It's a static method! > OK then let me reply pedantically: > Sorry Arnaud, I probably didn't made it clear enough : I do know it is > a staticmethod object. What I say is that > 1/ it's special-cased since you don't *explicitely* declare it as a > staticmethod In some cases you have to: class Foo(object): pass # Later on I want to redefine Foo.__new__ @staticmethod def Foo__new__(cls): print "new Foo!" return object.__new__(cls) Foo.__new__ = Foo__new__ >>> Foo() New Foo! >>> # Without the @staticmethod we would get a TypeError > 2/ it behaves just like a classmethod, since it takes the class as > first argument. When you invoke it implicitely maybe, but not when you do so explicitely! Look at my example below: to create my Foo object, I have to write object.__new__(Foo) > IOW, I'm talking about semantic, not implementation. I understand what you mean, and from that point of view you can argue against my example above (after all, my example is code, not pure concept) but for me it is simpler to think of __new__ as a staticmethod (which it is!), plain and simple. -- Arnaud From Russ.Paielli at gmail.com Mon May 26 23:10:29 2008 From: Russ.Paielli at gmail.com (Russ P.) Date: Mon, 26 May 2008 20:10:29 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <8763t3by81.fsf@benfinney.id.au> <09847cfc-eaec-4adc-8cbf-1e2ebbf940c4@m44g2000hsc.googlegroups.com> <039f3c2d-4ebb-4412-9cbf-458afa412c4e@i36g2000prf.googlegroups.com> Message-ID: <03655ec7-2136-4cea-9575-34e321356439@p25g2000pri.googlegroups.com> On May 26, 4:23 pm, "Gabriel Genellina" wrote: > To make things clear: _variables ARE visible when you import a module: > > C:\TEMP>type module.py > _variable = 123 > > (invoke python) > py> import module > py> module._variable > 123 > py> dir(module) > ['__builtins__', '__doc__', '__file__', '__name__', '_variable'] > py> > py> from module import _variable > py> _variable > 123 > > Only when you use "from module import *" _variable isn't imported. > (new python session): > > py> from module import * > py> _variable > Traceback (most recent call last): > File "", line 1, in > NameError: name '_variable' is not defined Hmmm... that seems a bit strange. Why should "_variable" be visible when you use "import module" but not when you use "from module import *"? > That last form should not be used normally, except when playing with the > interactive interpreter. OK, I have a confession to make. I use "from module import *" almost exclusively. But then, I'm different from most folks. I can drink six beers and still drive safely, for example. The key is to drive faster so I can get past dangerous situations quicker. From max at alcyone.com Sat May 3 17:31:33 2008 From: max at alcyone.com (Erik Max Francis) Date: Sat, 03 May 2008 14:31:33 -0700 Subject: Feature suggestion: sum() ought to use a compensated summation algorithm In-Reply-To: <87fxszrscz.fsf@physik.rwth-aachen.de> References: <481CB283.107@gmail.com> <8oudncYY4Mi1SoHVnZ2dnUVZ_rzinZ2d@speakeasy.net> <87fxszrscz.fsf@physik.rwth-aachen.de> Message-ID: Torsten Bronger wrote: > No, the above expression should yield ''+'abc'+'efg', look for the > signature of sum in the docs. You're absolutely right, I misread it. Sorry about that. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis From deets at nospam.web.de Sun May 25 07:40:47 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 25 May 2008 13:40:47 +0200 Subject: Python, Daemons and D-Bus In-Reply-To: <24f7b472-0a87-487d-9a7d-8706a546c54d@p39g2000prm.googlegroups.com> References: <739ea057-0839-4836-bbf9-6f9538f6eeaf@s21g2000prm.googlegroups.com> <24f7b472-0a87-487d-9a7d-8706a546c54d@p39g2000prm.googlegroups.com> Message-ID: <69t1i1F33b3ncU1@mid.uni-berlin.de> PurpleServerMonkey schrieb: > On May 25, 5:46 am, Sebastian 'lunar' Wiesner > wrote: >> [ PurpleServerMonkey ] >> >>> Would you use D-Bus or a more traditional IPC method such as sockets? >>> Although D-Bus is relatively new it looks interesting, just not sure >>> it would work well in this kind of project. >> DBus is not really intended for private communication between processes of >> the same application, but more for intercommunication between different >> applications. If the IPC interface of your backend daemons is intended to >> be used by other applications, DBus is the right choice, otherwise I would >> choose something different. >> >> The reason is, that DBus doesn't know about applications. It exposes all >> objects registered on the bus to every DBus client on the system and so >> makes you application-private API available to the public (and spams the >> bus with lots of generally useless objects ;) ). >> >> In case your IPC interface is application private, a custom IPC protocol >> (probably using XML RPC over unix sockets) is better suited. >> >> Moreover you should make your choice dependent on the type of data you >> transmit. Both DBus and XML-RPC wrap calls into XML messages, which is >> terribly inefficient for large binary data. >> >> -- >> Freedom is always the freedom of dissenters. >> (Rosa Luxemburg) > > Thanks Sebastian, > > Your comments make a lot of sense. I was thinking of creating a custom > session channel and using that for my purposes but as you mentioned > it's not very secure and I do want to keep the server to daemon > traffic private, the server has an XML-RPC interface with a public > API. > > Will definitely look at using a different IPC mechanism for this part > of the project. If you can - use Pyro. It is easy, fast and can be made secure using SSL AFAIK. Diez From afilash+python at gmail.com Wed May 21 12:54:55 2008 From: afilash+python at gmail.com (abhilash pp) Date: Wed, 21 May 2008 22:24:55 +0530 Subject: can someone with guessing a number In-Reply-To: <005101c8bb61$b78fb710$1300a8c0@Home> References: <005101c8bb61$b78fb710$1300a8c0@Home> Message-ID: <9f9d35df0805210954g5b2bb7bye48cf835b413069f@mail.gmail.com> if tries > 10: print 'you failed- give up' On Wed, May 21, 2008 at 10:12 PM, garywood wrote: > I would just like the program to exit after guessing the amount of > numbers wrong > > # Guess My Number > import random > the_number = random.randrange(100) + 1 > tries = 1 > # guessing loop > while (guess != the_number): > if (guess > the_number): > print "Lower..." > else: > print "Higher..." > > guess = int(raw_input("Take a guess: ")) > tries += 1 > if tries > 10: > print 'you failed- give up' > > print "You guessed it! The number was", the_number > print "And it only took you", tries, "tries!\n" > > raw_input("\n\nPress the enter key to exit.") > > many Thanks > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ppr.vitaly at gmail.com Thu May 29 06:14:07 2008 From: ppr.vitaly at gmail.com (Vitaliy) Date: Thu, 29 May 2008 03:14:07 -0700 (PDT) Subject: Error: Cannot convert Decimal("0.0000") to Decimal Message-ID: <32b8c8c0-e567-477f-9495-56e38ec2b2c1@e53g2000hsa.googlegroups.com> Hi I got this wired exception periodically (Python 2.5, Django based application) what does it mean ? From aisaac at american.edu Thu May 29 16:26:15 2008 From: aisaac at american.edu (Alan Isaac) Date: Thu, 29 May 2008 20:26:15 GMT Subject: should I put old or new style classes in my book? In-Reply-To: References: Message-ID: This thread raises two questions for me. 1. I take it from this thread that in Python 3 the following are equivalent: class Test: pass class Test(object): pass Is that correct, and if so, where is it stated explicitly? (I know about the "all classes are new style classes" statement.) 2. I take it from this thread that in Python 2.2+ if I put the following at the top of a module :: __metaclass__ = type then all the classes defined in that module will be newstyle classes. Is that correct? Somehow I did not grok that from but it seems right. Thank you, Alan Isaac From mszpadzik at gmail.com Thu May 29 15:01:30 2008 From: mszpadzik at gmail.com (Mike) Date: Thu, 29 May 2008 12:01:30 -0700 (PDT) Subject: Python threads and memory usage Message-ID: Hi, I'm writing client-server application in Python. It's monitoring system, where server listen and waits for TCP connections, and every connection takes own thread. Every thread puts data from clients to Queue and exits. Then there is one DB loader thread, which loads all data from Queue to MySQL DB. I observed, that every thread reserved some memory, and after exit thread doesn't freed it. When i leaved my server working for 3 days, then it takes 15% of 512MB memory (during that time about 15000 threads were created and stopped). When server starts it only takes about 1% of memory. I know that I can made client which connects once and keep this session with server thread all time (it should resolve my problems), but I'm curious if this is normal or it is something like memory leak. Or maybe I'm doing something wrong :) If You need I can paste all my code. Regards From arnodel at googlemail.com Wed May 7 14:21:12 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 07 May 2008 19:21:12 +0100 Subject: Idea for P3K References: <4821d418$0$932$ba4acef3@news.orange.fr> Message-ID: "M?ta-MCI (MVP)" writes: > Hi! > > print become a function ; OK > > I thought: and why the affection (=) would not become, also, a function? > Examples: > a = 123 return 123 > b,c = 543.21, "LOL" return (543.21, "LOL") Do you mean a = 3 would become an *expression* ? For one thing, it wouldn't fit with the Python's function call syntax: f(4, x=2) currently means that f is called with first positional argument equal to 4 and named argument 'x' equal to 2. Moreover, it seems to me utterly unpythonic (and I don't often feel like using this word!). Binding a name to a new value is something that needs to be clearly visible in the code flow, not hidden within an expression E.g. f(3, 4 + (x=2), 5) has the side-effect that x is now bound to 2, but it is only apparent if one closely scrutinises the code. -- Arnaud From marc at stopspam.goldak.ca Wed May 28 13:28:40 2008 From: marc at stopspam.goldak.ca (Marc Pelletier) Date: Wed, 28 May 2008 12:28:40 -0500 Subject: graphical ide?? References: Message-ID: "Gabriel Genellina" wrote in news:mailman.1632.1211848522.12834.python-list at python.org: > I'm unsure if you're looking for a development environment like these: > http://wiki.python.org/moin/IntegratedDevelopmentEnvironments > or an interface designer for wxPython (see the bottom part of > http://wiki.python.org/moin/GuiProgramming) > > Thanks Gabriel and others, I found these links useful and also followed a trail to something I thought was called "Python pit", which was very good, but I can't find it now. Most of the tools seem to be for creating and serializing the dialogs to xml or other, which will work fine, but unfortunately isn't what the previous developer on the project did. So I guess I'll have to continue with it manually. cheers Marc From ewertman at gmail.com Thu May 8 22:04:00 2008 From: ewertman at gmail.com (Eric Wertman) Date: Thu, 8 May 2008 22:04:00 -0400 Subject: How can I add spaces where ever I have capital letters? In-Reply-To: <4878ad7b0805081812l2a3412abh185a832866be2878@mail.gmail.com> References: <4878ad7b0805081812l2a3412abh185a832866be2878@mail.gmail.com> Message-ID: <92da89760805081904v2927bf73tc28c55415c405a4d@mail.gmail.com> Something like this. I'm sure there are other ways to do it. import re def addspace(m) : return ' ' + m.group(0) strng = "ModeCommand" newstr = re.sub('[A-Z]',addspace,strng) print newstr.strip() On Thu, May 8, 2008 at 9:12 PM, John Schroeder wrote: > I have a string (which I got from the names of my classes) and I would like > to print out my CamelCase classes as titles. > > I would like it to do this: > >>>> my_class_name = "ModeCommand" > ## Do some magic here >>>> my_class_name > 'Mode Command' > > Anyone know any easy way to do this? Thanks. > > -- > http://mail.python.org/mailman/listinfo/python-list > From larzluv at hotmail.com Sun May 11 21:43:18 2008 From: larzluv at hotmail.com (Larry Hale) Date: Sun, 11 May 2008 18:43:18 -0700 (PDT) Subject: Orlando Florida Python Tutor Needed References: <7ce42a69-8c6b-435b-a125-2a619b3a8603@k13g2000hse.googlegroups.com> Message-ID: On May 10, 11:42 am, vbgunz wrote: > I will pay anyone for a face-to-face tutoring in the Orlando Florida > area. I will pay $20.00 per hour (minimum 2 hours needed). What I need > are lessons in Decorators and Class methods. If I can walk away with > at least 5 lessons taught in both subjects I will be happy to offer an > additional $20.00. > > If you are interested in this offer feel free to either reply through > email OR here on this thread. There are no string attached, catches, > etc. I need to learn and if you can teach well, I will be happy to > learn. > > Best Regards > Victor B. Gonzalez I know you're looking for "one-on-one" help, direction, and/or tutelage, but since you've not received an answer (yet), here's some general info... --- For Class Methods, perhaps you could mention more of what you need to know? Otherwise, generically see: http://docs.python.org/tut/node11.html#SECTION0011340000000000000000 http://www.geocities.com/foetsch/python/new_style_classes.htm http://www.diveintopython.org/object_oriented_framework/defining_classes.html and obviously http://www.google.com/search?hl=en&q=python+class+methods&btnG=Google+Search --- For Decorators, have a gander at: http://www.ddj.com/web-development/184406073;jsessionid=QCNTPTSNXZP2WQSNDLPCKHSCJUNN2JVN?_requestid=749134 http://www.ibm.com/developerworks/linux/library/l-cpdecor.html and obviously http://www.google.com/search?hl=en&q=python+decorators&btnG=Google+Search Decorators are still rather new to -me-, and I've yet to "need" 'em, but they _seem_ like a handy feature. (Personally, I don't care too much for the syntax, but other than explicitly DOING what they do, which would be [1] messier and/or [2] non-transparent/duplicative, I sadly have no alternative thought[s]... ;) ) Cheers, -Larry Hale From Scott.Daniels at Acm.Org Sun May 18 00:25:06 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 17 May 2008 21:25:06 -0700 Subject: can't delete from a dictionary in a loop In-Reply-To: References: <482DFF63.7020701@islandtraining.com> Message-ID: Eduardo O. Padoan wrote: > On Fri, May 16, 2008 at 6:40 PM, Gary Herron wrote: >> bruno.desthuilliers at gmail.com wrote: >>> On 16 mai, 23:28, Hans Nowak wrote: >>> >>>> Dan Upton wrote: <> >>>> ...to solve the immediate problem: >>>> for pid in procs_dict.keys(): >> And then, in Python3, keys() produces something else altogether (call a view >> of the dictionary) which would provoke the same problem, so yet another >> solution would have to be found then. > In Python 3.0, list(procs_dict.keys()) would have the same effect. Or (simpler in either 3.0 or 2.X): for pid in list(procs_dict): ... --Scott David Daniels Scott.Daniels at Acm.Org From mrkmuthuraman at gmail.com Tue May 6 21:28:56 2008 From: mrkmuthuraman at gmail.com (fashion girl) Date: Tue, 6 May 2008 18:28:56 -0700 (PDT) Subject: The worlds largest FREE jobs and resume database! Message-ID: The worlds largest FREE jobs and resume database! Employers search resumes and post jobs FREE. Jobseekers post resumes and search jobs FREE. http://www.freewebs.com/eeyes/ From paul at boddie.org.uk Wed May 7 18:52:25 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 7 May 2008 15:52:25 -0700 (PDT) Subject: License selection for free software References: <3a8e0a8f-3bd1-4650-9104-5c273f14b097@w7g2000hsa.googlegroups.com> <1w4gs9bk.fsf@gmail.com> <87ve1se6q5.fsf_-_@benfinney.id.au> <8763tr5ov1.fsf@gmail.com> <6b46e4e9-4c71-47b7-aac8-3d3340b61b64@26g2000hsk.googlegroups.com> <3aoudmza.fsf@gmail.com> Message-ID: <7e675421-4f06-4f18-a2c7-5d1b083c0fc0@25g2000hsx.googlegroups.com> On 7 Mai, 19:48, vivai... at gmail.com (Ville M. Vainio) wrote: > Paul Boddie writes: > > original licence as well. Now, I did leave a fair amount of > > information about the heritage of the code, so that anyone who is > > scared of the LGPL could just go and get the original work, but that > > I doubt anyone is really afraid of LGPL. The only problem with LGPL is > that of static vs. dynamic linking, and that is only a problem in > platforms without dynamic linker (rarity these days). The wxWindows, erm, wxWidgets people seemed to be worried enough to neuter the licence, making the result a somewhat bizarre creation. > > You can almost never just "grab the code from somewhere without having > > to think about [the] license" since even permissive licences typically > > have a list of conditions that must be observed. Certainly, they > > Yeah, but you don't have to "worry" about license - just have the > license text in source code, or a text file in binary distribution. Yes, but you are still having to think about the licence: if it were public domain code (and provably so, opening up another discussion entirely) then you wouldn't need to think twice about doing whatever you wanted with the code. I accept that with the GPL, you're obliged to think about what you're going to need to do with the source, but in licences like the modified BSD licence, the FreeBSD licence or the X11 licence, that text file in the binary distribution is quite possibly something that some people might overlook. There are other things that could trip people up, of course: non- endorsement clauses, required notices of modifications, patent retaliation clauses, and so on. All these do feature in permissive licences. Paul From daveparker at flamingthunder.com Mon May 12 19:39:25 2008 From: daveparker at flamingthunder.com (Dave Parker) Date: Mon, 12 May 2008 16:39:25 -0700 (PDT) Subject: Python and Flaming Thunder Message-ID: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> I've read that one of the design goals of Python was to create an easy- to-use English-like language. That's also one of the design goals of Flaming Thunder at http://www.flamingthunder.com/ , which has proven easy enough for even elementary school students, even though it is designed for scientists, mathematicians and engineers. From needin4mation at gmail.com Thu May 1 17:25:11 2008 From: needin4mation at gmail.com (jmDesktop) Date: Thu, 1 May 2008 14:25:11 -0700 (PDT) Subject: where do I begin with web programming in python? Message-ID: <37ea096e-cf3e-4932-8370-306a15a2aebd@25g2000hsx.googlegroups.com> I have been to the main python site, but am still confused. I have been using .net, so it may be obvious how to do this to everyone else. I am aware there are various frameworks (Django, Pylons, etc.), but I would like to know how to create web pages without these. If I have mod_python or fastcgi on apache, where do I start? I don't have clue where to begin to create a web page from scratch in python. I am sure I will want to access database, etc., all the "normal" stuff, I just want to do it myself as opposed to the frameworks, for learning. Thank you for any help. From matthieu.brucher at gmail.com Fri May 30 04:33:23 2008 From: matthieu.brucher at gmail.com (Matthieu Brucher) Date: Fri, 30 May 2008 10:33:23 +0200 Subject: should I put old or new style classes in my book? In-Reply-To: References: Message-ID: 2008/5/29 Alan Isaac : > This thread raises two questions for me. > > > > 1. I take it from this thread that in Python 3 the > > following are equivalent: > > > > class Test: pass > > > > class Test(object): pass > > > > Is that correct, and if so, where is it stated explicitly? > > (I know about the "all classes are new style classes" statement.) > All classes are new style classes, and the usual class MyClass(object) pass should be replaced by the first class MyClass: pass IIRC. I don't know ATM where I read it. Matthieu -- French PhD student Website : http://matthieu-brucher.developpez.com/ Blogs : http://matt.eifelle.com and http://blog.developpez.com/?blog=92 LinkedIn : http://www.linkedin.com/in/matthieubrucher -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Mon May 12 11:29:51 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 12 May 2008 17:29:51 +0200 Subject: buffering choking sys.stdin.readlines() ? In-Reply-To: References: Message-ID: <68r63qF2s4ksaU1@mid.uni-berlin.de> cshirky schrieb: > Newbie question: > > I'm trying to turn a large XML file (~7G compressed) into a YAML file, > and my program seems to be buffering the input. > > IOtest.py is just > > import sys > for line in sys.stdin.readlines(): > print line > > but when I run > > $ gzcat bigXMLfile.gz | IOtest.py > > but it hangs then dies. > > The goal of the program is to build a YAML file with print statements, > rather than building a gigantic nested dictionary, but I am obviously > doing something wrong in passing input through without buffering. Any > advice gratefully fielded. readlines() reads all of the file into the memory. Try using xreadlines, the generator-version, instead. And I'm not 100% sure, but I *think* doing for line in sys.stdin: ... does exactly that. Diez From http Wed May 7 02:06:41 2008 From: http (Paul Rubin) Date: 06 May 2008 23:06:41 -0700 Subject: ]ANN[ Vellum 0.16: Lots Of Documentation and Watching References: Message-ID: <7xy76md4we.fsf@ruckus.brouhaha.com> "Zed A. Shaw" writes: > How do people feel about Vellum's GPLv3 status? I'm certainly in favor of it, though I didn't notice this question until it spawned its own thread, and I'm not currently a Vellum user or developer, so maybe my view shouldn't count for much. From phd at phd.pp.ru Sun May 4 10:18:13 2008 From: phd at phd.pp.ru (Oleg Broytmann) Date: Sun, 4 May 2008 18:18:13 +0400 Subject: SQLObject 0.10.1 Message-ID: <20080504141813.GD3097@phd.pp.ru> Hello! I'm pleased to announce version 0.10.1, a bugfix release of 0.10 branch of SQLObject. What is SQLObject ================= SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, Firebird, Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject ================== Site: http://sqlobject.org Development: http://sqlobject.org/devel/ Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.10.1 News and changes: http://sqlobject.org/News.html What's New ========== News since 0.10.0 ----------------- Bug Fixes ~~~~~~~~~ * Fixed a bug: limit doesn't work in sqlbuilder.Select. * A bug in inheritable delColumn() that doesn't remove properties was fixed. * A minor bug was fixed in col.py - the registry must be passed to findClass(). * Reverted the patch declarative.threadSafeMethod() - it causes more harm then good. For a more complete list, please see the news: http://sqlobject.org/News.html Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From jstucklex at attglobal.net Thu May 22 23:09:34 2008 From: jstucklex at attglobal.net (Jerry Stuckle) Date: Thu, 22 May 2008 23:09:34 -0400 Subject: php vs python In-Reply-To: References: <5l%Yj.77$mz3.53@fe101.usenetserver.com> Message-ID: inhahe wrote: > I don't like php. I tried it once and I had it sort a list, but the list > was apparently too long for its sorting function because it just sorted the > first so-many elements of it and left the rest in order, and didn't generate > any error. I like a language that's actually determined by what you tell it > to do. Then I suspect you had an error in your code. PHP's sort functions work fine. > I hear it has a lot of security issues too. The language has no security issues. Programmers have security issues - whether it be PHP, Python or any other language. > I'm not sure that php > *runs* faster than python, having seen benchmarks, but it certainly loads > faster. Maybe not so much of a difference once python25.dll is already in > the cache though (speaking from a windows perspective). because when i load > a program it can take a while but it's pretty quick if i'd just loaded one > recently. but you don't necessarily have to load python for each page > rendering anyway. > > I like the Python language a lot better than php. but I just really like > Python. > I like PHP much better than Python. To each their own. > php mixes html and code out-of-the-box (sort of.. i guess it's more like a > reversal of which one is explicit)... if you use Python you should look into > a 'templating engine' like mako. i use cheetah, but mako is supposed to be > better. > PHP can do that. There are also a number of templating engines available. The nice thing about PHP is you have a choice. > i think Python is the easiest language to learn, with the possible exception > of qbasic (just because making multidimensional arrays in python isnt that > obvious, although maybe it is using numpy, i've never tried it). Python > isn't as easy as basic if you use/have to read the more advanced features, > but those aren't even available in basic. so I find it a comfortable > learning curve. > > I found PHP easier to learn than Python. But that may be because I already have a strong C/C++ background. There isn't anything wrong with Python. I just prefer PHP. -- ================== Remove the "x" from my email address Jerry Stuckle JDS Computer Training Corp. jstucklex at attglobal.net ================== From apardon at forel.vub.ac.be Thu May 29 04:14:49 2008 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 29 May 2008 08:14:49 GMT Subject: unittest: Calling tests in liner number order References: Message-ID: On 2008-05-24, Fuzzyman wrote: > > A worthwhile question for the OP - your patch seems fairly simple. Is > it easy for you to extend unittest for your own testing needs by > subclassing? I've been ill the last days, but I will look into this possibility. -- Antoon Pardon From deets at nospam.web.de Mon May 19 06:01:56 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 19 May 2008 12:01:56 +0200 Subject: "Disabling" raw string to print newlines References: <7f63b5e9-e0d6-4505-9707-b13b70fe61c0@27g2000hsf.googlegroups.com> Message-ID: <69d1hnF32r2ugU1@mid.uni-berlin.de> kuratkull at kuratkull.com wrote: > Hello, > > *************** > import urllib2 > import re > import string > import sys > > url = "http://www.macgyver.com/" > request = urllib2.Request(url) > opener = urllib2.build_opener() > html = opener.open(request).read() > > match = re.compile("
(.+)
", re.DOTALL) > > out = match.findall(html) > > print out > ************** > > I would like to print out string with formatting, but as I read, the > string is made into a raw string when using re. > How could I disable or bypass this? You have a misconception here. A raw-string in python is *only* different as literal - that is, you can write r"fooo\bar" where you'd have to write "fooo\\bar" with "normal" string-literals. However, the result of both is a byte-string object that is exactly equal. So whatever out contains, it has nothing to do with raw-string or not. But what you probably mean is that putting out a list using print will use the repr()-call on the contained objects. So instead of doing print out do print "\n".join(out) or such. Diez From inhahe at gmail.com Thu May 22 15:29:42 2008 From: inhahe at gmail.com (inhahe) Date: Thu, 22 May 2008 15:29:42 -0400 Subject: Producing multiple items in a list comprehension References: <5RiZj.165543$ng7.151222@en-nntp-05.dc1.easynews.com> Message-ID: <5PjZj.78772$%15.70394@bignews7.bellsouth.net> "Joel Koltner" wrote in message news:5RiZj.165543$ng7.151222 at en-nntp-05.dc1.easynews.com... > Is there an easy way to get a list comprehension to produce a flat list > of, say, [x,2*x] for each input argument? > > E.g., I'd like to do something like: > > [ [x,2*x] for x in range(4) ] > > ...and receive > > [ 0,0,1,2,2,4,3,6] > > ...but of course you really get a list of lists: > > [[0, 0], [1, 2], [2, 4], [3, 6]] > > I'm aware I can use any of the standard "flatten" bits of code to turn > this back into what I want, but I was hoping there's some way to avoid the > "lists of lists" generation in the first place? > > A slightly similar problem: If I want to "merge," say, list1=[1,2,3] with > list2=[4,5,6] to obtain [1,4,2,5,3,6], is there some clever way with "zip" > to do so? > > Thanks, > ---Joel > i figured out a solution sum([x,2*x] for x in range(4)],[]) #not tested sum(zip(list1,list2),()) #not tested (you did say you knew of ways to flatten, but i dunno if you knew of that way or not) as an aside, i wish that sum didn't have to take the second parameter. it's kind of superfluous. it can just use the first item as the initial value instead of 0 when no initial value is specified. it would be a little complex to do without putting a conditional in your main loop and slowing it down, but it could be done. From cokofreedom at gmail.com Thu May 8 08:08:23 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Thu, 8 May 2008 05:08:23 -0700 (PDT) Subject: Newbie to python --- why should i learn ! References: <9f5ee6c3-86f7-401a-acc8-cd2c9b059fbd@x19g2000prg.googlegroups.com> <12b0b227-0a6c-4653-973b-8f13f2e5b3c1@v26g2000prm.googlegroups.com> Message-ID: <52d0031c-202c-48d2-a61b-27f6c76fd5f3@b64g2000hsa.googlegroups.com> C# using System; namespace HelloWorld { Class HelloWorld { static void Main(String[] args) { Console.WriteLine("Hello World"); } } } From marlin_rowley at hotmail.com Thu May 15 20:44:09 2008 From: marlin_rowley at hotmail.com (Marlin Rowley) Date: Thu, 15 May 2008 19:44:09 -0500 Subject: How do I use the unpack function? In-Reply-To: <482CC073.20402@islandtraining.com> References: <482C6E59.3020503@islandtraining.com> <482CA10E.1040602@islandtraining.com> <482CC073.20402@islandtraining.com> Message-ID: Thanks. I'll churn on this for awhile.. > Date: Thu, 15 May 2008 16:00:03 -0700> From: gherron at islandtraining.com> To: python-list at python.org> Subject: Re: How do I use the unpack function?> > Marlin Rowley wrote:> > Hey Gary!> > Please keep such discussions on the public python-list -- not personal > e-mail.> > Scroll down for an answer to your latest question.> >> > Here's what I have that renders fine but I see some optimization that > > can be done (as you mentioned):> >> > # Tile Generation> > # This is where all the drawing to the client window> > # will happen. > > def generateTile( txl, tyl, tileWidth, tileHeight, clientWindow ):> > # make rgba (8-bit) data structure and zero it out.> > rgb = zeros( tileWidth*tileHeight*3, UnsignedInt8 )> > alpha = zeros( tileWidth*tileHeight*3, UnsignedInt8 )> > > > #print 'tileWidth: %s' % tileWidth> > #print 'tileHeight: %s' % tileHeight> > # for each pixel in the tile> > # we must invert the rendering of each> > # tile for wxPython's Bitmap support.> > for y in range( (tileHeight-1),-1,-1 ):> > for color in range(4):> > > > # read per scanline> > pixelComp = clientWindow.fileIO.read(4*tileWidth) <<<< > > HERE'S YOUR OPTIMIZATION!!> > > > for x in range(tileWidth):> > # mental ray streams RGBA components across the width> > # of every tile. so it first does all the r's,> > # then all the g's, then all the b's, etc.. across> > # the width.. Then it streams the second row, etc..> > # However, wxPython Bitmap class accepts an array of> > # tuples or just a byte order of RGBARGBARGBA, etc..> > # so we convert, keeping track of an offset.> > if color < 3:> > index = (3*(y*tileWidth+x))+color> > else:> > index = (3*(y*tileWidth+x))> > > > > > # RGBA_FP> > if clientWindow.pixelCode == 13:> > > > # unpack the pixel> > #fourbytes = pixelComp[:4]> > #pixelComp = pixelComp[4:]> > buffer = unpack("!f", pixelComp[4*x:4*x+4]) > > <<<<<<<<<<<<<<<<<< YOUR OPTIMIZATION!!> > > > # convert from 32-bit to 8-bit precision> > gamma = clientWindow.gamma> > if gamma == 1.0:> > pixel = int(255 * buffer[0] + 0.5)> > pixel = clamp(pixel,0,255)> > if color == 3:> > alpha[index+0] = alpha[index+1] = > > alpha[index+2] = pixel> > else:> > rgb[index] = pixel> > else:> > pixel = int(buffer[0] * GAMMA_BIT_PRECISION + 0.5)> > pixel = clamp(pixel,0,GAMMA_BIT_PRECISION-1)> > # set the color and alpha> > if color == 3:> > alpha[index+0] = alpha[index+1] = > > alpha[index+2] = clientWindow.frame.gammaTable[pixel]> > else:> > rgb[index] = > > clientWindow.frame.gammaTable[pixel]> > > > > > # ...> >> > # create an empty rgb and alpha tile> > tileRGB = wx.BitmapFromBuffer( tileWidth, tileHeight, rgb )> > tileAlpha = wx.BitmapFromBuffer( tileWidth, tileHeight, alpha )> > > > # set up main device to render to the current> > # buffers> > dc = wx.BufferedDC( None,clientWindow.colorBuffer )> > dca = wx.BufferedDC( None,clientWindow.alphaBuffer )> > > > # draw tiles> > dc.DrawBitmap( tileRGB, txl, (clientWindow.height-tileHeight)-tyl )> > dca.DrawBitmap( tileAlpha, txl, (clientWindow.height-tileHeight)-tyl )> >> >> > I'm no python expert (as you can tell), but I'm trying.. :)> >> > I started to re-write this function but I'm confused on how to do:> >> > > Reshape the array into a 3D array (i.e., a rectangular array of RGBA> > > values)> >> > this without using a for loop.> > Yes, easily. No Python loops (although plenty of C-level loops.) (I > think you are using Numeric -- a ancient predecessor of numpy. However, > I think these operations work in Numeric.)> > > Again I create a small test case. The values will be in the order > rrrrggggbbbb to start with, and rgbrgbrgbrgb afterwards.> > Create a test array and examine it:> >>> a = numpy.frombuffer('rrrrggggbbbb', dtype='S1')> >>> a> array(['r', 'r', 'r', 'r', 'g', 'g', 'g', 'g', 'b', 'b', 'b', 'b'], > dtype='|S1')> > Isolate each color component (here height*width = 4)> >>> a.shape = (3,4)> >>> a> array([['r', 'r', 'r', 'r'],> ['g', 'g', 'g', 'g'],> ['b', 'b', 'b', 'b']],> dtype='|S1')> > Transpose it. (This creates a new array by copying efficiently.)> >>> b = a.transpose()> >>> b> array([['r', 'g', 'b'],> ['r', 'g', 'b'],> ['r', 'g', 'b'],> ['r', 'g', 'b']],> dtype='|S1')> > Reset it's shape to be a width*height array of rgb's.> >>> b.shape = (2,2,3)> >>> b> array([[['r', 'g', 'b'],> ['r', 'g', 'b']],> > [['r', 'g', 'b'],> ['r', 'g', 'b']]],> dtype='|S1')> > Put it out in byte array form:> >>> b.tostring()> 'rgbrgbrgbrgb'> > > Done.> > > Gary Herron> > > >> > -M> >> >> > > Date: Thu, 15 May 2008 13:46:06 -0700> > > From: gherron at islandtraining.com> > > CC: python-list at python.org> > > Subject: Re: How do I use the unpack function?> > >> > > Marlin Rowley wrote:> > > > Gary,> > > >> > > > I'm getting streaming tile data from a renderer in order to allow the> > > > user to see the rendering of tiles in real-time to create the total> > > > image. I'm NOT reading an entire image scanline-by-scanline. The> > > > renderer streams in a series of floats (for each tile) and I build> > > > this tile up from each individual color component passed in. I then> > > > convert it to a small bitmap and blit() it to the window that will> > > > eventually make up my entire image. I'm just wanting to make the> > > > process as fast as the renderer can render the tiles. I've noticed on> > > > scenes that aren't very complex for the renderer that my python > > script> > > > is spending most of it's time drawing while the renderer is already> > > > done. What you've given me has sped up the drawing a lot, but I'm> > > > hungry for more optimization!> > > >> > > > There is no file format to be read. The data is raw bytes and can be> > > > any format.> > >> > > You are misinterpreting what I mean by a format. All data is a string> > > of bytes, and interpreting that string of bytes to have some particular> > > form is applying a format to it. Your particular format is: each 4> > > bytes represents a float, and a string of such floats give the RGBA> > > values for a rectangle (of some size) of pixels. I doubt that you are> > > the first ever to use that particular format to encode an image, but I> > > also don't believe it matches any of the standard image formats.> > >> > > So... There is still hope to use already written tools to decode your> > > format.> > >> > > Here's a hint on how to use numpy for decoding a byte string into an> > > array of floats. My example byte string is a hand coded string of just> > > 12 bytes -- you should replace that with a whole row or better yet, a> > > whole tile's worth of bytes.> > >> > > >>> import numpy> > > >>> byteString = '\x00\x00\x80?\x00\x00\x00@\x00\x00@@'> > > >>> b = numpy.frombuffer(byteString, dtype=numpy.float32)> > > >>> b> > > array([ 1., 2., 3.], dtype=float32)> > >> > >> > > If you want to use the array module instead:> > >> > > >>> import array> > > >>> a = array.array('f')> > > >>> a.fromstring(byteString)> > > >>> a> > > array('f', [1.0, 2.0, 3.0])> > >> > >> > > In either case ANY number of bytes can be decoded into an array of> > > floats, in one highly efficient call from Python.> > >> > > What you do with that array of float afterwards is up to you....> > >> > > If I read your note correctly, here's what I'd do to turn the array of> > > bytes into an image of a tile to be displayed on the screen.> > >> > > Get the whole tile's worth of bytes with one read into a single string.> > > Decode that string into an array of floats (as above).> > > Reshape the array into a 3D array (i.e., a rectangular array of RGBA> > > values)> > > Convert that array of floats into an array of 8-bit integers (scaling> > > all by 255).> > > Extract (via tostring) that array into a string of bytes.> > > Send that string of bytes to the graphics system as an RGBA array of> > > pixels.> > >> > > Each of these calls is one Python call into a highly efficient library.> > > This is using Python as a, so called, glue language.> > >> > > Gary Herron> > >> > >> > >> > >> > >> > >> > >> > > >> > > > > Date: Thu, 15 May 2008 10:09:45 -0700> > > > > From: gherron at islandtraining.com> > > > > CC: python-list at python.org> > > > > Subject: Re: How do I use the unpack function?> > > > >> > > > > John Machin wrote:> > > > > > On May 16, 2:11 am, Gary Herron > > wrote:> > > > > >> > > > > >> Marlin Rowley wrote:> > > > > >>> > > > > >>> All:> > > > > >>>> > > > > >>> I've got a script that runs really slow because I'm reading > > from a> > > > > >>> stream a byte at a time:> > > > > >>>> > > > > >>> // TERRIBLE> > > > > >>> for y in range( height ):> > > > > >>> for color in range(4):> > > > > >>> for x in range( width ):> > > > > >>> pixelComponent = fileIO.read(4)> > > > > >>> buffer = unpack("!f",pixelComponent) << unpacks ONE> > > > > >>>> > > > > >> > > > > > [snip]> > > > > > Perhaps the OP might be able to use the Python Imaging Library > > (PIL)> > > > > > instead of reinventing an image-file handler.> > > > > >> > > > >> > > > > Indeed. That's why my original answer included the line:> > > > > There are probably better ways overall, but this directly answers> > > > > your question.> > > > >> > > > > Other possibilities.> > > > >> > > > > I don't recognize the file format being read in here, but if it is a> > > > > standard image format, the PIL suggestion is a good way to go.> > > > >> > > > > Or, if it is an image of not too enormous size, read the *whole* > > thing> > > > > in at once.> > > > >> > > > > Or rather than manipulate the array by carving off 4 bytes at a > > time,> > > > > just index through it in 4 byte chunks:> > > > > for i in range(width):> > > > > buffer = unpack("!f", pixelComponent[4*i:4*i+4])> > > > >> > > > > Or> > > > > for i in range(0,4*width,4):> > > > > buffer = unpack("!f", pixelComponent[i:i+4])> > > > >> > > > > Or> > > > > Use numpy. Create an array of floats, and initialize it with the > > byte> > > > > string, making sure to take endianess int account. (I'm quite > > sure this> > > > > could be made to work, and then the whole operation is > > enormously fast> > > > > with only several lines of Python code and *no* Python loops.> > > > >> > > > > Or> > > > > ...?> > > > >> > > > > Gary Herron> > > > >> > > > > > --> > > > > > http://mail.python.org/mailman/listinfo/python-list> > > > > >> > > > >> > > > > --> > > > > http://mail.python.org/mailman/listinfo/python-list> > > >> > > > > > ------------------------------------------------------------------------> > > > Windows Live SkyDrive lets you share files with faraway friends. > > Start> > > > sharing.> > > > > > > >> > > >> > > > > > ------------------------------------------------------------------------> > > >> > > > --> > > > http://mail.python.org/mailman/listinfo/python-list> > >> > > --> > > http://mail.python.org/mailman/listinfo/python-list> >> > ------------------------------------------------------------------------> > Get Free (PRODUCT) RED? Emoticons, Winks and Display Pics. Check it > > out! > > > > --> http://mail.python.org/mailman/listinfo/python-list _________________________________________________________________ Stay in touch when you're away with Windows Live Messenger. http://www.windowslive.com/messenger/overview.html?ocid=TXT_TAGLM_WL_Refresh_messenger_052008 -------------- next part -------------- An HTML attachment was scrubbed... URL: From bj_666 at gmx.net Tue May 13 03:22:05 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 13 May 2008 07:22:05 GMT Subject: anonymous assignment References: <1XNVj.133805$Cj7.33096@pd7urf2no> <7xmymwuu25.fsf@ruckus.brouhaha.com> <68q50pF2u2t25U2@mid.uni-berlin.de> <3T7Wj.134606$rd2.31796@pd7urf3no> Message-ID: <68ststF2uo1qcU1@mid.uni-berlin.de> On Tue, 13 May 2008 03:25:51 +0000, Yves Dorfsman wrote: > Marc 'BlackJack' Rintsch wrote: >>>> y, _, d, _, _, _, _, _, _ = time.localtime() >>> But you still have have a variable that's using memory for nothing. I >>> find this unsatisfactory... >> >> Get over it? > > Than what's the point of wanting a better language if every time we run in > something that looks wrong, or something that could be done better we should > just "get over it" ? That advice wasn't for every time something looks wrong but this particular one. You can solve it with `operator.itemgetter()` but that means importing another module and calling a function which looks much more "heavy weight" to me than one reference to an unused object which might go away at the end of the function anyway soon. Ciao, Marc 'BlackJack' Rintsch From nick at craig-wood.com Sat May 3 05:30:03 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Sat, 03 May 2008 04:30:03 -0500 Subject: portable fork+exec/spawn References: Message-ID: Jean-Paul Calderone wrote: > >For jobs which require interactivity ie send input, receive output, > >send input, receive output, ... it doesn't work well. There isn't a > >good cross platform solution for this yet. pyexpect works well under > >unix and is hopefully being ported to windows soon. > > There is a good cross-platform solution, in fact. It's Twisted's > spawnProcess API, which works on POSIX and Windows, supports supports > sending and receiving, and doesn't have deadlock issues since it's > event-driven. It took me a while but I found the documentation on this eventually http://twistedmatrix.com/documents/current/api/twisted.internet.interfaces.IReactorProcess.html Looks interesting - I'll have to try it next time I'm reaching for pexpect Thanks Nick -- Nick Craig-Wood -- http://www.craig-wood.com/nick From joe.p.cool at googlemail.com Sun May 25 17:32:00 2008 From: joe.p.cool at googlemail.com (Joe P. Cool) Date: Sun, 25 May 2008 14:32:00 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <8763t3by81.fsf@benfinney.id.au> Message-ID: <09847cfc-eaec-4adc-8cbf-1e2ebbf940c4@m44g2000hsc.googlegroups.com> On 24 Mai, 15:58, Ben Finney wrote: > Sh4wn writes: > > first, python is one of my fav languages, and i'll definitely keep > > developing with it. But, there's 1 one thing what I -really- miss: > > data hiding. I know member vars are private when you prefix them with > > 2 underscores, but I hate prefixing my vars, I'd rather add a keyword > > before it. > > From whom are you trying to hide your attributes? I saw this "don't need it" pattern in discussions about the ternary "if..else" expression and about "except/finally on the same block level". Now Python has both. Actually it is very useful to be able to distinguish between inside and outside. This is obvious for real world things e.g. your TV. Nobody likes to open the rear cover to switch the channel. Similar arguments apply to software objects. "data hiding" is a harsh name, I would call it "telling what matters". The need for this becomes indispensable in really big software packages like the Eclipse framework with approx. 100000 classes. If you cannot tell the difference between inside and outside you are lost. > In Python, the philosophy "we're all consenting adults here" applies. Please don't sell a missing feature as a philosophy. Say you don't need/want it. But don't call it philosophy. > You shouldn't pretend to know, at the time you write it, all the uses > to which your code will be put. It's *your* *decision* which uses will be available. Your explanation appears to me as a fear to decide. > If you want the users of your code to know that an attribute should > not be used as a public API for the code, use the convention of naming > the attribute with a single leading underscore. Littering your class definition with dozens of underscores is exactly the line noise we love to criticize in Perl. > > Python advertises himself as a full OOP language, but why does it > > miss one of the basic principles of OOP? > > Who taught you that enforced restrictions on attribute access was a > "basic principle" of OO? Nearly every introduction to OOP? Please don't tell me that encapsulation does not mean "enforced restriction". If the language has no syntactic support for encapsulation then it does not have encapsulation. Similar argument applies to Java where programmers sometimes claim that Java "has" properties because of setCrap/getCrap. __ Joe From nospam at here.com Sun May 18 15:34:34 2008 From: nospam at here.com (Dennis) Date: Sun, 18 May 2008 20:34:34 +0100 Subject: python confusion possibly related to pickle In-Reply-To: References: Message-ID: Never mind. I solved it. I had a file called pickle in the same folder I was in when I ran python, and that's the file it was trying to import. Duh @ me :s Dennis wrote: > > I have a problem that I don't understand at all. I run a python script, > which uses pickle, and it fails. That alone is, perhaps, no big deal. > > The problem that's got me annoyed is that after getting said error I > close the shell window, open a new one, run the python interpreter and > type "import pickle" and get the error that the script I'd run earlier > caused. Why is this ? > > To my knowledge, once python stopped running it didn't store anything > related to the last time it was run. From kay.schluehr at gmx.net Fri May 9 00:09:04 2008 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Thu, 8 May 2008 21:09:04 -0700 (PDT) Subject: RELEASED Python 2.6a3 and 3.0a5 References: Message-ID: <26dacfd7-e698-46c6-affb-7b4d6b18c3f5@59g2000hsb.googlegroups.com> On 9 Mai, 01:50, Barry Warsaw wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > On behalf of the Python development team and the Python community, I > am happy to announce the third alpha release of Python 2.6, and the > fifth alpha release of Python 3.0. > > Please note that these are alpha releases, and as such are not > suitable for production environments. We continue to strive for a > high degree of quality, but there are still some known problems and > the feature sets have not been finalized. These alphas are being > released to solicit feedback and hopefully discover bugs, as well as > allowing you to determine how changes in 2.6 and 3.0 might impact > you. If you find things broken or incorrect, please submit a bug > report at > > http://bugs.python.org > > For more information and downloadable distributions, see the Python > 2.6 website: > > http://www.python.org/download/releases/2.6/ > > and the Python 3.0 web site: > > http://www.python.org/download/releases/3.0/ > > These are the last planned alphas for both versions. If all goes > well, next month will see the first beta releases of both, which will > also signal feature freeze. Two beta releases are planned, with the > final releases scheduled for September 3, 2008. > > See PEP 361 for release details: > > http://www.python.org/dev/peps/pep-0361/ > > Enjoy, > - -Barry > > Barry Warsaw > ba... at python.org > Python 2.6/3.0 Release Manager > (on behalf of the entire python-dev team) > > -----BEGIN PGP SIGNATURE----- > Version: GnuPG v1.4.8 (Darwin) > > iQCVAwUBSCORrnEjvBPtnXfVAQIK+QQAgEUtAvW7uo0BxMiT1bCAo2E9ZecWJ9xe > DBgd/5IK8moITkqhqGAH5UvfytV6uPkOMgGIS/Uvk4hzhU3jwSopEIDJLFQ5nGtC > lCzOHzkDjSNZ8Q2OOAI9mbSHY8grvVxCMB4X2SVXIEMZ6M/X1AcV2b0utp9O1w/l > T/PEvP8U1uY= > =2Tnb > -----END PGP SIGNATURE----- http://www.python.org/ftp/python/3.0/python-3.0a5.msi Error 404: File Not Found http://www.python.org/ftp/python/3.0/python-3.0a5.amd64.msi Error 404: File Not Found From skanemupp at yahoo.se Sat May 31 08:48:20 2008 From: skanemupp at yahoo.se (globalrev) Date: Sat, 31 May 2008 05:48:20 -0700 (PDT) Subject: SMS sending and receiving from website? References: <6abq0uF36n019U1@mid.individual.net> Message-ID: <5d949166-5112-4a7a-91c3-77ccdd7ca695@j22g2000hsf.googlegroups.com> On 31 Maj, 04:04, John Henderson wrote: > globalrev wrote: > > can i send and receive messages from a website using python? > > Absolutely. But I'm not clear what you mean by "from a > website". Do you mean to use SMPP protocol to lodge and > receive messages? Or do you want access to your own cellular > hardware from a web interface? > > > how would that work with costs? would the mobileowner pay both > > ways? > > That depends on the country, the carrier and the offers/plans > that carrier makes. In most of the civilized world, SMS > receivers pay nothing. > > John i want to build a service where you can send an SMS with your cellphone to my website and then the site will collect the data you asked for and SMS it back. so what components would i need for that? From reid at reidster.net Mon May 19 20:58:50 2008 From: reid at reidster.net (Reid Priedhorsky) Date: Mon, 19 May 2008 19:58:50 -0500 Subject: scaling problems References: Message-ID: On Tue, 20 May 2008 10:47:50 +1000, James A. Donald wrote: > > 1. Looks to me that python will not scale to very large programs, > partly because of the lack of static typing, but mostly because there > is no distinction between creating a new variable and utilizing an > existing variable, so the interpreter fails to catch typos and name > collisions. I am inclined to suspect that when a successful small > python program turns into a large python program, it rapidly reaches > ninety percent complete, and remains ninety percent complete forever. I find this frustrating too, but not to the extent that I choose a different language. pylint helps but it's not as good as a nice, strict compiler. > 2. It is not clear to me how a python web application scales. Python > is inherently single threaded, so one will need lots of python > processes on lots of computers, with the database software handling > parallel accesses to the same or related data. One could organize it > as one python program for each url, and one python process for each > http request, but that involves a lot of overhead starting up and > shutting down python processes. Or one could organize it as one > python program for each url, but if one gets a lot of http requests > for one url, a small number of python processes will each sequentially > handle a large number of those requests. What I am really asking is: > Are there python web frameworks that scale with hardware and how do > they handle scaling? This sounds like a good match for Apache with mod_python. Reid From kyosohma at gmail.com Tue May 27 12:13:44 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 27 May 2008 09:13:44 -0700 (PDT) Subject: how to reply to posts on google groups (and not reply to just author) References: Message-ID: <8badaef0-1483-4635-b26b-cd88f7033c68@d77g2000hsb.googlegroups.com> On May 27, 10:44?am, davidj411 wrote: > I want to reply to the goups and not author for ?an older post (from > February) , but it seems i can only reply to the author (using google > groups). > > ?Is there a way (within Google groups) to reply to an older post to > keep that particular thread going instead of posting a new one (as i > am here now doing - sorry about this being a non-python question.) You might be able to use the CC functionality and put the c.l.py email in there to accomplish it. But I really don't know if that will work. Worth a try though. You can find the email address on the Python website. Mike From Scott.Daniels at Acm.Org Tue May 20 00:00:10 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 19 May 2008 21:00:10 -0700 Subject: Write bits in file In-Reply-To: References: Message-ID: <8sGdnS3nQNwg16_VnZ2dnUVZ_jqdnZ2d@pdx.net> Monica Leko wrote: > On May 18, 2:20 pm, Ken Starks wrote: >> You want your file considered as a sequence of bits rather >> than a sequence of 8-bit bytes, do you? > Yes. > >> is the 10-bit bit-pattern to be stored at an arbitrary bit-position in >> the file > Yes. I need arbitrary, 8bits, than 10 bits for something else, than > sequence of bytes, than 10 bits again, etc. You should know there is no single "natural" mapping of files to bit orders; rather there are several distinct natural such orders. Define the mapping you prefer and implement it. This is even worse than the "byte sex" issue (go ahead, look it up). --Scott David Daniels Scott.Daniels at Acm.Org From deets at nospam.web.de Mon May 5 10:45:38 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 05 May 2008 16:45:38 +0200 Subject: Pygame and PGU References: <1eb8b83f-cca0-464a-9ec9-4f3722423afd@r66g2000hsg.googlegroups.com> Message-ID: <688ktbF2rlolmU1@mid.uni-berlin.de> Zaka wrote: > Hi. I need some help to make map system in PGU. For exmple we have 2 > maps and when we leave first we enter to second. > > > -------------------- > ! > > > ___________ What is a PGU? What is a map-system? And what is that ascii art above? And what might you learn from reading this: http://www.catb.org/~esr/faqs/smart-questions.html Diez From kylotan at gmail.com Wed May 28 10:26:54 2008 From: kylotan at gmail.com (Ben Sizer) Date: Wed, 28 May 2008 07:26:54 -0700 (PDT) Subject: Using an object-relational mapper to convert between databases Message-ID: <019cb83a-d4b6-445a-b616-da12b6fd6a48@j22g2000hsf.googlegroups.com> Hello, I'd like to be able to do the following: - open a connection to a MySQL or PostgreSQL database - read the schema and contents for one or more tables - create a new sqlite database file and open a connection to it - write out the previously-read tables and their contents to this new database I get the impression that the various object-relational mappers such as SQLAlchemy and SQLObject can make this easier, especially if using something like SQLAlchemy's autoloading capability to query the schema from the DB rather than me having to explicitly specify it. But then how easy is it to make a corresponding sqlite table and write the same objects to it? I don't know how practical this is with SQLAlchemy, or if a different ORM library would be more useful for this. And since objects tend to be closely related to the database they are mapped to, I don't know how easy it is to reflect them onto a second database. I'd just like some advice and pointers from anybody who's tried something similar to this or who knows the packages well enough to point me in the right direction. -- Ben Sizer From skanemupp at yahoo.se Mon May 5 10:29:04 2008 From: skanemupp at yahoo.se (globalrev) Date: Mon, 5 May 2008 07:29:04 -0700 (PDT) Subject: pygame music, cant read mp3? References: <30fe7c79-dbac-47bb-9e29-bea61b7c3da8@56g2000hsm.googlegroups.com> <688af0F2pc3jjU1@mid.uni-berlin.de> <5e52e1b5-8698-4ba1-8fc2-180ba20491cb@m73g2000hsh.googlegroups.com> <0038dede-85c0-4d4d-a347-a4d23cab23ad@d45g2000hsc.googlegroups.com> Message-ID: On 5 Maj, 16:09, globalrev wrote: > On 5 Maj, 14:17, "Wojciech Walczak" > wrote: > > > 2008/5/5, globalrev : > > > > pygame.mixer.music.load('C:/Python25/myPrograms/pygameProgs/example1.mp3') > > > Are you sure that: > > > os.path.exists('C:/Python25/myPrograms/pygameProgs/example1.mp3') == True? > > > Check it with python. > > > -- > > Regards, > > Wojtek Walczakhttp://www.stud.umk.pl/~wojtekwa/ > >>> import os > >>> os.path.exists('C:/Python25/myPrograms/pygameProgs/dront.mp3') == True > > False > > but...it is there.... > > >>> os.path.exists('C:\Python25\myPrograms\pygameProgs\dront.mp3') == True > > False > > does it matter if i use / or \? which si recommended? i can find .png image in the same folder and when i just change filename from snake.png to example1.mp3 it is false. i renamed the file once, could that have anything to do with it? From java.oke at gmail.com Mon May 26 16:52:37 2008 From: java.oke at gmail.com (j.oke) Date: Mon, 26 May 2008 13:52:37 -0700 (PDT) Subject: blogs, longbets.org, and education of sociology References: <1c97ba8a-b758-4891-a3c4-20e462361934@z16g2000prn.googlegroups.com> Message-ID: <358ec7c3-4a25-4591-a705-03446e074b20@25g2000hsx.googlegroups.com> On 26 Mag, 01:25, "xah... at gmail.com" wrote: > For about the past 10 years, ... Q: How many comp.lang.X trolls does it take to change a light bulb? A: One, and Superman. One to hold the bulb, and Superman to screw the planet. -JO From gagsl-py2 at yahoo.com.ar Tue May 13 23:49:47 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 14 May 2008 00:49:47 -0300 Subject: wxpython dialog - do something after ShowModal()? References: Message-ID: En Tue, 13 May 2008 09:41:25 -0300, Iain King escribi?: > Hi. I have a modal dialog whcih has a "Browse..." button which pops > up a file selector. This all works fine, but the first thing the user > has to do when they open the dialog is select a file, so I would like > the dialog to automatically call the onBrowse function as soon as the > dialog opens. However, I don't know how to do this. I've seen you already answered your question. But are you sure that doing this is a good thing? If you try to be too clever or too helpful the interfase may become annoying at some times. You can't guess the user's intention or read his mind. By example, what if I already have the desired file name copied in the clipboard? I don't want the file selector to pop up. I completely *hate* Windows programs with a "Browse for folder" button that don't let me paste a name, neither start opened at the currently selected folder. -- Gabriel Genellina From fabiofz at gmail.com Mon May 12 11:42:09 2008 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Mon, 12 May 2008 12:42:09 -0300 Subject: Pydev 1.3.17 Released Message-ID: Hi All, Pydev and Pydev Extensions 1.3.17 have been released Details on Pydev Extensions: http://www.fabioz.com/pydev Details on Pydev: http://pydev.sf.net Details on its development: http://pydev.blogspot.com Release Highlights in Pydev Extensions: ----------------------------------------------------------------- * Minor bug-fixes Release Highlights in Pydev: ---------------------------------------------- * Pydev Package Explorer: projects that had the project folder in the pythonpath did not show children items correctly. * Debugger: Disable all works. Patch from: Oldrich Jedlicka * Debugger: Problem when making a step return / step over * Code-completion: Working for attributes found in a superclass imported with a relative import Patches from Felix Schwarz: o Allow to configure an interpreter even if the workspace path name contains spaces o Completion server does not work when the eclipse directory contains spaces o Fix deletion of resources in pydev package explorer for Eclipse 3.4 What is PyDev? --------------------------- PyDev is a plugin that enables users to use Eclipse for Python and Jython development -- making Eclipse a first class Python IDE -- It comes with many goodies such as code completion, syntax highlighting, syntax analysis, refactor, debug and many others. Cheers, -- Fabio Zadrozny ------------------------------------------------------ Software Developer ESSS - Engineering Simulation and Scientific Software http://www.esss.com.br Pydev Extensions http://www.fabioz.com/pydev Pydev - Python Development Enviroment for Eclipse http://pydev.sf.net http://pydev.blogspot.com From straton at lampsacos.demon.co.uk Sun May 18 08:20:14 2008 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Sun, 18 May 2008 13:20:14 +0100 Subject: Write bits in file In-Reply-To: References: Message-ID: You want your file considered as a sequence of bits rather than a sequence of 8-bit bytes, do you? is the 10-bit bit-pattern to be stored at an arbitrary bit-position in the file, or is the whole file regularly subdivided at 10-bit intervals? Monica Leko wrote: > Hi > > I have a specific format and I need binary representation. Does > Python have some built-in function which will, for instance, represent > number 15 in exactly 10 bits? From rdahlstrom at directedge.com Thu May 29 07:23:45 2008 From: rdahlstrom at directedge.com (Dahlstrom, Roger) Date: Thu, 29 May 2008 07:23:45 -0400 Subject: [python-win32] How to get all the variables in a python shell References: <483E650B.5060902@timgolden.me.uk> <79990c6b0805290422g5b61f3c5l65034ee6e5798178@mail.gmail.com> Message-ID: -----Original Message----- From: Paul Moore [mailto:p.f.moore at gmail.com] Sent: Thursday, May 29, 2008 7:23 AM To: Dahlstrom, Roger Cc: Python-Win32 List; python-list at python.org Subject: Re: [python-win32] How to get all the variables in a python shell On 29/05/2008, Dahlstrom, Roger wrote: > I'd try looking at memcached (http://www.danga.com/memcached/apis.html). > No hacking or reimplementation of the interpreter would be necessary, and > there's a Python api available. I haven't used it for anything production related, > but I have played with it a bit, and it's fast and stable. Is memcached available for Windows, then? I've heard nice things about it, but thought it was Unix-only. Paul. ---------------------------- It is available for Windows, yes. As a matter of fact, I've never used it on Unix. DISCLAIMER: This e-mail, and any attachments thereto, is intended only for use by the addressee(s) named herein and may contain legally privileged and/or confidential information. If you are not the intended recipient of this e-mail, you are hereby notified that any dissemination, distribution or copying of this e-mail, and any attachments thereto, is strictly prohibited. If you have received this in error, please immediately notify me and permanently delete the original and any copy of any e-mail and any printout thereof. E-mail transmission cannot be guaranteed to be secure or error-free. The sender therefore does not accept liability for any errors or omissions in the contents of this message which arise as a result of e-mail transmission. NOTICE REGARDING PRIVACY AND CONFIDENTIALITY Direct Edge ECN LLC may, at its discretion, monitor and review the content of all e-mail communications. www.directedge.com From bignose+hates-spam at benfinney.id.au Fri May 2 09:17:28 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 02 May 2008 23:17:28 +1000 Subject: #!/usr/bin/env python vs. #!/usr/bin/python References: <87abj91j8u.fsf@benfinney.id.au> <871w4l1cjj.fsf@benfinney.id.au> Message-ID: <87r6ckzvyv.fsf@benfinney.id.au> Jeroen Ruigrok van der Werven writes: > -On [20080502 07:51], Ben Finney (bignose+hates-spam at benfinney.id.au) wrote: > >To my mind, the Python interpreter installed by a package as > >distributed with the OS *is* OS territory and belongs in /usr/bin/. > > That's the difference with a distribution, such as Linux, and full > OSes , such as BSDs or commercial Unix variants. They prefer to keep > a pristine state for the OS vendor files versus what the user can > opt to install himself, hence the /usr/bin - /usr/local/bin > separation. Fine so far. /usr/local/ is certainly for "what the (system administrator) user opts to install themselves". > It effectively guarantees you can nuke /usr/local without ill > consequences for your OS. You say this as though it's a property that a GNU/Linux distribution doesn't have. But the "keep /usr/local/ untouched by OS packages" approach taken by GNU/Linux *also* means that /usr/local/ can be blown away without ill consequences for the OS. So I don't see why you draw that distinction here. The difference seems to be that Python is an OS-installable package on GNU/Linux, and thus gets installed to the OS-packaged location. So the default Python installation should work. Whereas if Python is *not* installed from an OS package, it's up to the sys admin to ensure that it works -- not up to my program. So I don't see the point in making it work by default, when what I want for my program is that it works *with the default Python*, not with some non-default installation. -- \ "Truth is stranger than fiction, but it is because fiction is | `\ obliged to stick to possibilities, truth isn't." -- Mark | _o__) Twain, _Following the Equator_ | Ben Finney From johnjsal at NOSPAMgmail.com Tue May 20 12:33:55 2008 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 20 May 2008 12:33:55 -0400 Subject: Misuse of list comprehensions? References: <038e4418$0$27258$c3e8da3@news.astraweb.com> <69g2bpF31ttuuU1@mid.uni-berlin.de> Message-ID: <027e4d96$0$25054$c3e8da3@news.astraweb.com> "Diez B. Roggisch" wrote in message news:69g2bpF31ttuuU1 at mid.uni-berlin.de... > the above code is pretty much of a no-no because it has quadratic runtime > behavior. What's that mean, exactly? Are you referring to both examples, or just the second one? From arnodel at googlemail.com Tue May 6 02:06:02 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 06 May 2008 07:06:02 +0100 Subject: word shifts References: <96a41fd1-23ca-482f-9575-5123611ade8a@z72g2000hsb.googlegroups.com> Message-ID: George Sakkis writes: > On May 5, 11:02 pm, dave wrote: >> On 2008-05-04 01:10:40 -0600, Arnaud Delobelle said: >> >> >> >> > dave writes: >> >> >> Hello, >> >> >> I made a function that takes a word list (one word per line, text >> >> file) and searches for all the words in the list that are 'shifts' of >> >> eachother. 'abc' shifted 1 is 'bcd' >> >> >> Please take a look and tell me if this is a viable solution. >> >> >> def shift(word, amt): >> >> ans = '' >> >> for letter in word: >> >> ans = ans + chr((ord(letter) - ord('a') + amt) % 26 + ord('a')) >> >> return ans >> >> > In Python, if you want to build a string from lots of parts you can >> > use ''.join(parts). I think it is considered more efficient. >> >> what would be the best way to write a "ans = ans + chr" into a >> ''.join(parts) ?? > > Well if you do it once, that would be simply "ans += chr". Arnaud was > referring to the case where you do it in a loop, like in your snippet. > A direct translation to use ''.join would be: > > ans = ''.join(chr((ord(letter) - ord('a') + amt) % 26 + ord('a')) > for letter in word) > > Of course it is simpler and more efficient if you factor out of the > loop the subexpressions that don't need to be recomputed: > > ord_a = ord('a') > shift = ord_a - amt > ans = ''.join(chr((ord(letter) - shift) % 26 + ord_a) > for letter in word) > > George Or keep the same layout as your original effort, but build a list of chars instead of a string, then join them all at the end. def shift(word, amt): shifted = '' ord_a = ord('a') shift = ord_a - amt for letter in word: shifted.append(chr((ord(letter) - shift) % 26 + ord_a)) return ''.join(shifted) (Which exactly the same as George's snippet, except that the generator expression is unwound) -- Arnaud From petr.poupa at gmail.com Mon May 12 12:19:48 2008 From: petr.poupa at gmail.com (petr.poupa at gmail.com) Date: Mon, 12 May 2008 09:19:48 -0700 (PDT) Subject: Socket and cycle problem References: Message-ID: On 12 Kv?, 17:54, Jean-Paul Calderone wrote: > On Mon, 12 May 2008 08:34:07 -0700 (PDT), petr.po... at gmail.com wrote: > >Hello, > >I am beginner but so I need help. I have small script for receive data > >from port 3883, but it print only once. > > >import socket > > >HOST = 'localhost' > >PORT = 3883 > >s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > >s.connect((HOST, PORT)) > >data = s.recv(2048) > >s.close() > >print 'receive data from server:', `data` > > >So I try to write cycle to this script, like this: > > >import socket > > >HOST = 'localhost' > >PORT = 3883 > >s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > >while 1: > > s.connect((HOST, PORT)) > > data = s.recv(2048) > > s.close() > > print 'receive data from server:', `data` > > >But Python reporting: > > >Traceback (most recent call last): > > File "C:\Documents and Settings\poupa\Plocha\TCP3.py", line 7, in > > > > s.connect((HOST, PORT)) > > File "", line 1, in connect > > File "C:\Python25\lib\socket.py", line 141, in _dummy > > raise error(EBADF, 'Bad file descriptor') > >error: (9, 'Bad file descriptor') > > >Where is the mistake? I dont know. > > You cannot reconnect a socket. You need to create a new one for each > connection. It's also almost certainly the case that the way you are > receiving data is incorrect. There is no guarantee that you will get > 2048 bytes from socket.recv(2048). It isn't even guaranteed that all > the bytes written to the socket by the peer will be returned by such > a call. Instead, you need a framing protocol to determine when all > data has been received. For example, you might length prefix the > data, or you might insert a delimiter (or a terminator) at the end. Or > if there is exactly one message to receive, then you should just read > until the recv call returns '', indicating EOF. > > Jean-Paul ok thanks, but I am true greenhorn, so you think that the best way is write new script? Could you send me code if it isnt long, becase I have no idea and unfortunately time as well. Petr Petr From gnewsg at gmail.com Sat May 31 15:36:36 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Sat, 31 May 2008 12:36:36 -0700 (PDT) Subject: Question about files? References: <3a260685-b285-43ef-9e2c-c42cfbd4c497@y38g2000hsy.googlegroups.com> Message-ID: <696821f8-33a6-47b1-874c-ca7a4bce5e2e@c58g2000hsc.googlegroups.com> On 31 Mag, 21:28, corvettecra... at gmail.com wrote: > On May 31, 3:25?pm, Dennis Lee Bieber wrote: > > > > > > > On Sat, 31 May 2008 11:44:14 -0700 (PDT), corvettecra... at gmail.com > > declaimed the following in comp.lang.python: > > > > I want to create a program where a user can type what ever they want > > > to, have it saved to a file, and the be able to re-open it and read > > > it. How would I do this? Thanks! > > > import os > > os.system("edit") ? ? # may be Windows specific > > > ? ? ? ? Start with:http://www.catb.org/~esr/faqs/smart-questions.html > > > (or, to expand on it... Exactly what part of the task are you having > > problems with? Opening files for read/write/update? Designing a command > > set for an editor? Designing a GUI for a text editor; what toolkit, does > > it have a generic text edit widget already? Do you really need to write > > another text editor when there are so many available that come with most > > operating systems (Windows: edit, notepad, maybe even wordpad; > > UNIX/Linux type systems: vi, vim, gvim, emacs) or can be downloaded > > (SciTE) ) > > > -- > > ? ? ? ? Wulfraed ? ? ? ?Dennis Lee Bieber ? ? ? ? ? ? ? KD6MOG > > ? ? ? ? wlfr... at ix.netcom.com ? ? ? ? ? ? ?wulfr... at bestiaria.com > > ? ? ? ? ? ? ? ? HTTP://wlfraed.home.netcom.com/ > > ? ? ? ? (Bestiaria Support Staff: ? ? ? ? ? ? ? web-a... at bestiaria.com) > > ? ? ? ? ? ? ? ? HTTP://www.bestiaria.com/ > > No, what I mean is for the user to input text directly into the python > program You can use raw_input() to ask user to type something, then use open() to create a file and write in it. http://docs.python.org/lib/bltin-file-objects.html > then the program would save it to a file and display it after > it is created. What do you mean by "display"? Open that file with a text editor? Print the content of the file on screen? --- Giampaolo http://code.google.com/p/pyftpdlib/ From univbgp100 at gmail.com Sat May 24 03:39:05 2008 From: univbgp100 at gmail.com (Dhanabal) Date: Sat, 24 May 2008 00:39:05 -0700 (PDT) Subject: FREE Tutorials on HTML XHTML CSS JavaScript XML XSL ASP SQL ADO VBScript, SAP - ABAP Message-ID: FREE Tutorials on HTML XHTML CSS JavaScript XML XSL ASP SQL ADO VBScript, SAP - ABAP visit ebooks.univdatabase.com From alex.m.gusarov at gmail.com Tue May 27 08:04:58 2008 From: alex.m.gusarov at gmail.com (Alex Gusarov) Date: Tue, 27 May 2008 19:04:58 +0700 Subject: integration with browser In-Reply-To: References: <69vmlgF35akucU1@mid.uni-berlin.de> <6a0722F33j3q5U1@mid.uni-berlin.de> <9469c3170805270149q4b67e572rafc0dddf9e3e657e@mail.gmail.com> Message-ID: > Web developers usually check only 3 browser > IE > FF > Opera > > I know that using an external engine limits the portability of the > solutions, but i need something that works exaclty as the browser. Really, try WebKit - Safari browser uses it. Last releases of PyQt4 (Qt, of course, too) includes QWebKit - WebKit wrappings. -- Best regards, Alex Gusarov From notbob at nothome.com Thu May 22 12:25:41 2008 From: notbob at nothome.com (notbob) Date: Thu, 22 May 2008 16:25:41 GMT Subject: php vs python References: <5l%Yj.77$mz3.53@fe101.usenetserver.com> Message-ID: <98hZj.1157$5u.860@fe127.usenetserver.com> On 2008-05-22, Larry Bates wrote: > Check out the Pylons blog tutorial. You will have a simple blog up and running > in less than 30 minutes and have a platform to extend it with as much > functionality as you want later on. > > Larry Bates > > Pylons blog tutorial: > > http://wiki.pylonshq.com/display/pylonscookbook/Making+a+Pylons+Blog Thnx, Larry. FYI: the above page doesn't exist: "The page you were trying to reach does not exist. You may want to try a search, or browse the site to find the page you were looking for." ....but, there's a link to a pylons cookbook, which I will explore. nb From arnodel at googlemail.com Mon May 26 17:07:11 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 26 May 2008 22:07:11 +0100 Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <8763t3by81.fsf@benfinney.id.au> <09847cfc-eaec-4adc-8cbf-1e2ebbf940c4@m44g2000hsc.googlegroups.com> <039f3c2d-4ebb-4412-9cbf-458afa412c4e@i36g2000prf.googlegroups.com> Message-ID: "Russ P." writes: > On May 26, 9:08 am, "Gabriel Genellina" > wrote: >> En Mon, 26 May 2008 06:14:19 -0300, Paul Boddie escribi?: >> >> >> I am also bothered a bit by the seeming inconsistency of the rules for >> >> the single underscore. When used at file scope, they make the variable >> >> or function invisible outside the module, but when used at class >> >> scope, the "underscored" variables or functions are still fully >> >> visible. For those who claim that the client should be left to decide >> >> what to use, why is the client prohibited from using underscored >> >> variables at file scope? >> >> > I don't remember why this is. I'll leave you to track down the >> > rationale for this particular behaviour. ;-) >> >> There is no rationale because this is not how it works... >> You can: >> - import a module and access *all* of their names, even names prefixed with an underscore >> - import any name from a module, even if it starts with an underscore >> - import * from a module, and it will import all names listed in __all__, even if they start with an underscore >> >> Only in that last case, and when the module doesn't define __all__, the list of names to be imported is built from all the global names excluding the ones starting with an underscore. And it seems the most convenient default. If one wants to access any "private" module name, any of the first two alternatives will do. >> >> -- >> Gabriel Genellina > > > Well, that's interesting, but it's not particularly relevant to the > original point. By default, underscored variables at file scope are > not made visible by importing the module in which they appear. But > underscored member variables of a class *are* made visible to the > client by default. That's seems at least slightly inconsistent to me. Apart from the fact that modules and classes are very different ideas, look at this code: ======================================== import random class A(object): def __init__(self, val): self._val = val class B(A): def f(self, other): return random.choice([self, other])._val a = A(1) b = B(2) b.f(a) ======================================== So you want the last line to return 2 if b is chosen and raise a ValueError if a is chosen. Good luck implementing that! > The issue here, for me at least, is not whether the data or methods > should be absolutely hidden from the client. I'm perfectly willing to > say that the client should have a back door -- or even a side door -- > to get access to "private" data or methods. > > But I also believe that some standard way should be available in the > language to tell the client (and readers of the code) which methods > are *intended* for internal use only. And that method should be based > on more than a naming convention. Why? Because (1) I don't like > leading underscores in my identifiers, and (2) I think I should be > free to choose my identifiers independently from their properties. Python is a dynamic language, attributes can be added to objects at any time in their life. Consider: class A(object): private x # Suspend belief for a minute... def __init__(self, x): self.x = x a = A() a.x = 2 # What behaviour do you propose here? > Is this a major issue? No. Is it a significant issue. Yes, I think so. > > Here's another suggestion. Why not use "priv" as shorthand for > "private"? Then, > > priv height = 24 > > at file scope would make "height" invisible outside the module by > default. And the same line in a class definition would give "height" > the equivalent of "protected" status in C++. > > I think "height" looks cleaner than "_height". And isn't clean code a > fundamental aspect of Python? I didn't use to be very fond of it either but I have to admit that it conveys very useful information. -- Arnaud From mnordhoff at mattnordhoff.com Sat May 10 09:26:29 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Sat, 10 May 2008 13:26:29 +0000 Subject: Simple question In-Reply-To: <205f1f1e-073b-4edc-ad18-59d1d1b065d6@59g2000hsb.googlegroups.com> References: <68lj5oF2sudm7U1@mid.individual.net> <205f1f1e-073b-4edc-ad18-59d1d1b065d6@59g2000hsb.googlegroups.com> Message-ID: <4825A285.3050002@mattnordhoff.com> Gandalf wrote: > my server is my computer and all i did way to install python on it. But what web server program are you using? Apache? IIS? Lighttpd? -- From gagsl-py2 at yahoo.com.ar Fri May 16 01:16:53 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 16 May 2008 02:16:53 -0300 Subject: Handling test data that depends on temporal data (that might change while the test runs) References: <1e5bcefd0805151021i6306946dre6e54307e91d9c1c@mail.gmail.com> <86ac1b9c0805151812i20a40908l590b342b6f1e9f52@mail.gmail.com> <1e5bcefd0805151844r2fba4141p29a0cf7d37a0a5ef@mail.gmail.com> <1e5bcefd0805151932ie56e5dcx999c5181ce799f27@mail.gmail.com> Message-ID: En Thu, 15 May 2008 23:32:38 -0300, Marcelo de Moraes Serpa escribi?: > New mantra: Test to the interfaces (as in program to the interfaces) :) Seems reasonable... > However, I'm curious on how you would test the mathprogram.divide(x,y) > function. But in this case I'm not testing the implementation. I don't > care > how the divide process is done, only that it is done correctly (10/2 = > 5). > Actually my posted example was meant to be like this: > > def test_divide > divdend = 10 > divisor = 2 > expected_result = 5 > #10/2 should be 5, so let's test if the method gets it right: > self.assertEquals(mathprogram.divide(dividend,divisor), > expected_result) Mmm, it's hard to tell in this example what's the purpose of mathprogram.divide, because Python already knows how to divide numbers. The code above is certainly a way to test the function; but aren't we testing the *Python* operator / instead of our own code? (I'm thinking of mock objects here [1] - this example is too simple, perhaps it's hard to get the idea, see the wikipedia article for a few other examples) [1] http://en.wikipedia.org/wiki/Mock_object -- Gabriel Genellina From tnelson at onresolve.com Wed May 7 15:52:05 2008 From: tnelson at onresolve.com (Trent Nelson) Date: Wed, 7 May 2008 12:52:05 -0700 Subject: REMINDER: Python Sprint Weekend This Weekend! Message-ID: <87D3F9C72FBF214DB39FA4E3FE618CDC6E249D3D17@EXMBX04.exchhosting.com> Just a friendly reminder that this weekend is the Python sprint weekend! Look forward to seeing everyone on #python-dev irc.freenode.net over the course of the weekend! Trent. On 16 Apr, 18:52, Trent Nelson wrote: > > Following on from the success of previous sprint/bugfix weekends and > sprinting efforts at PyCon 2008, I'd like to propose the next two > Global Python Sprint Weekends, taking place on the following dates: > > * May 10th-11th (four days after 2.6a3 and 3.0a5 are released) > * June 21st-22nd (~week before 2.6b2 and 3.0b2 are released) > > It seems there are a few of the Python User Groups keen on meeting > up in person and sprinting collaboratively, akin to PyCon, which I > highly recommend. I'd like to nominate Saturday across the board > as the day for PUGs to meet up in person, with Sunday geared more > towards an online collaboration day via IRC, where we can take care > of all the little things that got in our way of coding on Saturday > (like finalising/preparing/reviewing patches, updating tracker and > documentation, writing tests ;-). > > For User Groups that are planning on meeting up to collaborate, > please reply to this thread on python-dev at python.org and let every- > one know your intentions! > > As is commonly the case, #python-dev on irc.freenode.net will be > the place to be over the course of each sprint weekend; a large > proportion of Python developers with commit access will be present, > increasing the amount of eyes available to review and apply patches. > > For those that have an idea on areas they'd like to sprint on and > want to look for other developers to rope in (or just to communicate > plans in advance), please also feel free to jump on this thread via > python-dev@ and indicate your intentions. > > For those that haven't the foggiest on what to work on, but would > like to contribute, the bugs tracker at http://bugs.python.org is > the best place to start. Register an account and start searching > for issues that you'd be able to lend a hand with. > > All contributors that submit code patches or documentation updates > will typically get listed in Misc/ACKS.txt; come September when the > final release of 2.6 and 3.0 come about, you'll be able to point at > the tarball or .msi and exclaim loudly ``I helped build that!'', > and actually back it up with hard evidence ;-) > > Bring on the pizza and Red Bull! > > Trent. From __peter__ at web.de Fri May 30 14:25:57 2008 From: __peter__ at web.de (Peter Otten) Date: Fri, 30 May 2008 20:25:57 +0200 Subject: Python 2.5.2 on Ubuntu Hardy Utf-8-Euro error References: <4840407c$0$4845$9b622d9e@news.freenet.de> Message-ID: "Martin v. L?wis" wrote: >>> File >>> "/usr/lib/python2.5/site-packages/Dabo-0.8.3-py2.5.egg/dabo/db/dCursorMixin.py", >>> line 281, in execute >>> sql = unicode(sql, self.Encoding) >>> LookupError: unknown encoding: utf_8_euro >> >> At the application (DABO) mailing list, they have pointed that this has >> to be a Python issue. > > It's definitely not a Python issue. > >> As I'm a totally python newbie, I would ask if >> somebody has experimented this kind of error, and if there is any known >> solution. I've found no clue searching at Google right now. > > The problem is that self.Encoding is incorrect - it should not be > utf_8_euro. Instead, it should be UTF-8 (or perhaps utf_8). DABO > shouldn't use locale.getdefaultlocale()[1], but > locale.getpreferredencoding(). I think that is the effect of a bug: >>> locale._parse_localename("en_US.UTF-8 at euro") ('en_US', 'utf_8_euro') The function first normalizes the "@" away and then looks for it. Is that the expected behaviour? Peter From skunkwerk at gmail.com Fri May 9 00:30:32 2008 From: skunkwerk at gmail.com (skunkwerk) Date: Thu, 8 May 2008 21:30:32 -0700 (PDT) Subject: threading - race condition? References: Message-ID: <7e4721aa-4dac-466c-b884-6314ead136b6@q1g2000prf.googlegroups.com> On May 8, 4:54 pm, castiro... at gmail.com wrote: > On May 8, 5:45 pm, skunkwerk wrote: > > > > > i'm getting the wrong output for the 'title' attributes for this > > data. the queue holds a data structure (item name, position, and list > > to store results in). each thread takes in an item name and queries a > > database for various attributes. from the debug statements the item > > names are being retrieved correctly, but the attributes returned are > > those of other items in the queue - not its own item. however, the > > model variable is not a global variable... so i'm not sure what's > > wrong. > > > i've declared a bunch of workerthreads(100) and a queue into which > > new requests are inserted, like so: > > > queue = Queue.Queue(0) > > WORKERS=100 > > for i in range(WORKERS): > > thread = SDBThread(queue) > > thread.setDaemon(True) > > thread.start() > > > the thread: > > > class SimpleDBThread ( threading.Thread ): > > def __init__ ( self, queue ): > > self.__queue = queue > > threading.Thread.__init__ ( self ) > > def run ( self ): > > while 1: > > item = self.__queue.get() > > if item!=None: > > model = domain.get_item(item[0]) > > logger.debug('sdbthread item:'+item[0]) > > title = model['title'] > > scraped = model['scraped'] > > logger.debug("sdbthread title:"+title) > > > any suggestions? > > thanks > > I'll base this on terminology: if a model is in a brain (throughout > the known universe), and a dollar's a dollar, it may not pay to build > a computer out of brains. > > If man arises as a tool-carrier, we will carry tools, not people. > Don't use Python to make people; make money, and not too much. Pick a > wage and you might get somewhere. excuse me? From jschroed at gmail.com Thu May 8 22:50:20 2008 From: jschroed at gmail.com (John Schroeder) Date: Thu, 8 May 2008 19:50:20 -0700 Subject: How can I add spaces where ever I have capital letters? In-Reply-To: <55f521b4-c6eb-4668-b15e-01ba8d7bee47@k10g2000prm.googlegroups.com> References: <4878ad7b0805081812l2a3412abh185a832866be2878@mail.gmail.com> <55f521b4-c6eb-4668-b15e-01ba8d7bee47@k10g2000prm.googlegroups.com> Message-ID: <4878ad7b0805081950x309c4f6s9b260261c39183e9@mail.gmail.com> I do like one-liners and do not like regexps! That code puts mine to shame... Thanks for the tip. I'll use that one instead. On Thu, May 8, 2008 at 7:40 PM, Dan Bishop wrote: > > On Thu, May 8, 2008 at 9:12 PM, John Schroeder > wrote: > > > I have a string (which I got from the names of my classes) and I would > like > > > to print out my CamelCase classes as titles. > > > > > I would like it to do this: > > > > >>>> my_class_name = "ModeCommand" > > > ## Do some magic here > > >>>> my_class_name > > > 'Mode Command' > > > > > Anyone know any easy way to do this? Thanks. > > On May 8, 9:04 pm, "Eric Wertman" wrote: > > Something like this. I'm sure there are other ways to do it. > > > > import re > > > > def addspace(m) : > > return ' ' + m.group(0) > > > > strng = "ModeCommand" > > > > newstr = re.sub('[A-Z]',addspace,strng) > > > > print newstr.strip() > > Yes, there are other ways to do it. If, for example, you like one- > liners but not regexps: > > def add_spaces(text): > return text[:1] + ''.join((' ' + char if char.isupper() else char) > for char in text[1:]) > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From duncan.booth at invalid.invalid Sun May 11 15:55:31 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 11 May 2008 19:55:31 GMT Subject: File Creation Not Working In A Thread Class? References: <7qGVj.32505$KJ1.18416@newsfe19.lga> Message-ID: 7stud wrote: >> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? > ? ? ? ? ? ? ? ? ? ? ? ? ? ? tempfileName = "\"proctemp\\" + > self.matrix[c][0] + "_other.txt\"" It wouldn't exactly result in either of the error messages you posted, but I expect the spurious quote marks round the filename will be giving you problems. Surely you want the filename to be something like 'proctemp\fred_other.txt' rather than '"proctemp\fred_other.txt"' with the spurious double quotes? From paul at science.uva.nl Tue May 13 06:54:39 2008 From: paul at science.uva.nl (Paul Melis) Date: Tue, 13 May 2008 12:54:39 +0200 Subject: Backslash frowned upon? In-Reply-To: <230658ee-4b4e-48e7-b06a-88af33a5167c@25g2000hsx.googlegroups.com> References: <230658ee-4b4e-48e7-b06a-88af33a5167c@25g2000hsx.googlegroups.com> Message-ID: wxPythoner at gmail.com wrote: > Why is the \ backslash character frowned upon? Can I still use it in > Python 3.0 to achieve the same thing it was designed to do? Yes, it's still valid to use in a script. See http://docs.python.org/dev/3.0/whatsnew/3.0.html for the big changes coming with 3.0 Paul From takaurai at gmail.com Thu May 29 06:32:26 2008 From: takaurai at gmail.com (=?ISO-2022-JP?B?GyRCJD8kKxsoQg==?=) Date: Thu, 29 May 2008 03:32:26 -0700 (PDT) Subject: How do I tell "imconplete input" from "valid input"? References: <52dfcd24-3182-4dc7-9141-4324864783e5@g16g2000pri.googlegroups.com> Message-ID: thanks for your reply. I tried below python codes with "Py_single_input" instead of "Py_file_input". sample 1 : result is INCOMPLETE for i in range(3):\n sample 2 : result is COMPLETE(I want to get INCOMPLETE or something) for i in range(3):\n\tprint i or for i in range(3):\n\tprint i\n "Py_single_input" and "Py_file_input" seem the same. How come? > Plz check details in Grammar/Grammar from python source distribution thanks. I challenge it. --urai From rossgk at gmail.com Wed May 28 12:04:33 2008 From: rossgk at gmail.com (RossGK) Date: Wed, 28 May 2008 09:04:33 -0700 (PDT) Subject: Python Threads - stopped vs. gone vs. Alive References: <1495901c-62c0-4977-8623-46deee092b56@26g2000hsk.googlegroups.com> Message-ID: <2007b7d8-6548-4bf6-af91-71208930db27@2g2000hsn.googlegroups.com> On May 28, 12:01 pm, RossGK wrote: > I'm a newbie to python threads, and playing with some simple client > server stuff and lots of print statements. > > My server thread launched with > self.worker = WorkerThread(self) > completes an interaction and then if I check on it's status with > print "Status:", self.worker I get Status none > > A client thread behaves differently. Launched as > self.clientWorker( = ClientThreadself) > when it finishes it's work, I instead get: > Status: > > If I check the isAlive status on each of those, self.worker.isAlive > throws an exception, 'cause there is nothing there anymore to check > isAlive on. But self.clientWorker comes back as False, since it is a > stopped thread and hasn't gone away (which I'd like it to after it > finishes its work). > > So my question is when a thread finishes its work how do I more > predictably control whether it is just stopped, or goes away all > together? I don't want to do a double nested 'if' statement to check > if it exists before I check if it's alive. Pls ignore the obvious typos, this isn't a syntax question and google groups seems to be messing with my typing and spacing(!) e.g. > self.clientWorker( = ClientThreadself) should have read self.clientWorker = ClientThread(self) As I swear I had typed it... From cbc at unc.edu Mon May 19 14:01:48 2008 From: cbc at unc.edu (Chris Calloway) Date: Mon, 19 May 2008 14:01:48 -0400 Subject: Python and Plone Boot Camps in Chapel Hill, NC Message-ID: <4831C08C.1090706@unc.edu> Triangle (NC) Zope and Python Users Group (TriZPUG) is proud to open registration for our fourth annual ultra-low cost Plone and Python training camps, BootCampArama 2008: http://trizpug.org/boot-camp/2008/ Registration is now open for: PyCamp: Python Boot Camp, August 4 - 8 Plone Boot Camp: Customizing Plone, July 28 - August 1 Advanced Plone Boot Camp: Plone 3 Techniques, August 4 - 8 All of these take place on the campus of the University of North Carolina at Chapel Hill in state of the art high tech classrooms, with free mass transit, low-cost accommodations with free wireless, and convenient dining options. Plone Boot Camp is taught by Joel Burton, twice chair of the Plone Foundation. Joel has logged more the 200 days at the head of Plone classrooms on four continents. See plonebootcamps.com for dozens of testimonials from Joel's students. PyCamp is taught by Chris Calloway, facilitator for TriZPUG and application analyst for the Southeast Coastal Ocean Observing System. Chris has developed PyCamp for over 1500 hours on behalf of Python user groups. Early bird registration runs through June 30. So register today! PyCamp is TriZPUG's Python Boot Camp, which takes a programmer familiar with basic programming concepts to the status of Python developer with one week of training. If you have previous scripting or programming experience and want to step into Python programming as quickly and painlessly as possible, this boot camp is for you. PyCamp is also the perfect follow-on to Plone Boot Camp: Customizing Plone the previous week. At Plone Boot Camp: Customizing Plone you will learn the essentials you need to build your Plone site and deploy it. This course is the most popular in the Plone world--for a good reason: it teaches you practical skills in a friendly, hands-on format. This bootcamp is aimed at: * people with HTML or web design experience * people with some or no Python experience * people with some or no Zope/Plone experience It covers using Plone, customizing, and deploying Plone sites. At Advanced Plone Boot Camp: Plone 3 Techniques you will learn to build a site using the best practices of Plone 3 as well as advance your skills in scripting and developing for Plone. The course covers the new technologies in Plone 3.0 and 3.1 intended for site integrators and developers: our new portlet infrastructure, viewlets, versioning, and a friendly introduction to Zope 3 component architecture. Now, updated for Plone 3.1! The course is intended for people who have experience with the basics of Plone site development and HTML/CSS. It will cover what you need to know to take advantage of these new technologies in Plone 3. For more information contact: info at trizpug.org From bignose+hates-spam at benfinney.id.au Fri May 23 22:23:13 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 24 May 2008 12:23:13 +1000 Subject: unittest: Calling tests in liner number order References: Message-ID: <87hccocuem.fsf@benfinney.id.au> Antoon Pardon writes: > The answers seemed to be negative. Since I really would like this > behaviour I didn't see you explain *why* you think this behaviour is desirable. You've already had responses that explained why it leaves you open to more bugs when code only works if tests run in a specific order. > Are other people interrested in this behaviour? > Does the following patch has a chance of being introduced in the > standard python distribution? No and no. If anything, unit test cases should be run in a completely *non*-deterministic sequence. -- \ "In prayer, it is better to have a heart without words than | `\ words without heart." -- Mahatma Gandhi | _o__) | Ben Finney From upton at virginia.edu Fri May 16 14:28:27 2008 From: upton at virginia.edu (Dan Upton) Date: Fri, 16 May 2008 14:28:27 -0400 Subject: writing python extensions in assembly In-Reply-To: References: Message-ID: <5504f9ac0805161128t798f630br721c6a65e92fdbd9@mail.gmail.com> On Fri, May 16, 2008 at 2:08 PM, inhahe wrote: > > "Dan Upton" wrote in message > news:mailman.1236.1210959884.12834.python-list at python.org... > > >> >> On Fri, May 16, 2008 at 1:27 PM, Mensanator wrote: >>> >>> Why wouldn't the compilers support it? It's part of the x86 >>> architexture, >>> isn't it? >> >> Yeah, but I don't know if it uses it by default, and my guess is it >> depends on how the compiler back end goes about optimizing the code >> for whether it will see data access/computation patterns amenable to >> SIMD. > > perhaps you explicitly use them with some extended syntax or something? > Hey, I learned something today. http://www.tuleriit.ee/progs/rexample.php Also, from the gcc manpage, apparently 387 is the default when compiling for 32 bit architectures, and using sse instructions is default on x86-64 architectures, but you can use -march=(some architecture with simd instructions), -msse, -msse2, -msse3, or -mfpmath=(one of 387, sse, or sse,387) to get the compiler to use them. As long as we're talking about compilers and such... anybody want to chip in how this works in Python bytecode or what the bytecode interpreter does? Okay, wait, before anybody says that's implementation-dependent: does anybody want to chip in what the CPython implementation does? (or any other implementation they're familiar with, I guess) From casey.mcginty at gmail.com Wed May 28 01:09:27 2008 From: casey.mcginty at gmail.com (Casey McGinty) Date: Tue, 27 May 2008 19:09:27 -1000 Subject: Struct usages in Python In-Reply-To: References: Message-ID: > self.event[] = Event() *# Seems this is not allowed ?? * > self.event = [Event()] - Casey -------------- next part -------------- An HTML attachment was scrubbed... URL: From znfmail-pythonlang at yahoo.com Tue May 27 11:13:49 2008 From: znfmail-pythonlang at yahoo.com (Poppy) Date: Tue, 27 May 2008 11:13:49 -0400 Subject: CGI question References: <69vg5qF34vemeU1@mid.uni-berlin.de> Message-ID: Can you consider a webservice under something like CherryPY, rather than cgi? It may provide more options. "Rohan" wrote in message news:bf1929ee-647b-4046-b1ea-d693020503a2 at w1g2000prd.googlegroups.com... > Thanks Diez for your suggestion. > >> >> The only way I can think of is to regularly output something inside the >> CGI, >> and thus make it fail in the very moment the pipe is closed. >> > > I also thought of this, but this looks little crude approach. > The problem seems very generic I was wondering if it could be handled > more > gracefully by some configuration in Apache or cgi script. > > Apache process handling the request would close the connection with > client, > but it won't notify anything to spawned CGI process, so it keeps > running. > > From yves at zioup.com Mon May 12 23:25:51 2008 From: yves at zioup.com (Yves Dorfsman) Date: Tue, 13 May 2008 03:25:51 GMT Subject: anonymous assignment In-Reply-To: <68q50pF2u2t25U2@mid.uni-berlin.de> References: <1XNVj.133805$Cj7.33096@pd7urf2no> <7xmymwuu25.fsf@ruckus.brouhaha.com> <68q50pF2u2t25U2@mid.uni-berlin.de> Message-ID: <3T7Wj.134606$rd2.31796@pd7urf3no> Marc 'BlackJack' Rintsch wrote: >>> y, _, d, _, _, _, _, _, _ = time.localtime() >> But you still have have a variable that's using memory for nothing. I >> find this unsatisfactory... > > Get over it? Than what's the point of wanting a better language if every time we run in something that looks wrong, or something that could be done better we should just "get over it" ? Yves. From larry.bates at websafe.com` Fri May 30 09:43:39 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Fri, 30 May 2008 08:43:39 -0500 Subject: Generating event from event In-Reply-To: <37f8a6a1-dc98-4985-a84d-f74ead1ec2b7@z72g2000hsb.googlegroups.com> References: <37f8a6a1-dc98-4985-a84d-f74ead1ec2b7@z72g2000hsb.googlegroups.com> Message-ID: Gandalf wrote: > I have script which being triggered by pressing CTRL+Right mouse click > from any place in my O.P , Now I need to generate automatically event > like copy my selected item or double clicking the right mouse cursor > without user interfering. > how can i implement this width python? > > > thanks! You didn't tell us enough to answer your question. What GUI are you using? Nearly every one of them that I'm aware of allow you to register handlers for such events. -Larry From alexelder at gmail.com Mon May 5 06:47:51 2008 From: alexelder at gmail.com (alexelder at gmail.com) Date: Mon, 5 May 2008 03:47:51 -0700 (PDT) Subject: How to pass a multiline arg to exec('some.exe arg')? References: <7b6965a2-193d-42cf-8fad-2ad97c8de27b@i76g2000hsf.googlegroups.com> Message-ID: <7aadfbc6-f42a-4c63-91a2-a90acf9376af@r66g2000hsg.googlegroups.com> On May 5, 10:25 am, n00m wrote: > os:windows > ml = 'line1 \n line2 \n line3 \n' > exec('some.exe "' + ml + '"') > > and some.exe get only 'line1'... I think your problem lies with your "\n", escape chars. Assuming these are not arguments and are indeed separating statements, I suggest replacing "\n", with "&". That way, the command shell probably wont complain. An example: ml = 'line1 & line2 & line3' Alex. From martin at v.loewis.de Sun May 25 23:28:33 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 26 May 2008 05:28:33 +0200 Subject: set partition question In-Reply-To: <3b08539b-d4ba-4616-86df-529fceeeef01@q24g2000prf.googlegroups.com> References: <4839c866$0$32633$9b622d9e@news.freenet.de> <3b08539b-d4ba-4616-86df-529fceeeef01@q24g2000prf.googlegroups.com> Message-ID: <483a2e61$0$21475$9b622d9e@news.freenet.de> > There may be arbitrarily many set elements (denoted by integers > 1,2,3,...), arbitrarily many combinations of the elements composing > the sets s_i (s0, s1, ...). We can use any of python's set operations > or combination of those operations. That still allows for trivial solutions: Given s0, and s1..sn, the following Python code outputs a Python fragment that, when run, returns s0: print "set()", for e in s0: print ".union(set([%s]))" % repr(e), For s0=set([1,2,3]), I get set() .union(set([1])) .union(set([2])) .union(set([3])) Or, more trivially, print repr(s0) which gives me set([1,2,3]) In either case, s0 is generated through "any of python's set operations". Regards, Martin From sjmachin at lexicon.net Sun May 11 01:04:05 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 10 May 2008 22:04:05 -0700 (PDT) Subject: do you fail at FizzBuzz? simple prog test References: <39709320-66e1-40e9-a351-c769c9a94585@x41g2000hsb.googlegroups.com> Message-ID: On May 11, 1:24 pm, Mensanator wrote: > On May 10, 8:12?pm, globalrev wrote: > > > > >http://reddit.com/r/programming/info/18td4/comments > > > claims people take a lot of time to write a simple program like this: > > > "Write a program that prints the numbers from 1 to 100. But for > > multiples of three print "Fizz" instead of the number and for the > > multiples of five print "Buzz". For numbers which are multiples of > > both three and five print "FizzBuzz". > > > for i in range(1,101): > > ? ? if i%3 == 0 and i%5 != 0: > > ? ? ? ? print "Fizz" > > ? ? elif i%5 == 0 and i%3 != 0: > > ? ? ? ? print "Buzz" > > ? ? elif i%5 == 0 and i%3 == 0: > > ? ? ? ? print "FizzBuzz" > > ? ? else: > > ? ? ? ? print i > > > is there a better way than my solution? is mine ok? > > Define better. > > >>> f = ['','','Fizz']*100 > >>> b = ['','','','','Buzz']*100 > >>> for i in xrange(1,100): > > fb = f[i-1]+b[i-1] > if fb=='': > print i > else: > print fb You seem to have an unfortunate fixation on 100. Consider changing the above instances to 34, 20, and 101. From half.italian at gmail.com Thu May 1 21:17:37 2008 From: half.italian at gmail.com (Sean DiZazzo) Date: Thu, 1 May 2008 18:17:37 -0700 (PDT) Subject: TypeError: unsupported operand type(s) for /: 'NoneType' and 'NoneType' References: Message-ID: On May 1, 5:21?pm, "Jordan Harry" wrote: > I'm trying to write a simple program to calculate permutations. ?I created a file called "mod.py" and put the following in it: > > def factorial(n): > ? ? a = n > ? ? b = n > ? ? while a>0 and b>1: > ? ? ? ? n = (n)*(b-1) > ? ? ? ? b = b-1 > > def perm(n, r): > ? ? a = factorial(n) > ? ? b = factorial(n-r) > ? ? q = a / b > ? ? print q > > Then I went back to IDLE and input the following: > > >>> import mod > >>> mod.perm(5, 4) > > I recieved the following error message: > > Traceback (most recent call last): > ? File "", line 1, in > ? ? mod.perm(5, 4) > ? File "C:\Python25\mod.py", line 27, in perm > ? ? q = a / b > TypeError: unsupported operand type(s) for /: 'NoneType' and 'NoneType' > > I have no idea how to fix it. ?I'm pretty new to Python. ?I have IDLE 1.2.2 and Python 2.5.2, > > Please help. Your factorial function needs to return something. ~Sean From cokofreedom at gmail.com Wed May 21 09:28:35 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Wed, 21 May 2008 06:28:35 -0700 (PDT) Subject: C-like assignment expression? References: <68b5d090-9e3b-4e7d-9dda-fc1b099822c2@m73g2000hsh.googlegroups.com> <48340412$0$10773$426a74cc@news.free.fr> <87fxsbzxn4.fsf@mulj.homelinux.net> <7df99fd4-21c9-49a1-ba65-e55794fd4c12@26g2000hsk.googlegroups.com> Message-ID: <75ca6227-435c-46bf-8701-aa326d3533e0@p25g2000hsf.googlegroups.com> On May 21, 3:12 pm, "boblat... at googlemail.com" wrote: > On May 21, 1:47 pm, Hrvoje Niksic wrote: > > > Although that solution is pretty, it is not the canonical solution > > because it doesn't cover the important case of "if" bodies needing to > > access common variables in the enclosing scope. (This will be easier > > in Python 3 with 'nonlocal', though.) The snippet posted by Diez is > > IMHO closer to a canonical solution to this FAQ. > > Hello everybody, > > thanks for the various answers. I'm actually pretty puzzled because I > expected to see some obvious solution that I just hadn't found before. > In general I find Python more elegant and syntactically richer than C > (that's where I come from), so I didn't expect the solutions to be a > lot more verbose and/or ugly (no offense) than the original idea which > would have worked if Python's assignment statement would double as > expression, as in C. > > Thanks again, > robert > > PS: Since I'm testing only three REs, and I only need the match > results from one of them, I just re-evaluate that one. Is it really a lot to change to have it if my_re1.match(line): match = my_re1.match(line) elseif my_re2.match(line): match = my_re2.match(line) elseif my_re3.match(line): match = my_re3.match(line) ? That reads clearly to me... From srinivas.puvvala at gmail.com Wed May 21 08:31:50 2008 From: srinivas.puvvala at gmail.com (srinivas) Date: Wed, 21 May 2008 05:31:50 -0700 (PDT) Subject: about python modules Message-ID: <2fc55c56-7408-4f44-b6e2-64f85f341ac9@i36g2000prf.googlegroups.com> hi friends i am new to python programming. i am using Python 2.5 and IDLE as editor. i have developed some functions in python those will be calling frequently in my main method . now i want to know how to import my functions folder to python in sucha way that the functions in functions folder should work like python library modules . i have python in folder C:\python25\.. and functions folder D:\programs\Functions\ pls help me friends how to do that. From notnorwegian at yahoo.se Mon May 19 23:34:22 2008 From: notnorwegian at yahoo.se (notnorwegian at yahoo.se) Date: Mon, 19 May 2008 20:34:22 -0700 (PDT) Subject: conventions/requirements for 'is' vs '==', 'not vs '!=', etc References: <4dc24f2e-04f5-4ad6-b021-f416ef5c7415@z72g2000hsb.googlegroups.com> <8ebd28f1-887f-45c9-a35f-af9023b062ea@u12g2000prd.googlegroups.com> Message-ID: <3629843a-ebcb-4f15-82f1-899500f7b91f@t54g2000hsg.googlegroups.com> i am confused. x=5 y=5 x==y -> True x is y -> True shouldnt x is y return False since they shouldnt(dont?) point to the same place in memory, they just store an equal value? From ivan.illarionov at gmail.com Tue May 13 00:22:52 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Tue, 13 May 2008 04:22:52 +0000 (UTC) Subject: how to get information of a running prog in python References: <8b571818-25f0-4c5d-8b1c-5b7e73192d15@w5g2000prd.googlegroups.com> <58a5cb5c-5c10-43a3-bff0-58fa3c213a80@i36g2000prf.googlegroups.com> Message-ID: On Mon, 12 May 2008 20:29:46 -0700, George Sakkis wrote: > On May 12, 11:02?pm, Jimmy wrote: >> On May 13, 10:36 am, "Dan Upton" wrote: >> >> >> >> > On Mon, May 12, 2008 at 10:19 PM, Jimmy >> > wrote: >> > > Well, i know it may be a little non-python thing, however, I can >> > > think >> > > ?of no place better to post this question :) >> >> > > ?can anyone tell me, in python, how to obtain some information of >> > > ?a running program? >> > > ?paticularly, if i am playing some music in audacious or other >> > > ?media player, how can i get the the name and some other info of >> > > ?current playing song? It seems that audicious doesn't output on >> > > ?run-time -- >> > > ?http://mail.python.org/mailman/listinfo/python-list >> >> > In most cases, you'll probably need some sort of API, either in the >> > program itself or through some sort of plugin, that lets external >> > programs query it. ?For instance, there are some plugins to WinAmp >> > that allow external programs (like Last.FM or Mog-O-Matic) to see >> > what track is currently playing. ?You may also be able to do >> > something like get the window title (again, WinAmp's title bar >> > usually includes the artist and title) and parse it out. ?I don't >> > really know that there's anything specific to Python for accessing >> > these though, and it may vary depending on media player. >> >> > Just my two cents... >> >> > -dan >> >> thanks! >> >> In linux, I am always obfuscated by sort of APIs. Like how to get title >> information of a running program? where am I supposed to find these >> APIs > > I think you're a little confused about how computers work in general and > what a program can do, and you expect there is some general superprogram > able to decipher what an arbitrary other running program does. The > sentence "how to get title information of a running program" doesn't > even make sense for most programs since they don't play music anyway. > > Your best bet is if the *specific* program you're interested in (e.g. > audacious) exposes this information programmatically in some way. It's > up to the developers of this application if and how they choose to do > it. Even if they do it, there's no requirement that the same API will > work for any other program of the same category, unless there is some > popular industry standard that most applications implement. > > In short, you'll get more helpful replies at the audacious newsgroup. > > HTH, > George George, have you read my post in this thread? What OP wants is actually possible and it's quite easy. X server is the "superprogram" that knows the names of all GUI window titles. -- Ivan From iainking at gmail.com Tue May 13 10:06:07 2008 From: iainking at gmail.com (Iain King) Date: Tue, 13 May 2008 07:06:07 -0700 (PDT) Subject: wxpython dialog - do something after ShowModal()? References: <46508224-d4c6-4982-a29f-04d29b3d5a2c@m36g2000hse.googlegroups.com> Message-ID: <7f058ac1-e3e9-4d56-adf5-45ccc105f078@z72g2000hsb.googlegroups.com> On May 13, 2:43 pm, Iain King wrote: > On May 13, 2:20 pm, Larry Bates wrote: > > > > > Iain King wrote: > > > Hi. I have a modal dialog whcih has a "Browse..." button which pops > > > up a file selector. This all works fine, but the first thing the user > > > has to do when they open the dialog is select a file, so I would like > > > the dialog to automatically call the onBrowse function as soon as the > > > dialog opens. However, I don't know how to do this. > > > > dlg.ShowModal() > > > onBrowse() > > > > obviously doesn't work, and neither does the reverse. I was hoping > > > that the dialog would throw some kind of "I have been shown" event, > > > but it doesn't (as far as I can tell). How do I make the dialog do > > > something as soon as it's been shown? > > > > Iain > > > If the only things on your modal dialog are Browse and cancel, just call the > > wx.FileDialog directly and eliminate the intermediate modal dialog. If not > > don't bind the FileDialog to a button, just create an instance of it as the last > > you do in the __init__ method of the modal dialog code. > > > If this doesn't help, you will have better luck posting to wxpython newsgroup. > > > -Larry > > The dialog doesn't only let you call the file dialog, it does other > stuff too. Your suggestion of __init__ sounded promising, but neither > giving the dialog an __init__() method nor an OnInit() method worked. > Thanks anyway. > > Iain After having a hunt through the wxpython mailing list archives I found the answer: the event is EVT_INIT_DIALOG: dlg.Bind(wx.EVT_INIT_DIALOG, onInit, dlg) work. Thanks for the pointer. Iain From oyinbo55 at gmail.com Sun May 4 08:42:48 2008 From: oyinbo55 at gmail.com (oyinbo55) Date: Sun, 4 May 2008 05:42:48 -0700 (PDT) Subject: matplotlib pylab plot() BadWindow error Message-ID: <16f10cf9-a966-4492-891b-d6aedb9ad428@p25g2000hsf.googlegroups.com> I am trying to use the pylab plot command on my laptop running Ubuntu 6.06 (Dapper). Although the plot command works fine on my XP desktop at work, I cannot open the plot window on the laptop. I edited matplotlibrc to change interactive: to "True". In idle, I entered the commands: >>> from pylab import * >>> plot([1,2,3]) The terminal window closed abruptly when I typed the closing parenthesis. I have been warned not to use the show() command in interactive mode. I tried: oyinbo at oyinbo-laptop:~$ idle-python2.4 -n In idle -n, I entered the sam two commands. This time I got an error message: The program 'idle-python2.4' received an X Window System error. This probably reflects a bug in the program. The error was 'BadWindow (invalid Window parameter)'. (Details: serial 2875 error_code 3 request_code 15 minor_code 0) (Note to programmers: normally, X errors are reported asynchronously; that is, you will receive the error a while after causing it. To debug your program, run it with the --sync command line option to change this behavior. You can then get a meaningful backtrace from your debugger if you break on the gdk_x_error() function.) Using the Python prompt without idle, I got no error message, but the window simply didn't open: oyinbo at oyinbo-laptop:~$ python Python 2.4.3 (#2, Mar 7 2008, 01:58:20) [GCC 4.0.3 (Ubuntu 4.0.3-1ubuntu5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from pylab import * >>> plot([1,2,3]) [] Have I skipped a step? Thanks for all the great information on your group. Bill From not_here at no_where.com Sun May 18 20:56:30 2008 From: not_here at no_where.com (Brian) Date: Sun, 18 May 2008 17:56:30 -0700 Subject: How do *you* use Python in non-GUI work? In-Reply-To: <20080518182022.990193bd.johnjsal@NOSPAMgmail.com> References: <20080518182022.990193bd.johnjsal@NOSPAMgmail.com> Message-ID: <1f4Yj.60053$Fc1.23579@newsfe07.phx> John Salerno wrote: > Hey all. Just thought I'd ask a general question for my own interest. Every time I think of something I might do in Python, it usually involves creating a GUI interface, so I was wondering what kind of work you all do with Python that does *not* involve any GUI work. This could be any little scripts you write for your own benefit, or what you do at work, if you feel like talking about that! :) > > Thanks. here is some non-text stuff that I have done within the last two or three years 1. controlling and parsing thousands of label files several times per day, that are used by the factory to drive the printers that make product safety labels - code was easily approved by UL and CSA. 2. real-time control of platform in EMC lab for radiated emissions testing. 3. hi-speed data acquisition of 3 to 20 parameters during simulated abnormal operating conditions to demonstrate product compliance with product safety standards. 4. monitoring of several server logs, also sends email to me if it finds something it does not like. 5. parallel monitor/control systems for several greenhouses. From mnikhil at gmail.com Tue May 20 13:30:09 2008 From: mnikhil at gmail.com (Nikhil) Date: Tue, 20 May 2008 23:00:09 +0530 Subject: AttributeError: module object has no attribute Message-ID: I have recently written a small module. When I import the module, I always get the error only when I do >>> from local.my.module import * -- Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute '/xyz/py/file' --- but when I do the below, I do not get any error. -- >> import local.my.module >> -- Any ideas on what could be wrong? Thanks in advance. Nikhil From mccredie at gmail.com Fri May 2 02:17:08 2008 From: mccredie at gmail.com (Matimus) Date: Thu, 1 May 2008 23:17:08 -0700 (PDT) Subject: help with list comprehension References: Message-ID: <7917a0b4-7af2-46f0-adec-33d3b191eb17@y22g2000prd.googlegroups.com> On May 1, 10:50 pm, George Sakkis wrote: > On May 1, 11:46 pm, Carsten Haese wrote: > > > > > Yves Dorfsman wrote: > > > > In the following script, m1() and m2() work fine. I am assuming m2() is > > > faster although I haven't checked that (loops through the list twice > > > instead of once). > > > Well, let's check it: > > > $ python -m timeit -s "import x" "x.m1()" > > 100000 loops, best of 3: 6.43 usec per loop > > > $ python -m timeit -s "import x" "x.m2()" > > 100000 loops, best of 3: 8.34 usec per loop > > > As it turns out, m1 is faster than m2. The reason is that list > > comprehensions do the loop in C, whereas the for-append pattern does the > > loop on the Python level. > > > > Now what I am trying to do is something like m3(). As currently written > > > it does not work, and I have tried different ways, but I haven't managed > > > to make it work. > > > > Is there a possibility ? Or is m2() the optimum ? > > > > [...] > > > def m1(): > > > colours = [ e['colour'] for e in l ] > > > nums = [ e['num'] for e in l ] > > > > def m2(): > > > colours = [] > > > nums = [] > > > for e in l: > > > colours.append(e['colour']) > > > nums.append(e['num']) > > > > #def m3(): > > > # colours, nums = [ e['colour'], e['num'] for e in l ] > > > m3 doesn't work because you're building a list of 10 color/number pairs > > that you're trying to unpack that into just two names. The working > > "derivative" of m3 is m1, which is the most natural, fastest and > > clearest solution to your problem. > > Another alternative is: > > from operator import itemgetter > > def m3(): > colours, nums = zip(*map(itemgetter('colour','num'), l)) > > It's slower than m1() but faster than m2(); it's also the most > concise, especially if you extract more than two keys. > > George Why deal with zip and unpacking? This seems more obvious to me: colours, nums = map(itemgetter('colour'), l), map(itemgetter('num'), l) Matt From jstucklex at attglobal.net Mon May 26 19:42:20 2008 From: jstucklex at attglobal.net (Jerry Stuckle) Date: Mon, 26 May 2008 19:42:20 -0400 Subject: php vs python In-Reply-To: <5IH_j.3432$tF1.2671@trnddc01> References: <5l%Yj.77$mz3.53@fe101.usenetserver.com> <7xwslnwa3s.fsf@ruckus.brouhaha.com> <5IH_j.3432$tF1.2671@trnddc01> Message-ID: Curtis wrote: > Paul Rubin wrote: >> notbob writes: >>> Well, that's my actual question, then. Is php really so bad I'm just >>> wasting my time? Or is it really the quickest way to blog >>> functionality? >> >> php is very easy to get started with and some big sites have been >> written in it. There is lots of low cost php hosting available. It >> is not as good a language as Python. However, Python's advantages are >> strongest in more complex projects. For simple stuff, php is frankly >> less hassle just because of its wide deployment and that extensive >> function library that the blog post your quoted described as a bad >> thing. Python's libraries are not bad, but php's are more intensely >> focused on web apps and includes what you need as part of the standard >> build. With Python, if you want a database adapter or web template >> framework, you have to choose between a bunch of different ones and >> download and configure it which often involves head scratching when >> the auto-install stuff hits some quirk of your system. With php, it's >> all right there when you flip the switch. >> >> Knowing lots of languages is good for you. php is probably your >> quickest route to getting a rudimentary web app running. Python >> is a longer term project. Do both. > > PHP is more than capable for handling large projects, not just small > scripting jobs. However, Paul's right about PHP being more driven toward > web development, where as Python may be better for different types of apps. > > Even then, I think your first reply was best, it just comes down to what > you have more fun writing. Both languages are equally capable of getting > the job done. > > -- > Curtis Not true. PHP is quite capable of writing large, non-web based projects. While it's non-browser based display capabilities are somewhat lacking (although there are third party libraries which help a lot), I've written some pretty complicated batch scripts in the past. -- ================== Remove the "x" from my email address Jerry Stuckle JDS Computer Training Corp. jstucklex at attglobal.net ================== From rajarshi.guha at gmail.com Wed May 14 12:13:42 2008 From: rajarshi.guha at gmail.com (Rajarshi) Date: Wed, 14 May 2008 09:13:42 -0700 (PDT) Subject: usage of python References: Message-ID: <4ba3a7d9-19a8-4463-981c-dea90ee085fc@24g2000hsh.googlegroups.com> Thanks to the all posters. This will be very useful! From p.wallstedt at gmail.com Thu May 15 11:03:40 2008 From: p.wallstedt at gmail.com (p.wallstedt at gmail.com) Date: Thu, 15 May 2008 08:03:40 -0700 (PDT) Subject: pyserial and file open conflict? Message-ID: <21c8f220-aa3c-40b8-b1de-3aa35472e2dc@26g2000hsk.googlegroups.com> Hi all! I have a small but rather annoying problem with pyserial. I want to open a file on disk for reading and then open a com-port, write lines from the file to the port and then read something back and compare it to the next line in the file. Should be simple. And it is, apart from the fact that the file seems to be doubled ...? Or it loops through the file twice. If I exclude the "import serial" it works. Any ideas? thanks Peter From duncan.booth at invalid.invalid Thu May 8 03:56:12 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 8 May 2008 07:56:12 GMT Subject: The del statement References: <02860f2a-cd1d-4b1d-ad49-08b13032ba21@2g2000hsn.googlegroups.com> Message-ID: Arnaud Delobelle wrote: > > > George Sakkis wrote: >> One of the few Python constructs that feels less elegant than >> necessary to me is the del statement. For one thing, it is overloaded >> to mean three different things: >> (1) del x: Remove x from the current namespace >> (2) del x[i]: Equivalent to x.__delitem__(i) >> (3) del x.a: Equivalent to x.__delattr__('a') (or delattr(x,'a')) > > Note that the 'X = Y' construct has the corresponding three meanings: > > (1) x = 4 # Bind x to 4 in the 'current namespace' > (2) x[i] = 4 # equivalent to x.__setitem__(i, 4) > (3) x.a = 4 # Equivalent to x.__setattr__('a', 4) I think you both missed a case: (1b) global x; del x # Remove x from global namespace (1b) global x; x = 4 # Bind x to 4 in the global namespace > What conclusion should we draw from that? That Python is simple and consistent. From malaclypse2 at gmail.com Mon May 12 16:33:05 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Mon, 12 May 2008 16:33:05 -0400 Subject: thread stomp? In-Reply-To: References: Message-ID: <16651e80805121333y3e132ef0h6badc3ad492f55f@mail.gmail.com> On Mon, May 12, 2008 at 4:00 PM, pyn3wb wrote: > class main Why are you making main a class? It should almost certainly be a function (defined with "def", not "class"). > for i in dircache.listdir(dir): > //run over files > class1(dir).start() You've started a bunch of threads. If you want to wait for them to all finish, you need to call .join() on them all. You can't do that unless you save references to your threads, like this: threads = [] for i in dircache.listdir(dir): new_thread = class1(dir) new_thread.start() threads.append(new_thread) for thread in threads: thread.join() Beyond that, the code you've posted is not correct. You've left off a required ":" in your definition of class main, and your comments are not valid python comments. Your for loops don't make a whole lot of sense to me either. Are they supposed to be iterating across files in a directory? If so, why do you start up all of your threads with "dir" instead of "i" or "j" as the parameter to your new thread? -- Jerry From fuzzyman at gmail.com Sat May 24 09:24:27 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Sat, 24 May 2008 06:24:27 -0700 (PDT) Subject: unittest: Calling tests in liner number order References: Message-ID: On May 23, 10:36 am, Antoon Pardon wrote: > Some time ago I asked whether is would be possible that unittest would > perform the test in order of appearence in the file. > > The answers seemed to be negative. Since I really would like this > behaviour I took the trouble of looking throught the source and > I think I found a minor way to get this behaviour. > > Now my questions are: > > Are other people interrested in this behaviour? > Does the following patch has a chance of being introduced in the > standard python distribution? > > *** /usr/lib/python2.5/unittest.py 2008-04-17 16:26:37.000000000 +0200 > --- unittest.py 2008-05-23 11:19:57.000000000 +0200 > *************** > *** 570,575 **** > --- 570,577 ---- > """ > def isTestMethod(attrname, testCaseClass=testCaseClass, prefix=self.testMethodPrefix): > return attrname.startswith(prefix) and callable(getattr(testCaseClass, attrname)) > + def getlinenr(name): > + return getattr(testCaseClass, name).im_func.func_code.co_firstlineno > testFnNames = filter(isTestMethod, dir(testCaseClass)) > for baseclass in testCaseClass.__bases__: > for testFnName in self.getTestCaseNames(baseclass): > *************** > *** 577,582 **** > --- 579,586 ---- > testFnNames.append(testFnName) > if self.sortTestMethodsUsing: > testFnNames.sort(self.sortTestMethodsUsing) > + else: > + testFnNames.sort(key=getlinenr) > return testFnNames I second Roy's appreciation with you going to the trouble to post a patch. There is another problem with your code though, it is dependent on the CPython implementation. Currently unittest works *great* with IronPython, which your code wouldn't. Also, like others, I have had wonderful experiences of trying to track down test failures that depend on the order that tests run in. Having interdependencies between tests is a recipe for madness... Michael Foord http://www.ironpythoninaction.com/ From cokofreedom at gmail.com Wed May 21 10:28:17 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Wed, 21 May 2008 07:28:17 -0700 (PDT) Subject: C-like assignment expression? References: <68b5d090-9e3b-4e7d-9dda-fc1b099822c2@m73g2000hsh.googlegroups.com> <48340412$0$10773$426a74cc@news.free.fr> <87fxsbzxn4.fsf@mulj.homelinux.net> <7df99fd4-21c9-49a1-ba65-e55794fd4c12@26g2000hsk.googlegroups.com> <75ca6227-435c-46bf-8701-aa326d3533e0@p25g2000hsf.googlegroups.com> <69in0tF33sdj6U2@mid.uni-berlin.de> <07561bbe-0084-467d-b408-a53cfdc8b832@26g2000hsk.googlegroups.com> <69ioqaF32l8buU1@mid.uni-berlin.de> Message-ID: <4540a28e-59b4-4903-8c93-6239eb257c1f@j22g2000hsf.googlegroups.com> On May 21, 4:09 pm, "Diez B. Roggisch" wrote: > cokofree... at gmail.com wrote: > > >> And wastes time. regular expressions can become expensive to match - > >> doing it twice might be hurtful. > > >> Diez > > > match = (my_re1.match(line) or my_re2.match(line)) or > > my_re3.match(line) > > How do you know *which* of the three has matched then? > > Diez Depends if the OP wants to know that... From duncan.booth at invalid.invalid Wed May 28 09:52:34 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 28 May 2008 13:52:34 GMT Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <20080514215943.14c92f16.johnjsal@NOSPAMgmail.com> <94bac166-d13c-44dd-af84-db19e19488b8@w1g2000prd.googlegroups.com> <8cfd3523-8d16-40bc-b904-94a6a36a414d@p25g2000pri.googlegroups.com> <5c98049e-e62e-4ab1-afed-b0a3e186bd05@w1g2000prd.googlegroups.com> Message-ID: Dave Parker wrote: > Catch also gives you a > single, uniform, syntactically unambiguous way to embed statements (or > whole statement lists) into expressions -- without causing the > syntactic problems of = statements in if statements or the obfuscation > of question mark notation, etc. For example: > > If catch(set x to y+z.) < 0.1 then go to tinyanswer. > So what does this do exactly if the set throws an error? Is the error message printed at the top level going to be telling you about the failed addition or the failed comparison? Why do you need the catch anyway, if a statement is just an expression why can't you just put the statement into parentheses? For that matter, is there any way to distinguish between different errors and only catch particular ones? A bare except clause in Python is usually a signal of bad code: when handling errors you only want the errors you have anticipated, and want to be sure that any unexpected errors don't get caught. You have a great opportunity to avoid making some of the same mistakes that Python is trying to get out of. For example as of Python 2.5 KeyboardInterrupt and SystemExit to longer inherit from Exception. That means a bare except in Python no longer catches either of those: if you want to handle either of these exceptions you have to be explicit about it. -- Duncan Booth http://kupuguy.blogspot.com From tavares at fe.up.pt Thu May 1 11:49:28 2008 From: tavares at fe.up.pt (tavares at fe.up.pt) Date: Thu, 1 May 2008 08:49:28 -0700 (PDT) Subject: =?windows-1252?Q?Symposium_=93Image_Processing_and_Analysis=94_within?= =?windows-1252?Q?_the_ICCES=2709_Thailand_=2D_Announce_=26_Call_for_Papers?= Message-ID: <0d0443f2-0881-4063-a983-04d72223a589@56g2000hsm.googlegroups.com> (Our apologies for cross-posting. We appreciate if you kindly distribute this information by your co- workers and colleagues.) ********************************************************************************************************************** Symposium ?Image Processing and Analysis? International Conference on Computational & Experimental Engineering and Sciences 2009 (ICCES'09) Phuket, Thailand, 8-13 April 2009 http://icces.org/cgi-bin/ices09/pages/index ********************************************************************************************************************** Dear Colleague, Within the International Conference on Computational & Experimental Engineering and Sciences 2009 (ICCES'09), to be held in Phuket, Thailand, in 8-13 April 2009, we are organizing the Symposium ?Image Processing and Analysis?. Examples of some topics that will be considered in that symposium are: Image restoring, Description, Compression, Segmentation and Description; Objects tracking, Matching, Reconstruction and Registration; Visualization Enhance; Simulation and Animation; Software Development for Image Processing and Analysis; Grid Computing in Image Processing and Analysis; Applications of Image Processing and Analysis. Due to your research activities in those fields, we would like to invite you to submit your work and participate in the Symposium ?Image Processing and Analysis?. For instructions and submission, please access to the conference website at: http://icces.org/cgi-bin/ices09/pages/index. Please note, when submitting your work you should choose the Symposium ?Image Processing and Analysis?. Important dates and Instructions: - 15 Oct 2008: Start abstract submission; - 1 Jan 2009: Deadline for abstract submission; - 10 Jan 2009: End of abstract selection. If you intend to submit your work please notify as soon as possible the main organizer of your intention (tavares at fe.up.pt); Instructions for authors are available at: http://icces.org/cgi-bin/ices09/pages/guide. With kind regards, Yours sincerely, The Organizers, Jo?o Manuel R. S. Tavares (tavares at fe.up.pt) (main organizer) Faculty of Engineering of University of Porto, Porto, Portugal Yongjie (Jessica) Zhan (jessicaz at andrew.cmu.edu) Department of Mechanical Engineering, Carnegie Mellon University, Pittsburgh, USA Maria Jo?o M. Vasconcelos (maria.vasconcelos at fe.up.pt) Faculty of Engineering of University of Porto, Porto, Portugal From nagle at animats.com Thu May 22 16:07:58 2008 From: nagle at animats.com (John Nagle) Date: Thu, 22 May 2008 13:07:58 -0700 Subject: Using MySQLdb to select into the local file In-Reply-To: References: Message-ID: <4835cf41$0$34536$742ec2ed@news.sonic.net> Nikhil wrote: > I am using the MySQLdb python module. I have a table named 'testing' > with few columns, under the 'test' database, what is hosted on a remote > mysql server. > > I want to run the following query to get a comma-separated information > from the table > > > LOCK TABLES foo READ; > SELECT a,b,a+b INTO OUTFILE '/tmp/result.txt' > FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' > LINES TERMINATED BY '\n' > FROM 'testing' > UNLOCK TABLES; > > ..the query is running fine, but what I am noticing is /tmp/result.txt > is getting created locally on a mysqld running machine but not on the > client(python program) using the MySQLdb module. Unfortunately, while there is LOAD DATA LOCAL INFILE, which reads a file on the client, there is no SELECT INTO LOCAL OUTFILE. Actually, you probably want to turn off the FILE privilege for your MySQL. That blocks LOAD DATA INFILE and SELECT INTO OUTFILE, generally considered a good idea because those commands can access arbitrary file names. Also, if you're still using LOCK TABLES and UNLOCK TABLES, read up on InnoDB and transactions. Typically, you do something like this: import MySQLdb import csv def writedb(db, filename) : try : outcsv = csv.writer(filename) # output object for CSV cursor = db.cursor() cursor.execute("SELECT a,b,a+b FROM testing") while True : # do all rows row = cursor.fetchone() # get a tuple for one row if row is None : # if end of rows break # done outcsv.writerow(row) # write row in CSV format db.commit() # release locks except MySQLdb.OperationalError, message: print "Database trouble: ", message # handle any db problems raise # reraise exception hostname="???" # fill in appropriately user="???" password="???" db = MySQLdb.connect(host=hostname, # open database user=username, passwd=password, db=databasename) writedb(db, '/tmp/result.txt') # do it =============== Note that this is ASCII-oriented; if you Unicode, you need extra params to "connect". Also, the CSV module doesn't do Unicode well as yet. Make sure the "outcsv" object goes out of scope before you try to read the file, so the file gets flushed and closed. John Nagle From alex.m.gusarov at gmail.com Mon May 26 02:21:16 2008 From: alex.m.gusarov at gmail.com (Alex Gusarov) Date: Mon, 26 May 2008 13:21:16 +0700 Subject: PYQT- How to prevent a dialog being resized in qtdesigner In-Reply-To: <7530dbde-9fbb-4527-9f46-dbd8ecf060af@l28g2000prd.googlegroups.com> References: <7530dbde-9fbb-4527-9f46-dbd8ecf060af@l28g2000prd.googlegroups.com> Message-ID: There is no simple way to do it. But it seems to be a meaningless - resizing dialog in Designer is equal to changing its geometry. On Mon, May 26, 2008 at 9:30 AM, bbmerong wrote: > I have a question about qtdesigner. > > I'd like to know how to prevent a dialog being resized in qtdesigner. > > I'll wait for your answer. > > Then, Thank you in advance. > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeffober at gmail.com Fri May 2 15:47:15 2008 From: jeffober at gmail.com (Jeff) Date: Fri, 2 May 2008 12:47:15 -0700 (PDT) Subject: Python and SOAP status References: Message-ID: Twisted has SOAP support. From bockman at virgilio.it Mon May 12 03:55:25 2008 From: bockman at virgilio.it (bockman at virgilio.it) Date: Mon, 12 May 2008 00:55:25 -0700 (PDT) Subject: do you fail at FizzBuzz? simple prog test References: <39709320-66e1-40e9-a351-c769c9a94585@x41g2000hsb.googlegroups.com> Message-ID: On 12 Mag, 09:00, "Gabriel Genellina" wrote: > En Sat, 10 May 2008 22:12:37 -0300, globalrev escribi?: > > > > > > >http://reddit.com/r/programming/info/18td4/comments > > > claims people take a lot of time to write a simple program like this: > > > "Write a program that prints the numbers from 1 to 100. But for > > multiples of three print "Fizz" instead of the number and for the > > multiples of five print "Buzz". For numbers which are multiples of > > both three and five print "FizzBuzz". > > > for i in range(1,101): > > ? ? if i%3 == 0 and i%5 != 0: > > ? ? ? ? print "Fizz" > > ? ? elif i%5 == 0 and i%3 != 0: > > ? ? ? ? print "Buzz" > > ? ? elif i%5 == 0 and i%3 == 0: > > ? ? ? ? print "FizzBuzz" > > ? ? else: > > ? ? ? ? print i > > > is there a better way than my solution? is mine ok? > > Is it correct? Did you get at it in less than 15 minutes? If so, then it's OK. > The original test was not "write the most convoluted algorithm you can think of", nor "write the best program to solve this". It was a *practical* test: if you can't get anything remotely working for such a simple problem in 15 minutes, we're not interested in your services. > > (We used this question last year - some people gave a sensible answer in less than 5 minutes, but others did not even know how to start) > > -- > Gabriel Genellina- Nascondi testo tra virgolette - > > - Mostra testo tra virgolette - As a test, I would leave out the last sentence, and see how many people (and how fast) figure out than a number can be multiple of three _and_ five and that the requirement is somehow incomplete ... Ciao ----- FB From john106henry at hotmail.com Tue May 13 20:22:59 2008 From: john106henry at hotmail.com (John Henry) Date: Tue, 13 May 2008 17:22:59 -0700 (PDT) Subject: Why can't I import this? References: <7ddb9a42-9d5c-4266-aa0c-95466af10b6b@w34g2000prm.googlegroups.com> Message-ID: On May 13, 3:42 pm, Gary Herron wrote: > John Henry wrote: > > On May 13, 1:49 pm, Gary Herron wrote: > > >> John Henry wrote: > > >>> Hi list, > > >>> I can't understand this. The following import statement works fine: > > >>> from PythonCard.templates.dialogs import runOptionsDialog > > >>> but this one fails: > > >>> from PythonCard.tools.codeEditor.codeEditor import CodeEditor > > >> This kind of "dotted" name import only works for packages, and a > >> directory is considered a package only if it contains a file name > >> __init__.py. Looking around my installation of PythonCard (on Linux) > >> I see that most of those directories *do NOT* have a __init__.py, so > >> they are not packages and cannot be imported that way. > > >> Of course this leaves unanswered the question of *how* you are supposed > >> to import that code. I've never used PythonCard so I can't help > >> further, but I suggest looking at the documentation and examples > >> supplied. And perhaps waiting for someone with experience with > >> PythonCard to answer. > > >> Gary Herron > > >> P.S. It is usually a waste of time to tell us that something fails > >> without telling us *how* it fails. (Cut and paste the error message > >> always, and the traceback usually.) If you don't, you will usually get > >> a request to supply that information, and then have wast3ed the time for > >> one full round of message to the group. Even in this case, I'm only > >> guessing how it failed for you. > > >>> I've checked and rechecked to make sure that the spellings are proper > >>> and that the tools, the codeEditor directory, and codeEditor.py, and > >>> the class CodeEditor all exists and yet idle keep complaining that it > >>> can't import from PythonCard.tools. > > >>> What's going on? (Running Python2.5 under WinXP). > > >>> Regards, > >>> -- > >>>http://mail.python.org/mailman/listinfo/python-list > > > Thank you very much. I didn't know about the __init__.py > > requirement. Appreciate it. > > Actually I should have added that there ways to import such things, and > PythonCard must be using some such method itself. You can manipulate > the sys.path variable, or directly call the import mechanism using the > builtin __import__, or use a suppled "imp" module. However, you > should not have to do any such thing to use PythonCard. It should do > them in for you. I tried to call __import__ directly and didn't work neither. What I was doing is to invoke their codeEditor directly into my application. Their codeEditor was designed to be a stand alone application and that's why it didn't include the file you cited. I never quite understood what they were saying about __init__.py but now I understand. Learn something new every day. Thanks again. From collinyeung at shaw.ca Tue May 20 21:05:41 2008 From: collinyeung at shaw.ca (Collin) Date: Wed, 21 May 2008 01:05:41 GMT Subject: Python and Flaming Thunder In-Reply-To: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> Message-ID: Dave Parker wrote: > I've read that one of the design goals of Python was to create an easy- > to-use English-like language. That's also one of the design goals of > Flaming Thunder at http://www.flamingthunder.com/ , which has proven > easy enough for even elementary school students, even though it is > designed for scientists, mathematicians and engineers. Personally, FT is a bit meh to me. The way you issue your statements I always think something is wrong, mainly because when I want to define, say, x, in python I'd go: x = "whatever" Instantly noting that I defined x. While in Flaming Thunder I'd have to type: Set x to "whatever" It just feels wrong. From Magnus.Moraberg at gmail.com Tue May 27 08:06:53 2008 From: Magnus.Moraberg at gmail.com (Magnus.Moraberg at gmail.com) Date: Tue, 27 May 2008 05:06:53 -0700 (PDT) Subject: Extracting text from a Webpage using BeautifulSoup References: <426554a3-b635-4f4a-a6d8-f8df17fd56cb@w7g2000hsa.googlegroups.com> <6a27idF32hqrpU3@mid.uni-berlin.de> Message-ID: On 27 Maj, 12:54, Marc 'BlackJack' Rintsch wrote: > On Tue, 27 May 2008 03:01:30 -0700, Magnus.Moraberg wrote: > > I wish to extract all the words on a set of webpages and store them in > > a large dictionary. I then wish to procuce a list with the most common > > words for the language under consideration. So, my code below reads > > the page - > > >http://news.bbc.co.uk/welsh/hi/newsid_7420000/newsid_7420900/7420967.stm > > > a welsh language page. I hope to then establish the 1000 most commonly > > used words in Welsh. The problem I'm having is that > > soup.findAll(text=True) is returning the likes of - > > > u'doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN" "http:// > >www.w3.org/TR/REC-html40/loose.dtd"' > > Just extract the text from the body of the document. > > body_texts = soup.body(text=True) > > > and - > > >
> > Any suggestions how I might overcome this problem? > > Ask the BBC to produce HTML that's less buggy. ;-) > > http://validator.w3.org/reports bugs like "'body' tag not allowed here" > or closing tags without opening ones and so on. > > Ciao, > Marc 'BlackJack' Rintsch Great, thanks! From martin at v.loewis.de Fri May 30 17:33:48 2008 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Fri, 30 May 2008 23:33:48 +0200 Subject: Python 2.5.2 on Ubuntu Hardy Utf-8-Euro error In-Reply-To: References: <4840407c$0$4845$9b622d9e@news.freenet.de> Message-ID: <484072bc$0$27773$9b622d9e@news.freenet.de> > The function first normalizes the "@" away and then looks for it. Is that > the expected behaviour? I believe this functionality is broken by design. Python can't possibly know correctly what each locale name on each system means, and what encoding is used in the locale. Instead, the system's API to find out the encoding should be used, as exposed in locale.getpreferredencoding(). Regards, Martin From grante at visi.com Tue May 13 13:42:06 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 13 May 2008 12:42:06 -0500 Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <2b66a86e-5a05-4262-b3c9-4703b0ae3372@d1g2000hsg.googlegroups.com> <5b0e3f70-afde-4480-8713-e7113b1250d7@x35g2000hsb.googlegroups.com> <1f537717-00d0-48ee-99b6-7125b96a6133@t12g2000prg.googlegroups.com> <68t4o0F2vaoncU1@mid.uni-berlin.de> <2a32179a-9439-449c-bd07-fff6a4075aee@s50g2000hsb.googlegroups.com> <7ee5dffd-df8f-46f0-bd78-c81ac0418a9a@d77g2000hsb.googlegroups.com> <65ef773e-a1c3-4adb-a18b-e8b8451efe5e@b5g2000pri.googlegroups.com> <68trmmF2vjivnU1@mid.uni-berlin.de> Message-ID: On 2008-05-13, Dave Parker wrote: > And I'll be willing to bet that Flaming Thunder will have OO > features similar to Python before Python has the features that > Flaming Thunder already does. Well, python will definitely never have a name that sounds like a slang term for happens after you get food poisioning at a Thai restaurant... ;) -- Grant Edwards grante Yow! Edwin Meese made me at wear CORDOVANS!! visi.com From pavlovevidence at gmail.com Mon May 19 22:40:55 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 19 May 2008 19:40:55 -0700 (PDT) Subject: scaling problems References: Message-ID: <51dbdc85-b69c-477a-807d-58791870b525@l42g2000hsc.googlegroups.com> On May 19, 8:47 pm, James A. Donald wrote: > 1. Looks to me that python will not scale to very large programs, > partly because of the lack of static typing, but mostly because there > is no distinction between creating a new variable and utilizing an > existing variable, so the interpreter fails to catch typos and name > collisions. This factor is scale-neutral. You can expect the number of such bugs to be proportional to the lines of code. It might not scale up well if you engage in poor programming practives (for example, importing lots of unqualified globals with tiny, undescriptive names directly into every module's namespace), but if you do that you have worse problems than accidental name collisions. > I am inclined to suspect that when a successful small > python program turns into a large python program, it rapidly reaches > ninety percent complete, and remains ninety percent complete forever. Unlike most C++/Java/VB/Whatever programs which finish and ship, and are never patched or improved or worked on ever again? > 2. It is not clear to me how a python web application scales. Python > is inherently single threaded, No it isn't. It has some limitations in threading, but many programs make good use of threads nonetheless. In fact for something like a web app Python's threading limitations are relatively unimportant, since they tend to be I/O-bound under heavy load. [snip rest] Carl Banks From gagsl-py2 at yahoo.com.ar Mon May 12 00:39:14 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 12 May 2008 01:39:14 -0300 Subject: Free Memory References: <8a6035a00805081730g2a18b97cxc32ae6568fb10b81@mail.gmail.com> Message-ID: En Sun, 11 May 2008 01:06:13 -0300, Patrick Mullen escribi?: > Yeah I don't know much about locals or globals. I've never used them > before, just know they are there. But anyway, to illustrate what I meant by > the interesting behavior, here is the output (and sorry for it being so > long): > > IDLE 2.6a2 >>>> globals() > {'__builtins__': , '__name__': '__main__', > '__doc__': None, '__package__': None} >>>> globals().clear() >>>> globals() > {'__builtins__': {'bytearray': , 'IndexError': 'exceptions.WindowsError'>}} >>>> > > The OP wanted to clear the interpreter and I took a very broad (and highly > unresearched) stab at it, and saw some behavior that I wasn't expecting. > So before, all the builtin variables are hidden away in __builtins__, but > after clearing globals, they are filled into globals. This doesn't really > make sense to me, but I don't know much about __builtins__ or globals. Look more carefully: py> globals().clear() py> len(globals()) 1 py> globals().keys() ['__builtins__'] globals() contains now a single entry, the namespace of the __builtin__ module (that is, __builtin__.__dict__), not the individual builtin entries (these are the dictionary entries that you posted). As you later noticed, this happens only on IDLE. I don't know why IDLE behaves that way, but avoid entering "restricted mode" may be a reason (see http://docs.python.org/lib/restricted.html ) Usually, __builtins__ contains a reference to the __builtin__ module itself *only* in __main__; in all other modules, __builtins__ contains a reference to the __builtin__ namespace (like what you got in IDLE after clearing globals). I don't know *why* they are different either. -- Gabriel Genellina From mccredie at gmail.com Fri May 23 17:10:51 2008 From: mccredie at gmail.com (Matimus) Date: Fri, 23 May 2008 14:10:51 -0700 (PDT) Subject: Python database 'frontends', what's available? References: <4837141b$0$658$bed64819@news.gradwell.net> Message-ID: <8e4fc264-c19d-4bca-9984-757c0012ce8f@j22g2000hsf.googlegroups.com> On May 23, 11:59 am, tinn... at isbd.co.uk wrote: > I'm desperately trying to move a Microsoft Access database application > (a simple accounts system I wrote myself) to Linux. Python is one of > my preferred programming laguages so I wonder if there are any good > Python 'frameworks' for writing database applications, in particular I > need good reporting and forms writing facilities. The basic database > and logic/arithmetic seem fairly simple to me. > > -- > Chris Green You might look at web frameworks like django or turbo gears. The tutorials for django jump right into database access, and the default administrative stuff is robust and pretty simple. Matt From bj_666 at gmx.net Thu May 22 03:07:13 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 22 May 2008 07:07:13 GMT Subject: simple way to touch a file if it does not exist References: <68629786-1cef-4dc5-99d9-4967ebecd10f@r66g2000hsg.googlegroups.com> <4834C05D.6020608@gmail.com> <0cada27d-8f5f-482e-9acc-4da032edb27e@f36g2000hsa.googlegroups.com> Message-ID: <69kkd1F33ahahU1@mid.uni-berlin.de> On Wed, 21 May 2008 17:56:38 -0700, bukzor wrote: > On May 21, 5:37 pm, Nikhil wrote: > >> if os.path.exists('file'): >> open('file', 'w').close() >> >> Right? > > You only want to blank it if it exists? If it doesn't exist you won't > create it. > The .close() is superlative: since you don't keep the value, it gets > deallocated and closed by the destructor. The language neither guarantees *when* an object will be deallocated nor that its destructor is called *at all*. It's cleaner to explicitly close the file. Ciao, Marc 'BlackJack' Rintsch From kyosohma at gmail.com Tue May 27 10:43:51 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Tue, 27 May 2008 07:43:51 -0700 (PDT) Subject: Creating a web page with Python References: Message-ID: On May 27, 9:25?am, subhabrata.i... at hotmail.com wrote: > Dear Members of the group, > If any one can help me with an idea how to create a web page with > python? Do I have to use vbscript or something like that? I also want > to embed the function in the button of a form. How can I do it in > Python? > Regards, > Subhabrata Banerjee. There are many ways to do this. You can use Python kind of like cgi: http://www.python.org/doc/essays/ppt/sd99east/index.htm http://docs.python.org/lib/module-cgi.html WSGI: http://www.wsgi.org/wsgi Web Frameworks: Django, TurboGears, Pylons, mod-python, Zope/Plone Or you might just want to browse Python's wiki: http://wiki.python.org/moin/WebProgramming Mike From castironpi at gmail.com Tue May 13 01:52:47 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 12 May 2008 22:52:47 -0700 (PDT) Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <2b66a86e-5a05-4262-b3c9-4703b0ae3372@d1g2000hsg.googlegroups.com> <5b0e3f70-afde-4480-8713-e7113b1250d7@x35g2000hsb.googlegroups.com> <1f537717-00d0-48ee-99b6-7125b96a6133@t12g2000prg.googlegroups.com> Message-ID: On May 12, 8:36?pm, Dave Parker wrote: > On May 12, 7:20?pm, castiro... at gmail.com wrote: > > >?Yes, I am trying to visualize something. > > If it is related to making furniture comfortable for humans, have you > considered painting the furniture with thermochromic paint (http://en.wikipedia.org/wiki/Thermochromism)? ?It changes color in > response to temperature, which in part is determined by how hard a > body is pressed against it because close contact tends to trap heat. > An evenly distributed color might indicated evenly distributed > pressure. I do hold an argument that one can make too much money for one's own good quality of life. Am I trying to visualize thermal (and ergo possibly chemical too) gradients (thermovoltaic)? Yes in part. I'm pretty generally interested, but where can print layout take you? Microsales? From george.sakkis at gmail.com Thu May 8 01:07:38 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 7 May 2008 22:07:38 -0700 (PDT) Subject: slicing lists References: Message-ID: On May 7, 11:34?pm, Yves Dorfsman wrote: > So would it be a worthy addition to python, to add it right in the core of > the language, and hopefully in an efficient manner ? Given that it's a straightforward generalization of the existing slicing syntax, it sure does make sense from a theoretical standpoint. Whether it's a worthy addition is debatable though; I don't think there are many common use cases to convince the core developers to work on it. OTOH if you (or someone else) comes up with a working patch, it might improve its chances of getting accepted. George From jcd at sdf.lonestar.org Thu May 8 09:50:03 2008 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Thu, 08 May 2008 09:50:03 -0400 Subject: listen on TCP port In-Reply-To: <7052dd09-4032-46ab-9b37-ba0ca0326475@a1g2000hsb.googlegroups.com> References: <7052dd09-4032-46ab-9b37-ba0ca0326475@a1g2000hsb.googlegroups.com> Message-ID: <1210254603.8236.6.camel@aalcdl07.lib.unc.edu> On Thu, 2008-05-08 at 05:56 -0700, petr.poupa at gmail.com wrote: > Hello, > is it possibble listening on TCP port by python and how? I am trying > chilkat but poorly :(. > > Thanks > -- > http://mail.python.org/mailman/listinfo/python-list > You just asked this exact same question yesterday, and got a few responses, none of which are addressed in the post above. Do neither twisted nor the socket module work for you? From efurman at admailinc.com Wed May 21 14:42:00 2008 From: efurman at admailinc.com (Ethan Furman) Date: Wed, 21 May 2008 10:42:00 -0800 Subject: Struct usage and varying sizes of h, l, etc In-Reply-To: <48340df7$1@news.mel.dft.com.au> References: <48335269.2000809@admailinc.com> <48340df7$1@news.mel.dft.com.au> Message-ID: <48346CF8.8070109@admailinc.com> John Machin wrote: > Robert Kern wrote: > >> Ethan Furman wrote: >> >>> Greetings, >>> >>> I'm looking at the struct module for binary packing of ints and >>> floats. The documentation refers to C datatypes. It's been many >>> years since I looked at C, but I seem to remember that the data type >>> sizes were not fixed -- for example, an int might be two byes on one >>> machine, and four bytes on the next. Can any C programmers verify >>> this? If it is true, does that mean that struct.pack('h', 8001) >>> might give me different results depending on the machine it's >>> running on? >> >> >> Right. I believe (but could be wrong) that "char" is defined to be >> one byte, but that "short", "int", "long", and "long long" are >> defined as "at least as big as the previous type". >> >> In practice, though, on nearly every machine that Python runs on, >> "char" is one byte, "short" is two bytes, and "int" is four bytes. >> "longs" and "long longs" tend to vary substantially, though; never >> assume sizes for them. >> >> Single-precision floats are always four bytes and double-precision >> floats are always eight bytes. "long doubles" vary; they could be >> twelve bytes or sixteen. >> >> If you want to deal with fixed sizes, use struct.calcsize() to test >> the sizes of each of the integer types, assign them to width-specific >> aliases, and always use these aliases. >> > > This is all true if you want to operate in "native" mode; however in > "standard" mode the sizes are fixed -- otherwise there'd be no easy > way of reading/writing the fixed-size fields in many common file formats. > > As the manual says: > """ > Native size and alignment are determined using the C compiler's sizeof > expression. This is always combined with native byte order. > > Standard size and alignment are as follows: no alignment is required > for any type (so you have to use pad bytes); short is 2 bytes; int and > long are 4 bytes; long long (__int64 on Windows) is 8 bytes; float and > double are 32-bit and 64-bit IEEE floating point numbers, respectively. > """ > > If, as I suspect, Ethan's purpose is be able to read/write files in a > long-established PC file format, he will need to '<' for littleendian > order, and an appropriate selection from bBhHiI and d will do what he > needs. > > HTH, > John > -- > http://mail.python.org/mailman/listinfo/python-list John, you are correct in my purpose, and thank you (and to everyone) for the clarification. It does indeed help a great deal. -- Ethan From gherron at islandtraining.com Thu May 29 11:45:31 2008 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 29 May 2008 08:45:31 -0700 Subject: Tuple of coordinates In-Reply-To: References: Message-ID: <483ECF9B.5090502@islandtraining.com> victor.herasme at gmail.com wrote: > Hi, > > i am using a software which uses python as its scripting language. I > want to generate a list of coordinates more or less this way: > > for i in (beg, end, step): > for j in (beg, end, step): > for k in (beg, end, step): > ......... > > Coords = ((i1,j1,k1), (i2,j2,k2), ...,(in,jn.kn)) > Your statement of the problem makes it look like all three coordinates cover the same sequence of values. Is that true? Or does i's range (beg, end, step) differ from j's and k's. If they differ, are they all the same length? You pseudo-code makes it look like you want all combinations, but your sample output does not indicate that. Which is it, [(1,1,1), (2,2,2)] or [(1,1,1), (1,1,2),(1,2,1),(1,2,2), ...]? Depending on the answers to those questions, one of the following list comprehensions may demonstrate how to achieve a solution. >>> a = range(2,6,2) >>> b = range(3,7,2) >>> c = range(10,14,2) >>> print a,b,c [2, 4] [3, 5] [10, 12] >>> [(i,j,k) for i,j,k in zip(a,b,c)] # Using zip process three lists in lock-step [(2, 3, 10), (4, 5, 12)] >>> [(i,j,k) for i in a for j in b for k in c] #Nested loop give all possible combos. [(2, 3, 10), (2, 3, 12), (2, 5, 10), (2, 5, 12), (4, 3, 10), (4, 3, 12), (4, 5, 10), (4, 5, 12)] >>> Gary Herron > > Can anyone give me some advice on how to achieve this ? I got a little > idea, but still need to keep working til i get it. Thanks in advance, > > > Victor > -- > http://mail.python.org/mailman/listinfo/python-list > From lac at openend.se Mon May 26 10:36:13 2008 From: lac at openend.se (Laura Creighton) Date: Mon, 26 May 2008 16:36:13 +0200 Subject: looking for membership management software -- Open Source, written in Python Message-ID: <200805261436.m4QEaDdI026074@theraft.openend.se> I'm looking for an application that handles the membership of an organisation -- who's a member, who has paid fees, addressbook and the odd added field. Anybody got one they recommend? Language does not have to be English -- we're going to have to internationalise whatever we get in any case. Of course, if it happens to already speak various European languages, this will be a big plus. Thanks in advance, Laura Creighton From __peter__ at web.de Tue May 20 03:08:25 2008 From: __peter__ at web.de (Peter Otten) Date: Tue, 20 May 2008 09:08:25 +0200 Subject: test mult vars to same value, how to shorten expr? References: Message-ID: notnorwegian at yahoo.se wrote: > if i want o test: > if a == 5 and b ==5 and c==5 ... z==5 > > is there some synctactic suagr for this? > > rather than maiking one of my own i mean, something built-in like: > if a,b,c... z == 5: if all(x == 5 for x in a,b,c,...): print "yep" Peter From george.sakkis at gmail.com Thu May 1 21:13:22 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Thu, 1 May 2008 18:13:22 -0700 (PDT) Subject: RegEx for matching brackets References: <713f6d61-906d-490f-bcbc-befd19e086e5@d19g2000prm.googlegroups.com> Message-ID: On May 1, 7:44 pm, NevilleDNZ wrote: > Below is a (flawed) one line RegEx that checks curly brackets (from > awk/c/python input) are being matched. Is there a one liner for doing > this in python? There is not even a 1000-liner regular expression for this; it's a context-free language [1], not a regular one [2]. Either do it manually or use a parser generator [3]. George [1] http://en.wikipedia.org/wiki/Context-free_language [2] http://en.wikipedia.org/wiki/Regular_language [3] http://wiki.python.org/moin/LanguageParsing From gagsl-py2 at yahoo.com.ar Sun May 18 12:27:42 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 18 May 2008 13:27:42 -0300 Subject: Get all the instances of one class References: <29f39184-2daa-49fc-a7af-7f869fd2d688@h1g2000prh.googlegroups.com> <24267a4f-1406-42c2-bffc-f1ccd64f0218@w34g2000prm.googlegroups.com> Message-ID: En Sun, 18 May 2008 12:32:28 -0300, Terry escribi?: > On May 17, 8:04 am, "Gabriel Genellina" > wrote: >> En Fri, 16 May 2008 20:44:00 -0300, Terry >> escribi?: >> >> > Is there a simple way to get all the instances of one class? I mean >> > without any additional change to the class. >> >> Try with gc.get_referrers() > > But I saw in the help that we should "Avoid using get_referrers() for > any purpose other than debugging. " Yes - so what do you want to do actually? -- Gabriel Genellina From martin at v.loewis.de Tue May 20 14:48:15 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 20 May 2008 20:48:15 +0200 Subject: Access to sysctl on FreeBSD? In-Reply-To: References: Message-ID: <48331cef$0$32633$9b622d9e@news.freenet.de> > How do I access the sysctl(3) call from Python on BSD? > > Specifically I want to retrieve: > > $ sysctl -d net.inet.ip.stats > net.inet.ip.stats: IP statistics (struct ipstat, netinet/ip_var.h) > > So I'll need some way of getting to struct ipstat from Python as well At the moment, only through ctypes - if you need to use sysctl(3), and you'll have to manufacture the layout of struct ipstat yourself. Regards, Martin From jstucklex at attglobal.net Tue May 27 22:27:40 2008 From: jstucklex at attglobal.net (Jerry Stuckle) Date: Tue, 27 May 2008 22:27:40 -0400 Subject: php vs python In-Reply-To: References: <5l%Yj.77$mz3.53@fe101.usenetserver.com> <37b112d8-a3ba-446d-9d2f-d907d93c637b@w8g2000prd.googlegroups.com> <-t-dnWQ4bZN2MaTVnZ2dnUVZ_qGdnZ2d@comcast.com> <68cb8bb1-4cc5-4a28-8915-46e7d4e316d9@d1g2000hsg.googlegroups.com> <613388153.20080528051020@freemail.ru> <-o2dnfEz48JGJKHVnZ2dnUVZ_sidnZ2d@comcast.com> Message-ID: Ivan Illarionov wrote: > On Tue, 27 May 2008 21:47:55 -0400, Jerry Stuckle wrote: > >> Ivan Illarionov wrote: >>> On Wed, 28 May 2008 05:10:20 +0400, AnrDaemon wrote: >>> >>>> Greetings, Ivan Illarionov. >>>> In reply to Your message dated Monday, May 26, 2008, 04:47:00, >>>> >>>>>> As I've said before - good programmers can write good code in any >>>>>> language. >>>>> Yes, they can. But it may be harder to do for them in one language >>>>> and easier in another. >>>> It's obvious lie. If you have clear mind and you know language you're >>>> using, there are absolutely NOTHING can deny you to write clear code. >>>> Even using forth postfix notation, I have no problem writing good >>>> code, it's as easy as writing bad code. And yes, I do see the >>>> difference. >>> No. Language does matter. >> Not for a good programmer. Only for half-assed ones. > > No. Language does matter Only to half-assed programmers. Good programmers can write good code in any language they know. Ever seen good assembler? It can be done - really! Also fortran, cobol, forth... the list goes on. -- ================== Remove the "x" from my email address Jerry Stuckle JDS Computer Training Corp. jstucklex at attglobal.net ================== From kw at codebykevin.com Sat May 10 11:42:29 2008 From: kw at codebykevin.com (Kevin Walzer) Date: Sat, 10 May 2008 11:42:29 -0400 Subject: People still using Tkinter? In-Reply-To: References: Message-ID: <4825C265.90106@codebykevin.com> Guilherme Polo wrote: > 2008/5/10 Zentrader : >> I like New Mexico Tech's site as well. Also, take a look at the PMW >> extension for additional widgets, and TkTable and/or TableListWrapper. >> http://infohost.nmt.edu/tcc/help/pubs/tkinter/ > > There is also Tile, or Ttk since Tk 8.5, if you are interested in > extensions too. > Apparently there are three Tile wrappers now, two are incomplete > (sorry for saying that): > > http://bruno.thoorens.free.fr/ttk.html -- Missing Treeview, big part > of ttk styling, maybe other things and it is not only a ttk wrapper > (there are other things besides it) > http://bugs.python.org/file10010/Tile.py -- Missing several methods in > Treeview, big part of ttk styling and maybe something else. > > And there is also one I'm doing, that I expect to be complete: > > http://gpolo.ath.cx:81/projects/ttk_to_tkinter/ > > Documentation and samples are still lacking, but I'm working on them. > And I haven't tested it under Windows, so I invite you all to test it. > > Regards, > I'm the maintainer of Tile.py. It may well be incomplete, as it was first developed by Martin Franklin a couple of years ago and I've been modifying it as my own needs require. So you're doing your own implementation of ttk in Tkinter as a Google Summer of Code Project? Wonderful! Are you planning on submitting it for including in Tkinter's core, as I did? If yours proves to be the better implementation I'll gladly withdraw mine, as I'm not sure I have time to overhaul it extensively. I'll follow your progress with interest! --Kevin -- Kevin Walzer Code by Kevin http://www.codebykevin.com From bearophileHUGS at lycos.com Sun May 4 07:00:26 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Sun, 4 May 2008 04:00:26 -0700 (PDT) Subject: word shifts References: <7b142d7f-a9f6-4739-8b6f-1eca581b0517@j22g2000hsf.googlegroups.com> Message-ID: George Sakkis: > A faster algorithm is to create a 'key' for each word, defined as the > tuple of ord differences (modulo 26) of consecutive characters. Very nice solution, it uses the same strategy used to find anagrams, where keys are "".join(sorted(word)) Such general strategy to look for a possible invariant key for the subsets of the required solutions is quite useful. Bye, bearophile From tjreedy at udel.edu Wed May 21 19:42:28 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 21 May 2008 19:42:28 -0400 Subject: Returning to 'try' block after catching an exception References: Message-ID: "Karlo Lozovina" <_karlo_ at _mosor.net_> wrote in message news:Xns9AA6FDC59536mosornet at 161.53.160.65... | Andr? wrote in | news:a9913f2d-0c1a-4492-bf58-5c78813c4458 at s50g2000hsb.googlegroups.com: | | > How about something like the following (untested) | > | > done = False | > while not done: | > try: | > some_function() | > done = True | > except: | > some_function2() | > some_function3() | | Sure, that works, but I was aiming for something more elegant and Pythonic | ;). while True: try: some_function() break except Exception: patchup() ??? From timj at tolisgroup.com Mon May 5 14:32:17 2008 From: timj at tolisgroup.com (brucoder) Date: Mon, 5 May 2008 11:32:17 -0700 (PDT) Subject: Visual Studio 6 compile of 2.5.2 fails with missing db.h References: <1f1a09ff-5800-4ecb-ac9f-f2604454edfb@q1g2000prf.googlegroups.com> Message-ID: <0c647f30-3c99-4f3b-b726-4cc74f51abea@a9g2000prl.googlegroups.com> On May 5, 11:43?am, brucoder wrote: > Hi Folks, > > Searched the archives, but I can only find mention of db.h problems relating to Linux. > > I've downloaded the source for 2.5.2 and am trying to compile it in Visual Studio 6 (SP6). I've just stepped back to 2.3.7 and receive the same error when compiling bsddb... > ?The error reports read: > > --------------------Configuration: _bsddb - Win32 Debug-------------------- > Compiling... > _bsddb.c > C:\Documents and Settings\Tim\My Documents\Python-2.5.2\Modules\_bsddb.c(90) : fatal error C1083: Cannot open include file: 'db.h': > No such file or directory > Error executing cl.exe. > > _bsddb_d.pyd - 1 error(s), 0 warning(s) From Magnus.Moraberg at gmail.com Tue May 27 05:03:02 2008 From: Magnus.Moraberg at gmail.com (Magnus.Moraberg at gmail.com) Date: Tue, 27 May 2008 02:03:02 -0700 (PDT) Subject: HTTPError sometimes when using urllib2.urlopen Message-ID: <5978cac5-27e1-40cd-9abe-9e7536395468@d45g2000hsc.googlegroups.com> Hi, I have the following code - import urllib2 from BeautifulSoup import BeautifulSoup proxy_support = urllib2.ProxyHandler({"http":"http:// 999.999.999.999:8080"}) opener = urllib2.build_opener(proxy_support) urllib2.install_opener(opener) page = urllib2.urlopen('http://www.cornish-language.org/CORNISH/ membership.asp') soup = BeautifulSoup(page) pageText = soup.findAll(text=True) print pageText Sometimes when I run this code I get the exception - HTTPError: HTTP Error 407 Proxy authentication required I seem to get this error repeatidly for a while, then I go a surf for a moment and when I run the code again the exception might have gone away. No idea why... I have no problems with firefox which uses the same proxy. The proxy requires no authentication... What might the issue be? Thanks, Barry. From bignose+hates-spam at benfinney.id.au Mon May 12 02:24:23 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 12 May 2008 16:24:23 +1000 Subject: Is using range() in for loops really Pythonic? References: <482657ca$0$25026$607ed4bc@cv.net> <41078222-aec0-4e8b-8a1f-945cdf814498@m73g2000hsh.googlegroups.com> <48275446$0$11628$607ed4bc@cv.net> <87mymw8nr0.fsf@benfinney.id.au> Message-ID: <87iqxk6nvs.fsf@benfinney.id.au> Ivan Illarionov writes: > >> In such cases, the name 'dummy' is conventionally bound to the items > >> from the iterator, for clarity of purpose > [..] > > If a value isn't used, then I think the most clear name for it is > > "unused". > [...] > > Maybe my brain works differently, but I find both "dummy" and > "unused" are extremely confusing names for loop counters. The loop > begins to look like it doesn't iterate at all if its counter is > dummy or unused. > > If it *counts* it is *used* and it's *not* dummy. The value is unused by any of the code inside the block. For the purposes of that block, it is a dummy value. That something *else* (the iterator driving the 'for') is taking care of knowing when the loop is finished is great. However, in the code the programmer is writing, the loop counter is entirely unused. > Why reinvent the wheel when "a common identifier naming convention > is for the loop counter to use the variable names i, j and k (and so > on if needed)" (from Wikipedia > http://en.wikipedia.org/wiki/Loop_counter ) That is also regrettably common in Python code. It still suffers from being unnecessarily ambiguous, since there are *also* plenty of loops using 'i', 'j', etc. where the loop counter *is* used. Differentiating these use cases by appropriate naming is, IMO, worth the effort of choosing a meaningful name. -- \ "Ignorance more frequently begets confidence than does | `\ knowledge." ?Charles Darwin, _The Descent of Man_, 1871 | _o__) | Ben Finney From mensanator at aol.com Tue May 13 18:31:03 2008 From: mensanator at aol.com (Mensanator) Date: Tue, 13 May 2008 15:31:03 -0700 (PDT) Subject: do you fail at FizzBuzz? simple prog test References: <39709320-66e1-40e9-a351-c769c9a94585@x41g2000hsb.googlegroups.com> <688a0f5a-2cdf-45ca-abe7-5bbb89aac32f@s50g2000hsb.googlegroups.com> <482a00a2@news.mel.dft.com.au> Message-ID: <249560b3-7dd8-4fc1-8c14-11bc98a105ca@c65g2000hsa.googlegroups.com> On May 13, 3:57?pm, John Machin wrote: > Matthew Woodcraft wrote: > > Gabriel Genellina wrote: > >> I would like to write a similar problem without this non-programming ? > >> distracting issues (that is, a problem simple enough to be answered in a ? > >> few minutes, that requires only programming skills to be solved, and ? > >> leaving out any domain-specific knowledge). > > > Another reason not to like the FizzBuzz example is that it's quite > > closely balanced between two reasonable approaches (whether to just > > special-case multiples of 15 and say 'FizzBuzz', or whether to somehow > > add the Fizz and the Buzz together in that case). The interviewee might > > reasonably guess that this distinction is what's being tested, and get > > unnecessarily stressed about it. > > For such a trivial problem, fifteen minutes is more than enough to > present alternative answers. Perhaps the intention is to weed out those > who do become unnecessarily stressed in such circumstances. Employers > like to play tricks to see how interviewees respond e.g. hand over two > pages of a listing of code in language X, announce that there are 10 > syntax errors, and ask the interviewee to find and circle all the syntax > errors. Correct answer: 11 circles. They get away with that? The one time I was asked to compose a (hardware) test was because some interviewee threated to sue claiming discrimination. So I was asked to make an absolutely trick-free test. Such as what's the voltage at point A? +5v | 220 ohm | +-- A | 330 ohm | ground Would you be surprised at how many applicants couldn't figure that out because they forgot to bring their calculator? Sure, I had a page from a schematic, but only to ask how one of the shown T-flip-flops worked. One female interviewee took one glance at the schematic and said, "Oh, it's a parity generator." She got hired. I'm surprised anyone has to resort to tricks. From larry.bates at websafe.com` Fri May 9 18:08:22 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Fri, 09 May 2008 17:08:22 -0500 Subject: Property in derived class In-Reply-To: <31861d09-a273-45de-bc71-c8591b7722e6@w7g2000hsa.googlegroups.com> References: <31861d09-a273-45de-bc71-c8591b7722e6@w7g2000hsa.googlegroups.com> Message-ID: Joseph Turian wrote: > If I have a property in a derived class, it is difficult to override > the get and set functions: the property's function object had early > binding, whereas the overriden method was bound late. > This was previously discussed: > http://groups.google.com/group/comp.lang.python/browse_thread/thread/e13a1bd46b858dc8/9d32049aad12e1c1?lnk=gst#9d32049aad12e1c1 > > Could someone demonstrate how to implement the proposed solutions that > allow the property to be declared in the abstract base class, and > refer to a get function which is only implemented in derived classes? > > Thanks, > Joseph Sounds a little like you are trying to write Java in Python. 1) You don't need get/set functions to get/set properties in Python. You just get the property directly using dotted notation. 2) Properties defined in base class exist in derived class unless you override them. class foobase(object): def __init__(self): self.myProperty = 1 class foo(foobase): self.__init__(self, myProperty=None) foobase.__init__(self) if myProperty is not None: self.myProperty = myProperty obj = foo() print obj.myProperty >>> 1 obj = foo(6) print obj.myProperty >>> 6 obj.myProperty = 19 print obj.myProperty >>> 10 I hope this was what you were looking for. If not, I don't understand the question. -Larry From nagle at animats.com Wed May 28 00:19:06 2008 From: nagle at animats.com (John Nagle) Date: Tue, 27 May 2008 21:19:06 -0700 Subject: maximum recursion depth? In-Reply-To: <4789702b-53fd-490c-b5e2-7b5ff4432e5c@w34g2000prm.googlegroups.com> References: <7b55f3e5-b6f6-4c64-992e-47382d7803e7@m44g2000hsc.googlegroups.com> <4789702b-53fd-490c-b5e2-7b5ff4432e5c@w34g2000prm.googlegroups.com> Message-ID: <483cd9e2$0$34570$742ec2ed@news.sonic.net> alex23 wrote: > On May 28, 9:26 am, globalrev wrote: >> is there a definitie limit to the nbr of calls or is the memory that >> runs out? is that then the RAMmemory? is there a special amount of >> memory assigned for python or it just takes and takes until windows >> runs out of it? > > You can alter the recursion limit using sys.setrecursionlimit: > > setrecursionlimit(n) > > Set the maximum depth of the Python interpreter stack to n. This > limit prevents infinite recursion from causing an overflow of the > C > stack and crashing Python. The default is rather low. I've actually hit it parsing big HTML files with BeautifulSoup. John Nagle From arnodel at googlemail.com Tue May 27 16:34:53 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 27 May 2008 21:34:53 +0100 Subject: Weird exception in my, um, exception class constructor References: Message-ID: "Joel Koltner" writes: > I have a generic (do nothing) exception class that's coded like this: > > class MyError(exceptions.Exception): > def __init__(self,args=None): > self.args = args > > When I attempt to raise this exception via 'raise MyError' I get an > exception within the MyError constructor __init__ as follows: > > Traceback (most recent call last): > [lines deleted] > File "c:\Documents and Settings\Joel.Kolstad\My Documents\Python\ > MyStuff.py", line 7, in __init__ > self.args = args > TypeError: 'NoneType' object is not iterable That's because the class 'Exception' defines a descriptor 'args' which has to be a sequence. Just call 'args' something else, and it will work. E.g. >>> class MyError(Exception): ... def __init__(self, args=None): ... self.myargs = args ... >>> MyError() MyError() OTOH you could just take advantage of Exception.args: >>> class MyError(Exception): pass ... >>> MyError() MyError() >>> MyError(1, 2, 3) MyError(1, 2, 3) (Details in the documentation are a bit scant, but see http://docs.python.org/lib/module-exceptions.html) HTH -- Arnaud From upton at virginia.edu Fri May 30 11:01:19 2008 From: upton at virginia.edu (Dan Upton) Date: Fri, 30 May 2008 11:01:19 -0400 Subject: definition of a highlevel language? In-Reply-To: <80531$483b266d$3799@news.teranews.com> References: <2759eed3-956d-45c7-8dfb-9557f74133b3@56g2000hsm.googlegroups.com> <26d0b3d2-01cc-49bd-b284-1a849b0b835f@y38g2000hsy.googlegroups.com> <34dcbdc1-5285-41ec-be06-c88c56bb0372@i76g2000hsf.googlegroups.com> <45f03028-a86c-4357-9aa2-0148f7cc84dc@d45g2000hsc.googlegroups.com> <80531$483b266d$3799@news.teranews.com> Message-ID: <5504f9ac0805300801w5deb472dy3aed455e3f4747ef@mail.gmail.com> On Mon, May 26, 2008 at 5:06 PM, Paul Miller wrote: > On Mon, 26 May 2008 15:49:33 -0400, Dan Upton wrote: > >> On Mon, May 26, 2008 at 3:22 PM, wrote: > >> I don't know if it would necessarily look like the CPython VM, except >> for the decode stage (this being said without any knowledge of the >> CPython implementation, but with more than I ever thought I'd know about >> processor architecture/microarchitecture) > > Out of curiosity, do you know how easy it would be to make a Python chip > using FPGAs? I have little to no hardware knowledge, but it sounds like > a fun project in any case. Even if it's not likely to have blazing > performance, it'd be cool to load Python bytecode directly into > memory. :-) > I don't really know, but I would guess that it's hard, or at least time-consuming. The best example I can give you is "JOP: A Java Optimized Processor" which was basically an FPGA-based chip that executed Java bytecode natively. If you're curious, you can read about it at http://www.jopdesign.com/ . It looks like it was done as a PhD thesis at the Vienna University of Technology, and unless Austria has significantly lower PhD requirements... ;) From mensanator at aol.com Fri May 30 21:02:56 2008 From: mensanator at aol.com (Mensanator) Date: Fri, 30 May 2008 18:02:56 -0700 (PDT) Subject: How to covert ASCII to integer in Python? References: <5C5D68208EBBFD40A9DD9A194E957CCC2798EE@aust-mail.emsaus.com> <30b8b4ff-f0e5-4178-b9f7-513a5e404982@z72g2000hsb.googlegroups.com> Message-ID: <8ce037a7-b09c-40c2-a59c-2dff3d1a9126@34g2000hsh.googlegroups.com> On May 30, 7:59?pm, Mensanator wrote: > On May 30, 6:44?pm, Joshua Kugler wrote: > > > > > > > Skonieczny, Chris wrote: > > > YOU SHOULD REMOVE or CORRECT YOUR POST here: > > >http://mail.python.org/pipermail/python-list/2007-February/427841.html > > > > It is not true - eg. try : > > > a='P' ? ? ? ? ? ?# P is ASCII , isn't it ? > > > b=int(a) > > > and what you will get ? An error !!! > > > > Or probably you yourself should - quote : > > > "You probably should go through the tutorial ASAP that is located here: > > > >http://docs.python.org/tut/" > > > int() converts a strings that is a valid intenter. ?What you're looking for > > is ord(). > > Possibly. Perhaps the OP wants the position of 'P' > in the alphabet, in which case he wants b=64-ord(a) > or b=16. Oops! I meant ord(a)-64, of course. > > > > > > > In [1]: ord('d') > > Out[1]: 100 > > > In [2]: a='P' > > > In [3]: b=ord(a) > > > In [4]: b > > Out[4]: 80 > > > j From schickb at gmail.com Mon May 12 23:37:27 2008 From: schickb at gmail.com (schickb) Date: Mon, 12 May 2008 20:37:27 -0700 (PDT) Subject: Popen pipe hang References: Message-ID: <94c20ca2-57d9-4994-b3db-11ac4bdaeb8d@d19g2000prm.googlegroups.com> On May 12, 7:35 pm, Jean-Paul Calderone wrote: > >from subprocess import Popen, PIPE > >from array import array > > >arr = array('B') > >arr.fromstring("hello\n") > > >src = Popen( ["cat"], stdin=PIPE, stdout=PIPE) > >dst = Popen( ["cat"], stdin=src.stdout) > >arr.tofile(src.stdin) > >src.stdin.close() > >dst.wait() > > Alas, you haven't actually closed src's standard input. Though you did > close src.stdin, you didn't close the copy of it which was inherited by > dst! So though the file descriptor is no longer open in your main process, > it remains open due to the reference dst has to it. You can fix this by > having Popen close all file descriptors except 0, 1, and 2 before it execs > cat - pass close_fds=True to the 2nd Popen call and you should get the > behavior you want. > Thanks, that did the trick. Although I assume that by passing close_fds=True the second Popen is actually closing src.stdout (rather than src.stdin as mentioned)? With close_fds=True, is Python buffering the data even though bufsize=0 is the default? Otherwise I don't see how it could close the fd before executing the process. From exarkun at divmod.com Mon May 5 10:34:12 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 5 May 2008 10:34:12 -0400 Subject: Nested os.path.join()'s In-Reply-To: <1209997713.7106.32.camel@paul-laptop> Message-ID: <20080505143412.6859.316397324.divmod.quotient.59054@ohm> On Mon, 05 May 2008 16:28:33 +0200, Paul Scott wrote: > >On Mon, 2008-05-05 at 16:21 +0200, Paul Scott wrote: >> example: >> >> if os.path.exists(os.path.join(basedir,picdir)) == True : >> blah blah >> > >Sorry, pasted the wrong example... > >Better example: > > pics = glob.glob(os.path.join(os.path.join(basedir,picdir),'*')) > > >> Question is, is there a better way of doing this? The above *works* but >> it looks kinda hackish... How about not nesting the calls? >>> from os.path import join >>> join(join('x', 'y'), 'z') == join('x', 'y', 'z') True >>> Jean-Paul From goldnery at gmail.com Sat May 24 03:39:06 2008 From: goldnery at gmail.com (Gandalf) Date: Sat, 24 May 2008 00:39:06 -0700 (PDT) Subject: Another Question References: <5c2e7570-6bb1-46d8-8dd5-b1a257431b31@p25g2000hsf.googlegroups.com> <57c4cdf6-4920-46f9-986e-e2859de7de8b@27g2000hsf.googlegroups.com> Message-ID: On May 23, 10:47 pm, Mike Driscoll wrote: > On May 23, 1:44 pm, Gandalf wrote: > > > you've been very helpful but still i have only one problem. I wont the > > window not to be close after clicking the X button. > > I wont the program to stay on the toolbar > > > thanks! > > Well then, in your event handler, just don't do anything. > > def onClose(self, event): > pass > > or maybe you want to hide the frame? > > def onClose(self, event): > self.frame.Hide() > > Just make sure you give the user some other way to close it and in > that handler, you'll need to call self.frame.Destroy(). > > Alternatively, you can just tell the frame not to create the "X" > button: > > self.frame = wx.Frame(None, -1, title="My Frame", > style=wx.SYSTEM_MENU) > > However, that makes it pretty annoying to close. > > Mike OK the first method still didn't work. no matter what i do the window keep closing but the last one worked nice and all the top menu disappear thanks! From sturlamolden at yahoo.no Tue May 20 13:51:55 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 20 May 2008 10:51:55 -0700 (PDT) Subject: Using Python for programming algorithms References: <48315082$0$24599$426a74cc@news.free.fr> <62884fc6-6c74-4477-91de-7b7689b5fa75@m44g2000hsc.googlegroups.com> Message-ID: <7bd9e6b7-840a-4b08-b5d0-c22ca9503c9c@l64g2000hse.googlegroups.com> On May 20, 7:24 pm, Grant Edwards wrote: > > http://docs.python.org/lib/module-ctypes.html > Also see Cython (or Pyrex if you prefer the original). With Cython it is easy to call C functions, but Cython also alleviates the need for C to a great extent. The advantage of Cython over C + ctypes is of course the readability of Python and the presence of Python built-in types like strings, dicts and lists. Unfortunately, it is still a bit difficult to use NumPy ndarrays with Cython or Pyrex. NumPy ndarrays work very well with ctypes though. http://www.cython.org/ From castironpi at gmail.com Fri May 16 10:14:57 2008 From: castironpi at gmail.com (castironpi) Date: Fri, 16 May 2008 07:14:57 -0700 (PDT) Subject: Instance of class "object" References: <8763tea9sd.fsf@mulj.homelinux.net> Message-ID: On May 16, 4:16 am, Hrvoje Niksic wrote: > "??" writes: > > Howdy, > > I wonder why below does not work. > > > a = object() > > a.b = 1 # dynamic bind attribute failed... > > Because the default object class doesn't have a dict or other > indication of state. It's a "pure" Python object whose only visible > properties are its type and its identity. (On the implementation > level it also has a refcount.) > > This is necessary because all other Python objects (both new-style > classes and C extensions) inherit from 'object', on the C level. > Having state in 'object' would mean having that same in *all* other > Python objects. The current design, on the other hand, allows > creation of very lightweight python objects that don't even have a > dict. > > Subclassing object instructs Python as to what kind of state you want > your class to have. The default is to have a dict to store > properties: > > # a class with dict -- any property goes through dict, and creating a > # Foo object actually creates two objects, one Foo and one dict > class Foo(object): > pass > > But you can also specify: > > # an efficient 'Pair' class holding two objects > class Pair(object): > __slots__ = 'first', 'second' > > Instances of Pair take up even less room that 2-element tuples > because they don't carry the size information in the object. > > Now, if the object class carried a dict with it, it would be > impossible to create a class like 'Pair'. > > > To make it correct, we have to create a new class: > > class MyClass(object): pass > > a = MyClass() > > a.b = 1 # OK > > > Does this strange behavior break the LSP (Liskov substitution > > principle)? > > It follows from LSP that what the subclass may not introduce new > preconditions. In this case the subclass accepts a case that the > original class didn't, so it doesn't introduce a new precondition, it > simply weakens (removes) an existing one. Honor and narrow down: > Having state in 'object' would mean having that same in *all* other > Python objects. The current design, on the other hand, allows > creation of very lightweight python objects that don't even have a > dict. to: mass & volume, probably isolating -same-object- and -state-. No sinking. From Scott.Daniels at Acm.Org Sun May 4 10:58:18 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sun, 04 May 2008 07:58:18 -0700 Subject: Colors for Rows In-Reply-To: References: <4dc0cfea0804290733ic99e45eyec23a6d5b719eb8@mail.gmail.com> <20080429121105.f10c3862.darcy@druid.net> <4dc0cfea0804291114p4680f4bgb8446e7c6cb842cb@mail.gmail.com> <1209495803.5173.11.camel@aalcdl07.lib.unc.edu> Message-ID: D'Arcy J.M. Cain wrote: > On Tue, 29 Apr 2008 15:03:23 -0400 > "J. Cliff Dyer" wrote: >> Or, if you aren't sure how many colors you'll be using, try the more >> robust: >> >> bg[z % len(bg)] > > Good point although I would have calculated the length once at the > start rather than each time through the loop. > You may be surprised to find out that len(foo) is typically a retrieval question, not so much a calculation. Of course, measure anything you care about, and special methods may do much more, but in general, go for the simplest, clearest code you can write, and then speed it up when it needs it. I'd use len(bg) above unless my code was littered with calls to len of the same thing, in which case it might it might be clearer to choose a good name for len(bg). --Scott David Daniels Scott.Daniels at Acm.Org From duncan.booth at invalid.invalid Sat May 3 16:51:41 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 3 May 2008 20:51:41 GMT Subject: dict invert - learning question References: Message-ID: dave wrote: > Hello, > > here is a piece of code I wrote to check the frequency of values and > switch them around to keys in a new dictionary. Just to measure how > many times a certain key occurs: > > def invert(d): > inv = {} > for key in d: > val = d[key] > if val not in inv: > inv.setdefault(val, [key]) > else: > inv[val].append(key) > return inv > > > Using the methods above (I'm just a beginner) could I have written it > more concisely? Any criticism/critique in the code would be greatly > appreciated. > The obvious change I'd make is: if val not in inv: inv[val] = key else: ... etc. The setdefault method is only appropriate if you don't know whether or not the key is in the dictionary. since you've already tests that you should just go ahead and set the value. Otherwise it all seems fine. From george.sakkis at gmail.com Wed May 28 18:10:41 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 28 May 2008 15:10:41 -0700 (PDT) Subject: Writing a function from within Python References: Message-ID: <3c3f7866-75df-43c7-bbc6-cd2b80641a24@k30g2000hse.googlegroups.com> On May 28, 4:39 pm, Aaron Scott wrote: > Is it possible to change the content of a function after the function > has been created? For instance, say I make a class: > > class MyClass: > def ClassFunction(self): > return 1 > > And I create an object: > > MyObject = MyClass() > > Is there any way to change the content of the function, a la pseudo- > code: > > MyObject.ClassFunction = "return 2" > > Thanks for any insight you might be able to offer. The short answer is "yes". The longer answer is "yes but most likely there are better approaches to whatever you want to do". If you give a bit more context of the general problem you're trying to solve, I'm sure you'll get more helpful replies. George From hdante at gmail.com Thu May 22 00:41:13 2008 From: hdante at gmail.com (Henrique Dante de Almeida) Date: Wed, 21 May 2008 21:41:13 -0700 (PDT) Subject: Bug in floating-point addition: is anyone else seeing this? References: <0a9620e9-40f4-4d11-9ddf-9e0f424547b3@x35g2000hsb.googlegroups.com> Message-ID: <8fc0d94d-19bd-483a-8a57-8c03e47d2035@m45g2000hsb.googlegroups.com> On May 22, 1:36?am, Henrique Dante de Almeida wrote: > On May 22, 1:26?am, Henrique Dante de Almeida > wrote: > > > > > On May 21, 3:38?pm, Mark Dickinson wrote: > > > >>> a = 1e16-2. > > > >>> a > > > 9999999999999998.0 > > > >>> a+0.999 ? ? # gives expected result > > > 9999999999999998.0 > > > >>> a+0.9999 ? # doesn't round correctly. > > > > 10000000000000000.0 > > > ?Notice that 1e16-1 doesn't exist in IEEE double precision: > > ?1e16-2 == 0x1.1c37937e07fffp+53 > > ?1e16 == 0x1.1c37937e08p+53 > > > ?(that is, the hex representation ends with "7fff", then goes to > > "8000"). > > > ?So, it's just rounding. It could go up, to 1e16, or down, to 1e16-2. > > This is not a bug, it's a feature. > > ?I didn't answer your question. :-/ > > ?Adding a small number to 1e16-2 should be rounded to nearest (1e16-2) > by default. So that's strange. > > ?The following code compiled with gcc 4.2 (without optimization) gives > the same result: > > #include > > int main (void) > { > ? ? ? ? double a; > > ? ? ? ? while(1) { > ? ? ? ? ? ? ? ? scanf("%lg", &a); > ? ? ? ? ? ? ? ? printf("%a\n", a); > ? ? ? ? ? ? ? ? printf("%a\n", a + 0.999); > ? ? ? ? ? ? ? ? printf("%a\n", a + 0.9999); > ? ? ? ? } > > } > > However, compiling it with "-mfpmath=sse -msse2" it works. (it doesn't work with -msse either). From banibrata.dutta at gmail.com Mon May 12 13:43:35 2008 From: banibrata.dutta at gmail.com (Banibrata Dutta) Date: Mon, 12 May 2008 23:13:35 +0530 Subject: Is there no single/uniform RDBMS access API module for Python ? In-Reply-To: References: <3de8e1f70805112243u765fc507v32c5461be34d4077@mail.gmail.com> <4827E6B9.3080509@shopzeus.com> <3de8e1f70805112345u672d8ec0ia1aaa10a55e1b048@mail.gmail.com> Message-ID: <3de8e1f70805121043g786df5a4u2225862253858b87@mail.gmail.com> Thank you all for the pointers and precise information. Python community support surely rocks!! On 5/12/08, Daniel Fetchinson wrote: > > > >> Again a noob question. > > >> Based on this URL http://wiki.python.org/moin/DatabaseInterfaces , > is it > > >> correct to conclude that there is no RDBMS agnostic, single/uniform > DB > > >> access API for Python ? > > >> Something in the lines of JDBC for Java, DBD for Perl etc. ? > > >> How is the RDBMS change handled for solutions which need to work > with > > >> different RDBMSs ?? > > >> > > > http://www.python.org/dev/peps/pep-0249/ > > > > > > > > > That appears to be only an API specification. Are there any > implementations > > of that ? > > For sqlite: http://oss.itsystementwicklung.de/trac/pysqlite/ if you > have python < 2.5 for 2.5 and up it is included in the stdlib > > For mysql: http://sourceforge.net/projects/mysql-python > > There are a tons more, including postgresql, oracle, etc: > http://wiki.python.org/moin/DatabaseInterfaces > > Cheers, > Daniel > -- > Psss, psss, put it down! - http://www.cafepress.com/putitdown > -- > http://mail.python.org/mailman/listinfo/python-list > -- regards, Banibrata http://www.linkedin.com/in/bdutta http://octapod.wordpress.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From lists at cheimes.de Mon May 12 12:30:39 2008 From: lists at cheimes.de (Christian Heimes) Date: Mon, 12 May 2008 18:30:39 +0200 Subject: Compiling Python using Microsoft Visual C++ 2008 In-Reply-To: References: <482855df$0$14196$9b622d9e@news.freenet.de> Message-ID: <482870AF.6020500@cheimes.de> Colin J. Williams schrieb: >> See PCbuild/readme.txt. > > I presume that this is PCbuild8.txt No, it's PCbuild/readme.txt in Python 2.6 and 3.0 By the way you can call Tools\buildbot\external.bat from the root directory of the 2.6 and 3.0. It checks out and build the dependencies. The script requires the VS 9.0 tools and the svn command line executables. Christian From gagsl-py2 at yahoo.com.ar Mon May 26 19:23:39 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 26 May 2008 20:23:39 -0300 Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <8763t3by81.fsf@benfinney.id.au> <09847cfc-eaec-4adc-8cbf-1e2ebbf940c4@m44g2000hsc.googlegroups.com> <039f3c2d-4ebb-4412-9cbf-458afa412c4e@i36g2000prf.googlegroups.com> Message-ID: En Mon, 26 May 2008 17:02:21 -0300, Russ P. escribi?: > On May 26, 9:08 am, "Gabriel Genellina" > wrote: >> En Mon, 26 May 2008 06:14:19 -0300, Paul Boddie >> escribi?: >>> On May 26, 6:49 am, "Russ P." wrote: >>>> I am also bothered a bit by the seeming inconsistency of the rules for >>>> the single underscore. When used at file scope, they make the variable >>>> or function invisible outside the module, but when used at class >>>> scope, the "underscored" variables or functions are still fully >>>> visible. For those who claim that the client should be left to decide >>>> what to use, why is the client prohibited from using underscored >>>> variables at file scope? >> >> There is no rationale because this is not how it works... [snip >> explanation of how import works] > > Well, that's interesting, but it's not particularly relevant to the > original point. By default, underscored variables at file scope are > not made visible by importing the module in which they appear. But > underscored member variables of a class *are* made visible to the > client by default. That's seems at least slightly inconsistent to me. To make things clear: _variables ARE visible when you import a module: C:\TEMP>type module.py _variable = 123 (invoke python) py> import module py> module._variable 123 py> dir(module) ['__builtins__', '__doc__', '__file__', '__name__', '_variable'] py> py> from module import _variable py> _variable 123 Only when you use "from module import *" _variable isn't imported. (new python session): py> from module import * py> _variable Traceback (most recent call last): File "", line 1, in NameError: name '_variable' is not defined That last form should not be used normally, except when playing with the interactive interpreter. > The issue here, for me at least, is not whether the data or methods > should be absolutely hidden from the client. I'm perfectly willing to > say that the client should have a back door -- or even a side door -- > to get access to "private" data or methods. > > But I also believe that some standard way should be available in the > language to tell the client (and readers of the code) which methods > are *intended* for internal use only. And that method should be based > on more than a naming convention. Why? Because (1) I don't like > leading underscores in my identifiers, and (2) I think I should be > free to choose my identifiers independently from their properties. > > Is this a major issue? No. Is it a significant issue. Yes, I think so. Ok, that's what you'd like Python to be. Unfortunately your view appears not to be shared by the language developers. > Here's another suggestion. Why not use "priv" as shorthand for > "private"? Then, > > priv height = 24 > > at file scope would make "height" invisible outside the module by > default. And the same line in a class definition would give "height" > the equivalent of "protected" status in C++. Python data model is centered on namespaces, and it's hard to tell whether certain attribute is being accessed from "inside the class" or from "outside the class" in order to allow or deny access. It's not like static languages where the whole class definition has a certain lexical scope and it can't be modified afterwards; the set of allowed attributes is fixed at compile time. In Python you can add/remove/alter attributes (including methods) dynamically. You can create classes without using the class statement. The same method may be shared by many unrelated classes. If you can devise a practical and efficient mechanism to determine access right in all those varying circumstances, please post it to the python-ideas list for further discussion. (In the meantime we'll continue to use a naming convention for us consenting adults.) > I think "height" looks cleaner than "_height". And isn't clean code a > fundamental aspect of Python? I like the fact that the mere attribute name conveys useful information abut its intended usage. And I don't care about the _, it doesn't look ugly to me. But that's just my personal opinion. -- Gabriel Genellina From Scott.Daniels at Acm.Org Sat May 24 10:37:00 2008 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 24 May 2008 07:37:00 -0700 Subject: Code correctness, and testing strategies In-Reply-To: References: Message-ID: David wrote: > Specifically, if you've just written 100 new lines of Python code, then: > 1) How do you test the new code? > 2) How do you ensure that the code will work correctly in the future? > > Short version: > > For (1) I thoroughly (manually) test code as I write it, before > checking in to version control. > > For (2) I code defensively. > ... > As for point 1 (how do you test the new code?): > I like the idea of automated unit tests. However, in practice I find > they take a long time to write and test, especially if you want to > have good coverage (not just lines, but also possible logic branches). This is why I have reluctantly come to accept the XP people's view: if you you write the tests _as_ you develop (that is as far as I go w/o re-enforcement; they would have you write them _before_), you will have a body of tests that work to demonstrate the correctness or deficiencies of your code based on what it _should_ do. If you write tests after you've written the code, you will write tests that are based on what your code _actually_does_. You don't want the latter; the tests are brittle. The tests don't match needs, rather they match implementations. Therefore you'll need to discard more tests at every local rewrite. > 1) Add "raise 'UNTESTED'" lines to the top of every function String exceptions are deprecated. Just raise UNTESTED (and let the access to undefined global error be the issue). ...... > 11) Cause those sections of code to be run also (sometimes I need to > temporarily set vars to impossible values inside the script, since the > logic will never run otherwise) > > And here is one of my biggest problem with unit tests. How do you unit > test code which almost never runs? The only easy way I can think of is > for the code to have 'if or running test case XYZ> lines'. I know I'm meant to make 'fake' testing > classes which return erroneous values, and then pass these objects to > the code being tested. But this can take a long time and even then > isn't guaranteed to reach all your error-handling code. Ah, but now you tests are "brittle"; they only work for the code you have now. If you want to make sure you have code coverage with your test, the XP way is: Write a test for behavior you need. Watch it fail. Fix the code so all tests pass. Lather, rinse, repeat. You should not have untested code, because there was no test that made you write it. If you want to do code coverage, find a code coverage tool and count your code while runnign your unit tests. --Scott David Daniels Scott.Daniels at Acm.Org From daveparker at flamingthunder.com Tue May 13 13:41:00 2008 From: daveparker at flamingthunder.com (Dave Parker) Date: Tue, 13 May 2008 10:41:00 -0700 (PDT) Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <5b0e3f70-afde-4480-8713-e7113b1250d7@x35g2000hsb.googlegroups.com> <1f537717-00d0-48ee-99b6-7125b96a6133@t12g2000prg.googlegroups.com> <68t4o0F2vaoncU1@mid.uni-berlin.de> <2a32179a-9439-449c-bd07-fff6a4075aee@s50g2000hsb.googlegroups.com> <7ee5dffd-df8f-46f0-bd78-c81ac0418a9a@d77g2000hsb.googlegroups.com> <65ef773e-a1c3-4adb-a18b-e8b8451efe5e@b5g2000pri.googlegroups.com> <68trmmF2vjivnU1@mid.uni-berlin.de> <0bda514d-7e61-45ff-826b-9e64999b18c3@z24g2000prf.googlegroups.com> Message-ID: Time for me to get back to work now. Thank you all for your comments, they will help to make Flaming Thunder a better product. I can see that many people would like the ability to link to existing applications and libraries, etc, so I will raise that on my priority list. From tinnews at isbd.co.uk Thu May 15 06:52:44 2008 From: tinnews at isbd.co.uk (tinnews at isbd.co.uk) Date: 15 May 2008 10:52:44 GMT Subject: python newbie: some surprises References: <67b60370-bed9-4f43-b401-25ce2fd89522@t54g2000hsg.googlegroups.com> <48240fe6$0$5108$426a34cc@news.free.fr> <53e8ab1c-d786-493b-82df-66055949172a@w4g2000prd.googlegroups.com> <3c0c.482c0fc1.3224e@altium.nl> Message-ID: <482c15fc$0$656$bed64819@news.gradwell.net> Kees Bakker wrote: > > So far, I have seen only one editor that understands the difference between > TABs and indentation, and that is Emacs. Most vi clones (and the original vi) do too! :-) E.g. in the clone I use (vile) there are independent settings for tabstop and shiftwidth. In addition you can tell the editor to change tabs to spaces (or not) as you wish. -- Chris Green From mensanator at aol.com Sun May 11 00:16:15 2008 From: mensanator at aol.com (Mensanator) Date: Sat, 10 May 2008 21:16:15 -0700 (PDT) Subject: Prettyprinting SQL statements References: Message-ID: On May 10, 10:23?pm, MooJoo wrote: > I'm building a Python app that will be making queries to a MySQL server > using the MySQLdb module. The app will need to create SQL statements on > the fly which, in addition to going to the server, will occasionally > need to be displayed to the user. While these queries are not too > complex, they still can be difficult to decipher without doing some > formatting. I've done the requisite Googling to see if a library to > format SQL can be found but, other than commericial Windows apps and > some on-line formatters, I've not found anything remotely usable. Before > trying to write my own parser/formatter, I was hoping somebody might > know of a package to perform this function. > > Anybody? Ferris? Anybody at all? > > Thanks. I always just do this: def keyword(s): if s.isupper(): return '\n'+s+'\t' else: return s sql = "SELECT letter.*,letter1.* FROM letter,letter AS letter1 ORDER BY letter.n;" s = sql.split() pp = ' '.join(map(keyword,s)) print pp Then insert the pp strings into my source code as shown. # unjoined tables create a Cartesian Product # import sqlite3 con = sqlite3.connect(":memory:") cur = con.cursor() cur.executescript(""" create table letter(n); """) letters = [('a'),('b'),('c'),('d'),('e'),('f'),('g'),('h')] cur.executemany(""" INSERT INTO letter(n) VALUES (?); """ , letters) cur.execute(""" SELECT letter.*,letter1.* FROM letter,letter AS letter1 ORDER BY letter.n; """) cartesian_product = cur.fetchall() for i in cartesian_product: print i[0]+i[1], From daveparker at flamingthunder.com Mon May 19 23:33:43 2008 From: daveparker at flamingthunder.com (Dave Parker) Date: Mon, 19 May 2008 20:33:43 -0700 (PDT) Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <20080514215943.14c92f16.johnjsal@NOSPAMgmail.com> Message-ID: On May 14, 7:59?pm, John Salerno wrote: > Would it be valid to say: > > x = "concrete" > > or to say: > > if command (is) set to "quit" > > ?????? I like the idea of: If command is set to "quit" ... I've added it to my list of things to think about, and possibly implement. From bruno.42.desthuilliers at websiteburo.invalid Tue May 20 03:09:13 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 20 May 2008 09:09:13 +0200 Subject: explain this function to me, lambda confusion In-Reply-To: <74ce1ffa-0031-4101-8792-5f2ba7f22bca@b64g2000hsa.googlegroups.com> References: <5cc7ef7a-dd21-4772-a7e3-765410f810bb@l17g2000pri.googlegroups.com> <081fe61b-820b-4512-80a9-8a0805f3ce55@k13g2000hse.googlegroups.com> <74ce1ffa-0031-4101-8792-5f2ba7f22bca@b64g2000hsa.googlegroups.com> Message-ID: <48327914$0$30041$426a74cc@news.free.fr> Paul McGuire a ?crit : > On May 19, 11:04 am, Arnaud Delobelle wrote: >> Paul McGuire writes: >> >> [...] >> >> Could you use it as a decoratore instead? >> >> integer = Word("0123456789") >> >> @integer.setParseAction >> def parse_integer(tokens): >> return int(tokens[0]) >> >> I could make your grammar clearer, because you don't mix it with >> processing code... and no need for lambdas! > > What a sexy little idiom! You could really apply this to any API > method that accepts a callable as a single argument, and pyparsing > actually has several of these: > > setParseAction > addParseAction > setFailAction > setDebugActions > > (Unfortunately, setDebugActions requires 3 callables for its arguments > - one to be run when an expression is about to be parsed, one to be > run after parsing is complete, and one to be run if the expression > fails to be parsed. So setDebugActions can't be used in this > decorator manner.) You just have to provide three decorators instead, one for each callback. > > Using these methods as decorators deviates from the typical decorator > usage model as I understand it - instead of wrapping the provided > function within some enclosing setup/teardown code (like lock/unlock, > or open-file/close-file, or begin-transaction/commit-transaction), and > then returning the created wrapper function, the decorator usage you > propose is one in which the decorator uses the provided function with > some side-effect (such as setting a property), but then just returns > the original function. This is already a well-known decorator pattern. It's used in CherryPy to mark methods that are exposed as request handlers. From roy at panix.com Fri May 2 10:11:36 2008 From: roy at panix.com (Roy Smith) Date: Fri, 02 May 2008 10:11:36 -0400 Subject: #!/usr/bin/env python vs. #!/usr/bin/python References: <87abj91j8u.fsf@benfinney.id.au> <871w4l1cjj.fsf@benfinney.id.au> <87r6ckzvyv.fsf@benfinney.id.au> Message-ID: In article <87r6ckzvyv.fsf at benfinney.id.au>, Ben Finney wrote: > Whereas if Python is *not* installed from an OS package, it's up to > the sys admin to ensure that it works -- not up to my program. So I > don't see the point in making it work by default, when what I want for > my program is that it works *with the default Python*, not with some > non-default installation. Ben, Have you ever shipped software to a customer? Imagine the following conversation: Customer: "Your product is broken. It says it can't find python, and I know I have it installed". Vendor: "Where do you have it installed?" Customer: "In /opt/bin/python" Vendor: "Oh, that's your problem, it HAS to be in /usr/bin/python". Customer: "I can't install it there because . If you can't make your product work without requiring me to install python in /usr/bin, I'm afraid I can't buy your product". Vendor: "No problem sir, I'll be happy to tell our sales folks to stop bothering you". If you want to hard-code /usr/bin/python into your application, that's your decision. If you would like to take on the task of convincing every sysadmin in the world to do things the way you think they should be done, have fun. From maxm at mxm.dk Mon May 26 04:26:24 2008 From: maxm at mxm.dk (Max M) Date: Mon, 26 May 2008 10:26:24 +0200 Subject: Python web development that resembles PHP or classic ASP In-Reply-To: <66a261d8-c31d-4519-beb9-c8913f61a87d@m44g2000hsc.googlegroups.com> References: <66a261d8-c31d-4519-beb9-c8913f61a87d@m44g2000hsc.googlegroups.com> Message-ID: erik.oosterwaal at gmail.com skrev: > Hi All, > So that's when I started looking at other dynamic languages for > webdevelopment. I looked at Ruby on Rails and at the different web- > frameworks that are available for Python. The biggest problem there > for me is that the MVC type frameworks that are currently very popular > are also not what I'm looking for. Hi Erik, I am an experienced Python developer working mostly in Plone. Before that I came from asp like you. If you want something that is most like what you are used to, you should check out Django. I have not worked in it, but it get high praises from developers I trust. http://www.djangoproject.com/ If you want a more "modern" approach you should check out Grok. It has been built on all the experiences made with Zope 2, CMF and Plone. It is based on Zope 3. http://grok.zope.org/ It is the one I would choose if starting from fresh today. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From destroooooy at gmail.com Mon May 19 15:39:36 2008 From: destroooooy at gmail.com (destroooooy) Date: Mon, 19 May 2008 12:39:36 -0700 (PDT) Subject: conventions/requirements for 'is' vs '==', 'not vs '!=', etc Message-ID: I'm wondering what is the canonical usage of the keywords 'is' and 'not' when you're writing conditionals and loops. The one I've been following is completely arbitrary--I use the symbols '==', '!=' for numerical comparisons and the words 'is', 'not' for everything else. Thanks in advance! From ivan.illarionov at gmail.com Sat May 17 00:01:50 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Sat, 17 May 2008 04:01:50 +0000 (UTC) Subject: Classmethods are evil Message-ID: After re-reading "Python is not Java" I finally came to conclusion that classmethods in Python are a very Bad Thing. I can't see any use-case of them that couldn't be re-written more clearly with methods of metaclass or plain functions. They have the following issues: 1. You mix instance-level and class-level functionality in one place making your code a mess. 2. They are slower than metaclass methods or plain functions. I really want to hear your opinions on the subject. -- Ivan From wmcbrine at users.sf.net Wed May 28 01:01:37 2008 From: wmcbrine at users.sf.net (William McBrine) Date: Wed, 28 May 2008 05:01:37 GMT Subject: Keeping focus with sequential Tkinter windows? Message-ID: So, basically what I'm doing is this: window1 = Tkinter.Tk() ... window1.destroy() ... window2 = Tkinter.Tk() This works well in Linux and Mac OS X (and the PyGtk equivalent works on all platforms), but in Windows XP, the second window comes up without focus. (I have to click on it to focus it.) This is true even with no other windows on screen. I've tried window2.focus_set(), window2.lift(), etc., to no avail. What's the right way to do this? -- 09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -- pass it on From bignose+hates-spam at benfinney.id.au Sat May 24 10:00:32 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 25 May 2008 00:00:32 +1000 Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <8763t3by81.fsf@benfinney.id.au> Message-ID: <87zlqfajjz.fsf@benfinney.id.au> Ben Finney writes: > If you want the users of your code to know that an attribute should > not be used as a public API for the code, use the convention of > naming the attribute with a single leading underscore. This is a > string signal that the attribute is part of the implementation, not > the interface. Quite apart from whether it's a string signal, I meant to write that it's a *strong* signal. -- \ "Some people, when confronted with a problem, think 'I know, | `\ I'll use regular expressions'. Now they have two problems." | _o__) ?Jamie Zawinski, in alt.religion.emacs | Ben Finney From basti.wiesner at gmx.net Sat May 17 14:16:05 2008 From: basti.wiesner at gmx.net (Sebastian 'lunar' Wiesner) Date: Sat, 17 May 2008 20:16:05 +0200 Subject: Install man-pages with distutils/setuptools References: <482ec6e0$0$6774$9b4e6d93@newsspool2.arcor-online.net> Message-ID: [ Hartmut Goebel ] > Hi, > > is there a standard way or a snippet for installing man-pages with > > python set.py install > > when using distutils or setuptools? No, not even setuptools provides a standard way for man pages. -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) From deets at nospam.web.de Tue May 13 13:32:30 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 13 May 2008 19:32:30 +0200 Subject: Python and Flaming Thunder In-Reply-To: References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <5b0e3f70-afde-4480-8713-e7113b1250d7@x35g2000hsb.googlegroups.com> <1f537717-00d0-48ee-99b6-7125b96a6133@t12g2000prg.googlegroups.com> <68t4o0F2vaoncU1@mid.uni-berlin.de> <2a32179a-9439-449c-bd07-fff6a4075aee@s50g2000hsb.googlegroups.com> <7ee5dffd-df8f-46f0-bd78-c81ac0418a9a@d77g2000hsb.googlegroups.com> <65ef773e-a1c3-4adb-a18b-e8b8451efe5e@b5g2000pri.googlegroups.com> <68trmmF2vjivnU1@mid.uni-berlin.de> <68tuhfF2unducU1@mid.uni-berlin.de> <68tulsF2unducU2@mid.uni-berlin.de> Message-ID: <68u1lqF2sv8gjU1@mid.uni-berlin.de> Dave Parker schrieb: >> Just to support this statement: PHP runs an order of magnitude slower than >> python. Yet a great deal (if not the majority) of dynamic sites out there >> run under PHP. All of these are unhappy customers? > > The websites owners might not be unhappy, but lots of customers > complain about slow websites, so if the market is competitive then > eventually the PHP fad will die out. Slow websites mainly come from bad coding. I've seen websites performing slow written in Java - which should even surpass FT, btw. > For example, Slashdot recently interviewed a successful website in a > competitive market -- online newspapers -- and found that to enhance > customer happiness the New York Times uses hand-coded HTML. > > "He was asked how the Web site looks so consistently nice and polished > no matter which browser or resolution is used to access it. His answer > begins: 'It's our preference to use a text editor, like HomeSite, > TextPad or TextMate, to "hand code" everything, rather than to use a > wysiwyg (what you see is what you get) HTML and CSS authoring program, > like Dreamweaver. We just find it yields better and faster results.'" > http://news.slashdot.org/article.pl?sid=08/04/30/009245&from=rss You obviously have no clue what this aboven statement talks about. It is not about speed - it's about how HTML is generated, and the negative impact of visual design tools on that. What on earth has that to do with the execution speed of a webapp? > "Faster" wins in a competitive market, so if a programming language > can't deliver "faster", it is a fad that will die out. "Faster" wins, yes - in the sense of brain-cycles. Faster coding, faster changing, faster delivering. If it was anything else, we wouldn't have higher level languages, and still code assembler. You really don't know what you are talking about. But you are of course entitled to your opininon. Time will tell who is the "fad", and who not. I can assure you I have a strong opinion on that.... Diez From notbob at nothome.com Wed May 7 10:38:32 2008 From: notbob at nothome.com (notbob) Date: Wed, 07 May 2008 14:38:32 GMT Subject: Are rank noobs tolerated, here? References: <3zITj.35199$gB5.25251@fe105.usenetserver.com> <995582f9-754f-4f6e-857e-8156ea7b0b20@56g2000hsm.googlegroups.com> Message-ID: On 2008-05-06, hdante wrote: > When you have a problem with your code, always post here the complete > code and a complete execution. For example: I'll keep this example. Thnx. > /----------\ glued > | bruce | ------> 42 > \----------/ > > When you use a stamp, it returns what it's glued on: > > >>> bruce = 42 # glue a stamp > >>> print bruce # use the stamp > 42 > 'bruce' is a string (notice the quotes). In this case bruce is glued > to 'bruce': > > /----------\ glued > | bruce | ------> 'bruce' > \----------/ The light is dawning..... > Stupid. Not really. :-) I'd rather say that the problem is the book. Well, me too, of course. ;) > The book is just another introduction to programming. There's no > special attempt to make the reader learn to think like a computer > scientist. Apparently, and I understand. It's hard for someone who is very knowledgable on a subject to remain in "explain it like they're 5 yrs old" mode. It's tedious and time consuming. >> How am I supposed to get the original def to work? I've yet to figure out > file myfile.py: > ------------------------------- > def print_twice(bruce): > print bruce, bruce > > print_twice('bruce') > print_twice(2) > ------------------------------- > > execution: > ------------------------------- > $ python myfile.py > bruce bruce > 2 2 BINGO! (and it worked (after I got the indents right)) > Finally, you don't understand something, ask again. Thank you. I really do appreciate your taking the time to break it down so completely. I found another python book (A Byte of Python) that keeps it simple enough for me. I'm not really a programmer, but I decided to do something to challenge this old geezer brain and figured this would keep it awake. I'd also like to thank all you other folks who responded. I got some good info and tips from all of you. nb From iqbaltalaat at gmail.com Fri May 16 12:06:27 2008 From: iqbaltalaat at gmail.com (I-T) Date: Fri, 16 May 2008 09:06:27 -0700 (PDT) Subject: Making Variable Text Output More Pythonic? References: <015e35b2-165c-4693-bf6c-38ad0cce7553@t12g2000prg.googlegroups.com> <781ccceb-2474-484f-b6c8-f4b59b2396b5@27g2000hsf.googlegroups.com> Message-ID: A thousand apologies for my ignorance. I'll try not to get names mixed up again in the future. On May 16, 8:42?pm, Arnaud Delobelle wrote: > afrobeard writes: > > Arnaud's code wont work if self.opt1 is None, an empty list, an empty > > tuple, False, etc, because all these evaluate to false. They wont > > print the internal state of these variables. [Just an informational > > notice, this may be the behavior you expect] > > ??? My suggestion is to get rid of attributes altogether and does not > test any truth values. > > > > > Secondly, I'm not sure if you know the variable names from before hand > > in which case Casey's approach will work, or you need to know them via > > introspection.http://www.ibm.com/developerworks/library/l-pyint.html > > [Scroll down to attributes]. > > > On May 16, 1:44?am, Arnaud Delobelle wrote: > >> Casey writes: > >> > Hi, > > >> > I have some classes that print variable outputs depending on their > >> > internal state, like so: > > >> > def __str__(self): > >> > ? ? out = [] > >> > ? ? if self.opt1: out += ['option 1 is %s' % self.opt1'] > >> > ? ? if self.opt2: out += ['option 2 is %s' % self.opt2'] > >> > ? ? .... > >> > ? ? return '\n'.join(out) > > >> > Is there any way to make this cleaner? > > >> Maybe. > > >> Have a dictionary of options rather than individual attributes; > >> options not in the dictionary are not set. E.g. > > >> mask = { > >> ? ? 'opt1': 'option 1 is %s', > >> ? ? 'opt2': 'option 2 is %s', > >> ? ? ... > >> ? ? } > > >> def __str__(self): > >> ? ? return '\n'.join(mask[o] % v for o,v in self.options.iteritems()) > > >> -- > >> Arnaud From roy at panix.com Fri May 2 14:03:47 2008 From: roy at panix.com (Roy Smith) Date: Fri, 02 May 2008 14:03:47 -0400 Subject: Non-blocking connect References: <59915ad0-2af1-4903-8ffd-48da2ce4e647@y22g2000prd.googlegroups.com> Message-ID: In article <59915ad0-2af1-4903-8ffd-48da2ce4e647 at y22g2000prd.googlegroups.com>, mp wrote: > Code is at bottom. Basically, if I turn off socket blocking prior to > connecting, I get a "Socket is not connected" error when I try to send > data. However, if I do not turn off blocking, OR if I place a print > statement anywhere before the send call, it works! WTF? > > I'd like to understand what's going on in the background here, if you > know don't skimp on the details. > > Thanks > > --------------------------------------------------------------- > import > socket > sock = socket.socket(socket.AF_INET, > socket.SOCK_STREAM) > sock.setblocking(0) > sock.connect_ex(('localhost', > 9000)) > sock.setblocking(1) > sock.send('foo') > sock.close() I can't be 100% sure about this because I don't know what's running on your port 9000 that you're trying to connect to, but I think I know what's going on. I just tried your code, but changed 9000 to 22 (ssh). What I found is that if you eliminate the setblocking(0) call, the connect_ex() call returns 0, indicating it succeeded. If you leave the setblocking(0) call in, connect_ex() returns EINPROGRESS (Operation now in progress). This makes sense. Here's the code: import socket import os import errno sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setblocking(0) err = sock.connect_ex(('localhost', 22)) print errno.errorcode[err], os.strerror(err) When you do a TCP connect, there is what's called a three-way handshake that happens between the TCP stacks at the two ends of the connection. I send a packet with the SYN bit set, you respond with a packet with both SYN and ACK set, and I respond with an ACK. Even when both ends are on the same box (i.e. localhost), this has to happen. Quoting from http://docs.python.org/lib/socket-objects.html: > Some notes on socket blocking and timeouts: [...] In non-blocking mode, > operations fail (with an error that is unfortunately system-dependent) if > they cannot be completed immediately. Since the three-way handshake can't be completed immediately, the connect_ex call fails when you try it in non-blocking mode. So, that's the explanation. Now the question: What are you trying to do that you need non-blocking mode? Or are you just experimenting to see what happens? BTW, this was done on an OSX-10.5.2 box, but I think the result would be essentially the same on any platform. From gagsl-py2 at yahoo.com.ar Thu May 1 04:41:37 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 01 May 2008 05:41:37 -0300 Subject: Sending Cntrl-C ?? References: <0274834e-17e1-4a95-88ec-f2aa77aeb3a9@k10g2000prm.googlegroups.com> <8d53535b-b00e-40b4-b65f-1ca126884592@k10g2000prm.googlegroups.com> Message-ID: En Wed, 30 Apr 2008 15:06:13 -0300, gamename escribi?: >> win32api.GenerateConsoleCtrlEvent(win32con.CTRL_C_EVENT, pgid) > > How do you determine the value of 'pgid'? Make the child start a new process group, then its pid is the process group ID. You have to use the "creationflags" parameter of subprocess.open The documentation for GenerateConsoleCtrlEvent http://msdn.microsoft.com/en-us/library/ms683155.aspx states that you can't send CTRL_C_EVENT to another process group, only CTRL_BREAK_EVENT (and only to the same console as the sender process). A little example: import subprocess import ctypes import time CREATE_NEW_PROCESS_GROUP = 512 CTRL_C_EVENT = 0 CTRL_BREAK_EVENT = 1 GenerateConsoleCtrlEvent = ctypes.windll.kernel32.GenerateConsoleCtrlEvent print "start child process" p = subprocess.Popen("cmd /c for /L %d in (10,-1,0) do @(echo %d && sleep 1)", creationflags = CREATE_NEW_PROCESS_GROUP) print "pid=", p.pid print "wait 3 secs" time.sleep(3) print "send Ctrl-Break" GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, p.pid) print "wait for child to stop" print "retcode=", p.wait() print "done" Output: start child process pid= 872 wait 3 secs 10 9 8 7 send Ctrl-Break wait for child to stop retcode= 255 done (Instead of ctypes and those magical constants, you can install the pywin32 package and use win32api.GenerateConsoleCtrlEvent, win32con.CTRL_BREAK_EVENT and win32process.CREATE_NEW_PROCESS_GROUP) The only way I know of to send a Ctrl-C event to a different console involves remote code injection. -- Gabriel Genellina From castironpi at gmail.com Wed May 7 14:07:45 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 7 May 2008 11:07:45 -0700 (PDT) Subject: Generate labels for a multi-level outline References: <64734826-d678-4377-8307-ae3fc1933c16@24g2000hsh.googlegroups.com> Message-ID: <12bfe5e4-86ff-4706-bf42-4273a9938046@l64g2000hse.googlegroups.com> On May 7, 9:07?am, castiro... at gmail.com wrote: > ''' > On May 6, 4:43 pm, pyt... at bdurham.com honoring: > > >>> a.next( ) > ( "I", ) > >>> a.throw( up ) > ( "I", "A" ) > >>> a.next( ) > ( "I", "B" ) > >>> a.next( ) > ( "I", "C" ) > >>> a.throw( down ) > > ( "II", ) > ''' > > #funny declaration > class up( Exception ): pass > class down( Exception ): pass > > def outline( ): > ? ? stack= [ 1 ] > ? ? while 1: > ? ? ? ? try: > ? ? ? ? ? ? yield stack > ? ? ? ? ? ? stack[ -1 ]+= 1 > ? ? ? ? except up: > ? ? ? ? ? ? stack.append( 1 ) > ? ? ? ? except down: > ? ? ? ? ? ? stack.pop( -1 ) > ? ? ? ? ? ? stack[ -1 ]+= 1 > > a= outline( ) > print a.next( ) > print a.throw( up ) > print a.next( ) > print a.next( ) > print a.throw( down ) > print a.throw( up ) > print a.throw( up ) > print a.next( ) > print a.next( ) > print a.throw( down ) > > ##output: > > [1] > [1, 1] > [1, 2] > [1, 3] > [2] > [2, 1] > [2, 1, 1] > [2, 1, 2] > [2, 1, 3] > [2, 2] > > ## > > cf. > > formatter.NullFormatter.format_counter > formatter.NullFormatter.format_letter > formatter.NullFormatter.format_roman One execution of Python 3a4 included in built-ins. Python 3.0 win32 Type "help >>> next >> Do you want send and throw in it too? From rocky at panix.com Thu May 15 07:26:07 2008 From: rocky at panix.com (R. Bernstein) Date: Thu, 15 May 2008 07:26:07 -0400 Subject: Running an interactive interpreter inside a python References: Message-ID: "Alan J. Salmoni" writes: > I'm not sure if this is exactly what you're after, but try looking > into the 'code' module. > > It's fairly easy to make an interactive interpreter that runs within > your program. If you import your programs variables into > __main__.__dict__, you can have access to them which can be funky. You > can even override the showtraceback method to catch various exceptions > and do daft things like adding new methods to strings. I guess it > would even be possible to have the commands compared to a list of > commands and keywords to build a restricted interpreter, though how > secure this would be against a determined attack is another matter. > > Alan I think this (largely) does the trick. Thanks! I'm not sure about how to deal with globals yet which should come from a stackframe f_globals. It might be possible to save and restore __main__.__dict__ before and after the call to interact(). Probably would have been cooler to design interact() to take a globals parameter, same as eval does. > > On May 15, 11:31 am, ro... at panix.com (R. Bernstein) wrote: >> The next release of pydb will have the ability to go into ipython from >> inside the debugger. Sort of like how in ruby-debug you can go into >> irb :-) >> >> For ipython, this can be done pretty simply; there is an IPShellEmbed >> method which returns something you can call. But how could one do the >> same for the stock python interactive shell? >> >> To take this out of the realm of debugging. What you want to do is to >> write a python program that goes into the python interactive shell - >> without having to write your own a read/eval loop and deal with >> readline, continuation lines, etc. >> >> The solution should also allow >> - variables/methods in the calling PYthon program to be visible >> in the shell >> - variables set in the interactive (sub) shell should persist after the shell >> terminates, although this is a weaker requirement. POSIX subshells >> for example *don't* work this way. >> >> There has been much written about how to embed Python from C, so I >> suppose this may offer one way. And at worst, I could write >> a C extension which follows how C Python does this for itself. >> >> But is there a simpler way? >> >> Thanks. From paul at boddie.org.uk Wed May 21 10:23:04 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 21 May 2008 07:23:04 -0700 (PDT) Subject: Database Query Contains Old Data References: <33b13117-0f9f-435d-b8f8-19f1ed3a121a@d77g2000hsb.googlegroups.com> <4f0163cc-d943-4204-87e5-880477d6f7e0@f36g2000hsa.googlegroups.com> Message-ID: On 21 Mai, 15:22, giraffe... at gmail.com wrote: > > I did and I confirmed this by modifying the data, selecting it from > the mysql command line client to verify the changes, then running the > report again. If I exit the application and then start it again, > everything works as expected until the second instance of the report > is run. Note that if you have a connection open in your program, especially if that connection has already been used to select data, it may be the case that you then have to perform a rollback or commit before attempting to access newly added data. The reason for this behaviour is that the DB-API modules will have begun a transaction on your behalf, and while that transaction is open, changes committed in other transactions may be unavailable to your own transaction, depending on the transaction isolation level. MySQL appears to use "repeatable read" by default [1] as its transaction isolation level, whereas PostgreSQL (for example) uses "read committed" by default [2]. I would guess that if you were using PostgreSQL, this particular problem would not have occurred, but there are other reasons to be aware of the effects of long duration transactions in PostgreSQL, and the practice of periodically performing a rollback would still be worth considering with that database system. Paul [1] http://dev.mysql.com/doc/refman/5.1/en/innodb-transaction-isolation.html [2] http://www.postgresql.org/docs/8.1/interactive/transaction-iso.html From wizzardx at gmail.com Tue May 6 09:27:54 2008 From: wizzardx at gmail.com (David) Date: Tue, 6 May 2008 15:27:54 +0200 Subject: How do you debug memory usage? Message-ID: <18c1e6480805060627y32aecc65wf9b4874c7f37590@mail.gmail.com> Hi list. I've tried Googling for this and I checked the Python docs, but to no avail. What is the best way to debug memory usage in a Python script? I'd like to see what objects are using the most memory. Ideally this would be aware of references too. So if I have a small list that contains (references rather) some large variables, then I could see that the global list variable was responsible for X MB that couldn't be collected by the garbage collector. It would be nice if it could be used in a similar way to the 'du' Linux command. eg: eg output: >>> mem_debugger.pretty_print() A (type: list): 8 bytes, 10MB - a (type: string): 6 MB, 0 bytes - b (type: string): 4 MB, 0 bytes B (type: dict): 8 bytes, 5 MB - d (type: string): 3 MB, 0 bytes - c (type: string): 2 MB, 0 bytes In the output above, the 1st size is the memory used by the object itself, and the 2nd size is the memory used by objects it refers to. A & B are global vars (a string and a dict), a,b,c, and d are strings that were added to A & B at some point in the past, and aren't refered to by anything else. Also, the output is in descending order of size. Are there any tools/modules/etc I can use like this? David. From arnodel at googlemail.com Tue May 6 11:37:22 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 06 May 2008 16:37:22 +0100 Subject: STL multimap References: <43029641-3df0-45ac-8e22-9684f7354d80@k37g2000hsf.googlegroups.com> <3d9af15b-8b3d-4fd3-bc81-2a4ed0592a86@l64g2000hse.googlegroups.com> <6ce045cd-d41b-4f63-a7ef-12b2e65d8eac@d77g2000hsb.googlegroups.com> Message-ID: Aaron Watters writes: > I'm having trouble following your discussion > and I suspect you might be a friend of Mark V Cheney. > But I will focus on this one point. > > On May 5, 11:14 pm, castiro... at gmail.com wrote: >> If recursive generators are really useless (erect wall might not be), > > I would like to have recursive generators -- > for example to be able to traverse a tree > and yield the value at every node. Right now > to do this you need to build a chain of generators > from each leaf to the root of the tree (or avoid > recursion by managing your own stack of nodes). > Every yield must "bubble up the tree". There is a patch that allows them: http://bugs.python.org/issue2292 But I don't know how it is implemented (i.e. does the 'bubbling up' behaviour still happen behind the scene?). Else you could use a trampoline, as I've done here: http://www.marooned.org.uk/~arno/python/cogenerator.html (Scroll down to 'Flattening nested cogenerators' and 'recursive cogenerators' - I had fun doing it but it is terribly inefficient). -- Arnaud From ptmcg at austin.rr.com Mon May 19 09:01:19 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 19 May 2008 06:01:19 -0700 (PDT) Subject: "Disabling" raw string to print newlines References: <7f63b5e9-e0d6-4505-9707-b13b70fe61c0@27g2000hsf.googlegroups.com> Message-ID: <2196ab0c-93f4-4dba-807f-32f2a9391826@m36g2000hse.googlegroups.com> On May 19, 4:54?am, kuratk... at kuratkull.com wrote: > Hello, > > *************** > import urllib2 > import re > import string > import sys > > url = "http://www.macgyver.com/" > request = urllib2.Request(url) > opener = urllib2.build_opener() > html = opener.open(request).read() > > match = re.compile("
(.+)
", re.DOTALL) > > out = match.findall(html) > > print out > ************** > > I would like to print out string with formatting, but as I read, the > string is made into a raw string when using re. > How could I disable or bypass this? > > I googled for an hour and couldn't find a solution. > > Thank you in advance. Change your print statement to: print out[0] -- Paul From inhahe at gmail.com Fri May 23 07:14:08 2008 From: inhahe at gmail.com (inhahe) Date: Fri, 23 May 2008 07:14:08 -0400 Subject: Relationship between GUI and logic? References: <48363c34$0$15204$607ed4bc@cv.net> <69n3poF33hfhfU1@mid.uni-berlin.de> Message-ID: > >> To be more specific, let's say I want to create a simple, 2D strategy >> game. It will have a board layout like chess or checkers and the player >> will move around the board. Let's say this is all I know, and perhaps I >> don't even know *this* for sure either. Is it possible to write the >> logic for such a game at this point? > > Maybe even this is possible. But here you are not only drawing the line > between GUI and logic but also within the logic part itself because the > board layout isn't (just) a GUI issue. If you have checkers, hexagons, or > other shapes also has influence on the logic part, because you need > slightly different algorithms for finding ways from tile `A` to tile `B`, > or to decide when a piece is blocked by others, and how the rules to move > pieces around look like. Just imagine how to modify chess rules to a > board with hexagonal patterns. It would severely change the logic part. If the GUI defines that it's a board layout like chess or checkers and the player will move around the board, it's hard to say what's left for the "logic" part to do. I can't think of any generalization for the fact that it's a 2D strategy game. You could have a 2-dimensional array, the size of which is determined by the GUI, but even motion on it would have to be defined by the GUI, in which case the GUI would simply be using the "logic" part for storing the array and accessing it via index values. And then there's no reason not to put the array inside the GUI. Although it would help if only your "logic" part could provide persistence. Also, the "logic" part could provide many useful functions that games are likely to use, but then it's more like a library than anything else. Secondly, it's unclear whether the fact that it's a 2D strategy game was included in what he might not know, and in that possible case, strictly speaking, he didn't define anything that the logic part *does* know, and it being an example, one could theorize that that logically implies the "logic" part of the program is null. > >> Another example could be printing messages to the player. If I need to >> say "You killed the monster!", is there a general way to write this, or >> do I need to specifically refer to GUI widgets and methods, etc. in >> order for it to be displayed properly? > > The observer pattern can be used here. The GUI has to register a callback > function with your logic engine and every time you want to inform the > player about something, your game logic calls that function with the > message. It doesn't have to know if it will be rendered as graphic on > screen, displayed as text in a terminal, or synthesized as sexy female > computer voice. If the function name to register the callback function is hard-coded into the logic part and into the GUI, then so can the name of the callback function itself be, so that it doesn't need to be a callback, barring only the possibility of the callback function being changed from one instance to the next by the particular GUI, and even that can be done without a callback simply by reassigning the name, or in C++ you could cast a pointer to function within the hard-coded function and call it and and change that pointer when desired. Not that I know anything about MVC. From Tymoteusz.Jankowski at gmail.com Sun May 11 02:58:49 2008 From: Tymoteusz.Jankowski at gmail.com (XLiIV) Date: Sat, 10 May 2008 23:58:49 -0700 (PDT) Subject: Is using range() in for loops really Pythonic? References: <482657ca$0$25026$607ed4bc@cv.net> Message-ID: <41078222-aec0-4e8b-8a1f-945cdf814498@m73g2000hsh.googlegroups.com> On May 11, 4:19?am, John Salerno wrote: > I know it's popular and very handy, but I'm curious if there are purists > out there who think that using something like: > > for x in range(10): > ? ? #do something 10 times > > is unPythonic. The reason I ask is because the structure of the for loop > seems to be for iterating through a sequence. It seems somewhat > artificial to use the for loop to do something a certain number of > times, like above. > > Anyone out there refuse to use it this way, or is it just impossible to > avoid? The range() function returns a list and list is a sequence, isn't? From mal at egenix.com Sun May 18 08:31:31 2008 From: mal at egenix.com (M.-A. Lemburg) Date: Sun, 18 May 2008 14:31:31 +0200 Subject: multiple databases, what's the best interface ? In-Reply-To: <482F29DF.2040804@gmail.com> References: <482F29DF.2040804@gmail.com> Message-ID: <483021A3.9060908@egenix.com> On 2008-05-17 20:54, Stef Mientki wrote: > hello, > > I need to switch fluently between 2 or 3 types of dbases: > SQLite, Sybase ( and in the future MS SQL-server). > > I need both closed application and general purpose database manager, > which should run on different platforms (windows, windows mobile, not > web based). > > I would like to write the applications in Python. > What's the best interface so I can use the same program for all databases, > and just have to change the database name, if I want to use another > database ? If you need a common interface on all the platforms, then I'd suggest you have a look at our mxODBC: http://www.egenix.com/products/python/mxODBC/ If you also need to support Windows Mobile, then you'll be interested in our upcoming new product called "mxODBC Connect" which separates the client from the server. mxODBC Connect allows using the mxODBC API on platforms which don't come with ODBC drivers or where getting ODBC drivers is difficult. Due to it's client-server approach it also simplifies configuration a lot. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, May 18 2008) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From mccredie at gmail.com Mon May 5 19:16:15 2008 From: mccredie at gmail.com (Matimus) Date: Mon, 5 May 2008 16:16:15 -0700 (PDT) Subject: config files in python References: <44f9662d-a88d-418c-a11d-b7b472b01fc3@j33g2000pri.googlegroups.com> Message-ID: <87332548-4f15-49c3-8c92-4aa20e355747@n1g2000prb.googlegroups.com> On May 4, 11:35 pm, sandipm wrote: > Hi, > In my application, I have some configurable information which is used > by different processes. currently I have stored configration in a > conf.py file as name=value pairs, and I am importing conf.py file to > use this variable. it works well > > import conf > print conf.SomeVariable > > but if I need to change some configuration parameteres, it would need > me to restart processes. > > I want to store this data in some conf file (txt) and would like to > use it same way as I am using these variables as defined in py > files. > > one solution I can think of is writing data as a dictionary into conf > file. and then by reading data, apply eval on that data. and update > local dict? but this is not a good solution.... > > any pointers? > > Sandip I would load the configuration file using `imp.load_source'. This allows you to load the config file by filename, and gets away from the issue of accidentally importing a file somewhere else in pythons search path. Also, calling imp.load_source will reload the module when called a second time. http://docs.python.org/lib/module-imp.html [conf.py] a = 1 b = 2 class c: a = "hello" b = "world" [/end conf.py] >>> conf = imp.load_source("conf", "./conf.py") >>> conf.a 1 >>> conf.b 2 >>> conf.c.a 'hello' >>> conf.c.b 'world' There are so many ways potential solutions to your problem that, without any more details, it is hard to suggest anything. Here are some potential solutions: ConfigParser - module for handling ini files xml - several built-in modules for handling XML files sqlite3 - a `lite' SQL database built-in in python 2.5 + (can be used for config data) windows registry - _winreg module pickle - serialize python objects marshal - similar to pickle, only works for simple objects Those are just the built-in solutions. If you wanna look at 3rd party solutions, prepare for overload. The number of alternative INI parsers alone is staggering. Also, there are many ways to organize your data and use a solution similar to what you are already using. I guess what I'm trying to say is... don't roll your own, it would be a waste of time, this problem has been solved 100s of times. That is, unless you want to do it for fun. Matt From iapain at gmail.com Fri May 30 03:13:37 2008 From: iapain at gmail.com (iapain) Date: Fri, 30 May 2008 00:13:37 -0700 (PDT) Subject: make a string a list References: Message-ID: <20638c80-c869-4fc0-b60d-34aa5c93daa9@m45g2000hsb.googlegroups.com> On May 29, 11:30 pm, Nikhil wrote: > or a string iterable ? How can I do that. I have lots of '\r\n' > characters in the string which I think can be easier if it were made > into a list and I can easily see if the required value (its a numeral) > is present in it or not after some position or after some characters' > position. > > Thanks, > Nikhil If you just want to check required value then you can even use Sets or build your own hash table. From pavlovevidence at gmail.com Fri May 23 04:31:10 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 23 May 2008 01:31:10 -0700 (PDT) Subject: Python is slow References: <4836772e$0$6097$426a74cc@news.free.fr> Message-ID: <16cb4d63-1b40-4ab8-8ba7-120ece4f4d75@y38g2000hsy.googlegroups.com> On May 23, 3:50 am, Bruno Desthuilliers wrote: > Brad a ?crit : > > > cm_gui wrote: > >> Python is slow. > > > It ain't C++, but it ain't a punch card either... somewhere in between. > > I find it suitable for lots of stuff. I use C++ when performance really > > matters tho... right tool for the job. Learn a good interpreted language > > (Pyhton) and a good compiled language (C or C++) > > LordHaveMercy(tm). Could you guys please learn what you're talking about? > > 1/ being interpreted or compiled (for whatever definition of these > terms) is not a property of a language, but a property of an > implementation of a language. > > 2/ actually, all known Python implementations compile to byte-code. > > > and you'll be just > > fine. Until then, quit bitching. You know, even though you're technically correct, I'd like to see you abandon this little crusade. At this point it's more noisy than helpful. Like it or not, to most of the world, "interpreted" vs. "compiled" is a vague pragmatic distinction between fast machine-coded languages and not-so-fast non-machine-coded languages. And like it or not, the world rarely cares to make the distinction between language and implementation, and frankly, it's usually not necessary to. What Brad said is perfectly acceptable, and good advice IMHO, under the common usage of the terms. I really don't see much reason to call someone out on it unless they're being deliberately misleading. Carl Banks From gagsl-py2 at yahoo.com.ar Thu May 15 19:18:11 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 15 May 2008 20:18:11 -0300 Subject: basic comparing files References: Message-ID: En Thu, 15 May 2008 06:02:29 -0300, Beema shafreen escribi?: > I am comparing two files A and B > which has three columns a1, b1 of A and a2, b2 *three* columns? You menction only two of them. > say for example if need to compare a1 with a2 and if there are common i > have > display a1, b1, b2 > or else i have to display a1 , b1 or a1, b2 Do you have to syncrhonize both listings? That is, search for matches that are not in the same line? Or just compare line by line? In the first case, the difflib module may help: http://docs.python.org/lib/module-difflib.html In the second case, just iterate over both files, compare lines and display one thing or another. > is the set function going to be the best option or is there any other way Probably the set type won't be useful - a concrete example of what you want would help to provide better ideas. -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Tue May 13 02:56:10 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 13 May 2008 03:56:10 -0300 Subject: Inconsistency in retrieving exceptions via sys module References: <482874B1.4010504@rice.edu> Message-ID: En Mon, 12 May 2008 13:47:45 -0300, Raj Bandyopadhyay escribi?: > I am writing some C code which sets and retrieves a Python exception. I > set the exception using PyErr_SetString(), and retrieve it in 2 ways: 1) > using PyErr_Occurred() and 2) Using sys.exc_type. However, I get two > different results and am very puzzled by this apparent inconsistency. > Could anyone please clarify what I'm missing? I need both to work > consistently for my application. The sys.exc_* variables are just for backwards compatibility, don't use them; use sys.exc_info() in Python code and PyErr_Occurred (and the other PyErr... functions) in C. (Note that even PyErr_Occurred is not so common in C code, as most functions have some way to say "there was an error"; by example, functions that return a PyObject* mark an error returning NULL). The sys.exc_* variables are set only at the end of each Python bytecode instruction (see ceval.c) -- Gabriel Genellina From nc at iname.com Sun May 25 16:28:25 2008 From: nc at iname.com (NC) Date: Sun, 25 May 2008 13:28:25 -0700 (PDT) Subject: php vs python References: <5l%Yj.77$mz3.53@fe101.usenetserver.com> <37b112d8-a3ba-446d-9d2f-d907d93c637b@w8g2000prd.googlegroups.com> <-t-dnWQ4bZN2MaTVnZ2dnUVZ_qGdnZ2d@comcast.com> <68cb8bb1-4cc5-4a28-8915-46e7d4e316d9@d1g2000hsg.googlegroups.com> Message-ID: On May 25, 11:46 am, Ivan Illarionov wrote: > > If the OP wants to learn the guts of the blog or to implement > the blog from scratch, Python/Django would be a better choice > than PHP. The reason is that he can reuse and customize existing > high quality components for all these auth/auth, admin, comments, > etc, etc, etc. You are comparing apples to oranges... There are application frameworks for PHP as well (CakePHP and Symfony come to mind). CakePHP, if memory serves, actually has a development of a blog described in its tutorial... > Another reason is that Python and Django encourage very clean design > while PHP is too often ends up in "spaghetti SQL wrapped in spaghetti > PHP wrapped in spaghetti HTML". It's absolutely the same thing with PHP frameworks... > 2 man/year in PHP == 2 man/week in Python/Django. This, I daresay, is an exaggeration... Let's take your own example: > And there are Python/Django blog applications that already do almost > everything (and maybe more) that WordPress does.http://byteflow.su/ > is one of them (IMHO the most promising). A quick look at the revision log: http://byteflow.su/log/ reveals that the initial commit of 60 or so files has been done on 08/14/07 (10 months ago), a second developer came on board 12/01/07 (seven+ months ago), a third one, on 01/04/08 (six+ months ago), a fourth one, on 01/16/08 (also six+ months ago). There are at least nine discernible contributors overall. Say what you will, but it still looks an awful lot like like two man- years, Django or no Django... Cheers, NC From bignose+hates-spam at benfinney.id.au Fri May 16 04:57:43 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 16 May 2008 18:57:43 +1000 Subject: Instance of class "object" References: Message-ID: <87fxsitym0.fsf@benfinney.id.au> "??" writes: > Howdy, > I wonder why below does not work. > > a = object() > a.b = 1 # dynamic bind attribute failed... > > To make it correct, we have to create a new class: > class MyClass(object): pass > a = MyClass() > a.b = 1 # OK It's annoyingly difficult to search for information on this; "python class object type inherit bind attribute" aren't sufficiently distinguishing to know that we're talking about the built-in 'object' type, and inheriting from it. I'm interested to know the answer to your question; thanks for asking it. -- \ "Don't be afraid of missing opportunities. Behind every failure | `\ is an opportunity somebody wishes they had missed." -- Jane | _o__) Wagner, via Lily Tomlin | Ben Finney From danikar at gmail.com Sun May 4 06:01:37 2008 From: danikar at gmail.com (danikar at gmail.com) Date: Sun, 4 May 2008 03:01:37 -0700 (PDT) Subject: Open a file within an ISO in python. Message-ID: <8137a75f-f70d-4851-a5f1-3794a5bfad32@w8g2000prd.googlegroups.com> Is there a way to open a file that is inside of an ISO in python? Say I have an ISO file, danikars.iso and on the iso there is a file called information.txt I want to be able to do something like this. [code] iso_h = openiso("danikars.iso") file_h = iso_h.extract("information.txt") contents = file_h.read() [/code] Is there anything that will give me that functionality? Or close? Thanks, Danikar From frikker at gmail.com Mon May 19 16:02:24 2008 From: frikker at gmail.com (blaine) Date: Mon, 19 May 2008 13:02:24 -0700 (PDT) Subject: MDP: A Simple Feed Forward Network Message-ID: <6e5511c0-efad-47f5-a5e2-417e9c709bf1@26g2000hsk.googlegroups.com> Hey everyone, I was hoping to see some people out on the python list that are familiar with MDP (Modular Toolkit for Data Processing - http://mdp-toolkit.sourceforge.net/)? I am wanting to develop a very simple feed forward network. This network would consist of a few input neurons, some hidden neurons, and a few output neurons. There is no learning involved. This network is being used as a gene selection network in a genetic simulator where we are evolving the weights and connectivity. There are many different types of nodes listed as being supported, but i can't figure out the best one to use for this case. In this situation, we only want to iterate through the network X times. (In the simples version, with no cycles, this would mean that once the output nodes are calculated there would be no additional calculations since the system would be stable and non-learning). Node types are listed at the bottom here: http://mdp-toolkit.sourceforge.net/tutorial.html#quick-start In the more complex version, we would have the same model but instead of having straight connectivity all the way through, we would add a few cycles in the hidden layer so that a few neurons would feed back into themselves on the next time step. This could also be connected to a 'selector' layer, that feeds back on the hidden layer as well. Since we are only running this a finite number of times, the system would not spiral out into instability. Any suggestions for which node types to use, or possibly what other libraries would be helpful? I realize that due to the relative simplicity of this network I could hand code this from scratch. MDP just looks extremely handy and efficient and I'd like to use it if possible. Simple Network: (H is interconnected fully with the Input and Output layer) I -> H -> O I -> H -> O I -> H -> O Cycled Network (Trying to show that the first hidden neuron is connected back to itself) v---| I -> H -> O I -> H -> O I -> H -> O Complex Network (Trying to show that the first hidden neuron is connected to another hidden neuron S that connects back to the input of H. S would be interconnected with the other hidden neurons as well) v--- S <--| I -> H -> O I -> H -> O I -> H -> O Thanks! -Blaine From http Mon May 19 19:07:06 2008 From: http (Paul Rubin) Date: 19 May 2008 16:07:06 -0700 Subject: Thread killing - I know I know! References: <6fda9c2c-84fe-4339-8ce2-25b6d6b97ba4@t54g2000hsg.googlegroups.com> <8ac3f740-1c21-49c8-85e7-023ebe03d880@x41g2000hsb.googlegroups.com> Message-ID: <7xtzgtyjtx.fsf@ruckus.brouhaha.com> blaine writes: > How is it that you recommend killing a pure python thread? And also, > when i use the 'threading' module am I creating a process, or a (gasp) > thread? A thread. > (Is this an obvious question - and if so, how does one create > a 'process'?) os.fork() From alokkat at gmail.com Thu May 29 00:00:21 2008 From: alokkat at gmail.com (Alok Kumar) Date: Thu, 29 May 2008 00:00:21 -0400 Subject: Struct usages in Python In-Reply-To: References: <1211985562.3335.18.camel@aalcdl07.lib.unc.edu> Message-ID: Thanks to everyone for your help. I am able to use array of structure (here Event is a class) in the following manner. But here I am fixing the array index as 4. Is there any easy way to keep it appending dynamically. self.event = [Event() for x in range(4)] # Event is a class as posted in original message. I have one set of structures and want to process them, subsequently couple of them will not be able to pass the criteria and all passed ones I wanted to put in another list where I can dynamically append the structure. So that I can post this list to server. Thanks in advance. Regards Alok On Wed, May 28, 2008 at 1:53 PM, Arnaud Delobelle wrote: > Arnaud Delobelle writes: > > > "Alex Gusarov" writes: > > > >>> class Event(object): > >>> > >>> Always subclass object, unless you have a very compelling reason not > to, > >>> or you are subclassing something else. > >>> > >> > >> I've thought that if I write > >> > >> class Event: > >> pass > >> > >> , it'll be subclass of object too, I was wrong? > > > > You are wrong for Python 2.X, but right for Python 3 where old-style > > classes are gone for good. > > > > What you define with the statement > > > > class Event: pass > > > > is an 'old-style' class. Witness: > > > > >>> class Event: pass > > ... > > >>> class NewEvent(object): pass > > ... > > >>> type(Event) > > > > >>> type(NewEvent) > > > > >>> type(Event()) > > > > del>>> type(NewEvent()) > > > > > > All old-style classes are actually objects of type 'classobj' (they > > all have the same type!), all their instances are all of type 'instance'. > > Oops somthing disappeared in the copy/paste process: > > >>> class FooBar: pass > ... > > > >>> type(FooBar) == type(Event) > > True > > >>> type(FooBar()) == type(Event()) > > True > > > > Whereas instances of new-style classes are of type their class: > > > > >>> class NewFooBar(object): pass > > ... > > >>> type(NewFooBar) == type(NewEvent) > > True > > >>> type(NewFooBar()) == type(NewEvent()) > > False > > > > However, in python 2.X (X > 2?), you can force all classes to of a > > certain type by setting the global variable '__metaclass__'. So: > > > > >>> type(Event) # Event is an old-style class > > > > >>> __metaclass__ = type > > >>> class Event: pass > > ... > > >>> type(Event) # Now Event is new-style! > > > > > > HTH > > > > -- > > Arnaud > -- > http://mail.python.org/mailman/listinfo/python-list > -- Regards Alok Kumar -------------- next part -------------- An HTML attachment was scrubbed... URL: From cokofreedom at gmail.com Wed May 21 09:43:59 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Wed, 21 May 2008 06:43:59 -0700 (PDT) Subject: C-like assignment expression? References: <68b5d090-9e3b-4e7d-9dda-fc1b099822c2@m73g2000hsh.googlegroups.com> <48340412$0$10773$426a74cc@news.free.fr> <87fxsbzxn4.fsf@mulj.homelinux.net> <7df99fd4-21c9-49a1-ba65-e55794fd4c12@26g2000hsk.googlegroups.com> <75ca6227-435c-46bf-8701-aa326d3533e0@p25g2000hsf.googlegroups.com> <69in0tF33sdj6U2@mid.uni-berlin.de> Message-ID: <07561bbe-0084-467d-b408-a53cfdc8b832@26g2000hsk.googlegroups.com> > > And wastes time. regular expressions can become expensive to match - doing > it twice might be hurtful. > > Diez match = (my_re1.match(line) or my_re2.match(line)) or my_re3.match(line) ? From malaclypse2 at gmail.com Thu May 22 13:12:30 2008 From: malaclypse2 at gmail.com (Jerry Hill) Date: Thu, 22 May 2008 13:12:30 -0400 Subject: Why is math.pi slightly wrong? In-Reply-To: References: Message-ID: <16651e80805221012k70ade323qb020f9765e2f4a3@mail.gmail.com> On Thu, May 22, 2008 at 12:32 PM, Dutton, Sam wrote: > I've noticed that the value of math.pi -- just entering it at the interactive prompt -- is returned as 3.1415926535897931, whereas (as every pi-obsessive knows) the value is 3.1415926535897932... (Note the 2 at the end.) > > Is this a precision issue, or from the underlying C, or something else? How is math.pi calculated? I believe this is an issue with the precision of IEEE floating point numbers[1]. Those are the types of numbers used by the hardware floating point processor on your CPU. I'm not an expert, by any stretch of the imagination, but I believe you have two choices to represent pi as an IEEE double precision float: 3.1415926535897931 (stored as 0x400921FB54442D18) or 3.1415926535897936 (stored as 0x400921FB54442D19) 1: http://en.wikipedia.org/wiki/IEEE_floating-point_standard -- Jerry From fuzzyman at gmail.com Sun May 25 10:40:24 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Sun, 25 May 2008 07:40:24 -0700 (PDT) Subject: unittest: Calling tests in liner number order References: <84ff733a-e364-437d-9b5d-d8bb14cc692d@m73g2000hsh.googlegroups.com> <3300da64-ff6b-4c00-9bb4-339d44c9b204@f36g2000hsa.googlegroups.com> Message-ID: <8b1335c3-74d1-4ef5-b9c2-28d52837bf76@a70g2000hsh.googlegroups.com> On May 25, 3:13?pm, Roy Smith wrote: > In article > , > ?John Roth wrote: > > > I really don't care what the OP does in his own projects. My objection > > is that, if it goes into the standard library, is that it passes a > > signal that it's good practice to allow dependencies between tests. It > > most definitely is _not_ good practice. > > The OP stated that he wants the tests run in a given order. ?People are > assuming that's because he has dependencies between his tests. ?Maybe he > just wants them run in order because it's easier to understand the output > in a certain order. No, we're pointing out that running tests in a specific order can introduce hidden dependencies without you being aware of it. Whilst this is already the case with unittest, further enshrining it in the standard library is a bad idea. As mentioned elsewhere, providing a better reporting mechanism is probably the way to get better understandable output. Micahel Foord http://www.ironpythoninaction.com/ > > For example, I'm currently working on some low-level data marshalling code > (in another language). ?This is the sort of stuff which the Python struct > module handles -- converting between internal form and network > representation. ? > > There is a logical hierarchy of complexity. ?Handling characters is easier > than handling ints, which is easier than floats, which is easier than > doubles, and so on (arrays, sets and other composite types). ?If I was > porting this to a new platform, I would want the unit tests to run in a > logical order of simple to complex. ?If some assortment of tests failed, > you want to start debugging the problem on the least complex data types. ? > If the tests run in a specific order, it's easier to see where to start. > > It's not that any test depends on any other test to run, in the sense that > there's some shared state between them. ?It's just that from a human > factors point of view, there's a logical order to run them in. > > In fact, from a protocol point of view, some of the types really do depend > on each other. ?We send counted strings, for example, so we can't send a > string until we know how to send an int (for the string length). ?If the > first test that fails is the string test, I know right off that the problem > is not in how we send ints, because that test ran already and it passed. > > Earlier, I gave another example of wanting tests to be run in the same > order as some externally controlled set of functional requirements. ?Again, > not because the tests have inter-dependencies, but because it just makes it > easier to interpret the results. > > Don't assume inter-test dependencies (which I agree are a Bad Thing) is the > only reason you want to run tests in a specific order. From castironpi at gmail.com Thu May 15 07:50:20 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 15 May 2008 04:50:20 -0700 (PDT) Subject: Greetings Message-ID: <31e4b80a-4694-4d6e-bf04-a2031cf9472c@m3g2000hsc.googlegroups.com> Hail, Earthlings, I have an easy request to take over the newsgroup ("Taking Over the Newsgroup", "TOTN"). May I? Pros: Lifetime benefits Google product Talking Cons: World domination No crossing Social aspect* Read the fine print: *Social: Subscribers to TOTN may come talking, telling jokes, and laughing loudly. Neighbors subject to smiling. Vikings prone to capitalize. Settings include autovoltic, board, and charm. Dimensions include 4. Restrictions apply. States may vary. Void where prohibited. People include the living. Times include eternity. Toys include Legos. Assume screen is two-dimensions and audio stereo; what are building Legos? Assume digital. From sjmachin at lexicon.net Thu May 22 18:37:23 2008 From: sjmachin at lexicon.net (John Machin) Date: Thu, 22 May 2008 15:37:23 -0700 (PDT) Subject: where is the Write method of ElementTree?? References: <1e111b83-ad85-4e3e-baed-0ddee1255faa@d77g2000hsb.googlegroups.com> Message-ID: <0c26ec10-3492-4ce1-8b5a-ebfb747a9a8e@p39g2000prm.googlegroups.com> On May 23, 6:56 am, gray.bow... at gmail.com wrote: > I'm messing around with trying to write an xml file using > xml.etree.ElementTree. All the examples on the internet show the use > of ElementTree.write(), although when I try to use it it's not > available, gives me ... > > ElementTree(sectionElement).write("section.xml") > TypeError: 'module' object is not callable > > I'm new to python, so I think I'm doing something wrong.. any > thoughts? > > Thanks.' > > See code below: > > # Create xml structure > sectionElement = ElementTree.Element("section") > > # step through feed result and create elements for each article - > result[article] > for article in feedResult: > articleElement = ElementTree.Element("article") > > titleElement = ElementTree.SubElement(articleElement, "title") > titleElement.text = article['title'] > > bodyElement = ElementTree.SubElement(articleElement, "body") > bodyElement.text = article['body'] > > sectionElement.append(articleElement) > > #print ElementTree.tostring(sectionElement) > ElementTree(sectionElement).write("section.xml") It's complaining about ElementTree(whatever) As it says, you are trying to call a module. Looks like you need: sectionElement.write("section.xml") HTH, John From johnroth1 at gmail.com Mon May 26 14:57:13 2008 From: johnroth1 at gmail.com (John Roth) Date: Mon, 26 May 2008 11:57:13 -0700 (PDT) Subject: unittest: Calling tests in liner number order References: <84ff733a-e364-437d-9b5d-d8bb14cc692d@m73g2000hsh.googlegroups.com> <3300da64-ff6b-4c00-9bb4-339d44c9b204@f36g2000hsa.googlegroups.com> Message-ID: On May 25, 8:13 am, Roy Smith wrote: > In article > , > John Roth wrote: > > > > > Don't assume inter-test dependencies (which I agree are a Bad Thing) is the > only reason you want to run tests in a specific order. I'm not. As Michael Fnord and Diez Roggisch says in other responses, there are other solutions to those problems. It would be better to pursue them if you want a change to the standard library. John Roth From fivetwentysix at gmail.com Sat May 31 00:55:38 2008 From: fivetwentysix at gmail.com (fivetwentysix at gmail.com) Date: Fri, 30 May 2008 21:55:38 -0700 (PDT) Subject: compatability References: <62e2b0c6-dc81-494a-b2bd-c6455049ff77@d1g2000hsg.googlegroups.com> Message-ID: <793cc354-0251-4ea3-9ed9-5d873568e434@s33g2000pri.googlegroups.com> On May 30, 8:32?pm, budcrandall at hotmail.com wrote: > I'm currently using 3ds Max Design 2009 and Maya. Will Python and > Plone be compatible with my systems? I would really like to > incorporate this software. Thank You Bud ? budcrandall at hotmail.com. Please be more specific as to what type of system... Python is supported on almost all platforms: Unix, Mac, Windows, etc. Try visiting http://www.python.org/ From gandalf at shopzeus.com Fri May 2 05:43:10 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Fri, 02 May 2008 11:43:10 +0200 Subject: no cleanup on TERM signal In-Reply-To: References: Message-ID: <481AE22E.3040906@shopzeus.com> Yves Dorfsman wrote: > I did a few tests with this script: > > class byebye: > > def __del__(self): > print 'Bye, bye...' > > > x = byebye() > > > x.del() gets executed if: > -I del x, then run gc.collect() > -simply exit the script > -get the script to abort on an exception > > But if I kill it with the default signal TERM, the script dies, but I > don't get the message, so I am assuming that python isn't taking the > time to cleanup, even though that is (was) what TERM was intended for. TERM signal is unix specific. There is no special syntax/programming structure for signals inside the Python language, since it would be platform dependent. For simple client programs, usually it is not needed to setup signal handlers because they can easily be controlled in other ways. For sensitive resources, instead of writing __del__ methods, you should create a "close()" method. Python does this with file objects, DB API 2.0 with database connection objects etc. Then you can do res = create_resource() try: use_resource() finally: res.close() # Must free resource, but the object can still be alive... It is more common to use signals when you have more threads or child processes. You can use something like: import threading import signal stop_requested = threading.Event() exited_on_sigterm = False def free_all_resources(): pass # Free your resources here! def sigterm_handler(signum, frame): """Stop the server gracefully when on SIGTERM.""" global stop_requested global exited_on_sigterm exited_on_sigterm = True stop_requested.set() free_all_resources() def main(): global stop_requested global exited_on_sigterm logger = servicelog.getLogger('main',filename=LOGFILENAME) logger.info('Setting up the SIGTERM signal handler.') signal.signal(signal.SIGTERM, sigterm_handler) # Setup signal handler logger.info('Starting watchdog thread') watchdog = WatchDog() watchdog.start() worker1 = create_worker(stop_requested) worker2 = create_worker(stop_requested) # etc. Prepare things here... try: try: server = create_my_server() server.serve_until_not_stopped() except Exception, e: logger.error(dumpexc(e)) raise e finally: stop_requested.set() # Ask other threads to stop cooperatively # Join all threads here watchdog.join() worker1.join() worder2.join() # etc. wait for all threads to exit cooperatively. if exited_on_sigterm: logger.warning('Exited on SIGTERM!') Best, Laszlo From ivan.illarionov at gmail.com Fri May 16 22:46:11 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Sat, 17 May 2008 02:46:11 +0000 (UTC) Subject: writing python extensions in assembly References: Message-ID: On Fri, 16 May 2008 10:13:04 -0400, inhahe wrote: > Can anyone give me pointers/instructions/a template for writing a Python > extension in assembly (or better, HLA)? Look up pygame sources. They have some hot inline MMX stuff. I experimented with this rescently and I must admit that it's etremely hard to beat C compiler. My first asm code actually was slower than C, only after reading Intel docs, figuring out what makes 'movq' and 'movntq' different I was able to write something that was several times faster than C. D language inline asm and tools to make Python extensions look very promising although I haven't tried them yet. -- Ivan From arnodel at googlemail.com Fri May 30 09:36:06 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Fri, 30 May 2008 14:36:06 +0100 Subject: should I put old or new style classes in my book? References: Message-ID: "Eduardo O. Padoan" writes: > On Thu, May 29, 2008 at 3:06 PM, Jason wrote: >> I've got Python 3.0 alpha 2. In this version, it looks like you can >> define classes in either the old style or new style. (I snipped the >> top line a bit in the following example): > > Wrong. Py3k Classes are always new-style. They subclass object > implicitly when no superclass is given. I think he was talking about syntax, not object types. -- Arnaud From robert.kern at gmail.com Tue May 6 18:27:26 2008 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 06 May 2008 17:27:26 -0500 Subject: DISLIN Manual In-Reply-To: <61d60fe6-271a-4f33-b1a7-a2059a08c810@j22g2000hsf.googlegroups.com> References: <61d60fe6-271a-4f33-b1a7-a2059a08c810@j22g2000hsf.googlegroups.com> Message-ID: adolfo wrote: > I am at the very beginning of the DISLIN 9.3 Manual: 1.4 Quickplots I recommend asking the DISLIN author. I don't think that DISLIN is widely used in Python. > Some quickplots are added to the DISLIN module which are collections > of DISLIN routines for displaying data with one command. For example, > the function ?plot? displays two-dimensional curves. Example: > from Numeric import * > from dislin import * > x = arange (100, typecode=Float32) > plot (x, sin (x/5)) > disfin () > > Problems: > > 1. "from Numeric import * " statement produced an error message, I > had to replace it with "from numpy import *" If DISLIN still uses Numeric rather than numpy, you will probably need to use Numeric, too. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From castironpi at gmail.com Wed May 14 15:45:06 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 14 May 2008 12:45:06 -0700 (PDT) Subject: named tuple mutability References: Message-ID: <4fd64aae-d74b-412e-8acc-eee822ba8a47@t54g2000hsg.googlegroups.com> On May 14, 1:04?pm, castiro... at gmail.com wrote: > On May 14, 12:41?pm, Raymond Hettinger wrote: > > > >?Should tuples be named? > > > Yes. > > Not clearly should. ?Sequences ought be. ?If you're on the right time > for both, can't the library hold the B? On the web, you can. Both data types can go in the docs... sorry for the lunacy, I'm hacking. From castironpi at gmail.com Tue May 13 09:29:52 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 13 May 2008 06:29:52 -0700 (PDT) Subject: threads problem in python References: <48296275.9090602@al.com.au> Message-ID: On May 13, 5:38?am, "Gabriel Genellina" wrote: > En Tue, 13 May 2008 06:42:13 -0300, Astan Chee escribi?: > > > I have 2 classes in python, the first one runs first and and then the ? > > first one calls the second class. I want it to run the second class as a ? > > separate thread but I want the first one to wait until the second class ? > > is dead. > > Im having problem in both killing the second class when its done and ? > > making the first class wait for it to finish. > > Im very confused on doing threads in python. > > I'm confused trying to understand your requirements too. "run a class?" > Threads execute code, it's easier to think of them as *functions* that are ? > executed at the same time (or almost). > So you have a function A that runs first, and creates a second thread that ? > will execute function B. Then A will wait for B to finish. What do you ? > want to do in A while it's waiting? Nothing? Then why to use a second ? > thread? Or is it a graphical interfase? GUI libraries like wxPython, Qt ? > and others have specific ways to execute backgroung tasks while keeping ? > the user interface responsive - you should tell us which one you're using ? > in that case. > > -- > Gabriel Genellina I don't mean to be impertinent, but are you making any cents with the assignment? Both free-ers and workers come in here. I am a free-er who has reason to doubt that money-driven programs get stuck at that kind of ambiguity. I hold that money keeps you out of that mess. However, there are a number of things we can do to help, but as I, per se, am only one person, I may not give you the best advice to start with. How do you find the 'threading.py' docs? From bj_666 at gmx.net Tue May 20 02:41:59 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 20 May 2008 06:41:59 GMT Subject: test mult vars to same value, how to shorten expr? References: Message-ID: <69fa5nF2uih6aU2@mid.uni-berlin.de> On Mon, 19 May 2008 20:36:45 -0700, notnorwegian wrote: > if i want o test: > if a == 5 and b ==5 and c==5 ... z==5 > > is there some synctactic suagr for this? > > rather than maiking one of my own i mean, something built-in like: > if a,b,c... z == 5: Since Python 2.5 there's `all()`: In [81]: a, b, c, d = 5, 5, 5, 6 In [82]: all(x == 5 for x in (a, b, c)) Out[82]: True In [83]: all(x == 5 for x in (a, b, c, d)) Out[83]: False Ciao, Marc 'BlackJack' Rintsch From fc14301589 at icqmail.com Thu May 22 11:23:54 2008 From: fc14301589 at icqmail.com (TheSaint) Date: Thu, 22 May 2008 23:23:54 +0800 Subject: Publish a program References: <4833f0ff_2@news.tm.net.my> <48342434_2@news.tm.net.my> Message-ID: <48359018_2@news.tm.net.my> On 22:32, mercoled? 21 maggio 2008 python at bdurham.com wrote: >> appreciate somebody to join and put new views on this project > > Send us a link to one of the sites with your code, eg. > http://python.pastebin.com Thank you! Go to : http://it.geocities.com/call_me_not_now/index.html From bronger at physik.rwth-aachen.de Thu May 22 17:39:52 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Thu, 22 May 2008 23:39:52 +0200 Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <8Ot*rIxds@news.chiark.greenend.org.uk> Message-ID: <87abii2f2v.fsf@physik.rwth-aachen.de> Hall?chen! Matthew Woodcraft writes: > [...] > > At one time, Guido was very keen on the idea of Python as a > language to introduce non-programmers to (under the 'Computer > Programming for Everybody' slogan). > > I think it's rather a shame that this has more-or-less fallen by > the wayside. There are lots of people out there producing buggy > spreadsheets to do things that would be easier to do in a > programming language. I don't think so. It's still reasonably simple to write short Python programs for e.g. the analysis of measurement results. But people simply don't trust cheap non-point'n'click programs which don't occupy two shelves in the bookstore. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From maciej.blizinski at gmail.com Tue May 6 04:01:28 2008 From: maciej.blizinski at gmail.com (=?ISO-8859-2?Q?Maciej_Blizi=F1ski?=) Date: Tue, 6 May 2008 01:01:28 -0700 (PDT) Subject: Python MIDI in 2008 Message-ID: <1076a133-4376-4b96-a06b-4bb990ec3f42@f63g2000hsf.googlegroups.com> For the last couple of days, I've been looking for a Python midi library. I'm generally interested in sending MIDI events via ALSA. It seems like everything out there is pretty old; packages are from 2003 or 2005. Some packages don't seem to be really used, for instance portmidi doesn't even support installing it system-wide; you can compile it and... no make install for you. What I've found so far: - http://wiki.python.org/moin/PythonInMusic mostly point to non- existing or very old software packages - http://www.mxm.dk/products/public/pythonmidi/ -- no realtime support Promising packages: - http://trac2.assembla.com/pkaudio/browser/pyrtmidi -- something realtime, but I couldn't get the actual Subversion repository address - http://alumni.media.mit.edu/~harrison/code.html -- seems promising, but I haven't got it running. You can't (system-wide) install portmidi, and pyportmidi seems to want portmidi installed. Is there any other package that allows sending MIDI events in real time? Did anyone recently got any of the above packages to work? Maciej From arnodel at googlemail.com Mon May 12 04:35:32 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 12 May 2008 01:35:32 -0700 (PDT) Subject: do you fail at FizzBuzz? simple prog test References: <39709320-66e1-40e9-a351-c769c9a94585@x41g2000hsb.googlegroups.com> <482650a5$1@news.mel.dft.com.au> <65d792a8-4469-404c-8287-1357170eea05@x35g2000hsb.googlegroups.com> Message-ID: <08b7a27f-0e00-45cb-9c6c-e58cb7cac7d7@k37g2000hsf.googlegroups.com> On May 12, 9:30?am, Arnaud Delobelle wrote: [...] > # FizzBuzzer in action: > > >>> fizzbuzz = FizzBuzzer((3, 'Fizz'), (5, 'Buzz')) > >>> for val in fizzbuzz[1:21]: > > ... ? ? print val > ... > 1 21 1 ^^^^^^^^ Ignore this, it's debugging output > 1 > 2 > Fizz > 4 > Buzz > Fizz > 7 > 8 > Fizz > Buzz > 11 > Fizz > 13 > 14 > FizzBuzz > 16 > 17 > Fizz > 19 > Buzz>>> abc = FizzBuzzer((2, 'Ah'), (3, 'Bee'), (5, 'Cee')) > >>> list(abc[25:35]) > > 25 35 1 ^^^^^^^^^ Same > ['Cee', 'Ah', 'Bee', 'Ah', 29, 'AhBeeCee', 31, 'Ah', 'Bee', 'Ah'] -- Arnaud From gneuner2/ at /comcast.net Sat May 10 21:01:21 2008 From: gneuner2/ at /comcast.net (George Neuner) Date: Sat, 10 May 2008 21:01:21 -0400 Subject: The Importance of Terminology's Quality References: Message-ID: <3jgc2498f1te1uqh7rrf3odhevkrt3s75e@4ax.com> On Fri, 09 May 2008 22:45:26 -0500, rpw3 at rpw3.org (Rob Warnock) wrote: >George Neuner wrote: > >>On Wed, 7 May 2008 16:13:36 -0700 (PDT), "xahlee at gmail.com" >> wrote: > >>>? Functions [in Mathematica] that takes elements out of list >>>are variously named First, Rest, Last, Extract, Part, Take, >>>Select, Cases, DeleteCases... as opposed to ?car?, ?cdr?, >>>?filter?, ?filter?, ?pop?, ?shift?, ?unshift?, in lisps and >>>perl and other langs. > >>| Common Lisp doesn't have "filter". > >Of course it does! It just spells it REMOVE-IF-NOT!! ;-} ;-} I know. You snipped the text I replied to. Xah carelessly conflated functions snatched from various languages in an attempt to make some point about intuitive naming. If he objects to naming a function "filter", you can just imagine what he'd have to say about remove-if[-not]. George -- for email reply remove "/" from address From cokofreedom at gmail.com Wed May 14 03:24:39 2008 From: cokofreedom at gmail.com (cokofreedom at gmail.com) Date: Wed, 14 May 2008 00:24:39 -0700 (PDT) Subject: Is using range() in for loops really Pythonic? References: <482657ca$0$25026$607ed4bc@cv.net> <4829cac1$0$34550$742ec2ed@news.sonic.net> <68vfm3F2v0piaU2@mid.uni-berlin.de> Message-ID: On May 14, 8:37 am, Marc 'BlackJack' Rintsch wrote: > On Tue, 13 May 2008 10:20:41 -0700, John Nagle wrote: > > Matt Nordhoff wrote: > > >> Well, you should use "xrange(10)" instead of "range(10)". > > > CPython really is naive. That sort of thing should be a > > compile-time optimization. > > It's not naive, it can't know at compile time what object is bound to the > name `xrange` at runtime. > > Ciao, > Marc 'BlackJack' Rintsch I think he meant you should just use xrange over range at all times. From larry.bates at websafe.com` Wed May 21 21:48:44 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Wed, 21 May 2008 20:48:44 -0500 Subject: php vs python In-Reply-To: <5l%Yj.77$mz3.53@fe101.usenetserver.com> References: <5l%Yj.77$mz3.53@fe101.usenetserver.com> Message-ID: notbob wrote: > I'm not posting this just to initiate some religious flame war, though it's > the perfect subject to do so. No, I actaully want some serious advice about > these two languages and since I think usenet is the best arena to find it, > here ya' go. > > So, here's my delimna: I want to start a blog. Yeah, who doesn't. Yet, I > want learn the guts of it instead of just booting up some wordwank or > whatever. I started to learn python, but heard php was easier or faster or > more like shell scripting or... fill in the blank. Anyway, so I change over > to learning php. Then I run across that blog, Coding Horror, and start > reading articles like this: > > http://www.codinghorror.com/blog/archives/001119.html > > Now what? Go back to python. Soldier on with php? What do I know? Not > much. I can setup mysql and apache,, but don't know how to use 'em, really. > I use emacs and run slackware and can fumble my way through bash scripts, > but I can't really write them or do lisp. I've taken basic basic and basic > C, but am barely literate in html. Sometimes it seems overwhelming, but I > persevere because it's more fun/challenging than video games, which bore me > to tears. > > Well, that's my actual question, then. Is php really so bad I'm just > wasting my time? Or is it really the quickest way to blog functionality? > Would I be better served in the long run learning python, which claims to be > easy as pie to learn/program (still looks hard to me). I admit I'm no code > geek. But, I'm not completely brain dead, either, and I need something to > keep my geezer brain sparking. What say ye? > > nb Check out the Pylons blog tutorial. You will have a simple blog up and running in less than 30 minutes and have a platform to extend it with as much functionality as you want later on. Larry Bates Pylons blog tutorial: http://wiki.pylonshq.com/display/pylonscookbook/Making+a+Pylons+Blog From cmpython at gmail.com Fri May 2 15:53:31 2008 From: cmpython at gmail.com (CM) Date: Fri, 2 May 2008 12:53:31 -0700 (PDT) Subject: where do I begin with web programming in python? References: <37ea096e-cf3e-4932-8370-306a15a2aebd@25g2000hsx.googlegroups.com> <4995d686-881d-4526-9095-3162cbfc4b49@z72g2000hsb.googlegroups.com> Message-ID: On May 2, 10:18 am, "andrei.zavi... at gmail.com" wrote: > On May 2, 10:07 am, bvidinli wrote: > > > > > i also asked same question in this list last week. > > i foundhttp://www.cherrypy.org/tobe most suitable for me. > > it is basic, easy, pure... > > it contains its own webserver, very easy to start. > > > others have many framworks, structures, classes many many.. > > i wanted a pure web programming system , i found cherrypy. > > > see you. > > > 2008/5/2 jmDesktop : > > > > I have been to the main python site, but am still confused. I have > > > been using .net, so it may be obvious how to do this to everyone > > > else. I am aware there are various frameworks (Django, Pylons, etc.), > > > but I would like to know how to create web pages without these. If I > > > have mod_python or fastcgi on apache, where do I start? I don't have > > > clue where to begin to create a web page from scratch in python. I am > > > sure I will want to access database, etc., all the "normal" stuff, I > > > just want to do it myself as opposed to the frameworks, for learning. > > > > Thank you for any help. > > > -- > > > http://mail.python.org/mailman/listinfo/python-list > > > -- > > ?.Bahattin Vidinli > > Elk-Elektronik M?h. > > ------------------- > > iletisim bilgileri (Tercih sirasina gore): > > skype: bvidinli (sesli gorusme icin,www.skype.com) > > msn: bvidi... at iyibirisi.com > > yahoo: bvidinli > > > +90.532.7990607 > > +90.505.5667711 > > I agree. Try cherrypy. I was able to write simple issue tracking > system for my project with basic web interface within 2 weeks. > Prior to this I had no web development experience at all. It was > really easy with cherrypy to start. Really? I tried CherryPy for a few minutes--totally 100% new to web programming--and though I was pleased at the very basic "Hello, World!" tutorial, I was unable to figure out how to use the more advanced tutorials that come with the package. Could you suggest how one could learn? I have experience with Python and GUI app development, zero on web apps, but want to make widget-having web apps which uses Python as the logic. Any tips would be appreciated! Also, beyond just running a small test web app with the "server" running on my own computer, what is a basic way to try it out actually on the web? Thanks! From paul.hankin at gmail.com Sat May 17 06:29:16 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Sat, 17 May 2008 03:29:16 -0700 (PDT) Subject: ? References: Message-ID: <51336537-0374-470a-a243-c6aa01e1fe9a@59g2000hsb.googlegroups.com> On May 17, 11:08?am, Ruediger wrote: > urikaluzhny wrote: > > It seems that I rather frequently need a list or iterator of the form > > [x for x in <> while <>] > > And there is no one like this. > > May be there is another short way to write it (not as a loop). Is > > there? > > Thanks > > I usually have the same problem and i came up with an solution like that: > > from operator import ne > def test(iterable, value, op=ne): > ? ? _n = iter(iterable).next > ? ? while True: > ? ? ? ? _x = _n() > ? ? ? ? if op(_x, value): > ? ? ? ? ? ? yield _x > ? ? ? ? else: > ? ? ? ? ? ? raise StopIteration This is better written using takewhile... itertools.takewhile(lambda x: x != value, iterable) But if you really need to reinvent the wheel, perhaps this is simpler? def test(iterable, value, op=operator.ne): for x in iterable: if not op(x, value): return yield x -- Paul Hankin From clyfish at gmail.com Tue May 6 05:19:17 2008 From: clyfish at gmail.com (clyfish at gmail.com) Date: Tue, 6 May 2008 02:19:17 -0700 (PDT) Subject: how to use subprocess.Popen execute "find" in windows Message-ID: <5666ed04-8a2f-4dad-b7bc-3e3c3c084f03@f24g2000prh.googlegroups.com> In cmd, I can use find like this. C:\>netstat -an | find "445" TCP 0.0.0.0:445 0.0.0.0:0 LISTENING UDP 0.0.0.0:445 *:* C:\> And os.system is OK. >>> import os >>> os.system('netstat -an | find "445"') TCP 0.0.0.0:445 0.0.0.0:0 LISTENING UDP 0.0.0.0:445 *:* 0 >>> But I don't know how to use subprocess.Popen to do this. from subprocess import Popen, PIPE p1 = Popen(['netstat', '-an'], stdout = PIPE) p2 = Popen(['find', '"445"'], stdin = p1.stdout, stdout = PIPE) print p2.stdout.read() It doesn't work. Because subprocess.Popen execute "find" like this. C:\>find \"445\" ???? - \ C:\> It adds a '\' before each '"'. How to remove the '\'? Thank you. From kamhung.soh at gmail.com Sun May 18 21:52:57 2008 From: kamhung.soh at gmail.com (Kam-Hung Soh) Date: Mon, 19 May 2008 11:52:57 +1000 Subject: How do *you* use Python in non-GUI work? References: <20080518182022.990193bd.johnjsal@NOSPAMgmail.com> Message-ID: On Mon, 19 May 2008 08:20:22 +1000, John Salerno wrote: > Hey all. Just thought I'd ask a general question for my own interest. > Every time I think of something I might do in Python, it usually > involves creating a GUI interface, so I was wondering what kind of work > you all do with Python that does *not* involve any GUI work. This could > be any little scripts you write for your own benefit, or what you do at > work, if you feel like talking about that! :) > > Thanks. > -- > http://mail.python.org/mailman/listinfo/python-list > - Enhancing existing products by scripting new features. - Interface between databases, Excel and text files. - Convert data between flat files and XML. - Manage files for build processes. - Automating processes (e.g. checkout, builds, FTP). Wish I had some reasons to make a GUI application in Python. -- Kam-Hung Soh
Software Salariman From wuwei23 at gmail.com Tue May 13 07:13:01 2008 From: wuwei23 at gmail.com (alex23) Date: Tue, 13 May 2008 04:13:01 -0700 (PDT) Subject: Some comparison operators gone in Python 3.0? References: Message-ID: <0bff2507-7242-48a6-8f95-d65191b0177f@x19g2000prg.googlegroups.com> On May 13, 8:18 pm, "Gabriel Genellina" wrote: > May I ask *where* did you read that crazy idea? Grant Edwards outlines his past behaviour here: http://groups.google.com/group/comp.lang.python/msg/27553bd56827dc0f Given that all nine of his postings have inflammatory topics, he's beginning to sound like a troll. From bbxx789_05ss at yahoo.com Sun May 11 16:01:21 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Sun, 11 May 2008 13:01:21 -0700 (PDT) Subject: File Creation Not Working In A Thread Class? References: <7qGVj.32505$KJ1.18416@newsfe19.lga> Message-ID: On May 11, 1:28?pm, bc90021 wrote: > > ...and the exact error message was? > > > Here is a tip: if you want people to help you, then you have to help > > them to help you. ?Personally, I wouldn't respond to anymore of your > > questions because you seem incapable of posting the information that was > > requested. > > So far, the people who have answered this post have gone on the > assumption that I'm stupid. ?I'm not. ?I took perfectly working code, > cut it from one class, and put it in another. ?It stopped working in the > second class. ?I've spent days on this and trust me, given what I've > experienced of the Python community so far, if I didn't have to ask, I > wouldn't. > > (I really must say that so far the help I am getting in the Python > community is a big let down. ?Whether it's on IRC or here, everyone has > an arrogance that I don't find anywhere else in the open source > community, and it seriously makes me question the choice of language that > I've made.) > > The error message was at the top of the thread (am I incapable of posting > it, or are you incapable of following a thread?), but here it is again: > > IOError: [Errno 2] no such file u'tempfileName' Well, it appears to me that this error message is different than the one in your first post. But maybe I'm on LSD right now and things will be appear differently tomorrow. In addition, I've never seen a python error message that doesn't include the traceback, which you were asked to post, but apparently are still incapbable of doing. Also, any line numbers in the error message should be marked in your code with comments. That will help other people help you, remember? From exarkun at divmod.com Mon May 5 08:18:35 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 5 May 2008 08:18:35 -0400 Subject: confused about self, why not a reserved word? In-Reply-To: <972f7226-baef-4f94-a8ea-5bec99213540@34g2000hsf.googlegroups.com> Message-ID: <20080505121835.6859.754335118.divmod.quotient.59009@ohm> On Mon, 5 May 2008 04:57:25 -0700 (PDT), globalrev wrote: >class Foo(object): > def Hello(self): > print "hi" > >object is purple, ie some sort of reserved word. What your text editor of choice does with syntax coloring is its own business. It doesn't really have anything to do with the language, except inasmuch as one might hope that it is *somehow* based on it. >why is self in black(ie a normal word) when it has special powers. >replacing it with sel for example will cause an error when calling >Hello. Not true. exarkun at charm:~$ python -c ' > class Foo(object): > def Hello(monkeys): > print "hi" > > Foo().Hello() > ' hi exarkun at charm:~$ `self? as the name of the first parameter to an instance method is convention; beyond that, it has no special meaning in the language. `object?, on the other hand, is a builtin name which refers to a particular object. Jean-Paul From thomas.troeger.ext at siemens.com Tue May 20 05:50:22 2008 From: thomas.troeger.ext at siemens.com (Thomas Troeger) Date: Tue, 20 May 2008 11:50:22 +0200 Subject: compressing short strings? References: <7xy7658k8o.fsf_-_@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > I have a lot of short English strings I'd like to compress in order to > reduce the size of a database. That is, I'd like a compression > function that takes a string like (for example) "George Washington" [...] > > Thanks. I think your idea is good, maybe you'd want to build an LZ78 encoder in Python (LZ78 is pretty easy), feed it with a long English text and then pickle the resulting object. You could then unpickle it on program start and encode your short strings with it. I bet there's a working implementation around that already that does it ... but if you can't find any, LZ78 is implemented in 1 or 2 hours. There was a rather good explanation of the algorithm in German, unfortunately it's vanished from the net recently (I have a backup if you're interested). Cheers, Thomas. From siva.webhosting at gmail.com Tue May 27 21:18:39 2008 From: siva.webhosting at gmail.com (siva) Date: Tue, 27 May 2008 18:18:39 -0700 (PDT) Subject: More than 500 Free webhostings Message-ID: Hi Friends In this world everyone is searching for free webhostings for their websites So only i found this website after some struggle it's a free webhosting directory www.webhostingsfree.com Having more than 500 free web hosting websites and free file hostings ,image hostings etc.... From castironpi at gmail.com Thu May 15 20:16:57 2008 From: castironpi at gmail.com (castironpi) Date: Thu, 15 May 2008 17:16:57 -0700 (PDT) Subject: send yield References: <6a19b5bf-ed71-499c-a348-6e26e2f523eb@m45g2000hsb.googlegroups.com> <60bc3c8e-b084-47ce-a8d7-16359f17bcbc@a70g2000hsh.googlegroups.com> <7d37c335-1bac-4318-a3b0-bb0fd67a7a10@8g2000hse.googlegroups.com> <0d6e83bd-f6a8-4255-b5e9-d56c31c8e8f5@m45g2000hsb.googlegroups.com> <5e7bb9f0-3d3d-4682-b06d-6e2c2e41c214@p25g2000hsf.googlegroups.com> Message-ID: On May 15, 6:43?pm, castironpi wrote: > On May 15, 6:16?pm, castironpi wrote: > > > > > > > On May 15, 4:28?pm, "bruno.desthuilli... at gmail.com" > > > wrote: > > > On 15 mai, 16:40, castironpi wrote: > > > > > On May 15, 9:26 am, "Dan Upton" wrote: > > > > > > On Thu, May 15, 2008 at 9:32 AM, castironpi wrote: > > > > > > Why can't I write this? > > > > > > -- > > > > > > Because your antecedent is undefined? > > > > > Of the two ways to play, just to say #define this per se would be a > > > > bad move, but that's one that comes from the wrong group. ?#define is > > > > a big scary macro, that python hasn't been using; it's the one-line > > > > typo. ?Instance: > > > > > #define life1 Tron( drive.SIZE[ 0 ]/ 2, drive.SIZE[ 1 ]/ 2 ) > > > > > Use it to render planes in solids. > > > > > Back about 'this', I honestly hadn't remembered 'til this time, when I > > > > got a chance to reread the subject. ?Plus I keep ditching my radio. > > > > Jesus H. Christ. This really sounds like my mother in law. Scary, > > > definitively.- Hide quoted text - > > > > - Show quoted text - > > > Definitely. ?But, due, I forgot to complete an example. > > > > > #define life1 Tron( drive.SIZE[ 0 ]/ 2, drive.SIZE[ 1 ]/ 2 ) > > > in C. ?Python: > > > life1= 'Tron( drive.SIZE[ 0 ]/ 2, drive.SIZE[ 1 ]/ 2 )' > > exec( life1 ) > > > Where does it go?- Hide quoted text - > > > - Show quoted text - > > I'm supposed to talk about an entropy pool game. ?You can tunnel.- Hide quoted text - > > - Show quoted text - If I had a send-parachute, would all you need be yield? Let's drop graphics. From russblau at hotmail.com Fri May 9 06:11:24 2008 From: russblau at hotmail.com (Russell Blau) Date: Fri, 9 May 2008 06:11:24 -0400 Subject: Reusing IDLE file editor Message-ID: I have a need for some simple text-editing capabilities in a Tkinter program, and it occurred to me that IDLE is a Tkinter app that already has what I need in its file editor windows. I thought it would be nice if I could just use one of those windows as a widget in my application, in place of a plain Tkinter Text widget. I took a quick look at idlelib/EditorWindow.pyw, but it appears that the program is not written as a reusable widget; it's hard-coded to be a toplevel window. Before I start hacking at it myself, has anyone else modified IDLE to be able to reuse its windows in another application? Or, alternatively, is there another freely-available (under the Python license or something compatible) Tkinter widget out there that has similar text-editing capabilities? _________________________________________________________________ With Windows Live for mobile, your contacts travel with you. http://www.windowslive.com/mobile/overview.html?ocid=TXT_TAGLM_WL_Refresh_mobile_052008 -------------- next part -------------- An HTML attachment was scrubbed... URL: From dickinsm at gmail.com Thu May 22 13:32:17 2008 From: dickinsm at gmail.com (Mark Dickinson) Date: Thu, 22 May 2008 10:32:17 -0700 (PDT) Subject: Why is math.pi slightly wrong? References: Message-ID: <3026ddb4-1e9f-488c-a1dc-fe43020d72c7@k37g2000hsf.googlegroups.com> On May 22, 12:32?pm, "Dutton, Sam" wrote: > I've noticed that the value of math.pi -- just entering it at the interactive prompt -- is returned as 3.1415926535897931, whereas (as every pi-obsessive knows) the value is 3.1415926535897932... (Note the 2 at the end.) > There are two effects here: (1) pi isn't exactly representable as a floating-point number, so math.pi is merely an approximation to it, and (2) the value 3.1415926535897931 that you see when you print pi is itself an approximation to the actual value of math.pi. math.pi is exactly equal to 884279719003555/281474976710656, which is the closest C double to the actual value of pi. The problem in (2) occurs because floating-point numbers are stored in binary, but printed in decimal. Mark From kamhung.soh at gmail.com Thu May 29 22:12:36 2008 From: kamhung.soh at gmail.com (Kam-Hung Soh) Date: Fri, 30 May 2008 12:12:36 +1000 Subject: Finding file details... In-Reply-To: References: Message-ID: Roger Upole wrote: > Kalibr wrote: >> I've been trying to figure out how to find the details of files >> (specifically music for now) for a little sorting script I'm making, >> My aim is to get details on the artist, album, and genre for mp3 and >> wma files (possibly more in the future). My closest match was when I >> stumbled accross PyMedia, but it only supports up to 2.4 (I have 2.5). >> Now I see a bit mentioned on GetFileVersionInfo, but that doesn't seem >> to help (and most of it went over my head). Is there any module I can >> use to find this sort of data? I'm trying to not make it specialised >> in music, because I may want to extend this to picture, movie, text >> etc. files in the future. Any ideas how I could go about this? I think GetFileVersionInfo() only provides version information for DLL and EXE files. See: http://msdn.microsoft.com/en-us/library/ms646981.aspx > > You can use the shell COM objects to access media properties > as shown by Explorer. > > import win32com.client > sh=win32com.client.Dispatch('Shell.Application') > > folder= r'M:\Music\Bob Dylan\Highway 61 Revisited' > ns=sh.NameSpace(folder) > > ## the column index for Artist may vary from folder to folder > for c in range(0,255): > colname=ns.GetDetailsOf(None, c) > if colname=='Artists': ## This shows up as just Artist on XP > for i in ns.Items(): > artist=ns.GetDetailsOf(i, c) > if artist: > print ns.GetDetailsOf(i, 0), artist > break > > > Roger Great tip, Roger! This solution works for WMA files (I don't have any MP3 files handy), so I think it would work for any media files in Windows. -- Kam-Hung Soh Software Salariman From bj_666 at gmx.net Fri May 23 01:42:16 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 23 May 2008 05:42:16 GMT Subject: Relationship between GUI and logic? References: <48363c34$0$15204$607ed4bc@cv.net> Message-ID: <69n3poF33hfhfU1@mid.uni-berlin.de> On Thu, 22 May 2008 23:37:45 -0400, John Salerno wrote: > I know that it is good programming practice to keep GUI and logic code > physically separate, by using XRC for example, but I'm wondering if it's > also good practice (and even possible) to keep them separate from an > implementation standpoint as well. Basically what I mean is, should it > be possible to write, for example, the logic for a strategy game without > even knowing what the graphics will look like or how they will work? Yes, that's possible. > To be more specific, let's say I want to create a simple, 2D strategy > game. It will have a board layout like chess or checkers and the player > will move around the board. Let's say this is all I know, and perhaps I > don't even know *this* for sure either. Is it possible to write the > logic for such a game at this point? Maybe even this is possible. But here you are not only drawing the line between GUI and logic but also within the logic part itself because the board layout isn't (just) a GUI issue. If you have checkers, hexagons, or other shapes also has influence on the logic part, because you need slightly different algorithms for finding ways from tile `A` to tile `B`, or to decide when a piece is blocked by others, and how the rules to move pieces around look like. Just imagine how to modify chess rules to a board with hexagonal patterns. It would severely change the logic part. > Another example could be printing messages to the player. If I need to > say "You killed the monster!", is there a general way to write this, or > do I need to specifically refer to GUI widgets and methods, etc. in > order for it to be displayed properly? The observer pattern can be used here. The GUI has to register a callback function with your logic engine and every time you want to inform the player about something, your game logic calls that function with the message. It doesn't have to know if it will be rendered as graphic on screen, displayed as text in a terminal, or synthesized as sexy female computer voice. Ciao, Marc 'BlackJack' Rintsch From gagsl-py2 at yahoo.com.ar Fri May 9 10:11:44 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 09 May 2008 11:11:44 -0300 Subject: multiple Python versions, but on Windows (how to handle registry updates) References: <3de8e1f70805090358p27796919jb885138406ade6aa@mail.gmail.com> Message-ID: En Fri, 09 May 2008 07:58:33 -0300, Banibrata Dutta escribi?: > I already have Python25, and need to install Python24. I would prefer not to > remove Python25, but each Python version seems to update the registry, I > guess (not sure), overwriting each other's entries. Any way to have both > versions ? They can coexist peacefully. The last one you install will be the default version to handle .py files automatically. You may want to create a batch file like this: @c:\python24\python.exe %* (and a similar one for 2.5; put them somewhere on your PATH, like c:\windows\system32) Usage: python24 somescript.py -- Gabriel Genellina From rossgk at gmail.com Fri May 30 14:10:17 2008 From: rossgk at gmail.com (RossGK) Date: Fri, 30 May 2008 11:10:17 -0700 (PDT) Subject: PyDev multiple source files? Message-ID: Newbie questions on PyDev project setup. Things are going fine - writing python code in eclipse/pydev and running them with various imports etc, doing wxpython stuff blah, blah, blah. My .py code is in a module, in a package, in a project. It runs fine. Now I want to be able to break my single source file up into multiple files to segregate functions, divide up with others, etc, but I don't know how to configure it. I pulled one simple class definition out of my single source file and created a new .py file with just that in there. But now I'm stalled... What is the equivalent of an 'include' statement. I assume there's something I put into one .py file to say I'm using stuff in another local .py file. I tried using "import" but it doesn't seem to work - ie code doesn't know about the class in the other file. Also, how about global vars that are needed across multiple .py files? Where do I declare them to be understood in all the files that use that global. I suspect there is something I do in __init__.py - perhaps the equivalent of 'include' statements in there with all my globals stuffed in there too??? I'm lost here, but will continue to play with it. Any hints appreciated. Surely all python developers don't cram everything into one huge file (I hope). Ross. From george.sakkis at gmail.com Sat May 3 20:43:57 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Sat, 3 May 2008 17:43:57 -0700 (PDT) Subject: Feature suggestion: sum() ought to use a compensated summation algorithm References: <481CB283.107@gmail.com> Message-ID: <9d890b77-688e-4207-8eb3-8233d287ecb6@8g2000hse.googlegroups.com> On May 3, 7:12?pm, Ivan Illarionov wrote: > On Sun, 04 May 2008 00:31:01 +0200, Thomas Dybdahl Ahle wrote: > > On Sat, 2008-05-03 at 21:37 +0000, Ivan Illarionov wrote: > >> On Sat, 03 May 2008 20:44:19 +0200, Szabolcs Horv?t wrote: > > >> > Arnaud Delobelle wrote: > > >> >> sum() works for any sequence of objects with an __add__ method, not > >> >> just floats! ?Your algorithm is specific to floats. > > >> > This occurred to me also, but then I tried > > >> > sum(['abc', 'efg'], '') > > >> Interesting, I always thought that sum is like shortcut of > >> reduce(operator.add, ...), but I was mistaken. > > >> reduce() is more forgiving: > >> reduce(operator.add, ['abc', 'efg'], '' ) # it works 'abcefg' > > Hm, it works for lists: > > sum(([1], [2]), []) > > [1, 2] So it's not reduce() that is more forgiving, it's sum() that makes an exception for strings only. > > However I find the seccond argument hack ugly. Does the sum way have any > > performance advantages over the reduce way? > > Yes, sum() is faster: > > $ python -m timeit "" "sum([[1], [2], [3, 4]], [])" > 100000 loops, best of 3: 6.16 usec per loop > > $ python -m timeit "import operator" \ > "reduce(operator.add, [[1], [2], [3, 4]])" > 100000 loops, best of 3: 11.9 usec per loop Not really; you measure the import and the attribute access time in the second case. sum() is 2x faster for adding numbers only: # Adding integers python -mtimeit --setup="x=[1]*100" "sum(x)" 100000 loops, best of 3: 4.87 usec per loop python -mtimeit --setup="from operator import add; x=[1]*100" "reduce(add,x)" 100000 loops, best of 3: 10.1 usec per loop # Adding floats python -mtimeit --setup="x=[1.0]*100" "sum(x)" 100000 loops, best of 3: 5.14 usec per loop python -mtimeit --setup="from operator import add; x=[1.0]*100" "reduce(add,x)" 100000 loops, best of 3: 10.1 usec per loop # Adding tuples python -mtimeit --setup="x=[(1,)]*100" "sum(x,())" 10000 loops, best of 3: 61.6 usec per loop python -mtimeit --setup="from operator import add; x=[(1,)]*100" "reduce(add,x,())" 10000 loops, best of 3: 66.3 usec per loop # Adding lists python -mtimeit --setup="x=[[1]]*100" "sum(x,[])" 10000 loops, best of 3: 79.9 usec per loop python -mtimeit --setup="from operator import add; x=[[1]]*100" "reduce(add,x,[])" 10000 loops, best of 3: 84.3 usec per loop George From mypromise at sina.com Wed May 21 10:26:49 2008 From: mypromise at sina.com (zhf) Date: Wed, 21 May 2008 22:26:49 +0800 Subject: how to proccess the blank in the path on linux Message-ID: <48343129.4060205@sina.com> I want ro walk a directory and its sub directory on linux, to find some shell script file, and run them, but I found some path belong blank charactor, such as '8000 dir', if I write as follow, I got error "no such file" path = '8000 dir' for root, dirs, files in os.walk(path): cmd = ' ' cmd = 'cd ' + root os.system(cmd) How can I repair it? thanks, best regards. From paddy3118 at googlemail.com Sun May 11 01:30:45 2008 From: paddy3118 at googlemail.com (Paddy) Date: Sat, 10 May 2008 22:30:45 -0700 (PDT) Subject: firefox add-on to grab python code handily? References: <93e5303c-d19e-4037-9b39-368df4325c76@c65g2000hsa.googlegroups.com> Message-ID: <0731c156-e28b-4a7d-bb24-af85bfa5ce8a@x41g2000hsb.googlegroups.com> On May 10, 8:58 am, CM wrote: > I encounter a fair number of small Python scripts online, and usually > try them out by copying them to the clipboard, pasting into Notepad, > saving them, and either running them directly or opening them in > IDLE. > > And so I was wondering if anyone knew of an extension/add-on/script > for Firefox which would allow a way to do something like this: > > user highlights Python code on a webpage > right clicks > selects a menu item, "Save as Python code" > FF pops up a filename dialog or popup for filename > (and, though I don't know if this is possible, runs Python code) > > Not an important thing by any means, but it would be a nice > convenience. > I know there are similar add-ons in FF for grabbing highlighted text > and > saving, but they are not good, as they don't seem to preserve line > breaks > properly or append the .py extension, etc. I've Googled for this and > so far > it seems it doesn't exist. Anyone know? Take a look at the crunchy project: http://crunchy.sourceforge.net/ - Paddy. From gagsl-py2 at yahoo.com.ar Fri May 2 15:16:57 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 02 May 2008 16:16:57 -0300 Subject: Searching and replacing text ? References: <6c06af6c-e068-4569-9a2d-f42df5fe1ff4@k37g2000hsf.googlegroups.com> Message-ID: En Fri, 02 May 2008 15:51:42 -0300, Oltmans escribi?: > Hi, > > I'm new to Python (and admittedly not a very good programmer) and I've > come across a scenario where I've to search and replace text in a > file. > > For the sake of an example, I'm searching for every occurence of the > text > [[http://www.hotmail.com -> Hotmail]] > > I've to replace it with > [http://www.hotmail.com Hotmail] > > I've come up with following scheme > p=re.compile(r'\[\[') > q=re.compile(r'->') > > p.sub('[',txt) > q.sub('\b',txt) Is it a constant text? Then use the replace method of string objects: no re is needed. text = "This is [[http://www.hotmail.com -> Hotmail]] some text" print text.replace("[[http://www.hotmail.com -> Hotmail]]", "[http://www.hotmail.com Hotmail]") output: This is [http://www.hotmail.com Hotmail] some text Or, do you want to find '[[' followed by some word followed by ' -> ' followed by another word followed by ']]'? r = re.compile(r'\[\[(.+?)\s*->\s*(.+?)\]\]') print r.sub(r'[\1 \2]', text) (same output as above) () in the regular expression indicate groups, that you can reference as \1 \2 in the replacement string. -- Gabriel Genellina From ptmcg at austin.rr.com Sat May 24 09:42:56 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sat, 24 May 2008 06:42:56 -0700 (PDT) Subject: C-like assignment expression? References: <68b5d090-9e3b-4e7d-9dda-fc1b099822c2@m73g2000hsh.googlegroups.com> Message-ID: <43381ce3-3505-482e-82ac-0643eb57e25b@k37g2000hsf.googlegroups.com> On May 21, 4:38?am, boblat... at googlemail.com wrote: > Hello, > > I have an if-elif chain in which I'd like to match a string against > several regular expressions. Also I'd like to use the match groups > within the respective elif... block. The C-like idiom that I would > like to use is this: > > if (match = my_re1.match(line): > ? # use match > elsif (match = my_re2.match(line)): > ? # use match > elsif (match = my_re3.match(line)) > ? # use match > > ...buy this is illegal in python. The other way is to open up an else: > block in each level, do the assignment and then the test. This > unneccessarily leads to deeper and deeper nesting levels which I find > ugly. Just as ugly as first testing against the RE in the elif: clause > and then, if it matches, to re-evaluate the RE to access the match > groups. > > Thanks, > robert Try this. -- Paul class TestValue(object): """Class to support assignment and test in single operation""" def __init__(self,v=None): self.value = v """Add support for quasi-assignment syntax using '<<' in place of '='.""" def __lshift__(self,other): self.value = other return bool(self.value) import re tv = TestValue() integer = re.compile(r"[-+]?\d+") real = re.compile(r"[-+]?\d*\.\d+") word = re.compile(r"\w+") for inputValue in ("123 abc 3.1".split()): if (tv << real.match(inputValue)): print "Real", float(tv.value.group()) elif (tv << integer.match(inputValue)): print "Integer", int(tv.value.group()) elif (tv << word.match(inputValue)): print "Word", tv.value.group() Prints: Integer 123 Word abc Real 3.1 From bruno.42.desthuilliers at websiteburo.invalid Mon May 26 12:17:34 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 26 May 2008 18:17:34 +0200 Subject: Python web development that resembles PHP or classic ASP In-Reply-To: <66a261d8-c31d-4519-beb9-c8913f61a87d@m44g2000hsc.googlegroups.com> References: <66a261d8-c31d-4519-beb9-c8913f61a87d@m44g2000hsc.googlegroups.com> Message-ID: <483ae29c$0$21027$426a74cc@news.free.fr> erik.oosterwaal at gmail.com a ?crit : > Hi All, > (snip history and reasons to switch from old-style ASP). > > So that's when I started looking at other dynamic languages for > webdevelopment. I looked at Ruby on Rails and at the different web- > frameworks that are available for Python. The biggest problem there > for me is that the MVC type frameworks that are currently very popular > are also not what I'm looking for. > > I like having my directory tree conform to the structure of my > website, so the "Controller" part of the MVC style of development is > something I wouldn't want. What I -would- like is a separation of code > and display logic (so being able to include libraries in a page) and > being able to intermix code directly into the HTML. There are a couple points I don't get here. Mostly: how is your application logic separated from the presentation logic if you "intermix code directly into the HTML" ? Or are you pages including the libs, getting the appropriate data out of the DB, and then including another file acting as a template ? If so, then how are you're "pages" different from MVC frameworks controllers ? > As Python would be the language I prefer over Ruby, I thought I'd ask > here to see if anyone in the Python community knows if such a > development-framework exists in Python. mod_python + PSP would come to mind - it's probably the closer thing to ASP/PHP you'll get in Python - but I don't know if PSP is still maintained, and I would by no mean consider such a "framework" for new projects (and FWIW, PSP is a bit ugly IMHO). Mako is a templating engine that let you have quite a lot of Python code inside your templates, but you'll still need a separate controller for most things. Writing a wsgi-compatible framework that uses Mako as template engine and dispatch to controllers based on the filesystem might not be a very difficult task, but even then, I don't see the point of such an arrangement - specially when we already have more web frameworks than keywords... > For example, does IronPython > also use the same web forms approach as asp.net using VB? The > frameworks I looked at (Django, Pylons) seem to be able to use > different templating engines, does that mean it's just a question of > finding the right one? Django and Pylons both impose a distinct controller. > Also, for Python there is also the problem of meaningful indentation. > I'm not even sure if it's possible to use Python directly inside HTML, > because indentation would be at the very least tricky to maintain. It's indeed one of the ugly parts of PSP. > I'm > kind of hoping here that there are some solutions to these problems > available in Python. > > Any help would be greatly appreciated. I sincerely think you'd be better trying to get up and running with one of the existing MVC solutions like Django or Pylons. Now there are quite a couple other web frameworks in Python, you know - so perhaps you should have a closer look at them ? My 2 cents... From fuzzyman at gmail.com Sun May 25 16:03:14 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Sun, 25 May 2008 13:03:14 -0700 (PDT) Subject: 22.800000 and a 1 on the end!!?? References: Message-ID: On May 25, 8:58?pm, notnorweg... at yahoo.se wrote: > >>> x = 5 > >>> x /= 2 > >>> x > 2 > >>> x *=11.4 > >>> x > > 22.800000000000001 > > ok where does the 1 in the come from? Floating point arithmetic. Michael Foord http://www.ironpythoninaction.com/ From ivan.illarionov at gmail.com Sun May 25 14:46:32 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Sun, 25 May 2008 11:46:32 -0700 (PDT) Subject: php vs python References: <5l%Yj.77$mz3.53@fe101.usenetserver.com> <37b112d8-a3ba-446d-9d2f-d907d93c637b@w8g2000prd.googlegroups.com> <-t-dnWQ4bZN2MaTVnZ2dnUVZ_qGdnZ2d@comcast.com> Message-ID: <68cb8bb1-4cc5-4a28-8915-46e7d4e316d9@d1g2000hsg.googlegroups.com> Jerry Stuckle wrote: > Lie wrote: > > On May 22, 12:28 pm, NC wrote: > >> On May 21, 1:10 pm, notbob wrote: > >>> So, here's my delimna: I want to start a blog. ?Yeah, who doesn't. > >>> Yet, I want learn the guts of it instead of just booting up some > >>> wordwank or whatever. > >> Here's a simple computation to consider... ?WordPress' codebase is > >> approximately a megabyte of PHP code and megabyte of JavaScript code. > >> Assuming that the average line of that code is 50 characters long, you > >> are looking at 20,000 lines of code in PHP and as many in JavaScript. > >> Based on the notion that the average developer out there writes 100 > >> lines a day, either you're in for a two-year project or your product > >> is going to have seriously reduced functionality compared to something > >> that's been freely available for years. ?What's your choice? > > > Nope, the core functionality of a blogging software could be > > replicated in just a few lines of PHP codes, in the range of tens to > > hundreds of lines. If you're creating your own blogging software, you > > wouldn't seriously think you'd recreate all those things such as > > pingbacks, commenting system, etc, etc, etc. No, you'd start with some > > basic core functionalities: a few simple server side includes only. > > As he said - it's either a two man-year project or your product is going > to have seriously reduced functionality. ?It looks like you are opting > for the latter. > > Also, you still need to write the server-side includes. ?But they won't > do nearly enough for everything WordPress does. If the OP wants to learn the guts of the blog or to implement the blog from scratch, Python/Django would be a better choice than PHP. The reason is that he can reuse and customize existing high quality components for all these auth/auth, admin, comments, etc, etc, etc. Another reason is that Python and Django encourage very clean design while PHP is too often ends up in "spaghetti SQL wrapped in spaghetti PHP wrapped in spaghetti HTML". 2 man/year in PHP == 2 man/week in Python/Django. And there are Python/Django blog applications that already do almost everything (and maybe more) that WordPress does. http://byteflow.su/ is one of them (IMHO the most promising). Ivan From deets at nospam.web.de Sun May 4 17:27:28 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 04 May 2008 23:27:28 +0200 Subject: pygame.mixer.load not working In-Reply-To: <4c6d81b2-c2a7-4934-946e-826bec035bb7@w74g2000hsh.googlegroups.com> References: <4c6d81b2-c2a7-4934-946e-826bec035bb7@w74g2000hsh.googlegroups.com> Message-ID: <686o25F2rb5iqU1@mid.uni-berlin.de> globalrev schrieb: > import pygame > > pygame.mixer.music.load(example1.mp3) > pygame.mixer.music.play(loops=1, start=0.0) > > > Traceback (most recent call last): > File "C:\Python25\myPrograms\pygameProgs\musicexp.py", line 3, in > > pygame.mixer.music.load(example1.mp3) > NameError: name 'example1' is not defined > > example1 is in the same directory as the script http://docs.python.org/tut/node5.html#SECTION005120000000000000000 Diez From arnodel at googlemail.com Sat May 31 11:48:40 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sat, 31 May 2008 16:48:40 +0100 Subject: accumulator generators References: <7a41e745-956b-4582-bd61-eac699f1d892@34g2000hsf.googlegroups.com> Message-ID: George Sakkis writes: > On May 31, 4:19?am, Arnaud Delobelle wrote: >> Cameron writes: >> > I was reading this Paul >> > Graham article and he builds an accumuator generator function in >> > the appendix. His looks like this: >> >> >
>> > def foo(n):
>> > ? s = [n]
>> > ? def bar(i):
>> > ? ? s[0] += i
>> > ? ? return s[0]
>> > ? return bar
>> > 
>> >> > Why does that work, but not this: >> >> >
>> > def foo(n):
>> > ? s = n
>> > ? def bar(i):
>> > ? ? s += i
>> > ? ? return s
>> > ? return bar
>> > 
>> >> Others have explained why, but this looks like "pythonized LISP" to >> me. ?I would rather use a generator function: >> >> def foo(n): >> ? ? while True: >> ? ? ? ? n += yield n >> >> Although the problem is that you can't send it values the first time >> round! >> >> >>> bar = foo('s') >> >>> bar.next() >> 's' >> >>> bar.send('p') >> 'sp' >> >>> bar.send('am') >> >> 'spam' >> >> But: >> >> >>> bar = foo(3) >> >>> bar.send(2) >> >> Traceback (most recent call last): >> ? File "", line 1, in >> TypeError: can't send non-None value to a just-started generator > > I find the "pythonized LISP" solution more understandable, even > without the initial next() requirement. YMMV > > George In that case a class may be better? IMHO, what is such a natural idiom in LISP does not translate well literally into Python. class Foo(object): def __init__(self, n): self.s = n def __call__(self, i) self.s += i return self.s Anything to avoid the mutable container trick! Of course 'nonlocal' takes care of this in py3k. I have missed the absence of 'nonlocal' a lot, but now that it is around the corner, I grow less sure about it. -- Arnaud From wizzardx at gmail.com Sun May 25 13:36:06 2008 From: wizzardx at gmail.com (David) Date: Sun, 25 May 2008 19:36:06 +0200 Subject: Code correctness, and testing strategies In-Reply-To: <5hv*dSKds@news.chiark.greenend.org.uk> References: <18c1e6480805241317s4e960259pa8b2f1f8dc8d67f6@mail.gmail.com> <5hv*dSKds@news.chiark.greenend.org.uk> Message-ID: <18c1e6480805251036u22ec09f9y1d846b4698d6c09a@mail.gmail.com> Hi again. Taking the advice of numerous posters, I've been studying BDD further. I spent a while looking for a Python library which implemented BDD in Python similar to jbehave, as described by Dan North on this page: http://dannorth.net/introducing-bdd. I did find a few, but they either had awful-looking syntax, or they were overly-complicated. So I decided that using regular unit tests (via nosetest) was good enough, even if it doesn't have support for stories, scenarios, givens, etc, and it uses words with "Test" in it instead of "Behavior". One thing I just tried was to put together a basic stack class following BDD, with nosetest. I got the idea from this page: http://www.ibm.com/developerworks/web/library/j-cq09187/index.html It was an interesting exercise, and I'm encouraged to try it further. I ended up with these 2 modules: ======test_stack.py======== from nose.tools import raises import stack class TestStackBehaviour: def setup(self): self.stack = stack.Stack() @raises(stack.Empty) def test_should_throw_exception_upon_pop_without_push(self): self.stack.pop() def test_should_pop_pushed_value(self): self.stack.push(12345) assert self.stack.pop() == 12345 def test_should_pop_second_pushed_value_first(self): self.stack.push(1) self.stack.push(2) assert self.stack.pop() == 2 def test_should_leave_value_on_stack_after_peep(self): self.stack.push(999) assert self.stack.peep() == 999 assert self.stack.pop() == 999 def test_should_pop_values_in_reverse_order_of_push(self): self.stack.push(1) self.stack.push(2) self.stack.push(3) assert self.stack.pop() == 3 assert self.stack.pop() == 2 assert self.stack.pop() == 1 @raises(stack.Empty) def test_peep_should_fail_when_stack_is_empty(self): self.stack.peep() def test_should_be_empty_when_new(self): assert len(self.stack) == 0 ======stack.py======== class Empty(Exception): """Thrown when a stack operation is impossible because it is empty""" pass class Stack: """Basic implementation of a stack""" def __init__(self): self._data = [] def push(self, value): """Push an element onto a stack""" self._data.append(value) def pop(self): """Pop an element off a stack""" try: return self._data.pop() except IndexError: raise Empty def peep(self): """Return the top-most element of the stack""" try: return self._data[-1] except IndexError: raise Empty def __len__(self): """Return the number of elements in the stack""" return len(self._data) =================== Does the above look like a decent BDD-developed class? Is it ok that there are no 'scenarios', 'stories', 'having', 'given', etc references? Some pages suggest that you should use so-called contexts (EmptyStackContext, StackWithOneElementContext, FullStackContext, AlmostFullStackContext, etc). Would you normally start with a basic TestStackBehavoiur class, and when Stack becomes more complicated, split the tests up into TestEmptyStackContext, TestStackWithOneElementContext, etc? Another thing I noticed is that some of my test cases were redundant. Would you normally leave in the redundant tests, or remove the ones which are included in the more general test? Also, I have another question. How do you unit test event loops? eg: Your app is a (very basic) service, and you want to add some functionality (following BDD principles) Here's an example unit test: class TestServiceBehavior: def setup(self): ... def test_handles_event_xyz(self): ... If your service is normally single-threaded, would your unit test need to start the service in a separate thread to test it? Another method would be to update the event loop to enable unit testing. eg only iterate once if a 'being_tested' variable is set somewhere. None of the above are ideal. What is a good way to unit test event loops? David. From arnodel at googlemail.com Sun May 25 16:30:06 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 25 May 2008 21:30:06 +0100 Subject: set partition question References: Message-ID: pball.benetech at gmail.com writes: > dear pythonistas, > > So imagine that we have a set of sets S. If we pick arbitrarily one > set, s0, what are all the combinations of other sets in S which when > combined by set operations result in s0? > > s0 = set([1]) > s1 = set([1,2]) > s2 = set([2]) > S = set([s0,s1,s2]) > one answer we're searching for is s0 = s1 - s2 > > There may be arbitrarily many set elements (denoted by integers > 1,2,3,...) and arbitrarily many combinations of the elements composing > the sets s_i (s0, s1, ...). We can use any operation or function which > takes and returns sets. > > I think this problem is related to integer partitioning, but it's not > quite the same. The range of answers has a little combinatorial > explosion problem as S gains new members. In my problem, len(S) is > usually on the order of 1M, and in the worst case, 10M, and there are > on the order of 10k elements. > > My attempts to come up with an algorithm have not succeeded. Any ideas > occur to you folks? -- PB. Unless your sets have some sort of pattern, it sounds to me like this problem is at least exponential... Good luck! -- Arnaud From johnjsal at gmailNOSPAM.com Sun May 11 16:16:53 2008 From: johnjsal at gmailNOSPAM.com (John Salerno) Date: Sun, 11 May 2008 16:16:53 -0400 Subject: Is using range() in for loops really Pythonic? In-Reply-To: <41078222-aec0-4e8b-8a1f-945cdf814498@m73g2000hsh.googlegroups.com> References: <482657ca$0$25026$607ed4bc@cv.net> <41078222-aec0-4e8b-8a1f-945cdf814498@m73g2000hsh.googlegroups.com> Message-ID: <48275446$0$11628$607ed4bc@cv.net> XLiIV wrote: > The range() function returns a list and list is a sequence, isn't? I think you're missing the point. To me, there seems to be a fundamental difference between these two things: --- people = ['Sam', 'Bob', 'Fred'] for name in people: print name --- AND --- num = 33 for x in xrange(10): print num += 1 --- To me, the first example is a pure use of the for loop. You are iterating through an object and *using* the items you are stepping through. The second example, however, is simply doing something 10 times, and what it's doing has nothing to do with 'x' or xrange. So it seems like an abuse of the for loop. From castironpi at gmail.com Tue May 6 23:52:00 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 6 May 2008 20:52:00 -0700 (PDT) Subject: Reversing a dict? References: <6e3fdb8c-687f-42b6-b544-19c88950cc00@q1g2000prf.googlegroups.com> Message-ID: On May 6, 10:20?am, krumbleb... at gmail.com wrote: > Hi - further to my earlier query regarding partial matches (which with > all your replies enabled me to advance my understanding, thanks), I > now need to reverse a dict. > > I know how to reverse a list (with the reverse method - very handy), > but it doesn't seem possible to reverse a dict. It is not. Dictionaries provide constant time add and remove, -not- order. Are you sorting based on key or value? If you want a sorted state and sorted remove, use the 'bisect' module. > I suspect what I need to do is somehow go from: > > thelist=list(thedict) > thelist.reverse() > thedict=dict(thelist) > > Does anyone know how to convert / or reverse a dict? > > thanks > > kb. From bj_666 at gmx.net Fri May 9 05:52:03 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 9 May 2008 09:52:03 GMT Subject: the lvalue curse? let's play with this crazy idea ;) References: <68618c8b-f17e-496a-9092-5e2cd16b365b@p25g2000hsf.googlegroups.com> Message-ID: <68il63F2su97jU5@mid.uni-berlin.de> On Fri, 09 May 2008 02:13:34 -0700, XLiIV wrote: > Let's take a look at two ways of thinking... > the standard one which is well-known and loved by almost everyone :) > and that crazy concept below which suprised evan me :wacko: > > > import time > > ftime = time.time() > localtime = time.localtime(ftime) > localtime = list(localtime[:3]) > localtime = [str(i) for i in localtime] > print '-'.join(localtime) > > > It's harder to read than the below concept, isn't? > Maybe I didn't used to this way of thinking yet. I hope it'll change > soon or i'll quit ;) Maybe it's also harder to read than this:: print '-'.join(map(str, time.localtime()[:3])) Of course, if you don't mind the extra padding zeroes in day and month:: print time.strftime('%Y-%m-%d') > > time.time() -> ftime -> time.localtime() -> p -> p[:3] -> g -> list(g) > -> '-'.join() > You are a little bit inconsistent with the arguments. `g` is explicitly mentioned in ``list(g)``. But why the intermediate names at all? > My example conclusion and not-ansewered-yet question... > -it's nice to read and choosing the good names to variables aren't so > important > -what is the purpose of the variables here? :) Exactly. But look at my snippet above: No intermediate names either. > I realize that there is no chance to implement it, but I really want > to share it :] Maybe you should look into languages like SmallTalk or Io where everything is done with method calls. Your example in Io:: Date now do("#{year}-#{month}-#{day}" interpolate linePrint) Ciao, Marc 'BlackJack' Rintsch From admin at remembernobody.com Fri May 2 05:34:27 2008 From: admin at remembernobody.com (admin at remembernobody.com) Date: Fri, 2 May 2008 02:34:27 -0700 (PDT) Subject: Python documentation Message-ID: <02e9821d-10db-4164-bdf7-4285ee659fbb@w74g2000hsh.googlegroups.com> Hello, I have been learning python for some time using the dive into python book. I am interested to know if anyone can recommend a book which covers more advanced topics like threading and potentially GUI style coding. Regards, Ronald From bruno.42.desthuilliers at websiteburo.invalid Tue May 20 03:19:52 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 20 May 2008 09:19:52 +0200 Subject: Using Python for programming algorithms In-Reply-To: References: <48315082$0$24599$426a74cc@news.free.fr> <62884fc6-6c74-4477-91de-7b7689b5fa75@m44g2000hsc.googlegroups.com> <21d1d960-110c-4d70-99f5-7ce47c184544@k13g2000hse.googlegroups.com> Message-ID: <48327b93$0$15299$426a74cc@news.free.fr> Henrique Dante de Almeida a ?crit : > On May 19, 5:35 pm, "bruno.desthuilli... at gmail.com" > wrote: >>> The situation would be simpler if there were good well-known toolkits >>> for optimization in python (like numpy for matrix operations), but >>> that's not the case. >> There's at least Psyco (if you're willing and able to restrict >> yourself from using some of the most dynamic parts of Python - which >> might not be a problem here). One could also mention stuff like Pyrex >> and Cython. > > I meant toolkits for "optimization problems", not "code > optimization". oops, sorry. From castironpi at gmail.com Wed May 14 12:58:46 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 14 May 2008 09:58:46 -0700 (PDT) Subject: What is self.file = file for? References: <482a9438$0$21057$426a34cc@news.free.fr> Message-ID: <08469c91-45f2-481e-8281-44f490e851f2@a1g2000hsb.googlegroups.com> On May 14, 2:26?am, Bruno Desthuilliers wrote: > afrobeard a ?crit : > > (top-post corrected. Please, do not top-post). > > > > > > > On May 14, 3:08 am, wxPytho... at gmail.com wrote: > >> Hello! > > >> I have trouble understanding something in this code snippet: > > >> class TextReader: > >> ? ? """Print and number lines in a text file.""" > >> ? ? def __init__(self, file): > >> ? ? ? ? self.file = file > >> ? ? ? ? . > >> ? ? ? ? . > >> ? ? ? ? . > > >> When would you do a thing like ?self.file = file ?? I really don't > >> find an answer on this. Please help me understand this. > > > If you are familiar to C++ or a similar language, the concept of the > > this pointer might not be alien to you. self in this context is > > basically a reference to the class itself. > > Nope. It's a reference to the instance. > > > Hence self.file is creating > > a class member > > Nope. It's setting an instance attribute. > > > and setting to the input from file. > > > As Gary pointed out, during initialization, only the latter parameter > > i.e. file is being passed to __init__ > > Nope. Obviously, both parameters are passed - else it just wouldn't > work. Given an object 'obj' instance of class 'Cls', you can think of > obj.method(arg) as a convenient shortcut for Cls.method(obj, arg).- Hide quoted text - > > - Show quoted text - I am at the point of open-source, and I agree. From jurgenex at hotmail.com Fri May 9 03:01:02 2008 From: jurgenex at hotmail.com (Jürgen Exner) Date: Fri, 09 May 2008 07:01:02 GMT Subject: The Importance of Terminology's Quality References: <68i6b5F2soauaU1@mid.individual.net> <68ia3oF2t5308U1@mid.individual.net> Message-ID: <7ft7249u3a7vmgm50pi7sfcp7m8fevoq2m@4ax.com> "Waylen Gumbal" wrote: > so why not just skip the thread or toss the OP in your >killfile so you don't see his postings. Done years ago. >If others want to discuss his >topics, who are you or I to tell them not to? They are very welcome to do so in an appropriate NG for those topics. jue From exarkun at divmod.com Mon May 12 22:35:08 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 12 May 2008 22:35:08 -0400 Subject: Popen pipe hang In-Reply-To: <64cf0966-5e39-473c-8923-7a81ff99f905@u6g2000prc.googlegroups.com> Message-ID: <20080513023508.6859.732328355.divmod.quotient.62766@ohm> On Mon, 12 May 2008 17:35:44 -0700 (PDT), schickb wrote: >I'm trying to pipe data that starts life in an array('B') object >through several processes. The code below is a simplified example. The >data makes it through, but the wait() always hangs. Is there a better >way to indicate src.stdin has reach EOF? > >from subprocess import Popen, PIPE >from array import array > >arr = array('B') >arr.fromstring("hello\n") > >src = Popen( ["cat"], stdin=PIPE, stdout=PIPE) >dst = Popen( ["cat"], stdin=src.stdout) >arr.tofile(src.stdin) >src.stdin.close() >dst.wait() Alas, you haven't actually closed src's standard input. Though you did close src.stdin, you didn't close the copy of it which was inherited by dst! So though the file descriptor is no longer open in your main process, it remains open due to the reference dst has to it. You can fix this by having Popen close all file descriptors except 0, 1, and 2 before it execs cat - pass close_fds=True to the 2nd Popen call and you should get the behavior you want. Jean-Paul From mensanator at aol.com Fri May 23 14:44:19 2008 From: mensanator at aol.com (Mensanator) Date: Fri, 23 May 2008 11:44:19 -0700 (PDT) Subject: Why is math.pi slightly wrong? References: <6b7a57e3-0f0e-4b52-a2e8-246491dd0e7f@x35g2000hsb.googlegroups.com> <48365893$0$11617$607ed4bc@cv.net> Message-ID: <7a73869e-6091-430b-a68e-eef7d831ea5d@59g2000hsb.googlegroups.com> On May 23, 12:39?am, Andrew Lee wrote: > Mensanator wrote: > > On May 22, 11:32 am, "Dutton, Sam" wrote: > >> I've noticed that the value of math.pi -- just entering it at the interactive prompt -- is returned as 3.1415926535897931, whereas (as every pi-obsessive knows) the value is 3.1415926535897932... (Note the 2 at the end.) > > >> Is this a precision issue, or from the underlying C, or something else? How is math.pi calculated? > > > If you actually need that many digits, use a different library. > > >>>> import gmpy > > >>>> print gmpy.pi(64) # 64 bit precision > > 3.14159265358979323846 > >>>> print gmpy.pi(128) # 128 bit precision > > 3.141592653589793238462643383279502884197 > >>>> print gmpy.pi(16384) # 16384 bit precision > > 3.14159265358979323846264338327950288419716939937510582097494459 > > 23.... > > Heh! > > I wonder who needs that many digits? Pi digits specifically, or that many digits in general? I generally don't use pi, but I routinely work with numbers having that many digits. > > Certainly not number theorists (they need a LOT more). That depends on the problem. What's important to the number theorist is not how many digits there are, but the fact that every single one of them is significant. If pi is needed, the mantissa must have as many digits as the number to avoid loss of significance. For example, in the Collatz Conjecture, there is a nice closed form equation to tell you the ith, kth Generation Type [1,2] Mersenne Hailstone: a(i,k) = 2**(6*((i-1)*9**(k-1)+(9**(k-1)-1)/2+1)-1)-1 Which for a modest request like a(1,6) returns a number with 53,338 decimal digits. And you can't even compute the 11th generation without getting an "Outrageous Exponent" exception (the exponent exceeded 32 bits). Now, it's true you can't count up to such a number, but you can readily determine its Collatz Sequence as they are logarithmic (for a(1,6) the sequence contains 854,697 odd numbers and about twice that many even numbers). And since a(1,6) has only 177,149 bits, it's easy to verify that it is, indeed, the first of the infinite members of the 6th generation. > Certainly not > physicists -- they need about 30 digits to be within 1% of any > measurement from molecules to galaxies. ?Certainly not engineers, they > need half the digits that physicists need. ?Cryptographers are making a > dire mistake if they are using PI in any computations (possible > exception for elliptic curves -- see number theorists, above) ... so -- > other than PI-philes, who needs PI to thousands of digits?- Hide quoted text - > > - Show quoted text - From castironpi at gmail.com Wed May 7 13:57:41 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 7 May 2008 10:57:41 -0700 (PDT) Subject: letter frequency counter / your thoughts.. References: <5a9a4a7e-a4a3-4a59-a80f-01d44bc69a86@w1g2000prd.googlegroups.com> <4821e745$0$24414$5fc3050@news.tiscali.nl> Message-ID: <36a899fb-4480-437e-b1f5-0c4676575bbe@r66g2000hsg.googlegroups.com> On May 7, 12:30?pm, Paul Melis wrote: > umpsu... at gmail.com wrote: > > Here is my code for a letter frequency counter. ?It seems bloated to > > me and any suggestions of what would be a better way (keep in my mind > > I'm a beginner) would be greatly appreciated.. > > Not bad for a beginner I think :) > > > > > > > def valsort(x): > > ? ?res = [] > > ? ?for key, value in x.items(): > > ? ? ? ? ? ?res.append((value, key)) > > ? ?return res > > > def mostfreq(strng): > > ? ?dic = {} > > ? ?for letter in strng: > > ? ? ? ? ? ?if letter not in dic: > > ? ? ? ? ? ? ? ? ? ?dic.setdefault(letter, 1) > > ? ? ? ? ? ?else: > > ? ? ? ? ? ? ? ? ? ?dic[letter] += 1 > > ? ?newd = dic.items() > > ? ?getvals = valsort(newd) > > ? ?getvals.sort() > > ? ?length = len(getvals) > > ? ?return getvals[length - 3 : length] > > > thanks much!! > > Slightly shorter: > > def mostfreq(strng): > ? ? ?dic = {} > ? ? ?for letter in strng: > ? ? ? ? ?if letter not in dic: > ? ? ? ? ? ? ?dic[letter] = 0 > ? ? ? ? ?dic[letter] += 1 > ? ? ?# Swap letter, count here as we want to sort on count first > ? ? ?getvals = [(pair[1],pair[0]) for pair in dic.iteritems()] > ? ? ?getvals.sort() > ? ? ?return getvals[-3:] > > I'm not sure if ?you wanted the function mostfreq to return the 3 most > frequent letters of the first 3 letters? It seems to do the latter. The > code above uses the former, i.e. letters with highest frequency. > > Paul- Hide quoted text - > > - Show quoted text - I think I'd try to get a deque on disk. Constant indexing. Store disk addresses in b-trees. How long does 'less than' take? Is a sector small, and what's inside? From torriem at gmail.com Sun May 11 12:34:50 2008 From: torriem at gmail.com (Michael Torrie) Date: Sun, 11 May 2008 10:34:50 -0600 Subject: Module python-magic on/for Windows? In-Reply-To: References: Message-ID: <4827202A.5030104@gmail.com> Larry Hale wrote: > Now I *presume* my problem (at this point) is that I need to have > libmagic named as "magic1.dll" -wherever- this module is looking for > it. I'm just not sure, let alone if this is true, WHERE Python/ > modules expect to find such things. > > Also, which version(s)/file(s) should be placed where, or...?? The dll you are looking for is here: http://downloads.sourceforge.net/gnuwin32/file-4.21-bin.zip?modtime=1180175868&big_mirror=1 The .dll.a file you mention is just a linker stub for when you want to compile against it (as you are doing when building python-magic). The magic1.dll file in the file-4.21-bin.zip package should be placed anywhere in the path. Since you'll be using it with python, you could probably stick it in the python25/bin folder (where ever your python system is installed). From regnarg at seznam.cz Tue May 13 12:59:22 2008 From: regnarg at seznam.cz (Filip =?utf-8?B?xaB0xJtkcm9uc2vDvQ==?=) Date: Tue, 13 May 2008 18:59:22 +0200 Subject: Fill memeory with endless loop? In-Reply-To: <252c17a9-01a6-4abe-9515-2507e0e50a20@l64g2000hse.googlegroups.com> References: <252c17a9-01a6-4abe-9515-2507e0e50a20@l64g2000hse.googlegroups.com> Message-ID: <20080513165922.GA10304@sirius> On ?t, kv? 13, 2008 at 06:49:33 +0200, globalrev wrote: > if i do something like > while 1: > print "x" > > will the program ever stop because it runs out of memory? No, there is no reason to run out of memory. This will simply make an everlasting x-printer and there is no need to store anything (except output buffers, terminal scrollback, etc., but all of this is temporary and of limited size). In case of adding elements to a list, the memory usage can, of course, grow unlimitedly. On linux, if the process eats up too much memory, it gets killed. I do not know about windows, but they would probably crash with a BSOD or something of that sort. From wxPythoner at gmail.com Sat May 10 16:56:13 2008 From: wxPythoner at gmail.com (wxPythoner at gmail.com) Date: Sat, 10 May 2008 13:56:13 -0700 (PDT) Subject: Mathematics in Python are not correct References: <52c855d8-5609-43e0-b98f-9fa87b2808c2@m3g2000hsc.googlegroups.com><200805081914.06459.kyrie@uh.cu> Message-ID: I am stunned that this simple misunderstanding of mine ended in a mathematical clash of a sort. :) You guys really blew me away wih your mathematical knowledge. And also the 0**0 is a thing I've never thought about trying, until now that is. If the mathematical rule is that EVERYTHING raised to the power of 0 is 1, then we should accept that, even in the case of 0**0. This is just the way it is. I have two another interesting things to discuss about, for which I'll open new posts on this group. Look for "Python doesn't recognize quote types" and "Python, are you ill?". From hat at se-162.se.wtb.tue.nl Thu May 15 06:48:49 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Thu, 15 May 2008 12:48:49 +0200 Subject: List behaviour References: Message-ID: On 2008-05-15, Gabriel wrote: > Hi all > > Just wondering if someone could clarify this behaviour for me, please? > >>>> tasks = [[]]*6 >>>> tasks > [[], [], [], [], [], []] >>>> tasks[0].append(1) >>>> tasks > [[1], [1], [1], [1], [1], [1]] > > Well what I was expecting to end up with was something like: > ?>>> tasks > [[1], [], [], [], [], []] > > > I got this example from page 38 of Beginning Python. This is a more complicated case of a = [] b = a a.append(1) print b # Will print "[1]" This is the case, because both a and b refer to the same list data-value. In your case, basically what you are doing is a = [] # a is an empty list (introduced for easier explanation) tasks = [a] # tasks is a list with 1 'a' tasks = tasks*6 # you create 5 additional references to 'a' in 'tasks ie tasks is now the equivalent of [a, a, a, a, a, a]. It refers to the same 'a' list 6 times. When you print 'tasks', you actually print the same 'a' value 6 times. in particular, tasks is **NOT** a,b,c,d,e,f = [], [], [], [], [], [] # create 6 different empty list values tasks2 = [a, b, c, d, e, f] although when you print both tasks, you won't see the difference. Next, 'tasks[0]' refers to the first list element, that is, value 'a'. To that list you append an element. In other words, you do "a.append(1)". However, since tasks has 6 references to the same list 'a', all its members appear to be changed (but you are really displaying the same value 6 times). You can query this equality with 'is': print tasks[0] is tasks[1] # will print 'True' print tasks2[0] is tasks2[1] # Will print 'False' Sincerely, Albert From vivainio at gmail.com Sat May 24 05:43:23 2008 From: vivainio at gmail.com (Ville M. Vainio) Date: Sat, 24 May 2008 09:43:23 GMT Subject: Storing objects in relational database References: <03a17198-3eb2-438e-97c9-db18c0c24a80@c65g2000hsa.googlegroups.com> Message-ID: <87r6bsvxz7.fsf@gmail.com> "bruno.desthuilliers at gmail.com" writes: > I don't know if you'd label it 'elegant', but as far as I'm > concerned, storing serialized objects as blobs in a relational > database is mostly non-sense. If I use a relational database, it's > because it is a *relational* database. If you want an OODB, then we > have the ZODB, Durus and a couple others. ... not to forget object-relational mappers like SQLAlchemy, SQLObject... From wizzardx at gmail.com Sun May 4 13:37:04 2008 From: wizzardx at gmail.com (David) Date: Sun, 4 May 2008 19:37:04 +0200 Subject: Image grab in Python In-Reply-To: <18c1e6480805041033v1ae0a3adra3710e1414da0110@mail.gmail.com> References: <18c1e6480805040741p8c76a33q2f5464932b6524ff@mail.gmail.com> <18c1e6480805041033v1ae0a3adra3710e1414da0110@mail.gmail.com> Message-ID: <18c1e6480805041037p5147d2a7rfe9f6b576985d30b@mail.gmail.com> > > Another way would be to listen to all events sent through X, and act > based on the mouse events. VNC does something similar. > See the 'record_demo.py' example that comes with python-xlib. From lists at cheimes.de Tue May 20 16:43:53 2008 From: lists at cheimes.de (Christian Heimes) Date: Tue, 20 May 2008 22:43:53 +0200 Subject: List of disk drives on Windows? In-Reply-To: References: <2008052013180816807-bob@passcalnmtedu> Message-ID: <48333809.2020903@cheimes.de> Mike Driscoll schrieb: > On May 20, 2:45 pm, Tim Golden wrote: >> Bob Greschke wrote: >>> This MUST have been asked before, but I can't seem to Google the right >>> thing. How can I get a list of drives on a Windows box, like ["C:\", >>> "D:\"], like I can if I do something like listdir("/Volumes") on a Mac? >> A couple of options to get the ball rolling: >> >> 1) win32api.GetLogicalDriveStrings() > > > I gave this a go to see how it worked and ti gave me this: > > 'A:\\\x00C:\\\x00D:\\\x00G:\\\x00I:\\\x00L:\\\x00P:\\\x00Q:\\\x00R:\\ > \x00U:\\\x00X:\\\x00Y:\\\x00Z:\\\x00' > > Not exactly what I expected. Do I have to parse out the "\\\x00" > myself or is there an information level switch I should add? The data is separated by NUL bytes. Split it with \x00 and you'll get a list of drives: >> "A:\\\x00C:\\\x00D:\\\x00G:\\\x00I:\\\x00L:\\\x00P:\\\x00Q:\\\x00R:\\\x00U:\\\x00X:\\\x00Y:\\\x00Z:\\\x00".split("\x00") ['A:\\', 'C:\\', 'D:\\', 'G:\\', 'I:\\', 'L:\\', 'P:\\', 'Q:\\', 'R:\\', 'U:\\', 'X:\\', 'Y:\\', 'Z:\\', ''] Christian From straton at lampsacos.demon.co.uk Thu May 22 05:54:19 2008 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Thu, 22 May 2008 10:54:19 +0100 Subject: simple way to touch a file if it does not exist In-Reply-To: References: Message-ID: After os.path.exists, you need to check it _is_ a file, and not a directory. Giampaolo Rodola' wrote: > On 22 Mag, 01:15, Nikhil wrote: >> what are the simple ways? >> I could think of os.open(), os.exec(touch file) >> >> are there any simpler methods? > > Just use os.path.exists to check for file existence and open() as > replacement for touch. > >>>> import os >>>> if not os.path.exists('file'): > ... open('file', 'w').close() > ... > > > --- Giampaolo > http://code.google.com/p/pyftpdlib/ From pistacchio at gmail.com Thu May 8 06:02:58 2008 From: pistacchio at gmail.com (pistacchio) Date: Thu, 08 May 2008 12:02:58 +0200 Subject: PHP + TinyButStrong Python replacement References: <68dp9jF2sko92U1@mid.uni-berlin.de> <1693070c-76de-4fa7-8337-155996631fdd@m44g2000hsc.googlegroups.com> Message-ID: bruno.desthuilliers at gmail.com ha scritto: > On 7 mai, 16:17, pistacchio wrote: >> George Sakkis ha scritto: > (snip) >>> What does it matter if it's a single file or a dozen under a package ? >>> "Installation" for pure Python packages can be as simple as copying >>> the package under any directory in your PYTHONPATH. >> well, it doesn't matter if it's a single file or a package, but it >> _does_ matter if you have to put them under the path where python is >> installed because, in a typical shared web hosting environment (such the >> one that i use) you don't have access to system directories. > > You *never* have to install anything in the default path - install > your python libs wherever you want, and just make sure this wherever > is in your python path (usually via the PYTHONPATH environment > variable). > again, in a shared environment, you don't have access to environment variables. all you can do is copy files in your own little directory, and that's it. this directory is never something like /share/python, but something like /home/averagejoe. and /home/averagejoe is not usually in the PYTHONPATH >>> Check out Mako (http://www.makotemplates.org/), it's pretty powerful >>> and fast. >> woudl you suggest mako over cheetah? > > As far as I'm concerned, I would. Now if you're looking for a > somewhat barebone MVC framework, you may want to have a look at > web.py. > i've tried mako. sees to work fine for me, both for its potential and for its "installation" method. in fact i just copied it under my own directory /home/averagejoe test.py /mako mako stuff and the following testcase worked well: from mako.template import Template mytemplate = Template("hello world!") print mytemplate.render() can i do the same with web.py? mind that i work under an apache environment (mod_python). now, back to mako. can you provide an example of blocks and nested blocks in mako? the documentation doesn't seem to be too clear in this reguard. for example, if i want to show a table with a list of restaurants (gathered from a db query), i can construct a template like this: % for rest in restaurants: ${rest} % endfor
but what if if each restaurant has a list of dishes (pasta, pizza, meat, pie) and some (or each) dish has the ingrediets? is it just like embedding pure python into the template ( like $(rest['dish']) and $rest['dish']['ingredient']) )? thanks for you interest From sisson.j at gmail.com Thu May 1 22:55:15 2008 From: sisson.j at gmail.com (J Sisson) Date: Fri, 2 May 2008 02:55:15 +0000 Subject: #!/usr/bin/env python vs. #!/usr/bin/python In-Reply-To: References: Message-ID: <4297a9020805011955l5c9b4a39o256be5c4455980c8@mail.gmail.com> The first method allows python to be installed in an alternate location (i.e. /usr/local/bin). "env" in this case is being used to launch python from whatever location python is installed to. I like to think of it as an "abstraction" of the python location to make it "multiplatform-friendly" since not all Unix systems put python in /usr/bin. On Fri, May 2, 2008 at 1:36 AM, Yves Dorfsman wrote: > On UNIX, some people use > #!/usr/bin/env python > > While other use > #!/usr/bin/python > > Why is one preferred over the other one ? > > Thanks. > > -- > Yves. > http://www.SollerS.ca > -- > http://mail.python.org/mailman/listinfo/python-list > -- Computers are like air conditioners... They quit working when you open Windows. -------------- next part -------------- An HTML attachment was scrubbed... URL: From noah at noah.org Mon May 5 18:22:54 2008 From: noah at noah.org (Noah) Date: Mon, 5 May 2008 15:22:54 -0700 (PDT) Subject: get the pid of a process with pexpect References: Message-ID: On May 5, 7:18 am, Karim Bernardet wrote: > ssh_tunnel = pexpect.spawn (tunnel_command % globals()) > ... > print ssh_tunnel.pid > > but ssh_tunnel is not the pid of the ssh tunnel > > Is there a way to get it using pexpect ? You will notice that you can't get this information even from the shell. This does not work of course: ssh -f -N -L 81:localhost:80 noah at www.example.com echo $! However, this seems to work, but I don't trust it. Certainly it isn't a real daemon, but this work OK for you if you only need to manage the tunnel for the duration of your script. Notice that now Bash had the PID in $! variable: ssh -N -L 81:localhost:80 noah at www.example.com & TUNNEL_PID=$! echo $TUNNEL_PID What command-line are you using for 'tunnel_command'? This is hard because SSH does not provide a way to get the PID of the tunnel if you request ssh to go to the background (see the -f option). I always considered this a bug because it makes scripting hard. Even if you start the tunnel from a shell you can't use $! to get the PID because the daemonizing is initiated by ssh. This is not the same use using the shell to put a command into the background, so the shell won't know anything about the PID. I'm not sure if you can put ssh into the background using the shell and still have the tunnel work. So you might start a tunnel something like this: ssh -f -N -L 80:localhost:80 username at www.example.com But can you also do something like this? ssh -N -L 80:localhost:80 username at www.example.com & echo $! And for that to even work you will have to use Pexpect to start bash. Remember, Python doesn't start your command in a subshell, so you have to specify it if you want. So your tunnel command would have to be something like this: tunnel_command = '''bash -c "ssh -N -L ...foo... &"''' ssh_tunnel = pexpect.spawn (tunnel_command % globals()) -- Noah From szhorvat at gmail.com Sat May 3 12:50:34 2008 From: szhorvat at gmail.com (=?ISO-8859-1?Q?Szabolcs_Horv=E1t?=) Date: Sat, 03 May 2008 18:50:34 +0200 Subject: Feature suggestion: sum() ought to use a compensated summation algorithm Message-ID: I did the following calculation: Generated a list of a million random numbers between 0 and 1, constructed a new list by subtracting the mean value from each number, and then calculated the mean again. The result should be 0, but of course it will differ from 0 slightly because of rounding errors. However, I noticed that the simple Python program below gives a result of ~ 10^-14, while an equivalent Mathematica program (also using double precision) gives a result of ~ 10^-17, i.e. three orders of magnitude more precise. Here's the program (pardon my style, I'm a newbie/occasional user): from random import random data = [random() for x in xrange(1000000)] mean = sum(data)/len(data) print sum(x - mean for x in data)/len(data) A little research shows that Mathematica uses a "compensated summation" algorithm. Indeed, using the algorithm described at http://en.wikipedia.org/wiki/Kahan_summation_algorithm gives us a result around ~ 10^-17: def compSum(arr): s = 0.0 c = 0.0 for x in arr: y = x-c t = s+y c = (t-s) - y s = t return s mean = compSum(data)/len(data) print compSum(x - mean for x in data)/len(data) I thought that it would be very nice if the built-in sum() function used this algorithm by default. Has this been brought up before? Would this have any disadvantages (apart from a slight performance impact, but Python is a high-level language anyway ...)? Szabolcs Horv?t From mensanator at aol.com Mon May 12 15:02:41 2008 From: mensanator at aol.com (Mensanator) Date: Mon, 12 May 2008 12:02:41 -0700 (PDT) Subject: Learning Python for no reason References: <0383f3b8$0$27282$c3e8da3@news.astraweb.com> Message-ID: <4ae5beb9-40c4-42d5-b22e-612297c7d014@f36g2000hsa.googlegroups.com> On May 12, 12:27?pm, "John Salerno" wrote: > Just something that crosses my mind every time I delve into "Learning > Python" each night. Does anyone see any value in learning Python when you > don't need to for school, work, or any other reason? I mean, sure, there's > value in learning anything at any time, but for something like a programming > language, I can't help but feel that I will be mostly unable to use what I > learn simply because I have no reason to use it. > > The *process* of learning is enough fun for me, and every now and then I do > find a small use for Python that really pays off, but for the most part I'm > wondering what people's thoughts are as far as simply learning it for the > sake of learning. Does it seem like a silly endeavor to most people? Did > anyone here learn a programming language when you didn't need to? If so, how > much and in what capacity did you use it after you learned it? > > Hopefully this question even makes sense! Seems silly to learn a programming language for it's own sake. Why would you want to learn something you aren't going to use? My attitude is I may not have an immediate use planned, but such uses should become apparent as I learn more. For example, I collect movie ticket sales stats from The Internet Movie Database. That meant going to their site, finding the page that has the stats for a certain week, copy the page, fix it up a bit and then import it into Access. And since I only got around to updating once or twice a year, it was a labor intensive process. But in the course of learning Python, it became apparent that I could - have Python scrape the web pages - process the raw data - do the database inserts I never thought of those things when I started Python, but if you pay attention to what you're "learning", these kind of things should jump out at you. From rschroev_nospam_ml at fastmail.fm Mon May 19 09:30:52 2008 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Mon, 19 May 2008 15:30:52 +0200 Subject: Using Python for programming algorithms In-Reply-To: <48314dd0$0$32138$426a34cc@news.free.fr> References: <98fa5fa3-45ae-4df1-9fd3-1a227641244f@p25g2000hsf.googlegroups.com> <48314dd0$0$32138$426a34cc@news.free.fr> Message-ID: Bruno Desthuilliers schreef: > 1/ being interpreted or compiled (for whatever definition of these > terms) is not a property of a language, but a property of an > implementation of a language. > > 2/ actually, all known Python implementations compile to byte-code. > You keep saying that, and in theory you're right. But I'm still inclined to disagree with it, since the practical reality is different. Python is indeed compiled to byte code, but if you compare that byte code with assembly code you'll see that there's a whole world of difference between the two, largely because of the dynamical nature of Python. Fact is that Python was designed from the start to run on a virtual machine, not on the native hardware. C OTOH was designed to be compiled to assembly code (or directly to machine code) and as a result there are no (or virtually) no implementations that interpret C or compile it to bytecode. I love Python, but IMHO it's a bit silly to maintain that the fact that Python compiles to byte code instead of assembly code/machine code is purely a matter of implementation; on the contrary, I believe it's a result of its design. I also think that there's a large difference between byte code and machine code (in Python's case; I haven't looked at other languages), and that it's a bit silly to try to trivialize that difference. -- The saddest aspect of life right now is that science gathers knowledge faster than society gathers wisdom. -- Isaac Asimov Roel Schroeven From duncan.booth at invalid.invalid Thu May 1 03:36:21 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 1 May 2008 07:36:21 GMT Subject: computing with characters References: <474df$48180e0b$541fc2ec$12128@cache1.tilbu1.nb.home.nl> <481813E2.2030302@islandtraining.com> <61f41$48181d87$541fc2ec$29688@cache3.tilbu1.nb.home.nl> <2d6af$48183337$541fc2ec$23598@cache2.tilbu1.nb.home.nl> <87y76vyamr.fsf@physik.rwth-aachen.de> <74c070ce-1b8f-4746-9d1c-ac2227aaf515@y21g2000hsf.googlegroups.com> Message-ID: George Sakkis wrote: > On Apr 30, 5:06?am, Torsten Bronger > wrote: >> Hall?chen! >> >> SL writes: >> > "Gabriel Genellina" schreef in bericht >> >news:mailman.365.1209541507.12834.python-list at python.org... >> >> >> En Wed, 30 Apr 2008 04:19:22 -0300, SL escribi?: And >> >> that's a very reasonable place to search; I think chr and ord are >> >> builtin functions (and not str methods) just by an historical >> >> accident. (Or is there any other reason? what's wrong with >> >> "a".ord() or str.from_ordinal(65))? >> >> > yes when you know other OO languages you expect this. Anyone know >> > why builtins were chosen? Just curious >> >> *Maybe* for aesthetical reasons. ?I find ord(c) more pleasent for >> the eye. ?YMMV. >> >> The biggest ugliness though is ",".join(). ?No idea why this should >> be better than join(list, separator=" "). ? > > Seconded. While we're at it, a third optional 'encode=str' argument > should be added, to the effect of: > > def join(iterable, sep=' ', encode=str): > return sep.join(encode(x) for x in iterable) > > I can't count the times I've been bitten by TypeErrors raised on > ','.join(s) if s contains non-string objects; having to do > ','.join(map(str,s)) or ','.join(str(x) for x in s) gets old fast. > "Explicit is better than implicit" unless there is an obvious default. > I'm afraid I don't agree with you on this. Most places where I use join I already know the type of the values being joined. In those few cases where I want to join non strings, or want to do some other processing on the values the generator comprehension is easy and has the advantage that I can use a more complex expression than a simple function call without having to wrap it in a lambda or otherwise contort things: e.g. comma.join(x[1] for x in s) vs. comma.join(s, encode=operator.itemgetter(1)) or comma.join(s, encode=lambda x: x[1]) Plus of course, you aren't going to be writing ','.join(str(x) for x in s) more than once in any given program before you extract it out to a function, are you? From musiccomposition at gmail.com Thu May 29 22:58:31 2008 From: musiccomposition at gmail.com (Benjamin) Date: Thu, 29 May 2008 19:58:31 -0700 (PDT) Subject: New chairman References: <3720fb99-ac37-469b-b8ce-ece3ed27b8e5@m36g2000hse.googlegroups.com> <6a2ndjF35q29pU1@mid.uni-berlin.de> <0b18caad-4fbf-46e8-887f-ce29963e24a0@m3g2000hsc.googlegroups.com> Message-ID: On May 27, 10:48 am, Sverker Nilsson wrote: > Good luck to you to. Its just that it .. well it has never been easy > for me to introduce Python at work. This py3k, if I like it or not, is > not making it easier. > > Praktical, pragmatic, you know --- as I said, its not broken so lets > brake it > > I just try to get things to work. And with some style too. Their > connected. I think a 6 cylinder engine is one of the most stylist > things there are. And when I was at a museum in Stocholm, I saw Henry > Fords original enginge and was amazed, it looks just like the one in > dads car. > > Its not about changing and yes I dislike py3k, till somebody can > convince me otherwise > > Guido just seems to not care to post here anyways, so we can try to > make our own branch/business Do you have any idea how brilliant Guido is? The reason he's not here tending to your Python war wounds is that he's busy making important decisions on python-dev and python-3000. Maintaining a programming language is like raising 50 very unruly children, and Guido has done an excellent job. From http Wed May 21 11:43:40 2008 From: http (Paul Rubin) Date: 21 May 2008 08:43:40 -0700 Subject: compressing short strings? References: <7xy7658k8o.fsf_-_@ruckus.brouhaha.com> <1%WYj.78116$%15.75349@bignews7.bellsouth.net> Message-ID: <7xwslnzmqb.fsf@ruckus.brouhaha.com> "inhahe" writes: > i don't see anybody mentioning huffman encoding. i think it just works per > byte, so it's not as tight as gzip or whatever. but it sounds like it would > be easy to implement and wouldn't require any corpus-wide compression > information. except a character frequency count if you wanted to be optimal. In principle you could do it over digraphs but I tried that once and it didn't help much. Basially -because- it doesn't use any corpus-wide compression information, it doesn't compress anywhere near as well as LZ, DMC, or whatever. From jeffober at gmail.com Thu May 22 08:10:42 2008 From: jeffober at gmail.com (Jeff) Date: Thu, 22 May 2008 05:10:42 -0700 (PDT) Subject: merging the global namespaces of two modules References: Message-ID: Can you be more specific? modA and modB don't import from each other but both need to access objects in the global namespace of what module? The controlling application? Or do you mean that, for example, modA needs to access some functions in modB, but does not have import statements to do so, and you want the controlling program to do the imports for it? If that is the case, that is bad programming practice in Python. Python is not C and you can't just share header files :) If you need to avoid recursive import conflicts, you can perform your imports at the top of functions that use objects from another module. Jeff http://www.artfulcode.net From yves at zioup.com Fri May 9 11:11:20 2008 From: yves at zioup.com (Yves Dorfsman) Date: Fri, 09 May 2008 15:11:20 GMT Subject: slicing lists In-Reply-To: References: Message-ID: castironpi at gmail.com wrote: > The only thing is, is there is another natural meaning to [a,b:c]. > > Counting grids on the diagonals, the rational set is well defined: > > 0: 0, 0 > 1: 1, 0 > 2: 0, 1 > 3: 2, 0 > 4: 1, 1 > 5: 0, 2 > 6: 3, 0 > 7: 2, 1 > ... > > Thencefore ( 2, 0 ) : ( 3, 0 ) is well defined. Thencefore, > > a,b:c,d > > is not; x[a,b:c,d]= x[a]+ x[b:c]+ x[d]. I'm not sure what you mean here. Could you give me a simple piece of code to show an example ? Yves. http://www.SollerS.ca From arituay at gmail.com Fri May 16 16:03:51 2008 From: arituay at gmail.com (Chad Wilhite) Date: Fri, 16 May 2008 16:03:51 -0400 Subject: IDE for Python In-Reply-To: References: Message-ID: <3c50a9820805161303l5d3dcfd5q5c8a95a5f82cd880@mail.gmail.com> On Fri, May 16, 2008 at 11:33 AM, Jonathan Barbero < jonathan.barbero at gmail.com> wrote: > Hi! > > I?m newbie with Python and to learn it better I want to use a good IDE to > concentrate on Python power. There is any IDE like Eclipse for Java for > Python? If not, what is the best Python?s IDE for you? > > Thanks, > > Jonathan. > > -- > http://mail.python.org/mailman/listinfo/python-list > Jonathan, PyDev is a Python plugin for Eclipse, here is a link to its SourceForge site: http://sourceforge.net/projects/pydev Chad -------------- next part -------------- An HTML attachment was scrubbed... URL: From tinnews at isbd.co.uk Wed May 14 10:17:08 2008 From: tinnews at isbd.co.uk (tinnews at isbd.co.uk) Date: 14 May 2008 14:17:08 GMT Subject: Python libraries for iCalendar, which one to use? Message-ID: <482af464$0$661$bed64819@news.gradwell.net> I am about to try writing a little Python utility to extract some data from an iCalendar file. A quick Google search turns up two possible libraries to use - vobject and "iCalendar package for Python". First question - have I missed any other (better?) ones? Second question - how do I choose which to use. Do I just use the obvious criteria like recent activity, has the methods I want etc. or is there some place that assigns official/respectability to a library? -- Chris Green From castironpi at gmail.com Tue May 13 09:02:13 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 13 May 2008 06:02:13 -0700 (PDT) Subject: I'm stuck in Python! Message-ID: Hi all. I am trying to write to the Python newsgroup. I doubt (aha, but doubt) that I have come to the right place. (Incoming "this"!) Is this the Python newsgroup? I heard it was called comp.lang.python. Now to repeat the subject line. I'm stuck in Python. Now that was fun. I will also try to enumerate simple screen savers (graphicals, graphiclizers). It may be profitable on some non-bank- breaking scale to compile the results. Shall I proceed? The risk is "overunity", such that one person can't be at liberty to live, which in some technical political arenas would be an "anarchy", but there are sufficiently many of those that I will too. Does anyone want such a list, or if not, is it at least fun and recreational to make it? The dollar would come along the lines of PowerPoint (name (tm)), so it may be free to do it, very entertaining, and peaceable. (As the above would show, you would be free to approach me to -buy-; I won't oversell.) I like programming. (And is Guido getting his fair share? I am prepared to share with him.) Check in his name. I want to try to ally with other programmers and make cool games, like Tron, that one party can make games for on a console, such as live obstacles, incl. tear-down, and certain people have to play from time to time. But you can't charge to do it, so it's a guaranteed game. (That in virtue of that I'm typing.) Advantages include microspacing of time. Very summer. Resemblances would include Dungeons & Dragons with multi-host, or multi-ref small-shooter sport-likers. The real-time is definitely attractive (duh). As for voice, it's not clear it's the most entertaining, but I just don't have a mic. However, forseeing, I return with sailing, but that's in 3-space and not even in code, as though we'd construct the Royal Navy and battle. But I think we can keep it well. Thing is, someone has to play it to keep a synch (keep from falling), and tap-outs would have to live. Side note: In political theory, this is known as the problem of nominating a successor. Would it stay afloat, even for long enough to make it worth the negatives, yes which do include tear-down and fall, invasion of privacy, and rights infrigement? I code in Python (get the callbacks), but configurable servers could spread the work out, using relays to put each person on each's own turf to be a ref. If you feed the roles, it could get really fun, and c-l-py is the appropriate place to start such a thing, both and ask if it's been done before. From inhahe at gmail.com Sun May 18 11:41:31 2008 From: inhahe at gmail.com (inhahe) Date: Sun, 18 May 2008 11:41:31 -0400 Subject: explain this function to me, lambda confusion References: <5cc7ef7a-dd21-4772-a7e3-765410f810bb@l17g2000pri.googlegroups.com> Message-ID: > > Both the responses offer lambda free alternatives. That's fine, and > given the terse documentation and problems that I had understanding > them, I would agree. So what applications are lambdas suited to? I > think the parameterised function model is one. > What else? i've hardly ever used lambdas since map() and filter() were replaced by list comprehension. two other uses I can think of for it are: using it as a sorting key (which takes a function and lambdas are perfect for that when a direct function isn't available. for example, lambda x: x.myName), and I made an irc bot once that certain events had a list of fuctions that would be called after that event. it was like being able to dynamically add and remove event handlers. for example what if you asked the user a question and you wanted to know for the next input whether it was from that user and was an answer to that question. sometimes the function to add would be very simple, so writing a def for it would just be ugly. From casey.mcginty at gmail.com Thu May 15 16:21:44 2008 From: casey.mcginty at gmail.com (Casey) Date: Thu, 15 May 2008 13:21:44 -0700 (PDT) Subject: Making Variable Text Output More Pythonic? Message-ID: <015e35b2-165c-4693-bf6c-38ad0cce7553@t12g2000prg.googlegroups.com> Hi, I have some classes that print variable outputs depending on their internal state, like so: def __str__(self): out = [] if self.opt1: out += ['option 1 is %s' % self.opt1'] if self.opt2: out += ['option 2 is %s' % self.opt2'] .... return '\n'.join(out) Is there any way to make this cleaner? From aspersieman at gmail.com Mon May 26 05:41:26 2008 From: aspersieman at gmail.com (Aspersieman) Date: Mon, 26 May 2008 11:41:26 +0200 Subject: IOError in windows service Message-ID: <483A85C6.20803@gmail.com> Hi all I have a script (attached) that creates a windows service. Basically the service periodically runs a program 'program.exe'. This all works fine, but during testing I discovered that if I include any 'print' statements (used to debug the service when its run in 'debug' mode), when _not_ in debug mode, it throws an error: The instance's SvcRun() method failed File "C:\Python25\Lib\site-packages\win32\lib\win32serviceutil.py", line 785, in SvcRun self.SvcDoRun() File "C:\Program Files\Program\MyService.py", line 28, in SvcDoRun print "Entering while loop..." : (9, 'Bad file descriptor') I have removed the 'print' statements, after which the service runs fine, but was just curious to find out the reason for this error. Regards Nicol -- The three things to remember about Llamas: 1) They are harmless 2) They are deadly 3) They are made of lava, and thus nice to cuddle. -------------- next part -------------- A non-text attachment was scrubbed... Name: MyService.py Type: text/x-python Size: 2270 bytes Desc: not available URL: From skanemupp at yahoo.se Thu May 15 13:07:39 2008 From: skanemupp at yahoo.se (globalrev) Date: Thu, 15 May 2008 10:07:39 -0700 (PDT) Subject: exists=false, but no complaint when i open it!? References: <285e0ce6-1371-4ab7-9281-ad1d664a480f@a23g2000hsc.googlegroups.com> <6ee5c146-dfe7-4b0b-99e7-b0905023b62a@d1g2000hsg.googlegroups.com> Message-ID: On 15 Maj, 19:04, globalrev wrote: > when i try to write to the file... > > Traceback (most recent call last): > File "C:\Python25\myPrograms\netflix\netflix.py", line 10, in > > d.write('hej du galne kock') > IOError: [Errno 0] Error damn i take a break lol. r+ ldo when open file so i CAN write to it... From castironpi at gmail.com Wed May 14 19:34:29 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 14 May 2008 16:34:29 -0700 (PDT) Subject: named tuple mutability References: Message-ID: On May 14, 6:21?pm, castiro... at gmail.com wrote: > On May 14, 12:41?pm, Raymond Hettinger wrote: > > > >?Should tuples be named? > > > Yes. > > Good; they're named sequences. Can anyone make sling-shots of words? What's the splatter? From arnodel at googlemail.com Fri May 30 04:03:32 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Fri, 30 May 2008 09:03:32 +0100 Subject: should I put old or new style classes in my book? References: Message-ID: Alan Isaac writes: > This thread raises two questions for me. > > 1. I take it from this thread that in Python 3 the following are > equivalent: > > class Test: pass > > class Test(object): pass > > Is that correct, and if so, where is it stated explicitly? > (I know about the "all classes are new style classes" statement.) I don't know where it is stated, but how could they *not* be equivalent? > 2. I take it from this thread that in Python 2.2+ if I put the > following at the top of a module :: > > __metaclass__ = type > > then all the classes defined in that module will be newstyle > classes. Is that correct? Somehow I did not grok that from > > > > but it seems right. >From the URL you quote: The appropriate metaclass is determined by the following precedence rules: * If dict['__metaclass__'] exists, it is used. * Otherwise, if there is at least one base class, its metaclass is used (this looks for a __class__ attribute first and if not found, uses its type). * Otherwise, if a global variable named __metaclass__ exists, it is used. * Otherwise, the old-style, classic metaclass (types.ClassType) is used. Look at the third point. -- Arnaud From vivainio at gmail.com Sun May 25 07:31:50 2008 From: vivainio at gmail.com (Ville M. Vainio) Date: Sun, 25 May 2008 11:31:50 GMT Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <8763t3by81.fsf@benfinney.id.au> <5ea78616-e955-4ee0-8e60-a22734ec31be@79g2000hsk.googlegroups.com> <87prrbk85x.fsf@gmail.com> <06174f9e-ed5b-4107-b646-ef115262268f@d45g2000hsc.googlegroups.com> Message-ID: <87prra39hz.fsf@gmail.com> Duncan Booth writes: > Or if you code in C++ and they *really* need to get at something you > made private they will still get at it. I've been there and done > that: 'private' in languages which have it is rarely an advantage > and frequently a pain. Indeed. In C++, they recommend the "pimpl idiom" (private implementation), which actually has real advantages ;-) From hat at se-162.se.wtb.tue.nl Thu May 22 09:51:35 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Thu, 22 May 2008 15:51:35 +0200 Subject: Loading contents behind the scenes References: <32c00225-f231-4f85-9b01-51f0fd0f9392@k13g2000hse.googlegroups.com> Message-ID: On 2008-05-22, s0suk3 at gmail.com wrote: > Hi, I wanted to know how cautious it is to do something like: > > f = file("filename", "rb") > f.read() > > for a possibly huge file. When calling f.read(), and not doing > anything with the return value, what is Python doing internally? Is it > loading the content of the file into memory (regardless of whether it > is discarding it immediately)? I am not a Python interpreter developer, but as user, yes I'd expect that to happen. The method doesn't know you are not doing anything with its return value. > In my case, what I'm doing is sending the return value through a > socket: > > sock.send(f.read()) > > Is that gonna make a difference (memory-wise)? I guess I'm just > concerned with whether I can do a file.read() for any file in the > system in an efficient and memory-kind way, and with low overhead in > general. (For one thing, I'm not loading the contents into a > variable.) Doesn't matter. You allocate a string in which the contents is loaded (the return value of 'f.read()', and you hand over (a reference to) that string to the 'send()' method. Note that memory is allocated by data *values*, not by *variables* in Python (they are merely references to values). > Not that I'm saying that loading a huge file into memory will horribly > crash the system, but it's good to try to program in the safest way > possibly. For example, if you try something like this in the Depends on your system, and your biggest file. At a 32 bit platform, anything bigger than about 4GB (usually already at around 3GB) will crash the program for the simple reason that you are running out of address space to store bytes in. To fix, read and write blocks by specifying a block-size in the 'read()' call. Sincerely, Albert From grante at visi.com Sat May 10 18:57:20 2008 From: grante at visi.com (Grant Edwards) Date: Sat, 10 May 2008 17:57:20 -0500 Subject: Now what!? References: <68m0i1F2t8265U1@mid.uni-berlin.de> <7363f4c0-1dec-4943-a9f6-7a24c3aff971@e39g2000hsf.googlegroups.com> <9GlVj.168$PE5.102@fe087.usenetserver.com> Message-ID: <5dednf9GS5nNtbvVnZ2dnUVZ_qLinZ2d@posted.visi> On 2008-05-10, Dennis Lee Bieber wrote: >> These are the minute details that bedevil the poor noob. I've >> read dozens of tutorials on different prog langs and have >> never read a single thing on white space or blank lines >> preceding a shebang. Till now. I always get > > Well... The "shebang" line is OS and shell specific The "#!" is sort of a holdover from the "magic number" used back in the day on Unix systems. Traditionally, the type of an executable file on Unix systems was determined by a "magic number" that was read from the first two bytes of a file: http://en.wikipedia.org/wiki/Magic_number_(programming) Back then there was a text file somewhere that listed the various 16-bit values and what they meant. The "file" program used that list to guess what a file was. It's gotten considerably more complex since then, and the "magic" file has syntax to specify fairly large/complex patterns that are used to determine file types. If you're curious, there's probably a "magic" file somewhere on your system. On Gentoo it's at /usr/share/misc/file/magic, On a Linux system (and I presume on other Unixes), the kernel itself (if built with the proper options) knows know how start a "script" file that starts with the characters "#!". When the kernel is told to execute a file whose first two bytes are "#!" (0x32,0x21), it knows to read the newline terminated path of an executable starting at the byte following the "!" (the third byte in the file). The kernel then executes that file, appending the name of the original "script" file to the argv list. -- Grant Edwards grante Yow! My mind is making at ashtrays in Dayton ... visi.com From ocollioud at gmail.com Fri May 16 04:23:59 2008 From: ocollioud at gmail.com (olive) Date: Fri, 16 May 2008 01:23:59 -0700 (PDT) Subject: how to set python hosting ! References: Message-ID: On May 16, 9:16 am, "Ra... at MyKavita.com" wrote: > Hi, > > i do have some basic python know-how. i want to tryout by actually > implementing some python generated dynamic page etc. > > i am having websetup which runs with mysql on linux, and pythong is > installed on it. > > so is there any ref. from where i can know how to configure my > webserver for python. > > -Raxit Hi, see http://www.wsgi.org/wsgi hth From nick at craig-wood.com Thu May 22 11:30:07 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Thu, 22 May 2008 10:30:07 -0500 Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> Message-ID: Dave Parker wrote: > But after getting input from children and teachers, etc, it started > feeling right. > > For example, consider the two statements: > > x = 8 > x = 10 > > The reaction from most math teachers (and kids) was "one of those is > wrong because x can't equal 2 different things at the same time". This is a common feature in functional languages... Eg Erlang (BEAM) emulator version 5.6.2 [source] [smp:2] [async-threads:0] [kernel-poll:false] Eshell V5.6.2 (abort with ^G) 1> X = 8. 8 2> X = 10. ** exception error: no match of right hand side value 10 3> That error message is the erlang interpreter saying "Hey I know X is 8, and you've said it is 10 - that can't be right", which is pretty much what math teachers say too... -- Nick Craig-Wood -- http://www.craig-wood.com/nick From matthieu.brucher at gmail.com Sat May 17 17:35:53 2008 From: matthieu.brucher at gmail.com (Matthieu Brucher) Date: Sat, 17 May 2008 23:35:53 +0200 Subject: help compiling Python on vs 2008! In-Reply-To: References: Message-ID: 2008/5/17 Christian Heimes : > Matthieu Brucher schrieb: > > Hi, > > > > I did not manage to build extension with distutils with Python compiled > with > > VS different than 2003. The need for 2003 was hard-coded in distutils. > > You can try building extensions with VS2008 with Scons. This is what I do > a > > lot, and everything works fine as long as the interface does not use > > standard structures (like FILE, custom structures are fine) or objects > > allocated in the extension is freed in the extension. > > Python 2.5 is compiled with VS 2003. Neither VS 2005 nor 2008 are > officially supported. Even if you compile Python 2.5 with VS2008, VS2003 is used for the extensions, AFAIR. I didn't try Python 2.6 because I only have Visual C++ Express 2008. You can compile extensions with a different version of MS VC but it can > get you in a lot of trouble. Every version of the VS Compiler uses its > own C Runtime Library (MSVCRT). You can't share some resources like > allocated memory and FILE* objects between MSVCRTs. I don't see your point, that's what I wrote... Matthieu -- French PhD student Website : http://matthieu-brucher.developpez.com/ Blogs : http://matt.eifelle.com and http://blog.developpez.com/?blog=92 LinkedIn : http://www.linkedin.com/in/matthieubrucher -------------- next part -------------- An HTML attachment was scrubbed... URL: From bob at passcal.nmt.edu Tue May 20 15:18:08 2008 From: bob at passcal.nmt.edu (Bob Greschke) Date: Tue, 20 May 2008 13:18:08 -0600 Subject: List of disk drives on Windows? Message-ID: <2008052013180816807-bob@passcalnmtedu> This MUST have been asked before, but I can't seem to Google the right thing. ?How can I get a list of drives on a Windows box, like ["C:\", "D:\"], like I can if I do something like listdir("/Volumes") on a Mac? Thanks! Bob From badmuthahubbard at gmail.com Thu May 8 17:17:18 2008 From: badmuthahubbard at gmail.com (Chuckk Hubbard) Date: Fri, 9 May 2008 00:17:18 +0300 Subject: Surprising difference in behavior between "import blah" and "from blah import thing" In-Reply-To: <88edf8eb-c043-46f3-8ccb-653ffac10703@y18g2000pre.googlegroups.com> References: <874p984o4c.fsf@offby1.atm01.sea.blarg.net> <88edf8eb-c043-46f3-8ccb-653ffac10703@y18g2000pre.googlegroups.com> Message-ID: <8200bab70805081417t4cfdcb0dqe8561b5fd83dccf5@mail.gmail.com> :'( I'm confused On Fri, May 9, 2008 at 12:03 AM, offby1 wrote: > Ah. So from the point of view of mut.py, "thing" and "system.thing" > are separate, unrelated variables; the former of which is initialized > from the latter when mut says "from system import thing". Thanks. > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.badmuthahubbard.com From arnodel at googlemail.com Sun May 18 09:40:52 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 18 May 2008 14:40:52 +0100 Subject: explain this function to me, lambda confusion References: <5cc7ef7a-dd21-4772-a7e3-765410f810bb@l17g2000pri.googlegroups.com> Message-ID: Lie writes: > Lambda can actually be safely removed from python and no other > features would be missing. It is always possible to create a def > version of any lambda, so lambda is useless. It is just a convenience > for the times where we're just too lazy to invent a name and find a > place to place the def, instead just inlining the function. Note that the same thing can be said about generator expressions, which are nothing more than anonymous, non-reusable, generator functions. Instead these were _added_ to the language! -- Arnaud From johnjsal at NOSPAMgmail.com Mon May 12 23:40:11 2008 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: 13 May 2008 03:40:11 GMT Subject: Learning Python for no reason References: <0383f3b8$0$27282$c3e8da3@news.astraweb.com> <_w%Vj.9941$Qw5.889@fe107.usenetserver.com> Message-ID: <48290d9a$0$11626$607ed4bc@cv.net> notbob wrote: > On 2008-05-12, John Salerno wrote: > >> language, I can't help but feel that I will be mostly unable to use what I >> learn simply because I have no reason to use it. > >> The *process* of learning is enough fun for me, and every now and then I do >> find a small use for Python that really pays off, > > You're contradicting yourself. Which is it? You can or can't use it? > > I suspect the more you learn of it, the more you will be able to do with it. I > hope so, as I'm just doing it now, like you, for the sake of learning. I just meant that over the couple of years that I've been studying it, I've had a real occasion to use it maybe three or four times. For the most part, I don't use it regularly enough (which is why I'm in the process of re-learning some of it, because it's been so long since I used it). From zephyrfalcon!NO_SPAM! at gmail.com Thu May 29 22:14:25 2008 From: zephyrfalcon!NO_SPAM! at gmail.com (Hans Nowak) Date: Thu, 29 May 2008 22:14:25 -0400 Subject: Code execution in imported modules In-Reply-To: References: Message-ID: <0oJ%j.15824$Kk3.14125@bignews9.bellsouth.net> Eric Wertman wrote: > So I'm working on some file parsing and building up a stack of regular > expressions that I need to use. I was thinking of dropping them in an > external module. I was wondering.. if I put them in a file called > regex.py like so : > > import re > > re1 = ".. > re2 = ".. > > and then do: > > rgx1 = re.compile(re1) > rgx2 = re.compile(re2) > > > and, in my script, parse.py py I do: > > from regex import * > > text = "bunch of stuff......." > > m = rgx1.search(text) > > > Does the re get compiled when I import it, or every time I call it? > Since I'm calling it often, I'd like to compile it once. It is compiled when you import the module. -- Hans Nowak (zephyrfalcon at gmail dot com) http://4.flowsnake.org/ From kyosohma at gmail.com Mon May 19 10:10:57 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 19 May 2008 07:10:57 -0700 (PDT) Subject: How do *you* use Python in non-GUI work? References: 20080518182022.990193bd.johnjsal@NOSPAMgmail.com Message-ID: <3e7fa0d6-c8a4-4149-8fb7-b15f5e20414d@k37g2000hsf.googlegroups.com> On May 18, 5:20?pm, John Salerno wrote: > Hey all. Just thought I'd ask a general question for my own interest. Every time I think of something I might do in Python, it usually involves creating a GUI interface, so I was wondering what kind of work you all do with Python that does *not* involve any GUI work. This could be any little scripts you write for your own benefit, or what you do at work, if you feel like talking about that! :) > > Thanks. Most of my non-GUI stuff is login scripts and registry editing. I also have some scripts that can install various programs silently, such as Adobe Reader or Firefox. This is for work purposes as we have a specific set of applications that need to be installed on each machine. Mike From castironpi at gmail.com Tue May 13 07:31:04 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 13 May 2008 04:31:04 -0700 (PDT) Subject: where to get McMillan Installer? References: <74f142de-6485-4773-bae8-2a274be19b80@w7g2000hsa.googlegroups.com> Message-ID: <537c541a-4e96-404b-81c3-68ffa9a025b8@b64g2000hsa.googlegroups.com> On May 13, 5:47?am, "Gabriel Genellina" wrote: > En Tue, 13 May 2008 07:06:09 -0300, gsal escribi?: > > > There does not seem to be a valid url for the Installer, anywhere. > > Could anyone provide me with a copy of it? > > I think py2exe is its successor:http://www.py2exe.org/ > > -- > Gabriel Genellina I actually thought 'copy' was a banned word. I don't have one, but I can. I.e., cutting and pasting code is working fine currently. I just got two editors! From geoffrey.clementsNO at SPAMbaesystems.com Thu May 15 08:10:25 2008 From: geoffrey.clementsNO at SPAMbaesystems.com (Geoffrey Clements) Date: Thu, 15 May 2008 13:10:25 +0100 Subject: ? References: <51e0f25d-474a-450a-ad00-92f70c893c6c@m44g2000hsc.googlegroups.com> Message-ID: <482c2424$1_1@glkas0286.greenlnk.net> "urikaluzhny" wrote in message news:51e0f25d-474a-450a-ad00-92f70c893c6c at m44g2000hsc.googlegroups.com... On May 15, 10:06 am, "Terry Reedy" wrote: > "urikaluzhny" wrote in message > > news:f8229614-a000-450e-85eb-825e6c1386cf at w7g2000hsa.googlegroups.com... > | It seems that I rather frequently need a list or iterator of the form > | [x for x in <> while <>] > > I can think of two ways to interpret that. >> I mean like [x for x in if ], only that it breaks the loop when >> the expression is false. def gen(a): for x in a: if B: break yield x a_gen = gen(A) # now iterate over a_gen -- Geoff From ZeeGeek at gmail.com Tue May 20 12:31:27 2008 From: ZeeGeek at gmail.com (ZeeGeek) Date: Tue, 20 May 2008 09:31:27 -0700 (PDT) Subject: default gettext localedir on windows References: <6e4b1599-bdbd-4bb1-a104-1f2e8c66b33e@t12g2000prg.googlegroups.com> Message-ID: <0e7b13f0-649d-442d-ae6e-1df5d88663cd@b5g2000pri.googlegroups.com> On May 17, 8:39?pm, Thorsten Kampe wrote: > * ZeeGeek (Sun, 4 May 2008 10:56:52 -0700 (PDT)) > > > On May 5, 1:16?am, Thorsten Kampe wrote: > > > * ZeeGeek (Sun, 4 May 2008 08:59:05 -0700 (PDT)) > > > > > Hi, what's the default localedir for gettext module on windows? In > > > > Linux, it's /usr/share/locale. Where should I put the *.mo file in > > > > order to make the translation work? > > > > %PYTHONHOME%\share\locale > > > I tried moving the *.mo file into %PYTHONHOME%\share\locale\zh_CN > > \LC_MESSAGES, but still no luck. The following is the code snippet I > > use: > > > import gettext > > gettext.install('testprogram', unicode = True) > > The syntax is correct. Is the test program localised under Linux or > Cygwin? If not then the error is somewhere in your application. Yes, it's localized under linux. > How did you try to set the language on Windows? It works for me on Vista > with "set LANG=de" or "set LANGUAGE=de" while I think under XP it had to > be "set LANG=de_DE" (LANGUAGE or de alone did not work if I remember > correctly). I'm using Simplified Chinese Windows, so I didn't set anything specifically before firing up the program. I found that if I use gettext.GNUTranslations to read in the .mo file, then it's localized. But gettext.install doesn't work. From fc14301589 at icqmail.com Sat May 31 14:52:35 2008 From: fc14301589 at icqmail.com (TheSaint) Date: Sun, 01 Jun 2008 02:52:35 +0800 Subject: SMS sending and receiving from website? References: <6abq0uF36n019U1@mid.individual.net> <5d949166-5112-4a7a-91c3-77ccdd7ca695@j22g2000hsf.googlegroups.com> <2e1e103c-b436-445e-ad23-da735c0d8345@f36g2000hsa.googlegroups.com> Message-ID: <48419e73_2@news.tm.net.my> On 22:01, sabato 31 maggio 2008 globalrev wrote: > also, lets say i want to send a SMS to my own phone from the internet. > how would i do that? IMO, nowadays free SMS sending, via internet, is gone. There should be the chance from one's own subscribed network. -- Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html From inhahe at gmail.com Fri May 16 14:08:40 2008 From: inhahe at gmail.com (inhahe) Date: Fri, 16 May 2008 14:08:40 -0400 Subject: writing python extensions in assembly References: Message-ID: "Dan Upton" wrote in message news:mailman.1236.1210959884.12834.python-list at python.org... > > On Fri, May 16, 2008 at 1:27 PM, Mensanator wrote: >> >> Why wouldn't the compilers support it? It's part of the x86 >> architexture, >> isn't it? > > Yeah, but I don't know if it uses it by default, and my guess is it > depends on how the compiler back end goes about optimizing the code > for whether it will see data access/computation patterns amenable to > SIMD. perhaps you explicitly use them with some extended syntax or something? From castironpi at gmail.com Thu May 8 20:21:24 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 8 May 2008 17:21:24 -0700 (PDT) Subject: observer pattern question #1 (reference to subject) References: Message-ID: On May 8, 4:57?pm, Alan Isaac wrote: > Ville M. Vainio wrote: > > in case of stocks, you are probably monitoring several > > stock objects, so the stock should probably pass itself to > > the observer > > OK. ?This is related to my question #2 (in a separate > > thread), where I'd also appreciate your comments. > > > analogous to a typical UI scenario where you have several > > widgets forwarding events to one big observer - and they > > *do* provide the event source and event type. > > That is a helpful comparison. > > > All in all, though, the right solution should be obvious > > from the problem at hand. > > For CS types, maybe. ?The rest of us are just trying to get > > things done without as much background and context. > > Thanks, > > Alan My local vernacular calls them "carfulls" of people, which analogy to the body of collective man, extends pretty far. It's not the gas pedal we hate! I'm schedule more coasting on shore. From wizzardx at gmail.com Sun May 4 03:32:57 2008 From: wizzardx at gmail.com (David) Date: Sun, 4 May 2008 09:32:57 +0200 Subject: Script Optimization In-Reply-To: <6ed749de-1a7d-4db5-a229-d3400da4d24b@f24g2000prh.googlegroups.com> References: <6ed749de-1a7d-4db5-a229-d3400da4d24b@f24g2000prh.googlegroups.com> Message-ID: <18c1e6480805040032u6450bf34wc5ca9ea6c81da56@mail.gmail.com> > It's too long to post here (160 lines) so here's the link: > http://uppit.com/d2/CKOYHE/af78a6beeeed3e21a19d5871abb9b879/utils.py > (if that doesn't work: http://uppit.com/CKOYHE) > > Thanks in advance, > lev Neither link works for me. I get an error page "Error: invalid download linnk". How about you send it to the list as an attachment? David. From gherron at islandtraining.com Tue May 13 18:25:16 2008 From: gherron at islandtraining.com (Gary Herron) Date: Tue, 13 May 2008 15:25:16 -0700 Subject: What is self.file = file for? In-Reply-To: References: Message-ID: <482A154C.1030204@islandtraining.com> wxPythoner at gmail.com wrote: > Hello! > > I have trouble understanding something in this code snippet: > > class TextReader: > """Print and number lines in a text file.""" > def __init__(self, file): > self.file = file > . > . > . > > > When would you do a thing like self.file = file ? I really don't > find an answer on this. Please help me understand this. > -- > http://mail.python.org/mailman/listinfo/python-list > If you know about Object-Oriented Programming this should make sense. If you don't, then you have some reading/learning to do first. When someone wants to create an object of type TextReader, they must supply a value ob = TextReader(v) That calls the __init__ constructor with the supplied value of v in the variable named file. If the object being created wants to record the value for future use, then the line self.file = file does just that. "self" is the name of the object being created, "self.file" is an attribute named "file" of that object, and the assignment stores the supplied value there. Gary Herron From workitharder at gmail.com Fri May 23 12:36:44 2008 From: workitharder at gmail.com (bukzor) Date: Fri, 23 May 2008 09:36:44 -0700 (PDT) Subject: call f(a, *b) with f(*a, **b) ? References: <55bc8846-107e-461a-89de-25c83cbcfa27@2g2000hsn.googlegroups.com> <5coZj.13951$hv2.4218@bignews5.bellsouth.net> <9e688dbd-43fb-43ca-8c60-8dd2aaa66aa1@x1g2000prh.googlegroups.com> Message-ID: <46602e24-0285-4667-b09a-8f7ce7509f71@b5g2000pri.googlegroups.com> On May 23, 3:29?am, "inhahe" wrote: > "inhahe" wrote in message > > news:MKwZj.2749$772.668 at bignews2.bellsouth.net... > > > if we assume the constraints are that: > > 1.he has list, l > > 2.he has a dictionary, d > > 3.he wants the function to print the values in the dictionary according to > > a specific order of their keys as defined by the function, followed by the > > values of the list > > It's also possible (even likely) that he knows outside of the function what > order he wants the values in, and only used an (incidentally) unordered dict > called kwargs because he thought that's the only way to pass to those > parameters. ?in which case the function could be left untouched and the he > would call it like this: > > args = [1,2,3] > f(*args) > or > f(*[1,2,3]) You're actually pretty dead-on here. I preferred the keyword approach because printing it showed an explicit assignment of arguments, but it looks like I'll have to use a list if there's an *argv argument, since there's no way to assign it with keywords, and no (working) way to use them together. def f(a, *args): print a, args args = [2, 3] kwargs = {'a':1} f(*args, **kwargs) TypeError: f() got multiple values for keyword argument 'a' kwargs['args'] = args f(**kwargs) TypeError: f() got an unexpected keyword argument 'args' From grante at visi.com Mon May 12 10:44:58 2008 From: grante at visi.com (Grant Edwards) Date: Mon, 12 May 2008 09:44:58 -0500 Subject: Is using range() in for loops really Pythonic? References: <482657ca$0$25026$607ed4bc@cv.net> <41078222-aec0-4e8b-8a1f-945cdf814498@m73g2000hsh.googlegroups.com> <48275446$0$11628$607ed4bc@cv.net> <87mymw8nr0.fsf@benfinney.id.au> <4827bda2$0$11606$607ed4bc@cv.net> <87od7c6qua.fsf@benfinney.id.au> Message-ID: On 2008-05-12, Ben Finney wrote: I too, agree that requiring a name be bound to the values coming out of the iterator seems "wrong". > With "do something N times", there must be *something* to keep track > of which iteration we're up to (or, equivalently, how many iterations > remain) at a given moment. A Python iterator seems a fine choice to > hold that information, and better than many alternatives. An iterator like xrange() is an excellent choice. But, since the iterator contains that information, why require that that value be "exported" by the iterator and bound to an externally visible name? In the case in question, the only thing you need from the iterator is the StopIteration exception. To me, exposing the internal state of the iterator and requiring that the user bind a name to it each time through the loop feels we're like driving a nail with a screwdriver. -- Grant Edwards grante Yow! Was my SOY LOAF left at out in th'RAIN? It tastes visi.com REAL GOOD!! From bj_666 at gmx.net Tue May 20 14:13:08 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 20 May 2008 18:13:08 GMT Subject: AttributeError: module object has no attribute References: <483311EB.1040307@gmail.com> Message-ID: <69gilkF30tko7U1@mid.uni-berlin.de> On Tue, 20 May 2008 23:31:15 +0530, Nikhil wrote: > Peter Otten wrote: >> Nikhil wrote: >> >>> I have recently written a small module. When I import the module, I >>> always get the error >>> >>> >>> only when I do >>> >>> >>> from local.my.module import * >>> >>> -- >>> Traceback (most recent call last): >>> File "", line 1, in >>> AttributeError: 'module' object has no attribute '/xyz/py/file' >>> --- >>> >>> >>> but when I do the below, I do not get any error. >>> >>> -- >>> >> import local.my.module >>> >> >>> -- >>> >>> Any ideas on what could be wrong? >> >> Are you abusing the __all__ attribute? >> >> $ cat tmp.py >> __all__ = ['/xyz/py/file'] >> >> $ python -c "from tmp import *" >> Traceback (most recent call last): >> File "", line 1, in >> AttributeError: 'module' object has no attribute '/xyz/py/file' >> > > Yes, I am. Is there any reason not to? That your module raises the `AttributeError` and is broke is not reason enough!? :-) > basically, since this is implemented in the module, I have to export it > since the caller to the function in the module is responsible for > ensuring he has enough proper permissions to read the file. What do you mean by "implemented in the module"? `__all__` is for names that live in the module's namespace -- '/xyz/py/file' isn't even a legal identifier name in Python! Ciao, Marc 'BlackJack' Rintsch. From exarkun at divmod.com Tue May 6 12:35:26 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 6 May 2008 12:35:26 -0400 Subject: select.poll() and WSAPoll In-Reply-To: Message-ID: <20080506163526.6859.2102154164.divmod.quotient.59595@ohm> On Tue, 6 May 2008 08:44:36 -0700 (PDT), Giles Brown wrote: >On 6 May, 14:18, Jean-Paul Calderone wrote: >> On Tue, 6 May 2008 08:36:28 -0400, inhahe wrote: >> >select.poll isn't supported on Windows, because Windows doesn't have such a >> >feature, or at least it didn't until Vista. Vista implements the same thing >> >but called WSAPoll, an article is here >> >http://blogs.msdn.com/wndp/archive/2006/10/26/WSAPoll.aspx >> >I hope that the next edition of Python supports select.poll on Vista, or at >> >least that someone writes a third-party module fo it. As much as I'd love to >> >do it myself, it's probably beyond me.. i've never used poll before nor >> >written a Python extension. also, i don't have Vista. >> >Thanks >> >> If you use Twisted, then you can use I/O Completion Ports, which are even >> better than WSAPoll, and your code will also work with KQueue on BSD or >> EPoll on Linux without any changes. :) >> >> Jean-Paul > >The current docs describe the I/O Completion Ports reactor as >"extremely experimental". > >http://twistedmatrix.com/projects/core/documentation/howto/choosing-reactor.html#auto8 > >Is that overly conservative or is it as bleeding edge as it sounds? > >(IIRC there have been caveats like this on the Windows reactors for >a while) With the most recent release, the IOCP reactor is in much better shape than it ever has been before. It's not perfect, but it fails fewer than 10 unit tests from the Twisted suite (of almost 4300). The goal, of course, is for it to fail none of them. ;) It's possible we'll get there for a release in the not too distant future. The current results of the test suite are available at this extremely pretty URL: http://buildbot.twistedmatrix.com/waterfall?builder=win32-py2.4-iocp&builder=winxp32-py2.5-iocp&builder=vista-py2.5-iocp&builder=server-2k8-x86-py2.5-iocp&branch=trunk So I'd call it "almost working" rather than "extremely experimental" at this point. Thanks for bringing this up, we should probably adjust our docs. :) Jean-Paul From b0bm00r3 at gmail.com Sun May 11 02:45:00 2008 From: b0bm00r3 at gmail.com (philly_bob) Date: Sat, 10 May 2008 23:45:00 -0700 (PDT) Subject: Keeping two lists aligned after processing References: <823470c7-4c15-4653-8c51-7ab83acc9221@m36g2000hse.googlegroups.com> <7xbq3dfj0c.fsf@ruckus.brouhaha.com> Message-ID: <5cc8c484-a252-4cc2-b432-3ba13a064385@m44g2000hsc.googlegroups.com> On May 11, 2:32 am, Paul Rubin wrote: > philly_bob writes: > > algs=['AlgA', 'AlgB', 'AlgC', 'AlgD', 'AlgE'] > > accs=[] > > for alg in algs: > > thisacc=getattr(alg.accuracy)() # picked this technique on > > comp.lang.python last month > > accs.append(thisacc) > > I think what you mean is (untested): > > algs = [AlgA, AlgB, AlgC, AlgD, AlgE] > accs = sorted(((alg.accuracy(), alg.name()) for alg in algs), > reverse=True) > for i,(alg_acc, alg_name) in enumerate(accs): > print '%2d %5s %0.2f'% (i, alg_name, alg_acc) > > This assumes a method alg.name() which tells you the name of the > algorithm. I don't understand how you're converting the string 'AlgA' > to an algorithm object in your example above. The technique is described in this thread: http://groups.google.com/group/comp.lang.python/browse_frm/thread/ed652ba2fab47a6f/489f1746210e83b9?lnk=st&q=b0bm00r3#489f1746210e83b9 I've barely mastered it, but it does work. Bob= From bruno.desthuilliers at gmail.com Wed May 7 18:27:58 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Wed, 7 May 2008 15:27:58 -0700 (PDT) Subject: letter frequency counter / your thoughts.. References: <5a9a4a7e-a4a3-4a59-a80f-01d44bc69a86@w1g2000prd.googlegroups.com> Message-ID: <35e4c5fb-d09f-492d-a165-f03be93ff465@8g2000hse.googlegroups.com> On 7 mai, 23:51, "bruno.desthuilli... at gmail.com" wrote: (snip) Small improvement thanks to Paul Rubin: from collections import defaultdict from operator import itemgetter def get_letters_frequency(source): letters_count = defaultdict(int) for letter in source: letters_count[letter] += 1 return sorted( letters_count.iteritems(), key=itemgetter(1), reverse=True ) From pupeno at pupeno.com Fri May 16 17:53:03 2008 From: pupeno at pupeno.com (=?ISO-8859-1?Q?J=2E_Pablo_Fern=E1ndez?=) Date: Fri, 16 May 2008 14:53:03 -0700 (PDT) Subject: Getting elements and text with lxml Message-ID: Hello, I have an XML file that starts with: *-a out of it, I'd like to extract something like (I'm just showing one structure, any structure as long as all data is there is fine): [("ofc", "*"), "-", ("rad", "a")] How can I do it? I managed to get the content of boths tags and the text up to the first tag ("\n "), but not the - (and in other XML files, there's more text outside the elements). Thanks. From castironpi at gmail.com Fri May 16 18:19:03 2008 From: castironpi at gmail.com (castironpi) Date: Fri, 16 May 2008 15:19:03 -0700 (PDT) Subject: can't delete from a dictionary in a loop References: <43a76233-01cd-4350-b486-cf3e1b32d9dd@k13g2000hse.googlegroups.com> Message-ID: <85961d8b-5055-47a4-b5c1-55bee7460dd8@24g2000hsh.googlegroups.com> On May 16, 4:51?pm, Hans Nowak wrote: > bruno.desthuilli... at gmail.com wrote: > > On 16 mai, 23:34, "bruno.desthuilli... at gmail.com" > > wrote: > >> On 16 mai, 23:28, Hans Nowak wrote: > > >>> Dan Upton wrote: > >>>> for pid in procs_dict: > > (snip) > >>> ? ?for pid in procs_dict.keys(): > >> I'm afraid this will do the same exact thing. A for loop on a dict > >> iterates over the dict keys, so both statements are strictly > >> equivalent from a practical POV. > > > Hem. Forget it. I should think twice before posting - this will > > obviously make a big difference here. ?Sorry for the noise. > > :-) ?It appears that you would be right if this was Python 3.0, though: > > Python 3.0a5 (r30a5:62856, May 16 2008, 11:43:33) > [GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin > Type "help", "copyright", "credits" or "license" for more information. > ?>>> d = {1: 2, 3: 4, 5: 6} > ?>>> for i in d.keys(): del d[i] > ... > Traceback (most recent call last): > ? ?File "", line 1, in > RuntimeError: dictionary changed size during iteration > > Maybe 'for i in d' and 'for i in d.keys()' *are* functionally equivalent in 3.0, > as d.keys() returns an object that iterates over d's keys... but I haven't read > enough about it yet to be sure. ?In any case, the problem goes away when we > force a list: > > ?>>> d = {1: 2, 3: 4, 5: 6} > ?>>> for i in list(d.keys()): del d[i] > ... > ?>>> d > {} > > --Hans- Hide quoted text - > > - Show quoted text - You may be searching for: for i in d.keys()[:]: del d[ i ] From tgrav at mac.com Thu May 29 11:02:25 2008 From: tgrav at mac.com (Tommy Grav) Date: Thu, 29 May 2008 11:02:25 -0400 Subject: mysqldb install problem Message-ID: <58C1F8D5-DB1C-4598-B124-92FBC2B07041@mac.com> I am trying to install mysqldb-1.2.2 on my PPC running 10.5.2 and Activepython 2.5.1.1 when I get this error: running build running build_py copying MySQLdb/release.py -> build/lib.macosx-10.3-fat-2.5/MySQLdb running build_ext building '_mysql' extension gcc -isysroot /Developer/SDKs/MacOSX10.4u.sdk -fno-strict-aliasing - Wno-long-double -no-cpp-precomp -mno-fused-madd -fPIC -fno-common - dynamic -DNDEBUG -g -O3 -Wall -Wstrict-prototypes - Dversion_info=(1,2,2,'final',0) -D__version__=1.2.2 -I/usr/local/mysql/ include -I/Library/Frameworks/Python.framework/Versions/2.5/include/ python2.5 -c _mysql.c -o build/temp.macosx-10.3-fat-2.5/_mysql.o -g - Os -arch ppc64 -fno-common -D_P1003_1B_VISIBLE -DSIGNAL_WITH_VIO_CLOSE -DSIGNALS_DONT_BREAK_READ -DIGNORE_SIGHUP_SIGQUIT - DDONT_DECLARE_CXA_PURE_VIRTUAL In file included from /Library/Frameworks/Python.framework/Versions/ 2.5/include/python2.5/Python.h:57, from pymemcompat.h:10, from _mysql.c:29: /Library/Frameworks/Python.framework/Versions/2.5/include/python2.5/ pyport.h:734:2: error: #error "LONG_BIT definition appears wrong for platform (bad gcc/glibc config?)." In file included from _mysql.c:35: /usr/local/mysql/include/my_config.h:1095:1: warning: "SIZEOF_LONG" redefined In file included from /Library/Frameworks/Python.framework/Versions/ 2.5/include/python2.5/Python.h:8, from pymemcompat.h:10, from _mysql.c:29: /Library/Frameworks/Python.framework/Versions/2.5/include/python2.5/ pyconfig.h:807:1: warning: this is the location of the previous definition error: command 'gcc' failed with exit status 1 Anyone know what is going on? Cheers Tommy From duncan.booth at invalid.invalid Mon May 5 04:37:07 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 5 May 2008 08:37:07 GMT Subject: Feature suggestion: sum() ought to use a compensated summation algorithm References: Message-ID: "Gabriel Genellina" wrote: > En Sun, 04 May 2008 12:58:25 -0300, Duncan Booth > escribi?: > >> Szabolcs Horv?t wrote: >> >>> I thought that it would be very nice if the built-in sum() function >>> used this algorithm by default. Has this been brought up before? >>> Would this have any disadvantages (apart from a slight performance >>> impact, but Python is a high-level language anyway ...)? >> >> There's a thread you might find interesting: >> >> http://groups.google.com/group/comp.lang.python/browse_thread/thread/9 >> eda29faf92f532e/027cef7d4429aa3a >> >> In that thread I suggested that Python ought to implement sum by >> adding together each pair of values, then each pair of results and so >> on. This means that for input values of a similar magnitude the >> intermediate results stay balanced. The implementation doesn't >> actually do all the first level > > Python doesn't require __add__ to be associative, so this should not > be used as a general sum replacement. But if you know that you're > adding floating point numbers you can use whatever algorithm best fits > you. Or use numpy arrays; I think they implement Kahan summation or a > similar algorithm. > Yes, my argument is more along the line that it should have been implemented that way in the first place, but changing things now would require time machine intervention. :) From bignose+hates-spam at benfinney.id.au Fri May 2 10:44:00 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 03 May 2008 00:44:00 +1000 Subject: #!/usr/bin/env python vs. #!/usr/bin/python References: <87abj91j8u.fsf@benfinney.id.au> <87k5iczvdy.fsf@benfinney.id.au> Message-ID: <877ieczryn.fsf@benfinney.id.au> "D'Arcy J.M. Cain" writes: > On Fri, 02 May 2008 23:30:01 +1000 > Ben Finney wrote: > > The OP was asking why people prefer on over the other. My answer > > is that I prefer specifying "give me the default OS Python" > > because anything not installed by the OS is [too] non-standardised > > for me to worry about. > > As someone else pointed out, not all the world is Linux. It's a good thing I've never implied such to be the case. -- \ "If nature has made any one thing less susceptible than all | `\ others of exclusive property, it is the action of the thinking | _o__) power called an idea" -- Thomas Jefferson | Ben Finney From artyprog at gmail.com Wed May 21 03:56:17 2008 From: artyprog at gmail.com (Salvatore DI DI0) Date: Wed, 21 May 2008 09:56:17 +0200 Subject: Processing in Python References: <483345f5$0$902$ba4acef3@news.orange.fr> Message-ID: <4833d5a2$0$839$ba4acef3@news.orange.fr> Thanks all of you Regards Salvatore From hat at se-162.se.wtb.tue.nl Thu May 29 03:22:29 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Thu, 29 May 2008 09:22:29 +0200 Subject: How to get all the variables in a python shell References: Message-ID: On 2008-05-29, lixinyi.23 at gmail.com wrote: > Hi! > > I'm currently working on a scientific computation software built in > python. > What I want to implement is a Matlab style command window <-> > workspace interaction. ok, although I personally favor the style of writing and running a script/program, since it scales much better (you can easier automate steps), and it is much easier reproducible (something you probably want in scientific software) and storable (in a VCS). > For example, you type 'a=1' in the command window, and you see a list > item named 'a' in the workspace. > You double click the icon of the item, and you see its value. You can > modify the value of the list item, > 1 -> 100 etc, after which if you go back to the command window and > type 'a' and press enter, you see that > varable a's value has been changed to 100. I do hope you have made a fair estimate of the amount of work that it costs to change the value of a variable in this way. I would propose to simply use the interactive Python prompt. It doesn't give you popup icons for clicking, but you do get the entire Python interpreter, and all its libraries for free. The Python library has a frame work for customizing the interpreter. Have a look at 'cmd' module. > So my question is : if you have two DOS command windows running under > WINDOWS OS, how can you make them share the same internal variable > buffer? Or is there any easier way to implement such kind of > interaction? Now you have lost me. One window is not enough for interaction? Obviously, you'll need to have a common interpreter/storage backend. One solution may be to have a common execution back-end, and for each window a 'frontend' which passes commands entered to the back-end, and echoes results from the back-end to the terminal. > Maybe I could just build a small database to store all the values and > access them from both programs, but chances are sometimes I have to > deal with big arrays, and they will eat extra memory if I keep them in They eat memory when you keep them in a data base? It seems, you are making assumptions about implementations here without telling them. (ie pick a data base that uses a disk, and your problem is solved. Why is that not an option?) Sincerely, Albert From ulrich at dorda.net Sun May 25 06:32:30 2008 From: ulrich at dorda.net (ulrich at dorda.net) Date: Sun, 25 May 2008 03:32:30 -0700 (PDT) Subject: access interactive namespace from module (shared namespace?) References: Message-ID: Thanks for the reply, Of course the suggested solution is working and good, but a bit complicated. The module/function where i need to access the variable value from the interactive shell is burried quite deep and I would nedd to hand the locals() quite often from one module to another. Furthermore it makes the call function slightly more complicated, as the locals()-argunment has to be given every time. I was hoping for something a bit different: If I wanted to access a value b from another module "utest2.py", I would simply need to type in utest.py: import utest2; print 2*utest2.b Isn't there a name for the interactive namespace (like here the utest2), which I can use to access the variable without handing the whole dictionary? Cheers, Ulrich From dannywebster at googlemail.com Tue May 13 06:46:45 2008 From: dannywebster at googlemail.com (dannywebster at googlemail.com) Date: Tue, 13 May 2008 03:46:45 -0700 (PDT) Subject: Best way to delimit a list? References: <57129f75-b496-40fc-8b2d-d93ba544d4c5@u6g2000prc.googlegroups.com> Message-ID: <5c339461-b9d9-4b80-aa90-9bdd4d401525@q24g2000prf.googlegroups.com> On May 13, 11:28 am, dannywebs... at googlemail.com wrote: > Hi - I have a list returned from popen/readlines, and am wondering how > to go about iterating over each item which was returned (rather than > currently having the whole lot returned). > > so far: > > >>> f=os.open("./get_hostnames").readlines > > returns ['host1 host2 host3 ... hostN\n]' > > i'd like to be in a position to iterate through these, grabbing each > host. I have played with transmuting to a str, and using split, and > this works, but I get the subscript brackets from the list output as > expected, as the list output is now a string literal, and this is not > what I want - and I think it's a bit long-winded to do a search 'n > replace on it - hence why I ask in the subject what's the best way. > > >>> f=str(f) > >>> f.split() > > ["['host1","host2", ... ,"hostN\n']"] > > Any help is highly appreciated > > ta > > dan. I did indeed mean "os.popen", no "os.open" From none at this.time Mon May 26 17:06:53 2008 From: none at this.time (Paul Miller) Date: Mon, 26 May 2008 17:06:53 -0400 Subject: definition of a highlevel language? References: <2759eed3-956d-45c7-8dfb-9557f74133b3@56g2000hsm.googlegroups.com> <26d0b3d2-01cc-49bd-b284-1a849b0b835f@y38g2000hsy.googlegroups.com> <34dcbdc1-5285-41ec-be06-c88c56bb0372@i76g2000hsf.googlegroups.com> <45f03028-a86c-4357-9aa2-0148f7cc84dc@d45g2000hsc.googlegroups.com> Message-ID: <80531$483b266d$3799@news.teranews.com> On Mon, 26 May 2008 15:49:33 -0400, Dan Upton wrote: > On Mon, May 26, 2008 at 3:22 PM, wrote: > I don't know if it would necessarily look like the CPython VM, except > for the decode stage (this being said without any knowledge of the > CPython implementation, but with more than I ever thought I'd know about > processor architecture/microarchitecture) Out of curiosity, do you know how easy it would be to make a Python chip using FPGAs? I have little to no hardware knowledge, but it sounds like a fun project in any case. Even if it's not likely to have blazing performance, it'd be cool to load Python bytecode directly into memory. :-) -- code.py: a blog about Python. http://pythonista.wordpress.com ** Posted from http://www.teranews.com ** From nick at craig-wood.com Tue May 20 04:30:05 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 20 May 2008 03:30:05 -0500 Subject: TPCServer and xdrlib References: <5d56b071-1184-4112-bd82-89c00975b939@m73g2000hsh.googlegroups.com> <75dc8fc3-aef0-44ee-a6df-059f8cd2e226@d45g2000hsc.googlegroups.com> Message-ID: Henrique Dante de Almeida wrote: > On May 19, 10:28?am, Laszlo Nagy wrote: > > I cannot predict "acceptable speed" requirements, but I can tell that > > there will be some clients downloading 100MB report files from the > > server, so I presume that I will need a progress bar. I think that I > > need to develop my own protocol for this, and probably the underlying > > Okay, so you need to wrap large binary files in some kind of message, > without pre processing them. I think developing your own protocol > using XDR is a safe bet. You might want to consider using netstrings rather than XDR http://cr.yp.to/proto/netstrings.txt They are very simple and would be minimal overhead if all you are passing is a file and a bit of metadata. You'll find several modules for python with a bit of searching. Also I believe twisted supports them directly or you could easily roll your own. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From mabbikeel at gmail.com Sun May 18 14:06:10 2008 From: mabbikeel at gmail.com (Matt Porter) Date: Sun, 18 May 2008 19:06:10 +0100 Subject: Compress a string Message-ID: Hi guys, I'm trying to compress a string. E.g: "AAAABBBC" -> "ABC" The code I have so far feels like it could be made clearer and more succinct, but a solution is currently escaping me. def compress_str(str): new_str = "" for i, c in enumerate(str): try: if c != str[i+1]: new_str += c except IndexError: new_str += c return new_str Cheers Matt -- -- From wuwei23 at gmail.com Wed May 21 21:47:28 2008 From: wuwei23 at gmail.com (alex23) Date: Wed, 21 May 2008 18:47:28 -0700 (PDT) Subject: php vs python References: <5l%Yj.77$mz3.53@fe101.usenetserver.com> Message-ID: On May 22, 6:10 am, notbob wrote: > Well, that's my actual question, then. Is php really so bad I'm just > wasting my time? Or is it really the quickest way to blog functionality? > Would I be better served in the long run learning python, which claims to be > easy as pie to learn/program (still looks hard to me). I admit I'm no code > geek. But, I'm not completely brain dead, either, and I need something to > keep my geezer brain sparking. What say ye? Python has 71 built in functions (in 2.5). Atwood's list of PHP built ins beginning with 'a' is 124 functions long. There's a clear reason why people say Python "fits your brain" :) From jtc at theworld.com Sun May 11 20:43:08 2008 From: jtc at theworld.com (Jonathsn Cronin) Date: Mon, 12 May 2008 00:43:08 GMT Subject: Is using range() in for loops really Pythonic? References: <482657ca$0$25026$607ed4bc@cv.net> <41078222-aec0-4e8b-8a1f-945cdf814498@m73g2000hsh.googlegroups.com> <48275446$0$11628$607ed4bc@cv.net> Message-ID: <0001HW.C44D0ADD008F9F39F0284530@news.verizon.net> On Sun, 11 May 2008 16:16:53 -0400, John Salerno wrote (in message <48275446$0$11628$607ed4bc at cv.net>): > XLiIV wrote: > >> The range() function returns a list and list is a sequence, isn't? > > I think you're missing the point. To me, there seems to be a fundamental > difference between these two things: > > --- > > people = ['Sam', 'Bob', 'Fred'] > > for name in people: > print name > > --- > > AND > > --- > > num = 33 > > for x in xrange(10): > print num += 1 > > --- > > To me, the first example is a pure use of the for loop. You are > iterating through an object and *using* the items you are stepping through. > > The second example, however, is simply doing something 10 times, and > what it's doing has nothing to do with 'x' or xrange. So it seems like > an abuse of the for loop. I agree in principle; the first is iteration and the second is repetition. In Python, the common idiom for a fixed number of repetitions is iterating over a number range. This is true in most languages I am familiar with, probably because fixed repetition, where you don't care about the "index" value, is rarely used. The only language I've used that does have fixed repetition is an (old) dialect of lisp, and I'm not sure it even made it into Common Lisp. Smalltalk and Ruby do have fixed repetition. Using range may not be entirely elegant, but is pragmatic, and not, to me, particularly ugly. In Python, unlike some languages, you don't have to declare the x. I think you could add it without too much change to the parsing. for : Seeing a ":" instead of "in" would mean a repetition statement which would be interpreted as: -- if evaluates to an integer, execute the block that number of times. -- If evaluates to an iterator, execute the block until the iterator is exhausted. Even if possible, I see this at best a minor improvement and more likely a negative because the for keyword is now overloaded. (see "static" in C/Java.) You could add a new keyword but the benefit here is much to small to justify the trouble. Jonathan From google at mrabarnett.plus.com Wed May 14 18:55:47 2008 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 14 May 2008 15:55:47 -0700 (PDT) Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <5b0e3f70-afde-4480-8713-e7113b1250d7@x35g2000hsb.googlegroups.com> <1f537717-00d0-48ee-99b6-7125b96a6133@t12g2000prg.googlegroups.com> <68t4o0F2vaoncU1@mid.uni-berlin.de> <2a32179a-9439-449c-bd07-fff6a4075aee@s50g2000hsb.googlegroups.com> <7ee5dffd-df8f-46f0-bd78-c81ac0418a9a@d77g2000hsb.googlegroups.com> <65ef773e-a1c3-4adb-a18b-e8b8451efe5e@b5g2000pri.googlegroups.com> <68trmmF2vjivnU1@mid.uni-berlin.de> <68tuhfF2unducU1@mid.uni-berlin.de> <8b9560fa-7f29-4bfe-b312-e3da0e3779b6@z24g2000prf.googlegroups.com> <68u1avF2ujou9U1@mid.uni-berlin.de> Message-ID: <1e4287a7-321c-432a-9217-c97a91ec18b1@y21g2000hsf.googlegroups.com> On May 14, 10:30 pm, "bruno.desthuilli... at gmail.com" wrote: > > Dave Parker schrieb: > > > All of the calculators and textbooks that elementary school students > > > use, use "^" for powers. > > I've never seen this symbol in textbooks. In textbooks, powers are > written using superscript. > > >> Just like Flaming Thunder does. I haven't > > > seen "**" for powers since FORTRAN. > > I haven't seen any language using '^' as the power operator so far - > but I've seen quite a lot of them using it as the bitwise XOR operator. BASIC and Comal use '^' as the power operator. From gandalf at shopzeus.com Fri May 16 07:42:03 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Fri, 16 May 2008 13:42:03 +0200 Subject: ply yacc lineno not working? In-Reply-To: <482D70F0.9070202@shopzeus.com> References: <482D70F0.9070202@shopzeus.com> Message-ID: <482D730B.9090607@shopzeus.com> I'm sorry for the dumb question. I had to add these to the lexer: def t_comment(t): r"\#[^\n]*\n" t.lexer.lineno += 1 # We do not return anything - comments are ignored. # Define a rule so we can track line numbers def t_newline(t): r'\n+' t.lexer.lineno += len(t.value) Well, it is not very straightforward. From the docs, it was not clear that I HAVE TO increment t.lexer.lineno in my lexer if you want yacc to parse line numbers. But it is logical. I believe this could be done automatically, since "line number" ALWAYS means "\n", there is nothing to be configured here. (Am I wrong? There can be parsers to parse files where new lines are chr(255) or something?) Thanks, Laszlo From michael.pearmain at tangozebra.com Sun May 18 15:55:26 2008 From: michael.pearmain at tangozebra.com (Mike P) Date: Sun, 18 May 2008 12:55:26 -0700 (PDT) Subject: Rpy Module References: <4cbbf8ef-f123-47cd-b265-4d91925efa10@e39g2000hsf.googlegroups.com> Message-ID: <054ecd85-997e-417b-80d7-ee5c5f89e611@l42g2000hsc.googlegroups.com> Superb, thanks From tjreedy at udel.edu Sat May 17 12:13:47 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 17 May 2008 12:13:47 -0400 Subject: Markov Analysis Help References: <0e19f5d0-9898-48c0-9192-683c74dc7fad@c65g2000hsa.googlegroups.com> Message-ID: "dave" wrote in message news:g0mvc2$sic$1 at news.xmission.com... | bear, | thanks for the suggestions. I use IDLE to write the code and when it's | working I paste it over into a new window. Or you can just save code you want to keep to a new name. | To add doctests would I need to use a certain | filename for the tests to be run on? You can run a doctest on a file from within the file (as well as from without). if __name__ == '__main__': I presume the manual gives the details. | Can you have doctests on random functions? ??? tjr From badmuthahubbard at gmail.com Sat May 10 11:58:23 2008 From: badmuthahubbard at gmail.com (Chuckk Hubbard) Date: Sat, 10 May 2008 18:58:23 +0300 Subject: People still using Tkinter? In-Reply-To: References: Message-ID: <8200bab70805100858m11c57dc7l7a1ac19d6e3928d4@mail.gmail.com> I am, but "still" isn't the word, I just started. Good, *complete* docs seem to be hard to find, but using a combination of the free resources and going back and forth between them seems to work all right so far. -Chuckk On Sat, May 10, 2008 at 8:20 AM, Kenneth McDonald wrote: > Any guesses as to how many people are still using Tkinter? And can anyone > direct me to good, current docs for Tkinter? > > Thanks, > Ken > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.badmuthahubbard.com From jkrukoff at ltgc.com Thu May 15 19:48:53 2008 From: jkrukoff at ltgc.com (John Krukoff) Date: Thu, 15 May 2008 17:48:53 -0600 Subject: no inputstream? In-Reply-To: <1210894979.3312.14.camel@jmk> References: <87lk2ba4b4.fsf@mulj.homelinux.net> <8d566db4-c626-491f-82e4-303308c5b8da@25g2000hsx.googlegroups.com> <1210893082.3312.2.camel@jmk> <1210894364.3312.10.camel@jmk> <1210894979.3312.14.camel@jmk> Message-ID: <1210895333.3312.17.camel@jmk> On Thu, 2008-05-15 at 17:42 -0600, John Krukoff wrote: > On Thu, 2008-05-15 at 17:32 -0600, John Krukoff wrote: > > On Thu, 2008-05-15 at 17:11 -0600, John Krukoff wrote: > > > On Thu, 2008-05-15 at 15:35 -0700, max wrote: > > > > On May 15, 6:18 pm, MRAB wrote: > > > > > On May 15, 9:00 pm, max wrote: > > > > > > > > > > > you're right, my java implementation does indeed parse for Id3v2 > > > > > > (sorry for the confusion). i'm using the getrawid3v2() method of this > > > > > > bitstream class (http://www.javazoom.net/javalayer/docs/docs0.4/ > > > > > > javazoom/jl/decoder/Bitstream.html) to return an inputstream that then > > > > > > i buffer and parse. apologies if i misrepresented my code! > > > > > > > > > > > back to python, i wonder if i'm misusing the mutagen id3 module. this > > > > > > brief tutorial (http://www.sacredchao.net/quodlibet/wiki/Development/ > > > > > > Mutagen/Tutorial) leads me to believe that something like this might > > > > > > work: > > > > > > > > > > > from mutagen.mp3 import MP3 > > > > > > id3tags = MP3(urllib2.urlopen(URL)) > > > > > > > > > > > but this gives me the following TypeError: "coercing to Unicode: need > > > > > > string or buffer, instance found". does this mean i need to convert > > > > > > the "file-like object" that is returned by urlopen() into a unicode > > > > > > object? if so, do i just decode() with 'utf-8', or is this more > > > > > > complex? as of now, doing so gives me mostly "No such file or > > > > > > directory" errors, with a few HTTP 404s. > > > > > > > > > > [snip] > > > > > I think it's expecting the path of the MP3 but you're giving it the > > > > > contents. > > > > > > > > cool, so how do i give it the path, if not in the form of a URL > > > > string? maybe this is obvious... > > > > -- > > > > http://mail.python.org/mailman/listinfo/python-list > > > > > > It doesn't look like you can, with mutagen. So, time to find a different > > > library that supports arbitrary file objects instead of only file paths. > > > I'd suggest starting here: > > > http://pypi.python.org/pypi?%3Aaction=search&term=id3&submit=search > > > > > > Possibly one with actual documentation, since that would also be a step > > > up from mutagen. > > > > > > > After a bit of time looking around, looks like nearly all the python id3 > > modules expect to work with filenames, instead of file objects. > > > > I can't vouch for it, and the documentation still looks sparse, but this > > module at least looks capable of accepting a file object: > > http://pypi.python.org/pypi/tagpy > > > > Looks like it'd be a challenge to build if you're on windows, since it > > depends on an external library. > > > > Alternately, you could probably create a subclass of the mutagen stuff > > that used an existing file object instead of opening a new one. No idea > > what that might break, but seems like it would be worth a try. > > > > As last ditch option, could write the first few kb of the file out to a > > temp file and see if mutagen will load the partial file. > > > > Okay, now I'm officially spending too much time looking through this > stuff. > > However, looks like the "load" method of the MP3 class is what you'd > want to override to change mutagen's file loading behavior. Probably > pass the URL as the filename, and take a cut & paste version of the > default load method from ID3FileType and change it to use urllib2 to > open it instead of a local file open. > > Might work. Might not. No warranty express or implied. Hrm, damn, looks like you'd also have to create a custom ID3 class and override load there too, since that gets called from the ID3FileType load method. Definitely looks like work. -- John Krukoff Land Title Guarantee Company From bruno.desthuilliers at gmail.com Wed May 14 16:35:19 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Wed, 14 May 2008 13:35:19 -0700 (PDT) Subject: Class Methods Vs Any Other Callable References: <98b4a67c-9ec7-407c-8c80-06488bd48a68@e39g2000hsf.googlegroups.com> <690ap7F2u0ftdU1@mid.uni-berlin.de> <238061d6-9423-44c1-90b2-cc09f392db9b@p25g2000hsf.googlegroups.com> Message-ID: <2851a281-d3f2-46c5-8afe-a5dcd6fa31a6@59g2000hsb.googlegroups.com> On 14 mai, 19:45, Arnaud Delobelle wrote: > George Sakkis writes: > > On May 14, 10:19 am, "Diez B. Roggisch" wrote: > > >> > An instance method works on the instance > >> > A Static method is basically a function nested within a class object > >> > A class method is overkill? > > >> If anything, a static method is overkill. See it this way: *if* you for some > >> reason put a method into an enclosing context - isn't it worth having a > >> reference to that? > > > My feeling exactly; these days I almost always use class methods > > instead of static. I vaguely remember seeing somewhere an example > > where a static method was the only (elegant) solution; neither a class > > method nor a plain function would do. I'll post it if I find it unless > > someone beats me to it. > > > George > > __new__ is a static method! __new__ is a special-cased staticmethod that 1/ must not be declared as such and 2/ takes the class object as first args. As far as I'm concerned, it's semantically a classmethod. From marlin_rowley at hotmail.com Thu May 15 11:59:59 2008 From: marlin_rowley at hotmail.com (Marlin Rowley) Date: Thu, 15 May 2008 10:59:59 -0500 Subject: unpack() exploration! Message-ID: All: I've got a script that runs really slow because I'm reading from a stream a byte at a time: // TERRIBLE for y in range( height ): for color in range(4): for x in range( width ): pixelComponent = fileIO.read(4) buffer = unpack("!f",pixelComponent) << unpacks ONE float, but we now can do something with that pixel component. I can speed this up dramatically if I did this: // MUCH FASTER for y in range( height ): for color in range(4): pixelComponent = fileIO.read(4*width) <<<<<<<<< GET a LOT more data from the stream into memory FIRST!! for x in range( width ): buffer = unpack( ?????? ) <<<< how do I get each float from the pixelComponent??? -M _________________________________________________________________ Windows Live SkyDrive lets you share files with faraway friends. http://www.windowslive.com/skydrive/overview.html?ocid=TXT_TAGLM_WL_Refresh_skydrive_052008 -------------- next part -------------- An HTML attachment was scrubbed... URL: From Matthew.Moorland at gmail.com Mon May 5 01:35:43 2008 From: Matthew.Moorland at gmail.com (ETP) Date: Sun, 4 May 2008 22:35:43 -0700 (PDT) Subject: USB HID documentation? Message-ID: I have a little robot project I'm programming in python using the Lynxmotion SSC-32 servo controller via serial. I'd like to use a USB game controller (PS2 style) to control the robot. I've read a number of threads about the difficulty of using USB without extensive understanding of the way it works, but a few have stated that HID is different somehow. I definitely do not have any USB knowledge, and I don't care to get into that. However, if USB-HID is much simpler I would love to learn. I have the python extensions for windows: http://sourceforge.net/project/showfiles.php?group_id=78018 but I haven't found any documentation on how to implement HID in python. Can anyone give me some examples or links? Thanks much. From tjreedy at udel.edu Mon May 12 02:09:09 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 12 May 2008 02:09:09 -0400 Subject: Mathematics in Python are not correct References: <52c855d8-5609-43e0-b98f-9fa87b2808c2@m3g2000hsc.googlegroups.com><200805081914.06459.kyrie@uh.cu> <6b64d8f4-3f61-4295-9298-4633214d1e94@m73g2000hsh.googlegroups.com> Message-ID: "Mark Dickinson" wrote in message news:6b64d8f4-3f61-4295-9298-4633214d1e94 at m73g2000hsh.googlegroups.com... On May 11, 9:36 pm, "Terry Reedy" wrote: |> Do you have in mind any situations in which it is advantageous to have 0**0 |> undefined? | (Playing devil's advocate here.) If you regard x**y as exp(y*log(x)) Which, of course, I was not, but for the sake of discussion.... | then it's not at all clear that 0.**0. should be considered well-defined. Then it seems equally dubious that 0.**y, y>0, should be well-defined. It seems to me that lim as x goes to 0. exp(y*log(x)) is equally well defined whether y is 0 or not, even though there is a discontinuity in the limit. . ... | The big problem here is that the power operation is really trying | to combine two subtly different functionalities (integer powers | and real powers), with quite distinct use-cases, into a single | function. Which leads to problems: witness the mess that's | C99's pow specification: why does it make sense for (-2.0)**2.0 to | return 4.0, while (-2.0)**1.999999999 returns NaN? 2.5 raises an exception. In 3.0, >>> (-2)**1.99999999 (3.9999999722741113-1.2566370355167477e-07j) | Incidentally, the decimal module is slightly schizophrenic about this: That module follows the IBM-led standard, no matter how crazy. Terry Jan Reedy From vivainio at gmail.com Mon May 5 17:57:38 2008 From: vivainio at gmail.com (Ville M. Vainio) Date: Mon, 05 May 2008 21:57:38 GMT Subject: ]ANN[ Vellum 0.16: Lots Of Documentation and Watching References: <3a8e0a8f-3bd1-4650-9104-5c273f14b097@w7g2000hsa.googlegroups.com> Message-ID: <1w4gs9bk.fsf@gmail.com> Paul Boddie writes: > Anyway, I'm just confirming that I'm clearly not one of the "many" > described above. A lot of my own work is licensed under the GPL or I guess it's safe to assume that you are not opposed to using code based on more liberal license, right? :-) My point is: GPL is a reason to reject a tool for some, but MIT/BSD never is. Ultimately, of course, it's up to the preferences of the author but if the idea is to maximize the popularity, GPL is a worse bet. From kyrie at uh.cu Fri May 16 16:31:39 2008 From: kyrie at uh.cu (Luis Zarrabeitia) Date: Fri, 16 May 2008 16:31:39 -0400 Subject: encoding problem Message-ID: <200805161631.39307.kyrie@uh.cu> Hi, guys. I'm trying to read an xml file and output some of the nodes. For that, I'm doing a print node.toprettyxml() However, I get this exception: === out.write(tag.toxml()) UnicodeEncodeError: 'ascii' codec can't encode character u'\xba' in position 190: ordinal not in range(128) === That happens if I "print" it, or send it to stdout, or send it to a file. How can I fix it? cat file works perfectly, and I'm using an utf8 terminal. I'm particularly puzzled that it won't work even if I write to a file opened in "b" mode. Worst thing is... I don't really need that character, just a general idea of how the document looks like. -- Luis Zarrabeitia (aka Kyrie) Fac. de Matem?tica y Computaci?n, UH. http://profesores.matcom.uh.cu/~kyrie From ivlenin at gmail.com Sun May 25 22:42:58 2008 From: ivlenin at gmail.com (I V) Date: Mon, 26 May 2008 02:42:58 GMT Subject: which datastructure for fast sorted insert? References: <4fe8c6cf-9f29-48ab-861b-356f748ffa43@x35g2000hsb.googlegroups.com> Message-ID: On Sun, 25 May 2008 18:42:06 -0700, notnorwegian wrote: > def scrapeSites(startAddress): > site = startAddress > sites = set() > iterator = iter(sites) > pos = 0 > while pos < 10:#len(sites): > newsites = scrapeSite(site) > joinSets(sites, newsites) You change the size of "sites" here, which means you can no longer use the iterator. > wtf? im not multithreading or anything so how can the size change here? How about: def scrape_sites(start_address): sites = set([start_address]) sites_scraped = set() # This will run until it doesn't find any new sites, which may be # a long time while len(sites) > 0: new_sites = set() for site in sites: new_sites.update(scrape_site(site)) sites_scraped.update(sites) sites = new_sites.difference(sites_scraped) return sites From paddy3118 at googlemail.com Mon May 12 02:27:23 2008 From: paddy3118 at googlemail.com (Paddy) Date: Sun, 11 May 2008 23:27:23 -0700 (PDT) Subject: Is using range() in for loops really Pythonic? References: <482657ca$0$25026$607ed4bc@cv.net> <48275316$0$11629$607ed4bc@cv.net> Message-ID: <3042f24f-f32e-4266-8bf5-41cdb511b78d@m45g2000hsb.googlegroups.com> On May 11, 9:28 pm, Arnaud Delobelle wrote: Hi John, Arnaud; > Contrived example: > > # Print 'hello' 10 times; x is not used > for x in xrange(10): > print 'hello' I've used Fortran and C and so would tend to use either i,j,k as the unused loop variable above, or, for clarity, call it something descriptive like loop_count, if the loop body would be clearer. I would also just use range for small, (especially small constant), ranges. > > # By changing what is iterated over, no unused variable: > from itertools import repeat > for msg in repeat('hello', 10): > print msg I guess I would not go to the trouble of using itertools.repeat unless it was simplifying/homogenising a larger expression - i.e if it was part of some functional expression I've never fealt the need for a separate repeat statement myself either. - Paddy. P.S: I do understand that your examples are contrived. Just my thoughts. From greg at cosc.canterbury.ac.nz Thu May 15 04:52:35 2008 From: greg at cosc.canterbury.ac.nz (greg) Date: Thu, 15 May 2008 20:52:35 +1200 Subject: ANN: Pyrex 0.9.8 Message-ID: Pyrex 0.9.8 is now available: http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/ This version has a number of new features: * In-place operators (+= etc.) are now supported. * The Pyrex compiler now has built-in facilities for automatically tracking down and compiling all the modules a given module depends on, and for only compiling modules whose source has changed. * Some restrictions on nogil functions have been relaxed. In particular, it's now possible to declare a C method as nogil. * A feature has been added that makes it easier to manage circular imports between .pxd files. It's now possible to declare two extension types in different .pxd files that refer to each other. What is Pyrex? -------------- Pyrex is a language for writing Python extension modules. It lets you freely mix operations on Python and C data, with all Python reference counting and error checking handled automatically. From mishok13 at gmail.com Tue May 27 11:55:02 2008 From: mishok13 at gmail.com (Andrii V. Mishkovskyi) Date: Tue, 27 May 2008 18:55:02 +0300 Subject: New chairman In-Reply-To: <529d275a-1274-43f4-b6a8-a844c3692711@59g2000hsb.googlegroups.com> References: <3720fb99-ac37-469b-b8ce-ece3ed27b8e5@m36g2000hse.googlegroups.com> <529d275a-1274-43f4-b6a8-a844c3692711@59g2000hsb.googlegroups.com> Message-ID: <192840a00805270855i20ccdb1clfafe8bff575dbd59@mail.gmail.com> 2008/5/27 Sverker Nilsson : > I dont want to be a new Guido. Somebody else please. > Please, explain why should we fork Python? Because Python 3.0 will have 'print' as a function, not as a statement, am I right? Or maybe the reason is a major breakage of C API in Python 3.0, so that Guppy-PE/Heapy will both need a complete re-write? There is a rationale for these changes and you've been told about it several times, but you don't care much to listen. Well, anyway, nobody stops you from forking a project called 'Python'. Python is free software, as you know. > S. > > > On May 27, 5:21 pm, Sverker Nilsson wrote: >> I was talking about Guido van Rossum >> >> The one who decides, so far when people agree >> >> But we can make a new fork >> >> He is the originator, but now it seems, for me, it is hanging out in >> the air >> >> So we need some new leadership >> >> From somebody, somebody like you perhaps. Or me. >> >> Sverker >> >> On May 27, 4:50 pm, "Andrii V. Mishkovskyi" >> wrote: >> >> > 2008/5/27 Sverker Nilsson : >> >> > > seems to be needed >> >> > > He doesn't seem to care much anyway now >> >> > > Or if he cares, he have many other assignments >> >> > Who are you talking about? >> >> > > So should we try to elect a new chairman? >> >> > Chairman? Elaborate please. >> >> > > I am probably not eligible. There must be many others.! >> >> > > Do you dare?consper >> >> > Hm, are you and castrionpi twin brothers or something? >> >> > > S. >> > > -- >> > >http://mail.python.org/mailman/listinfo/python-list >> >> > -- >> > Wbr, Andrii Mishkovskyi. >> >> > He's got a heart of a little child, and he keeps it in a jar on his desk. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Wbr, Andrii Mishkovskyi. He's got a heart of a little child, and he keeps it in a jar on his desk. From roy at panix.com Wed May 21 08:40:37 2008 From: roy at panix.com (Roy Smith) Date: Wed, 21 May 2008 08:40:37 -0400 Subject: about python modules References: <2fc55c56-7408-4f44-b6e2-64f85f341ac9@i36g2000prf.googlegroups.com> Message-ID: In article <2fc55c56-7408-4f44-b6e2-64f85f341ac9 at i36g2000prf.googlegroups.com>, srinivas wrote: > hi friends i am new to python programming. > i am using Python 2.5 and IDLE as editor. > i have developed some functions in python those will be calling > frequently in my main method . > now i want to know how to import my functions folder to python in > sucha way that the functions in functions folder should work like > python library modules . > > i have python in folder C:\python25\.. > and functions folder D:\programs\Functions\ > > pls help me friends how to do that. You need to either: 1) Put your modules in some directory that's already on your python path. To find out what your path is, do: import sys print sys.path It should include a directory which ends in "site-packages". Just drop your modules into that directory. 2) Add the directory where you modules are to your python path. The easiest way to do this is to set PYTHONPATH in your environment. From kyrie at uh.cu Mon May 19 16:29:38 2008 From: kyrie at uh.cu (Luis Zarrabeitia) Date: Mon, 19 May 2008 16:29:38 -0400 Subject: conventions/requirements for 'is' vs '==', 'not vs '!=', etc In-Reply-To: References: Message-ID: <200805191629.38919.kyrie@uh.cu> On Monday 19 May 2008 03:39:36 pm destroooooy wrote: > I'm wondering what is the canonical usage of the keywords 'is' and > 'not' when you're writing conditionals and loops. The one I've been > following is completely arbitrary--I use the symbols '==', '!=' for > numerical comparisons and the words 'is', 'not' for everything else. It's not arbitrary, and you shouldn't be using that convention. The question is really about "equality" versus "identity". Two identical sized cubes may be equal, but they are certainly not the same cube. The main concept here: identity [usually] implies equality, but equality almost never implies identity (two objects that are equal may be distinct nonetheless). More practical example, two angles with the same measure are equal by every mathematical concept, but opposing angles on a parallelogram are not the same one. Sometimes, you need to test for equality, as in "is this user input equal to '1'?". Sometimes, you need to test for identity "is this user input this '1' that I have here?" (note: the second answer should be 'no', unless that by some dark magic the user manages to get that same '1' that is in your code). The most common use case is equality. You test for equality with == and !=. The darker case is identity. You test for identity with "is" and "is not". Whenever you use "is", ask yourself a question: does a negative answer makes sense if the objects are equal? Personally, I like to use "is" with singletons. I find it easier to type and read "if param is None" than "if param == None", but some python developers dislike the first one because of the "dark magic" involved in knowing that None is a singleton. When in doubt, test for equality. Use "is" only when you are certain that you know the difference. Python does some optimizations that may it seem like it is working with 'is' at first, but it really isn't: In: a="hi" In: b="hi" In: a is b Out: True <-- dark magic here, python optimized the string storage, In: a is "h"+"i" <-- by using the same object instead of creating a new one Out: False <-- but even that won't always work, so In: a="a very long string, at least longer than 'hi'" In: b="a very long string, at least longer than 'hi'" In: a is b Out: False <-- never, never rely on magic. I hope I was useful. Cheers, -- Luis Zarrabeitia (aka Kyrie) Fac. de Matem?tica y Computaci?n, UH. http://profesores.matcom.uh.cu/~kyrie From wuwei23 at gmail.com Thu May 22 04:59:28 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 22 May 2008 01:59:28 -0700 (PDT) Subject: HTMLParser error References: <628d3bbf-0fd9-4075-9749-6c8c81f887fa@z72g2000hsb.googlegroups.com> <1aecdaeb-76f1-4a57-88d3-2023dd6e00e4@e39g2000hsf.googlegroups.com> <06ba6753-712e-4c1c-8d2f-c1fd075ed0cf@u6g2000prc.googlegroups.com> <10f12f0c-d08e-41e1-ab6f-10488ae51010@p25g2000pri.googlegroups.com> <42323d1c-9a10-4030-8870-75ed2d10a31e@b64g2000hsa.googlegroups.com> Message-ID: <2b40f742-fe45-45eb-824a-ee904ab53360@b9g2000prh.googlegroups.com> On May 22, 6:22 pm, jonbutle... at googlemail.com wrote: > Still getting very odd errors though, this being the latest: > > Traceback (most recent call last): > File "spider.py", line 38, in > [...snip...] > raise InvalidURL("nonnumeric port: '%s'" % host[i+1:]) > httplib.InvalidURL: nonnumeric port: '' Okay. What I did was put some output in your Spider.parse method: def parse(self, page): try: print 'http://' + page self.feed(urlopen('http://' + page).read()) except HTTPError: print 'Error getting page source' And here's the output: >python spider.py What site would you like to scan? http://www.google.com http://www.google.com http://http://images.google.com.au/imghp?hl=en&tab=wi The links you're finding on each page already have the protocol specified. I'd remove the 'http://' addition from parse, and just add it to 'site' in the main section. if __name__ == '__main__': s = Spider() site = raw_input("What site would you like to scan? http://") site = 'http://' + site s.crawl(site) > Also could you explain why I needed to add that > HTMLParser.__init__(self) line? Does it matter that I have overwritten > the __init__ function of spider? You haven't overwritten Spider.__init__. What you're doing every time you create a Spider object is first get HTMLParser to initialise it as it would any other HTMLParser object - which is what adds the .rawdata attribute to each HTMLParser instance - *and then* doing the Spider- specific initialisation you need. Here's an abbreviated copy of the actual HTMLParser class featuring only its __init__ and reset methods: class HTMLParser(markupbase.ParserBase): def __init__(self): """Initialize and reset this instance.""" self.reset() def reset(self): """Reset this instance. Loses all unprocessed data.""" self.rawdata = '' self.lasttag = '???' self.interesting = interesting_normal markupbase.ParserBase.reset(self) When you initialise an instance of HTMLParser, it calls its reset method, which sets rawdata to an empty string, or adds it to the instance if it doesn't already exist. So when you call HTMLParser.__init__(self) in Spider.__init__(), it executes the reset method on the Spider instance, which it inherits from HTMLParser... Are you familiar with object oriented design at all? If you're not, let me know and I'll track down some decent intro docs. Inheritance is a pretty fundamental concept but I don't think I'm doing it justice. From goldnery at gmail.com Mon May 26 18:26:50 2008 From: goldnery at gmail.com (Gandalf) Date: Mon, 26 May 2008 15:26:50 -0700 (PDT) Subject: Keyboard Events References: <14d057b1-3b62-4efb-bdb2-c20394c7268c@r66g2000hsg.googlegroups.com> <1e920a06-3741-4154-94a1-73b90f659e1b@z72g2000hsb.googlegroups.com> Message-ID: <4d26372a-c07d-4a41-992f-4c158f0c40c3@56g2000hsm.googlegroups.com> On May 27, 12:18 am, Gandalf wrote: > On May 27, 12:00 am, Ivan Illarionov > wrote: > > > On Mon, 26 May 2008 14:40:18 -0700, Gandalf wrote: > > > Thanks! > > > Anyone know which library should i learn then? > > > Looks like you need to dive into Win32 APIhttp://msdn.microsoft.com/en-us/library/ms697544(VS.85).aspxhttp://ms... > > and others > > combined with ctypes. > > > Ivan > > well, that seems extremely valuable but how can i implement those > functions with python? You know what I'm sorry, I will try to understand the ctypes lib before bothering you. thank you all! From kwmsmith at gmail.com Thu May 22 13:49:39 2008 From: kwmsmith at gmail.com (Kurt Smith) Date: Thu, 22 May 2008 12:49:39 -0500 Subject: Books for learning how to write "big" programs In-Reply-To: <219c77ef-dd0c-464b-bb6a-e4f3bee89eae@x41g2000hsb.googlegroups.com> References: <219c77ef-dd0c-464b-bb6a-e4f3bee89eae@x41g2000hsb.googlegroups.com> Message-ID: On Thu, May 22, 2008 at 10:55 AM, duli wrote: > Hi: > I would like recommendations for books (in any language, not > necessarily C++, C, python) which have walkthroughs for developing > a big software project ? So starting from inception, problem > definition, design, coding and final delivery on a single theme > or application. The bigger the project, the more likely it is that you'll have documentation on how to use it (for a language or library, how to use the features in your program) but to take the time to write up a dead-tree book on the project's "inception, problem definition, design, coding and final delivery" is not likely well spent. Anyone who has the expertise to write such a book would probably be spending his time working on the next phase of the project itself. Someone will probably respond with an amazon link to a book that does exactly what you're asking, in which case, I will stand corrected. But I'll be surprised. > > Most of the code I have written and books that I have read deal with > toy programs and I am looking for something a bit more > comprehensive. For example, maybe a complete compiler written in C++ > for some language, or a complete web server or implementing > .net libraries in some language (just a few examples of the scale of > things I am interested in learning). It seems to me the reason toy programs are so prevalent is because they illustrate a (few) well defined ideas in a short amount of code. A big project, necessarily, brings together all kinds of stuff, much of which may not interest the author at all, and so doesn't motivate him to write a book about it. Compilers, web servers & .NET libraries are *widely* varying areas. You may have interest in them all, but to significantly contribute to any requires a fair amount of expertise and specialization. The best route I've found to learn how to organize & program large scale applications is this: find a cutting edge program that interests you and that is open source. Download its source, and read the code. Diagram it. Map it out. Read the comments. Join the mailing list (probably the developer's list), lurk for a while, and ask questions about why they organized things the way they did. Get the overall big picture and learn from it. Better yet, find out what pitfalls they found and avoided (or fell into). Compare their approach & organization with another competing project. This is the wonder of open source software -- you have access to everything, and can learn from all the expertise the developers put into their opus. You can learn the basics from books, but nothing beats analyzing a species in the wild. Kurt From nospam at here.com Sun May 18 15:28:34 2008 From: nospam at here.com (Dennis) Date: Sun, 18 May 2008 20:28:34 +0100 Subject: python confusion possibly related to pickle Message-ID: I have a problem that I don't understand at all. I run a python script, which uses pickle, and it fails. That alone is, perhaps, no big deal. The problem that's got me annoyed is that after getting said error I close the shell window, open a new one, run the python interpreter and type "import pickle" and get the error that the script I'd run earlier caused. Why is this ? To my knowledge, once python stopped running it didn't store anything related to the last time it was run. From ivan.illarionov at gmail.com Sat May 3 21:20:29 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Sun, 4 May 2008 01:20:29 +0000 (UTC) Subject: Feature suggestion: sum() ought to use a compensated summation algorithm References: <481CB283.107@gmail.com> <9d890b77-688e-4207-8eb3-8233d287ecb6@8g2000hse.googlegroups.com> Message-ID: On Sat, 03 May 2008 17:43:57 -0700, George Sakkis wrote: > On May 3, 7:12?pm, Ivan Illarionov wrote: >> On Sun, 04 May 2008 00:31:01 +0200, Thomas Dybdahl Ahle wrote: >> > On Sat, 2008-05-03 at 21:37 +0000, Ivan Illarionov wrote: >> >> On Sat, 03 May 2008 20:44:19 +0200, Szabolcs Horv?t wrote: >> >> >> > Arnaud Delobelle wrote: >> >> >> >> sum() works for any sequence of objects with an __add__ method, >> >> >> not just floats! ?Your algorithm is specific to floats. >> >> >> > This occurred to me also, but then I tried >> >> >> > sum(['abc', 'efg'], '') >> >> >> Interesting, I always thought that sum is like shortcut of >> >> reduce(operator.add, ...), but I was mistaken. >> >> >> reduce() is more forgiving: >> >> reduce(operator.add, ['abc', 'efg'], '' ) # it works 'abcefg' >> > Hm, it works for lists: >> > sum(([1], [2]), []) >> > [1, 2] > > So it's not reduce() that is more forgiving, it's sum() that makes an > exception for strings only. > > >> > However I find the seccond argument hack ugly. Does the sum way have >> > any performance advantages over the reduce way? >> >> Yes, sum() is faster: >> >> $ python -m timeit "" "sum([[1], [2], [3, 4]], [])" 100000 loops, best >> of 3: 6.16 usec per loop >> >> $ python -m timeit "import operator" \ "reduce(operator.add, [[1], [2], >> [3, 4]])" 100000 loops, best of 3: 11.9 usec per loop > > Not really; you measure the import and the attribute access time in the > second case. sum() is 2x faster for adding numbers only: > > # Adding integers > python -mtimeit --setup="x=[1]*100" "sum(x)" 100000 loops, best of 3: > 4.87 usec per loop python -mtimeit --setup="from operator import add; > x=[1]*100" "reduce(add,x)" > 100000 loops, best of 3: 10.1 usec per loop > > # Adding floats > python -mtimeit --setup="x=[1.0]*100" "sum(x)" 100000 loops, best of 3: > 5.14 usec per loop python -mtimeit --setup="from operator import add; > x=[1.0]*100" "reduce(add,x)" > 100000 loops, best of 3: 10.1 usec per loop > > # Adding tuples > python -mtimeit --setup="x=[(1,)]*100" "sum(x,())" 10000 loops, best of > 3: 61.6 usec per loop python -mtimeit --setup="from operator import add; > x=[(1,)]*100" "reduce(add,x,())" > 10000 loops, best of 3: 66.3 usec per loop > > # Adding lists > python -mtimeit --setup="x=[[1]]*100" "sum(x,[])" 10000 loops, best of > 3: 79.9 usec per loop python -mtimeit --setup="from operator import add; > x=[[1]]*100" "reduce(add,x,[])" > 10000 loops, best of 3: 84.3 usec per loop > > George Thanks for correction. Forget about --setup. -- Ivan From tjreedy at udel.edu Thu May 15 03:06:54 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 15 May 2008 03:06:54 -0400 Subject: [x for x in <> while <>]? References: Message-ID: "urikaluzhny" wrote in message news:f8229614-a000-450e-85eb-825e6c1386cf at w7g2000hsa.googlegroups.com... | It seems that I rather frequently need a list or iterator of the form | [x for x in <> while <>] I can think of two ways to interpret that. | And there is no one like this. | May be there is another short way to write it (not as a loop). Is | there? Using loops to write an example of what you mean would make the above clearer. tjr From j.spies at hccnet.nl Mon May 19 15:24:39 2008 From: j.spies at hccnet.nl (Jaap Spies) Date: Mon, 19 May 2008 21:24:39 +0200 Subject: Using Python for programming algorithms In-Reply-To: References: <56c15$483091b1$d4785a98$2536@cache6.tilbu1.nb.home.nl> Message-ID: <32aef$4831d3f8$d4785a98$9215@cache6.tilbu1.nb.home.nl> Vicent Giner wrote: > Thank you very much for all the answers I've got. > > As far as I have understood, Python can be a good alternative, or, at > least, a reasonable choice. > > I intend to design new algorithms for a kind of Optimization problems, > and then I have to implement them and show/prove that they are good > enough, in terms of effectiveness (quality of the solution that the > algorithm is able to find, for some given "difficult" problems), and > not mainly in terms of efficiency (time to find the solution). > > I mean, in order to prove that my algorithms are "good", I have to > compare them with the results given by other algorithms, in terms of > how much better is the solution given by my proposal, in front of the > previous ones. Only comparatives in terms of "number of iterations", > and not "time to find the solution", can be done (I think). > Here you find good company in the Sage developers community! Jaap > And I also realize, from your posted answers, that the point is doing > a good programming work, and that I will have to look very carefully > at all those packages and resources you have mentioned, to do a good > work at Python. > > Any other suggestion will be welcomed. :-) > > Thank you very much again! > > -- > Vicent From mattheww at chiark.greenend.org.uk Wed May 21 18:09:36 2008 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 21 May 2008 23:09:36 +0100 (BST) Subject: Running programs under a python program... References: <43c19b29-878a-41b8-b2c9-48b5d91233c3@t12g2000prg.googlegroups.com> Message-ID: samslists at gmail.com wrote: > So I have a python program that runs a bunch of other programs....it > then loops forever, occasionally executing other programs. > > To run each of these programs my python code executes: > subprocess.Popen(command_line, shell=True, stdout=fd, > stderr=subprocess.STDOUT) > > where command_line is an appropriate command line. :) > > Now my problem is when I abort this program it kills off all the child > processes I've started. In this case I don't want that. How can I > stop the child processes from dieing when I kill off the parent? It depends on why the children are dying. >From what you say, it seems likely that they're trying to write to their standard output, and exiting because that's a pipe that is now closed. If that's the case, it's probably best to start by deciding where you want that output to go when the parent process has ended. Perhaps you can just send it all to a log file in the first place. -M- From pataphor at gmail.com Sun May 18 02:50:23 2008 From: pataphor at gmail.com (pataphor) Date: Sun, 18 May 2008 08:50:23 +0200 Subject: "indexed properties"... References: <7o7r245pb3kqk42odihmf95sifpbbv0rqp@4ax.com> Message-ID: In article , dullrich at sprynet.com says... > >> window.pos = (x,y) > >> > >> seems more natural than > >> > >> window.SetPos(x,y); Yes, and to assign a row in a matrix I'd also like to use either tuples or lists on the right side. > def __add__(self, other): > return Row([x + y for x, y in zip(self, other)]) > > worked as hoped if self is a Row and other is a > Row _or_ a list.) > > Anyway, my m.rows[j] can't be a list, because > I want to be able to say things like > m.rows[0] += c*m.rows[2]. Allowing > m.rows[j] = [1,2,3] seems convenient, while > requiring m.rows[j] = Row([1,2,3]) fixes > this problem. Hmm. I'm not sure how far you'd go along with Gabriel's idea of decoupling views from data but I think there isn't even a need for using a matrix as the underlying data type. Why not use a flat list and compute matrix positions according to a row or column adressing scheme on the fly? P. From kyosohma at gmail.com Thu May 22 13:04:40 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Thu, 22 May 2008 10:04:40 -0700 (PDT) Subject: Python is slow References: Message-ID: <2aa4c986-57d8-41dd-9f18-911625965620@z72g2000hsb.googlegroups.com> On May 22, 11:14?am, cm_gui wrote: > Python is slow. ? ?Almost all of the web applications written in > Python are slow. ? Zope/Plone is slow, sloow, so very slooow. ?Even > Google Apps is not faster. ? Neither is Youtube. > Facebook and Wikipedia (Mediawiki), written in PHP, are so much faster > than Python. > Okay, they probably use caching or some code compilation -- but Google > Apps and those Zope sites probably also use caching. > > I've yet to see a web application written in Python which is really > fast. What about http://www.torontolife.com/ ? It uses Django... Mike From castironpi at gmail.com Tue May 13 06:57:35 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 13 May 2008 03:57:35 -0700 (PDT) Subject: Best way to delimit a list? References: <57129f75-b496-40fc-8b2d-d93ba544d4c5@u6g2000prc.googlegroups.com> <5c339461-b9d9-4b80-aa90-9bdd4d401525@q24g2000prf.googlegroups.com> Message-ID: On May 13, 5:46?am, dannywebs... at googlemail.com wrote: > On May 13, 11:28 am, dannywebs... at googlemail.com wrote: > > > > > > > Hi - I have a list returned from popen/readlines, and am wondering how > > to go about iterating over each item which was returned (rather than > > currently having the whole lot returned). > > > so far: > > > >>> f=os.open("./get_hostnames").readlines > > > returns ['host1 host2 host3 ... hostN\n]' > > > i'd like to be in a position to iterate through these, grabbing each > > host. ?I have played with transmuting to a str, and using split, and > > this works, but I get the subscript brackets from the list output as > > expected, as the list output is now a string literal, and this is not > > what I want - and I think it's a bit long-winded to do a search 'n > > replace on it - hence why I ask in the subject what's the best way. > > > >>> f=str(f) > > >>> f.split() > > > ["['host1","host2", ... ,"hostN\n']"] > > > Any help is highly appreciated > > > ta > > > dan. > > I did indeed mean "os.popen", no "os.open"- Hide quoted text - > > - Show quoted text - I do indeed write a pretty fine real-time, low-bandwidth, game. It is like real-time chess, and seen the movie, Tron. Can't the P2Ps zip up in an hour? From roy at panix.com Sat May 24 18:16:04 2008 From: roy at panix.com (Roy Smith) Date: Sat, 24 May 2008 18:16:04 -0400 Subject: Code correctness, and testing strategies References: Message-ID: David wrote: > While it is possible to describe all problems in docs, it can be very > hard to write actual test code. > > For example: sanity tests. Functions can have tests for situations > that can never occur, or are very hard to reproduce. How do you unit > test for those? In some cases, you can use mock objects to mimic the "can never happen" situations. But, you are right, there are certainly cases which are difficult or impossible to test for. TDD is a very powerful tool, but it's just that: a tool. It's not a magic wand. My suggestion is to make using TDD a habit, but don't turn it into a religion. You will undoubtedly find places where it's just the wrong tool. Don't let the fact that it can't do everything keep you from using it when it makes sense. From ian.g.kelly at gmail.com Wed May 14 09:29:33 2008 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 14 May 2008 07:29:33 -0600 Subject: list.__len__() or len(list) In-Reply-To: <87r6c5s71g.fsf@mulj.homelinux.net> References: <87r6c5s71g.fsf@mulj.homelinux.net> Message-ID: <3fc761710805140629yb2aa55ai4cf8f62522ea78d@mail.gmail.com> On Wed, May 14, 2008 at 1:01 AM, Hrvoje Niksic wrote: > Have you tried it? __len__ is in fact marginally slower because it > involves a dict lookup, whereas the built-in len() knows how to cheat > and invoke __len__ through a slot in the C type struct very > efficiently. > > $ python -m timeit -s 'l=[1, 2, 3]' 'len(l)' > 1000000 loops, best of 3: 0.24 usec per loop > $ python -m timeit -s 'l=[1, 2, 3]' 'l.__len__()' > 1000000 loops, best of 3: 0.347 usec per loop For built-in types, sure. For user-defined types in Python, it's the other way around: >>> setup = 'class L:\n def __len__(self): return 42\nl = L()' >>> t1 = timeit.Timer('len(l)', setup) >>> t2 = timeit.Timer('l.__len__()', setup) >>> t1.timeit() 0.63981378918270337 >>> t2.timeit() 0.41051271879526041 From grante at visi.com Sun May 11 20:03:43 2008 From: grante at visi.com (Grant Edwards) Date: Sun, 11 May 2008 19:03:43 -0500 Subject: python without while and other "explosive" statements References: Message-ID: <0oGdnUfSYOXCFLrVnZ2dnUVZ_uLinZ2d@posted.visi> On 2008-05-11, ivo talvet wrote: > Is it possible to have a python which not handle the execution of > "while", "for", and other loop statements ? I would like to allow > remote execution of python on a public irc channel, so i'm looking for > techniques which would do so people won't be able to crash my computer > (while 1: os.fork(1)), or at least won't won't freeze my python in a > infinite loop, make it unresponsive. The easiest thing to to is to limit the amount of files, disk-space, file descriptors, inodes, memory, cpu, and processes that the users are allowed. If bash is your shell, the builtin "ulimit" provides most of those features. The file system quota features provide the rest. > Is there a compiling option (or better, something i can get > with apt-get cos i think compiling myself and handle all the > metastuff myself is somehow dirty) for have a "secure python" > (you can guess what i mean by "secure" in my case) or must i > touch myself the source disable some code lines ? If last > solution, which modifications in which files should i do? My advice is don't try to secure Python itself: secure the environment in which the users are using it. -- Grant Edwards grante Yow! Did I SELL OUT yet?? at visi.com From amit.uttam at gmail.com Wed May 21 18:48:48 2008 From: amit.uttam at gmail.com (amit.uttam at gmail.com) Date: Wed, 21 May 2008 15:48:48 -0700 (PDT) Subject: Separate output for log file and stdout References: <54a53d7f-b137-49cc-8ea4-cc0b184384f0@k1g2000prb.googlegroups.com> <878wy9soce.fsf@benfinney.id.au> <60a036c9-aa6b-4751-b956-8bb8b04459f1@c19g2000prf.googlegroups.com> Message-ID: <46591c0a-7544-4674-8caa-fc56587e71b9@w8g2000prd.googlegroups.com> On May 19, 4:05 pm, "Kam-Hung Soh" wrote: > On Tue, 20 May 2008 06:58:28 +1000, wrote: > > On May 16, 6:37 pm, Ben Finney > > wrote: > >> amit.ut... at gmail.com writes: > >> > I've recently jumped big time into python and I'm working on a > >> > software program for testing automation. > > >> Welcome, to both fields :-) > > > Thanks! I am having a great time learning and coding in python. It's > > an amazing programming language. > > >> > I had a question about proper logging of output. What I would like > >> > is: > > >> > 1. a function syslog (to log output to log file only) > >> > 2. a function stdout (to log output to stdout only) > >> > 3. a function sslog (to log output to both log and stdout) > > >> > Right now I am using StandOut module > > >> Have you investigated the 'logging' module in the Python standard > >> library ? It appears > >> to meet your listed requirements, without need of external > >> dependencies. > > > Hmm..Yeah I didn't realize python had its own standard logging > > facility. I took a look at it and it seems to do the job. However, the > > output seems to be syslog style output. In the program I am writing, > > the log file stores all the output of the commands being run (e.g. tcl > > scripts, etc). Will this be possible using the built in python logging > > module? > > > Thanks, > > Amit > > -- > >http://mail.python.org/mailman/listinfo/python-list > > You can define the format of the log output in basicConfig(), for example: > > from logging import basicConfig, error, info, INFO > ... > basicConfig( > datefmt='%Y%m%d_T%H%M%S', > filemode='a', > filename=LOG_PATH, > format='%(asctime)s,%(levelname)s,%(message)s', > level=INFO > ) > > If you want to log the output of other commands in your log file, you can > connect a pipe to that command. Maybe look at "subprocess -- Subprocess > management" inhttp://docs.python.org/lib/module-subprocess.html > > -- > Kam-Hung Soh Software Salariman Thanks for the reply. Yeah I am using the subprocess module and I am able to capture the output and save it to log a file. However, looking at module-logging the output format is like syslog. What I want is my own custom log file format. I wrote a separate module containing all the functions for the logging but I can't seem to use it globally. How does one use global variables in python? Code: # log.py - A base class that provides logging functionality. # # Copyright 2008 Amit Uttamchandani # import os import sys logfile = None global logfile def createLogFile(filename): '''Opens a file for logging.''' try: logfile = open(filename, 'w') except IOError: print 'Error: Cannot create log file: %s' % os.abspath(logfile) sys.exit(0) def stdlog(logstr): '''Writes output to stdout.''' sys.stdout.write(logstr) def syslog(logstr): '''Writes output to logfile.''' logfile.write(logstr) def agglog(logstr): '''Aggregate output of logstr.''' syslog(logstr) stdlog(logstr) def closeLogFile(): '''Closes the log file.''' logfile.close() Thanks, Amit From darcy at druid.net Sat May 24 16:34:14 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Sat, 24 May 2008 16:34:14 -0400 Subject: Code correctness, and testing strategies In-Reply-To: <18c1e6480805240851t9aa79b4u6f1056a37e011afa@mail.gmail.com> References: <18c1e6480805240851t9aa79b4u6f1056a37e011afa@mail.gmail.com> Message-ID: <20080524163414.70b702b2.darcy@druid.net> On Sat, 24 May 2008 17:51:23 +0200 David wrote: > Basically, with TDD you write the tests first, then the code which > passes/fails the tests as appropriate. However, as you're writing the > code you will also think of a lot of corner cases you should also > handle. The natural way to do this is to add them to the code first. > But with TDD you have to first write a test for the corner case, even > if setting up test code for it is very complicated. So, you have these > options: > > - Take as much time as needed to put a complicated test case in place. Absolutely. You may think that it is slowing you down but I can assure you that in the long run you are saving yourself time. > - Don't add corner case to your code because you can't (don't have > time to) write a test for it. If you don't have time to write complete, working, tested code then you have a problem with your boss/client, not your methodology. > - Add the corner case handling to the code first, and try to add a > test later if you have time for it. Never! It won't happen. > Having to write tests for all code takes time. Instead of eg: 10 hours > coding and say 1/2 an hour manual testing, you spend eg: 2-3 hours > writing all the tests, and 10 on the code. In conventional development, 10 hours of code requires 90 hours of testing, debugging and maintenance. Under TDD (and agile in general) you spend 20 hours testing and coding. That's the real economics if you want to deliver a good product. > I think that automated tests can be very valuable for maintainability, > making sure that you or other devs don't break something down the > line. But these benefits must be worth the time (and general > inconvenience) spent on adding/maintaining the tests. I can assure you from experience that it always is worth the time. > If I did start doing some kind of TDD, it would be more of the 'smoke > test' variety. Call all of the functions with various parameters, test > some common scenarios, all the 'low hanging fruit'. But don't spend a > lot of time trying to test all possible scenarios and corner cases, > 100% coverage, etc, unless I have enough time for it. Penny wise, pound foolish. Spend the time now or spend the time later after your client complains. > I'm going to read more on the subject (thanks to Ben for the link). > Maybe I have some misconceptions. Perhaps just lack of experience. Read up on actual case studies. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From bbxx789_05ss at yahoo.com Mon May 12 19:07:10 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Mon, 12 May 2008 16:07:10 -0700 (PDT) Subject: downloading a link with javascript in it.. References: <5358bfb4-f79a-4575-98b8-9a85ba41652d@d45g2000hsc.googlegroups.com> Message-ID: <57fc5176-db60-413d-99cf-d8a71574cfe8@27g2000hsf.googlegroups.com> On May 12, 4:59?pm, 7stud wrote: > On May 12, 1:54?pm, Jetus wrote: > > > I am able to download this page (enclosed code), but I then want to > > download a pdf file that I can view in a regular browser by clicking > > on the "view" link. I don't know how to automate this next part of my > > script. It seems like it uses Javascript. > > The line in the page source says > > > href="javascript:openimagewin('JCCOGetImage.jsp? > > refnum=DN2007036179');" tabindex=-1> > > 1) Use BeautifulSoup to extract the path: > > JCCOGetImage.jsp?refnum=DN2007036179 > > from the html page. > BeautifulSoup will allow you to locate and extract the href attribute: javascript:openimagewin('JCCOGetImage.jsp?refnum=DN2007036179'); See: "The attributes of Tags" in the BS docs. Then you can use string functions(preferable) or a regex to get everything between the parentheses(remove the quotes around the path, too) From darcy at druid.net Fri May 2 00:44:16 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Fri, 2 May 2008 00:44:16 -0400 Subject: #!/usr/bin/env python vs. #!/usr/bin/python In-Reply-To: <87abj91j8u.fsf@benfinney.id.au> References: <87abj91j8u.fsf@benfinney.id.au> Message-ID: <20080502004416.94012685.darcy@druid.net> On Fri, 02 May 2008 13:24:01 +1000 Ben Finney wrote: > I much prefer "#! /usr/bin/python" because I want my Python programs > to, by default, be run with the default Python, and depend on Python > being installed by the operating system's package manager. On systems > that use shebang lines and that actually have standardised filesystem > locations, the default Python is found at '/usr/bin/python'. You have lived a sheltered life. Not every packaging system puts the executible in /usr/bin. Many systems use /usr/local/bin. NetBSD uses /usr/pkg/bin but allows you to define your own pkg root. Using /usr/bin/env allows your code to run on all these systems. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From mattheww at chiark.greenend.org.uk Sun May 25 09:11:08 2008 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 25 May 2008 14:11:08 +0100 (BST) Subject: need some help in serving static files inside a wsgi apps References: <6e15240b-520d-4f01-9d21-83f9feeefc2d@x41g2000hsb.googlegroups.com> <69r113F34rbeeU1@mid.uni-berlin.de> <69t1m5F33b3ncU2@mid.uni-berlin.de> Message-ID: <4ob*BLLds@news.chiark.greenend.org.uk> Diez B. Roggisch wrote: >Sebastian 'lunar' Wiesner schrieb: >> I guess, Apache does some kind of memory caching for files, which are often >> requested and small enough to fit into the system memory. May be, that's >> what the OP is referring to ... > I'm not aware of that, and I even more seriously doubt it. Because > caching is a complicated, domain-dependend subject that would > *immediately* cry for configuration - e.g. caching strategies and such. This is available in current apache with mod_file_cache (for an explicitly configured list of files). I think the circumstances where you'd want to use it are quite rare. -M- From castironpi at gmail.com Sat May 10 11:06:11 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 10 May 2008 08:06:11 -0700 (PDT) Subject: Now, as for the jokes: Python! Message-ID: Dear Monty, Grail This. The grail is unarmed and floating. Stop posting the newsgroup. Python is Monty Python. In the sense of identity ascription, of course. Trivially not, A Bartender. From paul at boddie.org.uk Wed May 7 06:27:20 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 7 May 2008 03:27:20 -0700 (PDT) Subject: Python MIDI in 2008 References: <1076a133-4376-4b96-a06b-4bb990ec3f42@f63g2000hsf.googlegroups.com> Message-ID: On 6 Mai, 11:43, Max M wrote: > [Python Midi] > It does not have real time support even though I did write it with that > support in mind. I just never got around to write it as I did not need > it myself. > > I also developed it on Windows and I found it to be a bore to get real > time midi working. > > It would probably be easier now that I am on Linux. I was previously quite interested in getting MIDI output working for a game I wrote, and I suppose that the Python Midi package would have been of interest (with pygame probably handling the interface to the hardware), but given the bizarre kernel module gymnastics required to support real-time output (and I still don't know if my sound hardware actually supports MIDI directly or not), I decided in the end to use timidity to generate normal audio files and to send those through the sound system instead. Of course, that more or less eliminates any real- time aspects. Paul From CLDWesterhof at gmail.com Sat May 3 06:05:31 2008 From: CLDWesterhof at gmail.com (Decebal) Date: Sat, 3 May 2008 03:05:31 -0700 (PDT) Subject: How to use a parameter in a class Message-ID: <4923419b-4de0-4739-b02d-753636ef0220@y21g2000hsf.googlegroups.com> I have the following class: ##### class Dummy(): value = 0 def __init__(self, thisValue): print thisValue self.value = thisValue value = thisValue def testing(self): print 'In test: %d' % self.value def returnValue(self): return self.value result = someFuntion(default = value) ##### But the last line does not work. I would like to do a call like: dummy = Dummy(thisValue = 12) And that someFunction gets a default value of 12. How can I do that? From mediocre_person at hotmail.com Fri May 2 15:14:17 2008 From: mediocre_person at hotmail.com (Nick J Chackowsky) Date: Fri, 02 May 2008 14:14:17 -0500 Subject: list.index crashes when the element is not found In-Reply-To: <18cd9b76-91e7-4830-af75-cc9c97536347@d45g2000hsc.googlegroups.com> References: <491f6$481b6455$547@news.teranews.com> <18cd9b76-91e7-4830-af75-cc9c97536347@d45g2000hsc.googlegroups.com> Message-ID: <32a12$481b6809$3524@news.teranews.com> TkNeo wrote: > On May 2, 1:58 pm, Nick J Chackowsky > wrote: >> TkNeo wrote: >>> WHAT ? >>> This is crazy >> Crazy like a fox? >> >> a = [1, 2, 3] >> try: >> a.index(99) >> except: >> a.append(99) >> finally: >> print a.index(99) >> >> MY question: which exception should I actually be catching there? >> ** Posted fromhttp://www.teranews.com** > > ofcouse try catch is going to work but in ideality the index function > should return a -1 and no way in hell crash. But -1 is a valid index in Python. a = [1, 2, 3] print a[-1] ** Posted from http://www.teranews.com ** From fetchinson at googlemail.com Wed May 21 12:33:48 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Wed, 21 May 2008 09:33:48 -0700 Subject: Python and Flaming Thunder In-Reply-To: <48343e56$0$5866$426a74cc@news.free.fr> References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <20080514215943.14c92f16.johnjsal@NOSPAMgmail.com> <94bac166-d13c-44dd-af84-db19e19488b8@w1g2000prd.googlegroups.com> <8cfd3523-8d16-40bc-b904-94a6a36a414d@p25g2000pri.googlegroups.com> <48343e56$0$5866$426a74cc@news.free.fr> Message-ID: >>> Or just: >>> >>> If command is "quit" ... >> >> Hmmm. In Flaming Thunder, I'm using "is" (and "is an", "is a", etc) >> for assigning and checking types. For example, to read data from a >> file and check for errors: >> >> Read data from "input.txt". >> If data is an error then go to ... > > Arf ! A goto ! You are surely aware of the fact that the C source of python also uses goto at tons of places. Is that Arf! too? Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From nicolas.dandrimont at gmail.com Sat May 10 17:13:10 2008 From: nicolas.dandrimont at gmail.com (Nicolas Dandrimont) Date: Sat, 10 May 2008 23:13:10 +0200 Subject: Python, are you ill? In-Reply-To: <893925d6-a4f8-4446-9bf3-475302dbaa04@j22g2000hsf.googlegroups.com> References: <893925d6-a4f8-4446-9bf3-475302dbaa04@j22g2000hsf.googlegroups.com> Message-ID: <20080510211310.GA24788@dirichlet.crans.org> * wxPythoner at gmail.com [2008-05-10 13:59:37 -0700]: > If you are in the interactive prompt of the Python interpreter and you > do this > > print """Testing\""" or print '''Testing\''' > > you get three dots [...] as if Python expects a code block. If you > press Enter, you get three dots again, and again, and again... You > can't get out of the code block with pressing the Enter key; That is because Python expects you to end the triple-quoted string with three unescaped quotes. > you have to press Ctrl+Z (if you're in Linux) in order to get out of that code > block, which then throws you back to the Linux command line, but > before that it prints this line > > [1]+ Stopped python > That ^Z just suspends your Python interpreter. It has become a job you can now bring to foreground again with "fg". (but it's a feature of your shell, not of Python) > > If you do > > print "Testing\" or print 'Testing\' > > you get an error, but not of you use the triple quotes. Is that a bug > in the interpreter perhaps? The fact is, that triple-quoted strings can span on multiple lines, and that single-quoted strings cannot (without the line ending with a "\"). So no, it's not a bug in the interpreter. Regards, -- Nicolas Dandrimont -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From bruno.desthuilliers at gmail.com Thu May 15 16:58:37 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Thu, 15 May 2008 13:58:37 -0700 (PDT) Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <2a32179a-9439-449c-bd07-fff6a4075aee@s50g2000hsb.googlegroups.com> <7ee5dffd-df8f-46f0-bd78-c81ac0418a9a@d77g2000hsb.googlegroups.com> <65ef773e-a1c3-4adb-a18b-e8b8451efe5e@b5g2000pri.googlegroups.com> <68trmmF2vjivnU1@mid.uni-berlin.de> <68tuhfF2unducU1@mid.uni-berlin.de> <68tulsF2unducU2@mid.uni-berlin.de> <68u1lqF2sv8gjU1@mid.uni-berlin.de> <6ed29b01-30c8-455f-b0be-2b5343e506da@p39g2000prm.googlegroups.com> <2f97dd8d-d2a7-4d2c-910b-047e8db29a1c@f63g2000hsf.googlegroups.com> Message-ID: On 15 mai, 19:30, Lie wrote: > On May 15, 4:08 am, "bruno.desthuilli... at gmail.com" > > > > wrote: > > On 14 mai, 08:08, Lie wrote: > > > > On May 14, 12:51 pm, Lie wrote: > > > > > And your 8 by 8 cross compiler doesn't impress me at all, they're all > > > > based on x86/IA-32 architecture which is quite similar, no PowerPC, > > > > SPARC, ARM, no other CISC or RISC architecture. And your compiler is a > > > > single language compiler instead of three dimensional compiler that > > > > GCC is (cross platform, cross target platform, cross language). > > > > And to add, I also need to mention that Python doesn't need to be > > > compiled at all, > > > No language needs compilation - it's an implementation problem, not a > > language problem. Now all the Python's implementations I know do use > > compilation (to byte-code). > > > its py and pyo file is architecture independent. > > > True, but this is not strictly related to being compiled or not. > > It's true, it's implementation problem whether a language is compiled > or not, but what I was emphasizing was that Python's code is > architecture independent at all stages (that is visible to the user > and the programmer), on the other hand, a compiled code is a compiled > code is a compiled code, Ever wondered what all these .pyc files were ? > it cannot be architecture independent without > packing multiple binaries in the same executable (like in Macintosh's > universal binary) or using an emulation (with huge overheads) or at > least using a compatibility layer (which doesn't always work) and all > this is done in the layer that is visible to user and programmer > (programmer having to compile against everything and user having to > download the correct executable) instead of being done in a platform > independent way that interpreted language like Python have. Python is not interpreted, because being interpreted is a feature of an implementation, not of a language. And so far, no known Python implementation is (strictly speaking) interpreted - they all compile to byte-code. "compiled" doesn't necessarily imply "compiled to platform native binary code", you know. Ok, this may look like a bit on the splitting hairs side. But may I remind you that to run ever a .pyc file, you do need to have the Python runtime (VM + quite a lot of libs) installed one way (normal install) or another (packed in something that looks like an ordinary "executable" - whatever this means for the target platform) ? OTHO, it's true that a .pyc file is platform-independant - it just requires the correct versions of quite a lot of platform-dependant binaries. Wait... Isn't this code some kind of a "visible to the user and programmer" "compatibilty layer" ? From nik600 at gmail.com Tue May 27 04:50:00 2008 From: nik600 at gmail.com (nik600) Date: Tue, 27 May 2008 10:50:00 +0200 Subject: integration with browser In-Reply-To: <6a0722F33j3q5U1@mid.uni-berlin.de> References: <69vmlgF35akucU1@mid.uni-berlin.de> <6a0722F33j3q5U1@mid.uni-berlin.de> Message-ID: <9469c3170805270149q4b67e572rafc0dddf9e3e657e@mail.gmail.com> On Mon, May 26, 2008 at 6:32 PM, Diez B. Roggisch wrote: > nik600 wrote: > >> Both win and linux if possible i don't have preference for gui. Thanks > > Qt4 now contains the WebKit html widget. > > Diez > -- > http://mail.python.org/mailman/listinfo/python-list > Thanks but the problem about using something different between IE of FF is that the css and javascript management is different. Web developers usually check only 3 browser IE FF Opera I know that using an external engine limits the portability of the solutions, but i need something that works exaclty as the browser. -- /*************/ nik600 https://sourceforge.net/projects/ccmanager https://sourceforge.net/projects/reportmaker https://sourceforge.net/projects/nikstresser From tjreedy at udel.edu Sun May 25 21:34:50 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 25 May 2008 21:34:50 -0400 Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com><8763t3by81.fsf@benfinney.id.au> <09847cfc-eaec-4adc-8cbf-1e2ebbf940c4@m44g2000hsc.googlegroups.com> Message-ID: "Joe P. Cool" wrote in message news:09847cfc-eaec-4adc-8cbf-1e2ebbf940c4 at m44g2000hsc.googlegroups.com... | Actually it is very useful to be able to distinguish | between inside and outside. Which Python allows one to do. | This is obvious for real world things e.g. your | TV. Nobody likes to open the rear cover to switch the channel. The original issue was that users might open the case to do something unplanned and that they would come to depend on and clamor for the maintenance of internal details that the manufacturer wants to change. But in the real world, most customers know and accept that custom alterations and extensions of a product my be model specific. Some things I buy even have a disclaimer that user-visible details might be different from what the instructions say, and only guarantee that the functionality will be as good or better than specified. [...] | Please don't sell a missing feature as a philosophy. I won't if you don't claim that a feature is missing because you don't like its implementation. To most of us, replacing the nearly never used '__' with a keyword would be a auful change. | Please don't tell me that encapsulation does not mean "enforced restriction". There are obviously degrees of enforced restriction. Take your TV example. Most users will respect a 'do not open' request by the manufacturer (Python's '_'.). But some will unscrew anyway. So some makers use fasteners that are resistent to opening without specialized tools from specialized sources -- or perhaps specialized knowledge (Python's '__'). (This is very frustrating if one needs to open such a system.) Or some mark the screws so they can detect and punish entry. At least one (Apple) has intentionally altered internals to punish entry and alteration. Or there is the 'embed in epoxy' method. If you want something equivalent to epoxy embedding, design it, implement it, and share it (if you want). Perhaps one could make an Opaque extension class, perhaps even usable as a mixin class rather than as a single-base class. Terry Jan Reedy From pecora at anvil.nrl.navy.mil Fri May 9 11:14:34 2008 From: pecora at anvil.nrl.navy.mil (Lou Pecora) Date: Fri, 09 May 2008 11:14:34 -0400 Subject: Mathematics in Python are not correct References: <52c855d8-5609-43e0-b98f-9fa87b2808c2@m3g2000hsc.googlegroups.com> Message-ID: In article , Michael Torrie wrote: > wxPythoner at gmail.com wrote: > > Have a look at this: > > > >>>> -123**0 > > -1 > > > > > > The result is not correct, because every number (positive or negative) > > raised to the power of 0 is ALWAYS 1 (a positive number 1 that is). > > No python is correct. you're expression parses this way, when converted > to a lisp-ish prefix expression: > > (- (123 ** 0 )) Yeah, it's just the standard parser. For other situations Python does fine. E.g. In [1]: x=-1 In [2]: x**0 Out[2]: 1 -- -- Lou Pecora From mishok13 at gmail.com Thu May 8 03:56:50 2008 From: mishok13 at gmail.com (Andrii V. Mishkovskyi) Date: Thu, 8 May 2008 10:56:50 +0300 Subject: strftime() argument 1 must be str, not unicode In-Reply-To: <3j952491dh15h5g09lcn0j5g47nkssr8i5@4ax.com> References: <48215537.100@promsoft.ru> <3j952491dh15h5g09lcn0j5g47nkssr8i5@4ax.com> Message-ID: <192840a00805080056g25dd98cu9b01545235f402c@mail.gmail.com> 2008/5/8 Tim Roberts : > "Andrii V. Mishkovskyi" wrote: > > >2008/5/7 Alexandr N Zamaraev : > > >> Subj is bag? > >> > >> Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit > >> (Intel)] on win32 > >> Type "help", "copyright", "credits" or "license" for more information. > >> >>> from datetime import datetime > >> >>> datetime.today().strftime('%Y_%m_%d %H_%M_%S.csv') > >> '2008_05_07 12_30_22.csv' > >> >>> datetime.today().strftime(u'%Y_%m_%d %H_%M_%S.csv') > >> Traceback (most recent call last): > >> File "", line 1, in > >> TypeError: strftime() argument 1 must be str, not unicode > > > > >Unicode and str objects are not the same. Why do you think that this > >is a bug? > > I think that's a perfectly reasonable thing to expect. At the risk of > over-generalization, there is no good reason why, by this point in time, > all of the standard library routines that accept strings shouldn't also > accept Unicode strings. > > It's the duck typing principle. Unicode strings look, walk, and talk like > regular strings. An error like this is not intuitive. On a second thought -- both of you (you and Alexander) are right. I changed mind and posted a bug on Roundup already (bug #2782). > -- > Tim Roberts, timr at probo.com > Providenza & Boekelheide, Inc. > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Wbr, Andrii Mishkovskyi. He's got a heart of a little child, and he keeps it in a jar on his desk. From fetchinson at googlemail.com Tue May 13 13:59:35 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Tue, 13 May 2008 10:59:35 -0700 Subject: Python and Flaming Thunder In-Reply-To: <5504f9ac0805131035t3080fd2fobdf9cee72f647c50@mail.gmail.com> References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <68t4o0F2vaoncU1@mid.uni-berlin.de> <2a32179a-9439-449c-bd07-fff6a4075aee@s50g2000hsb.googlegroups.com> <7ee5dffd-df8f-46f0-bd78-c81ac0418a9a@d77g2000hsb.googlegroups.com> <65ef773e-a1c3-4adb-a18b-e8b8451efe5e@b5g2000pri.googlegroups.com> <02a10e4b-5017-463c-96d2-e1779f2b9ebd@j22g2000hsf.googlegroups.com> <8bd40bb6-5f8d-4256-a41a-fe341d10d476@q1g2000prf.googlegroups.com> <87d4nqgllh.fsf@physik.rwth-aachen.de> <5504f9ac0805131035t3080fd2fobdf9cee72f647c50@mail.gmail.com> Message-ID: Hi Dave, Flaming Thunder looks interesting especially the fact that you claim to have maintainable multi-platform assembler code. Does this mean that if in the next 3 years a new processor architecture comes out you will be able to port your assembler code easily? Can you give us more detail about this? I also have some assembler code which works on 32-bit x86 architectures but porting that to 64-bit is already non-trivial, I mean has to be done by hand. Unless you have an automatic tool to do these things. About pricing: what led the company to pick this particular business model? Have you considered other options? Like releasing the source as GPL or something similar and offering technical support for money, training developers or selling of support material like documentation, etc? Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown -------------- next part -------------- An HTML attachment was scrubbed... URL: From bignose+hates-spam at benfinney.id.au Sun May 11 18:44:19 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 12 May 2008 08:44:19 +1000 Subject: Is using range() in for loops really Pythonic? References: <482657ca$0$25026$607ed4bc@cv.net> <41078222-aec0-4e8b-8a1f-945cdf814498@m73g2000hsh.googlegroups.com> <48275446$0$11628$607ed4bc@cv.net> Message-ID: <87mymw8nr0.fsf@benfinney.id.au> John Salerno writes: > num = 33 > > for x in xrange(10): > print num += 1 Which is better done by 'num += 10'. Can you come up with an example that isn't trivially replaced with clearer code? That might make it clearer what your concern is. > The [above] example [...] is simply doing something 10 times, and > what it's doing has nothing to do with 'x' or xrange. So it seems > like an abuse of the for loop. In such cases, the name 'dummy' is conventionally bound to the items from the iterator, for clarity of purpose:: for dummy in range(10): # do stuff that makes no reference to 'dummy' Also note that 'range' will return an iterator (not a list) in Python 3.0, and 'xrange' is removed since it's then obsolete . -- \ ?Isn?t it enough to see that a garden is beautiful without | `\ having to believe that there are fairies at the bottom of it | _o__) too?? ?Douglas Adams | Ben Finney From stef.mientki at gmail.com Sat May 10 19:18:29 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Sun, 11 May 2008 01:18:29 +0200 Subject: how to reference my own module ? In-Reply-To: References: <4825F6BB.9090707@gmail.com> Message-ID: <48262D45.7000803@gmail.com> Terry Reedy wrote: > "Stef Mientki" wrote in message > news:4825F6BB.9090707 at gmail.com... > | hello, > | > | I've a library that I import as > | > | import ppygui.api as gui > | > | the reason for this construct is that I've to use different libraries > | for different platforms. > | > | Now I like to write some examples in the library (activated by if > | __name__ == '__main__' :) > | and I would that these examples can be used in the user program just by > | copy / paste. > | > | For calling a function / class in the user program I've to write: > | > | sizer = gui.VBox () > | > | So also write exactly the same sentence in the library examples, > | but "gui" is not recognized > | > | Any ideas how I can realize the above ? > > Put the import statement in the example so 'gui' *is* recognized ;-) > > If I understand what you meant ... > xploro/test/begin.py > ----------------------------- > def start(): > print('hello') > > if __name__ == '__main__': > import xploro.test.begin as etb > etb.start() > ---------------------------- > prints 'hello'| > > Import is a name-binding statement that also creates a module when it does > not exist already. Modules can be bound to multiple names just like any > other object. > Thanks Terry, works like a charm, why is the obvious often so difficult overlooked ;-) cheers, Stef > Terry Jan Reedy > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From ohad911 at gmail.com Wed May 21 10:45:21 2008 From: ohad911 at gmail.com (ohad frand) Date: Wed, 21 May 2008 17:45:21 +0300 Subject: problem with import / namespace In-Reply-To: <483427BF.6030805@shopzeus.com> References: <483427BF.6030805@shopzeus.com> Message-ID: Hi Thanks for the answer. I probably didnt write the problem accurately but it is not as you described. (i already read before the section that you pointed and it didnt help me) the problem is that i dont want to import a file from different directory but only from the same directory. \\1\tmp2.py imports \\1\tmp1.py \\2\tmp2.py imports \\2\tmp2.py but when i execute the following script in the interpreter i get that the second tmp2.py file imports not the file from the same directory but the file that was already imported by the first executed tmp2.py file. the shell script is: >>> import os >>> os.chdir("c:\\1") >>> execfile("tmp2.py") <- here the executaion is OK >>> os.chdir("c:\\2") >>> execfile("tmp2.py") <- here the execution is not ok because tmp2.py file imports the tmp1.py file from c:\\1 which is not OK in between those two execfile commands i tried to do a lot of things but every time python imported the incorrect file for the second execution. (i am not building a package and those names are just examples for the problem, i am not really using 1 and 2 names as dirs) I hope that this time i am more understood Thanks again Ohad On Wed, May 21, 2008 at 4:46 PM, Laszlo Nagy wrote: > ohad frand wrote: > >> Hi >> I have a problem that the solution to it must be very simple but i couldnt >> fint it's answer in the internet so far (i searched for couple of days) >> the problme is as follows: >> >> i have two directories e.g. "\\1" and "\\2" >> in each directory i have two files with the same names e.g. "tmp1.py" and >> "tmp2.py" >> > > So this is what you have: > > /1/tmp1.py > /1/tmp2.py > /2/tmp1.py > /2/tmp2.py > > each tmp2.py file imports tmp1 from its same directory (import tmp1) - >> thats the problem >> if i execute one file (\\1\tmp2.py) than the execution is ok >> but when i try after that to execute the second file (\\2\tmp2.py) than >> the tmp1 file from the wrong directory ( - directory 1 in this case) is >> imported instead. >> > > When you try to import a module, python starts to search for it. The was it > does the search is very well defined. It mostly depends on the current > directory and sys.path. You can read more about this here: > > http://docs.python.org/tut/node8.html#searchPath > > This is very basic thing - you should read and go through the tutorial > before asking questions like this. :-) > > i tried many things to try to solve it, i removed the previous path from >> sys.path and added the new one, i tried to change current working directory >> with os.chdir() >> I tried to delete from locals and from globals the name tmp1 before >> running the second file but nothing worked. >> please help >> > The problem is still not well defined. Python works as expected and > documented, but apparently you do not know how to import 1/tmp2.py from > 2/tmp1.py. There are several ways to do it, and we cannot tell which one is > correct. It depends on what are these modules for. > > Here are the solution that you would use (most likely) as a beginner: > > > #1 first, rename your "1" and "2" directories to "one" and "two". If you > are creating a package with modules, then you have to define the package's > name with its directory. Since identifiers cannot begin with digits in > Python, you need to use an identifier-like name for your subdirs. It is a > good idea anyway. A package name called "1" would tell nothing about what it > does? > #2 place your main application in /app/app.py > #3 create /app/one/__init__.py and /app/two/__init__.py files (they can be > empty) > - inside your app.py file either make sure that the current dir is /app, or > insert /app in the first place in sys.path > > > Then for example, inside two/tmp1.py you can do this: > > > import one.tmp1 > import one.tmp2 > import two.tmp1 > > one.tmp1.somefunc() > two.tmp1.somefunc() > > > You got the idea. > > Laszlo > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From castironpi at gmail.com Thu May 8 01:27:43 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 7 May 2008 22:27:43 -0700 (PDT) Subject: pickle problem References: Message-ID: On May 7, 11:02?pm, krustymon... at gmail.com wrote: > I'm wondering if anyone can help with a workaround for a problem I > currently have. ?I'm trying to set up a prefork tcp server. > Specifically, I'm setting up a server that forks children and has them > listen on pipes created with os.pipe(). ?The parent process for the > group starts an inet:tcp server on a given port. ?In the parent, after > a "socket.accept()", I'm trying to pickle the connection object to > send over an IPC pipe (as stated previously), but I get the following > error: > > File "/usr/lib/python2.4/copy_reg.py", line 76, in _reduce_ex > ? ? raise TypeError("a class that defines __slots__ without " > TypeError: a class that defines __slots__ without defining > __getstate__ cannot be pickled > > Does anyone know of a workaround for this? ?Maybe my approach to this > is wrong? ?Any help would be appreciated. > > Jay The group currently holds that pickling socket objects is non-optimal to the ends of making money. We can tell you good ways to accomplish what you set out to do all the same. I find it educational; that's fine in my book. Part of the resistence comes from a resistence to monarchy. The bottleneck is the starting of a second Python process. There are a number of objects which can't be pickled, though. If you can objectively prioritize the next step in pickling sockets, you may find out sooner when it will come in to Python. But that's the hard part; speaker recommends against. We accept your idea is to get a process around the socket barrier. Can you close the server in Part N, hear the connection in Part N+1, spawn a new server in N+2, and handle the first one in N+3? Is it suitable to your minds? From castironpi at gmail.com Mon May 5 23:14:05 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Mon, 5 May 2008 20:14:05 -0700 (PDT) Subject: STL multimap References: <43029641-3df0-45ac-8e22-9684f7354d80@k37g2000hsf.googlegroups.com> Message-ID: <3d9af15b-8b3d-4fd3-bc81-2a4ed0592a86@l64g2000hse.googlegroups.com> On May 5, 6:40?pm, castiro... at gmail.com wrote: > On May 5, 1:26?pm, Aaron Watters wrote: > > > > > > > Hi there. ?Maybe a little more context would > > help us figure out what you want here... > > > On May 5, 1:28 pm, castiro... at gmail.com wrote: > > > > Is multimap just a syntax-checked dictionary of mutable sequences? > > > I think the equivalent of a multimap can be > > implemented several different ways, depending on > > what you need: > > > ? for > > ? ? ? ?1 maps to 2,3 > > ? ? ? ?5 maps to 7 > > ? - dictionary mapping to lists > > ? ? ? ?{ 1:[2,3], 5:[7] } # supports unhashable values > > ? - dictionary mapping to dictionary > > ? ? ? ?{ 1:{2:None,3:None}, 4:{7:None} } # faster for certain lookups > > and dense data > > ? - dictionary with tuple/pairs as keys > > ? ? ? ?{ (1,2):None, (1,3):None, (4,7):None } # streamlined for > > existence testing > > It's possible there are four different kinds of multimaps. > > objects map to set > objects map to frozenset > objects map to sequence > frozenset maps to object > > What does the STL use? ?I am interested in a serialization that > changes certain bits and appends more. ?Prior discussion brought me to > multimap, but that quotient stifled it. > > > If you search usenet (google groups) for multimap > > you will find some nice discussions by Alex Martelli and others. > > > > Is def( a ): a[:]= [x] a trick or part of the language? ?It looks > > > pretty sharp in variable-width. > > > You lost me here. > > I was referring to a couple of threads from the Winter [cit. off'd.] > that never really gelled. > > Modifying parameters is crucial to a number of control flow structures > (program divisions). ?Examples could come handy. I am questioning if value-succession is a sufficient protocol to side effects. Fibonacci numbers are formulaic. Month names are tabular. Factorials are recursive. Hold there is no use for a factorial generator, i.e. no factorials in business. Things the real world generates are network requests of a station, successive graphics (though so far only for games*), month names (and other units of time), produce, and dollar values in the form of prices. * Information display isn't the top of the market. Simple matching that's hard to explain in a formal language can yield scheduling, value, opinion. It is not clear that art or architecture have tender/vital value. I.e., it's possible that the only value of computers is automation in a system that is already pretty fine at food, utilities, and walls. If recursive generators are really useless (erect wall might not be), there's no jobs in looking in to it. Which brings me to persistence of generators juxtaposed to merely persistence of functions. Sequences could map into a database pretty easily, in a line or less, if deque/set/dict (i.e. non-sequential) don't modify easily on disk, what's the function that allocates in a database? > >>> def a( x ): x[:]= [x[0]+ 1] > ... > >>> b= [2] > >>> a(b) > >>> b > > [3] From cjw at ncf.ca Thu May 8 08:55:36 2008 From: cjw at ncf.ca (Colin J. Williams) Date: Thu, 08 May 2008 08:55:36 -0400 Subject: PCBuild.sin - Attempt to compile Python using Visual Studio 2008 Message-ID: The readme.txt has: All you need to do is open the workspace "pcbuild.sln" in Visual Studio, select the desired combination of configuration and platform and eventually build the solution. Unless you are going to debug a problem in the core or you are going to create an optimized build you want to select "Release" as configuration. Unfortunately, the Express Edition (Free) doesn't handle "solution" files. Installed Edition: VC Express Microsoft Visual C++ 2008 91909-152-0000052-60812 Microsoft Visual C++ 2008 Does anyone have any advice for a person who has limited C++ experience and none with the Visual C++ please? Colin W. From unknown_hero007 at hotmail.com Fri May 9 08:36:59 2008 From: unknown_hero007 at hotmail.com (Unknown Hero) Date: Fri, 9 May 2008 05:36:59 -0700 (PDT) Subject: Scanning through Windows registry... References: <48216129.5090405@timgolden.me.uk> <2f0e3ef0-c33d-4dc3-819e-1c78e5bccb31@8g2000hse.googlegroups.com> Message-ID: <3a2ea1ec-7fa1-4740-aefa-ff83807fc227@x35g2000hsb.googlegroups.com> Ah, never mind, got it to work. Here's the code now. I hope I won't run into another problems later :D #Goes through all keys and subkeys in the selected hive (defined as root) and replaces the value 'old' with the value 'new' # #IMPORTANT! You should always back up the registry before attempting to modify it. #The author of this script CANNOT BE HELD RESPONSIVE for any damage caused by running this script. # #To customize the script to your liking, you can alter the values old, new, root. # #old and new can be any string value #root has to be one of the following: # # _winreg.HKEY_LOCAL_MACHINE # _winreg.HKEY_CURRENT_USER # _winreg.HKEY_CLASSES_ROOT # _winreg.HKEY_USERS # _winreg.HKEY_CURRENT_CONFIG import _winreg #For accessing windows registry, included in Python 2.0. import sys #For reading arguments (command line), included in every Python release. HIVES = { "HKEY_LOCAL_MACHINE" : _winreg.HKEY_LOCAL_MACHINE, "HKEY_CURRENT_USER" : _winreg.HKEY_CURRENT_USER, "HKEY_CLASSES_ROOT" : _winreg.HKEY_CLASSES_ROOT, "HKEY_USERS" : _winreg.HKEY_USERS, "HKEY_CURRENT_CONFIG" : _winreg.HKEY_CURRENT_CONFIG } class RegKey: def __init__ (self, name, key): self.name = name self.key = key def __str__ (self): return self.name def walk (top): """walk the registry starting from the key represented by top in the form HIVE\\key\\subkey\\..\\subkey and generating key, subkey_names, values at each level. key is a lightly wrapped registry key, including the name and the HKEY object. subkey_names are simply names of the subkeys of that key values are 3-tuples containing (name, data, data-type). See the documentation for _winreg.EnumValue for more details. """ try: if "\\" not in top: top += "\\" root, subkey = top.split ("\\", 1) # print "KEY:", root + "\\" + subkey key = _winreg.OpenKey (HIVES[root], subkey, 0, _winreg.KEY_READ | _winreg.KEY_SET_VALUE) subkeys = [] i = 0 while True: try: subkeys.append (_winreg.EnumKey (key, i)) i += 1 except EnvironmentError: break values = [] i = 0 while True: try: values.append (_winreg.EnumValue (key, i)) i += 1 except EnvironmentError: break yield RegKey (top, key), subkeys, values for subkey in subkeys: for result in walk (top + "\\" + subkey): yield result except WindowsError: # print 'Could not open key', root + "\\" + subkey + ", access denied!\n" pass except: print 'Other error!' def main(start, startHandle, old, new): basickeys = [] i = 0 while True: try: basickeys.append (_winreg.EnumKey (startHandle, i)) i += 1 except EnvironmentError: # print i, 'subkeys found!' break for x in range(len(basickeys)): for key, subkey_names, values in walk (start + "\\" + basickeys[x]): # print key for (name, data, type) in values: # print " ", name, "=>", data if type == _winreg.REG_SZ: Character = 0 Correct = 0 FoundStart = FoundEnd = 0 Found = False for y in range(len(data)): try: if Character < len(old): # print old[Character], data[y] if old[Character] in data[y]: Character = Character + 1 Correct = Correct + 1 except: pass if Correct is len(old): # print 'Debug!' Replace = "" Character = 0 for y in range(len(data)): if not Found: if old[0] in data[y]: FoundStart = int(y) FoundEnd = FoundStart + len(old) Found = True # for y in range(FoundStart): # Replace = Replace + data[y] for y in range(len(new)): Replace = Replace + new[y] # for y in range(FoundEnd, len(data)): # Replace = Replace + data[y] Found = True if Found: # print "OLD:", old, "will be replaced with:", Replace _winreg.SetValueEx (key.key, name, 0, type, data.replace (old, Replace)) def help(): #Show help print 'USAGE: Registry.py [HIVE] [OLD] [NEW]' print ' HIVE: The root key in registry you want to go through.' print ' HKEY_CLASSES_ROOT' print ' HKEY_CURRENT_USER' print ' HKEY_LOCAL_MACHINE' print ' HKEY_USERS' print ' HKEY_CURRENT_CONFIG' print '' print ' OLD: The value to search for.' print ' Wrap multiword strings with \"\".' print '' print ' NEW: The value which will replace OLD.' print ' Wrap multiword strings with \"\".' #Check for arguments #HIVE, old, new while True: #Check if invalid number of arguments are given if len(sys.argv) is 1: help() break # for x in range(len(sys.argv)): # print 'sys.argv[' + str(x) + ']:', sys.argv[x] #Check if hive is first if sys.argv[1].upper() in ('HKEY_CURRENT_USER', 'HKEY_LOCAL_MACHINE', 'HKEY_CLASSES_ROOT', 'HKEY_USERS', 'HKEY_CURRENT_CONFIG'): start = sys.argv[1].upper() else: help() break #Check that not only one argument is given (at least two required, preferably three) if len(sys.argv) is 2: help() break old = sys.argv[2] if len(sys.argv) is 4: new = sys.argv[3] else: help() break if start in ('HKEY_CLASSES_ROOT'): startHandle = _winreg.HKEY_CLASSES_ROOT elif start in ('HKEY_CURRENT_USER'): startHandle = _winreg.HKEY_CURRENT_USER elif start in ('HKEY_LOCAL_MACHINE'): startHandle = _winreg.HKEY_LOCAL_MACHINE elif start in ('HKEY_USERS'): startHandle = _winreg.HKEY_USERS elif start in ('HKEY_CURRENT_CONFIG'): startHandle = _winreg.HKEY_CURRENT_CONFIG else: help() break main(start, startHandle, old, new) break From nyamatongwe+thunder at gmail.com Mon May 26 05:12:05 2008 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Mon, 26 May 2008 09:12:05 GMT Subject: Why does python not have a mechanism for data hiding? In-Reply-To: References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <8763t3by81.fsf@benfinney.id.au> <09847cfc-eaec-4adc-8cbf-1e2ebbf940c4@m44g2000hsc.googlegroups.com> Message-ID: Russ P.: > The encapsulation wouldn't be as > airtight as "private" in C++, so clients could still get access ... C++ private is not airtight as you have access to pointer arithmetic as well as #define private public Neil From skanemupp at yahoo.se Wed May 7 17:49:24 2008 From: skanemupp at yahoo.se (globalrev) Date: Wed, 7 May 2008 14:49:24 -0700 (PDT) Subject: explain this function to me, lambda confusion References: <81addfb5-254f-4a2b-a2bc-044592cee07f@p25g2000hsf.googlegroups.com> Message-ID: <080475c4-f5b3-4445-8c64-f99f82b87aac@b64g2000hsa.googlegroups.com> On 7 Maj, 23:47, globalrev wrote: > and what si the diffrence here: > > g = lambda x=5:x*x > g = lambda x:x*x > > the first was a mistake to write but it worked > and the x=5 seems to be completely ignored. why? it has no effect at > all? ah wait now i see it has a default kind of then. g() returns 25 while g(8) returns 64. From arnodel at googlemail.com Wed May 28 16:48:54 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 28 May 2008 21:48:54 +0100 Subject: Writing a function from within Python References: Message-ID: Aaron Scott writes: > Is it possible to change the content of a function after the function > has been created? For instance, say I make a class: > > class MyClass: > def ClassFunction(self): > return 1 > > And I create an object: > > MyObject = MyClass() > > Is there any way to change the content of the function, a la pseudo- > code: > > MyObject.ClassFunction = "return 2" Yes there is: >>> class Foo(object): ... def __init__(self, x): ... self.x = x ... def bar(self): ... return self.x ... >>> foo = Foo('spam') >>> foo.bar() 'spam' >>> from types import MethodType >>> def newbar(self): ... return self.x + ', yummy!' ... >>> foo.bar = MethodType(newbar, foo) >>> foo.bar() 'spam, yummy!' HTH -- Arnaud From castironpi at gmail.com Tue May 20 09:27:25 2008 From: castironpi at gmail.com (castironpi) Date: Tue, 20 May 2008 06:27:25 -0700 (PDT) Subject: do you fail at FizzBuzz? simple prog test References: <39709320-66e1-40e9-a351-c769c9a94585@x41g2000hsb.googlegroups.com> Message-ID: On May 20, 6:57?am, Wolfgang Grafen wrote: > globalrev schrieb: > > > > > > >http://reddit.com/r/programming/info/18td4/comments > > > claims people take a lot of time to write a simple program like this: > > > "Write a program that prints the numbers from 1 to 100. But for > > multiples of three print "Fizz" instead of the number and for the > > multiples of five print "Buzz". For numbers which are multiples of > > both three and five print "FizzBuzz". > > > for i in range(1,101): > > ? ? if i%3 == 0 and i%5 != 0: > > ? ? ? ? print "Fizz" > > ? ? elif i%5 == 0 and i%3 != 0: > > ? ? ? ? print "Buzz" > > ? ? elif i%5 == 0 and i%3 == 0: > > ? ? ? ? print "FizzBuzz" > > ? ? else: > > ? ? ? ? print i > > > is there a better way than my solution? is mine ok? > > Your example is comprehensive compared to many other suggestions which > is an advantage IMO. I minimised it further > > for i in range(start, stop, step): > ? ? ?if not i%15: > ? ? ? ? ?print "FizzBuzz" > ? ? ?elif not i%3: > ? ? ? ? ?print "Fizz" > ? ? ?elif not i%5: > ? ? ? ? ?print "Buzz" > ? ? ?else: > ? ? ? ? ?print i > > Best regards > > Wolfgang- Hide quoted text - > > - Show quoted text - This one eliminates the modulo operation. dyn= list( xrange( 1, 101 ) ) for i in xrange( 1, len( dyn ), 3 ): dyn[ i ]= '' for i in xrange( 1, len( dyn ), 5 ): dyn[ i ]= '' for i in xrange( 1, len( dyn ), 3 ): dyn[ i ]+= 'Fizz' for i in xrange( 1, len( dyn ), 5 ): dyn[ i ]+= 'Buzz' for d in dyn: print d Can we compare? From nyamatongwe+thunder at gmail.com Sun May 11 04:22:20 2008 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Sun, 11 May 2008 08:22:20 GMT Subject: Any other UI kits with text widget similar to that in Tk? In-Reply-To: References: Message-ID: <01yVj.94$IK1.36@news-server.bigpond.net.au> Kenneth McDonald: > I'm wondering if any of the other GUI kits have a text widget that is > similar in power to the one in Tk. The main text widget in GTK+ was modeled after Tk but I don't know how well it succeeded in implementing this. Neil From a_jtim at bellsouth.net Tue May 13 07:25:59 2008 From: a_jtim at bellsouth.net (Tim Arnold) Date: Tue, 13 May 2008 04:25:59 -0700 (PDT) Subject: using PIL for good screenshots References: Message-ID: On May 12, 8:11?pm, pyt... at bdurham.com wrote: > Tim, > > Sounds like an interesting project. > > Have you considered using SnagIt to produce your screenshots?www.TechSmith.com/SnagIt > > Malcolm Thanks for the interest on this, but I don't control what the writers use to get the screenshot. They give me a 8-bit png screenshots (sometimes 24-bit) captured at 96 dpi. The part I can control comes after that--I need a workflow for getting the screenshot into print, looking as good as possible. thanks, --Tim Arnold From paul.hankin at gmail.com Fri May 9 11:09:58 2008 From: paul.hankin at gmail.com (Paul Hankin) Date: Fri, 9 May 2008 08:09:58 -0700 (PDT) Subject: Grabbing previous iteration in a dict References: <25657e4e-45c2-4a1f-948d-26ac64a75cd7@u6g2000prc.googlegroups.com> Message-ID: <2bbcd24b-d36d-47dd-a0fa-4d7333e85fef@a23g2000hsc.googlegroups.com> On May 9, 10:10?am, dannywebs... at googlemail.com wrote: > Hello all, > > I have a dictionary of which i'm itervalues'ing through, and i'll be > performing some logic on a particular iteration when a condition is > met with trusty .startswith('foo'). ?I need to grab the previous > iteration if this condition is met. ?I can do something with an extra > var to hold every iteration while iterating, but this is hacky and not > elegant. Often when you're iterating, 'hacky' code can be lifted out into a separate generator, keeping the details of the hacks nicely away from your code. That's true here... def iterprevious(seq): """Generate pairs of (previous element, current element) from seq.""" last = None for x in iter(seq): yield last, x last = x Then, when you want use it... for previous, (key, value) in iterprevious(d.iteritems()): ... In the loop, previous will either be None if we're on the first element, otherwise (previous_key, previous_value). -- Paul Hankin From pavlovevidence at gmail.com Sun May 11 21:52:48 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 11 May 2008 18:52:48 -0700 (PDT) Subject: Is using range() in for loops really Pythonic? References: <482657ca$0$25026$607ed4bc@cv.net> <41078222-aec0-4e8b-8a1f-945cdf814498@m73g2000hsh.googlegroups.com> <48275446$0$11628$607ed4bc@cv.net> <87mymw8nr0.fsf@benfinney.id.au> Message-ID: On May 11, 6:44 pm, Ben Finney wrote: > In such cases, the name 'dummy' is conventionally bound to the items > from the iterator, for clarity of purpose:: > > for dummy in range(10): > # do stuff that makes no reference to 'dummy' Is this documented? I've never heard of this convention. It's not PEP 8, and I've never seen consistent usage of any name. I'd be interested in knowing where you read that this was a convention, or in what subcommunities it's a convention in. I think dummy is a terrible name to use for this, since in no other usage I can think of does the word "dummy" suggest something isn't used. In fact, quite the opposite. For example, the dummy_threads module is most definitely used; the word dummy means that it's stripped down. Based on that, your usage of the symbol dummy above would suggest to me that it's a value used in lieu of something else (such as a calculated value). In mathematics, a dummy argument another name for the independent variable of a function (or more accurately, the symbol used to represent it), which also doesn't match your usage. If a value isn't used, then I think the most clear name for it is "unused". Carl Banks From szrRE at szromanMO.comVE Tue May 27 00:52:35 2008 From: szrRE at szromanMO.comVE (szr) Date: Mon, 26 May 2008 21:52:35 -0700 Subject: blogs, longbets.org, and education of sociology References: <1c97ba8a-b758-4891-a3c4-20e462361934@z16g2000prn.googlegroups.com> <358ec7c3-4a25-4591-a705-03446e074b20@25g2000hsx.googlegroups.com> Message-ID: j.oke wrote: > On 26 Mag, 01:25, "xah... at gmail.com" wrote: >> For about the past 10 years, ... > > Q: How many comp.lang.X trolls does it take to change a light bulb? > > A: One, and Superman. One to hold the bulb, and Superman to screw the > planet. Are you saying Superman is harming the planet? :-) -- szr From skanemupp at yahoo.se Fri May 9 19:53:15 2008 From: skanemupp at yahoo.se (globalrev) Date: Fri, 9 May 2008 16:53:15 -0700 (PDT) Subject: regexp help References: <834d8448-5d6a-4f49-9be6-6501a0b5fd92@k37g2000hsf.googlegroups.com> Message-ID: ty. that was the decrypt function. i am slo writing an encrypt function. def encrypt(phrase): pattern = re.compile(r"([bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ])") return pattern.sub(r"1\o\1", phrase) doesnt work though, h becomes 1\\oh. def encrypt(phrase): pattern = re.compile(r"([bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ])") return pattern.sub(r"o\1", phrase) returns oh. i want hoh. i dont quite get it.why cant i delimit pattern with \ From dingo_1980 at yahoo.com Mon May 12 20:53:51 2008 From: dingo_1980 at yahoo.com (dingo_1980 at yahoo.com) Date: Mon, 12 May 2008 17:53:51 -0700 (PDT) Subject: Sparse Matrix Multiplications Message-ID: I was trying to create a sparse matrix using scipy.sparse (100000 X 100000) with just the first row and first column filled with ones. Lets call this matrix Asp. This is how I created Asp from scipy import sparse Asp = scipy.lil_matrix(100000,100000) for i in range(100000): Asp[i,0] = i Asp[0,i] = i Bsp = (Asp.tocsr())*(Asp.tocsr()) This multiplication to get Bsp is taking a long time (to the order of over an hour). Is there some other way of storing such huge sparse matrices and doing their multiplications or is this the most optimal way? From code at pizzashack.org Sun May 18 15:43:54 2008 From: code at pizzashack.org (Derek Martin) Date: Sun, 18 May 2008 15:43:54 -0400 Subject: python confusion possibly related to pickle In-Reply-To: References: Message-ID: <20080518194354.GA27968@dragontoe.org> On Sun, May 18, 2008 at 08:28:34PM +0100, Dennis wrote: > The problem that's got me annoyed is that after getting said error I > close the shell window, open a new one, run the python interpreter > and type "import pickle" and get the error that the script I'd run > earlier caused. Why is this ? Well, what's the error? Sounds like your system could be b0rked (or at least your python installation)... but depending on the error, there could be other explanations. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From usenet-nospam at well-adjusted.de Thu May 29 16:41:38 2008 From: usenet-nospam at well-adjusted.de (Jochen Schulz) Date: Thu, 29 May 2008 22:41:38 +0200 Subject: maximum recursion depth? References: <7b55f3e5-b6f6-4c64-992e-47382d7803e7@m44g2000hsc.googlegroups.com> <15b59f39-3983-4795-9482-d265a67a4fde@f63g2000hsf.googlegroups.com> <6a4oumF3464loU1@mid.uni-berlin.de> Message-ID: * Marc 'BlackJack' Rintsch: > On Wed, 28 May 2008 02:28:54 -0700, bearophileHUGS wrote: >> Dennis Lee Bieber, the ghost: >> >>> I'd have to wonder why so many recursive calls? >> >> Why not? > > Because of the recursion limit of course. And function call overhead in > Python is quite high compared to an iterative approach. One of my pet projects[1, it's about building and searching trees] made heavy use of recursion in the beginning. I rewrote parts of it using iteration because I hit the recursion limit and suspected a performance hit as well. To my (mild) surprise, the rewrite didn't perform significantly better. My benchmarks only showed an improvement of a few percent in runtime. I didn't measure memory usage, though. J. [1] http://well-adjusted.de/mspace.py/ (Sorry, baerophile, I'll get back to you about this! My SNV working copy is currently a mess and I need to clean that up first.) -- I feel yawning hollowness whilst talking to people at parties. [Agree] [Disagree] From srp at ideadevice.com Wed May 28 22:46:54 2008 From: srp at ideadevice.com (Saju Pillai) Date: Thu, 29 May 2008 08:16:54 +0530 Subject: Any way to loop through object variables? In-Reply-To: <483D8614.7000808@islandtraining.com> References: <483D7A47.3030606@ecs.soton.ac.uk> <483D8614.7000808@islandtraining.com> Message-ID: <7695C97A-008C-46A1-A872-1E8F73A560B4@ideadevice.com> On 28-May-08, at 9:49 PM, Gary Herron wrote: > Dave Challis wrote: >> Hi, >> Just wondering if there's a way to iterate through all variables >> which >> an object has set? >> >> Specifically, I'm using the OptionParser module, which returns an >> options object, containing all command line options as object >> variables. >> I'd like to iterate over these rather than getting at them by name. >> >> Cheers, >> Dave > > For this object (and many others), you can get at the attributes > with the vars(...) builtin. > It returns a dictionary of attribute names and values. Also dir(object) will get you the list of attributes of that object. -srp > > > Gary Herron > > > -- > http://mail.python.org/mailman/listinfo/python-list > > > -- > http://mail.python.org/mailman/listinfo/python-list From gilly.dekel at gmail.com Sun May 4 13:11:50 2008 From: gilly.dekel at gmail.com (Gilly) Date: Sun, 4 May 2008 10:11:50 -0700 (PDT) Subject: Real Time Midi File Playback - Reading and Writing midi at the same time Message-ID: <4e5b78a7-bc7a-4c1e-8552-b8175a9cbe32@m3g2000hsc.googlegroups.com> Hi I am trying to create an application that uses some form of input to create a midi file. I would like for this to be a 'real time' process. In other words, I want to be able to begin playing the midi file before I finish writing it, and continue writing as it plays. I would really appreciate any help possible on this matter. Thanks!! From deets at nospam.web.de Tue May 27 11:24:04 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 27 May 2008 17:24:04 +0200 Subject: New chairman References: <3720fb99-ac37-469b-b8ce-ece3ed27b8e5@m36g2000hse.googlegroups.com> Message-ID: <6a2ndjF35q29pU1@mid.uni-berlin.de> Sverker Nilsson wrote: > I was talking about Guido van Rossum > > The one who decides, so far when people agree > > But we can make a new fork Good luck with that. Weren't you the one concerned about changes in Py3K that forced you to change your memory profiler? Now you want to introduce a *third* codebase beside python2.x and python3.x? Interesting course of action. > He is the originator, but now it seems, for me, it is hanging out in > the air Why do you think so? Because you don't like Py3K? > So we need some new leadership > > From somebody, somebody like you perhaps. Or me. Well - be my guest to form your own cult. Diez From castironpi at gmail.com Thu May 15 22:30:48 2008 From: castironpi at gmail.com (castironpi) Date: Thu, 15 May 2008 19:30:48 -0700 (PDT) Subject: call tree tool? References: <3k1Xj.3430$7k7.2352@flpi150.ffdc.sbc.com> <13666537-1237-4165-8f61-780a752a2842@59g2000hsb.googlegroups.com> <37761a22-23db-455e-b23c-6b89a1ae77b2@b1g2000hsg.googlegroups.com> Message-ID: On May 15, 9:27?pm, castironpi wrote: > On May 15, 6:53?pm, castironpi wrote: > > > > > > > On May 15, 4:26?pm, "Dan Upton" wrote: > > > > On Thu, May 15, 2008 at 5:19 PM, jay graves wrote: > > > > On May 15, 3:47 pm, m... at pixar.com wrote: > > > >> I'm cleaning up some old code, and want to see what orphan > > > >> functions might be sitting around. > > > > >> Is there a static call tree analyzer for python? > > > > > How about > > > >http://pycallgraph.slowchop.com/ > > > > > ... > > > > Jay Graves > > > > -- > > > >http://mail.python.org/mailman/listinfo/python-list > > > > Have you checked to see if PyChecker or pylint can help you? > > > Apparently they can find unused variables at least, I don't know > > > whether they do functions or not. > > > I think of dynamic programming and dynamic code, but voice. ?Does that > > mean sing about it?- Hide quoted text - > > > - Show quoted text - > > I have to write a song. ?Somebody?- Hide quoted text - > > - Show quoted text - Sorry for the frequent posts: I think I have to write a noise about train cars crossing rail, putting numbers on frequencies, and send code. Train whistles are pretty good too. I believe those are the ones that start to go on keystrokes. I'd try to compare differences between those and bowling pins. A couple others are coins clinking and poker chips. Generally speaking, tapping metals and glass. From bbxx789_05ss at yahoo.com Sun May 11 22:27:29 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Sun, 11 May 2008 19:27:29 -0700 (PDT) Subject: File Creation Not Working In A Thread Class? References: <7qGVj.32505$KJ1.18416@newsfe19.lga> <48275955.4000106@islandtraining.com> <48275A1F.5080606@bc90021.net> Message-ID: On May 11, 5:50?pm, Gary Herron wrote: > bc90021 wrote: > > You are a perfect example of exactly what I was talking about, and why > > the Python community is such a poor one. > > I though you were treated quite fairly all things considered. ? (You > started the personal attacks, the whining about the group, the > accusations of arrogance, and the refusal to believe we all *knew* the > error was in your file name calculation and not in Python threads.) > > This group is widely acknowledged as one of the more friendly groups > around, ?and in fact we keep it that way by coming down rather hard on > those who abuse either the members of the group or the purpose of the > group. That is a blantant lie. This group has well known members that are some of the biggest jackasses I've ever encountered on the internet. I've never heard a peep out of anyone criticizing their behavior. If I were their employer, and I read some of the stuff they posted, I would fire them on the spot. From jzgoda at o2.usun.pl Fri May 16 10:24:15 2008 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Fri, 16 May 2008 16:24:15 +0200 Subject: Variable by label In-Reply-To: References: Message-ID: rocco.rossi at gmail.com pisze: > Is there any function which will return a variable by passing to it > the string containing the variable's name? Something like this for > instance: > > foo = some_function("foo") > > or perhaps it's a dictionary. I don't know, but I would really like to > find out how it can be done. I guess it is achievable. getattr(object, attrname, default) -- Jarek Zgoda Skype: jzgoda | GTalk: zgoda at jabber.aster.pl | voice: +48228430101 "We read Knuth so you don't have to." (Tim Peters) From kyosohma at gmail.com Fri May 9 10:07:15 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 9 May 2008 07:07:15 -0700 (PDT) Subject: help needed! References: Message-ID: <0829ee61-3322-44fd-9404-582d86e70347@r66g2000hsg.googlegroups.com> On May 9, 8:54?am, drjekil wrote: > i have a script which will do a specific task for a file in a folder,now i > would like to do the same task ?for the all files in that folder(25 > files).how can i do that? > > Thanks in advance. > > -- > View this message in context:http://www.nabble.com/help-needed%21-tp17148388p17148388.html > Sent from the Python - python-list mailing list archive at Nabble.com. Or use the glob module and a loop... Mike From workitharder at gmail.com Thu May 22 19:45:52 2008 From: workitharder at gmail.com (bukzor) Date: Thu, 22 May 2008 16:45:52 -0700 (PDT) Subject: simple way to touch a file if it does not exist References: <68629786-1cef-4dc5-99d9-4967ebecd10f@r66g2000hsg.googlegroups.com> <4834C05D.6020608@gmail.com> <0cada27d-8f5f-482e-9acc-4da032edb27e@f36g2000hsa.googlegroups.com> <69kkd1F33ahahU1@mid.uni-berlin.de> Message-ID: <62ba83ad-ee44-4d5a-bac9-346478effa69@a70g2000hsh.googlegroups.com> On May 22, 12:07 am, Marc 'BlackJack' Rintsch wrote: > On Wed, 21 May 2008 17:56:38 -0700, bukzor wrote: > > On May 21, 5:37 pm, Nikhil wrote: > > >> if os.path.exists('file'): > >> open('file', 'w').close() > > >> Right? > > > You only want to blank it if it exists? If it doesn't exist you won't > > create it. > > The .close() is superlative: since you don't keep the value, it gets > > deallocated and closed by the destructor. > > The language neither guarantees *when* an object will be deallocated nor > that its destructor is called *at all*. It's cleaner to explicitly close > the file. > > Ciao, > Marc 'BlackJack' Rintsch Good to know. From aahz at pythoncraft.com Sat May 24 23:30:16 2008 From: aahz at pythoncraft.com (Aahz) Date: 24 May 2008 20:30:16 -0700 Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> Message-ID: In article <52ba2118-d095-48a6-8844-2ee4c2ec2be1 at m36g2000hse.googlegroups.com>, Sh4wn wrote: > >first, python is one of my fav languages, and i'll definitely keep >developing with it. But, there's 1 one thing what I -really- miss: >data hiding. I know member vars are private when you prefix them with >2 underscores, but I hate prefixing my vars, I'd rather add a keyword >before it. > >Python advertises himself as a full OOP language, but why does it miss >one of the basic principles of OOP? Will it ever be added to python? Not directly addressing your point except insofar as it appears that your understanding of OOP may be limited: "...some experts might say a C++ program is not object-oriented without inheritance and virtual functions. As one of the early Smalltalk implementors myself, I can say they are full of themselves." --zconcept -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Need a book? Use your library! From banibrata.dutta at gmail.com Sun May 11 00:15:26 2008 From: banibrata.dutta at gmail.com (Banibrata Dutta) Date: Sun, 11 May 2008 09:45:26 +0530 Subject: multiple Python versions, but on Windows (how to handle registry updates) In-Reply-To: References: <3de8e1f70805090358p27796919jb885138406ade6aa@mail.gmail.com> <3de8e1f70805092138y4ca414ck2be6b5246afa664b@mail.gmail.com> Message-ID: <3de8e1f70805102115j5f0bf985w3952facf49a66d79@mail.gmail.com> Thanks Gabriel & Terry. Those explanations make perfect sense. What is the recommended way, to find the "compatible" packages that include .dll's / .pyd's or dependencies that are Python release specific ? For example, is there a 'yum' or other automatic dependency checking mechanism which works accross OS's (Windows & Linux), which will allow me to find the other (s.a. 3rd party) packages, which would work with say Python2.2 ? Is it a completely manual exercise, where I read the README or Package Notes or Release Notes, and figure out the required version of package ? On 5/11/08, Gabriel Genellina wrote: > > En Sat, 10 May 2008 01:38:24 -0300, Banibrata Dutta < > banibrata.dutta at gmail.com> escribi?: > > > given that I already have Python2.5 installed & will install Python2.4, > will > > copying the ../Lib/site-packages/ from 2.5 into 2.4's, work ? > > i think the answer is "no", but still asking. is it package specific ? > > > > does it matter if the packages were egg drops ? > > Packages containing only .py modules ("pure" packages) are OK; packages > using C extensions (.dll, .pyd) have to be rebuilt (or you have to download > the binaries for the other Python version). > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > -- regards, Banibrata http://www.linkedin.com/in/bdutta http://octapod.wordpress.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at timgolden.me.uk Thu May 29 04:18:19 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 29 May 2008 09:18:19 +0100 Subject: How to get all the variables in a python shell In-Reply-To: References: Message-ID: <483E66CB.1010003@timgolden.me.uk> lixinyi.23 at gmail.com wrote: > I'm currently working on a scientific computation software built in > python. > What I want to implement is a Matlab style command window <-> > workspace interaction. > > For example, you type 'a=1' in the command window, and you see a list > item named 'a' in the workspace. > You double click the icon of the item, and you see its value. You can > modify the value of the list item, > 1 -> 100 etc, after which if you go back to the command window and > type 'a' and press enter, you see that > varable a's value has been changed to 100. > > So my question is : if you have two DOS command windows running under > WINDOWS OS, how can you make them share the same internal variable > buffer? Or is there any easier way to implement such kind of > interaction? I stronly suggest you look at IPython [1]. To do what I think you're describing, you'd need to hack or reimplement the interpreter. And that's what they've done. ISTR that they even have a branch which is dealing with parallel instances. TJG [1] http://ipython.scipy.org/moin/ From deets at nospam.web.de Wed May 21 05:12:09 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 21 May 2008 11:12:09 +0200 Subject: scalable xml References: Message-ID: <69i7c8F32ha2iU1@mid.uni-berlin.de> hyperboreean wrote: > Hi, I am writing the application server for a three-tier architecture > and sending the client's response in xml. My question is: is there a way > to build the xml dom in a more scalable way and faster way than just > creating every textNode and element for it? I have tons of data to > transmit and it drives me crazy having to build that dom manually. > > I am not sure if this is a stupid question as I don't know other > alternatives ... maybe just provide a template xml which I can fill with > data but that can introduce some pretty ugly bugs in the application. You should have a look at the ElementTree-package (which also comes api-compatible as lxml). These allow for a much more pythonic way of creating XML-trees. However you might consider using a much more concise format such as json for transport (if you have control over the client). It reduces the data-amount to about a tenth or so (of course depending on your xml-dialect), with considerable gains in processing time. And then there in fact are some template languages such as KID and genshi that might suit you because they enforce proper XML. Diez From bruno.42.desthuilliers at websiteburo.invalid Thu May 15 10:31:29 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 15 May 2008 16:31:29 +0200 Subject: datamining .txt-files, library? In-Reply-To: <96f60dc3-fe60-45fa-befe-70d7ae5a330a@d77g2000hsb.googlegroups.com> References: <8ab6802f-ac2c-4492-b793-704126567a8e@a1g2000hsb.googlegroups.com> <96f60dc3-fe60-45fa-befe-70d7ae5a330a@d77g2000hsb.googlegroups.com> Message-ID: <482c4934$0$6041$426a74cc@news.free.fr> Chris a ?crit : > On May 15, 2:27 pm, globalrev wrote: >> i have a big collection of .txt files that i want to open and parse to >> extract information. >> >> is there a library for this or maybe even built in? > > os.open to open the files What's wrong with (builtin) open ? From pataphor at gmail.com Tue May 20 07:31:58 2008 From: pataphor at gmail.com (pataphor) Date: Tue, 20 May 2008 13:31:58 +0200 Subject: Write bits in file References: Message-ID: <20080520133158.3cdab604@hyperspace> On Sun, 18 May 2008 06:36:28 -0700 (PDT) Monica Leko wrote: > Yes. I need arbitrary, 8bits, than 10 bits for something else, than > sequence of bytes, than 10 bits again, etc. Here's something to get you started. No guarantees, but I managed to write four 10 bit numbers to a file producing 5 bytes, saying hello. I was just looking for an excuse to use send. P. def gen(f): L = [] def flush(L): L.reverse() s = ''.join(map(str,L)) j = int(s,2) f.write(chr(j)) while 1: x = yield if x in [0,1]: L.append(x) else: break if len(L) == 8: flush(L) L = [] if L: while len(L) < 8: L.append(0) flush(L) yield def tenbits(i): for j in range(9,-1,-1): yield i >> j & 1 def charbits(s): for c in s: i = ord(c) for j in range(8): yield i >> j &1 def byten(L): while L: yield L[:10] L = L[10:] def test(): f = file('out.dat','w') g = gen(f) g.send(None) for x in [90,611,397,758]: for bit in tenbits(x): g.send(bit) g.send('stop') f.close() def test1(): bits = list(charbits('hello')) L = [] for x in byten(bits): L.append(int(''.join(map(str,x)),2)) print L if __name__=='__main__': test() From mimi.vx at gmail.com Sun May 11 07:02:00 2008 From: mimi.vx at gmail.com (mimi.vx) Date: Sun, 11 May 2008 04:02:00 -0700 (PDT) Subject: what does int means for python ? References: <4826bf47$0$14345$e4fe514c@news.xs4all.nl> <7548143b-3dfe-478a-8db8-00541ec2863a@27g2000hsf.googlegroups.com> Message-ID: <3fdd2ec3-cfba-41a9-90d4-c75ff4fb5b82@m3g2000hsc.googlegroups.com> On May 11, 12:05 pm, alefajnie wrote: > > try arr[2][3] instead. > > > basically your version is trying to index an array with a tuple argument (2,3). > > > --irmen > > oh, you're right. > > btw, is any simple way to create multi-dimension array ? > any built-in function ? test numpy from scipy package :) on www.scipy.org From lists at cheimes.de Thu May 8 20:08:33 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 09 May 2008 02:08:33 +0200 Subject: Mathematics in Python are not correct In-Reply-To: <200805081914.06459.kyrie@uh.cu> References: <52c855d8-5609-43e0-b98f-9fa87b2808c2@m3g2000hsc.googlegroups.com> <200805081914.06459.kyrie@uh.cu> Message-ID: <48239601.1070200@cheimes.de> Luis Zarrabeitia schrieb: >>>> 0**0 > 1 > > That 0^0 should be a nan or exception, I guess, but not 1. No, that's correct for floats. Read the wikipedia article or the C99 standard for more information. Christian From bruno.desthuilliers at gmail.com Wed May 7 17:51:17 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Wed, 7 May 2008 14:51:17 -0700 (PDT) Subject: letter frequency counter / your thoughts.. References: <5a9a4a7e-a4a3-4a59-a80f-01d44bc69a86@w1g2000prd.googlegroups.com> Message-ID: On 7 mai, 18:39, umpsu... at gmail.com wrote: > Hello, > > Here is my code for a letter frequency counter. It seems bloated to > me and any suggestions of what would be a better way (keep in my mind > I'm a beginner) would be greatly appreciated.. > > def valsort(x): > res = [] > for key, value in x.items(): > res.append((value, key)) > return res > > def mostfreq(strng): > dic = {} > for letter in strng: > if letter not in dic: > dic.setdefault(letter, 1) You don't need dict.setdefault here - you could more simply use: dic[letter] = 0 > else: > dic[letter] += 1 > newd = dic.items() > getvals = valsort(newd) There's an error here, see below... > getvals.sort() > length = len(getvals) > return getvals[length - 3 : length] This is a very convoluted way to get the last (most used) 3 pairs. The shortest way is: return getvals[-3:] Now... Did you actually test your code ?-) mostfreq("abbcccddddeeeeeffffff") Traceback (most recent call last): File "", line 1, in File "/usr/tmp/python-1048583f.py", line 15, in mostfreq File "/usr/tmp/python-1048583f.py", line 3, in valsort AttributeError: 'list' object has no attribute 'items' Hint : you're passing valsort a list of pairs when it expects a dict... I don't see the point of the valsort function that - besides it doesn't sort anything (I can only second Arnaud about naming) - seems like an arbitrary extraction of a piece of code for no obvious reason, and could be expressed in a simple single line: getvals = [(v, k) for k, v in dic.items()] While we're at it, returning only the 3 most frequent items seems a bit arbitrary too - you could either return the whole thing, or at least let the user decide how many items he wants. And finally, I'd personnally hope such a function to return a list of (letter, frequency) and not a list of (frequency, letter). Here's a (Python 2.5.x only) possible implementation: from collections import defaultdict def get_letters_frequency(source): letters_count = defaultdict(int) for letter in source: letters_count[letter] += 1 sorted_count = sorted( ((freq, letter) for letter, freq in letters_count.iteritems()), reverse=True ) return [(letter, freq) for freq, letter in sorted_count] get_letters_frequency("abbcccddddeeeeeffffff") => [('f', 6), ('e', 5), ('d', 4), ('c', 3), ('b', 2), ('a', 1)] # and if you only want the top 3: get_letters_frequency("abbcccddddeeeeeffffff")[0:3] => [('f', 6), ('e', 5), ('d', 4)] HTH From tjreedy at udel.edu Sun May 11 21:36:39 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 11 May 2008 21:36:39 -0400 Subject: Mathematics in Python are not correct References: <52c855d8-5609-43e0-b98f-9fa87b2808c2@m3g2000hsc.googlegroups.com><200805081914.06459.kyrie@uh.cu> Message-ID: "Tim Roberts" wrote in message news:hkse24lhna7fp26tcfv5literfaded6nov at 4ax.com... | wxPythoner at gmail.com wrote: | > | >I am stunned that this simple misunderstanding of mine ended in a | >mathematical clash of a sort. :) You guys really blew me away wih | >your mathematical knowledge. And also the 0**0 is a thing I've never | >thought about trying, until now that is. If the mathematical rule is | >that EVERYTHING raised to the power of 0 is 1, then we should accept | >that, even in the case of 0**0. This is just the way it is. | | Sure, but it's ALSO the mathematical rule that 0 raised to any power is 0. That may be some people's (partial) rule but not everyone's. There is only agreement on 0 to a positive power. | Thus, there are multiple solutions to this problem, meaning that there is | NO solution to the problem. Only for some people. a**b := reduce(mul, [a]*b, 1) for all counts a and b is a simple, uniform, and useful rule. Do you have in mind any situations in which it is advantageous to have 0**0 undefined? tjr From mattheww at chiark.greenend.org.uk Sat May 24 14:22:32 2008 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 24 May 2008 19:22:32 +0100 (BST) Subject: Relationship between GUI and logic? References: <48363c34$0$15204$607ed4bc@cv.net> <2auf34dc59ajcjfq7f3fl0366eukfd98d5@4ax.com> Message-ID: David C. Ullrich wrote: > Matthew Woodcraft wrote: >> For example, if you were writing the 'logic' for a chess program you >> might choose a way of modelling the board that can't represent a >> position with more than one black king. And then when you got round >> to doing the GUI you might find out that your users would like to be >> able to have this temporarily when setting up a position. > What you say may be true, but this doesn't seem to me like a good > example. Not that I see _why_ the player would want to have two kings > temporarily, but if so I wouldn't have the view report this state to > the model, I'd have the view wait until the player had decided on the > final configuration betore saying anything to the model. The model > should only deal with legal positions. Then you end up implementing a second model of the board state in the UI layer. And if it turns out that you want to support things like 'save current position' and 'clone current position to a new window' during setup, you might well find yourself putting so much logic in the UI layer that some of what you already wrote in the 'logic' layer ends up unused. As for why you might want illegal positions during setup, imagine a UI where you can click on a square repeatedly and it cycles through the possible pieces (dunno whether this would be good in practice, but I do know that guessing whether a UI is good without trying it is rather unreliable). -M- From gherron at islandtraining.com Wed May 28 01:54:59 2008 From: gherron at islandtraining.com (Gary Herron) Date: Tue, 27 May 2008 22:54:59 -0700 Subject: multi dimensional dictionary In-Reply-To: References: Message-ID: <483CF3B3.3080805@islandtraining.com> Alok Kumar wrote: > Dear All, > > I am using dictionary for filling my xpath parsed data. > > I wanted to use in the following manner. > > mydict[index] ["key1"] ["key2"] #Can someone help me with right > declaration. > > So that I can fill my XML xpath parsed data > > mydict[0] ["person"] ["setTime"] = "12:09:30" > mydict[0] ["person"] ["clrTime"] = "22:09:30" That kind of thing can be done, but there's a better way perhaps: Create keys for a single level dictionary which are tuples composed of the sequence of keys you would have used in your multidimensional dictionary. mydict[(0,"person","setTime")] = "12:09:30" mydict[(0,"person","clrTime")] = "22:09:30" Would that work for you? Gary Herron > > Can someone help me with right declaration usages. Your help will be > highly appreciated. > > Regards > Alok > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list From bvidinli at gmail.com Fri May 2 03:07:55 2008 From: bvidinli at gmail.com (bvidinli) Date: Fri, 2 May 2008 10:07:55 +0300 Subject: where do I begin with web programming in python? In-Reply-To: <37ea096e-cf3e-4932-8370-306a15a2aebd@25g2000hsx.googlegroups.com> References: <37ea096e-cf3e-4932-8370-306a15a2aebd@25g2000hsx.googlegroups.com> Message-ID: <36e8a7020805020007n554f1dadm49571aade9fd1bc4@mail.gmail.com> i also asked same question in this list last week. i found http://www.cherrypy.org/ to be most suitable for me. it is basic, easy, pure... it contains its own webserver, very easy to start. others have many framworks, structures, classes many many.. i wanted a pure web programming system , i found cherrypy. see you. 2008/5/2 jmDesktop : > I have been to the main python site, but am still confused. I have > been using .net, so it may be obvious how to do this to everyone > else. I am aware there are various frameworks (Django, Pylons, etc.), > but I would like to know how to create web pages without these. If I > have mod_python or fastcgi on apache, where do I start? I don't have > clue where to begin to create a web page from scratch in python. I am > sure I will want to access database, etc., all the "normal" stuff, I > just want to do it myself as opposed to the frameworks, for learning. > > Thank you for any help. > -- > http://mail.python.org/mailman/listinfo/python-list > -- ?.Bahattin Vidinli Elk-Elektronik M?h. ------------------- iletisim bilgileri (Tercih sirasina gore): skype: bvidinli (sesli gorusme icin, www.skype.com) msn: bvidinli at iyibirisi.com yahoo: bvidinli +90.532.7990607 +90.505.5667711 From gagsl-py2 at yahoo.com.ar Fri May 2 23:15:47 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 03 May 2008 00:15:47 -0300 Subject: Pyserial - send and receive characters through linux serial port References: <6bb77eb0-9707-4a72-a385-881cb0365b41@r9g2000prd.googlegroups.com> <743d317e-bd06-42b1-a4fa-399ec18b548b@z24g2000prf.googlegroups.com> Message-ID: En Fri, 02 May 2008 15:44:09 -0300, terry escribi?: > On May 2, 10:26?am, terry wrote: >> On Apr 26, 8:21?am, Grant Edwards wrote: >> >> > Much of the time the exercise of writing a small demo program >> > will lead you to the answer. ?If not, then post it, along with >> > the output from the program that shows the problem. >> >> Here is the code. >> >> """Open serial connection""" >> ? ? ? ? def openSerialConnection(self,serpt): >> ? ? ? ? ? ? try: >> ? ? ? ? ? ? ? ? s1 = serial.Serial(serpt,timeout=10) >> >> ? ? ? ? ? ? except: >> ? ? ? ? ? ? ? ? self.print_u("Failed to open serial port %s. " %serpt) >> >> ? ? ? ? def enterThroughSerialPort(self,serpt): >> ? ? ? ? ? ? s1 = serial.Serial(serpt,timeout=10) >> ? ? ? ? ? ? ?self.print_u('Sending !!!!..') >> ? ? ? ? ? ? ?while True: >> ? ? ? ? ? ? ? ? s1.write('*') >> ? ? ? ? ? ? ? ?c = s1.read(1) >> ? ? ? ? ? ? ? ?if c: >> ? ? ? ? ? ? ? ? ? self.print_u('Found "*" ') >> ? ? ? ? ? ? ? ? ? ? break >> ? ? ? ? ? ? print c >> ? ? ? ? ? ? ?s1.write('enter\r') >> ? ? ? ? ? ? ?s1.read('login') >> >> if __name__ == '__main__': >> ? ? serpt = '/dev/ttyS0' >> ? ? x.openSerialConnection(serpt) >> ? ? # funtion to reboot the device goes here ---# >> ? ? x.enterThroughSerialPort(serpt) >> >> After opening the serial connection, the device is rebooted followed >> by sending '*' to serial port and reading back the same. I seem to >> have problem while trying to read '*' back from serial port. First of >> all I am not sure if serial port received the '*'. > > This is the err message I received: > > c = s1.read(1) > File "/usr/local/lib/python2.5/site-packages/serial/serialposix.py", > line 275, in read > ready,_,_ = select.select([self.fd],[],[], self._timeout) If you want some help, you have to help us to diagnose the problem. The above lines are just a small excerpt of the complete error report that surely you got; usually it includes the exception *type*, the exception *value*, and the whole *stack trace*. Now we have to *guess* what happened in that select call. Also, when posting code, try to post the *actual* code you run - copy and paste it. Do not retype it again. The code you posted has indentation errors, uninitialized variables... Try to make a *small*, runnable example that reproduces the problem; remove anything that isn't esential to the issue being discussed. Write down what is your expected behaviour, and what actually happens. If the program halts due to an error, copy the *whole* report including the exception type, message, and the complete traceback. In this particular case, due to the serial device, it's improbable that someone will be able to execute your program, but anyway try to write the example code. Sometimes you may find the problem yourself just by trying to write the example. A few notes on the code: - don't create many Serial objects; create only a single instance and use it everywhere it is needed. (That is, instead of using '/dev/ttyS0' as an argument, pass the Serial object already created, or save it as an instance attribute: self.serial = Serial(...) ) - ensure you're using the right protocol parameters (baud rate, bits, parity...) for the device. That's why it helps to create the Serial object in a single place. -- Gabriel Genellina From wuwei23 at gmail.com Wed May 21 22:09:08 2008 From: wuwei23 at gmail.com (alex23) Date: Wed, 21 May 2008 19:09:08 -0700 (PDT) Subject: Psyche (scheme in python), how to run on vista? References: <01afbef9-6225-487d-9468-cbdf9b03c64b@b1g2000hsg.googlegroups.com> Message-ID: <8c0885f8-380a-4c73-a7f4-30326c9d9563@y18g2000pre.googlegroups.com> On May 22, 5:19 am, notnorweg... at yahoo.se wrote: > anyone using psyche? > > how do you run it on Vista? what file do you click? there is no > obvious file like psyche.py... After installation, you should be able to find 'psyche.bat' in C: \Python2.X\Scripts. However, it hard codes the path for the python interpreter, so you'll need to edit it to fix. BUT! Doing so just reveals the next problem, running it I keep getting complaints about the following piece of code: def get_epsilon(self, None = None): """ Return the mapping for epsilon, or None. """ return self.special.get('', None) I've never used psyche and I've no idea what the author was thinking here, but the 'None = None' in the function parameters is a serious 'wtf?' You need to edit site-packages\psyche\Plex\Transitions.py line 85 to be: def get_epsilon(self): Then running psyche.bat will at least get the interpreter running. I can make no guarantees on its correctness, however. But at least it _seems_ to work: C:\Python25\Scripts>psyche Psyche version 0.4.3, Copyright (C) 2002 Y. Duppen Psyche comes with ABSOLUTELY NO WARRANTY. This is free software, and you are welcome to redistribute it under certain conditions; read the attached COPYING for details. psyche> (define (plus1 x) (+ x 1)) psyche> (plus1 2) 3 Hope this helps! - alex23 From jeremy+complangpython at jeremysanders.net Wed May 21 11:13:17 2008 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Wed, 21 May 2008 16:13:17 +0100 Subject: how to proccess the blank in the path on linux References: Message-ID: A.T.Hofkamp wrote: > Escape the space to prevent the shell from interpreting it as a word > seperator. This of course also holds for all other shell meta characters, > such as * [ ] \ > < & and a few others I probably have forgotten. If the command was useful (unlike cd), it might be better to use subprocess to launch it so that you don't need the escaping: subprocess.call(['ls', '8000 dir']) This avoids using the shell. -- Jeremy Sanders http://www.jeremysanders.net/ From notnorwegian at yahoo.se Sun May 25 21:14:51 2008 From: notnorwegian at yahoo.se (notnorwegian at yahoo.se) Date: Sun, 25 May 2008 18:14:51 -0700 (PDT) Subject: which datastructure for fast sorted insert? References: <6610cad9-384d-4755-9a2c-c605329be217@8g2000hse.googlegroups.com> <69sj10F34jb08U3@mid.uni-berlin.de> <5cae3f71-c699-4faa-97f3-d4c33e2daf9b@d77g2000hsb.googlegroups.com> Message-ID: <208739fb-46ab-4fc1-86c7-1b7b03d3cbe8@a70g2000hsh.googlegroups.com> On 26 Maj, 03:04, notnorweg... at yahoo.se wrote: > On 26 Maj, 01:30, I V wrote: > > > > > On Sun, 25 May 2008 15:49:16 -0700, notnorwegian wrote: > > > i meant like set[pos], not iterate but access a specific position in the > > > set. > > > If you need to access arbitrary elements, use a list instead of a set > > (but you'll get slower inserts). OTOH, if you just need to be able to get > > the next item from the set, you can use an iterator: > > > > now i have to do: > > > s = toSet.pop() > > > toSet.add(s) > > > i = iter(toSet) > > > s = i.next() > > > > if i want to get the url of the next item in a set, how would i do that? > > > i can do this with a list: > > > > def scrapeSitesX(startAddress, toList, listPos): return > > > scrapeSites(toList[listPos], toList, listPos+1) to use recursion with a > > > list. > > > i can work around that but it doesnt get as elegant. > > > Do you have to use recursion here? Why not: > > > for site in toList: > > scrape(site) > > i have tried both. > > anyway how do i concatenate sets? which i have to if use to funcions > like you suggest. > > and also when iterating a set is there any other way to avoid > exceptions than have a counter and compare to len(set). > is there no method that cna check if iter != None nevermind got it how to concatenate. but no builtin method for concatenating right? From ian.g.kelly at gmail.com Wed May 7 14:31:43 2008 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Wed, 7 May 2008 12:31:43 -0600 Subject: letter frequency counter / your thoughts.. In-Reply-To: <4821e745$0$24414$5fc3050@news.tiscali.nl> References: <5a9a4a7e-a4a3-4a59-a80f-01d44bc69a86@w1g2000prd.googlegroups.com> <4821e745$0$24414$5fc3050@news.tiscali.nl> Message-ID: <3fc761710805071131w45fd124cs5638db218585e35f@mail.gmail.com> On Wed, May 7, 2008 at 11:30 AM, Paul Melis wrote: > dic = {} > for letter in strng: > if letter not in dic: > dic[letter] = 0 > dic[letter] += 1 As a further refinement, you could use the defaultdict class from the collections module: dic = defaultdict(int) for letter in strng: dic[letter] += 1 From artyprog at gmail.com Tue May 20 17:43:16 2008 From: artyprog at gmail.com (Salvatore DI DI0) Date: Tue, 20 May 2008 23:43:16 +0200 Subject: Processing in Python Message-ID: <483345f5$0$902$ba4acef3@news.orange.fr> Hello, The Processing Graphics language has been implemented in Javascript. Does anybody tried to make this in Python ? Regards Salvatore http://processing.org/ From george.sakkis at gmail.com Fri May 9 22:00:25 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 9 May 2008 19:00:25 -0700 (PDT) Subject: RELEASED Python 2.6a3 and 3.0a5 References: Message-ID: <90cdf44a-f189-4264-9add-03d094ba48ab@e39g2000hsf.googlegroups.com> On May 8, 7:50?pm, Barry Warsaw wrote: > On behalf of the Python development team and the Python community, I ? > am happy to announce the third alpha release of Python 2.6, and the ? > fifth alpha release of Python 3.0. > > Please note that these are alpha releases, and as such are not ? > suitable for production environments. ?We continue to strive for a ? > high degree of quality, but there are still some known problems and ? > the feature sets have not been finalized. ?These alphas are being ? > released to solicit feedback and hopefully discover bugs, as well as ? > allowing you to determine how changes in 2.6 and 3.0 might impact > you. ?If you find things broken or incorrect, please submit a bug ? > report at > > ? ?http://bugs.python.org > > For more information and downloadable distributions, see the Python > 2.6 website: > > ? ?http://www.python.org/download/releases/2.6/ > > and the Python 3.0 web site: > > ? ?http://www.python.org/download/releases/3.0/ > > These are the last planned alphas for both versions. ?If all goes ? > well, next month will see the first beta releases of both, which will ? > also signal feature freeze. ?Two beta releases are planned, with the ? > final releases scheduled for September 3, 2008. > > See PEP 361 for release details: > > ? ? ?http://www.python.org/dev/peps/pep-0361/ > > Enjoy, > - -Barry I'm trying to install on the latest Ubuntu (8.04) and the following extension modules fail: _bsddb, _curses, _curse_panel, _hashlib, _sqlite3, _ssl, _tkinter, bz2, dbm, gdbm, readline, zlib All of them except for _tkinter are included in the preinstalled Python 2.5.2, so I guess the dependencies must be somewhere there. Does Ubuntu have any non-standard lib dir ? George From castironpi at gmail.com Fri May 16 09:51:46 2008 From: castironpi at gmail.com (castironpi) Date: Fri, 16 May 2008 06:51:46 -0700 (PDT) Subject: Instance of class "object" References: Message-ID: On May 16, 4:26 am, Peter Otten <__pete... at web.de> wrote: > ?? wrote: > > I wonder why below does not work. > > > a = object() > > a.b = 1 # dynamic bind attribute failed... > > The implementation of slots depends on that behaviour: > > http://docs.python.org/ref/slots.html > > > Does this strange behavior break the LSP (Liskov substitution principle)? > > Can you expand on that? > > Peter Spirals are important. From maxm at mxm.dk Sun May 4 16:13:02 2008 From: maxm at mxm.dk (Max M) Date: Sun, 04 May 2008 22:13:02 +0200 Subject: Real Time Midi File Playback - Reading and Writing midi at the same time In-Reply-To: <4e5b78a7-bc7a-4c1e-8552-b8175a9cbe32@m3g2000hsc.googlegroups.com> References: <4e5b78a7-bc7a-4c1e-8552-b8175a9cbe32@m3g2000hsc.googlegroups.com> Message-ID: <481E18CE.90508@mxm.dk> Gilly skrev: > Hi > I am trying to create an application that uses some form of input to > create a midi file. > I would like for this to be a 'real time' process. In other words, I > want to be able to begin playing the midi file before I finish writing > it, and continue writing as it plays. Perhaps csound can help with this. It has a lot of midi, realtime and python stuff. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From bruno.42.desthuilliers at websiteburo.invalid Wed May 21 06:01:31 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 21 May 2008 12:01:31 +0200 Subject: Using Python for programming algorithms In-Reply-To: References: <48315082$0$24599$426a74cc@news.free.fr> <62884fc6-6c74-4477-91de-7b7689b5fa75@m44g2000hsc.googlegroups.com> <52b543da-90f3-4624-a11c-553159832764@l42g2000hsc.googlegroups.com> Message-ID: <4833f2ef$0$3737$426a74cc@news.free.fr> sturlamolden a ?crit : > On May 19, 10:42 pm, "bruno.desthuilli... at gmail.com" > wrote: > >> Well... They do - they are called 'C compilers' !-) As Roel Schroven >> mentioned - and he is at least partially right on this point - C has >> been designed to make optimizing C compiler not to hairy to write. > > C has proven very difficult to optimize, particularly because pointer > aliasing prevents efficient register allocation. Does this compare to optimizing something like Python ? (serious question, but I think I already know part of the answer). From chris.hulan at gmail.com Wed May 28 10:34:18 2008 From: chris.hulan at gmail.com (Chris Hulan) Date: Wed, 28 May 2008 07:34:18 -0700 (PDT) Subject: Does this path exist? References: <2c6739d1-1128-469c-92b0-ee0263ec25d1@m36g2000hse.googlegroups.com> <3d9fdd77-8187-49f5-aaa2-de7d2363038c@x41g2000hsb.googlegroups.com> Message-ID: On May 28, 4:59 am, s0s... at gmail.com wrote: > On May 28, 3:47 am, Matt Nordhoff wrote: ... > Thanks. So if OSError().errno == errno.ENOENT, then it means the path > doesn't exist? (What does "ENOENT" stan for?) I always read it as Error NO ENTry From spoier at gmail.com Tue May 20 12:26:11 2008 From: spoier at gmail.com (Skye) Date: Tue, 20 May 2008 09:26:11 -0700 (PDT) Subject: Access to sysctl on FreeBSD? Message-ID: How do I access the sysctl(3) call from Python on BSD? Specifically I want to retrieve: $ sysctl -d net.inet.ip.stats net.inet.ip.stats: IP statistics (struct ipstat, netinet/ip_var.h) So I'll need some way of getting to struct ipstat from Python as well Thanks, Skye From nick at craig-wood.com Thu May 15 04:30:03 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Thu, 15 May 2008 03:30:03 -0500 Subject: sys.excepthack... References: Message-ID: David C. Ullrich wrote: > Becoming a fan of wxPython, but I can't stand > what it does with error messsages [snip] > So I want to pop up a modal dialog on error. [snip] > Came up with a ridiculous hack involving both sys.stderr > and sys.excepthook. Works exactly the way I want. > Seems ridiculous - what's the right way to do this? > > Ridiculous_hack.py: > > import sys > import wx > > def hook(*args): > try: > sys.__excepthook__(*args) > finally: > printer.Show() > > class ErrorDisplay: > def __init__(self): > self.buffer = '' > def write(self, text): > self.buffer = self.buffer + text > > def Show(self): > wx.MessageDialog(None, str(self.buffer), > 'Error:',wx.OK).ShowModal() > self.buffer = '' > > printer = ErrorDisplay() > sys.stderr = printer > sys.excepthook = hook Here is how I've done it in the past. It is a complete runnable example :- ------------------------------------------------------------ #!/usr/bin/python import wx import sys from traceback import format_exception class TestApp(wx.Frame): """Test error handling""" def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, -1, title, size=(200,200)) sys.excepthook = self.OnException button = wx.Button(self, wx.NewId(), "Produce Error") self.Bind(wx.EVT_BUTTON, self.OnClick) self.Show(True) def OnException(self, type, value, traceback): """ Called on OnException """ error_text = "".join(format_exception(type, value, traceback)) wx.MessageDialog(None, error_text, 'Custom Error:', wx.OK).ShowModal() def OnClick(self, evt): "Click with a deliberate mistake" adsfsfsdf if __name__ == "__main__": app = wx.PySimpleApp() frame = TestApp(None, -1, "Test") app.MainLoop() ------------------------------------------------------------ -- Nick Craig-Wood -- http://www.craig-wood.com/nick From vadim.pestovnikov at gmail.com Fri May 9 00:42:33 2008 From: vadim.pestovnikov at gmail.com (idev) Date: Thu, 8 May 2008 21:42:33 -0700 (PDT) Subject: Which way is faster for a simple web reporting system: django, web.py or cgi Message-ID: <5c04fa0a-076f-475e-9147-c1295e86d62b@l42g2000hsc.googlegroups.com> Hi all, May be this is a dump question, but it makes me crazy in my research. I am not a developer but I have experience with web development (PHP) in a past. Most my activities are around database administration and design. For most database administration tasks I am using Python. Very often I need to come up very quickly with web interface or web application to a database, more then less complicated. The standard set is: * speed of the development (I think a framework is the way, but which one?) * user authorization (my preferences are sessions) * form validation for input data * file uploading * export data to different format like csv, pdf, xml For example I need to create a simple reporting system. Using different filters like HTML drop down lists, radio buttons, check boxes and etc., I need to generate different output to my team and managers. I realize that today is very popular and useful, using a framework. Which Python framework or solution will be more faster to start (i.e. for start, usually I have maximum two weeks, if a project looks like a stable I can get three, four weeks), flexible (i.e. using SQL queries together with views) and easier in integration: django, web.py, CGI or something else? Thanks in advance. From michele.simionato at gmail.com Thu May 29 13:34:42 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Thu, 29 May 2008 10:34:42 -0700 (PDT) Subject: undocumented functions in pkgutil Message-ID: <04d9dbd9-ad9c-4756-afa5-163800a785eb@t54g2000hsg.googlegroups.com> I see that the pkgutil module has many useful functions which are however undocumented. Does anybody know why it is so? In particolar, can I safely use pkg.walk_packages without risking a change of interface in the future? I looks unlikely, since pkgutil is used in setuptools, but I want to be sure before relying on it. Michele Simionato From wgumgfy at gmail.com Fri May 9 02:43:03 2008 From: wgumgfy at gmail.com (Waylen Gumbal) Date: Thu, 8 May 2008 23:43:03 -0700 Subject: The Importance of Terminology's Quality References: <68i6b5F2soauaU1@mid.individual.net> Message-ID: <68ia3oF2t5308U1@mid.individual.net> Lew wrote: > Waylen Gumbal wrote: >> Not everyone follows language-neutral groups (such as >> comp,programming as you pointed out), so you actually reach more >> people by cross posting. This is what I don't understand - everyone >> seems to assume that by cross posting, one intends on start a >> "flamefest", when in fact most such "flamefests" are started by >> those who cannot bring themselves to skipping over the topic that >> they so dislike. > > It's not an assumption in Xah Lee's case. He spams newsgroups > irregularly with rehashed essays from years ago, and a number of > people are just tired of him. I did not know this. One should obviously not do that. > Don't blame the victims for the perpetrator's actions, OK? I'm not blaming any "victims", but I don't see anyone saying "read this or else", so why not just skip the thread or toss the OP in your killfile so you don't see his postings. If others want to discuss his topics, who are you or I to tell them not to? -- wg From samslists at gmail.com Sat May 3 14:12:45 2008 From: samslists at gmail.com (samslists at gmail.com) Date: Sat, 3 May 2008 11:12:45 -0700 (PDT) Subject: Problems replacing \ with \\ References: <0ca30eb2-3791-4910-9e78-f32e3b2a72cb@2g2000hsn.googlegroups.com> Message-ID: <19fcd6b9-75b7-480d-bf0b-572c52e213c5@f24g2000prh.googlegroups.com> Sorry for the late response. I've been travelling internationally and am just getting back to work. So--thank you to everyone who responded! To answer everyone's question---- I am dumping all of the data from a mysql database, then creating a postgresql database, then inserting the data into the new postgresql database. This seems to be a reasonable way to do it, because all I have to do is double my 's and my \s (I hope). Thanks On Apr 21, 7:12?pm, Michael Torrie wrote: > samsli... at gmail.com wrote: > > Hi... > > > Here's a weird problem...I'm trying to escape a bunch of data to put > > into a database. > > Is it possible to use the database API and prepared statements to avoid > having to go through this exercise? ?Also, most database APIs work > natively in unicode, so creating your prepared statement and then > passing in each parameter as an argument saves a lot of hassle, since > the API's usually decode the unicode strings automatically. From davidj411 at gmail.com Fri May 23 15:04:43 2008 From: davidj411 at gmail.com (davidj411) Date: Fri, 23 May 2008 12:04:43 -0700 (PDT) Subject: function returns , but variable values has not changed in the interactive prompt Message-ID: if you run execfile function to run a python script and that script has variables and functions, should't those variable change in the interactive prompt too? script snippet that calls the function which should return like this return (stuffedname,bigstring, numbertimes,num_times_search_string) this is the variable that calls the functions. when a function returns something AND there is a variable set as shown immediately below, does't the variable get updated? tu_count = CountStrings (name, balance, searchstr) this is the output from the script. notice how tu_count actually differs when called from interactive prompt after script exits. tu_count: ('peterjackson', 'peterjacksonpeterjacksonpeter', 2, 0) >>> tu_count ('davidjacksondavidjacksondavid', 2, 0) thanks From jkugler at bigfoot.com Mon May 12 13:12:21 2008 From: jkugler at bigfoot.com (Joshua Kugler) Date: Mon, 12 May 2008 09:12:21 -0800 Subject: Saving an audio file's waveform into an image References: <5ee7c96e-0301-438f-81f1-b6d46236115c@i36g2000prf.googlegroups.com> Message-ID: Julien wrote: > Hi, > > I would like to pull out the waveform of an audio file and save it > into an image file, for example in GIF format. Is that achievable, and > if so, how? Take a look at http://code.enthought.com/projects/chaco/ One of their examples does exactly this. Last example on this page: http://code.enthought.com/projects/chaco/gallery.php Hope that helps. j From paddy3118 at googlemail.com Tue May 20 17:29:49 2008 From: paddy3118 at googlemail.com (Paddy) Date: Tue, 20 May 2008 14:29:49 -0700 (PDT) Subject: Misuse of list comprehensions? References: <038e4418$0$27258$c3e8da3@news.astraweb.com> <6359d72c-f937-46cd-b1ce-b7450671b714@i76g2000hsf.googlegroups.com> Message-ID: <7c50dabd-7644-4166-9ac7-87d8c9b10384@a32g2000prf.googlegroups.com> On May 20, 3:58 pm, Paul McGuire wrote: > On May 20, 8:13 am, "John Salerno" wrote: > > > > > I posted this code last night in response to another thread, and after I > > posted it I got to wondering if I had misused the list comprehension. Here's > > the two examples: > > > Example 1: > > -------------------- > > def compress(s): > > new = [] > > > for c in s: > > if c not in new: > > new.append(c) > > return ''.join(new) > > ---------------------- > > > Example 2: > > ------------------------ > > def compress(s): > > new = [] > > [new.append(c) for c in s if c not in new] > > return ''.join(new) > > -------------------------- > > > In example 1, the intention to make an in-place change is explicit, and it's > > being used as everyone expects it to be used. In example 2, however, I began > > to think this might be an abuse of list comprehensions, because I'm not > > assigning the result to anything (nor am I even using the result in any > > way). > > > What does everyone think about this? Should list comprehensions be used this > > way, or should they only be used to actually create a new list that will > > then be assigned to a variable/returned/etc.? > > Why not make the list comp the actual list you are trying to build? ... Because it obscures the intent of the code. - Paddy. From bronger at physik.rwth-aachen.de Tue May 13 13:28:10 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Tue, 13 May 2008 19:28:10 +0200 Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <2b66a86e-5a05-4262-b3c9-4703b0ae3372@d1g2000hsg.googlegroups.com> <5b0e3f70-afde-4480-8713-e7113b1250d7@x35g2000hsb.googlegroups.com> <1f537717-00d0-48ee-99b6-7125b96a6133@t12g2000prg.googlegroups.com> <68t4o0F2vaoncU1@mid.uni-berlin.de> <2a32179a-9439-449c-bd07-fff6a4075aee@s50g2000hsb.googlegroups.com> <7ee5dffd-df8f-46f0-bd78-c81ac0418a9a@d77g2000hsb.googlegroups.com> <65ef773e-a1c3-4adb-a18b-e8b8451efe5e@b5g2000pri.googlegroups.com> <02a10e4b-5017-463c-96d2-e1779f2b9ebd@j22g2000hsf.googlegroups.com> <8bd40bb6-5f8d-4256-a41a-fe341d10d476@q1g2000prf.googlegroups.com> Message-ID: <87d4nqgllh.fsf@physik.rwth-aachen.de> Hall?chen! Dave Parker writes: >> Notice that I said "free software", not "*** FREE *** software >> !!!! 1!" (that is, free as in freedom, not free as in >> beer). Read again my answer, considering this. > > I misread your meaning. ... twice. Flaming Thunder itself is not free software, is it? Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From scott at rscorp.ab.ca Thu May 1 10:59:33 2008 From: scott at rscorp.ab.ca (Scott Sandeman-Allen) Date: Thu, 1 May 2008 08:59:33 -0600 Subject: Photo gallery software In-Reply-To: <0001HW.C43F80E40094984AB01AD9AF@news.individual.de> Message-ID: On 5/1/08, Jumping Arne (arnlen at mac.com) wrote: >I've searching for some software that would allow me to present my photos on >the web (I'm not interested a software that generates static pages that I >upload) and there are quite a few, see for example >, but I >haven't managed to find one that I like - Gallery 2 is close. > >So I've started to see if there is one that is based python (PHP isn't really >"my language") but when I search on Google almost the only thing I find are >photo galleries of snakes (to be honest I didn't know that people were *that* >interested in pythons). > >Do any anyone know if there exists photo gallery software written in Python? > >I've found > > I've been working with Photologue for a while with some nice results. It is a Django project , It includes support for tagging: It easily allows configuration of different image sizes and integrates with generic templates providing gallery and detail view support. HTH Scott From jcd at unc.edu Wed May 7 15:49:14 2008 From: jcd at unc.edu (J. Cliff Dyer) Date: Wed, 07 May 2008 15:49:14 -0400 Subject: [Fwd: Re: Am I missing something with Python not having interfaces?] Message-ID: <1210189754.4595.4.camel@aalcdl07.lib.unc.edu> -- Oook, J. Cliff Dyer Carolina Digital Library and Archives UNC Chapel Hill -------------- next part -------------- An embedded message was scrubbed... From: "J. Cliff Dyer" Subject: Re: Am I missing something with Python not having interfaces? Date: Wed, 07 May 2008 15:48:56 -0400 Size: 2255 URL: From ivan.illarionov at gmail.com Tue May 20 04:50:18 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Tue, 20 May 2008 08:50:18 +0000 (UTC) Subject: Using Python for programming algorithms References: <48315082$0$24599$426a74cc@news.free.fr> <62884fc6-6c74-4477-91de-7b7689b5fa75@m44g2000hsc.googlegroups.com> Message-ID: On Mon, 19 May 2008 11:07:06 -0700, Vicent Giner wrote: [...] > > By the way, is it possible (and easy) to call a C function from a Python > program?? Yes. http://groups.google.com/group/comp.lang.python/msg/9d47913a265c348a -- Ivan From kamhung.soh at gmail.com Tue May 13 01:08:04 2008 From: kamhung.soh at gmail.com (Kam-Hung Soh) Date: Tue, 13 May 2008 15:08:04 +1000 Subject: anonymous assignment References: <1XNVj.133805$Cj7.33096@pd7urf2no> Message-ID: On Tue, 13 May 2008 13:23:30 +1000, Yves Dorfsman wrote: > Scott David Daniels wrote: >> Yves Dorfsman wrote: >>> ... Sorry this was a typo (again :-), I meant: >>> d = time.local() >>> y = d[0] >>> d = d[2] >> Then: >> y, d = list(time.localtime())[:4:2] >> > > What is this ? > Could you point me to a document on this syntax ? > > I've tried it, it works, but I don't understand how. > > > Thanks. > > Yves. > -- > http://mail.python.org/mailman/listinfo/python-list > See: "Built-in Functions", "slice()", http://docs.python.org/lib/built-in-funcs.html l = range(10) l [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] l[:4] # first four elements [0, 1, 2, 3] l[::2] # every second element [0, 2, 4, 6, 8] l[:4:2] # every second element in the first four elements [0, 2] -- Kam-Hung Soh Software Salariman From kd015b3257 at blueyonder.co.uk Sat May 10 07:21:16 2008 From: kd015b3257 at blueyonder.co.uk (kdwyer) Date: Sat, 10 May 2008 12:21:16 +0100 Subject: PyXml References: <4825361E.8000102@behnel.de> Message-ID: Stefan Behnel wrote: > Martin v. L?wis wrote: >>> Can anyone recommend a Python validating parser that validates vs Xml >>> Schema? >> >> The libxml bindings for Python can do that. > > ... although the OP will likely prefer using lxml, where it's three lines > of Python (ok, plus an import), compared to quite a bit of code in the > official libxml2 bindings. > > http://codespeak.net/lxml > > Stefan > -- > http://mail.python.org/mailman/listinfo/python-list Stefan, Martin, Thanks for your replies. Kev From prasanths89 at gmail.com Sun May 25 12:13:57 2008 From: prasanths89 at gmail.com (Prasanth) Date: Sun, 25 May 2008 09:13:57 -0700 (PDT) Subject: Pinging a machine from python Message-ID: I tried pinging a machine from python using socket programming but could not do it. Is there any module which we can use to ping the machine < like net::ping in perl> or can you give me simple program. From notnorwegian at yahoo.se Sat May 24 19:20:19 2008 From: notnorwegian at yahoo.se (notnorwegian at yahoo.se) Date: Sat, 24 May 2008 16:20:19 -0700 (PDT) Subject: webspider getting stuck Message-ID: i am writing a simple webspider . how do i avoid getting stuck at something like this: Enter username for W3CACL at www.w3.org: ? i can obv add an if-clause for the specific site but since i guess there will be more of the same thats ov not a viable approach in the long run. From zondo42 at googlemail.com Sun May 4 20:00:27 2008 From: zondo42 at googlemail.com (Glenn Hutchings) Date: Mon, 05 May 2008 01:00:27 +0100 Subject: Are rank noobs tolerated, here? References: Message-ID: notbob writes: > Am I likely to receive any help, here, or is there another irc, forum, etc, > that might better serve a complete amateur such as myself. Thnx. You're very likely to receive help here. Or at the very least, people will point you at the best place to get it. Fire away! Glenn From theller at python.net Wed May 21 02:29:46 2008 From: theller at python.net (Thomas Heller) Date: Wed, 21 May 2008 08:29:46 +0200 Subject: Access to sysctl on FreeBSD? In-Reply-To: References: <48331cef$0$32633$9b622d9e@news.freenet.de> Message-ID: <69htqnF32242iU1@mid.individual.net> Skye schrieb: > Great, thanks for the help (I'm fairly new to Python, didn't know > about ctypes) > > from ctypes import * > libc = CDLL("libc.so.7") > size = c_uint(0) > libc.sysctlbyname("net.inet.ip.stats", None, byref(size), None, 0) > buf = c_char_p(" " * size.value) > libc.sysctlbyname("net.inet.ip.stats", buf, byref(size), None, 0) IIUC, sysctlbyname writes the information you requested into the buffer supplied as second argument. If this is true, then the above code is incorrect. c_char_p(src) creates an object that shares the buffer with the Python string 'src'; but Python strings are immutable and you must not write ctypes code that modifies them. Instead, you should code: from ctypes import * libc = CDLL("libc.so.7") size = c_uint(0) libc.sysctlbyname("net.inet.ip.stats", None, byref(size), None, 0) buf = create_string_buffer(size.value) libc.sysctlbyname("net.inet.ip.stats", buf, byref(size), None, 0) Thomas From thudfoo at opensuse.us Sat May 10 13:47:42 2008 From: thudfoo at opensuse.us (member thudfoo) Date: Sat, 10 May 2008 10:47:42 -0700 Subject: list object In-Reply-To: <066c62a8-4400-4f94-bddb-d23eac01486a@27g2000hsf.googlegroups.com> References: <066c62a8-4400-4f94-bddb-d23eac01486a@27g2000hsf.googlegroups.com> Message-ID: <3d881a310805101047s1cc9c803wb87805e8044b514c@mail.gmail.com> On 5/10/08, Gandalf wrote: > my manual contain chapter about lists with python. when i try to copy > paste : > > li = ["a", "b", "mpilgrim", "z", "example"] (1) > > > it i get this errore: > > "TypeError: 'list' object is not callable" > > i was wondering if their is any special module I should import before > i use this function > > i know i ask foolish questions it's my first day with python and i > have experience only with PHP and javascript, so please be patient > > thanks > > -- > http://mail.python.org/mailman/listinfo/python-list > Remove the "(1)" From duncan.booth at invalid.invalid Sun May 25 05:25:25 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 25 May 2008 09:25:25 GMT Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <8763t3by81.fsf@benfinney.id.au> <5ea78616-e955-4ee0-8e60-a22734ec31be@79g2000hsk.googlegroups.com> <87prrbk85x.fsf@gmail.com> <06174f9e-ed5b-4107-b646-ef115262268f@d45g2000hsc.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > Ben Finney: >>In Python, the philosophy "we're all consenting adults here" applies.< > > Michael Foord: >> They will use whatever they find, whether it is the best way to >> achieve a goal or not. Once they start using it they will expect us to >> maintain it - and us telling them it wasn't intended to be used by >> them in the first place won't cut it. > > So they will use the methods with one or two underscores too. And > imply that you want to document them too. > They don't seem adult enough, then ;-) > Internal API hiding seems quite less useful if you don't need to let > customers manage your code. > Or if you code in C++ and they *really* need to get at something you made private they will still get at it. I've been there and done that: 'private' in languages which have it is rarely an advantage and frequently a pain. Also note that private in C++ while it does make it harder to access (though not preventing it altogether) doesn't do any data hiding, so if you are subclassing a vendor-provided function you still have to take note of the private attributes to avoid naming collisions. At least Python's convention which hides the implementation without making it hard to access has some benefits. From _karlo_ at _mosor.net_ Thu May 22 04:19:40 2008 From: _karlo_ at _mosor.net_ (Karlo Lozovina) Date: Thu, 22 May 2008 08:19:40 +0000 (UTC) Subject: Returning to 'try' block after catching an exception References: Message-ID: Duncan Booth wrote in news:Xns9AA6596091F47duncanbooth at 127.0.0.1: > Catching only the specific exceptions you think you can handle would > be more Pythonic: that way things like sys.exit() will still work > inside some_function. I know, this was just a somewhat poorly example ;). > I prefer a 'for' loop rather than 'while' so I can limit the number of > retries. > > The following may or may not be 'more pythonic', but is something I've > used. It's a factory to generate decorators which will retry the > decorated function. You have to specify the maximum number of retries, > the exceptions which indicate that it is retryable, and an optional > filter function which can try to do fixups or just specify some > additional conditions to be tested. Interesting approach, I think I'll use something like that for avoding infinite loops. Thanks a lot... -- _______ Karlo Lozovina - Mosor | | |.-----.-----. web: http://www.mosor.net || ICQ#: 10667163 | || _ | _ | Parce mihi domine quia Dalmata sum. |__|_|__||_____|_____| From ian.g.kelly at gmail.com Tue May 27 23:46:58 2008 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Tue, 27 May 2008 21:46:58 -0600 Subject: Misuse of list comprehensions? In-Reply-To: References: <038e4418$0$27258$c3e8da3@news.astraweb.com> <69g2bpF31ttuuU1@mid.uni-berlin.de> <69g605F2v4102U2@mid.uni-berlin.de> <027e0b24$0$26906$c3e8da3@news.astraweb.com> <3fc761710805271043k2305b96bs125e794c26fcd036@mail.gmail.com> Message-ID: <3fc761710805272046k1d6d01b0x53afd81971761cda@mail.gmail.com> On Tue, May 27, 2008 at 8:08 PM, Gabriel Genellina wrote: > En Tue, 27 May 2008 14:43:52 -0300, Ian Kelly > escribi?: > >> It sounds like the wasteful list creation is the biggest objection to >> using a list comprehension. I'm curious what people think of this >> alternative, which avoids populating the list by using a generator >> expression instead (apart from the fact that this is still quadratic, >> which I'm aware of). >> >> def compress(s): >> new = [] >> filter(None, (new.append(c) for c in s if c not in new)) >> return ''.join(new) > > filter returns a newly created list, so this code is as wasteful as a list > comprehension (and harder to read). Here it returns a newly created *empty* list, which is not nearly as wasteful as one that's linear in the size of the input. I'll grant you the second point, though. I very much doubt that I would ever actually use this myself. I was just curious what others would think of it. From grante at visi.com Fri May 2 10:46:43 2008 From: grante at visi.com (Grant Edwards) Date: Fri, 02 May 2008 09:46:43 -0500 Subject: #!/usr/bin/env python vs. #!/usr/bin/python References: <87abj91j8u.fsf@benfinney.id.au> <871w4l1cjj.fsf@benfinney.id.au> Message-ID: On 2008-05-02, Jeroen Ruigrok van der Werven wrote: > -On [20080502 07:51], Ben Finney (bignose+hates-spam at benfinney.id.au) wrote: >>To my mind, the Python interpreter installed by a package as >>distributed with the OS *is* OS territory and belongs in /usr/bin/. > > That's the difference with a distribution, such as Linux, and full OSes , > such as BSDs or commercial Unix variants. They prefer to keep a pristine > state for the OS vendor files Python _is_ an OS vendor file in the Linux world. > versus what the user can opt to install himself, Traditionally, Python has not been optional. > hence the /usr/bin - /usr/local/bin separation. Same for sbin, > lib, and so on. It effectively guarantees you can nuke > /usr/local without ill consequences for your OS. That's the point. You _couldn't_ nuke Python and have your system keep running. That's why it was in /usr/bin. -- Grant From bruno.42.desthuilliers at websiteburo.invalid Fri May 23 03:38:58 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 23 May 2008 09:38:58 +0200 Subject: Relationship between GUI and logic? In-Reply-To: <48363c34$0$15204$607ed4bc@cv.net> References: <48363c34$0$15204$607ed4bc@cv.net> Message-ID: <4836747b$0$15488$426a74cc@news.free.fr> John Salerno a ?crit : > I know that it is good programming practice to keep GUI and logic code > physically separate, by using XRC for example, but I'm wondering if it's > also good practice (and even possible) to keep them separate from an > implementation standpoint as well. Basically what I mean is, should it > be possible to write, for example, the logic for a strategy game without > even knowing what the graphics will look like or how they will work? Depends on your definition of "logic". The point is not "keep GUI and logic code" separate, but to keep "domain" logic (as) separated (as possible) from user-interface stuff. > To be more specific, let's say I want to create a simple, 2D strategy > game. It will have a board layout like chess or checkers and the player > will move around the board. Let's say this is all I know, and perhaps I > don't even know *this* for sure either. Is it possible to write the > logic for such a game at this point? Yes : build a model of the board and pieces and functions/methods to allow (code-level) interaction with it. Then your user interface will just have to create a visual representation of this model (let's call it a view) and present the user with ways (connected to things we'll call 'controllers') to call the interaction functions/methods. Then : the view registers itself with the model, display itself, and wait for user interactions. These user interactions are sent to the appropriate controller, which will call on the model's interaction functions/methods. Then the model updates itself and notify the view that it's state has changed, so the view can refresh itself. Ever heard of the "Model/View/Controller" pattern ? > Let's say I want to write a "move" function (or perhaps it would be a > method of a "Character" class) for moving the player around. Could you > really write this function without 1) knowing what the interface will > look like, and 2) integrating GUI code with the logic? Yes. The move function will modify the state of the board/pieces ("character", whatever) model, which will then notify whoever is interested that it's state has changed. > Another example could be printing messages to the player. If I need to > say "You killed the monster!", is there a general way to write this, or > do I need to specifically refer to GUI widgets and methods, etc. in > order for it to be displayed properly? Idem. State change, notification. > Basically, the question is this: can you write the logic behind a > program (whether it be a game, an email client, a text editor, etc.) > without having any idea of how you will implement the GUI? s/GUI/ui/g The user interface doesn't need to be graphical. There were games and emails clients and text editors before GUIs existed, you know ? From arnodel at googlemail.com Fri May 2 15:26:55 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Fri, 02 May 2008 20:26:55 +0100 Subject: Finally had to plonk google gorups. References: <966256b2-fe7c-4ec5-900b-90b285311881@k10g2000prm.googlegroups.com> <87abjne42n.fsf@physik.rwth-aachen.de> <2dc0c81b0804300851h63500c54q8570202c9cece332@mail.gmail.com> <87r6cncp4r.fsf@physik.rwth-aachen.de> <2dc0c81b0804301029n5db13d7ej8cb71938f1980f7e@mail.gmail.com> <2dc0c81b0804301030x7858b8b5y14729ba3632c61b9@mail.gmail.com> <9ee1e917-a0c2-4c03-b611-e409e315c071@x41g2000hsb.googlegroups.com> Message-ID: Mensanator writes: > On May 2, 1:20?pm, Michael Torrie wrote: >> Mensanator wrote: >> > On May 2, 9:53 am, Michael Torrie wrote: >> >> Shawn Milochik wrote: >> >>> How does one "plonk" stuff from Google Groups? Specifically, how >> >>> can this be done in Gmail? >> >> Set up a filter that looks for some phrase in the mail headers that >> >> identifies messages originating from google groups. ?Gmail's filters are >> >> fairly flexible. ?I'd probably just have it look for certain words. >> >> Look at an e-mail's source (raw view) and particularly check in the >> >> headers for things to filter by. >> >> > Why don't you just block all messages from Gmail? >> >> Brilliant! ?Seeing as he's asking about doing the filtering in Gmail >> (implying it's use for his own posting and viewing the list) that would >> work splendidly for him! ?Or not. >> >> Of course you're not likely to see this message either since I and many >> folks on here post from gmail. >> >> Spam comes mainly from Google Groups, not as much from Gmail in my >> experience. > > I didn't say it was POSTED from gmail, but the spammers often have > gmail addresses, to wit: You're confusing gmail addresses and Google Groups (groups.google.com), which can be used as a web interface to usenet and mailing lists. Look at the 'Organisation' header of the messages you quote. It seems most of the spam on comp.lang.python is posted from Google Groups, *including* the one with a 'From' header which is not a gmail address. So it would be more efficient to block messages posted from Google Groups than the ones from gmail addresses. -- Arnaud From hugo_hurtig at hotmail.com Sat May 10 20:40:27 2008 From: hugo_hurtig at hotmail.com (hugo_hurtig at hotmail.com) Date: 11 May 2008 00:40:27 GMT Subject: generic chemical ampicillin chloramphenicol allergy antibiotic generic drug information generic tablets 1 Message-ID: <4826407b$0$6434$834e42db@reader.greatnowhere.com> generic chemical ampicillin chloramphenicol allergy antibiotic generic drug information generic tablets +++ ANTIBIOTICS +++ ANTIBIOTICS +++ ANTIBIOTICS +++ + + http://jhku.net/BUY-AMPICILLIN/ http://jhku.net/BUY-AMPICILLIN/ http://jhku.net/BUY-AMPICILLIN/ http://jhku.net/BUY-AMPICILLIN/ + + + + http://www.online-medical.net/?affid=6138 http://www.v-medical.com/?affid=6138 http://sads.myspace.com/index.cfm?fuseaction=advancedFind.results&searchtype=web&searchtarget=tweb&t=tweb&searchBoxID=HeaderWebResults&searchString=buy+viagra +online+cheap+viagra+buy-viagra-where.info&q=buy+viagra+online+cheap+viagra+buy-viagra-where.info http://www.generic-pharmacy.net/generic-propecia.html?affid=6138 http://www.generic-pharmacy.net/generic-soma.html?affid=6138 generic patent cheap pharmaceuticals ampicillin and e coli ampicillin half life lb ampicillin generic manufacturer cipro antibiotic use of ampicillin ampicillin plate chloramphenicol ampicillin ampicillin activity ampicillin e coli levaquin antibiotic generic formulation tetracycline antibiotic ampicillin amoxicillin ampicillin recipe generic gel ampicillin urinary tract infection generic solution generic pharmaceutical enterococcus ampicillin ampicillin sensitive concentration of ampicillin antimicrobial antibiotic sigma ampicillin ampicillin 250mg ampicillin and claforan generic treatment ampicillin stock ampicillin heat generic paracetamol keflex antibiotic ampicillin gentamicin ampicillin on e coli ampicillin manufacturer From tjreedy at udel.edu Sun May 11 21:20:58 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 11 May 2008 21:20:58 -0400 Subject: IDLE 3.0a5 has problems with Unicode References: <13b7e4cc-031b-4c57-8212-9fe186d97324@e39g2000hsf.googlegroups.com> <845f3e49-14ef-43dd-8cc9-806f1f50690c@59g2000hsb.googlegroups.com> Message-ID: "Sven Siegmund" wrote in message news:845f3e49-14ef-43dd-8cc9-806f1f50690c at 59g2000hsb.googlegroups.com... |> I have a source code which IDLE 3.0a5 cannot parse, but Python 3.0a5 | > can: | | Oh I see the posts in this newsgroup do not yet support Unicode. I think this depends on the reader and maybe the fonts on the system. OutlookExpress displays hatted c, for instance, fine. Most | of the special characters in my source code have been messed up. But | anyway, those who know Czech can handle it. The error is replicable | even with the messed-up characters. From lists at cheimes.de Fri May 2 06:07:11 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 02 May 2008 12:07:11 +0200 Subject: dropping win98 support? was Re: Python 2.6 and wrapping C libraries on Windows In-Reply-To: <86718726-ca5b-4f84-9fc9-7e13bcd25140@q24g2000prf.googlegroups.com> References: <_X8Sj.3499$XI1.3261@edtnps91> <9a4cc17e-deb2-4219-a093-bff5c1a20d5e@s33g2000pri.googlegroups.com> <372ae26a-d772-4182-aa4b-64330626d60f@l25g2000prd.googlegroups.com> <86718726-ca5b-4f84-9fc9-7e13bcd25140@q24g2000prf.googlegroups.com> Message-ID: <481AE7CF.20901@cheimes.de> illume schrieb: > There are still *lots* of people who still use win95, 98, 98se, me, > and win2k - as shown by the statistics I linked to in a previous > post. If you want more statistics about the number of people using > what OS they are fairly easy to find with a search engine. One day > win9x will be finally dead, but that's not yet(and the w3c stats show > it's usage actually increasing in march!). Windows 2000 is still supported by Python 2.6 and 3.0 although you may get into trouble if you haven't installed at least SP4. Christian From technopax at gmail.com Tue May 13 15:53:42 2008 From: technopax at gmail.com (Technopax) Date: Tue, 13 May 2008 12:53:42 -0700 (PDT) Subject: Socializing site EXCLUSIVELY for TECHIES Message-ID: <6abacda4-76b0-4e73-82b8-4da58c42815e@d19g2000prm.googlegroups.com> Technopax.com, (http://www.technopax.com) the first socializing web portal exclusively catering to the IT Professionals world over is launched. This web portal will be a common online platform for IT industry related professionals. Technopax.com primarily targets computer software and hardware professionals, networking & system administrators, nano Technologists, bio-technologists, graphics & animation designers, BPO/Call Center/ITES employees, telecom experts, employees of IT Departments of all business organizations and technology students etc as its members. According to the promoters, an online platform exclusively for Techies will improve their technical and professional skills through the sharing of knowledge base, methodologies and skill sets. Apart from building vast friends circle, this will also help them to be abreast with the latest developments that happen in the tech front world over. Technopax.com has many features for the members to collaborate and socialize. It has text/audio and video chat, online clubs, events, forums, classified advertisements, discussion rooms, music and video sharing, web profiles etc. Please verify. From http Thu May 8 20:01:42 2008 From: http (Paul Rubin) Date: 08 May 2008 17:01:42 -0700 Subject: anagram finder / dict mapping question References: Message-ID: <7xve1oxs49.fsf@ruckus.brouhaha.com> dave writes: > if newtlist not in mapdic: > mapdic[newtlist] = [line] > if line not in mapdic[newtlist]: > mapdic[newtlist].append(line) I'd use the defaultdict module to avoid the above. > for value in mapdic.values(): > if len(value) <= 1: > pass > else: > print value I'd write: for value in mapdic.values(): if len(value) > 1: print value I'd actually use itervalues rather than values, but that's a little bit fancy, you don't have to worry about it til later. From notnorwegian at yahoo.se Fri May 23 23:30:10 2008 From: notnorwegian at yahoo.se (notnorwegian at yahoo.se) Date: Fri, 23 May 2008 20:30:10 -0700 (PDT) Subject: why is com-prompt faster and how do i start at cprompt at mydir/ ? Message-ID: when running a very computationalheavy program in the shell it sometimes freezes but the commandprompt runs it without problems and muh faster, why? also, the command prompt starts at C:\Users\user> i want to start at C:\python25\progs how do i change that? From lixinyi.23 at gmail.com Fri May 30 20:02:06 2008 From: lixinyi.23 at gmail.com (Lee) Date: Sat, 31 May 2008 09:02:06 +0900 Subject: How to get all the variables in a python shell In-Reply-To: Message-ID: <001001c8c2b1$919e74e0$1740a8c0@xxip78t6pqlqgp> Hi, thank your for your reply. I will try iPython. I did try sage for a while, but I found it quite heavy, and I'm not sure whether it's easy to expand like python or not. New libraries can be easily imported in python, and those libraries could be build in almost any popular computer language. Can sage do that? The reason why I want to work on this is the same with you. I'm an automotive engineer. What I need is a powerful yet light-weight computation software, which can help me in analyzing datas on the engine test bench. Matlab is powerful, but it contains so much stuff that I actually don't need but have to buy, and you know that it's quite expansive. So my idea is to build a GUI with python first, and then intergrate as many exsiting computation libraries as possible. There also has to be a plotting app, which is quite important and need to think about. I did try Gnuplot-python combination and matplotlib, but found both terrible inferior to Matlab plotting functionality. Do you know any plotting programs written in python? -----Original Message----- From: python-list-bounces+lixinyi.23=gmail.com at python.org [mailto:python-list-bounces+lixinyi.23=gmail.com at python.org] On Behalf Of caca at mailinator.com Sent: Friday, May 30, 2008 9:55 PM To: python-list at python.org Subject: Re: How to get all the variables in a python shell Your project interests me. Actually I was thinking about doing the same. I hadn't worked on it at all, but I though about it and had the idea about reading the session namespace directly, which I though would be stored in the __dict__ attribute of something. After reading your post, I have been trying a little bit, and I have found a way to do it with ipython. If you open an ipython console, press _ then hit TAB, you'll see it stores some useful information, including all input, all output, and after some searching, a dictionary matching all variables to its values. __IPYTHON__.user_ns There is a little extra stuff in there that you don't want, but that can be easily filtered (the extra stuff is either 'In', 'Out', 'help' or starts with '_'). I've tried it, and you can change the value in that dict to alter the value of the real variable. Say you have a variable 'test': test=5 __IPYTHON__.user_ns['test']=4 print test #prints 5 If I get it right, python is a dynamic language, and you won't break things by messing around with its inner stuff like this, but you better check it. Is this what you had in mind? -- http://mail.python.org/mailman/listinfo/python-list From jkrukoff at ltgc.com Thu May 15 19:32:44 2008 From: jkrukoff at ltgc.com (John Krukoff) Date: Thu, 15 May 2008 17:32:44 -0600 Subject: no inputstream? In-Reply-To: <1210893082.3312.2.camel@jmk> References: <87lk2ba4b4.fsf@mulj.homelinux.net> <8d566db4-c626-491f-82e4-303308c5b8da@25g2000hsx.googlegroups.com> <1210893082.3312.2.camel@jmk> Message-ID: <1210894364.3312.10.camel@jmk> On Thu, 2008-05-15 at 17:11 -0600, John Krukoff wrote: > On Thu, 2008-05-15 at 15:35 -0700, max wrote: > > On May 15, 6:18 pm, MRAB wrote: > > > On May 15, 9:00 pm, max wrote: > > > > > > > you're right, my java implementation does indeed parse for Id3v2 > > > > (sorry for the confusion). i'm using the getrawid3v2() method of this > > > > bitstream class (http://www.javazoom.net/javalayer/docs/docs0.4/ > > > > javazoom/jl/decoder/Bitstream.html) to return an inputstream that then > > > > i buffer and parse. apologies if i misrepresented my code! > > > > > > > back to python, i wonder if i'm misusing the mutagen id3 module. this > > > > brief tutorial (http://www.sacredchao.net/quodlibet/wiki/Development/ > > > > Mutagen/Tutorial) leads me to believe that something like this might > > > > work: > > > > > > > from mutagen.mp3 import MP3 > > > > id3tags = MP3(urllib2.urlopen(URL)) > > > > > > > but this gives me the following TypeError: "coercing to Unicode: need > > > > string or buffer, instance found". does this mean i need to convert > > > > the "file-like object" that is returned by urlopen() into a unicode > > > > object? if so, do i just decode() with 'utf-8', or is this more > > > > complex? as of now, doing so gives me mostly "No such file or > > > > directory" errors, with a few HTTP 404s. > > > > > > [snip] > > > I think it's expecting the path of the MP3 but you're giving it the > > > contents. > > > > cool, so how do i give it the path, if not in the form of a URL > > string? maybe this is obvious... > > -- > > http://mail.python.org/mailman/listinfo/python-list > > It doesn't look like you can, with mutagen. So, time to find a different > library that supports arbitrary file objects instead of only file paths. > I'd suggest starting here: > http://pypi.python.org/pypi?%3Aaction=search&term=id3&submit=search > > Possibly one with actual documentation, since that would also be a step > up from mutagen. > After a bit of time looking around, looks like nearly all the python id3 modules expect to work with filenames, instead of file objects. I can't vouch for it, and the documentation still looks sparse, but this module at least looks capable of accepting a file object: http://pypi.python.org/pypi/tagpy Looks like it'd be a challenge to build if you're on windows, since it depends on an external library. Alternately, you could probably create a subclass of the mutagen stuff that used an existing file object instead of opening a new one. No idea what that might break, but seems like it would be worth a try. As last ditch option, could write the first few kb of the file out to a temp file and see if mutagen will load the partial file. -- John Krukoff Land Title Guarantee Company From smitty1e at gmail.com Sat May 3 16:50:16 2008 From: smitty1e at gmail.com (smitty1e) Date: Sat, 3 May 2008 13:50:16 -0700 (PDT) Subject: unified command line args, environment variables, .conf file settings. References: <87ve1wxdyk.fsf@benfinney.id.au> Message-ID: On May 2, 11:29 pm, Ben Finney wrote: > smitty1e writes: > > Just a fun exercise to unify some of the major input methods for a > > script into a single dictionary. > > Here is the output, given a gr.conf file in the same directory with > > the contents stated below: > > > smitty at localhost ~/proj/mddl4/test $ ./inputs.py > > {'source_db': '/home/sweet/home.db'} > > smitty at localhost ~/proj/mddl4/test $ source_db="test_env" ./inputs.py > > {'source_db': 'test_env'} > > smitty at localhost ~/proj/mddl4/test $ ./inputs.py -f "test_cli" > > {'source_db': 'test_cli'} > > A good start. However, you need to account for two conventions with > configuration of programs via environment variables: [snip] > This is probably best done by a mapping specifically for the > environment variable names: > > config_env_names = { > 'source_db': 'GR_SOURCE_DB', > } > > and then referencing that dictionary when inspecting the environment: > > for key in config.keys(): > # ... > environ_name = config_env_names[key] > environ_value = os.environ.get(environ_name) > if environ_value is not None: > config[key] = environ_value > #... Hmmm... I kinda think your excellent points are more in the realm of policy than mechanism. What I was going for was to assert that there a designated section (of many possible ones) in a .conf file that represents the set of possible program inputs, and then offering an example of letting environment and command line arguments override that .conf section. Your points for reducing collision are well taken. Possibly having a removable prefix (which could be a "magic" .conf entry) would allow for a de-conflictor prefix like MY_PROGRAM_REALLY_ROCKSsource_db without having to propagate such an eyesore throughout the program code. In any case, it stands as a fun little worked example. R, C From gagsl-py2 at yahoo.com.ar Tue May 13 06:47:06 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 13 May 2008 07:47:06 -0300 Subject: where to get McMillan Installer? References: <74f142de-6485-4773-bae8-2a274be19b80@w7g2000hsa.googlegroups.com> Message-ID: En Tue, 13 May 2008 07:06:09 -0300, gsal escribi?: > There does not seem to be a valid url for the Installer, anywhere. > Could anyone provide me with a copy of it? I think py2exe is its successor: http://www.py2exe.org/ -- Gabriel Genellina From jurgenex at hotmail.com Fri May 9 01:45:21 2008 From: jurgenex at hotmail.com (Jürgen Exner) Date: Fri, 09 May 2008 05:45:21 GMT Subject: The Importance of Terminology's Quality References: <68i6b5F2soauaU1@mid.individual.net> Message-ID: <9vo724prqd0etqlraapsv8e3j6bcigh5ea@4ax.com> "Waylen Gumbal" wrote: >Sherman Pendley wrote: >> kodifik at eurogaran.com writes: >> > >> > > PLEASE DO NOT | :.:\:\:/:/:.: >> > > FEED THE TROLLS | :=.' - - '.=: >Not everyone follows language-neutral groups (such as comp,programming >as you pointed out), so you actually reach more people by cross posting. You seem so have failed to grasp the concept of why Usenet is divided into separate groups in the first place. >This is what I don't understand - everyone seems to assume that by cross >posting, one intends on start a "flamefest", when in fact most such >"flamefests" are started by those who cannot bring themselves to >skipping over the topic that they so dislike. By your argument there is no need for individual groups in the first place. We could just as well use a single "HereGoesEverything" and just skip over those topics that we so dislike. jue From pecora at anvil.nrl.navy.mil Sat May 3 11:24:13 2008 From: pecora at anvil.nrl.navy.mil (Lou Pecora) Date: Sat, 03 May 2008 11:24:13 -0400 Subject: #!/usr/bin/env python vs. #!/usr/bin/python References: <87abj91j8u.fsf@benfinney.id.au> <87k5iczvdy.fsf@benfinney.id.au> <877ieczryn.fsf@benfinney.id.au> Message-ID: In article , Grant Edwards wrote: > On 2008-05-02, D'Arcy J.M. Cain wrote: > > On Sat, 03 May 2008 00:44:00 +1000 > > Ben Finney wrote: > >> "D'Arcy J.M. Cain" writes: > >> > As someone else pointed out, not all the world is Linux. > >> > >> It's a good thing I've never implied such to be the case. > > > > You haven't *said* it but you have definitely *implied* it. > > Installing Python in /usr/bin is not common. > > It is common. That's where it's installed by almost all Linux > distributions. MacOS X system python (or links to them) is in the same place. -- -- Lou Pecora From larry.bates at websafe.com` Thu May 22 18:51:39 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Thu, 22 May 2008 17:51:39 -0500 Subject: Python is slow In-Reply-To: References: Message-ID: <3J6dnbQZld6PZKjVnZ2dnUVZ_sDinZ2d@comcast.com> cm_gui wrote: > Python is slow. Almost all of the web applications written in > Python are slow. Zope/Plone is slow, sloow, so very slooow. Even > Google Apps is not faster. Neither is Youtube. > Facebook and Wikipedia (Mediawiki), written in PHP, are so much faster > than Python. > Okay, they probably use caching or some code compilation -- but Google > Apps and those Zope sites probably also use caching. > > I've yet to see a web application written in Python which is really > fast. You are just dead wrong about this. Bad programmers will write slow software in any language. There are some HUGE sites using Zope. I think much of Google's software is written in Python. I have programs that have surprised me with their speed. If your Python program is slow, you have almost assuredly approached it with a wrong method or algorithm. www.websafe.com is completely written in Python and we support thousands of users uploading data simultaneously at wire speed (and that includes AES-256 encryption on our end). -Larry From ivan.illarionov at gmail.com Mon May 26 18:00:18 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Mon, 26 May 2008 22:00:18 +0000 (UTC) Subject: Keyboard Events References: <14d057b1-3b62-4efb-bdb2-c20394c7268c@r66g2000hsg.googlegroups.com> <1e920a06-3741-4154-94a1-73b90f659e1b@z72g2000hsb.googlegroups.com> Message-ID: On Mon, 26 May 2008 14:40:18 -0700, Gandalf wrote: > Thanks! > Anyone know which library should i learn then? Looks like you need to dive into Win32 API http://msdn.microsoft.com/en-us/library/ms697544(VS.85).aspx http://msdn.microsoft.com/en-us/library/ms645530(VS.85).aspx and others combined with ctypes. Ivan From jstucklex at attglobal.net Tue May 27 21:47:55 2008 From: jstucklex at attglobal.net (Jerry Stuckle) Date: Tue, 27 May 2008 21:47:55 -0400 Subject: php vs python In-Reply-To: References: <5l%Yj.77$mz3.53@fe101.usenetserver.com> <37b112d8-a3ba-446d-9d2f-d907d93c637b@w8g2000prd.googlegroups.com> <-t-dnWQ4bZN2MaTVnZ2dnUVZ_qGdnZ2d@comcast.com> <68cb8bb1-4cc5-4a28-8915-46e7d4e316d9@d1g2000hsg.googlegroups.com> <613388153.20080528051020@freemail.ru> Message-ID: <-o2dnfEz48JGJKHVnZ2dnUVZ_sidnZ2d@comcast.com> Ivan Illarionov wrote: > On Wed, 28 May 2008 05:10:20 +0400, AnrDaemon wrote: > >> Greetings, Ivan Illarionov. >> In reply to Your message dated Monday, May 26, 2008, 04:47:00, >> >>>> As I've said before - good programmers can write good code in any >>>> language. >>> Yes, they can. But it may be harder to do for them in one language and >>> easier in another. >> It's obvious lie. If you have clear mind and you know language you're >> using, there are absolutely NOTHING can deny you to write clear code. >> Even using forth postfix notation, I have no problem writing good code, >> it's as easy as writing bad code. And yes, I do see the difference. > > No. Language does matter. Not for a good programmer. Only for half-assed ones. -- ================== Remove the "x" from my email address Jerry Stuckle JDS Computer Training Corp. jstucklex at attglobal.net ================== From davidj411 at gmail.com Thu May 15 16:25:33 2008 From: davidj411 at gmail.com (davidj411) Date: Thu, 15 May 2008 13:25:33 -0700 (PDT) Subject: FTP upload issue Message-ID: <44eede8c-05b5-441d-9207-210074e55f8f@f36g2000hsa.googlegroups.com> I am having difficulty uploading a text file using Python 2.5 on MAC OSX. SCRIPT filename='/tmp/mac.info2.txt' fh=open(filename,'w') fh.write('yes, i have a mac but don't hold that against me - just example data') fh.close() from ftplib import FTP 'host, username, and password are string variables that have already been defined. ftp = FTP(host) ftp.login(username,password) 'so far, logged in, all is well , error is on next line. ftp.storlines("STOR" + filename, file(filename)) ftp.quit() What am i doing wrong? the file DOES exist, the path is correct, and the file was closed after being written. file(filename) should open it again for the upload? http://www.python.org/doc/lib/ftp-objects.html says that the command should be an appropriate "STOR" command: "STOR filename". file is an open file object which is read... ERROR File "mac.inventory.py", line 44, in ftp.storlines("STOR " + filename, file(filename)) File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/ftplib.py", line 437, in storlines conn = self.transfercmd(cmd) File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/ftplib.py", line 356, in transfercmd return self.ntransfercmd(cmd, rest)[0] File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/ftplib.py", line 327, in ntransfercmd resp = self.sendcmd(cmd) File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/ftplib.py", line 241, in sendcmd return self.getresp() File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/ftplib.py", line 216, in getresp raise error_perm, resp ftplib.error_perm: 550 /tmp/mac.info2.txt: The system cannot find the path specified. From ivan.illarionov at gmail.com Sun May 11 22:33:41 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Mon, 12 May 2008 02:33:41 +0000 (UTC) Subject: Is using range() in for loops really Pythonic? References: <482657ca$0$25026$607ed4bc@cv.net> <41078222-aec0-4e8b-8a1f-945cdf814498@m73g2000hsh.googlegroups.com> <48275446$0$11628$607ed4bc@cv.net> <87mymw8nr0.fsf@benfinney.id.au> Message-ID: On Sun, 11 May 2008 18:52:48 -0700, Carl Banks wrote: > On May 11, 6:44 pm, Ben Finney > wrote: >> In such cases, the name 'dummy' is conventionally bound to the items >> from the iterator, for clarity of purpose:: >> >> for dummy in range(10): >> # do stuff that makes no reference to 'dummy' > > Is this documented? I've never heard of this convention. It's not PEP > 8, and I've never seen consistent usage of any name. I'd be interested > in knowing where you read that this was a convention, or in what > subcommunities it's a convention in. > > I think dummy is a terrible name to use for this, since in no other > usage I can think of does the word "dummy" suggest something isn't used. > In fact, quite the opposite. For example, the dummy_threads module is > most definitely used; the word dummy means that it's stripped down. > Based on that, your usage of the symbol dummy above would suggest to me > that it's a value used in lieu of something else (such as a calculated > value). > > In mathematics, a dummy argument another name for the independent > variable of a function (or more accurately, the symbol used to represent > it), which also doesn't match your usage. > > If a value isn't used, then I think the most clear name for it is > "unused". > > > Carl Banks I agree with Carl. This group is the only place I've heard about this convension and it looks terrible IMO. Even if a value is not used, the variable still has a meaning: it is a counter, or an index. I know about the other convention: "for i in xrange" or "for i in range". Wikipedia agrees with me: http://en.wikipedia.org/wiki/For_loop Examples in wikipedia article use either "i" or "counter". It is established convention in almost every programming language and its origins are in mathematics (matrix indices). Google search for "for dummy in range" (with quotes) gives 164 results While "for dummy in range" gives 146 000 results. Almost thousand times more. So, "i" is more conventional and as such is more readable. -- Ivan From torriem at gmail.com Sat May 24 22:09:13 2008 From: torriem at gmail.com (Michael L Torrie) Date: Sat, 24 May 2008 20:09:13 -0600 Subject: Code correctness, and testing strategies In-Reply-To: <18c1e6480805241317s4e960259pa8b2f1f8dc8d67f6@mail.gmail.com> References: <18c1e6480805241317s4e960259pa8b2f1f8dc8d67f6@mail.gmail.com> Message-ID: <4838CA49.7000705@gmail.com> David wrote: > Seriously, 10 hours of testing for code developed in 10 hours? What > kind of environment do you write code for? This may be practical for > large companies with hordes of full-time testing & QA staff, but not > for small companies with just a handful of developers (and where you > need to borrow somone from their regular job to do non-developer > testing). In a small company, programmers do the lions share of > testing. For programmers to spend 2 weeks on a project, and then > another 2 weeks testing it is not very practical when they have more > than one project. Watch your programmers then. They do have to write and debug the code. And they will spend at least as much or more time debugging as writing the code. It's a fact. I have several programmers working for me on several projects. What you have been told is fact. In my experience it's 3-10x more time debugging as programming. I've heard that *good* programmers write, on average, 10 new lines of code per day. I can also verify that this is pretty accurate, both in my own programming experience, and watching programmers working for me. From castironpi at gmail.com Thu May 8 19:49:25 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Thu, 8 May 2008 16:49:25 -0700 (PDT) Subject: Mathematics in Python are not correct References: <52c855d8-5609-43e0-b98f-9fa87b2808c2@m3g2000hsc.googlegroups.com> Message-ID: On May 8, 6:10?pm, Nicolas Dandrimont wrote: > * wxPytho... at gmail.com [2008-05-08 15:54:42 -0700]: > > > Have a look at this: > > > >>> -123**0 > > -1 > > > The result is not correct, because every number (positive or negative) > > raised to the power of 0 is ALWAYS 1 (a positive number 1 that is). > > > The problem is that Python parses -123**0 as -(123**0), not as > > (-123)**0. > > And why is this a problem ? It is the "standard" operator precedence > that -123^0 is -(123^0), isn't it ? > > > I suggest making the Python parser omit the negative sign if a > > negative number is raised to the power of 0. That way the result will > > always be a positive 1, which is the mathematically correct result. > > That's what it does : > > >>> -123**0 > -1 > >>> (-123)**0 > > 1 > > > This is a rare case when the parser is fooled, but it must be fixed in > > order to produce the correct mathematical result. > > Again, the mathematical result is correct. -123^0 is -(123^0), not > (-123)^0. > > Regards, > -- > Nicolas Dandrimont > > ?signature.asc > 1KDownload Signs include power. >>> -2**0 -1 >>> (-2)**0 1 >>> -(2**0) -1 +x, -x Positive, negative ~x Bitwise not ** Exponentiation from Help; However: >>> 2+3**1 5 >>> 2+3**2 11 So, the order of precedence table has not listed the identical order of operations with the implementation. I have hit parentheses in rolling too. In terms of money, processor-based operations may not be equals. Clock cycles cost fractions of time. But, I don't see x= -x in realty. From gagsl-py2 at yahoo.com.ar Mon May 5 01:04:53 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 05 May 2008 02:04:53 -0300 Subject: Script Optimization References: <6ed749de-1a7d-4db5-a229-d3400da4d24b@f24g2000prh.googlegroups.com> <15e73598-1186-40d5-af63-f176976c5ed1@s33g2000pri.googlegroups.com> Message-ID: En Sun, 04 May 2008 17:01:15 -0300, lev escribi?: >> * Change indentation from 8 spaces to 4 > I like using tabs because of the text editor I use, the script at > the end is with 4 though. Can't you configure it to use 4 spaces per indent - and not use "hard" tabs? >> * Remove useless "pass" and "return" lines > I replaced the return nothing lines with passes, but I like > keeping them in case the indentation is ever lost - makes it easy to > go back to original indentation I can't think of a case when only indentation "is lost" - if you have a crash or something, normally you lose much more than indentation... Simple backups or a SCM system like cvs/svn will help. So I don't see the usefulness of those "pass" statements; I think that after some time using Python you'll consider them just garbage, as everyone else. >> * Temporarily change broken "chdir" line > removed as many instances of chdir as possible (a few useless ones > to accomodate the functions - changed functions to not chdir as much), > that line seems to work... I made it in case the script is launched > with say: 'python somedir\someotherdir\script.py' rather than 'python > script.py', because I need it to work in it's own and parent > directory. You can determine the directory where the script resides using import os basedir = os.path.dirname(os.path.abspath(__file__)) This way it doesn't matter how it was launched. But execute the above code as soon as possible (before any chdir) > checksums = open(checksums, 'r') > for fline in checksums.readlines(): You can directly iterate over the file: for fline in checksums: (readlines() reads the whole file contents in memory; I guess this is not an issue here, but in other cases it may be an important difference) Although it's perfectly valid, I would not reccomend using the same name for two different things (checksums refers to the file name *and* the file itself) > changed_files_keys = changed_files.keys() > changed_files_keys.sort() > missing_files.sort() > print '\n' > if len(changed_files) != 0: > print 'File(s) changed:' > for key in changed_files_keys: You don't have to copy the keys and sort; use the sorted() builtin: for key in sorted(changed_files.iterkeys()): Also, "if len(changed_files) != 0" is usually written as: if changed_files: The same for missing_files. > for x in range(len(missing_files)): > print '\t', missing_files[x] That construct range(len(somelist)) is very rarely used. Either you don't need the index, and write: for missing_file in missing_files: print '\t', missing_file Or you want the index too, and write: for i, missing_file in enumerate(missing_files): print '%2d: %s' % (i, missing_file) > def calculate_checksum(file_name): > file_to_check = open(file_name, 'rb') > chunk = 8196 Any reason to use such number? 8K is 8192; you could use 8*1024 if you don't remember the value. I usually write 1024*1024 when I want exactly 1M. -- Gabriel Genellina From mnordhoff at mattnordhoff.com Sun May 11 21:54:44 2008 From: mnordhoff at mattnordhoff.com (Matt Nordhoff) Date: Mon, 12 May 2008 01:54:44 +0000 Subject: python without while and other "explosive" statements In-Reply-To: <3dd0b1a30805111639n2d6db827v166104f28825a29c@mail.gmail.com> References: <3dd0b1a30805111639n2d6db827v166104f28825a29c@mail.gmail.com> Message-ID: <4827A364.9040507@mattnordhoff.com> ivo talvet wrote: > Hello, > > Is it possible to have a python which not handle the execution of > "while", "for", and other loop statements ? I would like to allow > remote execution of python on a public irc channel, so i'm looking for > techniques which would do so people won't be able to crash my computer > (while 1: os.fork(1)), or at least won't won't freeze my python in a > infinite loop, make it unresponsive. Is there a compiling option (or > better, something i can get with apt-get cos i think compiling myself > and handle all the metastuff myself is somehow dirty) for have a > "secure python" (you can guess what i mean by "secure" in my case) or > must i touch myself the source disable some code lines ? If last > solution, which modifications in which files should i do ? (sorry for > my bad english) > > Thanks. > > Ivo is a pastebin-like website that lets people upload code in a dozen different languages, and it runs it. They have info up about how it's secure at . I'm pretty sure there's another similar website that's specific to Python, but I can't remember it. Anyway, it was similar, using virtual machines, a firewall, and killing stuff that ran for longer than 20 seconds, IIRC. (Thanks for the link to codepad, habnabit.) -- From zapwireDASHgroups at yahoo.com Fri May 23 15:40:04 2008 From: zapwireDASHgroups at yahoo.com (Joel Koltner) Date: Fri, 23 May 2008 12:40:04 -0700 Subject: Reloading function obtained via 'from xxx import yyy' Message-ID: How do I get Python to correctly re-load this function definition? In test.py: def testFunc(): print 'My testFunc!' I execute... >>> from test import testFunc >>> testFunc() My testFunc! Fine... now I change test.py to: def testFunc(): print 'Modified testFunc!' ...and I'd like to reload testFunc. How do I do so? 'from test import testFunc' keeps the old definition around, and 'reload test' of course doesn't work becayse I didn't use 'import test' in the first place. Thanks for the help, ---Joel From aisaac at american.edu Thu May 8 10:26:55 2008 From: aisaac at american.edu (Alan Isaac) Date: Thu, 08 May 2008 14:26:55 GMT Subject: observer pattern question #1 (reference to subject) Message-ID: I have two questions about the "observer pattern" in Python. This is question #1. (I'll put the other is a separate post.) Here is a standard example of the observer pattern in Python: http://en.wikipedia.org/wiki/Observer_pattern Contrast with this rather standard discussion: http://www.dofactory.com/Patterns/PatternObserver.aspx#_self1 The difference I am focusing on is that in the latter, the observer (investor) maintains a reference to the subject (stock). (Many questions can be raised of course: see the discussion at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/131499). Is anything lost by not maintaining this reference (other than error checking ...)? If I feel the observer needs access to the subject, what is wrong with just having the subject pass itself as part of the notification? Thank you, Alan Isaac From chinasupply00 at 126.com Tue May 13 18:58:05 2008 From: chinasupply00 at 126.com (chinasupply00 at 126.com) Date: Tue, 13 May 2008 15:58:05 -0700 (PDT) Subject: Discount Price !! AF1 Jordan1-23 Sneakers, Chloe Coach UGG Handbags, GGG EDhardy T-shirts, Dior Sandals, ETC Message-ID: Discount Prada Handbags, Chanel Handbags, LV Handbags, (G U C C I)Handbags, D&G Handbags, Chloe Handbags, Hermes Handbags, Guess Handbags, Jimmy Choo Handbags, Bcbg Handbags. Supply Dior Wallet, Fendi Wallet, Coach Purse, Juicy Purse, Miumiu Purse Supply BOSS t-shirts, men's Lacoste T-shirts, G U C C I women's t- shirts,Polo T- shirts, BBC T-shirts, Bape T-shirts, ED hardy T-shirts, Coogi T-shirts, Christian Audigier T-shirts, Gian Green Glalal (ggg) T- shirts, Artful Dodger T-shirts, LRG T-shirts, Burberry T-shirts, Affliction T-shirts, LRG jeans, Red Monkey Jeans... wholesale Pro Bowl NFL jersey, NBA Jersey, NHL jersey, MLB jersey discount price. Suppliers NFL sports jersey, NFL basketball jersey, NFL football jersey, Reebok NFL jersey, 2008 New NFL jersey Prada LV Handbags, Chanel Miumiu Purse, Fendi Dior Wallet wholesale Discount Coach Sandals, Dior Sandals, Prada Sandals, Chanel Sandals, Versace Sandals, Crocs Sandals, Women's Sandals Men's Slippers From China From myshelter at gmail.com Sun May 4 07:59:53 2008 From: myshelter at gmail.com (Protected) Date: Sun, 4 May 2008 04:59:53 -0700 (PDT) Subject: Please help - Tkinter not doing anything References: <20562a9d-200c-40ae-a850-eb0f9a943d3f@l42g2000hsc.googlegroups.com> <237aa3894dff4c8976896df85f4d7d23@localhost> <3ab5d06a0805040239m6cf12d39ufcde4fcc585f81e4@mail.gmail.com> Message-ID: <05343da9-b929-4d86-a2b0-80984af9c25c@l64g2000hse.googlegroups.com> On May 4, 12:18 pm, s0s... at gmail.com wrote: > On May 4, 5:22 am, Protected wrote: > > > I had previously ran the import line. I prepended it to the example > > code I'm trying to run every time but it did not help, still nothing > > happens. With or without var before 'root'. I'm pasting the code in > > IDLE and using Windows XP as written in the first post. > > Tkinter doesn't work if you type the statements in IDLE. I don't > remember the specifics of it, but essentially it doesn't work because > IDLE is itself a Tkinter app. You have to type it at the Python > command line or save it in a file. BTW, if you're on Windows, you > should definitely check wxPython. I used to work with Tkinter, > struggling with it all the time only to get a lame result most of the > time. Then I switched to wxPython, and in the same week I was learning > it I did a better GUI than I ever did in Tkinter (with months of > work!). I feel it makes it easier to make your program have a better > structure and design, and thus lets you focus on the actual task of > the program, rather than in the GUI itself. Plus, on Windows, you'll > get the widgets to look more natively, like any good quality > application there is on Windows. Ah, but is it cross platform? (Thanks for letting me know about IDLE.) From kyosohma at gmail.com Wed May 7 09:01:24 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Wed, 7 May 2008 06:01:24 -0700 (PDT) Subject: PHP + TinyButStrong Python replacement References: Message-ID: On May 7, 6:12?am, pistacchio wrote: > hi! i'm a php user and a python programmer. i'd love to use python for > my server side needs but i can't seem to find what i'm looking for. for > most of my php work i use mysql and tinyButStrong > (http://www.tinybutstrong.com) which is a very lightweight template > engine that offers powerful functionalities. you insert TBS tags in web > pages like: > >
[var.x]
> > and it replaces [var.x] with the value of global variable x. it also > makes blocks (and nested blocks) easy to implement: > >

[blk1;block=begin] [blk1.val]
> [blk1;block=end]

> > in the previous code it cycles throu all the values of the array blk1. > > it does many more things, like htlm escaping, url and js encoding etc, > conditional displaying etc, but it is not more confusing that inserting > pieces of code into the HTML (aka: littering the code and kissing > goodbye to the code/presentation separation). it comes in the form of a > single file with a single class that you can easily include in the code > and go. > > now, i've searched the net and it seems full of python-based frameworks > for doing server side scripting and templating, but none that suits my > needs. > > ? ? 1. i like writing code and i like control. i mean, open up the > simplest text editor and write in it. i don't want something that is > command-line driven or that writes code for me like ">>> > makePagesFromThisDatabase()". > ? ? 2. i want something very lightweight. i don't want dozen of options, > pre-made blogging parts ecc. i just need a good non invasive template > engine and the basic functions for server side scripting, like session > managing, request parsing, functions to manipulate html code (encodings etc) > ? ? 3. i don't want to beg my hosting provider to install the libraries. > a simple include file should do the work. > ? ? 4. object oriented programming is not required (better: i prefer > plain old procedural programming). > > any help? thanks in advance Did you look at TurboGears or Django? TG uses Kid in the 1.x series and Genshi in 2.x (I think) for templating purposes. There's also Cheetah, one of the more powerful Python templating engines out there. http://genshi.edgewall.org/ http://www.kid-templating.org/ http://www.cheetahtemplate.org/ http://turbogears.org/ Maybe those links will get you going. Mike From ndbecker2 at gmail.com Wed May 21 12:48:59 2008 From: ndbecker2 at gmail.com (Neal Becker) Date: Wed, 21 May 2008 12:48:59 -0400 Subject: [ctypes] convert pointer to string? References: <5349ef25-2900-4706-b6ab-f293da263eb9@m3g2000hsc.googlegroups.com> Message-ID: marek.rocki at wp.pl wrote: > Neal Becker napisa?(a): >> In an earlier post, I was interested in passing a pointer to a structure >> to fcntl.ioctl. >> >> This works: >> >> c = create_string_buffer (...) >> args = struct.pack("iP", len(c), cast (pointer (c), c_void_p).value) >> err = fcntl.ioctl(eos_fd, request, args) >> >> Now to do the same with ctypes, I have one problem. >> >> class eos_dl_args_t (Structure): >> _fields_ = [("length", c_ulong), >> ("data", c_void_p)] >> ... >> args = eos_dl_args_t() >> args_p = cast(pointer(args), c_void_ptr).value >> fcntl.ioctl(fd, request, args_p) <<< May fail here >> >> That last may fail, because .value creates a long int, and ioctl needs a >> string. >> >> How can I convert my ctypes structure to a string? It _cannot_ be a >> c-style 0-terminate string, because the structure may contain '0' values. > > Hello. I'm not completely sure what your problem is ("may fail" is not > a good description. Does it fail or does it not?). May fail is exactly what I meant. As written, ioctl will accept a 3rd arg that is either a string or int. In this case, it is int. If the address fits in an int it works, but if the address (which is a long) doesn't fit it fails (gives an overflow error). Seems to be random (as well as platform dependent). From afrobeard at gmail.com Thu May 29 07:24:55 2008 From: afrobeard at gmail.com (afrobeard) Date: Thu, 29 May 2008 04:24:55 -0700 (PDT) Subject: Compare 2 files and discard common lines References: <8d55718c-6881-4844-b8d1-bbe1c5929f46@x35g2000hsb.googlegroups.com> Message-ID: Another way of doing this might be to use the module difflib to calculate the differences. It has a sequence matcher under it which has the function get_matching_blocks difflib is included with python. On May 29, 2:02?pm, Chris wrote: > On May 29, 10:36?am, loial wrote: > > > I have a requirement to compare 2 text files and write to a 3rd file > > only those lines that appear in the 2nd file but not in the 1st file. > > > Rather than re-invent the wheel I am wondering if anyone has written > > anything already? > > How large are the files ? You could load up the smallest file into > memory then while iterating over the other one just do 'if line in > other_files_lines:' and do your processing from there. ?By your > description it doesn't sound like you want to iterate over both files > simultaneously and do a line for line comparison because that would > mean if someone plonks an extra newline somewhere it wouldn't gel. From daveparker at flamingthunder.com Tue May 13 10:05:28 2008 From: daveparker at flamingthunder.com (Dave Parker) Date: Tue, 13 May 2008 07:05:28 -0700 (PDT) Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <2b66a86e-5a05-4262-b3c9-4703b0ae3372@d1g2000hsg.googlegroups.com> <5b0e3f70-afde-4480-8713-e7113b1250d7@x35g2000hsb.googlegroups.com> <1f537717-00d0-48ee-99b6-7125b96a6133@t12g2000prg.googlegroups.com> <68t4o0F2vaoncU1@mid.uni-berlin.de> <3d8cb22c-5b5a-49c1-9ee0-9c09ed91106a@k37g2000hsf.googlegroups.com> Message-ID: On May 13, 7:44?am, castiro... at gmail.com wrote: > I am not convinced that the colorspace occupies three dimensions necessarily. Apparently there are some people -- called tetrachromats -- who can see color in four dimensions. They have extra sets of cones in their retinas containing a different photopigment. So, the dimensions of color appear to be an artifact of our visual systems, and not inherent in the colors themselves which are linear (one-dimensional) in frequency. http://en.wikipedia.org/wiki/Tetrachromacy From hdante at gmail.com Mon May 19 21:13:52 2008 From: hdante at gmail.com (Henrique Dante de Almeida) Date: Mon, 19 May 2008 18:13:52 -0700 (PDT) Subject: Using Python for programming algorithms References: <98fa5fa3-45ae-4df1-9fd3-1a227641244f@p25g2000hsf.googlegroups.com> <48314dd0$0$32138$426a34cc@news.free.fr> <4d44955c-4eee-42bd-ae7f-a3cf511869c2@27g2000hsf.googlegroups.com> Message-ID: On May 19, 5:25?pm, "bruno.desthuilli... at gmail.com" wrote: > There's at least one (possibly incomplete) C interpreter. FWIW, it > would not be harder (and possibly simpler) to write a byte-code+VM > based C implementation than it is to write CPython, Jython or You may (right now, readily, without experimental software) compile C to, for example, llvm bytecode, interpret it in the VM, JIT-compile it, native-compile it, etc. There's also experimental support for compiling C to the JVM. Notice that you usually want to optimize C code, so it will be harder than writing a python interpreter. > IronPython. The point is that it's just useless - C is a (very) low- It's not useless. Consider that you may distribute your C application in byte-code instead of native code and during the installation process, it is native compiled and optimized exactly to your architecture (like a better "Gentoo", with the compilation split between you and the user). > point is that, given Python's (as a language) extrem dynamism, > compiling it to native code wouldn't buy you much in terms of raw > performances. The problem is not with writing a native-code > compiler[1}, but with writing an *optimising* native-code compiler. That's the job of pypy folks. And they are getting there. They use a python subset, called RPython: http://morepypy.blogspot.com/2008/01/rpython-can-be-faster-than-c.html (note: the test in the site compares garbage collection speed) BTW, here's how to compile RPython to (optimized) native code: http://codespeak.net/pypy/dist/pypy/doc/standalone-howto.html And here is the document that talks about all that: http://codespeak.net/pypy/dist/pypy/doc/dynamic-language-translation.html > I'm not trying to "trivialize" anything. I'm just getting fed up with > this "Python is an interpreted and therefore slow language" non- > sense. ?Python is a language, and as such is neither slow nor fast nor I'm sorry for creating all those offtopic posts. I feel so ashamed :- (. Well, not really. :-P My suggestion was to use code suitable for optimization (not considering things that you'd need to worry about the way you write code, like RPython, or psyco). That's all. :-) From bignose+hates-spam at benfinney.id.au Tue May 6 07:06:49 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 06 May 2008 21:06:49 +1000 Subject: #!/usr/bin/env python vs. #!/usr/bin/python References: <87bq3ozs09.fsf@benfinney.id.au> <20080502110755.85e2ea4e.darcy@druid.net> <956b3035-4f82-4391-8d1e-7f88875f8d21@w1g2000prd.googlegroups.com> <3de8e1f70805060135h5b5078fpe12fe5348d24a421@mail.gmail.com> Message-ID: <874p9belo6.fsf@benfinney.id.au> "Wojciech Walczak" writes: > 2008/5/6, Banibrata Dutta : > > > Use /usr/bin/env. If env is not in /usr/bin, put a link to it there. > > > > So why not put symlink to Python over there on all machines, if > > we can put one (or env itself) there ? > > To avoid linking all the rest of interpreters like perl, ruby, lua > and dozens of others. The argument was being made from "thousands of scripts". Isn't "dozens of symlinks" better? -- \ "It is difficult to get a man to understand something when his | `\ salary depends upon his not understanding it." ?Upton | _o__) Sinclair, 1935 | Ben Finney From fetchinson at googlemail.com Wed May 7 16:49:09 2008 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Wed, 7 May 2008 13:49:09 -0700 Subject: Idea for P3K In-Reply-To: <4821fea4$0$880$ba4acef3@news.orange.fr> References: <4821d418$0$932$ba4acef3@news.orange.fr> <4821fea4$0$880$ba4acef3@news.orange.fr> Message-ID: > > I don't often feel like using this word > > Look at languages like OCAML or F # > I looked at OCAML and F#. Now what? Cheers, Daniel From nobody at yahoo.com Thu May 22 19:57:07 2008 From: nobody at yahoo.com (Andrew) Date: Thu, 22 May 2008 23:57:07 GMT Subject: Tun/Tap Driver using OpenVPN and DeviceIoControl Message-ID: Hello I am trying to port some code and I am running into some issues I may or may not be able to solve on my own and would appreciate your help Basically I am trying to open the Tun Driver through openvpn in Ether (Tap mode). code is as follows f = win32file.CreateFile("C:\\WINDOWS\\System32\\drivers\\tunmp.sys", GENERIC_READ, 0, None, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0) if WINDOWS: ifs = win32file.DeviceIoControl(f, TUNSETIFF, struct.pack("16sH", "wj%d", TUNMODE), 0, None) else: ifs = ioctl(f, TUNSETIFF, struct.pack("16sH", "wj%d", TUNMODE)) ifname = ifs[:16].strip("\x00") print "Interface %s created. Configure it and use it" % ifname but does not seem to work so well I get "The Paramater is incorrect" Traceback (most recent call last): File "wifi.py", line 167, in ifs = win32file.DeviceIoControl(f, TUNSETIFF, struct.pack("16sH", "wj%d", TU NMODE), 0, None) pywintypes.error: (87, 'DeviceIoControl', 'The parameter is incorrect.') Would appreciate any help Ty From samslists at gmail.com Wed May 21 02:36:21 2008 From: samslists at gmail.com (samslists at gmail.com) Date: Tue, 20 May 2008 23:36:21 -0700 (PDT) Subject: Running programs under a python program... Message-ID: <43c19b29-878a-41b8-b2c9-48b5d91233c3@t12g2000prg.googlegroups.com> So I have a python program that runs a bunch of other programs....it then loops forever, occasionally executing other programs. To run each of these programs my python code executes: subprocess.Popen(command_line, shell=True, stdout=fd, stderr=subprocess.STDOUT) where command_line is an appropriate command line. :) Now my problem is when I abort this program it kills off all the child processes I've started. In this case I don't want that. How can I stop the child processes from dieing when I kill off the parent? Thanks! From gaojihuiyuan at yahoo.cn Thu May 15 14:14:55 2008 From: gaojihuiyuan at yahoo.cn (gaojihuiyuan) Date: Thu, 15 May 2008 11:14:55 -0700 (PDT) Subject: Computer Message-ID: Plastic Coat Your Cedar with EPL EPL is a clear thin polymer coat that will maintain the bright cedar wood look. Buy online today. http://www.healthhuman.com.cn/Computer.htm Cedar Wood Find Deals on Cedar Wood and other Home & Garden Products at DealTime. Choose from millions of deals. Save time and money every time you shop. http://www.healthhuman.com.cn/Computer.htm Cedar Wood - Bargain Prices Shop fast, Buy smart, Shopzilla for Wood Outdoor Furniture and other Furniture and Outdoor Decor. Every product from every store means you get a Bargain Price. Don't just shop, Shopzilla. http://www.healthhuman.com.cn/Computer.htm From marco at sferacarta.com Tue May 6 05:12:46 2008 From: marco at sferacarta.com (Marco Mariani) Date: Tue, 06 May 2008 11:12:46 +0200 Subject: Decimal vs Float comparasion In-Reply-To: References: Message-ID: Gasto wrote: > I still don't see why such a module exists. There are 2.0 types of programmers: those who always use floating point, and those who know how to use them. From sjmachin at lexicon.net Sat May 10 21:49:28 2008 From: sjmachin at lexicon.net (John Machin) Date: Sun, 11 May 2008 01:49:28 GMT Subject: do you fail at FizzBuzz? simple prog test In-Reply-To: <39709320-66e1-40e9-a351-c769c9a94585@x41g2000hsb.googlegroups.com> References: <39709320-66e1-40e9-a351-c769c9a94585@x41g2000hsb.googlegroups.com> Message-ID: <482650a5$1@news.mel.dft.com.au> globalrev wrote: > http://reddit.com/r/programming/info/18td4/comments > > claims people take a lot of time to write a simple program like this: > > > "Write a program that prints the numbers from 1 to 100. But for > multiples of three print "Fizz" instead of the number and for the > multiples of five print "Buzz". For numbers which are multiples of > both three and five print "FizzBuzz". > > for i in range(1,101): > if i%3 == 0 and i%5 != 0: > print "Fizz" > elif i%5 == 0 and i%3 != 0: > print "Buzz" > elif i%5 == 0 and i%3 == 0: > print "FizzBuzz" > else: > print i > > > is there a better way than my solution? is mine ok? Try doing it using %3 and %5 only once each. From george.sakkis at gmail.com Fri May 16 12:30:49 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 16 May 2008 09:30:49 -0700 (PDT) Subject: morning in Python References: <409ea9f1-9774-4bf2-abac-2daf997bc97f@c65g2000hsa.googlegroups.com> Message-ID: <19286799-53b1-4ba9-bb16-e3f963da7dc6@m3g2000hsc.googlegroups.com> On May 16, 11:58?am, "inhahe" wrote: > I'm not an expert in this but what does it mean to emphasize state? ?It > seems the opposite of that would be a) functional programming, and b) > passing parameters instead of using global or relatively local variables. > And maybe c) coroutines (generators as implemented in Python), although > perhaps coroutines could be said to emphasize state inasmuch as they go out > of their way to capture, objectify and reuse it (Stackless' microthreads, > even moreso). ?And Python seems to be well-noted for implementing some > functional programming methodology, and as for passing parameters it's just > as object-oriented as the rest of them. > > But as I said, I'm not an expert, so let me know if I've gone astray.. > > > I have a proposition to ask you all: Python emphasizes state. ?Is it > > true? Please don't feed the bots. From nospam at nospam.invalid Wed May 28 23:19:24 2008 From: nospam at nospam.invalid (Rahul) Date: Thu, 29 May 2008 03:19:24 +0000 (UTC) Subject: adding tkinter support on an existing python installation Message-ID: 'import _tkinter' fails on my system. I wanted to enable tk support. I do have tk and tk-devel installed (but they weren't around when we installed python). What's the best way to get these modules into python? I hope I do not have to reinstall python itself? Or do I? -- Rahul From arnodel at googlemail.com Tue May 20 12:50:31 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 20 May 2008 17:50:31 +0100 Subject: Misuse of list comprehensions? References: <038e4418$0$27258$c3e8da3@news.astraweb.com> <6359d72c-f937-46cd-b1ce-b7450671b714@i76g2000hsf.googlegroups.com> <86e5f3b2-d1ae-414f-976e-062e7a293c9b@25g2000hsx.googlegroups.com> Message-ID: Paul McGuire writes: > On May 20, 10:17?am, Arnaud Delobelle wrote: [...] >> >> Isn't >> >> ? ? c not in seen and (seen.add(c) or True) >> >> the same as >> >> ? ? seen.add(c) or c not in seen >> >> ? >> >> > ? ? return ''.join(new) >> >> (notice I haven't closed the tag!) >> >> -- >> Arnaud- Hide quoted text - >> >> - Show quoted text - > > Unfortunately, no. "seen.add(c) or c not in seen" will never return > true, since c gets added to seen before testing if c in seen. > > -- Paul Ha you're right of course. But I haven't closed the tag yet, so: c not in seen and (seen.add(c) or True) is definitely the same as c not in seen and not seen.add(c) which is not (c in seen or seen.add(c)) :) -- Arnaud From ganeshborse at gmail.com Fri May 9 09:34:02 2008 From: ganeshborse at gmail.com (grbgooglefan) Date: Fri, 9 May 2008 06:34:02 -0700 (PDT) Subject: how to pass C++ object to another C++ function via Python function References: <1810b155-5598-4f17-a8e9-e4aa848db5de@i36g2000prf.googlegroups.com> <136a9a29-1193-4ebc-89de-7fa6b9c7dfd5@r9g2000prd.googlegroups.com> Message-ID: <91e5ada4-09bb-488a-a175-762a83daf658@f24g2000prh.googlegroups.com> Yes, that worked. I "protected" the variable which I did not want to get freed. I incremented reference for that variable & it started working. Thanks for all your guidance. On May 3, 5:23?am, "Gabriel Genellina" wrote: > Python will do nothing with the pointer inside a PyCObject - unless you ? > want to, and pass a cleanup function as the second argument to the ? > PyCObject constructor. > > -- > Gabriel Genellina- Hide quoted text - > > - Show quoted text - From ivan.illarionov at gmail.com Sun May 25 20:47:00 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Mon, 26 May 2008 00:47:00 +0000 (UTC) Subject: php vs python References: <5l%Yj.77$mz3.53@fe101.usenetserver.com> <37b112d8-a3ba-446d-9d2f-d907d93c637b@w8g2000prd.googlegroups.com> <-t-dnWQ4bZN2MaTVnZ2dnUVZ_qGdnZ2d@comcast.com> <68cb8bb1-4cc5-4a28-8915-46e7d4e316d9@d1g2000hsg.googlegroups.com> Message-ID: Jerry Stuckle wrote: > As I've said before - good programmers can write good code in any > language. Yes, they can. But it may be harder to do for them in one language and easier in another. Ivan From sjmachin at lexicon.net Sat May 24 19:28:55 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 24 May 2008 23:28:55 GMT Subject: Hexadecimal: how to convert 'ED6F3C01' to "\xED\x6F\x3C\x01" in python coding? In-Reply-To: References: Message-ID: <4838a4b4$1@news.mel.dft.com.au> zxo102 wrote: > Hi, > how to change the hexadecimal 'ED6F3C01' (or 'ED 6F 3C 01') to > "\xED\x6F\x3C\x01" in python coding? If by "in python coding" you mean "in Python source code", then just type it in with \x in front of each pair of hex digits, like you did above. However if you mean e.g. how to change a data string x into a data string y, something like this is what you want >>> import binascii >>> x = 'ED 6F 3C 01' >>> y = binascii.unhexlify(x.replace(' ', '')) >>> y '\xedo<\x01' ... which is correct ('o' == '\x6f' and '<' == '\x3c'); see below: >>> ' '.join(['%02x' % ord(c) for c in y]) 'ed 6f 3c 01' >>>> len(y) 4 Does (len(y) == 4) surprise you? > When I take 'ED6F3C01' as a string and insert '\x' into it, I just got > the error information : invalid \x escape. It's rather difficult to guess what you mean here ... insert how many '\x'? where?? what gave you the error information??? Consider showing us a copy/paste of exactly what you did and what was the response, like I did above. HTH, John From castironpi at gmail.com Wed May 7 20:05:25 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 7 May 2008 17:05:25 -0700 (PDT) Subject: howto print binary number References: <482214BE.4040702@islandtraining.com> Message-ID: <543e6dfe-7414-4a4a-8c9c-5b04fe815b02@f36g2000hsa.googlegroups.com> On May 7, 4:03?pm, Joel Bender wrote: > > Python 3.0 has such a formatting operation, but Python 2.x does not. ? > > However it's not hard to write. > > Indeed. ?Refraining from using named lambdas: > > ? ? ?>>> def bin(x): > ? ? ?... ? ? return ''.join(x & (1 << i) and '1' or '0' for i in > ? ? ?... ? ? ? ? range(7,-1,-1)) > ? ? ?... > ? ? ?>>> bin(12) > ? ? ?'00001100' > ? ? ?>>> bin(63) > ? ? ?'00111111' > > It would be nice to have str(x, 2) like int(x, 2), but there are bigger > fish in pond. +1 str( x, base ) +1 From brad at 16systems.com Thu May 22 21:15:14 2008 From: brad at 16systems.com (Brad) Date: Thu, 22 May 2008 21:15:14 -0400 Subject: MVC In-Reply-To: <8a269063-ae96-4707-afdc-5d2c9270e0ff@a9g2000prl.googlegroups.com> References: <8a269063-ae96-4707-afdc-5d2c9270e0ff@a9g2000prl.googlegroups.com> Message-ID: George Maggessy wrote: > Hi Gurus, > > I'm a Java developer and I'm trying to shift my mindset to start > programming python. So, my first exercise is to build a website. > However I'm always falling back into MVC pattern. I know it's a > standard, but the implementation language affects the use of design > patter. So, here goes my question. Is that OK if I follow this? ... Yes. Python does not impose design patterens onto developers. Pick your poison. It is somewhat OOP, but allows for other development paradigms as well... rather like C++ IMO although a bit more OOP focused. Best of luck, Brad From badmuthahubbard at gmail.com Sun May 4 06:04:20 2008 From: badmuthahubbard at gmail.com (Chuckk Hubbard) Date: Sun, 4 May 2008 13:04:20 +0300 Subject: Please help - Tkinter not doing anything In-Reply-To: <3ab5d06a0805040239m6cf12d39ufcde4fcc585f81e4@mail.gmail.com> References: <20562a9d-200c-40ae-a850-eb0f9a943d3f@l42g2000hsc.googlegroups.com> <237aa3894dff4c8976896df85f4d7d23@localhost> <3ab5d06a0805040239m6cf12d39ufcde4fcc585f81e4@mail.gmail.com> Message-ID: <8200bab70805040304y2a33e116l1454f75c80ea956b@mail.gmail.com> Try adding: from Tkinter import * at the beginning, and you don't need "var" in front of root=Tk(), just "root = Tk()" (<-without the quotes of course) What OS are you on? Are you running "python testapp.py" or similar to make it run? -Chuckk On Sun, May 4, 2008 at 12:39 PM, Protected wrote: > Good thinking. It was indented with spaces, so I replaced them with tabs. > Now I'm getting a SyntaxError: invalid syntax in root = Tk(). If I split the > code in two parts (with the second one beginning in that line) and run them > separately, I get no errors, but still nothing happens. > > class Application(Frame): > def say_hi(self): > print "hi there, everyone!" > > def createWidgets(self): > self.QUIT = Button(self) > self.QUIT["text"] = "QUIT" > self.QUIT["fg"] = "red" > self.QUIT["command"] = self.quit > > self.QUIT.pack({"side": "left"}) > > self.hi_there = Button(self) > self.hi_there["text"] = "Hello", > self.hi_there["command"] = self.say_hi > > self.hi_there.pack({"side": "left"}) > > def __init__(self, master=None): > Frame.__init__(self, master) > self.pack() > self.createWidgets() > > var root = Tk() > app = Application(master=root) > app.mainloop() > root.destroy() > > On Sun, May 4, 2008 at 12:33 PM, Q4 wrote: > > > On Sun, 4 May 2008 02:23:37 -0700 (PDT), Protected > > wrote: > > > > > > > > > Hello. I'm a complete newbie trying to learn Python. I decided to try > > > some Tkinter examples, including the one from the library reference, > > > but they don't seem to do anything! Shouldn't there be, like, a > > > dialog? > > > > > > I'm running Windows XP and using IDLE. You can assume my version of > > > Python is the latest. > > > -- > > > http://mail.python.org/mailman/listinfo/python-list > > > > If you just copy the code from the python doc the indentation might be > > broken. > > Send the code and I'll take a look at it. > > > > Do you get any errors? > > > > -- > > My website: > > http://www.riddergarn.dk/koder/ > > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.badmuthahubbard.com From hdante at gmail.com Mon May 19 12:11:40 2008 From: hdante at gmail.com (Henrique Dante de Almeida) Date: Mon, 19 May 2008 09:11:40 -0700 (PDT) Subject: Using Python for programming algorithms References: <48315082$0$24599$426a74cc@news.free.fr> Message-ID: <62884fc6-6c74-4477-91de-7b7689b5fa75@m44g2000hsc.googlegroups.com> On May 19, 7:03?am, Bruno Desthuilliers wrote: > Vicent Giner a ?crit : > > > Hello. > > > I am new to Python. It seems a very interesting language to me. Its > > simplicity is very attractive. > > > However, it is usually said that Python is not a compiled but > > interpreted programming language > > cf my answer to you and Henrique on this. > > > I am working on my PhD Thesis, which is about Operations Research, > > heuristic algorithms, etc., and I am considering the possibility of > > programming all my algorithms in Python. > > > The usual alternative is C, ?but I like Python more. > > Then use it. > > > The main drawbacks I see to using Python are these: > > > * As far as I understand, the fact that Python is not a compiled > > language makes it slower than C, when performing huge amounts of > > computations within an algorithm or program. > > In which way is this a problem here ? I thought your thesis was about > algorithm, not about implementation optimisation ? And if it's the > later, then even C might sometimes be too high level - you should drop > to assembly language. > > > * I don't know how likely it is to find libraries in Python related to > > my research field. > > I can't tell but you'd be surprised by the quantity of available Python > libs. > > > * I know Python is a "serious" and mature programming language, of > > course. But I do not know if it is seen as "just funny" in a research > > context. Is Python considered as a good programming language for > > implementing Operations Research algorithms, such as heuristics and > > other soft-computing algorithms? > > Don't know if this answers your question, but it seems that at least > some authors consider it a good choice:http://www.oreilly.com/catalog/9780596529321/ > > All code examples in this books are in Python - very badly written > Python, alas... > > > Maybe this is not the right forum, but maybe you can give me some > > hints or tips... > > Hem... Obviously, most people here will have a little biased, you know ?-) I agree with what most people here said, that the language doesn't really matter, etc., but that simply does not apply to the specific case of optimization research. The little I know about optimization, even trivial problems may be hairy problems. Na?ve implementations simply don't finish and the performance bottlenecks are not necessarily in the numeric computation algorithms (so numpy doesn't help much here). If the guy is doing research on that, it possible that he will work with thousands (or millions) of weird constraints. I'm pretty sure about that: when the algorithms take 4 hours to test a single execution, you value processor time. The situation would be simpler if there were good well-known toolkits for optimization in python (like numpy for matrix operations), but that's not the case. From jonathan.barbero at gmail.com Fri May 16 11:33:18 2008 From: jonathan.barbero at gmail.com (Jonathan Barbero) Date: Fri, 16 May 2008 12:33:18 -0300 Subject: IDE for Python Message-ID: Hi! I?m newbie with Python and to learn it better I want to use a good IDE to concentrate on Python power. There is any IDE like Eclipse for Java for Python? If not, what is the best Python?s IDE for you? Thanks, Jonathan. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bellman at lysator.liu.se Tue May 20 09:56:02 2008 From: bellman at lysator.liu.se (Thomas Bellman) Date: Tue, 20 May 2008 13:56:02 +0000 (UTC) Subject: Accumulating values in dictionary References: <07fbc8ec-924a-4e90-b212-ca4cc66f2b85@i76g2000hsf.googlegroups.com> Message-ID: Zack wrote: > There's nothing wrong (that I know of) by doing it as I have up there, > but is there a simpler, easier way? Looking forward to hearing about > how much of a n00b I am. Thanks in advance! You want the defaultdict type: import collections d = collections.defaultdict(lambda: 0) for person in People: fav_food = person.fav_food d[fav_food] += 1 New in Python 2.5, so if you require older Python versions, you can't use that. Note also that this can become slow if most keys are unique; the function given to defaultdict will be called the first time a key is mentioned, and if the keys are mostly unique, that will be the majority of the times, and calling a pure Python function is fairly slow in CPython. (It probably won't matter unless you have many thousands of unique keys, though.) -- Thomas Bellman, Lysator Computer Club, Link??ping University, Sweden "If you ignore performance problems long enough, they ! bellman @ somehow seem to go away." -- Barry A Warsaw ! lysator.liu.se From ian.g.kelly at gmail.com Fri May 9 18:58:08 2008 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Fri, 9 May 2008 16:58:08 -0600 Subject: Property in derived class In-Reply-To: <31861d09-a273-45de-bc71-c8591b7722e6@w7g2000hsa.googlegroups.com> References: <31861d09-a273-45de-bc71-c8591b7722e6@w7g2000hsa.googlegroups.com> Message-ID: <3fc761710805091558g3a494d2bt54a88364d235bd41@mail.gmail.com> On Fri, May 9, 2008 at 3:20 PM, Joseph Turian wrote: > Could someone demonstrate how to implement the proposed solutions that > allow the property to be declared in the abstract base class, and > refer to a get function which is only implemented in derived classes? One way is to have the property refer to a proxy that performs the late binding, which might look something like this: def _bar(self): return self.bar() prop = property(fget=_bar) Another way is to declare properties using something like the following indirectproperty class. I haven't thoroughly tested this, so I don't know whether it works exactly right. class indirectproperty(object): def __init__(self, sget=None, sset=None, sdel=None): self.sget = sget self.sset = sset self.sdel = sdel def __get__(self, instance, owner): if instance is not None: fget = getattr(instance, self.sget) else: fget = getattr(owner, self.sget) return fget() def __set__(self, instance, value): fset = getattr(instance, self.sset) fset(value) def __delete__(self, instance): fdel = getattr(instance, self.sdel) fdel() class Foo(object): def func(self): return "foo" callfunc = indirectproperty(sget="func") class Bar(Foo): def func(self): return "bar" From castironpi at gmail.com Thu May 15 19:53:24 2008 From: castironpi at gmail.com (castironpi) Date: Thu, 15 May 2008 16:53:24 -0700 (PDT) Subject: call tree tool? References: <3k1Xj.3430$7k7.2352@flpi150.ffdc.sbc.com> <13666537-1237-4165-8f61-780a752a2842@59g2000hsb.googlegroups.com> Message-ID: On May 15, 4:26?pm, "Dan Upton" wrote: > On Thu, May 15, 2008 at 5:19 PM, jay graves wrote: > > On May 15, 3:47 pm, m... at pixar.com wrote: > >> I'm cleaning up some old code, and want to see what orphan > >> functions might be sitting around. > > >> Is there a static call tree analyzer for python? > > > How about > >http://pycallgraph.slowchop.com/ > > > ... > > Jay Graves > > -- > >http://mail.python.org/mailman/listinfo/python-list > > Have you checked to see if PyChecker or pylint can help you? > Apparently they can find unused variables at least, I don't know > whether they do functions or not. I think of dynamic programming and dynamic code, but voice. Does that mean sing about it? From frankdmartinez at gmail.com Mon May 12 09:16:20 2008 From: frankdmartinez at gmail.com (frankdmartinez at gmail.com) Date: Mon, 12 May 2008 06:16:20 -0700 (PDT) Subject: Initializing a subclass with a super object? References: <17fce6b5-6506-4e78-8ba1-d8d1bb33c8a4@34g2000hsh.googlegroups.com> <7242ff91-dac4-4380-ba80-c18fa9494181@v26g2000prm.googlegroups.com> Message-ID: <1c99de2e-96db-4fd7-8a0e-7f366c32ebb7@56g2000hsm.googlegroups.com> On May 11, 3:19?am, Francesco Bochicchio wrote: > But there is not such a thing, in Python. What you have is that A > has the same attributes/methods of B plus its own. > What you could do is ?adding in class A a method like this: > > ? class A(B): > ? ? ?... > ? ? ?def set_b_attributes(self, instance_of_b): > ? ? ? ? ?for k, value in instance_of_b.__dict__: > ? ? ? ? ? ? ? ? setattr(self, k, value ) > > and the use it like this: > > ? ?a1.set_b_attributes(b1) Hi, Francesco. Thanx! That's actually exactly what I needed (though I didn't know it). From hdante at gmail.com Tue May 27 20:56:57 2008 From: hdante at gmail.com (Henrique Dante de Almeida) Date: Tue, 27 May 2008 17:56:57 -0700 (PDT) Subject: definition of a highlevel language? References: <2759eed3-956d-45c7-8dfb-9557f74133b3@56g2000hsm.googlegroups.com> Message-ID: <2c41298e-5041-4756-8fc4-c10d165a81b2@b1g2000hsg.googlegroups.com> On May 26, 3:34?pm, notnorweg... at yahoo.se wrote: > > what is the definition of a highlevel-language? > There's no formal definition of high level language. Thus, the following are true: 1) You can safely treat it as buzzword 2) You can't formally define a level hierarchy of languages 3) You can't formally classify any language as high, low, etc. level 4) Language theory literature ignore this term, so it's also irrelevant 5) You can use it to vaguely criticize a language that you don't like as being too high/low level :-) 6) You shouldn't try to label a language as high level or low level or something else without a context 7) You probably should ignore this term Now we have a problem. How can we define the "easiness" of a language ? I think a good way to do this is simply list the language architecture/paradigms and philosophy and let the listener decide by himself if it's an "easy" language or not. For a great example, see the description of python at: http://www.python.org/about/ From kamhung.soh at gmail.com Mon May 12 19:53:42 2008 From: kamhung.soh at gmail.com (Kam-Hung Soh) Date: Tue, 13 May 2008 09:53:42 +1000 Subject: python vs. grep References: <011f43ea-9bc8-499a-a3fe-dba24b47932e@c58g2000hsc.googlegroups.com> <7f44a73f-e88d-4edc-97e5-95cac7a26b14@2g2000hsn.googlegroups.com> <48284E1C.5050107@bigfoot.com> Message-ID: On Tue, 13 May 2008 00:03:08 +1000, Ricardo Ar?oz wrote: > Ville Vainio wrote: >> On May 8, 8:11 pm, Ricardo Ar?oz wrote: >> >>> All these examples assume your regular expression will not span >>> multiple >>> lines, but this can easily be the case. How would you process the file >>> with regular expressions that span multiple lines? >> re.findall/ finditer, as I said earlier. >> > > Hi, sorry took so long to answer. Too much work. > > findall/finditer do not address the issue, they merely find ALL the > matches in a STRING. But if you keep reading the files a line at a time > (as most examples given in this thread do) then you are STILL in trouble > when a regular expression spans multiple lines. > The easy/simple (too easy/simple?) way I see out of it is to read THE > WHOLE file into memory and don't worry. But what if the file is too > heavy? So I was wondering if there is any other way out of it. Does grep > read the whole file into memory? Does it ONLY process a line at a time? > > -- > http://mail.python.org/mailman/listinfo/python-list > Standard grep can only match a line at a time. Are you thinking about "sed", which has a sliding window? See http://www.gnu.org/software/sed/manual/sed.html, Section 4.13 -- Kam-Hung Soh Software Salariman From vadim.pestovnikov at gmail.com Thu May 1 11:46:15 2008 From: vadim.pestovnikov at gmail.com (idev) Date: Thu, 1 May 2008 08:46:15 -0700 (PDT) Subject: Please help me with linking libraries on Solaris 10 sparc References: <89620267-578c-4d06-9afd-0684b5d646f5@c58g2000hsc.googlegroups.com> <4819D40A.1000205@v.loewis.de> <675e5d14-49c0-4ee3-8ab9-88f8926b68a3@x41g2000hsb.googlegroups.com> <4819E4AF.4060103@v.loewis.de> Message-ID: <55b033af-4c84-4e29-9dcd-598e7cde7057@m44g2000hsc.googlegroups.com> On May 1, 11:41 am, "Martin v. L?wis" wrote: > > Martin, could you please tell me how to do this, I am pretty new in > > Solaris. > > It's fairly complicated, so I'm not sure I can give you the full > tutorial in a Usenet message. > > In essence, you need to spot the linker line in the build process, > (e.g. by the -o option to the compiler), and add -lm to it. > > If you cannot do this on your own, I recommend you hire somebody > who can. > > Regards, > Martin Thanks Martin, For sure I am not maintainer :). Thanks for the help and explanations. From duncan.booth at invalid.invalid Fri May 2 08:26:50 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 2 May 2008 12:26:50 GMT Subject: no cleanup on TERM signal References: <481AE22E.3040906@shopzeus.com> Message-ID: Christian Heimes wrote: >> res = create_resource() >> try: >> use_resource() >> finally: >> res.close() # Must free resource, but the object can still be >> alive... > > You can replace the try/finally code with a "with resource: > do_something()" block if the object supporst the context manager > protocol. > or replace it with: with contextlib.closing(create_resource()) as res: do_something() if the object does not support the context manager protocol. From larry.bates at websafe.com` Fri May 9 14:37:44 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Fri, 09 May 2008 13:37:44 -0500 Subject: Web Framework suggestions for a RIA type application for managing lab specimens In-Reply-To: References: Message-ID: <4rudnZWRbKoYBLnVnZ2dnUVZ_sCtnZ2d@comcast.com> rynt wrote: > Hello all. > > I'm Looking for suggestions for which Python web framework(e.g. > Django, Turbogears,etc.) would work best to develop a cross platform > browser based system to manage lab specimens. > > Requirements are: > a. highly secure > b. run on internet or intranet > e. RDBMS read/write intensive > d. be able to work on-line or off-line (with automatic updates to db > when coming back on-line) > e. be able to print reports and labels using a variety of > printers(laser, deskjet, label printers) > f. have a rich set of desktop-like components > > Perhaps a web based app isn't the way to go. Arguments for and > against gratefully accepted. > > Pros and Cons for any frameworks gratefully accepted. > > Perhaps a framework isn't really what's needed here, but a combination > of different web components and technologies? > > Anyway, I'm grateful for any ideas you may be able to give me. > > Thanks > Ruben > > a. highly secure Can be accomplished with XMLRPC over HTTPS if you want web application or you can use something simple like RDP to hosted application. > b. run on internet or intranet Most applications that have a database backend can do this if written properly. > e. RDBMS read/write intensive This might push me to something like RDP (or xWindows), but it depends on where the data is coming from that causes the 'intense' writing and the nature of the 'intense' reading'. You certainly don't want to be moving the data over the Internet any more than is necessary. > d. be able to work on-line or off-line (with automatic updates to db > when coming back on-line) This would require quite a lot of work and using some sort of DB synchronization. This item is the holy grail that many try to achive, but IMHO few actually fully achieve it. > e. be able to print reports and labels using a variety of > printers(laser, deskjet, label printers) Web applications are REALLY bad a printing. They have no real ability to interact with a printer like a client application does. If I wanted to drive label printers, I would use a client hosted application (but might get the data from a remote server via XMLRPC, WEBDAV, etc). > f. have a rich set of desktop-like components You can use components like Yahoo User Interface (YUI) or Google Web Toolkit. (GWT) but they are nothing like the rich set of tools you get from wxWindows, QT, etc. on a client application and development takes a LOT longer to get correct. The disconnected nature of the Web can make applications that are trivial when written as client-server, quite difficult. From what you have given me, I would lean towards a hosted application with RDP connection. A lot more information would be required to make the final choice of development architecture, languages, database, UI toolkits, etc. Hope this helps. -Larry Bates From python at rcn.com Mon May 5 04:16:42 2008 From: python at rcn.com (Raymond Hettinger) Date: Mon, 5 May 2008 01:16:42 -0700 (PDT) Subject: Feature suggestion: sum() ought to use a compensated summation algorithm References: <481CB283.107@gmail.com> <9d890b77-688e-4207-8eb3-8233d287ecb6@8g2000hse.googlegroups.com> Message-ID: > > > However I find the seccond argument hack ugly. Does the sum way have any > > > performance advantages over the reduce way? > > > Yes, sum() is faster: ... > Not really; you measure the import and the attribute access time in > the second case. sum() is 2x faster for adding numbers only: Try it with Py2.6 or Py3.0. The sum() function has been optimized and should be at least 6x faster for summing ints and floats. It should even beat psyco optimized sums! Raymond From paddy3118 at googlemail.com Fri May 9 14:37:21 2008 From: paddy3118 at googlemail.com (Paddy) Date: Fri, 9 May 2008 11:37:21 -0700 (PDT) Subject: Wanted: Citation supporting Duck Typing References: <2385391e-f550-43be-b52e-cc23ba4f5381@d45g2000hsc.googlegroups.com> Message-ID: <014a1de8-3300-4920-b3dd-3bf452b49fc5@t54g2000hsg.googlegroups.com> On May 9, 6:30 pm, Paddy wrote: > Hi, > The wikipedia article on Duck Typing has this criticism section that > needs a citation: > (Fron:http://en.wikipedia.org/wiki/Duck_typing#Criticism) > > An often cited criticism is this: > One issue with duck typing is that it forces the programmer to > have a much wider understanding of the code he or she is working with > at any given time. In a strongly and statically typed language that > uses type hierarchies and parameter type checking, it's much harder to > supply an unexpected object type to a class. For instance, in python, > you could easily create a class called Wine, which expects a class > implementing the "press" method as an ingredient. However, a class > called Trousers might also implement the press() method. With Duck > Typing, in order to prevent strange, hard to detect errors, the coder > needs to be aware of each potential use of the method "press", even > when it's conceptually unrelated to what he or she is working on. With > type checking and hierarchical type declarations, all wine ingredients > would be subclasses of WineIngredient or something like that, negating > the problem. > > In essence, the problem is that, "if it walks like a duck and > quacks like a duck", it could be a dragon doing a duck impersonation. > You may not always want to let dragons into a pond, even if they can > impersonate a duck. > > In practice, the issue is equivalent to not mixing dissimilar objects > for duck-typing and is handled almost transparently as part of the > knowledge of the codebase required to maintain it.[citation needed] > > I've only found this so far as a citation: > http://jessenoller.com/2007/05/30/typeducking-on-duck-vs-static-typing/ > Whilst it is good, do you know any other work that refutes the > criticism? > > (I, and many others don't see the problem, but who has written about > it). > > Thanks, Paddy. A bit more searching gives me: http://hans.fugal.net/blog/articles/2006/07/08/duck-typing-defended And: http://www.mindview.net/WebLog/log-0025 I don't have a collection of Dynamic language books though. - Paddy. From gagsl-py2 at yahoo.com.ar Thu May 1 06:52:02 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 01 May 2008 07:52:02 -0300 Subject: A bug in difflib module? (find_longest_match) References: <8054bd25-5a14-446d-a775-6efca1d5a2a0@m3g2000hsc.googlegroups.com> <7292bae2-993e-41cc-8f0e-8d1339ecebdf@25g2000hsx.googlegroups.com> Message-ID: En Thu, 01 May 2008 06:21:22 -0300, n00m escribi?: >> > import difflib >> > s = difflib.SequenceMatcher(None, s1, s2) >> > print s.find_longest_match(0, len(s1), 0, len(s2)) >> > (0, 0, 0) >> > >> > I think it's line #314 in difflib "who's to blame" -- >> >> Me too. Could you think of some alternative? Simply disabling that >> "popularity check" would slow down the algorithm, according to the >> comments. > > No idea :) The "ignore popular elements" is only an optmization, and it should not be applied in your case because it forces the algorithm to yield an invalid result. I can think of two alternatives: - tune up the conditions when the optimization is used, or - make it user configurable SequenceMatcher is a public class, and it is also internally used by Differ and others to compare both sequences of lines *and* pairs of similar lines (considered as sequences of characters). In this last usage the "ignore popular elements" has no much sense, as shown in your example feeding directly two dissimilar strings. In principle one should disable the "populardict" stuff when dealing with strings. Below is a simple attempt to detect that case: (around line 311 in difflib.py) b_is_string = isinstance(b, basestring) # add this line for i, elt in enumerate(b): if elt in b2j: indices = b2j[elt] if not b_is_string and n >= 200 and len(indices) * 100 > n: # change this line populardict[elt] = 1 del indices[:] else: indices.append(i) else: b2j[elt] = [i] -- Gabriel Genellina From paul at boddie.org.uk Mon May 5 17:36:46 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Mon, 5 May 2008 14:36:46 -0700 (PDT) Subject: ]ANN[ Vellum 0.16: Lots Of Documentation and Watching References: Message-ID: <3a8e0a8f-3bd1-4650-9104-5c273f14b097@w7g2000hsa.googlegroups.com> On 5 Mai, 20:26, vivai... at gmail.com (Ville M. Vainio) wrote: > > Basically, avoiding GPL maximizes the brainshare that a small-ish tool > is going to attract, and many (including myself, FWIW) view GPL as a > big turn-off when I consider spending some time to familiarize myself > with a tool, or recommending it to someone else. I'd like to cast a vote for the opposing camp: I'm probably more likely to look at GPL-licensed code, although I recognise that I have the benefit of not having anyone superior to me wanting to release proprietary software. Applications and tools are ideal candidates for GPL-licensing, although I also recognise that someone might want to adapt the code for a library, and that they might not feel comfortable with the copyleft aspects of the resulting licence on that library. Anyway, I'm just confirming that I'm clearly not one of the "many" described above. A lot of my own work is licensed under the GPL or LGPL, and while I'd be the first to admit that not much of what I've written is wildly popular, I think the reasons for not using it purely because of the licences are typically overstated. Paul From kyosohma at gmail.com Fri May 23 16:54:43 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 23 May 2008 13:54:43 -0700 (PDT) Subject: Python database 'frontends', what's available? References: <4837141b$0$658$bed64819@news.gradwell.net> Message-ID: <08424ab8-e5c4-4aca-a492-1410e56f38a2@y38g2000hsy.googlegroups.com> On May 23, 1:59?pm, tinn... at isbd.co.uk wrote: > I'm desperately trying to move a Microsoft Access database application > (a simple accounts system I wrote myself) to Linux. ?Python is one of > my preferred programming laguages so I wonder if there are any good > Python 'frameworks' for writing database applications, in particular I > need good reporting and forms writing facilities. ?The basic database > and logic/arithmetic seem fairly simple to me. > > -- > Chris Green You might take a look at Dabo. It's made for databases and is pretty cool. http://dabodev.com/ Not sure what else is out there. Mike From florencio.cano at gmail.com Sun May 11 04:44:42 2008 From: florencio.cano at gmail.com (Florencio Cano) Date: Sun, 11 May 2008 10:44:42 +0200 Subject: Some error messages in Python are ugly In-Reply-To: <1af83e8f-8083-4b5d-95e1-534193d059e5@24g2000hsh.googlegroups.com> References: <1af83e8f-8083-4b5d-95e1-534193d059e5@24g2000hsh.googlegroups.com> Message-ID: This is not a Python error, this is a bash message that appears when you press ctrl+z and put the application in the background. Execute fg to return the app to the foreground. 2008/5/11 : > This really looks ugly for an error message: > > [1]+ Stopped python > > > Please explain to me the role of the '+' sign. And why is there such a > gap between 'Stopped' and 'python'? From greg at cosc.canterbury.ac.nz Tue May 20 23:01:55 2008 From: greg at cosc.canterbury.ac.nz (greg) Date: Wed, 21 May 2008 15:01:55 +1200 Subject: Code/test ratio wrt static vs dynamic typing [was: Re: Python Success stories] In-Reply-To: References: <1ad1c0c4-c1b5-46aa-b26c-0426c86522b4@a70g2000hsh.googlegroups.com> <57d73312-37b1-4c53-9669-803e84a6901f@p25g2000hsf.googlegroups.com> <263d5498-821f-4705-9e1d-cc9e97a98e07@34g2000hsf.googlegroups.com> Message-ID: <69hi0iF32kli9U1@mid.individual.net> Someone wrote: >>>I'm just curious whether this >>>argument against dynamic typing - that you end up doing the job of a >>>static compiler in test code - holds in practice. I suspect that, although some of the things caught by the tests would be caught by static typing, the very *same* tests are also catching a lot of things that wouldn't be caught by static typing. Also, I don't think it's valid to equate the size of the tests with the amount of effort it took to develop them. For instance, the test suite for Pyrex is currently larger than the Pyrex compiler, but I've still spent far more time and effort developing the compiler than writing the tests. -- Greg From subhabrata.iisc at hotmail.com Wed May 28 09:59:28 2008 From: subhabrata.iisc at hotmail.com (subhabrata.iisc at hotmail.com) Date: Wed, 28 May 2008 06:59:28 -0700 (PDT) Subject: Error handling in Python Message-ID: <5d6a51a9-3d35-4c99-b7ef-fa79f950ece8@l17g2000pri.googlegroups.com> Dear Members of the group, If I open a url by urlopen in the urllib, the file is either opening a file or if no url is there it would give error. The error is generated can be handled by IOError handling schemes. But if there are thousands or millions of URLs and I do not know who will open and who won't open. How can I handle this kind of situation? If any one can help solving this problem. Regards, Subhabrata. From Tymoteusz.Jankowski at gmail.com Fri May 9 13:05:34 2008 From: Tymoteusz.Jankowski at gmail.com (XLiIV) Date: Fri, 9 May 2008 10:05:34 -0700 (PDT) Subject: the lvalue curse? let's play with this crazy idea ;) References: <68618c8b-f17e-496a-9092-5e2cd16b365b@p25g2000hsf.googlegroups.com> <68il63F2su97jU5@mid.uni-berlin.de> Message-ID: On May 9, 11:52?am, Marc 'BlackJack' Rintsch wrote: > Maybe it's also harder to read than this:: > > ? print '-'.join(map(str, time.localtime()[:3])) I like this concept, it's so, .. ziped :) > Of course, if you don't mind the extra padding zeroes in day and month:: > > ? print time.strftime('%Y-%m-%d') I'll be humble, it covers my need the most :) If you have a lack of knowladge you work harder... One instruction (besides 'print')... . Do you believe it? :) > You are a little bit inconsistent with the arguments. ?`g` is explicitly > mentioned in ``list(g)``. ?But why the intermediate names at all? > That's right, because it was just a scratch of an idea.. The point of the idea was this... I read from left to right, and because of that it's easier to me follow this way of writing (you only follow by one direction and the value is handing over, from left to rigght ...): value -> do_something -> result -> action_on_the_result -> ... than this multiline lvalues assignes variable = value # I take a look at the left then the right result = do_something(variable) # Here I check also left and right side, and perhaps I (a short memory) may check the line over action_on_the_result(result) ... However, I've just found out, that even the more difficult method to me isn't so scary if I read it like this ... 6 7 4 5 2 3 1 However the 2nd: because there is: print '-'.join(map(str, time.localtime()[:3])) so i'm not serious convincing anyone :) > Maybe you should look into languages like SmallTalk or Io where everything > is done with method calls. ?Your example in Io:: I took a brief look at them, and Python is still Nr OnE :) From steven.klass at gmail.com Wed May 14 19:07:30 2008 From: steven.klass at gmail.com (rh0dium) Date: Wed, 14 May 2008 16:07:30 -0700 (PDT) Subject: More fun with PyParsing - almost did it on my own.. Message-ID: Hi all, I almost did my first pyparsing without help but here we go again. Let's start with my code. The sample data is listed below. # This will gather the following ( "NamedPin" "PinDirection" "OptionalSignal" ) guts = Group( LPAR.suppress() + quotedString.setParseAction(removeQuotes).setResultsName("name") + quotedString.setParseAction(removeQuotes).setResultsName("direction") + Optional(quotedString.setParseAction(removeQuotes).setResultsName("signal")) + RPAR.suppress()) # This will simply wrap the Cell Info around it cell = Group( Literal("dbSetCellPortTypes").suppress() + quotedString.setParseAction(removeQuotes).setResultsName("library") + quotedString.setParseAction(removeQuotes).setResultsName("name") + Literal("'").suppress() + LPAR.suppress() + OneOrMore(guts).setResultsName("pins") + RPAR.suppress() ) + Literal("#f").suppress() | Literal("#t").suppress() # This grabs many cells cells = OneOrMore(cell) OK and it sorta works if I do the following: x = cells.parseString(data) print x[0].asDict() reveals {'pins': ([(['A', 'Input'], {'direction': [('Input', 1)], 'name': [('A', 0)]}), (['B', 'Input'], {'direction': [('Input', 1)], 'name': [('B', 0)]}), (['Y', 'Output'], {'direction': [('Output', 1)], 'name': [('Y', 0)]}), (['VDD', 'Inout', 'Power'], {'direction': [('Inout', 1)], 'name': [('VDD', 0)], 'signal': [('Power', 2)]}), (['VSS', 'Inout', 'Ground'], {'direction': [('Inout', 1)], 'name': [('VSS', 0)], 'signal': [('Ground', 2)]})], {}), 'name': 'AND2X1', 'library': 'stdcell130'} As you can see the Pins is all jacked up and I want is not that. I want the following { 'name': 'AND2X1', 'library':'stdcell130' 'pins': [ { 'name': 'VSS', 'direction':'Inout', 'signal':'Ground'}, { 'name': 'VDD', 'direction':'Inout', 'signal':'Power'}, { 'name': 'A', 'direction':'Input' }, { 'name': 'B', 'direction':'Input' }, { 'name': 'Y', 'direction':'Output' } ] } What did I do wrong in my code.. Thanks again! ] I would expect my results to look like this: But to get any info I must do this print x[0].asDict() which is not really what want. What I expect is this: [ data = """dbSetCellPortTypes "stdcell130" "AND2X1" '( ("A" "Input" ) ("B" "Input" ) ("Y" "Output" ) ("VDD" "Inout" "Power" ) ("VSS" "Inout" "Ground" ) ) #f dbSetCellPortTypes "stdcell130" "AND2X2" '( ("A" "Input" ) ("B" "Input" ) ("Y" "Output" ) ("VDD" "Inout" "Power" ) ("VSS" "Inout" "Ground" ) ) #f """ From arnodel at googlemail.com Tue May 20 10:43:41 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Tue, 20 May 2008 15:43:41 +0100 Subject: Using Python for programming algorithms References: <482F71B0.3050808@ncf.ca> Message-ID: brad writes: >> Vicent Giner wrote: > >> The usual answer is that development time is more important than >> running time. > > This depends. Run time is not important until you are asked to scale > to millions or billions of users or computations or large data > sets. I've seen this first hand. Getting results back the same day or > sooner may be important. In cases such as this, I use C or > C++... nothing else will do. Nothing else is as fast. Although I > always keep a py version around for testing and for smaller > tasks. Don't get me wrong, I love Python, but there are times when > nothing, but pure, hard speed will do. Sure. Be careful not to overdose on it though. -- Arnaud From notnorwegian at yahoo.se Mon May 26 22:46:43 2008 From: notnorwegian at yahoo.se (notnorwegian at yahoo.se) Date: Mon, 26 May 2008 19:46:43 -0700 (PDT) Subject: sort list doesnt work, key=str still doesnt work Message-ID: >>> x [',', ',', 'CHAPTER', 'Emma', 'I', 'I', 'VOLUME', 'Woodhouse', 'clever', 'handsome'] >>> x=sorted([',', ',', 'CHAPTER', 'Emma', 'I', 'I', 'VOLUME', 'Woodhouse', 'clever', 'handsome'], key=str) >>> x [',', ',', 'CHAPTER', 'Emma', 'I', 'I', 'VOLUME', 'Woodhouse', 'clever', 'handsome'] >>> what do i need to do? From larry.bates at websafe.com` Tue May 6 16:20:57 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Tue, 06 May 2008 15:20:57 -0500 Subject: Am I missing something with Python not having interfaces? In-Reply-To: <45de2f7e-484a-4871-bbaa-bf7eed5dfa40@x35g2000hsb.googlegroups.com> References: <45de2f7e-484a-4871-bbaa-bf7eed5dfa40@x35g2000hsb.googlegroups.com> Message-ID: jmDesktop wrote: > Studying OOP and noticed that Python does not have Interfaces. Is > that correct? Is my schooling for nought on these OOP concepts if I > use Python. Am I losing something if I don't use the "typical" oop > constructs found in other languages (Java, C# come to mind.) I'm > afraid that if I never use them I'll lose them and when I need them > for something beside Python, I'll be lost. Thank you. Zope has an implementation of interfaces that Zope 3 and Twisted both use if you want to take a look. http://www.zope.org/Products/ZopeInterface Frankly, I've never missed them. -Larry From castironpi at gmail.com Wed May 14 14:09:36 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 14 May 2008 11:09:36 -0700 (PDT) Subject: I'm stuck in Python! References: <0563506d-bd36-404d-8961-4c4c5d1cc029@t54g2000hsg.googlegroups.com> <6a0167c3-bd87-4ddc-a161-249b7bf933c2@s50g2000hsb.googlegroups.com> <1f6bc3b5-da44-42a2-82f1-4aec5a6d31b1@c58g2000hsc.googlegroups.com> <499bc2af-6c7d-4ff4-abba-db06f4122cf9@x41g2000hsb.googlegroups.com> <0a3717f4-5992-484d-a39c-04f0d2cfec3a@m45g2000hsb.googlegroups.com> <4559b920-f42f-4fdb-afc7-fc6bfc1b9ff1@r66g2000hsg.googlegroups.com> Message-ID: <8c23edae-a957-42c8-82a0-82853467aaa4@s50g2000hsb.googlegroups.com> On May 14, 1:07?pm, castiro... at gmail.com wrote: > On May 14, 1:06?pm, castiro... at gmail.com wrote: > > > > > > > On May 14, 1:02?pm, castiro... at gmail.com wrote: > > > > On May 14, 12:51?pm, castiro... at gmail.com wrote: > > > > > On May 14, 5:25?am, castiro... at gmail.com wrote: > > > > > > On May 14, 4:32?am, castiro... at gmail.com wrote: > > > > > > > On May 13, 9:55?pm, alex23 wrote: > > > > > > > > On May 14, 5:41 am, "inhahe" wrote: > > > > > > > > > "George Sakkis" wrote in message > > > > > > > > > You must be new here. It is an AS (Artificial Stupidity) trolling bot, > > > > > > > > > you can safely ignore its posts. > > > > > > > > > How does it generate text? > > > > > > > > My guess is by inhaling a lot of intoxicants. > > > > > > > However you know what would be helpful? ?If I could go to the right > > > > > > place to start the ring. > > > > > > I have a slightly sinister role on stage. ?Does anyone want to play? > > > > > I'd stay on mutability for the world domination factor. ?Fluent > > > > currency is buoyant currency; turn on a local clock, and someone gets > > > > some cubic verticals. > > > > > Now if sense-reference is trading on the BDFL, I'm still holding Tron > > > > can pretty well win work.- Hide quoted text - > > > > > - Show quoted text - > > > > I have a self-referential on Pygame: it's a Hand Tool object. > > > Currently, it decays over time. ?You said 'flip' in the newsgroup, and > > > 'check', 'cross', and 'mate'. ?Now who jumps who?- Hide quoted text - > > > > - Show quoted text - > > > If Python can plot in to chess, and Tron rings live, then why not > > group it knew?- Hide quoted text - > > > - Show quoted text - > > That would be know. ?Plot and split in too.- Hide quoted text - > > - Show quoted text - Now can I catch function-type objects from a throw? I'm crossing all of those. From mail at timgolden.me.uk Thu May 29 05:55:08 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 29 May 2008 10:55:08 +0100 Subject: Finding file details... In-Reply-To: References: Message-ID: <483E7D7C.5080605@timgolden.me.uk> Kalibr wrote: > I've been trying to figure out how to find the details of files > (specifically music for now) for a little sorting script I'm making, > My aim is to get details on the artist, album, and genre for mp3 and > wma files (possibly more in the future). My closest match was when I > stumbled accross PyMedia, but it only supports up to 2.4 (I have 2.5). > Now I see a bit mentioned on GetFileVersionInfo, but that doesn't seem > to help (and most of it went over my head). Is there any module I can > use to find this sort of data? I'm trying to not make it specialised > in music, because I may want to extend this to picture, movie, text > etc. files in the future. Any ideas how I could go about this? You don't say, but I assume you're on Windows since you mention GetFileVersionInfo (which doesn't have anything to do with media files, by the way) and WMA. There may be packages out there to do all this already but if not you'll need to pull in a few disparate modules and mix'n'match. While ID3 readers (which determine the metadata for MP3) are reasonably common few of them come ready-compiled for Windows. I've used Ned Batchelder's id3reader [1] successfully for simple tasks so you might try that. On the WMA side, you can automate Windows Media Player to get metadata. (And it might work for .mp3; I've not tried). import win32com.client player = win32com.client.gencache.EnsureDispatch ("WMPlayer.OCX") wmedia = player.mediaCollection.add (r"c:\temp\bells.mp3") try: artist = wmedia.getItemInfo ("Artist") finally: player.mediaCollection.remove (wmedia, False) print "bells.mp3 has artist", artist You're going to have to dig around for docs on this one. And it's not pretty. Try starting from: http://msdn.microsoft.com/en-us/library/bb249009(VS.85).aspx TJG [1] http://nedbatchelder.com/code/modules/id3reader.html From google at mrabarnett.plus.com Thu May 22 13:05:42 2008 From: google at mrabarnett.plus.com (MRAB) Date: Thu, 22 May 2008 10:05:42 -0700 (PDT) Subject: Loading contents behind the scenes References: <32c00225-f231-4f85-9b01-51f0fd0f9392@k13g2000hse.googlegroups.com> Message-ID: On May 22, 3:20 pm, s0s... at gmail.com wrote: > On May 22, 8:51 am, "A.T.Hofkamp" wrote: > > > > > On 2008-05-22, s0s... at gmail.com wrote: > > > > Hi, I wanted to know how cautious it is to do something like: > > > > f = file("filename", "rb") > > > f.read() > > > > for a possibly huge file. When calling f.read(), and not doing > > > anything with the return value, what is Python doing internally? Is it > > > loading the content of the file into memory (regardless of whether it > > > is discarding it immediately)? > > > I am not a Python interpreter developer, but as user, yes I'd expect that to > > happen. The method doesn't know you are not doing anything with its return > > value. > > > > In my case, what I'm doing is sending the return value through a > > > socket: > > > > sock.send(f.read()) > > > > Is that gonna make a difference (memory-wise)? I guess I'm just > > > concerned with whether I can do a file.read() for any file in the > > > system in an efficient and memory-kind way, and with low overhead in > > > general. (For one thing, I'm not loading the contents into a > > > variable.) > > > Doesn't matter. You allocate a string in which the contents is loaded (the > > return value of 'f.read()', and you hand over (a reference to) that string to > > the 'send()' method. > > > Note that memory is allocated by data *values*, not by *variables* in Python > > (they are merely references to values). > > > > Not that I'm saying that loading a huge file into memory will horribly > > > crash the system, but it's good to try to program in the safest way > > > possibly. For example, if you try something like this in the > > > Depends on your system, and your biggest file. > > > At a 32 bit platform, anything bigger than about 4GB (usually already at around > > 3GB) will crash the program for the simple reason that you are running out of > > address space to store bytes in. > > > To fix, read and write blocks by specifying a block-size in the 'read()' call. > > I see... Thanks for the reply. > > So what would be a good approach to solve that problem? The best I can > think of is something like: > > MAX_BUF_SIZE = 100000000 # about 100 MBs > > f = file("filename", "rb") > f.seek(0, 2) # relative to EOF > length = f.tell() > bPos = 0 > > while bPos < length: > f.seek(bPos) > bPos += sock.send(f.read(MAX_BUF_SIZE)) I would go with: f = file("filename", "rb") while True: data = f.read(MAX_BUF_SIZE) if not data: break sock.sendall(data) From robert.kern at gmail.com Tue May 20 18:59:30 2008 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 20 May 2008 17:59:30 -0500 Subject: Struct usage and varying sizes of h, l, etc In-Reply-To: <48335269.2000809@admailinc.com> References: <48335269.2000809@admailinc.com> Message-ID: Ethan Furman wrote: > Greetings, > > I'm looking at the struct module for binary packing of ints and floats. > The documentation refers to C datatypes. It's been many years since I > looked at C, but I seem to remember that the data type sizes were not > fixed -- for example, an int might be two byes on one machine, and four > bytes on the next. Can any C programmers verify this? If it is true, > does that mean that struct.pack('h', 8001) might give me different > results depending on the machine it's running on? Right. I believe (but could be wrong) that "char" is defined to be one byte, but that "short", "int", "long", and "long long" are defined as "at least as big as the previous type". In practice, though, on nearly every machine that Python runs on, "char" is one byte, "short" is two bytes, and "int" is four bytes. "longs" and "long longs" tend to vary substantially, though; never assume sizes for them. Single-precision floats are always four bytes and double-precision floats are always eight bytes. "long doubles" vary; they could be twelve bytes or sixteen. If you want to deal with fixed sizes, use struct.calcsize() to test the sizes of each of the integer types, assign them to width-specific aliases, and always use these aliases. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun May 4 06:17:24 2008 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sun, 04 May 2008 12:17:24 +0200 Subject: is +=1 thread safe References: <4819DA2D.3030508@ggmail.com> <481BD50F.5080608@ggmail.com> Message-ID: <685gpkF2r5j39U1@mid.individual.net> Gary Herron wrote: > No NO NO! The only way to increment a variable in memory is > through a three step process: > > Load a register from a memory location > Increment the register > Store the value back into memory. I suggest you read "Intel 64 and IA-32 Architectures Software Developer's Manual" (2A, Instruction Set Reference A-M). INC and DEC can have register *or* memory location as operand, and can be executed atomically even in multiprocessor environments (LOCK prefix). > Ages ago, there were architectures that would do an increment on a > memory location in an atomic way, but with the current (RISC) > architectures these are three separate operations. That may be true for RISC architectures. Unfortunately, all 8086 based CPUs are CISC. Regards, Bj?rn -- BOFH excuse #277: Your Flux Capacitor has gone bad. From jhenRemoveThis at talk21.com Sat May 31 13:50:09 2008 From: jhenRemoveThis at talk21.com (John Henderson) Date: Sun, 01 Jun 2008 03:50:09 +1000 Subject: SMS sending and receiving from website? References: <6abq0uF36n019U1@mid.individual.net> <5d949166-5112-4a7a-91c3-77ccdd7ca695@j22g2000hsf.googlegroups.com> Message-ID: <6adhelF371mogU1@mid.individual.net> globalrev wrote: > i want to build a service where you can send an SMS with your > cellphone to my website and then the site will collect the > data you asked for and SMS it back. > > so what components would i need for that? Arguably the simplest route is to use a phone with a serial connection to a computer, whether that connection be RS232, USB, IrDA or Bluetooth. For outgoing messages in large volume, SMS lodgement directly to an SMSC (message centre) via SMPP over an internet connection is likely to be a cheaper option in the long term. But that'll depend on what's on offer in your part of the world. There's probably some means of receiving messages without using your own hardware, but I'm not aware of any details. If using your own hardware, I'd suggest a cellular modem rather than a handset. These are permanently powered by a low voltage DC supply, rather than a battery you need to keep charged without destroying it with constant overcharge. And a modem is more likely to support text-mode command interactions with your computer rather than raw PDU-mode interactions. PDU-mode requires your software to translate to/from the raw transmitted SMS data, but gives you much greater control. The rest is software, and your cost will depend on how you get or develop that. You might be able to get a SIM (assuming a GSM or UMTS cellular device) with very cheap SMS rates. A pre-paid service will limit your losses if your software ever gets over-enthusiastic about sending messages. John From badmuthahubbard at gmail.com Mon May 12 19:41:39 2008 From: badmuthahubbard at gmail.com (Chuckk Hubbard) Date: Tue, 13 May 2008 02:41:39 +0300 Subject: Learning Python for no reason In-Reply-To: <0383f3b8$0$27282$c3e8da3@news.astraweb.com> References: <0383f3b8$0$27282$c3e8da3@news.astraweb.com> Message-ID: <8200bab70805121641n7ec4d23ds2efadfa6c65a307d@mail.gmail.com> I'm another one pretty early in his programming education, but here's my take. Python was specifically recommended to me by a few people for a specific program I wanted to write (userspace, GUI, music). While I gradually learn more about it, I start to spend a lot of time on certain aspects I don't really need for this task. I think curiosity is one of the vital qualities for a programmer, and through mine, over a few years, I've built up more and more understanding of what's going on in my box, more than I set out to have, but I can't see how any of this can be called wasted time if it rounds out my general understanding. On the other hand, as Python is about the second "serious" language I've tried to learn (the others being web- or music- oriented, and I didn't approach them as programming), I don't have much to compare it to. I was under the impression before reading your message that Python was very popular and useful. This list is far more active than all the others to which I'm subscribed put together! So, either it doesn't seem like a silly endeavor to learn it for its own sake, or they're using it for something. If it is a silly endeavor, I'm going to have to ask you to stop this thread, it's too silly. -Chuckk On Mon, May 12, 2008 at 8:27 PM, John Salerno wrote: > Just something that crosses my mind every time I delve into "Learning > Python" each night. Does anyone see any value in learning Python when you > don't need to for school, work, or any other reason? I mean, sure, there's > value in learning anything at any time, but for something like a programming > language, I can't help but feel that I will be mostly unable to use what I > learn simply because I have no reason to use it. > > The *process* of learning is enough fun for me, and every now and then I do > find a small use for Python that really pays off, but for the most part I'm > wondering what people's thoughts are as far as simply learning it for the > sake of learning. Does it seem like a silly endeavor to most people? Did > anyone here learn a programming language when you didn't need to? If so, how > much and in what capacity did you use it after you learned it? > > Hopefully this question even makes sense! > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.badmuthahubbard.com From bearophileHUGS at lycos.com Wed May 28 05:28:54 2008 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Wed, 28 May 2008 02:28:54 -0700 (PDT) Subject: maximum recursion depth? References: <7b55f3e5-b6f6-4c64-992e-47382d7803e7@m44g2000hsc.googlegroups.com> Message-ID: <15b59f39-3983-4795-9482-d265a67a4fde@f63g2000hsf.googlegroups.com> Dennis Lee Bieber, the ghost: > I'd have to wonder why so many recursive calls? Why not? Maybe the algorithm is written in a recursive style. A language is good if allows you to use that style too. On modern CPUs 50000 levels don't look that many levels. Bye, bearophile From zerge69 at gmail.com Wed May 21 00:00:07 2008 From: zerge69 at gmail.com (zerge69 at gmail.com) Date: Tue, 20 May 2008 21:00:07 -0700 (PDT) Subject: Port scan module Message-ID: I programmed a port scanning module which you can download here http://code.google.com/p/portscan/ Including the module in your program allows you to scan specific ports in an IP, using the function scan(ip,port,timeout). Instead of getting a cryptic code in return, the function will return "open", "closed", "filtered", or "timeout". It's a great way of learning about port scanning with Python From vbgunz at gmail.com Wed May 14 10:04:50 2008 From: vbgunz at gmail.com (vbgunz) Date: Wed, 14 May 2008 07:04:50 -0700 (PDT) Subject: Class Methods Vs Any Other Callable Message-ID: <98b4a67c-9ec7-407c-8c80-06488bd48a68@e39g2000hsf.googlegroups.com> I remember learning closures in Python and thought it was the dumbest idea ever. Why use a closure when Python is fully object oriented? I didn't grasp the power/reason for them until I started learning JavaScript and then BAM, I understood them. Just a little while ago, I had a fear of decorators because I really couldn't find a definitive source to learn them (how to with with @). How important are they? They must be important otherwise why have'em in the language? I had to learn'em and then suddenly, BAM. I understand them. My main issue with closures and decorators was hidden in the fact of how *dead simple* they were. All I needed were reasons to use them over doing it X style. So what is my point? How dead simple are class methods? I must be missing there point so I am convinced they must be dead simple. classes, functions, instance and static methods are easy. So easy in fact, I could shoot myself in the foots without looking (preferably without aiming). So, why am I stuck on the *idea* of a class method? An instance method works on the instance A Static method is basically a function nested within a class object A class method is overkill? I can call a static or class method through either the class OR any instance of it. I've never designed a method that took advantage of the class name except in cases where I needed to extend a super class *but* even in this case, I didn't use the enclosing class name... Whats the deal with class methods, why use them over anything else? What does a class method accomplish in at least one line shorter than anything else? Does it help reduce duplication or typing? I am at a lost for words that can shed at least *one* good reason to use them. What is the one greatest reason to use them? A little syntax and explanation can go a long long way. I am failing to understand them so any help is really appreciated here! From mail at timgolden.me.uk Fri May 16 09:25:10 2008 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 16 May 2008 14:25:10 +0100 Subject: Problem creating a shorcut In-Reply-To: <826cf534-a674-4861-8d60-5f6a4be30125@d77g2000hsb.googlegroups.com> References: <2715b502-d636-4541-ac0e-05697f02b2ae@m44g2000hsc.googlegroups.com> <322a200a-ed9a-44d2-b5ea-5f059884b53a@27g2000hsf.googlegroups.com> <826cf534-a674-4861-8d60-5f6a4be30125@d77g2000hsb.googlegroups.com> Message-ID: <482D8B36.4000406@timgolden.me.uk> Mike Driscoll wrote: > Ah. I was unaware of the Arguments parameter. That works quite well. > Where does one find this information anyway? I think I found mine from > bits and pieces scattered in various tutorials. The canonical place would be: http://msdn.microsoft.com/en-us/library/bb774950(VS.85).aspx TJG From n00m at narod.ru Tue May 6 01:52:15 2008 From: n00m at narod.ru (n00m) Date: Mon, 5 May 2008 22:52:15 -0700 (PDT) Subject: How to pass a multiline arg to exec('some.exe arg')? References: Message-ID: > Yes, call flush() each time you're done writing. No, it would be too easy & simple. While stdin is NOT CLOSED stdout has not EOF, but readlines() waits for its appearence ... and so freezes for good. IMO. Should be like this: import popen2 o=popen2.popen2('osql -E -S(local) -dpubs -c"GO" -n -w8000') while 1: o[1].write(raw_input()+'\nGO\n') o[1].flush() # this line can be commented res='' while 1: line=o[0].readline() if line=='\n': # ?????????????????????????????? break res+=line print res How to break the while loop? What is the sign of "there is left nothing to read"? 2. I'm still curious why multiline parameter does not work in Py. This is how it looks in VBS (and works Ok): Set w = CreateObject("WScript.Shell") q = "select * from authors" & vbCrLf q = q + "select getdate()" & vbCrLf q = q + "select * from jobs" Set e = w.Exec("osql.exe -Q""" + q + """") In shell line it looks like: osql.exe <...> -Q"select * from bla" From efurman at admailinc.com Tue May 13 15:44:31 2008 From: efurman at admailinc.com (Ethan Furman) Date: Tue, 13 May 2008 11:44:31 -0800 Subject: looking for a pdf module In-Reply-To: <4829B52E.6060903@islandtraining.com> References: <4829C0B8.9090605@admailinc.com> <4829B52E.6060903@islandtraining.com> Message-ID: <4829EF9F.80009@admailinc.com> Gary Herron wrote: > Ethan Furman wrote: > >> Greetings! >> >> I'm hoping to be able to generate pdf files on the fly -- are there >> any python modules out there to do that? >> >> All help appreciated! >> -- >> Ethan >> ------------------------------------------------------------------------ >> >> -- >> http://mail.python.org/mailman/listinfo/python-list > > ReportLabs is a quite extensive open-source project for generating PDF > files. > > http://www.reportlab.org/ > > Enjoy, > > Gary Herron > Awesome, thanks! -- Ethan -------------- next part -------------- An HTML attachment was scrubbed... URL: From irmen.NOSPAM at xs4all.nl Mon May 12 07:48:28 2008 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Mon, 12 May 2008 13:48:28 +0200 Subject: Import/Create module from buffer In-Reply-To: References: <09bfaed8-8bf6-4faf-80f9-e0b97aa03127@a70g2000hsh.googlegroups.com> Message-ID: <48282e92$0$14346$e4fe514c@news.xs4all.nl> Gruik wrote: > But before that 1 question: what if I'm in Python ? > Following your solution, I did that in Python : > > def load_buffer(buffer) : > compiled_buffer = compile(buffer, "module_name", "exec") > exec(compiled_buffer) > > It works great except that I can't have a module object and that it is > as if I did "from module import *" > But I need the module object and not an "import *" behavior. > Any idea about the way to do that? Something along the lines of: import new mymodule = new.module("mymodule") exec <<>> in mymodule.__dict__ --irmen From lists at svrinformatica.it Fri May 23 10:10:33 2008 From: lists at svrinformatica.it (Mailing List SVR) Date: Fri, 23 May 2008 16:10:33 +0200 Subject: Python treeview and recursion: help needed In-Reply-To: <1211527245.7401.3.camel@localhost.localdomain> References: <1211527245.7401.3.camel@localhost.localdomain> Message-ID: <1211551833.7401.15.camel@localhost.localdomain> Il giorno ven, 23/05/2008 alle 09.20 +0200, Mailing List SVR ha scritto: > ?Hi, > > I have a database with the following structure: > > id name sublevel > > for example > > 1 Node1 None > 2 Node2 1 > 3 Node3 2 > 4 Node4 None > 5 Node5 1 > 6 Node6 5 > .... > .... > > > where Node1 and Node4 are treeview's master nodes, Node2 is a subnode of > Node1, Node3 is a subnode of Node2, Node5 is a subnode of Node1 and > Node6 a subnode of Node5 and so on > > I need a recursive function to populate treeview and I'm stuck on this > function :confused: > > I need a list where I have the master node with child node inside and if > a child node as others child nodes, I need thess nodes inside the child > nodes. > > Something like this: > > [ > {"id":1,"name":"Node1","Childs":[{"id:2","name":"Node2","Childs":[{"id":3,"name":"Node3","Childs":[]}]}, > {"id":5, > "name":"Node5","Childs":[{"id":6,"name":"Node6","Childs":[]}]}]},{"id":4,"name":"Node4","Childs":[]} > ] > > I'm using django so I access the data as > > all=Data.objects.all() > > and I can do something like > > for a in all: > print a.id > print a.name > > to get database value. > > Any help is appreciated, > > thanks, > Nicola > > -- > http://mail.python.org/mailman/listinfo/python-list only for the records attacched is a working solution, maybe not the best one but a working one, regards Nicol -------------- next part -------------- A non-text attachment was scrubbed... Name: ricorsioneid.py Type: text/x-python Size: 2085 bytes Desc: not available URL: From lists at cheimes.de Tue May 13 21:14:42 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 14 May 2008 03:14:42 +0200 Subject: list.__len__() or len(list) In-Reply-To: <3fc761710805131718y448ef0b8r67dcc8cf118bc80a@mail.gmail.com> References: <3fc761710805131718y448ef0b8r67dcc8cf118bc80a@mail.gmail.com> Message-ID: <482A3D02.3020001@cheimes.de> Ian Kelly schrieb: > The purpose of obj.__len__() is to implement len(obj), which simply > calls it. So obj.__len__() may be faster, but only marginally. The > reason to prefer len(obj) is that if you inadvertently pass an object > that does not implement __len__, you get the more appropriate > TypeError rather than an AttributeError. len(obj) is faster than obj.__len__() for several types like str. In general len() is as least as fast __len__(). len() also does some extra sanity checks. python2.5 -m timeit "'abc'.__len__()" 1000000 loops, best of 3: 0.453 usec per loop python2.5 -m timeit "len('abc')" 1000000 loops, best of 3: 0.292 usec per loop Common code paths are already highly optimized. Don't try to be clever unless you really understand what happens inside the interpreter. The __internal__ methods are called magic methods for a reason. ;) Christian From ptmcg at austin.rr.com Mon May 19 09:18:53 2008 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 19 May 2008 06:18:53 -0700 (PDT) Subject: "Disabling" raw string to print newlines References: <7f63b5e9-e0d6-4505-9707-b13b70fe61c0@27g2000hsf.googlegroups.com> <67828af6-82a6-4c5d-adc0-d5f8d4b083b0@x41g2000hsb.googlegroups.com> Message-ID: <3e70e415-a276-4f91-b9d1-95dfc2f242ea@59g2000hsb.googlegroups.com> On May 19, 8:09?am, Paul McGuire wrote: > On May 19, 4:54?am, kuratk... at kuratkull.com wrote:> Hello, > > > > > > > print out > > ************** > > Since you have no control over spacing and line breaks in the input, > you can reformat using the textwrap module. ?First replace all "\n"s > with " ", then use re.sub to replace multiple spaces with a single > space, then call textwrap.fill to reformat the line into lines up to > 'n' characters long (I chose 50 in the sample below, but you can > choose any line length you like). > > out = match.findall(html) > out = out[0].replace("\n"," ") > out = re.sub("\s+"," ",out) > > print textwrap.fill(out,50) > > -- Paul One last try - .replace("\n"," ") is unnecessary, textwrap.fill takes care of removing extra newlines already. out = match.findall(html) out = out[0] out = re.sub("\s+"," ",out) print textwrap.fill(out,50) -- Paul From gherron at islandtraining.com Mon May 19 04:29:51 2008 From: gherron at islandtraining.com (Gary Herron) Date: Mon, 19 May 2008 01:29:51 -0700 Subject: arrays In-Reply-To: References: Message-ID: <48313A7F.4050909@islandtraining.com> Marlin Rowley wrote: > All: > > Say I have an array: > > a = (['rrrrggggbbbbaaaa'],['rrrrggggbbbbaaaa']) > > How do I make it so that I now have: > > starting with first element (a[0]) > new_arr[0] = 'r' > new_arr[1] = 'g' > new_arr[2] = 'b' > new_arr[3] = 'a' > new_arr[4] = 'r' > ..... > > continuing "through" a[1] with the same new_arr > new_arr[N] = 'r' > new_arr[N+1] = 'g' > .... > > -M > > ------------------------------------------------------------------------ > Give to a good cause with every e-mail. Join the i?m Initiative from > Microsoft. > > > ------------------------------------------------------------------------ > > -- > http://mail.python.org/mailman/listinfo/python-list 2 questions: 1. Why have you flooded this news group with three identical copies of a question under three different subject? This is a (mild) bit of abuse of the newsgroup. One copy with a reasonable subject line is enough. 2. Haven't I answered this question for you often enough already? Was my answer not clear enough, or has the problem again changed slightly enough to require a new answer? Having solved 3 or 4 versions of this problem for you already, I'm wondering why I'm seeing it posed yet one more time. If this is *exactly* the same problem I solved once already (and I believe it is), why are we seeing it again, and if it is not the *exact* same problem, why are we seeing so many similar version of it? It's starting to feel like a slight abuse of my time to see this problem on the newsgroup again. Gary Herron From rhh2109 at columbia.edu Fri May 9 07:21:39 2008 From: rhh2109 at columbia.edu (Roy H. Han) Date: Fri, 9 May 2008 07:21:39 -0400 Subject: Pythonwin In-Reply-To: References: Message-ID: <6a5569ec0805090421x34a74f22tc2c16758a93ff53a@mail.gmail.com> Hi Clive, For ArcGIS, I use plain old VIM, IPython and IDLE. If you really want PythonWin, then you can download Mark Hammond's Python for Windows extensions: http://sourceforge.net/projects/pywin32/ Note also that with the pywin32 extensions, you can also use Python 2.5 to access ArcGIS using from win32com.client import Dispatch arcgis = Dispatch('esriGeoprocessing.GpDispatch') If you just need to access shapefiles, there is shapelib: http://shapelib.maptools.org/ To make shapelib bindings for Python 2.5 1. Download *shapelib_1_2_10.zip *from http://dl.maptools.org/dl/shapelib/ 2. Download *pyshapelib-0.3.zip* from ftp://intevation.de/users/bh/pyshapelib 3. Extract *pyshapelib-0.3.zip* 4. Extract *shapelib_1_2_10.zip* to the folder containing pyshapelib. Rename the extracted folder as *shapelib* 5. From the pyshapelib directory, run python setup.py build. The script looks in its parent folder for the shapelib folder. 5. From the pyshapelib directory, python setup.py install Hope that helps, Roy ** On Fri, May 9, 2008 at 6:46 AM, Niklas Norrthon wrote: > On 9 Maj, 12:30, Clive_S wrote: > > Hi > > > > I am trying to use Python with ArcGIS. > > > > I have installed Python 2.4. I have an icon for IDLE and command line. > > I do not see Python PythonWin. > > > > How do you install or launch pythonwin?? > > There is a distribution of PythonWin bundled with the > ArcGIS Desktop installation media, but it is not > installed by the ArcGIS installer. > > You have three options: > 1. Install it manually from the ArcGIS installation > media. > 2. Find it on the web (google for it), download and > install. > 3. (My recommendation) Don't bother. IDLE is pretty > good. Emacs even better (unless you hate emacs). > > -- > Niklas Norrthon > ESRI S-GROUP > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From alokkat at gmail.com Wed May 28 08:41:06 2008 From: alokkat at gmail.com (Alok Kumar) Date: Wed, 28 May 2008 08:41:06 -0400 Subject: Struct usages in Python In-Reply-To: References: Message-ID: while traversing I get out of index error as mentioned below. class EventTimeFilter: def __init__(self): * self.event = [Event()]* def populateScheduleData(self): self.doc = libxml2.parseFile(self.FILENAME) for eachcamera in self.doc.xpathEval('SetDeviceConfiguration/Camera/.'): cameraIndex = eachcamera.get_properties() #print cameraIndex index = int(cameraIndex.content,10) print index xpathEventType = 'SetDeviceConfiguration/Camera[@cameraIndex=' + cameraIndex.content +']/Filter/Event' for searchResults in self.doc.xpathEval(xpathEventType): eventType = searchResults.get_properties() * self.event[index-1].cameraEventType = eventType.content # Error* *#Error as below* self.event[index-1].cameraEventType = eventType.content IndexError: list index out of range Any guidance why I am getting *list index out of range error*? index value runs from 1 to 4. Thanks for all your help. Alok On Wed, May 28, 2008 at 1:09 AM, Casey McGinty wrote: > > self.event[] = Event() *# Seems this is not allowed ?? * >> > > self.event = [Event()] > > - Casey > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Regards Alok Kumar -------------- next part -------------- An HTML attachment was scrubbed... URL: From mnikhil at gmail.com Fri May 23 14:13:34 2008 From: mnikhil at gmail.com (Nikhil) Date: Fri, 23 May 2008 23:43:34 +0530 Subject: Using MySQLdb to select into the local file References: <4835cf41$0$34536$742ec2ed@news.sonic.net> Message-ID: John Nagle wrote: > Nikhil wrote: >> I am using the MySQLdb python module. I have a table named 'testing' >> with few columns, under the 'test' database, what is hosted on a >> remote mysql server. >> >> I want to run the following query to get a comma-separated information >> from the table >> >> >> LOCK TABLES foo READ; >> SELECT a,b,a+b INTO OUTFILE '/tmp/result.txt' >> FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' >> LINES TERMINATED BY '\n' >> FROM 'testing' >> UNLOCK TABLES; >> >> ..the query is running fine, but what I am noticing is /tmp/result.txt >> is getting created locally on a mysqld running machine but not on the >> client(python program) using the MySQLdb module. > > Unfortunately, while there is LOAD DATA LOCAL INFILE, which > reads a file on the client, there is no SELECT INTO LOCAL OUTFILE. > > Actually, you probably want to turn off the FILE privilege > for your MySQL. That blocks LOAD DATA INFILE and SELECT INTO > OUTFILE, generally considered a good idea because those commands can > access arbitrary file names. > > Also, if you're still using LOCK TABLES and UNLOCK TABLES, > read up on InnoDB and transactions. > > Typically, you do something like this: > > import MySQLdb > import csv > > def writedb(db, filename) : > try : > outcsv = csv.writer(filename) # output object for CSV > cursor = db.cursor() > cursor.execute("SELECT a,b,a+b FROM testing") > while True : # do all rows > row = cursor.fetchone() # get a tuple for one row > if row is None : # if end of rows > break # done > outcsv.writerow(row) # write row in CSV format > db.commit() # release locks > > except MySQLdb.OperationalError, message: > print "Database trouble: ", message # handle any db problems > raise # reraise exception > > > hostname="???" # fill in appropriately > user="???" > password="???" > db = MySQLdb.connect(host=hostname, # open database > user=username, passwd=password, db=databasename) > > writedb(db, '/tmp/result.txt') # do it > > =============== > > Note that this is ASCII-oriented; if you Unicode, you need > extra params to "connect". Also, the CSV module doesn't do > Unicode well as yet. Make sure the "outcsv" object > goes out of scope before you try to read the file, so the > file gets flushed and closed. > > John Nagle Thanks John. That was a useful tip. Regards, Nikhil From nick at craig-wood.com Fri May 23 05:30:08 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Fri, 23 May 2008 04:30:08 -0500 Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> Message-ID: I V wrote: > On Thu, 22 May 2008 19:35:50 -0700, Charles Hixson wrote: > > Although when comparing Candygram with Erlang it's worth noting that > > Candygram is bound to one processor, where Erlang can operate on > > multiple processors. (I'd been planning on using Candygram for a project > > at one point, but this made it unusable.) > > Really? The FAQ says it uses operating system threads, which I would have > thought would mean it runs on multiple processors (modulo, I suppose, the > issues with the GIL). I think candygram is crying out to be married with stackless &or PyPy. It also needs an IPC channel to compete with Erlang directly. If you are interested in stackless python vs Erlang then take a look at this... http://muharem.wordpress.com/2007/07/31/erlang-vs-stackless-python-a-first-benchmark/ ...and read the discussion too! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From upton at virginia.edu Mon May 26 17:26:46 2008 From: upton at virginia.edu (Dan Upton) Date: Mon, 26 May 2008 17:26:46 -0400 Subject: python raycaster, pycaster, where? In-Reply-To: <1e8fccc5-21d1-4194-95ff-7f57939f184c@c58g2000hsc.googlegroups.com> References: <1e8fccc5-21d1-4194-95ff-7f57939f184c@c58g2000hsc.googlegroups.com> Message-ID: <5504f9ac0805261426k589a4643m3970aaf27c2659b4@mail.gmail.com> On Mon, May 26, 2008 at 4:52 PM, wrote: > i tried googling this thing but couldnt find it. i cant find it in > pyagme either. > Really? http://www.google.com/search?q=pycaster The first link has downloads for it. From basti.wiesner at gmx.net Mon May 26 13:32:12 2008 From: basti.wiesner at gmx.net (Sebastian 'lunar' Wiesner) Date: Mon, 26 May 2008 19:32:12 +0200 Subject: Python web development that resembles PHP or classic ASP References: <66a261d8-c31d-4519-beb9-c8913f61a87d@m44g2000hsc.googlegroups.com> Message-ID: -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 [ Ivan Illarionov ] > On Mon, 26 May 2008 17:49:01 +0200, Sebastian 'lunar' Wiesner wrote: > > [...] >> Modern frameworks like Django or Grok require a somewhat great adaption, >> since they strongly restrict the programmer's freedom. I doubt, that >> you would get Django or Grok working like your asp framework. > > Actually, mordern frameworks (at least Djagno) does not "restrict the > programmer's freedom", they only encourage clean design. Can we agree on the fact, that Django _encourages clean design_ by _restricting the programmers freedom to some degree_? This comprise would avoid an endless war about framework philosophy ;) (and isn't so far from the truth, btw) > It's perfectly possible to write Django app with only one view and url > pattern that redirects everything to different template engine like > Cheetah or Mako and all the logic could be put inside those templates. Absolutely, but that's not what Django is about. If you don't follow Django's conventions and don't make use of Djangos facilities like its ORM or its admin interface, Django just doesn't make sense anymore. An application such as you outlined would depend on a big, heavy framework to do a task, that could easily be done with plain WSGI or a WSGI wrapper like Werkzeug. > But, IMHO, writing PHP-style Python webapp is silly. I completely agree here, but that's not, what the OP asked for ;) - -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) -----BEGIN PGP SIGNATURE----- Version: GnuPG v2.0.9 (GNU/Linux) iEYEARECAAYFAkg69CIACgkQn3IEGILecb5vyACeLCLF2WfvKSUe466HeUqZYXj8 AC8An1+sUvbyWiIu9mBixQ9ME0j1Ts+j =6lQT -----END PGP SIGNATURE----- From inhahe at gmail.com Sun May 18 04:27:56 2008 From: inhahe at gmail.com (inhahe) Date: Sun, 18 May 2008 04:27:56 -0400 Subject: morning in Python References: <409ea9f1-9774-4bf2-abac-2daf997bc97f@c65g2000hsa.googlegroups.com> Message-ID: By the way, "state" as a meronym of "city" and "state" as it applies to programming (i.e. stasis) are two unrelated things. >I'd start to discuss state property in appertanance to city >property. >What are some properties of the state? From python at rcn.com Fri May 30 23:46:07 2008 From: python at rcn.com (Raymond Hettinger) Date: Fri, 30 May 2008 20:46:07 -0700 (PDT) Subject: Nasty gotcha/bug in heapq.nlargest/nsmallest References: <66daa0cc-f0df-4282-82b7-ff33617bcbe5@a23g2000hsc.googlegroups.com> Message-ID: <8c937dcb-082f-4182-be44-429fec31a8b9@z24g2000prf.googlegroups.com> On May 15, 12:06?am, Peter Otten <__pete... at web.de> wrote: > According > to my ad hoc test you need <, <=, and == for nlargest()/nsmallest() to > work: In Py2.6 and after, you only need < and ==. I replaced the LE tests with LT to match list.sort() and bisect.bisect(). The == arises because nlargest/nsmallest compare decorated tuples. Tuple comparison always starts with equality tests to find the first unequal element and then switches back to testing whichever inequality test was requested. Raymond From lists at cheimes.de Thu May 1 13:55:21 2008 From: lists at cheimes.de (Christian Heimes) Date: Thu, 01 May 2008 19:55:21 +0200 Subject: Problems with Cheese Shop In-Reply-To: <87zlr9vry8.fsf@physik.rwth-aachen.de> References: <87zlr9vry8.fsf@physik.rwth-aachen.de> Message-ID: <481A0409.6040706@cheimes.de> Torsten Bronger schrieb: > Hall?chen! > > How can I authorise to the Python Cheese Shop in order to use > setup.py upload? Currently, I get > > Upload failed (401): You must be identified to edit package information Try "python setup.py register sdist upload" Christian From exarkun at divmod.com Mon May 5 15:32:52 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 5 May 2008 15:32:52 -0400 Subject: SSL through python. possible ? In-Reply-To: <715b8048-8b88-44cd-a40a-722650125f19@e53g2000hsa.googlegroups.com> Message-ID: <20080505193252.6859.1948998822.divmod.quotient.59157@ohm> On Mon, 5 May 2008 11:11:19 -0700 (PDT), TkNeo wrote: >On May 2, 1:52 pm, Mike Driscoll wrote: >> On May 2, 1:20 pm, Heikki Toivonen wrote: >> >> > Mike Driscoll wrote: >> > > On Apr 29, 8:56 am,TkNeo wrote: >> > >> I need to do SSL file transfer using python? Is there a library i can >> > >> use ? >> >> > >http://sandbox.rulemaker.net/ngps/m2/ >> >> > M2Crypto has since moved tohttp://chandlerproject.org/Projects/MeTooCrypto >> >> > -- >> > Heikki Toivonen >> >> Whoops...I just went with the first link Google gave me. The link I >> gave doesn't mention that the project has moved. Looks like the one >> you link to is the 9th link on my Google search using the terms: >> "python m2crypto". >> >> Sorry if I spread misinformation though. >> >> Mike > >ok i have tried around a lot but no luck. I think M2Crypto is my best >option except it requires a minimum of python 2.4 which i don't have. > >What i am trying to do is to do an FTP transfer that uses SSL >(username, password authentication) and not a certificate file. The >few example i have found of the Openssl module use a certificate for >authentication unlike what i want to do. > >Anyone has any ideas ? FWIW, though not as complete as an OpenSSL wrapper as M2Crypto, pyOpenSSL works with Python 2.3. As far as the details of the authentication that you are attempting go, it sounds like you want to use ephemeral DH key exchange. This is something which is on my list to figure out. ;) Jean-Paul From george.sakkis at gmail.com Sat May 17 04:06:12 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Sat, 17 May 2008 01:06:12 -0700 (PDT) Subject: can't delete from a dictionary in a loop References: Message-ID: <95294ce6-38a0-44cd-8b0f-2bce0642886d@27g2000hsf.googlegroups.com> On May 16, 5:22?pm, "Dan Upton" wrote: > This might be more information than necessary, but it's the best way I > can think of to describe the question without being too vague. > > The task: > > I have a list of processes (well, strings to execute said processes) > and I want to, roughly, keep some number N running at a time. ?If one > terminates, I want to start the next one in the list, or otherwise, > just wait. > > The attempted solution: > > Using subprocess, I Popen the next executable in the list, and store > it in a dictionary, with keyed on the pid: > (outside the loop) > procs_dict={} > > (inside a while loop) > process = Popen(benchmark_exstring[num_started], shell=true) > procs_dict[process.pid]=process > > Then I sleep for a while, then loop through the dictionary to see > what's terminated. ?For each one that has terminated, I decrement a > counter so I know how many to start next time, and then try to remove > the record from the dictionary (since there's no reason to keep > polling it since I know it's terminated). ?Roughly: > > for pid in procs_dict: > ? if procs_dict[pid].poll() != None > ? ?# do the counter updates > ? ?del procs_dict[pid] Since you don't look up processes by pid, you don't need a dictionary here. A cleaner and efficient solution is use a deque to pop processes from one end and push them to the other if still alive, something like this: from collections import deque processes = deque() # start processes and put them in the queue while processes: for i in xrange(len(processes)): p = processes.pop() if p.poll() is None: # not finished yet processes.append_left(p) time.sleep(5) HTH, George From exhuma at gmail.com Wed May 21 08:27:17 2008 From: exhuma at gmail.com (Michel Albert) Date: Wed, 21 May 2008 05:27:17 -0700 (PDT) Subject: qrcode in python? Message-ID: <6498df89-1298-445b-9674-f4d92e0cd298@x41g2000hsb.googlegroups.com> I am planning to write a python-module for python as I haven't found anything on the tubes so far. If anyone has any interesting insight on this topic, replies are welcome! ;) Q: What is QR-Code? A: http://www.denso-wave.com/qrcode/qrstandard-e.html So far (as of May 21st 2008): Google (1 sensible hit): http://mail.python.org/pipermail/python-list/2006-May/385258.html The Cheese shop (nothing): http://pypi.python.org/pypi?%3Aaction=search&term=qrcode&submit=search Sourceforge (1 hit - no files/code): http://sourceforge.net/projects/qrcode/ I was planning to make use of qr-code in a web-application which is written in python. So far I was not yet lucky to find any existing module. I just contacted the project lead of http://sourceforge.net/projects/qrcode/ on this topic as well. Let's see what he replies. So..... any pointers/ideas ? From KyleMcG at gmail.com Wed May 7 22:14:35 2008 From: KyleMcG at gmail.com (Kyle McGivney) Date: Wed, 7 May 2008 19:14:35 -0700 (PDT) Subject: The Importance of Terminology's Quality References: Message-ID: > ? Module, Block, in Mathematica is in lisp's various ?let*?. The > lisp's keywords ?let?, is based on the English word ?let?. That word > is one of the English word with multitudes of meanings. If you look up > its definition in a dictionary, you'll see that it means many > disparate things. One of them, as in ?let's go?, has the meaning of > ?permit; to cause to; allow?. This meaning is rather vague from a > mathematical sense. Mathematica's choice of Module, Block, is based on > the idea that it builds a self-contained segment of code. (however, > the choice of Block as keyword here isn't perfect, since the word also > has meanings like ?obstruct; jam?) If the purpose of let is to introduce one or more variable bindings, then I don't see how changing to block or module would improve anything. I've always found it fairly intuitive to parse (let ((x 5)) ...) to "let x be five". Additionally, replacing let with the synonyms you provided would approximately yield "permit x to be five" or "allow x to be five". In my mind you have constructed an argument in favor of let here (obviously it's better than block, because nobody's going to come along and be confused about whether let will "obstruct" or "jam" them :) There are many easy targets to poke at in the CL spec. let isn't one of those. From alex.m.gusarov at gmail.com Mon May 26 11:37:04 2008 From: alex.m.gusarov at gmail.com (Alex Gusarov) Date: Mon, 26 May 2008 22:37:04 +0700 Subject: Overloading virtual method of widget without inheriting (PyQt) Message-ID: Hello, I have strong .NET background with C# and want to do some familiar things from it with Python, but don't know how. For example, I created form in qt designer with QCalendarWidget, translated it into Python module and want to overload virtual method paintCell of QCalendarWidget. In C# I can write following (abstract) code: this.calendar.PaintCell += new PaintEventHandler(myPaintCellHandler); void myPaintCellHandler(object sender, PaintEventArgs e) { // some work here } I can't find how I can do similar thing in Python without inheriting QCalendarWidget and overloading this method in inherited class (it's long and I must create additional class). So, I need to run my code whenever paintCell is called by Qt internals and I have no enough experience with Python for it. Please, give me some advice, I know Python must be good enough to do such things. -- Best regards, Alex Gusarov -------------- next part -------------- An HTML attachment was scrubbed... URL: From clyfish at gmail.com Fri May 9 02:39:48 2008 From: clyfish at gmail.com (clyfish at gmail.com) Date: Thu, 8 May 2008 23:39:48 -0700 (PDT) Subject: how to use subprocess.Popen execute "find" in windows References: <5666ed04-8a2f-4dad-b7bc-3e3c3c084f03@f24g2000prh.googlegroups.com> <708883cd-5cc8-4507-b91e-841dd10d149a@c19g2000prf.googlegroups.com> <8c5a14fe-dd65-4ed0-bcd5-384ba3e6ffe2@q27g2000prf.googlegroups.com> Message-ID: <122616fb-29a1-4532-9e16-845c596b56ad@z24g2000prf.googlegroups.com> On 5?8?, ??5?39?, "Gabriel Genellina" wrote: > En Wed, 07 May 2008 23:29:58 -0300, escribi?: > > > > > On 5?7?, ??9?45?, Justin Ezequiel > > wrote: > >> On May 6, 5:19 pm, clyf... at gmail.com wrote: > > >> > p1 = Popen(['netstat', '-an'], stdout = PIPE) > >> > p2 = Popen(['find', '"445"'], stdin = p1.stdout, stdout = PIPE) > >> > print p2.stdout.read() > > >> > It doesn't work. > >> > Because subprocess.Popen execute "find" like this. > > >> > C:\>find \"445\" > > >> > It adds a '\' before each '"'. > >> > How to remove the '\'? > >> > Thank you. > > >> cannot help with the backslashes but try findstr instead of find > > > Thank you. > > findstr doesn't need quotes, so it works. > > Build the command line yourself -instead of using a list of arguments-. Popen doesn't play with the quotes in that case: > > p1 = Popen(['netstat', '-an'], stdout = PIPE) # using list > p2 = Popen('find "445"', stdin = p1.stdout, stdout = PIPE) # using str > print p2.communicate()[0] > > -- > Gabriel Genellina Thanks very much. You solved my problem. From bellman at lysator.liu.se Tue May 20 10:21:05 2008 From: bellman at lysator.liu.se (Thomas Bellman) Date: Tue, 20 May 2008 14:21:05 +0000 (UTC) Subject: Misuse of list comprehensions? References: <038e4418$0$27258$c3e8da3@news.astraweb.com> <69g2bpF31ttuuU1@mid.uni-berlin.de> <027e4d96$0$25054$c3e8da3@news.astraweb.com> Message-ID: "John Salerno" writes: > "Diez B. Roggisch" wrote in message > news:69g2bpF31ttuuU1 at mid.uni-berlin.de... >> the above code is pretty much of a no-no because it has quadratic runtime >> behavior. > What's that mean, exactly? It means that running time will increase with the square of the problem size. 2.000.000 items will take 4 times as long as 1.000.000 items, and 5.000.000 items will take 25 times as long as 1.000.000 items. > Are you referring to both examples, or just the > second one? The problem is that the lookup you did to see if an item had already been seen, is done by a linear search of a list. The search time is linearly proportional to the number of items on the list 'new', but since the number of times you do that search increases with the length of the input, the total runtime for your function increases even more. This thus applies to both your examples, since they really do the same thing. However, it actually depends on what your input is. For the runtime to increase with the square of the input length in your function, the number of *unique* items on the input must be a constant fraction of the input length. By that I mean that, for example, 5% of the input items are unique, so that if your input is 100 items, then the list 'new' will be 5 items at the end of the function, and if your input is 5.000.000 items, then 'new' will become 250.000 items long. This might not be the case in your use. If you for example know that the input only consists of integers between 0 and 10, then 'new' will never become longer than 11 items, regardless of whether the input is 20 or 20.000.000.000 items. The runtime of your function then suddenly becomes linear in the problem size instead of quadratic. Even so, maintaining the set of already seen items as a set is likely to be faster than keeping them as a list, even for a fairly small number of unique items. One small exception from this, though. If only maintaining one data structure (the ordered list 'new' in your code) makes your working set fit within the processor cache, while maintaining two data structures (a list for keeping the order, and a set for searching) will make it *not* fit within the cache, then it *might* actually be faster to just maintain the list. Unlikely, but not entirely impossible, and just a small change of the problem size can change the balance again. -- Thomas Bellman, Lysator Computer Club, Link??ping University, Sweden "What sane person could live in this world ! bellman @ lysator.liu.se and not be crazy?" -- Ursula K LeGuin ! Make Love -- Nicht Wahr! From pistacchio at gmail.com Wed May 7 09:27:36 2008 From: pistacchio at gmail.com (pistacchio) Date: Wed, 07 May 2008 15:27:36 +0200 Subject: PHP + TinyButStrong Python replacement References: Message-ID: Mike Driscoll ha scritto: > On May 7, 6:12 am, pistacchio wrote: >> hi! i'm a php user and a python programmer. i'd love to use python for >> my server side needs but i can't seem to find what i'm looking for. for >> most of my php work i use mysql and tinyButStrong >> (http://www.tinybutstrong.com) which is a very lightweight template >> engine that offers powerful functionalities. you insert TBS tags in web >> pages like: >> >>
[var.x]
>> >> and it replaces [var.x] with the value of global variable x. it also >> makes blocks (and nested blocks) easy to implement: >> >>

[blk1;block=begin] [blk1.val]
>> [blk1;block=end]

>> >> in the previous code it cycles throu all the values of the array blk1. >> >> it does many more things, like htlm escaping, url and js encoding etc, >> conditional displaying etc, but it is not more confusing that inserting >> pieces of code into the HTML (aka: littering the code and kissing >> goodbye to the code/presentation separation). it comes in the form of a >> single file with a single class that you can easily include in the code >> and go. >> >> now, i've searched the net and it seems full of python-based frameworks >> for doing server side scripting and templating, but none that suits my >> needs. >> >> 1. i like writing code and i like control. i mean, open up the >> simplest text editor and write in it. i don't want something that is >> command-line driven or that writes code for me like ">>> >> makePagesFromThisDatabase()". >> 2. i want something very lightweight. i don't want dozen of options, >> pre-made blogging parts ecc. i just need a good non invasive template >> engine and the basic functions for server side scripting, like session >> managing, request parsing, functions to manipulate html code (encodings etc) >> 3. i don't want to beg my hosting provider to install the libraries. >> a simple include file should do the work. >> 4. object oriented programming is not required (better: i prefer >> plain old procedural programming). >> >> any help? thanks in advance > hi, thanks for replaying > Did you look at TurboGears or Django? TG uses Kid in the 1.x series > and Genshi in 2.x (I think) for templating purposes. There's also > Cheetah, one of the more powerful Python templating engines out there. > django is exacly the kind of giant i'm trying to avoid > http://genshi.edgewall.org/ the first lines of the tutorial read: "First, make sure you have CherryPy 3.0.x installed" Now, cherrypy is something that is not properly "include a file and get going!" > http://www.kid-templating.org/ kid seems to have a non-linear approach, but i may give it a try > http://www.cheetahtemplate.org/ cheetah was something that i already considered using. have i to "install" it or can i just import it? > http://turbogears.org/ same problem as with django! > > Maybe those links will get you going. > > Mike From pavlovevidence at gmail.com Wed May 7 03:26:04 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 7 May 2008 00:26:04 -0700 (PDT) Subject: License selection for free software References: <3a8e0a8f-3bd1-4650-9104-5c273f14b097@w7g2000hsa.googlegroups.com> <1w4gs9bk.fsf@gmail.com> <87ve1se6q5.fsf_-_@benfinney.id.au> <8763tr5ov1.fsf@gmail.com> <7xbq3iaa82.fsf@ruckus.brouhaha.com> Message-ID: <15eb97d1-4318-4648-9120-d7d27d7dc435@b64g2000hsa.googlegroups.com> On May 7, 2:39 am, Paul Rubin wrote: > vivai... at gmail.com (Ville M. Vainio) writes: > > > In practice, the probability of hijacking of source code by an evil > > corporation is very low for most projects. And even when it did > > happen, the evil corporation would likely submit patches. > > If they're going to submit patches then they shouldn't have any problem > with the GPL. Nonsense. They could be more than willing to contribute their patches, but aren't willing to accept the GPL's limitation to being used only in open source packages. LGPL? No, there is probably no reason to have a serious problem with that if you're going to submit patches, but GPL, yes. Carl Banks From gagsl-py2 at yahoo.com.ar Mon May 12 03:00:21 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 12 May 2008 04:00:21 -0300 Subject: do you fail at FizzBuzz? simple prog test References: <39709320-66e1-40e9-a351-c769c9a94585@x41g2000hsb.googlegroups.com> Message-ID: En Sat, 10 May 2008 22:12:37 -0300, globalrev escribi?: > http://reddit.com/r/programming/info/18td4/comments > > claims people take a lot of time to write a simple program like this: > > > "Write a program that prints the numbers from 1 to 100. But for > multiples of three print "Fizz" instead of the number and for the > multiples of five print "Buzz". For numbers which are multiples of > both three and five print "FizzBuzz". > > for i in range(1,101): > if i%3 == 0 and i%5 != 0: > print "Fizz" > elif i%5 == 0 and i%3 != 0: > print "Buzz" > elif i%5 == 0 and i%3 == 0: > print "FizzBuzz" > else: > print i > > > is there a better way than my solution? is mine ok? Is it correct? Did you get at it in less than 15 minutes? If so, then it's OK. The original test was not "write the most convoluted algorithm you can think of", nor "write the best program to solve this". It was a *practical* test: if you can't get anything remotely working for such a simple problem in 15 minutes, we're not interested in your services. (We used this question last year - some people gave a sensible answer in less than 5 minutes, but others did not even know how to start) -- Gabriel Genellina From gnewsg at gmail.com Thu May 22 08:58:19 2008 From: gnewsg at gmail.com (Giampaolo Rodola') Date: Thu, 22 May 2008 05:58:19 -0700 (PDT) Subject: simple way to touch a file if it does not exist References: Message-ID: On 22 Mag, 11:54, Ken Starks wrote: > After os.path.exists, you need to check it _is_ a > file, and not a directory. > > > > Giampaolo Rodola' wrote: > > On 22 Mag, 01:15, Nikhil wrote: > >> what are the simple ways? > >> I could think of os.open(), os.exec(touch file) > > >> are there any simpler methods? > > > Just use os.path.exists to check for file existence and open() as > > replacement for touch. > > >>>> import os > >>>> if not os.path.exists('file'): > > ... ? ? open('file', 'w').close() > > ... > > > --- Giampaolo > >http://code.google.com/p/pyftpdlib/- Nascondi testo tra virgolette - > > - Mostra testo tra virgolette - Yeah, I forgot. :\ --- Giampaolo http://code.google.com/p/pyftpdlib From bj_666 at gmx.net Sun May 25 03:32:49 2008 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 25 May 2008 07:32:49 GMT Subject: which datastructure for fast sorted insert? References: <6610cad9-384d-4755-9a2c-c605329be217@8g2000hse.googlegroups.com> Message-ID: <69sj10F34jb08U3@mid.uni-berlin.de> On Sun, 25 May 2008 00:10:45 -0700, notnorwegian wrote: > sets dont seem to be so good because there is no way to iterate them. Err: In [82]: for x in set(['a', 'b', 'c']): ....: print x ....: a c b Ciao, Marc 'BlackJack' Rintsch From inhahe at gmail.com Sun May 18 07:37:37 2008 From: inhahe at gmail.com (inhahe) Date: Sun, 18 May 2008 07:37:37 -0400 Subject: how would you...? References: <1449c36e-10ce-42f4-bded-99d53a0a2569@a1g2000hsb.googlegroups.com> Message-ID: <3xUXj.11305$hv2.9481@bignews5.bellsouth.net> "Sanoski" wrote in message news:1449c36e-10ce-42f4-bded-99d53a0a2569 at a1g2000hsb.googlegroups.com... > I'm pretty new to programming. I've just been studying a few weeks off > and on. I know a little, and I'm learning as I go. Programming is so > much fun! I really wish I would have gotten into it years ago, but > here's my question. I have a longterm project in mind, and I wont to > know if it's feasible and how difficult it will be. > > There's an XML feed for my school that some other class designed. It's > just a simple idea that lists all classes, room number, and the person > with the highest GPA. The feed is set up like this. Each one of the > following lines would also be a link to more information about the > class, etc. > > Economics, Room 216, James Faker, 3.4 > Social Studies, Room 231, Brain Fictitious, 3.5 > > etc, etc > > The student also has a picture reference that depicts his GPA based on > the number. The picture is basically just a graph. I just want to > write a program that uses the information on this feed. > > I want it to reach out to this XML feed, record each instance of the > above format along with the picture reference of the highest GPA > student, download it locally, and then be able to use that information > in various was. I figured I'll start by counting each instance. For > example, the above would be 2 instances. > > Eventually, I want it to be able to cross reference data you've > already downloaded, and be able to compare GPA's, etc. It would have a > GUI and everything too, but I am trying to keep it simple right now, > and just build onto it as I learn. > > So lets just say this. How do you grab information from the web, in > this case a feed, and then use that in calculations? How would you > implement such a project? Would you save the information into a text > file? Or would you use something else? Should I study up on SQLite? > Maybe I should study classes. I'm just not sure. What would be the > most effective technique? People usually say BeautifulSoup for getting stuff from the web. I think I tried it once and had some problem and gave up. But since this is XML I think all you'd need is an xml.dom.minidom or xml.etree.ElementTree. i'm not sure which is easier. see doc\python.chm in the Python directory to study up on those. To grab the webpage to begin with you'd use urllib2. That takes around one line of code. I wouldn't save it to a text file, because they're not that good for random access. Or storing images. I'd save it in a database. There are other database modules than SQLite, but SQLite is a good one, for simple projects like that where you're just going to be running one instance of the program at a time. SQLite is fast and it's the only one that doesn't require a separate database engine to be installed and running. Classes are just a way of organizing code (and a little more, but they don't have a lot to do with saving stuff to file). I'm not clear on whether the GPA is available as text and an image, or just an image. If it's just available as an image you're going to want to use PIL (Python Image Library). Btw, use float() to convert a textual GPA to a number. You'll have to learn some basics of the SQL language (that applies to any database). Or maybe not with SQLObject or SQLAlchemy, but I don't know how easy those are to learn. Or if you don't want to learn SQL you could use a text file with fixed-length fields and perhaps references to individual filenames that store the pictures, and I could tell you how to do that. But a database is a lot more flexible, and you wouldn't need to learn much SQL for the same purposes. Btw, I used SQLite version 2 before and it didn't allow me to return query results as dictionaries (i.e., indexable by field name), just lists of values, except by using some strange code I found somewhere. But a list is also easy to use. But if version 3 doesn't do it either and you want the code I have it. From paul at boddie.org.uk Tue May 20 17:17:47 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Tue, 20 May 2008 14:17:47 -0700 (PDT) Subject: self.var hmm? References: <4f28a341-8f27-4e07-8940-57ae2d09c0df@q27g2000prf.googlegroups.com> Message-ID: On 20 Mai, 22:58, notnorweg... at yahoo.se wrote: > class TaskGroup: > def __init__(self): > self.group = [] > > def addTask(self, task): > self.group.append(task) > > is this wrong? i have a program thats too big to post but should i > just do group.append in addTask? No, you have to do self.group.append, since group isn't a local variable in the addTask method, and I doubt that you'd want addTask to make changes to any global variable called group, which is what might happen otherwise - that could be a source of potential problems, so you need to be aware of that! > reason is when later doing TaskGroup.group i get None TaskGroup.group would be referencing a class attribute called group, which is "shared" by all TaskGroup instances (and the TaskGroup class itself, of course). What you need to do is to access the instance attribute called group via each instance, and the self.group notation does exactly that: self is the reference to a particular instance (in the addTask method, it's the instance used to call the addTask method). You might wonder why Python doesn't know inside a method that group is a reference to an instance attribute of that name. The reason, somewhat simplified, is that Python only has assignments to populate namespaces (such as the contents of an instance), whereas languages which employ declarations (such as Java) would have you list the instance attributes up front. In these other languages, the compiler/ interpreter would know that you're executing a method belonging to an instance of a particular class, and it would also know what names to expect as references to class and instance attributes. Anyway, I hope this makes more sense now than it did a few moments ago. :-) Paul From pistacchio at gmail.com Mon May 12 04:10:00 2008 From: pistacchio at gmail.com (pistacchio) Date: Mon, 12 May 2008 01:10:00 -0700 (PDT) Subject: module global variables References: Message-ID: On 12 Mag, 10:01, alex23 wrote: > On May 12, 5:17 pm, pistacchio wrote: > > > hi to all! > > can i load a module passing to it, automatically and as default, all > > the caller's global variables to act as module's global variables? > > thanks > > module = __import__('module', globals=globals()) > > I think that's what you're looking for. > > - alex23 hmm, well, maybe yes.. should i ovveride the standard import function of the module? say that the module is called "pycatrix", would adding this to the module solve the problem? def __import__('pycatrix', globals=globals()): From gherron at islandtraining.com Tue May 27 13:31:40 2008 From: gherron at islandtraining.com (Gary Herron) Date: Tue, 27 May 2008 10:31:40 -0700 Subject: New chairman In-Reply-To: References: <3720fb99-ac37-469b-b8ce-ece3ed27b8e5@m36g2000hse.googlegroups.com> Message-ID: <483C457C.4060006@islandtraining.com> Max M wrote: > Sverker Nilsson skrev: >> I was talking about Guido van Rossum >> >> The one who decides, so far when people agree > > I have been using Python since the nineties. I cannot remember when I > have had to rewrite old code because of changes in the language. > > At the same time I have been feeling as if I was sitting in a time > machine watching other languages whoosh by at breakneck speed. > > Entire technologies have been developed to make programming as > practical and easy as it has been in Python the entire time. > > So I find it hard to see exactly what it is that Guido is doing wrong? > Please don't feed the trolls. (http://en.wikipedia.org/wiki/Internet_troll#Troll_FAQs) From johnjsal at NOSPAMgmail.com Mon May 19 23:54:24 2008 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 19 May 2008 23:54:24 -0400 Subject: How do *you* use Python in non-GUI work? References: <20080518182022.990193bd.johnjsal@NOSPAMgmail.com> <6fb308f2-a5be-4641-aa04-561b1782c6bb@z72g2000hsb.googlegroups.com> <20080518202516.e858910c.johnjsal@NOSPAMgmail.com> <3b0ba35b-c2b9-4ab2-8e7c-fecebce465c2@d77g2000hsb.googlegroups.com> Message-ID: <20080519235424.8addcf12.johnjsal@NOSPAMgmail.com> On Sun, 18 May 2008 23:08:11 -0700 (PDT) s0suk3 at gmail.com wrote: > Every now and then, however, I do build some interface (mostly GUI), > such as a monitor, notification mechanism, etc. But I never feel like > I'm losing focus on the actual problem; maybe because I develop the > core program first and the think about a possible and optional > interface. Maybe a good suggestion is to put the GUI stuff on another > module or package, and make interface functions or methods to handle > the needed GUI controls, so that the GUI stuff shows up as little as > possible in the core part of the program. I certainly don't *not* like GUI programming. In fact, learning wxPython was really fun and interesting and I enjoy GUI stuff. And after learning about XRC (putting the GUI component in a separate XML file, away from the program logic) that helped me learn how to keep things separate as well. I even wrote a tutorial on how to use XRC with wxPython! :) From castironpi at gmail.com Thu May 15 19:56:42 2008 From: castironpi at gmail.com (castironpi) Date: Thu, 15 May 2008 16:56:42 -0700 (PDT) Subject: Using file objects with elementtree References: <5dca8f2f-ba08-4cf6-9d45-da2b2e532af8@x35g2000hsb.googlegroups.com> <69184aF2tsmnaU1@mid.uni-berlin.de> <482C7D93.2080809@behnel.de> Message-ID: <67e6826f-e90d-4f4f-bed8-7e3dd0003942@l64g2000hse.googlegroups.com> On May 15, 1:14?pm, Stefan Behnel wrote: > castiro... at gmail.com wrote: > > What do we render? > > Sur. > > Stefan I'm pretty sure 'inputs' come from the real world. I guess the fear would be my hands aren't happy. Concerns include age fitity, a propriety, and making up words. Blah? From nick at craig-wood.com Tue May 6 17:30:03 2008 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 06 May 2008 16:30:03 -0500 Subject: Newbie question - probably FAQ (but not exactly answered by regular FAQ) References: <482010d3$0$12566$426a74cc@news.free.fr> Message-ID: Banibrata Dutta wrote: > As such 2.6 & 3.0 are also cooking, but from what I see on the mailing > list, some of the features are a bit controversial. So if I start with > 2.5 now, unless there are some break-thru preformance gains, or > annoying defects fixed, I'd stick to it. If I can do something > "well-enough" with 2.5, I'd not refactor for 2.6, for quite some > fore-seeable future. I started programming with python at version 2.0 so I've seen it evolve over the years. In case you are interested here are some links to what has changed from the different versions over the years. 2.0: http://www.amk.ca/python/2.0/ 2.1: http://www.amk.ca/python/2.1/ 2.2: http://www.python.org/doc/2.2.3/whatsnew/ 2.3: http://www.python.org/doc/2.3/whatsnew/ 2.4: http://www.python.org/doc/2.4.3/whatsnew/whatsnew24.html 2.5: http://docs.python.org/whatsnew/whatsnew25.html 2.5: http://docs.python.org/dev/whatsnew/2.6.html I personally wouldn't like to use older than 2.2 any more. I find new style classes, iterators and generators to be invaluable. Features I like from 2.3's are enumerate, csv and datetime modules. And from 2.4 I like the subprocess module (though it runs on 2.3 just fine too - it just isn't included). I have occasionally used the decorator syntax, but since it is syntactic sugar anyway it isn't absolutely necessary. In 2.5 has ctypes which is great though it is available as a 3rd party module for 2.3 and 2.4. As is sqlite3. So in my opinion the real difference between the 2.2, 2.3, 2.4 and 2.5 are the built in modules. The actual language changes are very minor. If you write your code for 2.5 which is probably a good idea, you'll have no problem backporting it to 2.4, 2.3 or even 2.2 should that be necessary. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From gherron at islandtraining.com Wed May 7 15:41:17 2008 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 07 May 2008 12:41:17 -0700 Subject: Idea for P3K In-Reply-To: <4821fea4$0$880$ba4acef3@news.orange.fr> References: <4821d418$0$932$ba4acef3@news.orange.fr> <4821fea4$0$880$ba4acef3@news.orange.fr> Message-ID: <482205DD.90506@islandtraining.com> M?ta-MCI (MVP) wrote: > Hi! > >> I don't often feel like using this word > > Look at languages like OCAML or F # > > @-salutations Well of course, we're all well aware of other languages that allow variables to be bound in the middle of an expression. It's just that Python was purposely created without that (mis)feature because it's so unclear, and easy to abuse. Most of us in the community support that point of view and would fight the introduction of such a feature into Python. Gary Herron From martin at v.loewis.de Sun May 25 11:01:33 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 25 May 2008 17:01:33 +0200 Subject: need some help in serving static files inside a wsgi apps In-Reply-To: <4ob*BLLds@news.chiark.greenend.org.uk> References: <6e15240b-520d-4f01-9d21-83f9feeefc2d@x41g2000hsb.googlegroups.com> <69r113F34rbeeU1@mid.uni-berlin.de> <69t1m5F33b3ncU2@mid.uni-berlin.de> <4ob*BLLds@news.chiark.greenend.org.uk> Message-ID: <48397F4D.8040009@v.loewis.de> >>> I guess, Apache does some kind of memory caching for files, which are often >>> requested and small enough to fit into the system memory. May be, that's >>> what the OP is referring to ... > >> I'm not aware of that, and I even more seriously doubt it. Because >> caching is a complicated, domain-dependend subject that would >> *immediately* cry for configuration - e.g. caching strategies and such. > > This is available in current apache with mod_file_cache (for an > explicitly configured list of files). I think the circumstances where > you'd want to use it are quite rare. Interestingly enough, this *doesn't* do memory caching for files. Instead, it either keeps the file handle open, so you can seek to the beginning of the file on the next request (avoiding the directory lookup), or you can mmap the file. However, even if you mmap the file, it is still the operating system's choice whether or not to cache the file contents in memory. Regards, Martin From paul at boddie.org.uk Mon May 5 18:47:32 2008 From: paul at boddie.org.uk (Paul Boddie) Date: Mon, 5 May 2008 15:47:32 -0700 (PDT) Subject: ]ANN[ Vellum 0.16: Lots Of Documentation and Watching References: <3a8e0a8f-3bd1-4650-9104-5c273f14b097@w7g2000hsa.googlegroups.com> <1w4gs9bk.fsf@gmail.com> Message-ID: <803a75aa-9de6-45e5-bb0a-a2512f8bdd32@m36g2000hse.googlegroups.com> On 5 Mai, 23:57, vivai... at gmail.com (Ville M. Vainio) wrote: > Paul Boddie writes: > > Anyway, I'm just confirming that I'm clearly not one of the "many" > > described above. A lot of my own work is licensed under the GPL or > > I guess it's safe to assume that you are not opposed to using code > based on more liberal license, right? :-) As long as it's a GPL-compatible licence. ;-) > My point is: GPL is a reason to reject a tool for some, but MIT/BSD > never is. Ultimately, of course, it's up to the preferences of the > author but if the idea is to maximize the popularity, GPL is a worse > bet. I know you were talking about small tools, but since we're being jocular, I still can't resist the obligatory "tell it to Linus Torvalds" remark. :-) Paul P.S. I've actually released at least one work derived from a permissively licensed work under the LGPL (and I did ask the original author if he had any problems with that, out of politeness), mostly because I didn't object to people building applications under a wider range of licences, but I did want end-users to get the benefit of the library source code, including any modifications. From larry.bates at websafe.com` Thu May 29 21:27:35 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Thu, 29 May 2008 20:27:35 -0500 Subject: Help needed in choosing an algorithm for Cryptographic services. In-Reply-To: References: Message-ID: abhishek wrote: > Hi group, recently my employer asked me too implement encryption/ > decryption for secure data transfer over internet. Problem is that the > client application is written using C# and the webserver where i need > to store the information is developed using python. > > My situation of dilemma is which cryptographic method suits me best > for this purpose. > > Help/Suggestions are urgently required > > Thank you , > Abhishek Languages don't have anything to do with "what is best method". It depends on your application requirements. If all you want is secure data "transfer" just use SSL to encrypt the information while being transmitted. If you wish to have the data "stored encrypted" look into PGP. -Larry From deets at nospam.web.de Wed May 21 14:52:03 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 21 May 2008 20:52:03 +0200 Subject: Bug in floating-point addition: is anyone else seeing this? In-Reply-To: References: Message-ID: <69j9b6F33ckopU1@mid.uni-berlin.de> Mark Dickinson schrieb: > On SuSE 10.2/Xeon there seems to be a rounding bug for > floating-point addition: > > dickinsm at weyl:~> python > Python 2.5 (r25:51908, May 25 2007, 16:14:04) > [GCC 4.1.2 20061115 (prerelease) (SUSE Linux)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> a = 1e16-2. >>>> a > 9999999999999998.0 >>>> a+0.999 # gives expected result > 9999999999999998.0 >>>> a+0.9999 # doesn't round correctly. > 10000000000000000.0 > > The last result here should be 9999999999999998.0, > not 10000000000000000.0. Is anyone else seeing this > bug, or is it just a quirk of my system? It is working under OSX: (TG1044)mac-dir:~/projects/artnology/Van_Abbe_RMS/Van-Abbe-RMS deets$ python Python 2.5.1 (r251:54869, Apr 18 2007, 22:08:04) [GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin Type "help", "copyright", "credits" or "license" for more information. Welcome to rlcompleter2 0.96 for nice experiences hit multiple times >>> a = 1e16-2. >>> a 9999999999999998.0 >>> a+0.9999 9999999999999998.0 >>> But under linux, I get the same behavior: Python 2.5.1 (r251:54863, May 2 2007, 16:56:35) [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. Welcome to rlcompleter2 0.96 for nice experiences hit multiple times >>> a = 1e16-2. >>> a+0.9999 10000000000000000.0 >>> So - seems to me it's a linux-thing. I don't know enough about IEEE-floats to make any assumptions on the reasons for that. Diez From johnjsal at NOSPAMgmail.com Mon May 19 23:48:03 2008 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 19 May 2008 23:48:03 -0400 Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <2b66a86e-5a05-4262-b3c9-4703b0ae3372@d1g2000hsg.googlegroups.com> <5b0e3f70-afde-4480-8713-e7113b1250d7@x35g2000hsb.googlegroups.com> <1f537717-00d0-48ee-99b6-7125b96a6133@t12g2000prg.googlegroups.com> <68t4o0F2vaoncU1@mid.uni-berlin.de> <2a32179a-9439-449c-bd07-fff6a4075aee@s50g2000hsb.googlegroups.com> <7ee5dffd-df8f-46f0-bd78-c81ac0418a9a@d77g2000hsb.googlegroups.com> <65ef773e-a1c3-4adb-a18b-e8b8451efe5e@b5g2000pri.googlegroups.com> <20080514223033.0ec9fff0.johnjsal@NOSPAMgmail.com> <3650313b-fe8d-4beb-bfbd-2748757233e2@p25g2000pri.googlegroups.com> Message-ID: <20080519234803.5734b65f.johnjsal@NOSPAMgmail.com> On Mon, 19 May 2008 20:20:28 -0700 (PDT) Dave Parker wrote: > To whit: you pointed out the awkwardness in Python of having to > declare a for-loop variable when you only wanted to loop a specific > number of times and didn't need the variable. Well, I wasn't so much trying to point out an awkwardness as I was asking if anyone really *found* it awkward. And of course, my question also raises the question of whether or not it's good programming to simply want to do something a certain number of times. I suppose that situation may come up, but I wonder if it can be implemented in a more significant way than simply doing something X number of times. From matt at tplus1.com Mon May 12 12:10:21 2008 From: matt at tplus1.com (Matthew Wilson) Date: Mon, 12 May 2008 16:10:21 GMT Subject: In metaclass, when to use __new__ vs. __init__? Message-ID: I have been experimenting with metaclasses lately. It seems possible to define a metaclass by either subclassing type and then either redefining __init__ or __new__. Here's the signature for __init__: def __init__(cls, name, bases, d): and here's __new__: def __new__(meta, classname, bases, d): Every metaclass I have found monkeys with d, which is available in both methods. So when is it better to use one vs the other? Thanks for the help. Matt -- Programming, life in Cleveland, growing vegetables, other stuff. http://blog.tplus1.com From gagsl-py2 at yahoo.com.ar Mon May 19 09:21:56 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 19 May 2008 10:21:56 -0300 Subject: python script to windows exe References: <4541e631-d38a-4047-b578-bd9afdde0af8@s50g2000hsb.googlegroups.com> <9951d859-330f-4a7a-a869-df73cdce5f67@m44g2000hsc.googlegroups.com> Message-ID: En Mon, 19 May 2008 06:59:22 -0300, sandeep escribi?: > the py code that i have written is here.when i run this code i wont > get any errors it just works fine for me.but when i created the exe i > start getting an error in my 'getMailContent' function. The error > description is > > TypeError:unsupported operand type(s) for :- 'instance' and 'int' > > i dont know why i am start getting this error when i run it through > the exe. By example, your code uses os.getcwd() - so it depends on the current dir. Try running it from a different directory. Don't focus too much on the ".exe" vs ".py" difference: it might not be relevant, the error may reside elsewhere. Please post the complete exception message *and* traceback. Don't retype it; copy and paste the message from the console. Your message above doesn't appear to be correctly typed, it says `:-` but Python would print `-:` and I don't see any `-` operation in your code that could fail in that way. Also, don't do this: > try: > mailItem.SaveAs(path+name+".txt",OlSaveAsType['olTXT']) > except BaseException: > print BaseException because you're completely hiding important information about *what* happened. -- Gabriel Genellina From jon at ffconsultancy.com Thu May 1 12:50:32 2008 From: jon at ffconsultancy.com (Jon Harrop) Date: Thu, 01 May 2008 17:50:32 +0100 Subject: pop langs website ranking References: <41fbaf27-a80b-402b-b406-c048a65a8643@b64g2000hsa.googlegroups.com> <2819d214-1208-4552-9b59-122e980e01d4@t12g2000prg.googlegroups.com> Message-ID: xahlee at gmail.com wrote: > Alexa's data is more reliable than quantcast. Alexa claim to have accurate data on lots of sites but I just tried to correlate their data with the exact data on our web server and the discrepancies are huge. For example, combining our number of absolute visitors with their measure of "reach" for our site indicates that there are 58 billion internet users. So their data are not even order-of-magnitude accurate. The only web analyst I ever met was an astrophysicist so this does not really surprise me. ;-) -- Dr Jon D Harrop, Flying Frog Consultancy http://www.ffconsultancy.com/products/?u From manthra.mohan at gmail.com Thu May 1 15:06:07 2008 From: manthra.mohan at gmail.com (Krishna) Date: Thu, 1 May 2008 12:06:07 -0700 (PDT) Subject: data manipulation Message-ID: <083cef9c-6bfe-4a1f-afc0-7384c043dc6d@u12g2000prd.googlegroups.com> I have a script that reads an excel file and and do manipulations on it. But, now, I have a text file that needs the same manipulation. I tried the same script, but it will not work, when I use command such as: workbook = xlrd.open_workbook('C:/trial.txt'), its giving me errors saying "expected BOF record". I was wondering how to work around this. Do I have to do some format conversion to accomplish this or am I missing something Thanks Krishna From Caseyweb at gmail.com Fri May 9 19:45:09 2008 From: Caseyweb at gmail.com (Casey) Date: Fri, 9 May 2008 16:45:09 -0700 (PDT) Subject: Problem with help() in python/ipython interpreters Message-ID: <62818f52-025a-48b1-b451-70abae1e6580@a23g2000hsc.googlegroups.com> I'm running python 2.5.2 on WinXP. I've always used a GUI for interactive development, but I wanted to try out ipython which better supports matplotlib in this mode. Unfortunately, whenever I try to use help() I get the following error: (Sys) The system cannot find the file specified. "C:\documents" It turns out that the regular (python.exe) interpreter has the same problem. I have the HTML docs installed, my PYTHONDOCS environment variable points to the HTML directory, and I actually uninstalled and reinstalled every library I use from scratch to make sure it wasn't some random config issue. The error message leads me to believe that the help() function is trying to access something in my windows user directory structure (C: \Documents and Settings\\...) and is having problems with the embedded space. The really strange thing is that my python directory is rooted at c:\python25 including my html docs. I know that ipython does by default create a profile directory in %HOME%\_ipython but that doesn't seem to be a problem and wouldn't impact the default python.exe interpreter. Any ideas? From dannywebster at googlemail.com Tue May 13 07:14:16 2008 From: dannywebster at googlemail.com (dannywebster at googlemail.com) Date: Tue, 13 May 2008 04:14:16 -0700 (PDT) Subject: Best way to delimit a list? References: <57129f75-b496-40fc-8b2d-d93ba544d4c5@u6g2000prc.googlegroups.com> Message-ID: On May 13, 11:51 am, "Gabriel Genellina" wrote: > > You meant readlines(), I presume. A file acts as its own iterator: > > f=os.open("./get_hostnames") > try: > for line in f: > # do something with line > finally: > f.close() > > -- > Gabriel Genellina Hi - thank you for your reply. I meant: f=os.popen("./get_hostnames").readlines() So f is a list, rather than a file object, of which os.open would have returned (my initial typo redirected the missive of this post, sorry!) cheers From kyosohma at gmail.com Fri May 16 09:15:41 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Fri, 16 May 2008 06:15:41 -0700 (PDT) Subject: Problem creating a shorcut References: <2715b502-d636-4541-ac0e-05697f02b2ae@m44g2000hsc.googlegroups.com> <322a200a-ed9a-44d2-b5ea-5f059884b53a@27g2000hsf.googlegroups.com> Message-ID: <826cf534-a674-4861-8d60-5f6a4be30125@d77g2000hsb.googlegroups.com> On May 16, 1:51?am, Chris wrote: > On May 15, 5:13?pm, Mike Driscoll wrote: > > > > > Hi, > > > I've had this niggling issue from time to time. I want to create a > > shortcut on the user's desktop to a website that specifically loads > > Firefox even if Firefox is not the default browser. > > > I usually use COM as it allows very specific settings of the shortcut, > > such as the Working Directory and the Target Path. However, the > > following will not work for some reason: > > > > > > import win32com.client > > import winshell > > > shell = win32com.client.Dispatch('WScript.Shell') > > userDesktop = winshell.desktop() > > > shortcut = shell.CreateShortCut(userDesktop + '\\MyShortcut.lnk') > > shortcut.Targetpath = r'"C:\Program Files\Mozilla Firefox\firefox.exe" > > https:\www.myCompanyWebsite.com\auth\preauth.php' > > shortcut.WorkingDirectory = r'C:\Program Files\Mozilla > > Firefox' > > shortcut.save() > > > > > > This creates the following target path (which doesn't work): > > > "C:\"C:\Program Files\Mozilla Firefox\firefox.exe" https: > > \www.myCompanyWebsite.com\auth\preauth.php" > > > If I leave the website off, it works. If I leave the path to Firefox > > out, it works too. Is there another method I can use other than > > creating the shortcut by hand and using the shutil module? > > > Thank you for any ideas. > > > Mike > > Don't set arguments in the path. > > shortcut = shell.CreateShortCut(userDesktop + '\\MyShortcut.lnk') > shortcut.TargetPath = r'Program Files\Mozilla Firefox\firefox.exe' > shortcut.Arguments = r'https:\www.myCompanyWebsite.com\auth > \preauth.php' > shortcut.WorkingDirectory = r'C:\Program Files\Mozilla Firefox' > shortcut.save() Ah. I was unaware of the Arguments parameter. That works quite well. Where does one find this information anyway? I think I found mine from bits and pieces scattered in various tutorials. Thanks a lot. Mike From patrickstinson.lists at gmail.com Mon May 26 15:17:38 2008 From: patrickstinson.lists at gmail.com (Patrick Stinson) Date: Mon, 26 May 2008 11:17:38 -0800 Subject: definition of a highlevel language? In-Reply-To: <34dcbdc1-5285-41ec-be06-c88c56bb0372@i76g2000hsf.googlegroups.com> References: <2759eed3-956d-45c7-8dfb-9557f74133b3@56g2000hsm.googlegroups.com> <26d0b3d2-01cc-49bd-b284-1a849b0b835f@y38g2000hsy.googlegroups.com> <34dcbdc1-5285-41ec-be06-c88c56bb0372@i76g2000hsf.googlegroups.com> Message-ID: <6214d7a20805261217x14021c2bx643a07166d69ac9c@mail.gmail.com> The way I think of it is that a language is commonly referred to by the implementation of syntax and semantics. The implementation is defined by a processable medium, for example 1) punch cards, 2) processor-specific code, or 3) some processor code interpreting some other code. Examples include: 1) I'm too young to know :) 2) common low-level language like C 3) common high-level like python ikke norska? kvorfor ikkje? itne? hva for noke? On Mon, May 26, 2008 at 11:02 AM, wrote: > On 26 Maj, 20:57, miller.pau... at gmail.com wrote: > > On May 26, 2:34 pm, notnorweg... at yahoo.se wrote: > > > > I wanted to address some other points I failed to mention in my first > > response. > > > > > so are they fundamentally differently built or is it just a lot of > > > lowlevel operations built on top of each other? > > > > Partly. A high-level language is essentially one that gives you high- > > level operations, like "apply the function f to each element of the > > sequence seq, and return [f(seq[0]), f(seq[1]), ... f(seq[n])]. > > > > But, it's more than that. (You use Haskell as your example, but I'll > > use Python because I know it roughly a million percent better than > > Haskell... hehe.) In Python, you have support from the language to > > treat functions as first-class objects; in C, you explicitly cannot do > > this -- to map an arbitrary function over a sequence, you're > > restricted to accessing the function through a pointer. On the > > surface, it's the same operation, but that extra level of indirection > > can really bog one's mind down. Think about how difficult it is for a > > human to interpret the declaration of a function pointer in C, for > > instance. > > > > > haskell is considered a very highlevellanguage but can you do > > > systemsprogramming with it(yes maybe it is very unpractical i dont > > > know but can you)? > > > is lambda calculus a more abstract and efficient way of modeling a > > > computer? > > > > Lambda calculus doesn't model computers. It models *computation*. > > That is, given a Turing machine, there's a set of functions in the > > lambda calculus, which, when suitably combined, will yield the exact > > same result as the original Turing machine. That doesn't in any way > > imply that Turing machines work by interpreting lambda calculus. > > > > > how did lispmachines work? was the basic system programmed in LISP? > > > > Yes, the whole kit and kaboodle, all the way down to the microcode was > > programmed in LISP. In principle, there's no reason we couldn't have > > Haskell machines or Python machines. It's just that nobody's been > > crazy enough to do it, that I know of. :-) > > > what is crazy about it? > > in the same way programming webapps in C would be annoying because you > have to do a lot of lowlevel tasks it is dumb to program computer ina > highlevellanguage because you dont have direct access to lowlevel > tasks meaning you cant program it very efficiently, ie make it fast? > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at v.loewis.de Sun May 25 16:15:56 2008 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 25 May 2008 22:15:56 +0200 Subject: 22.800000 and a 1 on the end!!?? In-Reply-To: References: Message-ID: <4839C8FC.2020408@v.loewis.de> > ok where does the 1 in the come from? http://www.python.org/doc/faq/general/#why-are-floating-point-calculations-so-inaccurate Regards, Martin From ivlenin at gmail.com Sun May 25 22:51:15 2008 From: ivlenin at gmail.com (I V) Date: Mon, 26 May 2008 02:51:15 GMT Subject: php vs python References: <5l%Yj.77$mz3.53@fe101.usenetserver.com> <37b112d8-a3ba-446d-9d2f-d907d93c637b@w8g2000prd.googlegroups.com> <-t-dnWQ4bZN2MaTVnZ2dnUVZ_qGdnZ2d@comcast.com> <68cb8bb1-4cc5-4a28-8915-46e7d4e316d9@d1g2000hsg.googlegroups.com> <9IWdnbyQq5GKl6fVnZ2dnUVZ_oGdnZ2d@comcast.com> Message-ID: On Sun, 25 May 2008 21:41:09 -0400, Jerry Stuckle wrote: > The the good programmers are able to adapt to the language and make the > most of whatever language they're using. The result is good code. OTOH, > poor programmers I have known have found all kinds of excuses - from the > language itself to lack of requirements, to anything else they can > blame, except the real root of the problem. That's true - but I wonder if there might not be differences at the margins. Some languages (and, which is not quite the same but not easy to fully distinguish either, the communities around some languages) may encourage mediocre programmers to produce slightly more or less mediocre programs. Some features of Python (the one that really stands out for me is not default-initializing variables on first use; the comparatively clean standard library might be another), and some features of the Python community (which, IME, has more members more explicitly committed to writing clean code) I think do make Python a better environment for us mediocre programmers. But maybe I'm wrong - I've never been paid to write Python programs, whereas I have been paid to write PHP, so I might just be projecting my frustrations with work onto the language. I've also not used PHP5 much in anger, which does look to be a lot nicer than earlier versions. From arne at vajhoej.dk Fri May 30 21:35:47 2008 From: arne at vajhoej.dk (=?ISO-8859-1?Q?Arne_Vajh=F8j?=) Date: Fri, 30 May 2008 21:35:47 -0400 Subject: The Importance of Terminology's Quality In-Reply-To: References: Message-ID: <4840ab73$0$90274$14726298@news.sunsite.dk> Stephan Bour wrote: > Lew wrote: > } John Thingstad wrote: > } > Perl is solidly based in the UNIX world on awk, sed, bash and C. > } > I don't like the style, but many do. > } > } Please exclude the Java newsgroups from this discussion. > > Did it ever occur to you that you don't speak for entire news groups? Did it occur to you that there are nothing about Java in the above ? Arne From fuzzyman at gmail.com Sun May 25 08:11:18 2008 From: fuzzyman at gmail.com (Fuzzyman) Date: Sun, 25 May 2008 05:11:18 -0700 (PDT) Subject: Why does python not have a mechanism for data hiding? References: <52ba2118-d095-48a6-8844-2ee4c2ec2be1@m36g2000hse.googlegroups.com> <8763t3by81.fsf@benfinney.id.au> <5ea78616-e955-4ee0-8e60-a22734ec31be@79g2000hsk.googlegroups.com> <87prrbk85x.fsf@gmail.com> <87tzgm3h4q.fsf@gmail.com> Message-ID: On May 25, 9:47?am, vivai... at gmail.com (Ville M. Vainio) wrote: > Fuzzyman writes: > >> Perhaps a lint-like validation tool would be optimal for this > >> problem... > > > So we can refuse to execute their code if they use private APIs? > > No, but it could complain and point out the exact offending lines, > pointing their development effort to right direction. > > > Proxying so that we can really hide our internal APIs is a better > > solution. > > How about pyprotocols and other interface packages? > We're using IronPython. I haven't looked at pyprotocols but I know the Zope interface package is at least partly written in C. Our spreadsheet object model is very 'performance sensitive', so that's a consideration. We should definitely explore the prior art in this area before we implement anything ourselves. Thanks Michael Foord http://www.ironpythoninaction.com/ > Proxying is pretty workable too, and it easily makes sense that the > official API objects should be different from the logic executing > objects. From woodygar at sky.com Sat May 24 14:32:56 2008 From: woodygar at sky.com (garywood) Date: Sat, 24 May 2008 19:32:56 +0100 Subject: for some reason the actual tries figure is not right Message-ID: <002301c8bdcc$979ce8c0$1300a8c0@Home> can someone explain why the tries displays the wrong number thanks orginally i started off with tries = 0 but it was off by 2 # Word Jumble # # The computer picks a random word # The player has to guess the original word can give hint import random tries = 1 # create a sequence of words to choose from word = ("python", "jumble", "xylophone", "difficult", "answer") # pick one word randomly from the sequence word = random.choice(word) # create a variable to use later to see if the guess is correct correct = word # start the game print \ """ Welcome to Word Jumble! (Press the enter key at the prompt to quit.) """ if word == "python": hint = 'snake' if word == "jumble": hint = 'mess' if word == "difficult": hint = 'hard' if word == "answer": hint = 'correct' if word == "xylophone": hint = 'music' guess = raw_input("\nYour guess: ") guess = guess.lower() while (guess != correct) and (guess != ""): print "Sorry, that's not it." + hint guess = raw_input("Your guess: ") guess = guess.lower() if guess != correct: print hint tries += 1 if guess == correct: print "That's it! You guessed it!\n" print "Thanks for playing." print tries raw_input("\n\nPress the enter key to exit.") -------------- next part -------------- An HTML attachment was scrubbed... URL: From usenet at janc.be Fri May 16 18:03:22 2008 From: usenet at janc.be (Jan Claeys) Date: Fri, 16 May 2008 22:03:22 GMT Subject: downloading a link with javascript in it.. References: <5358bfb4-f79a-4575-98b8-9a85ba41652d@d45g2000hsc.googlegroups.com> <68rmafF2t1vboU1@mid.uni-berlin.de> Message-ID: Op Mon, 12 May 2008 22:06:28 +0200, schreef Diez B. Roggisch: > There is no way to interpret the JS in Python, There is at least one way: -- JanC From sposnjak at gmail.com Mon May 5 10:30:37 2008 From: sposnjak at gmail.com (Simon Posnjak) Date: Mon, 5 May 2008 16:30:37 +0200 Subject: How to convert unicode string to unsigned char * In-Reply-To: <20080505141651.6859.554247783.divmod.quotient.59048@ohm> References: <725404980805050705t24557608v9de541d1bcea546d@mail.gmail.com> <20080505141651.6859.554247783.divmod.quotient.59048@ohm> Message-ID: <725404980805050730n1efe320fpf03dec3735fc1875@mail.gmail.com> On Mon, May 5, 2008 at 4:16 PM, Jean-Paul Calderone wrote: > > On Mon, 5 May 2008 16:05:08 +0200, Simon Posnjak wrote: > > > On Mon, May 5, 2008 at 3:48 PM, Jean-Paul Calderone > wrote: > > > > > On Mon, 5 May 2008 15:41:08 +0200, Simon Posnjak > wrote: > > > > > > > Hi! > > > > > > > > I have a C module for which I created a wrapper with swig. The > function > > > def is: > > > > > > > > C: > > > > > > > > int some_thing(unsigned char * the_str); > > > > > > > > eg: > > > > > > > > Python: > > > > > > > > some_module.some_thing (the_str) > > > > > > > > Now I would like to feed it with a UTF-8 formatted string: > > > > > > > > test = u'Make \u0633\u0644\u0627\u0645, not war.' > > > > > > > > > > `test? is not a UTF-8 encoded string. It's a unicode string. > > > > > > To get a UTF-8 encoded string from a unicode string, use the `encode? > > > method: > > > > > > some_module.some_thing(test.encode('utf-8')) > > > > > > > Yes you are correct. It is unicode string. But still if I use encode I > > get the same error: > > > > TypeError with message: in method 'some_thing', argument 1 of type > > 'unsigned char *' > > > > So I am looking for a way to "cast" unicode string to unsigned char *. > > > > > > You need to provide some more information about `some_module.some_thing?. > How is it implemented? What Python type does it expect? If it doesn't > take a unicode string and it doesn't take a byte string, I don't know > what kind of string it does take. some_module.some_thing(the_string) function is a swig generated function from a C lib. The C lib function expects unsigned char *. The generated function is: SWIGINTERN PyObject *_wrap_some_thing(PyObject *SWIGUNUSEDPARM(self), PyObject *args) { PyObject *resultobj = 0; unsigned char *arg1 = (unsigned char *) 0 ; unsigned char result; void *argp1 = 0 ; int res1 = 0 ; PyObject * obj0 = 0 ; if (!PyArg_ParseTuple(args,(char *)"O:cpot_printer_simple_printf",&obj0)) SWIG_fail; res1 = SWIG_ConvertPtr(obj0, &argp1,SWIGTYPE_p_unsigned_char, 0 | 0 ); if (!SWIG_IsOK(res1)) { SWIG_exception_fail(SWIG_ArgError(res1), "in method '" some_thing"" "', argument " "1"" of type '" "unsigned char *""'"); } arg1 = (unsigned char *)(argp1); result = (unsigned char)some_thing(arg1); resultobj = SWIG_From_unsigned_SS_char((unsigned char)(result)); return resultobj; fail: return NULL; } From venkat83 at gmail.com Fri May 16 07:22:17 2008 From: venkat83 at gmail.com (Venkatraman.S.) Date: Fri, 16 May 2008 04:22:17 -0700 (PDT) Subject: managing properties/configurations References: <408a6c83-8869-4c76-9acf-48cd42075658@y22g2000prd.googlegroups.com> <9976ee1f-1d37-4252-802a-8dd3c3de7d3d@k1g2000prb.googlegroups.com> Message-ID: <1ff9bbaa-ae04-495a-a9a3-d2f7741e6cc5@k10g2000prm.googlegroups.com> On May 16, 7:45 am, "A.T.Hofkamp" wrote: Thanks > By picking better names, the config gets much more readable. > > The big advantage here is that a config file is something readable and editable > without appearing it to be Python. > If this is too low level for your users, you can use it as a data exchange > format between the processing application and the frontend application where > users can change the values. The problem being, if i change the config file, then the configobj has to reload this file again. I do not want to 'refresh' the config obj per transaction but only when the config params change. > > Now when i 'manually' make some changes to the value of a,b,c,d then > > the the checkCutoff func should refer to the new values. > > Maybe reload the file each time you run the program? The program is never-ending and do not think in terms of websites here - probably something like a server/middleware which can never be brought down. I was thinking along the terms of an Interrupt driven program, which when getting a custom interrupts reloads the file - any potential loopholes/falls that anyone can anticipate? Regards, Venkat From cshirky at gmail.com Mon May 12 14:30:52 2008 From: cshirky at gmail.com (cshirky) Date: Mon, 12 May 2008 11:30:52 -0700 (PDT) Subject: buffering choking sys.stdin.readlines() ? References: <68r63qF2s4ksaU1@mid.uni-berlin.de> Message-ID: <819bdd3b-ec6b-41a5-99ab-ac85f08b99a7@8g2000hse.googlegroups.com> > readlines() reads all of the file into the memory. Try using xreadlines, > the generator-version, instead. And I'm not 100% sure, but I *think* doing > > for line in sys.stdin both work -- many thanks. -clay From larzluv at hotmail.com Mon May 12 03:14:51 2008 From: larzluv at hotmail.com (Larry Hale) Date: Mon, 12 May 2008 00:14:51 -0700 (PDT) Subject: Module python-magic on/for Windows? References: <3a66adfe-3fd6-4f23-a6e8-4b219db1a3cd@x41g2000hsb.googlegroups.com> <2eb6f620-4aca-469e-9cdd-d6b0174da41e@8g2000hse.googlegroups.com> Message-ID: <18b87c2b-742d-458f-aee0-404249547baf@l42g2000hsc.googlegroups.com> On May 12, 1:34 am, Larry Hale wrote: > The file source (previously linked from http://hupp.org/adam/hg/python-magic/) > has the man pages... Err... I meant "http://downloads.sourceforge.net/gnuwin32/file-4.21- bin.zip?modtime=1180175868&big_mirror=1"! :) From skanemupp at yahoo.se Tue May 13 14:20:35 2008 From: skanemupp at yahoo.se (globalrev) Date: Tue, 13 May 2008 11:20:35 -0700 (PDT) Subject: usage of python References: Message-ID: On 13 Maj, 19:10, Rajarshi wrote: > Hi, I teach an introductory programming course in Python. As part of > the introduction I'd like to highlight the usage of Python in > industry. The idea is to show that there are big players using Python > for a variety of tasks. Given that the students come from a variety of > backgrounds and are not necessarily 'hackers', I'm trying to look for > examples with a bit of wow-factor. > > Is there any list with people/groups/companies using Python for > impressive things? > > Any pointers would be appreciated > > Thanks, > Rajarshi nasa, google, industrial light and magic(starwars second trilogy) , astra zeneca, reddit. From lists at cheimes.de Tue May 13 18:30:43 2008 From: lists at cheimes.de (Christian Heimes) Date: Wed, 14 May 2008 00:30:43 +0200 Subject: usage of python In-Reply-To: References: Message-ID: Rajarshi schrieb: > Hi, I teach an introductory programming course in Python. As part of > the introduction I'd like to highlight the usage of Python in > industry. The idea is to show that there are big players using Python > for a variety of tasks. Given that the students come from a variety of > backgrounds and are not necessarily 'hackers', I'm trying to look for > examples with a bit of wow-factor. > > Is there any list with people/groups/companies using Python for > impressive things? > > Any pointers would be appreciated Additionally to the other URLs: http://highscalability.com/youtube-architecture http://highscalability.com/google-architecture http://www.ohloh.net/projects/python Christian From hdante at gmail.com Sat May 3 16:13:04 2008 From: hdante at gmail.com (hdante) Date: Sat, 3 May 2008 13:13:04 -0700 (PDT) Subject: Feature suggestion: sum() ought to use a compensated summation algorithm References: <481CB283.107@gmail.com> Message-ID: On May 3, 3:44?pm, Szabolcs Horv?t wrote: > Arnaud Delobelle wrote: > > > sum() works for any sequence of objects with an __add__ method, not > > just floats! ?Your algorithm is specific to floats. > > This occurred to me also, but then I tried > > sum(['abc', 'efg'], '') > > and it did not work. ?Or is this just a special exception to prevent the > ? misuse of sum to join strings? ?(As I said, I'm only an occasional user.) > > Generally, sum() seems to be most useful for numeric types (i.e. those > that form a group with respect to __add__ and __neg__/__sub__), which > may be either exact (e.g. integers) or inexact (e.g. floating point > types). ?For exact types it does not make sense to use compensated > summation (though it wouldn't give an incorrect answer, either), and > sum() cannot decide whether a user-defined type is exact or inexact. > > But I guess that it would still be possible to make sum() use > compensated summation for built-in floating point types (float/complex). > > Or, to go further, provide a switch to choose between the two methods, > and make use compensated summation for float/complex by default. ?(But > perhaps people would consider this last alternative a bit too messy.) > > (Just some thoughts ...) The benefits should be weighted considering the common case. For example, do you find an error of 10^-14 unbearable ? How many times someone will add 1.000.000 numbers in a typical scientific application written in python ? I believe that moving this to third party could be better. What about numpy ? Doesn't it already have something similar ? From fiacre.patrick at gmail.com Fri May 23 03:05:58 2008 From: fiacre.patrick at gmail.com (Andrew Lee) Date: Fri, 23 May 2008 03:05:58 -0400 Subject: can python do some kernel stuff? In-Reply-To: <983ec0f6-1316-40cd-a4d4-ce9b5e272a60@h1g2000prh.googlegroups.com> References: <983ec0f6-1316-40cd-a4d4-ce9b5e272a60@h1g2000prh.googlegroups.com> Message-ID: <48366cfa$0$15168$607ed4bc@cv.net> Jimmy wrote: > Hi to all > > python now has grown to a versatile language that can > accomplish tasks for many different purposes. However, > AFAIK, little is known about its ability of kernel coding. > > So I am wondering if python can do some kernel coding that > used to be the private garden of C/C++. For example, can python > intercept the input of keyboard on a system level? someone told me > it's a kernel thing, isn't it? http://wiki.python.org/moin/elmer From castironpi at gmail.com Wed May 7 20:41:17 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 7 May 2008 17:41:17 -0700 (PDT) Subject: saving a webpage's links to the hard disk References: <9a4733b4-5320-4a66-b0ce-5dcebc02d9a7@y38g2000hsy.googlegroups.com> <7ccc9c7b-002c-4385-9832-aaa0981638da@2g2000hsn.googlegroups.com> <68dpjdF2rvl8oU1@mid.uni-berlin.de> Message-ID: On May 7, 8:36?am, "Diez B. Roggisch" wrote: > Jetus wrote: > > On May 4, 7:22 am, castiro... at gmail.com wrote: > >> On May 4, 12:33 am, "Gabriel Genellina" > >> wrote: > > >> > En Sun, 04 May 2008 01:33:45 -0300, Jetus > >> > escribi?: > > >> > > Is there a good place to look to see where I can find some code that > >> > > will help me to save webpage's links to the local drive, after I have > >> > > used urllib2 to retrieve the page? > >> > > Many times I have to view these pages when I do not have access to > >> > > the internet. > > >> > Don't reinvent the wheel and use wgethttp://en.wikipedia.org/wiki/Wget > > >> > -- > >> > Gabriel Genellina > > >> A lot of the functionality is already present. > > >> import urllib > >> urllib.urlretrieve( 'http://python.org/', 'main.htm' ) > >> from htmllib import HTMLParser > >> from formatter import NullFormatter > >> parser= HTMLParser( NullFormatter( ) ) > >> parser.feed( open( 'main.htm' ).read( ) ) > >> import urlparse > >> for a in parser.anchorlist: > >> ? ? print urlparse.urljoin( 'http://python.org/', a ) > > >> Output snipped: > > >> ...http://python.org/psf/http://python.org/dev/http://python.org/links/h... > >> ... > > > How can I modify or add to the above code, so that the file references > > are saved to specified local directories, AND the saved webpage makes > > reference to the new saved files in the respective directories? > > Thanks for your help in advance. > > how about you *try* to do so - and if you have actual problems, you come > back and ask for help? Alternatively, there's always guru.com > > Diez- Hide quoted text - > > - Show quoted text - I've tried, no avail. How does the open-source plug to Python look/ work? Firefox was able to spawn Python in a toolbar in a distant land. Does it still? I believe under DOM, return a file named X that contains a list of changes to make to the page, or put it at the top of one, to be removed by Firefox. At that point, X would pretty much be the last lexicly-sorted file in a pre-established directory. Files are really easy to create and add syntax too, if you create a bunch of them. Sector size was bouncing though, which brings that all the way up to file system. for( int docID= 0; docID++ ) { if ( doc.links[ docID ]== pythonfileA.links[ pyID ] ) { doc.links[ docID ].anchor= pythonfileB.links[ pyID ]; pyID++; } } From torriem at gmail.com Wed May 7 17:51:37 2008 From: torriem at gmail.com (Michael Torrie) Date: Wed, 07 May 2008 15:51:37 -0600 Subject: Why don't generators execute until first yield? In-Reply-To: References: Message-ID: <48222469.70803@gmail.com> Martin Sand Christensen wrote: > Why don't > generators follow the usual eager evaluation semantics of Python and > immediately execute up until right before the first yield instead? A great example of why this behavior would defeat some of the purpose of generators can be found in this amazing PDF presentation: http://www.dabeaz.com/generators/Generators.pdf > Giving generators special case semantics for no good reason is a really > bad idea, so I'm very curious if there is a good reason for it being > this way. With the current semantics it means that errors can pop up at > unexpected times rather than the code failing fast. Most assuredly they do have good reason. Consider the cases in the PDF I just mentioned. Building generators that work on the output of other generators allows assembling entire pipelines of behavior. A very powerful feature that would be impossible if the generators had the semantics you describe. If you want generators to behave as you suggest they should, then a conventional for x in blah approach is likely the better way to go. I use a generator anytime I want to be able to iterate across something that has a potentially expensive cost, in terms of memory or cpu, to do all at once. From bronger at physik.rwth-aachen.de Tue May 13 12:04:27 2008 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Tue, 13 May 2008 18:04:27 +0200 Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <2b66a86e-5a05-4262-b3c9-4703b0ae3372@d1g2000hsg.googlegroups.com> <5b0e3f70-afde-4480-8713-e7113b1250d7@x35g2000hsb.googlegroups.com> <1f537717-00d0-48ee-99b6-7125b96a6133@t12g2000prg.googlegroups.com> <68t4o0F2vaoncU1@mid.uni-berlin.de> <2a32179a-9439-449c-bd07-fff6a4075aee@s50g2000hsb.googlegroups.com> <7ee5dffd-df8f-46f0-bd78-c81ac0418a9a@d77g2000hsb.googlegroups.com> <65ef773e-a1c3-4adb-a18b-e8b8451efe5e@b5g2000pri.googlegroups.com> Message-ID: <87hcd2gph0.fsf@physik.rwth-aachen.de> Hall?chen! Dave Parker writes: > [...] > > Perhaps. Flaming Thunder is only $19.95 per year for an > individual (and even less per individual for site licenses), which > is less than the cost of just one book on Python. First of all: Although I consider myself part of the Free Software community, I have no problems at all with such a licence model. But ... > [...] > > Plus, me getting paid to work on Flaming Thunder is far more > motivating than me not getting paid to work on Python. This > weekend, Python users will still be debating how to fix > awkwardnesses in the languages (such as FOR loops where you're > just counting the loops and not referencing the loop variable) -- > but Flaming Thunder users will be getting work done using the > REPEAT n TIMES constructs that I'll be implementing. Well, this is besides the point in my opinion. First, what you consider a wart may be loved by someone else. I for example would consider a "REPEAT n TIMES" feature as Ruby offers it (and soon FT apparently) ugly because it is superfluous. And secondly, *every* language has their warts. So many languages start as clean babies because they offer little and focus on a specific domain. But grown up, they include the same dirty tricks and suprising corners as the big languages. For me being a physicist and a hobby programmer, FT still is a toy language. Cute but titchy. It surely has its applications, but if you produce pocket calculators, don't tell a computer manufacturer that your machines are much simpler to use. Instead, both things simply have their purposes. > Python has been around about 15 years, yet still has those > awkwardnesses. Flaming Thunder has been out less than 6 months > and those awkwardnesses are already getting fixed. The > difference: I can't afford to ignore users. Really, the Python developers listen *very* carefully what the users want. Of course, the response time in Python is months rather than days, which has turned out to be a good thing more than once. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for further contact info.) From hrpenf at gmail.com Wed May 21 05:07:38 2008 From: hrpenf at gmail.com (RaymondHe) Date: Wed, 21 May 2008 02:07:38 -0700 (PDT) Subject: How to transfer files over serial? Message-ID: I want to transfer files over serial,but PySerial Module does not support any protocol such as xmodem/ymodem,and I find nothing about these protocol write in python What should I do?Thank you From ivan.illarionov at gmail.com Mon May 12 23:18:10 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Tue, 13 May 2008 03:18:10 +0000 (UTC) Subject: how to get information of a running prog in python References: <8b571818-25f0-4c5d-8b1c-5b7e73192d15@w5g2000prd.googlegroups.com> Message-ID: On Mon, 12 May 2008 19:19:05 -0700, Jimmy wrote: > Well, i know it may be a little non-python thing, however, I can think > of no place better to post this question :) > > can anyone tell me, in python, how to obtain some information of a > running program? > paticularly, if i am playing some music in audacious or other media > player, how can i get the the name and some other info of current > playing song? It seems that audicious doesn't output on run-time In case of Audatious running on X11 all you need is Python X library http://python-xlib.sourceforge.net/ And something like: from Xlib import display dpy = display.Display() root = dpy.screen().root NET_WM_NAME = dpy.intern_atom('_NET_WM_NAME') UTF8_STRING = dpy.intern_atom('UTF8_STRING') for win in root.query_tree().children: try: window_title = win.get_full_property(NET_WM_NAME, UTF8_STRING).value except AttributeError: continue if window_title.endswith('Audacious'): song = window_title.split(' - ')[:-1] if song: print song -- Ivan From webmaster at monzell.com Sun May 11 01:05:02 2008 From: webmaster at monzell.com (Rilindo Foster) Date: Sun, 11 May 2008 01:05:02 -0400 Subject: Now what!? In-Reply-To: <8eb3fdfb-b8ae-4a1f-a2f3-fde46206b637@d77g2000hsb.googlegroups.com> References: <68m0i1F2t8265U1@mid.uni-berlin.de> <7363f4c0-1dec-4943-a9f6-7a24c3aff971@e39g2000hsf.googlegroups.com> <9GlVj.168$PE5.102@fe087.usenetserver.com> <8eb3fdfb-b8ae-4a1f-a2f3-fde46206b637@d77g2000hsb.googlegroups.com> Message-ID: <83DE3A94-92A2-4852-B44F-B2F91E924B2B@monzell.com> I don't know the context of the discussion, since I just joined the list, but: On May 10, 2008, at 11:05 PM, hdante wrote: > On May 10, 8:22 pm, notbob wrote: >> On 2008-05-10, Dennis Lee Bieber wrote: >> >>> So... in short, you'd need to have been reading a tutorial >>> specific >>> to "shell" scripting... >> >> I have been. I'm also trying to learn bash shell scripting, not to >> mention >> sed/awk, php, etc. I should have started this a long time ago, but >> I'm lazy > > Throw all of this away and learn just python. That will be much > simpler for you. Ummm, if you are working with Unix and Unix-like systems, you should know shell scripting. Work through that first and then when you find that you can't get things done with a shell script, go with Python (or failing that, Perl :) ). - Rilindo From mccredie at gmail.com Tue May 27 12:10:09 2008 From: mccredie at gmail.com (Matimus) Date: Tue, 27 May 2008 09:10:09 -0700 (PDT) Subject: New chairman References: <3720fb99-ac37-469b-b8ce-ece3ed27b8e5@m36g2000hse.googlegroups.com> Message-ID: <176349fa-381e-4b02-8b41-3a7da3725b76@p25g2000pri.googlegroups.com> On May 27, 8:21?am, Sverker Nilsson wrote: > I was talking about Guido van Rossum > > The one who decides, so far when people agree > > But we can make a new fork > > He is the originator, but now it seems, for me, it is hanging out in > the air > > So we need some new leadership > > From somebody, somebody like you perhaps. Or me. > > Sverker > > On May 27, 4:50 pm, "Andrii V. Mishkovskyi" > wrote: > > > 2008/5/27 Sverker Nilsson : > > > > seems to be needed > > > > He doesn't seem to care much anyway now > > > > Or if he cares, he have many other assignments > > > Who are you talking about? > > > > So should we try to elect a new chairman? > > > Chairman? Elaborate please. > > > > I am probably not eligible. There must be many others.! > > > > Do you dare?consper > > > Hm, are you and castrionpi twin brothers or something? > > > > S. > > > -- > > >http://mail.python.org/mailman/listinfo/python-list > > > -- > > Wbr, Andrii Mishkovskyi. > > > He's got a heart of a little child, and he keeps it in a jar on his desk. > > Guido is the BDFL: Benevolent Dictator For Life. He was not elected. If you want new leadership in Python it won't be done via a vote, it will be via a coup. You will need to create your own community (and probably fork of Python) that is superior to the existing version. So much that people decide to migrate from one to the other. Any conversation that leads to such a communal fork would probably begin with discussing things that should be done differently in Python and garnering support. Personally, what I like _most_ about python is the community. Guido played a large part in establishing this community. If you put together a coherent argument regarding the future of Python people will listen, including Guido. Matt From ian.g.kelly at gmail.com Thu May 8 23:48:48 2008 From: ian.g.kelly at gmail.com (Ian Kelly) Date: Thu, 8 May 2008 21:48:48 -0600 Subject: Free Memory In-Reply-To: <8a6035a00805081730g2a18b97cxc32ae6568fb10b81@mail.gmail.com> References: <8a6035a00805081730g2a18b97cxc32ae6568fb10b81@mail.gmail.com> Message-ID: <3fc761710805082048q1da9be4fw2c75a06ec3ebdc6e@mail.gmail.com> On Thu, May 8, 2008 at 6:30 PM, Dark Wind wrote: > Hi, > > How can I free all the memory in python by deleting all variables. I am > looking for the equivalent of 'clear' from Matlab. > > I know del x deletes a variable x, but it doesn't free all the available > memory. I don't know if there's a good way to do exactly what you're asking for. However, if you really want to reset *everything*, you could replace the current process with a fresh interpreter by calling os.execlp("python"). From fabiofz at gmail.com Wed May 7 10:16:50 2008 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Wed, 7 May 2008 11:16:50 -0300 Subject: Pydev 1.3.16 Released Message-ID: Hi All, Pydev and Pydev Extensions 1.3.16 have been released Details on Pydev Extensions: http://www.fabioz.com/pydev Details on Pydev: http://pydev.sf.net Details on its development: http://pydev.blogspot.com Release Highlights in Pydev Extensions: ----------------------------------------------------------------- * Code Analysis: __path__ Not correctly found on some situations. * Local rename (ctrl+2+r): Positions correctly ordered for tabbing. Release Highlights in Pydev: ---------------------------------------------- * Interactive console: help() works * Interactive console: context information showing in completions * Interactive console: backspace will also delete the selected text * Interactive console: ESC does not close the console when in floating mode anymore * Code completion: calltips context info correctly made 'bold' * Code completion: variables starting with '_' do not come in import * * Code completion: can be requested for external files (containing system info) * Code completion: fixed recursion condition * Code completion: egg file distributed with dll that has a source module with the same name only with a __bootstrap__ method now loads the dll instead of the source module (e.g.: numpy egg) * Debugger: Step over/Step return can now execute with untraced frames (much faster) * Debugger: Problem when handling thread that had no context traced and was directly removed. * Launching: F9 will reuse an existing launch instead of creating a new one every time * Launching: The default launch with Ctrl+F11 will not ask again for the launch associated with a file (for new launches -- old launches should be deleted) * Project Explorer: fixed integration problems with CDT (and others) * Launch: console encoding passed as environment variable (no longer written to the install location) * More templates for "surround with" (Ctrl+1) * Previous/next method could match 'class' and 'def' on invalid location * Outline: Assign with multiple targets is recognized * Bug fix for pydev package explorer when refreshed element parent was null What is PyDev? --------------------------- PyDev is a plugin that enables users to use Eclipse for Python and Jython development -- making Eclipse a first class Python IDE -- It comes with many goodies such as code completion, syntax highlighting, syntax analysis, refactor, debug and many others. Cheers, -- Fabio Zadrozny ------------------------------------------------------ Software Developer ESSS - Engineering Simulation and Scientific Software http://www.esss.com.br Pydev Extensions http://www.fabioz.com/pydev Pydev - Python Development Enviroment for Eclipse http://pydev.sf.net http://pydev.blogspot.com From matthieu.brucher at gmail.com Sun May 18 03:53:09 2008 From: matthieu.brucher at gmail.com (Matthieu Brucher) Date: Sun, 18 May 2008 09:53:09 +0200 Subject: Python and Flaming Thunder In-Reply-To: <20080514225208.3f02fd70.johnjsal@NOSPAMgmail.com> References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <2b66a86e-5a05-4262-b3c9-4703b0ae3372@d1g2000hsg.googlegroups.com> <5b0e3f70-afde-4480-8713-e7113b1250d7@x35g2000hsb.googlegroups.com> <1f537717-00d0-48ee-99b6-7125b96a6133@t12g2000prg.googlegroups.com> <20080514225208.3f02fd70.johnjsal@NOSPAMgmail.com> Message-ID: 2008/5/15 John Salerno : > On Tue, 13 May 2008 06:25:27 -0700 (PDT) > Dave Parker wrote: > > > > I'm pretty generally interested, but where can print layout take you? > > > > Not far, especially with books disappearing. Our library says that > > these days, only 25% of their checkouts are books; the other 75% are > > DVDs, CDs, etc. > > Sorry, but I must point out a logical flaw in this statement. Assuming your > stats are even true, just because books are now only 25% of checkouts rather > than, for example, 80%, doesn't necessarily imply that any less books are > being checked out (i.e. "disappearing"). It can just as easily mean that > *more* of the other things are being checked out while books remain the > same. > > Example: > > Total number of items checked out: 100 > Total number of books checked out: 80 > Percentage of books checked out: 80% > > Total number of items checked out: 320 > Total number of books checked out: 80 # same as above > Percentage of books checked out: 25% > -- > http://mail.python.org/mailman/listinfo/python-list > In France, the book market is bigger (in terms of money) than the DVD and CD market IIRC. That's strange, isn't it ? Matthieu -- French PhD student Website : http://matthieu-brucher.developpez.com/ Blogs : http://matt.eifelle.com and http://blog.developpez.com/?blog=92 LinkedIn : http://www.linkedin.com/in/matthieubrucher -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Fri May 16 11:28:52 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 16 May 2008 17:28:52 +0200 Subject: writing python extensions in assembly In-Reply-To: References: <695jdlF30fp0gU1@mid.uni-berlin.de> Message-ID: <695ni3F30u8tgU2@mid.uni-berlin.de> inhahe schrieb: > Well the problem is that I'm actually not an assembler guru, so I don't know > how to implement a dll in asm or use a c calling convention, although I'm > sure those instructions are available on the web. I was just afraid of > trying to learn that AND making python-specific extensions at the same time. > I thought of making a c extension with embedded asm, but that just seemed > less than ideal. But if somebody thinks that's the Right Way to do it, > that's good enough.. I think the right thing to do if you are not as fluent in assembly is do not do anything in it at all. What do you need it for? Diez From pavlovevidence at gmail.com Tue May 13 14:47:23 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 13 May 2008 11:47:23 -0700 (PDT) Subject: Literate programs in Python References: <37e8fb41-8008-45aa-a123-b71455bc7ce5@t54g2000hsg.googlegroups.com> Message-ID: <6bb0ca79-1070-4d42-90a9-a1066b152210@d1g2000hsg.googlegroups.com> On May 13, 1:44 pm, Mike Driscoll wrote: > On May 13, 10:28 am, Paul Miller wrote: > > > Does anyone know of any (preferably largish) examples of literate > > programs written using Python? Alternatively, does anyone know of any > > literate programming tools which support Python well? (I am aware of > > Leo and I've been to literateprogramming.com, but any additional > > pointers would be much appreciated!) > > Check out Zope, bittorrent, or Editra. You should just go to > SourceForge and do a search for projects done in Python. Those aren't examples of literate programming AFAIK. (Check Wikipedia for "literate programming" if you're still confused.) It occurs to me that one could get pretty close to literate programming with Pure Python (if they stick to regular function calls and not expect code weaving, which would need a preprocessor). A fairly simple script could parse docstrings and Python source files to produce a document from the source. In fact, there are tools that can do that sort of thing already, but I doubt they output documents according to literate programming expectations. Don't know of any tools specifically for literate programming. Carl Banks From sophacles at gmail.com Thu May 22 20:00:14 2008 From: sophacles at gmail.com (Erich) Date: Thu, 22 May 2008 17:00:14 -0700 (PDT) Subject: Python is slow References: Message-ID: <9ef43041-3bf6-45b5-8623-afaf7755d660@z66g2000hsc.googlegroups.com> On May 22, 1:18 pm, Arnaud Delobelle wrote: > My mum's fast... > Arnaud Was it a good idea to include that bit in a troll response? If English isn't your first language, it's one of those language idioms that's not very nice to say about someone's mother (especially your own mother). Erich From castironpi at gmail.com Wed May 14 12:20:18 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 14 May 2008 09:20:18 -0700 (PDT) Subject: named tuple mutability Message-ID: I'm concerned over the future of Python. Should tuples be named? From gagsl-py2 at yahoo.com.ar Sun May 11 17:15:38 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 11 May 2008 18:15:38 -0300 Subject: multiple Python versions, but on Windows (how to handle registry updates) References: <3de8e1f70805090358p27796919jb885138406ade6aa@mail.gmail.com> <3de8e1f70805092138y4ca414ck2be6b5246afa664b@mail.gmail.com> <3de8e1f70805102115j5f0bf985w3952facf49a66d79@mail.gmail.com> <3de8e1f70805102117p584e5920hb4a99166488c6448@mail.gmail.com> Message-ID: En Sun, 11 May 2008 01:17:22 -0300, Banibrata Dutta escribi?: > I realized that my query was not making much sense, or a bit convoluted. A > simler form of the question: > > For packages which do contain .dlls & .pyd's (not pure Python) their latest > version may be compatible with -- say Python 2.5, whereas I need the version > compatible for Python2.2. Is this a completely manual exercise ? You don't have to try - binaries for different Python versions *are* *not* compatible (up to the second digit: 2.4 and 2.5 are not compatible, but 2.5.1 and 2.5.2 are). So any extension using a .pyd/.dll will have to be recompiled, at least. Even pure Python code written for 2.5 may use features not available in 2.2. Packages built using setuptools (eggs) may contain explicit dependency information but I don't know for sure. -- Gabriel Genellina From arnodel at googlemail.com Sun May 11 14:28:17 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Sun, 11 May 2008 19:28:17 +0100 Subject: File Creation Not Working In A Thread Class? References: <7qGVj.32505$KJ1.18416@newsfe19.lga> Message-ID: Arnaud Delobelle writes: > bc90021 writes: > >> On Sun, 11 May 2008 18:36:25 +0100, Arnaud Delobelle wrote: >> >>> bc90021 writes: >>> >>>> Hi All, >>>> >>>> Thanks in advance for any and all help! >>>> >>>> I have this code: >>>> >>>> g = open(fileName, 'a') >>>> >>>> where fileName is defined before the line it's used in. It works fine >>>> when I use it outside a thread class. >>>> >>>> When I put the same line in a thread class, it no longer works, and I >>>> get an error: >>>> >>>> IOError: [Errno 2] no such file u'fileName' >>>> >>>> >>> It's telling you that you haven't got a file called 'fileName'. Posting >>> the code that triggers this error would allow people to diagnose the >>> error accurately rather than guessing. >> >> f = open(otherFile).readlines() >> for i in len(f): >> for c in range(0,24,1): >> if os.name == "posix": >> tempfileName = "\"proctemp/" + self.matrix[c][0] >> + "_tmp_" + fileName + ".txt\"" >> if re.search(f[i], pattern): >> g = open(tempfileName, 'a') >> g.write(f[i]) >> >> >> This code works *perfectly* unless I put it in a class that inherits from >> threading.Thread. In the thread class, everything works (I can see the >> "c" value, and I can print out each line in "f[i]", it's just that the g >> = open line doesn't work. > > It's difficult to know what's wrong with the code you posted because: > > * it is not self-contained: otherFile, fileName, pattern are names > which you do not define; > > * the IOError you reported earlier can't arise as a result of running > this code. Correction: it can, if otherFile == u'fileName' So I put 1000 rupees on this being the cause of the error :) -- Arnaud From andrej.panjkov at climatechange.qld.gov.au Wed May 7 20:53:07 2008 From: andrej.panjkov at climatechange.qld.gov.au (andrej.panjkov at climatechange.qld.gov.au) Date: Wed, 7 May 2008 17:53:07 -0700 (PDT) Subject: explain this function to me, lambda confusion References: Message-ID: On May 8, 10:34 am, andrej.panj... at climatechange.qld.gov.au wrote: > > >>> HeightDistrib = (170, 20) > That should be > >>> HeightDistrib = Gaussian(170, 20) From george.sakkis at gmail.com Mon May 5 23:11:54 2008 From: george.sakkis at gmail.com (George Sakkis) Date: Mon, 5 May 2008 20:11:54 -0700 (PDT) Subject: config files in python References: <44f9662d-a88d-418c-a11d-b7b472b01fc3@j33g2000pri.googlegroups.com> Message-ID: On May 5, 6:57 pm, Matimus wrote: > On May 5, 10:22 am, Francesco Bochicchio wrote: > > > > > On Mon, 05 May 2008 00:35:51 -0700, sandipm wrote: > > > Hi, > > > In my application, I have some configurable information which is used > > > by different processes. currently I have stored configration in a > > > conf.py file as name=value pairs, and I am importing conf.py file to > > > use this variable. it works well > > > > import conf > > > print conf.SomeVariable > > > > but if I need to change some configuration parameteres, it would need > > > me to restart processes. > > > > I want to store this data in some conf file (txt) and would like to > > > use it same way as I am using these variables as defined in py > > > files. > > > > one solution I can think of is writing data as a dictionary into conf > > > file. and then by reading data, apply eval on that data. and update > > > local dict? but this is not a good solution.... > > > > any pointers? > > > > Sandip > > > The 'simple but relatively dangerous way', already suggested, is to > > reload() the module. > > > A safer way - but requiring more work - could be to build something around > > the Configparser module in the standard library ... > > > Ciao > > ----- > > FB > > How is it relatively dangerous? I mean, aside from any `dangers' > associated with importing a user defined module in the first place. Read the caveats in reload()'s description. Briefly: - It does not reload names imported with "from ... import ...". - Any existing instances of classes defined in the module still refer to the original class, not the reloaded one (assuming it is still present). - The module's dictionary (containing the module's global variables) is retained and updated in place, so names that are deleted in the module are still available. - It is not recursive. - And more... George From ricaraoz at gmail.com Tue May 13 19:08:51 2008 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Tue, 13 May 2008 20:08:51 -0300 Subject: python vs. grep In-Reply-To: <87k5hy20eo.fsf@gmail.com> References: <011f43ea-9bc8-499a-a3fe-dba24b47932e@c58g2000hsc.googlegroups.com> <7f44a73f-e88d-4edc-97e5-95cac7a26b14@2g2000hsn.googlegroups.com> <87k5hy20eo.fsf@gmail.com> Message-ID: <482A1F83.2030505@bigfoot.com> Ville M. Vainio wrote: > Ricardo Ar?oz writes: > >> The easy/simple (too easy/simple?) way I see out of it is to read THE >> WHOLE file into memory and don't worry. But what if the file is too > > The easiest and simplest approach is often the best with > Python. Keep forgetting that! > > If the file is too big, you might want to look up mmap: > > http://effbot.org/librarybook/mmap.htm Thanks! From andrej.panjkov at climatechange.qld.gov.au Wed May 7 20:34:56 2008 From: andrej.panjkov at climatechange.qld.gov.au (andrej.panjkov at climatechange.qld.gov.au) Date: Wed, 7 May 2008 17:34:56 -0700 (PDT) Subject: explain this function to me, lambda confusion References: Message-ID: On May 8, 7:38 am, globalrev wrote: > i have a rough understanding of lambda but so far only have found use > for it once(in tkinter when passing lambda as an argument i could > circumvent some tricky stuff). > what is the point of the following function? > > def addn(n): > return lambda x,inc=n: x+inc > > if i do addn(5) it returns > > >>> def addn(n): > > return lambda x,inc=n: x+inc > > >>> addn(5) > > at 0x01D81830> > > ok? so what do i write to make it actually do something. and is the > inc=n necessary i cant do x+n? Here are some notes I have written for our local wiki on lambdas in python. I hope you will find them illuminating, and I would welcome any suggestions for improving them. I have just cut and pasted from our wiki, so the fancy formatting has been lost. ----- Python lambdas. The on-line documentation for python lambdas is not very illuminating. Here?s my take and my first simple examples. I would describe a lambda as a parameterised function template. If you dig, the docs call lambdas anonymous functions not bound to a name. There is a bit of resemblance to C macros. Here is a simple lambda that implements an exclusive or: >>> def XOR(x,y) : >>> return lambda : ( ( x ) and not ( y ) ) or ( not ( x ) and ( y ) ) (Because of the resemblance to C macros, I have been cautious and written the lambda with lots of parentheses.) To use this in later code, we define instances of the lambda with specific function arguments. >>> topping = XOR( cream, icecream) >>> sauce = XOR( tomato, BBQ ) We now have two ?functions?, topping() and sauce() which we can use later to test flags. >>> cream = True >>> icecream = False >>> print topping() True So in the definition of the XOR lambda, think of x and y as the parameters of the function template, and XOR as the function name placeholder. By putting in specific objects for the parameters (here the boolean variables cream and icecream for example), we produce a specific instance of the lambda, topping() which looks like a function with no arguments. If we use different objects for the parameters (say tomato and BBQ) then we get a different function, sauce. Here is another simple lambda, (template) to set up three new functions AddOnly, DeleteOnly, and ReplaceOnly. #--# Lambda function to check that a flag is only on when the other two are off. #--# def TFF(x,y,z) : return lambda : ( ( x ) and not ( y ) and not ( z ) ) AddOnly = TFF( options.AddAction, options.ReplaceAction, options.DeleteAction ) DeleteOnly = TFF( options.DeleteAction, options.AddAction, options.ReplaceAction ) ReplaceOnly = TFF( options.ReplaceAction, options.AddAction, options.DeleteAction ) if( not (DeleteOnly() or AddOnly() or ReplaceOnly() ) ): print "Error: Exactly one of [ --add | --replace | --delete ] allowed. " parser.print_help() exit More advanced lambdas. The examples above give function instances that have no arguments, once the parameters of the lambda are chosen. For a function template with arguments and parameters, we add the arguments on the 2nd line. Parameters are in the first line. The Gaussian distribution is exp(-(x-?)?/ 2?? ) / ?(4 ??). While we can think of this as a function of three variables, we normally view it as a family of functions of a single variable x, parameterised by ? and ?. Selecting fixed values for ? and ? gives us a single distribution for x. >>> import math >>> def Gaussian( mu, sigma ) : ... return lambda x : math.exp( - (x-mu)**2 / 2 /sigma**2 ) / math.sqrt (2 * math.pi *sigma **2 ) ... >>> and here are some instances: >>> Normal = Gaussian (0, 1) >>> HeightDistrib = (170, 20) which we later use as >>> y = Normal( 0.5 ) 0.35206532676429952 >>> x = 192 >>> HeightDistrib(x) 0.0073381331586869951 I recommend defining the instances of the lambda right after the lambda. If you define it in code far removed from the definition of the lambda, it looks like an assignment, so comment it. From tjreedy at udel.edu Thu May 1 18:43:02 2008 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 1 May 2008 18:43:02 -0400 Subject: Pep11 References: <481a068c$0$9757$9b622d9e@news.freenet.de> Message-ID: The syllable link at the bottem is not currently working. The site itself is still alive and distributing 2.5.1 terry From deets at nospam.web.de Mon May 26 15:54:54 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 26 May 2008 21:54:54 +0200 Subject: Question about wsgi.input In-Reply-To: References: <6a0htmF35sj8eU1@mid.uni-berlin.de> Message-ID: <6a0isiF35d89iU1@mid.uni-berlin.de> inhahe schrieb: > That's what I would have thought, just seems strange since it seems to imply > that if I use StringIO or cStringIO, then whenever i write to it i have to > save the position, seek to the end, write, and then seek to the position i > saved. Are there any other classes that are more suitable for pipes, but > qualify as 'file-like objects'? Who uses StringIO for what? if you have two processes (server and application), you can of course use a pipe of some sort. If you write a WSGI-server that is supposed to pass the wsgi.input to an application, just use StringIO with the completely initialized data - there is no writing in-between. Diez From larzluv at hotmail.com Sun May 11 21:02:48 2008 From: larzluv at hotmail.com (Larry Hale) Date: Sun, 11 May 2008 18:02:48 -0700 (PDT) Subject: Module python-magic on/for Windows? References: Message-ID: After putting the magic1.dll file to C:\Program Files\Python25\DLLs (looking at the directory structure, that seemed as good a place as any), now I can *import* the module, but... >>> import magic >>> test = magic.Magic() Traceback (most recent call last): File "", line 1, in File "build\bdist.win32\egg\magic.py", line 32, in __init__ File "build\bdist.win32\egg\magic.py", line 72, in _check_error magic.MagicException: could not find any magic files! I've placed 474,146 magic 1,037,440 magic.mgc 32,203 magic.mime 45,696 magic.mime.mgc 77,312 magic1.dll into C:\windows\system32 in Windows/System PATH AND (simultaneously) C:\Program Files\python25\DLLs in sys.path/PYTHONPATH (I've also tried putting copies into different dirs in both PYTHONPATH and system PATH, to no avail.) Obviously, magic1.dll/magic.py (et al) can't FIND the needed file(s), but I'm not sure how to go about discerning WHERE it/they are looking - any thought(s)/suggestion(s), anyone?? Thanks in advance! -Larry P.S.: Thanks, again, Michael! ;) - L From python at bdurham.com Mon May 12 20:11:06 2008 From: python at bdurham.com (python at bdurham.com) Date: Mon, 12 May 2008 20:11:06 -0400 Subject: using PIL for good screenshots In-Reply-To: References: Message-ID: <1210637466.13155.1252798043@webmail.messagingengine.com> Tim, Sounds like an interesting project. Have you considered using SnagIt to produce your screenshots? www.TechSmith.com/SnagIt Malcolm From wuwei23 at gmail.com Tue May 6 04:46:15 2008 From: wuwei23 at gmail.com (alex23) Date: Tue, 6 May 2008 01:46:15 -0700 (PDT) Subject: Python MIDI in 2008 References: <1076a133-4376-4b96-a06b-4bb990ec3f42@f63g2000hsf.googlegroups.com> Message-ID: On May 6, 6:01 pm, Maciej Blizi?ski wrote: > Is there any other package that allows sending MIDI events in real > time? Did anyone recently got any of the above packages to work? There's MidiKinesis (http://www.sci.ccny.cuny.edu/~brinkman/software/ midikinesis/) which allows for midi events to be bound to X-Windows events. It looks like it achieves this using ctypes to wrap around the ALSA libs, which may be another approach to consider. The MidiKineses codebase would be a good place to start if you wanted to give that a try. I'm sorry I can't be of much more help but please keep us posted on what you find! - alex23 From sn at sncs.se Tue May 27 11:26:01 2008 From: sn at sncs.se (Sverker Nilsson) Date: Tue, 27 May 2008 08:26:01 -0700 (PDT) Subject: New chairman References: <3720fb99-ac37-469b-b8ce-ece3ed27b8e5@m36g2000hse.googlegroups.com> Message-ID: <529d275a-1274-43f4-b6a8-a844c3692711@59g2000hsb.googlegroups.com> I dont want to be a new Guido. Somebody else please. S. On May 27, 5:21 pm, Sverker Nilsson wrote: > I was talking about Guido van Rossum > > The one who decides, so far when people agree > > But we can make a new fork > > He is the originator, but now it seems, for me, it is hanging out in > the air > > So we need some new leadership > > From somebody, somebody like you perhaps. Or me. > > Sverker > > On May 27, 4:50 pm, "Andrii V. Mishkovskyi" > wrote: > > > 2008/5/27 Sverker Nilsson : > > > > seems to be needed > > > > He doesn't seem to care much anyway now > > > > Or if he cares, he have many other assignments > > > Who are you talking about? > > > > So should we try to elect a new chairman? > > > Chairman? Elaborate please. > > > > I am probably not eligible. There must be many others.! > > > > Do you dare?consper > > > Hm, are you and castrionpi twin brothers or something? > > > > S. > > > -- > > >http://mail.python.org/mailman/listinfo/python-list > > > -- > > Wbr, Andrii Mishkovskyi. > > > He's got a heart of a little child, and he keeps it in a jar on his desk. From lists at cheimes.de Fri May 2 15:41:36 2008 From: lists at cheimes.de (Christian Heimes) Date: Fri, 02 May 2008 21:41:36 +0200 Subject: portable /dev/null In-Reply-To: <1jkwzhktzddwv.xxl22p30ivrs.dlg@40tude.net> References: <1jkwzhktzddwv.xxl22p30ivrs.dlg@40tude.net> Message-ID: <481B6E70.7000503@cheimes.de> Brendan Miller schrieb: > Hi, > > I have functions that take a file object and write to it. In some cases I > just want to throw out what is written to that file object. I want > something like open('/dev/null', 'w'), but portable. import os null = open(os.devnull, "wb") :) Christian From Graham.Dumpleton at gmail.com Mon May 26 00:00:31 2008 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Sun, 25 May 2008 21:00:31 -0700 (PDT) Subject: Beginner question References: Message-ID: <3c816e91-5acb-4dd4-bfc4-164d4a2f1100@q27g2000prf.googlegroups.com> On May 26, 4:13?am, howa wrote: > Hi, > > Just want to try mod_python but it is more complicated then I > expected... > > I just followed the tutorial on:http://www.modpython.org/live/mod_python-2.7.8/doc-html/inst-testing.... > > E.g. > > URL =http://www.example.com/mptest.py > > It return > > ImportError: No module named mptest > > 1. If I removed addHandler mod_python .py and PythonHandler mptest, I > can see the SOURCE CODE > > 2. The PythonHandler mod_python.testhandler seems return correct > result, showing I am using python 2.4.3 > > any idea? Why are you using the documentation from version 2.7.8 of mod_python when you are using a much newer version? Also read: http://www.dscpl.com.au/wiki/ModPython/Articles/GettingModPythonWorking Graham From gandalf at shopzeus.com Thu May 15 09:51:29 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Thu, 15 May 2008 15:51:29 +0200 Subject: create window on panel In-Reply-To: <70da959d-dfce-4355-8279-2b33123db568@w5g2000prd.googlegroups.com> References: <93cd94a9-4fc6-46a9-b0b6-2303371d5245@h1g2000prh.googlegroups.com> <70da959d-dfce-4355-8279-2b33123db568@w5g2000prd.googlegroups.com> Message-ID: <482C3FE1.3060700@shopzeus.com> >> URL:http://www.daa.com.au/~james/software/pygtk/ >> / >> /It should be easy to read the docs, view the demo programs and create >> your own program. >> >> L >> > > thanks~ it seems attractive, however, I did not find much useful > information :( > http://www.pygtk.org/ -- full docs http://packages.ubuntu.com/dapper/doc/python-gtk2-tutorial -- This seems to be a tutorial for python-gnome2. Let me know if it doesn't help. L From bruno.desthuilliers at gmail.com Thu May 22 15:39:17 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Thu, 22 May 2008 12:39:17 -0700 (PDT) Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> Message-ID: <77fa9cbd-7253-4b70-9334-b1ceac1cb15a@l64g2000hse.googlegroups.com> On 22 mai, 18:56, Mensanator wrote: > On May 22, 10:30 am, Nick Craig-Wood wrote: > > > > > Dave Parker wrote: > > > But after getting input from children and teachers, etc, it started > > > feeling right. > > > > For example, consider the two statements: > > > > x = 8 > > > x = 10 > > > > The reaction from most math teachers (and kids) was "one of those is > > > wrong because x can't equal 2 different things at the same time". > > > This is a common feature in functional languages... > > > Eg > > > Erlang (BEAM) emulator version 5.6.2 [source] [smp:2] > > [async-threads:0] [kernel-poll:false] > > > Eshell V5.6.2 (abort with ^G) > > 1> X = 8. > > 8 > > 2> X = 10. > > ** exception error: no match of right hand side value 10 > > 3> > > > That error message is the erlang interpreter saying "Hey I know X is > > 8, and you've said it is 10 - that can't be right", which is pretty > > much what math teachers say too... > > Are you saying that erlang treats 1> as an assignment, yet > treats 2> as a comparison? Nope. Both are treated as pattern matching. The first one binds X because it's by that time a free variable, the second fails because it doesn't match. > That's inconsistent. That's consistent when you understand how Erlang works. > No wonder nobody uses erlang. Strange enough, it seems that more and more developpers and company start to look at Erlang as a possible solution to massive scaling problems. > Why isn't erlang smart, like Python, and avoid such confusion? Erlang *is* smart. It's just totally different from Python. And there's no confusion here (except on your side...). From arnodel at googlemail.com Mon May 19 04:34:49 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Mon, 19 May 2008 01:34:49 -0700 (PDT) Subject: explain this function to me, lambda confusion References: <5cc7ef7a-dd21-4772-a7e3-765410f810bb@l17g2000pri.googlegroups.com> Message-ID: <6062786d-6f83-4850-bf55-4db4ec27bdea@b1g2000hsg.googlegroups.com> On May 19, 5:22 am, "Terry Reedy" wrote: > "Arnaud Delobelle" wrote in message [...] > | Note that the same thing can be said about generator expressions, > | which are nothing more than anonymous, non-reusable, generator > | functions. > > Right. So if someone posted on genexp confusion, I would suggest > 'write a full generator function'. I was just arguing against arguing for the removal of lambda on the basis that it doesn't add any functionality to the language! > | Instead these were _added_ to the language! > > As a convenience. > Actually, if one uses more that one for-clause in a generator expression, > there is a potential gotcha in relation to name capture. So if that bites, > the genexp is not so much a convenience, and one might better write > the full function. > > tjr Yes, IMHO this is a bug, and I wish I had the time to dive into the code to see if I can fix it. -- Arnaud From darcy at druid.net Wed May 21 13:25:10 2008 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Wed, 21 May 2008 13:25:10 -0400 Subject: Unsubscribe request In-Reply-To: <20080521131911.9d3b2056.darcy@PyGreSQL.org> References: <338512.44068.qm@web39704.mail.mud.yahoo.com> <20080521131911.9d3b2056.darcy@PyGreSQL.org> Message-ID: <20080521132510.af959b7b.darcy@druid.net> On Wed, 21 May 2008 13:19:11 -0400 "D'Arcy J.M. Cain" wrote: > On Wed, 21 May 2008 09:21:05 -0700 (PDT) > ahmed khattab wrote: > > unsubscribe me form python list plz > > Please use the admin interface that you used when you subscribed: > > http://mail.python.org/mailman/listinfo/python-list Oops. I thought I was replying to a different list that I admin. Sorry for the noise. However, the advice was still correct. Don't send unsubscribe requests to the list. This is true of pretty much every list, not just this one. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From dullrich at sprynet.com Sun May 25 07:54:51 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Sun, 25 May 2008 06:54:51 -0500 Subject: access interactive namespace from module (shared namespace?) References: Message-ID: On Sun, 25 May 2008 03:32:30 -0700 (PDT), ulrich at dorda.net wrote: >Thanks for the reply, > >Of course the suggested solution is working and good, but a bit >complicated. The module/function where i need to access the variable >value from the interactive shell is burried quite deep and I would >nedd to hand the locals() quite often from one module to another. >Furthermore it makes the call function slightly more complicated, as >the locals()-argunment has to be given every time. > >I was hoping for something a bit different: If I wanted to access a >value b from another module "utest2.py", I would simply need to type >in utest.py: import utest2; print 2*utest2.b >Isn't there a name for the interactive namespace (like here the >utest2), which I can use to access the variable without handing the >whole dictionary? """utest.py""" import __main__ def doit(): print 2*__main__.a >Cheers, > >Ulrich > > David C. Ullrich From stef.mientki at gmail.com Mon May 5 18:25:33 2008 From: stef.mientki at gmail.com (Stef Mientki) Date: Tue, 06 May 2008 00:25:33 +0200 Subject: Browser + local Python-based web server vs. wxPython In-Reply-To: References: Message-ID: <481F895D.9050905@gmail.com> Mike Driscoll wrote: > On May 5, 9:22 am, pyt... at bdurham.com wrote: > >> I'm looking at rewriting some legacy VB applications and am pondering >> which of the following techniques to use: >> >> 1. Browser based GUI with local web server (Browser + >> wsgiref.simple_server) (I'm assuming that simple_server is class I want >> to build from for a local web server) >> >> -OR- >> >> 2. wxPython based GUI >> >> My thought is that a browser/local web server setup may be more portable >> to mobile environments than wxPython and may offer a way to scale a >> single user offline application to a multi-user online application using >> a remote vs. local web server. Some groups of users may feel more >> comfortable with a browser based interface as well. >> >> I'm looking for feedback from anyone that has pondered the same question >> as well as any pros/cons or tips from anyone that has chosen the >> browser/lcoal web server route. >> >> Thanks, >> >> Malcolm >> > > wxPython is great for desktop applications on Linux, Windows and Mac. > However, there isn't much support for it on mobile platforms at the > moment. If you're thinking your application will be mostly for mobile > environments, I've been looking for several months now for a way to program mobile devices, and indeed as Mike said, wxPython has not much support so I didn't dare to try it. A week ago I found PocketPyGui, which is well supported, rock stable and qua functionality quit similar to wxPython and in some aspects even much easier than wxPython. The only disadavantage is that it's only suited for windows mobile. To give an idea, how well it works: in a week of spare time, I build an application with about 20 screens, build an emulator for it in wxPython ( not completely finished), and I now consider to build a wxPython wrapper (so I only have to know 1 kind of syntax) cheers, Stef From mensanator at aol.com Fri May 16 13:27:44 2008 From: mensanator at aol.com (Mensanator) Date: Fri, 16 May 2008 10:27:44 -0700 (PDT) Subject: writing python extensions in assembly References: Message-ID: <6ed4b0ff-5411-4384-b97d-e39667beb955@c65g2000hsa.googlegroups.com> On May 16, 11:24?am, "inhahe" wrote: > "D'Arcy J.M. Cain" wrote in messagenews:mailman.1232.1210952591.12834.python-list at python.org... > > > > > 2. Once the code is functioning, benchmark it and find the > > bottlenecks. ?Replace the problem methods with a C extension. ?Refactor > > (and check your unit tests again) if needed to break out the problem > > areas into as small a piece as possible. > > There's probably only 2 or 3 basic algorithms that will need to have all > that speed. > > > > > 3. ?If it is still slow, embed some assembler where it is slowing down. > > I won't know if the assembler is faster until I embed it, and if I'm going > to do that I might as well use it. > Although it's true I'd only have to embed it for one system to see (more or > less). > > > > >> For portability, I'd simply write different asm routines for different > >> systems. ?How wide a variety of systems I'd support I don't know. ?As a > >> bare > >> minimum, 32-bit x86, 64-bit x86, and one or more of their available forms > >> of > >> SIMD. > > > Even on the same processor you may have different assemblers depending > > on the OS. > > yeah I don't know much about that, ?I was figuring perhaps I could limit the > assembler parts / methodology to something I could write generically > enough.. and if all else fails write for the other OS's or only support > windows. ? also I think I should be using SIMD of some sort, and I'm not > sure but I highly doubt C++ compilers support SIMD. The Society for Inherited Metabolic Disorders? Why wouldn't the compilers support it? It's part of the x86 architexture, isn't it? From saluk64007 at gmail.com Wed May 28 01:07:10 2008 From: saluk64007 at gmail.com (Patrick Mullen) Date: Tue, 27 May 2008 22:07:10 -0700 Subject: Struct usages in Python In-Reply-To: References: Message-ID: I don't know if this will go through (my posts seem to have become blocked lately), but I'll give it a shot anyhow. You seem to be under a misconception that a python list is similar to a list in say, Java or other languages that have a rigid idea of variables and types. In python, a list is a list of objects - any type of object can be stored in a list. Just as you don't declare types for variables, you also don't declare types for lists. Here is your modified code: class Event(): def __init__(self, cameraEventType="", zone=99, setDay="",setTime ="", clrTime=""): self.cameraEventType = cameraEventType self.zone = zone self.setDay = setDay self.setTime = setTime self.clrTime = clrTime class EventTimeFilter: def __init__(self): self.event = [] #Create an empty list, bind to the name "event" under the "self" namespace self.event.append(Event()) #Create an event object and append to the end of the list Python won't stop you from putting other objects into self.event besides Event objects, but in practice this isn't often an issue. The real benefit, is if you subclass event or make some other type of object that is similar to events, with maybe some of the same fields, you can still store them in the list and it will play along with the rest of your code. -------------- next part -------------- An HTML attachment was scrubbed... URL: From pydev at rscorp.ab.ca Thu May 1 11:00:02 2008 From: pydev at rscorp.ab.ca (Scott SA) Date: Thu, 1 May 2008 09:00:02 -0600 Subject: Photo gallery software Message-ID: On 5/1/08, Jumping Arne (arnlen at mac.com) wrote: >I've searching for some software that would allow me to present my photos on >the web (I'm not interested a software that generates static pages that I >upload) and there are quite a few, see for example >, but I >haven't managed to find one that I like - Gallery 2 is close. > >So I've started to see if there is one that is based python (PHP isn't really >"my language") but when I search on Google almost the only thing I find are >photo galleries of snakes (to be honest I didn't know that people were *that* >interested in pythons). > >Do any anyone know if there exists photo gallery software written in Python? > >I've found > > I've been working with Photologue for a while with some nice results. It is a Django project , It includes support for tagging: It easily allows configuration of different image sizes and integrates with generic templates providing gallery and detail view support. HTH Scott From irmen.NOSPAM at xs4all.nl Mon May 19 14:25:11 2008 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Mon, 19 May 2008 20:25:11 +0200 Subject: TPCServer and xdrlib In-Reply-To: References: Message-ID: <4831c608$0$14361$e4fe514c@news.xs4all.nl> Laszlo Nagy wrote: > >> It is possible to change the serialization used by Pyro >> >> http://pyro.sourceforge.net/manual/9-security.html#pickle >> >> to the the 'gnosis' XML Pickler. >> > As I said earlier, I would not use XML. Just an example - I need to be > able to transfer image files, word and excel documents. How silly it > would be to base64encode a binary file, then put it into an XML. > > L > Fair enough. In that case, here's 5 suggestions: - use simple file copying from a mounted network drive - use http (web server) - use ftp - use scp - use rsync Why wouldn't one of these work for you? Did I miss something in your original requirements? All of the above high level protocols are very efficient in concurrently transferring files from a server to multiple clients. --irmen From pavlovevidence at gmail.com Tue May 6 16:02:12 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 6 May 2008 13:02:12 -0700 (PDT) Subject: License selection for free software References: <3a8e0a8f-3bd1-4650-9104-5c273f14b097@w7g2000hsa.googlegroups.com> <1w4gs9bk.fsf@gmail.com> <87ve1se6q5.fsf_-_@benfinney.id.au> <8763tr5ov1.fsf@gmail.com> Message-ID: <316b2772-576e-49ba-a368-e78c8930a07e@b1g2000hsg.googlegroups.com> On May 6, 1:22 pm, vivai... at gmail.com (Ville M. Vainio) wrote: > Excuse the long post. > > Ben Finney writes: > >> I guess it's safe to assume that you are not opposed to using code > >> based on more liberal license, right? :-) > > > I'm less inclined to base work on, or contribute to, a work under a > > non-copyleft license, because I have less assurance that the code will > > remain free for all recipients. > > In practice, the probability of hijacking of source code by an evil > corporation is very low for most projects. And even when it did > happen, the evil corporation would likely submit patches. The Wine project changed from MIT (I think) to LGPL because evil corporations were hijacking its source code and not submitting patches. It happens. Carl Banks From iqbaltalaat at gmail.com Fri May 16 14:53:33 2008 From: iqbaltalaat at gmail.com (I-T) Date: Fri, 16 May 2008 11:53:33 -0700 (PDT) Subject: write to specific line in file? References: Message-ID: <28ab4221-d494-4ae1-ab6f-d2f596e23d27@j22g2000hsf.googlegroups.com> Open the file inside your script in append mode. open('filename', 'wa') On May 16, 11:41?pm, globalrev wrote: > i ahve a program that takes certain textsnippets out of one file and > inserts them into another. > > problem is it jsut overwrites the first riow every time. > > i want to insert every new piece of text into the next row. > so: > 1. how do i write to a new line every time i write to the file? > > 2. if i dont want to write to a new line but just want to insert it > after the last token in the file, how do i do then? From castironpi at gmail.com Wed May 14 13:01:40 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 14 May 2008 10:01:40 -0700 (PDT) Subject: Usenet References: <6bafdf82-cf8a-42cd-9f72-d98a39fab5b5@j22g2000hsf.googlegroups.com> Message-ID: On May 14, 11:58?am, "Terry Reedy" wrote: > "Duncan Booth" wrote in message > > news:Xns9A9EA1FF16358duncanbooth at 127.0.0.1... > | I also recommend Gmane which provides a free news server for most mailing > | lists: mailing lists are a lot more manageable when gatewayed into a news > | server. If you just want to access comp.lang.python I think you'll find > the > | mailing list to which it is connected is available for free on Gmane. > > gmane.comp.python.general > > which is where I am answering this from. ?Works great. Love them opticals. From swapsun at gmail.com Wed May 7 09:01:55 2008 From: swapsun at gmail.com (swapsun at gmail.com) Date: Wed, 7 May 2008 06:01:55 -0700 (PDT) Subject: Learning question... References: <68dm40F2rekquU1@mid.uni-berlin.de> Message-ID: On May 7, 8:36?am, "Diez B. Roggisch" wrote: > swap... at gmail.com wrote: > > Any idea why the following program does not work? I was learning IO on > > Python and the following generates a TypeError: range() integer end > > argument expected, got str. > > I am a beginner. > > Because raw_input does return you as string which you need explicitly > convert to a number, e.g. doing > > i = int(input) > > Diez Thank you, Diez! From exarkun at divmod.com Fri May 2 15:53:59 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Fri, 2 May 2008 15:53:59 -0400 Subject: Non-blocking connect In-Reply-To: Message-ID: <20080502195359.6859.299919246.divmod.quotient.58224@ohm> On Fri, 02 May 2008 14:38:47 -0400, Roy Smith wrote: >In article ><1029ba0a-74e0-41d3-8397-7e326f4611bf at a9g2000prl.googlegroups.com>, > mp wrote: > >> Thanks Roy. I was just trying to understand someone else's code, but >> in the end it turns out that this was just a bug. >> >> What weirded me out was how injecting a print statement preventing the >> error from occurring, but now I get it. Without blocking, the >> connection handshake occurs in parallel after the connect_exc method >> is called. In my example, my processor reaches the send call before >> the connection manages to complete in the background. However, if you >> stick in a print statement after the connect_exc call and before the >> send call, it delays processing just long enough for the connection to >> complete, thus no exception is thrown by the send call. > >I don't really understand that last part. There shouldn't be any >background processing going on, unless there's a lot more code than you >showed. > >The three-way handshake *can't* happen in the background, because >connect_ex() has no way to know what value to return until the handshake is >completed. Let's say I send a SYN, and 15 seconds later, you send a RST >(indicating that the connection has been refused). The connect_ex() call >has to have waited the 15 seconds for this to happen so it knows to return >an appropriate error code. > >I do not understand why sticking a print statement in there should make any >difference. The background processing is going on in the kernel, where the TCP/IP implementation is. After userspace has indicated the desire to establish a connection, the kernel doesn't need any further input in order to set up that connection. So non-blocking connect_ex starts the process and the process will complete on its own (successfully or with an error) without any further socket calls from the userspace application. The right way to know when the connect attempt has actually completed (successfully or with an error) is to use a mechanism like select() to check for writeability. Once the socket is writeable, if it has a 0 SO_ERROR, the connection was successful, otherwise it failed. Jean-Paul From sjmachin at lexicon.net Sat May 10 17:05:31 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 10 May 2008 14:05:31 -0700 (PDT) Subject: Python, are you ill? References: <893925d6-a4f8-4446-9bf3-475302dbaa04@j22g2000hsf.googlegroups.com> Message-ID: <0541dfbd-e11f-45c1-8a36-33b205eb15dd@w34g2000prm.googlegroups.com> On May 11, 6:59 am, wxPytho... at gmail.com wrote: > If you are in the interactive prompt of the Python interpreter and you > do this > > print """Testing\""" or print '''Testing\''' > > you get three dots [...] as if Python expects a code block. If you > press Enter, you get three dots again, and again, and again... You > can't get out of the code block with pressing the Enter key; you have > to press Ctrl+Z (if you're in Linux) in order to get out of that code > block, which then throws you back to the Linux command line, but > before that it prints this line > > [1]+ Stopped python > > If you do > > print "Testing\" or print 'Testing\' > > you get an error, but not of you use the triple quotes. Is that a bug > in the interpreter perhaps? No. This might clue you in: >>> print """Testing\"""" Testing" >>> Cheers, John From vivainio at gmail.com Wed May 7 13:48:27 2008 From: vivainio at gmail.com (Ville M. Vainio) Date: Wed, 07 May 2008 17:48:27 GMT Subject: License selection for free software References: <3a8e0a8f-3bd1-4650-9104-5c273f14b097@w7g2000hsa.googlegroups.com> <1w4gs9bk.fsf@gmail.com> <87ve1se6q5.fsf_-_@benfinney.id.au> <8763tr5ov1.fsf@gmail.com> <6b46e4e9-4c71-47b7-aac8-3d3340b61b64@26g2000hsk.googlegroups.com> Message-ID: <3aoudmza.fsf@gmail.com> Paul Boddie writes: > original licence as well. Now, I did leave a fair amount of > information about the heritage of the code, so that anyone who is > scared of the LGPL could just go and get the original work, but that I doubt anyone is really afraid of LGPL. The only problem with LGPL is that of static vs. dynamic linking, and that is only a problem in platforms without dynamic linker (rarity these days). > You can almost never just "grab the code from somewhere without having > to think about [the] license" since even permissive licences typically > have a list of conditions that must be observed. Certainly, they Yeah, but you don't have to "worry" about license - just have the license text in source code, or a text file in binary distribution. From castironpi at gmail.com Tue May 20 09:40:26 2008 From: castironpi at gmail.com (castironpi) Date: Tue, 20 May 2008 06:40:26 -0700 (PDT) Subject: Distributing applications that use 3rd party modules References: <8728ad1c-2b4a-47db-aeda-8d2416b6bdc8@i76g2000hsf.googlegroups.com> Message-ID: On May 20, 7:56?am, Mike Driscoll wrote: > On May 17, 4:42?am, eliben wrote: > > > > > > > Hello, > > > I'm getting into Python now after years of Perl, and as part of my > > research I must understand how to do some common tasks I need. > > > I have a bunch of Windows PCs at work to which I want to distribute an > > application I've developed on my PC. All these PCs have Python 2.5 > > installed. > > > If my application contains only code I've developed, I simply zip its > > directory with .py files and send it to everyone, who can then use it > > by running the entry-point .py file. However, what if I've installed > > some 3rd party modules on my PC, and my application uses them (for > > example pyparsing, PiYAML and some others) ? I don't want to manually > > install all these packages (there may be dozens of them) on all those > > PCs (there may be dozens of those too). What is the best method I can > > use ? Naturally, I want all the non-standard packages my app uses to > > be detected automatically and collected into some kind of convenient > > distributable that is easy to pass around and run. > > > I'm aware of py2exe - tried it and it works fine. But it creates huge > > executables, and I don't want to distribute those all the time. I much > > prefer a zipped directory of .py scripts that takes some 10s of KBs. > > > Thanks in advance, > > Eli > > One way I forgot to mention is to put Python on the network (i.e. the > intranet). We do that here at work and I can develop my applications > on my machine and then put them on there for anyone to use. That way > they never have to install Python, let alone the bother of installing > dependencies. > > Mike- Hide quoted text - > > - Show quoted text - Impossible and Useless here: I assert there's no way to generate the list. a= raw_input( ) if a== 'something unknown': b= 'imp' b+= 'ort ' b+= 'os' exec( b ) From danb_83 at yahoo.com Thu May 22 01:00:30 2008 From: danb_83 at yahoo.com (Dan Bishop) Date: Wed, 21 May 2008 22:00:30 -0700 (PDT) Subject: related to python References: Message-ID: On May 21, 9:34?pm, "salil_reeves" wrote: > develop a function called standardise_phrase to convert > the user's input to a standard form for subsequent processing. This > involves: > 1. removing all inter-word punctuation, which for our purposes is > assumed to > consist only of commas (`,'), full stops (`.'), exclamation marks > (`!') or > question marks (`?'); > 2. stripping away any leading and trailing blank spaces; and > 3. replacing words in the user's input with ELIZA's preferred > vocabulary. > how it is done ?? > can anyone help me with it Yes, but I'm only as willing to put as much effort into my answer as you do into your thread titles. help(str) From duncan.booth at invalid.invalid Wed May 7 08:31:19 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 7 May 2008 12:31:19 GMT Subject: Why don't generators execute until first yield? References: <9chUj.34561$o06.23748@tornado.fastwebnet.it> Message-ID: Marco Mariani wrote: > Duncan Booth wrote: > >> It does this: >> >>>>> @greedy >> def getCommandsFromUser(): >> while True: >> yield raw_input('Command?') >> >> >>>>> for cmd in getCommandsFromUser(): >> print "that was command", cmd >> >> >> Command?hello >> Command?goodbye >> that was command hello >> Command?wtf >> that was command goodbye >> Command? > > > Not here.. > > > In [7]: def getCommandsFromUser(): > while True: > yield raw_input('Command?') > ...: > ...: > > In [10]: for cmd in getCommandsFromUser(): print "that was command", cmd > ....: > Command?hi > that was command hi > Command?there > that was command there > Command?wuwuwuw > that was command wuwuwuw > Command? > Perhaps if you'd copied all of my code (including the decorator that was the whole point of it)... From ricaraoz at gmail.com Thu May 8 13:11:00 2008 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Thu, 08 May 2008 14:11:00 -0300 Subject: python vs. grep In-Reply-To: References: <011f43ea-9bc8-499a-a3fe-dba24b47932e@c58g2000hsc.googlegroups.com> Message-ID: <48233424.1010202@bigfoot.com> Anton Slesarev wrote: > I try to save my time not cpu cycles) > > I've got file which I really need to parse: > -rw-rw-r-- 1 xxx xxx 3381564736 May 7 09:29 bigfile > > That's my results: > > $ time grep "python" bigfile | wc -l > 2470 > > real 0m4.744s > user 0m2.441s > sys 0m2.307s > > And python scripts: > > import sys > > if len(sys.argv) != 3: > print 'grep.py ' > sys.exit(1) > > f = open(sys.argv[2],'r') > > print ''.join((line for line in f if sys.argv[1] in line)), > > $ time python grep.py "python" bigfile | wc -l > 2470 > > real 0m37.225s > user 0m34.215s > sys 0m3.009s > > Second script: > > import sys > > if len(sys.argv) != 3: > print 'grepwc.py ' > sys.exit(1) > > f = open(sys.argv[2],'r',100000000) > > print sum((1 for line in f if sys.argv[1] in line)), > > > time python grepwc.py "python" bigfile > 2470 > > real 0m39.357s > user 0m34.410s > sys 0m4.491s > > 40 sec and 5. This is really sad... > > That was on freeBSD. > > > > On windows cygwin. > > Size of bigfile is ~50 mb > > $ time grep "python" bigfile | wc -l > 51 > > real 0m0.196s > user 0m0.169s > sys 0m0.046s > > $ time python grepwc.py "python" bigfile > 51 > > real 0m25.485s > user 0m2.733s > sys 0m0.375s > > -- > http://mail.python.org/mailman/listinfo/python-list > All these examples assume your regular expression will not span multiple lines, but this can easily be the case. How would you process the file with regular expressions that span multiple lines? From gagsl-py2 at yahoo.com.ar Tue May 13 06:42:03 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 13 May 2008 07:42:03 -0300 Subject: Backslash frowned upon? References: <230658ee-4b4e-48e7-b06a-88af33a5167c@25g2000hsx.googlegroups.com> Message-ID: En Tue, 13 May 2008 07:25:06 -0300, escribi?: > Why is the \ backslash character frowned upon? Can I still use it in > Python 3.0 to achieve the same thing it was designed to do? Uh... where do you get your (mis)information about 3.0? See http://docs.python.org/dev/3.0/whatsnew/3.0.html -- Gabriel Genellina From ulrich at dorda.net Sun May 25 05:47:55 2008 From: ulrich at dorda.net (Ulrich Dorda) Date: Sun, 25 May 2008 11:47:55 +0200 Subject: access interactive namespace from module (shared namespace?) Message-ID: <483935CB.6050901@dorda.net> I've got a probably embarrassing trivial problem with namespaces, but couldn't solve it myself nor find an answer in the net. Hopefully one of you guys can help me. What I want to do: Use the interactive shell and e.g define the variable a there. Then load a module and access a from within. e.g file "utest.py" def doit(): print 2*a in the shell: import utest a=3 utest.doit() <- I want this to print 2*a, but of course obtain: : global name 'a' is not defined Any change I do to a in the shell should be seen from the doit() function, any variable assignment I do in the doit() function should be seen in the shell. I guess it's somehow a namespace sharing. Actually the function doit() will contain an eval() function that should evaluate a (via a gui) dynamically inserted expression. Any one got a clue? (a clue what I try to say and how to help?!) Thanks a lot in advance!! Ulrich From jstucklex at attglobal.net Sun May 25 21:41:09 2008 From: jstucklex at attglobal.net (Jerry Stuckle) Date: Sun, 25 May 2008 21:41:09 -0400 Subject: php vs python In-Reply-To: References: <5l%Yj.77$mz3.53@fe101.usenetserver.com> <37b112d8-a3ba-446d-9d2f-d907d93c637b@w8g2000prd.googlegroups.com> <-t-dnWQ4bZN2MaTVnZ2dnUVZ_qGdnZ2d@comcast.com> <68cb8bb1-4cc5-4a28-8915-46e7d4e316d9@d1g2000hsg.googlegroups.com> <9IWdnbyQq5GKl6fVnZ2dnUVZ_oGdnZ2d@comcast.com> Message-ID: Ivan Illarionov wrote: > On Sun, 25 May 2008 20:53:28 -0400, Jerry Stuckle wrote: > >> Ivan Illarionov wrote: >>> Jerry Stuckle wrote: >>> >>>> As I've said before - good programmers can write good code in any >>>> language. >>> Yes, they can. But it may be harder to do for them in one language and >>> easier in another. >>> >>> Ivan >> Not for a good programmer it isn't. I've known a few good programmers >> in my 40+ years of programming. I've known a lot more poor programmers >> who think they're good. > > I can't argue with your experience. I don't think that I'm good > programmer. I want to be better. And I hope that when I'll have 48+ years > experience I won't have to use it as argumentum ad hominem. No ad hominems on my part. I said nothing about you or your abilities. I spoke only of programmers I have known, both good and poor. The the good programmers are able to adapt to the language and make the most of whatever language they're using. The result is good code. OTOH, poor programmers I have known have found all kinds of excuses - from the language itself to lack of requirements, to anything else they can blame, except the real root of the problem. If you take exception to that, then I'm sorry for you. -- ================== Remove the "x" from my email address Jerry Stuckle JDS Computer Training Corp. jstucklex at attglobal.net ================== From dullrich at sprynet.com Mon May 19 07:29:18 2008 From: dullrich at sprynet.com (David C. Ullrich) Date: Mon, 19 May 2008 06:29:18 -0500 Subject: "indexed properties"... References: <7o7r245pb3kqk42odihmf95sifpbbv0rqp@4ax.com> Message-ID: <7sm234hp8u9ia850uaopn3amtq95jqbt5t@4ax.com> On Sun, 18 May 2008 18:18:34 +0200, pataphor wrote: >In article , >dullrich at sprynet.com says... > >> Is there some reason that would be better? It would make a lot >> of the code more complicated. Ok, it would require only one >> bit of added code, I suppose, but I don't see the plus side. > >The plus side is you give up an untenable position :-) Maybe you could be more specific? Various "positions" I've taken in all this may well be untenable, but I can't think of any that have anything to do with whether the data should be a single list instead of a list of lists. (The only way I can parse this to make it relevant is to assume that the position you're referring to is that a list of lists is better than a single list. If so: First, I haven't said that it was. Second, saying "B is untenable" is not much of an answer when someone asks why you say A is better than B.) >And to address an >item in a matrix costs two lookups, row and column, while an array needs >only one. The phrase "premature optimization" springs to mind. This is _Python_ we're talking about. Supposing you're right that doing two lookups _in Python_ is faster than doing one lookup plus the calculuation col + row*width _in Python_, it can't make enough difference to matter. In the sort of application I have in mind things already happen "instantaneously". The point is not to improve on NumPy. Trying to improve on NumPy in pure Python code would be silly - if I wanted optimized large matrices I'd _use_ NumPy. The point is just to give a simple "intuitive" way to manipulate rows and columns in small matrices. So I'm not looking ahead to the future, things are not scalable? The thing is not _supposed_ to scale up to large matricies. If a person were dealing with large matricies then almost all of it would need to be rewritten (and if a person were dealing with really large matrices then trying to do the thing in pure Python would be silly in the first place, and insisting on being able to write things like "m.row[0] = m.row[1] + m.row[2]" could very well be a totally wrong approach to begin with - I'd figure out the operations I expected to need to do and write functions to do them.) Really. In one of the intended applications the matrix entries are going to be home-made Rationals. Just adding two of those guys takes a long time. It's still more than fast enough for the intended application, but [oh, never mind. Sorry about the argumentative tone - I _would_ like to know which "untenable position" you're referring to... >P. David C. Ullrich From Lie.1296 at gmail.com Fri May 30 05:39:20 2008 From: Lie.1296 at gmail.com (Lie) Date: Fri, 30 May 2008 02:39:20 -0700 (PDT) Subject: Assignment and comparison in one statement References: Message-ID: <5c5744cb-d801-48aa-b34d-c03c036d4885@w8g2000prd.googlegroups.com> On May 24, 5:59?am, Johannes Bauer wrote: > Hello group, > > I'm just starting with Python and am extremely unexperienced with it so > far. Having a strong C/C++ background, I wish to do something like > > if (q = getchar()) { > ? ? ? ? printf("%d\n", q); > > } > > or translated to Python: > > if (p = myfunction()): > ? ? ? ? print p > > However, this "assignment and comparison" is not working. What's the > "Python way" of doing this kind of thing? > > Thanks a lot, > Johannes Python often tries to avoid things it considers "bad design" in a language, "assignment and comparison" is, for example, a bad design because it is easily mistaken with "equality comparison", among other things. This avoidance of bad design sometimes go as far as making "the way" to do something in python completely different than doing the same thing in other languages, thus it is always a good idea to state what you intent in doing, rather than stating what you think you need to do. An example is python's notion for 'for' loop, which can only loop a list, most people coming from other languages would use range/xrange here and there, a pythonic code would only rarely use a range/xrange (usually in situations where the number of repetition is constant). Try reasking by stating what you wanted to do, rather than the abstract question that states what you think you need to do you've just asked. What functions you wanted to use and for what? From castironpi at gmail.com Wed May 14 08:50:13 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 14 May 2008 05:50:13 -0700 (PDT) Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <5b0e3f70-afde-4480-8713-e7113b1250d7@x35g2000hsb.googlegroups.com> <1f537717-00d0-48ee-99b6-7125b96a6133@t12g2000prg.googlegroups.com> <68t4o0F2vaoncU1@mid.uni-berlin.de> <2a32179a-9439-449c-bd07-fff6a4075aee@s50g2000hsb.googlegroups.com> <7ee5dffd-df8f-46f0-bd78-c81ac0418a9a@d77g2000hsb.googlegroups.com> <65ef773e-a1c3-4adb-a18b-e8b8451efe5e@b5g2000pri.googlegroups.com> <68trmmF2vjivnU1@mid.uni-berlin.de> <0bda514d-7e61-45ff-826b-9e64999b18c3@z24g2000prf.googlegroups.com> Message-ID: <31f96940-b658-48ed-9227-29c2d4826acf@d1g2000hsg.googlegroups.com> On May 14, 5:53?am, "J. Clifford Dyer" wrote: > On Tue, 2008-05-13 at 10:33 -0700, Dave Parker wrote: > > > You sound like a commercial. > > > Get Flaming Thunder for only $19.95! ?It slices, it dices! > > > > And while programs and libraries written in assembly may be twice as fast > > > as programs and libraries written in C, ... > > > It's a myth that they're only twice as fast. ?An experienced assembly > > language programmer can usually get out at least a factor of 5 by > > using tricks such as cache-coherence, carry flag tricks, stack > > manipulations, etc. > > > > ... they're real hell to maintain. > > > That's also a myth. ?For example, if C is easy to maintain, why is > > Flaming Thunder the only single-asset 8-by-8 shotgun cross compiler in > > the world? ?There should be lots of single-asset 8-by-8 shotgun cross > > compilers written in C, if C is easier to maintain. > > Not only is it the world's only "single-asset 8-by-8 shotgun cross > compiler," but according to google, it's also the world's only "shotgun > cross compiler" period. ?But I guess if you make up your own terminology > you're bound to be unique. ?:) ?Do you mind if I ask: what exactly is a > single-asset 8x8 shotgun cross compiler, and what makes that of any > value to me? > > Cheers, > Cliff- Hide quoted text - > > - Show quoted text - You can examine those criteria by trying to buy a chair. Is Tron good practice for Opticals? Who wants a memory lane crossing? Is compiling bad? From bignose+hates-spam at benfinney.id.au Thu May 1 23:24:01 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 02 May 2008 13:24:01 +1000 Subject: #!/usr/bin/env python vs. #!/usr/bin/python References: Message-ID: <87abj91j8u.fsf@benfinney.id.au> Yves Dorfsman writes: > On UNIX, some people use > #!/usr/bin/env python > > While other use > #!/usr/bin/python You haven't indicated your understanding of what the difference in meaning is, so I'll explain it for those who might not know. The shebang line (the initial line of the file beginning with "#!") takes advantage of OS kernels that determine how to execute a file based on the first few bytes of the file. The shebang line tells the kernel that this file should be executed by passing it as input to a process started by another command. The specified command takes the form of a fully-qualified file path, and zero or one arguments to the program. That command is then executed by the kernel, and the Python program file is passed as input to the resulting process. The difference between the two is thus what command is executed to interpret the Python program. * "#! /usr/bin/env python" will run the command "/usr/bin/env python". The 'env(1)' manual page says its purpose is to "run a program in a modified environment", but it also has the effect that the command is searched on the current PATH variable, and executed based on the first occurrence. * "#! /usr/bin/python" will run the command "/usr/bin/python", which is of course the system Python instance as installed by most OS packaging systems. That command is run, and the result is the Python interpreter. > Why is one preferred over the other one ? I've never clearly understood why people want to use "#! /usr/bin/env python", which is prone to finding a different Python from the one installed by the operating system. I'd be interested to see what responses are in favour of it, and what the reasoning is. One possible reason is that the programmer is attempting to allow for systems where Python has been installed, but not from an operating system package. I much prefer "#! /usr/bin/python" because I want my Python programs to, by default, be run with the default Python, and depend on Python being installed by the operating system's package manager. On systems that use shebang lines and that actually have standardised filesystem locations, the default Python is found at '/usr/bin/python'. -- \ "Any sufficiently advanced bug is indistinguishable from a | `\ feature." ?Rich Kulawiec | _o__) | Ben Finney From geoldr at gmail.com Thu May 22 15:32:25 2008 From: geoldr at gmail.com (Geoldr) Date: Thu, 22 May 2008 12:32:25 -0700 (PDT) Subject: Restarting a program References: <52fd6be0-41f9-4c84-b165-7fd9ce998c42@p25g2000hsf.googlegroups.com> <26169d93-32c4-412e-aa15-e6015c0204bb@z24g2000prf.googlegroups.com> Message-ID: <1fafb41e-4bf4-495d-ad81-12aa1e431c9a@w5g2000prd.googlegroups.com> On May 22, 11:58?am, Mike Driscoll wrote: > On May 22, 1:38?pm, Geoldr wrote: > > > > > On May 22, 10:07?am, Mike Driscoll wrote: > > > > On May 22, 10:59?am, Geoldr wrote: > > > > > Hello all, I have written a simple program, and at the end of it, > > > > instead of it closing I would like it to restart from the beggining. > > > > Is there a way to do this? Put my code into a class function, or > > > > something? > > > > I guess I could do a while loop, but I think if there is a way to run > > > > my code if it's in a class would be an easier option. I can't seem to > > > > find many guides online but maybe I have not been looking in the right > > > > places. > > > > > Anybody have any ideas? > > > > Putting your code in a function or class is probably the way to go. > > > When I was doing C++, we'd just use a while loop for simple stuff, > > > though. > > > > It really shouldn't be all that hard to tell the code to call up the > > > beginning of the program again. > > > > Mike > > > That's what I am trying to figure out, but it doesn't seem to work. Do > > you have any example code of classes/functions that work for you? > > No...but I through some concept code together that does the basics: > > > > def repeater(): > > ? ? for i in range(10): > ? ? ? ? print i > > def main(): > ? ? ret = 'Y' > ? ? while 1: > ? ? ? ? if ret.upper() == 'Y': > ? ? ? ? ? ? repeater() > ? ? ? ? else: > ? ? ? ? ? ? print 'Program finished...goodbye!' > ? ? ? ? ? ? break > ? ? ? ? ret = raw_input('Do you want to continue? (Y/N)') > > if __name__ == '__main__': > ? ? main() > > > > I found that using the while was the easiest to create on short > notice. You could probably do it with recursion too, but I'm not > especially good at that. > > Another idea is to have some kind of sentinel value that both > functions can access and use it somehow to tell whether or not to > repeat. > > Hope that helps you get going. > > Mike Thank you, the "def" option works the best. From onsen-neko at gmx.net Thu May 8 03:05:49 2008 From: onsen-neko at gmx.net (Daniel Marcel Eichler) Date: Thu, 8 May 2008 09:05:49 +0200 Subject: Am I missing something with Python not having interfaces? In-Reply-To: <200805071639.30414.kyrie@uh.cu> References: <45de2f7e-484a-4871-bbaa-bf7eed5dfa40@x35g2000hsb.googlegroups.com> <200805072119.30744.onsen-neko@gmx.net> <200805071639.30414.kyrie@uh.cu> Message-ID: <200805080905.49342.onsen-neko@gmx.net> Am Mittwoch 07 Mai 2008 22:39:30 schrieb Luis Zarrabeitia: > There you have it, interfaces are not enough to ensure that the > implementors actually implement the methods. They are useful for > warning at compile time if there is a missing method, but nothing > more. It's not the fault of the enviroment, if the coder is to stupid to use it the right way. > I believe you could achieve a very similar warning in python > using some kind of Interface metaclass (too lazy right now to hack a > proof of concept, but it looks doable). Of course. And unlike Javas interfaces, it ensure a more dynamic coding-style, without great tools which check all the time for correct behaviour. From http Fri May 2 16:14:37 2008 From: http (Paul Rubin) Date: 02 May 2008 13:14:37 -0700 Subject: is +=1 thread safe References: <4819DA2D.3030508@ggmail.com> <7xbq3pjhav.fsf@ruckus.brouhaha.com> <87bq3pglkf.fsf@mulj.homelinux.net> Message-ID: <7xr6ckfope.fsf@ruckus.brouhaha.com> Hrvoje Niksic writes: > Since the += operator is not compiled into a single bytecode > instruction, it needs the lock. Aha, you are right. What I was remembering is that xrange.next is atomic in CPython, i.e. you can say something like counter = xrange(10000) and then a = counter.next() doesn't need a lock. I am personally squeamish about relying on things like this but apparently it is a standard idiom. I will guess, but I haven't checked and I don't remember hearing, that itertools.count() also works like that. From michael at stroeder.com Mon May 5 03:35:10 2008 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Mon, 05 May 2008 09:35:10 +0200 Subject: config files in python In-Reply-To: <44f9662d-a88d-418c-a11d-b7b472b01fc3@j33g2000pri.googlegroups.com> References: <44f9662d-a88d-418c-a11d-b7b472b01fc3@j33g2000pri.googlegroups.com> Message-ID: sandipm wrote: > In my application, I have some configurable information which is used > by different processes. currently I have stored configration in a > conf.py file as name=value pairs, and I am importing conf.py file to > use this variable. it works well > > import conf > print conf.SomeVariable > > but if I need to change some configuration parameteres, it would need > me to restart processes. reload(conf) http://docs.python.org/lib/built-in-funcs.html#l2h-61 But you should carefully consider what updating the configuration means in your application. Ciao, Michael. From marco at sferacarta.com Wed May 7 08:28:06 2008 From: marco at sferacarta.com (Marco Mariani) Date: Wed, 07 May 2008 14:28:06 +0200 Subject: Why don't generators execute until first yield? In-Reply-To: <9chUj.34561$o06.23748@tornado.fastwebnet.it> References: <9chUj.34561$o06.23748@tornado.fastwebnet.it> Message-ID: Marco Mariani wrote: > Not here.. Oh, sorry, I obviously didn't see the @greedy decorator amongst all the quoting levels. Anyway, the idea doesn't make much sense to me :) From grayaii at gmail.com Wed May 7 16:25:49 2008 From: grayaii at gmail.com (grayaii) Date: Wed, 7 May 2008 13:25:49 -0700 (PDT) Subject: subprocess wait() waits forever, but os.system returns Message-ID: <84a23679-56e2-41b5-83eb-741a696095da@59g2000hsb.googlegroups.com> There are so many threads on this subject, but I ran across a situation on Windows that I can't figure out. I'm trying to run this little command-line exe and when I launch like this, it hangs: >>> import subprocess >>> command = r'c:\mydir\foo.exe' >>> run = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stdin=None, stderr=subprocess.PIPE, env=os.environ, universal_newlines=True) >>> returncode = run.wait() ## HANGS HERE ## I can run this exe manually via the command prompt and it returns after a few seconds, but more importantly when I run it as follows it works fine: >>> import os >>> command = r'c:\mydir\foo.exe' >>> os.system(command) ## WORKS FINE! ## Unfortunately I don't know too much about the exe (well, I do know that it spits out some stdout that I collect, but I don't know the exe's source code.) I can't figure out why the subprocess module is having a hard time with this particular exe. I've tried so many different permutations of subprocess.Popen and they all hang on this exe. Even if try to do the usual (pseudo code): while(returncode is None): returncode = run.poll() time.sleep(1) blah blah blah returncode is always None... In other words, it's hung. I can't figure out why os.system works fine, but subprocess.Popen thinks the process hasn't finished. Any ideas would be greatly appreciated. I'm all ears. From vginer at gmail.com Mon May 19 14:01:14 2008 From: vginer at gmail.com (Vicent Giner) Date: Mon, 19 May 2008 11:01:14 -0700 (PDT) Subject: Using Python for programming algorithms References: <56c15$483091b1$d4785a98$2536@cache6.tilbu1.nb.home.nl> Message-ID: Thank you very much for all the answers I've got. As far as I have understood, Python can be a good alternative, or, at least, a reasonable choice. I intend to design new algorithms for a kind of Optimization problems, and then I have to implement them and show/prove that they are good enough, in terms of effectiveness (quality of the solution that the algorithm is able to find, for some given "difficult" problems), and not mainly in terms of efficiency (time to find the solution). I mean, in order to prove that my algorithms are "good", I have to compare them with the results given by other algorithms, in terms of how much better is the solution given by my proposal, in front of the previous ones. Only comparatives in terms of "number of iterations", and not "time to find the solution", can be done (I think). And I also realize, from your posted answers, that the point is doing a good programming work, and that I will have to look very carefully at all those packages and resources you have mentioned, to do a good work at Python. Any other suggestion will be welcomed. :-) Thank you very much again! -- Vicent From gandalf at shopzeus.com Thu May 15 04:07:47 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Thu, 15 May 2008 10:07:47 +0200 Subject: Recommended way to POST with cookies? In-Reply-To: References: Message-ID: <482BEF53.1070708@shopzeus.com> Gilles Ganault wrote: > Hello > > According to Google, there seems to be several tools available, > possibly deprecated, to download data from web pages by POSTing forms > and save cookies to maintain state. > > I need to write a script under Windows with ActivePython 2.5.1.1 that > would do this: > 1. Connect through a local proxy, so I can see the whole dialog > between the Python script and the web server > 2. POST form variables > 3. Save cookies sent by the server (session cookie to keep state) > 4. Save received data into an SQLite file > > Which tools would you recommend for this type of script? > Within a day this is the second request for a browser emulator. Looks like many pepole want this. I just posted a recipe that you can try: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/572202 Best, Laszlo From duncan.booth at invalid.invalid Wed May 14 11:37:28 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 14 May 2008 15:37:28 GMT Subject: list.__len__() or len(list) References: Message-ID: Nikhil wrote: > Then why to have __len__() internal method at all when the built-in > len() is faster? Because the internal method is used internally. The idea is that you define __len__() on your objects when appropriate. You are not expected to ever call it. From cliveswan at yahoo.co.uk Fri May 9 09:40:38 2008 From: cliveswan at yahoo.co.uk (Clive_S) Date: Fri, 9 May 2008 06:40:38 -0700 (PDT) Subject: Pythonwin References: <11c8a80e-41bb-4cea-88d6-c9515e1a9d13@j22g2000hsf.googlegroups.com> Message-ID: <8afc345b-139d-4a98-bc29-cc71ef703d0a@e39g2000hsf.googlegroups.com> Hi all I downloaded (from Python) and installed python-2.4.4.msi I have python and pythonw.exe in the Python 24 folder (but not in my start menu). When I click on the pythonw.exe it is not launched?? Thanks Clive On 9 May, 14:09, Mike Driscoll wrote: > On May 9, 5:30?am, Clive_S wrote: > > > Hi > > I am trying to use Python with ArcGIS. > > I have installed Python 2.4. I have an icon for IDLE and command line. > > I do not see Python PythonWin. > > How do you install or launch pythonwin?? > > Thanks > > Clive > > I have PythonWin installed in my Start Menu --> Programs --> Python > 2.5. I may have installed the ActiveState version though. Just check > if it's there on your system and if not, you can follow Niklas's > advice. > > Mike From castironpi at gmail.com Tue May 13 11:24:01 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Tue, 13 May 2008 08:24:01 -0700 (PDT) Subject: I'm stuck in Python! References: <7ff9c6b7-ed99-49eb-8dce-9749b1287f7e@i76g2000hsf.googlegroups.com> Message-ID: <171eac06-c184-4e09-a51a-00c1f8e4eddc@d77g2000hsb.googlegroups.com> On May 13, 10:08?am, castiro... at gmail.com wrote: > Just catch throw, stuff, and information. ?I think it's fine. ?I have > an hour to write some code. ?Who wants parity stuff? > > On May 13, 8:46?am, Sanoski wrote: > > > > > Any programming that helps you solve a problem is fun and > > recreational. At least, that's how I look at it. I suppose it really > > depends on why you're doing it, what your objective is, etc. But I'd > > say, why not? > > > Tron! That's one I haven't seen in awhile. I'll have to take a mental > > note to rent the movie again someday. I always thought a game based on > > the movie hackers would be cool. Actually not based on the movie > > itself, but on that 3D computer world they kept breaking into. Ah man, > > it's so funny looking back on that film. Gibson, that's what they > > called it. It was like a 3D database. That in itself wouldn't make a > > very good game, but I suppose one could easily be created around that > > idea. Perhaps it could be combined with Lawnmower-man. You're somehow > > trapped in this 80's looking 3D world that has access to all the > > world's information. More stuff could be thrown in to make it more > > interesting. And of course, there would have to be hidden references > > or parodies to whatever movies inspired it. > > > Good luck with your project > > > Sincerely, > > Joshua > > > On May 13, 9:02?am, castiro... at gmail.com wrote: > > > > Hi all. > > > > I am trying to write to the Python newsgroup. ?I doubt (aha, but > > > doubt) that I have come to the right place. ?(Incoming "this"!) ?Is > > > this the Python newsgroup? ?I heard it was called comp.lang.python. > > > Now to repeat the subject line. ?I'm stuck in Python. > > > > Now that was fun. ?I will also try to enumerate simple screen savers > > > (graphicals, graphiclizers). ?It may be profitable on some non-bank- > > > breaking scale to compile the results. ?Shall I proceed? ?The risk is > > > "overunity", such that one person can't be at liberty to live, which > > > in some technical political arenas would be an "anarchy", but there > > > are sufficiently many of those that I will too. > > > > Does anyone want such a list, or if not, is it at least fun and > > > recreational to make it? ?The dollar would come along the lines of > > > PowerPoint (name (tm)), so it may be free to do it, very entertaining, > > > and peaceable. ?(As the above would show, you would be free to > > > approach me to -buy-; I won't oversell.) ?I like programming. ?(And is > > > Guido getting his fair share? ?I am prepared to share with him.) > > > Check in his name. > > > > I want to try to ally with other programmers and make cool games, like > > > Tron, that one party can make games for on a console, such as live > > > obstacles, incl. tear-down, and certain people have to play from time > > > to time. ?But you can't charge to do it, so it's a guaranteed game. > > > (That in virtue of that I'm typing.) ?Advantages include microspacing > > > of time. ?Very summer. > > > > Resemblances would include Dungeons & Dragons with multi-host, or > > > multi-ref small-shooter sport-likers. ?The real-time is definitely > > > attractive (duh). ?As for voice, it's not clear it's the most > > > entertaining, but I just don't have a mic. > > > > However, forseeing, I return with sailing, but that's in 3-space and > > > not even in code, as though we'd construct the Royal Navy and battle. > > > But I think we can keep it well. > > > > Thing is, someone has to play it to keep a synch (keep from falling), > > > and tap-outs would have to live. > > > > Side note: In political theory, this is known as the problem of > > > nominating a successor. ?Would it stay afloat, even for long enough to > > > make it worth the negatives, yes which do include tear-down and fall, > > > invasion of privacy, and rights infrigement? > > > > I code in Python (get the callbacks), but configurable servers could > > > spread the work out, using relays to put each person on each's own > > > turf to be a ref. ?If you feed the roles, it could get really fun, and > > > c-l-py is the appropriate place to start such a thing, both and ask if > > > it's been done before.- Hide quoted text - > > > - Show quoted text -- Hide quoted text - > > - Show quoted text - My head tongue is itching. My tongue is itching my had head. From gagsl-py2 at yahoo.com.ar Tue May 6 01:14:48 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 06 May 2008 02:14:48 -0300 Subject: How can we write a class factory that dynamically redefines the __init__ function etc. References: <4878ad7b0805051634k2666943bmd71fa9947816ab68@mail.gmail.com> Message-ID: En Mon, 05 May 2008 20:34:32 -0300, John Schroeder escribi?: > Basically I have some classes like this: > > > ############################################################################### > # 0x01: ModeCommand > ############################################################################### > class ModeCommand: > """This is the Mode Command Packet class.""" > def __init__(self, mode, command, id=0x01): > """The unspecial init function.""" > self.mode = mode > self.command = command > self.id = id > > def RawData(self): > return [self.id, self.mode, self.command] > > def __getitem__(self, index): > """[] operator (read): indexes from the byte data.""" > return self.RawData()[index] > > def __str__(self): > """Print a nice thing.""" > string = "Mode = %d\n" % self.mode + \ > "Command = %d\n" % self.command + \ > "ID = %d\n\n" % self.id > return string > > ############################################################################### > # 0x02: CallRequest > ############################################################################### > class CallRequest: > """This is the Call Request Packet class. (Look familiar?)""" > def __init__(self, service_number, id=0x02): > """The unspecial init function.""" > self.service_number = service_number > self.id = id > > def RawData(self): > return [self.id, self.service_number] > > def __getitem__(self, index): > """[] operator (read): indexes from the byte data.""" > return self.RawData()[index] > > def __str__(self): > """Print a nice thing.""" > string = "Service Number = %d\n" % self.service_number + \ > "ID = %d\n\n" % self.id > return string > > > ############################################################################### > # Test Code > ############################################################################### > x = ModeCommand(mode=1, command=0) > print x[:] > print x > y = CallRequest(service_number=2001) > print y[:] > print y > > > Which is ok but I had to do this over 100 times. It is difficult to > maintain and no one else can understand what the heck I did here. So I > was > trying to look a metaclasses to do something fancy like this: You don't need a metaclass, nor a class factory. You only need a base class. __getitem__ is the same on both classes, and presumably on all: move it to the base class. And the only difference between both versions of __init__, RawData and __str__ is the name and order of the attributes: let's make them a parameter, a class attribute. The default id attribute may be a class attribute too. So in principle, if you have the right base class, the subclasses could be defined as simply as: class ModeCommand(Base): """This is the Mode Command Packet class.""" parameters = "mode command id".split() id = 0x01 class CallRequest(Base): """This is the Call Request Packet class. (Look familiar?)""" parameters = "service_number id".split() id = 0x02 and that's all. Now we have to write the Base class: class Base(object): parameters = None # redefined in all subclasses id = None def __init__(self, **kw): assert self.parameters is not None # must be redefined for name in kw: if name in self.parameters: setattr(self, name, kw[name]) else: raise NameError, "unknown parameter: %s" % name assert self.id is not None # must be redefined def RawData(self): return [getattr(self, name) for name in self.parameters] def __getitem__(self, index): return self.RawData()[index] def __str__(self): return '\n'.join( ["%s = %r" % (name, getattr(self, name)) for name in self.parameters]) py> x = ModeCommand(mode=1, command=0) py> print x[:] [1, 0, 1] py> print x mode = 1 command = 0 id = 1 py> y = CallRequest(service_number=2001, id=13) py> print y[:] [2001, 13] py> print y service_number = 2001 id = 13 (the convention is to use lowercase names for attributes: rawdata instead of RawData) -- Gabriel Genellina From arituay at gmail.com Fri May 16 16:14:01 2008 From: arituay at gmail.com (Chad Wilhite) Date: Fri, 16 May 2008 16:14:01 -0400 Subject: morning in Python In-Reply-To: <5504f9ac0805161154k1fec9250y9763e6d6c31715d@mail.gmail.com> References: <409ea9f1-9774-4bf2-abac-2daf997bc97f@c65g2000hsa.googlegroups.com> <19286799-53b1-4ba9-bb16-e3f963da7dc6@m3g2000hsc.googlegroups.com> <28kXj.142759$Er2.39732@bignews6.bellsouth.net> <5504f9ac0805161154k1fec9250y9763e6d6c31715d@mail.gmail.com> Message-ID: <3c50a9820805161314h363ad017r6652de7822d2b7c2@mail.gmail.com> On Fri, May 16, 2008 at 2:54 PM, Dan Upton wrote: > On Fri, May 16, 2008 at 2:12 PM, inhahe wrote: > > > > "George Sakkis" wrote in message > > news:19286799-53b1-4ba9-bb16-e3f963da7dc6 at m3g2000hsc.googlegroups.com... > > On May 16, 11:58 am, "inhahe" wrote: > >> I'm not an expert in this but what does it mean to emphasize state? It > >> seems the opposite of that would be a) functional programming, and b) > >> passing parameters instead of using global or relatively local > variables. > >> And maybe c) coroutines (generators as implemented in Python), although > >> perhaps coroutines could be said to emphasize state inasmuch as they go > >> out > >> of their way to capture, objectify and reuse it (Stackless' > microthreads, > >> even moreso). And Python seems to be well-noted for implementing some > >> functional programming methodology, and as for passing parameters it's > >> just > >> as object-oriented as the rest of them. > >> > >> But as I said, I'm not an expert, so let me know if I've gone astray.. > >> > >> > I have a proposition to ask you all: Python emphasizes state. Is it > >> > true? > > > > Please don't feed the bots. > > > > -- > > > > > > I figured the question was interesting enough to warrant discussion > whether > > it was a bot or not. But i'm not an avid forum user, so maybe I'm wrong. > > > > Also, if it's a bot I'm floored and the man who wrote it could probably > > solve cancer and world hunger with five lines of asm. > > > > Yeah... when he/she/it first appeared the replies were at least mostly > lucid, if not necessarily helpful, and spawned a few interesting > discussions. Recently it's gone downhill... Could be some sort of bot > that was trying to learn 'speech' patterns and it overloaded its > database. (I've seen that happen on at least one chatbot...) > -- > http://mail.python.org/mailman/listinfo/python-list > I am trying to filter out this bot via my gmail account but what ends up happening is that any thread it posts ends up being deleted instead of just its individual posts. Does anyone know how to filter out just a specific user in gmail thread view? Thanks, Chad -------------- next part -------------- An HTML attachment was scrubbed... URL: From arnodel at googlemail.com Wed May 28 12:59:42 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Wed, 28 May 2008 17:59:42 +0100 Subject: accessing class attributes References: <5827888d-4e9b-45bd-9361-108714c9043a@m45g2000hsb.googlegroups.com> Message-ID: eliben writes: > Hello, > > I have a game class, and the game has a state. Seeing that Python has > no enumeration type, at first I used strings to represent states: > "paused", "running", etc. But such a representation has many > negatives, so I decided to look at the Enum implementation given here: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/413486 > > So, I've defined: > > class Game: > self.GameState = Enum('running', 'paused', 'gameover') > > def __init__ > ... etc > > Later, each time I want to assign a variable some state, or check for > the state, I must do: > > if state == self.GameState.running: > > This is somewhat long and tiresome to type, outweighing the benefits > of this method over simple strings. > > Is there any better way, to allow for faster access to this type, or > do I always have to go all the way ? What do other Python programmers > usually use for such "enumeration-obvious" types like state ? Why not define GameState outside your Game class? Then you can write: if state == GameState.running which is slightly shorter. Or you could do: class Game: RUNNING, PAUSED, GAMEOVER = 0, 1, 2 and test like this: if state == Game.RUNNING Or, I've just thought of this simple state class: class State(object): def __init__(self, state): object.__setattr__(self, '_state', state) def __getattr__(self, attr): return attr == self._state def __setattr__(self, attr, val): object.__setattr__(self, '_state', attr) >>> state = State('running') >>> state.running True >>> state.paused False >>> state.paused = True >>> state.paused True >>> state.running False So you could write: if state.running: ... -- Arnaud From szrRE at szromanMO.comVE Sat May 31 01:40:03 2008 From: szrRE at szromanMO.comVE (szr) Date: Fri, 30 May 2008 22:40:03 -0700 Subject: The Importance of Terminology's Quality References: <4840ab73$0$90274$14726298@news.sunsite.dk> Message-ID: Arne Vajh?j wrote: > Stephan Bour wrote: >> Lew wrote: >> } John Thingstad wrote: >> } > Perl is solidly based in the UNIX world on awk, sed, bash and C. >> } > I don't like the style, but many do. >> } >> } Please exclude the Java newsgroups from this discussion. >> >> Did it ever occur to you that you don't speak for entire news groups? > > Did it occur to you that there are nothing about Java in the above ? Looking at the original post, it doesn't appear to be about any specific language. -- szr From http Tue May 20 20:59:07 2008 From: http (Paul Rubin) Date: 20 May 2008 17:59:07 -0700 Subject: feature proposal, debug on exception Message-ID: <7xtzgsqxpg.fsf_-_@ruckus.brouhaha.com> There's an occasional question here about how to get python to launch pdb on encountering an uncaught exception. The answer is to look in some ASPN recipe and do some weird magic. I guess that works, but it's another thing to remember or keep looking up when the occasion arises (some program crashes unexpectedly). I find myself manually adding tracing instead, finding out that I did it wrong and having to re-launch a long-running program, etc. I'd like to propose that debug-on-exception be made into a standard feature that is easy to enable, e.g. with a command line option or with a simple pdb call immediately after the import: import pdb pdb.debug_on_exception(True) ... Would there be big obstacles to this? It would have saved me considerable hassle on a number of occasions. I'm constantly processing large data sets that will munch along happily for hours and hours before hitting some unanticipated condition in the data, and it would be great to trap immediately rather than have to analyze the resulting stack dump and restart. From jeffober at gmail.com Sat May 17 08:23:32 2008 From: jeffober at gmail.com (Jeff) Date: Sat, 17 May 2008 05:23:32 -0700 (PDT) Subject: Help on thread pool References: <323a8e66-7cc0-4d1f-9d7a-fc70f0c0a442@56g2000hsm.googlegroups.com> Message-ID: <262b4f46-f3d6-4a29-b7a6-91eb279d1f29@j22g2000hsf.googlegroups.com> Your worker threads wait around forever because there is no place for them to exit. Queue.get() by default blocks until there is an item in the queue available. You can do something like this to cause the worker to quit when the queue is empty. Just make sure that you fill the queue before starting the worker threads. from Queue import Queue, Empty # in your worker while True: try: item = q.get(block=False) except Empty: break do_something_with_item() q.task_done() You can also use a condition variable and a lock or a semaphore to signal the worker threads that all work has completed. From gagsl-py2 at yahoo.com.ar Sat May 24 15:54:12 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 24 May 2008 16:54:12 -0300 Subject: persistent deque version 4 References: <29451c2a-cb0a-43a6-b140-6c16e3cb46ac@c65g2000hsa.googlegroups.com> Message-ID: En Thu, 22 May 2008 12:20:56 -0300, inhahe escribi?: > I thought about the fact that a decorator is merely syntactic sugar, so it > shouldn't have any closure magic that I can't make myself, and I realized > that I could have done it the following way: > > def makefunc(func): > def func2(instance, *args): > result = func(instance, *args) > instance.save() > return result > return func2 Using functools.wraps is better because it helps to preserve the function name and signature: def makefunc(func): @wraps(func) def wrapper(self, *args, **kwds): result = func(self, *args, **kwds) self.save() return result return wrapper -- Gabriel Genellina From benjamin.kaplan at case.edu Tue May 27 12:42:21 2008 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 27 May 2008 12:42:21 -0400 Subject: New chairman In-Reply-To: <0b18caad-4fbf-46e8-887f-ce29963e24a0@m3g2000hsc.googlegroups.com> References: <3720fb99-ac37-469b-b8ce-ece3ed27b8e5@m36g2000hse.googlegroups.com> <6a2ndjF35q29pU1@mid.uni-berlin.de> <0b18caad-4fbf-46e8-887f-ce29963e24a0@m3g2000hsc.googlegroups.com> Message-ID: On Tue, May 27, 2008 at 11:48 AM, Sverker Nilsson wrote: > Good luck to you to. Its just that it .. well it has never been easy > for me to introduce Python at work. This py3k, if I like it or not, is > not making it easier. > > Praktical, pragmatic, you know --- as I said, its not broken so lets > brake it > > I just try to get things to work. And with some style too. Their > connected. I think a 6 cylinder engine is one of the most stylist > things there are. And when I was at a museum in Stocholm, I saw Henry > Fords original enginge and was amazed, it looks just like the one in > dads car. > > Its not about changing and yes I dislike py3k, till somebody can > convince me otherwise > > Guido just seems to not care to post here anyways, so we can try to > make our own branch/business > > Just because Guido doesn't post to the python users' mailing list doesn't mean he isn't involved with the continuing development of Python. > > S. > > On May 27, 5:24 pm, "Diez B. Roggisch" wrote: > > Sverker Nilsson wrote: > > > I was talking about Guido van Rossum > > > > > The one who decides, so far when people agree > > > > > But we can make a new fork > > > > Good luck with that. Weren't you the one concerned about changes in Py3K > > that forced you to change your memory profiler? Now you want to introduce > a > > *third* codebase beside python2.x and python3.x? Interesting course of > > action. > > > > > He is the originator, but now it seems, for me, it is hanging out in > > > the air > > > > Why do you think so? Because you don't like Py3K? > > > > > So we need some new leadership > > > > > From somebody, somebody like you perhaps. Or me. > > > > Well - be my guest to form your own cult. > > > > Diez > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ivan.illarionov at gmail.com Thu May 1 19:54:10 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Thu, 1 May 2008 23:54:10 +0000 (UTC) Subject: Best way to store config or preferences in a multi-platform way. References: <790cec6c-b057-4a2d-bc2c-e683630c1127@w7g2000hsa.googlegroups.com> <52a268cc-dae7-4eda-81df-cc82dbcbdcd7@56g2000hsm.googlegroups.com> <071d4536-2b40-4b75-87e1-096a1773f886@f63g2000hsf.googlegroups.com> Message-ID: On Thu, 01 May 2008 16:32:00 -0700, Carl Banks wrote: > On May 1, 4:50 pm, Ivan Illarionov wrote: >> On Thu, 01 May 2008 11:56:20 -0700, Carl Banks wrote: >> > On May 1, 1:30 pm, Ivan Illarionov wrote: >> >> On Thu, 01 May 2008 09:45:28 -0700, Carl Banks wrote: >> >> > On May 1, 12:11 pm, Jon Ribbens >> >> > wrote: >> >> >> On 2008-05-01, Ivan Illarionov wrote: >> >> >> >> > IMO .ini-like config files are from the stone age. The modern >> >> >> > approach is to use YAML (http://www.yaml.org). >> >> >> >> You mean YAML isn't a joke!? It's so ludicrously overcomplicated, >> >> >> and so comprehensively and completely fails to achieve its stated >> >> >> main goal of being "readable by humans", that I had assumed it >> >> >> was an April Fool along the lines of Intercal or brainf***. >> >> >> > YAML, ISTM, took a simple concept that worked for small, >> >> > straightforward data, and tried to make into a format that could >> >> > anything anywhere, with disastrous results. It's not unlike Perl >> >> > in this regard. It's quite ridiculous. >> >> >> > My recommendation to the OP would be: >> >> >> > If you intend to write a GUI that completely sets all the options, >> >> > use XML. You can bet there are some users who would prefer text >> >> > editing options files, and XML, while not the most readable format >> >> > available, at least gives users the option. >> >> >> > If you don't intend to write a GUI to do that, write a simple text >> >> > file parser (if the options are simple), use ConfigParser, or use >> >> > a Python file that you exec. >> >> >> > Store the file in $HOME/.appname/config.ext on Unix, $USERDIR/ >> >> > ApplicationData/Appname/config.ext on Windows. I don't recommend >> >> > using the Windows registry to store options; use it to modify >> >> > Windows behavior (like file associations) but keep your own >> >> > program's options in your own file. >> >> >> If you don't like YAML, use JSON or something similar -- XML is >> >> overkill and .INI is too limited. >> >> > I don't think you know the OP's requirements enough to know whether >> > INI or XML is suitable. You're welcome to suggest alternatives but >> > what I suggested is fine. >> >> > As for XML being overkill for anything, I highly disagree. XML is >> > suitable for the smallest tasks. These days I use XML for almost all >> > my data exchange needs: including conf files. Elementtree makes it >> > possible to process XML and pull out some typical data in ten or so >> > lines of code. What could possibly be overkill about that? >> >> > Carl Banks >> >> I used XML for almost everything in the past until I found YAML. >> Elementtree makes it easy but not easy enough. > > I'm honestly very happy for you that you have found the data transfer > format that you are happy with, but I'm sorry, that doesn't amount to a > blanket invalidation of everything you've ever tried and rejected. > > >> The most powerful thing >> about YAML is that it was designed to map directly to native data types >> in languages like Python (see another my post in this thread for >> example). And this means that simple YAML files will always be easier >> to process in Python than XML or INI. And this in turn means that OP >> with any requirements will have to write less code to read and write >> his config files. > > I will mention that Python already has, built in, a data transfer format > that maps directly to Python types: pickle. > > And not only that, it's more readable than YAML. > > > I will also add that what you think of as a strength is not always > thought of as a strength by everyone. In my early days of Python, I > would use pickle for all kinds of things. I've now pretty much switched > entirely to XML, because I no longer believe that direct correspondance > to Python types is a good thing; at least it isn't for me. There is a > very basic reason for this: whenever I write a pair of tools, one to > output some XML data, and another further down the chain to read it back > in, I hardly ever want the data to have the same structure in memory in > both tools. For me, YAML or pickle would not gain me anything; I'd be > doing all that reformatting anyway. Agree, all depends on programmer's preferences. > Of course, the OP wasn't talking about data transfer, he was talking > about a freaking config file. Reading in a config file is a ridulously > silly thing to try to hyperoptimize. Do you really want him to add an > extra dependency just to reduce code used by five lines? > > > Carl Banks No, all I want is to give the OP a useful alternative and make him aware of the latest trend in the config file formats. -- Ivan From johnjsal at NOSPAMgmail.com Wed May 14 22:55:57 2008 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 14 May 2008 22:55:57 -0400 Subject: Accepting text input References: <72QVj.262833$pM4.115744@pd7urf1no> <84QVj.133083$rd2.94188@pd7urf3no> Message-ID: <20080514225557.2617ab7b.johnjsal@NOSPAMgmail.com> On Thu, 15 May 2008 02:36:29 GMT Collin wrote: > So the .lower() string method is just to convert the string to lowercase > letters so that you don't have to type a bunch of if - then statements > in both cases, I'm assuming? You can also type: dir(str) to get a list of all the methods you can call on a string object. If you see anything interesting, then type: help(str.) # e.g. help(str.split) to find out how it works. :) From bruno.desthuilliers at gmail.com Mon May 12 13:42:30 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Mon, 12 May 2008 10:42:30 -0700 (PDT) Subject: do you fail at FizzBuzz? simple prog test References: <39709320-66e1-40e9-a351-c769c9a94585@x41g2000hsb.googlegroups.com> Message-ID: <688a0f5a-2cdf-45ca-abe7-5bbb89aac32f@s50g2000hsb.googlegroups.com> On 12 mai, 09:00, "Gabriel Genellina" wrote: > En Sat, 10 May 2008 22:12:37 -0300, globalrev escribi?: > > > > >http://reddit.com/r/programming/info/18td4/comments > > > claims people take a lot of time to write a simple program like this: > > > "Write a program that prints the numbers from 1 to 100. But for > > multiples of three print "Fizz" instead of the number and for the > > multiples of five print "Buzz". For numbers which are multiples of > > both three and five print "FizzBuzz". > > > for i in range(1,101): > > if i%3 == 0 and i%5 != 0: > > print "Fizz" > > elif i%5 == 0 and i%3 != 0: > > print "Buzz" > > elif i%5 == 0 and i%3 == 0: > > print "FizzBuzz" > > else: > > print i > > > is there a better way than my solution? is mine ok? > > Is it correct? Did you get at it in less than 15 minutes? If so, then it's OK. > The original test was not "write the most convoluted algorithm you can think of", nor "write the best program to solve this". It was a *practical* test: if you can't get anything remotely working for such a simple problem in 15 minutes, we're not interested in your services. > > (We used this question last year - some people gave a sensible answer in less than 5 minutes, but others did not even know how to start) I just can't believe someone applying for a programmer position cannot provide a sensible anwser in 5 or less minutes. From pball.benetech at gmail.com Mon May 26 02:33:00 2008 From: pball.benetech at gmail.com (pball.benetech at gmail.com) Date: Sun, 25 May 2008 23:33:00 -0700 (PDT) Subject: set partition question References: <7b64328e-d4e0-4ec1-8918-3cab94e2f815@e39g2000hsf.googlegroups.com> <3cf66f61-5a7e-44a2-8cc4-b879269fd98b@y22g2000prd.googlegroups.com> <3a550801-6e43-4c81-9749-7cb157446668@y21g2000hsf.googlegroups.com> Message-ID: On May 25, 10:41?pm, miller.pau... at gmail.com wrote: > So, basically, V = (v_1, v_2, ... , v_{k-1}, v_k) can be regarded as > an abstract, k-dimensional vector, right? Yes. > If I understand your revised problem statement correctly, what you > really want to do is build a graph of these vectors, where graph > adjacency is equivalent to adjacency in your sense. ?That is, imagine > you have V_1, V_2, ... , V_n all sitting out in front of you, > represented abstractly as simple points. ?Draw a line between V_i and > V_j if they are "adjacent" in your sense of the word. ?What you have > then is a graph structure where your version of adjacency exactly > corresponds to graph adjacency. ?Then, in your language, a stratum is > simply a path in this graph, and finding those is easy. You're solving an earlier part of the problem which I call stratum generation. I've never thought to use a graph representation for stratum generation -- very interesting, and I'll pursue it. Would you be willing to outline how you'd do it here? I've had fun "breeding" strata using genetic algorithms, and a lot of interesting ideas came out of that experiment, in particular the utility of building randomly shaped strata to do indirect estimates (the objective of the set arithmetic described here). I used GA's because I think that the space of possible strata is too big to search by brute force. I'd still like to have the graph representation for the brute force solution. Or, in another random algorithm, the graph could be a sampling frame from which random paths could be pulled. In a real dataset, some of the strata will contain adequate data to make an estimate, and these are called valid strata. Other legal strata (as shown by a path through the graph) may not have adequate data to make an estimate (thus, legal but invalid). We've done this problem by hand: observing that we can estimate a stratum (1,2,3) and another (2,3) but not (1). So E(1) = E(1,2,3) - E(2,3) There are issues with the variance of E(1), but that's a very different problem. Using the valid strata E(1,2,3) and E(2,3) we've made an indirect estimate of E(1). I'm looking for an algorithm which automates the search for combinations like the one above. Given a set of valid strata[1], yield combinations of valid strata which, when combined via union or difference[2], evaluate to a stratum (adjacent but possibly not valid). The combination of valid strata is called an indirect estimate [1] strata can be generated via many methods; they all end up in the same database [2] Note that the set of operations is shrinking :) Thanks in advance for your thoughts -- PB. From bruno.42.desthuilliers at websiteburo.invalid Fri May 30 07:56:50 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 30 May 2008 13:56:50 +0200 Subject: should I put old or new style classes in my book? In-Reply-To: References: Message-ID: <483feb70$0$16182$426a74cc@news.free.fr> allendowney at gmail.com a ?crit : > Hi All, > > I am working on a revised edition of How To Think Like a Computer > Scientist, > which is going to be called Think Python. It will be published by > Cambridge > University Press, but there will still be a free version under the GNU > FDL. > > You can see the latest version at thinkpython.com; I am revising now, > so > I welcome all comments, suggestions, corrections, etc. > > Anyway, I am posting to ask about the current status of new style > classes. > I am planning to present only one style in the book, because the > differences > between them don't matter for anything I am doing in the book. > > The current edition of the book presents old style classes. I am > considering > switching to new style classes on the assumption that this should be > the default > choice for new programs. The drawback is that a lot of the online > documentation > still uses old style classes. > > Thanks for any guidance you can provide. Same remarks as anyone else that answered so far: definitively use new-style classes, and just add a note about the old-style syntax. From zutesmog at gmail.com Sun May 18 20:41:57 2008 From: zutesmog at gmail.com (timh) Date: Sun, 18 May 2008 17:41:57 -0700 (PDT) Subject: How do *you* use Python in non-GUI work? References: <20080518182022.990193bd.johnjsal@NOSPAMgmail.com> Message-ID: <5707fe7c-0694-47c9-aa30-9d557c0aa0d1@b9g2000prh.googlegroups.com> On May 19, 6:20?am, John Salerno wrote: > Hey all. Just thought I'd ask a general question for my own interest. Every time I think of something I might do in Python, it usually involves creating a GUI interface, so I was wondering what kind of work you all do with Python that does *not* involve any GUI work. This could be any little scripts you write for your own benefit, or what you do at work, if you feel like talking about that! :) > > Thanks. Hi I work fulltime developing in python and have done so for more than 5 years now, and I would say 99.8% of the time I have not built anything with a GUI (Unless you consider a web page as a GUI ;-) Much of my work is web based (zope backend stuff), test frameworks for windows build environments that need to compare the output of 1000's of images from rendering pipelines. Lots of data integration and manipulation utilities as part of processing pipelines. All sorts of stuff that just doesn't use a GUI. T From aspersieman at gmail.com Tue May 13 08:49:57 2008 From: aspersieman at gmail.com (Aspersieman) Date: Tue, 13 May 2008 14:49:57 +0200 Subject: Need to install Python in windows 32 bit processor In-Reply-To: <21A05FE37618574F9BBDFF23172DDCE603C185A0@CTSINCHNSXUT.cts.com> References: <21A05FE37618574F9BBDFF23172DDCE603C185A0@CTSINCHNSXUT.cts.com> Message-ID: <48298E75.4080906@gmail.com> An HTML attachment was scrubbed... URL: From castironpi at gmail.com Sat May 10 08:02:46 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Sat, 10 May 2008 05:02:46 -0700 (PDT) Subject: slicing lists References: <1c8a388a-4d04-4152-9b6e-3d64d96ec7f0@24g2000hsh.googlegroups.com> Message-ID: <57e0a2c5-88f3-4799-9feb-dca33232c497@e53g2000hsa.googlegroups.com> On May 9, 3:17?pm, castiro... at gmail.com wrote: > On May 9, 10:11?am, Yves Dorfsman wrote: > > > > > > > castiro... at gmail.com wrote: > > > The only thing is, is there is another natural meaning to [a,b:c]. > > > > Counting grids on the diagonals, the rational set is well defined: > > > > 0: 0, 0 > > > 1: 1, 0 > > > 2: 0, 1 > > > 3: 2, 0 > > > 4: 1, 1 > > > 5: 0, 2 > > > 6: 3, 0 > > > 7: 2, 1 > > > ... > > > > Thencefore ( 2, 0 ) : ( 3, 0 ) is well defined. ?Thencefore, > > > > a,b:c,d > > > > is not; x[a,b:c,d]= x[a]+ x[b:c]+ x[d]. > > > I'm not sure what you mean here. Could you give me a simple piece of code to > > show an example ? > > > Yves.http://www.SollerS.ca-Hide quoted text - > > > - Show quoted text - > > Yves, sadly, simple piece of code is not the writer's forte. ?I was > merely advising against leaping in to syntax additions, changes even. > The point was, even though a,b:c,d is shown ill-defined, a,b:c may not > be.- Hide quoted text - > > - Show quoted text - Now: In the case of enumerate( rationals ), list slicing can be plenty fine. Any use to the dirational enumerate? From castironpi at gmail.com Wed May 14 06:25:19 2008 From: castironpi at gmail.com (castironpi at gmail.com) Date: Wed, 14 May 2008 03:25:19 -0700 (PDT) Subject: I'm stuck in Python! References: <0563506d-bd36-404d-8961-4c4c5d1cc029@t54g2000hsg.googlegroups.com> <6a0167c3-bd87-4ddc-a161-249b7bf933c2@s50g2000hsb.googlegroups.com> Message-ID: <1f6bc3b5-da44-42a2-82f1-4aec5a6d31b1@c58g2000hsc.googlegroups.com> On May 14, 4:32?am, castiro... at gmail.com wrote: > On May 13, 9:55?pm, alex23 wrote: > > > On May 14, 5:41 am, "inhahe" wrote: > > > > "George Sakkis" wrote in message > > > > You must be new here. It is an AS (Artificial Stupidity) trolling bot, > > > > you can safely ignore its posts. > > > > How does it generate text? > > > My guess is by inhaling a lot of intoxicants. > > However you know what would be helpful? ?If I could go to the right > place to start the ring. I have a slightly sinister role on stage. Does anyone want to play? From bbxx789_05ss at yahoo.com Mon May 12 18:59:01 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Mon, 12 May 2008 15:59:01 -0700 (PDT) Subject: downloading a link with javascript in it.. References: <5358bfb4-f79a-4575-98b8-9a85ba41652d@d45g2000hsc.googlegroups.com> Message-ID: On May 12, 1:54?pm, Jetus wrote: > I am able to download this page (enclosed code), but I then want to > download a pdf file that I can view in a regular browser by clicking > on the "view" link. I don't know how to automate this next part of my > script. It seems like it uses Javascript. > The line in the page source says > > href="javascript:openimagewin('JCCOGetImage.jsp? > refnum=DN2007036179');" tabindex=-1> > 1) Use BeautifulSoup to extract the path: JCCOGetImage.jsp?refnum=DN2007036179 from the html page. 2) The path is relative to the current url, so if the current url is: http://www.landrecords.jcc.ky.gov/records/S3DataLKUP.jsp Then the url to the page you want is: http://www.landrecords.jcc.ky.gov/records/JCCOGetImage.jsp?refnum=DN2007036179 You can use urlparse.urljoin() to join a relative path to the current url: import urlparse base_url = 'http://www.landrecords.jcc.ky.gov/records/S3DataLKUP.jsp' relative_url = 'JCCOGetImage.jsp?refnum=DN2007036179' target_url = urlparse.urljoin(base_url, relative_url) print target_url --output:-- http://www.landrecords.jcc.ky.gov/records/JCCOGetImage.jsp?refnum=DN2007036179 3) Python has a webbrowser module that allows you to open urls in a browser: import webbrowser webbrowser.open("www.google.com") You could also use system() or os.startfile()[Windows], to do the same thing: os.system(r'C:\"Program Files"\"Mozilla Firefox"\firefox.exe') #You don't have to worry about directory names #with spaces in them if you use startfile(): os.startfile(r'C:\Program Files\Mozilla Firefox\firefox.exe') All the urls you posted give me errors when I try to open them in a browser, so you will have to sort out those problems first. From pavlovevidence at gmail.com Tue May 6 16:11:02 2008 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 6 May 2008 13:11:02 -0700 (PDT) Subject: ]ANN[ Vellum 0.16: Lots Of Documentation and Watching References: Message-ID: <929fa98b-b04d-4703-8dad-6541cf610ebd@k37g2000hsf.googlegroups.com> On Apr 29, 3:51 am, "Zed A. Shaw" wrote: > GPLv3? > > How do people feel about Vellum's GPLv3 status? It's going to scare away some folks. Using LGPL will almost certainly scare away fewer. People who don't like GPL are usually concerned about its viral aspects moreso than the requirement to contribute back released changes. Carl Banks From vivainio at gmail.com Thu May 8 11:02:01 2008 From: vivainio at gmail.com (Ville M. Vainio) Date: Thu, 08 May 2008 15:02:01 GMT Subject: observer pattern question #1 (reference to subject) References: Message-ID: Alan Isaac writes: > Is anything lost by not maintaining this reference (other > > than error checking ...)? If I feel the observer needs > > access to the subject, what is wrong with just having the > > subject pass itself as part of the notification? It reduces the number of places the observer can be called from, because now the event source is part of the function signature. If you omit the event source in the signature, you gain looser coupling - it's the observer business to create the dependency. Also, consider the situation where you want all investors to refresh their idea about stock prices (because of, short network failure). It's easy to run through a list of them and call update() for everybody, while it's not so easy to find out what stock the investor is observing (that's the investors business!) and pass that object to the investor in the call. Are these school questions btw? ;-) From x31equsenet at gmail.com Sat May 17 01:04:44 2008 From: x31equsenet at gmail.com (Graham Breed) Date: Sat, 17 May 2008 13:04:44 +0800 Subject: Is using range() in for loops really Pythonic? References: <482657ca$0$25026$607ed4bc@cv.net> <48275316$0$11629$607ed4bc@cv.net> <3042f24f-f32e-4266-8bf5-41cdb511b78d@m45g2000hsb.googlegroups.com> <873aoo6k8z.fsf@benfinney.id.au> <87skwn5dly.fsf@benfinney.id.au> <761a3c96-3faf-4347-aeb7-4ca9cba67e42@a23g2000hsc.googlegroups.com> Message-ID: George Sakkis wrote: > If you push this logic too far, you should del every name immediately > after the last statement it is used in the scope. I would generally > find less readable some code spread with del every few lines, micro- > managing the effective scope of each name. YMMV. Yes, but ... how about for i in range(10): del i do stuff ? It makes it clear you aren't using the index and ensures you get a run-time error if you clobbered an existing variable. Graham From deets at nospam.web.de Sun May 4 15:08:46 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 04 May 2008 21:08:46 +0200 Subject: Real Time Midi File Playback - Reading and Writing midi at the same time In-Reply-To: <167e310e-c801-4562-ad28-0c127b9663ef@i76g2000hsf.googlegroups.com> References: <4e5b78a7-bc7a-4c1e-8552-b8175a9cbe32@m3g2000hsc.googlegroups.com> <167e310e-c801-4562-ad28-0c127b9663ef@i76g2000hsf.googlegroups.com> Message-ID: <686fu3F2s4cu0U1@mid.uni-berlin.de> Gilly schrieb: > On May 4, 9:14 pm, David wrote: >> On Sun, May 4, 2008 at 7:11 PM, Gilly wrote: >>> Hi >>> I am trying to create an application that uses some form of input to >>> create a midi file. >>> I would like for this to be a 'real time' process. In other words, I >>> want to be able to begin playing the midi file before I finish writing >>> it, and continue writing as it plays. >> Have you tried the MIDI libraries listed on this page? >> >> http://wiki.python.org/moin/PythonInMusic >> >> David. > > Yes. I haven't found anything that would help me out... You didn't provide enough information. who is consuming the midi-files for example. Diez From grflanagan at gmail.com Thu May 22 15:14:01 2008 From: grflanagan at gmail.com (Gerard flanagan) Date: Thu, 22 May 2008 21:14:01 +0200 Subject: Producing multiple items in a list comprehension In-Reply-To: <5RiZj.165543$ng7.151222@en-nntp-05.dc1.easynews.com> References: <5RiZj.165543$ng7.151222@en-nntp-05.dc1.easynews.com> Message-ID: <4835C5F9.5040600@gmail.com> Joel Koltner wrote: > Is there an easy way to get a list comprehension to produce a flat list of, > say, [x,2*x] for each input argument? > > E.g., I'd like to do something like: > > [ [x,2*x] for x in range(4) ] > > ...and receive > > [ 0,0,1,2,2,4,3,6] > > ...but of course you really get a list of lists: > > [[0, 0], [1, 2], [2, 4], [3, 6]] > > I'm aware I can use any of the standard "flatten" bits of code to turn this > back into what I want, but I was hoping there's some way to avoid the "lists > of lists" generation in the first place? > > A slightly similar problem: If I want to "merge," say, list1=[1,2,3] with > list2=[4,5,6] to obtain [1,4,2,5,3,6], is there some clever way with "zip" to > do so? > > Thanks, > ---Joel > > > -- > http://mail.python.org/mailman/listinfo/python-list > For the first part: def gen(n): for i in xrange(n): yield i yield 2*i print list(gen(4)) [0, 0, 1, 2, 2, 4, 3, 6] gerard From __peter__ at web.de Tue May 13 05:10:38 2008 From: __peter__ at web.de (Peter Otten) Date: Tue, 13 May 2008 11:10:38 +0200 Subject: Sparse Matrix Multiplications References: Message-ID: Peter Otten wrote: > Peter Otten wrote: > >> # use at your own risk >> import numpy >> >> N = 10**4 # I get a MemoryError for a bigger exponent >> b = numpy.array(range(N)) >> a = numpy.zeros((N, N)) + b >> a *= a.transpose() >> a[0,0] = (b*b).sum() >> print a > > Sorry, this is nonsense. Maybe not as bad as I feared. I seems you can't transpose and inplace-multiply, so # use at your own risk import numpy N = 5 b = numpy.array(range(N)) a = numpy.zeros((N, N)) + b a = a * a.transpose() a[0,0] = (b*b).sum() print a might work if there is sufficient memory available... Peter From szhorvat at gmail.com Mon May 5 03:37:38 2008 From: szhorvat at gmail.com (=?ISO-8859-15?Q?Szabolcs_Horv=E1t?=) Date: Mon, 05 May 2008 09:37:38 +0200 Subject: Feature suggestion: sum() ought to use a compensated summation algorithm In-Reply-To: References: Message-ID: Gabriel Genellina wrote: > > Python doesn't require __add__ to be associative, so this should not be used as a general sum replacement. It does not _require_ this, but using an __add__ that is not commutative and associative, or has side effects, would qualify as a serious misuse, anyway. So I think that this isn't a real disadvantage (it can always be documented that sum() expects __add__ to have these properties). But you are right that summing floats with a requirement of high precision is a quite specific use case, so there are no serious arguments to do this, either. From kamhung.soh at gmail.com Fri May 30 01:03:28 2008 From: kamhung.soh at gmail.com (Kam-Hung Soh) Date: Fri, 30 May 2008 15:03:28 +1000 Subject: Finding file details... In-Reply-To: References: Message-ID: Kalibr wrote: > On May 30, 1:41 am, "Roger Upole" wrote: >> You can use the shell COM objects to access media properties >> as shown by Explorer. >> >> import win32com.client >> sh=win32com.client.Dispatch('Shell.Application') >> >> folder= r'M:\Music\Bob Dylan\Highway 61 Revisited' >> ns=sh.NameSpace(folder) >> >> ## the column index for Artist may vary from folder to folder >> for c in range(0,255): >> colname=ns.GetDetailsOf(None, c) >> if colname=='Artists': ## This shows up as just Artist on XP >> for i in ns.Items(): >> artist=ns.GetDetailsOf(i, c) >> if artist: >> print ns.GetDetailsOf(i, 0), artist >> break >> >> Roger > > I shall give that a go. (is the module you reference this one? > http://python.net/crew/mhammond/win32/Downloads.html ) If you installed ActiveState's Python, the win32com module should be installed. -- Kam-Hung Soh Software Salariman From kw at codebykevin.com Thu May 29 17:23:43 2008 From: kw at codebykevin.com (Kevin Walzer) Date: Thu, 29 May 2008 17:23:43 -0400 Subject: Getting up and running with Python on a Mac In-Reply-To: <7d593f8a-92b8-4dfe-935f-dd6a22c70faf@m45g2000hsb.googlegroups.com> References: <7d593f8a-92b8-4dfe-935f-dd6a22c70faf@m45g2000hsb.googlegroups.com> Message-ID: <483F1EDF.6040207@codebykevin.com> tkpmep at hotmail.com wrote: > I've just bought an iMac (OS X 10.5.2, will almost immediately jump to > 10.5.3), and am looking to install Python on it, and to use it with > XCode, Apple's IDE. Some googling suggests that a number of people > have had trouble getting Python to run satisfactorily on their Macs. > This is my first Mac, and I'd appreciate some guidance on what to do > (and what not to) when installing Python and potential problems to > keep an eye open for. I want to do a fair bit of scientific / > numerical computing, so it would seem that SAGE ot the Enthought > Python distribution would seem to be the most relevant - I'd > appreciate your guidance on getting Python to run on a Mac with a > particular focus on these two distributions. > > Thank you in advance > > Thomas Philips OS X 10.5 comes with Python installed already: 2.5.1. If you want to use Xcode with Python that's the way to go. If you want a later version of Python, you can download one from python.org, but I am not sure how that integrates wtih Xcode. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From florencio.cano at gmail.com Thu May 8 10:16:37 2008 From: florencio.cano at gmail.com (Florencio Cano) Date: Thu, 8 May 2008 16:16:37 +0200 Subject: Best technology for agent/web server architecture Message-ID: Hi, I would be interested in your opinion about what technology you considear the ideal technology for implementing in Python an agent that should comunicate information to a web server. I have read about SOAP but I'm now sure if this will be the right one. The aim of the agent is gather inventory information and the web application (I'm programming it in Django) will receive this information and will store it in the database and will show it in tables. From ivan.illarionov at gmail.com Sun May 11 00:39:30 2008 From: ivan.illarionov at gmail.com (Ivan Illarionov) Date: Sun, 11 May 2008 04:39:30 +0000 (UTC) Subject: do you fail at FizzBuzz? simple prog test References: <39709320-66e1-40e9-a351-c769c9a94585@x41g2000hsb.googlegroups.com> Message-ID: On Sun, 11 May 2008 04:26:10 +0000, Ivan Illarionov wrote: > On Sat, 10 May 2008 18:12:37 -0700, globalrev wrote: > >> http://reddit.com/r/programming/info/18td4/comments >> >> claims people take a lot of time to write a simple program like this: >> >> >> "Write a program that prints the numbers from 1 to 100. But for >> multiples of three print "Fizz" instead of the number and for the >> multiples of five print "Buzz". For numbers which are multiples of both >> three and five print "FizzBuzz". >> >> for i in range(1,101): >> if i%3 == 0 and i%5 != 0: >> print "Fizz" >> elif i%5 == 0 and i%3 != 0: >> print "Buzz" >> elif i%5 == 0 and i%3 == 0: >> print "FizzBuzz" >> else: >> print i >> >> >> is there a better way than my solution? is mine ok? > > ['%s%s' % (not i%3 and 'Fizz' or '', not i%5 and 'Buzz' or '') > or str(i) for i in xrange(1, 101)] > > -- Ivan or, more correctly, if you actually need to "print": sys.stdout.write('\n'.join('%s%s' % (not i%3 and 'Fizz' or '', not i%5 aBuzz' or '') or str(i) for i in xrange(1, 101))) -- Ivan From torriem at gmail.com Thu May 8 19:11:56 2008 From: torriem at gmail.com (Michael Torrie) Date: Thu, 08 May 2008 17:11:56 -0600 Subject: Mathematics in Python are not correct In-Reply-To: <482386FA.10700@gmail.com> References: <52c855d8-5609-43e0-b98f-9fa87b2808c2@m3g2000hsc.googlegroups.com> <482386FA.10700@gmail.com> Message-ID: <482388BC.7020208@gmail.com> Ahem... That should have been: (negate (pow 123 0)) Using parenthesis to indicate precedence order of ops: -(123 ^ 0) The "-" you are using is not part of the number. It's a unary operator that negates something. In normal order of operations, it has a much lower priority than power. Your post really took me back to my grade school days! I remember first looking with consternation at my scientific calculator when it insisted that -2^0 is -1. The order of python operations can be found here: http://docs.python.org/ref/summary.html Hope this helps From rhamph at gmail.com Fri May 9 12:12:46 2008 From: rhamph at gmail.com (Rhamphoryncus) Date: Fri, 9 May 2008 09:12:46 -0700 (PDT) Subject: Feature suggestion: sum() ought to use a compensated summationalgorithm References: Message-ID: On May 8, 3:09 pm, "Terry Reedy" wrote: > "Szabolcs Horv?t" wrote in message > > news:fvmdg1$1e4p$1 at toralf.uib.no...| Gabriel Genellina wrote: > > | > > | > Python doesn't require __add__ to be associative, so this should not be > used as a general sum replacement. > | > | It does not _require_ this, but using an __add__ that is not commutative > | and associative, or has side effects, would qualify as a serious misuse, > > seq + seq is not commutative ;-) There's no point switching to a special algorithm unless a float is detected. What you're really arguing is seq + seq + float is not commutative. In either case we may have to hurt you. ;) From hdante at gmail.com Thu May 8 18:21:01 2008 From: hdante at gmail.com (hdante) Date: Thu, 8 May 2008 15:21:01 -0700 (PDT) Subject: "prove" References: Message-ID: <03435960-37bd-4bd1-afd8-d86f38c60f0e@27g2000hsf.googlegroups.com> On May 8, 10:50?am, "Lucas Prado Melo" wrote: > Hello, > How could I "prove" to someone that python accepts this syntax using > the documentation (I couldn't find it anywhere): > classname.functionname(objectname) It's in the language reference, section 3.2 "The standard type hierarchy", subsection "Classes". The relevant paragraphs are those: Classes Class objects are created by class definitions (see section 7.7, ``Class definitions''). A class has a namespace implemented by a dictionary object. Class attribute references are translated to lookups in this dictionary, e.g., "C.x" is translated to "C.__dict__["x"]". When the attribute name is not found there, the attribute search continues in the base classes. The search is depth- first, left-to-right in the order of occurrence in the base class list. When a class attribute reference (for class C, say) would yield a user-defined function object or an unbound user-defined method object whose associated class is either C or one of its base classes, it is transformed into an unbound user-defined method object whose im_class attribute is C. When it would yield a class method object, it is transformed into a bound user-defined method object whose im_class and im_self attributes are both C. When it would yield a static method object, it is transformed into the object wrapped by the static method object. See section 3.4.2 for another way in which attributes retrieved from a class may differ from those actually contained in its __dict__. http://docs.python.org/ref/types.html From exarkun at divmod.com Sat May 17 16:06:23 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Sat, 17 May 2008 16:06:23 -0400 Subject: waiting on an event blocks all signals In-Reply-To: <4878ad7b0805171249r58428b47g4f6ebd8d0e3fcd0@mail.gmail.com> Message-ID: <20080517200623.4714.412132081.divmod.quotient.61@ohm> On Sat, 17 May 2008 12:49:54 -0700, John Schroeder wrote: >On Sat, May 17, 2008 at 12:32 PM, alan wrote: > >> This ignores CTRL-C on every platform I've tested: >> >> python -c "import threading; threading.Event().wait()" >> ^C^C^C^C >> >> It looks to me like all signals are masked before entering wait(). Can >> someone familiar with the internals explain and/or justify this >> behavior? Thanks, >> > >^C only kills the main thread. Use Control-Break to kill all threads. > Look at that program. It's single-threaded. Where do you think the ^C is going? :) Jean-Paul From deets at nospam.web.de Mon May 12 16:06:28 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 12 May 2008 22:06:28 +0200 Subject: downloading a link with javascript in it.. In-Reply-To: <5358bfb4-f79a-4575-98b8-9a85ba41652d@d45g2000hsc.googlegroups.com> References: <5358bfb4-f79a-4575-98b8-9a85ba41652d@d45g2000hsc.googlegroups.com> Message-ID: <68rmafF2t1vboU1@mid.uni-berlin.de> Jetus schrieb: > I am able to download this page (enclosed code), but I then want to > download a pdf file that I can view in a regular browser by clicking > on the "view" link. I don't know how to automate this next part of my > script. It seems like it uses Javascript. > The line in the page source says > href="javascript:openimagewin('JCCOGetImage.jsp? > refnum=DN2007036179');" tabindex=-1> > > So, in summary, when I download this page, for each record, I would > like to initiate the "view" link. > Can anyone point me in the right direction? > > When the "view" link is clicked on in IE or Firefox, it returns a pdf > file, so I should be able to download it with > urllib.urlretrieve('pdffile, 'c:\temp\pdffile') > > Here is the following code I have been using > ---------------------------------------------------------------- > import urllib, urllib2 > > params = [ > ('booktype', 'L'), > ('book', '930'), > ('page', ''), > ('hidPageName', 'S3Search'), > ('DoItButton', 'Search'),] > > data = urllib.urlencode(params) > > f = urllib2.urlopen("http://www.landrecords.jcc.ky.gov/records/ > S3DataLKUP.jsp", data) > > s = f.read() > f.close() > open('jcolib.html','w').write(s) Use something like the FireBug-extension to see what the openimagewin-function ultimately creates as reqest. Then issue that, parametrised from parsed information out of the above href. There is no way to interpret the JS in Python, let alone mimic possible browser dom behavior. Diez From castironpi at gmail.com Fri May 16 18:22:34 2008 From: castironpi at gmail.com (castironpi) Date: Fri, 16 May 2008 15:22:34 -0700 (PDT) Subject: write to specific line in file? References: <104ddf01-e860-4194-87bb-753a5e837ec0@s50g2000hsb.googlegroups.com> Message-ID: <29b9fb36-17bb-4449-aab9-e10361d0b0e4@b1g2000hsg.googlegroups.com> On May 16, 2:25?pm, 7stud wrote: > globalrev wrote: > > i ahve a program that takes certain textsnippets out of one file and > > inserts them into another. > > > problem is it jsut overwrites the first riow every time. > > > i want to insert every new piece of text into the next row. > > so: > > 1. how do i write to a new line every time i write to the file? > > > 2. if i dont want to write to a new line but just want to insert it > > after the last token in the file, how do i do then? > > Generally, you can't "insert" anything into a file. ?You can either > append to the end of a file, or you can rewrite the whole file. ?It > sounds like you probably want to read the file into an array using > readlines(). ?Then manipulate that array however you want--appending > and inserting--and when you are done, overwrite the file with your > array. > > However, you should be aware that as soon as you open a file for > writing all the data is erased, and if your program should happen to > crash right then, the array containing the data will disappear into > the ether and your file will be empty--in other words all your data > will be gone. ?To prevent such an occurence, you should write your > final data to another file, then delete the original file, and finally > change the other file's name to the original file name. Some options: 1. Limit line length. Then offset is ( line* length ). 2. Name your relation. 3. Hijack the operating system. Remember: abc def on disk looks like abc\ndef where abcd def looks like abcd\ndef So, if you want line 2, you have to scan line 1. From inhahe at gmail.com Fri May 23 00:40:50 2008 From: inhahe at gmail.com (inhahe) Date: Fri, 23 May 2008 00:40:50 -0400 Subject: php vs python References: <5l%Yj.77$mz3.53@fe101.usenetserver.com> Message-ID: > PHP can do that. There are also a number of templating engines > available. The nice thing about PHP is you have a choice. i just meant that php is sort of invented to combine html and code, so if you use python instead you should use a templating engine. but i suppose it's useful for php too. From goldnery at gmail.com Thu May 29 17:19:12 2008 From: goldnery at gmail.com (Gandalf) Date: Thu, 29 May 2008 14:19:12 -0700 (PDT) Subject: question Message-ID: how do i write this code in order for python to understand it and print me the x variable x=1 def aaaa(): x++ if x > 1: print "wrong" else : print x aaaa() From wuwei23 at gmail.com Thu May 29 19:13:10 2008 From: wuwei23 at gmail.com (alex23) Date: Thu, 29 May 2008 16:13:10 -0700 (PDT) Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <5c98049e-e62e-4ab1-afed-b0a3e186bd05@w1g2000prd.googlegroups.com> <3dd6fa95-e9fe-4922-a46d-020cf9263469@w4g2000prd.googlegroups.com> <20080529175745.b3e7a579.darcy@druid.net> Message-ID: <024e8e62-d6d2-498b-b01f-0e85b64b51e6@v26g2000prm.googlegroups.com> On May 30, 8:02 am, "Dan Upton" wrote: > Yeah, but if you look past the "FT is better than Python" propaganda, > there's some interesting discussion of language design. Which is more appropriate on a group focused on such a topic. From goldnery at gmail.com Tue May 27 04:37:16 2008 From: goldnery at gmail.com (Gandalf) Date: Tue, 27 May 2008 01:37:16 -0700 (PDT) Subject: Keyboard Events References: <14d057b1-3b62-4efb-bdb2-c20394c7268c@r66g2000hsg.googlegroups.com> <1e920a06-3741-4154-94a1-73b90f659e1b@z72g2000hsb.googlegroups.com> <4d26372a-c07d-4a41-992f-4c158f0c40c3@56g2000hsm.googlegroups.com> Message-ID: On May 27, 2:36 am, Mike Driscoll wrote: > On May 26, 5:38 pm, Ivan Illarionov wrote: > > > > > On Mon, 26 May 2008 15:26:50 -0700, Gandalf wrote: > > > On May 27, 12:18 am, Gandalf wrote: > > >> On May 27, 12:00 am, Ivan Illarionov wrote: > > > >> > On Mon, 26 May 2008 14:40:18 -0700, Gandalf wrote: > > >> > > Thanks! > > >> > > Anyone know which library should i learn then? > > > >> > Looks like you need to dive into Win32 > > >> > APIhttp://msdn.microsoft.com/en-us/library/ms697544 > > > (VS.85).aspxhttp://ms... > > > >> > and others > > >> > combined with ctypes. > > > >> > Ivan > > > >> well, that seems extremely valuable but how can i implement those > > >> functions with python? > > > > You know what I'm sorry, I will try to understand the ctypes lib before > > > bothering you. > > > > thank you all! > > > No need to sorry. I have actually found very valuable information athttp://www.brunningonline.net/simon/blog/archives/000652.html > > while googling to answer your question. I didn't know that such things > > are really possible with Python/Win32! It'll help me a lot. Thank you! > > > Ivan > > If you guys are going to go digging into the PyWin32 modules, make > sure you check this site out: > > http://aspn.activestate.com/ASPN/docs/ActivePython/2.5/pywin32/PyWin3... > > It has the docs for the distro and a link to the user's group too. Bot > have been very helpful to me. > > Mike OK thanks guys I'm going try and if I will succeed I will tel you how I did it From paddy3118 at googlemail.com Sun May 11 01:19:10 2008 From: paddy3118 at googlemail.com (Paddy) Date: Sat, 10 May 2008 22:19:10 -0700 (PDT) Subject: Is using range() in for loops really Pythonic? References: <482657ca$0$25026$607ed4bc@cv.net> Message-ID: <41c9f303-219e-4b4d-a1b6-ee998b406a39@c65g2000hsa.googlegroups.com> On May 11, 3:19 am, John Salerno wrote: > I know it's popular and very handy, but I'm curious if there are purists > out there who think that using something like: > > for x in range(10): > #do something 10 times > > is unPythonic. The reason I ask is because the structure of the for loop > seems to be for iterating through a sequence. It seems somewhat > artificial to use the for loop to do something a certain number of > times, like above. > > Anyone out there refuse to use it this way, or is it just impossible to > avoid? Hi John, If you have an object that is both indexable and iterable, then visiting every member by first generating an index then indexing the object is un-pythonic. You should just iterate over the object. Like most rules, things can get fuzzy around the edges: if you have n objects to be visited each index at a time, then the more functional approach would be to izip all the objects and iterate over the result. Another way would be to iterate over the the enumeration of one object and use the index created to index the other n-1 objects. In all such situations you need to remember that things such as code clarity, and speed, might make the final decision for you. In the following examples then the first is what I would use, izip. If I needed an index then I'd prefer the last, which combines izip and enumerate: PythonWin 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win32. Portions Copyright 1994-2006 Mark Hammond - see 'Help/About PythonWin' for further copyright information. >>> obj1 = 'CSM' >>> obj2 = 'aue' >>> obj3 = 'tmn' >>> from itertools import izip >>> for x,y,z in izip(obj1, obj2, obj3): ... print x,y,z ... C a t S u m M e n >>> for i,x in enumerate(obj1): ... print x, obj2[i], obj3[i] ... C a t S u m M e n >>> for i in range(len(obj1)): ... print obj1[i], obj2[i], obj3[i] ... C a t S u m M e n >>> for i,(x,y,z) in enumerate(izip(obj1, obj2, obj3)): ... print i, x, y, z ... 0 C a t 1 S u m 2 M e n >>> - Paddy. From kyrie at uh.cu Wed May 28 14:09:31 2008 From: kyrie at uh.cu (Luis Zarrabeitia) Date: Wed, 28 May 2008 14:09:31 -0400 Subject: Python and Flaming Thunder In-Reply-To: <5c98049e-e62e-4ab1-afed-b0a3e186bd05@w1g2000prd.googlegroups.com> References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <5c98049e-e62e-4ab1-afed-b0a3e186bd05@w1g2000prd.googlegroups.com> Message-ID: <200805281409.31644.kyrie@uh.cu> On Wednesday 28 May 2008 09:22:53 am Dave Parker wrote: > I think in a month or two, Flaming Thunder will be using catch/throw > exception and error handling. ?So, for example: Nice... Flaming Thunder sure evolves quickly. Too quickly to be considered a 'feature' of the language. Following your posts in this thread, I see that you 'plan to add soon' every cool feature that every other language seems to have. That means that I won't have to test my program only against every major versions of Flaming Thunder... i will have to test it with every week's version. With no certainty whatsoever that today's program will work on tomorrow's FT. Why don't you wait a bit, until Flaming Thunder is mature enough to be stable, before trying to advertise it to us? And in the meantime, some of us are going to keep trying to add all the features we've always wanted, to the next major version of Python. -- Luis Zarrabeitia (aka Kyrie) Fac. de Matem?tica y Computaci?n, UH. http://profesores.matcom.uh.cu/~kyrie From grante at visi.com Fri May 2 10:44:59 2008 From: grante at visi.com (Grant Edwards) Date: Fri, 02 May 2008 09:44:59 -0500 Subject: #!/usr/bin/env python vs. #!/usr/bin/python References: <87abj91j8u.fsf@benfinney.id.au> Message-ID: On 2008-05-02, Jeroen Ruigrok van der Werven wrote: >>I've never clearly understood why people want to use "#! /usr/bin/env >>python", which is prone to finding a different Python from the one >>installed by the operating system. I'd be interested to see what >>responses are in favour of it, and what the reasoning is. > > Simple, some systems are not as peculiar as a lot of Linux boxes which > chug everything into /usr/bin, which is OS territory On many Linux distros, Python is pretty much part of the OS. Since the early days of RedHat, Python has been part of the base/minimum install since a lot of the "required" system utilities were written in python. In Redhat, the package manger was originally written in Python, so Python had to be in "OS territory". > (as has been decreed long ago by hier(7)), but rather use > /usr/local/bin (all BSD Unix and derivatives) or /opt or > whatever convention a particular operating system has. In the Linux world, /usr/local/bin and /opt are for stuff installed by the user, not stuff that is an integral, required part of the OS distribution. -- Grant From Dominique.Holzwarth at ch.delarue.com Thu May 8 03:26:28 2008 From: Dominique.Holzwarth at ch.delarue.com (Dominique.Holzwarth at ch.delarue.com) Date: Thu, 8 May 2008 08:26:28 +0100 Subject: Problems with os.walk Message-ID: <5213E58D85BC414998FA553C701E386C0EDD1C81D9@SGBD012511.dlrmail.ad.delarue.com> Hi everyone The following code: scriptPath = os.path.dirname(__file__) (dirpath, dirnames, filenames) = os.walk(scriptPath) print 'dirpath\n' print dirpath print 'dirnames\n' pprint.pprint(dirnames) print 'filenames\n' pprint.pprint(filnames) Fails on the os.walk call with the following error: (dirpath, dirnames, filenames) = os.walk(scriptPath) ValueError: need more than 1 value to unpack Any ideas what could be wrong? Thx & greetings Dominique ***************************************************************************** This e-mail and any files attached are strictly confidential, may be legally privileged and are intended solely for the addressee. If you are not the intended recipient please notify the sender immediately by return email and then delete the e-mail and any attachments immediately. The views and or opinions expressed in this e-mail are not necessarily the views of De La Rue plc or any of its subsidiaries and the De La Rue Group of companies, their directors, officers and employees make no representation about and accept no liability for its accuracy or completeness. You should ensure that you have adequate virus protection as the De La Rue Group of companies do not accept liability for any viruses. De La Rue plc Registered No.3834125, De La Rue Holdings plc Registered No 58025 and De La Rue International Limited Registered No 720284 are all registered in England with their registered office at: De La Rue House, Jays Close, Viables, Hampshire RG22 4BS ***************************************************************************** From sturlamolden at yahoo.no Wed May 21 13:29:23 2008 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 21 May 2008 10:29:23 -0700 (PDT) Subject: Using Python for programming algorithms References: <48315082$0$24599$426a74cc@news.free.fr> <62884fc6-6c74-4477-91de-7b7689b5fa75@m44g2000hsc.googlegroups.com> <52b543da-90f3-4624-a11c-553159832764@l42g2000hsc.googlegroups.com> <4833f2ef$0$3737$426a74cc@news.free.fr> Message-ID: <64fb9443-5e52-4f55-9b83-2bd43d64b596@m36g2000hse.googlegroups.com> On May 21, 12:01 pm, Bruno Desthuilliers wrote: > > C has proven very difficult to optimize, particularly because pointer > > aliasing prevents efficient register allocation. > > Does this compare to optimizing something like Python ? (serious > question, but I think I already know part of the answer). In Python different references can alias the same object. But the objects for which this is important in C, is typically elementary types like ints and floats. Pointer aliasing has the consequence that the compiler often cannot choose to keep an int or a float in a register inside a tight loop. This will often have serious consequences for numerical computing. But these elementary types are immutable in Python, so Python is actually somewhat immune to this. This is one of several reasons why RPython sometimes can be "faster than C". But there are other much more important issues if you are to generate efficient machine code from Python, e.g. getting rid of redundant attribute lookups. From rupole at hotmail.com Wed May 7 09:08:32 2008 From: rupole at hotmail.com (Roger Upole) Date: Wed, 7 May 2008 09:08:32 -0400 Subject: Can't drag and drop onto .py in Windows XP? References: Message-ID: Sizer wrote: >I have several python utils that look at sys.argv to get a list of > filenames to process and mangle the files in various ways. If I have a > bar.bat file in Windows XP then I can just drag foo.avi onto bar.bat and > bar.bat gets called with foo.avi as an argument, everyone's happy. But if > I > have a bar.py (or .pyw) and try to drag and drop foo.avi to it, I get a > big > NO cursor and nothing happens. > > Now I can work around this by creating a _bar.bat and having the _bar.bat > call bar.pyw with the filenames it was passed (this is obviously > ridiculous). Or I can create a shortcut which has the target of > c:\python25\pythonw.exe c:\mybar\bar.pyw > and that works, but makes telling people how to install my utilities on > their computer a pain in the rear. It's just a little weird that I can't > just drag and drop file names onto .pyw or .py files. Am I missing > something here? > > Thanks for any help. You can register a DropHandler for the Python file class. Put this in a .reg file and merge it into the registry: REGEDIT4 [HKEY_CLASSES_ROOT\Python.File\shellex\DropHandler] @="{86C86720-42A0-1069-A2E8-08002B30309D}" Roger From upton at virginia.edu Wed May 21 15:38:19 2008 From: upton at virginia.edu (Dan Upton) Date: Wed, 21 May 2008 15:38:19 -0400 Subject: best way to check if pid is dead? In-Reply-To: <90ecca29-c4d8-4e89-908a-93850d7de1bf@i76g2000hsf.googlegroups.com> References: <90ecca29-c4d8-4e89-908a-93850d7de1bf@i76g2000hsf.googlegroups.com> Message-ID: <5504f9ac0805211238s77dfa919kbcfd16420fe98a3@mail.gmail.com> On Wed, May 21, 2008 at 3:02 PM, bukzor wrote: > Does anyone have a pythonic way to check if a process is dead, given > the pid? > > This is the function I'm using is quite OS dependent. A good candidate > might be "try: kill(pid)", since it throws an exception if the pid is > dead, but that sends a signal which might interfere with the process. > > Thanks. > --Buck > -- > http://mail.python.org/mailman/listinfo/python-list > I don't know if you would call this pythonic, but the way I do it in linux is: import os os.path.exists("/proc/%d"%(pid)) Or, more to the point, I'm usually checking to see if processes I forked have finished, without just having to do a wait4 on them; in the case you can do something like procfile = open("/proc/%d/stat" %(pid)) procfile.readline().split[2] You can do man proc to see what each of the possible letters means; I look for Z to find that the process has exited but it's waiting for its parent to do a wait4. HTH -dan From sjmachin at lexicon.net Fri May 9 23:46:37 2008 From: sjmachin at lexicon.net (John Machin) Date: Sat, 10 May 2008 03:46:37 GMT Subject: regexp help In-Reply-To: References: <834d8448-5d6a-4f49-9be6-6501a0b5fd92@k37g2000hsf.googlegroups.com> <4824fcec$1@news.mel.dft.com.au> Message-ID: <48251a9a@news.mel.dft.com.au> globalrev wrote: >> The inner pair of () are not necessary. > > yes they are? You are correct. I was having a flashback to a dimly remembered previous incarnation during which I used regexp software in which something like & or \0 denoted the whole match (like MatchObject.group(0)) :-) From gagsl-py2 at yahoo.com.ar Sun May 25 14:51:01 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 25 May 2008 15:51:01 -0300 Subject: Showing the method's class in expection's traceback References: <79c7d6fb-a6b8-481f-9a36-81b980628710@59g2000hsb.googlegroups.com> <69bi20F31j4kdU1@mid.uni-berlin.de> <483406a0$0$10773$426a74cc@news.free.fr> <6a8c7499-7d8c-4d5d-9ea6-a3e1ba2f9565@c58g2000hsc.googlegroups.com> <48353a94$0$12639$426a74cc@news.free.fr> Message-ID: En Sun, 25 May 2008 06:15:45 -0300, Duncan Booth escribi?: > "Gabriel Genellina" wrote: >> En Thu, 22 May 2008 07:55:44 -0300, Duncan Booth >> escribi?: >>> >>> It might be worth considering an alternative approach here: a >>> formatted exception includes the relevant source lines (where >>> possible). >> >> Just to note that the standard cgitb module already does that, among >> other things. >> > Anywhere Python prints a traceback already does that. The 'alternative > approach' I was suggesting was the part you snipped, i.e. extracting the > enclosing class name from the source. Ah, sorry for the misunderstanding! -- Gabriel Genellina From kyosohma at gmail.com Mon May 19 11:40:38 2008 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 19 May 2008 08:40:38 -0700 (PDT) Subject: Running commands on cisco routers using python References: Message-ID: <2d943acb-2ac8-4cfa-9aad-80fed7e1bb45@8g2000hse.googlegroups.com> On May 19, 10:18 am, SPJ wrote: > Is it possible to run specific commands on cisco router using Python? > I have to run command "show access-list" on few hundred cisco routers and get the dump into a file. Please let me know if it is feasible and the best way to achieve this. > > Thanks, > SPJ I think it depends on how you're connecting to the routers. Theoretically, you should be able to use Python's socket or ssh modules to connect to them, send commands and capture the output. Just experiment with one or two routers until you get it. Mike From bruno.desthuilliers at gmail.com Fri May 16 17:47:02 2008 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: Fri, 16 May 2008 14:47:02 -0700 (PDT) Subject: namespaces and eval References: <31750f1d-910b-4fcc-90c0-0df9634f2c73@l28g2000prd.googlegroups.com> Message-ID: On 16 mai, 23:23, dave.g1... at gmail.com wrote: > Thanks for the responses. I'm well aware that the function can be > passed in the parameters, passing in the functino as an arg defeats > the purpose of what I'm going after. Why so ? > @ Arnaud - Nice. I'm not sure what the performance of mine vs. yours, > but a perfunctory glance looks like we're doing the close to the same > thing. Maybe one advanage to doing it wrap(x).foo().... is that you > can pass in other parameters to foo. I may be wrong (if so please pardon my lack of intelligence and/or provide a couple use case), but it looks like you're trying to reinvent partial application. from functools import partial def foo(x, y): return x + y pfoo = partial(foo, 2) print pfoo(42) Don't know if this helps... From rossgk at gmail.com Thu May 15 16:12:12 2008 From: rossgk at gmail.com (RossGK) Date: Thu, 15 May 2008 13:12:12 -0700 (PDT) Subject: Pydev Console use vs. stdout/stderr Message-ID: Just getting used to the PyDev environment in eclipse by playing with a few simple programs. I'm also using wxPython GUI stuff. I've noticed though that simple print commands in my code cause a "wxPython:stdout/stderr" popup window to display any print's I might be dumping out, rather than going to the console in Eclipse. Any suggestions of why this is? Another code example I was looking at (which does not include any wx GUI stuff) has print commands whose result ends up in the Eclipse console, just to further confuse me. Is this something that wxPython is imposing on the environment? Thx. Ross. From bruno.42.desthuilliers at websiteburo.invalid Fri May 23 08:19:16 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 23 May 2008 14:19:16 +0200 Subject: Calling class method by name passed in variable In-Reply-To: References: <48366fb1$0$4879$426a74cc@news.free.fr> Message-ID: <4836b62b$0$24427$426a74cc@news.free.fr> Nick Craig-Wood a ?crit : > Bruno Desthuilliers wrote: >>> Can someone suggest an efficient way of calling method whose name is >>> passed in a variable? >>> >> method = getattr(obj, 'method_name', None) >> if callable(method): >> method(args) > > I think that that is needless LBYL... From experience, it isn't. > getattr(obj, 'method_name')(args) > > Will produce some perfectly good exceptions The problem is that you can't tell (without reading the exception's message and traceback etc) if the exception happened in you code or within the called method. From daveparker at flamingthunder.com Tue May 13 12:56:08 2008 From: daveparker at flamingthunder.com (Dave Parker) Date: Tue, 13 May 2008 09:56:08 -0700 (PDT) Subject: Python and Flaming Thunder References: <567f7222-ac10-42aa-8105-0654f63368e6@h1g2000prh.googlegroups.com> <5b0e3f70-afde-4480-8713-e7113b1250d7@x35g2000hsb.googlegroups.com> <1f537717-00d0-48ee-99b6-7125b96a6133@t12g2000prg.googlegroups.com> <68t4o0F2vaoncU1@mid.uni-berlin.de> <2a32179a-9439-449c-bd07-fff6a4075aee@s50g2000hsb.googlegroups.com> <7ee5dffd-df8f-46f0-bd78-c81ac0418a9a@d77g2000hsb.googlegroups.com> <65ef773e-a1c3-4adb-a18b-e8b8451efe5e@b5g2000pri.googlegroups.com> <68trmmF2vjivnU1@mid.uni-berlin.de> <68tuhfF2unducU1@mid.uni-berlin.de> Message-ID: <8b9560fa-7f29-4bfe-b312-e3da0e3779b6@z24g2000prf.googlegroups.com> > Who has conducted the research that supports that statement? And since when > is ^ the better operator for "to the power of" that **? Because latex uses > it? I need to see the elementary school students who use that... All of the calculators and textbooks that elementary school students use, use "^" for powers. Just like Flaming Thunder does. I haven't seen "**" for powers since FORTRAN. On May 13, 10:38?am, "Diez B. Roggisch" wrote: > > True. ?But in Python, you don't see statically-linked pure-syscall CGI > > scripts being cross-compiled under Windows for ftp'ing up to a Linux > > server. ?And you don't see the speed of pure assembly language > > libraries. ?And I'll be willing to bet that Flaming Thunder will have > > OO features similar to Python before Python has the features that > > Flaming Thunder already does. > > Your bets don't count anything here. These things don't exist, so don't brag > on them being superior. > > > For many people, being 5 to 10 times faster at numerical analysis and > > CGI scripting is reason enough to pay $19 per year. ?But maybe for > > other people, having slow, inefficient programs and websites is > > acceptable. > > Quite a revealing statement I'd say. And unless you don't show any > real-world site running on FT that needs things like sessions, cookies, > database-connectivity, unicode and a ton more of stuff FT doesn't support > out-of-the-box or through 3rd-party-libs, I wouldn't mention "the people" > as well. So far, *all* that you've been showing on your site regarding CGI > are toy-scripts. Nothing more. > > >> And what is really expensive is brain-cycles, not cpu-cycles. > > > Depends on whether you're the programmer, or the customer. ?I've found > > that customers prefer products that are 5 to 10 times faster, instead > > of products that were easy for the developer. > > This shows how much you don't know about customers, and their needs. A > customer gives a s**t about 5-10 times faster sites. They care if it is > *fast enough*, but beyond that they don't bother. But what *always* bothers > them is development time & flexibility. Because that directly affects the > price they pay. > > And if a average man-day costs $600 (which is not expensive), and the > project is of average size of a couple of man-months - well, you care about > mathematics, do the math yourself what that means that FT lacks anything > but a simple CGI-interface. > > > And I disagree that Flaming Thunder requires more brain-cycles. > > Because it's based on leveraging existing English and math fluency > > (which was one of the original goals of Python, was it not?), I think > > that Flaming Thunder requires fewer brain-cycles because fewer brains > > cells have to be devoted to memorizing language peculiarities. > > It does require more, because it lacks all the libs and 3rdparty-libs. And > because it lacks features such as OO and other stuff, it will be harder to > write these as well as use them. > > Show me how to beat a quickstarted TurboGears/Django webproject. *Then* you > can talk business here. > > > Perhaps. ?But if elementary school students can easily understand why > > one programming language gives the answer 100 (Flaming Thunder): > > > ? Write 10^2. > > > but can't understand why another programming language gives the answer > > 8 (Python): > > > ? Print 10^2 > > > then I think the comparison moves beyond a matter of taste into the > > realm of measurable ease-of-use. > > Who has conducted the research that supports that statement? And since when > is ^ the better operator for "to the power of" that **? Because latex uses > it? I need to see the elementary school students who use that... > > Even *if* that would be true, how does a perceived advantage in one field FT > was explicitly created for show that it is the generally better one and > understandable one for more diverse applications? > > Diez From deets at nospam.web.de Mon May 12 10:50:02 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 12 May 2008 16:50:02 +0200 Subject: Removing option from optparse In-Reply-To: References: Message-ID: <68r3p5F2t6nq8U1@mid.uni-berlin.de> GustavoTabares at gmail.com schrieb: > Hello, > > I'm trying to figure out if the following is a bug or if I'm using the > remove_option in the wrong way. > > #!/usr/bin/env python > import optparse > parser = optparse.OptionParser() > parser.add_option("--test", help="This is a test option") > parser.remove_option('--test') > print parser.parse_args() > > this will output: > (, []) > > If you execute the --help on the file above you will not see --test as > expected. I'm curious as to why parse_args is still returning this as > an option. I'm guessing here - but it is *one* thing to disable an option for the user because of whatever condition, and another to remove the options default value that code could possibly rely on to work. So I'd say the behavior is sane. Diez From bignose+hates-spam at benfinney.id.au Sat May 24 21:28:30 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 25 May 2008 11:28:30 +1000 Subject: Code correctness, and testing strategies References: Message-ID: <87r6br9npd.fsf@benfinney.id.au> David writes: > Is it considered to be cheating if you make a test case which always > fails with a "TODO: Make a proper test case" message? I consider it so. What I often do, though, is write a TODO comment in the unit test suite: # TODO: test_frobnitz_produces_widget_for_znogplatz_input(self): At which point I've got: * A unit test suite that has the same number of tests. * A comment that my editor will highlight, and that many tools are tuned to look for and flag for my attention (the "TODO:" convention). * A description of what the test should be testing, as the name of the function that will implement the test. (This also forces me to think of exactly what it is I want to assert about the code's behaviour, by writing a test case name that embodies that assertion.) * The beginnings fo the test case function itself, simply by removing the "# TODO: " part when I get around to that test case. Then I get back to the work I was doing when that idea struck me, knowing thaat it's recorded so I don't have to focus on it now. > For example: sanity tests. Functions can have tests for situations > that can never occur, or are very hard to reproduce. How do you unit > test for those? That depends, of course, on how hard they are to reproduce. But one common technique is isolation via test doubles . If you want to see how a specific unit of code behaves under certain conditions, such as a disk failure, you're not interested in testing the disk subsystem itself, only your code's behaviour. So you isolate your code by having the unit test (often in a fixture) provide a "test double" for the disk subsystem, and rig that double so that it will predictably provide exactly the hard-to-get event that you what your code to respond to correctly. > A few examples off the top of my head: > > * Code which checks for hardware defects (pentium floating point, > memory or disk errors, etc). > > * Code that checks that a file is less than 1 TB large (but you only > have 320 GB harddrives in your testing environment). > > * Code which checks if the machine was rebooted over a year ago. All of these can, with the right design, be tested by providing a test double in place of the subsystem that the code under test will exercise, and making that test double provide exactly the response you want to trigger the behaviour in your code. > Also, there are places where mock objects can't be used that easily. > > eg 1: A complicated function, which needs to check the consistency of > it's local variables at various points. That's a clear sign the function is too complicated. Break out the "stages" in the function to separate functions, and unit test those so you know they're behaving properly. Then, if you need to, you can easily provide test doubles for those functions; or you may find you don't need to once you know they're fully test covered. > It *is* possible to unit test those consistency checks, but you may > have to do a lot of re-organization to enable unit testing. This results in more modular code with looser coupling (fewer interdependencies between components). This is a good thing. > In other cases it might not be appropriate to unit test, because it > makes your tests brittle (as mentioned by another poster). > > eg: You call function MyFunc with argument X, and expect to get result Y. > > MyFunc calls __private_func1, and __private_func2. If you've got name-mangled functions, that's already a bad code smell. Not necessarily wrong, but that's the way to bet. > You can check in your unit test that MyFunc returns result Y, but you > shouldn't check __private_func1 and __private_func2 directly, even if > they really should be tested (maybe they sometimes have unwanted side > effects unrelated to MyFunc's return value). Don't write functions with unwanted side effects. Or, if those side effects are actually caused by other subsystems beyond your control, test those functions with test doubles in place of the external subsystems. > eg: Resource usage. > > How do you unit test how much memory, cpu, temporary disk space, etc > a function uses? This is beyond the scope of unit tests. You should be testing resource usage by profiling the entire application, not in unit tests. > eg: Platforms for which unit tests are hard to setup/run. > > - embedded programming. You would need to load your test harness into > the device, and watch LED patterns or feedback over serial. Assuming > it has enough memory and resources :-) > - mobile devices (probably the same issues as above) Yes, it's unfortunate that some systems don't yet have good tools to enable unit testing. Fix that, or pay others to fix it, because it's in your best interests (and your customers's interests) to have unit testing be as easy as feasible on all platforms that you target. > eg: race conditions in multithreaded code: You can't unit test > effectively for these. Another good reason to avoid multithreaded code where possible. I find that "it's really hard to deterministically figure out what's going on" is reason enough to avoid it. If it's so hard to know the current state of the system, it's therefore a poor choice, because I have no good way to report to my customer how close I am to finishing the implementation. Others may have successfully achieved unit tests for conditions that only arise in multithreaded code, but that's outside my experience. -- \ "How many people here have telekenetic powers? Raise my hand." | `\ -- Emo Philips | _o__) | Ben Finney From sebastian.noack at googlemail.com Tue May 27 01:43:53 2008 From: sebastian.noack at googlemail.com (sebastian.noack at googlemail.com) Date: Mon, 26 May 2008 22:43:53 -0700 (PDT) Subject: tarfile.open(mode='w:gz'|'w|gz'|..., fileobj=StringIO()) fails. References: <133193d2-a87f-4000-b70c-29fdbb36f6d0@59g2000hsb.googlegroups.com> Message-ID: <35552ee8-4c87-4694-b783-aa4315f3ce18@m73g2000hsh.googlegroups.com> On May 27, 2:17 am, "Gabriel Genellina" wrote: > It's not a bug, you must extract the StringIO contents *after* closing > tar_file, else you won't get the last blocks pending to be written. I looked at tarfile's source code last night after I wrote this message and figured it out. But the problem is that TarFile's close method closes the underlying file object after the last block is written and when you close StringIO you can not get its content anymore. Wtf does it close the underlying file? There is absolute no reason for doing this. Are you still sure this isn't a bug? Regards Sebastian Noack From arnodel at googlemail.com Fri May 16 10:09:29 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Fri, 16 May 2008 07:09:29 -0700 (PDT) Subject: Variable by label References: Message-ID: rocco.ro... at gmail.com wrote: > Is there any function which will return a variable by passing to it > the string containing the variable's name? Something like this for > instance: > > foo = some_function("foo") > > or perhaps it's a dictionary. I don't know, but I would really like to > find out how it can be done. I guess it is achievable. > > Thank you. There are the globals() and locals() builtins. >>> a = 42 >>> globals()['a'] 42 >>> -- Arnaud From hdante at gmail.com Mon May 19 11:53:11 2008 From: hdante at gmail.com (Henrique Dante de Almeida) Date: Mon, 19 May 2008 08:53:11 -0700 (PDT) Subject: Using Python for programming algorithms References: <98fa5fa3-45ae-4df1-9fd3-1a227641244f@p25g2000hsf.googlegroups.com> <48314dd0$0$32138$426a34cc@news.free.fr> Message-ID: On May 19, 6:52?am, Bruno Desthuilliers wrote: > Henrique Dante de Almeida a ?crit : > > > On May 17, 7:32 pm, Vicent Giner wrote: > >> Hello. > > (snip) > >> However, it is usually said that Python is not a compiled but > >> interpreted programming language ?I mean, it is not like C, in that > >> sense. > > (snip) > > ?I guess that python is not a good language for that. > (snip) > > ?My opinion: choose compiled or byte compiled languages. > > Slightly OT (ie : not talking about computation-heavy alorgithm being > better implemented in C then wrapped in Python - this seems quite > obvious) but just a couple facts: > > 1/ being interpreted or compiled (for whatever definition of these > terms) is not a property of a language, but a property of an > implementation of a language. > > 2/ actually, all known Python implementations compile to byte-code. Yes, I was actually referring to statically typed JIT-compiled languages. Sorry about that, blame the beers that entered my digestive system that night. :-P From robert.kern at gmail.com Fri May 16 18:25:00 2008 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 16 May 2008 17:25:00 -0500 Subject: numpy.frombuffer != unpack() ?? In-Reply-To: References: Message-ID: Marlin Rowley wrote: > All: > > I'm getting different floating point values when I use numpy vs. unpack(). > > frgba = numpy.frombuffer(, dtype=float32) > buffer = unpack("!f", byte) > > frgba[0] != buffer[0] > > why? This is forcing me use the unpack() function since it's giving me > the correct values. What am I doing wrong? Endianness, perhaps? '!' specifies big-endian data (an alias for '>'). Most likely, you are on a little-endian platform. All of the dtypes in numpy default to the native-endianness unless specified. If you want to read big-endian data using numpy, do this: frgba = numpy.frombuffer(, dtype='>f') If you have any more problems with numpy, please join us on the numpy mailing list. When reporting problems, please try to provide a small but complete snippet of self-contained code, the output that you got, and explain the output that you expected to get. Thank you. http://www.scipy.org/Mailing_Lists -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From hniksic at xemacs.org Fri May 16 18:56:20 2008 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Sat, 17 May 2008 00:56:20 +0200 Subject: Instance of class "object" In-Reply-To: =?utf-8?Q?=28=22=E7=94=9C=E7=93=9C=22=27?= =?utf-8?Q?smessage_of_=22Fri\=2C_=316_May_2=30=308_=318\=3A=309\=3A29?= =?utf-8?Q?=2B=308=30=30=22=29?= References: <8763tea9s d.fsf@mulj.homelinux.net> Message-ID: <873aoh7t9n.fsf@mulj.homelinux.net> "??" writes: >> # an efficient 'Pair' class holding two objects >> class Pair(object): >> __slots__ = 'first', 'second' >> >> Instances of Pair take up even less room that 2-element tuples >> because they don't carry the size information in the object. >> >> Now, if the object class carried a dict with it, it would be >> impossible to create a class like 'Pair'. >> > Really interesting. When the tuple ('first', 'second') is assigning > to __slot__, a special operation is done which makes __slot__ > pointing to a magic structure rather than a normal tuple. Am I > right? It's more like this: when the 'Pair' class is created, the class creation mechanism notices that the class contain a __slots__ member. It then uses that member as a specification for the layout of instances of the 'Pair' type. In this case, instead of a regular dict (which can hold any number of attributes), Pair instances hold exactly two attributes, as if[1] it had been declared as: struct Pair { PyObject_HEAD // type and refcnt, needed for Python PyObject *first; // holds pair.first PyObject *second; // holds pair.second }; I'm not sure what you mean by "pointing to a magic structure rather than a normal tuple", but without __slots__, the layout would be roughly equivalent to: struct Pair { PyObject_HEAD // type and refcnt, needed for Python PyObject *dict; // holds all pair attributes }; [1] I'm intentionally simplifying here, for example omitting weakrefs. From duncan.booth at invalid.invalid Mon May 5 06:24:00 2008 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 5 May 2008 10:24:00 GMT Subject: Feature suggestion: sum() ought to use a compensated summation algorithm References: <2aa02543-c04a-49cf-acc0-815913136172@26g2000hsk.googlegroups.com> Message-ID: Szabolcs wrote: > On May 5, 9:37 am, Szabolcs Horv?t wrote: >> Gabriel Genellina wrote: >> >> > Python doesn't require __add__ to be associative, so this should >> > not be > used as a general sum replacement. >> >> It does not _require_ this, but using an __add__ that is not >> commutative and associative, or has side effects, would qualify as a >> serious misuse, anyway. > > Sorry, I meant associative only, not commutative. > Unfortunately an __add__ which is not associative is actually perfectly reasonable. For example you could have a Tree class where adding two trees returns a new tree so (a+b)+c gives you: . / \ . c / \ a b but a+(b+c) gives: . / \ a . / \ b c From larry.bates at websafe.com` Thu May 15 15:03:22 2008 From: larry.bates at websafe.com` (Larry Bates) Date: Thu, 15 May 2008 14:03:22 -0500 Subject: Problem creating a shorcut In-Reply-To: <2715b502-d636-4541-ac0e-05697f02b2ae@m44g2000hsc.googlegroups.com> References: <2715b502-d636-4541-ac0e-05697f02b2ae@m44g2000hsc.googlegroups.com> Message-ID: Mike Driscoll wrote: > Hi, > > I've had this niggling issue from time to time. I want to create a > shortcut on the user's desktop to a website that specifically loads > Firefox even if Firefox is not the default browser. > > I usually use COM as it allows very specific settings of the shortcut, > such as the Working Directory and the Target Path. However, the > following will not work for some reason: > > > > import win32com.client > import winshell > > shell = win32com.client.Dispatch('WScript.Shell') > userDesktop = winshell.desktop() > > shortcut = shell.CreateShortCut(userDesktop + '\\MyShortcut.lnk') > shortcut.Targetpath = r'"C:\Program Files\Mozilla Firefox\firefox.exe" > https:\www.myCompanyWebsite.com\auth\preauth.php' > shortcut.WorkingDirectory = r'C:\Program Files\Mozilla > Firefox' > shortcut.save() > > > > This creates the following target path (which doesn't work): > > "C:\"C:\Program Files\Mozilla Firefox\firefox.exe" https: > \www.myCompanyWebsite.com\auth\preauth.php" > > If I leave the website off, it works. If I leave the path to Firefox > out, it works too. Is there another method I can use other than > creating the shortcut by hand and using the shutil module? > > Thank you for any ideas. > > Mike Either you copied wrong or the problem is: "C:\"C:\Program Files... Note the C:\ is specified twice in the string. I think it should read: > "C:\Program Files\Mozilla Firefox\firefox.exe" https: > \www.myCompanyWebsite.com\auth\preauth.php" -Larry From arnodel at googlemail.com Thu May 8 13:45:48 2008 From: arnodel at googlemail.com (Arnaud Delobelle) Date: Thu, 08 May 2008 18:45:48 +0100 Subject: Newbie to python --- why should i learn ! References: <9f5ee6c3-86f7-401a-acc8-cd2c9b059fbd@x19g2000prg.googlegroups.com> <68gcn4F2su97jU1@mid.uni-berlin.de> Message-ID: pistacchio writes: > ocalm forces you to di OOP Ocaml *allows* you to do OOP. It's very much an optional feature of the language, just like for Python. -- Arnaud From gherron at islandtraining.com Fri May 23 03:36:20 2008 From: gherron at islandtraining.com (Gary Herron) Date: Fri, 23 May 2008 00:36:20 -0700 Subject: error using all()/numpy [TypeError: cannot perform reduce with flexible type] In-Reply-To: References: Message-ID: <483673F4.5090104@islandtraining.com> Marc Oldenhof wrote: > Hello all, > > I'm pretty new to Python, but use it a lot lately. I'm getting a crazy > error trying to do operations on a string list after importing numpy. > Minimal example: > > [start Python] > > Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit > (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > > >>>> a=['1','2','3'] >>>> all(a) >>>> > True > >>>> from numpy import * >>>> all(a) >>>> > Traceback (most recent call last): > File "", line 1, in > File "C:\Python25\lib\site-packages\numpy\core\fromnumeric.py", line > 982, in all > return _wrapit(a, 'all', axis, out) > File "C:\Python25\lib\site-packages\numpy\core\fromnumeric.py", line > 37, in _wrapit > result = getattr(asarray(obj),method)(*args, **kwds) > TypeError: cannot perform reduce with flexible type > > [end of example] > > It seems that Python calls numpy's "all" instead of the standard one, > is that right? If so, how can I call the standard "all" after the > numpy import? ["import numpy" is not a desirable option, I use a lot > of math in my progs] > > Is there another way around this error? > Yes, there are several solutions, but before that I'll say that "from ... import *" is frowned upon for just this reason. You have no control (and often no idea) what * ends up importing, and if any of those names overwrite an existing name (as you've found here), you may not notice. (It's not quite fair to say "Python calls numpy's "all". *You* call it after you chose to replace Python's "all" with numpy's "all".) Solutions: Save Python's "all" first under another name: original_all = all from numpy import all Now you can call all(...) or original_all(...). The built-in (as they are called) are always available through __builtins__: from numpy import * all(...) # is numpy's all __builtins__.all(...) # Is the original all Don't import *, but rather import only those things you need. from numpy import array, dot, float32, int32, ... and if you need numpy's all from numpy import all as numpy_all Gary Herron > Marc > -- > http://mail.python.org/mailman/listinfo/python-list > From gandalf at shopzeus.com Tue May 20 10:22:46 2008 From: gandalf at shopzeus.com (Laszlo Nagy) Date: Tue, 20 May 2008 16:22:46 +0200 Subject: TPCServer and xdrlib In-Reply-To: <4831c608$0$14361$e4fe514c@news.xs4all.nl> References: <4831c608$0$14361$e4fe514c@news.xs4all.nl> Message-ID: <4832DEB6.1010909@shopzeus.com> > > - use simple file copying from a mounted network drive Untrustable clients should not mount out anything from my server. (Also, it is not a protocol. I need to communicate with a real program, not just copying files.) > - use http (web server) I mentioned this before - don't know how to keep-alive with simplehttpserver. Similar solutions e.g. Apache + mod_python are too heavy weight. Too many dependencies etc. > - use ftp > - use scp > - use rsync > > Why wouldn't one of these work for you? Did I miss something in your > original requirements? Yes. I also need business logic on the server. Not just copying file. It happens that some of the messages will contain images. Thank you for all your efforts. I think I'll go with TCPServer + xdrlib. Laszlo From goldnery at gmail.com Fri May 23 13:02:47 2008 From: goldnery at gmail.com (Gandalf) Date: Fri, 23 May 2008 10:02:47 -0700 (PDT) Subject: Another Question References: <5c2e7570-6bb1-46d8-8dd5-b1a257431b31@p25g2000hsf.googlegroups.com> Message-ID: On May 23, 6:25 pm, Mike Driscoll wrote: > On May 23, 10:45 am, Gandalf wrote: > > > How can i bind function that handle the mouse clicking window X event > > or clicking alt+F4 > > > thanks > > You really need to learn to ask good questions. Unless people dive > into your previous posts, they won't know what Python GUI toolkit you > are using, which version of said toolkit, which Python or which OS. > > Here's a good place to read about events in general: > > http://wiki.wxpython.org/EventPropagation > > If you use Google, you can look for the close event, which gives you > this: > > http://www.wxpython.org/docs/api/wx.CloseEvent-class.html > > So you'll want to bind your frame to EVT_CLOSE. You can disable the > "X" in your frame's window by using non-standard style parameters. > > Mike OK you right. I use WX on windows XP. I didn't understood how to use this wx.CloseEvent function. i really struggle with my poor english to understand this language, so your help is crucial for my progress and i appreciate it Thanks From marlin_rowley at hotmail.com Thu May 15 12:03:09 2008 From: marlin_rowley at hotmail.com (Marlin Rowley) Date: Thu, 15 May 2008 11:03:09 -0500 Subject: How do I use the unpack function? Message-ID: All: I've got a script that runs really slow because I'm reading from a stream a byte at a time: // TERRIBLE for y in range( height ): for color in range(4): for x in range( width ): pixelComponent = fileIO.read(4) buffer = unpack("!f",pixelComponent) << unpacks ONE float, but we now can do something with that pixel component. I can speed this up dramatically if I did this: // MUCH FASTER for y in range( height ): for color in range(4): pixelComponent = fileIO.read(4*width) <<<<<<<<< GET a LOT more data from the stream into memory FIRST!! for x in range( width ): buffer = unpack( ?????? ) <<<< how do I get each float from the pixelComponent??? -M _________________________________________________________________ With Windows Live for mobile, your contacts travel with you. http://www.windowslive.com/mobile/overview.html?ocid=TXT_TAGLM_WL_Refresh_mobile_052008 -------------- next part -------------- An HTML attachment was scrubbed... URL: From bruno.42.desthuilliers at websiteburo.invalid Fri May 23 03:45:29 2008 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 23 May 2008 09:45:29 +0200 Subject: MVC In-Reply-To: <8a269063-ae96-4707-afdc-5d2c9270e0ff@a9g2000prl.googlegroups.com> References: <8a269063-ae96-4707-afdc-5d2c9270e0ff@a9g2000prl.googlegroups.com> Message-ID: <48367601$0$20550$426a74cc@news.free.fr> George Maggessy a ?crit : > Hi Gurus, > > I'm a Java developer and I'm trying to shift my mindset to start > programming python. Welcome onboard then. > So, my first exercise is to build a website. > However I'm always falling back into MVC pattern. And ? Is there anything wrong with web-style MVC ? > I know it's a > standard, but the implementation language affects the use of design > patter. So, here goes my question. Is that OK if I follow this? Should > I create DAOs, View Objects, Controllers and etc? Is there any sort of > best practice / standard to Python? http://pylonshq.com/ http://www.djangoproject.com/ http://webpy.org/ From Avowkind at gmail.com Tue May 27 18:04:18 2008 From: Avowkind at gmail.com (Avowkind) Date: Tue, 27 May 2008 15:04:18 -0700 (PDT) Subject: definition of a highlevel language? References: <2759eed3-956d-45c7-8dfb-9557f74133b3@56g2000hsm.googlegroups.com> Message-ID: On May 27, 6:34 am, notnorweg... at yahoo.se wrote: > (might not be the right forum for this but...) > > what is the definition of a highlevel-language? > > well there isnt one specifically and wikipedia and the like gives just > a very general description obv you can say it abstracts away lowlever > operations. > > yes but how? > > a function like map takes a function and applies it to a list for > example. > this abstracts away a common procedure like iterate through a list and > for every position do a computation. > so it is a higherorderfunction. is this how higher-level-languages are > built? > > so are they fundamentally differently built or is it just a lot of > lowlevel operations built on top of each other? > > haskell is considered a very highlevellanguage but can you do > systemsprogramming with it(yes maybe it is very unpractical i dont > know but can you)? > > is lambda calculus a more abstract and efficient way of modeling a > computer? meaning you start at a higher level of abstraction and can > work up to even higher even faster? > > how did lispmachines work? was the basic system programmed in LISP? A lot of the previous comments have been about levels of abstraction of the programming langauge - which may be the answer you want. Another way of looking at it is that we want to be able to move from the language of the solution domain - e.g. computers, bits and bytes to the language of the problem domain. When we think about 'level' we don't just want to look at how basic statements work. we also need to think about whether the language is capable of simply and clearly expressing the problem. If your problem domain is mathematics then mathcad and its ilk are near perfect high level programming languages as the programs look just like the problems. if your problem domain is controlling a water works then you may tend to write your problem like this: if the water level is over 10 metres then start pump if the water level is below 5 metres then stop pump which in python might turn out to be if water_level > 10: pump.start() if water_level < 5: pump.stop() which is fairly close. of course with the addition of some brackets C++ could be this clear too. The key though is the abstraction given by the pump class and implicitly by object oriented design. In this pattern Form designers, visual web page layout tools and their ilk are very high level - but only if your problem is that you need to design a lot of business forms or web pages. Some problems are best described visually, some in text, some in mathematics. Andrew. From bignose+hates-spam at benfinney.id.au Thu May 15 05:57:32 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 15 May 2008 19:57:32 +1000 Subject: [off-topic] Usenet References: <6bafdf82-cf8a-42cd-9f72-d98a39fab5b5@j22g2000hsf.googlegroups.com> <20080514220126.e13d7cf1.johnjsal@NOSPAMgmail.com> Message-ID: <87abiryjn7.fsf@benfinney.id.au> "Terry Reedy" writes: > "John Salerno" wrote in message > news:20080514220126.e13d7cf1.johnjsal at NOSPAMgmail.com... > | On Wed, 14 May 2008 12:58:12 -0400 > | "Terry Reedy" wrote: > | > | > gmane.comp.python.general > | > | So that's the same as c.l.p.? > > It is the same as python-list, which happens to be the same as c.l.p.. Which, to be clear, is a special case: the fact that the mailing list 'python-list' and the newsgroup 'comp.lang.python' interchange messages, and are effectively the same forum, has nothing to do with Gmane. That situation predates, and is unaffected by, the introduction of Gmane. -- \ ?Good morning, Pooh Bear,? said Eeyore gloomily. ?If it is a | `\ good morning,? he said. ?Which I doubt,? said he. ?A. A. | _o__) Milne, _Winnie-the-Pooh_ | Ben Finney From grante at visi.com Tue May 20 13:24:43 2008 From: grante at visi.com (Grant Edwards) Date: Tue, 20 May 2008 12:24:43 -0500 Subject: Using Python for programming algorithms References: <48315082$0$24599$426a74cc@news.free.fr> <62884fc6-6c74-4477-91de-7b7689b5fa75@m44g2000hsc.googlegroups.com> Message-ID: On 2008-05-20, Ivan Illarionov wrote: > On Mon, 19 May 2008 11:07:06 -0700, Vicent Giner wrote: > [...] >> >> By the way, is it possible (and easy) to call a C function from a Python >> program?? > > Yes. > > http://groups.google.com/group/comp.lang.python/msg/9d47913a265c348a Even easier: http://docs.python.org/lib/module-ctypes.html -- Grant Edwards grante Yow! I'd like some JUNK at FOOD ... and then I want to visi.com be ALONE -- From hat at se-162.se.wtb.tue.nl Wed May 21 11:13:58 2008 From: hat at se-162.se.wtb.tue.nl (A.T.Hofkamp) Date: Wed, 21 May 2008 17:13:58 +0200 Subject: Code For Five Threads To Process Multiple Files? References: <8ddc1f4d-b6c1-4380-baaa-ab7e58d980ad@f36g2000hsa.googlegroups.com> Message-ID: On 2008-05-21, tdahsu at gmail.com wrote: > I'd appreciate any help. I've got a list of files in a directory, and > I'd like to iterate through that list and process each one. Rather > than do that serially, I was thinking I should start five threads and > process five files at a time. > > Is this a good idea? I picked the number five at random... I was Depends what you are doing. If you are mainly reading/writing files, there is not much to gain, since 1 process will already push the disk IO system to its limit. If you do a lot of processing, then more threads than the number of processors is not much use. If you have more 'burtsy' behavior (first do lot of reading, then lot of processing, then again reading, etc), then the system may be able to do some scheduling and keep both the processors and the file system busy. I cannot really give you advice on threading, I have never done that. You may want to consider an alternative, namely multi-tasking at OS level. If you can easily split the files over a number of OS processes (written in Python), you can make the Python program really simple, and let the OS handle the task-switching between the programs. Sincerely, Albert From ewertman at gmail.com Wed May 21 12:40:27 2008 From: ewertman at gmail.com (Eric Wertman) Date: Wed, 21 May 2008 12:40:27 -0400 Subject: time module question - time zones In-Reply-To: <92da89760805210923w39152f84ic4bb7cf0baa676b8@mail.gmail.com> References: <92da89760805210923w39152f84ic4bb7cf0baa676b8@mail.gmail.com> Message-ID: <92da89760805210940vc99afetc1c30d04d4cd9b24@mail.gmail.com> Sorry, my time zone is +4, not minus 4, which means that something else is causing my source data to be in the future. I still do need to understand where the time routines determine the time zone offset, so I can be sure I'm passing around the neutral value. Thanks! On Wed, May 21, 2008 at 12:23 PM, Eric Wertman wrote: > I tend to deal with dates a lot in different formats and places... > typically I'll convert them to a time tuple with strptime(), and pass > them around like that before I need to write them back out. > > One set of time/dates I'm getting are in UTC, but the string doesn't > say that specifically. So I do this.. I had expected the outcome to > be offset properly (I'm EST5EDT). But I'm obviously missing > something: > > #!/usr/bin/env python > > import time > > utc_str = '2008-05-10 03:05:00 UTC' > > d = time.strptime(utc_str,'%Y-%m-%d %H:%M:%S %Z') > t = time.mktime(d) > > print d > print time.gmtime(t) > print time.localtime(t) > > output : > > (2008, 5, 10, 3, 5, 0, 5, 131, 0) > (2008, 5, 10, 8, 5, 0, 5, 131, 0) > (2008, 5, 10, 4, 5, 0, 5, 131, 1) > > > I believe that I should be getting (2008, 5, 9, 23, 5, 0, 5, 130, 1) > out of one of those, since the original 3:05am time was UTC, and my TZ > is currently -4. Does that make sense? I didn't even think I needed > to do any business with time.localtime() and time.gmtime(). I > expected time.strftime() to return the locale appropriate time, but > it didn't. > > TIA > > Eric > From gagsl-py2 at yahoo.com.ar Tue May 20 18:29:04 2008 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 20 May 2008 19:29:04 -0300 Subject: regarding process preemption in linux References: <67eb1c790805192118l646fd5c4l681b196ade76b5d2@mail.gmail.com> Message-ID: En Tue, 20 May 2008 01:18:29 -0300, PARIMALA KALAVALA escribi?: > I am presently working on linux. > I wanted to know how to view the preemption of one process by another > process. If we give TOP command we are not able to visualize it or do we > need to write any different code to see it or is it possible to see it in > the proc file system. I suggest you ask in a linux group. There is nothing Python specific in this question. -- Gabriel Genellina From michele.simionato at gmail.com Tue May 13 23:57:29 2008 From: michele.simionato at gmail.com (Michele Simionato) Date: Tue, 13 May 2008 20:57:29 -0700 (PDT) Subject: Literate programs in Python References: <37e8fb41-8008-45aa-a123-b71455bc7ce5@t54g2000hsg.googlegroups.com> Message-ID: On May 13, 5:28 pm, Paul Miller wrote: > Does anyone know of any (preferably largish) examples of literate > programs written using Python? Alternatively, does anyone know of any > literate programming tools which support Python well? (I am aware of > Leo and I've been to literateprogramming.com, but any additional > pointers would be much appreciated!) > > Thanks, > > Paul You may be interested in this: http://stacktrace.it/articoli/2008/01/geek-publishing/ (you may want to use the Google Translator, unless you know Italian). From python at bc90021.net Sun May 11 14:42:21 2008 From: python at bc90021.net (bc90021) Date: Sun, 11 May 2008 18:42:21 GMT Subject: File Creation Not Working In A Thread Class? References: <7qGVj.32505$KJ1.18416@newsfe19.lga> Message-ID: > It's difficult to know what's wrong with the code you posted because: > > * it is not self-contained: otherFile, fileName, pattern are names > which you do not define; > > * the IOError you reported earlier can't arise as a result of running > this code. > > * you claim it works unless you put it in a subclass of > threading.Thread. Why don't you post this instead, and show us the > traceback? > > HTH > > FWIW, my crystal ball (whose predictions I don't usually report!) tells > me the same as Garry Herron's. Here's the thread class: #single file is the file we're working on, whose name is passed into the class and which does exist #matrix is a list of lists that contains info about the files - for this example, [c][0] contains a string, [c][2] contains true or false, and [c][3] contains a pattern to match #tfValue is another true or false value class FileProcThread(threading.Thread): def __init__(self, singleFile, matrix, tfValue): self.singleFile = singleFile self.matrix = matrix self.tfValue = tfValue threading.Thread.__init__(self) def run(self): (dirName, fileName) = os.path.split(self.singleFile) f = open(self.singleFile).readlines() copying = False for i in range(len(f)): for c in range (len(self.matrix)): if (re.search(self.matrix[c][3], f[i])): if (self.matrix[c][2] == True): copying = True if os.name == "posix": if (self.tfValue == False): tempfileName = "\"proctemp/" + self.matrix[c][0] + "_tmp_" + fileName + ".txt\"" else: tempfileName = "\"proctemp/" + self.matrix[c][0] + "_other.txt\"" else: if (self.tfValue == False): tempfileName = "\"proctemp\\" + self.matrix[c][0] + "_tmp_" + fileName + ".txt\"" else: tempfileName = "\"proctemp\\" + self.matrix[c][0] + "_other.txt\"" else: copying = False if (re.search(self.matrix[c][4], f[i])): copying = False if (copying): print "We're in copying, and tempfileName is: %s...\n" % tempfileName #The above line correctly prints the temporary file name every time! The directory exists, too! g = open(tempfileName, 'a') #This does not work. Notice I do NOT have quotes around tempfileName, as I said. g.write(f[i]) g.close() Like I said, this works FINE outside the thread class. I hope that the formatting comes through... From exarkun at divmod.com Mon May 12 11:54:47 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 12 May 2008 11:54:47 -0400 Subject: Socket and cycle problem In-Reply-To: <67c1d643-5445-46c8-b00f-20238badd398@56g2000hsm.googlegroups.com> Message-ID: <20080512155447.6859.1735358497.divmod.quotient.62519@ohm> On Mon, 12 May 2008 08:34:07 -0700 (PDT), petr.poupa at gmail.com wrote: >Hello, >I am beginner but so I need help. I have small script for receive data >from port 3883, but it print only once. > >import socket > >HOST = 'localhost' >PORT = 3883 >s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) >s.connect((HOST, PORT)) >data = s.recv(2048) >s.close() >print 'receive data from server:', `data` > >So I try to write cycle to this script, like this: > >import socket > >HOST = 'localhost' >PORT = 3883 >s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) >while 1: > s.connect((HOST, PORT)) > data = s.recv(2048) > s.close() > print 'receive data from server:', `data` > >But Python reporting: > >Traceback (most recent call last): > File "C:\Documents and Settings\poupa\Plocha\TCP3.py", line 7, in > > s.connect((HOST, PORT)) > File "", line 1, in connect > File "C:\Python25\lib\socket.py", line 141, in _dummy > raise error(EBADF, 'Bad file descriptor') >error: (9, 'Bad file descriptor') > >Where is the mistake? I dont know. You cannot reconnect a socket. You need to create a new one for each connection. It's also almost certainly the case that the way you are receiving data is incorrect. There is no guarantee that you will get 2048 bytes from socket.recv(2048). It isn't even guaranteed that all the bytes written to the socket by the peer will be returned by such a call. Instead, you need a framing protocol to determine when all data has been received. For example, you might length prefix the data, or you might insert a delimiter (or a terminator) at the end. Or if there is exactly one message to receive, then you should just read until the recv call returns '', indicating EOF. Jean-Paul From florencio.cano at gmail.com Mon May 26 14:18:48 2008 From: florencio.cano at gmail.com (Florencio Cano) Date: Mon, 26 May 2008 20:18:48 +0200 Subject: Using Python to unit test C code Message-ID: Hi! I would like to hear any information about how to unit test C code using Python. Thanks! From miller.paul.w at gmail.com Mon May 26 01:02:39 2008 From: miller.paul.w at gmail.com (miller.paul.w at gmail.com) Date: Sun, 25 May 2008 22:02:39 -0700 (PDT) Subject: Performance of Python builtins References: Message-ID: On May 25, 11:05?pm, Benjamin wrote: > http://wiki.python.org/moin/TimeComplexityis a start. Awesome. That's pretty much what I was after! From tonal at promsoft.ru Wed May 7 03:07:35 2008 From: tonal at promsoft.ru (Alexandr N Zamaraev) Date: Wed, 07 May 2008 14:07:35 +0700 Subject: strftime() argument 1 must be str, not unicode Message-ID: <48215537.100@promsoft.ru> Subj is bag? Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from datetime import datetime >>> datetime.today().strftime('%Y_%m_%d %H_%M_%S.csv') '2008_05_07 12_30_22.csv' >>> datetime.today().strftime(u'%Y_%m_%d %H_%M_%S.csv') Traceback (most recent call last): File "", line 1, in TypeError: strftime() argument 1 must be str, not unicode From bbxx789_05ss at yahoo.com Sun May 11 16:08:26 2008 From: bbxx789_05ss at yahoo.com (7stud) Date: Sun, 11 May 2008 13:08:26 -0700 (PDT) Subject: File Creation Not Working In A Thread Class? References: <7qGVj.32505$KJ1.18416@newsfe19.lga> Message-ID: <4ab8c284-7e07-4666-b2f5-123c52f02749@t54g2000hsg.googlegroups.com> On May 11, 2:01?pm, 7stud wrote: > On May 11, 1:28?pm, bc90021 wrote: > > > > > > ...and the exact error message was? > > > > Here is a tip: if you want people to help you, then you have to help > > > them to help you. ?Personally, I wouldn't respond to anymore of your > > > questions because you seem incapable of posting the information that was > > > requested. > > > So far, the people who have answered this post have gone on the > > assumption that I'm stupid. ?I'm not. ?I took perfectly working code, > > cut it from one class, and put it in another. ?It stopped working in the > > second class. ?I've spent days on this and trust me, given what I've > > experienced of the Python community so far, if I didn't have to ask, I > > wouldn't. > > > (I really must say that so far the help I am getting in the Python > > community is a big let down. ?Whether it's on IRC or here, everyone has > > an arrogance that I don't find anywhere else in the open source > > community, and it seriously makes me question the choice of language that > > I've made.) > > > The error message was at the top of the thread (am I incapable of posting > > it, or are you incapable of following a thread?), but here it is again: > > > IOError: [Errno 2] no such file u'tempfileName' > > Well, it appears to me that this error message is different than the > one in your first post. ?But maybe I'm on LSD right now and things > will be appear differently tomorrow. > > In addition, I've never seen a python error message that doesn't > include the traceback, which you were asked to post, but apparently > are still incapbable of doing. ?Also, any line numbers in the error > message should be marked in your code with comments. ?That will help > other people help you, remember? In addition, posting the exact output from this: >print "We're in copying, and tempfileName is: %s...\n" % tempfileName > #The above line correctly prints the temporary file name every time! > The directory exists, too! would be helpful. In addition, reducing your code to a simple 10 line example that produces the same problem and that anyone can run would be helpful. You might find that making the effort to produce a simple 10 line example that mimics the problem, will actually result in your solving the problem yourself. From vadim.pestovnikov at gmail.com Thu May 1 10:34:35 2008 From: vadim.pestovnikov at gmail.com (idev) Date: Thu, 1 May 2008 07:34:35 -0700 (PDT) Subject: Please help me with linking libraries on Solaris 10 sparc References: <89620267-578c-4d06-9afd-0684b5d646f5@c58g2000hsc.googlegroups.com> <4819D40A.1000205@v.loewis.de> Message-ID: <675e5d14-49c0-4ee3-8ab9-88f8926b68a3@x41g2000hsb.googlegroups.com> On May 1, 10:30 am, "Martin v. L?wis" wrote: > > lib/python/site-packages/psycopg2/_psycopg.so: symbol round: > > referenced symbol not found > > You need to link _psycopg.so with the math library, -lm. > > Regards, > Martin Martin, could you please tell me how to do this, I am pretty new in Solaris. From hyugaricdeau at gmail.com Fri May 9 10:55:10 2008 From: hyugaricdeau at gmail.com (Hyuga) Date: Fri, 9 May 2008 07:55:10 -0700 (PDT) Subject: Grabbing previous iteration in a dict References: <25657e4e-45c2-4a1f-948d-26ac64a75cd7@u6g2000prc.googlegroups.com> Message-ID: <9058e146-1d86-46cb-befc-7b40f92e9511@k37g2000hsf.googlegroups.com> On May 9, 5:10 am, dannywebs... at googlemail.com wrote: > I have a dictionary of which i'm itervalues'ing through, and i'll be > performing some logic on a particular iteration when a condition is > met with trusty .startswith('foo'). I need to grab the previous > iteration if this condition is met. I can do something with an extra > var to hold every iteration while iterating, but this is hacky and not > elegant. Why is that so terrible? previous = None for key in mydict: if key.starswith('foo') and previous is not None: # ...do stuff... previous = key Doesn't seem too ugly to me. > Is there a mechanism whereby I can just index the dict value > subscripts like in an array? I could just rewind by 1 if so. You can't rely on the keys in a dictionary being in any specific order. But if you want a list of the keys you can just call mydict.keys() which will give a copy of the dictionary's keys in a list. Then you can iterate that and use it however you would use any other list. Note that it's a copy though. It might help if you better explained exactly what you need to do. From usenet1 at anton.e4ward.com Sun May 4 12:32:27 2008 From: usenet1 at anton.e4ward.com (Anton81) Date: Sun, 04 May 2008 18:32:27 +0200 Subject: Weird import problem Message-ID: I have a directory structure like NS/dir1/file1.py NS/dir2/file2.py if in the python shell I type import NS.dir1.file1 it works, however typing import NS.dir2.file2 fails with ImportError: No module named dir2.file2 Any ideas what could go wrong? Directory permissions seem to be OK. From exarkun at divmod.com Wed May 7 11:21:10 2008 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Wed, 7 May 2008 11:21:10 -0400 Subject: listening on TCP port In-Reply-To: <1515d2cc-6dec-4552-822c-0ba558be98c6@t54g2000hsg.googlegroups.com> Message-ID: <20080507152110.6859.130552924.divmod.quotient.60093@ohm> On Wed, 7 May 2008 08:03:35 -0700 (PDT), petr.poupa at gmail.com wrote: >Hello, >is there anybody who has experience with listening on TCP port with >python? I am looking for anything codes, tutorials,... . >Thanks for any information Take a look at http://twistedmatrix.com/projects/core/documentation/howto/servers.html which gives a brief overview of writing TCP servers with Twisted. Jean-Paul From castironpi at gmail.com Sat May 17 11:16:41 2008 From: castironpi at gmail.com (castironpi) Date: Sat, 17 May 2008 08:16:41 -0700 (PDT) Subject: save dictionary for later use? References: <99403e9d-4c67-4e3f-a726-7bb02e72423a@m3g2000hsc.googlegroups.com> <9ec97b27-e4a8-40e0-b8b3-a2cdaeba448e@d77g2000hsb.googlegroups.com> <72d09350-ba1b-4af4-8fc5-190b6888bbb6@y21g2000hsf.googlegroups.com> Message-ID: On May 17, 3:52?am, castironpi wrote: > On May 16, 4:23?pm, Hans Nowak > wrote: > > > > > > > globalrev wrote: > > > pickle.dumps(mg) > > > pickle.load(mg) > > > > 'dict' object has no attribute 'readline' > > > dumps load(well i dont know but i get no complaint but running load > > > generates that error) > > > The 'loads' and 'dumps' methods use strings: > > > ?>>> import pickle > > ?>>> d = {"this": 42, "that": 101, "other": 17} > > ?>>> s = pickle.dumps(d) > > ?>>> s > > "(dp0\nS'this'\np1\nI42\nsS'other'\np2\nI17\nsS'that'\np3\nI101\ns." > > ?>>> pickle.loads(s) > > {'this': 42, 'other': 17, 'that': 101} > > > If you want to store to / restore from file, use 'dump' and 'load': > > > # write to file 'out'... > > ?>>> f = open("out") > > ?>>> f = open("out", "wb") > > ?>>> pickle.dump(d, f) > > ?>>> f.close() > > > # restore it later > > ?>>> g = open("out", "rb") > > ?>>> e = pickle.load(g) > > ?>>> g.close() > > ?>>> e > > {'this': 42, 'other': 17, 'that': 101} > > > Also seehttp://docs.python.org/lib/pickle-example.html. > > > Hope this helps! > > > --Hans > > I want to compare that cleanliness with other languages to compare > formats. > > Is pickle.load( open( 'out', 'rb' ) ) any better or worse than > pickle.load( 'out', 'rb' )?- Hide quoted text - > > - Show quoted text - This is a check-in on live-time writing. pickle.load didn't take two parameters. From marlin_rowley at hotmail.com Sat May 17 16:34:38 2008 From: marlin_rowley at hotmail.com (Marlin Rowley) Date: Sat, 17 May 2008 15:34:38 -0500 Subject: how to use the transpose function in numpy? Message-ID: All: Say I have a series of arrays arranged like so: [[[0,1,2,3] [4,5,6,7] [8,9,10,11] [12,13,14,15]] [[16,17,18,19] [20,21,22,23] [24,25,26,27] [28,29,30,31]]] Now if I do this: transpose((2,0,1)), I get this: [[[0,4,8,12] [16,20,24,28]] [[1,5,9,13] [17,21,25,29]] [[2,6,10,14][18,22,26,30]] [[3,7,11,15][19,23,27,31]]] This is NOT what I want. I want the new array to be: [0,4,8,12][1,5,9,13] [2,6,10,14][3,7,11,15] [16,20,24,28][17,21,25,29] [18,22,26,30][19,23,27,31] How do I do this? -M _________________________________________________________________ Make every e-mail and IM count. Join the i?m Initiative from Microsoft. http://im.live.com/Messenger/IM/Join/Default.aspx?source=EML_WL_ MakeCount -------------- next part -------------- An HTML attachment was scrubbed... URL: From upton at virginia.edu Thu May 15 20:07:51 2008 From: upton at virginia.edu (Dan Upton) Date: Thu, 15 May 2008 20:07:51 -0400 Subject: send yield In-Reply-To: <200805152005.52062.kyrie@uh.cu> References: <6a19b5bf-ed71-499c-a348-6e26e2f523eb@m45g2000hsb.googlegroups.com> <200805152005.52062.kyrie@uh.cu> Message-ID: <5504f9ac0805151707o1998d947sa210fc2aeec59712@mail.gmail.com> On Thu, May 15, 2008 at 8:05 PM, Luis Zarrabeitia wrote: > On Thursday 15 May 2008 09:32:37 am castironpi wrote: >> Why can't I write this? >> -- >> http://mail.python.org/mailman/listinfo/python-list > > yield recieved. > > Thanks. Should that be ack yield ? From upton at virginia.edu Mon May 12 22:36:53 2008 From: upton at virginia.edu (Dan Upton) Date: Mon, 12 May 2008 22:36:53 -0400 Subject: how to get information of a running prog in python In-Reply-To: <8b571818-25f0-4c5d-8b1c-5b7e73192d15@w5g2000prd.googlegroups.com> References: <8b571818-25f0-4c5d-8b1c-5b7e73192d15@w5g2000prd.googlegroups.com> Message-ID: <5504f9ac0805121936k1c835b20w8d59927d3e457004@mail.gmail.com> On Mon, May 12, 2008 at 10:19 PM, Jimmy wrote: > Well, i know it may be a little non-python thing, however, I can think > of no place better to post this question :) > > can anyone tell me, in python, how to obtain some information of a > running program? > paticularly, if i am playing some music in audacious or other media > player, how can i get the the name and some other info of current > playing song? It seems that audicious doesn't output on run-time > -- > http://mail.python.org/mailman/listinfo/python-list > In most cases, you'll probably need some sort of API, either in the program itself or through some sort of plugin, that lets external programs query it. For instance, there are some plugins to WinAmp that allow external programs (like Last.FM or Mog-O-Matic) to see what track is currently playing. You may also be able to do something like get the window title (again, WinAmp's title bar usually includes the artist and title) and parse it out. I don't really know that there's anything specific to Python for accessing these though, and it may vary depending on media player. Just my two cents... -dan From vivainio at gmail.com Sun May 11 16:00:42 2008 From: vivainio at gmail.com (Ville M. Vainio) Date: Sun, 11 May 2008 20:00:42 GMT Subject: observer pattern (notification chain synchronization) References: Message-ID: <87prrswqz7.fsf@gmail.com> Alan Isaac writes: > OK, thanks. > > Another approach is to begin with a set of stocks > > and remove them as they report. You can then trigger > > a report with the empty set instead of repeatedly > > calling ``all``. After a report the set can be > > "refilled". Ah, and I obviously didn't read the whole thread before posting ;-) From daveparker at flamingthunder.com Mon May 19 22:51:41 2008 From: daveparker at flamingthunder.com (Dave Parker) Date: Mon, 19 May 2008 19:51:41 -0700 (PDT) Subject: Is using range() in for loops really Pythonic? References: <482657ca$0$25026$607ed4bc@cv.net> Message-ID: <90007ef4-0b1e-46ea-b8dc-116407e538af@q24g2000prf.googlegroups.com> Your point about for-loops was applicable not only to Python, but to many other programming languages. So in response, I've added two new for-loop variations to Flaming Thunder. The two new variations are for-forever-do and for-expression-times-do. For-forever allows you to explicitly create infinite loops, and for- expression-times allows you to do something a specific number of times without having to declare a looping variable if you don't need one. Examples: Write "Fa". For 8 times do write "-la". For forever do ( Write "Do you know the definition of insanity? ". Read response. ). On May 10, 8:19?pm, John Salerno wrote: > I know it's popular and very handy, but I'm curious if there are purists > out there who think that using something like: > > for x in range(10): > ? ? #do something 10 times > > isunPythonic. The reason I ask is because the structure of the for loop > seems to be for iterating through a sequence. It seems somewhat > artificial to use the for loop to do something a certain number of > times, like above. > > Anyone out there refuse to use it this way, or is it just impossible to > avoid? From maxwell.newlands at gmail.com Thu May 15 10:02:20 2008 From: maxwell.newlands at gmail.com (max) Date: Thu, 15 May 2008 07:02:20 -0700 (PDT) Subject: no inputstream? References: <692sk0F3090hfU1@mid.uni-berlin.de> <46abd84e-f943-48a5-94b9-81f2f47cc887@f63g2000hsf.googlegroups.com> Message-ID: <974fe6b4-7e53-4a5f-bd66-6b40aa718d5d@34g2000hsh.googlegroups.com> On May 15, 9:51?am, castironpi wrote: > On May 15, 8:37?am, Marc 'BlackJack' Rintsch wrote: > > > On Thu, 15 May 2008 06:08:35 -0700, max wrote: > > > i currently have locations of the mp3s in question as strings, which > > > works for parsing local files, but gives me a "No such file or > > > directory" error when it tries to process URLs. ?it seems terribly > > > inefficient to download each mp3 just to get at that small tag data, > > > and i assume there's a way to do this with file() or open() or > > > something, i just can't get it to work. > > > You can use `urllib2.urlopen()` to open URLs as files. ?But if you deal > > with ID3 V1 tags you'll have to download the file anyway because those are > > in the last 128 bytes of an MP3 file. > > > Ciao, > > ? ? ? ? Marc 'BlackJack' Rintsch > > Just don't import time. ?What would you do with an autolocking timer, > such as time.sleep( ) on a thread? ?I am tongue tied in the presence > of a lady. thanks guys. i guess i just figured there'd be a way to get at those id3 bytes at the end without downloading the whole file. if java can do this, seems like i should just stick with that implementation, no? From ewertman at gmail.com Sat May 24 10:07:49 2008 From: ewertman at gmail.com (Eric Wertman) Date: Sat, 24 May 2008 10:07:49 -0400 Subject: Python is slow In-Reply-To: References: <2aa4c986-57d8-41dd-9f18-911625965620@z72g2000hsb.googlegroups.com> <5ccb8e61-ad53-48aa-b6ac-a6034907c36c@a32g2000prf.googlegroups.com> Message-ID: <92da89760805240707o41c580a8mdf99e5e0ceb4b8b5@mail.gmail.com> > if python is such a good programming/scripting language, why can't they > build a faster interpreter/compiler engine? and beat php and zend. > to the python team, rebuild your interpreter! while this is just a boring troll.. it does bring me to a more interesting point... it would be cool if the interpreter were multi-threaded to make better use of smp systems. While you can do threading, if you really want to drive more than one cpu some forking is in order. From bignose+hates-spam at benfinney.id.au Sun May 18 21:38:37 2008 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 19 May 2008 11:38:37 +1000 Subject: New to Python, Discussion Groups. References: Message-ID: <87abinjco2.fsf@benfinney.id.au> cmoller writes: > I am new to Python and the use of discussion groups. Welcome to both. > Is there a FAQ for basic information so certain questions are not > repeated? Congratulations on asking this question; it puts you ahead of many other first-time posters. Python's official FAQ documents are on the Python site . Despite its arrogant tone, the document "How to Ask Questions the Smart Way" is a good guide for interacting well with technical discussion forums. -- \ "I bet one legend that keeps recurring throughout history, in | `\ every culture, is the story of Popeye." -- Jack Handey | _o__) | Ben Finney From eric.hanchrow at gmail.com Thu May 8 18:15:28 2008 From: eric.hanchrow at gmail.com (offby1) Date: Thu, 8 May 2008 15:15:28 -0700 (PDT) Subject: anagram finder / dict mapping question References: Message-ID: Been there, done that: http://polyglot-anagrams.googlecode.com/svn/trunk/python/ From fc14301589 at icqmail.com Tue May 27 04:21:01 2008 From: fc14301589 at icqmail.com (TheSaint) Date: Tue, 27 May 2008 16:21:01 +0800 Subject: Using poplib to parse headers References: Message-ID: <483bc46e_2@news.tm.net.my> On 06:39, marted? 27 maggio 2008 Jean-Claude Neveu wrote: > However, if I understand right, the Python poplib library will also > parse the email for me so that I can iterate through the headers See my program at http://it.geocities.com/call_me_not_now/index.html You may study it. But for short you can use from email.Parser import HeaderParser # then you can parse the mail, body etc here below M = poplib.POP3('mail.blah.com') M.user('username') M.pass_('password') numMsgs = len(M.list()[1]) for cnt in range(1, numMsgs +1): header= M.top(cnt,0)[1]) HTH From netizen at gmx.de Fri May 23 03:29:42 2008 From: netizen at gmx.de (Michael Fesser) Date: Fri, 23 May 2008 09:29:42 +0200 Subject: php vs python References: <5l%Yj.77$mz3.53@fe101.usenetserver.com> Message-ID: .oO(Nick Craig-Wood) >Damon Getsman wrote: >> PHP has great support for accessing a MySQL database, > >Actually I'd say PHP's mysql support is lacking a very important >feature. mysql_query() doesn't support parameters (or placeholders, >usually '?') Where were you the last couple of years? It's lacking a lot more features, but that's not the fault of the MySQL extension, which is quite old. Meanwhile we have the improved MySQL extension and PDO. >It is not a big deal, but I've had it drummed into me to always use >parameters for user input and I was really suprised PHP didn't have >them. PHP supports them since _years_, you just have to choose the right database interface. Micha From deets at nospam.web.de Tue May 27 08:50:23 2008 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 27 May 2008 14:50:23 +0200 Subject: decorators when? References: <3m0o34hbb0c6rpr6ec0qh3hlkaagt8pfi5@4ax.com> Message-ID: <6a2edeF356g4eU1@mid.uni-berlin.de> David C. Ullrich wrote: > What version added decorators (using the > @decorator syntax)? > > (Is there a general way I could have found out the answer myself?) > > Is there a somthing such that "from __future__ import something" > will make decorators work in 2.5.2? They do work. They were introduced in python2.4 Diez From straton at lampsacos.demon.co.uk Mon May 19 09:31:51 2008 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Mon, 19 May 2008 14:31:51 +0100 Subject: How do *you* use Python in non-GUI work? In-Reply-To: <20080518182022.990193bd.johnjsal@NOSPAMgmail.com> References: <20080518182022.990193bd.johnjsal@NOSPAMgmail.com> Message-ID: John Salerno wrote: > Hey all. Just thought I'd ask a general question for my own interest. Every time I think of something I might do in Python, it usually involves creating a GUI interface, so I was wondering what kind of work you all do with Python that does *not* involve any GUI work. This could be any little scripts you write for your own benefit, or what you do at work, if you feel like talking about that! :) > > Thanks. The vast majority of my Python work is Non-GUI. As an example, this weekend, I wrote a script to help in making a 'Lyrics' track in an audacity file, which is (more-or-less) an XML variety. In audacity, I created 'markers' in the file (as the song played) at the start of each line. The result was 'blank' markers at the correct times: