Re: Python 3
* Steven D'Aprano: On Thu, 05 Nov 2009 13:27:09 +1100, Ben Finney wrote: Steven D'Aprano writes: On Wed, 04 Nov 2009 23:08:54 +1100, Ben Finney wrote: Steven D'Aprano writes: Why would I want to use an already existing library that is fast, well- written and well-supported, when I can toss together a nasty kludge myself? Because using that library will ensure you can't migrate to Python 3 any time soon? Why would I want to migrate to Python 3 any time soon? Sounds like you've answered the questions posed, then. Good for you! I was actually only being *half* tongue in cheek, which is why I left out the smiley. On the python-dev list at the moment is a lot of discussion on why uptake of Python 3.1 has been slower than hoped. But one of the things that people haven't really discussed -- or at least that I haven't seen -- is why one would prefer 3.1 over 2.5 or 2.6. I've played around with 3.0, and I've read the What's New for 3.1 (and am installing 3.1 now), and while the changes look nice, I'm not sure that they're nice enough to deal with the pain of 2to3 migration. So how about that, 3.1 fans? What are the most compelling reasons for you that convinced you to change? Since I'm just learning Python and am an utter Python novice this might not amount to much, but it's in the nature of language evolution that the new more or less incompatible version *does* become the dominant one, and for new things it's then a good idea to adopt the coming in future generally used version of the language, instead of being left in a quagmire trying to catch up with new versions of tools and libs suddenly not so compatible with the old code. This happened with e.g. C++ standardization in 1998. The whole standard library was revamped and put in a namespace, and old headers like [iostream.h] were removed. And as with the Python "/" operator core language functionality was changed: in C++98 'new' suddenly threw (Pythoneese raised) an exception instead of returning 0 on failure, and templates were suddenly "two phase" with quite different semantics, so that much old code didn't even compile, and when it did, didn't work correctly. But those who chose to stay behind paid and still for some pay the price, having to use ages old tools and libs. One amusing or sad (depending one's point of view) variant was where firms chose to get along with the language evolution, tools etc., but still restrict themselves to not only pre-standard C++ but some early 1980's version, not much more than "C with classes" or "better C". For example, at Google they generally don't use C++ exceptions, presumably because they have a large code base of non-exception-safe code. Still, assuming that's the rationale, it would surprise me if they don't use exceptions in their new code. This is perhaps an heretical view, that the new language version's advantages don't matter so much as the fact that the new language version is incompatible, viewing that incompatibility as a /reason/ to change. But I think it's realistic; getting the advantages (such as with Python 3.x improved efficiency for range etc., and thus also more clear notation) is just an added bonus. Cheers & hth., - Alf -- http://mail.python.org/mailman/listinfo/python-list
Re: Pyfora, a place for python
Daniel Fetchinson wrote: > Yes, this is about the right kind of response I think everybody > deserves who puts energy/enthusiasm/effort/time into putting together > a python-related forum. So what's the right kind of response deserved by those who put energy/ enthusiasm/effort/time into sustaining _this_ python-related forum? Accusations of hostility? Second-guessing their intentions? What right do you have to demand different behaviour from that which you yourself have demonstrated? -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 3
On Thu, 05 Nov 2009 13:27:09 +1100, Ben Finney wrote: > Steven D'Aprano writes: > >> On Wed, 04 Nov 2009 23:08:54 +1100, Ben Finney wrote: >> >> > Steven D'Aprano writes: >> >> Why would I want to use an already existing library that is fast, >> >> well- written and well-supported, when I can toss together a nasty >> >> kludge myself? >> > >> > Because using that library will ensure you can't migrate to Python 3 >> > any time soon? >> >> Why would I want to migrate to Python 3 any time soon? > > Sounds like you've answered the questions posed, then. Good for you! I was actually only being *half* tongue in cheek, which is why I left out the smiley. On the python-dev list at the moment is a lot of discussion on why uptake of Python 3.1 has been slower than hoped. But one of the things that people haven't really discussed -- or at least that I haven't seen -- is why one would prefer 3.1 over 2.5 or 2.6. I've played around with 3.0, and I've read the What's New for 3.1 (and am installing 3.1 now), and while the changes look nice, I'm not sure that they're nice enough to deal with the pain of 2to3 migration. So how about that, 3.1 fans? What are the most compelling reasons for you that convinced you to change? -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter callback arguments
* Alf P. Steinbach: * Steven D'Aprano: On Wed, 04 Nov 2009 08:50:42 +0100, Alf P. Steinbach wrote: * Gabriel Genellina: I don't understand either. R1 and R2 have *different* semantics. Assume that they have the very exact same semantics Why would we assume that when you have explicitly told us that they don't? You stated categorically that they behave differently when you assign to the attribute/property "top". Uh, severe reading difficulties ... referring to self in plural ... Hm. :-) But anyway, in the example description I wrote "With R1 direct changes of left and top keeps the rectangle's size" and this is in the context of a discussion of modifying data attributes directly versus using properties. Perhaps this makes it more clear: in R1, which has a width/height based rectangle representation, assigning directly to the top data attribute /effectively/ moves the rectangle vertically without changing its height, since the height attribute is unchanged. But that does not reflect any intended semantics, it's not a requirement; it's an implementation artifact, a behavior that just results from direct modification and the choice of a particular rectangle representation. Real world Python example of that kind of artifact: as discussed in some other thread here, doing open( ..., 'r+' ) followed by write followed directly by read will on some implementations/systems produce garbage. Presumably because those implementations use C "FILE*" to implement the functionality, and implements it by a fairly direct mapping of calls down to the C level, where this sequence is in general Undefined Behavior. You might regard it as semantics, and it's quite real and presumably in a sense well-defined for the particular implementation on the particular system, but it's not part of any intended semantics, and any who relies on that behavior is doing it at other's risk. For the R1 class the indended semantics, the specification that the programmer was handed down or produced or had in mind, might include just rectangle construction, checking intersection with other rectangle, and obtaining any of three pairs of values: left upper corner, right lower corner and width+height. For example. :-) Cheers & hth., - Alf -- http://mail.python.org/mailman/listinfo/python-list
Re: Python 3
Steven D'Aprano writes: > On Wed, 04 Nov 2009 23:08:54 +1100, Ben Finney wrote: > > > Steven D'Aprano writes: > >> Why would I want to use an already existing library that is fast, > >> well- written and well-supported, when I can toss together a nasty > >> kludge myself? > > > > Because using that library will ensure you can't migrate to Python 3 > > any time soon? > > Why would I want to migrate to Python 3 any time soon? Sounds like you've answered the questions posed, then. Good for you! -- \“The whole area of [treating source code as intellectual | `\property] is almost assuring a customer that you are not going | _o__) to do any innovation in the future.” —Gary Barnett | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Pyfora, a place for python
Alan Franzoni writes: > That's right... forums, although more "accessible" to all the people > who can't/doesn't want to use specific email or nntp clients, are > quite slow to use. > > But I think Ubuntu forums support threads and are kind of "channeled" > between ML and webinterface... something like Google Groups; I think > THAT would be a good idea. What about trying to "channel" > comp.lang.python and a forum? Please, be more specific. As I said earlier in this thread, a “forum” could be a mailing list, a Usenet newsgroup, a walled-garden web application, an IRC channel, or a face-to-face meeting in a pub. So speaking of comp.lang.python as though it's *not* a forum is confusing. Please choose a term that makes it clear why what one is speaking about is distinct from the comp.lang.python forum. -- \ “Just because nobody complains doesn't mean all parachutes are | `\ perfect.” —Benny Hill | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Pyfora, a place for python
In article , Alan Franzoni wrote: > On 11/2/09 3:44 PM, Diez B. Roggisch wrote: > > Being from germany, I can say that we *have* this fragmentation, and > > frankly: I don't like it. I prefer my communication via NNTP/ML, and not > > with those visually rather noisy and IMHO suboptimal forums. E.g. it > > That's right... forums, although more "accessible" to all the people who > can't/doesn't want to use specific email or nntp clients, are quite slow > to use. > > But I think Ubuntu forums support threads and are kind of "channeled" > between ML and webinterface... something like Google Groups; I think > THAT would be a good idea. What about trying to "channel" > comp.lang.python and a forum? comp.lang.python *is* already "channel"ed in multiple venues: the Usenet group itself, the base python.org mailing list, gmane.org (NNTP newsgroup from the mailing list, various web interfaces, RSS feed), google groups, and others. -- Ned Deily, n...@acm.org -- http://mail.python.org/mailman/listinfo/python-list
Re: multicast
Forgot the code... doh! :) #! /usr/bin/env python import socket import time class MulticastSender(object): def __init__(self, MCAST_ADDR = "224.168.2.9", MCAST_PORT = 1600): self.MCAST_ADDR = MCAST_ADDR self.MCAST_PORT = MCAST_PORT ANY = "0.0.0.0" SENDERPORT=1501 #create a UDP socket self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) #allow multiple sockets to use the same PORT number self.sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) #The sender is bound on (0.0.0.0:1501) self.sock.bind((ANY,SENDERPORT)) #Tell the kernel that we want to multicast and that the data is sent #to everyone (255 is the level of multicasting) self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 255) def send(self, data): self.sock.sendto(data, (self.MCAST_ADDR, self.MCAST_PORT)); class MulticastReceiver(object): def __init__(self, MCAST_ADDR = "224.168.2.9", MCAST_PORT = 1600): ANY = "0.0.0.0" #create a UDP socket self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) #allow multiple sockets to use the same PORT number self.sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) #Bind to the port that we know will receive multicast data self.sock.bind((ANY,MCAST_PORT)) #tell the kernel that we are a multicast socket self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 255) #Tell the kernel that we want to add ourselves to a multicast group #The address for the multicast group is the third param status = self.sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, socket.inet_aton(MCAST_ADDR) + socket.inet_aton(ANY)); self.sock.setblocking(0) def setblocking(self, flag): self.sock.setblocking(flag) def recv(self, size = 1024): return self.sock.recvfrom(size) class Multicast(object): def __init__(self): self.__ms = MulticastSender() self.__mr = MulticastReceiver() def send(self, data): self.__ms.send(data) def recv(self, size = 1024): return self.__mr.recv() if __name__ == "__main__": mc = Multicast() while 1: try: data, addr = mc.recv() except socket.error, e: #print "sock.error: ", e pass else: print "FROM: ", addr print "DATA: ", data -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter callback arguments
* Steven D'Aprano: On Wed, 04 Nov 2009 08:50:42 +0100, Alf P. Steinbach wrote: * Gabriel Genellina: I don't understand either. R1 and R2 have *different* semantics. Assume that they have the very exact same semantics Why would we assume that when you have explicitly told us that they don't? You stated categorically that they behave differently when you assign to the attribute/property "top". Uh, severe reading difficulties ... referring to self in plural ... Hm. :-) But anyway, in the example description I wrote "With R1 direct changes of left and top keeps the rectangle's size" and this is in the context of a discussion of modifying data attributes directly versus using properties. Anyway, if that formulation was confusing I have clarified it later, so you really, ideally, should have no problem grasping this. According to your own description, setting R1.top moves the rectangle, while setting R2.top resizes it. Perhaps the difference between "move" and "resize" is too subtle for you, but you can trust us on this, they are different semantics. No, I would absolutely not trust you Steven, whether that's plural or singular, to assign semantics to my examples. -- like two TV sets that look the same and work the same except when you open 'em up and poke around in there, oh holy cow, in this one there's stuff that isn't in the other. Whether "top" is an attribute or a property is irrelevant, Sorry, that's incorrect. For example, if it is a read only property than you can't assign to the property. For another example, if it is a read/write property than it can update any parts of the rectangle represention. it is still part of the public API of the class. Sorry, that's incorrect; it depends on the class. Such public attributes are NOT private internal details, they are part of the public interface. Sorry, that's incorrect; it depends on the class, and as far as I know and have been informed here there are no private attributes in Python, just a notational convention. You've been told this repeatedly. Sorry, but repeating what you want me to have meant in my example, contrary to the direct text of the example, contrary to its context, choosing a meaningless interpreteration of what's left when you have ignored the text, plus contrary to further clarifications, well that's daft to say the least. Perhaps one more time may help: Public attributes are public. It would be nice if Python had private ones, yes. Cheers & hth., - Alf -- http://mail.python.org/mailman/listinfo/python-list
Re: set pdb break condition based upon number of hits?
Reckoner schrieb: Is it possible to set pdb break condition based upon number of hits? I mean something like (Pdb) break line_number (number_of_hits_for_this_breakpoint >10) any help appreciated. MY_GLOBAL_COUNTER = 0 MY_GLOBAL_COUNTER += 1 if MY_GLOBAL_COUNTER >= 10: import pdb; pdb.set_trace() Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: module imports and st_mtime
On Nov 4, 4:08 pm, tow wrote: > Does anyone have any ideas what might be going on, or where further to > look? I'm at a bit of a loss. Does Mac OS have a concept of process-local filesystem modification? I.e. when loading the library does it create a process-local copy of the file with an updated timestamp? Only thing I can think of, and if so it's probably not something you want to turn off. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter callback arguments
On Wed, 04 Nov 2009 08:50:42 +0100, Alf P. Steinbach wrote: > * Gabriel Genellina: >> >> I don't understand either. R1 and R2 have *different* semantics. > > Assume that they have the very exact same semantics Why would we assume that when you have explicitly told us that they don't? You stated categorically that they behave differently when you assign to the attribute/property "top". According to your own description, setting R1.top moves the rectangle, while setting R2.top resizes it. Perhaps the difference between "move" and "resize" is too subtle for you, but you can trust us on this, they are different semantics. > -- like two TV > sets that look the same and work the same except when you open 'em up > and poke around in there, oh holy cow, in this one there's stuff that > isn't in the other. Whether "top" is an attribute or a property is irrelevant, it is still part of the public API of the class. Such public attributes are NOT private internal details, they are part of the public interface. You've been told this repeatedly. Perhaps one more time may help: Public attributes are public. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
module imports and st_mtime
I'm seeing a very strange effect which is confusing me - in brief, one python process appears to temporarily affect the os.stat results of another - perhaps someone can enlighten me. This is on Mac OS X Leopard, using the system python (2.5) The issue arises using Django. The default Django http server runs a watcher thread, which checks if any code is changing, and reloads itself. It does this by iterating over all loaded modules, and checking the mtime of each __file__. This was behaving oddly, and finding out why exposed this strangeness. (The relevant code is in django/utils/autoreload.py) Some of the code running under this django server imports simplejson, the C-implemented module of which has been put at /Users/tow/.python- eggs/simplejson-2.0.9-py2.5-macosx-10.5-i386.egg-tmp/simplejson/ _speedups.so This hasn't been touched since it was installed: ls -l ~/.python-eggs/simplejson-2.0.9-py2.5-macosx-10.5-i386.egg-tmp/ simplejson/_speedups.so -rwxr-xr-x 1 tow staff 77596 12 Aug 17:56 /Users/tow/.python-eggs/ simplejson-2.0.9-py2.5-macosx-10.5-i386.egg-tmp/simplejson/ _speedups.so If I check the mtime of that file from within django, it finds it correctly: print datetime.datetime.utcfromtimestamp(os.stat("/Users/tow/.python- eggs/simplejson-2.0.9-py2.5-macosx-10.5-i386.egg-tmp/simplejson/ _speedups.so").st_mtime) 2009-08-12 17:56:02 The strange effect occurs when I open another python process, and import simplejson there as well. As soon as I've done that, the mtime that Django sees slips by an hour: print datetime.datetime.utcfromtimestamp(os.stat("/Users/tow/.python- eggs/simplejson-2.0.9-py2.5-macosx-10.5-i386.egg-tmp/simplejson/ _speedups.so").st_mtime) 2009-08-12 16:56:02 In fact, to be precise, this happens as soon as the simplejson._speedups module *finishes* being imported. (Tested by stepping through every line with pdb) The second Python process still sees the correct mtime, though, both before and after it imports simplejson. Restarting the Django process resets its view of the world, and it sees the correct mtime again. The current time as seen by the Django process is correct both before and after the mtime slippage. This seems to be 100% reproducible here, except for the time offset. Usually it loses one hour, sometimes it gains 5 hours. (For what it's worth, I'm currently on GMT, but the file was created during daylight savings time). I haven't managed to replicate it when the first process is something other than Django. I've seen the effect on other Mac OS machines, but haven't tested it on Linux so far. I've only seen the effect with simplejson's C module, but I think this is the only C module which might be being imported twice in this way for me. Does anyone have any ideas what might be going on, or where further to look? I'm at a bit of a loss. Toby -- http://mail.python.org/mailman/listinfo/python-list
Re: How to test urllib|urllib2-using code?
On Wed, 04 Nov 2009 15:06:45 +0100, Lutz Horn wrote: > Hi, > > kj wrote: >> I want to write some tests for code that uses both urllib and urllib2. > > Take a look at the discussion under the title "How can one mock/stub > python module like urllib" at stackoverflow: > > http://stackoverflow.com/questions/295438/how-can-one-mock-stub-python- module-like-urllib Oh noes!!! Ur fragmenting teh python communities1!!! DO NOT WANT!!! *grin* (And for those who don't know what on earth I'm referring to, see the thread "Pyfora, a place for python".) -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Python 3 [was Re: substituting list comprehensions for map()]
On Wed, 04 Nov 2009 23:08:54 +1100, Ben Finney wrote: > Steven D'Aprano writes: > >> On Tue, 03 Nov 2009 22:43:45 -0600, Robert Kern wrote: >> > from numpy import dot >> > >> > scalar = dot(vec1, vec2) >> >> Why would I want to use an already existing library that is fast, well- >> written and well-supported, when I can toss together a nasty kludge >> myself? > > Because using that library will ensure you can't migrate to Python 3 any > time soon? Why would I want to migrate to Python 3 any time soon? 2.5 and 2.6 meet my needs (so far), and the new features in Python 3 aren't especially compelling to me. Particularly if migrating to 3 requires me to re-write all the libraries, where's the advantage? -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Using logging module for conditional nested logs
On Nov 4, 1:30 pm, Vinay Sajip wrote: > On Nov 4, 7:40 pm, Reckoner wrote: > > > > > I hope that made some sense. > > Not especially :-( > > Sorry I don't understand exactly what you mean, because I find your > terminology confusing. For example, "logger that is attached to foo2" > - loggers are not attached to functions. "It responds to the 'root' > logger" - what responds? What's meant by "respond"? > > Loggers correspond to specific code components in an application. > Normally these areas are modules and sometimes they're classes. > > You can certainly treat functions as areas but this will typically > become unwieldy in any sizeable application. It doesn't (in general) > make sense to have a specific logger for foo1 for use only when it's > called by foo2. These seem like anti-patterns to me. > > Handlers are attached to loggers to make events logged via those > loggers available to different audiences - via console, file, email > etc. > > If you want to log that foo1 is being called by foo2, you can do this. > For example, you could have a utility function which walks (a > sufficient part of) the call stack to see the function call hierarchy, > then log this as additional information (e.g. using the 'extra' > parameter to the logging call). You can attach Filters to loggers and > handlers which use this information to decide where and whether to > actually record the event. > > As well as the Python logging documentation, you may also find the > following link useful: > > http://plumberjack.blogspot.com/2009/09/python-logging-101.html > > Regards, > > Vinay Sajip I appreciate your patience, as I am new to this. Your comments have put me on the right track. I will look at the link you specify. Thanks again. -- http://mail.python.org/mailman/listinfo/python-list
Re: restricted mode???
> I thought that restricted mode died ages ago. > > Any ideas what could be causing this? Restricted mode is still available, and activated whenever a frame's builtins directory is different from the interpreter's; see PyFrame_IsRestricted. Regards, Martin -- http://mail.python.org/mailman/listinfo/python-list
Re: Pyfora, a place for python
On 11/2/09 3:44 PM, Diez B. Roggisch wrote: > Being from germany, I can say that we *have* this fragmentation, and > frankly: I don't like it. I prefer my communication via NNTP/ML, and not > with those visually rather noisy and IMHO suboptimal forums. E.g. it That's right... forums, although more "accessible" to all the people who can't/doesn't want to use specific email or nntp clients, are quite slow to use. But I think Ubuntu forums support threads and are kind of "channeled" between ML and webinterface... something like Google Groups; I think THAT would be a good idea. What about trying to "channel" comp.lang.python and a forum? -- Alan Franzoni contact me at pub...@[mysurname].eu -- http://mail.python.org/mailman/listinfo/python-list
Re: problem in installing wxwidgets for python.
This additional links should come in hand: http://www.gossamer-threads.com/lists/python/python/785413?page=last http://www.daniweb.com/forums/thread235862.html# http://forum.amule.org/index.php?topic=11728.0 http://www.linuxquestions.org/questions/linux-software-2/problem-in-installing-wxwidgets...-76/ I hope it can help. Good luck and have fun! ThreaderSladh -- Forwarded message -- From: Ishwor Gurung To: python-list@python.org Date: Wed, 4 Nov 2009 23:11:39 +1100 Subject: Re: problem in installing wxwidgets for python.. Hi, 2009/11/4 Jebagnana Das : > Hello friends, > I've tried to install wxwidgets in my mandriva 2009 spring > for GUI interaction with python. In the installation instruction it said > that i need gtk+ library. So i downloaded GTK+. When i configured GTK+ i got > the message You probably want wxpython binding instead - http://www.wxpython.org/ Use binaries provided by Mandriva's package manager where possible unless you _really_ want to do a source installation. > checking for BASE_DEPENDENCIES... configure: error: Package requirements > (glib-2.0 >= 2.21.3atk >= 1.13.0pango >= 1.20cairo >= 1.6) were > not met: > > > Requested 'glib-2.0 >= 2.21.3' but version of GLib is 2.20.1 > > Consider adjusting the PKG_CONFIG_PATH environment variable if you > installed software in a non-standard prefix. $ export PKG_CONFIG_PATH=/usr/lib/ pkgconfig:/usr/local/lib/pkgconfig (considering that your local installs went to those directories. Try replacing those directories accordingly for glib, atk, pango and cairo). The files you're after is a ".pc" (pkg-config need them) file. A quick find will tell you where it is if it is installed. Run configure script again. > Alternatively, you may set the environment variables > BASE_DEPENDENCIES_CFLAGS > > and BASE_DEPENDENCIES_LIBS to avoid the need to call pkg-config. > See the pkg-config man page for more details. > > Then i downloaded glib2.21.3,atk 1.13.0,pango 1.20 and cairo 1.6. I > installed all the packages using the following commands. [...] > tar xvzf filename.tar.gz > cd folder > ./configure > > make > make install Yep. Check where it installed them one by one. In short, you need access to a ".pc" file that they provide. If not, write one yourself. > I've not specified anf options like --prefix and i installed in the folder > itself. man pkg-config for further info. > when i tried to install gtk+ after installing all this it showed the same > error. What should i do to install wxwidgets? Plz. reply as soon as > possible.. Coz. i've to finish my proj. quickly.. Thanks and regards... See above. -- http://mail.python.org/mailman/listinfo/python-list
Re: disable image loading to speed up webpage load
On 4-11-2009 8:32, elca wrote: Diez B. Roggisch-2 wrote: Use urllib2. you can show me some more specific sample or demo? It's not even more than 1 click away in the Python standard lib documentation... how hard can it be? http://docs.python.org/library/urllib2.html#examples -irmen -- http://mail.python.org/mailman/listinfo/python-list
Re: python os.path.exists failure
In article <9aaf6a31-a34e-454b-a8f0-e206ad9b7...@t2g2000yqn.googlegroups.com>, koranthala wrote: > >path = r'C:/"Program Files"/testfolder/2.3/test.txt' >if os.path.lexists(path): >print 'Path Exists' >else: >print 'No file found in path - %s' %path >print Popen(path, stdout=PIPE, shell=True).stdout.read() Avoiding shell=True is a Good Idea -- Aahz (a...@pythoncraft.com) <*> http://www.pythoncraft.com/ [on old computer technologies and programmers] "Fancy tail fins on a brand new '59 Cadillac didn't mean throwing out a whole generation of mechanics who started with model As." --Andrew Dalke -- http://mail.python.org/mailman/listinfo/python-list
Re: Using logging module for conditional nested logs
On Nov 4, 7:40 pm, Reckoner wrote: > > I hope that made some sense. Not especially :-( Sorry I don't understand exactly what you mean, because I find your terminology confusing. For example, "logger that is attached to foo2" - loggers are not attached to functions. "It responds to the 'root' logger" - what responds? What's meant by "respond"? Loggers correspond to specific code components in an application. Normally these areas are modules and sometimes they're classes. You can certainly treat functions as areas but this will typically become unwieldy in any sizeable application. It doesn't (in general) make sense to have a specific logger for foo1 for use only when it's called by foo2. These seem like anti-patterns to me. Handlers are attached to loggers to make events logged via those loggers available to different audiences - via console, file, email etc. If you want to log that foo1 is being called by foo2, you can do this. For example, you could have a utility function which walks (a sufficient part of) the call stack to see the function call hierarchy, then log this as additional information (e.g. using the 'extra' parameter to the logging call). You can attach Filters to loggers and handlers which use this information to decide where and whether to actually record the event. As well as the Python logging documentation, you may also find the following link useful: http://plumberjack.blogspot.com/2009/09/python-logging-101.html Regards, Vinay Sajip -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter callback arguments
* Terry Reedy: Alf P. Steinbach wrote: However, the natural semantics is that various logical properties, such as left, top, right, bottom, width and height, can be varied independently. But they *CANNOT* be varied independently. A rectangle with side parallel to the axes has exactly 4 degress of freedom, not 6. Yes . That's the basic idea of the example I presented up-thread, that's discussed here. With R1's state variables width and heigh can be varied independently by direct modification, with R2 it's right and bottom. The public interface must also make this choice, but it's an independent choice: the internal rectangle representation can have the opposite choice. And conversely, that means that if the internal representation isn't used directly, then it can be changed without affecting the public interface. Cheers, - Alf -- http://mail.python.org/mailman/listinfo/python-list
Re: regexp help
Simon Brunning wrote: 2009/11/4 Nadav Chernin : Thanks, but my question is how to write the regex. re.match(r'.*\.(exe|dll|ocx|py)$', the_file_name) works for me. How about: os.path.splitext(x)[1] in (".exe", ".dll", ".ocx", ".py"): DaveA -- http://mail.python.org/mailman/listinfo/python-list
Using logging module for conditional nested logs
Hi, I am getting started with your logging module and I went through the tutorial and know-how to create a top-level 'root' logger with the appropriate handlers. I have a number of functions,say, def foo1() def foo2() ... foo1() # foo2 calls foo1 and I know how to connect each of these functions to the 'root' logger by doing something like def foo1() logger = getLogger('root.foo1') but I want to arrange it so that foo1 adds to the logfile that foo2 is using ONLY when foo2 calls foo1. In other words, if I do def foo2() logger = getLogger('root.foo2') or def foo1() logger = getLogger('root.foo2.foo1') it responds to the 'root' logger when I want it to respond to *any* logger that is attached to foo2. Then, the question is how can I set up foo1 to log to whatever logger foo2 is using. The purpose of doing this is that I am interested in capturing when and by whom foo1 is called in whatever logger foo2 is using. So, if I attach a separate logger to a third function, say, foo3 (), then I can avoid reporting those instances when foo3 calls foo1. I hope that made some sense. -- http://mail.python.org/mailman/listinfo/python-list
Re: comparing alternatives to py2exe
Hi, in this discussion I read that we con create a bundle executable for our application, since I'm having troubles with create a exe due problems with kinterbasdb, can you show me tutorials for creating exe from bundle. thanks in advance. On Wed, Nov 4, 2009 at 11:21 AM, Vesa Köppä wrote: > iu2 wrote: > >> Another thing that I think is of interest is whether the application >> support modifying the version and description of the exe (that is, on >> Windows, when you right-click on an application and choose >> 'properties' you view the version number and description of the >> application, it is a resource inside the exe). I think py2exe supports >> it. >> > > Pyinstaller supports this. > > Vesa > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Pyfora, a place for python
Valentina Boycheva wrote: I was following this discussion first with curiosity and then with increasing disbelief. > So stop following it. Really. As a scientist and a programmer, I always considered myself belonging to a group of people who are broad-minded and task-oriented. Ditto. I read python-list as the newgroup gmane.comp.python.general and only download the posts I select, which is well less than half, depending on my mood;-). -- which is to say, whether or not I am looking for time-wasting entertainment ;-) Being an occasional Python programmer, I subscribed to this list in the hopes of learning from the pros. Most of the time I do. But I also see a disturbing trend of petty bickering, splitting hairs and one-upmanship. I have been reading for over 10 years and see no increasing trend. The worst times were definitely in the past. I understand there will be occasional language slips and misconstrued jokes but can we please stick to the topic and remain courteous at all times? I completely agree, but have given up most admonishments ;-) > I am seriously considering unsubscribing from this UL That would be a shame. (and maybe joining Pyfora.) That should be an independent decision. Most PHPBBS web forums I have seen are about the same or worse as far as civility. Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I install dlls and exes for libtidy and others?
Lme clarify my problems. My earlier emails were pretty vague... so this should help. Problem: I have been wanting to try out many libraries that use Python to C/C++ app bindings. This means I install the Python library using easy_install and then install the pre-compiled Windows binaries and/or dlls... but that is where the problem arises: * I do not know where to install the pre-compiled binaries. There are no instructions on this -- it's like everyone assumes I know what to do. * I tried copying the exe and/or dlls to Python, Python\Lib, Python\Dll * import libxml2, import libxslt, and import libtidy do not work. For example for libtidy, I get: import tidy OSError: Couldn't find libtidy, please make sure it is installed. * The problem is always when a library requires pre-compiled Windows binaries. I can't every get any such libraries to work. My questions. What is the proper way to setup these pre-compiled binaries so that they will work with Python libraries? What are all the steps? Is there some things I can do to help diagnose problems? Could the problems be something different? _ Windows 7: Unclutter your desktop. http://go.microsoft.com/?linkid=9690331&ocid=PID24727::T:WLMTAGL:ON:WL:en-US:WWL_WIN_evergreen:112009 -- http://mail.python.org/mailman/listinfo/python-list
Re: import from a string
Gabriel Genellina wrote: En Wed, 04 Nov 2009 02:45:23 -0300, iu2 escribió: On Nov 4, 3:10 am, "Gabriel Genellina" wrote: txt = """ def foo(x): print 'x=', x def bar(x): return x + x """ py> namespace = {} py> exec txt in namespace py> namespace.keys() ['__builtins__', 'foo', 'bar'] py> namespace['foo']('hello') x= hello What happens if both global and local dictionaries are supplied: where are the newly created entities created? In the local dict? The amazing thing about Python is how easy is to experiment in the interpreter. Just see it by yourself! Hint: they are created in the same namespace they always are (ignoring nested functions and nonlocal namespaces). But I agree with Gabriel: just try it. n1,n2={},{}; exec Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter callback arguments
Alf P. Steinbach wrote: However, the natural semantics is that various logical properties, such as left, top, right, bottom, width and height, can be varied independently. But they *CANNOT* be varied independently. A rectangle with side parallel to the axes has exactly 4 degress of freedom, not 6. Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: a is b
On Wed, Nov 4, 2009 at 10:37 AM, Sebastian wrote: > I have a question from the pyar list that may have been discussed on this > list, but i didn't catch it. > Have some common objects been somewhat hardcoded into python, like some > integers as shown in the examples below? What other object have been > hardcoded (strings ,etc) and what was the criteria used to select them? Any > hints? See recent thread on the subject: http://www.mail-archive.com/python-list@python.org/msg264434.html Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
a is b
I have a question from the pyar list that may have been discussed on this list, but i didn't catch it. Have some common objects been somewhat hardcoded into python, like some integers as shown in the examples below? What other object have been hardcoded (strings ,etc) and what was the criteria used to select them? Any hints? cheers, - Seb >>> p = 500 >>> q = 500 >>> p == q True >>> p is q False >>> n = 50 >>> m = 50 >>> n == m True >>> n is m True >>> p = 500; q = 500 >>> p is q True >>> for i in range(-20,258): ... a = i ... b = i+0 ... if not (a is b): print i ... -20 -19 -18 -17 -16 -15 -14 -13 -12 -11 -10 -9 -8 -7 -6 257 -- http://mail.python.org/mailman/listinfo/python-list
[ANN] Pyjamas 0.7pre1 Web Widget Set and python-to-javascript Compiler released
Current Release: 0.7~pre1 --- This is a 0.7 prerelease of Pyjamas, to invite users to help test the latest version. The latest svn is regularly but informally tested against the regression tests and the examples, and used in production, but not extensively tested against all known browsers on each commit. Community assistance by running against a wider range of browsers ensures that *you* get a stable release. Pyjamas --- Pyjamas is a port of Google Web Toolkit to Python, and thus enables the development of Rich Media AJAX applications in Python, with no need for special browser plugins. Pyjamas contains a stand-alone python-to-javascript compiler, and also a Widget Set API that looks very similar to Desktop Widget Set APIs (such as PyQT4 or PyGTK2). Pyjamas also contains a Desktop Widget Set version, running as pure python. Using web browser technology provides an alternative to PyQT4 and PyGTK2 that has the advantage of having full support for HTML, CSS, Plugin and other web-related features already built-in. For the windows port, this can save users around 30mb of downloads, as MSHTML is preinstalled as part of IE. For more information, see: http://pyjs.org http://pyjs.org/FAQ.html http://pyjs.org/features.html Known bugs: http://code.google.com/p/pyjamas/issues #290, #227, #228, #230, #304 Changelog Summary - Features and enhancements of the stand-alone 0.7 series javascript compiler include: * the addition of generators (support for yield, by rewriting the function so that it can be re-called and continue from the previous state); * the beginnings of decorators support, and support for properties; * some dramatic performance improvements due to a rewrite of for-loops; * improved support for import syntax (from . import module); * the addition of a built-in AST parser, use of which allows python 2.4 to compile programs with python 2.5 / 2.6 syntax into javascript; * addition of int and long types, and support for operator functions, so that e.g list multiplication by numbers and list addition now work, along with coercion between int, float and long types, and support for floating point exceptions. Overall, this release is a significant "pythonic" upgrade: for full details, see the CHANGELOG. In the User-Interface suite, which is separate from the Pyjamas stand-alone python-to-javascript compiler, the features and enhancements include: * An SVG / VML Canvas Library (a port of GWTCanvas). This has been ported to pure python, and consequently work under Pyjamas-Desktop as well. * A Graphical Chart Library (a port of GChart). This has been ported to pure python, and consequently work under Pyjamas-Desktop as well. For the same speed optimisations present in GChart, GChart for Pyjamas can also use the python port of GWTCanvas. * An internal restructure of Event handling, similar to GWT 1.7, providing Focus, Mouse and Click "Mixin" modules so that developers creating their own widgets have a minimal amount of work to do. This redesign could only take place once Pyjamas supported multiple inheritance (added in 0.6). Pyjamas-Desktop --- Pyjamas runs your application in a Web Browser (as javascript); Pyjamas-Desktop runs exactly the same python application on the Desktop (as python) http://pyjd.org Release 0.6 of Pyjamas incorporated Pyjamas-Desktop directly into the Pyjamas Distribution. To use Pyjamas-Desktop there are three choices, with more planned [MacOSX PyObjC; KDE's PyKHTML]. All ports of Pyjamas-Desktop will require a JSON library to be installed: as there are plenty already, it is counter-productive to write yet another one. Simplejson is recommended. 1) - XULRunner install hulahop and python-xpcom. hulahop is distributed with both Debian and Ubuntu; python-xpcom is part of XULRunner and is also distributed with both Debian and Ubuntu. Other users should investigate the installation instructions for python-xpcom and hulahop for the operating system of their choice on the appropriate web sites. GNU/Linux, FreeBSD and other POSIX systems are strongly advised to use XULRunner for Pyjamas-Desktop: it is the most stable of the PyJD ports. 2) - PyWebKitGtk you will need a patched version of pywebkitgtk: http://code.google.com/p/pywebkitgtk/issues/detail?id=13 you will need a patched version of webkit: http://github.com/lkcl/webkit/16401.master Detailed build instructions are available here: http://wiki.github.com/lkcl/webkit/helping-with-16401master 3) - MSHTML For Windows users, all that's required, other than installing python and Internet Explorer, is one further package: Win32 "comtypes". Win32 "comtypes" can be downloaded here: * http://sourceforge.net/projects/comtypes/ -- http://mail.python.org/mailman/listinfo/python-list
Re: About one class/function per module
Peng Yu wrote: With some automated script, I don't think it is a nightmare to change function names. I can change function names and filenames and their reference with a simple command. I'd think that this is the limitation of current version control system. I don't aware of any version control system that allows easy change of filenames. But why such features can not be implemented in the version control system? So one function per files bring so many problems that you need an automated script to change one function name and complain about version control systems messing up with your file history. Still you insist on stating that this is the solution and that version control system have to adapt. It has already been told to you, and you should really consider the following advice: When everything is wrong except you, it may happen that *your* are somehow wrong. Among all the responses you got, I don't remember any one that would suggest you are in the right way. So what is your conclusion now ? JM -- http://mail.python.org/mailman/listinfo/python-list
How do I install dlls and exes for libtidy and others?
1. I already asked how to setup libxml2 and libxslt, but nobody answered how to... so if anyone knows I'm still having those problems. 2. I now can't get libtidy to work, which requires the same thing: I need to put some dlls and exes somewhere to make it work in Python. Thing is, I don't know where. There are no instructions on this part. Details: I get the following error: import tidy OSError: Couldn't find libtidy, please make sure it is installed. I downloaded these two files (the exe and the dll): http://www.paehl.com/open_source/?HTML_Tidy_for_Windows I copied the exe and dll to the Python directory and Python\Lib and Python\Dlls ... nothing worked I ran this installer (didn't solve the problem): http://int64.org/projects/tidy-binaries So, how can I setup libtidy to work with Python? What do I do with the exe and dll files? Do I need to make additional changes to the system? How do I get other programs like libxml2 and libxslt to work with python -- as in what do I do with the exe and dlls? _ Bing brings you maps, menus, and reviews organized in one place. http://www.bing.com/search?q=restaurants&form=MFESRP&publ=WLHMTAG&crea=TEXT_MFESRP_Local_MapsMenu_Resturants_1x1 -- http://mail.python.org/mailman/listinfo/python-list
Re: Request for comments - concurrent ssh client
mk wrote: Hello everyone, Since I'm not happy with shmux or pssh, I wrote my own "concurrent ssh" program for parallel execution of SSH commands on multiple hosts. Before I release program to the wild, I would like to hear (constructive) comments on what may be wrong with the program and/or how to fix it. (note: the program requires paramiko ssh client module) [snip] if opts.cmd == None and opts.script == None: print "You have to specify one of the following: command to run, using -c command or --cmd command, or script to run, using -s scriptfile or --script scriptfile." print failit = True The normal way to test for None is to use "is None" or "is not None". You do actually do that in some places! [snip] hosts = [ s.strip() for s in hosts if s != '' and s != None and s != '\n' ] hosts = [ s.split() for s in hosts ] [snip] Both '' and None are treated as false by 'if' and 'while'; non-empty strings are treated as true. Also, "s.split()" splits on whitespace and disregards leading and trailing whitespace. The preceding lines can be simplified to: hosts = [ s.split() for s in hosts if s and s != '\n' ] if hosts == []: [snip] Empty lists are also treated as false and non-empty lists as true. The Pythonic way to write the preceding line is: if not hosts: [snip] scriptcomp = script.strip().split() As mentioned earlier, ".strip().split()" can be simplified to just ".split()": scriptcomp = script.split() [snip] try: self.conobj.connect(self.ip, username=self.username, password=self.passw, port=self.port, timeout=opts.timeout, allow_agent=False, look_for_keys = False) loginsuccess = True except: pass [snip] Avoid bare "except" wherever possible. In this case you're ignoring _every_ exception that might occur. VERY BAD IDEA! def execcmds(self): so = se = '' try: si, so, se = self.conobj.exec_command(self.cmd) sol = so.readlines() sel = se.readlines() so = ''.join([ s.replace('\r\n','\n') for s in sol ]) se = ''.join([ s.replace('\r\n','\n') for s in sel ]) [snip] Recent versions of Python will accept generator expressions here, so instead of iterating through a list and creating a new list, which is then passed to '.join', you can let '.join' do the iterating. This can save time and memory: so = ''.join( s.replace('\r\n','\n') for s in sol ) se = ''.join( s.replace('\r\n','\n') for s in sel ) if sol != [] or sel != []: As mentioned earlier, non-empty lists are treated as true: if sol or sel: > def chmodscript(self): # just in case, as sometimes and on some operating systems the execution flags on the script are not always set self.execcmdonscript('chmod 0755 %s' % self.rspath) [snip] You could also use: os.chmod(self.rspath, 0755) def delscript(self): self.execcmdonscript('rm -f %s' % self.rspath) [snip] You could also use: os.remove(self.rspath) for ip, th in queue: if th.finished: th.sshclose() th.join() thfinished.append((ip,th)) queue.remove((ip,th)) Never modify a list (or any container, in fact) while iterating through it. Some containers handle iteration by using an index, but if you remove an item from the container then the index might no longer be correct. Instead, build a new list of the items you want to keep: new_queue = [] for ip, th in queue: if th.finished: th.sshclose() th.join() thfinished.append((ip,th)) else: new_queue.append((ip,th)) queue = new_queue If there are other references to the queue itself then it might be better to replace the contents of the existing queue with those of the new one instead by changing: queue = new_queue to: queue[:] = new_queue -- http://mail.python.org/mailman/listinfo/python-list
Re: unable to compile Python 2.6.4 on AIX using gcc
Thanks Mark. That was indeed very helpful. Here's the current status: === 1. applied changes suggested by Bob Atkins in that thread. 2. setting env variables. export OBJECT_MODE=64 export CC="gcc" export CFLAGS="-maix64 -mcpu=power5" export LDFLAGS="-maix64 -L/usr/lib64 -L/opt/freeware/lib64 -L/opt/freeware/64/lib -L/usr/X11R6/lib -L/opt/freeware/lib" export CPPFLAGS="-I/opt/freeware/include -I/usr/lpp/X11/include/X11" 3. configuring and compiling using configure --with-gcc --enable-shared --prefix=/usr/local/Python-2.6.4 > config_264.log 2>&1 ; make > make_264.log 2>&1 === Both python (executable) and libpython2.6.a build just fine and are in the same directory as configure. However, none of the extensions build. I keep getting libpython2.6 not found error. Here's an example: building 'math' extension gcc -pthread -fno-strict-aliasing -maix64 -mcpu=power5 -DNDEBUG -O3 -Wall -Wstrict-prototypes -I. -I/usr/local/build/python/Python-2.6.4/./Include -I. - IInclude -I./Include -I/opt/freeware/include -I/usr/lpp/X11/include/X11 -I/usr/local/include -I/usr/local/build/python/Python-2.6.4/Include -I/usr/local /build/python/Python-2.6.4 -c /usr/local/build/python/Python-2.6.4/Modules/mathmodule.c -o build/temp.aix-5.3-2.6/usr/local/build/python/Python-2.6.4/Mo dules/mathmodule.o ./Modules/ld_so_aix gcc -pthread -bI:Modules/python.exp -maix64 -L/usr/lib64 -L/opt/freeware/lib64 -L/opt/freeware/64/lib -L/usr/X11R6/lib -L/opt/freewa re/lib -fno-strict-aliasing -maix64 -mcpu=power5 -DNDEBUG -O3 -Wall -Wstrict-prototypes -I. -IInclude -I./Include -I/opt/freeware/include -I/usr/lpp/X11 /include/X11 build/temp.aix-5.3-2.6/usr/local/build/python/Python-2.6.4/Modules/mathmodule.o -L/usr/lib64 -L/opt/freeware/lib64 -L/opt/freeware/64/lib - L/usr/X11R6/lib -L/opt/freeware/lib -L/usr/local/lib -lm -lpython2.6 -o build/lib.aix-5.3-2.6/math.so collect2: library libpython2.6 not found I hacked Makefile to LDFLAGS=<> -L./ I now get: ld: 0711-224 WARNING: Duplicate symbol: PyObject_Size ld: 0711-345 Use the -bloadmap or -bnoquiet option to obtain more information. Fatal Python error: Interpreter not initialized (version mismatch?) make: The signal code from the last command is 6. There are no other versions of python on that machine. I would appreciate any help. Do I need to set the exec_prefix as well? Thanks. Mark Dickinson wrote: On Nov 3, 10:40 pm, chuck wrote: Hello -- I am trying to compile Python 2.6.4 on a Power 5 PC with AIX 5.3. Here are the settings: Take a look at: http://bugs.python.org/issue1628484 Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: regexp help
2009/11/4 Nadav Chernin : > No, I need all files except exe|dll|ocx|py not re.match(r'.*\.(exe|dll|ocx|py)$', the_file_name) Now that wasn't so hard, was it? ;-) -- Cheers, Simon B. -- http://mail.python.org/mailman/listinfo/python-list
RE: regexp help
No, I need all files except exe|dll|ocx|py -Original Message- From: simon.brunn...@gmail.com [mailto:simon.brunn...@gmail.com] On Behalf Of Simon Brunning Sent: ד 04 נובמבר 2009 19:13 To: Nadav Chernin Cc: Python List Subject: Re: regexp help 2009/11/4 Nadav Chernin : > Thanks, but my question is how to write the regex. re.match(r'.*\.(exe|dll|ocx|py)$', the_file_name) works for me. -- Cheers, Simon B. -- http://mail.python.org/mailman/listinfo/python-list
Re: regexp help
Nadav Chernin wrote: > Thanks, but my question is how to write the regex. See http://www.amk.ca/python/howto/regex/ . -- Carsten Haese http://informixdb.sourceforge.net -- http://mail.python.org/mailman/listinfo/python-list
Re: regexp help
2009/11/4 Nadav Chernin : > Thanks, but my question is how to write the regex. re.match(r'.*\.(exe|dll|ocx|py)$', the_file_name) works for me. -- Cheers, Simon B. -- http://mail.python.org/mailman/listinfo/python-list
RE: regexp help
Thanks, but my question is how to write the regex. -Original Message- From: simon.brunn...@gmail.com [mailto:simon.brunn...@gmail.com] On Behalf Of Simon Brunning Sent: ד 04 נובמבר 2009 18:44 To: Nadav Chernin; Python List Subject: Re: regexp help 2009/11/4 Nadav Chernin : > I’m trying to write regexp that find all files that are not with next > extensions: exe|dll|ocx|py, but can’t find any command that make it. http://code.activestate.com/recipes/499305/ should be a good start. Use the re module and your regex instead of fnmatch.filter(), and you should be good to go. -- Cheers, Simon B. -- http://mail.python.org/mailman/listinfo/python-list
Re: Web development with Python 3.1
On Oct 30, 6:23 pm, Dotan Cohen wrote: > The point is that I want to use only _Python_ features, not > Django/Mako/whatever features. Pure python has a builtin templating system -- its called % See http://simonwillison.net/2003/Jul/28/simpleTemplates/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Pyfora, a place for python
>>Daniel Fetchinson writes: > >Probably this thread is going by far too far :) >Ben Finney [ben+pyt...@benfinney.id.au] writes: > Agreed. I was following this discussion first with curiosity and then with increasing disbelief. As a scientist and a programmer, I always considered myself belonging to a group of people who are broad-minded and task-oriented. Being an occasional Python programmer, I subscribed to this list in the hopes of learning from the pros. Most of the time I do. But I also see a disturbing trend of petty bickering, splitting hairs and one-upmanship. I understand there will be occasional language slips and misconstrued jokes but can we please stick to the topic and remain courteous at all times? I am seriously considering unsubscribing from this UL (and maybe joining Pyfora.) -- http://mail.python.org/mailman/listinfo/python-list
Re: regexp help
2009/11/4 Nadav Chernin : > I’m trying to write regexp that find all files that are not with next > extensions: exe|dll|ocx|py, but can’t find any command that make it. http://code.activestate.com/recipes/499305/ should be a good start. Use the re module and your regex instead of fnmatch.filter(), and you should be good to go. -- Cheers, Simon B. -- http://mail.python.org/mailman/listinfo/python-list
Re: Calendar Problem
Victor Subervi wrote: > That's what I initially had. My server, that I am in > the process of leaving, rejected that syntax. What version of Python does that server use? The calendar.Calendar class first appeared in Python 2.5. I suspect your server is using an older version. -- Carsten Haese http://informixdb.sourceforge.net -- http://mail.python.org/mailman/listinfo/python-list
regexp help
Hello all, I'm trying to write regexp that find all files that are not with next extensions: exe|dll|ocx|py, but can't find any command that make it. Please, help me Nadav -- http://mail.python.org/mailman/listinfo/python-list
Re: About one class/function per module
Peng Yu a écrit : On Mon, Nov 2, 2009 at 3:03 AM, Bruno Desthuilliers wrote: Peng Yu a écrit : (snip) I prefer organized my code one class/function per file (i.e per module in python). I know the majority of programmers don't use this approach. Therefore, I'm wondering what its disadvantage is. Hmmm... As far as I'm concerned, you already answered your own question: "the majority of programmers don't use this approach". Now, for a much more practical answer: 1/ having to handle thousands of files for even a simple project is a king-size PITA for the maintainer. 2/ having to load thousands of modules will add quite a lot of overhead when actually running the code. 3/ as a result, the poor guy that will end up maintaining your code will positively hate you. Beware : this poor guy might as well be you. I still don't understand why it is a nightmare to maintain the code. Been here, done that. You obviously don't have enough experience with Python to understand why your "organization" suck. And given your apparent tendency to insist on imposing your own views / preconceptions on the language instead of learning how to use it properly (the canonical "I can write Java in any language" syndrom), it will probably take a long time before you get there - if you ever get there at all. My friendly (really) advice is to stop fighting the langage and start going with the flow. (snip lots of stuff that require neither "one line of code per file" nor fancy scripts) -- http://mail.python.org/mailman/listinfo/python-list
Re: Calendar Problem
Well, you're right. That's what I initially had. My server, that I am in the process of leaving, rejected that syntax. Lovely. Thanks, V On Tue, Nov 3, 2009 at 6:56 PM, Dave Angel wrote: > > > MichaB Klich wrote: > >> Dnia wtorek 03 listopada 2009 o 20:50:10 Victor Subervi napisał(a): >> >> >>> Hi; >>> I have the following: >>> >>> import calendar, datetime >>> >>> myCal =alendar.calendar(6) >>> today =atetime.date.today() >>> day =oday.day >>> mo =oday.month >>> yr =oday.year >>> month =yCal.monthdayscalendar(yr, mo) >>> >>> >>> The last line throws errors no matter how I try and tweak it. The current >>> incarnation complains about myCal being a string. What do? >>> TIA, >>> Victor >>> >>> >>> >> >> You should use >> >> myCal =calendar.Calendar(6) >> >> This creates calendar.Calendar object. >> >> >> > Right. But I wanted to tell the OP what to do with an error like this. > > > You should post the actual error traceback, and tell us what version of > Python you're using: > > Traceback (most recent call last): > File "M:\Programming\Python\sources\dummy\stuff2.py", line 15, in > > month = myCal.monthdayscalendar(yr, mo) > AttributeError: 'str' object has no attribute 'monthdayscalendar' > > > Now, since it says that myCal is a 'str' object, the next thing you should > do is look at the value. I get an actual printable calendar for a year. So > clearly, it's not the Calendar object you were looking for. So you need to > change from the calendar() function to the Calendar() constructor. > > DaveA > > -- http://mail.python.org/mailman/listinfo/python-list
Re: About one class/function per module
Ben Finney a écrit : "Diez B. Roggisch" writes: Don't get me wrong - innovation often comes from scratching ones personal itch. But you seem to be suffering from a rather bad case of neurodermatitis. +1 QOTW Make it +2 QOTW !-) -- http://mail.python.org/mailman/listinfo/python-list
Re: self.__dict__ tricks
Dennis Lee Bieber wrote: > Perfectly valid answer -- there are no fish as there is no > Atlantic sea Steven D'Aprano wrote: > Once in the distant past, there were no fish in what would become the > Atlantic Ocean (not sea) What's with the bias against the word 'sea'? sea –noun 1. the salt waters that cover the greater part of the earth's surface. 2. a division of these waters, of considerable extent, more or less definitely marked off by land boundaries: the North Sea. 3. one of the seven seas; ocean. I'd say the Atlantic qualifies! ;-) ~Ethan~ -- http://mail.python.org/mailman/listinfo/python-list
Re: Calling a method with a variable name
May I be the first to say "Doh!" Problem solved, many thanks to both Carsten and Diez! SM 2009/11/4 Carsten Haese : > Simon Mullis wrote: >> def main(): >> stats_obj = Statistic() >> name = re.sub("[^A-Za-z]", "", sys.argv[0]) >> method = getattr(stats_obj, name, None) >> if callable(method): >> stats_obj.name() #> else: >> print "nope, not sure what you're after" >> --- >> >> However, as I'm sure you've all noticed already, there is no method >> called "name". I would really prefer to get a nudge in the right >> direction before I start evaling variables and so on. > > At the point you marked "HERE", you've already found the method, and you > have determined that it is callable. You just need to call it. Like > this: method(). > > HTH, > > -- > Carsten Haese > http://informixdb.sourceforge.net > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Simon Mullis _ si...@mullis.co.uk -- http://mail.python.org/mailman/listinfo/python-list
Re: how to remove the same words in the paragraph
Can we use inp_paragraph.count(iter_word) to make it simple ? It would work, but the performance will drop off sharply as the length of the paragraph grows, and you'd still have to keep track of which words you already printed so you can correctly print the first one. So you might as well not bother with counting. -tkc -- http://mail.python.org/mailman/listinfo/python-list
Re: Calling a method with a variable name
Simon Mullis wrote: > def main(): > stats_obj = Statistic() > name = re.sub("[^A-Za-z]", "", sys.argv[0]) > method = getattr(stats_obj, name, None) > if callable(method): > stats_obj.name() #else: > print "nope, not sure what you're after" > --- > > However, as I'm sure you've all noticed already, there is no method > called "name". I would really prefer to get a nudge in the right > direction before I start evaling variables and so on. At the point you marked "HERE", you've already found the method, and you have determined that it is callable. You just need to call it. Like this: method(). HTH, -- Carsten Haese http://informixdb.sourceforge.net -- http://mail.python.org/mailman/listinfo/python-list
Re: C api and exception handling
Thanks for your help Carl as usual. Will go with the getattr override method which is cleaner as you explained. Regards, Elias "Carl Banks" wrote in message news:f02c069c-e536-4c6b-b114-2215aa611...@k17g2000yqh.googlegroups.com... On Nov 2, 7:16 am, "lallous" wrote: Hello, Is there is a way, using the Python C api, to install an exception handler that: - will be triggered when an exception occurs - analyze the reason of the exception - correct the situation and try again (something like exception handling on windows where the exception handler can retrieve the registers context->faulting instruction->fix situation if needed->restart execution from the same point) Python has no concept of "retrying", at either the Python or C API level. You might be able to do something Evil in C to get this effect but I don't recommend it, it'll be fundamentally averse to how Python works and future versions are likely to break it. Since I will be asked: "what are you trying to achieve?", this is what I want: func_call("hello") <- no exceptions, good code: function is defined and called properly SomeUndefinedFunction("x", "y") <- undefined function call will trigger an exception. I want my python/C exception handler to inspect the reason of the exception, if it was a call to an undefined function call then redirect the execution to a certain method, say: ExecuteByName("SomeUndefinedFunction", "x", "y") I know if I create a small class with getattr hooked, what I want can be achieved. I'd do it that way. There is ordinarily no way to hook into a plain function call like SomeUndefinedFunction() in Python; if you go around hacking up the interpreter to do that users will be highly confused and surprised. OTOH, hooking into attributes is pretty well-known. When a person sees attribute notation they know there's an opportunity to do weird stuff. When a strange function is called, they will be like, "oh, someone overrode __getattr__". But can it be done otherwise (without using a class and instead relying on exception handlers and correcting the exception)? Just forget about exception handling. If you REALLY insist on doing this, and I highly recommend against it, the best chance you have is to try to hook into the importing process and load a module that uses a custom dictionary object. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: Calling a method with a variable name
Simon Mullis wrote: > Hi All, > > I'm collating a bunch of my utility scripts into one, creating a > single script to which I will symbolic link multiple times. This way > I only have to write code for error checking, output-formatting etc a > single time. > > So, I have > > ~/bin/foo -> ~/Code/python/mother_of_all_utility_scripts.py > ~/bin/bar -> ~/Code/python/mother_of_all_utility_scripts.py > ~/bin/baz -> ~/Code/python/mother_of_all_utility_scripts.py > > I would like "bar" to run the bar method (and so on). > > - > class Statistic() > def __init__(self): > pass > > def foo(self): > return "foo!" > > def bar(self): > return "bar!" > > #... and so on... > > def main(): > stats_obj = Statistic() > name = re.sub("[^A-Za-z]", "", sys.argv[0]) > method = getattr(stats_obj, name, None) > if callable(method): > stats_obj.name() #else: > print "nope, not sure what you're after" > --- > > However, as I'm sure you've all noticed already, there is no method > called "name". I would really prefer to get a nudge in the right > direction before I start evaling variables and so on. > > Does my approach make sense? If not, please give me a hint... You are almost there. Why don't you do if callable(method): method() ? Diez -- http://mail.python.org/mailman/listinfo/python-list
Calling a method with a variable name
Hi All, I'm collating a bunch of my utility scripts into one, creating a single script to which I will symbolic link multiple times. This way I only have to write code for error checking, output-formatting etc a single time. So, I have ~/bin/foo -> ~/Code/python/mother_of_all_utility_scripts.py ~/bin/bar -> ~/Code/python/mother_of_all_utility_scripts.py ~/bin/baz -> ~/Code/python/mother_of_all_utility_scripts.py I would like "bar" to run the bar method (and so on). - class Statistic() def __init__(self): pass def foo(self): return "foo!" def bar(self): return "bar!" #... and so on... def main(): stats_obj = Statistic() name = re.sub("[^A-Za-z]", "", sys.argv[0]) method = getattr(stats_obj, name, None) if callable(method): stats_obj.name() #
Re: Pyfora, a place for python
Daniel Fetchinson wrote: I was referring to this comment by Ben: "Suggestion: Please don't make efforts to fragment the community." This IMHO is hostile, because it presupposes that the mere goal of the OP is fragmenting the community It presupposes nothing of any goal. It describes a predictable result of the OP's efforts, and requests those efforts to cease. So I deny the characterisation of that request as hostile. [mass snippitude] If yes, with the substitution A = Ben and B = OP we get "in order for Ben's request to make sense, Ben has to assume that the OP is making an effort to fragment the community". This assumption on the part of Ben, I think, is hostile, since it assumes that the OP is making an effort to do something not nice. Whether the OP is indeed doing something not nice, is irrelevant. If the OP does do something not nice, the hostility is warranted. If the OP is not doing anything not nice, the hostility is unwarranted. But the fact that Ben was hostile is a fact :) You were doing fine until you brought in the hostility. I must agree with Ben that his comment was not hostile. It was merely a statement. Not an exclamation, no name calling, just a plain request rooted in reality. Okay, before we get to quarks let's see what 'hostile' means :) From Merriam-Webster http://www.learnersdictionary.net/dictionary/hostile : 1 a : of or relating to an enemy b : marked by malevolence c : openly opposed or resisting d (1) : not hospitable (2) : having an intimidating, antagonistic, or offensive nature Now, I think the OP was perceived by Ben as doing something which he thinks is not good. We most probably agree on this. In other words, Ben was opposing the OP's ideas. Yet in other words, Ben was resisting the OP's ideas. And yet in other words, Ben was not hospitable. So perhaps 1a and 1b doesn't quite fit the bill since Ben didn't go as far as call the OP an enemy and he wasn't evil or wished harm to the OP, but 1c and d(1) are certainly correctly describing his behavior and to a lesser extent d(2) as well. AH hahahahahahah. Okay, you got me. However, if we're going to start looking up the exact denotations of words to justify our remarks, surely we should also pay attention to the connotations? In normal, everyday speach the denotations of 'resisting' and 'opposed to' are very different from 'hostile' -- hence such phrases as 'resisting with hostility' and 'hostiley opposed to'. In other words, I'll grant you the win of that hair, but I still would not characterize it as hostile. ;-) ~Ethan~ -- http://mail.python.org/mailman/listinfo/python-list
Re: substituting list comprehensions for map()
Steven D'Aprano writes: > On Tue, 03 Nov 2009 10:22:28 -0500, J Kenneth King wrote: > >> However in this case the procedure by which we derive the value is not >> important or even interesting. It is much more succinct to think of the >> operation as a value and express it accordingly. There's no need to >> clutter the mind with extra name bindings and iteration keywords. They >> won't make our idea any more clear. >> >> dot_product = map(mul, vec1, vec2) >> >> vs >> >> dot_product = [a * b for a, b in zip(vec1, vec2)] >> >> It's very clear, at least to me, what a dot-product is in this case. > > Except it's not. > > The dot product of two vectors returns a scalar, not another vector: > http://en.wikipedia.org/wiki/Dot_product > > So what you want is: > > dot_product = sum(map(mul, vec1, vec2)) Derh. Thanks for the catch. My bad. >> Adding in the loop construct and name bindings doesn't enhance my >> understanding of what a dot-product is. I don't need to see the loop >> construct at all in this case. A dot product is simply the >> multiplication of each element in a vector sequence. > > What you need is to define a function dot-product, and not hijack the > name for a local value. Then the function's implementation is irrelevant > to you: it could use a list comp, or could use map, it could use a for- > loop, a while loop, recursion, or black magic: > > scalar = dot_product(vec1, vec2) Even better. But now I'm afraid the example is running away from the point. So to summarize: 1. Extra name bindings and loop keywords aren't always easier to read. 2. Expressing what we want rather than how we get it is much more clear. and (third dirty argument added) 3. List comprehensions leak their name bindings to the surrounding scope. :p Have a nice day. :) -- http://mail.python.org/mailman/listinfo/python-list
Request for comments - concurrent ssh client
Hello everyone, Since I'm not happy with shmux or pssh, I wrote my own "concurrent ssh" program for parallel execution of SSH commands on multiple hosts. Before I release program to the wild, I would like to hear (constructive) comments on what may be wrong with the program and/or how to fix it. (note: the program requires paramiko ssh client module) #!/usr/local/bin/python -W ignore::DeprecationWarning import time import sys import os import operator import paramiko import threading import subprocess import optparse usage = "Usage: cssh [options] IP1 hostname2 IP3 hostname4 ...\n\n(IPs/hostnames on the commandline are actually optional, they can be specified in the file, see below.)" op = optparse.OptionParser(usage=usage) op.add_option('-c','--cmd',dest='cmd',help="""Command to run. Mutually exclusive with -s.""") op.add_option('-s','--script',dest='script',help="""Script file to run. Mutually exclusive with -c. Script can have its own arguments, specify them in doublequotes, like "script -arg arg".""") op.add_option('-i','--script-dir',dest='scriptdir',help="""The directory where script will be copied and executed. Defaults to /tmp.""") op.add_option('-l','--cleanup',dest='cleanup',action='store_true',help="""Delete the script on remote hosts after executing it.""") op.add_option('-f','--file',dest='file',help="""File with hosts to use, one host per line. Concatenated with list of hosts/IP addresses specified at the end of the commandline. Optionally, in a line of the file you can specify sequence: "Address/Hostname Username Password SSH_Port" separated by spaces (additional parameters can be specified on a subset of lines; where not specified, relevant parameters take default values).""") op.add_option('-d','--dir',dest='dir',help='Directory for storing standard output and standard error of command. If specified, directory will be created, with subdirs named IPs/hostnames and relevant files stored in those subdirs.') op.add_option('-u','--username',dest='username',help="""Username to specify for SSH. Defaults to 'root'.""") op.add_option('-p','--password',dest='password',help="""Password. Password is used first; if connection fails using password, cssh uses SSH key (default or specified).""") op.add_option('-o','--port',dest='port',help="""Default SSH port.""") op.add_option('-k','--key',dest='key',help="""SSH Key file. Defaults to '/root/.ssh/id_dsa'.""") op.add_option('-n','--nokey',dest='nokey',action="store_true", help="""Turns off using SSH key.""") op.add_option('-t','--timeout',dest='timeout',help="""SSH connection timeout. Defaults to 20 seconds.""") op.add_option('-m','--monochromatic',dest='mono',action='store_true',help="""Do not use colors while printing output.""") op.add_option('-r','--maxthreads',dest='maxthreads',help="""Maximum number of threads working concurrently. Default is 100. Exceeding 200 is generally not recommended due to potential exhaustion of address space (each thread can use 10 MB of address space and 32-bit systems have a maximum of 4GB of address space).""") op.add_option('-q','--quiet',dest='quiet',action='store_true',help="""Quiet. Do not print out summaries like IPs for which communication succeeded or failed, etc.""") # add resource file? (opts, args) = op.parse_args() failit = False if opts.cmd == None and opts.script == None: print "You have to specify one of the following: command to run, using -c command or --cmd command, or script to run, using -s scriptfile or --script scriptfile." print failit = True if opts.cmd != None and opts.script != None: print "Options command (-c) and script (-s) are mutually exclusive. Specify either one." print failit = True if opts.cmd == None and opts.script != None: try: scriptpath = opts.script.split()[0] scriptfo = open(scriptpath,'r') scriptfo.close() except IOError: print "Could not open script file %s." % opts.script print failit = True if opts.file == None and args == []: print "You have to specify at least one of the following:" print " - list of IPs/hostnames at the end of the command line (after all options)" print " - list of IPs/hostnames stored in file specified after -f or --file option (like: -f hostnames.txt)" print " You can also specify both sources. In that case IP/hostname lists will be concatenated." print failit = True if opts.password == None and opts.nokey: print "Since using key has been turned off using -n option, you have to specify password using -p password or --password password." print failit = True if opts.key is not None and opts.nokey: print "Options -n and -k keyfile are mutually exclusive. Specify either one." print failit = True if failit: sys.exit(0) if opts.scriptdir == None: opts.scriptdir = '/tmp' if opts.cleanup == None: opts.cleanup = False if opts.key == None: opts.key = '/root
Re: How to test urllib|urllib2-using code?
Hi, kj wrote: > I want to write some tests for code that uses both urllib and > urllib2. Take a look at the discussion under the title "How can one mock/stub python module like urllib" at stackoverflow: http://stackoverflow.com/questions/295438/how-can-one-mock-stub-python-module-like-urllib Lutz -- http://mail.python.org/mailman/listinfo/python-list
Re: unittest & setup
On Tue, Nov 3, 2009 at 11:02 PM, Jonathan Haddad wrote: > I've got a class, in the constructor it loads a CSV file from disc. I'd > like only 1 instance of the class to be instantiated. However, when running > multiple unit tests, multiple instances of the class are created. What's > the best way for me to avoid this? It takes about a few seconds to load the > CSV file. This post that might be worth reading, as it relates to testing with singletons. http://misko.hevery.com/2008/08/17/singletons-are-pathological-liars/ As is this http://misko.hevery.com/code-reviewers-guide/ -- http://mail.python.org/mailman/listinfo/python-list
Re: how to remove the same words in the paragraph
On Wed, Nov 4, 2009 at 4:27 AM, Tim Chase wrote: > kylin wrote: > >> I need to remove the word if it appears in the paragraph twice. could >> some give me some clue or some useful function in the python. >> > > Sounds like homework. To fail your class, use this one: > > >>> p = "one two three four five six seven three four eight" > >>> s = set() > >>> print ' '.join(w for w in p.split() if not (w in s or s.add(w))) > one two three four five six seven eight > > which is absolutely horrible because it mutates the set within the list > comprehension. The passable solution would use a for-loop to iterate over > each word in the paragraph, emitting it if it hadn't already been seen. > Maintain those words in set, so your words know how not to be seen. ("Mr. > Nesbitt, would you please stand up?") > > Can we use inp_paragraph.count(iter_word) to make it simple ? This also assumes your paragraph consists only of words and whitespace. But > since you posted your previous homework-sounding question on stripping out > non-word/whitespace characters, you'll want to look into using a regexp like > "[\w\s]" to clean up the cruft in the paragraph. Neither solution above > preserves non white-space/word characters, for which I'd recommend using a > re.sub() with a callback. Such a callback class might look something like > > >>> class Dedupe: > ... def __init__(self): > ... self.s = set() > ... def __call__(self, m): > ... w = m.group(0) > ... if w in self.s: return '' > ... self.s.add(w) > ... return w > ... > >>> r.sub(Dedupe(), p) > > where I leave the definition of "r" to the student. Also beware of > case-differences for which you might have to normalize. > > You'll also want to use more descriptive variable names than my one-letter > tokens. > > -tkc > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Yours, S.Selvam -- http://mail.python.org/mailman/listinfo/python-list
Re: Cast into custom type
Gabriel, thanks for your reply. See my comments below. On Tue, 03 Nov 2009 21:31:27 -0300, Gabriel Genellina wrote: > En Tue, 03 Nov 2009 09:07:01 -0300, Henning Bredel > escribió: >> On Tue, 03 Nov 2009 10:18:29 +, Steven D'Aprano wrote: > > Then forget about the code you read in that blog post, doesn't apply to > your use case. Well, but it shows how to mount plugins into the application without creating instances instantly. I only use one plugin/module at a time, so I'd like to avoid holding instances which aren't used. If the solution from the blogpost are meant completely different, I'd appreciate if you could point me on some concrete arguments why I shouldn't realize plugin mechanism in that way. BTW: I made it work now (was only a(nother) misinterpretation of how a callable should look like. > Try something like this: [...] > class PluginManager: > def __init__(self, plugin_directory): > self.plugin_directory = plugin_directory self.plugins = [] > > def load_all(self): > for fn in glob(os.path.join(self.plugin_directory, '*.py')): > namespace = {} > execfile(fn, namespace) > for name, obj in namespace.items(): > if (isinstance(obj, type) and > issubclass(obj, Plugin) and > obj is not Plugin): > # obj is a Plugin subclass > cls = obj > print cls.__name__, fn > print cls.__doc__ > print > plugin = cls(self) # call the constructor > self.plugins.append(plugin) [...] Yes, I get your point. But you instantiate all available plugins. I'd like to avoid that. Will a callable like `plugin().initialize' avoid that, or is an instance created immediately when passing this callable? > Plugin is the base class; all plugins must inherit from it. PluginMgr > scans the plugin directory, executes all modules it finds there (be > careful...), and looks for Plugin subclasses. Then creates an instance > of each Plugin subclass. Well, as far I understand it, I'd say that the ActionProvider class from the blogpost is the (nearly) the same as your Plugin base class. All new plugins has to implement the abstract ActionProvider class. The module loading/recognizing is done by my main application. So what would be the main difference here? Thanks for your advice Henning -- http://mail.python.org/mailman/listinfo/python-list
Re: How do I install libxml2 and libxslt?
Kevin Ar18, 02.11.2009 21:44: >> According to the lxml installation instructions you linked=2C >> the windows lxml binary is statically linked and you do not >> need to install the libraries separately. > > The install instructions say" "You need libxml2 and libxslt" and then links= > to where to download the binaries=3B this means I need to install separate= > ly=2C right? If not=2C those are aweful instructions. :) Not being able to scroll down half a page (to the section titled "MS Windows") is not an excuse for blaming the docs. > I can download the binaries=2C but I don't know where or how to install the= > m? Is there any instructions anywhere? Yes, see the short section titled "Installation" at the top of the installation instructions page. Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: elementtree XML() unicode
John Machin, 04.11.2009 02:56: > On Nov 4, 12:14 pm, Kee Nethery wrote: >> The reason I am confused is that getResponse2 is classified as an >> "str" in the Komodo IDE. I want to make sure I don't lose the non- >> ASCII characters coming from the URL. > > str is all about 8-bit bytes. True in Py2.x, false in Py3. What you mean is the "bytes" type, which, sadly, was named "str" in Python 2.x. The problem the OP ran into was due to the fact that Python 2.x handled "ASCII characters in a unicode string" <-> "ASCII encoded byte string" conversion behind the scenes, which lead to all sorts of trouble to loads of people, and was finally discarded in Python 3.0. Stefan -- http://mail.python.org/mailman/listinfo/python-list
How to test urllib|urllib2-using code?
I want to write some tests for code that uses both urllib and urllib2. I would like to be able to run these tests locally. Are there modules to facilitate the writing of such tests (e.g. for setting up a mock web server locally, etc.)? BTW, in the Perl world, one very easy way to learn how to write tests for stuff is to study the test suites that come with every module distribution, and which are usually readily recognizable as a bunch of files of the form t/*.t. (E.g. I'm sure I could find some good answers to my question above if I could look at the test suites for urllib and urllib2, but I can't find them anywhere. In fact, I don't even know what exactly I should be looking for.) Where can I find the equivalent for Python distributions? Thanks! kynn -- http://mail.python.org/mailman/listinfo/python-list
Re: Pyfora, a place for python
> My personal preference would be a link in each sub-paragraph in the official > documentation to a wiki page devoted to that specific aspect of the Python > language. A place were users could augment the documentation by providing > sample code and by expanding out the documentation for those of us who don't > live and breath Python in our sleep. Real Python coders would not click on > the user wiki links and all of us newbies could communicate with each other. > But until a place like that exists, perhaps Pyfora will get us part way > there. > The PHP documentation has this feature: user comments right on the same page (no link to a wiki, though). It's great, most of the best usage practices that I have learned in that language came from the user's comments, not from the official documentation itself. -- Dotan Cohen http://what-is-what.com http://gibberish.co.il -- http://mail.python.org/mailman/listinfo/python-list
python 3.1.1 and --libdir option broken.
I've been trying to install Python 3.1.1 into /usr/lib64 via the configure script option --libdir, but it is ignored and Python 3.1.1 is installed in /usr/lib. Has anyone ran into this problem and solved it? Looking at the Makefile is seems as thought /lib in hard coded into the file. Any suggestions to fix this? Todd :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Pyfora, a place for python
>>> Hi everyone, >>> >>> I am proud to announce the release of Pyfora (http://pyfora.org), an >>> online community of Python enthusiasts to supplement comp.lang.python >>> and #python. While the site is small right now, please feel free to >>> register and post any questions or tips you may have. >> >> I'll feel free to not even bookmark it. I'm sorry, but it is just a bad >> idea. >> >> Your forum cannot (and should not) compete either with Python's official >> newsgroup, IRC channel and mailing list or with popular, well- made and >> well-frequented general programming sites like stackoverflow.com. > > Are you saying that now that comp.lang.python and stackoverflow exists, > there no more room in the world for any more Python forums? Exactly. > I think that's terrible. Exactly. > Saketh, would you care to give a brief explanation for sets your forum > apart from the existing Python forums, and why people should choose to > spend time there instead of (or as well as) the existing forums? What > advantages does it have? Yes, this is about the right kind of response I think everybody deserves who puts energy/enthusiasm/effort/time into putting together a python-related forum. Cheers, Daniel >> It would be the Internet equivalent of looking for a poker tournament in >> a desert valley instead of driving half an hour less and going to Las >> Vegas: there are no incentives to choose your forum, except perhaps for >> isolationists who value being a big fish in a small pond over being part >> of a community. > > (Funny you mention Las Vegas -- it started off as a tiny little town in > the middle of the desert too.) > > How about avoiding the noise and obtrusive advertising and bright lights > of Las Vegas, the fakery, the "showmanship", the horrible fake pyramid > and has-been celebrities, the crowds, the tackiness, the high prices, the > bright lights that never turn off (Las Vegas is the brightest city on > Earth)... if you're interested in poker without all the mayonnaise, maybe > that poker tournament away from the tourists is exactly what you need. > > Personally, if I wanted to gamble, the last place I would go is any house > which had gold-plated taps in the bathrooms. That tells me the house's > percentage is *way* too high. -- Psss, psss, put it down! - http://www.cafepress.com/putitdown -- http://mail.python.org/mailman/listinfo/python-list
Re: Pyfora, a place for python
I was referring to this comment by Ben: "Suggestion: Please don't make efforts to fragment the community." This IMHO is hostile, because it presupposes that the mere goal of the OP is fragmenting the community >>> >>>It presupposes nothing of any goal. It describes a predictable result of >>>the OP's efforts, and requests those efforts to cease. >>> >>>So I deny the characterisation of that request as hostile. >> > > [mass snippitude] > >> If yes, with the substitution A = Ben and B = OP we get "in order for >> Ben's request to make sense, Ben has to assume that the OP is making >> an effort to fragment the community". This assumption on the part of >> Ben, I think, is hostile, since it assumes that the OP is making an >> effort to do something not nice. Whether the OP is indeed doing >> something not nice, is irrelevant. If the OP does do something not >> nice, the hostility is warranted. If the OP is not doing anything not >> nice, the hostility is unwarranted. But the fact that Ben was hostile >> is a fact :) > > You were doing fine until you brought in the hostility. I must agree > with Ben that his comment was not hostile. It was merely a statement. > Not an exclamation, no name calling, just a plain request rooted in reality. Okay, before we get to quarks let's see what 'hostile' means :) >From Merriam-Webster http://www.learnersdictionary.net/dictionary/hostile : 1 a : of or relating to an enemy b : marked by malevolence c : openly opposed or resisting d (1) : not hospitable (2) : having an intimidating, antagonistic, or offensive nature Now, I think the OP was perceived by Ben as doing something which he thinks is not good. We most probably agree on this. In other words, Ben was opposing the OP's ideas. Yet in other words, Ben was resisting the OP's ideas. And yet in other words, Ben was not hospitable. So perhaps 1a and 1b doesn't quite fit the bill since Ben didn't go as far as call the OP an enemy and he wasn't evil or wished harm to the OP, but 1c and d(1) are certainly correctly describing his behavior and to a lesser extent d(2) as well. And the quarks.. :) Cheers, Daniel > And that's a fact. ;-) > > Shall we now discuss the nature of the space/time continuum and the > exact reality of quarks? -- Psss, psss, put it down! - http://www.cafepress.com/putitdown -- http://mail.python.org/mailman/listinfo/python-list
Re: Handling large datastore search
(This reply was offline, but I forwarded parts so that others with Google App Engine experience might jump in) Ahmed Barakat wrote: but I was trying to make use of everything provided by App engine. On Wed, Nov 4, 2009 at 1:27 AM, Dave Angel wrote: Ahmed Barakat wrote: In case I have a huge datastore (1 entries, each entry has like 6 properties), what is the best way to handle the search within such a huge datastore, and what if I want to make a generic search, for example you write a word and i use it to search within all properties I have for all entries? Is the conversion to XML a good solution, or it is not? sorry for being new to web development, and python. Thanks in advance. I don't see anything about your query which is specific to web development, and there's no need to be apologetic for being new anyway. One person's "huge" is another person's "pretty large." I'd say 1 items is pretty small if you're working on the desktop, as you can readily hold all the data in "memory." I edit text files bigger than that. But I'll assume your data really is huge, or will grow to be huge, or is an environment which treats it as huge. When you're parsing large amounts of data, there are always tradeoffs between performance and other characteristics, usually size and complexity. If you have lots of data, you're probably best off by using a standard code system -- a real database. The developers of such things have decades of experience in making certain things fast, reliable, and self-consistent. But considering only speed here, I have to point out that you have to understand databases, and your particular model of database, pretty well to really benefit from all the performance tricks in there. Keeping it abstract, you specify what parts of the data you care about fast random access to. If you want fast search access to "all" of it, your database will generally be huge, and very slow to updates. And the best way to avoid that is to pick a database mechanism that best fits your search mechanism. I hate to think how many man-centuries Google has dedicated to getting fast random word access to its *enormous* database. I'm sure they did not build on a standard relational model. If you plan to do it yourself, I'd say the last thing you want to do is use XML. XML may be convenient way to store self-describing data, but it's not quick to parse large amounts of it. Instead, store the raw data in text form, with separate index files describing what is where. Anything that's indexed will be found rapidly, while anything that isn't will require search of the raw data. There are algorithms for searching raw data that are faster than scanning every byte, but a relevant index will almost always be faster. DaveA Clearly, you left a few things out of your original query. Now that you mention App Engine, I'm guessing you meant Google's Datastore and that this whole query is about building a Google app. So many of my comments don't apply, because I was talking about a desktop environment, using (or not using) a traditional (relational) database. I've never used Google's AppEngine, and never done a database web-app. So I'm the wrong person to give more than general advice. Google's Datastore is apparently both more and less powerful than a relational database, and web apps have very different tradeoffs. So you need to respecify the problem, giviing the full requirements first, and maybe somebody with more relevant experience will then respond. Meanwhile, try the following links, and see if any of them help. http://code.google.com/appengine/docs/ http://code.google.com/appengine/docs/whatisgoogleappengine.html http://code.google.com/appengine/docs/datastore/ http://code.google.com/appengine/docs/python/gettingstarted/usingdatastore.html http://snarfed.org/space/datastore_talk.html http://video.google.com/videosearch?q=app+engine+data+store&oe=utf-8&rls=org.mozilla:en-US:official&client=firefox-a&um=1&ie=UTF-8&ei=uGjxSrX-HcPp8Qbb2uWACQ&sa=X&oi=video_result_group&ct=title&resnum=11&ved=0CDIQqwQwCg DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: problem in installing wxwidgets for python..
Hi, 2009/11/4 Jebagnana Das : > Hello friends, > I've tried to install wxwidgets in my mandriva 2009 spring > for GUI interaction with python. In the installation instruction it said > that i need gtk+ library. So i downloaded GTK+. When i configured GTK+ i got > the message You probably want wxpython binding instead - http://www.wxpython.org/ Use binaries provided by Mandriva's package manager where possible unless you _really_ want to do a source installation. > checking for BASE_DEPENDENCIES... configure: error: Package requirements > (glib-2.0 >= 2.21.3atk >= 1.13.0pango >= 1.20cairo >= 1.6) were > not met: > > > Requested 'glib-2.0 >= 2.21.3' but version of GLib is 2.20.1 > > Consider adjusting the PKG_CONFIG_PATH environment variable if you > installed software in a non-standard prefix. $ export PKG_CONFIG_PATH=/usr/lib/pkgconfig:/usr/local/lib/pkgconfig (considering that your local installs went to those directories. Try replacing those directories accordingly for glib, atk, pango and cairo). The files you're after is a ".pc" (pkg-config need them) file. A quick find will tell you where it is if it is installed. Run configure script again. > Alternatively, you may set the environment variables > BASE_DEPENDENCIES_CFLAGS > > and BASE_DEPENDENCIES_LIBS to avoid the need to call pkg-config. > See the pkg-config man page for more details. > > Then i downloaded glib2.21.3,atk 1.13.0,pango 1.20 and cairo 1.6. I > installed all the packages using the following commands. [...] > tar xvzf filename.tar.gz > cd folder > ./configure > > make > make install Yep. Check where it installed them one by one. In short, you need access to a ".pc" file that they provide. If not, write one yourself. > I've not specified anf options like --prefix and i installed in the folder > itself. man pkg-config for further info. > when i tried to install gtk+ after installing all this it showed the same > error. What should i do to install wxwidgets? Plz. reply as soon as > possible.. Coz. i've to finish my proj. quickly.. Thanks and regards... See above. -- Regards, Ishwor Gurung -- http://mail.python.org/mailman/listinfo/python-list
Re: substituting list comprehensions for map()
Steven D'Aprano writes: > On Tue, 03 Nov 2009 22:43:45 -0600, Robert Kern wrote: > > from numpy import dot > > > > scalar = dot(vec1, vec2) > > Why would I want to use an already existing library that is fast, > well- written and well-supported, when I can toss together a nasty > kludge myself? Because using that library will ensure you can't migrate to Python 3 any time soon? *rimshot* -- \ “… a Microsoft Certified System Engineer is to information | `\ technology as a McDonalds Certified Food Specialist is to the | _o__) culinary arts.” —Michael Bacarella | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: substituting list comprehensions for map()
Steven D'Aprano wrote: On Tue, 03 Nov 2009 22:43:45 -0600, Robert Kern wrote: Or use the appropriate libraries: from numpy import dot scalar = dot(vec1, vec2) Why would I want to use an already existing library that is fast, well- written and well-supported, when I can toss together a nasty kludge myself? because you want to perform a dot-product on strings? >>> dot_product(['a', 'b', 'c'], [2,3,4]) 'aabbb' [grins, ducks and scampers away after the sum-shouldn't-special-case-strings-with-an-error thread] -tkc -- http://mail.python.org/mailman/listinfo/python-list
problem in installing wxwidgets for python..
Hello friends, I've tried to install wxwidgets in my mandriva 2009 spring for GUI interaction with python. In the installation instruction it said that i need gtk+ library. So i downloaded GTK+. When i configured GTK+ i got the message checking for BASE_DEPENDENCIES... configure: error: Package requirements (glib-2.0 >= 2.21.3atk >= 1.13.0pango >= 1.20 cairo >= 1.6) were not met: Requested 'glib-2.0 >= 2.21.3' but version of GLib is 2.20.1 Consider adjusting the PKG_CONFIG_PATH environment variable if you installed software in a non-standard prefix. Alternatively, you may set the environment variables BASE_DEPENDENCIES_CFLAGS and BASE_DEPENDENCIES_LIBS to avoid the need to call pkg-config. See the pkg-config man page for more details. Then i downloaded glib2.21.3,atk 1.13.0,pango 1.20 and cairo 1.6. I installed all the packages using the following commands. tar xvzf filename.tar.gz cd folder ./configure make make install I've not specified anf options like --prefix and i installed in the folder itself. when i tried to install gtk+ after installing all this it showed the same error. What should i do to install wxwidgets? Plz. reply as soon as possible.. Coz. i've to finish my proj. quickly.. Thanks and regards... -- http://mail.python.org/mailman/listinfo/python-list
Re: comparing alternatives to py2exe
iu2 wrote: Another thing that I think is of interest is whether the application support modifying the version and description of the exe (that is, on Windows, when you right-click on an application and choose 'properties' you view the version number and description of the application, it is a resource inside the exe). I think py2exe supports it. Pyinstaller supports this. Vesa -- http://mail.python.org/mailman/listinfo/python-list
Re: unable to compile Python 2.6.4 on AIX using gcc
On Nov 3, 10:40 pm, chuck wrote: > Hello -- I am trying to compile Python 2.6.4 on a Power 5 PC with AIX > 5.3. Here are the settings: > > export OBJECT_MODE=64 > export AR="ar -X64" > export MAKE=/usr/bin/gmake > export CC="gcc" > export CFLAGS="-maix64 -O2 -g -mcpu=power5" > export LDFLAGS="-L/usr/lib64 -L/opt/freeware/lib64 > -L/opt/freeware/64/lib -L/usr/X11R6/lib -L/opt/freeware/lib" > export CPPFLAGS="-I/opt/freeware/include -I/usr/lpp/X11/include/X11" > ../Python-2.6.4/configure --with-gcc --disable-ipv6 > --prefix=/usr/local/Python-2.6.4 > config_264.log 2>&1 > make > make_264.log 2>&1 > > make fails very early with the following error > > === > > gcc -pthread -c -fno-strict-aliasing -DNDEBUG -O3 -Wall > -Wstrict-prototypes -I. -IInclude -I../Python-2.6.4/Includ > e -I/opt/freeware/include -I/usr/lpp/X11/include/X11 -DPy_BUILD_CORE -o > Modules/python.o ../Python-2.6.4/Modules/python.c > In file included from ../Python-2.6.4/Include/Python.h:58, > from ../Python-2.6.4/Modules/python.c:3: > ../Python-2.6.4/Include/pyport.h:685:2: error: #error "LONG_BIT > definition appears wrong for platform (bad gcc/glibc config > ?)." > make: The error code from the last command is 1. > === > > I would appreciate any help. Thanks. Take a look at: http://bugs.python.org/issue1628484 Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: using csv dictreader in python
On Wed, Nov 04, 2009 at 01:25:16PM +0530, Siva Subramanian wrote: > This only gets me the following output > > {'FieldName1': '4', 'FieldName2': '0.00', 'FieldName3': > '4001433', 'FieldName4': '759'} > > 1. How do i access the 4, 0.00, ... the values ? >>> a= {'FieldName1': '4', 'FieldName2': '0.00', 'FieldName3': '4001433', >>> 'FieldName4': '759'} >>> a {'FieldName4': '759', 'FieldName1': '4', 'FieldName3': '4001433', 'FieldName2': '0.00'} >>> a['FieldName3'] '4001433' > 2. How do i compare it with another csv file ? If you have the values in one file, get the values in the other one and then compare. I am not sure I understand what is the problem here. Regards Johann -- Johann Spies Telefoon: 021-808 4599 Informasietegnologie, Universiteit van Stellenbosch "Train up a child in the way he should go: and when he is old, he will not depart from it." Proverbs 22:6 -- http://mail.python.org/mailman/listinfo/python-list
restricted mode???
A reportlab user running via mod_python+django (Python 2.5.2 and mod_python 3.3.1) reports a strange intermittent error involving failure to read files which are known to be present. After some debugging efforts we got this clearer error message File "/usr/lib/python2.5/site-packages/reportlab/lib/utils.py", line 810, in dump f = open(self.fn,'wb') IOError: file() constructor not accessible in restricted mode this is not the original error, but part of our efforts to debug; however, the original error was during an attempt to read a file so presumably open was not available there. Googling the error indicates something to do with restricted environments/mod_python+threads. I thought that restricted mode died ages ago. Any ideas what could be causing this? -- Robin Becker -- http://mail.python.org/mailman/listinfo/python-list
Re: import bug
On Oct 31, 5:12 pm, kj wrote: > I give up: what's the trick? (Of course, renaming ham/re.py is > hardly "the trick." It's rather Procrustes' Bed.) I realize that this is probably not the answer you were looking for, but: $ python -m ham.spam or ==> ./spammain.py <== import ham.spam $ python spammain.py I've found it easier to not fight the module/package system but work with it. But yes, I also think the problem you're seeing is a wart or bug even. Best regards Mark Leander -- http://mail.python.org/mailman/listinfo/python-list
Re: python compare and process a csv file
Chris Rebert wrote: > On Tue, Nov 3, 2009 at 7:43 AM, Siva Subramanian > wrote: >> Hello all, >> >> I am new on this list and computer programming >> >> I have two distinct statistical files (both csv) >> >> 1. Report_2_5 – this is a report dump containing over a 10 million >> records and is different every day >> >> 2. Customer_id dump – this is a daily dump of customers who have >> made payments. This is generally a million record >> >> I need to extract past history depending on customers who make regular >> payments >> >> For example, >> >> Report_2_5 >> >> Customer ID, Plan_NO, stat1, vol2, amount3 >> 2134, Ins1, 1, 2, 10 >> 2112, Ins3, 3, 2, 10 >> 2121, Ins3, 3, 2, 10 >> 2145, Ins2, 15000, 1, 5 >> 2245, Ins2, 15000, 1, 5 >> 0987, Ins1, 1, 2, 10 >> >> 4546, Ins1, 10020, 21000, 10 >> >> 6757, Ins1, 10200, 22000, 10 >> … >> >> customer_id dump >> >> >> 0987 >> >> 4546 >> >> 6757 >> >> 2134 >> >> I need to process the Report_2_5 and extract the following output >> >> Stat1: 40220 >> Vol2 : 83000 >> Amount3 : 40 >> >> I am new to programming and I have been extracting this data using MS – >> Access and I badly need a better solution. > > Have you considered using a proper SQL database? (See > http://en.wikipedia.org/wiki/SQL ; MySQL is one example: > http://en.wikipedia.org/wiki/MySQL) > Mucking around with CSV files like this is basically doing the work of > some simple SQL queries, only in an ad-hoc, inefficient manner. (MS > Access is essentially a non-industrial-strength SQL for > non-programmers.) Industrial strength or not, Access should be capable of solving the OP's problem. So it would be interesting what's so bad about it in this case. Anyway, here's a database-free python solution: import csv REPORT = "report.csv" CUSTOMERS = "customers.csv" with open(CUSTOMERS) as instream: next(instream) # skip header # put customer ids into a set for fast lookup customer_ids = set(line.strip() for line in instream) with open(REPORT) as instream: rows = csv.reader(instream) # find columns headers = [column.strip() for column in rows.next()] customer_column = headers.index("Customer ID") sum_over_columns = [headers.index(s) for s in "stat1 vol2 amount3".split()] # initialize totals sigma = [0] * len(headers) # calculate totals for row in rows: if row[customer_column] in customer_ids: for index in sum_over_columns: sigma[index] += int(row[index]) # print totals for index in sum_over_columns: print "%-10s %10d" % (headers[index] + ":", sigma[index]) The limiting factor for this approach is the customer_ids set which at some point may no longer fit into memory. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter callback arguments
* Gabriel Genellina: En Wed, 04 Nov 2009 04:50:42 -0300, Alf P. Steinbach escribió: * Gabriel Genellina: I don't understand either. R1 and R2 have *different* semantics. Assume that they have the very exact same semantics -- like two TV sets that look the same and work the same except when you open 'em up and poke around in there, oh holy cow, in this one there's stuff that isn't in the other. They don't behave the same. Assume that they do -- except when you go poking into the innards. And the problem is...? That the internal details are different? Who cares? (I'm lost now.) It's a common Usenet phenomenon: the warping thread. Context is lost. It is available by going back up-thread but at the cost of some work. :-) Cheers & hth., - Alf -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter callback arguments
En Wed, 04 Nov 2009 04:50:42 -0300, Alf P. Steinbach escribió: * Gabriel Genellina: I don't understand either. R1 and R2 have *different* semantics. Assume that they have the very exact same semantics -- like two TV sets that look the same and work the same except when you open 'em up and poke around in there, oh holy cow, in this one there's stuff that isn't in the other. They don't behave the same. Assume that they do -- except when you go poking into the innards. And the problem is...? That the internal details are different? Who cares? (I'm lost now.) -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: python compare and process a csv file
On Tue, Nov 3, 2009 at 7:43 AM, Siva Subramanian wrote: > Hello all, > > I am new on this list and computer programming > > I have two distinct statistical files (both csv) > > 1. Report_2_5 – this is a report dump containing over a 10 million > records and is different every day > > 2. Customer_id dump – this is a daily dump of customers who have made > payments. This is generally a million record > > I need to extract past history depending on customers who make regular > payments > > For example, > > Report_2_5 > > Customer ID, Plan_NO, stat1, vol2, amount3 > 2134, Ins1, 1, 2, 10 > 2112, Ins3, 3, 2, 10 > 2121, Ins3, 3, 2, 10 > 2145, Ins2, 15000, 1, 5 > 2245, Ins2, 15000, 1, 5 > 0987, Ins1, 1, 2, 10 > > 4546, Ins1, 10020, 21000, 10 > > 6757, Ins1, 10200, 22000, 10 > … > > customer_id dump > > > 0987 > > 4546 > > 6757 > > 2134 > > I need to process the Report_2_5 and extract the following output > > Stat1: 40220 > Vol2 : 83000 > Amount3 : 40 > > I am new to programming and I have been extracting this data using MS – > Access and I badly need a better solution. Have you considered using a proper SQL database? (See http://en.wikipedia.org/wiki/SQL ; MySQL is one example: http://en.wikipedia.org/wiki/MySQL) Mucking around with CSV files like this is basically doing the work of some simple SQL queries, only in an ad-hoc, inefficient manner. (MS Access is essentially a non-industrial-strength SQL for non-programmers.) Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: How to print zero-padded floating point numbers in python 2.6.1
On Wed, Nov 4, 2009 at 12:04 AM, Lorenzo Di Gregorio wrote: > Hello, > > I thought that I could zero-pad a floating point number in 'print' by > inserting a zero after '%', but this does not work. > > I get: > > print '%2.2F' % 3.5 > 3.50 > print '%02.2F' % 3.5 > 3.50 > > How can I get print (in a simple way) to print 03.50? >>> print ("%.2f" % 3.5).zfill(5) 03.50 >>> print ("%5.2f" % 3.5).replace(' ','0') 03.50 Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Win XP: How to hide command window for sub processes?
klausfpga schrieb: > On Oct 29, 11:25 am, Rüdiger Ranft <_r...@web.de> wrote: > Thanks Ruediger, > > I'll try that immediately tomorrow, when working again on a windows > host. > > Good to know, that the Python API supports this. > though this feature was not that easy to be found in the doc. Well, getting the point from subproces.py was easy. Finding the documentation about STARTUPINFO in the MSDN was not. I better stop here before this post turns into a rant about Mircosofts use of javascript. bye Rudi -- http://mail.python.org/mailman/listinfo/python-list
Re: How to print zero-padded floating point numbers in python 2.6.1
Lorenzo Di Gregorio schrieb: > print '%2.2F' % 3.5 > 3.50 > print '%02.2F' % 3.5 > 3.50 > > How can I get print (in a simple way) to print 03.50? print '%05.2F' % 3.5 Lutz -- http://mail.python.org/mailman/listinfo/python-list
Re: Pyfora, a place for python
On Tue, 03 Nov 2009 02:11:59 -0800, Lorenzo Gatti wrote: > On Nov 1, 8:06 am, Saketh wrote: >> Hi everyone, >> >> I am proud to announce the release of Pyfora (http://pyfora.org), an >> online community of Python enthusiasts to supplement comp.lang.python >> and #python. While the site is small right now, please feel free to >> register and post any questions or tips you may have. > > I'll feel free to not even bookmark it. I'm sorry, but it is just a bad > idea. > > Your forum cannot (and should not) compete either with Python's official > newsgroup, IRC channel and mailing list or with popular, well- made and > well-frequented general programming sites like stackoverflow.com. Are you saying that now that comp.lang.python and stackoverflow exists, there no more room in the world for any more Python forums? I think that's terrible. Saketh, would you care to give a brief explanation for sets your forum apart from the existing Python forums, and why people should choose to spend time there instead of (or as well as) the existing forums? What advantages does it have? > It would be the Internet equivalent of looking for a poker tournament in > a desert valley instead of driving half an hour less and going to Las > Vegas: there are no incentives to choose your forum, except perhaps for > isolationists who value being a big fish in a small pond over being part > of a community. (Funny you mention Las Vegas -- it started off as a tiny little town in the middle of the desert too.) How about avoiding the noise and obtrusive advertising and bright lights of Las Vegas, the fakery, the "showmanship", the horrible fake pyramid and has-been celebrities, the crowds, the tackiness, the high prices, the bright lights that never turn off (Las Vegas is the brightest city on Earth)... if you're interested in poker without all the mayonnaise, maybe that poker tournament away from the tourists is exactly what you need. Personally, if I wanted to gamble, the last place I would go is any house which had gold-plated taps in the bathrooms. That tells me the house's percentage is *way* too high. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: self.__dict__ tricks
Simon Brunning writes: > 2009/11/1 Steven D'Aprano : > > > > The only stupid question is the one you are afraid to ask. > > I was once asked, and I quote exactly, "are there any fish in the > Atlantic sea?" > > That's pretty stupid. ;-) Not at all. The person asking the question might be ignorant of the facts about fishing, or the Atlantic, or marine ecosystems in that region, etc., in which case the question is smart and wise and to the point. Especially compared with the alternative: not asking the question perpetuates the ignorance. -- \ “If I had known what it would be like to have it all... I might | `\ have been willing to settle for less.” —Jane Wagner, via Lily | _o__) Tomlin | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Pyfora, a place for python
Daniel Fetchinson writes: > Probably this thread is going by far too far :) Agreed. -- \德不孤、必有鄰。 (The virtuous are not abandoned, they shall | `\ surely have neighbours.) —孔夫子 Confucius, 551 BCE – 479 BCE | _o__) | Ben Finney -- http://mail.python.org/mailman/listinfo/python-list
Re: Pyfora, a place for python
On Nov 3, 11:37 am, Steven D'Aprano wrote: > On Tue, 03 Nov 2009 02:11:59 -0800, Lorenzo Gatti wrote: [...] > Are you saying that now that comp.lang.python and stackoverflow exists, > there no more room in the world for any more Python forums? > > I think that's terrible. Although there is a high barrier to entry for general Python forums, it is not a problem because the door is always open for specialized forums that become the natural "home" of some group or thought leader or of some special interest, for example the forum of a new software product or of the fans of an important blog. Unfortunately, pyfora.org has neither a distinct crowd behind it nor an unique topic, and thus no niche to fill; it can only contribute fragmentation, which is unfortunate because Saketh seems enthusiastic. What in some fields (e.g. warez forums or art boards) would be healthy redundancy and competition between sites and forums becomes pure fragmentation if the only effect of multiple forums is to separate the same questions and opinions that would be posted elsewhere from potential readers and answerers. Reasonable people know this and post their requests for help and discussions either in the same appropriate places as everyone else or in random places they know and like; one needs serious personal issues to abandon popular forums for obscure ones. > Saketh, would you care to give a brief explanation for sets your forum > apart from the existing Python forums, and why people should choose to > spend time there instead of (or as well as) the existing forums? What > advantages does it have? That's the point, I couldn't put it better. > > It would be the Internet equivalent of looking for a poker tournament in > > a desert valley instead of driving half an hour less and going to Las > > Vegas: > > [...] > How about avoiding the noise and obtrusive advertising and bright lights > of Las Vegas, the fakery, the "showmanship", > [...] > if you're interested in poker without all the mayonnaise, maybe > that poker tournament away from the tourists is exactly what you need. I didn't explain my similitude clearly: I was comparing the fitness for purpose of going to Las Vegas with a plan to gamble with the absurdity of stopping, say, at an isolated gas station in the hope of finding a poker tournament there. If you are hinting that popular newsgroups and forums might be so full of fakery, showmanship, mayonnaise, etc. to deserve secession, it's another topic. Regards, Lorenzo Gatti -- http://mail.python.org/mailman/listinfo/python-list
python compare and process a csv file
Hello all, I am new on this list and computer programming I have two distinct statistical files (both csv) 1. Report_2_5 – this is a report dump containing over a 10 million records and is different every day 2. Customer_id dump – this is a daily dump of customers who have made payments. This is generally a million record I need to extract past history depending on customers who make regular payments For example, Report_2_5 Customer ID, Plan_NO, stat1, vol2, amount3 2134, Ins1, 1, 2, 10 2112, Ins3, 3, 2, 10 2121, Ins3, 3, 2, 10 2145, Ins2, 15000, 1, 5 2245, Ins2, 15000, 1, 5 0987, Ins1, 1, 2, 10 4546, Ins1, 10020, 21000, 10 6757, Ins1, 10200, 22000, 10 … customer_id dump 0987 4546 6757 2134 I need to process the Report_2_5 and extract the following output Stat1: 40220 Vol2 : 83000 Amount3 : 40 I am new to programming and I have been extracting this data using MS – Access and I badly need a better solution. Will really appreciate any sample code in python. Thanks in advance Siva -- http://mail.python.org/mailman/listinfo/python-list
Re: comparing alternatives to py2exe
Maxim Khitrov schrieb: > 1. I don't think cx_freeze supports single exe. I haven't even been > able to get it to append the generated library.zip file to the > executable using documented options. Other things like .pyd files > always seem to be separate. At the same time, singe executables > generated by py2exe do not always work. I have a program that works > fine on Windows XP, Vista, and 7 if it is built under XP. However, if > I build the exact same program under Windows 7, it no longer works on > Vista or XP. I'm sure it has something to do with SxS or other dll > issues. I had similar issues with under Vista generated programs not running under 2K (unfortunately I have to support it). This behavior came from the .dll dependency tracking of py2exe, which included a OS .dll into the dist output. These are the steps I toke to find the offending .dll * generated a "flat" directory (the .dll's not packed into library.zip) with options = { [...], 'bundle_files': 3 } * extracted the not loadable extension from library.zip * examined the dependencies of this module with Microsoft's "Dependency Walker" (you can find it somewhere in the MSDN) * added the superfluous .dll to the options = { [...], 'dll_excludes': ['offending.dll'] } parameter HTH Rudi -- http://mail.python.org/mailman/listinfo/python-list
How to print zero-padded floating point numbers in python 2.6.1
Hello, I thought that I could zero-pad a floating point number in 'print' by inserting a zero after '%', but this does not work. I get: print '%2.2F' % 3.5 3.50 print '%02.2F' % 3.5 3.50 How can I get print (in a simple way) to print 03.50? Best Regards, Lorenzo -- http://mail.python.org/mailman/listinfo/python-list
using csv dictreader in python
Hello all, I am now trying to access the csv file using dictreader. import csv r25 = csv.DictReader(open('Report_ 25', 'rb'), delimiter=',') rownum = 1 for row in r25: # Save header row. if rownum == 0: header = row else: colnum = 0 for col in row: This only gets me the following output {'FieldName1': '4', 'FieldName2': '0.00', 'FieldName3': '4001433', 'FieldName4': '759'} 1. How do i access the 4, 0.00, ... the values ? 2. How do i compare it with another csv file ? Thanks in advance Siva -- http://mail.python.org/mailman/listinfo/python-list