PyGTK Introduction @ Toronto Area Python User's Group Meeting next Tuesday
Our topic for the next PyGTA meeting is the PyGTK binding to the Open Source GTK+ GUI library. Myles Braithwaite, a local developer and consultant will be presenting an introduction to the library including how to get started programming with it. Myles has used GTK, among other things, to develop a pair of games for the OLPC laptop. GTK is reasonably portable Free software that has a number of GUI-layout tools, with the Glade system being the most well-known among them. We'll be meeting at our regular venue, Linux Caffe, which is open until 11pm for the summer, affording us a much more relaxed pace for our meetings. We'll plan to start the presentation for 7:15pm, with people encouraged to gather at 7:00 to chat and socialise. Linux Caffe is at the corner of Grace and Harbord streets, 1 block South of Christie station. Free WiFi is available, as are snacks and sandwiches, ice cream, smoothies, coffee, tea and the like. Details on how to get to Linux Caffe are available on the PyGTA next-meeting page: http://www.pygta.org/ Have fun all, Mike -- Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
bbfreeze 0.95.1
Hi all, I've just uploaded bbfreeze 0.95.1 to python's cheeseshop. bbfreeze creates standalone executables from python scripts. It's similar in functionality to py2exe or cx_Freeze. This release fixes some problems with egg files and with some of the recipes. *NEW* support for egg files: bbfreeze scans zipped egg files and now includes whole egg files/directories in the distribution. Programs using setuptools' pkg_resources module will now work. It offers the following features: easy installation bbfreeze can be installed with setuptools' easy_install command. zip/egg file import tracking bbfreeze tracks imports from zip files. multiple script freezing bbfreeze can freeze multiple scripts at once. python interpreter included bbfreeze will create an extra executable named 'py', which might be used like the python executable itself. bbfreeze works on windows and UNIX-like operating systems. It currently does not work on OS X. bbfreeze has been tested with python 2.4 and 2.5. bbfreeze will not work with python versions prior to 2.3 as it uses the zipimport feature introduced with python 2.3. Links cheese shop entry: http://cheeseshop.python.org/pypi/ bbfreeze/http://cheeseshop.python.org/pypi/bbfreeze/ homepage: http://systemexit.de/bbfreeze/ mercurial repository: http://systemexit.de/repo/bbfreeze Regards, - Ralf -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Try a different type of debugger.
This one does not need you to set any breakpoints. It records the entire run. Handy, if you don't know where to start. Run the program once and after that all the runtime data is available to you. Which means you can jump to any point in the run and verify the code against runtime data. The user interface is the python code itself viewed inside a Firefox browser. Scroll to a line you're interested in and click the variable. It requires Firefox and Python 2.5. http://codeinvestigator.googlepages.com/main -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
Visualizing a wav file?
Hey everyone, I've done a good bit of google searching, and have found quite a few different libraries available for sound processing. I was wondering if anyone with more experience would like to say which one(s) they would use for displaying the waveform of a .wav file in real-time, or at least as the .wav is being played. Or is this something that would be better handled by the GUI code? Data from whatever's reading the sound, visualization by Tkinter or wx or whatnot? -- http://mail.python.org/mailman/listinfo/python-list
Re: bool behavior in Python 3000?
Steven D'Aprano wrote: On Tue, 10 Jul 2007 23:42:01 +0200, Bjoern Schliessmann wrote: Alan G Isaac wrote: My preference would be for the arithmetic operations *,+,- to be given the standard interpretation for a two element boolean algebra: http://en.wikipedia.org/wiki/Two-element_Boolean_algebra [bool(True+True), bool(True+False)] [True, True] Works for me, or did I misunderstand you? It seems to me that you deliberately misunderstood him. Why else would you type-cast the integers 2 and 1 to bools to supposedly demonstrate that there's nothing wrong with operations between bools returning ints? [snip] No, I think Bjoern just wanted to point out that all those binary boolean operators already work *perfectly*. You just have to emphasize that you're doing boolean algebra there, using `bool()`. Explicit is better than implicit. -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple search and Display system, no need for db?
On Wed, 11 Jul 2007 01:57:28 +, flit wrote: The user goes there: - Choose the building -- Department and the user receive an html table with all names . So the user gives two inputs and receive the names. Currently we are using this in mysql, This is the reason of the debate. If our list will never change and we are supposing that will be true for a long time, is it not too much use an mysql? Maybe mysql is really a bit heavy for this. If you still want to use an SQL DB then SQLite seems to be a candidate here. It doesn't need a server and comes with Python 2.5. SQLite doesn't handle concurrent updating of data that well, but in the given scenario there seem to be far more queries than updates. If the data is not too large, simple text files would do. Maybe in CSV format. Either with building and department as columns in the files or coded into the file name or path. Another approach would be the JSON_ format. Again, if the data is not too large one might send the whole JSON document to the client browser and use JavaScript on the client side to display and filter the name lists. Then you can slap the Web 2.0 buzz label onto the system. ;-) Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: concatenate file-like objects - file-like object
On Tue, 10 Jul 2007 17:55:52 -0700, kgk wrote: I would like to concatenate several file-like objects to create a single file-like object. I've looked at fileinput, however this returns a fileinput object that is not very file-like. something like # a has 50 bytes, and b has 100 bytes f = FileList (open('a'), open('b')) f.read (100) # read 50 bytes from a and 50 from b My interest is in passing several files to an incremental parser as if they came from a single file. I would rather not load them in memory using StringIO and the parser reads only from file-like objects. Then program a file like object yourself. Something like this (untestet): class FileList(object): def __init__(self, files): self.files = reversed(files) self.current_file = self.files.pop() def read(size): result = '' while self.files: data = self.current_file.read(size) result += data if len(data) != size: self.current_file = self.files.pop() size = size - len(data) return result Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: storing pickles in sql data base
In article [EMAIL PROTECTED], David Bear wrote: I need to store pickled objects in postgresql. You have this : http://blog.melhase.net/articles/2006/06/06/ a-tale-of-postgresql-types-and-python http://blog.melhase.net/articles/2006/06/13/ auto-postgresql-pickles Philippe Bouige -- http://mail.python.org/mailman/listinfo/python-list
Re: bool behavior in Python 3000?
Stargaming wrote: I think Bjoern just wanted to point out that all those binary boolean operators already work *perfectly*. bool(False-True) True But reread Steven. Cheers, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: bool behavior in Python 3000?
Bjoern Schliessmann wrote: Is there any type named bool in standard Python? type(True) type 'bool' Cheers, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: Dynamic method
I have an issue I think Python could handle. But I do not have the knowledge to do it. Suppose I have a class 'myClass' and instance 'var'. There is function 'myFunc(..)'. I have to add (or bind) somehow the function to the class, or the instance. Any help, info or point of reference is wellcome How about this (note the first argument 'self' which is the instance itself in the second case): def method_for_instance( message ): print message def method_for_class( self, message ): print message class myClass( object ): pass inst = myClass( ) inst.method = method_for_instance inst.method( 'hello' ) This won't work as expected: class Bidule(object): def __init__(self, name): self.name = name def greet(self, who): print hello %s, my name is %s % (who, self.name) b = Bidule('Bruno') b.greet = greet b.greet('Daniel') = Traceback (most recent call last): File stdin, line 1, in module File /tmp/python-23258Nq5.py, line 10, in module b.greet('Daniel') TypeError: greet() takes exactly 2 arguments (1 given) Well, I thought the name method_for_instance and method_for_class are clear enough that if you want to 'attach' one of them to an instance then method_for_instance should be used :) And method_for_instance has only one argument and so will work as in the example I gave (I guess you just overlooked them). The point is that Python functions are descriptor objects that, when looked up, return a (bound or unbound) method object wrapping themselves. So to attach functions as method *on a per-instance basis*, you either need to use new.instancemethod (as explained by Alex), or directly use the descriptor protocol, ie: b.greet = greet.__get__(b) b.greet('Daniel') = hello Daniel, my name is Bruno Note that you don't need this to attach a function as method to a class - the descriptor protocol will then JustWork(tm). I agree that in general the solution explained by Alex and you is better. -- http://mail.python.org/mailman/listinfo/python-list
Re: bool behavior in Python 3000?
Steven D'Aprano wrote: From a purely functional perspective, bools are unnecessary in Python. I think of True and False as syntactic sugar. But they shouldn't be syntactic sugar for 1 and 0 any more than they should be syntactic sugar for {x: foo} and {}. But `bools` are usefull in some contexts. Consider this: 1 == 1 True cmp(1, 1) 0 1 == 2 False cmp(1, 2) -1 At first look you can see that `cmp` does not return boolean value what not for all newbies is so obvious. Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: Visualizing a wav file?
Perhaps you can use parts/routines of Audacity. See: http://en.wikipedia.org/wiki/Audacity Wim Vogelaar, http://home.wanadoo.nl/w.h.vogelaar/ -- http://mail.python.org/mailman/listinfo/python-list
Re: bool behavior in Python 3000?
On Jul 11, 2:50 am, Alan Isaac [EMAIL PROTECTED] wrote: bool(False-True) True What boolean operation does '-' represent? -- http://mail.python.org/mailman/listinfo/python-list
Re: bool behavior in Python 3000?
Alan Isaac schrieb: Stargaming wrote: I think Bjoern just wanted to point out that all those binary boolean operators already work *perfectly*. bool(False-True) True But reread Steven. Cheers, Alan Isaac What would you expect this operation to return then? The * and + operations described in the previously mentioned document (http://en.wikipedia.org/wiki/Two-element_Boolean_algebra) work as you'd expect them to do, if you explicitly state hey, this should be a boolean algebra operation. And that's okay in my opinion. If you could describe what's wrong about that result, we could probably help better. Steven just suggests another (IMO totally unrelated) implementation of bool types. A point that Bjoern does not even touch here. Besides, his implementations fails at the * operation. Bjoern does not (sorry, if I say anything wrong, Bjoern) say the current behaviour is right or wrong. He just says that you can make Python aware of boolean algrebra utilizing `bool()` easily. bool-ly, Stargaming -- http://mail.python.org/mailman/listinfo/python-list
Re: os.wait() losing child?
Jason Zheng wrote: Hate to reply to my own thread, but this is the working program that can demonstrate what I posted earlier: I've figured out what's going on. The Popen class has a __del__ method which does a non-blocking wait of its own. So you need to keep the Popen instance for each subprocess alive until your wait call has cleaned it up. The following version seems to work okay. import os from subprocess import Popen pids = {} counts = [0,0,0] p = [None, None, None] for i in xrange(3): p[i] = Popen('sleep 1', shell=True) pids[p[i].pid] = i print Starting child process %d (%d) % (i,p[i].pid) while (True): (pid,exitstat) = os.wait() i = pids[pid] del pids[pid] counts[i]=counts[i]+1 #terminate if count10 if (counts[i]==10): print Child Process %d terminated. % i if reduce(lambda x,y: x and (y=10), counts): break continue print Child Process %d (%d) terminated, restarting % (i, pid), p[i] = Popen('sleep 1', shell=True) pids[p[i].pid] = i print (%d) % p[i].pid -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: Visualizing a wav file?
On 7/11/07, Wim Vogelaar [EMAIL PROTECTED] wrote: Perhaps you can use parts/routines of Audacity. See: http://en.wikipedia.org/wiki/Audacity Wim Vogelaar, http://home.wanadoo.nl/w.h.vogelaar/ -- http://mail.python.org/mailman/listinfo/python-list I'm aware of audacity. Correct me if I'm wrong, but I don't think Audacity is written in Python, although I think someone wrote a way to script it a bit using python. While looking at their code might prove useful to me, I'm looking for a way to implement this in python. To provide a clearer (and audacity related) example, I'd like to be able to show the waveform as it's playing - like if you zoomed in decently far on a sample in audacity while playing it back. If I can accomplish that, I think I can figure out most of the other stuff I'd like to do on my own. Just looking for some points in the right direction. -- http://mail.python.org/mailman/listinfo/python-list
Re: binascii.unhexlify ... not clear about usage, and output
On May 30, 1:31 pm, Peter Otten [EMAIL PROTECTED] wrote: Vishal wrote: I have a file with a long list of hex characters, and I want to get a file with corresponding binary characters here's what I did: import binascii f1 = 'c:\\temp\\allhex.txt' f2 = 'c:\\temp\\allbin.txt' sf = open(f1, 'rU') df = open(f2, 'w') slines = sf.readlines() for line in slines: ... x = line.rstrip('\n') ... y = binascii.unhexlify(x) ... df.write(y) ... df.close() sf.close() Your code is OK, but you have to open f2 in binary mode if your data is truly binary (an image, say). But what I get is all garbage, atleast textpad and notepad show that I tried doing it for only one string, and this is what I am seeing on the interpreter: x '0164' y '\x01d' I was expecting 'y' would come out as a string with binary characters!!! What are binary characters? What am i missing here? Can someone please help. What /exactly/ did you expect? Note that \x01d and \x01\x64 are just different renderings of the same string chr(0x01) + chr(0x64). Peter Thanks Peter for the explanation. Actually what I want is: if Input is 0x0164, Output should be: 000101100100 where each nibble is separated and the output appears in terms of '0's and '1's. Can I do that with this function binascii.unhexlify()??? Thanks and best regards, Vishal -- http://mail.python.org/mailman/listinfo/python-list
Re: Dynamic method
Daniel Nogradi a écrit : (snip) def method_for_instance( message ): print message class myClass( object ): pass inst = myClass( ) inst.method = method_for_instance inst.method( 'hello' ) (snip) This won't work as expected: class Bidule(object): def __init__(self, name): self.name = name def greet(self, who): print hello %s, my name is %s % (who, self.name) b = Bidule('Bruno') b.greet = greet b.greet('Daniel') = Traceback (most recent call last): File stdin, line 1, in module File /tmp/python-23258Nq5.py, line 10, in module b.greet('Daniel') TypeError: greet() takes exactly 2 arguments (1 given) Well, I thought the name method_for_instance and method_for_class are clear enough that if you want to 'attach' one of them to an instance then method_for_instance should be used :) And method_for_instance has only one argument and so will work as in the example I gave (I guess you just overlooked them). I didn't overlooked anything. *You* did. Your method_for_instance is *not* a method - it's a function. It's easy to check this out: class Toto(object): ... def truc(self): ... print %s.truc % self ... def chose(): ... print in chose, no 'self' here ... t = Toto() t.truc bound method Toto.truc of __main__.Toto object at 0xb7925c0c t.chose = chose t.chose function chose at 0xb7db541c The whole point of methods is that they do have access to the object (instance or class) - which is not the case of your method_for_instance. Please reread the following: The point is that Python functions are descriptor objects that, when looked up, return a (bound or unbound) method object wrapping themselves. So to attach functions as method *on a per-instance basis*, you either need to use new.instancemethod (as explained by Alex), or directly use the descriptor protocol, ie: b.greet = greet.__get__(b) b.greet('Daniel') = hello Daniel, my name is Bruno Note that you don't need this to attach a function as method to a class - the descriptor protocol will then JustWork(tm). I agree that in general the solution explained by Alex and you is better. They are not better - they are correct. HTH -- http://mail.python.org/mailman/listinfo/python-list
Where to find Python Enthought Edition for Linux?
Dear all, Is there any way I can download Python 2.4.3 Enthought Edition for Linux. AFAIK, from your website I can only find Enthought Tool Suite for Linux, which is not exactly what I want. The Enthought Edition is truly incredible. I want to re-place my original Python in my Linux box with Enthought Edition. This really save me trouble installing all those packages on my own. Hope to hear from you again. -- Gundala Viswanath -- http://mail.python.org/mailman/listinfo/python-list
Re: socket: connection reset by server before client gets response
ahlongxp [EMAIL PROTECTED] wrote: I feel a little embarrassed now. There is nothing to be embarrassed about. Experience is a thing that is hard won. As someone once said: no Pain, no Gain - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Time A Script
Hello Guys, What's the best way to time how long it takes a script to run, from top to bottom and then have it print that execution time at the end? Thanks guys, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: Visualizing a wav file?
kaens wrote: On 7/11/07, Wim Vogelaar [EMAIL PROTECTED] wrote: Perhaps you can use parts/routines of Audacity. See: http://en.wikipedia.org/wiki/Audacity Wim Vogelaar, http://home.wanadoo.nl/w.h.vogelaar/ -- http://mail.python.org/mailman/listinfo/python-list I'm aware of audacity. Correct me if I'm wrong, but I don't think Audacity is written in Python, although I think someone wrote a way to script it a bit using python. While looking at their code might prove useful to me, I'm looking for a way to implement this in python. To provide a clearer (and audacity related) example, I'd like to be able to show the waveform as it's playing - like if you zoomed in decently far on a sample in audacity while playing it back. If I can accomplish that, I think I can figure out most of the other stuff I'd like to do on my own. Just looking for some points in the right direction. For the visualization, you'll need a GUI-toolkit. Google this group for a plethora of discussions which are available and the respective advantages/disadvantages. The main problem will be the synchronization between the playing-process and your display. I have no idea if there is any feedback from the sound system that you can faciliate to compute the actual playing position. diez -- http://mail.python.org/mailman/listinfo/python-list
Re: stripping the first byte from a binary file
On Jul 11, 1:28 pm, Steven D'Aprano [EMAIL PROTECTED] wrote: On Wed, 11 Jul 2007 01:06:04 +, rvr wrote: Is there a way to edit the file in place? The best I seem to be able to do is to use your second solution to read the file into the string, then re-open the file for writing and put the whole thing back (minus the first byte). Thanks. I don't believe that any of the popular operating systems in common use (Windows, Linux, Mac, *BSD) have any such functionality. For safety, you are best off copying the file (minus the first byte) to a temporary file, then renaming the copy over the original. That way if your process dies midway through copying the file, you don't lose data. Renaming the file is atomic under Linux and (probably) Mac, so it is as safe as possible. Even under Windows, which isn't atomic, it has a smaller margin for disaster than over-writing the file in place. Thanks for your response. While searching for solution, I found this: http://mail.python.org/pipermail/python-list/2001-December/116519.html Quoting from it: Replace 2 bytes in place beginning at offset 100 (101st byte): f = open('text_input', 'r+b') f.seek(100) f.write(chr(123) + chr(0x80)) f.seek(0,2) f.close() Can I use the seek() and write() methods in a similar way to remove the first byte? For whatever reason I can't seem to make it work myself. Thanks again. ~rvr -- http://mail.python.org/mailman/listinfo/python-list
Re: stripping the first byte from a binary file
rvr wrote: On Jul 11, 1:28 pm, Steven D'Aprano [EMAIL PROTECTED] wrote: On Wed, 11 Jul 2007 01:06:04 +, rvr wrote: Is there a way to edit the file in place? The best I seem to be able to do is to use your second solution to read the file into the string, then re-open the file for writing and put the whole thing back (minus the first byte). Thanks. I don't believe that any of the popular operating systems in common use (Windows, Linux, Mac, *BSD) have any such functionality. For safety, you are best off copying the file (minus the first byte) to a temporary file, then renaming the copy over the original. That way if your process dies midway through copying the file, you don't lose data. Renaming the file is atomic under Linux and (probably) Mac, so it is as safe as possible. Even under Windows, which isn't atomic, it has a smaller margin for disaster than over-writing the file in place. Thanks for your response. While searching for solution, I found this: http://mail.python.org/pipermail/python-list/2001-December/116519.html Quoting from it: Replace 2 bytes in place beginning at offset 100 (101st byte): f = open('text_input', 'r+b') f.seek(100) f.write(chr(123) + chr(0x80)) f.seek(0,2) f.close() Can I use the seek() and write() methods in a similar way to remove the first byte? For whatever reason I can't seem to make it work myself. Thanks again. Funny. I just happened to read ESR's how to ask questions the smart way and your posts match quite a few of the examples. :) No, you can't. Steven's solution is what I'd go for. Stefan -- http://mail.python.org/mailman/listinfo/python-list
Re: Python IRC bot using Twisted
I have another problem with my IRC bot. There is privmsg(self, user, channel, msg) function (this function handles the incoming IRC data) in the code that was mentioned above. I have a special condition in this function that if a user sends to bot a private message (in other words: if channel == self.nickname) bot sends it to the main channel. Everything works fine except sending message to the main channel (for example #www). I write something like this: if channel == self.nickname: self.msg('www', msg) This code doesn't work. But if try to send private message back to user: if channel == self.nickname: self.msg(user, msg) everything works fine. I really don't know what to do. -- http://mail.python.org/mailman/listinfo/python-list
Re: What is the most efficient way to test for False in a list?
Paul Rubin a écrit : Duncan Booth [EMAIL PROTECTED] writes: status = not (False in list) That is an equality test, not an identity test: False in [0] True Arrh! Strongly typed language, my eye ;-) Thanks. We're quite a few to still think that the introduction of a boolean type in Python was perhaps not such a great idea. -- http://mail.python.org/mailman/listinfo/python-list
Re: SafeConfigParser can set unsafe values
Matimus wrote: I agree, but that was a trivial example to demonstrate the problem. Writing the file out to disk writes it exactly as set(), causing a get() to fail just the same later. No... The above statement is not true. Yes, it is. Whatever you set gets written out directly. Your example proves this: cp.set(sect,opt,hello%world) cp.write(sys.stdout) [/code] Produces this output: [sect] opt = hello%world Then when you get() this value later, it fails. The write method never calls get. However, when you read the file that was output by the above code using .get(...) will raise an error. You can avoid that error by setting the optional 'raw' parameter to True. But then you have disabled substitution, which is not the same thing! I don't necessarily want to disable substitution, I just want transparent handling of lone %s. Since SafeConfigParser.get() is fussy about the format of interpolation instructions, SafeConfigParser.set() can safely know when you're not trying to use them and escape lone percents. To summarise: set() should not set something which get() will ALWAYS fail on! Hamish -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple search and Display system, no need for db?
flit wrote: Hello All, I was discussing with a friend and we get in a hot debate. We have homepage that act like a name list. The user goes there: - Choose the building -- Department and the user receive an html table with all names . So the user gives two inputs and receive the names. Currently we are using this in mysql, This is the reason of the debate. If our list will never change and we are supposing that will be true for a long time, is it not too much use an mysql? Which kind of structure can we use in python? in web? What about using a simple dictionary in Python. You can use the module pickle (or cpickle) to dump it to disk and load it next time. Furthermore you can easily write the whole web server in Python, e.g. I like http://karrigell.sourceforge.net/ -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany -- http://mail.python.org/mailman/listinfo/python-list
Re: Python IRC bot using Twisted
On Wed, 11 Jul 2007 03:51:27 -0700, ddtm [EMAIL PROTECTED] wrote: I have another problem with my IRC bot. There is privmsg(self, user, channel, msg) function (this function handles the incoming IRC data) in the code that was mentioned above. I have a special condition in this function that if a user sends to bot a private message (in other words: if channel == self.nickname) bot sends it to the main channel. Everything works fine except sending message to the main channel (for example #www). I write something like this: if channel == self.nickname: self.msg('www', msg) This code doesn't work. But if try to send private message back to user: if channel == self.nickname: self.msg(user, msg) everything works fine. I really don't know what to do. self.msg('www', msg) will send msg to the user named `www'. To send to channels, be sure to include the '#' prefix. Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: pattern match !
[EMAIL PROTECTED] wrote: Extract the application name with version from an RPM string like hpsmh-1.1.1.2-0-RHEL3-Linux.RPM, i require to extract hpsmh-1.1.1.2-0 from above string. Sometimes the RPM string may be hpsmh-1.1.1.2-RHEL3- Linux.RPM. Have a try with import re P=re.compile(r'(\w+(?:[-.]\d+)+)-RHEL3-Linux\.RPM') S=hpsmh-1.1.1.2-0-RHEL3-Linux.RPM PO= P.match(S) if PO : print PO.group(1) -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany -- http://mail.python.org/mailman/listinfo/python-list
Re: stripping the first byte from a binary file
On Jul 11, 1:25 pm, Stefan Behnel [EMAIL PROTECTED] wrote: rvr wrote: On Jul 11, 1:28 pm, Steven D'Aprano [EMAIL PROTECTED] wrote: On Wed, 11 Jul 2007 01:06:04 +, rvr wrote: Is there a way to edit the file in place? The best I seem to be able to do is to use your second solution to read the file into the string, then re-open the file for writing and put the whole thing back (minus the first byte). Thanks. I don't believe that any of the popular operating systems in common use (Windows, Linux, Mac, *BSD) have any such functionality. For safety, you are best off copying the file (minus the first byte) to a temporary file, then renaming the copy over the original. That way if your process dies midway through copying the file, you don't lose data. Renaming the file is atomic under Linux and (probably) Mac, so it is as safe as possible. Even under Windows, which isn't atomic, it has a smaller margin for disaster than over-writing the file in place. Thanks for your response. While searching for solution, I found this: http://mail.python.org/pipermail/python-list/2001-December/116519.html Quoting from it: Replace 2 bytes in place beginning at offset 100 (101st byte): f = open('text_input', 'r+b') f.seek(100) f.write(chr(123) + chr(0x80)) f.seek(0,2) f.close() Can I use the seek() and write() methods in a similar way to remove the first byte? For whatever reason I can't seem to make it work myself. Thanks again. Funny. I just happened to read ESR's how to ask questions the smart way and your posts match quite a few of the examples. :) No, you can't. Steven's solution is what I'd go for. Stefan Forgive my newbie ignorance, but I am wondering why the other method would not work? I mean it may not be very safe, but I guess it may perform a lot better, than having to read the whole file just to cut out the first byte. TIA, ./alex -- .w( the_mindstorm )p. -- http://mail.python.org/mailman/listinfo/python-list
Re: bool behavior in Python 3000?
Steven D'Aprano wrote: On Tue, 10 Jul 2007 16:41:58 -0700, Paul Rubin wrote: Steven D'Aprano [EMAIL PROTECTED] writes: Pretending that False and True are just magic names for 0 and 1 might be easier than real boolean algebra, but that puts the cart before the horse. Functionality comes first: Python has lists and dicts and sets despite them not being ints, and somehow newcomers cope. I'm sure they will cope with False and True not being integers either. Are they are aren't they? I'm sorry, I can't parse that sentence. print 1 in [True] print 1 == True print len(set(map(type, [1, 1]))) print len(set(map(type, [1, True]))) But I guess that you are probably trying to make the point that True and False are instances of a _subtype_ of int rather than ints, under the mistaken idea that this pedantry would matter. (If this is not the case, then I apologize for casting aspersions.) However, you may notice that I said _integers_, which is not the same thing as ints: the Python types int and bool are both implementations of the mathematical integer or whole number. You can only cast aspersions in C, C# and similar languages. In Python you'd have to explicitly convert the aspersions to some other type ;-) regards Steve -- Steve Holden+1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --- Asciimercial -- Get on the web: Blog, lens and tag the Internet Many services currently offer free registration --- Thank You for Reading - -- http://mail.python.org/mailman/listinfo/python-list
Screen Scraping Question
Hey, I am trying to make a bot for a flash game using python. However I am having some trouble with a screen scraping strategy. Is there an accepted way to compare a full screenshot with the image that I want to locate? It is a math based game, so I just have to check what number, 1-9, appears in the center of the flash game. Is there an easier method to do this? Thanks -Jeff -- http://mail.python.org/mailman/listinfo/python-list
Re: bool behavior in Python 3000?
Miles wrote: What boolean operation does '-' represent? Complementation. And as usual, a-b is to be interpreted as a+(-b). In which case the desired behavior is False-True = False+(-True)=False+False = False In response to Stargaming, Steve is making a point about the incoherence of certain arguments, not proposing an implementation. Cheers, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: Portable general timestamp format, not 2038-limited
Ilya Zakharevich wrote: [A complimentary Cc of this posting was sent to Martin Gregorie [EMAIL PROTECTED]], who wrote in article [EMAIL PROTECTED]: Its in A Short History of Time. Sorry I can't quote chapter or page, but a friend borrowed my copy and lent me Dawkins Climbing Mount Improbable before vanishing, never to be seen since. Not an equal exchange: I preferred ASHOT to CMI. Oops - I should have written A Brief History of Time. It was the first edition, so I don't know if it was altered/edited out of later versions. I would prefer a reference to a peer-reviewed paper. ;-) Sure, but I don't think you'll find one. It was in a descriptive, rather than rigorous, passage. But then, the book famously had only one equation in it. -- martin@ | Martin Gregorie gregorie. | Essex, UK org | -- http://mail.python.org/mailman/listinfo/python-list
Re: How to Machine A python script execute Machine B python script?
johnny wrote: Anyone know how I can make Machine A python script execute a python script on Machine B ? have a look to py.execnet; in the simplest case, it does not need any special setup on machine B, just a working ssh server and a python interpreter installed: http://codespeak.net/py/dist/execnet.html ciao Anto -- http://mail.python.org/mailman/listinfo/python-list
Re: bool behavior in Python 3000?
Since it is seemingly ignored in most of the comments on this thread, I just want to remind that PEP 285 http://www.python.org/dev/peps/pep-0285/ says this: In an ideal world, bool might be better implemented as a separate integer type that knows how to perform mixed-mode arithmetic. I mentioned Python 3000 since that is an opportunity for an ideal world. Cheers, Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: bool behavior in Python 3000?
Steven D'Aprano wrote: On Tue, 10 Jul 2007 17:47:47 -0600, Steven Bethard wrote: But I think all you're really saying is that newbies don't expect things like +, -, *, etc. to work with bools at all. Which I agree is probably true. No, what I am saying is that True and False being integers under the hood is a surprising implementation detail. It has no _inherent_ benefit: it is merely a practical way to bring bools into the language while remaining backward compatible. For Python 2.x, that was the least bad solution to the issue oops, we should have included a bool type. Python 3 is allowed to break backwards compatibility, and there is no reason I can see to keep the current hack. Remember that while Python 3 is allowed to break backwards compatibility, it's only supposed to do it when there are concrete benefits. Clearly there are existing use cases for treating bools like ints, e.g. from Alexander Schmolck's email: (x b) * f(x) -1 ** (i == j) If you want to remove this functionality, you're going to need to provide some new use cases that it satisfies that are clearly more important than these existing ones. STeVe -- http://mail.python.org/mailman/listinfo/python-list
Re: stripping the first byte from a binary file
Forgive my newbie ignorance, but I am wondering why the other method would not work? I mean it may not be very safe, but I guess it may perform a lot better, than having to read the whole file just to cut out the first byte. Because seeking is not moving? Shifting data bytewise isn't something that is supported by the underlying OS filesystems, and thus not supported. But replacing bytes with others is. Which seek is for. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Portable general timestamp format, not 2038-limited
greg [EMAIL PROTECTED] wrote: Another thought: If the cosmologists ever decide if and when the Big Crunch is going to happen, we may be able to figure out once and for all how many bits we need in the timestamp. Unless of course, its all an oscillation - bang, crunch, bang, crunch, as the cosmic engine ticks over... But of course, cycles other than our own are kind of unreachable. - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Re: python extra
[EMAIL PROTECTED] wrote: On Jul 8, 12:59?pm, Neal Becker [EMAIL PROTECTED] wrote: Just a little python humor: http://www.amazon.com/Vitamin-Shoppe-Python-Extra-tablets/dp/B00012NJ... Aren't there any female Python programmers? No, of course not. Oh, and guys: If you take those pills please observe the warning; Safety information: Do not use if you are pregnant or nursing! :P -- http://mail.python.org/mailman/listinfo/python-list
Re: profiling a C++ python extension
rasmus wrote: I have used gprof to profile stand alone C++ programs. I am also aware of pure python profilers. However, is there a way to get profile information on my C++ functions when they are compiled in a shared library (python extension module) and called from python. From what I can tell, gmon.out will not be generated unless the entire executable (python interpreter) was compiled with -pg. Is my only solution to recompile the python interpreter with -pg so that my extension module (also compiled with -pg) produces a gmon.out? Any suggestions or tips would be helpful. Matt This may not be the best solution but it will work without any recompiles. Use the binary instrumentation tool PIN from Intel (you can get it here: http://rogue.colorado.edu/pin/) as far as I understand the license it's free for non-commercial use (if you're looking for commercial use ask your legal department... :) ). Once you're using PIN all you need to do is write a simple pintool (a profiler) that will profile only your shared library and leave the rest of the code alone. (there is a mailing list called pinheads in yahoo that is monitored by the developers and a lot of example code in the released kits). Hope this helps, Gal Diskin -- http://mail.python.org/mailman/listinfo/python-list
Python and Test Director
Hello, Can anyone tell me how to drive python test script via Test Director?? I am doing a project to translate Procomm script to python which is doable, but the purpose is so that the new .py scripts can be driven via Test Director. I am trying to research how to do it before this translation will be started. Either advice me with steps if you ever did or refer me to some materials I can read, thanks. PS: I heard (true or not) Test Director can run only python 2.2 or below, if that's the case what to do since I am running 2.4. Can I use WinRunner in between (Test Director and python) though I don't know how to do it either? Thanks again !! Solon Lee DIVFONT size=1 E-mail confidentiality. This e-mail contains confidential and / or privileged information belonging to Spirent Communications plc, its affiliates and / or subsidiaries. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution and / or the taking of any action based upon reliance on the contents of this transmission is strictly forbidden. If you have received this message in error please notify the sender by return e-mail and delete it from your system. If you require assistance, please contact our IT department at [EMAIL PROTECTED] Spirent Communications plc, Spirent House, Crawley Business Quarter, Fleming Way, Crawley, West Sussex, RH10 9QL, United Kingdom. Tel No. +44 (0) 1293 767676 Fax No. +44 (0) 1293 767677 Registered in England Number 470893 Registered at Spirent House, Crawley Business Quarter, Fleming Way, Crawley, West Sussex, RH10 9QL, United Kingdom Or if within the US, Spirent Communications, 26750 Agoura Road, Calabasas, CA, 91302, USA. Tel No. 1-818-676- 2300 /FONT/DIV -- http://mail.python.org/mailman/listinfo/python-list
Re: stripping the first byte from a binary file
Alex Popescu wrote: Forgive my newbie ignorance, but I am wondering why the other method would not work? I mean it may not be very safe, but I guess it may perform a lot better, than having to read the whole file just to cut out the first byte. Why would you expect that? It *might* perform better if there was a system call for removing bytes from inside a file, as that could reduce the intermediate space requirements to the size of a hard disk sector rather than the remaining size of the file (note that the time consumption would not be reduced significantly, if the remaining file has to be copied around to fill the sectors). But since that is a rather rare use case that most people would prefer being handled in a safe rather than space-optimal way, I don't see the need for such a function. Stefan -- http://mail.python.org/mailman/listinfo/python-list
python and Test Director
Hello, I have sent this similar email via another email address before I have registered with this email address, so the previous one may be rejected. I am sending agian via this newly established email address of mine. I am working on a project to translate Procomm to .py scripts, but the buttom line is to drive this .py test scripts via Test Dorector, can anyone guide me how to do it or refer me to some materials to read?I also heard which I am not sure if it's true or not that Test Director can work only with python 2.2 or below, if that's the case, what to do with python 2.4 that I am using now? Can I use WinRunner in between (python and Test Director), I don't know how this will work either. Thanks a lot!! Solon Lee-- http://mail.python.org/mailman/listinfo/python-list
Re: A clean way to program an interface
On Jul 9, 1:19 pm, rh0dium [EMAIL PROTECTED] wrote: Hi all, OK so I've started re-writing this based on the feedback you all gave me. How does this look? class Scanner: def __init__(self, *args, **kwargs): description # Setup Logging self.log = logging.getLogger(module+self.__class__.__name__) self.loglevel = kwargs.get('loglevel', logging.WARN) self.setLoglevel(self.loglevel) self.serialport=kwargs.get('port', PORT) self.serialbps=kwargs.get('bps', 115200) self.uniden=UnidenConnection.UnidenConnection(port=self.serialport, bps=self.serialbps, loglevel=self.loglevel) if self.inProgramMode(): self.PRGMode=True else: self.PRGMode=False def setLoglevel(self,loglevel): setLog log level if loglevel is not False: self.log.setLevel(loglevel) self.log.debug(Setting Logging level to %s % loglevel) else: self.log.setLevel(logging.WARN) if self.loglevel == logging.DEBUG: self.debug = True else: self.debug=False def ProgramMode(fn): def _prgmode(self,*args,**kwargs): progmode=True if not self.PRGMode: self.log.debug(Going into programming mode) progmode=False self.PRG() ret = fn(self,*args,**kwargs) if not progmode: self.log.debug(Getting out of programming mode) self.EPG() return ret return _prgmode def __orderedDictValues(self,orderedlist,dictvals): rlist = [] for x in orderedlist: if dictvals.has_key(x) or x == rsv: if x == rsv: rlist.append() else: rlist.append(str(dictvals[x])) else: break return rlist def STS(self): Get Current Status cmd = STS p = self.uniden.write(cmd) retargs = dsp_form l1_char l1_mode l2_char l2_mode l3_char l3_mode \ l4_char l4_mode l5_char l5_mode l6_char l6_mode l7_char \ l7_mode l8_char l8_mode sql mut rsv wat led_1 led_2 sig_lvl \ bk_color bk_dimmer.split() t = dict((k,v) for k, v in zip(retargs,p) if v != ) return t def PRG(self): Enter Programming Mode self.PRGMode=True return self.uniden.write(PRG) def EPG(self): Exit Programming Mode self.PRGMode=True return self.uniden.write(EPG) @ProgramMode def SIN(self, *args, **kwargs): Get/Set System Index cmd = SIN iptargs=index name quick_key hld lout dly skp rsv rsv apco \ threshold start_key record latitude longitude range \ gps_enable rsv.split() iptarglist=self.__orderedDictValues(iptargs,kwargs) if len(iptarglist) != len(iptargs) and len(iptarglist) != 1: raise SyntaxError, Missing arguments for %s expected 1 or %d got %d - given %s % (cmd, len(iptargs), len(iptarglist), kwargs) p = self.uniden.write(%s,%s % (cmd,,.join(iptarglist))) retargs = sys_type name quick_key hld lout dly skp rsv rsv apco \ threshold rev_index fwd_index chn_grp_head chn_grp_tail \ seq_no start_key record latitude longitude range gps enable \ rsv.split() t = dict((k,v) for k, v in zip(retargs,p) if v != ) return t def inProgramMode(self): try: printPRGMODE,self.STS() if self.STS()[l2_char].strip()==Remote Mode: print IN PRG return True else: return False except: return False -- http://mail.python.org/mailman/listinfo/python-list
Re: bool behavior in Python 3000?
On Jul 11, 3:37 am, Rob Wolfe [EMAIL PROTECTED] wrote: But `bools` are usefull in some contexts. Consider this: 1 == 1 True cmp(1, 1) 0 1 == 2 False cmp(1, 2) -1 At first look you can see that `cmp` does not return boolean value what not for all newbies is so obvious. Excellent point! And as long as we have them I agree with Alan that the boolean data type should implement real boolean algebra with respect to +, *, and ~, for example supporting operator precedence appropriately (versus using and, or, not) and also correctly implementing DeMorgan's laws and other property's of boolean algebra ~(a*b) == ~a + ~b etcetera. 1+True is bad practice and should be an error. Anything else is false advertising (and the java community has the patent on that methodology :c) ). -- Aaron Watters === Why does a giraffe have such a long neck? Because its head is so far from its body! -- http://mail.python.org/mailman/listinfo/python-list
Re: Best architecture for proxy?
On Jul 10, 8:19 pm, Steve Holden [EMAIL PROTECTED] wrote: Bjoern Schliessmann wrote: Andrew Warkentin wrote: I am going to write a general-purpose modular proxy in Python. It will consist of a simple core and several modules for things like filtering and caching. I am not sure whether it is better to use multithreading, or to use an event-driven networking library like Twisted or Medusa/ Asyncore. Which would be the better architecture to use? I'd definitely use an event-driven approach with Twisted. Generally, multithreading is less performant than multiplexing. High performance servers mostly use a combination of both, though. Converselt I'd recommend Medusa - not necessarily because it's better, but becuase I know it better. There's also a nice general-purpose proxy program (though I'd be surprised if Twisted didn't also have one). Would an event-driven proxy be able to handle multiple connections with large numbers of possibly CPU-bound filters? I use The Proxomitron (and would like to write my own proxy that can use the same filter sets, but follows the Unix philosophy) and some of the filters appear to be CPU-bound, because they cause The Proxomitron to hog the CPU (although that might just be a Proxomitron design flaw or something). Wouldn't CPU-bound filters only allow one connection to be filtered at a time? On the Medusa site, it said that an event-driven architecture only works for I/O-bound programs. -- http://mail.python.org/mailman/listinfo/python-list
Re: bool behavior in Python 3000?
On Wed, 11 Jul 2007 00:37:38 -0700, Rob Wolfe wrote: Steven D'Aprano wrote: From a purely functional perspective, bools are unnecessary in Python. I think of True and False as syntactic sugar. But they shouldn't be syntactic sugar for 1 and 0 any more than they should be syntactic sugar for {x: foo} and {}. But `bools` are usefull in some contexts. Consider this: 1 == 1 True cmp(1, 1) 0 1 == 2 False cmp(1, 2) -1 At first look you can see that `cmp` does not return boolean value what not for all newbies is so obvious. Sorry I fail to see your point!? What has ``==`` to do with `cmp()` here? The return of `cmp()` is an integer that cannot and should not be seen as boolean value. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: bool behavior in Python 3000?
Steven D'Aprano wrote: How could Python cast objects to bool before bool existed? Time machine? Sorry, I couldn't resist. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: bool behavior in Python 3000?
Steven D'Aprano a écrit : (snip) I mean, really, does anyone *expect* True+True to give 2, or that 2**True even works, I may be biased since I learned C before Python and learned Python before it had a Boolean type, but I'd think that having False==0 and True==1 is not that surprising for most programmers. without having learnt that Python bools are ints? I doubt it. And the old Python idiom for an if...then...else expression: [something, or other][True] tends to come as a great surprise to most newbies. This idiom should slowly disappear now we have a clean syntax for such expressions. So I would argue that bools being ints is more surprising than the opposite would be. I suppose this mostly have to do with one's background. -- http://mail.python.org/mailman/listinfo/python-list
Re: stripping the first byte from a binary file
On Jul 11, 4:15 pm, Diez B. Roggisch [EMAIL PROTECTED] wrote: Forgive my newbie ignorance, but I am wondering why the other method would not work? I mean it may not be very safe, but I guess it may perform a lot better, than having to read the whole file just to cut out the first byte. Because seeking is not moving? Shifting data bytewise isn't something that is supported by the underlying OS filesystems, and thus not supported. But replacing bytes with others is. Which seek is for. Diez As far as I know seek is just about positioning and nothing else. So, in fact the problem boils down to os support for deleting a bytes. bests, ./alex -- .w( the_mindstorm )p. -- http://mail.python.org/mailman/listinfo/python-list
wxPython vs. Tkinter event loops
I'm porting a Tkinter application to wxPython and had a question about wxPython's event loop. The Tkinter app provides a GUI to a command-line tool. It gathers user input, and opens an asynchronous pipe to the external tool via os.popen(). Then, it dumps the output from the external process into a text display. Although threads are often recommended for use with GUI apps, I am able to keep the GUI responsive with Tkinter's event loop, i.e. with regular calls to self.update(); I am still able to update the GUI as needed. When I tried the same functions using threads, I noticed no measurable improvement in application responsiveness or performance. Thus, the application currently runs in a single thread and is updated via Tkinter's event loop only. Does wxPython's event loop function as smoothly as Tkinter's with an asynchronous process, i.e. is the wx.UpdateUIEvent() class analogous to Tkinter.update(), or are threads absoutely essential to keeping a wx GUI updated with a long-running background process? -- Kevin Walzer Code by Kevin http://www.codebykevin.com -- http://mail.python.org/mailman/listinfo/python-list
Re: bool behavior in Python 3000?
Alan Isaac schrieb: Miles wrote: What boolean operation does '-' represent? Complementation. And as usual, a-b is to be interpreted as a+(-b). In which case the desired behavior is False-True = False+(-True)=False+False = False I always thought, at least in a Python context, A-B would trigger A.__sub__(B), while A+(-B) triggers A.__add__(B.__neg__()). A better choice could be A+~B (A.__add__(B.__invert__())) because it's always unary (and IMO slightly more visible). In response to Stargaming, Steve is making a point about the incoherence of certain arguments, not proposing an implementation. Why should it be incoherent? Bjoern is pointing out an important aspect of how Python handles binary algebra (correctly). In contrast, Steven tries to invert his argument. Following, I showed why Steven's proof is wrong because his implementation fails at some aspects where the current one works. So I cannot see how Bjoern's argument is either wrong or not relevant. -- http://mail.python.org/mailman/listinfo/python-list
Re: Best architecture for proxy?
On Wed, 11 Jul 2007 07:00:18 -0700, Andrew Warkentin [EMAIL PROTECTED] wrote: On Jul 10, 8:19 pm, Steve Holden [EMAIL PROTECTED] wrote: Bjoern Schliessmann wrote: Andrew Warkentin wrote: I am going to write a general-purpose modular proxy in Python. It will consist of a simple core and several modules for things like filtering and caching. I am not sure whether it is better to use multithreading, or to use an event-driven networking library like Twisted or Medusa/ Asyncore. Which would be the better architecture to use? I'd definitely use an event-driven approach with Twisted. Generally, multithreading is less performant than multiplexing. High performance servers mostly use a combination of both, though. Converselt I'd recommend Medusa - not necessarily because it's better, but becuase I know it better. There's also a nice general-purpose proxy program (though I'd be surprised if Twisted didn't also have one). Would an event-driven proxy be able to handle multiple connections with large numbers of possibly CPU-bound filters? I use The Proxomitron (and would like to write my own proxy that can use the same filter sets, but follows the Unix philosophy) and some of the filters appear to be CPU-bound, because they cause The Proxomitron to hog the CPU (although that might just be a Proxomitron design flaw or something). Wouldn't CPU-bound filters only allow one connection to be filtered at a time? On the Medusa site, it said that an event-driven architecture only works for I/O-bound programs. Handling all of your network traffic with a single OS thread doesn't necessarily mean that all of your filters need to run in the same thread (or even in the same process, or on the same computer). Typically, however, a filtering rule should only need to operate on a small number of bytes (almost always only a few kilobytes). Is it the case that handling even this amount of data incurs a significant CPU cost? If not, then there's probably nothing to worry about here, and you can do everything in a single thread. If it is the case, then you might want to keep around a thread pool (or process pool, or cluster) and push the filtering work to it, reserving the IO thread strictly for IO. This is still a win, since you end up with a constant number of processes vying for CPU time (and you can tune this to an ideal value given your available hardware), rather than one per connection. This translates directly into reduced context switch overhead. Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: bool behavior in Python 3000?
Marc 'BlackJack' Rintsch wrote: On Wed, 11 Jul 2007 00:37:38 -0700, Rob Wolfe wrote: Steven D'Aprano wrote: From a purely functional perspective, bools are unnecessary in Python. I think of True and False as syntactic sugar. But they shouldn't be syntactic sugar for 1 and 0 any more than they should be syntactic sugar for {x: foo} and {}. But `bools` are usefull in some contexts. Consider this: 1 == 1 True cmp(1, 1) 0 1 == 2 False cmp(1, 2) -1 At first look you can see that `cmp` does not return boolean value what not for all newbies is so obvious. Sorry I fail to see your point!? What has ``==`` to do with `cmp()` here? The return of `cmp()` is an integer that cannot and should not be seen as boolean value. Before `bool` appeared it looked like this: 1 == 1 1 cmp(2, 1) 1 Wich result is boolean value? Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: bool behavior in Python 3000?
Steven Bethard a écrit : (snip) Remember that while Python 3 is allowed to break backwards compatibility, it's only supposed to do it when there are concrete benefits. Clearly there are existing use cases for treating bools like ints, e.g. from Alexander Schmolck's email: (x b) * f(x) -1 ** (i == j) Both can be cleanly handled using int(): int(x b) * f(x) -1 ** int(i == j) Not that I have any clear opinion on the topic FWIW. -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython vs. Tkinter event loops
On 7/11/07, Kevin Walzer [EMAIL PROTECTED] wrote: I'm porting a Tkinter application to wxPython and had a question about wxPython's event loop. The Tkinter app provides a GUI to a command-line tool. It gathers user input, and opens an asynchronous pipe to the external tool via os.popen(). Then, it dumps the output from the external process into a text display. Although threads are often recommended for use with GUI apps, I am able to keep the GUI responsive with Tkinter's event loop, i.e. with regular calls to self.update(); I am still able to update the GUI as needed. When I tried the same functions using threads, I noticed no measurable improvement in application responsiveness or performance. Thus, the application currently runs in a single thread and is updated via Tkinter's event loop only. Does wxPython's event loop function as smoothly as Tkinter's with an asynchronous process, i.e. is the wx.UpdateUIEvent() class analogous to Tkinter.update(), No. It provides a totally different purpose - it's an idle event thats used to do things like ensure that menu items and toolbar buttons are kept in sync. or are threads absoutely essential to keeping a wx GUI updated with a long-running background process? No again. wxPython provides a Process class for executing external applications and providing events in response to input, app exit, and similar. You can also implement it in a similar way to your Tkinter implementation, but backwards - poll the pipe repeatedly using wx.CallAfter or wx.CallLater calls. -- http://mail.python.org/mailman/listinfo/python-list
Re: Should I use Python for these programs?
On 7/10/07, CC [EMAIL PROTECTED] wrote: Bjoern Schliessmann wrote: Grant Edwards wrote: Most of the graphics I do with Python is with Gnuplot (not really appropriate for what you want to do. wxWidgets/Floatcanvas might be worth looking into. Agreed (I'm quite sure you mean wxPython though). Also, in wxPython in Action (the official book) a simple drawing app is constructed. It could help to start from there. Ooh, that's interesting. The programming contractor at work who does all our DAQ stuff also uses wxPython so it's looking like I should use that since I can get lots of help. Since the book was written, wxPython has grown a vector graphics system that might be more suitable for your needs. Look at the wxGraphicsContext class. -- http://mail.python.org/mailman/listinfo/python-list
Re: profiling a C++ python extension
Googling for profiling python extensions leads to the following link which worked for me a while ago: http://plexity.blogspot.com/2006/02/profiling-python-extensions.html On 7/10/07, rasmus [EMAIL PROTECTED] wrote: I have used gprof to profile stand alone C++ programs. I am also aware of pure python profilers. However, is there a way to get profile information on my C++ functions when they are compiled in a shared library (python extension module) and called from python. From what I can tell, gmon.out will not be generated unless the entire executable (python interpreter) was compiled with -pg. Is my only solution to recompile the python interpreter with -pg so that my extension module (also compiled with -pg) produces a gmon.out? Any suggestions or tips would be helpful. Matt -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Passing a CookieJar instead of a cookieproc to urllib2.build_opener
On Jul 10, 11:10 pm, [EMAIL PROTECTED] (John J. Lee) wrote: [EMAIL PROTECTED] [EMAIL PROTECTED] writes: urllib2.build_opener happily accepts and ignores a FileCookieJar.I had a bug in my code which looked like urllib2.build_opener(func_returning_cookie_jar()) which should have been urllib2.build_opener(HTTPCookieProcessor(func_returning_cookie_jar()) The problem is that the code ran happily without actually sending the cookie, the CookieJar was just ignored. I think that build_opener should throw an exception when add_handler doesn't actually add. Is this worth filing a bug for, or is it acceptable behavior? IMO, it's worth filing iff: a) you think it's worthwhile (this one sounds worthwhile to me) b) you write a patch and are prepared to patiently keep at it until it gets applied Make sure your patch follows PEP 8. Make sure the patch includes test and documentation updates / additions (you don't need to write docs in LaTeX format -- other people will do the conversion to LaTeX for you if you like). If there are no doc changes required, state that explicitly in the patch tracker. If your patch gets ignored, review five other patches, and post to python-dev stating you have done so and requesting that your patch is reviewed (there's a shortage of patch reviewers). John The patch is on the tracker here. http://sourceforge.net/tracker/index.php?func=detailaid=1750931group_id=5470atid=305470 Are the docs themselves in subversion? I suppose I should also update the doc at http://docs.python.org/lib/module-urllib2.html -- http://mail.python.org/mailman/listinfo/python-list
Re: stripping the first byte from a binary file
Alex Popescu wrote: On Jul 11, 4:15 pm, Diez B. Roggisch [EMAIL PROTECTED] wrote: Forgive my newbie ignorance, but I am wondering why the other method would not work? I mean it may not be very safe, but I guess it may perform a lot better, than having to read the whole file just to cut out the first byte. Because seeking is not moving? Shifting data bytewise isn't something that is supported by the underlying OS filesystems, and thus not supported. But replacing bytes with others is. Which seek is for. Diez As far as I know seek is just about positioning and nothing else. It is. So, in fact the problem boils down to os support for deleting a bytes. Which there isn't, as I and several others pointed out. And replacing is not removing. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython vs. Tkinter event loops
On Jul 11, 11:17 am, Chris Mellon [EMAIL PROTECTED] wrote: No again. wxPython provides a Process class for executing external applications and providing events in response to input, app exit, and similar. You can also implement it in a similar way to your Tkinter implementation, but backwards - poll the pipe repeatedly using wx.CallAfter or wx.CallLater calls. You can also set up a callback on the idle event and do a little processing every time it's called, though that can be odd because it tends to e.g. update more often when the mouse is moving over the window and such. There may be other ways, too, I don't have access to my docs or the demo here (just poked my head in because I'm waiting for my work program to stop being frozen ...). -Weaver -- http://mail.python.org/mailman/listinfo/python-list
Problem with Python's robots.txt file parser in module robotparser
Python's robots.txt file parser may be misinterpreting a special case. Given a robots.txt file like this: User-agent: * Disallow: // Disallow: /account/registration Disallow: /account/mypro Disallow: /account/myint ... the python library robotparser.RobotFileParser() considers all pages of the site to be disallowed. Apparently Disallow: // is being interpreted as Disallow: /. Even the home page of the site is locked out. This may be incorrect. This is the robots.txt file for http://ibm.com;. Some IBM operating systems recognize filenames starting with // as a special case like a network root, so they may be trying to handle some problem like that. The spec for robots.txt, at http://www.robotstxt.org/wc/norobots.html says Disallow: The value of this field specifies a partial URL that is not to be visited. This can be a full path, or a partial path; any URL that starts with this value will not be retrieved. That suggests that // should only disallow paths beginning with //. John Nagle SiteTruth -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple search and Display system, no need for db?
On Jul 11, 3:06 am, Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote: If the data is not too large, simple text files would do. Maybe in CSV format. Either with building and department as columns in the files or coded into the file name or path. That seems to be a good idea, but I am afraid the web hosting does not have the csv modules.. (maybe if I do an split?) -- http://mail.python.org/mailman/listinfo/python-list
asyncore and OOB data
Hi there, In an asyncore based FTP server I wrote I should be able to receive OOB data from clients. A client sending such kind of data should act like this: import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('127.0.0.1', 21)) s.sendall('hello there\r\n', socket.MSG_OOB) According to asyncore documentation I should handle this kind of event in handle_expt method of dispatcher class, that should be called when OOB is received by the underlying socket. I've tried to override handle_expt method in such way: def handle_expt(self): print OOB data arrived data = self.socket.recv(1024, socket.MSG_OOB) print data ...but, even if it is called, data contains only a \n character instead of the entire string (hello there\r\n). Why does this happen? Should I have to use a different approach? Thanks in advance. -- http://mail.python.org/mailman/listinfo/python-list
Re: Simple search and Display system, no need for db?
On Wed, 11 Jul 2007 16:52:32 +, flit wrote: That seems to be a good idea, but I am afraid the web hosting does not have the csv modules.. The `csv` module is part of the standard library. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: 2**2**2**2**2 wrong? Bug?
On Jul 10, 12:47 am, Jim Langston [EMAIL PROTECTED] wrote: Paul Rubin http://[EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] Jim Langston [EMAIL PROTECTED] writes: In Python 2.5 on intel, the statement 2**2**2**2**2 evaluates to 2**2**2**2**2 I get the same number from hugs--why do you think it might be wrong? 2**2 = 4 4**2 = 16 16**2 = 256 256**2 = 65536 65536**2 = 4294967296 In fact, if I put (2**2)**2**2**2 it comes up with the correct answer, 4294967296 Actually, the correct answer (even by your own demonstration) is 65536. Assuming left-associativity, i.e., (((2**2)**2)**2)**2, python returns 65536. The answer of 4294967296 is actually 2**2)**2)**2)**2)**2, which is one extra raise-to-the-power-of-two instruction. The statement (2**2)**2**2**2 is the same as 4**16, following right- associativity rules, which just happens to be the same as 2**2)**2)**2)**2)**2. David -- http://mail.python.org/mailman/listinfo/python-list
Re: Embedding Matplotlib in wxpython wx.Panel problem
On Jul 10, 2:09 pm, abakshi11 [EMAIL PROTECTED] wrote: I was wondering if you ever got to create a small GUI program that did plots using Matplotlib I am gettin an error where its saying WXagg's accelerator requires the wxPython headers-the wxpython header files can not be located in any of the standard include directories reported by 'wx-config --cppflags' Do you think you can help? Soren-3 wrote: Hi, I'm trying to create a small GUI program where I can do plots using Matplotlib. I've been trying to borrow code from the examples at the matplotlib website, but I can't get it to work. I want to be able to create a wx.Panel that contains an axis for plotting. Around it i want other panels containing various settings, buttons etc. to control the plot. So far I can't even get the program to actually show a plot in a panel. Does anyone here have experience in making a wxpython GUI with matplotlib? Any help would be appreciated! Thanks, Soren My code shows a frame, and I'm trying to set up two panels.. one with a plot and one with a button.. The plotpanel is just a little square in the corner when I run it.. ??? My code is as follows: import wx import pylab from matplotlib.numerix import arange, sin, cos, pi import matplotlib matplotlib.use('WXAgg') from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg from matplotlib.backends.backend_wx import NavigationToolbar2Wx from matplotlib.figure import Figure matplotlib.interactive(False) class App(wx.App): def OnInit(self): self.frame = MainFrame(Autoplotter, (50,60), (700,700)) self.frame.Show() return True class MainFrame(wx.Frame): def __init__(self, title, pos, size): wx.Frame.__init__(self, None, -1, title, pos, size) pPanel = PlotPanel(self, -1)# Plot panel bPanel = ButtonPanel(self, 100,500, (200,100))# button panel sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(pPanel,0) sizer.Add(bPanel,0) self.SetSizer(sizer) class ButtonPanel(wx.Panel): def __init__(self, Parent, xPos, yPos, insize): pos = (xPos, yPos) wx.Panel.__init__(self, Parent, -1, pos, style = wx.RAISED_BORDER, size = insize) button = wx.Button(self, -1, 'HELLO!!', (10,10), (150,50)) class NoRepaintCanvas(FigureCanvasWxAgg): We subclass FigureCanvasWxAgg, overriding the _onPaint method, so that the draw method is only called for the first two paint events. After that, the canvas will only be redrawn when it is resized. def __init__(self, *args, **kwargs): FigureCanvasWxAgg.__init__(self, *args, **kwargs) self._drawn = 0 def _onPaint(self, evt): Called when wxPaintEvt is generated if not self._isRealized: self.realize() if self._drawn 2: self.draw(repaint = False) self._drawn += 1 self.gui_repaint(drawDC=wx.PaintDC(self)) class PlotPanel(wx.Panel): def __init__(self, parent, id = -1, color = None,\ dpi = None, style = wx.NO_FULL_REPAINT_ON_RESIZE, **kwargs): wx.Panel.__init__(self, parent, id = id, style = style, **kwargs) self.figure = Figure(None, dpi) self.canvas = NoRepaintCanvas(self, -1, self.figure) self._resizeflag = True self.Bind(wx.EVT_IDLE, self._onIdle) self.Bind(wx.EVT_SIZE, self._onSize) self._SetSize() def draw(self): # just draw something! if not hasattr(self, 'subplot'): self.subplot = self.figure.add_subplot(111) theta = arange(0, 45*2*pi, 0.02) rad = (0.8*theta/(2*pi)+1) r = rad*(8 + sin(theta*7+rad/1.8)) x = r*cos(theta) y = r*sin(theta) #Now draw it self.subplot.plot(x,y, '-r') def _onSize(self, event): self._resizeflag = True def _onIdle(self, evt): if self._resizeflag: self._resizeflag = False self._SetSize() self.draw() def _SetSize(self, pixels = None): This method can be called to force the Plot to be a desired size, which defaults to the ClientSize of the panel if not pixels: pixels = self.GetClientSize() self.canvas.SetSize(pixels) self.figure.set_figsize_inches(pixels[0]/ self.figure.get_dpi(), pixels[1]/self.figure.get_dpi()) if __name__ == __main__: app = App(0) app.MainLoop() -- http://mail.python.org/mailman/listinfo/python-list -- View this message in context:http://www.nabble.com/Embedding-Matplotlib-in-wxpython-wx.Panel-probl... Sent from the Python - python-list
condor_compiled python interpreter
Does anyone know where I could find help on condor_compiling a python interpreter? My own attempts have failed, and I can't find anything on google. Here's the condor page: http://www.cs.wisc.edu/condor/ Thanks, Tom -- http://mail.python.org/mailman/listinfo/python-list
Re: condor_compiled python interpreter
On Wed, Jul 11, 2007 at 10:28:52AM -0700, Thomas Nelson wrote: Does anyone know where I could find help on condor_compiling a python interpreter? My own attempts have failed, and I can't find anything on google. This is probably more condor-related than Python-related, but are you building for the standard universe? It shouldn't be too hard. See this thread[0] for some more bits, including a step-by-step. [0] https://lists.cs.wisc.edu/archive/condor-users/2007-March/msg00216.shtml https://lists.cs.wisc.edu/archive/condor-users/2007-March/msg00217.shtml -- [Will [EMAIL PROTECTED]|http://www.lfod.us/] -- http://mail.python.org/mailman/listinfo/python-list
Re: binascii.unhexlify ... not clear about usage, and output
On Jul 11, 3:21 am, Vishal [EMAIL PROTECTED] wrote: On May 30, 1:31 pm, Peter Otten [EMAIL PROTECTED] wrote: Vishal wrote: I have a file with a long list of hex characters, and I want to get a file with corresponding binary characters here's what I did: import binascii f1 = 'c:\\temp\\allhex.txt' f2 = 'c:\\temp\\allbin.txt' sf = open(f1, 'rU') df = open(f2, 'w') slines = sf.readlines() for line in slines: ... x = line.rstrip('\n') ... y = binascii.unhexlify(x) ... df.write(y) ... df.close() sf.close() Your code is OK, but you have to open f2 in binary mode if your data is truly binary (an image, say). But what I get is all garbage, atleast textpad and notepad show that I tried doing it for only one string, and this is what I am seeing on the interpreter: x '0164' y '\x01d' I was expecting 'y' would come out as a string with binary characters!!! What are binary characters? What am i missing here? Can someone please help. What /exactly/ did you expect? Note that \x01d and \x01\x64 are just different renderings of the same string chr(0x01) + chr(0x64). Peter Thanks Peter for the explanation. Actually what I want is: if Input is 0x0164, Output should be: 000101100100 where each nibble is separated and the output appears in terms of '0's and '1's. Can I do that with this function binascii.unhexlify()??? You can with gmpy: import gmpy x = 0x0164 s = gmpy.digits(x,2) # convert to base 2 y = '0'*(16-len(s)) + s # pad to 16 bits y '000101100100' Thanks and best regards, Vishal -- http://mail.python.org/mailman/listinfo/python-list
Re: asyncore and OOB data
If it could be useful I attach the complete server application I used for doing tests: code import asyncore, asynchat, socket, os class Handler(asynchat.async_chat): def __init__(self, sock_obj): asynchat.async_chat.__init__(self, conn=sock_obj) self.remote_ip, self.remote_port = self.socket.getpeername() self.in_buffer = self.out_buffer = self.set_terminator(\r\n) def handle_expt(self): print OOB data arrived data = self.socket.recv(1024, socket.MSG_OOB) print tuple(data) def collect_incoming_data(self, data): self.in_buffer += data def found_terminator(self): print self.in_buffer self.in_buffer = '' def handle_error(self): raise class Server(asyncore.dispatcher): def __init__(self): asyncore.dispatcher.__init__(self) self.create_socket(socket.AF_INET, socket.SOCK_STREAM) if os.name == 'posix': self.set_reuse_addr() self.bind(('', 21)) self.listen(5) def handle_accept(self): sock_obj, addr = self.accept() Handler(sock_obj) def handle_error(self): raise Server() asyncore.loop(timeout=1) -- http://mail.python.org/mailman/listinfo/python-list
Re: bool behavior in Python 3000?
On Jul 11, 2007, at 2:04 AM, Stargaming wrote: No, I think Bjoern just wanted to point out that all those binary boolean operators already work *perfectly*. You just have to emphasize that you're doing boolean algebra there, using `bool()`. Explicit is better than implicit. I think that the assignability to the names 'True' and 'False' is incorrect, or at the very least subject to all sorts of odd results. Look at this: True, False (True, False) True = False True, False (False, False) True == False True (True == False) == True False Yeah, I know: Doctor, it hurts when I do this. Doc: So don't do that!. I haven't kept up with all the Python 3000 docs, so does anyone know if True and False will become true keywords, and whether oddball stuff like the above will no longer be possible? -- Ed Leafe -- http://leafe.com -- http://dabodev.com -- http://mail.python.org/mailman/listinfo/python-list
Re: os.wait() losing child?
Greg, That explains it! Thanks a lot for your help. I guess this is something they do to prevent zombie threads? ~Jason greg wrote: Jason Zheng wrote: Hate to reply to my own thread, but this is the working program that can demonstrate what I posted earlier: I've figured out what's going on. The Popen class has a __del__ method which does a non-blocking wait of its own. So you need to keep the Popen instance for each subprocess alive until your wait call has cleaned it up. The following version seems to work okay. import os from subprocess import Popen pids = {} counts = [0,0,0] p = [None, None, None] for i in xrange(3): p[i] = Popen('sleep 1', shell=True) pids[p[i].pid] = i print Starting child process %d (%d) % (i,p[i].pid) while (True): (pid,exitstat) = os.wait() i = pids[pid] del pids[pid] counts[i]=counts[i]+1 #terminate if count10 if (counts[i]==10): print Child Process %d terminated. % i if reduce(lambda x,y: x and (y=10), counts): break continue print Child Process %d (%d) terminated, restarting % (i, pid), p[i] = Popen('sleep 1', shell=True) pids[p[i].pid] = i print (%d) % p[i].pid -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Tuple vs List: Whats the difference?
Hello folks, I am an experienced programmer, but very new to python (2 days). I wanted to ask: what exactly is the difference between a tuple and a list? I'm sure there are some, but I can't seem to find a situation where I can use one but not the other. Thanks in advance, --Shafik -- http://mail.python.org/mailman/listinfo/python-list
Re: Tuple vs List: Whats the difference?
On 7/11/07, Shafik [EMAIL PROTECTED] wrote: I am an experienced programmer, but very new to python (2 days). I wanted to ask: what exactly is the difference between a tuple and a list? I'm sure there are some, but I can't seem to find a situation where I can use one but not the other. The differences are explained pretty good on here. Although, I am pretty new to Python as well. http://diveintopython.org/native_data_types/tuples.html -- http://mail.python.org/mailman/listinfo/python-list
Re: os.wait() losing child?
greg [EMAIL PROTECTED] wrote: I've figured out what's going on. The Popen class has a __del__ method which does a non-blocking wait of its own. So you need to keep the Popen instance for each subprocess alive until your wait call has cleaned it up. I don't think this will be enough for the poster, who has Python 2.4: in that version, opening a new Popen object would trigger the wait on all 'outstanding' Popen-managed subprocesses. It seems to me that subprocess.py assumes that it will do all wait()ing on its children itself; I'm not sure if it's safe to rely on the details of how this is currently arranged. Perhaps a better way would be for subprocess.py to provide its own variant of os.wait() for people who want 'wait-for-any-child' (though it would be hard to support programs which also had children not managed by subprocess.py). -M- -- http://mail.python.org/mailman/listinfo/python-list
Re: binascii.unhexlify ... not clear about usage, and output
On Wed, 11 Jul 2007 10:46:23 -0700, [EMAIL PROTECTED] wrote: You can with gmpy: import gmpy x = 0x0164 s = gmpy.digits(x,2) # convert to base 2 y = '0'*(16-len(s)) + s # pad to 16 bits y '000101100100' For the padding I'd use the `zfill()` method. In [15]: a = 0x0164 In [16]: gmpy.digits(a, 2).zfill(16) Out[16]: '000101100100' Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Encode Bytes
Hi All, I am new to python and I am using a strip down version of python that does not support struc,pack,etc. I have a binary protocol that is define as follows: PARTOffSet Lenght ID 02 VER 21 CMD 32 PGKID52 DATE 73 TIME103 CRC 132 DLEN152 How do I encode these the offset is in Bytes. Thank you very much. -- http://mail.python.org/mailman/listinfo/python-list
Re: os.wait() losing child?
greg wrote: Jason Zheng wrote: Hate to reply to my own thread, but this is the working program that can demonstrate what I posted earlier: I've figured out what's going on. The Popen class has a __del__ method which does a non-blocking wait of its own. So you need to keep the Popen instance for each subprocess alive until your wait call has cleaned it up. The following version seems to work okay. It still doesn't work on my machine. I took a closer look at the Popen class, and I think the problem is that the __init__ method always calls a method _cleanup, which polls every existing Popen instance. The poll method does a nonblocking wait. If one of my child process finishes as I create a new Popen instance, then the _cleanup method effectively de-zombifies the child process, so I can no longer expect to see the return of that pid on os.wait() any more. ~Jason -- http://mail.python.org/mailman/listinfo/python-list
Re: os.wait() losing child?
Matthew Woodcraft wrote: greg [EMAIL PROTECTED] wrote: I've figured out what's going on. The Popen class has a __del__ method which does a non-blocking wait of its own. So you need to keep the Popen instance for each subprocess alive until your wait call has cleaned it up. I don't think this will be enough for the poster, who has Python 2.4: in that version, opening a new Popen object would trigger the wait on all 'outstanding' Popen-managed subprocesses. It seems to me that subprocess.py assumes that it will do all wait()ing on its children itself; I'm not sure if it's safe to rely on the details of how this is currently arranged. Perhaps a better way would be for subprocess.py to provide its own variant of os.wait() for people who want 'wait-for-any-child' (though it would be hard to support programs which also had children not managed by subprocess.py). -M- Thanks, that's exactly what I need, my program really needs the os.wait() to be reliable. Perhaps I could pass a flag to Popen to tell it to never os.wait() on the new pid (but it's ok to os.wait() on other Popen instances upon _cleanup()). -- http://mail.python.org/mailman/listinfo/python-list
Re: Tuple vs List: Whats the difference?
Shafik [EMAIL PROTECTED] writes: Hello folks, I am an experienced programmer, but very new to python (2 days). I wanted to ask: what exactly is the difference between a tuple and a list? I'm sure there are some, but I can't seem to find a situation where I can use one but not the other. Try mutating the tuple or using the list as a hashkey. 'as -- http://mail.python.org/mailman/listinfo/python-list
Re: Tuple vs List: Whats the difference?
On Jul 11, 12:05 pm, Alexander Schmolck [EMAIL PROTECTED] wrote: Shafik [EMAIL PROTECTED] writes: Hello folks, I am an experienced programmer, but very new to python (2 days). I wanted to ask: what exactly is the difference between a tuple and a list? I'm sure there are some, but I can't seem to find a situation where I can use one but not the other. Try mutating the tuple or using the list as a hashkey. 'as Cool thanks guys. --Shafik -- http://mail.python.org/mailman/listinfo/python-list
lists and dictionaries
Hi, I have a list of dictionaries. e.g. [{'index': 0, 'transport': 'udp', 'service_domain': 'dp0.example.com'}, {'index': 1, 'transport': 'udp', 'service_domain': 'dp1.example.com'}, {'index': 0, 'transport': 'tcp', 'service_domain': 'dp0.example.com'}, {'index': 1, 'transport': 'tcp', 'service_domain': 'dp1.example.com'}] how could I make a new list of dictionaries which would look like: [{'transports': ['udp','tcp'], 'service_domain': 'dp0.example.com'}, {'transports': ['udp','tcp'], 'service_domain': 'dp1.example.com'}] Could you help me, please? Lada -- http://mail.python.org/mailman/listinfo/python-list
Re: 2**2**2**2**2 wrong? Bug?
On Jul 11, 12:04 pm, David Jones [EMAIL PROTECTED] wrote: In fact, if I put (2**2)**2**2**2 it comes up with the correct answer, 4294967296 Actually, the correct answer (even by your own demonstration) is 65536. It might be easier to demonstrate if we chose a less homogeneous problem: 2**3**2. A right (rightly?) associative language (such as Python) reads this as 2**(3**2), or 2**9=512. A left-associative language (such as VB) reads this as (2**3)**2 or 8**2=64. As was pointed out earlier, left-associativity with exponentiation is of little value, since (2**3)**2 is the same as 2**(3*2) or 2**6=64. -- Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: lists and dictionaries
On Jul 11, 12:08 pm, Ladislav Andel [EMAIL PROTECTED] wrote: Hi, I have a list of dictionaries. e.g. [{'index': 0, 'transport': 'udp', 'service_domain': 'dp0.example.com'}, {'index': 1, 'transport': 'udp', 'service_domain': 'dp1.example.com'}, {'index': 0, 'transport': 'tcp', 'service_domain': 'dp0.example.com'}, {'index': 1, 'transport': 'tcp', 'service_domain': 'dp1.example.com'}] how could I make a new list of dictionaries which would look like: [{'transports': ['udp','tcp'], 'service_domain': 'dp0.example.com'}, {'transports': ['udp','tcp'], 'service_domain': 'dp1.example.com'}] You provide scant information for this task. For example, is the new list ordered or unordered? Can the list corresponding to the 'transports' key contain duplicates? Regardless, here's an example: li = [ {'index': 0, 'transport': 'udp', 'service_domain': 'dp0.example.com'}, {'index': 1, 'transport': 'udp', 'service_domain': 'dp1.example.com'}, {'index': 0, 'transport': 'tcp', 'service_domain': 'dp0.example.com'}, {'index': 1, 'transport': 'tcp', 'service_domain': 'dp1.example.com'}] group_by_service_domain = dict() for d in li: sd = d['service_domain'] nested_d = group_by_service_domain.setdefault(sd, {'service_domain': sd, 'transports': set()}) nested_d['transports'].add(d['transport']) new_li = [dict(transports=list(d['transports']), service_domain=d['service_domain']) for d in group_by_service_domain.values()] print new_li -- Hope this helps, Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: ImportError: MemoryLoadLibrary failed loading
On Jul 9, 12:47 pm, [EMAIL PROTECTED] wrote: Hi, Recently I began my journey into creating executables. I am using Andrea Gavana's cool GUI2EXE program which works very well and that is a GUI for py2ece. I am also using Inno Setup to create a script/executable. Anyway, today I am putting the program to the test with some volunteer testers and I've hit a wall. On the first tester's PC the program installed beautifully and runs great. The next tester's PC, the program failed to run complaining that MSVCR71.dll didn't exist. I copied that file on there and now I get the following traceback written to my exe's log file: Traceback (most recent call last): File reminder.py, line 23, in ? File zipextimporter.pyo, line 78, in load_module File wx\__init__.pyo, line 45, in ? File zipextimporter.pyo, line 78, in load_module File wx\_core.pyo, line 4, in ? File zipextimporter.pyo, line 91, in load_module ImportError: MemoryLoadLibrary failed loading wx\_core_.pyd I see other user's have this issue too sometimes and they talk a lot about a gdiplus.dll file. My user's PC has that file in 4 places on her computer and my development PC has it in 6 places. Does either DLL have to be in a specific location for the executable to find it? Is this something else entirely? I tried sticking the gdiplus.dll file in the directory my executable runs from too, but that didn't work either. I have posted this to the wxPython's group and the py2exe group, but the latter doesn't have much activity and the wxPython suggestions didn't work. Thanks a lot! Mike I figured this out, not that anyone probably cares. It seems the program was looking for MSVCP71.dll, but I (alas) included the MSVCR71.dll instead. If I include the correct file, it works. For all the newbs out there, spelling makes a difference! Mike -- http://mail.python.org/mailman/listinfo/python-list
Re: os.wait() losing child?
Jason Zheng [EMAIL PROTECTED] wrote: greg wrote: Jason Zheng wrote: Hate to reply to my own thread, but this is the working program that can demonstrate what I posted earlier: I've figured out what's going on. The Popen class has a __del__ method which does a non-blocking wait of its own. So you need to keep the Popen instance for each subprocess alive until your wait call has cleaned it up. The following version seems to work okay. It still doesn't work on my machine. I took a closer look at the Popen class, and I think the problem is that the __init__ method always calls a method _cleanup, which polls every existing Popen instance. The poll method does a nonblocking wait. If one of my child process finishes as I create a new Popen instance, then the _cleanup method effectively de-zombifies the child process, so I can no longer expect to see the return of that pid on os.wait() any more. The problem you are having is you are letting Popen do half the job and doing the other half yourself. Here is a way which works, done completely with Popen. Polling the subprocesses is slightly less efficient than using os.wait() but does work. In practice you want to do this anyway to see if your children exceed their time limits etc. import os import time from subprocess import Popen processes = [] counts = [0,0,0] for i in xrange(3): p = Popen('sleep 1', shell=True, cwd='/home', stdout=file(os.devnull,'w')) processes.append(p) print Starting child process %d (%d) % (i, p.pid) while (True): for i,p in enumerate(processes): exitstat = p.poll() pid = p.pid if exitstat is not None: break else: time.sleep(0.1) continue counts[i]=counts[i]+1 #terminate if count10 if (counts[i]==10): print Child Process %d terminated. % i if reduce(lambda x,y: x and (y=10), counts): break continue print Child Process %d terminated, restarting % i processes[i] = Popen('sleep 1', shell=True, cwd='/home', stdout=file(os.devnull,'w')) -- Nick Craig-Wood [EMAIL PROTECTED] -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list
Re: bool behavior in Python 3000?
Alan Isaac [EMAIL PROTECTED] wrote: Miles wrote: What boolean operation does '-' represent? Complementation. And as usual, a-b is to be interpreted as a+(-b). In which case the desired behavior is False-True = False+(-True)=False+False = False If you want to do algebra with bools in python then use the logical operators (and or not) and not the arithmetical operators. Eg False or not True False -- Nick Craig-Wood [EMAIL PROTECTED] -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list
Re: storing pickles in sql data base
David Bear [EMAIL PROTECTED] wrote: I need to store pickled objects in postgresql. I reading through the pickle docs it says to always open a file in binary mode because you can't be sure if the pickled data is binary or text. So I have 2 question. Can I set the pickle to be text -- and then store it in a 'text' type field in my sql table, or should what sql type should I save the pickle as? You could always encode it into text form, eg from cPickle import dumps, loads a = range(10) a [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] b = dumps(a).encode(zip).encode(base64).strip() b 'eJzTyCkw5PI04Er0NARiIyA2BmITIDYFYjMgNgdiCyC25ErUAwD5DQqD' loads(b.decode(base64).decode(zip)) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] -- Nick Craig-Wood [EMAIL PROTECTED] -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list
Re: binascii.unhexlify ... not clear about usage, and output
On Jul 11, 1:38 pm, Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote: On Wed, 11 Jul 2007 10:46:23 -0700, [EMAIL PROTECTED] wrote: You can with gmpy: import gmpy x = 0x0164 s = gmpy.digits(x,2) # convert to base 2 y = '0'*(16-len(s)) + s # pad to 16 bits y '000101100100' For the padding I'd use the `zfill()` method. In [15]: a = 0x0164 In [16]: gmpy.digits(a, 2).zfill(16) Out[16]: '000101100100' Ciao, Marc 'BlackJack' Rintsch Damn, I didn't know you could do that. If only there was a built-in base 2 conversion. -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with Python's robots.txt file parser in module robotparser
In article [EMAIL PROTECTED], John Nagle [EMAIL PROTECTED] wrote: Python's robots.txt file parser may be misinterpreting a special case. Given a robots.txt file like this: User-agent: * Disallow: // Disallow: /account/registration Disallow: /account/mypro Disallow: /account/myint ... the python library robotparser.RobotFileParser() considers all pages of the site to be disallowed. Apparently Disallow: // is being interpreted as Disallow: /. Even the home page of the site is locked out. This may be incorrect. This is the robots.txt file for http://ibm.com;. Hi John, Are you sure you're not confusing your sites? The robots.txt file at www.ibm.com contains the double slashed path. The robots.txt file at ibm.com is different and contains this which would explain why you think all URLs are denied: User-agent: * Disallow: / I don't see the bug to which you're referring: import robotparser r = robotparser.RobotFileParser() r.set_url(http://www.ibm.com/robots.txt;) r.read() r.can_fetch(WhateverBot, http://www.ibm.com/foo.html;) 1 r.can_fetch(WhateverBot, http://www.ibm.com//foo.html;) 0 I'll use this opportunity to shamelessly plug an alternate robots.txt parser that I wrote to address some small bugs in the parser in the standard library. http://NikitaTheSpider.com/python/rerp/ Cheers -- Philip http://NikitaTheSpider.com/ Whole-site HTML validation, link checking and more -- http://mail.python.org/mailman/listinfo/python-list
C Python Network Performance
Hello, I am writing an application bulk of which is sending and receving UDP data. I was evaluating which language will be a better fit for the job. I wrote following small pieces of code in Python and C respectively: from socket import * import sys if __name__ == '__main__': s = socket(AF_INET, SOCK_DGRAM) while True: s.sendto(hello, (sys.argv[1], int(sys.argv[2]))) #include sys/socket.h #include arpa/inet.h #include stdio.h #include string.h #include netinet/in.h #define true 1 #define false 0 int main(int len, char** args){ int s = socket(AF_INET, SOCK_DGRAM, 0); struct sockaddr_in s_addr; inet_pton(AF_INET, args[1], (s_addr.sin_addr)); printf(%s:%s\n, args[1], args[2]); in_port_t port; sscanf(args[2], %u, port); s_addr.sin_port = htons(port); s_addr.sin_family = AF_INET; char* msg = hello; int msg_len = 6; int addr_len = sizeof(struct sockaddr); struct sockaddr* s_g_addr = (struct sockaddr*) s_addr; while(true){ int success = sendto(s, msg, msg_len, 0, s_g_addr, addr_len); } } Both pieces of code, take IP address and port on command line initely send UDP messages to the target. In this experiment target is another machine of mine and I record the data rate received at that machine. I was surpirised to see that python code was able to achieve 4-10 times higher data rate than C. I was expecting C code to perform the same, if not better. Can anyone please explain why this is the case? Thanks Ghulam Memon - Building a website is a piece of cake. Yahoo! Small Business gives you all the tools to get online.-- http://mail.python.org/mailman/listinfo/python-list
RE: S2K DTS and Python
-Original Message- From: Tim Golden [mailto:[EMAIL PROTECTED] Sent: Tuesday, 10 July 2007 7:58 p.m. Cc: python-list@python.org Subject: Re: S2K DTS and Python Phil Runciman wrote: I am a Python newbie so please be gentle on me. Tim Golden replied: Welcome to Python. I have created a program that takes text files within a directory and it successfully parses the information from them to create 3 CSV files. Tim Golden replied: Good so far. However, I now want to update some tables in MSAccess, and it occurred to me that because Sequel Server 2000 DTS can interface with scripting languages that maybe I could call my first Python program from within DTS and then update the tables using DTS. (I am learning DTS hence the idea). Tim Golden replied: Unless you *really* wanted to learn DTS (and I don't find it that useful myself) then simply do this through Python... and have some fun at the same time :) My questions are: Has anyone used Python within DTS? Tim Golden replied: Haven't, but I wouldn't even try. Unless I were constrained by some kind of contractual binding, I wouldn't even *start* using DTS if I could use Python. I find it far too opaque. Thanks for your welcome Tim. I share your views and would much prefer to develop my Python expertise. :) However, I am tasked with learning DTS. It is OK, but really lacks conceptual clarity. IMHO I think it is a bit of a kludge, but better than nothing. It does get rid of a lot of donkey-work even if its diagrams are more of an aide-de-memoir than anything else. Am I off the wall trying such a thing? No, but I think it's easier to use the csv module, pyodbc [1] and either code the SQL directly, which is what I tend to do, or use one of the several SQL-ORM-style wrappers around: SQLObject[2], sqlalchemy[3] and its friend Elixir[4], or the newly-advertised Storm[5] from Canonical. Feel free to post back with questions or progress. TJG [1] http://pyodbc.sf.net [2] http://www.sqlobject.org/ [3] http://sqlalchemy.org [4] http://elixir.ematia.de/ [5] https://storm.canonical.com/ -- http://mail.python.org/mailman/listinfo/python-list
RE: S2K DTS and Python
-Original Message- From: stefaan [mailto:[EMAIL PROTECTED] Sent: Wednesday, 11 July 2007 6:47 a.m. To: python-list@python.org Subject: Re: S2K DTS and Python However, I now want to update some tables in MSAccess, and it occurred to me that because Sequel Server 2000 DTS can interface with scripting languages that maybe I could call my first Python program from within DTS and then update the tables using DTS. (I am learning DTS hence the idea). I have never heard about DTS, so I cannot advise you on that. But since you mentioned MsAccess, I want to mention that I have successfully used the DejaVu object relational mapper[1] to access MsAccess databases. Other ORMs like SqlObject and SqlAlchemy - to the best of my knowledge - do not support MsAccess out of the box (yet?). [1] http://projects.amor.org/docs/dejavu/1.5.0RC1/ Thanks for your reply Stefaan. I will file away that information. It looks useful. -- http://mail.python.org/mailman/listinfo/python-list
Re: bool behavior in Python 3000?
Ed Leafe [EMAIL PROTECTED] wrote in message news:[EMAIL PROTECTED] | I think that the assignability to the names 'True' and 'False' is | incorrect, or at the very least subject to all sorts of odd results. It is necessary for 2.x to not break older code. I believe they will somehow be reserved, like None, in 3.0. tjr -- http://mail.python.org/mailman/listinfo/python-list
Re: 2**2**2**2**2 wrong? Bug?
On 7/11/07, Paul McGuire [EMAIL PROTECTED] wrote: On Jul 11, 12:04 pm, David Jones [EMAIL PROTECTED] wrote: In fact, if I put (2**2)**2**2**2 it comes up with the correct answer, 4294967296 Actually, the correct answer (even by your own demonstration) is 65536. It might be easier to demonstrate if we chose a less homogeneous problem: 2**3**2. A right (rightly?) associative language (such as Python) reads this as 2**(3**2), or 2**9=512. A left-associative language (such as VB) reads this as (2**3)**2 or 8**2=64. As was pointed out earlier, left-associativity with exponentiation is of little value, since (2**3)**2 is the same as 2**(3*2) or 2**6=64. It doesn't have anything to do with the language being left/right associative, it has to do with the operators in question. For example, subtraction is always left associative -- you would be really surprised if 3 - 2 - 1 evaluated to 2. Python happens to choose right associativity for exponentiation because it is more useful for that operator, but that doesn't make the language itself right associative. -- Evan Klitzke [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: asyncore and OOB data
In article [EMAIL PROTECTED], billiejoex [EMAIL PROTECTED] writes: In an asyncore based FTP server I wrote I should be able to receive OOB data from clients. A client sending such kind of data should act like this: import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('127.0.0.1', 21)) s.sendall('hello there\r\n', socket.MSG_OOB) According to asyncore documentation I should handle this kind of event in handle_expt method of dispatcher class, that should be called when OOB is received by the underlying socket. I've tried to override handle_expt method in such way: def handle_expt(self): print OOB data arrived data = self.socket.recv(1024, socket.MSG_OOB) print data ...but, even if it is called, data contains only a \n character instead of the entire string (hello there\r\n). Why does this happen? Should I have to use a different approach? You should use a different approach, but first you need to read the relevant documentation. I've never used asyncore, but when I look at the documentation, the only reference that I find to OOB says: Called when there is out of band (OOB) data for a socket connection. This will almost never happen, as OOB is tenuously supported and rarely used. That should be fair warning. Second, when I look at the FTP specification, I don't find the concept of OOB anywhere. So, it's not clear what OOB data would mean in terms of the defined FTP commands in any case. Third, the TCP protocol, which you have selected via the SOCK_STREAM option doesn't support OOB at all, so there's no way that you can even send OOB data in the manner that you are expecting. Let's switch to the positive, however. What TCP does have is the concept of urgent data. Urgent data is data that the sender believes is so important that the receiver should discard intermediate data, if necessary, in order to process the urgent data -- but the urgent data is sent *in-band*. In the case of FTP, the concept of urgent data is used to allow the user side to interrupt the data transfer, which it does by sending an ABOR command. The underlying problem is that the server might be blocked on a receive on the data connection and not listening for commands on the control connection. So the user side is required to perform some special action that includes sending urgent data, which the server can then process specially. This problem arises primarily in systems without either threading or asynchronous I/O APIs. Your use of asyncore should alleviate this problem. The thing that may be confusing you is that for whatever reason the designers of the Berkeley socket API (which is what you are using when running under POSIX/Linux/MS Windows), chose to use the OOB flags (e.g., MSG_OOB) to indicate the *transmission* of OOB data -- but it's not really OOB data. In fact, when I attempt to receive using the MSG_OOB flag using the OS interfaces on my system, I get back an error (EINVAL - Invalid argument). I would expect that asyncore would report this error somehow or other. In summary, you almost certainly can't use the concept of a separate OOB channel to transfer data in an FTP environment. If you really, really need something like this, you will need to extend the FTP protocol for your special purposes. - dmw -- . Douglas Wells . Connection Technologies . . Internet: -sp9804- -at - contek.com- . -- http://mail.python.org/mailman/listinfo/python-list