Re: [Tutor] os.listdir blocks threads?
Hello, first, I believe listdir is implemented so as to block other threads because underlying C functions are *not* thread safe ! So if you try reading two directories in two different threads you may end up with really strange things happening ! For your process problem, if you want to have full control of the process while abstracting the pipe things, you may want to use the popen2 module and, more precisely, the Popen3 or Popen4 objects that will give you access to the PID. However, be aware that functions involving PID are always OS-dependant. So you may want to abstract it a bit to call UNIX, Windows or OS-X functions depending on the current plateform. Pierre Wolfgang Braun a écrit : Hello List, I try to read large directories off network shares (samba3,NT) with os.listdir(). The listdir() takes up to 5 minutes and blocks the rest of the program (gui refreshes, ...) The idea now is to put the listdir call into a separate thread so the program can go on doing stuff (see below). Unfortunately, as soon as I start a rdir instance the whole python process locks up and waits for the os.listdir to return. Plan b was to popen('/bin/ls -1 '%dir) in the rdir thread which works better but is a bit kludgy (needs to work on NT, too) and the program cannot be shudown cleanly unless the rdir thread has finished. Obviously I'm doing something wrong? What would be the Right Way to handle this situation? Thanks, Wolfgang # --- skeleton listdir in a thread class rdir(threading.Thread): def __init__(self,dir,glob=None): super(rdir,self).__init__() self.dir=dir self.content=() def start(self): self.setDaemon(True) super(dircache,self).start() def run(self): self.content=os.listdir(self.dir) # alternatively os.popen(' /bin/ls -1U '%dir) # stuff to keep run() from returning ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77fax : (33) 4 67 61 56 68 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Importing Modules Within Classes
Kent Johnson a écrit : Daniel Watkins wrote: [...] However, someone (I don't recall who) said that there were occasions when it would be appropriate to import modules the former way. I was just wondering under what circumstances importing should be done this way? That was me. I nest imports quite frequently in Jython code where the first import of a module is fairly expensive in time. Putting the import in the function that needs it delays the import and perhaps the module won't be imported at all. import is an executable statement. When it runs, the interpreter first looks to see if the module has already been imported. If so, the existing module is bound to the import name in the current namespace. If the module has not yet been imported, it is loaded *and executed*, then bound to the name in the current namespace. So if module A imports B which imports C and D, then importing A will also load and execute B, C and D. If any of these are time-consuming you may want to defer them. I found with my Jython programs that I could shorten start-up time quite a bit by deferring some imports until they were needed. Another reason for the nested style of imports is to resolve problems with circular imports. There are some subtle problems that can occur when A imports B and B imports A. By nesting one of the imports you can defer it and sometimes avoid the problem. In this case I think removing the circular import is a much better solution - circular dependencies are evil! A third reason is not to load module that will probably not be used :) In my code, I have objects that have geometrical representations. My objects can produce images of themselves using differente libraries. Some are huge and takes time and memory to load ... also one specific user will probably use only one such library at a time (and will probably load it before ...) As each function run is quite time consuming, adding the module check is not a problem also ! (never import a module in a small function likely to be called in an inner-loop !) Pierre -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77fax : (33) 4 67 61 56 68 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] stopping threads?
Hello Marcus, Marcus Goldfish a écrit : I'm a little confused about threading in Python. Here is a sample class I've written for monitoring for events. Included in the comments are a couple of questions, specifically: (1) can I use super() in the constructor, or is direct call to base class preferred? IMO, it is better to explicitely call the base class ... I think it is more readable. But I don't know if there is any drawback for any solution... (2) do I need to sleep in the run() method? If so, why? It seems to improve my programs responsiveness Yes, you need to sleep ! What you're doing is called polling, you have an infinite loop watching some state. If you don't wait, you'll use your processor 100% for ... nothing ! Global responsiveness will decrease as your program will always ask the OS for run-time ! Now, if you sleep, you will test the state once, let other threads/process run and watch some other time... 0.1 sec is quite a long time for processes and so short for us ;) So if you need human-time responsiveness, you definitely need this sleep. However, you may consider other way of blocking/watching like using events or semaphors. So that your thread will be blocked until someone releases it by sending the event or releasing the semaphor. (3) what happens after run() finishes-- does the thread die, get suspended, go away? Should I try to force the thread into one of these states, and if so how? Yop ! after run() finishes, the thread dies. This is the normal way to finish a thread ... just end its main function :) Any help is appreciated! Thanks, Marcus class Monitor(threading.Thread): def __init__(self): threading.Thread.__init__(self) # would super() also work here? which is preferred self.undetected = True # presumably, when the event occurs it sets this attribute to False def run(self): print looking for event while self.undetected is True: time.sleep(0.1) # another minor point: why do I need to sleep here? self.processEvent() # what happens here-- does the thread die? def processEvent(self): print yeah-- event detected ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77fax : (33) 4 67 61 56 68 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Aschenputtel problem
Well, in the specific case of numeric arrays, you can use Numeric or numarray : from Numeric import array, compress ol = array(original_list) selection = array([condition(i) for i in original_list) list1 = compress(selection, ol) list2 = compress(!selection, ol) Even better, if condition can be expressed directly on the matrix itself (which is pretty common with Numeric/numarray): ol = array(original_list) selection = condition(ol) list1 = compress(selection, ol) list2 = compress(!selection, ol) Remember: if you have complex index operations on arrays of numbers, Numeric (and even more numarray) contains a lot of very usefull efficient functions. Pierre Christopher Arndt a écrit : Hi, I wonder if there is a shorter form of the following idiom: list1 = [] list2 = [] for item in original_list: if condition(item): list1.append(item) else: list2.append(item) (optional step:) original_list[:] = list1 I call this the Aschenputtel problem, because it is described by the famous quote from the fairy tale as told by the Grimm brothers: Die guten ins Töpfchen, die schlechten ins Kröpfchen. (The good ones in the pot, the bad ones in the crop) Chris ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77fax : (33) 4 67 61 56 68 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Aschenputtel problem - Shorter is not better?
cinderella1 ist the traditional approach, cinderella3 builds up a list of positives and then checks that against the original list by using the in operator. This scales very badly for longer lists, as you can see in the second timing. cinderella7 ist the Numeric approach proposed by Pierre Barbier de Reuille. It doesn't compare very well, probably because it has to iterate 3 times over the original list and once more over the list of positives. The solution using sets (cinderella4) seems to do very well too, but has several limitations: - does not preserver order of elements - elements must be unique - only available from Python 2.3 I leave it as an axcercise to the reader to try how the different soltutions behave when condition(item) is more expansive (i.e takes longer). Chris -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77fax : (33) 4 67 61 56 68 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Multiple Simultaneous Loops
You have a much simpler solution ! As this is a most common task to iterate on a sequence while keeping track of the index, there is an object just for that : for i,x in enumerate(iterable): # Here i is the index and x the element Also, to get some advance iteration schemes, have a lot at the module itertools ... there is a bunch of very usefull items in it (the most usefull to me bzing izip) ! Pierre Pujo Aji a écrit : assume: you have two list with the same size L1 = [1,2,3] L2 = [11,22,33] you can zip the L1 and L2 into L L = zip(L1,L2) # L = [(1,11),(2,22),(3,33)] then you can process: for x in L: dosomething(x[0])... dosomething(x[1])... I'm not so sure about your problem but If you want to do something parallel processing then you should go to threading or pyro. Cheers, pujo -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77fax : (33) 4 67 61 56 68 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] [tutor] threading problem in GUI
Great :) Just to be clear about that: you can see the connect line as a dynamic registration process (with the symetric disconnect operation available via ... disconnect). The only thing you need is to connect (at runtime) the even before it's called (obvious isn't it ? ;) ), but you have no other constraint. You can even choose to connect/disconnect events when they are used/unused ... You can also connect a single event many times (to different functions) or you can connect many events to the same function. This is the power of this system :) Like now if you want to log your strings on a file, you just define the function writing in the file and connect the event to this function: you'll have both the GUI and the log-file outputs ! This is, AFAIK, the best existing implementation for user interfaces ! Pierre nephish a écrit : Pierre Barbier de Reuille wrote: nephish a écrit : one more thing. if i uncomment the lines gtk.threads_enter() and gtk.threads_leave() the whole thing locks up when the function is called. the gui, and the thread both lock up. Well, that's just normal. However, what you should do is to send a signal from your thread with the text to append in your textbuffer. Then, you catch the signal in your main widget to show it ! To emit a signal use : gtk.gdk.threads_enter() self.emit(writing, str) gtk.gdk.threads_leave() To catch it: emitting_object.connect(writing, self.method_handling_to_signal) Well, I used that and it just work ! Using the signal does not solve any threading problem but allow you to separate between the event and the answer to the event, which is a good habit to take ! Pierre I finally got it working !! thanks so much for all your help i would not have gotten it working without you, (or this mailing list) God bless shawn -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77fax : (33) 4 67 61 56 68 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] threading problem in GUI
Ok, comments inside your code ... nephish a écrit : Pierre Barbier de Reuille wrote: nephish a écrit : Pierre Barbier de Reuille wrote: [...] ok, i am still having a little problem understanding. tried it but i don't know if i have things set in the right order. gtk.gdk.threads_init() # Here initialize what you want [...] # Launch the Gtk loop gtk.gdk.threads_enter() # Unneeded if you don't want to call GUI # functions from other threads gtk.main() gtk.gdk.threads_leave() # Needed only with threads_enter at the part where you wrote # Here initialize what you want [...] is that where i define the function that will run the thread? i get the part about having the enter and leave i just seem to have a hang up (so to speak) with where the function gets defined. do i need to build it as a class like the example in the link you sent? Well, no you don't need to create a class. As for the place where to put your function, it's not a problem, [...] is the place where you will *execute* some initialization code (if needed) before you launch your interface. That's all (typically that's where you will instanciate your widgets). thanks for your help on this Your welcome, Pierre ok, i am still kinda stuck. im posting what i think is necessary, because the whole thing is rather long. so here goes. #!/usr/bin/python import os import time from time import strftime import sys import gtk import pygtk import serial import threading from threading import Thread import tokenize import gtk.glade import weakref import inspect import re gtk.gdk.threads_init() def main(self): gtk.gdk.threads_enter() gtk.main() gtk.gdk.threads_leave() def on_StartEnginesButton_clicked(self, widget, *args): print on_StartEnginesButton_clicked called with self.%s % widget.get_name() Input1Iter = self.Input1Buffer.get_end_iter() Input2Iter = self.Input2Buffer.get_end_iter() Input1Data = 'Reading Serial device ttyS14 \n' Input2Data = 'Reading Serial device ttys15 \n' self.Input1Buffer.insert(Input1Iter, Input1Data) self.Input2Buffer.insert(Input2Iter, Input2Data) time.sleep(2) def Serial1(): print 'running serial 1' ser = serial.Serial('/dev/ttyS15', 2400, timeout=None) loopy = 1 i = 1 while loopy 5: for x in range(5): i = i + 1 a = ser.read(1)#read one byte a = ord(a) # change byte to integer if (a 64 )or (a 127): breakb = ser.read(1) b = ord(b) if (b 64 )or (b 127): break c = ser.read(1) c = ord(c) if c 92: break d = ser.read(1) d = ord(d) if d 128: break Sensor_ID = (a 63) + (b 63) * 64 + (c 1) * 4096 Status = (c 62) / 2 + (d 63) * 32 c = int(c) d = int(d) x_Now = strftime('%Y-%m-%d %H:%M:%S') gtk.threads_enter() Input1Data = str(Sensor_ID)+'\t'+str(Status)+'\t-\t'+x_Now+'\n' Input1Iter = self.Input1Buffer.get_end_iter() self.Input1Buffer.insert(Input1Iter, Input1Data) gtk.threads_leave() f = open('/home/piv/PivData/tmp/Serial/'+str(i), 'w') f.write(str(Sensor_ID)+'\n'+str(c)+'\n'+str(d)+'\n'+str(Status)+'\n'+x_Now) f.close() Thread.start(Serial1()) hehehe ... got it ! Serial1() just call the function ... it will be evaluated and then the result will be sent to Thread.start ... So try: Thread.start(Serial) thanks, i am learning from several sources. two books from O'Reilly, and a dozen or so websites, not everybody does everything the same way . if something here looks alarming, please let me know. thanks -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77fax : (33) 4 67 61 56 68 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Is there an easy way to combine dictionaries?
Is this what you want ? c = dict(a) c.update(b) Pierre Lane, Frank L a écrit : Hi List, Is there an easy way to combine dictionaries? e.g. a = {} b = {} a = {'a':'a', 'b':'b', 'c':'c'} b = {'1':1, '2':2, '3':3} c = a + b # doesn't seem to work desired: c = {'a':'a', 'b':'b', 'c':'c', '1':1, '2':2, '3':3} Thanks, Frank ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77fax : (33) 4 67 61 56 68 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] threading problem in GUI
nephish a écrit : Hello there ! Hello, i am having a problem with threading. OK, i have this GUI app that i am building with pygtk. there is a process (four actually, just working on getting one right now) that needs to run in the background. Please, do not mix process and threads ... there very different ... you're talking about threads here, so you want Threads to run in the background ... there is a button that starts the background function. But, it locks up the gui. it doesn't run in the background, it locks everything up. It still runs though. That's just normal ... if you read PyGtk documentation, you'll see you need to initialise PyGtk to handle threads : http://www.async.com.br/faq/pygtk/index.py?req=index - 20. The GTK Mainloop and Threading http://www.async.com.br/faq/pygtk/index.py?req=showfile=faq20.006.htp - This is exactly your problem ! http://www.pygtk.org/pygtk2reference/gdk-functions.html#function-gdk--threads-init This is done like this : # First call to PyGtk function ever gtk.gdk.threads_init() # Here initialize what you want [...] # Launch the Gtk loop gtk.gdk.threads_enter() # Unneeded if you don't want to call GUI # functions from other threads gtk.main() gtk.gdk.threads_leave() # Needed only with threads_enter one of the things this background process is to do is updata a viewable area on the GUI. Now when run from a terminal, when i hit CTRL+C it stops the thread, but doesnt kill the GUI, and the TextView gets updated right then with everything it should have gotten before. def Serial1(): print 'running serial 1' ser = serial.Serial('/dev/ttyS15', 2400, timeout=None) loopy = 1 i = 1 while loopy 5: x_Now = strftime('%Y-%m-%d %H:%M:%S') i = i + 1 a = ser.read(1)#read one byte a = ord(a) # change byte to integer if (a 64 )or (a 127): continue b = ser.read(1) b = ord(b) if (b 64 )or (b 127): continue c = ser.read(1) c = ord(c) if c 92: continue d = ser.read(1) d = ord(d) if d 128: continue Sensor_ID = (a 63) + (b 63) * 64 + (c 1) * 4096 Status = (c 62) / 2 + (d 63) * 32 c = int(c) d = int(d) x_Now = strftime('%Y-%m-%d %H:%M:%S') f = open('/home/piv/PivData/tmp/Serial/'+str(i), 'w') Input1Data = str(Sensor_ID)+'\t'+str(Status)+'\t-\t'+x_Now+'\n' Input1Iter = self.Input1Buffer.get_end_iter() self.Input1Buffer.insert(Input1Iter, Input1Data) f.write(str(Sensor_ID)+'\n'+str(c)+'\n'+str(d)+'\n'+str(Status)+'\n'+x_Now) f.close() thread.start_new(Serial1()) the code may not be best form, i am still fairly new at this. so i am also open to any constructive critisism. thanks shawn ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77fax : (33) 4 67 61 56 68 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Instance attribute as a parameter's default value
Jan Eden a écrit : Hi, Jan Eden wrote on 26.08.2005: Hi, I need to use an instance attribute as the default value for a parameter to a method. This obviously won't work: page.Children() def Children(self, id=self.id, level=2): How can I get the id parameter to use the attribute page.id? I know I could simply use the method call page.Children(id=page.id) but I thought it is much more elegant to use a default value here. Is it possible? Addition: I do use def Children(self, id=0, level=2): if not id: id = self.id right now. But still - there has to be a smarter way. Well, I prefer the use of None for that, as it cannot be mixed up with any other value: def Children(self, id=None, level=2): if id is None: id = self.id Another possibility (mainly if you have many such arguments) is the use of something like: def Children(self, **kwords): id = kwords.pop(id, None) level = kwords.pop(level, 2) Although it is not equivalent ! In the second cases, you have to name the parameter to set it ! But I sometimes find this A Good Thing (tm) when no argument order is better ... Pierre -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77fax : (33) 4 67 61 56 68 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Generate 8 digit random number
Is 0 a valid digit for your password ? If the answer is YES then, remember that the 0 at the left of a number are juste removed ! In that case, try writing your password with : %08d % password Pierre Alberto Troiano a écrit : Hi everyone I need to generate a password..It has to be an 8 digit number and it has to be random The code I've been trying is the following: import random random.randrange(,) The code works but sometimes it picks a number with 7 digits. Is there any way that I can tell him to select always a random number with 8 digits? Thanks in advanced Alberto ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77fax : (33) 4 67 61 56 68 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Source PC MAC address
The problem is: you cannot do that using the socket interface as the OS IP stack will drop all the ethernet informations. However, you can ask the network explicitly for the MAC address handling some IP address: the protocol is called ARP (RFC 826). To do so, the Python package dpkt (http://www.monkey.org/~dugsong/dpkt/) might be interesting for you (although I never used it ...) as it includes a module to handle ARP requests. Pierre PS: do not forget to send your answers to Python Tutor also ... BTW, could it be possible de configure the list so that the reply-to field is set to the Python Tutor list instead of the sender ? Johan Geldenhuys a écrit : Is there a other way of doing this? Getting the MAC. I am on a ethernet network. Johan Sujet: Re: [Tutor] Source PC MAC address Expéditeur: Pierre Barbier de Reuille [EMAIL PROTECTED] Date: Wed, 24 Aug 2005 17:00:46 +0200 Destinataire: Python Tutor tutor@python.org Destinataire: Python Tutor tutor@python.org Return-Path: [EMAIL PROTECTED] Received: from earth.accesstel.co.za ([unix socket]) by earth (Cyrus v2.1.9) with LMTP; Wed, 24 Aug 2005 16:59:09 +0200 X-Sieve: CMU Sieve 2.2 Received: by earth.accesstel.co.za (Postfix, from userid 65534) id F00D011DD9; Wed, 24 Aug 2005 16:59:08 +0200 (SAST) Received: from localhost.localdomain (localhost [127.0.0.1]) by earth.accesstel.co.za (Postfix) with ESMTP id 11EF911DD9 for [EMAIL PROTECTED]; Wed, 24 Aug 2005 16:59:08 +0200 (SAST) Received: from smtp-vbr1.xs4all.nl (smtp-vbr1.xs4all.nl [194.109.24.21]) by gateway.azitech.co.za (8.11.6/8.11.6) with ESMTP id j7OEnmr23311 for [EMAIL PROTECTED]; Wed, 24 Aug 2005 16:49:49 +0200 Received: from bag.python.org (bag.python.org [194.109.207.14]) by smtp-vbr1.xs4all.nl (8.13.3/8.13.3) with ESMTP id j7OEvApb033830; Wed, 24 Aug 2005 16:57:10 +0200 (CEST) (envelope-from [EMAIL PROTECTED]) Received: from bag.python.org (bag [127.0.0.1]) by bag.python.org (Postfix) with ESMTP id DA7B61E400F; Wed, 24 Aug 2005 16:57:15 +0200 (CEST) X-Original-To: tutor@python.org Received: from bag.python.org (bag [127.0.0.1]) by bag.python.org (Postfix) with ESMTP id 5382C1E4003 for tutor@python.org; Wed, 24 Aug 2005 16:57:13 +0200 (CEST) Received: from bag (HELO bag.python.org) (127.0.0.1) by bag.python.org with SMTP; 24 Aug 2005 16:57:13 +0200 Received: from auvergne.cirad.fr (auvergne.cirad.fr [195.221.173.145]) by bag.python.org (Postfix) with ESMTP for tutor@python.org; Wed, 24 Aug 2005 16:57:13 +0200 (CEST) Received: from auvergne.cirad.fr (auvergne.cirad.fr [195.221.173.145]) by auvergne.cirad.fr (8.13.2/8.13.2) with ESMTP id j7OEsnoG028104 for tutor@python.org; Wed, 24 Aug 2005 16:54:49 +0200 Received: from [195.221.175.162] ([EMAIL PROTECTED] [195.221.175.162]) by auvergne.cirad.fr (8.13.2/8.13.2) with ESMTP id j7OEsmMS028090 for tutor@python.org; Wed, 24 Aug 2005 16:54:48 +0200 ID du Message: [EMAIL PROTECTED] Agent utilisateur: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7.6) Gecko/20050817 Thunderbird/1.0.2 Mnenhy/0.7 X-Accept-Language: fr, en Version de MIME: 1.0 Références: [EMAIL PROTECTED] In-Reply-To: [EMAIL PROTECTED] X-Enigmail-Version: 0.91.0.0 X-BeenThere: tutor@python.org X-Mailman-Version: 2.1.6 Precedence: list List-Id: Discussion for learning programming with Python tutor.python.org List-Unsubscribe: http://mail.python.org/mailman/listinfo/tutor, mailto:[EMAIL PROTECTED] List-Archive: http://mail.python.org/pipermail/tutor List-Post: mailto:tutor@python.org List-Help: mailto:[EMAIL PROTECTED] List-Subscribe: http://mail.python.org/mailman/listinfo/tutor, mailto:[EMAIL PROTECTED] Content-Type: text/plain; charset=iso-8859-15 Expéditeur: [EMAIL PROTECTED] Errors-To: [EMAIL PROTECTED] X-Virus-Scanned: by XS4ALL Virus Scanner X-Accesstel-MailScanner-Information: Please contact Accesstel for information X-Accesstel-MailScanner: Found to be clean X-MIME-Autoconverted: from quoted-printable to 8bit by gateway.azitech.co.za id j7OEnmr23311 X-Fetched: by SuSE Linux Openexchange Server from [EMAIL PROTECTED] for [EMAIL PROTECTED] via pop X-Spam-Status: No, hits=-7.6 required=4.8 tests=AWL,BAYES_01,IN_REP_TO,QUOTED_EMAIL_TEXT,REFERENCES, REPLY_WITH_QUOTES,SIGNATURE_LONG_SPARSE, USER_AGENT_MOZILLA_UA autolearn=ham version=2.55 X-Spam-Checker-Version: SpamAssassin 2.55 (1.174.2.19-2003-05-19-exp) Content-Transfer-Encoding: 8bit Socket is built up on IP, not on Ethernet: you have no way of finding a MAC address using sockets simply because it may not exist one ! (if you're not on an Ethernet network) You need to access lower levels of network and probably access directly the network packet as your network card is sending it to your OS ! Pierre Johan Geldenhuys a écrit : Hi List, I am doing some networking programming and would like to limit access to my
Re: [Tutor] cPickle usage
Jorge Louis de Castro a écrit : Hi, [Sorry for the repost, there was a typo previously] I think I may have misinterpreted the syntax of cPickle. I have dumped data onto a file using: [...] I thought I could unpickle this using the load feature, something like: inFile = codecs.open(.\\+self.filename, r) cPickle.load(self.terms, inFile) cPickle.load(self.username, inFile) cPickle.load(self.age, inFile) cPickle.load(self.gender, inFile) cPickle.load(self.totalMsgs, inFile) cPickle.load(self.occurrences, inFile) self.terms = cPickle.load(inFile) self.username = cPickle.load(inFile) ... should work better :) Which would unpickle the data onto the variables. It does not work like that, unfortunately. When I try reading the whole file I only get the first object read as output. Any ideas how to achieve what this? chrs j. -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77fax : (33) 4 67 61 56 68 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Source PC MAC address
Socket is built up on IP, not on Ethernet: you have no way of finding a MAC address using sockets simply because it may not exist one ! (if you're not on an Ethernet network) You need to access lower levels of network and probably access directly the network packet as your network card is sending it to your OS ! Pierre Johan Geldenhuys a écrit : Hi List, I am doing some networking programming and would like to limit access to my socket server on the the source devices' MAC address. I know the IP from where the connection is coming, but how could I find out what the MAC of the source device is? Any quick answers / ideas? Is there a build-in function in socket that can do this? Thanks, Johan ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77fax : (33) 4 67 61 56 68 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Thread deamon
Well, I don't know how it works on Windows, but on UNIX, if you want to create a deamon able to stay alive when you deconnect you just have to catch the HUP signal and ... do nothing of it :) By default this signal exit the application. You have two ways of doing so : 1 - use the standard signal handling to intercept the SIGHUP signal and ignore it 2 - launch your program using nohup : $ nohup my_prg In both cases it should stay alive after the death of the terminal. Pierre Jorge Louis de Castro a écrit : Hi, Anyone knows how to setDaemon(True) or pass it as an argument to start_new_thread() with the code snippet below? server.listen(1) thread.start_new_thread(run_server,(server,)) Otherwise the thread stops running when I close the telnet client (even using Unix's operator for background running) chrs j. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77fax : (33) 4 67 61 56 68 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] String formatting
Jorge Louis De Castro a écrit : Hi, I'm slighty confused with python's string formatting operators. Why is it that this prints as a string: channel, info = server.accept() print Connection from, info And this doesn't? channel, info = server.accept() print Connection from %s % info Well, when using the % operator on string always put a tuple or a dictionnary on the RHS : print Connection from %s % (info,) Like that, even if info is iterable you'll have the representation of info and not of its first element (if it has only one) and an error if it has more. Also, anyone knows how do I pass arguments to a logger? logger.debug(Connection from:, args) thanks and chrs j. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77fax : (33) 4 67 61 56 68 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] String formatting
Kent Johnson a écrit : Pierre Barbier de Reuille wrote: [...] Well, when using the % operator on string always put a tuple or a dictionnary on the RHS : print Connection from %s % (info,) No, you can put a single item on the right without putting it in a tuple: print 'x = %s' % 3 x = 3 I never said it does not work, but I say it is Bad Practice (TM). The reason (as I already explained) is, if the variable suddently happen to become a tuple the semantic of your print statement will change ! Just try that if you're not convinced : def foo(x): ... print x = %s % x foo(3) foo((3,)) foo((1,2,3)) Now, if you change the function with : def foo(x): ... print x = %s % (x,) It will always work as intended ! And when you're debugging this is *very* important ! Pierre -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77fax : (33) 4 67 61 56 68 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How do I make Python calculate square roots?
Or, you can use: complex(-1)**0.5 However the result is strange ... complex(-1)**0.5 (6.1230317691118863e-17+1j) Pierre Danny Yoo a écrit : On Sat, 2 Jul 2005, Reed L. O'Brien wrote: Does anyone know how to make Python calculate square roots? Raise to the 1/2 power. 4**.5 2.0 16**.5 4.0 81**.5 9.0 By the way, if you need to take the square roots of negative numbers, then the 'sqrt' function in the cmath module should do the trick: ## (-1)**0.5 Traceback (most recent call last): File stdin, line 1, in ? ValueError: negative number cannot be raised to a fractional power import cmath cmath.sqrt(-1) 1j ## Best of wishes! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77fax : (33) 4 67 61 56 68 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Changing what you've already printed
Well, it is certainly possible. First, the hard way: you use the ANSI termainal control commands (you can find the reference on the web, or if you need it I can send you an HTML file containing them). Second, the better way: you can use the ncurse library (via the curses Python module). There you'll get a whole toolkit for TUI (Terminal User Interface ;) ). BTW, if you happen to need this while drawing only a single line, the \r char gets you at the beginning of the current line ! So flushing stdout and then sending the \r char will allow you to overwrite the current line. Pierre Ed Singleton a écrit : Is it possible (and easy) to change something you've already printed rather than print again? For example, if I'm making a little noughts and crosses game and I print the board: | | | | ___|___|___ | | | | ___|___|___ | | | | | | Then the computer has it's go, and rather than print the board out again and have the previous empty board appear higher up, I want to just add a X to the board I've already created. Eg. | | | | ___|___|___ | | | X | ___|___|___ | | | | | | I've programs do this on the command line in Linux, so I assume it must be possible. (I don't mind making my programs Linux only so that's not a problem). Any clues or pointers to documentation gratefully recieved. Thanks Ed ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77fax : (33) 4 67 61 56 68 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] help: threading + cron in python?
Ok, there is an easy way :) You can write something like : from datetime import datetime import time def run_at( t, fct, fct_args = (), fct_words = {}): now = datetime.today() delta = (t-now).minutes time.sleep(delta) fct(*fct_args, **fct_kwords) Now you can just launch this function in a new thread :) It will wait the wanted time and launch the function at that moment ! Pierre Aaron a écrit : Lets say you have a threaded program. Is there any way to make it so that an operation occurs at a certain time every hour (eg) like the cron daemon? I'm afraid I don't really understanding threading enought to make this work.. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77fax : (33) 4 67 61 56 68 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] python's bash wait and ampersand equivalent?
I do not understand why you don't want the so simple fork/exec pattern ! In UNIX programming this is the way to go ... I cannot think of anything simpler than that : for i in xrange( 10 ): pid = os.fork() if not pid: os.execv( /bin/echo, [ echo, toto ] ) try: while True: os.wait() except OSError: pass print all done I fear that python programming is a little less process-oriented than shells ... but then, it is just normal for an all-purpose language (or at least an all-purpose wanna-be language ;) ). Pierre chumpy town a écrit : Hello all, I am trying to convert from bash to python for scripting. What is the simplest cleanest way to do the following in python: #!/bin/bash for i in `seq 1 1000` do my-other-script done wait echo all done I at first tried os.system(my-other-script ) and os.wait() but this caused os.wait() to throw an exception and say no child processes. Alternatively, I know I can use os.fork(), os.exec() and os.wait() but this seems cumbersome. As a second alternative, os.spawnlp() and os.wait() works, but I need to additionally redirect the spawned process' stdout to the spawnee's stdout, etc. - again an extra step. Experienced python programmers, what's the best thing to do here? Thanks a lot! -david ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77fax : (33) 4 67 61 56 68 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] one line code
[EMAIL PROTECTED] a écrit : This is a perfect opportunity to give the reminder that the conversion functions are also types that can be used more transparently for such Neat I didn't know\ that. How dioes Python equate a function object to a type? Is it hard wired? No, you see it the wrong way ! int is a type, not a function ! But, in Python, types append to be callable (ie. to behave like functions). For example when you define a class Foo with : class Foo: def __init__(self): pass Foo is a type but you can also *call* Foo with : f = Foo() But this construct an object (and involves many function calls) and is not a simple function call. So there is no need to hardwire that kind of things (even if it _may_ be hardwired to improve efficiency). -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77fax : (33) 4 67 61 56 68 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] [HELP]how to test properties of a file
Tthe simplest, IMHO, is : try: f = file(filename, w) [...] except IOError: print The file is not writable Of course, not that this method empty the file if it is writable ! The best is to just put your IO code in such a try block ... That way, you're sure the file has the right mode. If you don't want to open the file to detect its mode, then you need to use the os and stat modules together ... Pierre Shidai Liu a écrit : Dear all, Here is a simple question. But I can't find a simple answer. How to test if a file is readable, executalbe or writable, especially, writable? -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77fax : (33) 4 67 61 56 68 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] primes
Gregor Lingl a écrit : Hi! Who knows a more concise or equally concise but more efficient expression, which returns the same result as [x for x in range(2,100) if not [y for y in range(2,x) if x%y==0]] Gregor P.S.: ... or a more beautiful one ;-) ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor The fastest know way for your problem is the Eratosten sieve ... Here's an implementation : from sets import Set from math import sqrt def sieve( max ): max_val = int( sqrt( max ) ) s = Set(xrange( 4, max, 2 )) for i in xrange( 3, max_val, 2 ): s.update( xrange( 2*i, max, i ) ) return [ i for i in xrange( 2, max ) if i not in s ] I compared with the implementations of Gregor (optimized) and Max and here is the result : listPrimes(10)= 0.637619972229 (Max implementation) primeConciseOptimized(10) = 2.9141831398 (Gregor optimized) sieve(10) = 0.49525809288 (Eratosten sieve) You'll just notice that Eratosten sieve is O(n) space consumption when others are less (I don't remember the density of prime numbers :o) ) were n is the maximum number you're looking for. Pierre -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77fax : (33) 4 67 61 56 68 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Re: How do you share a method (function) among several objects?
Well, for me, the more logical answer is : multi-inheritance ! If part of your class is the same, (same semantic, same implementation), then you want to have a base class for that. If you dislike this kindof inheritance, then your function should be an external one. Even more because it's 'just' an implementation function. The user don't need it as a method ... So why bother add it to your object ? Pierre Xif a écrit : Javier Ruere wrote: Xif wrote: Hello There are several different objects. However, they all share the same function. Since they are not the same or similar, it's not logical to use a common superclass. So I'm asking, what's a good way to allow those objects to share that function? The best solution I've found so far is to put that function in a module, and have all objects import and use it. But I doubt that's a good use-case for modules; writing and importing a module that contains just a single function seems like an abuse. Thanks, Xif Could you give an example? Javier ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor +++ This Mail Was Scanned By Mail-seCure System at the Tel-Aviv University CC. Sure, I can describe my particular case. It's a program that retrieves / updates Microsoft Excel spreadsheet data. There are two major classes: 1) an Excel class, that represents of the whole Excel program 2) a Cells class, that abstracts retrieval and editing of cells. Both classes use a function called getCells() as part of their __getitem__() methods. getCells() parses the __getitem__() call arguments, and returns an iterator over the appropriate cells. The difference between the 2 classes is that a Cells instance just converts the generator into a list and returns it: #code return list(getCells(self.sheet, cells)) #/code while an Excel instance returns the values of the cells: #code return [cell.Value for cell in getCells(self.sheet, cells)] #/code As you can see, both use the getCells() function. So my question is, where is the best way to put it so instances of both classes can use it? Xif ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77fax : (33) 4 67 61 56 68 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Re: How do you share a method (function) among several objects?
The position to put it is a design choice and there is no single best solution. What I'd do is to gather all the small homeless functions in a single separate module. And if they come to be too numerous, I'll sort them in some modules, ... But that's because I don't like having a single function in a module ^_^ Of course, if this is a complex function, that can make sense ... I hope I helped and didn't make things worst ;) Pierre Xif a crit : Ok, so keeping getCells() as an external function makes sense. But where exactly do you recommend I'd put it? In a seperate module, like I currently do, even though it's going to be the only piece of code contained inside that module? Xif Pierre Barbier de Reuille wrote: Well, for me, the more logical answer is : multi-inheritance ! If part of your class is the same, (same semantic, same implementation), then you want to have a base class for that. If you dislike this kindof inheritance, then your function should be an external one. Even more because it's 'just' an implementation function. The user don't need it as a method ... So why bother add it to your object ? Pierre Xif a crit : Javier Ruere wrote: Xif wrote: Hello There are several different objects. However, they all share the same function. Since they are not the same or similar, it's not logical to use a common superclass. So I'm asking, what's a good way to allow those objects to share that function? The best solution I've found so far is to put that function in a module, and have all objects import and use it. But I doubt that's a good use-case for modules; writing and importing a module that contains just a single function seems like an abuse. Thanks, Xif Could you give an example? Javier ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor +++ This Mail Was Scanned By Mail-seCure System at the Tel-Aviv University CC. Sure, I can describe my particular case. It's a program that retrieves / updates Microsoft Excel spreadsheet data. There are two major classes: 1) an Excel class, that represents of the whole Excel program 2) a Cells class, that abstracts retrieval and editing of cells. Both classes use a function called getCells() as part of their __getitem__() methods. getCells() parses the __getitem__() call arguments, and returns an iterator over the appropriate cells. The difference between the 2 classes is that a Cells instance just converts the generator into a list and returns it: #code return list(getCells(self.sheet, cells)) #/code while an Excel instance returns the values of the cells: #code return [cell.Value for cell in getCells(self.sheet, cells)] #/code As you can see, both use the getCells() function. So my question is, where is the best way to put it so instances of both classes can use it? Xif ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77fax : (33) 4 67 61 56 68 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Trivia program.
Mmmhh ... one very simple way would be to replace your first line by : name = raw_input(Hi. What's your name? ) + But if you want to keep the name as it is, I bet the best way is to replace your second line by : called = .join([ name for i in xrange(5) ]) The advantage of this second method is theis added only *between* the names, and not after ... Pierre . Sm0kin'_Bull a écrit : Hi, I got a problem with this program. name = raw_input(Hi. What's your name? ) called = name * 5 print \nIf a small child were trying to get your attention, \ your name would become: print called When i input the name like John Goodman it prints like... John GoodmanJohn GoodmanJohn GoodmanJohn GoodmanJohn Goodman But i want to print it like... John Goodman John Goodman John Goodman John Goodman John Goodman How can I do it? Express yourself instantly with MSN Messenger! MSN Messenger http://g.msn.com/8HMBEN/2728??PS=47575 Download today it's FREE! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77fax : (33) 4 67 61 56 68 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Re: print out lines that start with a word
Wolfram Kraus a écrit : Liam Clarke wrote: regexes are common across a lot of languages, even Java has them. Though the pain that would be I daren't not imagine. So the syntax is familiar, whereas string methods may not be. But IMHO string methods are (more) explicit and readable, the name tells you what the method is doing. I know that sometimes regexp are really fine, e.g. extracting something from html or maybe speed issues (can anyone enlighten me on that one?), but for simple task like the OP's problem I'd always use string methods. Wolfram I completely agree ! Then, it will very probably be more efficient. And the methods (or functions) like startwith are avalaible in almost every string library ! Pierre -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77fax : (33) 4 67 61 56 68 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hex to Str - still an open issue
, Liam Clarke On Fri, 4 Feb 2005 23:30:19 -0500, Jacob S. [EMAIL PROTECTED] wrote: The binary value is the same as the hex value. The binary representation is 00010100, but unfortunately Python doesn't support binary in its string formatting(although it does in int()! Uh, question. Why not? It seems that all simple types should be included. Since the computer stores it as binary, why shouldn't python be able to display a string of it in binary? That seems to be a short coming that should be added to the next release... IMHO of course. Jacob Schmidt ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ## # binString.py # by Liam Clarke #(Let me know when it's included in the standard library ;-)) ## Converts a integer base 10 to a string base 2 def binary(decimalInt, bigEndian = True, bits = 32, truncExcess = False): Integer to be converted is essential, Endianess is an optional flag; me being a Win32 user, Endianess is big by default, defaults to a 32-bit representation, most integers in Python being 32 bit. truncExcess will strip place-holder zeros for succintness. Oh, and it will represent as 256, as I'm not sure whether you want to start counting for zero with this. It's a simple matter to change. tempList = ['0' for x in range(bits)] for bitPlace in range(bits, -1, -1): if decimalInt - 2**bitPlace = 0: tempList[bitPlace] = '1' decimalInt = decimalInt - 2**bitPlace if bigEndian: tempList.reverse() outPut = ''.join(tempList) if truncExcess: if bigEndian: outPut=outPut.lstrip('0') else: outPut=outPut.rstrip('0') return outPut ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77fax : (33) 4 67 61 56 68 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Match on current line and next line. Possible?
MMmh ... one way to do that : Py file_content = open('/somefile', 'r').readlines() Py next_file_content = iter(file_content) Py next_file_content.next() Py for (line, next_line) in izip(file_content, next_file_content): Py match_one = re.search('^Python', line) Py match_two = re.search('^\tBLAH', line) Py if match_one and nextline == match_two: Pydo_something() Pierre Tom Tucker a écrit : Hello! How can I instruct Python to match on the current line and the next line? Assumptions; - We are reading in one line at a time BROKEN EXAMPLE (discussion) ## file = open('/somefile','r').readlines() for line in file: match_one = re.search('^Python', line) match_two = re.search('^\tBLAH', line) if match_one and nextline == match_two: do_something() Maybe this just isn't possible, since we are working line by line. Any suggestions? Tom ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77fax : (33) 4 67 61 56 68 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] This Deletes All my Files
Ok, so in Python, arguments are evaluated first, left to right ! The outer-most function used in your sample is : file.write(self, filename, mode) So the first argument evaluated is self ... and in your case self is open(item, 'w') so the first thing your line does is opening for writing the file named by item and as w empty the file ... you can read it afterward, it will be empty ! Pierre PS: general in programs: do NEVER rely on arguments evaluation order, unless you have no other choices and you are damn sure of what you're doing. In any case, do NEVER do that if you're no expert in the programming language used. Chad Crabtree a écrit : I've tried this and I cannot figure out why this does not work. I figure this has something to do with order of operations. I figured someone would know exactly why it doesn't work. Wouldn't this start inside parens then from left to right? open(item,'w').write(open(item,'r').read().replace('nbsp;','')) I tried this on the shell just trying to do some quick text replacement because I could figure out how to get awk to do it, and I didn't want to spend 5 hours RTFM. I got it to work by breaking it up to several statements, but I would like to know. __ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77fax : (33) 4 67 61 56 68 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Hex to Str
Given you have a number in 'a' : hex(a) returns the hexadecimal representation of 'a' as a string ! You can also try : %x % a After that, I don't know if there is some builtin to print a number in any base you want ! Pierre Tamm, Heiko a écrit : Hello, I like to know, if it's possible to convert a Hex number into String or other formats? How can it be done? Kind regards Heiko ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77fax : (33) 4 67 61 56 68 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to sum rows and columns of a matrix?
Even better : import numarray m = numarray.arange(16,shape=(4,4)) numarray.sum(m) array([24, 28, 32, 36]) numarray.sum(axis=1) array([ 6, 22, 38, 54]) Pierre Kent Johnson a écrit : Kent Johnson wrote: Liam Clarke wrote: There's a specific package for arrays http://www.stsci.edu/resources/software_hardware/numarray that implements array mathematics. I use it for pixel map manipulation in pygame, so it's relatively fast. Here is one way to do what you want using numarray: Here is another way, probably more idiomatic and faster. (I'm just doodling with numarray so there may still be a better way to do this...) import numarray m=numarray.array(range(16),shape=(4,4)) numarray.add.reduce(m) array([24, 28, 32, 36]) numarray.add.reduce(m, axis=1) array([ 6, 22, 38, 54]) Kent -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77fax : (33) 4 67 61 56 68 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] class instance with identity crisis
My opinion is : this is a very dangerous and stupid thing to do !!! Try to imagine the complexity of your program for someone who is trying to understand how your code is working if an object suddenly change its own type !!! Clearly, if you want to change the type of an object, you want a conversion method (or function) and creates a new object (that's what you'll do anyway). If you don't need the old object anymore, you can just reuse the variable name. Then, it's impossible to achieve in Python (at least in the general case ... you could do it with pure Python objects). And I hope it will forever remain impossible ! And last, I think you misunderstood the behaviour of the assignment statement in Python. In no way an assignement will overwrite an existing value. It will simply make the variable assigned point on another object. The consequence is, if there are many variables pointing on the same object, reassigning one of them will not affect the other ones. So when you write self = Prune() you don't change the variable the user holds but only the local self variable, variable that will disappear at the end of the method and so your Prune object will be discarded. I hope my last paragraph is clear (but I don't think so :D). Pierre Barnaby Scott a écrit : This is probably a very easy question, and one that I was shocked to find I was stuck on, having thought I understood classes! I was wondering how you can get an instance of a class to change itself into something else (given certain circumstances), but doing so from within a method. So: class Damson: def __str__(self): return 'damson' def dry(self): self = Prune() class Prune: def __str__(self): return 'prune' weapon = Damson() weapon.dry() print weapon All the old hands will of course know this will produce the output damson but something in me suggests it should produce prune After all, 'self' refers to the instance 'weapon'. Obviously one could reassign weapon to a Prune outside the class definition, but I was hoping to write something in which, given certain circustances arising, the instance would change itself into something else. Time to go back to school! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Pierre Barbier de Reuille INRA - UMR Cirad/Inra/Cnrs/Univ.MontpellierII AMAP Botanique et Bio-informatique de l'Architecture des Plantes TA40/PSII, Boulevard de la Lironde 34398 MONTPELLIER CEDEX 5, France tel : (33) 4 67 61 65 77fax : (33) 4 67 61 56 68 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor