From carroll at tjc.com Wed Dec 1 00:07:12 2004 From: carroll at tjc.com (Terry Carroll) Date: Wed Dec 1 00:07:16 2004 Subject: [Tutor] Timer() (was: (no subject) In-Reply-To: Message-ID: On Wed, 1 Dec 2004, Liam Clarke wrote: > Do you need to use the threading module? Or are you using solely the timer? I was wondering that too, as a general case. What is the advantage of having a facility to delayedly start a thread? I'd expect that this could be done just as effectively, in the rare case it's needed, by just putting a sleep() call in the thread. Why would you ever need something like Timer() ? From jeffpeery at yahoo.com Wed Dec 1 00:10:10 2004 From: jeffpeery at yahoo.com (Jeff Peery) Date: Wed Dec 1 00:10:14 2004 Subject: [Tutor] (no subject) In-Reply-To: Message-ID: <20041130231010.49921.qmail@web60107.mail.yahoo.com> that will work! thanks. just for reference, how do variables pass between functions and nested functions? Liam Clarke wrote: Hi, Do you need to use the threading module? Or are you using solely the timer? You could do a - import time while 1: time.sleep(30) dataBack=update() if dataBack: #process data That would be an infinite loop, and would rely on update returning None or similar if no update had occurred. I hope that helps in a small way. Regards, Liam Clarke On Tue, 30 Nov 2004 14:04:45 -0800 (PST), Jeff Peery wrote: > > hello again, > > I am thoroughly confused. I am using Timer from the threading module. I want > to check a specific file every few minutes to see if it has been altered (I > do this by checking the size of the file using stat) if it hasn't then I do > nothing, if it has then I attempt to read the file, grab all the new > numerical data and update a graph on my computer. > > this file I am reading holds liquid volumetric flow rate measurement data > and the python code I am writing is to be used as a statistical process > control. basically I watch the results from the measurements by watching a > particular file for updates, when an update occurs I grab the data do some > more stats, then update my graphs that show on my desktop. > > the timer I used is a class, so I defined a new object (I think thats the > right word) as: > > myTimer = Timer(30.0, Update) > > where the timer runs every 30 seconds and Update is a function that checks > if the file has been altered and if so then it updates my graphs. I then > start the timer: > > myTimer.start() > > I am confused by two things: > 1) I want my timer to restart every 30 seconds. as it shows above it will go > just one time. If I put this in a while loop, will the while loop loop > through the start command faster than 30 second intervals or will it wait > for the timer to execute the Update function before calling timer.start() > again? > 2) I am also confused about how variables are handled when I have multiple > and nested functions. for example, I would like to initiate the Update > function every 30 seconds and I want the Update funtion to return any new > data. how can I return something from a function when the function is called > from a timer? I cannot do an assignment statement from within the > definnition of myTimer? or do I even need to return the data? if I create a > variable in the update function is it available in my main function? I am > not sure how python handles variables that are defined in different > functions. > > thank you very much for spending the time to help me, I appreciate it! > > Jeff > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041130/3eeed30f/attachment.html From jeffpeery at yahoo.com Wed Dec 1 00:10:10 2004 From: jeffpeery at yahoo.com (Jeff Peery) Date: Wed Dec 1 00:10:15 2004 Subject: [Tutor] (no subject) In-Reply-To: Message-ID: <20041130231010.49921.qmail@web60107.mail.yahoo.com> that will work! thanks. just for reference, how do variables pass between functions and nested functions? Liam Clarke wrote: Hi, Do you need to use the threading module? Or are you using solely the timer? You could do a - import time while 1: time.sleep(30) dataBack=update() if dataBack: #process data That would be an infinite loop, and would rely on update returning None or similar if no update had occurred. I hope that helps in a small way. Regards, Liam Clarke On Tue, 30 Nov 2004 14:04:45 -0800 (PST), Jeff Peery wrote: > > hello again, > > I am thoroughly confused. I am using Timer from the threading module. I want > to check a specific file every few minutes to see if it has been altered (I > do this by checking the size of the file using stat) if it hasn't then I do > nothing, if it has then I attempt to read the file, grab all the new > numerical data and update a graph on my computer. > > this file I am reading holds liquid volumetric flow rate measurement data > and the python code I am writing is to be used as a statistical process > control. basically I watch the results from the measurements by watching a > particular file for updates, when an update occurs I grab the data do some > more stats, then update my graphs that show on my desktop. > > the timer I used is a class, so I defined a new object (I think thats the > right word) as: > > myTimer = Timer(30.0, Update) > > where the timer runs every 30 seconds and Update is a function that checks > if the file has been altered and if so then it updates my graphs. I then > start the timer: > > myTimer.start() > > I am confused by two things: > 1) I want my timer to restart every 30 seconds. as it shows above it will go > just one time. If I put this in a while loop, will the while loop loop > through the start command faster than 30 second intervals or will it wait > for the timer to execute the Update function before calling timer.start() > again? > 2) I am also confused about how variables are handled when I have multiple > and nested functions. for example, I would like to initiate the Update > function every 30 seconds and I want the Update funtion to return any new > data. how can I return something from a function when the function is called > from a timer? I cannot do an assignment statement from within the > definnition of myTimer? or do I even need to return the data? if I create a > variable in the update function is it available in my main function? I am > not sure how python handles variables that are defined in different > functions. > > thank you very much for spending the time to help me, I appreciate it! > > Jeff > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041130/3eeed30f/attachment.htm From jeff at ccvcorp.com Wed Dec 1 01:38:32 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed Dec 1 01:34:28 2004 Subject: [Tutor] Timer() In-Reply-To: References: Message-ID: <41AD1288.3010104@ccvcorp.com> Terry Carroll wrote: > I was wondering that too, as a general case. What is the advantage of > having a facility to delayedly start a thread? I'd expect that this could > be done just as effectively, in the rare case it's needed, by just putting > a sleep() call in the thread. I believe that it's just a convenience function. Note that (I presume) Timer doesn't so much start a thread after a particular delay, as it does start a thread which waits for a period of time and then runs a function. You could easily define a function that takes a time parameter and another callable, and sleeps before calling the latter, and then use that function as a Thread's target. In fact, I'm presuming that that's exactly what Timer does. It's just a bit more convenient to have it already done for you. And I can think of a number of potential uses for such a thing, though I haven't needed it myself. For example, it could be used for an autosave feature -- wait five minutes (or however long) and then save the current data/document. Jeff Peery wrote: > 1) I want my timer to restart every 30 seconds. as it shows above it > will go just one time. If I put this in a while loop, will the while > loop loop through the start command faster than 30 second intervals > or will it wait for the timer to execute the Update function before > calling timer.start() again? One way of handling this is to have Update() call Timer(30, Update) again before it ends. Each Update() event schedules the next one. Jeff Shannon Technician/Programmer Credit International From hugonz-lists at h-lab.net Wed Dec 1 00:16:17 2004 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Wed Dec 1 01:47:04 2004 Subject: [Tutor] Cannot cPickle.load() Message-ID: <41ACFF41.4010206@h-lab.net> Hi Tutors, I think I must be missing something here. I pickled a dictionary of lists into a file, using protocol 2, some weeks ago. Now I'm trying to load it and I can't. File is 21kB long, so I know it has data in it, and when I read it into a string (without pickling) I understand the pickle is there. Here's my log: IDLE 1.0.3 >>> import cPickle >>> import pickle >>> myfilep=open("e:\Devel\listpickled", "r") >>> myfilep >>> mydict = cPickle.load(myfilep) Traceback (most recent call last): File "", line 1, in -toplevel- mydict = cPickle.load(myfilep) EOFError >>> myfilep.tell() 4096L >>> myfilep.seek(0) >>> mydict= pickle.load(myfilep) Traceback (most recent call last): File "", line 1, in -toplevel- mydict= pickle.load(myfilep) File "C:\Python23\lib\pickle.py", line 1390, in load return Unpickler(file).load() File "C:\Python23\lib\pickle.py", line 872, in load dispatch[key](self) File "C:\Python23\lib\pickle.py", line 1189, in load_binput i = ord(self.read(1)) TypeError: ord() expected a character, but string of length 0 found >>> myfilep.tell() 512L >>> myfilep.seek(0) >>> mystring = myfilep.read() >>> mystring '\x80\x02]q\x01(U\x05Aaronq\x02U\x04Abelq\x03U\x08Abelardoq\x04U\x07Abelinoq\x05U\x07Abigailq\x06U\x07Abrahamq\x07U\x05Abrilq\x08U\x06Abundiq\tU\x03Adaq\nU\x05Adahiq\x0bU\x06Adalayq\x0cU\tAdalbertoq\rU\x08Adalgisaq\x0eU\x06Adalidq\x0fU\x07Adamariq\x10U\x04Adelq\x11U\x05Adelaq\x12U\x08Adelaidaq\x13U\x07Adelinaq\x14U\x06Adizonq\x15U\x06Adolfoq\x16U\x06Adonayq\x17U\x06Adrianq\x18U\x07Adrianaq\x19U\x04Ad\xe1nq' >>> #But this is not the full contents of the file! >>> myfilep.tell() 20480L >>> len(mystring) 257 >>> mystring = myfilep.read() >>> len(mystring) 157 >>> mystring = myfilep.read() >>> len(mystring) 0 >>> #ok, done with the reading >>> I cannot make any sense of it. Both implementations of load() tell me they're encountering EOF right away. If I use read, there's the pickled data, but I cannot read the entire file into the variable. Please help if possible. I don't know what elese to do... (!) Hugo From hugonz-lists at h-lab.net Wed Dec 1 01:47:26 2004 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Wed Dec 1 01:47:30 2004 Subject: [Tutor] Cannot cPickle.load() Message-ID: <41AD149E.80907@h-lab.net> Hi Tutors, I think I must be missing something here. I pickled a dictionary of lists into a file, using protocol 2, some weeks ago. Now I'm trying to load it and I can't. File is 21kB long, so I know it has data in it, and when I read it into a string (without pickling) I understand the pickle is there. Here's my log: IDLE 1.0.3 >>> import cPickle >>> import pickle >>> myfilep=open("e:\Devel\listpickled", "r") >>> myfilep >>> mydict = cPickle.load(myfilep) Traceback (most recent call last): File "", line 1, in -toplevel- mydict = cPickle.load(myfilep) EOFError >>> myfilep.tell() 4096L >>> myfilep.seek(0) >>> mydict= pickle.load(myfilep) Traceback (most recent call last): File "", line 1, in -toplevel- mydict= pickle.load(myfilep) File "C:\Python23\lib\pickle.py", line 1390, in load return Unpickler(file).load() File "C:\Python23\lib\pickle.py", line 872, in load dispatch[key](self) File "C:\Python23\lib\pickle.py", line 1189, in load_binput i = ord(self.read(1)) TypeError: ord() expected a character, but string of length 0 found >>> myfilep.tell() 512L >>> myfilep.seek(0) >>> mystring = myfilep.read() >>> mystring '\x80\x02]q\x01(U\x05Aaronq\x02U\x04Abelq\x03U\x08Abelardoq\x04U\x07Abelinoq\x05U\x07Abigailq\x06U\x07Abrahamq\x07U\x05Abrilq\x08U\x06Abundiq\tU\x03Adaq\nU\x05Adahiq\x0bU\x06Adalayq\x0cU\tAdalbertoq\rU\x08Adalgisaq\x0eU\x06Adalidq\x0fU\x07Adamariq\x10U\x04Adelq\x11U\x05Adelaq\x12U\x08Adelaidaq\x13U\x07Adelinaq\x14U\x06Adizonq\x15U\x06Adolfoq\x16U\x06Adonayq\x17U\x06Adrianq\x18U\x07Adrianaq\x19U\x04Ad\xe1nq' >>> #But this is not the full contents of the file! >>> myfilep.tell() 20480L >>> len(mystring) 257 >>> mystring = myfilep.read() >>> len(mystring) 157 >>> mystring = myfilep.read() >>> len(mystring) 0 >>> #ok, done with the reading >>> I cannot make any sense of it. Both implementations of load() tell me they're encountering EOF right away. If I use read, there's the pickled data, but I cannot read the entire file into the variable. Please help if possible. I don't know what elese to do... (!) Hugo From cyresse at gmail.com Wed Dec 1 01:56:09 2004 From: cyresse at gmail.com (Liam Clarke) Date: Wed Dec 1 01:56:12 2004 Subject: [Tutor] (no subject) In-Reply-To: <20041130231010.49921.qmail@web60107.mail.yahoo.com> References: <20041130231010.49921.qmail@web60107.mail.yahoo.com> Message-ID: Not sure quite what you mean, but I guess you have def doThisFunc(firstVar, secondVar): #do something return aVar, anotherVar def aFunc(): (x, y)=doThisFunc(10,20) so aFunc calls doThisFunc and passes the variables, and assigns the returned results. You may also want to know this - (from Python Docs) Function call semantics are described in more detail in section 5.3.4. A function call always assigns values to all parameters mentioned in the parameter list, either from position arguments, from keyword arguments, or from default values. If the form ``*identifier'' is present, it is initialized to a tuple receiving any excess positional parameters, defaulting to the empty tuple. If the form ``**identifier'' is present, it is initialized to a new dictionary receiving any excess keyword arguments, defaulting to a new empty dictionary. **identifiers always go last. So, for instance def someMaths(*tupleONum): sum = 0 for item in tupleONum: sum + = item return sum print someMaths(1,2,3,4,5) 15 whereas normally - def sum2Numbers(numA, numB): sum = numA + numB return sum print sum2Numbers(1,2,3,4,5) will give an error. OK, I have a function - def hadOne(): x = x / 2 return x def doThis(): x=10 hadOne() will generate a 'unbound local variable' error for function hadOne(), as it doesn't grab the x automatically. You either need to - def doThis(): x = 10 global x hadOne() Which is bad, as globals mess up namespace badly. or def hadOne(x): x= x/2 print x return x def doThis(): x=10 x2=hadOne(x) print x, x2 will give - 5 10, 5 As you can see the 'x' within hadOne() is a different 'x' to the one within doThis(). You need to explicitly assign, or use globals. Try not to use globals. And within a class - class MyApp(bg): self.Bla=10 def aFunc(): print Bla - 5 def bFunc(): Bla = 7 print Bla - 7 x=MyApp() x.aFunc() will produce an error of 'variable Bla not found', whereas x.bFunc() will work fine. If you were to either do this - def aFunc(): print self.Bla -5 x.aFunc() would print 5 Or you could set up aFunc like so - def aFunc(Bla): print Bla - 5 x.aFunc(10) 5 print x.Bla 10 x.aFunc(x.Bla) 5 Confused yet? :D Basically each variable only exists within it's function, unless it's specifically a global or a self.var value in a class. So, the values have to be passed to functions and returned explicitly. And globals are bad. : ) Try using them repeatedly and see what Python has to say about that. And, I think you'd use the threading.Timer within a thread controlling module, so I'd assume that you wouldn't want to be receiving data back from the called function. (Experts? I'm guessing like crazy here.) Standard disclaimer - I know very little on this, a more concise and elegant method or example is likely to be posted, and you should always trust the advice of Danny Yoo, Kent Johnson, Alan Gauld, Bill Mill, and I'm sure I'm forgetting ten others. Oh, and check out Alan's excellent tutorial at http://www.freenetpages.co.uk/hp/alan.gauld/ I hope this helps, Liam Clarke On Tue, 30 Nov 2004 15:10:10 -0800 (PST), Jeff Peery wrote: > > that will work! thanks. > > just for reference, how do variables pass between functions and nested > functions? > > > > Liam Clarke wrote: > > > Hi, > > Do you need to use the threading module? Or are you using solely the timer? > > You could do a - > > import time > > while 1: > time.sleep(30) > dataBack=update() > if dataBack: > #process data > > That would be an infinite loop, and would rely on update returning > None or similar if no update had occurred. > > I hope that helps in a small way. > > Regards, > > Liam Clarke > > On Tue, 30 Nov 2004 14:04:45 -0800 (PST), Jeff Peery > wrote: > > > > hello again, > > > > I am thoroughly confused. I am using Timer from the threading module. I > want > > to check a specific file every few minutes to see if it has been altered > (I > > do this by checking the size of the file using stat) if it hasn't then I > do > > nothing, if it has then I attempt to read the file, grab all the new > > nume! rical data and update a graph on my computer. > > > > > > this file I am reading holds liquid volumetric flow rate measurement data > > and the python code I am writing is to be used as a statistical process > > control. basically I watch the results from the measurements by watching a > > particular file for updates, when an update occurs I grab the data do some > > more stats, then update my graphs that show on my desktop. > > > > the timer I used is a class, so I defined a new object (I think thats the > > right word) as: > > > > myTimer = Timer(30.0, Update) > > > > where the timer runs every 30 seconds and Update is a function that checks > > if the file has been altered and if so then it updates my graphs. I then > > start the timer: > > > > myTimer.start() > > > > I am confused by two things: > > 1) I want my timer to restart every 30 seconds. as it shows above it will > go > > just ! one time. If I put this in a while loop, will the while loop loop > > through the start command faster than 30 second intervals or will it wait > > for the timer to execute the Update function before calling timer.start() > > again? > > 2) I am also confused about how variables are handled when I have multiple > > and nested functions. for example, I would like to initiate the Update > > function every 30 seconds and I want the Update funtion to return any new > > data. how can I return something from a function when the function is > called > > from a timer? I cannot do an assignment statement from within the > > definnition of myTimer? or do I even need to return the data? if I create > a > > variable in the update function is it available in my main function? I am > > not sure how python handles variables that are defined in different > > functions. > > > > thank you very much for spending the time to help me, I appreciate it!! > > > > Jeff > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > -- > 'There is only one basic human right, and that is to do as you damn well > please. > And with it comes the only basic human duty, to take the consequences. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From cyresse at gmail.com Wed Dec 1 02:04:50 2004 From: cyresse at gmail.com (Liam Clarke) Date: Wed Dec 1 02:04:53 2004 Subject: [Tutor] Cannot cPickle.load() In-Reply-To: <41AD149E.80907@h-lab.net> References: <41AD149E.80907@h-lab.net> Message-ID: myfilep=open("e:\Devel\listpickled", "r") > >>> myfilep > > >>> mydict = cPickle.load(myfilep) Have you tried - mypick = pickle.Unpickler(myfilep) mydict =mypick.load() I think that's how you do it. On Tue, 30 Nov 2004 18:47:26 -0600, Hugo Gonz?lez Monteverde wrote: > > > Hi Tutors, > > I think I must be missing something here. I pickled a dictionary of > lists into a file, using protocol 2, some weeks ago. Now I'm trying to > load it and I can't. > > File is 21kB long, so I know it has data in it, and when I read it into > a string (without pickling) I understand the pickle is there. Here's my > log: > > IDLE 1.0.3 > >>> import cPickle > >>> import pickle > >>> myfilep=open("e:\Devel\listpickled", "r") > >>> myfilep > > >>> mydict = cPickle.load(myfilep) > > Traceback (most recent call last): > File "", line 1, in -toplevel- > mydict = cPickle.load(myfilep) > EOFError > >>> myfilep.tell() > 4096L > >>> myfilep.seek(0) > >>> mydict= pickle.load(myfilep) > > Traceback (most recent call last): > File "", line 1, in -toplevel- > mydict= pickle.load(myfilep) > File "C:\Python23\lib\pickle.py", line 1390, in load > return Unpickler(file).load() > File "C:\Python23\lib\pickle.py", line 872, in load > dispatch[key](self) > File "C:\Python23\lib\pickle.py", line 1189, in load_binput > i = ord(self.read(1)) > TypeError: ord() expected a character, but string of length 0 found > >>> myfilep.tell() > 512L > >>> myfilep.seek(0) > >>> mystring = myfilep.read() > >>> mystring > '\x80\x02]q\x01(U\x05Aaronq\x02U\x04Abelq\x03U\x08Abelardoq\x04U\x07Abelinoq\x05U\x07Abigailq\x06U\x07Abrahamq\x07U\x05Abrilq\x08U\x06Abundiq\tU\x03Adaq\nU\x05Adahiq\x0bU\x06Adalayq\x0cU\tAdalbertoq\rU\x08Adalgisaq\x0eU\x06Adalidq\x0fU\x07Adamariq\x10U\x04Adelq\x11U\x05Adelaq\x12U\x08Adelaidaq\x13U\x07Adelinaq\x14U\x06Adizonq\x15U\x06Adolfoq\x16U\x06Adonayq\x17U\x06Adrianq\x18U\x07Adrianaq\x19U\x04Ad\xe1nq' > >>> #But this is not the full contents of the file! > >>> myfilep.tell() > 20480L > >>> len(mystring) > 257 > >>> mystring = myfilep.read() > >>> len(mystring) > 157 > >>> mystring = myfilep.read() > >>> len(mystring) > 0 > >>> #ok, done with the reading > >>> > > I cannot make any sense of it. Both implementations of load() tell me > they're encountering EOF right away. If I use read, there's the pickled > data, but I cannot read the entire file into the variable. > > Please help if possible. I don't know what elese to do... (!) > > Hugo > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From cyresse at gmail.com Wed Dec 1 02:19:03 2004 From: cyresse at gmail.com (Liam Clarke) Date: Wed Dec 1 02:19:05 2004 Subject: [Tutor] comapring lists In-Reply-To: <6.2.0.14.0.20041129121822.02e22d80@mail.mric.net> References: <200411160439.XAA03967@webmail10.cac.psu.edu> <6.2.0.14.0.20041129121822.02e22d80@mail.mric.net> Message-ID: Looking at the two dictionaries, he's offsetting by 1? How about to encrypt - x="" y=raw_input('Enter phrase to crypt like') for item in y: a=ord(item)+1 x += chr(a) To decrypt - x1="" for item in x: a=ord(x)-1 x1 += chr(a) On Mon, 29 Nov 2004 12:30:40 -0700, Bob Gailer wrote: > At 09:39 PM 11/15/2004, Jim De Caro wrote: > > > >I am getting user input and comparing it to an iterated list. I can get the > >input to print out verbatim. I want to then "swap" individual letters in the > >input with letters from a second list so it is like a simple encryption. I > >can't figure out the correct logic or syntax. Here is what I have so far: > > > >user = raw_input("Enter your selection: ") > > > > > > > >encrypt = > >['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','0','1','2','3','4','5','6','7','8','9','0'] > > > >decrypt > >=['b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','a','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','A','0','1','2','3','4','5','6','7','8','9','0'] > > > > > >for i in range(len(encrypt)): > > print user[0:62] > > break > > > >for j in range(len(decrypt)): > > for j in zip(decrypt): > > print 'Encrypted-> %s' % (j,user) > > break > > > >This does not work. > > "does not work" is not helpful. We'd rather hear what results you are > getting (if any) and (if needed) how they differ from what you expect. > > The code above does nothing useful. It is hard to even begin to diagnose > it. But get rid of the break statements. They cause the loops to end after > 1 iteration. > > Is this a homework problem? > > Can you write a pseudocode version of what you think the program should > look like? > > Bob Gailer > bgailer@alum.rpi.edu > 303 442 2625 home > 720 938 2625 cell > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From rdm at rcblue.com Wed Dec 1 02:49:11 2004 From: rdm at rcblue.com (Dick Moores) Date: Wed Dec 1 02:49:24 2004 Subject: [Tutor] Problem with 2.4's IDLE Message-ID: <6.1.2.0.2.20041130174224.05213dc0@rcblue.com> I installed 2.4 today and find that when using its IDLE, File|Open opens to \Documents and Settings\Dick, a long ways from \Python24. Actually, I'd prefer \Python24\MyScripts. Same for File|Save. Is there a way to control this behavior? WinXP Thanks, Dick Moores rdm@rcblue.com From ARobert at MFS.com Wed Dec 1 02:50:22 2004 From: ARobert at MFS.com (Robert, Andrew) Date: Wed Dec 1 02:50:37 2004 Subject: [Tutor] The case of the missing close References: <968452DD78695147AA4A369C3DF9E40A01F942DF@BOSMAILBOX3.corp.mfs.com> <41ACD11B.1060002@h-lab.net> Message-ID: <968452DD78695147AA4A369C3DF9E40A22571F@BOSMAILBOX3.corp.mfs.com> Hi Hugo, That is a good suggestion. I tried doing the cursobj.close() in previous code but my DBA did a scan which showed the database still having inactive connections. On second thought though, that may have been a remanent from a previous failed attempt that did not clear. The example I sent was from one of my frustration periods were I just threw code at it to diagnose by errors generated. I'll get the connections cleared and try again. Thanks for the help Hugo. Much appreciated. Thank you, Andrew Robert Systems Architect Information Technologies Massachusetts Financial Services Phone: 617-954-5882 Pager: 781-764-7321 "MFS Relay Service" made the following annotations on 11/30/2004 08:56:02 PM ------------------------------------------------------------------------------ This email communication and any attachments may contain proprietary, confidential, or privileged information. If you are not the intended recipient, you are hereby notified that you have received this email in error and that any review, disclosure, dissemination, distribution or copying of it or its contents is prohibited. The sender does not waive confidentiality or any privilege by mistransmission. If you have received this email in error, please notify the sender immediately, delete this email, and destroy all copies and any attachments. ============================================================================== From tim.peters at gmail.com Wed Dec 1 02:54:02 2004 From: tim.peters at gmail.com (Tim Peters) Date: Wed Dec 1 02:54:07 2004 Subject: [Tutor] Cannot cPickle.load() In-Reply-To: <41ACFF41.4010206@h-lab.net> References: <41ACFF41.4010206@h-lab.net> Message-ID: <1f7befae04113017543bc2756e@mail.gmail.com> [Hugo Gonz?lez Monteverde ] > I think I must be missing something here. I pickled a dictionary of > lists into a file, using protocol 2, some weeks ago. Now I'm trying to > load it and I can't. > > File is 21kB long, so I know it has data in it, and when I read it into > a string (without pickling) I understand the pickle is there. Here's my > log: > > IDLE 1.0.3 > >>> import cPickle > >>> import pickle > >>> myfilep=open("e:\Devel\listpickled", "r") Change "r" to "rb" and try again. You're on Windows, pickles are binary files, and binary files must always be opened in binary mode on Windows. When you wrote the data to the file to begin with, I hope you opened the file in binary mode then too. Else the data in the file is corrupt now. From r2b2 at myway.com Wed Dec 1 03:36:45 2004 From: r2b2 at myway.com (Rene Bourgoin) Date: Wed Dec 1 03:36:56 2004 Subject: [Tutor] converting unicode Message-ID: <20041201023645.D78C5398C@mprdmxin.myway.com> Wandering how i could convert an entire tuple of unicode strings to python strings using str(u'string') stringtuple = () stringtuple = (u'string1',u'string2',u'string3') str(u stringtuple) # syntax problem here!!! thanks _______________________________________________ No banners. No pop-ups. No kidding. Make My Way your home on the Web - http://www.myway.com From maxnoel_fr at yahoo.fr Wed Dec 1 04:00:18 2004 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Wed Dec 1 04:00:45 2004 Subject: [Tutor] converting unicode In-Reply-To: <20041201023645.D78C5398C@mprdmxin.myway.com> References: <20041201023645.D78C5398C@mprdmxin.myway.com> Message-ID: <21C33588-4345-11D9-AC84-000393CBC88E@yahoo.fr> On Dec 1, 2004, at 02:36, Rene Bourgoin wrote: > > Wandering how i could convert an entire tuple of unicode strings to > python strings using str(u'string') > > stringtuple = () > stringtuple = (u'string1',u'string2',u'string3') > > str(u stringtuple) # syntax problem here!!! That's another job for my friends the list comprehensions! out = tuple([str(element) for element in stringtuple]) -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From kent37 at tds.net Wed Dec 1 04:03:21 2004 From: kent37 at tds.net (Kent Johnson) Date: Wed Dec 1 04:03:27 2004 Subject: [Tutor] comapring lists In-Reply-To: References: <200411160439.XAA03967@webmail10.cac.psu.edu> <6.2.0.14.0.20041129121822.02e22d80@mail.mric.net> Message-ID: <41AD3479.9080305@tds.net> If you want to stay within the same character set you need to do some wraparound at the ends, otherwise you have things like >>> chr(ord('9') + 1) ':' >>> chr(ord('Z') + 1) '[' Kent Liam Clarke wrote: > Looking at the two dictionaries, he's offsetting by 1? > > How about to encrypt - > > x="" > y=raw_input('Enter phrase to crypt like') > > for item in y: > a=ord(item)+1 > x += chr(a) > > To decrypt - > > x1="" > > for item in x: > a=ord(x)-1 > x1 += chr(a) > From isrgish at fastem.com Wed Dec 1 04:04:06 2004 From: isrgish at fastem.com (Isr Gish) Date: Wed Dec 1 04:04:29 2004 Subject: [Tutor] The case of the missing close Message-ID: <20041201030427.9E3311E4005@bag.python.org> Hi Robert, -----Original Message----- >From: "Robert, Andrew" >Sent: 11/30/04 11:05:57 AM >To: "tutor@python.org" >Subject: [Tutor] The case of the missing close >The problem is in closing the connection. > >No matter what I try, I receive an error stating that the name is not >defined. > >I receive an error such as: > >Traceback (most recent call last): > File "M:\My >Documents\python_code\oracle\maestrodev_oracle_connector.py", line 55, >in ? > db_utils.close() >AttributeError: 'module' object has no attribute 'close' The traceback is telling us exactly wats wrong. In the db_utils module you don't have a function called close. Therfore, when you call db_utils.close() it gives you an error. You probebly have to call close on the connection. But here I realy don't know anything about connections, so i cant help. All the best, Isr > >Does anyone have any ideas on how to properly close the connection? > > > >The db_utils module code is a rather short > > >def dbopen(db,uname,passwd): > # > # Import required system modules needed specifically for function > # > import cx_Oracle > > # > # Connect to remote database > # > connection = cx_Oracle.connect(dsn=db,user=uname,password=passwd) > > # > # Return cursor object to calling program > # > return(connection.cursor()) > > >The code that calls the db_utils module is > >#!c:\Python23\python ># ># File name: maestrodev_oracle_connector.py ># Author: Andrew Robert ># Date: 11/26/04 ># ># ># Modification History ># ># Version Programmer Description ># 1.0 AAR Creation ># 1.1 AAR Shift database opens to called >module ># 1.2 AAR Fixed database link close - now >works ># ># ># Note on modules ># ># The imported db_utils module was designed by AAR to make standard >database ># routines available to all python programs as callable functions. ># ># Called functions are prefaced with the module name and then the >function ># within the module. ># > > >import sys,db_utils > ># ># Make connection to Oracle development database and assign to object ># > >print 'Establishing connection to remote database\n' >cursobj = db_utils.dbopen('test_d','FOO','foo') > ># ># Formulate sample querry ># >cursobj.execute('SELECT userid, name, role, desk_phone, pager FROM >contacts') > ># ># Extract querry results ># >results=cursobj.fetchall() > >for row in results: > print row > ># ># Break connection to Oracle development database ># >print '\n\n\nDisconnecting from remote database' > >db_utils.close() > >raw_input("\n\n\t\tPress Enter To Continue") > > >Any help you can provide on this would be greatly appreciated. > > > > >Thank you, >Andrew Robert >Systems Architect >Information Technology >Massachusetts Financial Services >Phone: 617-954-5882 >Pager: 781-764-7321 >E-mail: arobert@mfs.com >Linux User Number: #201204 > > >"MFS Relay Service" made the following > annotations on 11/30/2004 11:11:35 AM >------------------------------------------------------------------------------ >This email communication and any attachments may contain proprietary, confidential, or privileged information. If you are not the intended recipient, you are hereby notified that you have received this email in error and that any review, disclosure, dissemination, distribution or copying of it or its contents is prohibited. The sender does not waive confidentiality or any privilege by mistransmission. If you have received this email in error, please notify the sender immediately, delete this email, and destroy all copies and any attachments. >============================================================================== > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > From carroll at tjc.com Wed Dec 1 04:05:33 2004 From: carroll at tjc.com (Terry Carroll) Date: Wed Dec 1 04:05:37 2004 Subject: [Tutor] converting unicode In-Reply-To: <20041201023645.D78C5398C@mprdmxin.myway.com> Message-ID: On Tue, 30 Nov 2004, Rene Bourgoin wrote: > Wandering how i could convert an entire tuple of unicode strings to python strings using str(u'string') > > stringtuple = () > stringtuple = (u'string1',u'string2',u'string3') > > str(u stringtuple) # syntax problem here!!! >>> stringtuple = (u'a', u'bcd', u'e') >>> ''.join(stringtuple) u'abcde' Interestingly, this is one area where string.join() gets a different result: >>> from string import join >>> stringtuple = (u'a', u'bcd', u'e') >>> join(stringtuple) u'a bcd e' I'm not sure why that would be. From carroll at tjc.com Wed Dec 1 04:06:41 2004 From: carroll at tjc.com (Terry Carroll) Date: Wed Dec 1 04:06:44 2004 Subject: [Tutor] converting unicode In-Reply-To: <21C33588-4345-11D9-AC84-000393CBC88E@yahoo.fr> Message-ID: On Wed, 1 Dec 2004, Max Noel wrote: > That's another job for my friends the list comprehensions! > out = tuple([str(element) for element in stringtuple]) List comprehension is indeed cool, but overkill here, I think. From carroll at tjc.com Wed Dec 1 04:08:06 2004 From: carroll at tjc.com (Terry Carroll) Date: Wed Dec 1 04:08:09 2004 Subject: [Tutor] converting unicode In-Reply-To: Message-ID: On Tue, 30 Nov 2004, Terry Carroll wrote: > On Wed, 1 Dec 2004, Max Noel wrote: > > > That's another job for my friends the list comprehensions! > > out = tuple([str(element) for element in stringtuple]) > > List comprehension is indeed cool, but overkill here, I think. Oh, hell, never mind. I just realized I answered a question that the OP wasn't actually asking. From kent37 at tds.net Wed Dec 1 04:12:27 2004 From: kent37 at tds.net (Kent Johnson) Date: Wed Dec 1 04:12:31 2004 Subject: [Tutor] converting unicode In-Reply-To: <20041201023645.D78C5398C@mprdmxin.myway.com> References: <20041201023645.D78C5398C@mprdmxin.myway.com> Message-ID: <41AD369B.7030403@tds.net> If you want a tuple as a result: Python 2.4 way using a generator comprehension: tuple(str(s) for s in stringtuple) Python 2.3 uses list comprehension: tuple([str(s) for s in stringtuple]) Old-timer's way using map :-) tuple(map(str, stringtuple)) Kent If a list is OK use either of the last two without the tuple() part... Rene Bourgoin wrote: > Wandering how i could convert an entire tuple of unicode strings to python strings using str(u'string') > > stringtuple = () > stringtuple = (u'string1',u'string2',u'string3') > > str(u stringtuple) # syntax problem here!!! > > > thanks > > > _______________________________________________ > No banners. No pop-ups. No kidding. > Make My Way your home on the Web - http://www.myway.com > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From maxnoel_fr at yahoo.fr Wed Dec 1 04:13:57 2004 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Wed Dec 1 04:14:01 2004 Subject: [Tutor] comapring lists In-Reply-To: <41AD3479.9080305@tds.net> References: <200411160439.XAA03967@webmail10.cac.psu.edu> <6.2.0.14.0.20041129121822.02e22d80@mail.mric.net> <41AD3479.9080305@tds.net> Message-ID: <09D1F7FB-4347-11D9-AC84-000393CBC88E@yahoo.fr> On Dec 1, 2004, at 03:03, Kent Johnson wrote: > If you want to stay within the same character set you need to do some > wraparound at the ends, otherwise you have things like > >>> chr(ord('9') + 1) > ':' > >>> chr(ord('Z') + 1) > '[' For that, it's best to use the modulo operator (%), of course. The "general" algorithm is something like: character = base_offset + ((original - base_offset + key) % size) -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From kent37 at tds.net Wed Dec 1 04:18:43 2004 From: kent37 at tds.net (Kent Johnson) Date: Wed Dec 1 04:18:47 2004 Subject: [Tutor] comapring lists In-Reply-To: <09D1F7FB-4347-11D9-AC84-000393CBC88E@yahoo.fr> References: <200411160439.XAA03967@webmail10.cac.psu.edu> <6.2.0.14.0.20041129121822.02e22d80@mail.mric.net> <41AD3479.9080305@tds.net> <09D1F7FB-4347-11D9-AC84-000393CBC88E@yahoo.fr> Message-ID: <41AD3813.4030801@tds.net> And the arithmetic needs to be on the indices in the character arrays, not the actual character values, because the intended character set actually has several distinct ranges - a-z, A-Z and 0-9. Kent Max Noel wrote: > > On Dec 1, 2004, at 03:03, Kent Johnson wrote: > >> If you want to stay within the same character set you need to do some >> wraparound at the ends, otherwise you have things like >> >>> chr(ord('9') + 1) >> ':' >> >>> chr(ord('Z') + 1) >> '[' > > > For that, it's best to use the modulo operator (%), of course. The > "general" algorithm is something like: > > character = base_offset + ((original - base_offset + key) % size) > > -- Max > maxnoel_fr at yahoo dot fr -- ICQ #85274019 > "Look at you hacker... A pathetic creature of meat and bone, panting and > sweating as you run through my corridors... How can you challenge a > perfect, immortal machine?" > > From maxnoel_fr at yahoo.fr Wed Dec 1 04:20:02 2004 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Wed Dec 1 04:20:10 2004 Subject: [Tutor] converting unicode In-Reply-To: <41AD369B.7030403@tds.net> References: <20041201023645.D78C5398C@mprdmxin.myway.com> <41AD369B.7030403@tds.net> Message-ID: On Dec 1, 2004, at 03:12, Kent Johnson wrote: > If you want a tuple as a result: > > Python 2.4 way using a generator comprehension: > tuple(str(s) for s in stringtuple) Ooh, now that's nifty! I'm still gonna wait for Tiger to upgrade to Python 2.4, though. Multiple versions of Python tend to cause various Bad Things on OS X which I can't be arsed to manually resolving. ^^ -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From kent37 at tds.net Wed Dec 1 04:21:38 2004 From: kent37 at tds.net (Kent Johnson) Date: Wed Dec 1 04:21:43 2004 Subject: [Tutor] The case of the missing close In-Reply-To: <968452DD78695147AA4A369C3DF9E40A01F942DF@BOSMAILBOX3.corp.mfs.com> References: <968452DD78695147AA4A369C3DF9E40A01F942DF@BOSMAILBOX3.corp.mfs.com> Message-ID: <41AD38C2.2010803@tds.net> I don't know cx_Oracle, but my guess is you want to close the actual connection object, not the cursor. Your dbopen() function doesn't expose the connection. One option would be to return the connection rather than the cursor. Then clients could close the connection when done. Another option is to create a class that holds both the connection and the cursor, then you can have close() on the class actually close the connection. Kent Robert, Andrew wrote: > Hi everyone, > > I am trying to create a generic db_utils.py module that I will then > generically import into programs as needed. > > The first function I am trying to implement iis to generically open an > Oracle database connection based on passed database/authentication > parameters. > > So far, I have been able to: > > - import the custom module db_utils > - pass the parameters function dbopen in the custom module > - open the connection to the requested database > - pass back the cursor object to the calling program for later > processing. > > The problem is in closing the connection. > > No matter what I try, I receive an error stating that the name is not > defined. > > I receive an error such as: > > Traceback (most recent call last): > File "M:\My > Documents\python_code\oracle\maestrodev_oracle_connector.py", line 55, > in ? > db_utils.close() > AttributeError: 'module' object has no attribute 'close' > > Does anyone have any ideas on how to properly close the connection? > > > > The db_utils module code is a rather short > > > def dbopen(db,uname,passwd): > # > # Import required system modules needed specifically for function > # > import cx_Oracle > > # > # Connect to remote database > # > connection = cx_Oracle.connect(dsn=db,user=uname,password=passwd) > > # > # Return cursor object to calling program > # > return(connection.cursor()) > > > The code that calls the db_utils module is > > #!c:\Python23\python > # > # File name: maestrodev_oracle_connector.py > # Author: Andrew Robert > # Date: 11/26/04 > # > # > # Modification History > # > # Version Programmer Description > # 1.0 AAR Creation > # 1.1 AAR Shift database opens to called > module > # 1.2 AAR Fixed database link close - now > works > # > # > # Note on modules > # > # The imported db_utils module was designed by AAR to make standard > database > # routines available to all python programs as callable functions. > # > # Called functions are prefaced with the module name and then the > function > # within the module. > # > > > import sys,db_utils > > # > # Make connection to Oracle development database and assign to object > # > > print 'Establishing connection to remote database\n' > cursobj = db_utils.dbopen('test_d','FOO','foo') > > # > # Formulate sample querry > # > cursobj.execute('SELECT userid, name, role, desk_phone, pager FROM > contacts') > > # > # Extract querry results > # > results=cursobj.fetchall() > > for row in results: > print row > > # > # Break connection to Oracle development database > # > print '\n\n\nDisconnecting from remote database' > > db_utils.close() > > raw_input("\n\n\t\tPress Enter To Continue") > > > Any help you can provide on this would be greatly appreciated. > > > > > Thank you, > Andrew Robert > Systems Architect > Information Technology > Massachusetts Financial Services > Phone: 617-954-5882 > Pager: 781-764-7321 > E-mail: arobert@mfs.com > Linux User Number: #201204 > > > "MFS Relay Service" made the following > annotations on 11/30/2004 11:11:35 AM > ------------------------------------------------------------------------------ > This email communication and any attachments may contain proprietary, confidential, or privileged information. If you are not the intended recipient, you are hereby notified that you have received this email in error and that any review, disclosure, dissemination, distribution or copying of it or its contents is prohibited. The sender does not waive confidentiality or any privilege by mistransmission. If you have received this email in error, please notify the sender immediately, delete this email, and destroy all copies and any attachments. > ============================================================================== > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at freenet.co.uk Wed Dec 1 10:13:33 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed Dec 1 10:12:57 2004 Subject: [Tutor] Problem with 2.4's IDLE References: <6.1.2.0.2.20041130174224.05213dc0@rcblue.com> Message-ID: <01d001c4d786$12407460$f1598651@xp> > I installed 2.4 today and find that when using its IDLE, File|Open opens > to \Documents and Settings\Dick, a long ways from \Python24. Actually, > I'd prefer \Python24\MyScripts. Same for File|Save. Is there a way to > control this behavior? Looks like someone has fixed IDLE so that it does what any well behaved Windows program should - default to the users MyDocuments folder - where Bill G believes we should store all our documents including python files... Of course if that is whats happened there should also be an option to change the default, or alternatively t should remember the last place you saved to... Provided it does one of those two things its doing what it should do! Alan G From dyoo at hkn.eecs.berkeley.edu Wed Dec 1 10:14:33 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Dec 1 10:14:52 2004 Subject: [Tutor] Problem with 2.4's IDLE In-Reply-To: <6.1.2.0.2.20041130174224.05213dc0@rcblue.com> Message-ID: On Tue, 30 Nov 2004, Dick Moores wrote: > I installed 2.4 today and find that when using its IDLE, File|Open opens > to \Documents and Settings\Dick, a long ways from \Python24. Actually, > I'd prefer \Python24\MyScripts. Same for File|Save. Is there a way to > control this behavior? Hi Dick, Yes, I believe so. The directory that you are finding yourself in, '\Documents and Settings\Dick', is considered your personal "HOME" directory, and I suspect IDLE is sending you there initially. You may want to first change the current working directory to \Python24\MyScripts instead. I did some code diving. Here's a sort of running dialog I'm having with myself to see if we can figure this out. In idlelib/IOBinding.py, around line 515, there's code that handles the file open dialog box: ### def askopenfile(self): dir, base = self.defaultfilename("open") if not self.opendialog: self.opendialog = tkFileDialog.Open(master=self.text, filetypes=self.filetypes) return self.opendialog.show(initialdir=dir, initialfile=base) ### Ok, that looks very promising. The initial directory is defined by some method called "defaultfilename". Let's see what that looks like. ### idlelib/IOBinding.py, line 522 def defaultfilename(self, mode="open"): if self.filename: return os.path.split(self.filename) elif self.dirname: return self.dirname, "" else: try: pwd = os.getcwd() ## <-- (dyoo: This looks like it!) except os.error: pwd = "" return pwd, "" ### Without looking at this more closely, this appears to confirm our suspicions. If no file has been opened yet, IDLE uses the current working directory as its initial file-opening default. If we can somehow change the current working directory that IDLE uses, then we're all set. Unfortunately, I don't know how things work on Windows, nor how it sets the current working directory of a double-clicked application. If you feel really kludgy, you modify that line in the defaultfilename() function so that, instead of it doing: pwd = os.getcwd() it can be munged to: pwd = '/Python24/MyScripts' A better approach, of course, would be to get the IDLE folks to add an option for changing the default file opening location. *grin* Try sending them a patch request for a configurable default file-open directory. If it's not in there already, it actually doesn't seem like a hard thing to implement. Good luck to you! From rdm at rcblue.com Wed Dec 1 11:04:00 2004 From: rdm at rcblue.com (Dick Moores) Date: Wed Dec 1 11:04:21 2004 Subject: [Tutor] Problem with 2.4's IDLE In-Reply-To: References: <6.1.2.0.2.20041130174224.05213dc0@rcblue.com> Message-ID: <6.1.2.0.2.20041201020105.04d91900@rcblue.com> Danny Yoo wrote at 01:14 12/1/2004: >If you feel really kludgy, you modify that line in the defaultfilename() >function so that, instead of it doing: > > pwd = os.getcwd() > >it can be munged to: > > pwd = '/Python24/MyScripts' Danny, how do you know so much? I am feeling kludgy tonight, and went with the munging. Works like a charm! Thanks very much, Dick From ARobert at MFS.com Wed Dec 1 11:05:24 2004 From: ARobert at MFS.com (Robert, Andrew) Date: Wed Dec 1 11:10:20 2004 Subject: [Tutor] The case of the missing close References: <968452DD78695147AA4A369C3DF9E40A01F942DF@BOSMAILBOX3.corp.mfs.com> <41AD38C2.2010803@tds.net> Message-ID: <968452DD78695147AA4A369C3DF9E40A225720@BOSMAILBOX3.corp.mfs.com> Hi Kent, I tried returning the connection but that didn't work either. In fact, returning the connection fails to create the cursor object in the calling program and the whole program dies a miserable death. I am intrigued about the idea of a class though. I've never really had the need to use them before now but it seems like now is a good time to start. I'll let you know how things work out. -----Original Message----- From: tutor-bounces@python.org on behalf of Kent Johnson Sent: Tue 11/30/2004 10:21 PM Cc: tutor@python.org Subject: Re: [Tutor] The case of the missing close I don't know cx_Oracle, but my guess is you want to close the actual connection object, not the cursor. Your dbopen() function doesn't expose the connection. One option would be to return the connection rather than the cursor. Then clients could close the connection when done. Another option is to create a class that holds both the connection and the cursor, then you can have close() on the class actually close the connection. Kent "MFS Relay Service" made the following annotations on 12/01/2004 05:15:44 AM ------------------------------------------------------------------------------ This email communication and any attachments may contain proprietary, confidential, or privileged information. If you are not the intended recipient, you are hereby notified that you have received this email in error and that any review, disclosure, dissemination, distribution or copying of it or its contents is prohibited. The sender does not waive confidentiality or any privilege by mistransmission. If you have received this email in error, please notify the sender immediately, delete this email, and destroy all copies and any attachments. ============================================================================== From kent37 at tds.net Wed Dec 1 11:38:13 2004 From: kent37 at tds.net (Kent Johnson) Date: Wed Dec 1 11:38:19 2004 Subject: [Tutor] converting unicode In-Reply-To: References: Message-ID: <41AD9F15.6090804@tds.net> Terry Carroll wrote: >>>>stringtuple = (u'a', u'bcd', u'e') >>>>''.join(stringtuple) > > u'abcde' > > Interestingly, this is one area where string.join() gets a different > result: > > >>>>from string import join >>>>stringtuple = (u'a', u'bcd', u'e') >>>>join(stringtuple) > > u'a bcd e' join(stringtuple, '') is the equivalent to ''.join(stringtuple). If you omit the second argument to string.join, it defaults to a single space, not the empty string. Kent From kent37 at tds.net Wed Dec 1 11:44:39 2004 From: kent37 at tds.net (Kent Johnson) Date: Wed Dec 1 11:44:49 2004 Subject: [Tutor] Problem with 2.4's IDLE In-Reply-To: References: Message-ID: <41ADA097.9060508@tds.net> If I start IDLE from the shortcut in the Start / Programs / Python24 menu, the open dialog defaults to C:=Python24. Looking at the shortcut properties (just right-click on IDLE in the menu) it says, Start in C:\Python24\. So if you start IDLE from the menu (or a similarly configured shortcut somewhere else) it should do what you want without changing any code. I think I'll change it to D:\ - I don' put my programs in the Python24 directory...hey, it works! Sweet! Kent Danny Yoo wrote: > > On Tue, 30 Nov 2004, Dick Moores wrote: > > >>I installed 2.4 today and find that when using its IDLE, File|Open opens >>to \Documents and Settings\Dick, a long ways from \Python24. Actually, >>I'd prefer \Python24\MyScripts. Same for File|Save. Is there a way to >>control this behavior? > > > > Hi Dick, > > > Yes, I believe so. The directory that you are finding yourself in, > '\Documents and Settings\Dick', is considered your personal "HOME" > directory, and I suspect IDLE is sending you there initially. You may > want to first change the current working directory to \Python24\MyScripts > instead. > > > I did some code diving. Here's a sort of running dialog I'm having with > myself to see if we can figure this out. > > > In idlelib/IOBinding.py, around line 515, there's code that handles the > file open dialog box: > > ### > def askopenfile(self): > dir, base = self.defaultfilename("open") > if not self.opendialog: > self.opendialog = tkFileDialog.Open(master=self.text, > filetypes=self.filetypes) > return self.opendialog.show(initialdir=dir, initialfile=base) > ### > > Ok, that looks very promising. The initial directory is defined by some > method called "defaultfilename". Let's see what that looks like. > > > ### idlelib/IOBinding.py, line 522 > def defaultfilename(self, mode="open"): > if self.filename: > return os.path.split(self.filename) > elif self.dirname: > return self.dirname, "" > else: > try: > pwd = os.getcwd() ## <-- (dyoo: This looks like it!) > except os.error: > pwd = "" > return pwd, "" > ### > > > Without looking at this more closely, this appears to confirm our > suspicions. If no file has been opened yet, IDLE uses the current working > directory as its initial file-opening default. > > If we can somehow change the current working directory that IDLE uses, > then we're all set. Unfortunately, I don't know how things work on > Windows, nor how it sets the current working directory of a double-clicked > application. > > If you feel really kludgy, you modify that line in the defaultfilename() > function so that, instead of it doing: > > pwd = os.getcwd() > > it can be munged to: > > pwd = '/Python24/MyScripts' > > > A better approach, of course, would be to get the IDLE folks to add an > option for changing the default file opening location. *grin* > > Try sending them a patch request for a configurable default file-open > directory. If it's not in there already, it actually doesn't seem like a > hard thing to implement. > > > Good luck to you! > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Wed Dec 1 11:53:32 2004 From: kent37 at tds.net (Kent Johnson) Date: Wed Dec 1 11:53:39 2004 Subject: [Tutor] The case of the missing close In-Reply-To: <968452DD78695147AA4A369C3DF9E40A225720@BOSMAILBOX3.corp.mfs.com> References: <968452DD78695147AA4A369C3DF9E40A01F942DF@BOSMAILBOX3.corp.mfs.com> <41AD38C2.2010803@tds.net> <968452DD78695147AA4A369C3DF9E40A225720@BOSMAILBOX3.corp.mfs.com> Message-ID: <41ADA2AC.4030002@tds.net> Here is a sketch to get you started. I'm not sure how cursors work so I may be off the mark! You may want to keep the cursor as an attribute of db so you can reuse it? class db: def __init__(self, db, uname, passwd) self.connection = cx_Oracle.connect(dsn=db,user=uname,password=passwd) def execute(self, sql): cursor = connection.cursor() cursor.execute(sql) return cursor def close(self): self.connection.close() self.connection = None # Prevent reusing a closed connection Your client code would look like this: import db_utils dbobj = db_utils.db('test_d','FOO','foo') cursobj = dbobj.execute('SELECT userid, name, role, desk_phone, pager FROM contacts') results=cursobj.fetchall() for row in results: print row dbobj.close() Kent Robert, Andrew wrote: > Hi Kent, > > I tried returning the connection but that didn't work either. > > In fact, returning the connection fails to create the cursor object in the calling program and the whole program dies a miserable death. > > I am intrigued about the idea of a class though. > > I've never really had the need to use them before now but it seems like now is a good time to start. > > I'll let you know how things work out. > > > > -----Original Message----- > From: tutor-bounces@python.org on behalf of Kent Johnson > Sent: Tue 11/30/2004 10:21 PM > Cc: tutor@python.org > Subject: Re: [Tutor] The case of the missing close > > I don't know cx_Oracle, but my guess is you want to close the actual connection object, not the > cursor. Your dbopen() function doesn't expose the connection. > > One option would be to return the connection rather than the cursor. Then clients could close the > connection when done. Another option is to create a class that holds both the connection and the > cursor, then you can have close() on the class actually close the connection. > > Kent > > > "MFS Relay Service" made the following > annotations on 12/01/2004 05:15:44 AM > ------------------------------------------------------------------------------ > This email communication and any attachments may contain proprietary, confidential, or privileged information. If you are not the intended recipient, you are hereby notified that you have received this email in error and that any review, disclosure, dissemination, distribution or copying of it or its contents is prohibited. The sender does not waive confidentiality or any privilege by mistransmission. If you have received this email in error, please notify the sender immediately, delete this email, and destroy all copies and any attachments. > ============================================================================== > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Wed Dec 1 12:01:41 2004 From: kent37 at tds.net (Kent Johnson) Date: Wed Dec 1 12:01:46 2004 Subject: [Tutor] (no subject) In-Reply-To: <20041130220445.13168.qmail@web60108.mail.yahoo.com> References: <20041130220445.13168.qmail@web60108.mail.yahoo.com> Message-ID: <41ADA495.3020401@tds.net> Jeff, I was looking through your other posts and saw the question about pickling and the one about detecting changed files. It makes me think, if you have control of both writing and reading of this data, you should consider a multi-user database. Then the database will take care of all the concurrency issues for you. If you are only appending to the database then checking for new items is just a matter of counting rows in the db. If you also change items you could store a time stamp in the db and check it periodically for changes. With a db you can retrieve sorted data or subsets easily. Kent Jeff Peery wrote: > hello again, > > I am thoroughly confused. I am using Timer from the threading module. I > want to check a specific file every few minutes to see if it has been > altered (I do this by checking the size of the file using stat) if it > hasn't then I do nothing, if it has then I attempt to read the file, > grab all the new numerical data and update a graph on my computer. > > this file I am reading holds liquid volumetric flow rate measurement > data and the python code I am writing is to be used as a statistical > process control. basically I watch the results from the measurements by > watching a particular file for updates, when an update occurs I grab the > data do some more stats, then update my graphs that show on my desktop. > > the timer I used is a class, so I defined a new object (I think thats > the right word) as: > > myTimer = Timer(30.0, Update) > > where the timer runs every 30 seconds and Update is a function that > checks if the file has been altered and if so then it updates my graphs. > I then start the timer: > > myTimer.start() > > I am confused by two things: > 1) I want my timer to restart every 30 seconds. as it shows above it > will go just one time. If I put this in a while loop, will the while > loop loop through the start command faster than 30 second intervals or > will it wait for the timer to execute the Update function before calling > timer.start() again? > 2) I am also confused about how variables are handled when I have > multiple and nested functions. for example, I would like to initiate the > Update function every 30 seconds and I want the Update funtion to return > any new data. how can I return something from a function when the > function is called from a timer? I cannot do an assignment statement > from within the definnition of myTimer? or do I even need to return the > data? if I create a variable in the update function is it available in > my main function? I am not sure how python handles variables that are > defined in different functions. > > thank you very much for spending the time to help me, I appreciate it! > > Jeff > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From cyresse at gmail.com Wed Dec 1 12:17:28 2004 From: cyresse at gmail.com (Liam Clarke) Date: Wed Dec 1 12:17:30 2004 Subject: [Tutor] True/False evaluations? Message-ID: Hi all, Got myself in a twist around logic of functions, I'll show you what I mean. >>> def x(): ... return 0 ... >>> def y(): ... return [] ... >>> x() 0 >>> y() [] >>> x()==False True >>> y()==False False >>> x()== y() False >>> if not x(): ... print 'x is false' ... else: ... print 'guess x is true' ... x is false >>> if not y(): ... print 'y is false' ... else: ... print 'hmmm' ... y is false It's y() not being False (or True), but evaluating as true for 'if not y()' which gets me, as I thought that [], 0, None, False, & {} all evaluated the same. General query however - >>> def k(): ... return [], 0 ... >>> print k() ([], 0) >>> if not k(): ... print "It's false" ... else: ... print 'This tuple is going to cause me grief' ... This tuple is going to cause me grief So, as k() returns a tuple, it's not false, even though the tuple contains two zero values. Is there a way I could do something like? for item in k(): if not item: #do something on one line? i.e. check for true/false of any value returned by k(), whether it be a 2 or 20 digits long tuple Um, -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From kent37 at tds.net Wed Dec 1 13:51:28 2004 From: kent37 at tds.net (Kent Johnson) Date: Wed Dec 1 13:51:35 2004 Subject: [Tutor] True/False evaluations? In-Reply-To: References: Message-ID: <41ADBE50.9050409@tds.net> Liam Clarke wrote: > Hi all, > > Got myself in a twist around logic of functions, I'll show you what I mean. > It's y() not being False (or True), but evaluating as true for 'if > not y()' which gets me, as I thought that [], 0, None, False, & {} all > evaluated the same. As you have discovered, an empty list is not the same as False, but it evaluates to False in conditionals. One way to think of it is, when you evaluate a conditional, the result is coerced to a boolean value. Numeric zeros and empty collections are coerced to False; everything else is True. >>> [] is False False >>> bool([]) is False True A list with elements in it is not an empty list, even if the elements themselves are empty. For example, a list containing None is different from an empty list, and its boolean value is True: >>> len( [None] ) 1 >>> [None] == [] False >>> bool( [None] ) True If you have some math background, it might help to think of the difference between the empty set (which is empty) and the set containing the empty set (which is not empty, it has one member). > > General query however - > So, as k() returns a tuple, it's not false, even though the tuple > contains two zero values. Is there a way I could do something like? > > for item in k(): > if not item: > #do something > > on one line? i.e. check for true/false of any value returned by k(), > whether it be a 2 or 20 digits long tuple >>> if reduce(lambda x, y: x or y, [ [], 1, None ]): ... print 'do something' ... else: ... print 'nothing to do' ... do something >>> if reduce(lambda x, y: x or y, [ [], 0, None ]): ... print 'do something' ... else: ... print 'nothing to do' ... nothing to do lambda x, y: x or y just gives us a function that applies logical or to its arguments. reduce() uses the given function as an accumulator. So the whole expression is roughly equivalent to [] or 0 or None Kent From kent37 at tds.net Wed Dec 1 13:53:17 2004 From: kent37 at tds.net (Kent Johnson) Date: Wed Dec 1 13:53:20 2004 Subject: [Tutor] The case of the missing close In-Reply-To: <41ADA2AC.4030002@tds.net> References: <968452DD78695147AA4A369C3DF9E40A01F942DF@BOSMAILBOX3.corp.mfs.com> <41AD38C2.2010803@tds.net> <968452DD78695147AA4A369C3DF9E40A225720@BOSMAILBOX3.corp.mfs.com> <41ADA2AC.4030002@tds.net> Message-ID: <41ADBEBD.80102@tds.net> Kent Johnson wrote: > Here is a sketch to get you started. I'm not sure how cursors work so I > may be off the mark! You may want to keep the cursor as an attribute of > db so you can reuse it? > > class db: > def __init__(self, db, uname, passwd) > self.connection = cx_Oracle.connect(dsn=db,user=uname,password=passwd) > > def execute(self, sql): > cursor = connection.cursor() should be cursor = self.connection.cursor() > cursor.execute(sql) > return cursor > > def close(self): > self.connection.close() > self.connection = None # Prevent reusing a closed connection From ARobert at MFS.com Wed Dec 1 13:59:28 2004 From: ARobert at MFS.com (Robert, Andrew) Date: Wed Dec 1 13:59:41 2004 Subject: [Tutor] The case of the missing close Message-ID: <968452DD78695147AA4A369C3DF9E40A0200ADFF@BOSMAILBOX3.corp.mfs.com> Hi Kent, That's great. I tried the code changes you mentioned but am now running into an error with the cx_Oracle module. I get the message Traceback (most recent call last): File "C:\python_code\oracle\maestrodev_oracle_connector.py", line 34, in ? dbobj = db_utils.db('maestro_d','MAESTRO_OWNER','joecool') File "C:\python_code\oracle\db_utils.py", line 9, in __init__ class db: NameError: global name 'cx_Oracle' is not defined The main script imports this module on load so I am a little confused as to why it is balking. Any thoughts? Thank you, Andrew Robert Systems Architect Information Technology - OpenVMS Massachusetts Financial Services Phone: 617-954-5882 Pager: 781-764-7321 E-mail: arobert@mfs.com Linux User Number: #201204 -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of Kent Johnson Sent: Wednesday, December 01, 2004 7:53 AM To: tutor@python.org Subject: Re: [Tutor] The case of the missing close Kent Johnson wrote: > Here is a sketch to get you started. I'm not sure how cursors work so I > may be off the mark! You may want to keep the cursor as an attribute of > db so you can reuse it? > > class db: > def __init__(self, db, uname, passwd) > self.connection = cx_Oracle.connect(dsn=db,user=uname,password=passwd) > > def execute(self, sql): > cursor = connection.cursor() should be cursor = self.connection.cursor() > cursor.execute(sql) > return cursor > > def close(self): > self.connection.close() > self.connection = None # Prevent reusing a closed connection _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor "MFS Relay Service" made the following annotations on 12/01/2004 08:05:08 AM ------------------------------------------------------------------------------ This email communication and any attachments may contain proprietary, confidential, or privileged information. If you are not the intended recipient, you are hereby notified that you have received this email in error and that any review, disclosure, dissemination, distribution or copying of it or its contents is prohibited. The sender does not waive confidentiality or any privilege by mistransmission. If you have received this email in error, please notify the sender immediately, delete this email, and destroy all copies and any attachments. ============================================================================== From kent37 at tds.net Wed Dec 1 14:21:44 2004 From: kent37 at tds.net (Kent Johnson) Date: Wed Dec 1 14:25:34 2004 Subject: [Tutor] The case of the missing close In-Reply-To: <968452DD78695147AA4A369C3DF9E40A0200ADFF@BOSMAILBOX3.corp.mfs.com> References: <968452DD78695147AA4A369C3DF9E40A0200ADFF@BOSMAILBOX3.corp.mfs.com> Message-ID: <41ADC568.8000101@tds.net> You have to import cx_Oracle (or any other module) in every module where you use it. Importing a module introduces it into the namespace of the importing module only. (Other than __builtin__) there is no truly global namespace in Python. Kent Robert, Andrew wrote: > Hi Kent, > > That's great. > > I tried the code changes you mentioned but am now running into an error > with the cx_Oracle module. > > I get the message > > Traceback (most recent call last): > File "C:\python_code\oracle\maestrodev_oracle_connector.py", line 34, > in ? > dbobj = db_utils.db('maestro_d','MAESTRO_OWNER','joecool') > File "C:\python_code\oracle\db_utils.py", line 9, in __init__ > class db: > NameError: global name 'cx_Oracle' is not defined > > The main script imports this module on load so I am a little confused as > to why it is balking. > > Any thoughts? > > Thank you, > Andrew Robert > Systems Architect > Information Technology - OpenVMS > Massachusetts Financial Services > Phone: 617-954-5882 > Pager: 781-764-7321 > E-mail: arobert@mfs.com > Linux User Number: #201204 > > -----Original Message----- > From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On > Behalf Of Kent Johnson > Sent: Wednesday, December 01, 2004 7:53 AM > To: tutor@python.org > Subject: Re: [Tutor] The case of the missing close > > Kent Johnson wrote: > >>Here is a sketch to get you started. I'm not sure how cursors work so > > I > >>may be off the mark! You may want to keep the cursor as an attribute > > of > >>db so you can reuse it? >> >>class db: >> def __init__(self, db, uname, passwd) >> self.connection = > > cx_Oracle.connect(dsn=db,user=uname,password=passwd) > >> def execute(self, sql): >> cursor = connection.cursor() > > > should be > cursor = self.connection.cursor() > > >> cursor.execute(sql) >> return cursor >> >> def close(self): >> self.connection.close() >> self.connection = None # Prevent reusing a closed connection > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > > "MFS Relay Service" made the following > annotations on 12/01/2004 08:05:08 AM > ------------------------------------------------------------------------------ > This email communication and any attachments may contain proprietary, confidential, or privileged information. If you are not the intended recipient, you are hereby notified that you have received this email in error and that any review, disclosure, dissemination, distribution or copying of it or its contents is prohibited. The sender does not waive confidentiality or any privilege by mistransmission. If you have received this email in error, please notify the sender immediately, delete this email, and destroy all copies and any attachments. > ============================================================================== > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From BranimirP at cpas.com Wed Dec 1 14:35:53 2004 From: BranimirP at cpas.com (Branimir Petrovic) Date: Wed Dec 1 14:36:06 2004 Subject: [Tutor] The case of the missing close Message-ID: <33678E78A2DD4D418396703A750048D4010250FE@RIKER> > I get the message > > Traceback (most recent call last): > File > "C:\python_code\oracle\maestrodev_oracle_connector.py", line 34, > in ? > dbobj = db_utils.db('maestro_d','MAESTRO_OWNER','joecool') > File "C:\python_code\oracle\db_utils.py", line 9, in __init__ > class db: > NameError: global name 'cx_Oracle' is not defined > > The main script imports this module on load so I am a little > confused as > to why it is balking. > > Any thoughts? > Import of cx_Oracle should happen in your module that is using it i.e. module db_utils.py should do it. Following snippet is from "my way" of dealing with cursor/connection "situation" (you'd have to rip out all references to 'ermpap' if you want to run it): # FileName: oraUtils.py import cx_Oracle, onErrorActionMapper as ermap def openCursor(userName=None, userPWD=None, sqlnetName=None, as_sysdba=False, errorActionFnct=ermap.quitInFlames, echoToSTDOUT=True, loggerObj=None): """Open cursor or 'quitInFlames' if can not. Echo to STDOUT or not, log to logfile or not.""" def __SQLPlusInput(sqlStatement): """Wrap up actual sql statement in SQL*Plus look-alike line""" return "%s%s%s" % ("SQL> ", sqlStatement, ";") try: if as_sysdba: sqlStatement = __SQLPlusInput('CONNECT %s/%s@%s AS SYSDBA' % \ (userName, userPWD, sqlnetName)) else: sqlStatement = __SQLPlusInput('CONNECT %s/%s@%s' % \ (userName, userPWD, sqlnetName)) if echoToSTDOUT: print sqlStatement if loggerObj: loggerObj.writeLine(sqlStatement) if as_sysdba: __connection = cx_Oracle.connect(userName, userPWD, sqlnetName, cx_Oracle.SYSDBA) else : __connection = cx_Oracle.connect(userName, userPWD, sqlnetName) cursor = __connection.cursor() cursor.arraysize = 1000 if echoToSTDOUT: print 'Connected.\n' if loggerObj: loggerObj.writeLine('Connected.\n') return cursor except cx_Oracle.DatabaseError, err: errMsg=str(err) if callable(errorActionFnct): errorActionFnct(ermap.OnOpenCursorError(errMsg), loggerObj=loggerObj) return False def closeCursor(cursor): """Closes opened cursor 'softly' returning True if cursor got closed. (silently fails returning False if cursor was already closed)""" if cursor: try: cursor.close() return True except cx_Oracle.InterfaceError: return False else: return False def closeCursorAndConnection(cursor): """Close opened cursor AND the connetction that opened this cursor. Return True if both got closed. Return False if attempt to close both fails (for any reason).""" if cursor: connection = cursor.connection cursor_close_result = closeCursor(cursor) try: connection.close() return cursor_close_result except cx_Oracle.InterfaceError: return False else : return False From orbitz at ezabel.com Wed Dec 1 14:38:09 2004 From: orbitz at ezabel.com (orbitz) Date: Wed Dec 1 14:38:17 2004 Subject: [Tutor] (no subject) In-Reply-To: <20041130220445.13168.qmail@web60108.mail.yahoo.com> References: <20041130220445.13168.qmail@web60108.mail.yahoo.com> Message-ID: <41ADC941.9090502@ezabel.com> If you are on *NIX, there are python bindings for using libfam, which is a bit better than your current solution, but why not have a fifo or something so you just check if there is new data to be read after whatever it is that writes it, writes it, that way you don't have to do this constant checking. Don't know what you mean by nested functions and all but: def blah(): def ooch(): # ooch has access to all of the variables in blah's scope. Jeff Peery wrote: > hello again, > > I am thoroughly confused. I am using Timer from the threading module. > I want to check a specific file every few minutes to see if it has > been altered (I do this by checking the size of the file using stat) > if it hasn't then I do nothing, if it has then I attempt to read the > file, grab all the new numerical data and update a graph on my computer. > > this file I am reading holds liquid volumetric flow rate measurement > data and the python code I am writing is to be used as a statistical > process control. basically I watch the results from the measurements > by watching a particular file for updates, when an update occurs I > grab the data do some more stats, then update my graphs that show on > my desktop. > > the timer I used is a class, so I defined a new object (I think thats > the right word) as: > > myTimer = Timer(30.0, Update) > > where the timer runs every 30 seconds and Update is a function that > checks if the file has been altered and if so then it updates my > graphs. I then start the timer: > > myTimer.start() > > I am confused by two things: > 1) I want my timer to restart every 30 seconds. as it shows above it > will go just one time. If I put this in a while loop, will the while > loop loop through the start command faster than 30 second intervals or > will it wait for the timer to execute the Update function before > calling timer.start() again? > 2) I am also confused about how variables are handled when I have > multiple and nested functions. for example, I would like to initiate > the Update function every 30 seconds and I want the Update funtion to > return any new data. how can I return something from a function when > the function is called from a timer? I cannot do an assignment > statement from within the definnition of myTimer? or do I even need to > return the data? if I create a variable in the update function is it > available in my main function? I am not sure how python handles > variables that are defined in different functions. > > thank you very much for spending the time to help me, I appreciate it! > > Jeff > >------------------------------------------------------------------------ > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > From mhansen at cso.atmel.com Wed Dec 1 16:14:35 2004 From: mhansen at cso.atmel.com (Mike Hansen) Date: Wed Dec 1 16:14:40 2004 Subject: [Tutor] Python 2.4 IDLE Windows 2000 Message-ID: <41ADDFDB.9040409@cso.atmel.com> After uninstalling Python 2.3.4, I installed Python 2.4 on my Windows 2000 workstation. For some reason IDLE won't launch. I see a hourglass cursor and a bit of hard drive activity, then nothing. I rebooted the PC, but that didn't work. I uninstalled 2.4 and reinstalled, but that didn't work. I didn't have any issues with 2.3.4. Anyone got any ideas? Thanks, Mike From kent37 at tds.net Wed Dec 1 17:57:52 2004 From: kent37 at tds.net (Kent Johnson) Date: Wed Dec 1 18:01:42 2004 Subject: [Tutor] True/False evaluations? In-Reply-To: <41ADECCF.6070307@latte.ca> References: <41ADBE50.9050409@tds.net> <41ADECCF.6070307@latte.ca> Message-ID: <41ADF810.90705@tds.net> No, I actually tried that first. operator.or_ is a bitwise or, not a logical or. IOW, operator.or_(a, b) is the same as a | b not a or b which is what I needed. There doesn't seem to be an equivalent to 'a or b' in the operator module. Kent Blake Winton wrote: > Kent Johnson wrote: > >> >>> if reduce(lambda x, y: x or y, [ [], 0, None ]): >> ... print 'do something' >> ... else: >> ... print 'nothing to do' >> ... >> nothing to do >> >> lambda x, y: x or y >> just gives us a function that applies logical or to its arguments. > > > You could use operator.or_ for the same thing, but without needing to > explain lambda. ;) (I recently did some exploring in that territory, > and came across it.) > > Later, > Blake. > > From mark.kels at gmail.com Wed Dec 1 18:14:49 2004 From: mark.kels at gmail.com (Mark Kels) Date: Wed Dec 1 18:14:52 2004 Subject: [Tutor] Problem with data storage Message-ID: Hello, I'm building an app that needs to get input from the user and compare it to data that should be in some kind of data storage file. The problem is that I dont know what data storage file/module to use... I need it to be easy for the user to edit by himself (I don't want to make an UI to edit the file), organized as list of pairs (or a table) and multy platform (if no such thing then WIN only). Thanks!! From kent37 at tds.net Wed Dec 1 18:28:22 2004 From: kent37 at tds.net (Kent Johnson) Date: Wed Dec 1 18:32:11 2004 Subject: [Tutor] Problem with data storage In-Reply-To: References: Message-ID: <41ADFF36.90602@tds.net> Sounds like a plain text file or a CSV file will work. If there is character that doesn't appear in your data (e.g. space, comma, tab) you can use it as a delimiter in a plain text file. If you need to allow any text in the data then us a CSV file and the csv module. In either case, the file will have one data pair per line. Kent Mark Kels wrote: > Hello, > > I'm building an app that needs to get input from the user and compare > it to data that should be in some kind of data storage file. > The problem is that I dont know what data storage file/module to use... > I need it to be easy for the user to edit by himself (I don't want to > make an UI to edit the file), organized as list of pairs (or a table) > and multy platform (if no such thing then WIN only). > > Thanks!! > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From flaxeater at yahoo.com Wed Dec 1 18:32:15 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Wed Dec 1 18:32:19 2004 Subject: [Tutor] Problem with data storage Message-ID: <20041201173215.13926.qmail@web54309.mail.yahoo.com> The Ideal solution for this is csv. http://www.python.org/doc/2.3.4/lib/module-csv.html that way it can be edited by any spreadsheet program. and even a text editor if the user is careful. Or you can just build the data structer yourself. something like ###file## key1=value1 key2=value2 ###Reader aDict={} for line in aFile: key,value=line.strip().split("=") aDict[key]=value HTH Mark Kels wrote: >Hello, > > > >I'm building an app that needs to get input from the user and compare > >it to data that should be in some kind of data storage file. > >The problem is that I dont know what data storage file/module to use... > >I need it to be easy for the user to edit by himself (I don't want to > >make an UI to edit the file), organized as list of pairs (or a table) > >and multy platform (if no such thing then WIN only). > > > >Thanks!! > >_______________________________________________ > >Tutor maillist - Tutor@python.org > >http://mail.python.org/mailman/listinfo/tutor > > > > > __________________________________ Do you Yahoo!? Yahoo! Mail - Helps protect you from nasty viruses. http://promotions.yahoo.com/new_mail From op73418 at mail.telepac.pt Wed Dec 1 19:07:09 2004 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Wed Dec 1 19:03:54 2004 Subject: [Tutor] The case of the missing close In-Reply-To: <41ADC568.8000101@tds.net> References: <968452DD78695147AA4A369C3DF9E40A0200ADFF@BOSMAILBOX3.corp.mfs.com> <41ADC568.8000101@tds.net> Message-ID: <41AE084D.8020309@mail.telepac.pt> Kent Johnson wrote: > You have to import cx_Oracle (or any other module) in every module where > you use it. Importing a module introduces it into the namespace of the > importing module only. (Other than __builtin__) there is no truly global > namespace in Python. > Actually there is, the __builtin__ module: >>> __builtins__ >>> And you can stick things inside it too: >>> __builtins__.my_own_private_variable = "Hey, I'm a global!" >>> def f(): ... print my_own_private_variable ... >>> f() Hey, I'm a global! >>> But after learning this, forget about it: it is a very nice way to shoot yourself painful death after painful death. With my best regards, G. Rodrigues From op73418 at mail.telepac.pt Wed Dec 1 19:15:59 2004 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Wed Dec 1 19:12:39 2004 Subject: [Tutor] The case of the missing close In-Reply-To: <41AE084D.8020309@mail.telepac.pt> References: <968452DD78695147AA4A369C3DF9E40A0200ADFF@BOSMAILBOX3.corp.mfs.com> <41ADC568.8000101@tds.net> <41AE084D.8020309@mail.telepac.pt> Message-ID: <41AE0A5F.6080403@mail.telepac.pt> Gon?alo Rodrigues wrote: > Kent Johnson wrote: > >> You have to import cx_Oracle (or any other module) in every module >> where you use it. Importing a module introduces it into the namespace >> of the importing module only. (Other than __builtin__) there is no >> truly global namespace in Python. >> > > Actually there is, the __builtin__ module: > Oops, sorry, I answered too fast and my eye missed that conspicuous parenthesis. Best regards, G. Rodrigues From bgailer at alum.rpi.edu Wed Dec 1 19:35:41 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed Dec 1 19:35:09 2004 Subject: [Tutor] True/False evaluations? In-Reply-To: <41ADBE50.9050409@tds.net> References: <41ADBE50.9050409@tds.net> Message-ID: <6.2.0.14.0.20041201113220.05672a70@mail.mric.net> At 05:51 AM 12/1/2004, Kent Johnson wrote: >Liam Clarke wrote: >>Hi all, >>Got myself in a twist around logic of functions, I'll show you what I mean. >>It's y() not being False (or True), but evaluating as true for 'if >>not y()' which gets me, as I thought that [], 0, None, False, & {} all >>evaluated the same. > >As you have discovered, an empty list is not the same as False, but it >evaluates to False in conditionals. One way to think of it is, when you >evaluate a conditional, the result is coerced to a boolean value. Numeric >zeros and empty collections are coerced to False; everything else is True. To be more complete and precise (from the language manual) "... when expressions are used by control flow statements, the following values are interpreted as false: None, numeric zero of all types, empty sequences (strings, tuples and lists), and empty mappings (dictionaries). All other values are interpreted as true." Of course this is not precise in that "control flow statements" AFAIK include if while for and try, but only in the context of if and while does the above apply. >[snip] Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From dyoo at hkn.eecs.berkeley.edu Wed Dec 1 19:38:55 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Dec 1 19:39:05 2004 Subject: [Tutor] Problem with 2.4's IDLE In-Reply-To: <41ADA097.9060508@tds.net> Message-ID: [Danny] > > I did some code diving. Here's a sort of running dialog I'm having with > > myself to see if we can figure this out. [Kent] > If I start IDLE from the shortcut in the Start / Programs / Python24 > menu, the open dialog defaults to C:=Python24. Looking at the shortcut > properties (just right-click on IDLE in the menu) it says, Start in > C:\Python24\. So if you start IDLE from the menu (or a similarly > configured shortcut somewhere else) it should do what you want without > changing any code. > > I think I'll change it to D:\ - I don' put my programs in the Python24 > directory...hey, it works! Again, I definitely like Kent's approach much better than my own. *grin* From bvande at po-box.mcgill.ca Wed Dec 1 20:05:57 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Wed Dec 1 20:06:34 2004 Subject: [Tutor] Cannot cPickle.load() In-Reply-To: <1f7befae04113017543bc2756e@mail.gmail.com> References: <41ACFF41.4010206@h-lab.net> <1f7befae04113017543bc2756e@mail.gmail.com> Message-ID: <41AE1615.3060704@po-box.mcgill.ca> Tim Peters said unto the world upon 2004-11-30 20:54: > Change > "r" > to > "rb" > and try again. > > You're on Windows, pickles are binary files, and binary files must > always be opened in binary mode on Windows. When you wrote the data > to the file to begin with, I hope you opened the file in binary mode > then too. Else the data in the file is corrupt now. Hi all, Tim's post confuses me. (I've cc'ed you Tim as somehow I doubt you are a regular reader of Tutor -- apologies if that annoys.) I'm on Windows with Python 2.3.4 (waiting for extension updates to use 2.4). When I run: import pickle a_dict = {1:2, 3:4, 5:6} print a_dict pic_file = file('c:/testpickle.pic', 'w') pickle.dump(a_dict, pic_file) pic_file.close() a_dict = {} print a_dict pic_file = file('c:/testpickle.pic', 'r') a_dict = pickle.load(pic_file) print a_dict I get the output: IDLE 1.0.3 >>> ========================= RESTART ======================= >>> {1: 2, 3: 4, 5: 6} {} {1: 2, 3: 4, 5: 6} Which makes it look to me like pickle is working just fine without using binary mode. I tried the same thing with cPickle and also made sure to close IDLE and try reading the pickled data in a command prompt Python. In all cases, I recovered the pickled data without difficulty. So, what have I misunderstood? Thanks, and best to all, Brian vdB From tim.peters at gmail.com Wed Dec 1 20:21:41 2004 From: tim.peters at gmail.com (Tim Peters) Date: Wed Dec 1 20:21:44 2004 Subject: [Tutor] Cannot cPickle.load() In-Reply-To: <41AE1615.3060704@po-box.mcgill.ca> References: <41ACFF41.4010206@h-lab.net> <1f7befae04113017543bc2756e@mail.gmail.com> <41AE1615.3060704@po-box.mcgill.ca> Message-ID: <1f7befae04120111213e7db64d@mail.gmail.com> [Brian van den Broek] > Tim Peters said unto the world upon 2004-11-30 20:54: > > > > >> Change >> "r" >> to >> "rb" >> and try again. >> >> You're on Windows, pickles are binary files, and binary files must >> always be opened in binary mode on Windows. When you wrote >> the data to the file to begin with, I hope you opened the file in >> binary mode then too. Else the data in the file is corrupt now. > Tim's post confuses me. (I've cc'ed you Tim as somehow I doubt > you are a regular reader of Tutor -- apologies if that annoys.) No, I read Tutor regularly, I just don't have time to reply regularly . > I'm on Windows with Python 2.3.4 (waiting for extension updates > to use 2.4). When I run: > > > import pickle > > a_dict = {1:2, 3:4, 5:6} > print a_dict > > pic_file = file('c:/testpickle.pic', 'w') > pickle.dump(a_dict, pic_file) > pic_file.close() > > a_dict = {} > print a_dict > > pic_file = file('c:/testpickle.pic', 'r') > a_dict = pickle.load(pic_file) > print a_dict > > > I get the output: > .... > {1: 2, 3: 4, 5: 6} > {} > {1: 2, 3: 4, 5: 6} > > Which makes it look to me like pickle is working just fine without > using binary mode. I tried the same thing with cPickle and also > made sure to close IDLE and try reading the pickled data in a > command prompt Python. > > In all cases, I recovered the pickled data without difficulty. > > So, what have I misunderstood? It can work by accident, just as any binary file *may* not contain data that causes it to fail when opened in text mode on Windows. In particular, because you didn't specify a pickle protocol in the above, it defaulted to protocol 0, which uses only printable characters. Note that Hugo (the OP) said he was using protocol 2, which does not restrict itself to printable characters (and neither does protocol 1). Even if your pickle happened to appear to work, there's no guarantee it will work if you try to load the same pickle on a non-Windows box: Windows text mode transforms \n to \r\n on write, and does the reverse transformation on read. Linux does neither, so you're not necessarily safe cross-platform even sticking to protocol 0 pickles. The bottom line: pickles are binary data, and if you want to avoid disaster, you must open pickle files in binary mode on Windows, for both writing and reading. You *should* also do that on non-Windows platforms, although most non-Windows platforms don't make any distinction between binary and text modes. If you do 'rb' and 'wb' anyway, your program will be portable across platforms. BTW2, Hugo replied in private, saying that switching to binary mode open() fixed his problem. Of course this was obvious from what he said in his first message . From jeffpeery at yahoo.com Wed Dec 1 20:31:28 2004 From: jeffpeery at yahoo.com (Jeff Peery) Date: Wed Dec 1 20:31:32 2004 Subject: [Tutor] time.sleep? Message-ID: <20041201193129.61028.qmail@web60110.mail.yahoo.com> hello I am using time.sleep(seconds) within a while loop. I don't understand the output from this loop. I pasted it below. When I push the go button I would expect first that the message "monitor initiated" would appear in the text field, then another message "monitor sleeping", then a delay in time caused by sleep(), then another message "checking file size". I would also expect this to occur ten times because I have a for loop. however what happens is that nothing appears in the text field until const_checkTime*10 seconds have gone by and then all the messages appear, that is there are three different messages and ten replicates. So nothing actually appears until the for loop and sleep are finished. if I take out the for loop, no messages are executed before the time delay, the delay takes place and then all three messages appear. I would like to use a while loop and have this work continuously although nothing appears if I do this. why is this happening? thanks,Jeff def OnGoButton(self, event): self.go = TRUE self.TextField.SetValue("Monitor Initiated\n%s" %self.TextField.GetValue()) self.fileSize = int(stat(self.textCtrl1.GetValue())[6]) for i in range(0,10): self.TextField.SetValue("Monitor Sleeping\n%s" %self.TextField.GetValue()) time.sleep(const_checkTime) self.TextField.SetValue("Checking File Size\n%s" %self.TextField.GetValue()) dummy = CheckFile(self, self.textCtrl1.GetValue(), self.fileSize) -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041201/ec282154/attachment.html From bvande at po-box.mcgill.ca Wed Dec 1 20:45:36 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Wed Dec 1 20:46:10 2004 Subject: [Tutor] Cannot cPickle.load() In-Reply-To: <1f7befae04120111213e7db64d@mail.gmail.com> References: <41ACFF41.4010206@h-lab.net> <1f7befae04113017543bc2756e@mail.gmail.com> <41AE1615.3060704@po-box.mcgill.ca> <1f7befae04120111213e7db64d@mail.gmail.com> Message-ID: <41AE1F60.3070407@po-box.mcgill.ca> Tim Peters said unto the world upon 2004-12-01 14:21: > [Brian van den Broek] > >>Tim Peters said unto the world upon 2004-11-30 20:54: >> >> >> >> >>>Change >>> "r" >>>to >>> "rb" >>>and try again. >>> >>>You're on Windows, pickles are binary files, and binary files must >>>always be opened in binary mode on Windows. When you wrote >>>the data to the file to begin with, I hope you opened the file in >>>binary mode then too. Else the data in the file is corrupt now. > > >>Tim's post confuses me. (I've cc'ed you Tim as somehow I doubt >>you are a regular reader of Tutor -- apologies if that annoys.) > > > No, I read Tutor regularly, I just don't have time to reply regularly . Noted for future cases. It is nice (if a bit intimidating ;-) to know that tutor is read by core developers, too. >>I'm on Windows with Python 2.3.4 (waiting for extension updates >>to use 2.4). When I run: >> >> >>I get the output: >> >>Which makes it look to me like pickle is working just fine without >>using binary mode. I tried the same thing with cPickle and also >>made sure to close IDLE and try reading the pickled data in a >>command prompt Python. >> >>In all cases, I recovered the pickled data without difficulty. >> >>So, what have I misunderstood? > > > It can work by accident, just as any binary file *may* not contain > data that causes it to fail when opened in text mode on Windows. In > particular, because you didn't specify a pickle protocol in the above, > it defaulted to protocol 0, which uses only printable characters. > Note that Hugo (the OP) said he was using protocol 2, which does not > restrict itself to printable characters (and neither does protocol 1). > > Even if your pickle happened to appear to work, there's no guarantee > it will work if you try to load the same pickle on a non-Windows box: > Windows text mode transforms \n to \r\n on write, and does the reverse > transformation on read. Linux does neither, so you're not necessarily > safe cross-platform even sticking to protocol 0 pickles. > > The bottom line: pickles are binary data, and if you want to avoid > disaster, you must open pickle files in binary mode on Windows, for > both writing and reading. You *should* also do that on non-Windows > platforms, although most non-Windows platforms don't make any > distinction between binary and text modes. If you do 'rb' and 'wb' > anyway, your program will be portable across platforms. OK, thanks. I just did my first pickling about a week ago, so I'm very glad to have been straightened out before I had too much 'unhappy' code to fix. Best to all, Brian vdB From Christian.Wyglendowski at greenville.edu Wed Dec 1 20:51:45 2004 From: Christian.Wyglendowski at greenville.edu (Christian Wyglendowski) Date: Wed Dec 1 20:51:56 2004 Subject: [Tutor] time.sleep? Message-ID: > -----Original Message----- > > hello I am using time.sleep(seconds) within a while loop. I > don't understand the output from this loop. I pasted it below. Hey Jeff, Looks like you are using wxPython. I am not an expert by any means, but I have been doing some stuff in wxPython recently too, so I'll see if I can help. > When I push the go button I would expect first that the > message "monitor initiated" would appear in the text field, > then another message "monitor sleeping", then a delay in time > caused by sleep(), then another message "checking file size". > I would also expect this to occur ten times because I have a > for loop. however what happens is that nothing appears in the > text field until const_checkTime*10 seconds have gone by and > then all the messages appear, that is there are three > different messages and ten replicates. So nothing actually > appears until the for loop and sleep are finished. I think that is because wxPython is waiting for the function to exit before updating the GUI. Since your OnGoButton() function sleeps for some amount of time, it will take a while before the GUI gets updated. > if I take out the for loop, no messages are executed before > the time delay, the delay takes place and then all three > messages appear. I would like to use a while loop and have > this work continuously although nothing appears if I do this. I think that you will find the wxPyWiki page at the following link helpful. It gives a few different options for accomplishing basically what you are trying to do. http://wiki.wxpython.org/index.cgi/LongRunningTasks After all the threading talk on Tutor a few weeks ago I forced myself to get familiar with them and they aren't that bad. That said, the threaded example at the link above looks like the best solution. HTH, Christian http://www.dowski.com From dyoo at hkn.eecs.berkeley.edu Wed Dec 1 22:45:53 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Dec 1 22:46:02 2004 Subject: [Tutor] Python 2.4 IDLE Windows 2000 In-Reply-To: <41ADDFDB.9040409@cso.atmel.com> Message-ID: On Wed, 1 Dec 2004, Mike Hansen wrote: > After uninstalling Python 2.3.4, I installed Python 2.4 on my Windows > 2000 workstation. For some reason IDLE won't launch. I see a hourglass > cursor and a bit of hard drive activity, then nothing. I rebooted the > PC, but that didn't work. I uninstalled 2.4 and reinstalled, but that > didn't work. I didn't have any issues with 2.3.4. Anyone got any ideas? Hi Mike, There are two things about IDLE that can complicate installation: IDLE depends on Tkinter for its GUI, and it also uses network sockets. Lately, the network stuff has been troublesome, since many computers come with broken firewall setups. Do you have firewall software installed? Recent versions of IDLE will try to open network sockets to itself, so firewall software can actually interfere with it. There's a mention of this issue on the "bugs" list: http://python.org/2.4/bugs.html If you do have a firewall running, try turning the firewall off temporarely, and start up IDLE again. If IDLE starts to work, then it's very likely that the firewall software is to blame. Also, If you can start up the console version of Python, try executing the following: ### >>> import Tkinter >>> root = Tkinter.root() ### and tell us what the computer does when those commands are executed. This tries to bring up a Tkinter graphical root window, and if this breaks, then it's likely that something funky is going on with Tkinter. Good luck to you! From dyoo at hkn.eecs.berkeley.edu Wed Dec 1 22:51:42 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Dec 1 22:51:49 2004 Subject: [Tutor] Python 2.4 IDLE Windows 2000 In-Reply-To: Message-ID: > Also, If you can start up the console version of Python, try executing the > following: > > ### > >>> import Tkinter > >>> root = Tkinter.root() > ### Doh. Sorry, I should have tested that. The commands should actually be: ### >>> import Tkinter >>> root = Tkinter.Tk() ### You should see a small, blank window pop up if Tkinter is working properly. From v-nijs at kellogg.northwestern.edu Wed Dec 1 23:10:03 2004 From: v-nijs at kellogg.northwestern.edu (Vincent Nijs) Date: Wed Dec 1 23:12:05 2004 Subject: [Tutor] Connecting to interactive program Message-ID: Hi, I am trying to send information from an editor (vim) to an interative program (say the Python commandline, R, Matlab, etc.). I have tried to connect a named pipe to the interactive program using mkfifo. For some reason this doesn't work properly however ( seems to be the first thing sent). Could anyone provide a very very simple example where from a terminal command line I could send, say, 'x=3' to an open interactive python session? I'd like to have something that works on WinXP and Mac (or Linux). Thanks! Vincent -- From r2b2 at myway.com Thu Dec 2 02:18:06 2004 From: r2b2 at myway.com (Rene Bourgoin) Date: Thu Dec 2 02:18:13 2004 Subject: [Tutor] unicode help (COM) Message-ID: <20041202011806.55DCC12CD9@mprdmxin.myway.com> Thanks for the responses. i'm a non-programmer and was learning/playing with some pyhton COM . I'm trying to get my resluts from an excel spreadsheet to be saved or printed or stored as a python string. when i run this the results are in unicode..... from win32com.client import Dispatch xlApp = Dispatch("Excel.Application") xlApp.Visible = 0 xlApp.Workbooks.Open("c:\sheet.xls") excelout = () excelout = xlApp.ActiveSheet.Range("C4:D10").Value for item in excelout: print item _______________________________________________ No banners. No pop-ups. No kidding. Make My Way your home on the Web - http://www.myway.com From jeff at ccvcorp.com Thu Dec 2 02:51:10 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu Dec 2 02:47:28 2004 Subject: [Tutor] time.sleep? In-Reply-To: References: Message-ID: <41AE750E.7010306@ccvcorp.com> Christian Wyglendowski wrote: >>-----Original Message----- >>[...] So nothing actually >>appears until the for loop and sleep are finished. > > I think that is because wxPython is waiting for the function to exit > before updating the GUI. Since your OnGoButton() function sleeps for > some amount of time, it will take a while before the GUI gets updated. Yep, exactly. The key here is that, when using a GUI or other event-driven framework, you need to allow the framework some execution time too. What has happened is that you've told the framework to add a message to the text field, but the framework doesn't update the screen until *after* you're done handling all the events in your event queue. Obviously, if you're still in the same event handler, you haven't finished handling all events... ;) Given that you're (apparently) using wxPython, you should look into using wx.Timer. In essence, instead of sleeping in a loop and then updating the message every X seconds, your button handler will simply toggle a flag variable saying "I'm running". You will also have a handler for the timer's event, and in that handler, you check the flag variable. If the flag is set, then you check the file and update the message as needed. If the flag is *not* set, then you do nothing. (It's also possible to start and stop the timer events from happening in the first place, rather than just ignoring them if the flag isn't set. But I don't remember how to do that off the top of my head, so I'm not going into detail here. ;) ) Jeff Shannon Technician/Programmer Credit International From carroll at tjc.com Thu Dec 2 03:59:57 2004 From: carroll at tjc.com (Terry Carroll) Date: Thu Dec 2 04:00:00 2004 Subject: [Tutor] Python 2.4 IDLE Windows 2000 In-Reply-To: Message-ID: On Wed, 1 Dec 2004, Danny Yoo wrote: > Lately, the network stuff has been troublesome, since many computers come > with broken firewall setups. Do you have firewall software installed? > Recent versions of IDLE will try to open network sockets to itself, so > firewall software can actually interfere with it. Yowza; that's some bug. Danny, do you happen to know the bug number? I can't find it on sourceforge. I would expect Idle to at least generate an alert if the port's blocked. From carroll at tjc.com Thu Dec 2 04:00:53 2004 From: carroll at tjc.com (Terry Carroll) Date: Thu Dec 2 04:00:56 2004 Subject: [Tutor] converting unicode In-Reply-To: <41AD9F15.6090804@tds.net> Message-ID: On Wed, 1 Dec 2004, Kent Johnson wrote: > join(stringtuple, '') is the equivalent to ''.join(stringtuple). If you omit the second argument to > string.join, it defaults to a single space, not the empty string. Thanks. From cyresse at gmail.com Thu Dec 2 06:56:17 2004 From: cyresse at gmail.com (Liam Clarke) Date: Thu Dec 2 06:56:20 2004 Subject: [Tutor] time.sleep? In-Reply-To: <41AE750E.7010306@ccvcorp.com> References: <41AE750E.7010306@ccvcorp.com> Message-ID: Timer's in wxPython have to be attached to a widget, don't know why, some quirk of wx. def on_openBackground(self, event): self.myTimer = wx.wxTimer(self.components.field1, -1) # create a timer self.myTimer.Start(5000) # launch timer, to fire every 5000ms (5 seconds) def on_field1_timer(self, event): print this Or, if you wanted something to activate every 10 seconds, and then stop after the fifteenth activation - def on_init(self, event); self.timerFires = 0 def on_startTimer_mouseClick(self, event): self.myTimer = wx.wxTimer(self.components.field1, -1) self.myTimer.Start(10000) def on_field1_timer(self, event): print "Bang!" self.timerFires += 1 if self.timerFires == 10: self.myTimer.Stop() On Wed, 01 Dec 2004 17:51:10 -0800, Jeff Shannon wrote: > Christian Wyglendowski wrote: > > >>-----Original Message----- > >>[...] So nothing actually > >>appears until the for loop and sleep are finished. > > > > I think that is because wxPython is waiting for the function to exit > > before updating the GUI. Since your OnGoButton() function sleeps for > > some amount of time, it will take a while before the GUI gets updated. > > Yep, exactly. > > The key here is that, when using a GUI or other event-driven > framework, you need to allow the framework some execution time too. > What has happened is that you've told the framework to add a message > to the text field, but the framework doesn't update the screen until > *after* you're done handling all the events in your event queue. > Obviously, if you're still in the same event handler, you haven't > finished handling all events... ;) > > Given that you're (apparently) using wxPython, you should look into > using wx.Timer. In essence, instead of sleeping in a loop and then > updating the message every X seconds, your button handler will simply > toggle a flag variable saying "I'm running". You will also have a > handler for the timer's event, and in that handler, you check the flag > variable. If the flag is set, then you check the file and update the > message as needed. If the flag is *not* set, then you do nothing. > (It's also possible to start and stop the timer events from happening > in the first place, rather than just ignoring them if the flag isn't > set. But I don't remember how to do that off the top of my head, so > I'm not going into detail here. ;) ) > > Jeff Shannon > Technician/Programmer > Credit International > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From cyresse at gmail.com Thu Dec 2 06:58:46 2004 From: cyresse at gmail.com (Liam Clarke) Date: Thu Dec 2 06:58:49 2004 Subject: [Tutor] time.sleep? In-Reply-To: References: <41AE750E.7010306@ccvcorp.com> Message-ID: Oops, forgot to mention - that's in a Pythoncard GUI, which wraps around wxPython, so unsure how to do it exactly in wxPython. On Thu, 2 Dec 2004 18:56:17 +1300, Liam Clarke wrote: > Timer's in wxPython have to be attached to a widget, don't know why, > some quirk of wx. > > def on_openBackground(self, event): > self.myTimer = wx.wxTimer(self.components.field1, -1) # create a timer > self.myTimer.Start(5000) # launch timer, to fire every 5000ms (5 seconds) > > def on_field1_timer(self, event): > print this > > Or, if you wanted something to activate every 10 seconds, and then > stop after the fifteenth activation - > > def on_init(self, event); > self.timerFires = 0 > > def on_startTimer_mouseClick(self, event): > self.myTimer = wx.wxTimer(self.components.field1, -1) > self.myTimer.Start(10000) > > def on_field1_timer(self, event): > print "Bang!" > self.timerFires += 1 > if self.timerFires == 10: > self.myTimer.Stop() > > > > > On Wed, 01 Dec 2004 17:51:10 -0800, Jeff Shannon wrote: > > Christian Wyglendowski wrote: > > > > >>-----Original Message----- > > >>[...] So nothing actually > > >>appears until the for loop and sleep are finished. > > > > > > I think that is because wxPython is waiting for the function to exit > > > before updating the GUI. Since your OnGoButton() function sleeps for > > > some amount of time, it will take a while before the GUI gets updated. > > > > Yep, exactly. > > > > The key here is that, when using a GUI or other event-driven > > framework, you need to allow the framework some execution time too. > > What has happened is that you've told the framework to add a message > > to the text field, but the framework doesn't update the screen until > > *after* you're done handling all the events in your event queue. > > Obviously, if you're still in the same event handler, you haven't > > finished handling all events... ;) > > > > Given that you're (apparently) using wxPython, you should look into > > using wx.Timer. In essence, instead of sleeping in a loop and then > > updating the message every X seconds, your button handler will simply > > toggle a flag variable saying "I'm running". You will also have a > > handler for the timer's event, and in that handler, you check the flag > > variable. If the flag is set, then you check the file and update the > > message as needed. If the flag is *not* set, then you do nothing. > > (It's also possible to start and stop the timer events from happening > > in the first place, rather than just ignoring them if the flag isn't > > set. But I don't remember how to do that off the top of my head, so > > I'm not going into detail here. ;) ) > > > > Jeff Shannon > > Technician/Programmer > > Credit International > > > > > > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > -- > 'There is only one basic human right, and that is to do as you damn well please. > And with it comes the only basic human duty, to take the consequences. > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From ramster6 at gmail.com Thu Dec 2 07:53:07 2004 From: ramster6 at gmail.com (Ramkumar Parimal Alagan) Date: Thu Dec 2 07:53:14 2004 Subject: [Tutor] gzip In-Reply-To: <479803a704112304212658a198@mail.gmail.com> References: <20041123110109.700051E4016@bag.python.org> <41A32977.1040103@gmail.com> <479803a704112304212658a198@mail.gmail.com> Message-ID: <82c0f73b041201225319da0cf3@mail.gmail.com> I am trying to zip some files off a folder in windows Xp, can u let me know is wrong in the script below. import os import gzip source = ['D:\\down'] target = ['d:\\'] zip = gzip.open(source[rb[9[target]]]) if os.system(zip) == 0: print 'Successful backup to', target else: print 'Backup FAILED' From dyoo at hkn.eecs.berkeley.edu Thu Dec 2 08:28:58 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Dec 2 08:29:07 2004 Subject: [Tutor] gzip In-Reply-To: <82c0f73b041201225319da0cf3@mail.gmail.com> Message-ID: On Thu, 2 Dec 2004, Ramkumar Parimal Alagan wrote: > I am trying to zip some files off a folder in windows Xp, can u let me > know is wrong in the script below. Hi Ramkumar, Do you get an error message? If so, please show the error message to us, so that we can be sure that whatever problems we see are the same problems that you're seeing. *grin* > zip = gzip.open(source[rb[9[target]]]) Ok, I see that you're trying to use the gzip module that's documented in: http://www.python.org/doc/lib/module-gzip.html However, I think you're misreading the documentation. When the documentation says: """ open(filename[, mode[, compresslevel]]) This is a shorthand for GzipFile(filename, mode, compresslevel). The filename argument is required; mode defaults to 'rb' and compresslevel defaults to 9. """ the brace symbols '[' ']' that are used in the documentation are meant to show optional parameter arguments. When you are using gzip.open(), don't put those brace sybmols literally into the statement: they're meant as typographic hints to you. The documentation for open() says that it can take in either one, two, or three arguments. The first arugment is the filename, the second is the mode, and the third is the compression level. So instead of: > zip = gzip.open(source[rb[9[target]]]) you may want to try something like: ### zip = gzip.open(target, "rb", 9) ### If you are already familiar with Python's regular open() command, just think of gzip.open() as a specialized version that transparently compresses as you write to it. > if os.system(zip) == 0: > print 'Successful backup to', target > else: > print 'Backup FAILED' This looks problematic. os.system() takes in a string that's passed to the shell for execution. But you don't need to shell out if you're using the 'gzip' module: the program already has a file-like object that can be written into. From olli.s.rajala at tut.fi Thu Dec 2 10:56:59 2004 From: olli.s.rajala at tut.fi (Olli Rajala) Date: Thu Dec 2 10:57:01 2004 Subject: [Tutor] Problem with data storage In-Reply-To: <20041201173215.13926.qmail@web54309.mail.yahoo.com> References: <20041201173215.13926.qmail@web54309.mail.yahoo.com> Message-ID: <20041202095659.GA8310@students.cc.tut.fi> > ###Reader > aDict={} > for line in aFile: > key,value=line.strip().split("=") > aDict[key]=value Hmm, in my photogallery, I have data organized as number:value-pairs (one/line) and I can have ':' in value, so I use line.split(":", 1) to split it just from the first ':'. It works in my system, but as I'm not very seasoned programmer, don't know if it's the right way to do it... :) Yours, -- Olli Rajala http://www.students.tut.fi/~rajala37/ "In theory, Theory and Practice should be the same. But in practice, they aren't." - Murphy's Proverbs From mhansen at cso.atmel.com Thu Dec 2 15:20:19 2004 From: mhansen at cso.atmel.com (Mike Hansen) Date: Thu Dec 2 15:20:27 2004 Subject: [Tutor] Python 2.4 IDLE Windows 2000 In-Reply-To: References: Message-ID: <41AF24A3.3070707@cso.atmel.com> I'm pretty sure that there isn't any firewall software running on the workstation. I do get a blank window when I run the commands below, so Tkinter seems to be working. This is strange since IDLE in Python 2.3.4 was working fine. Thanks for the help. I welcome any other ideas. Mike Danny Yoo wrote: > > >>Also, If you can start up the console version of Python, try executing the >>following: >> >>### >> >> >>>>>import Tkinter >>>>>root = Tkinter.root() >>>>> >>>>> >>### >> >> > >Doh. Sorry, I should have tested that. The commands should actually be: > >### > > >>>>import Tkinter >>>>root = Tkinter.Tk() >>>> >>>> >### > >You should see a small, blank window pop up if Tkinter is working >properly. > > > > From benvinger at yahoo.co.uk Thu Dec 2 17:37:15 2004 From: benvinger at yahoo.co.uk (Ben Vinger) Date: Thu Dec 2 17:37:17 2004 Subject: [Tutor] os.popen doesn't give up Message-ID: <20041202163715.65190.qmail@web25801.mail.ukl.yahoo.com> I call net-snmp from a Python script as below. The script works fine and runs every 5 minutes. But after collecting data for a few weeks, I noticed many instances of the script, as well as the snmpget executable in the process table. I think this must be due to times when the remote site was not available, so would like to know how I can get os.popen and snmpget not to do this (ie, give it a rest when the remote site doesn't respond) I = os.popen(r'snmpget -Os -c ' + SNMPcommunity + ' -v 2c -r 3 ' + IP + ' ' + counter, 'r') Thanks Ben ___________________________________________________________ Moving house? Beach bar in Thailand? New Wardrobe? Win ?10k with Yahoo! Mail to make your dream a reality. Get Yahoo! Mail www.yahoo.co.uk/10k From bgailer at alum.rpi.edu Thu Dec 2 17:53:27 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu Dec 2 17:52:53 2004 Subject: [Tutor] os.popen doesn't give up In-Reply-To: <20041202163715.65190.qmail@web25801.mail.ukl.yahoo.com> References: <20041202163715.65190.qmail@web25801.mail.ukl.yahoo.com> Message-ID: <6.2.0.14.0.20041202094826.02d8daa8@mail.mric.net> At 09:37 AM 12/2/2004, Ben Vinger wrote: >I call net-snmp from a Python script as below. The >script works fine and runs every 5 minutes. But after >collecting data for a few weeks, I noticed many >instances of the script, as well as the snmpget >executable in the process table. I think this must be >due to times when the remote site was not available, >so would like to know how I can get os.popen and >snmpget not to do this (ie, give it a rest when the >remote site doesn't respond) > > >I = os.popen(r'snmpget -Os -c ' + SNMPcommunity + ' -v >2c -r 3 ' + IP + ' ' + counter, 'r') From the os module reference "popen( command[, mode[, bufsize]]) Open a pipe to or from command. The return value is an open file object connected to the pipe, which can be read or written depending on whether mode is 'r' (default) or 'w' That explains it. l "is an open file object connected to the pipe, which can be read". snmpget stays in execution waiting for its output to be read. Solutions: 1 - os.popen(r'snmpget -Os -c ' + SNMPcommunity + ' -v2c -r 3 ' + IP + ' ' + counter, 'r'). Discards (therefore closes) the file object. 2 - l = os.popen(r'snmpget -Os -c ' + SNMPcommunity + ' -v2c -r 3 ' + IP + ' ' + counter, 'r').read() Puts snmpget's output in l. 3 - l = os.popen(r'snmpget -Os -c ' + SNMPcommunity + ' -v2c -r 3 ' + IP + ' ' + counter, 'r') l.close() Enough? Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041202/8bf481fb/attachment.html From ARobert at MFS.com Thu Dec 2 18:20:54 2004 From: ARobert at MFS.com (Robert, Andrew) Date: Thu Dec 2 18:21:11 2004 Subject: [Tutor] os.popen doesn't give up and snmp Message-ID: <968452DD78695147AA4A369C3DF9E40A02090221@BOSMAILBOX3.corp.mfs.com> Hi Ben, To make life easier, you may want to use the pysnmp module instead of popen statements. Pysnmp can be found at http://www.python.org/pypi?:action=display&name=pysnmp&version=3.x . Good luck. Thank you, Andrew Robert Systems Architect Information Technology - OpenVMS Massachusetts Financial Services Phone: 617-954-5882 Pager: 781-764-7321 E-mail: arobert@mfs.com Linux User Number: #201204 "MFS Relay Service" made the following annotations on 12/02/2004 12:26:39 PM ------------------------------------------------------------------------------ This email communication and any attachments may contain proprietary, confidential, or privileged information. If you are not the intended recipient, you are hereby notified that you have received this email in error and that any review, disclosure, dissemination, distribution or copying of it or its contents is prohibited. The sender does not waive confidentiality or any privilege by mistransmission. If you have received this email in error, please notify the sender immediately, delete this email, and destroy all copies and any attachments. ============================================================================== -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041202/a1c6a2f6/attachment.htm From mohamed at your-site.com Thu Dec 2 18:29:17 2004 From: mohamed at your-site.com (Mohamed Lrhazi) Date: Thu Dec 2 18:29:20 2004 Subject: [Tutor] Equivalent of PHP's __FUNCTION__ ? Message-ID: <12779281.1101990557@[192.168.1.76]> Hello all, In php one can produce nice debugging and logging use code like: print __FUNCTION__ . ": Invalid arguments\n"; __FUNCTION__ will be replaced by the name of the function to which that line belongs, same with __LINE__ and __FILE__ I believe. How do I get the current method's name? and class? Thanks. Mohamed~ From jeff at ccvcorp.com Thu Dec 2 19:10:41 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu Dec 2 19:06:39 2004 Subject: [Tutor] time.sleep? In-Reply-To: References: <41AE750E.7010306@ccvcorp.com> Message-ID: <41AF5AA1.1010109@ccvcorp.com> Liam Clarke wrote: > Timer's in wxPython have to be attached to a widget, don't know why, > some quirk of wx. It's because of the event-driven framework structure. A timer needs a place to deliver an event to, in order to indicate that the time is up. (Or so I theorize. I can use wx, but I'm far from being an expert in its internal architecture or anything... :) ) Jeff Shannon Technician/Programmer Credit International From jeff at ccvcorp.com Thu Dec 2 19:16:36 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu Dec 2 19:12:46 2004 Subject: [Tutor] Problem with data storage In-Reply-To: References: Message-ID: <41AF5C04.10706@ccvcorp.com> Mark Kels wrote: > I'm building an app that needs to get input from the user and compare > it to data that should be in some kind of data storage file. > The problem is that I dont know what data storage file/module to use... > I need it to be easy for the user to edit by himself (I don't want to > make an UI to edit the file), organized as list of pairs (or a table) > and multy platform (if no such thing then WIN only). You might want to check out the ConfigParser standard module. It provides a convenient cross-platform way to create files that are equivalent to the standard Windows INI files. You get straightforward key/value pairs organized into named sections. The files are both standard and easy to read/edit manually. Jeff Shannon Technician/Programmer Credit International From benvinger at yahoo.co.uk Thu Dec 2 19:17:28 2004 From: benvinger at yahoo.co.uk (Ben Vinger) Date: Thu Dec 2 19:17:29 2004 Subject: [Tutor] os.popen doesn't give up In-Reply-To: <6.2.0.14.0.20041202094826.02d8daa8@mail.mric.net> Message-ID: <20041202181728.30840.qmail@web25806.mail.ukl.yahoo.com> --- Bob Gailer wrote: > Solutions: > 1 - os.popen(r'snmpget -Os -c ' + SNMPcommunity + ' > -v2c -r 3 ' + IP + ' ' > + counter, 'r'). Discards (therefore closes) the > file object. > 2 - l = os.popen(r'snmpget -Os -c ' + SNMPcommunity > + ' -v2c -r 3 ' + IP + > ' ' + counter, 'r').read() Puts snmpget's output in > l. > 3 - l = os.popen(r'snmpget -Os -c ' + SNMPcommunity > + ' -v2c -r 3 ' + IP + > ' ' + counter, 'r') > l.close() Thanks Bob. 1 is no solution, because I need to do something with the output of net-snmp, so I've opted for 2. Robert I originallyly had a brief look at pysnmp, but couldn't get my head around it within the allocated time (3 minutes). But maybe I'll use that in future. ___________________________________________________________ Moving house? Beach bar in Thailand? New Wardrobe? Win ?10k with Yahoo! Mail to make your dream a reality. Get Yahoo! Mail www.yahoo.co.uk/10k From kent37 at tds.net Thu Dec 2 19:42:09 2004 From: kent37 at tds.net (Kent Johnson) Date: Thu Dec 2 19:42:08 2004 Subject: [Tutor] Equivalent of PHP's __FUNCTION__ ? In-Reply-To: <12779281.1101990557@[192.168.1.76]> References: <12779281.1101990557@[192.168.1.76]> Message-ID: <41AF6201.5010509@tds.net> Here is one way to do it, based on this Python Cookbook recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66062 def debug(msg): import sys frame = sys._getframe(1) name = frame.f_code.co_name line_number = frame.f_lineno filename = frame.f_code.co_filename return 'File "%s", line %d, in %s: %s' % (filename, line_number, name, msg) def test(): print debug("Invalid arguments") test() Kent Mohamed Lrhazi wrote: > Hello all, > > In php one can produce nice debugging and logging use code like: > print __FUNCTION__ . ": Invalid arguments\n"; > > __FUNCTION__ will be replaced by the name of the function to which that > line belongs, same with __LINE__ and __FILE__ I believe. > > How do I get the current method's name? and class? > > Thanks. > > Mohamed~ > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From mohamed at your-site.com Thu Dec 2 20:33:18 2004 From: mohamed at your-site.com (Mohamed Lrhazi) Date: Thu Dec 2 20:33:21 2004 Subject: [Tutor] Equivalent of PHP's __FUNCTION__ ? In-Reply-To: <41AF6201.5010509@tds.net> References: <12779281.1101990557@[192.168.1.76]> <41AF6201.5010509@tds.net> Message-ID: <20220203.1101997998@[192.168.1.76]> --On Thursday, December 02, 2004 1:42 PM -0500 Kent Johnson wrote: > Here is one way to do it, Thanks so much. that's perfect. From kent37 at tds.net Thu Dec 2 21:02:09 2004 From: kent37 at tds.net (Kent Johnson) Date: Thu Dec 2 21:02:09 2004 Subject: [Tutor] Equivalent of PHP's __FUNCTION__ ? In-Reply-To: <41AF6201.5010509@tds.net> References: <12779281.1101990557@[192.168.1.76]> <41AF6201.5010509@tds.net> Message-ID: <41AF74C1.6070005@tds.net> Kent Johnson wrote: > Here is one way to do it, based on this Python Cookbook recipe: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66062 Use of sys._getframe() is generally considered something of a skanky hack. (Though it is often done anyway.) Here is another solution that only uses supported public interfaces: def debug(msg): import traceback frame = traceback.extract_stack(limit=1)[0] filename, line_number, name, text = frame return 'File "%s", line %d, in %s: %s' % (filename, line_number, name, msg) > > def debug(msg): > import sys > frame = sys._getframe(1) > > name = frame.f_code.co_name > line_number = frame.f_lineno > filename = frame.f_code.co_filename > > return 'File "%s", line %d, in %s: %s' % (filename, line_number, > name, msg) > > > def test(): > print debug("Invalid arguments") > > > test() > > Kent > > Mohamed Lrhazi wrote: > >> Hello all, >> >> In php one can produce nice debugging and logging use code like: >> print __FUNCTION__ . ": Invalid arguments\n"; >> >> __FUNCTION__ will be replaced by the name of the function to which >> that line belongs, same with __LINE__ and __FILE__ I believe. >> >> How do I get the current method's name? and class? >> >> Thanks. >> >> Mohamed~ >> _______________________________________________ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor >> > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From mdcooper at uvic.ca Thu Dec 2 23:08:41 2004 From: mdcooper at uvic.ca (mdcooper) Date: Thu Dec 2 23:08:46 2004 Subject: [Tutor] Strange Appending Message-ID: <41B05184@wm2.uvic.ca> Hello, I am trying to append a list to another list, but everytime I do, the new parent list has a new child list, but all the other lists have become the same as the new child list. Code: self._f.write(str(self.residue.atoms[int(t[0])-1].element) + ' ') for m in t: self._f.write(str(m)+' ') self._f.write('\n') self.a.append(t) # WHY DOES THIS NOT WORK????? print self.a Output: [[1, 234, 543]] [[1, 234, 548], [1, 234, 548]] [[1, 234, 59], [1, 234, 59], [1, 234, 59]] [[1, 237, 543], [1, 237, 543], [1, 237, 543], [1, 237, 543]] Can anyone help? thanks, Matthew (mdcooper at uvic dot ca) From marilyn at deliberate.com Thu Dec 2 23:41:03 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Thu Dec 2 23:41:07 2004 Subject: [Tutor] Strange Appending In-Reply-To: <41B05184@wm2.uvic.ca> Message-ID: On Thu, 2 Dec 2004, mdcooper wrote: > Hello, > > I am trying to append a list to another list, but everytime I do, the new > parent list has a new child list, but all the other lists have become the same > as the new child list. > > Code: > > > self._f.write(str(self.residue.atoms[int(t[0])-1].element) + ' ') > for m in t: > self._f.write(str(m)+' ') > self._f.write('\n') > > self.a.append(t) # WHY DOES THIS NOT WORK????? Hi, I'm not sure that I understand your question because I don't see all the code and I don't know what you hope will happen. But ... append appends the object as a single element. Try self.a.extend(t) extend attaches the t list to the end of the list. Does this give you what you expect? Marilyn Davis > print self.a > > Output: > > [[1, 234, 543]] > [[1, 234, 548], [1, 234, 548]] > [[1, 234, 59], [1, 234, 59], [1, 234, 59]] > [[1, 237, 543], [1, 237, 543], [1, 237, 543], [1, 237, 543]] > > > Can anyone help? > > thanks, > > Matthew (mdcooper at uvic dot ca) > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- From benvinger at yahoo.co.uk Fri Dec 3 00:39:40 2004 From: benvinger at yahoo.co.uk (Ben Vinger) Date: Fri Dec 3 00:39:42 2004 Subject: [Tutor] os.popen doesn't give up Message-ID: <20041202233940.92871.qmail@web25809.mail.ukl.yahoo.com> --- Ben Vinger wrote: > --- Bob Gailer wrote: > > Solutions: > > 2 - l = os.popen(r'snmpget -Os -c ' + > SNMPcommunity > > + ' -v2c -r 3 ' + IP + > > ' ' + counter, 'r').read() Puts snmpget's output > in > > l. Sorry, now I have doubts again. Originally, I had: I = os.popen(r'snmpget -Os -c ' + SNMPcommunity + ' -v 2c -r 3 ' + IP + ' ' + counter, 'r') bytes = string.split(I.read(), None)[3] With Bob's suggestion, I have: I = os.popen(r'snmpget -Os -c ' + SNMPcommunity + ' -v 2c -r 3 ' + IP + ' ' + counter, 'r').read() bytes = string.split(I, None)[3] But is this really different? I can add I.close() as you suggested, maybe that will do the trick. Thanks Ben ___________________________________________________________ Moving house? Beach bar in Thailand? New Wardrobe? Win ?10k with Yahoo! Mail to make your dream a reality. Get Yahoo! Mail www.yahoo.co.uk/10k From guillermo.fernandez.castellanos at gmail.com Fri Dec 3 02:15:52 2004 From: guillermo.fernandez.castellanos at gmail.com (Guillermo Fernandez Castellanos) Date: Fri Dec 3 02:15:57 2004 Subject: [Tutor] unittest.makeSuite question In-Reply-To: <20041202233940.92871.qmail@web25809.mail.ukl.yahoo.com> References: <20041202233940.92871.qmail@web25809.mail.ukl.yahoo.com> Message-ID: <7d7029e70412021715742b759e@mail.gmail.com> Hi, I've been through the unittest tutorial page and I've seen this function: suite = unittest.makeSuite(Testname,'test') In the python 2.4 Python Library Reference I have find no reference to such a fucntion (there is an example, exactly the same but without the 'test' parameter). I could not really understand the sources neither... What is the 'test' parameter? Is there another possible values? Any reference of the function? Thanks! Guille From cyresse at gmail.com Fri Dec 3 03:12:57 2004 From: cyresse at gmail.com (Liam Clarke) Date: Fri Dec 3 03:13:01 2004 Subject: [Tutor] Python 2.4 IDLE Windows 2000 In-Reply-To: <41AF24A3.3070707@cso.atmel.com> References: <41AF24A3.3070707@cso.atmel.com> Message-ID: >Yowza; that's some bug. Danny, do you happen to know the bug number? I >can't find it on sourceforge. It's been like that since 2.3 as far as I know. It generates a connection to localhost to run code in a separate environment. On Thu, 02 Dec 2004 07:20:19 -0700, Mike Hansen wrote: > I'm pretty sure that there isn't any firewall software running on the > workstation. > > I do get a blank window when I run the commands below, so Tkinter seems > to be working. > > This is strange since IDLE in Python 2.3.4 was working fine. > > Thanks for the help. I welcome any other ideas. > > Mike > > > > Danny Yoo wrote: > > > > > > >>Also, If you can start up the console version of Python, try executing the > >>following: > >> > >>### > >> > >> > >>>>>import Tkinter > >>>>>root = Tkinter.root() > >>>>> > >>>>> > >>### > >> > >> > > > >Doh. Sorry, I should have tested that. The commands should actually be: > > > >### > > > > > >>>>import Tkinter > >>>>root = Tkinter.Tk() > >>>> > >>>> > >### > > > >You should see a small, blank window pop up if Tkinter is working > >properly. > > > > > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From cyresse at gmail.com Fri Dec 3 04:02:24 2004 From: cyresse at gmail.com (Liam Clarke) Date: Fri Dec 3 04:02:27 2004 Subject: [Tutor] Strange Appending In-Reply-To: References: <41B05184@wm2.uvic.ca> Message-ID: What's t supposed to be, what are you initialising self.a as, where is t generated, what is your expected output? What else is happening to self.a? Looks like an indentation error to me. This kind of output [[1, 237, 543], [1, 237, 543], [1, 237, 543], [1, 237, 543]] would only come from a loop iterating over the command that appends [1,237,543] several times. I'd check your logic, logical errors are the hardest. I use that kind of thing often - i.e. x=[] a="Hello 123, How is 456?" for item in a: try: w=(int(item))/1 except TypeError: continue x.append(item) print x ['1','2','3','4','5','6'] But yeah, post up all the relevant code please, just not the bit that's not breaking. I can't see your loop that's writing the wrong values, or perhaps self.a is getting reinitialized wrong? If you get my point. Regards, Liam Clarke On Thu, 2 Dec 2004 14:41:03 -0800 (PST), Marilyn Davis wrote: > On Thu, 2 Dec 2004, mdcooper wrote: > > > > > Hello, > > > > I am trying to append a list to another list, but everytime I do, the new > > parent list has a new child list, but all the other lists have become the same > > as the new child list. > > > > Code: > > > > > > self._f.write(str(self.residue.atoms[int(t[0])-1].element) + ' ') > > for m in t: > > self._f.write(str(m)+' ') > > self._f.write('\n') > > > > self.a.append(t) # WHY DOES THIS NOT WORK????? > > Hi, > > I'm not sure that I understand your question because I don't see all > the code and I don't know what you hope will happen. But ... > > append appends the object as a single element. > > Try self.a.extend(t) > > extend attaches the t list to the end of the list. > > Does this give you what you expect? > > Marilyn Davis > > > > > print self.a > > > > Output: > > > > [[1, 234, 543]] > > [[1, 234, 548], [1, 234, 548]] > > [[1, 234, 59], [1, 234, 59], [1, 234, 59]] > > [[1, 237, 543], [1, 237, 543], [1, 237, 543], [1, 237, 543]] > > > > > > Can anyone help? > > > > thanks, > > > > Matthew (mdcooper at uvic dot ca) > > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > -- > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From keridee at jayco.net Fri Dec 3 03:15:25 2004 From: keridee at jayco.net (Jacob S.) Date: Fri Dec 3 04:10:29 2004 Subject: [Tutor] new function and a 3 line program not working References: <000a01c4c4c5$f55d9990$6500a8c0@cdca1h1bro1> <005001c4d63d$62d3bfd0$f1598651@xp> Message-ID: <00ca01c4d8e5$9b61ba00$c15328cf@JSLAPTOP> I thought that the '.py ' in this import statement would make the interpreter think that newline was a package and therefore try to recognize py as a module in the newline package. from newline.py import newline Perhaps you said this to help explain what's going on? Jacob Schmidt > > If so that is the problem. You cannot call newLine() in a separate > file from the one where you defined it - python doesn't know about it. > You need to *import* the file where you defined the function, like > this: > > from newline.py import newline > > Ah, but reading further in your post and looking at the tutorial text > you posted, the author does NOT say create a new file. Rather > he (she?) says (or implies) to just keep on typing the program > after the function definition in the same file. That way Python > can read the file including the newline() definition. > > HTH, > > Alan G. > > > ========================== > > The first couple of functions we are going to write have no > parameters, so the syntax looks like this: > > def newLine(): > print > > This function is named newLine. The empty parentheses indicate that it > has no parameters. It contains only a single statement, which outputs > a newline character. (That's what happens when you use a printcommand > without any arguments.) > > The syntax for calling the new function is the same as the syntax for > built-in functions: > > print "First Line." > newLine() > print "Second Line." > > definition> > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From keridee at jayco.net Fri Dec 3 03:50:20 2004 From: keridee at jayco.net (Jacob S.) Date: Fri Dec 3 04:10:39 2004 Subject: [Tutor] programming newbie question References: <16044.156.153.255.243.1099587688.squirrel@phome.pointclark.net> Message-ID: <00cc01c4d8e5$a0ff8ff0$c15328cf@JSLAPTOP> > I am fairly new to programming and I have started to learn programming > then stopped out of frustration several times in the past. I guess my > frustration stems from not being able to understand when to use certain > aspects of programming such as functions or classes. Use functions when you will execute a certain code block many, many times during a script. Or if you want to make a code block simpler and more generic. For example... def rfill(stri,length,sep=" "): # stri is short for string, and sep (seperator) is defaulted to a space stri = str(stri) # This is to help make sure that what the user gives us is a string if stri < length: stri = stri + sep*(length-len(stri)) # This fills the string to the length with seperators return stri # This returns the string so we can assign it, print it etc. Usage is as follows: a = 'The' b = 'Many' c = 'Two' e = 'Forty' f = [a,b,c,e] for i in range(4): print "%s%d" % (rfill(f[i],15),i) yields The 0 Many 1 Two 2 Forty 3 This is just one example. You can use functions over and over from anywhere in your script. Classes are just like defining new types. You have the usual types like dictionary, list, tuple, integer, float, etc. but with classes you can define your own. Methods are just attributes of classes, or so I understand. For example... class MyClass: def __init__(self,pos=[0,1,0]): self.pos = pos def printpos(self): print self.pos Which in turn can be used like this. >>> a = MyClass() ## pos defaults to [0,1,0] so I don't have to specify explicitly >>> print a.pos [1,0,1] >>> a.pos = [1,2,1] >>> a.printpos() [1,2,1] >>> The most interesting use of classes that I have seen is the VPython package where they define new classes (again I think of them as types) as shapes with attributes (or methods - like L.append() which refers to appending to lists) like position, color, radius, axis, etc. But I digress. HTH, Jacob Schmidt > I have read enough > books and tutorials to know the syntax of python and I understand most > everything related to the concepts of programming, but I have never been > able to put it all together and learn how and when to use specific > features. Can anyone suggest a method or some reading to help out with > this? I also struggle with finding projects to work on does anyone know > of projects that a novice could contribute to? > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From keridee at jayco.net Fri Dec 3 03:26:15 2004 From: keridee at jayco.net (Jacob S.) Date: Fri Dec 3 04:10:40 2004 Subject: [Tutor] Problem with data storage References: Message-ID: <00cb01c4d8e5$9fb89100$c15328cf@JSLAPTOP> Hello, The way I do it is as follows. def open(): a = open('myfile.txt','r') di = a.read() a.close() di = eval(di) return di def save(di): a = open('myfile.txt','w') a.write(str(di)) a.close() def dosomethingwithdi(di): '''You can put whatever you want in here for example...''' open() print di di['key'] = 'value' save(di) print 'Done' HTH, Jacob Schmidt > Hello, > > I'm building an app that needs to get input from the user and compare > it to data that should be in some kind of data storage file. > The problem is that I dont know what data storage file/module to use... > I need it to be easy for the user to edit by himself (I don't want to > make an UI to edit the file), organized as list of pairs (or a table) > and multy platform (if no such thing then WIN only). > > Thanks!! > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From keridee at jayco.net Fri Dec 3 03:58:39 2004 From: keridee at jayco.net (Jacob S.) Date: Fri Dec 3 04:10:42 2004 Subject: [Tutor] Pythonw.exe doesn't work in the python2.4 distribution? References: <000701c4d598$5bb6d2f0$215328cf@JSLAPTOP> <001501c4d607$85857e50$f1598651@xp> Message-ID: <00ce01c4d8e5$a40f8f10$c15328cf@JSLAPTOP> > > execute the scripts using python24. However, the "Edit with IDLE" > command in > > the shorcut menu (right-click pull down menu) no longer worked. So I > went to > > the registry (I know the risks involved) > > BUt entirely unnecesary here! > The way to check/fix the context(right-click) menu options is via > Explorer. Its much easier and much safer. > > Go to Tools->Folder Optoions->File Types > > Select the file type you areinterested inn- .PYW in this case > > Hit the Change button, from the dialog you can select the > associated executable. Using the Advanced button you can > edit the existing entries, changing startup flags etc. > > You can also add new contrext actions there too - such as > Edit with SCite or whatever. Thank you! I knew there was a way I did it last time, I just couldn't remember! for i in range(100): print 'Thank you' > > "C:\python23\pythonw.exe" "C:\python24\lib\idlelib\idle.pyw -n -e > %1" > > > > A few things... > > > > 1) Can anyone explain why pythonw.exe doesn't do what it is supposed > to do > > in python24? > > That I can't help with not having loaded 2.4 yet. > > > 3) Can anyone off-hand tell me what the arguments -n and -e mean in > the > > above string? Does anybody know of a list of these? (Not urgent, if > no one > > knows, I won't bother extensively searching for one.) > > According to the usage message in PyShell.py > > -n => start with no subprocess > > -e file => edit That makes perfect sense. Thanks! Jacob Schmidt From keridee at jayco.net Fri Dec 3 04:06:35 2004 From: keridee at jayco.net (Jacob S.) Date: Fri Dec 3 04:10:52 2004 Subject: [Tutor] comapring lists References: <200411160439.XAA03967@webmail10.cac.psu.edu> Message-ID: <00cf01c4d8e5$a51f7870$c15328cf@JSLAPTOP> If you or anybody else is interested, I've written a script for codes like kids in junior high use to write notes to each other with... It will cipher and decipher mixed letters (encryption), turn words inside out (try it and see), date code (mixed letters that changes with the date), morse code, piglatin (primitive)... See for yourself. import time lowercase = 'abcdefghijklmnopqrstuvwxyz' whitespace = '\t\n\x0b\x0c\r ' punctuation = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~' print """\ Types of codes are: mixed letters insideout date code morse ode piglatin """ while 1: unordo = raw_input('Are we going to decipher or cipher? ') if unordo == 'quit': break type = raw_input('Which type of code would you like? ').lower() if type == 'mixed letters': if unordo == 'cipher': ask = raw_input('Please type the code text using regular language. ') returnlist = [] copyofask = ask ## For use when checking the capitalization later... ask = ask.lower() ref = lowercase increment = raw_input('What letter would you like "a" paired with? ') added = increment increment = ref.index(increment) ask = list(ask) for x in ask: if x in whitespace or x in punctuation: returnlist.append(x) else: ind = ref.index(x) ind = ind+increment while ind >= 26: ind = ind - 26 returnlist.append(ref[ind]) returnlist.append(added) inde = 0 for x in copyofask: if x == x.upper(): returnlist[inde] = returnlist[inde].upper() inde = inde+1 returnlist = "".join(returnlist) print print returnlist print if unordo == 'decipher': ask = raw_input('Please type in the coded message. ') returnlist = [] copyofask = ask ## For use when checking the capitalization later... ask = ask.lower() ref = lowercase ask = list(ask) del copyofask[-1] added = ask.pop() increment = ref.index(added) for x in ask: if x in whitespace or x in punctuation: returnlist.append(x) else: ind = ref.index(x) ind = ind-increment while ind < 0: ind = ind+26 returnlist.append(ref[ind]) inde = 0 for x in copyofask: if x == x.upper(): returnlist[inde] = returnlist[inde].upper() inde = inde+1 returnlist = "".join(returnlist) print print returnlist print if type == 'insideout': if unordo == 'cipher': returnlist = [] ask = list(raw_input('Please type in the message. ')) while len(ask) > 0: returnlist.append(ask.pop(0)) ask.reverse() returnlist.reverse() returnlist = "".join(returnlist) print print returnlist print if unordo == 'decipher': returnlist = [] ask = list(raw_input('Please type in the message. ')) returnlist.append(ask.pop(0)) while len(ask) > 0: returnlist.append(ask.pop(0)) returnlist.reverse() returnlist = "".join(returnlist) print print returnlist print if type == 'date code': if unordo == 'cipher': ask = raw_input('Please type in the message. ') copyofask = ask returnlist = [] ask = list(ask.lower()) datesmall = raw_input('What is the date you want to use? ') if datesmall == '': datesmall = time.strftime('%m%d%y') dateexpanded = time.strftime('%B %d, %Y') else: dateexpanded = datesmall datesmall = time.strptime(datesmall,'%B %d, %Y') datesmall = time.strftime('%m %d %y',datesmall).split(" ") datesmall = [str(int(x)) for x in datesmall] datesmall = list("".join(datesmall)) datesmall = [int(x) for x in datesmall] print print dateexpanded t = 0 for x in ask: if x in punctuation or x in whitespace: returnlist.append(x) t = t - 1 else: m = t while m >= len(datesmall): m = m - len(datesmall) start = lowercase.index(x)+datesmall[m] if start >= 26: start = start-26 returnlist.append(lowercase[start]) t = t+1 inde = 0 for x in copyofask: if x in uppercase: returnlist[inde] = returnlist[inde].upper() inde = inde+1 returnlist = "".join(returnlist) print returnlist print if unordo == 'decipher': date = raw_input('Please type the date on the message. ') ask = raw_input('Please type the message. ') copyofdate = date copyofask = ask returnlist = [] ask = list(ask.lower()) month = time.strptime(date,'%B %d, %Y') datesmall = time.strftime('%m %d %y',month).split(" ") datesmall = [str(int(x)) for x in datesmall] datesmall = list("".join(datesmall)) datesmall = [int(x) for x in datesmall] t = 0 for x in ask: if x in punctuation or x in whitespace: returnlist.append(x) t = t - 1 else: m = t while m >= len(datesmall): m = m - len(datesmall) start = lowercase.index(x)-datesmall[m] if start >= 26: start = start-26 returnlist.append(lowercase[start]) t = t+1 inde = 0 for x in copyofask: if x == x.upper(): returnlist[inde] = returnlist[inde].upper() inde = inde+1 returnlist = "".join(returnlist) print print copyofdate print returnlist print if type == 'morse code': morseletters = ['*-','-***','-*-*','-**','*','**-*','--*','****','**','*---','-*-','*-**',' --','-*','---','*--*','--*-','*-*','***','-','**-','***-','*--','-**-','-*-- ','--**'] morsedigits = ['-----','*----','**---','***--','****-','*****','-****','--***','---**','-- --*'] if unordo == 'cipher': ask = (raw_input('Give me text in English. ').lower()) returnlist = [] for x in ask: if x in punctuation or x in whitespace: returnlist.append(x) else: ind = lowercase.index(x) returnlist.append(morseletters[ind]) returnlist = " ".join(returnlist).replace(" "," ]|[ ") print print returnlist print if unordo == 'decipher': returnlist = [] words = raw_input('Please give me the morse code -- letters seperated by one space -- words by two. ').split(' ') for x in words: for m in x.split(" "): ind = morseletters.index(m) returnlist.append(lowercase[ind]) returnlist.append(' ') returnlist = "".join(returnlist) print print returnlist print if type == 'pig latin' or type == 'piglatin': vowels = 'aeiouyAEIOUY' if unordo == 'cipher': words = raw_input('Give me text in English. ').split(' ') for x in words: x = list(x) a = '' if x[-1] in punctuation: a = x.pop() if x[0] in vowels: x.append('yay') else: letter = x.pop(0) x.append(letter) x.append('ay') x.append(a) x = "".join(x) ask = " ".join(words) print print ask print if unordo == 'decipher': words = raw_input('iveGay emay hetay igPay atinLay, owNay!!! ').split(' ') for x in words: a = '' x = list(x) end = '' if x[-1] in punctuation: end = x.pop() if x[-3:] == ['y','a','y']: del x[-3:] else: del x[-2:] a = x.pop() x[0:0] = a x.append(end) x = "".join(x) ask = " ".join(words) print print ask print > I am getting user input and comparing it to an iterated list. I can get the > input to print out verbatim. I want to then "swap" individual letters in the > input with letters from a second list so it is like a simple encryption. I > can't figure out the correct logic or syntax. Here is what I have so far: > > user = raw_input("Enter your selection: ") > > > > encrypt = > ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s' ,'t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L' ,'M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','0','1','2','3','4' ,'5','6','7','8','9','0'] > > decrypt > =['b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t ','u','v','w','x','y','z','a','B','C','D','E','F','G','H','I','J','K','L','M ','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','A','0','1','2','3','4 ','5','6','7','8','9','0'] > > > for i in range(len(encrypt)): > print user[0:62] > break > > for j in range(len(decrypt)): > for j in zip(decrypt): > print 'Encrypted-> %s' % (j,user) > break > > This does not work. Any suggestions? > > Thanks > Jim DeCaro > Microsoft Certified Systems Engineer > Windows 2000 - Windows NT 4.0 + Internet > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From kent37 at tds.net Fri Dec 3 04:12:42 2004 From: kent37 at tds.net (Kent Johnson) Date: Fri Dec 3 04:12:47 2004 Subject: [Tutor] unittest.makeSuite question In-Reply-To: <7d7029e70412021715742b759e@mail.gmail.com> References: <20041202233940.92871.qmail@web25809.mail.ukl.yahoo.com> <7d7029e70412021715742b759e@mail.gmail.com> Message-ID: <41AFD9AA.1030904@tds.net> makeSuite() creates a TestSuite object that consolidates all the test methods of the class named by the first argument. Test methods are identified by having names starting with the second argument. 'test' is the default value so you could omit it; in fact the most recent documentation does omit this argument. If you wanted to name your test methods something different you could use this argument to change it. The basic pattern shown in the first page of the tutorial will work for most unit testing. It also shows a use of makeSuite(), but you can easily get by without using makeSuite(). http://docs.python.org/lib/node160.html The page on "Organizing Test Code" is, IMO, more confusing than helpful. It shows some of the building blocks of tests and some ways of using unittest that I have never seen in practice. HTH Kent Guillermo Fernandez Castellanos wrote: > Hi, > > I've been through the unittest tutorial page and I've seen this function: > suite = unittest.makeSuite(Testname,'test') > > In the python 2.4 Python Library Reference I have find no reference to > such a fucntion (there is an example, exactly the same but without the > 'test' parameter). > > I could not really understand the sources neither... > > What is the 'test' parameter? Is there another possible values? Any > reference of the function? > > Thanks! > > Guille > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From cyresse at gmail.com Fri Dec 3 04:36:35 2004 From: cyresse at gmail.com (Liam Clarke) Date: Fri Dec 3 04:36:38 2004 Subject: [Tutor] programming newbie question In-Reply-To: <00cc01c4d8e5$a0ff8ff0$c15328cf@JSLAPTOP> References: <16044.156.153.255.243.1099587688.squirrel@phome.pointclark.net> <00cc01c4d8e5$a0ff8ff0$c15328cf@JSLAPTOP> Message-ID: IMAP / POP3 /SMTP connections/sessions as objects are very useful, as you can pass them from function to function. On Thu, 2 Dec 2004 21:50:20 -0500, Jacob S. wrote: > > I am fairly new to programming and I have started to learn programming > > then stopped out of frustration several times in the past. I guess my > > frustration stems from not being able to understand when to use certain > > aspects of programming such as functions or classes. > > Use functions when you will execute a certain code block many, many times > during a script. Or if you want to make a code block simpler and more > generic. For example... > > def rfill(stri,length,sep=" "): # stri is short for string, and sep > (seperator) is defaulted to a space > stri = str(stri) # This is to help make sure that what the user gives us > is a string > if stri < length: > stri = stri + sep*(length-len(stri)) # This fills the string to the > length with seperators > return stri # This returns the string so we can assign it, print it etc. > > Usage is as follows: > > a = 'The' > b = 'Many' > c = 'Two' > e = 'Forty' > f = [a,b,c,e] > for i in range(4): > print "%s%d" % (rfill(f[i],15),i) > > yields > > The 0 > Many 1 > Two 2 > Forty 3 > > This is just one example. You can use functions over and over from anywhere > in your script. > Classes are just like defining new types. You have the usual types like > dictionary, list, tuple, integer, float, etc. but with classes you can > define your own. Methods are just attributes of classes, or so I understand. > For example... > > class MyClass: > def __init__(self,pos=[0,1,0]): > self.pos = pos > def printpos(self): > print self.pos > > Which in turn can be used like this. > > >>> a = MyClass() ## pos defaults to [0,1,0] so I don't have to specify > explicitly > >>> print a.pos > [1,0,1] > >>> a.pos = [1,2,1] > >>> a.printpos() > [1,2,1] > >>> > > The most interesting use of classes that I have seen is the VPython package > where they define new classes (again I think of them as types) as shapes > with attributes (or methods - like L.append() which refers to appending to > lists) like position, color, radius, axis, etc. > But I digress. > > HTH, > Jacob Schmidt > > > > > I have read enough > > books and tutorials to know the syntax of python and I understand most > > everything related to the concepts of programming, but I have never been > > able to put it all together and learn how and when to use specific > > features. Can anyone suggest a method or some reading to help out with > > this? I also struggle with finding projects to work on does anyone know > > of projects that a novice could contribute to? > > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From dshemwell at charter.net Fri Dec 3 05:10:42 2004 From: dshemwell at charter.net (Daniel) Date: Fri Dec 3 05:08:54 2004 Subject: [Tutor] Help Message-ID: <3khj1f$doq186@mxip06a.cluster1.charter.net> I need to know how to run another module through one what is the command do I have to include a path name and if there is any special way I have to save the file -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041202/d024e307/attachment.htm From ramster6 at gmail.com Fri Dec 3 07:08:25 2004 From: ramster6 at gmail.com (Ramkumar Parimal Alagan) Date: Fri Dec 3 07:08:29 2004 Subject: [Tutor] backup failed - gzip In-Reply-To: <82c0f73b04120220241d0ac@mail.gmail.com> References: <82c0f73b041201225319da0cf3@mail.gmail.com> <82c0f73b04120220241d0ac@mail.gmail.com> Message-ID: <82c0f73b041202220849ccafe3@mail.gmail.com> This is what i intend to do: 1. The files and directories to be backed up are given in a list. 2. The backup must be stored in a main backup directory. 3. The files are backed up into a zip file. 4. The name of the zip archive is the current date and time. the coding: ______________ import os import time source = ['D:\\down', 'D:\\Pics'] target_dir = 'D:\\backup' target = target_dir + time.strftime('%Y%m%d%H%M%S') + '.zip' zip_command = "zip -qr '%s' %s" % (target, ' '.join(source)) if os.system(zip_command) == 0: print 'Successful backup to', target else: print 'Backup FAILED' _____________________________ result : Backup FAILED whats wrong ? From cyresse at gmail.com Fri Dec 3 07:46:14 2004 From: cyresse at gmail.com (Liam Clarke) Date: Fri Dec 3 07:46:19 2004 Subject: [Tutor] backup failed - gzip In-Reply-To: <82c0f73b041202220849ccafe3@mail.gmail.com> References: <82c0f73b041201225319da0cf3@mail.gmail.com> <82c0f73b04120220241d0ac@mail.gmail.com> <82c0f73b041202220849ccafe3@mail.gmail.com> Message-ID: As the below quote from the manual shows - On Windows, the return value is that returned by the system shell after running command, given by the Windows environment variable COMSPEC: on command.com systems (Windows 95, 98 and ME) this is always 0; on cmd.exe systems (Windows NT, 2000 and XP) this is the exit status of the command run; on systems using a non-native shell, consult your shell documentation. Your return value is OS specific. What OS are you using? Did you check to see if your zip files were created? It may just be a funky return code. On Fri, 3 Dec 2004 12:08:25 +0600, Ramkumar Parimal Alagan wrote: > This is what i intend to do: > > 1. The files and directories to be backed up are given in a list. > 2. The backup must be stored in a main backup directory. > 3. The files are backed up into a zip file. > 4. The name of the zip archive is the current date and time. > > the coding: > > ______________ > > import os > import time > > source = ['D:\\down', 'D:\\Pics'] > > target_dir = 'D:\\backup' > > target = target_dir + time.strftime('%Y%m%d%H%M%S') + '.zip' > > zip_command = "zip -qr '%s' %s" % (target, ' '.join(source)) > > if os.system(zip_command) == 0: > print 'Successful backup to', target > else: > print 'Backup FAILED' > > _____________________________ > > result : Backup FAILED > > whats wrong ? > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From dyoo at hkn.eecs.berkeley.edu Fri Dec 3 08:54:11 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Dec 3 08:54:14 2004 Subject: [Tutor] gzip (fwd) Message-ID: Hi Ramkumar, I'm forwarding your message to Python-tutor; in your replies, please make sure that you are using the "reply-to-all" feature in your email client. This will allow your response to reach the others on the tutor list. Don't rely on me alone: give the community the chance to help you. I don't have enough information to pinpoint what the problem is yet. I'll have to ask more questions, and others on the Tutor list will probably also ask a few questions. Please try to answer them, because that will help us give a better idea of what the problem is. It looks like you are trying to zip up whole directories. Does the program work if you zip up single files? It also appears that you're using the '-q' and '-r' options of the 'zip' command line utility. '-q' stands for 'quiet' mode, and although that's nice when the command is working properly, it's not helpful when you're debugging a situation. Try turning quiet mode off, so that you have a better chance of getting good error output from the zip command. Even better, try enabling verbose mode, so you can see better what 'zip' is attempting to do. Do you see anything else when you execute the program? Does anything else come out of standard error? Good luck to you. ---------- Forwarded message ---------- Date: Fri, 3 Dec 2004 10:24:15 +0600 From: Ramkumar Parimal Alagan To: Danny Yoo Subject: Re: [Tutor] gzip This is what i intend to do: 1. The files and directories to be backed up are given in a list. 2. The backup must be stored in a main backup directory. 3. The files are backed up into a zip file. 4. The name of the zip archive is the current date and time. the coding: ______________ import os import time source = ['D:\\down', 'D:\\Pics'] target_dir = 'D:\\backup' target = target_dir + time.strftime('%Y%m%d%H%M%S') + '.zip' zip_command = "zip -qr '%s' %s" % (target, ' '.join(source)) if os.system(zip_command) == 0: print 'Successful backup to', target else: print 'Backup FAILED' _____________________________ result : Backup FAILED whats wrong ? From dyoo at hkn.eecs.berkeley.edu Fri Dec 3 09:01:10 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Dec 3 09:01:19 2004 Subject: [Tutor] Python 2.4 IDLE Windows 2000 In-Reply-To: Message-ID: > >Yowza; that's some bug. Danny, do you happen to know the bug number? > >I can't find it on sourceforge. > > It's been like that since 2.3 as far as I know. It generates a > connection to localhost to run code in a separate environment. Hi Mike, I wish I knew what the problem was in better detail. IDLE is a part of the Standard Library, so it's actually possible to try turning on individual pieces of it, one after the other. Maybe that will help us debug what's going on. Start up your console version of Python, and try: ### >>> import idlelib.PyShell >>> idlelib.PyShell.main() ### That should start IDLE up manually, and if anything bad happens, at least we should see some errors pop up that will help us debug the situation. Let's make sure this doesn't fail quietly. *grin* Good luck to you! From alan.gauld at freenet.co.uk Fri Dec 3 09:04:25 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Dec 3 09:04:37 2004 Subject: [Tutor] new function and a 3 line program not working References: <000a01c4c4c5$f55d9990$6500a8c0@cdca1h1bro1> <005001c4d63d$62d3bfd0$f1598651@xp> <00ca01c4d8e5$9b61ba00$c15328cf@JSLAPTOP> Message-ID: <003001c4d90e$b55eb970$c6ca8751@xp> > I thought that the '.py ' in this import statement would make the > interpreter think that newline was a package and therefore try to recognize > py as a module in the newline package. > > from newline.py import newline Quite right it should have been from newline import mnewline! oops, sorry. Alan g. From dyoo at hkn.eecs.berkeley.edu Fri Dec 3 09:38:48 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Dec 3 09:38:55 2004 Subject: [Tutor] comapring lists In-Reply-To: <00cf01c4d8e5$a51f7870$c15328cf@JSLAPTOP> Message-ID: On Thu, 2 Dec 2004, Jacob S. wrote: > If you or anybody else is interested, I've written a script for codes like > kids in junior high use to write notes to each other with... Hi Jacob, Cool! Do you mind if I make some comments on the code? If you do mind... um... skip this message. *grin* The main body of the program feels a bit too long: it screams to be broken into a few helper functions. I see that there are two critical variables that are used to figure out which part of the program comes next: ### unordo = raw_input('Are we going to decipher or cipher? ') type = raw_input('Which type of code would you like? ').lower() if type == 'mixed letters': if unordo == 'cipher': # ... do mixed letter ciphering if unordo == 'decipher': # ... do mixed letter deciphering if type == 'insideout': if unordo == 'cipher': # ... do insideout ciphering if unordo == 'decipher': # ... do mixed letter decipering # ... rest of the program follows similar structure ### In a case like this, we can break the program into separate functions, like this: ### def dispatchOnTypeAndUnordo(type, unordo): if type == 'mixed letters': if unordo == 'cipher': mixedLetterCipher() if unordo == 'decipher': mixedLetterDecipher() if type == 'insideout': if unordo == 'cipher': insideoutCipher() if unordo == 'decipher': insideoutDecipher() # ... rest of the program follows similar structure ### We make each 'body' of the inner "if"'s into their own functions, like 'mixedLetterCipher()'. This restructuring doesn't improve the program's performance at all, but it does help readability: the main improvement is to make the overall shape of the program all visible at once. This structural change also paves the way for a "table-driven" way to implement a decision tree. Experienced programmers really try to avoid code that looks like "if/if/if/if/if..." because that's probably some kind of repeating structure that we can take advantage of. The logic on the function dispatchOnTypeAndUnordo() has an internal rhythm that we can capture as a data structure. Here's a dictionary that tries to capture the essentials of the beat: ### dispatchTable = { 'mixed letters': (mixedLetterCipher, mixedLetterDecipher), 'insideout' : (insideOutCipher, insideOutDecipher), ## ... rest of the dictionary follows similar structure } ### [Note: the values in this dictionary --- the function names --- are intentionally without parentheses. We don't want to "call" the functions just yet, but just want to store them off.] If we have a dispatch table like this, then the dispatchOnTypeandUnordo() magically dissolves: ### def dispatchOnTypeAndUnordo(type, unordo): (cipherFunction, decipherFunction) = dispatchTable[type] if unordo == 'cipher': cipherFunction() elif unordo == 'decipher': decipherFunction() ### This is a "table-driven" or "data-driven" approach. The choices available to the program have been migrated away from the explicit, separate 'if' statements, and now really live as part of the 'dispatchTable' dictionary. Does this make sense so far? Please feel free to ask questions. From dyoo at hkn.eecs.berkeley.edu Fri Dec 3 09:50:07 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Dec 3 09:50:11 2004 Subject: [Tutor] Help In-Reply-To: <3khj1f$doq186@mxip06a.cluster1.charter.net> Message-ID: On Thu, 2 Dec 2004, Daniel wrote: > I need to know how to run another module through one Hi Daniel, Have you had a chance to look at one of the tutorials on: http://www.python.org/moin/BeginnersGuide_2fNonProgrammers I'm guessing that youe trying to use modules; most of the tutorials show examples of modules in action. Here's a link to one of them: http://www.freenetpages.co.uk/hp/alan.gauld/tutfunc.htm I could be completely misunderstanding your question though; if I am, please be patient with me; I need to sleep more. *grin* > what is the command do I have to include a path name > and if there is any special way I have to save the file I'm not quite sure I understand your other questions yet. I'm guessing that this is related to your first question, but I'm still slightly stuck. Can you tell us what you are trying to do? Good luck! From alan.gauld at freenet.co.uk Fri Dec 3 09:51:05 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Dec 3 09:50:46 2004 Subject: [Tutor] Help References: <3khj1f$doq186@mxip06a.cluster1.charter.net> Message-ID: <006701c4d915$3a4186d0$c6ca8751@xp> > I need to know how to run another module through one what is the command do > I have to include a path name and if there is any special way I have to save > the file See my tutor for more info on modules and functions. The short answer is that if you create a module (ie a python file) and put the code into functions, then you can impot the module and execute the functions. Any code that is not in a function will be executed when you import the module. Thus: ############### # File: mymodule.py print 'welcome to my module' def myfunction(): print 'this is my function' def another(): return 42 ################## ################# # file myprogram.py import mymodule mymodule.myfunction() print mymodule.another() mymodule.myfunction() ################## When I run myprogram.py I get: welcome to my module this is my function 42 this is my function The first line gets printed by the import statement, the second,third and fourth by the function calls. Notice that the first line can only be generated once but the functions can be used as often as you like. So the best course of action is to put all the module code into functions and you can access those as and when you need them. Notice too that the module is just a regular python file, there is nothing special needed to make it "a module". Provided it is in the same folder as your program, or anywhere in pythons search path (sys.path) python will import it without need for any path specifications etc. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From revanna at mn.rr.com Fri Dec 3 09:54:06 2004 From: revanna at mn.rr.com (Anna Ravenscroft) Date: Fri Dec 3 09:54:16 2004 Subject: [Tutor] Strange Appending In-Reply-To: <41B05184@wm2.uvic.ca> References: <41B05184@wm2.uvic.ca> Message-ID: <41B029AE.4000401@mn.rr.com> mdcooper wrote: > Hello, > > I am trying to append a list to another list, but everytime I do, the new > parent list has a new child list, but all the other lists have become the same > as the new child list. > > Code: > > > self._f.write(str(self.residue.atoms[int(t[0])-1].element) + ' ') > for m in t: > self._f.write(str(m)+' ') > self._f.write('\n') > > self.a.append(t) # WHY DOES THIS NOT WORK????? > print self.a > > Output: > > [[1, 234, 543]] > [[1, 234, 548], [1, 234, 548]] > [[1, 234, 59], [1, 234, 59], [1, 234, 59]] > [[1, 237, 543], [1, 237, 543], [1, 237, 543], [1, 237, 543]] > I'm guessing what you mean is: for m in t: self.... # misc filewriting self.a.append(m) # appending *items* of t print self.a See if that little difference works. Anna From dyoo at hkn.eecs.berkeley.edu Fri Dec 3 10:05:26 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Dec 3 10:05:52 2004 Subject: [Tutor] unittest.makeSuite question In-Reply-To: <41AFD9AA.1030904@tds.net> Message-ID: On Thu, 2 Dec 2004, Kent Johnson wrote: > makeSuite() creates a TestSuite object that consolidates all the test > methods of the class named by the first argument. Test methods are > identified by having names starting with the second argument. [text cut] The unit testing framework is closely related to a similar system written in Java called "JUnit", and the JUnit folks have written a nice tutorial on the concepts behind their framework: http://junit.sourceforge.net/doc/testinfected/testing.htm I highly recommend the article... even if the programming language syntax seems a bit stuffy. *grin* The authors do a good job to explain the core ideas behind unit testing. One is that a "suite" is a collection of tests. With a suite, we can glue a bunch of tests together. Being able to aggregate tests doesn't sound too sexy, but it's actually very powerful. As a concrete example, we can write a module that dynamically aggregates all unit tests in a directory into a single suite: ### """test_all.py: calls all the 'test_*' modules in the current directory. Danny Yoo (dyoo@hkn.eecs.berkeley.edu) """ import unittest from glob import glob from unittest import defaultTestLoader def suite(): s = unittest.TestSuite() for moduleName in glob("test_*.py"): if moduleName == 'test_all.py': continue testModule = __import__(moduleName[:-3]) s.addTest(defaultTestLoader.loadTestsFromModule(testModule)) return s if __name__ == '__main__': unittest.TextTestRunner().run(suite()) ### Here, we search for all the other test classes in our relative vicinity, and start adding them to our test suite. We then run them en-masse. And now we have a "regression test" that exercises all the test classes in a package. Hope this helps! From ramster6 at gmail.com Fri Dec 3 10:16:27 2004 From: ramster6 at gmail.com (Ramkumar Parimal Alagan) Date: Fri Dec 3 10:16:32 2004 Subject: [Tutor] gzip (fwd) In-Reply-To: References: Message-ID: <82c0f73b041203011670566c48@mail.gmail.com> I have only 2 word documents in both the directories, i tried removing '-qr' too, but no change, no zip files formed. i'm using windows XP. On Thu, 2 Dec 2004 23:54:11 -0800 (PST), Danny Yoo wrote: > Hi Ramkumar, > > I'm forwarding your message to Python-tutor; in your replies, please make > sure that you are using the "reply-to-all" feature in your email client. > This will allow your response to reach the others on the tutor list. > Don't rely on me alone: give the community the chance to help you. > > I don't have enough information to pinpoint what the problem is yet. I'll > have to ask more questions, and others on the Tutor list will probably > also ask a few questions. Please try to answer them, because that will > help us give a better idea of what the problem is. > > It looks like you are trying to zip up whole directories. Does the > program work if you zip up single files? > > It also appears that you're using the '-q' and '-r' options of the 'zip' > command line utility. '-q' stands for 'quiet' mode, and although that's > nice when the command is working properly, it's not helpful when you're > debugging a situation. Try turning quiet mode off, so that you have a > better chance of getting good error output from the zip command. Even > better, try enabling verbose mode, so you can see better what 'zip' is > attempting to do. > > Do you see anything else when you execute the program? Does anything else > come out of standard error? > > Good luck to you. > > ---------- Forwarded message ---------- > Date: Fri, 3 Dec 2004 10:24:15 +0600 > From: Ramkumar Parimal Alagan > To: Danny Yoo > Subject: Re: [Tutor] gzip > > This is what i intend to do: > > 1. The files and directories to be backed up are given in a list. > 2. The backup must be stored in a main backup directory. > 3. The files are backed up into a zip file. > 4. The name of the zip archive is the current date and time. > > the coding: > > ______________ > > import os > import time > > source = ['D:\\down', 'D:\\Pics'] > > target_dir = 'D:\\backup' > > target = target_dir + time.strftime('%Y%m%d%H%M%S') + '.zip' > > zip_command = "zip -qr '%s' %s" % (target, ' '.join(source)) > > if os.system(zip_command) == 0: > print 'Successful backup to', target > else: > print 'Backup FAILED' > > _____________________________ > > result : Backup FAILED > > whats wrong ? > > -- << The end depends upon the beginning. >> From matthew.williams at cancer.org.uk Fri Dec 3 12:50:55 2004 From: matthew.williams at cancer.org.uk (Matt Williams) Date: Fri Dec 3 12:51:04 2004 Subject: [Tutor] Creating & Handling lots of objects Message-ID: <1102074655.2956.8.camel@dhcp0320.acl.icnet.uk> Dear Tutor-list, I'm sorry for this appallingly dumb question, but I'm having a little problem with objects. I've written a class, with some methods. I then want to be able to call the class repeatedly, to create some objects. The number of objects, and some of their initialisation parameters need to be specified later (i.e. at run-time). When I generate all these objects, how do I keep track of them. For a finite (and small) number I can do this: a=MyClass("a") b=MyClass("b") but this is obviously not scaleable. If I use a list, I can do: MyObjects=[] l=["a","b","c"] for i in l: MyObjects.add(MyClass(i)) but then I have to search the list (MyObjects) for the object where Object.name="a". The only other option seems to be finding objects via their hash codes, which I'm sure isn't right I'd like to be able to automate something closer to the a=MyClass("a") but don't know how to do it....It may be that I'm trying to do it very badly, which is Python seems to make it hard for me. Thanks, Matt From kent37 at tds.net Fri Dec 3 13:41:34 2004 From: kent37 at tds.net (Kent Johnson) Date: Fri Dec 3 13:41:39 2004 Subject: [Tutor] Creating & Handling lots of objects In-Reply-To: <1102074655.2956.8.camel@dhcp0320.acl.icnet.uk> References: <1102074655.2956.8.camel@dhcp0320.acl.icnet.uk> Message-ID: <41B05EFE.20205@tds.net> If you want to be able to access the objects by name, you can put them in a dict. For example, MyObjects={} l=["a","b","c"] for i in l: MyObjects[i] = MyClass(i) Then you can refer to MyObjects["a"] If all the operations on the objects are done to all objects in a batch, putting them in a list might work. Then you can use list iteration to access all of them: MyObjects=[] l=["a","b","c"] for i in l: MyObjects.add(MyClass(i)) then to process all the objects: for myObj in MyObjects: # do something with myObj Kent Matt Williams wrote: > Dear Tutor-list, > > I'm sorry for this appallingly dumb question, but I'm having a little > problem with objects. > > I've written a class, with some methods. I then want to be able to call > the class repeatedly, to create some objects. The number of objects, and > some of their initialisation parameters need to be specified later (i.e. > at run-time). > > When I generate all these objects, how do I keep track of them. For a > finite (and small) number I can do this: > > a=MyClass("a") > b=MyClass("b") > > but this is obviously not scaleable. If I use a list, I can do: > > MyObjects=[] > l=["a","b","c"] > for i in l: > MyObjects.add(MyClass(i)) > > but then I have to search the list (MyObjects) for the object where > Object.name="a". > > The only other option seems to be finding objects via their hash codes, > which I'm sure isn't right > > I'd like to be able to automate something closer to the a=MyClass("a") > but don't know how to do it....It may be that I'm trying to do it very > badly, which is Python seems to make it hard for me. > > Thanks, > > Matt > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From ARobert at MFS.com Fri Dec 3 13:59:38 2004 From: ARobert at MFS.com (Robert, Andrew) Date: Fri Dec 3 13:59:59 2004 Subject: [Tutor] Creating & Handling lots of objects Message-ID: <968452DD78695147AA4A369C3DF9E40A0209073B@BOSMAILBOX3.corp.mfs.com> Although I have never done so, I believe you can also store/manipulate objects in a database. Has anyone ever worked this option? Thank you, Andrew Robert Systems Architect Information Technology - OpenVMS Massachusetts Financial Services Phone: 617-954-5882 Pager: 781-764-7321 E-mail: arobert@mfs.com Linux User Number: #201204 -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of Kent Johnson Sent: Friday, December 03, 2004 7:42 AM To: Python Tutor Subject: Re: [Tutor] Creating & Handling lots of objects If you want to be able to access the objects by name, you can put them in a dict. For example, MyObjects={} l=["a","b","c"] for i in l: MyObjects[i] = MyClass(i) Then you can refer to MyObjects["a"] If all the operations on the objects are done to all objects in a batch, putting them in a list might work. Then you can use list iteration to access all of them: MyObjects=[] l=["a","b","c"] for i in l: MyObjects.add(MyClass(i)) then to process all the objects: for myObj in MyObjects: # do something with myObj Kent Matt Williams wrote: > Dear Tutor-list, > > I'm sorry for this appallingly dumb question, but I'm having a little > problem with objects. > > I've written a class, with some methods. I then want to be able to call > the class repeatedly, to create some objects. The number of objects, and > some of their initialisation parameters need to be specified later (i.e. > at run-time). > > When I generate all these objects, how do I keep track of them. For a > finite (and small) number I can do this: > > a=MyClass("a") > b=MyClass("b") > > but this is obviously not scaleable. If I use a list, I can do: > > MyObjects=[] > l=["a","b","c"] > for i in l: > MyObjects.add(MyClass(i)) > > but then I have to search the list (MyObjects) for the object where > Object.name="a". > > The only other option seems to be finding objects via their hash codes, > which I'm sure isn't right > > I'd like to be able to automate something closer to the a=MyClass("a") > but don't know how to do it....It may be that I'm trying to do it very > badly, which is Python seems to make it hard for me. > > Thanks, > > Matt > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor "MFS Relay Service" made the following annotations on 12/03/2004 08:05:23 AM ------------------------------------------------------------------------------ This email communication and any attachments may contain proprietary, confidential, or privileged information. If you are not the intended recipient, you are hereby notified that you have received this email in error and that any review, disclosure, dissemination, distribution or copying of it or its contents is prohibited. The sender does not waive confidentiality or any privilege by mistransmission. If you have received this email in error, please notify the sender immediately, delete this email, and destroy all copies and any attachments. ============================================================================== From mhansen at cso.atmel.com Fri Dec 3 15:52:22 2004 From: mhansen at cso.atmel.com (Mike Hansen) Date: Fri Dec 3 15:52:55 2004 Subject: [Tutor] Python 2.4 IDLE Windows 2000 In-Reply-To: References: Message-ID: <41B07DA6.1030703@cso.atmel.com> That rooted out the problem. A while ago, I changed the colors to kind of match my VIM color theme(ps_color). When I did idlelib.PyShell.main(), IDLE came up with my custom color theme. However, there was a bunch of warnings about my theme. From IDLE, I deleted the theme. Now IDLE will launch normally. I'll set up the color theme later. Maybe older color themes aren't compatible with the newer IDLE? The color theme must have been laying around. I didn't brute force it in or anything like that. I appreciate the help. Mike Danny Yoo wrote: > > >>>Yowza; that's some bug. Danny, do you happen to know the bug number? >>>I can't find it on sourceforge. >>> >>> >>It's been like that since 2.3 as far as I know. It generates a >>connection to localhost to run code in a separate environment. >> >> > >Hi Mike, > >I wish I knew what the problem was in better detail. IDLE is a >part of the Standard Library, so it's actually possible to try turning on >individual pieces of it, one after the other. Maybe that will help us >debug what's going on. > >Start up your console version of Python, and try: > >### > > >>>>import idlelib.PyShell >>>>idlelib.PyShell.main() >>>> >>>> >### > >That should start IDLE up manually, and if anything bad happens, at least >we should see some errors pop up that will help us debug the situation. >Let's make sure this doesn't fail quietly. *grin* > > >Good luck to you! > > > From dyoo at hkn.eecs.berkeley.edu Fri Dec 3 19:01:07 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Dec 3 19:01:17 2004 Subject: [Tutor] Python 2.4 IDLE Windows 2000 In-Reply-To: <41B07DA6.1030703@cso.atmel.com> Message-ID: On Fri, 3 Dec 2004, Mike Hansen wrote: > That rooted out the problem. A while ago, I changed the colors to kind > of match my VIM color theme(ps_color). When I did > idlelib.PyShell.main(), IDLE came up with my custom color theme. > However, there was a bunch of warnings about my theme. From IDLE, I > deleted the theme. Now IDLE will launch normally. I'll set up the color > theme later. Maybe older color themes aren't compatible with the newer > IDLE? The color theme must have been laying around. I didn't brute force > it in or anything like that. Hi Mike, Ah, whew, I'm glad that actually worked. *grin* The information about the color theme problem is valuable to know: can you send a message to the IDLE developers with a summary of the situation? It's possible that a lot of other folks might be running into a similar startup problem. Let's make sure that no one else has to go through hoops to get IDLE working again. The IDLE development list is: http://mail.python.org/mailman/listinfo/idle-dev Good luck to you! From davholla2002 at yahoo.co.uk Fri Dec 3 21:11:19 2004 From: davholla2002 at yahoo.co.uk (David Holland) Date: Fri Dec 3 21:11:21 2004 Subject: [Tutor] Create a binary for a python game In-Reply-To: <20041203090551.4970B1E4012@bag.python.org> Message-ID: <20041203201119.76966.qmail@web25401.mail.ukl.yahoo.com> I have created a simple python game and I would like to convert it into a binary executable that can be used to play it in Linux without needing the various libraries (pygame etc). Is this possible ? ___________________________________________________________ Win a castle for NYE with your mates and Yahoo! Messenger http://uk.messenger.yahoo.com From ARobert at MFS.com Fri Dec 3 21:17:33 2004 From: ARobert at MFS.com (Robert, Andrew) Date: Fri Dec 3 21:18:51 2004 Subject: [Tutor] Create a binary for a python game Message-ID: <968452DD78695147AA4A369C3DF9E40A02090C53@BOSMAILBOX3.corp.mfs.com> Sure is. Try cx_freeze. It can be found at http://starship.python.net/crew/atuining/cx_Freeze/index.html . I've used it with great success. Thank you, Andrew Robert Systems Architect Information Technology - OpenVMS Massachusetts Financial Services Phone: 617-954-5882 Pager: 781-764-7321 E-mail: arobert@mfs.com Linux User Number: #201204 -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of David Holland Sent: Friday, December 03, 2004 3:11 PM To: tutor@python.org Subject: [Tutor] Create a binary for a python game I have created a simple python game and I would like to convert it into a binary executable that can be used to play it in Linux without needing the various libraries (pygame etc). Is this possible ? ___________________________________________________________ Win a castle for NYE with your mates and Yahoo! Messenger http://uk.messenger.yahoo.com _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor "MFS Relay Service" made the following annotations on 12/03/2004 03:23:18 PM ------------------------------------------------------------------------------ This email communication and any attachments may contain proprietary, confidential, or privileged information. If you are not the intended recipient, you are hereby notified that you have received this email in error and that any review, disclosure, dissemination, distribution or copying of it or its contents is prohibited. The sender does not waive confidentiality or any privilege by mistransmission. If you have received this email in error, please notify the sender immediately, delete this email, and destroy all copies and any attachments. ============================================================================== From ps_python at yahoo.com Fri Dec 3 22:23:56 2004 From: ps_python at yahoo.com (kumar s) Date: Fri Dec 3 22:23:59 2004 Subject: [Tutor] Python regular expression Message-ID: <20041203212356.9959.qmail@web53707.mail.yahoo.com> Dear group, I have a file with 645,984 lines. This file is composedcompletely of bocks. For e.g. [Unit111] Name=NONE Direction=2 NumAtoms=16 NumCells=32 UnitNumber=111 UnitType=3 NumberBlocks=1 [Unit111_Block1] Name=31318_at BlockNumber=1 NumAtoms=16 NumCells=32 StartPosition=0 StopPosition=15 CellHeader=X Y PROBE FEAT QUAL EXPOS POS CBASE PBASE TBASE ATOM INDEX CODONIND CODON REGIONTYPE REGION Cell1=24 636 N control 31318_at 0 13 A A A 0 407064 -1 -1 99 Cell2=24 635 N control 31318_at 0 13 A T A 0 406424 -1 -1 99 Cell3=631 397 N control 31318_at 1 13 T A T 1 254711 -1 -1 99 [Unit113] Name=NONE Direction=2 NumAtoms=16 NumCells=32 UnitNumber=113 UnitType=3 NumberBlocks=1 [Unit113_Block1] Name=31320_at BlockNumber=1 NumAtoms=16 NumCells=32 StartPosition=0 StopPosition=15 CellHeader=X Y PROBE FEAT QUAL EXPOS POS CBASE PBASE TBASE ATOM INDEX CODONIND CODON REGIONTYPE REGION Cell1=68 63 N control 31320_at 0 13 T A T 0 40388 -1 -1 99 Cell2=68 64 N control 31320_at 0 13 T T T 0 41028 -1 -1 99 Cell3=99 194 N control 31320_at 1 13 C C C 1 124259 -1 -1 99 I have a file with identifiers that are found in the first file as : Name=31320_at I am interested in getting lines of block that are present in first to be written as a file. I am search: search = re.search ["_at") my question: how can i tell python to select some rows that have particular pattern such as [Name] or Name of [Unit]. is there any way of doing this. please help me thanks kumar __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From rick_muller at yahoo.com Fri Dec 3 22:34:17 2004 From: rick_muller at yahoo.com (Rick Muller) Date: Fri Dec 3 22:34:24 2004 Subject: [Tutor] Python regular expression In-Reply-To: <20041203212356.9959.qmail@web53707.mail.yahoo.com> Message-ID: <20041203213417.49502.qmail@web42004.mail.yahoo.com> The file type you mention is also called an INI file, and is used for Windows initialization scripts, among other things. There's a nice recipe on this in the Python Cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65334 This will read your file in as a dictionary. You can then do searches through lists of the keys: mydict = LoadConfig(file.ini) for key in mydict.keys(): if re.search(key,"_at"): do_something(mydict[key]) --- kumar s wrote: > Dear group, > > I have a file with 645,984 lines. This file is > composedcompletely of bocks. > > For e.g. > > [Unit111] > Name=NONE > Direction=2 > NumAtoms=16 > NumCells=32 > UnitNumber=111 > UnitType=3 > NumberBlocks=1 > > [Unit111_Block1] > Name=31318_at > BlockNumber=1 > NumAtoms=16 > NumCells=32 > StartPosition=0 > StopPosition=15 > CellHeader=X Y PROBE FEAT QUAL EXPOS POS CBASE PBASE > TBASE ATOM INDEX CODONIND CODON REGIONTYPE REGION > Cell1=24 636 N control 31318_at 0 13 A A A 0 407064 > -1 > -1 99 > Cell2=24 635 N control 31318_at 0 13 A T A 0 406424 > -1 > -1 99 > Cell3=631 397 N control 31318_at 1 13 T A T 1 254711 > -1 -1 99 > > > > [Unit113] > Name=NONE > Direction=2 > NumAtoms=16 > NumCells=32 > UnitNumber=113 > UnitType=3 > NumberBlocks=1 > > [Unit113_Block1] > Name=31320_at > BlockNumber=1 > NumAtoms=16 > NumCells=32 > StartPosition=0 > StopPosition=15 > CellHeader=X Y PROBE FEAT QUAL EXPOS POS CBASE PBASE > TBASE ATOM INDEX CODONIND CODON REGIONTYPE REGION > Cell1=68 63 N control 31320_at 0 13 T A T 0 40388 -1 > -1 99 > Cell2=68 64 N control 31320_at 0 13 T T T 0 41028 -1 > -1 99 > Cell3=99 194 N control 31320_at 1 13 C C C 1 124259 > -1 > -1 99 > > > > > > I have a file with identifiers that are found in the > first file as : > Name=31320_at > > > I am interested in getting lines of block that are > present in first to be written as a file. > > I am search: > > search = re.search ["_at") > > > my question: > how can i tell python to select some rows that have > particular pattern such as [Name] or Name of [Unit]. > > is there any way of doing this. > please help me > > thanks > kumar > > __________________________________________________ > 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 > ===== Rick Muller rick_muller@yahoo.com __________________________________ Do you Yahoo!? Dress up your holiday email, Hollywood style. Learn more. http://celebrity.mail.yahoo.com From maxnoel_fr at yahoo.fr Fri Dec 3 22:43:04 2004 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Fri Dec 3 22:43:18 2004 Subject: [Tutor] Python regular expression In-Reply-To: <20041203213417.49502.qmail@web42004.mail.yahoo.com> References: <20041203213417.49502.qmail@web42004.mail.yahoo.com> Message-ID: <50368CF8-4574-11D9-8ECD-000393CBC88E@yahoo.fr> On Dec 3, 2004, at 21:34, Rick Muller wrote: > The file type you mention is also called an INI file, > and is used for Windows initialization scripts, among > other things. > > There's a nice recipe on this in the Python Cookbook: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65334 > > This will read your file in as a dictionary. You can > then do searches through lists of the keys: > > mydict = LoadConfig(file.ini) > for key in mydict.keys(): > if re.search(key,"_at"): do_something(mydict[key]) Given the size of the file, I don't think that's a good idea... -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From rick_muller at yahoo.com Fri Dec 3 23:31:42 2004 From: rick_muller at yahoo.com (Rick Muller) Date: Fri Dec 3 23:31:45 2004 Subject: [Tutor] Python regular expression In-Reply-To: <50368CF8-4574-11D9-8ECD-000393CBC88E@yahoo.fr> Message-ID: <20041203223142.49597.qmail@web42001.mail.yahoo.com> Well, you could *try* ;-). Okay, here's a one-pass approach: #!/usr/bin/env python import re # Regular expressions stolen from PyCookbook: # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/132326 sec = re.compile(r'^\[(.*)\]') eq = re.compile(r'^([^=]+)=(.*)') def main(fname='file.ini',pattern='_at'): holder = None pat = re.compile(pattern) for line in open(fname).xreadlines(): if sec.match(line): # We've found a new section. Before we overwrite the # holder dictionary, search through the last one if holder and holder.has_key('Name') and pat.search(holder['Name']): print holder # Now create a new dictionary section_name = sec.findall(line)[0] holder = dict(section_name=section_name) if eq.match(line): key,val = eq.findall(line)[0][:2] holder[key] = val return if __name__ == '__main__': main() --- Max Noel wrote: > > On Dec 3, 2004, at 21:34, Rick Muller wrote: > > > The file type you mention is also called an INI > file, > > and is used for Windows initialization scripts, > among > > other things. > > > > There's a nice recipe on this in the Python > Cookbook: > > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65334 > > > > This will read your file in as a dictionary. You > can > > then do searches through lists of the keys: > > > > mydict = LoadConfig(file.ini) > > for key in mydict.keys(): > > if re.search(key,"_at"): > do_something(mydict[key]) > > Given the size of the file, I don't think that's a > good idea... > > -- Max > maxnoel_fr at yahoo dot fr -- ICQ #85274019 > "Look at you hacker... A pathetic creature of meat > and bone, panting > and sweating as you run through my corridors... How > can you challenge a > perfect, immortal machine?" > > ===== Rick Muller rick_muller@yahoo.com __________________________________ Do you Yahoo!? Send a seasonal email greeting and help others. Do good. http://celebrity.mail.yahoo.com From alan.gauld at freenet.co.uk Sat Dec 4 01:14:43 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat Dec 4 01:14:11 2004 Subject: [Tutor] Creating & Handling lots of objects References: <1102074655.2956.8.camel@dhcp0320.acl.icnet.uk> Message-ID: <00ba01c4d996$418232b0$c6ca8751@xp> > I've written a class, with some methods. I then want to be able to call > the class repeatedly, to create some objects. The number of objects, and > some of their initialisation parameters need to be specified later (i.e. > at run-time). Not quite sure what you mean by the last bit but I'll come back to that... > When I generate all these objects, how do I keep track of them. Check out the OOP topic in my tutor, it discusses this within the context of a bank account example - how to manage large numbers of account holders. The short answer is put them in a list or dictionary. > but this is obviously not scaleable. If I use a list, I can do: > ... > but then I have to search the list (MyObjects) for the object where > Object.name="a". > > The only other option seems to be finding objects via their hash codes, > which I'm sure isn't right Why not? After all Python uses dictionaries(hashes) for all of its variables, and every object is an instance of a dictionary which holds all the attributes... This is exactly the kind of thing hashes are for. As for using different initialisation parameters. Do you mean different types of values or just different values? If the former - like Java/C++ having multiple constructors - then the best approach is to use named parameters - look at how Tkinter does this as a good example. class C: def __init__(self, a=None, b=None, c=None, d=None) # do stuff here now provided you can think up some suitable default values you can init your object with any combination of a,b,c and d you like like this: c1 = C(a="fred",d=42) c2 = C(b=27,d=0) c3 = C(a="joe", c=[1,2,3]) and so on... I'm not sure if thats what you wanted but if not post again to clarify... Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Sat Dec 4 01:18:10 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat Dec 4 01:17:43 2004 Subject: [Tutor] Creating & Handling lots of objects References: <968452DD78695147AA4A369C3DF9E40A0209073B@BOSMAILBOX3.corp.mfs.com> Message-ID: <00c101c4d996$bd349c40$c6ca8751@xp> > Although I have never done so, I believe you can also > store/manipulate objects in a database. You can but its a lot slower than memory - but a lot more scaleale too! > Has anyone ever worked this option? Yes, lots of times. In fact most large scale projects will need to save objects to some kind of persistent store eventually. This could be a text file (see my tutor for an example) or a full blown database. Foor simple persistence the pickle and shelve modules are useful. If you need to do random access and searches then a full RDBMS like MySQL will be better. An Object database might also work - I believe Zope has one but I've never used it, nor even read up on it... Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Sat Dec 4 01:21:10 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat Dec 4 01:20:35 2004 Subject: [Tutor] Python regular expression References: <20041203212356.9959.qmail@web53707.mail.yahoo.com> Message-ID: <00ce01c4d997$285c8e60$c6ca8751@xp> Have you looked at the ConfigParser module that was mentioned earlier today? Your file fits its format exactly... But regular expressions can be used, try the intro in my tutorial, or the excellent HowTo on the Python web site... Alan G. ----- Original Message ----- From: "kumar s" To: Sent: Friday, December 03, 2004 9:23 PM Subject: [Tutor] Python regular expression > Dear group, > > I have a file with 645,984 lines. This file is > composedcompletely of bocks. > > For e.g. > > [Unit111] > Name=NONE > Direction=2 > NumAtoms=16 > NumCells=32 > UnitNumber=111 > UnitType=3 > NumberBlocks=1 > > [Unit111_Block1] > Name=31318_at > BlockNumber=1 > NumAtoms=16 > NumCells=32 > StartPosition=0 > StopPosition=15 > CellHeader=X Y PROBE FEAT QUAL EXPOS POS CBASE PBASE > TBASE ATOM INDEX CODONIND CODON REGIONTYPE REGION > Cell1=24 636 N control 31318_at 0 13 A A A 0 407064 -1 > -1 99 > Cell2=24 635 N control 31318_at 0 13 A T A 0 406424 -1 > -1 99 > Cell3=631 397 N control 31318_at 1 13 T A T 1 254711 > -1 -1 99 > > > > [Unit113] > Name=NONE > Direction=2 > NumAtoms=16 > NumCells=32 > UnitNumber=113 > UnitType=3 > NumberBlocks=1 > > [Unit113_Block1] > Name=31320_at > BlockNumber=1 > NumAtoms=16 > NumCells=32 > StartPosition=0 > StopPosition=15 > CellHeader=X Y PROBE FEAT QUAL EXPOS POS CBASE PBASE > TBASE ATOM INDEX CODONIND CODON REGIONTYPE REGION > Cell1=68 63 N control 31320_at 0 13 T A T 0 40388 -1 > -1 99 > Cell2=68 64 N control 31320_at 0 13 T T T 0 41028 -1 > -1 99 > Cell3=99 194 N control 31320_at 1 13 C C C 1 124259 -1 > -1 99 > > > > > > I have a file with identifiers that are found in the > first file as : > Name=31320_at > > > I am interested in getting lines of block that are > present in first to be written as a file. > > I am search: > > search = re.search ["_at") > > > my question: > how can i tell python to select some rows that have > particular pattern such as [Name] or Name of [Unit]. > is there any way of doing this. > please help me > > thanks > kumar > > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection around > http://mail.yahoo.com > > From cyresse at gmail.com Sat Dec 4 07:01:09 2004 From: cyresse at gmail.com (Liam Clarke) Date: Sat Dec 4 07:01:13 2004 Subject: [Tutor] backup failed - gzip In-Reply-To: <82c0f73b0412022301692a9864@mail.gmail.com> References: <82c0f73b041201225319da0cf3@mail.gmail.com> <82c0f73b04120220241d0ac@mail.gmail.com> <82c0f73b041202220849ccafe3@mail.gmail.com> <82c0f73b0412022301692a9864@mail.gmail.com> Message-ID: Hi Rankumar - That's your problem then - if os.system(zip_command) == 0: > > > print 'Successful backup to', target So, os.system() returns 0 for Win 95,98, ME. For XP, it returns whatever the exit code your programme returns . So whatever zip returns, is what os.system() returns, which may or may not be 0. Try rewriting your code to find out like so - import os import os.path import time source = ['D:\\down', 'D:\\Pics'] target_dir = 'D:\\backup' target = target_dir + time.strftime('%Y%m%d%H%M%S') + '.zip' zip_command = "zip -qr '%s' %s" % (target, ' '.join(source)) returnCode=os.system(zip_command) if os.path.isfile(target): print "Back-up succeeded!" print returnCode, " is a successful return code." else: print "Back-up failed." print returnCode, " is an unsuccessful return code." #if os.system(zip_command) == 0: #print 'Successful backup to', target #else: #print 'Backup FAILED' os.path.isfile(path) checks if there is a regular existing file there - i.e. target="c:/windows/win.ini" if not os.path.isfile(target): print "I'm in serious trouble here." Check it out, hope it helps. Regards, Liam Clarke On Fri, 3 Dec 2004 13:01:44 +0600, Ramkumar Parimal Alagan wrote: > Thanks for your reply Liam, I am using Windows Xp > > > > > On Fri, 3 Dec 2004 19:46:14 +1300, Liam Clarke wrote: > > As the below quote from the manual shows - > > > > On Windows, the return value is that returned by the system shell > > after running command, given by the Windows environment variable > > COMSPEC: on command.com systems (Windows 95, 98 and ME) this is always > > 0; on cmd.exe systems (Windows NT, 2000 and XP) this is the exit > > status of the command run; on systems using a non-native shell, > > consult your shell documentation. > > > > Your return value is OS specific. What OS are you using? Did you check > > to see if your zip files were created? It may just be a funky return > > code. > > > > > > > > On Fri, 3 Dec 2004 12:08:25 +0600, Ramkumar Parimal Alagan > > wrote: > > > This is what i intend to do: > > > > > > 1. The files and directories to be backed up are given in a list. > > > 2. The backup must be stored in a main backup directory. > > > 3. The files are backed up into a zip file. > > > 4. The name of the zip archive is the current date and time. > > > > > > the coding: > > > > > > ______________ > > > > > > import os > > > import time > > > > > > source = ['D:\\down', 'D:\\Pics'] > > > > > > target_dir = 'D:\\backup' > > > > > > target = target_dir + time.strftime('%Y%m%d%H%M%S') + '.zip' > > > > > > zip_command = "zip -qr '%s' %s" % (target, ' '.join(source)) > > > > > > if os.system(zip_command) == 0: > > > print 'Successful backup to', target > > > else: > > > print 'Backup FAILED' > > > > > > _____________________________ > > > > > > result : Backup FAILED > > > > > > whats wrong ? > > > _______________________________________________ > > > Tutor maillist - Tutor@python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > -- > > 'There is only one basic human right, and that is to do as you damn well please. > > And with it comes the only basic human duty, to take the consequences. > > > > > -- > > << The end depends upon the beginning. >> > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From cyresse at gmail.com Sat Dec 4 07:08:13 2004 From: cyresse at gmail.com (Liam Clarke) Date: Sat Dec 4 07:08:16 2004 Subject: [Tutor] gzip (fwd) In-Reply-To: <82c0f73b041203011670566c48@mail.gmail.com> References: <82c0f73b041203011670566c48@mail.gmail.com> Message-ID: >target_dir = 'D:\\backup' >target = target_dir +"Zipnametoreplacestrftimeformatstring"+ '.zip' Just noticed this - target_dir("D:\\backup") + "Zipnametoreplacestrftimeformatstring"+ '.zip' = D:\\backupZipnametoreplacestrftimeformatstring.zip No wonder it doesn't work. Try target=target_dir+'\\'+time.strftime('%Y%m%d%H%M%S') + '.zip' Regards, Liam Clarke PS Yes, do use reply to all On Fri, 3 Dec 2004 15:16:27 +0600, Ramkumar Parimal Alagan wrote: > I have only 2 word documents in both the directories, i tried removing > '-qr' too, but no change, no zip files formed. i'm using windows XP. > > On Thu, 2 Dec 2004 23:54:11 -0800 (PST), Danny Yoo > > > wrote: > > Hi Ramkumar, > > > > I'm forwarding your message to Python-tutor; in your replies, please make > > sure that you are using the "reply-to-all" feature in your email client. > > This will allow your response to reach the others on the tutor list. > > Don't rely on me alone: give the community the chance to help you. > > > > I don't have enough information to pinpoint what the problem is yet. I'll > > have to ask more questions, and others on the Tutor list will probably > > also ask a few questions. Please try to answer them, because that will > > help us give a better idea of what the problem is. > > > > It looks like you are trying to zip up whole directories. Does the > > program work if you zip up single files? > > > > It also appears that you're using the '-q' and '-r' options of the 'zip' > > command line utility. '-q' stands for 'quiet' mode, and although that's > > nice when the command is working properly, it's not helpful when you're > > debugging a situation. Try turning quiet mode off, so that you have a > > better chance of getting good error output from the zip command. Even > > better, try enabling verbose mode, so you can see better what 'zip' is > > attempting to do. > > > > Do you see anything else when you execute the program? Does anything else > > come out of standard error? > > > > Good luck to you. > > > > ---------- Forwarded message ---------- > > Date: Fri, 3 Dec 2004 10:24:15 +0600 > > From: Ramkumar Parimal Alagan > > To: Danny Yoo > > Subject: Re: [Tutor] gzip > > > > This is what i intend to do: > > > > 1. The files and directories to be backed up are given in a list. > > 2. The backup must be stored in a main backup directory. > > 3. The files are backed up into a zip file. > > 4. The name of the zip archive is the current date and time. > > > > the coding: > > > > ______________ > > > > import os > > import time > > > > source = ['D:\\down', 'D:\\Pics'] > > > > target_dir = 'D:\\backup' > > > > target = target_dir + time.strftime('%Y%m%d%H%M%S') + '.zip' > > > > zip_command = "zip -qr '%s' %s" % (target, ' '.join(source)) > > > > if os.system(zip_command) == 0: > > print 'Successful backup to', target > > else: > > print 'Backup FAILED' > > > > _____________________________ > > > > result : Backup FAILED > > > > whats wrong ? > > > > > > > -- > > << The end depends upon the beginning. >> > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From marilyn at deliberate.com Sat Dec 4 07:37:46 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Sat Dec 4 07:37:52 2004 Subject: [Tutor] eval and exec Message-ID: Hello Tutors, I'm having trouble understanding the difference between eval and exec. Can anyone explain it to me please? Marilyn Davis -- From bvande at po-box.mcgill.ca Sat Dec 4 10:28:45 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat Dec 4 10:28:52 2004 Subject: [Tutor] eval and exec In-Reply-To: References: Message-ID: <41B1834D.5030801@po-box.mcgill.ca> Marilyn Davis said unto the world upon 2004-12-04 01:37: > Hello Tutors, > > I'm having trouble understanding the difference between eval and exec. > > Can anyone explain it to me please? > > Marilyn Davis > Hi Marilyn, does this help? >>> print a Traceback (most recent call last): File "", line 1, in -toplevel- print a NameError: name 'a' is not defined >>> # as expected, since 'a' doesn't yet point to anything. >>> exec("a = 2 + 40") >>> # this means 'Run the string "a = 2 + 40" by assuming it is Python >>> # code. Python code instructions are called "statements". (See [*] >>> # note below. >>> exec("print a") 42 >>> # As before, run "print a" as code. Since we have run the code in >>> # the string "a = 2 + 40" this is the expected result. >>> eval("print a") Traceback (most recent call last): File "", line 1, in -toplevel- eval("print a") File "", line 1 print a ^ SyntaxError: invalid syntax >>> # Error because eval("print a") means 'take the expression[*] >>> # in the string "print a" and evaluate it (tell me what it points >>> # to). [*] "Expression" means *roughly* "name of some object". Since >>> # 'print a' isn't an object at all but an instruction, eval >>> # complains. (Do watch for more experienced posters to clarify on >>> # the exact meaning of "expression" and "statement". I'm no expert. >>> eval("a = 38 + 4") Traceback (most recent call last): File "", line 1, in -toplevel- eval("a = 38 + 4") File "", line 1 a = 38 + 4 ^ SyntaxError: invalid syntax >>> # Again, an error, as "a = 38 + 4" is a statement (a code >>> # instruction) and eval wants an expression. >>> eval("a == 38 + 4") True >>> # As expected, as "a == 38 + 4" is a string for a complicated name of >>> # True. So, eval evaluates expressions (namelike things) and exec runs strings as though they were Python code. HTH, Brian vdB From alan.gauld at freenet.co.uk Sat Dec 4 10:34:49 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat Dec 4 10:34:52 2004 Subject: [Tutor] eval and exec References: Message-ID: <00f501c4d9e4$80236270$c6ca8751@xp> > I'm having trouble understanding the difference between eval and exec. eval evaluates an *expression* - that is something that returns a value. exec executes a piece of code, it need not return a value. eval is slightly safer than exec (but not much). Some examples: print 'hello' # use exec for this 6+7-9/3 # use eval for this myfunction(42) # use eval for this to make eval useful you need to assign the result to a variable: res = eval('6+7-9/3') but exec is just executed on its own: exec('print "hello"') Both are extremely dangerous functions from a security and maintenance/reliability pouint of view and should be used very rarely. Was there anything more specific you wanted to know? HTH Alan G. From bvande at po-box.mcgill.ca Sat Dec 4 10:51:33 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat Dec 4 10:52:55 2004 Subject: [Tutor] eval and exec In-Reply-To: <41B1834D.5030801@po-box.mcgill.ca> References: <41B1834D.5030801@po-box.mcgill.ca> Message-ID: <41B188A5.1080407@po-box.mcgill.ca> Brian van den Broek said unto the world upon 2004-12-04 04:28: > Marilyn Davis said unto the world upon 2004-12-04 01:37: > >> Hello Tutors, >> >> I'm having trouble understanding the difference between eval and exec. >> >> Can anyone explain it to me please? >> >> Marilyn Davis >> > > Hi Marilyn, > > does this help? Darn. I left a few things that might help: >>> exec("a = 2 + 40") >>> exec("print a") > > 42 > >>> eval('a') 42 >>> As before, exec("a = 2 + 40") runs the code "a = 2 + 40", making 'a' point to 42. Thus, exec("print a") is synonymous with: >>> print a *in the interpreter* "eval('a')" also gives 42. This is because, *in the interpreter* >>> a 42 But, run this script: exec('a=42') exec('print a') exec("print eval('a') == eval('21 * 2')") eval('a') a OUTPUT: >>> =========================== RESTART =========================== >>> 42 True >>> *In a script*, a doesn't produce any output at all. This script does print 'True' because of the third line. It reads: Run the sting "print eval('a') == eval('21 * 2')" as code. So, print the expression you get by putting an '==' between the results of evaluating the expressions "a" and "21 * 2". Thus, print an expression equivalent to 42 == 42. And its almost 5am and I've begun to worry I'm muddying the waters, rather than helping. It is to be hoped that someone will clean up any messes I have made. (Ken? Danny? . . . .) Best, brian vdB From pythontut at pusspaws.net Sat Dec 4 11:43:47 2004 From: pythontut at pusspaws.net (Dave S) Date: Sat Dec 4 11:43:54 2004 Subject: [Tutor] Global presets ? Message-ID: <41B194E3.4020300@pusspaws.net> Hi there, I have some common data directories, like /home/dave/mygg/gg1.3/logs /home/dave/mygg/gg1.3/data /home/dave/mygg/gg1.3/datacore /home/dave/mygg/gg1.3/arch_data which increasing numbers of scripts are accessing. At the begining of each script I end up putting in declarations like arch_data_dir='/home/dave/mygg/gg1.3/arch_data' data_dir='/home/dave/mygg/gg1.3/data' .... over & over. This is OK until I want to move a directory Somewhere I read about importing a script to define common globals for all the scripts that import it. I tried this, and failed - the variable was only valid for the module, to be expected really :) Can anyone make a suggestion howto set up common global presets. Cheers Dave From kent37 at tds.net Sat Dec 4 12:21:43 2004 From: kent37 at tds.net (Kent Johnson) Date: Sat Dec 4 12:21:48 2004 Subject: [Tutor] Global presets ? In-Reply-To: <41B194E3.4020300@pusspaws.net> References: <41B194E3.4020300@pusspaws.net> Message-ID: <41B19DC7.4080006@tds.net> You are on the right track. Put your common definitions in a configuration module like this: # Config.py arch_data_dir='/home/dave/mygg/gg1.3/arch_data' data_dir='/home/dave/mygg/gg1.3/data' Then in client code, import Config. When you use the names defined in Config you have to prefix them with the module name like this: import Config print Config.data_dir Alternately you can use either of these forms: # Get a couple of names from Config into our global namespace from Config import arch_data_dir, data_dir or this: # Get *all* names defined in Config into our global namespace from Config import * to make the bare names available in the client. Kent Dave S wrote: > Hi there, > > I have some common data directories, like > > /home/dave/mygg/gg1.3/logs > /home/dave/mygg/gg1.3/data > /home/dave/mygg/gg1.3/datacore > /home/dave/mygg/gg1.3/arch_data > > which increasing numbers of scripts are accessing. At the begining of > each script > I end up putting in declarations like > > arch_data_dir='/home/dave/mygg/gg1.3/arch_data' > data_dir='/home/dave/mygg/gg1.3/data' > .... > > over & over. This is OK until I want to move a directory > > Somewhere I read about importing a script to define common globals for > all the scripts that import it. > > I tried this, and failed - the variable was only valid for the module, > to be expected really :) > > Can anyone make a suggestion howto set up common global presets. > > Cheers > Dave > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From pythontut at pusspaws.net Sat Dec 4 12:41:53 2004 From: pythontut at pusspaws.net (Dave S) Date: Sat Dec 4 12:42:02 2004 Subject: [Tutor] Global presets ? In-Reply-To: <41B194E3.4020300@pusspaws.net> References: <41B194E3.4020300@pusspaws.net> Message-ID: <41B1A281.3000001@pusspaws.net> Thanks Guys, They are both good ways of getting round my problem, I appreciate your input & will have a play. Cheers Dave :-) :-) :-) :-) From thisreallybeatsme at yahoo.com Sat Dec 4 12:54:19 2004 From: thisreallybeatsme at yahoo.com (Just Incase) Date: Sat Dec 4 12:54:23 2004 Subject: [Tutor] Simple RPN calculator Message-ID: <20041204115419.6172.qmail@web54402.mail.yahoo.com> Hi Tutors, I am new to programming and so don't know "anything" much, yet. I am having problem with implementing a simple RPN calculator in python. I have tried editing some other programs I have been referenced to earlier and I was able to play around with hoping to get something out of it but the problem I have is that I don't know how to make it request for input(s) of say a simple math like "1 2 3 4 5 + - * /". Help please with any suggestions or any other better and easier way of implementing a RPN calculator. Thank you, Justice The following is what I have: --------------------------------- Do you Yahoo!? The all-new My Yahoo! – What will yours do? -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041204/a8d1f351/attachment.htm From alan.gauld at freenet.co.uk Sat Dec 4 12:55:52 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat Dec 4 12:55:55 2004 Subject: [Tutor] Global presets ? References: <41B194E3.4020300@pusspaws.net> Message-ID: <010801c4d9f8$34d64170$c6ca8751@xp> > I have some common data directories, like > > /home/dave/mygg/gg1.3/logs > /home/dave/mygg/gg1.3/data > /home/dave/mygg/gg1.3/datacore > /home/dave/mygg/gg1.3/arch_data > > which increasing numbers of scripts are accessing. have you considered making the root directory an environment variable? That way you can read the value (os.getenv) at the start of the script. And if you ever need to move the structure you can simply change the environment value. It also means different users can use their own structures by defining their own environment value... > Somewhere I read about importing a script to define common globals for > all the scripts that import it. > > I tried this, and failed - the variable was only valid for the module, > to be expected really :) ############ # File myvars.py value1 = 42 value2 = 'spam' ############# # File: prog1.py import myvars localvar = myvars.value1 myvars.value2 = 'Alan' ############## # File prog2.py import myvars newvar = myvars.value2 print myvars.value1 - 27 ############## Does that help? Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Sat Dec 4 13:46:37 2004 From: kent37 at tds.net (Kent Johnson) Date: Sat Dec 4 13:46:41 2004 Subject: [Tutor] Simple RPN calculator In-Reply-To: <20041204115419.6172.qmail@web54402.mail.yahoo.com> References: <20041204115419.6172.qmail@web54402.mail.yahoo.com> Message-ID: <41B1B1AD.6080902@tds.net> I didn't get the attachment, can you try again? Thanks, Kent Just Incase wrote: > Hi Tutors, > > I am new to programming and so don't know "anything" much, yet. I am > having problem with implementing a simple RPN calculator in python. I > have tried editing some other programs I have been referenced to earlier > and I was able to play around with hoping to get something out of it but > the problem I have is that I don't know how to make it request for > input(s) of say a simple math like "1 2 3 4 5 + - * /". > > Help please with any suggestions or any other better and easier way of > implementing a RPN calculator. > > Thank you, > > Justice > > The following is what I have: > > > > ------------------------------------------------------------------------ > Do you Yahoo!? > The all-new My Yahoo! ? What will yours do? > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From "erimendz at bluebottle.com" at bluebottle.com Sat Dec 4 13:53:36 2004 From: "erimendz at bluebottle.com" at bluebottle.com (Eri Mendz) Date: Sat Dec 4 13:53:53 2004 Subject: [Tutor] Address book sort of Message-ID: Dear Tutor, I like to know what is the proper procedure (is algorithmn the right term?) in creating data in a program, write it to file, close the app then retrieve the data when run again. Basically, I'm trying to simulate a simple address book (well not really for the datas are just names for now) and so far have created the basic menu interface. It is console base so forget gui. I ask user input and store it in a list. There are menus to change, delete the data, and to save the data list in file. I use cPickle for this and have verified the file is created by checking in my $PWD. I want to retrieve that data when program is run again. What to add in my code? I thought not to post the code but explain it as above. What i want: when program is run again, the saved data is loaded when user selects option 1 below. Of course the first time it is run, the list is empty. def print_options(): print ''' Options: [1] - Print content of list [2] - Add name to list [3] - Delete name from list [4] - Change name in list [5] - Save list to file [P] - Print this menu [Q] - Quit ''' -- Regards, Eri Mendz Using PC-Pine 4.61 -- Using PC-Pine 4.61 From "erimendz at bluebottle.com" at bluebottle.com Sat Dec 4 14:05:36 2004 From: "erimendz at bluebottle.com" at bluebottle.com (Eri Mendz) Date: Sat Dec 4 14:05:42 2004 Subject: [Tutor] OT: test Message-ID: sorry it seems like my email address is mangled in my earlier post. resending new message with address in sig. -- Using PC-Pine 4.61 email: erimendz_at_bluebottle.com reply to: erimendz_at_fastmail.fm From rick_muller at yahoo.com Sat Dec 4 14:28:11 2004 From: rick_muller at yahoo.com (Rick Muller) Date: Sat Dec 4 14:28:15 2004 Subject: [Tutor] Address book sort of In-Reply-To: Message-ID: <20041204132811.78308.qmail@web42006.mail.yahoo.com> Couldn't tell if this got sent, so I'm re-sending. Apologies for duplicates: Well, one option is to use pickle (or cPickle, preferrably) to dump the python objects to a file: from cPickle import load, dump def save(fname,addressbook): file = open(filename,'w') dump(addressbook,file) file.close() return def read(fname): file = open(filename) addressbook = load(file) file.close() return addressbook The advantage of pickle is that you don't have to decide on a text format for your data -- it just dumps and then reloads the python code. You can waste a lot of time deciding on a text format, implementing the readers/writers, etc. Rick --- Eri Mendz <"erimendz@bluebottle.com"@bluebottle.com> wrote: > Dear Tutor, > > I like to know what is the proper procedure (is > algorithmn the right > term?) in creating data in a program, write it to > file, close the app > then retrieve the data when run again. Basically, > I'm trying to simulate > a simple address book (well not really for the datas > are just names for > now) and so far have created the basic menu > interface. It is console > base so forget gui. I ask user input and store it in > a list. There are > menus to change, delete the data, and to save the > data list in file. I > use cPickle for this and have verified the file is > created by checking > in my $PWD. I want to retrieve that data when > program is run again. What > to add in my code? I thought not to post the code > but explain it as > above. > > What i want: when program is run again, the saved > data is loaded when user > selects option 1 below. Of course the first time it > is run, the list is > empty. > > def print_options(): > print ''' > Options: > [1] - Print content of list > [2] - Add name to list > [3] - Delete name from list > [4] - Change name in list > [5] - Save list to file > [P] - Print this menu > [Q] - Quit > ''' > > > > -- > Regards, > Eri Mendz > Using PC-Pine 4.61 > > > -- > Using PC-Pine 4.61 > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ===== Rick Muller rick_muller@yahoo.com __________________________________ Do you Yahoo!? Yahoo! Mail - Find what you need with new enhanced search. http://info.mail.yahoo.com/mail_250 From pythontut at pusspaws.net Sat Dec 4 14:43:47 2004 From: pythontut at pusspaws.net (Dave S) Date: Sat Dec 4 14:43:52 2004 Subject: [Tutor] Global presets ? In-Reply-To: <010801c4d9f8$34d64170$c6ca8751@xp> References: <41B194E3.4020300@pusspaws.net> <010801c4d9f8$34d64170$c6ca8751@xp> Message-ID: <41B1BF13.10409@pusspaws.net> Alan Gauld wrote: > >have you considered making the root directory an environment variable? >That way you can read the value (os.getenv) at the start of the >script. >And if you ever need to move the structure you can simply change the >environment value. It also means different users can use their own >structures by defining their own environment value... > > > >############ ># File myvars.py >value1 = 42 >value2 = 'spam' > > > Got ya so far .. >############# ># File: prog1.py > >import myvars > >localvar = myvars.value1 >myvars.value2 = 'Alan' > > > Never thought of setting 'myvars.value2 = 'Alan'' I guess this would just set the variable in the myvars namespace since it could not change myvars.py itself. >############## ># File prog2.py > >import myvars > >newvar = myvars.value2 > > With you ... >print myvars.value1 - 27 > > Have I misunderstood, should this not be 42 ? Typo or me not understanding ? >############## > >Does that help? > >Alan G >Author of the Learn to Program web tutor >http://www.freenetpages.co.uk/hp/alan.gauld > > > > > From ps_python at yahoo.com Sat Dec 4 15:07:38 2004 From: ps_python at yahoo.com (kumar s) Date: Sat Dec 4 15:07:41 2004 Subject: [Tutor] How to select particular lines from a text Message-ID: <20041204140738.61678.qmail@web53701.mail.yahoo.com> Dear group, This is continuation to my previous email with sugject line "Python regular expression". My text file although, looks like .ini file, but it is not. It is a chip definition file from Gene chip. it is a huge file with over 340,000 lines. I have particular set of question in general not related to that file: Exmple text: Name: City: xxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxx .................... xxxxxxxxxxxxxxxxxxxx Name: City: xxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxx Characterstics of this text: 1. This text is divided into blocks and every block start with 'Name'. The number of lines after this identifier is random. In this particular case how a particular logic I can think of to extract some of these blocks is: 1.write a reg.exp to identify the Name identifier one need. 2. based on the this, ask the program to select all lines after that until it hits either a new line OR another name identifier: My question: How can I tell my program these 2 conditions: 1. mark the identifier i need and select all the lines after that identifier until it hits a new line or another name identifier. please englihten me with your suggestions. thank you. kumar __________________________________ Do you Yahoo!? Read only the mail you want - Yahoo! Mail SpamGuard. http://promotions.yahoo.com/new_mail From pythontut at pusspaws.net Sat Dec 4 15:24:45 2004 From: pythontut at pusspaws.net (Dave S) Date: Sat Dec 4 15:24:53 2004 Subject: [Tutor] Accuracy of time.sleep() Message-ID: <41B1C8AD.6060806@pusspaws.net> OK I may be pushing it, ;-) I need a script to sleep from any point to 8:05AM when in needs to re-start. So I calculate the number of seconds with the following .... def secs_till_805(): # Returns the number of seconds till 8:05AM secs_5min=5*60 secs_24hr=24*60*60 secs_8hr=(8*60*60)+secs_5min secs_8hr_24hr=secs_24hr-secs_8hr hours=int(strftime('%H')) mins=int(strftime('%M')) secs=int(strftime('%S')) sec_left=secs_24hr-((hours*60*60)+(mins*60)+secs) # If we are before 8:05, then ... if sec_left>secs_8hr_24hr: return sec_left-secs_8hr_24hr # If we are after 8:05, then ... return sec_left+secs_8hr Then I ... sleep(secs_till_805()) I expected the script to re-start 2-3 seconds after 8:05, python reloading after a long sleep etc, what I get is the script restarting at 08:04.55, earlier ??? OK this is not a world stopping problem, more of a curiosity. Any suggestions Dave From maxnoel_fr at yahoo.fr Sat Dec 4 15:30:56 2004 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Sat Dec 4 15:32:07 2004 Subject: [Tutor] Accuracy of time.sleep() In-Reply-To: <41B1C8AD.6060806@pusspaws.net> References: <41B1C8AD.6060806@pusspaws.net> Message-ID: <1C43DA3E-4601-11D9-8ECD-000393CBC88E@yahoo.fr> On Dec 4, 2004, at 14:24, Dave S wrote: > OK I may be pushing it, ;-) > > I need a script to sleep from any point to 8:05AM when in needs to > re-start. > > So I calculate the number of seconds with the following .... IMO, instead of doing this you should use cron to make your script start at 08:05. It's probably cleaner. (and yes, there are some versions of cron for Windows -- I don't know where they can be found, but I used one called nnCron Lite at my job this summer) -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From kent37 at tds.net Sat Dec 4 16:09:14 2004 From: kent37 at tds.net (Kent Johnson) Date: Sat Dec 4 16:09:20 2004 Subject: [Tutor] How to select particular lines from a text In-Reply-To: <20041204140738.61678.qmail@web53701.mail.yahoo.com> References: <20041204140738.61678.qmail@web53701.mail.yahoo.com> Message-ID: <41B1D31A.8000904@tds.net> kumar, Here is a solution for you. The makeSections() function will iterate through blocks in the file and return each one in turn to the caller. makeSections() is a generator function - the use of yield makes it one. That means that it returns an iterator that can be used in a for loop. Each time yield is executed it returns a new value to the loop. In this case, the values returned are the contents of each section. The loop in makeSections just walks through the lines of the input file. It accumulates the lines into a list and looks for special markers. The markers are, a 'Name:' line, to start a new section, and a blank line, to end a section. When it finds a marker it outputs the current section, if there is one, and starts a new one. Kent PS this question is much better asked than the last - you clearly stated what you want in a simple form. data = ''' Name: City: xxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxx .................... xxxxxxxxxxxxxxxxxxxx Name: City: xxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxx ''' import cStringIO # just for test def makeSections(f): ''' This is a generator function. It will return successive sections of f until EOF. Sections are every line from a 'Name:' line to the first blank line. Sections are returned as a list of lines with line endings stripped. ''' currSection = [] for line in f: line = line.strip() if line == 'Name:': # Start of a new section if currSection: yield currSection currSection = [] currSection.append(line) elif not line: # Blank line ends a section if currSection: yield currSection currSection = [] else: # Accumulate into a section currSection.append(line) # Yield the last section if currSection: yield currSection f = cStringIO.StringIO(data) for section in makeSections(f): print 'Section' for line in section: print ' ', line print kumar s wrote: > Dear group, > This is continuation to my previous email with > sugject line "Python regular expression". My text > file although, looks like .ini file, but it is not. It > is a chip definition file from Gene chip. it is a > huge file with over 340,000 lines. > > I have particular set of question in general not > related to that file: > > Exmple text: > > Name: > City: > xxxxxxxxxxxxxxxxxxxx > xxxxxxxxxxxxxxxxxxxx > .................... > xxxxxxxxxxxxxxxxxxxx > > > Name: > City: > xxxxxxxxxxxxxxxxxxxx > xxxxxxxxxxxxxxxxxxxx > > Characterstics of this text: > 1. This text is divided into blocks and every block > start with 'Name'. The number of lines after this > identifier is random. > > In this particular case how a particular logic I can > think of to extract some of these blocks is: > 1.write a reg.exp to identify the Name identifier one > need. > 2. based on the this, ask the program to select all > lines after that until it hits either a new line OR > another name identifier: > > My question: > > How can I tell my program these 2 conditions: > > 1. mark the identifier i need and select all the lines > after that identifier until it hits a new line or > another name identifier. > > > please englihten me with your suggestions. > > thank you. > > kumar > > > > __________________________________ > Do you Yahoo!? > Read only the mail you want - Yahoo! Mail SpamGuard. > http://promotions.yahoo.com/new_mail > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From wallison1 at sc.rr.com Sat Dec 4 17:18:05 2004 From: wallison1 at sc.rr.com (William Allison) Date: Sat Dec 4 17:17:00 2004 Subject: [Tutor] Upgrade to 2.4 Message-ID: <41B1E33D.1080601@sc.rr.com> I compiled Python 2.3.4 from source, but now I would like to upgrade to 2.4. There doesn't seem to be a "make uninstall" target for 2.3.4. Will compiling 2.4 overwrite the older version, or will I have two versions of Python on my system? Thanks, Will From mark.kels at gmail.com Sat Dec 4 17:19:28 2004 From: mark.kels at gmail.com (Mark Kels) Date: Sat Dec 4 17:19:49 2004 Subject: [Tutor] Broblem with exiting a Tkinter app Message-ID: Hi all , I got 2 questions for you guys. The fist question: I wrote small Tkinter app while laerning about the Radiobutton widget, and I added a "Quit" button, like this: bb=Button(root, text="Quit", fg="BLUE", command=root.quit).pack() When I pressed the button the app crashed and I got an error message ( program is not responding ) from windows. I tried to add a frame to the program and then exit the frame, like this: bb=Button(f, text="Quit", fg="BLUE", command=f.quit).pack() But the result is the same... Here is the full source code of the app: from Tkinter import * import sys root=Tk() f=Frame(root) text=Label(root, text="how old are you?").pack() v = IntVar(root) Radiobutton(f, text="less than 13", variable=v, value=1).pack(side=LEFT) Radiobutton(f, text="13-20", variable=v, value=2).pack(side=LEFT) Radiobutton(f, text="20-40", variable=v, value=3).pack(side=LEFT) Radiobutton(f, text="40+", variable=v, value=4).pack(side=LEFT) bb=Button(f, text="Quit", fg="BLUE", command=f.quit).pack() f.pack() root.mainloop() The second question: I dont understand how to get the input fron the radio buttons... It doesnt returns any value, so how can the app know what the user chose? Thanks!! From bgailer at alum.rpi.edu Sat Dec 4 17:42:58 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sat Dec 4 17:42:12 2004 Subject: [Tutor] Accuracy of time.sleep() In-Reply-To: <41B1C8AD.6060806@pusspaws.net> References: <41B1C8AD.6060806@pusspaws.net> Message-ID: <6.2.0.14.0.20041204094001.05c33f10@mail.mric.net> At 07:24 AM 12/4/2004, Dave S wrote: >OK I may be pushing it, ;-) > >I need a script to sleep from any point to 8:05AM when in needs to re-start. >[snip] If you're running on a version of windows that supports the AT command that gives you another way to do this. At a DOS prompt try AT. If you get something other than a command not found kind of error then we can do something. Let us know. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From amonroe at columbus.rr.com Sat Dec 4 18:51:00 2004 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sat Dec 4 18:51:21 2004 Subject: [Tutor] How to select particular lines from a text In-Reply-To: <20041204140738.61678.qmail@web53701.mail.yahoo.com> References: <20041204140738.61678.qmail@web53701.mail.yahoo.com> Message-ID: <64451373370.20041204125100@columbus.rr.com> > Name: > City: > xxxxxxxxxxxxxxxxxxxx > xxxxxxxxxxxxxxxxxxxx > Characterstics of this text: > 1. This text is divided into blocks and every block > start with 'Name'. The number of lines after this > identifier is random. [snip] > 1. mark the identifier i need and select all the lines > after that identifier until it hits a new line or > another name identifier. A "while" loop was invented for those times in life where you don't know in advance how many times you want to repeat something. while line != "Name:": bigfile.readline() #once this loop exits, you know you've found the first "Name:" line while line != "Name:": bigfile.readline() #keep reading every line upto the NEXT one do stuff here From amonroe at columbus.rr.com Sat Dec 4 18:52:37 2004 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sat Dec 4 18:52:58 2004 Subject: [Tutor] Accuracy of time.sleep() In-Reply-To: <1C43DA3E-4601-11D9-8ECD-000393CBC88E@yahoo.fr> References: <41B1C8AD.6060806@pusspaws.net> <1C43DA3E-4601-11D9-8ECD-000393CBC88E@yahoo.fr> Message-ID: <168451470500.20041204125237@columbus.rr.com> > IMO, instead of doing this you should use cron to make your script > start at 08:05. It's probably cleaner. > (and yes, there are some versions of cron for Windows -- I don't know > where they can be found, but I used one called nnCron Lite at my job > this summer) There's the "at" commandline tool, and the Scheduled Tasks Control Panel, both built in to Windows. Alan From pythontut at pusspaws.net Sat Dec 4 18:55:08 2004 From: pythontut at pusspaws.net (Dave S) Date: Sat Dec 4 18:55:14 2004 Subject: [Tutor] Accuracy of time.sleep() In-Reply-To: <41B1C8AD.6060806@pusspaws.net> References: <41B1C8AD.6060806@pusspaws.net> Message-ID: <41B1F9FC.7060401@pusspaws.net> > > I expected the script to re-start 2-3 seconds after 8:05, python > reloading after a long sleep etc, what I get is the script restarting > at 08:04.55, earlier ??? > > OK this is not a world stopping problem, more of a curiosity. > > Any suggestions > > Dave > Thanks for your input guys, I have used cron (fcron for me) in the past (Im a Gentoo Linux guy :-) ) I was just trying to keep it all pure python. As I said its more of a curiosity. It must be cummulative error over 10s of thousands of seconds. Its a bodge (& cron or at are better) but I suppose I could calculate seconds to 8:05 sleep(seconds*0.95), re calculate secs to 8:05 sleep(seconds) which should reduce the error to almost zip. Dave From bvande at po-box.mcgill.ca Sat Dec 4 18:34:35 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat Dec 4 19:00:42 2004 Subject: [Tutor] Global presets ? In-Reply-To: <41B19DC7.4080006@tds.net> References: <41B194E3.4020300@pusspaws.net> <41B19DC7.4080006@tds.net> Message-ID: <41B1F52B.2050503@po-box.mcgill.ca> Kent Johnson said unto the world upon 2004-12-04 06:21: > You are on the right track. Put your common definitions in a > configuration module like this: > > # Config.py > arch_data_dir='/home/dave/mygg/gg1.3/arch_data' > data_dir='/home/dave/mygg/gg1.3/data' > > Then in client code, import Config. When you use the names defined in > Config you have to prefix them with the module name like this: > Alternately you can use either of these forms: > or this: > > # Get *all* names defined in Config into our global namespace > from Config import * > > to make the bare names available in the client. > > Kent > > Dave S wrote: > >> Hi there, >> >> I have some common data directories, like >> >> /home/dave/mygg/gg1.3/logs >> /home/dave/mygg/gg1.3/data >> /home/dave/mygg/gg1.3/datacore >> /home/dave/mygg/gg1.3/arch_data >> >> which increasing numbers of scripts are accessing. At the begining of >> each script >> I end up putting in declarations like >> >> arch_data_dir='/home/dave/mygg/gg1.3/arch_data' >> data_dir='/home/dave/mygg/gg1.3/data' >> .... >> >> over & over. This is OK until I want to move a directory >> >> Somewhere I read about importing a script to define common globals for >> all the scripts that import it. >> >> I tried this, and failed - the variable was only valid for the module, >> to be expected really :) >> >> Can anyone make a suggestion howto set up common global presets. >> >> Cheers >> Dave >> >> >> Hi Dave, Kent, and all, I have a caution about the from Config import * idiom that Kent didn't mention. It can lead to namespace pollution, in that if you have a module 'foo' with a name 'bar' and you are witting a script which says from foo import * you have to be very careful that your script doesn't also assign to the name 'bar', else you may end up thinking you have two different things available when you don't. ('bar' will either point to your script's bar or to Config.bar, depending on whether you imported Config before or after your scripts assignment to bar.) The first time this bites you, it can eat up hours of your life. (But I'm not bitter;-) I avoid this by using the import examplemodule as em That imports everything so that you accesses it by em.some_name rather than examplemodule.some_name I find that really handy for the handful of utility modules I import into most of my scripts. Then, I just have to be sure to avoid a small set of names -- 'em' in this case. And my python files have nice descriptive names, but I only have to type then once. Best, Brian vdB From tim.peters at gmail.com Sat Dec 4 20:17:05 2004 From: tim.peters at gmail.com (Tim Peters) Date: Sat Dec 4 20:17:15 2004 Subject: [Tutor] Accuracy of time.sleep() In-Reply-To: <41B1C8AD.6060806@pusspaws.net> References: <41B1C8AD.6060806@pusspaws.net> Message-ID: <1f7befae04120411171c7df739@mail.gmail.com> [Dave S ] > OK I may be pushing it, ;-) Yup . > I need a script to sleep from any point to 8:05AM when in needs to > re-start. > > So I calculate the number of seconds with the following .... > > def secs_till_805(): > # Returns the number of seconds till 8:05AM > > secs_5min=5*60 > secs_24hr=24*60*60 > secs_8hr=(8*60*60)+secs_5min > secs_8hr_24hr=secs_24hr-secs_8hr > > hours=int(strftime('%H')) > mins=int(strftime('%M')) > secs=int(strftime('%S')) Ouch. Never try to pick apart the current time by computing it more than once. For example, if the time at the start of that block is just a fraction of a second before 9AM, it's quite possible you'll end up with hours==8 and mins==secs==0 (because the time is 8:59:59 at the time you do the "%H" business, and but it's 9:00:00 by the time you get to "%M"). That would throw you off by an hour. The same kind of thing can happen a little before the (any) minute changes too. > sec_left=secs_24hr-((hours*60*60)+(mins*60)+secs) > > # If we are before 8:05, then ... > if sec_left>secs_8hr_24hr: > return sec_left-secs_8hr_24hr > > # If we are after 8:05, then ... > return sec_left+secs_8hr Here's a different way, computing current time only once, and using the datetime module to do all the fiddly work: def seconds_until(h, m=0, s=0): from datetime import datetime, time, timedelta target_time = time(h, m, s) now = datetime.now() target = datetime.combine(now.date(), target_time) if target < now: target += timedelta(days=1) diff = target - now return diff.seconds + diff.microseconds / 1e6 This returns seconds as a float, which is good (Python's time.sleep() can make sense of floats, and sleep for fractional seconds). > Then I ... > > sleep(secs_till_805()) With the above, you'd do time.sleep(seconds_until(8, 5)) instead. > I expected the script to re-start 2-3 seconds after 8:05, python > reloading after a long sleep etc, what I get is the script restarting at > 08:04.55, earlier ??? You'll probably never know why for sure. Python calls platform C library gimmicks to sleep, which in turn invoke operating system facilities. Understanding the whole story would require that you understand everything all of those do. [later] > It must be cummulative error over 10s of thousands of seconds. Maybe. > Its a bodge (& cron or at are better) but I suppose I could calculate seconds > to 8:05 sleep(seconds*0.95), re calculate secs to 8:05 sleep(seconds) > which should reduce the error to almost zip. That's also a good idea in order to avoid surprises due to crossing daylight time boundaries (assuming you mean 8:05 according to the local wall clock). Here's a function building on the above: def sleep_until(h, m=0, s=0): from time import sleep while True: delay = seconds_until(h, m, s) if delay < 10.0: sleep(delay) return else: sleep(delay / 2) That is, it cuts the sleep time in half repeatedly, until less than 10 seconds remain. It can sleep for hours at a time, but as the target time approaches it wakes up more frequently. This should keep the program loaded in memory as the target time gets near. From kent37 at tds.net Sat Dec 4 20:38:06 2004 From: kent37 at tds.net (Kent Johnson) Date: Sat Dec 4 20:38:10 2004 Subject: [Tutor] Broblem with exiting a Tkinter app In-Reply-To: References: Message-ID: <41B2121E.907@tds.net> Mark Kels wrote: > Hi all , > I got 2 questions for you guys. > > The fist question: > I wrote small Tkinter app while laerning about the Radiobutton widget, > and I added a "Quit" button, like this: > bb=Button(root, text="Quit", fg="BLUE", command=root.quit).pack() > When I pressed the button the app crashed and I got an error message ( > program is not responding ) from windows. > I tried to add a frame to the program and then exit the frame, like this: > bb=Button(f, text="Quit", fg="BLUE", command=f.quit).pack() > But the result is the same... > > Here is the full source code of the app: > from Tkinter import * > import sys > root=Tk() > f=Frame(root) > text=Label(root, text="how old are you?").pack() > v = IntVar(root) > Radiobutton(f, text="less than 13", variable=v, value=1).pack(side=LEFT) > Radiobutton(f, text="13-20", variable=v, value=2).pack(side=LEFT) > Radiobutton(f, text="20-40", variable=v, value=3).pack(side=LEFT) > Radiobutton(f, text="40+", variable=v, value=4).pack(side=LEFT) > bb=Button(f, text="Quit", fg="BLUE", command=f.quit).pack() > f.pack() > root.mainloop() This program works fine for me on Win2K. How are you running the program? > > The second question: > I dont understand how to get the input fron the radio buttons... > It doesnt returns any value, so how can the app know what the user chose? Read the value from the variable associated with the buttons - v. For example if you define def quit(): print 'You chose button', v.get() f.quit() and change the command on bb to command=quit, the program will print the selection value on exit. (You have to define quit before bb or you will get a NameError.) Kent > > Thanks!! > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From bill at celestial.net Sat Dec 4 20:46:08 2004 From: bill at celestial.net (Bill Campbell) Date: Sat Dec 4 20:46:13 2004 Subject: [Tutor] eval and exec In-Reply-To: <00f501c4d9e4$80236270$c6ca8751@xp> References: <00f501c4d9e4$80236270$c6ca8751@xp> Message-ID: <20041204194608.GA24232@alexis.mi.celestial.com> On Sat, Dec 04, 2004, Alan Gauld wrote: >> I'm having trouble understanding the difference between eval and >exec. > >eval evaluates an *expression* - that is something that returns a >value. > ... >Both are extremely dangerous functions from a security >and maintenance/reliability pouint of view and should be >used very rarely. True enough, but useful upon occassion. In particular I've had a question on the back burner for a while. Suppose I have a dictionary of database instances, dbtables, keyed on table name, and I want a general way of creating variables with the name of the table so I'm not accessing the dictionary. Would something like this work: # dbtables is already built for table in dbtables.keys(): exec("%s = dbtables['%s']" % (table, table)) Bill -- INTERNET: bill@Celestial.COM Bill Campbell; Celestial Software LLC UUCP: camco!bill PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 URL: http://www.celestial.com/ My brother sent me a postcard the other day with this big satellite photo of the entire earth on it. On the back it said: ``Wish you were here''. -- Steven Wright From mark.kels at gmail.com Sat Dec 4 21:06:25 2004 From: mark.kels at gmail.com (Mark Kels) Date: Sat Dec 4 21:06:32 2004 Subject: [Tutor] Broblem with exiting a Tkinter app In-Reply-To: <41B2121E.907@tds.net> References: <41B2121E.907@tds.net> Message-ID: On Sat, 04 Dec 2004 14:38:06 -0500, Kent Johnson wrote: > Mark Kels wrote: > > > > Hi all , > > I got 2 questions for you guys. > > > > The fist question: > > I wrote small Tkinter app while laerning about the Radiobutton widget, > > and I added a "Quit" button, like this: > > bb=Button(root, text="Quit", fg="BLUE", command=root.quit).pack() > > When I pressed the button the app crashed and I got an error message ( > > program is not responding ) from windows. > > I tried to add a frame to the program and then exit the frame, like this: > > bb=Button(f, text="Quit", fg="BLUE", command=f.quit).pack() > > But the result is the same... > > > > Here is the full source code of the app: > > from Tkinter import * > > import sys > > root=Tk() > > f=Frame(root) > > text=Label(root, text="how old are you?").pack() > > v = IntVar(root) > > Radiobutton(f, text="less than 13", variable=v, value=1).pack(side=LEFT) > > Radiobutton(f, text="13-20", variable=v, value=2).pack(side=LEFT) > > Radiobutton(f, text="20-40", variable=v, value=3).pack(side=LEFT) > > Radiobutton(f, text="40+", variable=v, value=4).pack(side=LEFT) > > bb=Button(f, text="Quit", fg="BLUE", command=f.quit).pack() > > f.pack() > > root.mainloop() > > This program works fine for me on Win2K. How are you running the program? > > > > The second question: > > I dont understand how to get the input fron the radio buttons... > > It doesnt returns any value, so how can the app know what the user chose? > > Read the value from the variable associated with the buttons - v. For example if you define > def quit(): > print 'You chose button', v.get() > f.quit() > > and change the command on bb to command=quit, the program will print the selection value on exit. > (You have to define quit before bb or you will get a NameError.) > > Kent > > > > Thanks!! > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > Thats weird... Suddenly the program started to work fine :-) ! Thank you very much for your time. From pythontut at pusspaws.net Sat Dec 4 22:15:19 2004 From: pythontut at pusspaws.net (Dave S) Date: Sat Dec 4 22:15:28 2004 Subject: [Tutor] Accuracy of time.sleep() In-Reply-To: <1f7befae04120411171c7df739@mail.gmail.com> References: <41B1C8AD.6060806@pusspaws.net> <1f7befae04120411171c7df739@mail.gmail.com> Message-ID: <41B228E7.5080307@pusspaws.net> Tim Peters wrote: First, thank you for such a brilliant answer :-) >[Dave S ] > > >>OK I may be pushing it, ;-) >> >> > >Yup . > > > >>I need a script to sleep from any point to 8:05AM when in needs to >>re-start. >> >>So I calculate the number of seconds with the following .... >> >>def secs_till_805(): >> # Returns the number of seconds till 8:05AM >> >> secs_5min=5*60 >> secs_24hr=24*60*60 >> secs_8hr=(8*60*60)+secs_5min >> secs_8hr_24hr=secs_24hr-secs_8hr >> >> hours=int(strftime('%H')) >> mins=int(strftime('%M')) >> secs=int(strftime('%S')) >> >> > >Ouch. Never try to pick apart the current time by computing it more >than once. For example, if the time at the start of that block is >just a fraction of a second before 9AM, it's quite possible you'll end >up with hours==8 and mins==secs==0 (because the time is 8:59:59 at the >time you do the "%H" business, and but it's 9:00:00 by the time you >get to "%M"). That would throw you off by an hour. The same kind of >thing can happen a little before the (any) minute changes too. > > > This is a possibility that had not enterd my mind, but also very true. Thanks for saving me from that particular black hole. Its always that 1 in a thousand possibility that sends things south at the worst possible moment ! >> sec_left=secs_24hr-((hours*60*60)+(mins*60)+secs) >> >> # If we are before 8:05, then ... >> if sec_left>secs_8hr_24hr: >> return sec_left-secs_8hr_24hr >> >> # If we are after 8:05, then ... >> return sec_left+secs_8hr >> >> > >Here's a different way, computing current time only once, and using >the datetime module to do all the fiddly work: > >def seconds_until(h, m=0, s=0): > from datetime import datetime, time, timedelta > > target_time = time(h, m, s) > now = datetime.now() > target = datetime.combine(now.date(), target_time) > if target < now: > target += timedelta(days=1) > diff = target - now > return diff.seconds + diff.microseconds / 1e6 > >This returns seconds as a float, which is good (Python's time.sleep() >can make sense of floats, and sleep for fractional seconds). > > > OK Im pydoc'ing & looking at datetime, a module I have not explored before. This is stretching me a bit but its a good way to learn. >>Then I ... >> >>sleep(secs_till_805()) >> >> > >With the above, you'd do > > time.sleep(seconds_until(8, 5)) > >instead. > > > >>I expected the script to re-start 2-3 seconds after 8:05, python >>reloading after a long sleep etc, what I get is the script restarting at >>08:04.55, earlier ??? >> >> > >You'll probably never know why for sure. Python calls platform C >library gimmicks to sleep, which in turn invoke operating system >facilities. Understanding the whole story would require that you >understand everything all of those do. > > > If only I had the time ... (no pun intended) >[later] > > >>It must be cummulative error over 10s of thousands of seconds. >> >> > >Maybe. > > > >>Its a bodge (& cron or at are better) but I suppose I could calculate seconds >>to 8:05 sleep(seconds*0.95), re calculate secs to 8:05 sleep(seconds) >>which should reduce the error to almost zip. >> >> > >That's also a good idea in order to avoid surprises due to crossing >daylight time boundaries (assuming you mean 8:05 according to the >local wall clock). Here's a function building on the above: > >def sleep_until(h, m=0, s=0): > from time import sleep > > while True: > delay = seconds_until(h, m, s) > if delay < 10.0: > sleep(delay) > return > else: > sleep(delay / 2) > > Thats neat, and more elegent than my hamfisted attempt, I err might borrow it for my code, on a tempory basis you understand ;-) sleep_secs=secs_till_805() log('II','ftsed','Sleeping for '+str(sleep_secs)+' Seconds') # To compensate for the commulative error over 86,000 secs ! sleep(sleep_secs*0.95) sleep(secs_till_805()) >That is, it cuts the sleep time in half repeatedly, until less than 10 >seconds remain. It can sleep for hours at a time, but as the target >time approaches it wakes up more frequently. This should keep the >program loaded in memory as the target time gets near. > > > > Cheers Dave From pythontut at pusspaws.net Sat Dec 4 22:45:04 2004 From: pythontut at pusspaws.net (Dave S) Date: Sat Dec 4 22:45:09 2004 Subject: [Tutor] Global presets ? In-Reply-To: <41B1F52B.2050503@po-box.mcgill.ca> References: <41B194E3.4020300@pusspaws.net> <41B19DC7.4080006@tds.net> <41B1F52B.2050503@po-box.mcgill.ca> Message-ID: <41B22FE0.8020309@pusspaws.net> Brian van den Broek wrote: > > Hi Dave, Kent, and all, > > I have a caution about the > from Config import * > idiom that Kent didn't mention. > > It can lead to namespace pollution, in that if you have a module 'foo' > with a name 'bar' and you are witting a script which says > from foo import * > you have to be very careful that your script doesn't also assign to > the name 'bar', else you may end up thinking you have two different > things available when you don't. ('bar' will either point to your > script's bar or to Config.bar, depending on whether you imported > Config before or after your scripts assignment to bar.) > > The first time this bites you, it can eat up hours of your life. (But > I'm not bitter;-) > > I avoid this by using the > import examplemodule as em > > That imports everything so that you accesses it by > em.some_name > rather than > examplemodule.some_name > > I find that really handy for the handful of utility modules I import > into most of my scripts. Then, I just have to be sure to avoid a small > set of names -- 'em' in this case. And my python files have nice > descriptive names, but I only have to type then once. > > Best, > > Brian vdB > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > Thanks for pointing that out. Im a bit of a Python coward and opted for from config import data_dir,HTML_addr Mainly so I can see where these variables come from. I have never seen the 'as' operator on an import before, so much to learn (and remember) ;-) Dave From op73418 at mail.telepac.pt Sat Dec 4 23:51:50 2004 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Sat Dec 4 23:48:29 2004 Subject: [Tutor] eval and exec In-Reply-To: <20041204194608.GA24232@alexis.mi.celestial.com> References: <00f501c4d9e4$80236270$c6ca8751@xp> <20041204194608.GA24232@alexis.mi.celestial.com> Message-ID: <41B23F86.90808@mail.telepac.pt> Bill Campbell wrote: > On Sat, Dec 04, 2004, Alan Gauld wrote: > >>>I'm having trouble understanding the difference between eval and >> >>exec. >> >>eval evaluates an *expression* - that is something that returns a >>value. >> > > ... > >>Both are extremely dangerous functions from a security >>and maintenance/reliability pouint of view and should be >>used very rarely. > > > True enough, but useful upon occassion. In particular I've had a > question on the back burner for a while. Suppose I have a > dictionary of database instances, dbtables, keyed on table name, > and I want a general way of creating variables with the name of > the table so I'm not accessing the dictionary. Would something > like this work: > > # dbtables is already built > for table in dbtables.keys(): > exec("%s = dbtables['%s']" % (table, table)) > Yes it works, since it sticks that binding in the module namespace. But the question is, why would you want to do that? You already have the names in the dictionary... and to round off the irony, namespaces in Python are implemented as dictionaries! Is there a compelling reason why you need this? As has been already said, the thumbrule is that exec and it's brother eval are to be used in only a very few specialized situations. For example, giving the oportunity to the user of an application to interact directly with it via Python code. For the majority of the situations there is always a better (and faster and...) solution. With my best regards, G. Rodrigues From alan.gauld at freenet.co.uk Sun Dec 5 00:30:55 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Dec 5 00:30:56 2004 Subject: [Tutor] Simple RPN calculator References: <20041204115419.6172.qmail@web54402.mail.yahoo.com> Message-ID: <012e01c4da59$4dd7cf70$c6ca8751@xp> > I am new to programming and so don't know "anything" much, yet. > I am having problem with implementing a simple RPN calculator > in python. I'm not surprised. While an RPN vcalculator is one of the easier calculators to build its not exactly trivial. It sounds like the kind of thing an ambitious (or optimistic?) teacher might set for homework... Would I nbe right? > to make it request for input(s) of say a simple math like "1 2 3 4 5 + - * /". Look at raw_input() But if you are that much of a beginner you need to take several steps back and try one of the tutorials, they all cover raw_input fairly early on... And finally doesn't RPN put the operators first? Or is it me thats getting confused fromtoo much Lisping recently?... > Help please with any suggestions or any other better and easier > way of implementing a RPN calculator. Python is a fine place to start building RPN calculators. But thee are so many available that I van't help suspecting homewoprk here, and we can only offer limited guidance in that case. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Sun Dec 5 00:32:59 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Dec 5 00:32:57 2004 Subject: [Tutor] Address book sort of References: Message-ID: <013301c4da59$9792a090$c6ca8751@xp> > then retrieve the data when run again. Basically, I'm trying to simulate > a simple address book (well not really for the datas are just names for > now) I use an address book as an example program in the early stages of my tutorial. The finished(well sort of) program is in the modules & functions topic. I don't use pickle though since it is very Python specific. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Sun Dec 5 00:35:32 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Dec 5 00:35:32 2004 Subject: [Tutor] Global presets ? References: <41B194E3.4020300@pusspaws.net> <010801c4d9f8$34d64170$c6ca8751@xp> <41B1BF13.10409@pusspaws.net> Message-ID: <013c01c4da59$f29ce6d0$c6ca8751@xp> > >myvars.value2 = 'Alan' > > > > > > > Never thought of setting 'myvars.value2 = 'Alan'' I guess this would > just set the variable in the myvars namespace since it could not change > myvars.py itself. Absolutely correct and why I put the example in - but I forgot to point out the hidden gotcha! Glad you figured it out ;-) > >print myvars.value1 - 27 > > > > > Have I misunderstood, should this not be 42 ? Typo or me not understanding ? value1 is 42 so the print statement prints 42-27 => 15 Just proving that you can use the values any way you like, including in expressions. Alan G. From alan.gauld at freenet.co.uk Sun Dec 5 00:38:54 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Dec 5 00:40:10 2004 Subject: [Tutor] How to select particular lines from a text References: <20041204140738.61678.qmail@web53701.mail.yahoo.com> Message-ID: <014101c4da5a$6b5f5c60$c6ca8751@xp> > This is continuation to my previous email with > sugject line "Python regular expression". My text > file although, looks like .ini file, but it is not. It > is a chip definition file from Gene chip. it is a > huge file with over 340,000 lines. Thats big but by no means outragous, I have processed files with over 1 millionlines before. And they were much more complex format too - over 10 fields in a pseudo CSV format. It took a few minutes but not not hours. Try it, if there's a real problem think about fixing it. But it may just work... On a modern PC you will probably even have enough RAM to get it all into memory - less than 30M I'd guess! Alan G. From alan.gauld at freenet.co.uk Sun Dec 5 00:44:09 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Dec 5 00:44:07 2004 Subject: [Tutor] Accuracy of time.sleep() References: <41B1C8AD.6060806@pusspaws.net> <1C43DA3E-4601-11D9-8ECD-000393CBC88E@yahoo.fr> Message-ID: <015601c4da5b$26ab5be0$c6ca8751@xp> > (and yes, there are some versions of cron for Windows -- I don't know > where they can be found, but I used one called nnCron Lite at my job > this summer) And on XP/Win2K you can use the 'at' command to schedule jobs. The only case for sleep() is if you need to maintain context in memory (maybe because some other interrupt can come in too). Even then sleep is not, as you discovered absolutely accurate, it depends on things like CPU load. Instead I'd set sleep to wake me up a few minutes early (10 minutes say?), then run a new fuction to calculate the time to go and sleep for the shorter period, then for the last few seconds sleep for a few seconds at a time and check time each wake up. Of course even that only gets you within a second or two. Other options are to use the system clock and interrupts or signals. But if possible go with cron or at - thats why thety are there! Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From maxnoel_fr at yahoo.fr Sun Dec 5 00:45:18 2004 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Sun Dec 5 00:45:24 2004 Subject: [Tutor] Simple RPN calculator In-Reply-To: <012e01c4da59$4dd7cf70$c6ca8751@xp> References: <20041204115419.6172.qmail@web54402.mail.yahoo.com> <012e01c4da59$4dd7cf70$c6ca8751@xp> Message-ID: <8DB6AB80-464E-11D9-99F7-000393CBC88E@yahoo.fr> On Dec 4, 2004, at 23:30, Alan Gauld wrote: >> to make it request for input(s) of say a simple math like "1 2 3 4 > 5 + - * /". > > Look at raw_input() > > But if you are that much of a beginner you need to take several > steps back and try one of the tutorials, they all cover raw_input > fairly early on... > > And finally doesn't RPN put the operators first? Or is it me thats > getting confused fromtoo much Lisping recently?... Nope, RPN calculators (such as the HP48GX, IMHO the best calculator ever made) require you to input the operands first, then the operators. It's both easier to implement and more intuitive (not to mention way faster to both input and compute) once you've gotten the hang of it. You can probably do a very basic RPN calculator in less than a hundred lines of code, using raw_input() and a stack (well, a list's append() and pop() methods). -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From alan.gauld at freenet.co.uk Sun Dec 5 00:46:22 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Dec 5 00:46:19 2004 Subject: [Tutor] Accuracy of time.sleep() References: <41B1C8AD.6060806@pusspaws.net> <41B1F9FC.7060401@pusspaws.net> Message-ID: <016501c4da5b$765e30e0$c6ca8751@xp> > It must be cummulative error over 10s of thousands of seconds. Just so, and depends on howm many other processes are running, how busy the CPU is etc. > bodge (& cron or at are better) but I suppose I could calculate seconds > to 8:05 sleep(seconds*0.95), re calculate secs to 8:05 sleep(seconds) > which should reduce the error to almost zip. Thats the approach I suggest in my otther email :-) Alan G From cullennewsom at yahoo.com Sun Dec 5 01:53:55 2004 From: cullennewsom at yahoo.com (Cullen Newsom) Date: Sun Dec 5 01:54:00 2004 Subject: [Tutor] hello.py: line 1: print: command not found Message-ID: <20041205005355.14241.qmail@web10806.mail.yahoo.com> Hello List, Here is my Error: hello.py: line 1: print: command not found Here is my cat hello.py: nooseisloose@linux:~> cat hello.py #!/usr/bin/python print "Hello, world!" nooseisloose@linux:~> Here is some info which might help that I learned from an earlier post: >>> print repr(open('/home/nooseisloose/hello.py', 'rb').read(160)) '#!/usr/bin/python\n\nprint "Hello, world!"\n\n' >>> Here is my echo $PATH: nooseisloose@linux:~> echo $PATH /home/nooseisloose/bin:/usr/local/bin:/usr/bin:/usr/X11R6/bin:/bin:/usr/games:/opt/gnome/bin:/opt/kde3/bin:/usr/lib/java/bin:/usr/bin/python:/usr/bin/python:/usr/lib/python:/usr/lib/python2.3/ nooseisloose@linux:~> Everything runs fine from root. I am running SuSE 9.1 Linux linux 2.6.4-52-default I know this is a Linux question (or SuSE question) as much as a python question, but I do not think there is a more appropriate place to ask this question, and hopefully it will help save someone some time and frustration, especially since a person new to Python might well believe it to be a problem with Python. Anyone know the proper thing to set, or change? Thanks. Cullen __________________________________ Do you Yahoo!? Read only the mail you want - Yahoo! Mail SpamGuard. http://promotions.yahoo.com/new_mail From bill at celestial.net Sun Dec 5 02:20:25 2004 From: bill at celestial.net (Bill Campbell) Date: Sun Dec 5 02:20:29 2004 Subject: [Tutor] eval and exec In-Reply-To: <41B23F86.90808@mail.telepac.pt> References: <00f501c4d9e4$80236270$c6ca8751@xp> <20041204194608.GA24232@alexis.mi.celestial.com> <41B23F86.90808@mail.telepac.pt> Message-ID: <20041205012025.GA45211@alexis.mi.celestial.com> On Sat, Dec 04, 2004, Gon?alo Rodrigues wrote: >Bill Campbell wrote: ... >>>Both are extremely dangerous functions from a security >>>and maintenance/reliability pouint of view and should be >>>used very rarely. >> >> >>True enough, but useful upon occassion. In particular I've had a >>question on the back burner for a while. Suppose I have a >>dictionary of database instances, dbtables, keyed on table name, >>and I want a general way of creating variables with the name of >>the table so I'm not accessing the dictionary. Would something >>like this work: >> >># dbtables is already built >>for table in dbtables.keys(): >> exec("%s = dbtables['%s']" % (table, table)) >> > >Yes it works, since it sticks that binding in the module namespace. But >the question is, why would you want to do that? You already have the >names in the dictionary... and to round off the irony, namespaces in >Python are implemented as dictionaries! Is there a compelling reason why >you need this? Primarily because it's easier to type, thus less prone to errors. A secondary reason is that I'm in the process of converting an accounting application, written in C, to use a python front end, and the source code requires less modification doing it this way. Bill -- INTERNET: bill@Celestial.COM Bill Campbell; Celestial Software LLC UUCP: camco!bill PO Box 820; 6641 E. Mercer Way FAX: (206) 232-9186 Mercer Island, WA 98040-0820; (206) 236-1676 URL: http://www.celestial.com/ ``Most people, sometime in their lives, stumble across truth. Most jump up, brush themselves off, and hurry on about their business as if nothing had happened.'' - Sir Winston Churchill From maxnoel_fr at yahoo.fr Sun Dec 5 02:40:16 2004 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Sun Dec 5 02:40:32 2004 Subject: [Tutor] hello.py: line 1: print: command not found In-Reply-To: <20041205005355.14241.qmail@web10806.mail.yahoo.com> References: <20041205005355.14241.qmail@web10806.mail.yahoo.com> Message-ID: <9D114612-465E-11D9-99F7-000393CBC88E@yahoo.fr> On Dec 5, 2004, at 00:53, Cullen Newsom wrote: > Hello List, > > Here is my Error: > hello.py: line 1: print: command not found > Here is my cat hello.py: > > nooseisloose@linux:~> cat hello.py > #!/usr/bin/python > > print "Hello, world!" > > nooseisloose@linux:~> > > > I know this is a Linux question (or SuSE question) as much > as a python question, but I do not think there is a more > appropriate place to ask this question, and hopefully it will > help save someone some time and frustration, especially since a > person new to Python might well believe it to be a problem with > Python. > Anyone know the proper thing to set, or change? Thanks. > > Cullen How are you running your script? Are you doing a basic "python Hello.py", or have you set Hello.py to +x and are you relying on the first line to tell the script where the Python interpreter is? If it's answer #2, you should try replacing your first line with "#!/usr/bin/env python" , and see what happens. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From marilyn at deliberate.com Sun Dec 5 03:04:33 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Sun Dec 5 03:04:37 2004 Subject: [Tutor] eval and exec In-Reply-To: <41B23F86.90808@mail.telepac.pt> Message-ID: Thank you. You guys are great. I was trying to eval("import %s" % something). exec("import %s" % something) works just fine and now I understand why. But, why is this so extremely dangerous? Marilyn From kent37 at tds.net Sun Dec 5 03:35:16 2004 From: kent37 at tds.net (Kent Johnson) Date: Sun Dec 5 03:35:21 2004 Subject: [Tutor] eval and exec In-Reply-To: References: Message-ID: <41B273E4.3060605@tds.net> Marilyn Davis wrote: > Thank you. You guys are great. > > I was trying to eval("import %s" % something). > > exec("import %s" % something) works just fine and now I understand why. > > But, why is this so extremely dangerous? The danger is in exec'ing code whose source is not trusted. Using exec to import a module or create a name in your own code is fine. Using exec to run code from a untrusted source such as user input is opening yourself to any kind of mischief. For example you wouldn't want to exec("import os; os.system('del /f /q *')") Kent > > Marilyn > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From cullennewsom at yahoo.com Sun Dec 5 05:53:56 2004 From: cullennewsom at yahoo.com (Cullen Newsom) Date: Sun Dec 5 05:54:00 2004 Subject: [Tutor] hello.py: line 1: print: command not found In-Reply-To: <9D114612-465E-11D9-99F7-000393CBC88E@yahoo.fr> Message-ID: <20041205045356.79686.qmail@web10803.mail.yahoo.com> Max, Thanks for your reply. I have already tried to set my shebang to /usr/bin/env python. But for everyone's benefit. I've tried it again, and the same behavior persists. As another confirmation that this is not a file permission problem, I should say that I can run hello.py as root, and get the expected result. I can also run it as normal user, from /usr/lib/python and get the proper behavior. It is from /home/user/hello.py that this error persists. I included below the attribute flags from ls-l. Thanks again for your help, any ideas are appreciated. Cullen nooseisloose@linux:~> ls -l hello.py -rwxrwxrwx 1 nooseisloose users 42 2004-12-04 18:36 hello.py > On Dec 5, 2004, at 00:53, Cullen Newsom wrote: > > > Hello List, > > > > Here is my Error: > > hello.py: line 1: print: command not found > > Here is my cat hello.py: > > > > nooseisloose@linux:~> cat hello.py > > #!/usr/bin/python > > > > print "Hello, world!" > > > > nooseisloose@linux:~> > > > > > > I know this is a Linux question (or SuSE question) as > much > > as a python question, but I do not think there is a more > > appropriate place to ask this question, and hopefully it > will > > help save someone some time and frustration, especially > since a > > person new to Python might well believe it to be a problem > with > > Python. > > Anyone know the proper thing to set, or change? Thanks. > > > > Cullen > > How are you running your script? Are you doing a basic > "python > Hello.py", or have you set Hello.py to +x and are you relying > on the > first line to tell the script where the Python interpreter is? > > If it's answer #2, you should try replacing your first line > with > "#!/usr/bin/env python" , and see what happens. > > -- Max > maxnoel_fr at yahoo dot fr -- ICQ #85274019 > "Look at you hacker... A pathetic creature of meat and bone, > panting > and sweating as you run through my corridors... How can you > challenge a > perfect, immortal machine?" __________________________________ Do you Yahoo!? Yahoo! Mail - now with 250MB free storage. Learn more. http://info.mail.yahoo.com/mail_250 From cyresse at gmail.com Sun Dec 5 06:31:50 2004 From: cyresse at gmail.com (Liam Clarke) Date: Sun Dec 5 06:31:56 2004 Subject: [Tutor] Simple RPN calculator In-Reply-To: <8DB6AB80-464E-11D9-99F7-000393CBC88E@yahoo.fr> References: <20041204115419.6172.qmail@web54402.mail.yahoo.com> <012e01c4da59$4dd7cf70$c6ca8751@xp> <8DB6AB80-464E-11D9-99F7-000393CBC88E@yahoo.fr> Message-ID: RPN calculator, with operators and operands separate? Sounds counter-intuitive to me. What's the advantage I'm missing? P.S. Nice Shodan quote Max ;) On Sat, 4 Dec 2004 23:45:18 +0000, Max Noel wrote: > > > > On Dec 4, 2004, at 23:30, Alan Gauld wrote: > > >> to make it request for input(s) of say a simple math like "1 2 3 4 > > 5 + - * /". > > > > Look at raw_input() > > > > But if you are that much of a beginner you need to take several > > steps back and try one of the tutorials, they all cover raw_input > > fairly early on... > > > > And finally doesn't RPN put the operators first? Or is it me thats > > getting confused fromtoo much Lisping recently?... > > Nope, RPN calculators (such as the HP48GX, IMHO the best calculator > ever made) require you to input the operands first, then the operators. > It's both easier to implement and more intuitive (not to mention way > faster to both input and compute) once you've gotten the hang of it. > You can probably do a very basic RPN calculator in less than a hundred > lines of code, using raw_input() and a stack (well, a list's append() > and pop() methods). > > -- Max > maxnoel_fr at yahoo dot fr -- ICQ #85274019 > "Look at you hacker... A pathetic creature of meat and bone, panting > and sweating as you run through my corridors... How can you challenge a > perfect, immortal machine?" > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From cullennewsom at yahoo.com Sun Dec 5 07:13:01 2004 From: cullennewsom at yahoo.com (Cullen Newsom) Date: Sun Dec 5 07:13:05 2004 Subject: [Tutor] Simple RPN calculator In-Reply-To: Message-ID: <20041205061301.87970.qmail@web10801.mail.yahoo.com> > RPN calculator, with operators and operands separate? Sounds > counter-intuitive to me. > What's the advantage I'm missing? Yes, by all means, please explain the advantages/differences of RPN calculators. All I know about them is that in High School, I went to UIL Calculator Math competition, and all us with out RPN calculators who thought we knew a thing or two, got our asses handed to us by the RPN-calc. guys. There should have been two classes of us, the TI class and HP class. It was a rout. I'm here to tell you that there is an advantage, I just have no idea what it is. Cheers, Cullen __________________________________ Do you Yahoo!? Yahoo! Mail - Easier than ever with enhanced search. Learn more. http://info.mail.yahoo.com/mail_250 From jerimed at myrealbox.com Sun Dec 5 07:22:25 2004 From: jerimed at myrealbox.com (Eri Mendz) Date: Sun Dec 5 07:22:21 2004 Subject: [Tutor] Address book sort of (fwd) Message-ID: -- Regards, Eri Mendz ---------- Forwarded message ---------- Date: Sat, 4 Dec 2004 15:53:36 +0300 (Arab Standard Time) Subject: Address book sort of Dear Tutor, I like to know what is the proper procedure (is algorithmn the right term?) in creating data in a program, write it to file, close the app then retrieve the data when run again. Basically, I'm trying to simulate a simple address book (well not really for the datas are just names for now) and so far have created the basic menu interface. It is console base so forget gui. I ask user input and store it in a list. There are menus to change, delete the data, and to save the data list in file. I use cPickle for this and have verified the file is created by checking in my $PWD. I want to retrieve that data when program is run again. What to add in my code? I thought not to post the code but explain it as above. What i want: when program is run again, the saved data is loaded when user selects option 1 below. Of course the first time it is run, the list is empty. def print_options(): print ''' Options: [1] - Print content of list [2] - Add name to list [3] - Delete name from list [4] - Change name in list [5] - Save list to file [P] - Print this menu [Q] - Quit ''' From maxnoel_fr at yahoo.fr Sun Dec 5 07:24:47 2004 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Sun Dec 5 07:24:54 2004 Subject: [Tutor] Simple RPN calculator In-Reply-To: References: <20041204115419.6172.qmail@web54402.mail.yahoo.com> <012e01c4da59$4dd7cf70$c6ca8751@xp> <8DB6AB80-464E-11D9-99F7-000393CBC88E@yahoo.fr> Message-ID: <5C8BCE6E-4686-11D9-81E6-000393CBC88E@yahoo.fr> On Dec 5, 2004, at 05:31, Liam Clarke wrote: > RPN calculator, with operators and operands separate? Sounds > counter-intuitive to me. > What's the advantage I'm missing? Well, the best way to explain is to take an example. Let's say you want to calculate ((2 + 5) * 3 - (4 / 6)) * ((8 - 2 * 3) / 9 + (10 - 1)) Using a conventional calculator, you'd input the entire expression as above. Considering you have a good calculator (i.e. the parens are not shifted), that's at least 34 keystrokes, you have to get the parens right, and the calculator, which is idling as you type the expression, requires some extra processing time as soon as you hit "enter" to turn it into something it can understand. Now, with a RPN calculator, you input your expression as a tree, where the leaves are the operands and the nodes are the operators, in the order where they have to be processed. In other words, if you were using a HP48, here's what you'd be inputting: 2 5 + 3 * 4 6 / 8 2 3 * - 9 / 10 1 - + * What happens, is that every time you enter an operand (in our case, a number), it's pushed in a stack (which is visible on the screen). And every time you enter an operator, it is applied to the last two operands you entered (they get popped out of the stack) and the result is pushed back in. The economy in keystrokes (32 in that case, given that you have to hit enter after each operand, but operators can be set up so that you don't) is marginal. However: 1) You don't need parentheses any more. You don't have to worry about forgetting to close one, or closing one at the wrong place. In fact, you don't even need to remember the operator priorities. 2) The calculator is working as you type: when you enter an operator, it knows it can compute an operation, unambiguously -- so it does. As a result, RPN calculators often "feel" faster. And since your keystrokes are buffered, you don't even have to worry about slow elementary operations. 3) Not only does the calculator feel faster, it also is faster. Traditional calculators have to parse the algebraic expression to actually convert it to a RPN-like format that can then be evaluated. RPN calculators don't have to. Most RPN calculators also include an algebraic mode to allow you to see the difference; in the case of the HP48 series, using said algebraic mode immediately makes you feel the calculator's main weakness: its processor is ridiculously slow (4 MHz 4-bit Saturn CPU). But when using the calculator in RPN mode, it takes a TI-92 (which sports a 10 MHz 68000) to beat it. Not too bad for a machine that dates back to 1990. All of this, combined to a powerful programming language (RPL -- Reverse Polish Lisp) and a few other interesting features (the most noticeable being almost out-of-the-box Assembly programming capabilities) gave the HP48 somewhat of a cult following, and an incredible game development community: by the time mine gave up the ghost about 6 years ago, there were perfect conversions of Lemmings and Civilization, Dune 2 was well on its way, artists were displaying pictures in 16-greyscale on a screen that has a depth of 1 bit, playing PCM sound on the shittiest buzzer in the world, and people were using the IR data capabilities of the 48 to turn it into a TV remote. But I digress ;) In any case, it takes a while to get used to RPN, but once you get the hang of it, you feel frustrated when you come back to regular algebraic notation. Although as far as pocket calculators are concerned, you don't have a choice anymore -- HP stopped producing calculators a few years ago, having basically done nothing in 15 years to improve the design of the 48/49 series. A shame, really. I call it the "Commodore effect". > P.S. > > Nice Shodan quote Max ;) Hehe... Thanks. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From bvande at po-box.mcgill.ca Sun Dec 5 07:27:22 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sun Dec 5 07:28:44 2004 Subject: [Tutor] Simple RPN calculator In-Reply-To: References: <20041204115419.6172.qmail@web54402.mail.yahoo.com> <"012e01c4da59 $4dd7cf70$c6ca8751"@xp> <8DB6AB80-464E-11D9-99F7-000393CBC88E@yahoo.fr> Message-ID: <41B2AA4A.6020604@po-box.mcgill.ca> Liam Clarke said unto the world upon 2004-12-05 00:31: > RPN calculator, with operators and operands separate? Sounds > counter-intuitive to me. > What's the advantage I'm missing? > > P.S. Hi Liam and all, Is RPN really written with operators and operands separate? If so, that is a bit odd. The name, so far as I know, comes from a notation developed in Poland in the 1920's (+/- 5 years) for writing logical formula without brackets. But it does not quite separate out the two classes of symbols. Writing 'v' for or and '&' for and, A v ((B & C) v D) would go over as: vAv&BCD and (A v B) & (C v D) as &vABvCD The advantage is 1) everything can be unambiguously written without '(' characters, and thus, 2) parsing code is a bit easier to write. By analogy, I had always assumed that Polish Arithmetic would read (2 + 3) - 1 and 2 + (3 - 1) as: -+231 and +2-31 I further assumed that RPN would simply reverse this. If that isn't true, I think I need to go investigate the origins of the name. Best to all, Brian vdB From billburns at pennswoods.net Sun Dec 5 08:45:18 2004 From: billburns at pennswoods.net (Bill Burns) Date: Sun Dec 5 08:37:05 2004 Subject: [Tutor] hello.py: line 1: print: command not found In-Reply-To: <20041205045356.79686.qmail@web10803.mail.yahoo.com> References: <20041205045356.79686.qmail@web10803.mail.yahoo.com> Message-ID: <200412050245.18643.billburns@pennswoods.net> On Saturday 04 December 2004 11:53 pm, Cullen Newsom wrote: > Max, > > Thanks for your reply. I have already tried to set my > confirmation that this is not a file permission problem, I > should say that I can run hello.py as root, and get the expected > result. I can also run it as normal user, from /usr/lib/python > and get the proper behavior. It is from /home/user/hello.py > that this error persists. I included below the attribute flags > from ls-l. Thanks again for your help, any ideas are > appreciated. > > Cullen > > > nooseisloose@linux:~> ls -l hello.py > -rwxrwxrwx 1 nooseisloose users 42 2004-12-04 18:36 hello.py > > Hello Cullen, I don't know if this will help solve your problem or not. I thought I would fool around with it since I also use SUSE 9.1. As I believe you suspected, as well as Max, your error is coming from the shell, not python, Bash doesn't know how to execute the code. Your file works on my box using either shebang. I can only replicate your error if I do the following: 1). Completely remove "#!/usr/bin/python" as the first line in the script. 2). Make print "Hello, world!" the first line in the script. 3). Make sure that execute permissions (+x) are set and issue the command "./hello.py". bill@blkbox:~/Desktop> ./hello.py ./hello.py: line 1: print: command not found Because your error contains "line 1: print:" , it would seem that the print command is on line one and that your first line does not contain "#!/usr/bin/python". But your output from "cat" and "print repr(open('/home/nooseisloose/hello.py', 'rb').read(160))" say that you do have it at the top of the file. Strange! I know that there was an updated Bash for our distro a while ago but I have no idea what the specific problem was. Looking at your kernel version I can see that's your system is not up to date (at least the kernel anyway), maybe you need to do an update. I'm currently using bash-2.05b-305.1. HTH Bill From singingxduck at gmail.com Sun Dec 5 09:12:13 2004 From: singingxduck at gmail.com (Orri Ganel) Date: Sun Dec 5 09:12:19 2004 Subject: [Tutor] Simple RPN calculator In-Reply-To: <5C8BCE6E-4686-11D9-81E6-000393CBC88E@yahoo.fr> References: <20041204115419.6172.qmail@web54402.mail.yahoo.com> <012e01c4da59$4dd7cf70$c6ca8751@xp> <8DB6AB80-464E-11D9-99F7-000393CBC88E@yahoo.fr> <5C8BCE6E-4686-11D9-81E6-000393CBC88E@yahoo.fr> Message-ID: <3449428f04120500123ccaa642@mail.gmail.com> Hello all, > Well, the best way to explain is to take an example. Let's say you > want to calculate ((2 + 5) * 3 - (4 / 6)) * ((8 - 2 * 3) / 9 + (10 - > 1)) > In other words, if you were > using a HP48, here's what you'd be inputting: > > 2 > 5 > + > 3 > * > 4 > 6 > / > 8 > 2 > 3 > * > - > 9 > / > 10 > 1 > - > + > * Just to clarify, that would actually be 2 5 + 3 * 4 6 / - << 8 2 3 * - 9 / 10 1 - + * , correct? (There should be a minus after "4 6 /") Also, in order to find the answer it looks like you want (in Python), you should do ((2 + 5) * 3 - (4.0 / 6)) * ((8 - 2 * 3) / 9.0 + (10 - 1)) and, if your RPN doesn't handle numbers as floats or Decimals (new as of Python 2.3 I believe), 2 5 + 3 * 4.0 6 / - 8 2 3 * - 9.0 / 10 1 - + * Otherwise you get 189 because (4 / 6) evaluates to 0, as does ((8 - 2 * 3) / 9). By the way, anyone interested in seeing/reviewing an RPN calculator I wrote, feel free to visit http://rafb.net/paste/results/BW1hxH51.html (57 lines) From kabads at gmail.com Sun Dec 5 09:47:47 2004 From: kabads at gmail.com (Adam Cripps) Date: Sun Dec 5 09:47:55 2004 Subject: [Tutor] Address book sort of (fwd) In-Reply-To: References: Message-ID: On Sun, 5 Dec 2004 09:22:25 +0300 (Arab Standard Time), Eri Mendz wrote: > > > -- > Regards, > Eri Mendz > > ---------- Forwarded message ---------- > Date: Sat, 4 Dec 2004 15:53:36 +0300 (Arab Standard Time) > Subject: Address book sort of > > Dear Tutor, > > I like to know what is the proper procedure (is algorithmn the right > term?) in creating data in a program, write it to file, close the app > then retrieve the data when run again. Basically, I'm trying to simulate > a simple address book (well not really for the datas are just names for > now) and so far have created the basic menu interface. It is console > base so forget gui. I ask user input and store it in a list. There are > menus to change, delete the data, and to save the data list in file. I > use cPickle for this and have verified the file is created by checking > in my $PWD. I want to retrieve that data when program is run again. What > to add in my code? I thought not to post the code but explain it as > above. > > What i want: when program is run again, the saved data is loaded when user > selects option 1 below. Of course the first time it is run, the list is > empty. > > def print_options(): > print ''' > Options: > [1] - Print content of list > [2] - Add name to list > [3] - Delete name from list > [4] - Change name in list > [5] - Save list to file > [P] - Print this menu > [Q] - Quit > ''' > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > This sounds slightly similar to one of my first applications in Python using object orientated design: https://savannah.nongnu.org/projects/newmag - which is a magazine catalogue. Feel free to browse the code, and reuse if you wish (under conditions of the license). It creates objects, and then writes the objects (using pickle) to a file - the process of opening is simple - you just open the file and then Python reloads all the objects into memory again. Adam -- http://www.monkeez.org PGP key: 7111B833 From alan.gauld at freenet.co.uk Sun Dec 5 09:49:25 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Dec 5 09:49:18 2004 Subject: [Tutor] Simple RPN calculator References: <20041204115419.6172.qmail@web54402.mail.yahoo.com> <012e01c4da59$4dd7cf70$c6ca8751@xp> <8DB6AB80-464E-11D9-99F7-000393CBC88E@yahoo.fr> Message-ID: <016c01c4daa7$539565f0$c6ca8751@xp> > > And finally doesn't RPN put the operators first? Or is it me thats > > getting confused fromtoo much Lisping recently?... > > Nope, RPN calculators (such as the HP48GX, IMHO the best calculator > ever made) require you to input the operands first, then the operators. Yeah, you are right. I had a Novus RPN calculator in the 70's and it worked exactly as you describe. And yes, it was a lot faster than infix notation. Too much Lisp confusing my mind.... :-) Alan g From alan.gauld at freenet.co.uk Sun Dec 5 09:56:51 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Dec 5 09:56:45 2004 Subject: [Tutor] eval and exec References: <00f501c4d9e4$80236270$c6ca8751@xp> <20041204194608.GA24232@alexis.mi.celestial.com> Message-ID: <017d01c4daa8$5cbbf800$c6ca8751@xp> > dictionary of database instances, dbtables, keyed on table name, > and I want a general way of creating variables with the name of > the table so I'm not accessing the dictionary. Would something > like this work: > > # dbtables is already built > for table in dbtables.keys(): > exec("%s = dbtables['%s']" % (table, table)) It will create a lot of variables named after your tables. The problem with this approach is how will the code that comes after this dynamic naming know about those names which don't exist when you wrote it? You can only access variables that you know exist, but if you know they will exist you don't need to do the dynamic naming thing... So this approach is only useful where you know a lot of names in advance but don't want to go to the hassle of explicitly initialising them all before using them. The cost of this small time saving is the use of a potentially dangerous exec call. This kind of dynamic naming scheme is only really useful in some kind of interactive session, when you run a program thats written in advance it is much better to put dynamically created objects into a collection IMHO. Alan g. From alan.gauld at freenet.co.uk Sun Dec 5 10:05:19 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Dec 5 10:05:06 2004 Subject: [Tutor] eval and exec References: Message-ID: <019f01c4daa9$8bf03540$c6ca8751@xp> > I was trying to eval("import %s" % something). > > exec("import %s" % something) works just fine and now I understand why. But much better to use the __import__() function for doing that if possible... Or simply importing all the modules you might need at the beginning, its not a big overhead... Alan G. From python at kapitalisten.no Sun Dec 5 11:31:32 2004 From: python at kapitalisten.no (=?iso-8859-1?Q?=D8yvind?=) Date: Sun Dec 5 11:31:59 2004 Subject: [Tutor] Real time reading Message-ID: <4435.193.216.161.244.1102242692.squirrel@mail.sporck.net> I would like to analyze a maillog. The maillog is automatically generated and every mail sent is added to the log. I would like to check if someone send more than 5 mails pr minute (spams) and if so, get Python to send a warningmail to the mailmaster. How would I in the best way read the log? To open the file and close it every second sounds like a bad idea? Is there some function to analyze the file, and automatically extract additions to the file? Thanks in advance. -- This email has been scanned for viruses & spam by Decna as - www.decna.no Denne e-posten er sjekket for virus & spam av Decna as - www.decna.no From bgailer at alum.rpi.edu Sun Dec 5 11:33:25 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sun Dec 5 11:32:50 2004 Subject: [Tutor] Simple RPN calculator In-Reply-To: <8DB6AB80-464E-11D9-99F7-000393CBC88E@yahoo.fr> References: <20041204115419.6172.qmail@web54402.mail.yahoo.com> <012e01c4da59$4dd7cf70$c6ca8751@xp> <8DB6AB80-464E-11D9-99F7-000393CBC88E@yahoo.fr> Message-ID: <6.2.0.14.0.20041205032700.02da0988@mail.mric.net> At 04:45 PM 12/4/2004, Max Noel wrote: >On Dec 4, 2004, at 23:30, Alan Gauld wrote: > >>>to make it request for input(s) of say a simple math like "1 2 3 4 >>5 + - * /". >> >>Look at raw_input() >> >>But if you are that much of a beginner you need to take several >>steps back and try one of the tutorials, they all cover raw_input >>fairly early on... >> >>And finally doesn't RPN put the operators first? Or is it me thats >>getting confused fromtoo much Lisping recently?... > > Nope, RPN calculators (such as the HP48GX, IMHO the best > calculator ever made) require you to input the operands first, then the > operators. It's both easier to implement and more intuitive (not to > mention way faster to both input and compute) once you've gotten the hang > of it. > You can probably do a very basic RPN calculator in less than a > hundred lines of code, using raw_input() and a stack (well, a list's > append() and pop() methods). For grins I just wrote one that takes '1 2.3 - 3 4 5 + * /' as input and prints -0.0481481.... 8 lines of Python. That indeed is less than 100. Took about 7 minutes to code and test. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From cyresse at gmail.com Sun Dec 5 12:22:54 2004 From: cyresse at gmail.com (Liam Clarke) Date: Sun Dec 5 12:22:59 2004 Subject: [Tutor] Real time reading In-Reply-To: <4435.193.216.161.244.1102242692.squirrel@mail.sporck.net> References: <4435.193.216.161.244.1102242692.squirrel@mail.sporck.net> Message-ID: You could just get Python to see if the maillog has increased in size, and if so then open it, or you could get the 'last modified date' and so forth... os module will do this. Or, all changes to the maillog could be passed through Python, which writes it? http://www.python.org/doc/2.3/lib/module-StringIO.html ??? Good luck, Liam Clarke On Sun, 5 Dec 2004 11:31:32 +0100 (CET), ?yvind wrote: > I would like to analyze a maillog. The maillog is automatically generated > and every mail sent is added to the log. I would like to check if someone > send more than 5 mails pr minute (spams) and if so, get Python to send a > warningmail to the mailmaster. > > How would I in the best way read the log? To open the file and close it > every second sounds like a bad idea? Is there some function to analyze the > file, and automatically extract additions to the file? > > Thanks in advance. > > -- > This email has been scanned for viruses & spam by Decna as - www.decna.no > Denne e-posten er sjekket for virus & spam av Decna as - www.decna.no > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From bgailer at alum.rpi.edu Sun Dec 5 12:56:01 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sun Dec 5 12:55:21 2004 Subject: [Tutor] Re: Can I see it? In-Reply-To: <20041205103627.10451.qmail@web54408.mail.yahoo.com> References: <20041205103627.10451.qmail@web54408.mail.yahoo.com> Message-ID: <6.2.0.14.0.20041205045050.057bf8f8@mail.mric.net> At 03:36 AM 12/5/2004, you wrote: >Hi Bob, > >That is what I am looking for! A simple RPN calculator program! >Can I see what you have please? That depends. Are you are working on a homework assignment? I ask because when we see several posts of a similar question we suspect it is an assignment given to a class, and our hope is to support education with guidance rather than answers. Assuming for the moment that this is homework I'd like to see what you have done so far, and where you are stuck. Then I'll give some pointers. Hints: my program uses lists, a dictionary, and imports a module named operators Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From kent37 at tds.net Sun Dec 5 12:55:19 2004 From: kent37 at tds.net (Kent Johnson) Date: Sun Dec 5 12:55:24 2004 Subject: [Tutor] Simple RPN calculator In-Reply-To: <41B2AA4A.6020604@po-box.mcgill.ca> References: <20041204115419.6172.qmail@web54402.mail.yahoo.com> <"012e01c4da59 $4dd7cf70$c6ca8751"@xp> <8DB6AB80-464E-11D9-99F7-000393CBC88E@yahoo.fr> <41B2AA4A.6020604@po-box.mcgill.ca> Message-ID: <41B2F727.7070107@tds.net> RPN reverses the order of operator and operand, it doesn't reverse the whole string. So in Polish Notation 2 + 3 is +23 and (2 + 3) - 1 is -+231; in RPN they become 23+ and 23+1- Kent Brian van den Broek wrote: > By analogy, I had always assumed that Polish Arithmetic would read > > (2 + 3) - 1 and > 2 + (3 - 1) > > as: > > -+231 and > +2-31 > > I further assumed that RPN would simply reverse this. If that isn't > true, I think I need to go investigate the origins of the name. > > Best to all, > > Brian vdB > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From ps_python at yahoo.com Sun Dec 5 14:11:21 2004 From: ps_python at yahoo.com (kumar s) Date: Sun Dec 5 14:11:23 2004 Subject: [Tutor] Can i define anywhere on file object function for reading a range of lines? Message-ID: <20041205131121.12275.qmail@web53710.mail.yahoo.com> Dear group, For instance I have a text that looks like following: Segment:Page 21 xxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxx ............................. xxxxxxxxxxxxxxxxxxxxxxxxxxxxx Segment:Page 22 xxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxx ............................ Segment:Page 23 XXXXXXXXXXXXXXXXXXXXXXXXXXXX ............................ xxxxxxxxxxxxxxxxxxxxxxxxxxxx I have another file with Page numbers that looks like this: Page 1 Page 2 ...... Page 22 Page 34 Page 200 I can see that Page 22 is existing in my first file. Now I am trying locate Page 22 segment in first file and asking my program to read STARTING from Segment:Page 22 to End of page 22 segment that is a blank line(empty line) OR Start of another segment which Segment: Page 23. Question: Is there any function where I can specify to python buit-in function to select specific line (such as starting from segment: page 22 TO the next new line) instead of the whole lines until EOF. e.g.: a = readlines (From , TO ) I asked a similar question before and that was well taught by experts, however, I am still confused. Can any one please help me again. Thank you. Kumar __________________________________ Do you Yahoo!? The all-new My Yahoo! - What will yours do? http://my.yahoo.com From kent37 at tds.net Sun Dec 5 14:58:18 2004 From: kent37 at tds.net (Kent Johnson) Date: Sun Dec 5 14:58:23 2004 Subject: [Tutor] unicode help (COM) In-Reply-To: <20041202011806.55DCC12CD9@mprdmxin.myway.com> References: <20041202011806.55DCC12CD9@mprdmxin.myway.com> Message-ID: <41B313FA.8010309@tds.net> Rene Bourgoin wrote: > Thanks for the responses. i'm a non-programmer and was learning/playing with some pyhton COM . > > I'm trying to get my resluts from an excel spreadsheet to be saved or printed or stored as a python string. when i run this the results are in unicode..... What problem are the unicode strings causing? If you want to convert them to normal strings you can use the encode method: >>> s=u'abc' >>> s u'abc' >>> s.encode('ascii') 'abc' Now it's a plain string. If the unicode string includes characters that aren't available in the selected encoding you will get an error: >>> s=u'?' >>> s.encode('ascii') Traceback (most recent call last): File "", line 1, in ? UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in position 0: ordinal not in range(128) You can change the handling of unknown characters by passing a second 'error' parameter: >>> s.encode('ascii', 'replace') '?' or pick a different encoding: >>> s.encode('utf-8') '\xc3\xa4' You can find a list of supported encodings in the docs for the 'codecs' module. Kent > > > from win32com.client import Dispatch > xlApp = Dispatch("Excel.Application") > xlApp.Visible = 0 > xlApp.Workbooks.Open("c:\sheet.xls") > excelout = () > excelout = xlApp.ActiveSheet.Range("C4:D10").Value > for item in excelout: > print item > > _______________________________________________ > No banners. No pop-ups. No kidding. > Make My Way your home on the Web - http://www.myway.com > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From singingxduck at gmail.com Sun Dec 5 15:21:03 2004 From: singingxduck at gmail.com (Orri Ganel) Date: Sun Dec 5 15:21:06 2004 Subject: [Tutor] Can i define anywhere on file object function for reading a range of lines? In-Reply-To: <20041205131121.12275.qmail@web53710.mail.yahoo.com> References: <20041205131121.12275.qmail@web53710.mail.yahoo.com> Message-ID: <3449428f0412050621596a84f8@mail.gmail.com> > Question: > Is there any function where I can specify to python > buit-in function to select specific line (such as > starting from segment: page 22 TO the next new line) > instead of the whole lines until EOF. > e.g.: > a = readlines (From , TO ) Well, Kumar, I don't know what you heard before, but you can always write your own modified "read" module and call it, say, "myread", with parameters fileobj (self explanatory: an open file), frompat (the pattern signifying where in the file you want to start collecting data), and endpat (the pattern signifying where in the file you want to stop collecting data). ### Start Code ### def myread(fileobj, frompat, endpat): fileobj.seek(0) ## ok, first make sure you're at the start of the file readl = [] try: while 1: line = fileobj.next() if line == frompat: ## if line is the starting pattern, readl.append(line) ## record it break ## but stop reading lines except StopIteration: ## if you've gone through the entire file without finding print "Sorry, could not find your starting pattern." ## the start pattern return False try: while 1: line = fileobj.next() if line != endpat: ## very similar to before, only now you record until readl.append(line) ## you reach the end pattern, not when you else: ## reach the starting pattern readl.append(line) break except StopIteration: print "Sorry, could not find your ending pattern." print "Here's the file past your starting pattern, though: " return readl return readl ### End Code ### And that's it! For your situation, you'd probably use it like: myread("segmentfile.txt", "Segment:Page 22\n", "Segment:Page 23\n") and modify the module so that it does not record the last line, ie take out the 3rd "readl.append(line)" line at line 19 in the module HTH, Orri. -- Email: dragonfirebane@aol.com AIM: singingxduck Programming Python for the fun of it. From rdm at rcblue.com Sun Dec 5 17:17:26 2004 From: rdm at rcblue.com (Dick Moores) Date: Sun Dec 5 17:18:02 2004 Subject: [Tutor] Could I have used time or datetime modules here? Message-ID: <6.1.2.0.2.20041205075719.02377370@rcblue.com> I'm wondering if my timer3.py could have been written more simply and easily by using the time or datetime modules to get the number of seconds separating the time now and the time to which the alarm is set. IOW, is there an easier way to calculate the time difference between the time now, say 08:51 and say, tomorrow at 03:45, to take an example of the most difficult case? See timer3.py at Thanks, tutors. Dick Moores rdm@rcblue.com From olli.s.rajala at tut.fi Sun Dec 5 17:28:01 2004 From: olli.s.rajala at tut.fi (Olli Rajala) Date: Sun Dec 5 17:28:05 2004 Subject: [Tutor] Address book sort of In-Reply-To: <20041204132811.78308.qmail@web42006.mail.yahoo.com> References: <20041204132811.78308.qmail@web42006.mail.yahoo.com> Message-ID: <20041205162801.GA21364@students.cc.tut.fi> Rick Muller(rick_muller@yahoo.com)@2004.12.04 05:28:11 +0000: > The advantage of pickle is that you don't have to > decide on a text format for your data -- it just dumps > and then reloads the python code. You can waste a lot > of time deciding on a text format, implementing the > readers/writers, etc. Well, it may be an advantage or it may one of the worst options... I try to avoid binary formats whenever possible. They're harder to debug, and usually don't offer much benefits when comparing to textual formats, etc. Read for example The Art of Unix Programming from Eric. S. Raymond if you want to know more. So, it may take much time to implement your read/write-functions but it's almost always at least as good as binary approach. Of course, as usual, YMMV and IMHO. :) -- Olli Rajala "In theory, Theory and Practice should be the same. But in practice, they aren't." - Murphy's Proverbs From bvande at po-box.mcgill.ca Sun Dec 5 17:40:38 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sun Dec 5 18:02:54 2004 Subject: [Tutor] Simple RPN calculator In-Reply-To: <41B2F727.7070107@tds.net> References: <20041204115419.6172.qmail@web54402.mail.yahoo.com> <"012e01c4da59 $4dd7cf70$c6ca8751"@xp> <8DB6AB80-464E-11D9-99F7-000393CBC88E@yahoo.fr> <41B2AA4A.6020604@po-box.mcgill.ca> <41B2F727.7070107@tds.net> Message-ID: <41B33A06.4090306@po-box.mcgill.ca> Kent Johnson said unto the world upon 2004-12-05 06:55: > RPN reverses the order of operator and operand, it doesn't reverse the > whole string. So in Polish Notation 2 + 3 is +23 and (2 + 3) - 1 is > -+231; in RPN they become 23+ and 23+1- > > Kent Hi all, Thanks Kent, that is what I had assumed it would be by analogy to Polish notation in logic. Somewhere on the thread, I though it had been asserted that all opps and operands were separated. For a bit there, I thought I'd gone all goofy :-) So, thanks for clearing that up. Thanks also for the other interesting posts on the thread. Largely off-topic things follow: One other advantage, at least from the logicians perspective is that standard "infix" notation is only able to comfortably deal with binary and unary operations (operations that have 2 or 1 arguments). For arithmetic, where you can do everything with zero, successor, multiplication, and addition, that isn't so important. But notice that general function notation, in Python and in math, is also Polish -- to write a 4 placed function that takes, say, the greatest common divisor of two numbers, and the least common multiple of two others, and tells you if the first divides the second, you've got to write: f(a,b,c,d). So, Polish notation makes manifest the conceptual similarity between the addition -- ADD(a,b) -- 2-placed function and arbitrary n-placed functions. This also helps out a lot in some of the areas where formal logic and formal semantics for natural languages bleed into each other. At a cost of patience, all truth functions can be expressed in terms of the "not both" truth function, so polyadic truth-functions past binary don't really need Polish notation. But, when you consider the quantifiers ('for everything . . .' and 'there is at least on thing . . . '), standard ones are one-placed (with a given universe of discourse set assumed). In the 1950's and 1960's mathematicians began exploring generalizations of the quantifier notion. There have, since the 1980's, been a sizable group of linguists who argue that natural language quantification is almost always 2 or higher placed. After two places, this too needs Polish notation (or heroic and ugly conventions). Brian vdB From alan.gauld at freenet.co.uk Sun Dec 5 18:55:59 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Dec 5 18:55:43 2004 Subject: [Tutor] Real time reading References: <4435.193.216.161.244.1102242692.squirrel@mail.sporck.net> Message-ID: <01e401c4daf3$ae186940$c6ca8751@xp> > send more than 5 mails pr minute (spams) and if so, get Python to send a > warningmail to the mailmaster. > > How would I in the best way read the log? Using the standard file methods... > To open the file and close it > every second sounds like a bad idea? It would be but you don't need to, you could read it every 5 minutes, every 15 minutes or even every hour. So long as the messages are timestamped - and in a log file they usually are - you can simply record where you got to last time, search down to that point and read forward from there. In fact, never mind time stamping, you could just find the position in the file using tell(), and the do a seek() that would be much faster... The frequency that you analyze the file will be governed by how often you need to notify the administrator - and he/she can't possibly read messages coming every second! (in fact in the event of a DoS attack your alerts would probably lock up the admins console - and make you almost as unpopular as the attackers!) Once every 5 minutes is probably a reasonable time interval. But why not make the number of minutes you check the file a configurable item, either a startup parameter or an environment variable, ir even store in a config file (seems to have been a lot about these this week :-) > Is there some function to analyze the > file, and automatically extract additions to the file? If you store where you got to last trime and use seek() to get back there you can just use read() (or readlines) to grab the new bits on one go, then use tell() to see where the end is and store that (that config file again?) Analyzing the contents is something you will need to write but that's straight string manipulation (I assume it is a text file!) HTH Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From bvande at po-box.mcgill.ca Sun Dec 5 18:54:29 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sun Dec 5 18:57:15 2004 Subject: [Tutor] Could I have used time or datetime modules here? In-Reply-To: <6.1.2.0.2.20041205075719.02377370@rcblue.com> References: <6.1.2.0.2.20041205075719.02377370@rcblue.com> Message-ID: <41B34B55.1010208@po-box.mcgill.ca> Dick Moores said unto the world upon 2004-12-05 11:17: > I'm wondering if my timer3.py could have been written more simply and > easily by using the time or datetime modules to get the number of > seconds separating the time now and the time to which the alarm is set. > IOW, is there an easier way to calculate the time difference between the > time now, say 08:51 and say, tomorrow at 03:45, to take an example of > the most difficult case? > > See timer3.py at > > > Thanks, tutors. > > Dick Moores > rdm@rcblue.com > Hi Dick and all, as you may recall, it was a week or so ago that I was show how to use datetime, so I'd be cautious about using my suggestion without testing :-) But, does this do what is wanted? import datetime def dif_in_seconds(dif): return dif.days * (24 * 60 * 60) + dif.seconds t1 = datetime.datetime(2004, 12, 5, 8, 51, 00) t2 = datetime.datetime(2004, 12, 6, 15, 45, 00) dif = t2 - t1 seconds_dif = dif_in_seconds(dif) print seconds_dif with output >>> 111240 I didn't check your link, or read your thread closely, so I don't know if this counts as "easier". But it does look pretty darned easy :-) Best, Brian vdB From marilyn at deliberate.com Sun Dec 5 19:06:41 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Sun Dec 5 19:06:44 2004 Subject: [Tutor] eval and exec In-Reply-To: <20041205032205.56219.qmail@web54309.mail.yahoo.com> Message-ID: On Sat, 4 Dec 2004, Chad Crabtree wrote: > Marilyn Davis wrote: > > >Thank you. You guys are great. > > > >I was trying to eval("import %s" % something). > > > >exec("import %s" % something) works just fine and now I understand > why. > > > >But, why is this so extremely dangerous? > > > >Marilyn > > > > > Mainly it's only extremely dangerous if it's going to be attacked at > all. What I mean is it will run any code that it imports this way, > even > untrusted code(possibly). Mostly I think that it's difficult to > debug, > however if it works you should use it. It seems that many people do > this at one point or another, and considered I guess inelegent by > some. > If security is an issue then this is a very big no no according to > what > I've heard. And Alan said: > But much better to use the __import__() function for doing that if > possible... Or simply importing all the modules you might need at the > beginning, its not a big overhead... > > Alan G. There's something about this that I'm not getting. Is it more dangerous than having the python interpreter around? Users will have access to our machine via the web and via email. We want to be safe against attack. As I understand it, Apache has modpython, so it runs all the python code that happens, no matter how many users, with only one copy of the interpreter in memory. It's sort of a big exec-machine, isn't it? I want to do the same trick for my Mail Transfer Agent, exim. Exim has a new feature where you can configure it to talk to an AF_UNIX socket to get any info it needs. An AF_UNIX socket is file-based and is not open for outside machines to connect to. So I made a little python program with a socket and threads so that exim can call the various python programs that I've written for sorting out mail. I don't want to introduce insecurity. But also I want to really understand what the problem is -- especially because I teach python. And I can't see the security problem, unless there's a security problem already, like if I allowed incoming email to dictate the parameters that I send through the socket. The email provides data for argv[1:] but argv[0] is hard-coded. And I don't see how web traffic can get there at all. If we had real users with login rights, then they could get to the interpreter and wouldn't need my little daemon to wreck havoc -- if I had my persmissions wrong. So what am I missing? Thank you for your help. Marilyn From marilyn at deliberate.com Sun Dec 5 19:23:08 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Sun Dec 5 19:23:11 2004 Subject: [Tutor] eval and exec In-Reply-To: Message-ID: And how can __import__ be safer? If an attacker can usurp the string in an exec call, couldn't he usurp the string in an __import__ call? And couldn't he import untrusted code? It could have a call to exec() in it? And what about the apply() function? Aren't all of these the same open door? I love the exec() call. I love the idea of code that makes and execs code. I'll make myself obsolete. :^) Marilyn On Sun, 5 Dec 2004, Marilyn Davis wrote: > On Sat, 4 Dec 2004, Chad Crabtree wrote: > > > Marilyn Davis wrote: > > > > >Thank you. You guys are great. > > > > > >I was trying to eval("import %s" % something). > > > > > >exec("import %s" % something) works just fine and now I understand > > why. > > > > > >But, why is this so extremely dangerous? > > > > > >Marilyn > > > > > > > > Mainly it's only extremely dangerous if it's going to be attacked at > > all. What I mean is it will run any code that it imports this way, > > even > > untrusted code(possibly). Mostly I think that it's difficult to > > debug, > > however if it works you should use it. It seems that many people do > > this at one point or another, and considered I guess inelegent by > > some. > > If security is an issue then this is a very big no no according to > > what > > I've heard. > > And Alan said: > > > But much better to use the __import__() function for doing that if > > possible... Or simply importing all the modules you might need at the > > beginning, its not a big overhead... > > > > Alan G. > > There's something about this that I'm not getting. > > Is it more dangerous than having the python interpreter around? > > Users will have access to our machine via the web and via email. We > want to be safe against attack. > > As I understand it, Apache has modpython, so it runs all the python > code that happens, no matter how many users, with only one copy of the > interpreter in memory. It's sort of a big exec-machine, isn't it? > > I want to do the same trick for my Mail Transfer Agent, exim. Exim > has a new feature where you can configure it to talk to an AF_UNIX > socket to get any info it needs. An AF_UNIX socket is file-based and > is not open for outside machines to connect to. So I made a little > python program with a socket and threads so that exim can call the > various python programs that I've written for sorting out mail. > > I don't want to introduce insecurity. But also I want to really > understand what the problem is -- especially because I teach python. > > And I can't see the security problem, unless there's a security > problem already, like if I allowed incoming email to dictate the > parameters that I send through the socket. The email provides data > for argv[1:] but argv[0] is hard-coded. > > And I don't see how web traffic can get there at all. > > If we had real users with login rights, then they could get to the > interpreter and wouldn't need my little daemon to wreck havoc -- if I > had my persmissions wrong. > > So what am I missing? > > Thank you for your help. > > Marilyn > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- From mgoerg at siemens.sn.uni-magdeburg.de Sun Dec 5 19:38:23 2004 From: mgoerg at siemens.sn.uni-magdeburg.de (Matthias Goergens) Date: Sun Dec 5 19:38:29 2004 Subject: [Tutor] pickle In-Reply-To: <20041205175546.899DC1E4010@bag.python.org> References: <20041205175546.899DC1E4010@bag.python.org> Message-ID: >> The advantage of pickle is that you don't have to >> decide on a text format for your data -- it just dumps >> and then reloads the python code. You can waste a lot >> of time deciding on a text format, implementing the >> readers/writers, etc. > Well, it may be an advantage or it may one of the worst options... I > try to avoid binary formats whenever possible. They're harder to > debug, and usually don't offer much benefits when comparing to textual > formats, etc. Read for example The Art of Unix Programming from > Eric. S. Raymond if you want to know more. > So, it may take much time to implement your read/write-functions but > it's almost always at least as good as binary approach. Pickle does not dump actual python code, but some simple stack language. I think it might be even in RPN. Pickle offers you a choice between binary and text format. It defaults to text format. Matthias -----BEGIN GEEK CODE BLOCK----- Version: 3.1 GM/P/>SS/>CC d--(+) s-: a--- C++ UL++ P-? L++ E- W++ N o? K? !w-- !O? !M? !V? PS+++ PE++ Y+ PGP>+ t+ 5?>+ X(+) R+ !tv- b++(+++) DI?>+ D+++ G+ e->+++ h+ r y ------END GEEK CODE BLOCK------ "I have made this letter longer than usual because I lack the time to make it shorter." -- Blaise Pascal From alan.gauld at freenet.co.uk Sun Dec 5 20:37:38 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Dec 5 20:37:17 2004 Subject: [Tutor] Can i define anywhere on file object function for reading arange of lines? References: <20041205131121.12275.qmail@web53710.mail.yahoo.com> Message-ID: <01fd01c4db01$e18fbb80$c6ca8751@xp> > Is there any function where I can specify to python > buit-in function to select specific line (such as > starting from segment: page 22 TO the next new line) > instead of the whole lines until EOF. > e.g.: > a = readlines (From , TO ) Not quite, but you can do: readlines()[from:to] With the disadvantage that the whoile file gets read into RAM before the slicing takes place - but then it gets garbage collected again pretty well immediately... HTH, Alan G. From rdm at rcblue.com Sun Dec 5 21:03:10 2004 From: rdm at rcblue.com (Dick Moores) Date: Sun Dec 5 21:03:59 2004 Subject: [Tutor] Could I have used time or datetime modules here? In-Reply-To: <41B34B55.1010208@po-box.mcgill.ca> References: <6.1.2.0.2.20041205075719.02377370@rcblue.com> <41B34B55.1010208@po-box.mcgill.ca> Message-ID: <6.1.2.0.2.20041205112204.04e9d100@rcblue.com> Thanks, Brian. I looked at your code a long time, and also read the 11/26 thread you started. I can see how I could use datetime() and your t2 - t1 to get the seconds for time.sleep(), but the resulting code I have in mind is more convoluted than the heart of my timer3.py, which I quote below. (I don't need the alarm time to be more than 24 hours from current time--therefore I want to ignore the year, month, and day.) ======================================= import time alarm = raw_input("Enter alarm time as hhmm: ") now = time.strftime("%X") # produces current time in format hh:mm:ss nowSecond = int(now[6:]) nowMinute = int(now[3:5]) nowHour = int(now[0:2]) alarmMinute = int(alarm[2:4]) alarmHour = int(alarm[0:2]) hoursDiff = alarmHour - nowHour minutesDiff = alarmMinute - nowMinute if hoursDiff < 0 or (hoursDiff == 0 and minutesDiff <= 0): hoursDiff = hoursDiff + 24 # add a day sleepSeconds = hoursDiff*3600 + minutesDiff*60 - nowSecond time.sleep(sleepSeconds) ==================================== If I'm wrong, could someone please set me right? Dick Brian van den Broek wrote at 09:54 12/5/2004: >Dick Moores said unto the world upon 2004-12-05 11:17: >>I'm wondering if my timer3.py could have been written more simply and >>easily by using the time or datetime modules to get the number of >>seconds separating the time now and the time to which the alarm is set. >>IOW, is there an easier way to calculate the time difference between >>the time now, say 08:51 and say, tomorrow at 03:45, to take an example >>of the most difficult case? >>See timer3.py at >> >>Thanks, tutors. >>Dick Moores >>rdm@rcblue.com > >Hi Dick and all, > >as you may recall, it was a week or so ago that I was show how to use >datetime, so I'd be cautious about using my suggestion without testing :-) > >But, does this do what is wanted? > > >import datetime > >def dif_in_seconds(dif): > return dif.days * (24 * 60 * 60) + dif.seconds > >t1 = datetime.datetime(2004, 12, 5, 8, 51, 00) >t2 = datetime.datetime(2004, 12, 6, 15, 45, 00) >dif = t2 - t1 > >seconds_dif = dif_in_seconds(dif) >print seconds_dif > > >with output > > >>> >111240 > >I didn't check your link, or read your thread closely, so I don't know >if this counts as "easier". But it does look pretty darned easy :-) > >Best, > >Brian vdB From dyoo at hkn.eecs.berkeley.edu Sun Dec 5 22:05:27 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Dec 5 22:05:38 2004 Subject: [Tutor] Upgrade to 2.4 In-Reply-To: <41B1E33D.1080601@sc.rr.com> Message-ID: On Sat, 4 Dec 2004, William Allison wrote: > I compiled Python 2.3.4 from source, but now I would like to upgrade to > 2.4. There doesn't seem to be a "make uninstall" target for 2.3.4. > Will compiling 2.4 overwrite the older version, or will I have two > versions of Python on my system? Hi Will, According to the README, you can install Python 2.4 in a way that doesn't overwrite your older version of Python. Here's a snippet from the README: """ If you have a previous installation of Python that you don't want to replace yet, use make altinstall This installs the same set of files as "make install" except it doesn't create the hard link to "python" named "python" and it doesn't install the manual page at all. """ This should install '/usr/local/bin/python2.4', but otherwise, it should leave the rest of your Python 2.3.4 installation intact. Hope this helps! From keridee at jayco.net Sun Dec 5 21:41:03 2004 From: keridee at jayco.net (Jacob S.) Date: Sun Dec 5 22:23:58 2004 Subject: [Tutor] Accuracy of time.sleep() References: <41B1C8AD.6060806@pusspaws.net> Message-ID: <002701c4db10$afe84110$4d5328cf@JSLAPTOP> You know, since time.sleep() builds up errors, this is what I do to keep it purely pythonic... (not tested) from time import gmtime alarmhr = 8 alarmmin = 5 alarmsec = 0 while 1: t = gmtime() hour = t[3] min = t[4] sec = t[5] if (alarmhr,alarmmin,alarmsec) == (hour,min,sec): print "It is 8:05 AM. Please do whatever you are supposed to at this time. raw_input() break > OK I may be pushing it, ;-) > > I need a script to sleep from any point to 8:05AM when in needs to > re-start. > > So I calculate the number of seconds with the following .... > > > > > def secs_till_805(): > # Returns the number of seconds till 8:05AM > > secs_5min=5*60 > secs_24hr=24*60*60 > secs_8hr=(8*60*60)+secs_5min > secs_8hr_24hr=secs_24hr-secs_8hr > > hours=int(strftime('%H')) > mins=int(strftime('%M')) > secs=int(strftime('%S')) > > sec_left=secs_24hr-((hours*60*60)+(mins*60)+secs) > > # If we are before 8:05, then ... > if sec_left>secs_8hr_24hr: > return sec_left-secs_8hr_24hr > > # If we are after 8:05, then ... > return sec_left+secs_8hr > > > > Then I ... > > sleep(secs_till_805()) > > I expected the script to re-start 2-3 seconds after 8:05, python > reloading after a long sleep etc, what I get is the script restarting at > 08:04.55, earlier ??? > > OK this is not a world stopping problem, more of a curiosity. > > Any suggestions > > Dave > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From keridee at jayco.net Sun Dec 5 14:38:39 2004 From: keridee at jayco.net (Jacob S.) Date: Sun Dec 5 22:24:18 2004 Subject: [Tutor] comapring lists References: Message-ID: <002601c4db10$ad745ae0$4d5328cf@JSLAPTOP> Wow! I never thought of using dictionaries to store function objects like that! The "table-driven" approach is much better than my own! Thanks a lot! Jacob Schmidt > > > On Thu, 2 Dec 2004, Jacob S. wrote: > > > If you or anybody else is interested, I've written a script for codes like > > kids in junior high use to write notes to each other with... > > Hi Jacob, > > Cool! Do you mind if I make some comments on the code? If you do mind... > um... skip this message. *grin* > > > The main body of the program feels a bit too long: it screams to be broken > into a few helper functions. I see that there are two critical variables > that are used to figure out which part of the program comes next: > > > ### > unordo = raw_input('Are we going to decipher or cipher? ') > type = raw_input('Which type of code would you like? ').lower() > > if type == 'mixed letters': > if unordo == 'cipher': > # ... do mixed letter ciphering > if unordo == 'decipher': > # ... do mixed letter deciphering > if type == 'insideout': > if unordo == 'cipher': > # ... do insideout ciphering > if unordo == 'decipher': > # ... do mixed letter decipering > # ... rest of the program follows similar structure > ### > > > > In a case like this, we can break the program into separate functions, > like this: > > ### > def dispatchOnTypeAndUnordo(type, unordo): > if type == 'mixed letters': > if unordo == 'cipher': > mixedLetterCipher() > if unordo == 'decipher': > mixedLetterDecipher() > if type == 'insideout': > if unordo == 'cipher': > insideoutCipher() > if unordo == 'decipher': > insideoutDecipher() > # ... rest of the program follows similar structure > ### > > We make each 'body' of the inner "if"'s into their own functions, like > 'mixedLetterCipher()'. This restructuring doesn't improve the program's > performance at all, but it does help readability: the main improvement is > to make the overall shape of the program all visible at once. > > > This structural change also paves the way for a "table-driven" way to > implement a decision tree. Experienced programmers really try to avoid > code that looks like "if/if/if/if/if..." because that's probably some kind > of repeating structure that we can take advantage of. > > > The logic on the function dispatchOnTypeAndUnordo() has an internal rhythm > that we can capture as a data structure. Here's a dictionary that tries > to capture the essentials of the beat: > > ### > dispatchTable = { 'mixed letters': (mixedLetterCipher, > mixedLetterDecipher), > 'insideout' : (insideOutCipher, > insideOutDecipher), > ## ... rest of the dictionary follows similar structure > } > ### > > [Note: the values in this dictionary --- the function names --- are > intentionally without parentheses. We don't want to "call" the functions > just yet, but just want to store them off.] > > > If we have a dispatch table like this, then the dispatchOnTypeandUnordo() > magically dissolves: > > ### > def dispatchOnTypeAndUnordo(type, unordo): > (cipherFunction, decipherFunction) = dispatchTable[type] > if unordo == 'cipher': > cipherFunction() > elif unordo == 'decipher': > decipherFunction() > ### > > > This is a "table-driven" or "data-driven" approach. The choices available > to the program have been migrated away from the explicit, separate 'if' > statements, and now really live as part of the 'dispatchTable' dictionary. > > > Does this make sense so far? Please feel free to ask questions. > > > From keridee at jayco.net Sun Dec 5 22:31:59 2004 From: keridee at jayco.net (Jacob S.) Date: Sun Dec 5 22:34:03 2004 Subject: [Tutor] Address book sort of References: Message-ID: <003b01c4db12$1d709bf0$4d5328cf@JSLAPTOP> I did something like this about three or four months ago... This is what I did. Notice the use of the built-in str() and eval() functions to write and receive data to and from Telephone.cfg... from __future__ import division tel = {} try: file = open('Telephone.cfg', 'r') except: file = open('Telephone.cfg','w') file.close() file = open('Telephone.cfg','r') try: tel = eval(file.read()) a = 0 except: a = 1 print "No entries on file." pass print """\ Commands are: add get save delete quit all is a wildcard """ while 1: ask = raw_input('Tell me what you wish to do. ') if ask == "quit": break ask = ask.split(" ") command = ask[0] entity = ask[1:] entity = " ".join(entity) if entity == '': entity = raw_input("Who do you want to %s? " % command) if command == 'add': person = entity if tel.has_key(person): print "That person is already in there. If you wish to edit the file, please delete the record first." else: tel[person] = raw_input("What is their phone number? ") if command == 'get': if a == 1: print "Sorry, there are no entries available." else: person = entity if person == 'all': key = tel.keys() key.sort() print for x in key: print "%s\n%s\n" % (x,tel[x]) elif tel.has_key(person): print "\n%s\n%s\n" % (person,tel[person]) else: print "%s is not in your records." % person if command == 'save': file=open('Telephone.cfg', 'w') file.write(str(tel)) file.close() print 'Saved in Telephone.cfg' if command == 'delete': if a == 1: print "Sorry, there are no entries available." else: person = entity if person == 'all': tel={} newfile=open('Telephone.cfg', 'w') newfile.close() else: if tel.has_key(person): del tel[person] else: print "%s is not in your records." % person file.close() file = open('Telephone.cfg', 'w') file.write(str(tel)) file.close() As always, feel free to modify, use, and otherwise tear apart my code and give me suggests on how to improve it. Jacob Schmidt > Dear Tutor, > > I like to know what is the proper procedure (is algorithmn the right > term?) in creating data in a program, write it to file, close the app > then retrieve the data when run again. Basically, I'm trying to simulate > a simple address book (well not really for the datas are just names for > now) and so far have created the basic menu interface. It is console > base so forget gui. I ask user input and store it in a list. There are > menus to change, delete the data, and to save the data list in file. I > use cPickle for this and have verified the file is created by checking > in my $PWD. I want to retrieve that data when program is run again. What > to add in my code? I thought not to post the code but explain it as > above. > > What i want: when program is run again, the saved data is loaded when user > selects option 1 below. Of course the first time it is run, the list is > empty. > > def print_options(): > print ''' > Options: > [1] - Print content of list > [2] - Add name to list > [3] - Delete name from list > [4] - Change name in list > [5] - Save list to file > [P] - Print this menu > [Q] - Quit > ''' > > > > -- > Regards, > Eri Mendz > Using PC-Pine 4.61 > > > -- > Using PC-Pine 4.61 > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From dyoo at hkn.eecs.berkeley.edu Sun Dec 5 22:40:35 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun Dec 5 22:40:40 2004 Subject: [Tutor] eval and exec In-Reply-To: Message-ID: > I don't want to introduce insecurity. But also I want to really > understand what the problem is -- especially because I teach python. Hi Marilyn, Here is an example of a string that can cause a StackOverflow error to happen: ### s = "(lambda loop: loop(loop)) (lambda self: self(self))" eval(s) ### The string 's' here looks funky, but in effect, it's definition is an infinite loop in heavy lambda disguise. (Well, it would have been infinite if Python had tail call optimization... *grin*) The problem about eval() is that it's deceptively powerful: a single expression in a language might seem like a small thing. But as soon as we allow someone the ability to evaluate a single arbitrary expression, we've basically given them the ability to do practically anything in Python. eval() is THAT POWERFUL. Here's another example: ### def myint(x): """Makes an integer out of x.""" return eval(x) print myint("41") + 1 print myint("42 and __import__('os').system('tail /etc/passwd')") ### > And I can't see the security problem, unless there's a security problem > already, like if I allowed incoming email to dictate the parameters that > I send through the socket. The email provides data for argv[1:] but > argv[0] is hard-coded. The problem is one of capability. At worse, a function like: ### def myint(x): return int(x) if __name__ == '__main__': print myint(sys.argv[1]) + 1 ### can raise an exception if given weird command line arguments, but it at least doesn't give the caller the ability to run an arbitrary shell command. Contrast this situation to the version of myint() that uses eval(). Does this make sense? Please ask more questions on this if you have any: using eval() is almost certainly not a good idea unless you really know what you're doing. From cyresse at gmail.com Sun Dec 5 22:56:44 2004 From: cyresse at gmail.com (Liam Clarke) Date: Sun Dec 5 22:56:48 2004 Subject: [Tutor] Simple RPN calculator In-Reply-To: <41B33A06.4090306@po-box.mcgill.ca> References: <20041204115419.6172.qmail@web54402.mail.yahoo.com> <8DB6AB80-464E-11D9-99F7-000393CBC88E@yahoo.fr> <41B2AA4A.6020604@po-box.mcgill.ca> <41B2F727.7070107@tds.net> <41B33A06.4090306@po-box.mcgill.ca> Message-ID: My head boggles. This is like trying to understand game theory. On Sun, 05 Dec 2004 11:40:38 -0500, Brian van den Broek wrote: > Kent Johnson said unto the world upon 2004-12-05 06:55: > > RPN reverses the order of operator and operand, it doesn't reverse the > > whole string. So in Polish Notation 2 + 3 is +23 and (2 + 3) - 1 is > > -+231; in RPN they become 23+ and 23+1- > > > > Kent > > Hi all, > > Thanks Kent, that is what I had assumed it would be by analogy to Polish > notation in logic. Somewhere on the thread, I though it had been > asserted that all opps and operands were separated. For a bit there, I > thought I'd gone all goofy :-) So, thanks for clearing that up. > > Thanks also for the other interesting posts on the thread. > > Largely off-topic things follow: > > One other advantage, at least from the logicians perspective is that > standard "infix" notation is only able to comfortably deal with binary > and unary operations (operations that have 2 or 1 arguments). For > arithmetic, where you can do everything with zero, successor, > multiplication, and addition, that isn't so important. But notice that > general function notation, in Python and in math, is also Polish -- to > write a 4 placed function that takes, say, the greatest common divisor > of two numbers, and the least common multiple of two others, and tells > you if the first divides the second, you've got to write: > f(a,b,c,d). > > So, Polish notation makes manifest the conceptual similarity between the > addition -- ADD(a,b) -- 2-placed function and arbitrary n-placed functions. > > This also helps out a lot in some of the areas where formal logic and > formal semantics for natural languages bleed into each other. At a cost > of patience, all truth functions can be expressed in terms of the "not > both" truth function, so polyadic truth-functions past binary don't > really need Polish notation. > > But, when you consider the quantifiers ('for everything . . .' and > 'there is at least on thing . . . '), standard ones are one-placed (with > a given universe of discourse set assumed). In the 1950's and 1960's > mathematicians began exploring generalizations of the quantifier notion. > There have, since the 1980's, been a sizable group of linguists who > argue that natural language quantification is almost always 2 or higher > placed. After two places, this too needs Polish notation (or heroic and > ugly conventions). > > > > Brian vdB > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From keridee at jayco.net Sun Dec 5 23:06:17 2004 From: keridee at jayco.net (Jacob S.) Date: Sun Dec 5 23:06:36 2004 Subject: [Tutor] gzip (fwd) References: <82c0f73b041203011670566c48@mail.gmail.com> Message-ID: <009901c4db16$a694a760$4d5328cf@JSLAPTOP> Hello! > >target_dir = 'D:\\backup' > >target = target_dir +"Zipnametoreplacestrftimeformatstring"+ '.zip' > > Just noticed this - > > target_dir("D:\\backup") + "Zipnametoreplacestrftimeformatstring"+ '.zip' > > = D:\\backupZipnametoreplacestrftimeformatstring.zip > > No wonder it doesn't work. > > Try > > target=target_dir+'\\'+time.strftime('%Y%m%d%H%M%S') + '.zip' Instead of doing this, use os.path.join to make it more platform independent. target = os.path.join(target_dir,time.strftime('%Y%m%d%H%M%S')+'.zip') > > Regards, > > Liam Clarke > > PS Yes, do use reply to all > > > > > On Fri, 3 Dec 2004 15:16:27 +0600, Ramkumar Parimal Alagan > wrote: > > I have only 2 word documents in both the directories, i tried removing > > '-qr' too, but no change, no zip files formed. i'm using windows XP. > > > > On Thu, 2 Dec 2004 23:54:11 -0800 (PST), Danny Yoo > > > > > > wrote: > > > Hi Ramkumar, > > > > > > I'm forwarding your message to Python-tutor; in your replies, please make > > > sure that you are using the "reply-to-all" feature in your email client. > > > This will allow your response to reach the others on the tutor list. > > > Don't rely on me alone: give the community the chance to help you. > > > > > > I don't have enough information to pinpoint what the problem is yet. I'll > > > have to ask more questions, and others on the Tutor list will probably > > > also ask a few questions. Please try to answer them, because that will > > > help us give a better idea of what the problem is. > > > > > > It looks like you are trying to zip up whole directories. Does the > > > program work if you zip up single files? > > > > > > It also appears that you're using the '-q' and '-r' options of the 'zip' > > > command line utility. '-q' stands for 'quiet' mode, and although that's > > > nice when the command is working properly, it's not helpful when you're > > > debugging a situation. Try turning quiet mode off, so that you have a > > > better chance of getting good error output from the zip command. Even > > > better, try enabling verbose mode, so you can see better what 'zip' is > > > attempting to do. > > > > > > Do you see anything else when you execute the program? Does anything else > > > come out of standard error? > > > > > > Good luck to you. > > > > > > ---------- Forwarded message ---------- > > > Date: Fri, 3 Dec 2004 10:24:15 +0600 > > > From: Ramkumar Parimal Alagan > > > To: Danny Yoo > > > Subject: Re: [Tutor] gzip > > > > > > This is what i intend to do: > > > > > > 1. The files and directories to be backed up are given in a list. > > > 2. The backup must be stored in a main backup directory. > > > 3. The files are backed up into a zip file. > > > 4. The name of the zip archive is the current date and time. > > > > > > the coding: > > > > > > ______________ > > > > > > import os > > > import time > > > > > > source = ['D:\\down', 'D:\\Pics'] > > > > > > target_dir = 'D:\\backup' > > > > > > target = target_dir + time.strftime('%Y%m%d%H%M%S') + '.zip' > > > > > > zip_command = "zip -qr '%s' %s" % (target, ' '.join(source)) > > > > > > if os.system(zip_command) == 0: > > > print 'Successful backup to', target > > > else: > > > print 'Backup FAILED' > > > > > > _____________________________ > > > > > > result : Backup FAILED > > > > > > whats wrong ? > > > > > > > > > > > > -- > > > > << The end depends upon the beginning. >> > > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > -- > 'There is only one basic human right, and that is to do as you damn well please. > And with it comes the only basic human duty, to take the consequences. > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From domain.admin at online.ie Sun Dec 5 23:08:10 2004 From: domain.admin at online.ie (Guybrush Threepwood) Date: Sun Dec 5 23:08:15 2004 Subject: [Tutor] CGI Video collection application File I/O troubles Message-ID: <1102284490.41b386cac3033@mail.online.ie> Hello! I am having some problems with a simple CGi application I am coding for my gf. It is supposed to be a video collection program. I can't manage to write the value of a dictionary key to a file. Like thisL f.write(videodb['title']) It just creates a blank file. When i try to access the videodb['title'] key from the python shell it prints out the correct value respecitvely. Even when I use the print command to write to a HTML file it outputs the correct value of videodb['title'] for example. When I run the script in python shell it says: TypeError: argument 1 must be string or read-only character buffer, not None Why doesn't it write the value to the file? Here's the complete source code: #!/usr/bin/python import cgi,string filename='/var/www/cgi-bin/videodb' print "Content-type: text/html\n" #extract variable s form=cgi.FieldStorage() title=form.getvalue("title") year=form.getvalue("year") director=form.getvalue("director") videodb={'title':title,'year':year,'director':director} #save to database f=open(filename,'w') f.write(videodb['title']) f.close() -- The lady on the call box in Monkey Island 2 Guybrush: I'm lost in the Inky Island Jungle in Monkey 2 Lady: Just walk off the edge of the screen From keridee at jayco.net Sun Dec 5 23:20:31 2004 From: keridee at jayco.net (Jacob S.) Date: Sun Dec 5 23:20:49 2004 Subject: [Tutor] CGI Video collection application File I/O troubles References: <1102284490.41b386cac3033@mail.online.ie> Message-ID: <00ba01c4db18$a53d1bc0$4d5328cf@JSLAPTOP> Hi! Can I ask a few questions? (Other than this one...) What output did you expect? A string, tuple, or what? I'm not strong with cgi stuff. Also, you don't need the string module 1) because you don't use it 2) because you can use string methods. Jacob Schmidt > Hello! > > I am having some problems with a simple CGi application I am > coding for my gf. It is supposed to be a video collection > program. I can't manage to write the value of a dictionary > key to a file. Like thisL > f.write(videodb['title']) > > It just creates a blank file. When i try to access the > videodb['title'] key from the python shell it prints > out the correct value respecitvely. Even when I use the > print command to write to a HTML file it outputs the > correct value of videodb['title'] for example. > When I run the script in python shell it says: > TypeError: argument 1 must be string or read-only character buffer, not None > > Why doesn't it write the value to the file? > > Here's the complete source code: > > #!/usr/bin/python > import cgi,string > > filename='/var/www/cgi-bin/videodb' > print "Content-type: text/html\n" > > #extract variable s > form=cgi.FieldStorage() > title=form.getvalue("title") > year=form.getvalue("year") > director=form.getvalue("director") > > videodb={'title':title,'year':year,'director':director} > > #save to database > f=open(filename,'w') > f.write(videodb['title']) > f.close() > > -- > The lady on the call box in Monkey Island 2 > Guybrush: I'm lost in the Inky Island Jungle in Monkey 2 > Lady: Just walk off the edge of the screen > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From domain.admin at online.ie Sun Dec 5 23:32:27 2004 From: domain.admin at online.ie (Guybrush Threepwood) Date: Sun Dec 5 23:32:29 2004 Subject: Fwd: Re: [Tutor] CGI Video collection application File I/O troubles Message-ID: <1102285947.41b38c7b3b248@mail.online.ie> Quoting "Jacob S." : > Hi! > > Can I ask a few questions? (Other than this one...) > What output did you expect? A string, tuple, or what? A string output. When I create a dictionary variable from the python shell like this: videodb={'title':'Crash','year':'1996','director':'David Cronenberg'} and type in videodb['title'] afterwards python spits out the value 'Crash'. That's fine I get a string as expected. But when I try to write the value of videodb['title'] to a file nothing gets written. I hope I clarified the issue somewhat. > I'm not strong with > cgi stuff. > Also, you don't need the string module 1) because you don't use it 2) > because you can use string methods. > > Jacob Schmidt ok. I'll remove it. thanx. [snip] -- The lady on the call box in Monkey Island 2 Guybrush: I'm lost in the Inky Island Jungle in Monkey 2 Lady: Just walk off the edge of the screen From patric at usa.net Sun Dec 5 23:44:13 2004 From: patric at usa.net (Patric Michael) Date: Sun Dec 5 23:43:10 2004 Subject: Just Because (Was: Re: [Tutor] Global presets ?) In-Reply-To: <41B1F52B.2050503@po-box.mcgill.ca> References: <41B19DC7.4080006@tds.net> Message-ID: <41B31EBD.27829.9E27126@localhost> <> Folks... I originally discovered this list while searching Google for the mathematical expression to convert yards to inches. Seems someone already did it in a python function. (I think maybe it was Kent?) At any rate, I subscribed to the list out of curiosity, partly because I like python (even the math challenged like me can manage it!) and because I am nowhere near fluent with it. And I stay with the list, partly because the folks who frequent it are by and large quite friendly, and because there are always little tidbits like the one below: > I avoid this by using the > import examplemodule as em How many times have I clobbered a namespace while trying to save a bit of time typing... Yeesh! So, while most everyone here is better suited to make replies, let me just say "Thanks!" to everyone who takes the time to read, and especially to those who respond to the wide variety of questions we post. Thanks! Patric From keridee at jayco.net Sun Dec 5 23:46:39 2004 From: keridee at jayco.net (Jacob S.) Date: Sun Dec 5 23:46:54 2004 Subject: [Tutor] CGI Video collection application File I/O troubles References: <1102284490.41b386cac3033@mail.online.ie> <00ba01c4db18$a53d1bc0$4d5328cf@JSLAPTOP> <1102285829.41b38c05994f0@mail.online.ie> Message-ID: <00de01c4db1c$4ab85c60$4d5328cf@JSLAPTOP> Your error message says that you are getting an empty string from your cgi variable. I IMHO would suggest printing videodb['title'] before writing it to a file to see what the variable contains. Or you might print out videodb to see what the dictionary looks like. My off the wall guess is that 1) Your cgi variables are not returning the value from the actual object that you want 2) The script is running and assigning values to title, etc. before the afore mentioned object is given a value. IOW, maybe you haven't assigned values to the form before you try to read them. Another suggestion. Comment out the file writing part and print everything to the screen to verify that the output is what you want. "When in doubt, print it out." - Jacob Schmidt HTH, Jacob > Quoting "Jacob S." : > > > Hi! > > > > Can I ask a few questions? (Other than this one...) > > What output did you expect? A string, tuple, or what? > > A string output. When I create a dictionary variable from > the python shell like this: > videodb={'title':'Crash','year':'1996','director':'David Cronenberg'} > > and type in videodb['title'] afterwards python spits out the > value 'Crash'. That's fine I get a string as expected. > But when I try to write the value of videodb['title'] to > a file nothing gets written. > I hope I clarified the issue somewhat. > > > I'm not strong with > > cgi stuff. > > Also, you don't need the string module 1) because you don't use it 2) > > because you can use string methods. > > > > Jacob Schmidt > > ok. I'll remove it. thanx. > > [snip] > > -- > The lady on the call box in Monkey Island 2 > Guybrush: I'm lost in the Inky Island Jungle in Monkey 2 > Lady: Just walk off the edge of the screen > > From pythontut at pusspaws.net Mon Dec 6 00:08:34 2004 From: pythontut at pusspaws.net (Dave S) Date: Mon Dec 6 00:08:41 2004 Subject: [Tutor] Accuracy of time.sleep() In-Reply-To: <002701c4db10$afe84110$4d5328cf@JSLAPTOP> References: <41B1C8AD.6060806@pusspaws.net> <002701c4db10$afe84110$4d5328cf@JSLAPTOP> Message-ID: <41B394F2.9060703@pusspaws.net> Jacob S. wrote: >You know, since time.sleep() builds up errors, this is what I do to keep it >purely pythonic... (not tested) > >from time import gmtime > >alarmhr = 8 >alarmmin = 5 >alarmsec = 0 > >while 1: > t = gmtime() > hour = t[3] > min = t[4] > sec = t[5] > if (alarmhr,alarmmin,alarmsec) == (hour,min,sec): > print "It is 8:05 AM. Please do whatever you are supposed to at this >time. > raw_input() > break > > > Yep this is an option that makes sense to me, getting time once & breaking it down with []'s to avoid the trap I almost fell into. I know cron is probarbly the way to go but .... Its kind of nice to keep it all Python if you know what I mean ;-) Dave From wallison1 at sc.rr.com Mon Dec 6 00:19:42 2004 From: wallison1 at sc.rr.com (William Allison) Date: Mon Dec 6 00:18:35 2004 Subject: [Tutor] Upgrade to 2.4 In-Reply-To: References: Message-ID: <41B3978E.70301@sc.rr.com> Danny Yoo wrote: >On Sat, 4 Dec 2004, William Allison wrote: > > > >> I compiled Python 2.3.4 from source, but now I would like to upgrade to >>2.4. There doesn't seem to be a "make uninstall" target for 2.3.4. >>Will compiling 2.4 overwrite the older version, or will I have two >>versions of Python on my system? >> >> > >Hi Will, > >According to the README, you can install Python 2.4 in a way that doesn't >overwrite your older version of Python. Here's a snippet from the README: > > >""" >If you have a previous installation of Python that you don't >want to replace yet, use > > make altinstall > >This installs the same set of files as "make install" except it >doesn't create the hard link to "python" named "python" and >it doesn't install the manual page at all. >""" > >This should install '/usr/local/bin/python2.4', but otherwise, it should >leave the rest of your Python 2.3.4 installation intact. > > >Hope this helps! > > > > Yeah, I saw that, but didn't want two versions of Python hanging around. I went ahead and did "make install" for 2.4 and it replaced the previous version. Thanks, Will From alan.gauld at freenet.co.uk Mon Dec 6 00:41:34 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Dec 6 00:41:20 2004 Subject: [Tutor] eval and exec References: Message-ID: <021901c4db23$f4ee4210$c6ca8751@xp> > And I can't see the security problem, unless there's a security > problem already, like if I allowed incoming email to dictate the > parameters that I send through the socket. The email provides data > for argv[1:] but argv[0] is hard-coded. > > And I don't see how web traffic can get there at all. You can generate a CGI call b by typing the GET string straight into the address bar of the browser. If a smart user realises that some of the parameters are being interpreted they can (and often will) try to fake what the page genersates, this could involve putting python commands, such as 'import os;os.system("rm -f /")' into the escape string... Equally if you embed Python in a program and allow users to type strings whoich are then exec() or eval()'d they could type a similar os.system() command. Or they might use print and dir to find variable names and manipulate those. Even in a config file, if its plain text a hostile (or just mischievous) user could add a dangerous line and when you try to exec it bad things happen. Any time you allow users to influence what code runs you have potential for trouble - that is the principle behind all these "buffer overrun" security errors as well as all the script kiddie attacks - MS allows Outlook to run scripts when mail is open, if those scripts are harmful we have a virus! > If we had real users with login rights, then they could get to the > interpreter and wouldn't need my little daemon to wreck havoc -- if I > had my persmissions wrong. But by opening access to exec() you effectively give your users access to a PYthon session within *your* login rights (or root or the web user etc) Its not a trivial thing to exploit but it can be done and either accidentally(*) or deliberately bad things can result. (*) Recall that one of the most common user support issues on Unix systems is people typing "rm / foo" with a space instead of "rm /foo". The first one (attempts to) delete the root directory - oops! Alan G. From alan.gauld at freenet.co.uk Mon Dec 6 00:48:29 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Dec 6 00:48:12 2004 Subject: [Tutor] eval and exec References: Message-ID: <021e01c4db24$ec979840$c6ca8751@xp> > And how can __import__ be safer? Safer because it is limited in what it can do, import a file. The file must exist in the python path, so its much harder for the user to do something bad - they have to create a new file with malicious code in it and insert it into the python path and then get that filename string into your program. Its much, much easier when you can type malicious code directly > And couldn't he import untrusted code? Yes, but he has to get the code onto your machine first! > in it? And what about the apply() function? Aren't all of these the > same open door? Again apply calls a pre-existing function, the attacker has to actually create the function and get it into your namespace before calling it. All of these are potentially dangerous, you are right, but they are second order dangers because they 1) have a clearly delimited scope of what can be done 2) the string executed is not directly executed, it must fit a specific form and is therefore more easily monitored for "sanity" before execution. 3) The code that is executed must already exist. > I love the exec() call. I love the idea of code that makes and execs > code. I'll make myself obsolete. :^) It is very powerful, and self modifying code is indeed fun to play with (albeit surprisingly difficult to find a genuine use for!) But it must be used in full cognisance of the security dangers. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From michael.j.eve at gmail.com Mon Dec 6 01:21:20 2004 From: michael.j.eve at gmail.com (Mike Eve) Date: Mon Dec 6 01:21:39 2004 Subject: [Tutor] Socket events and wxPython events? Message-ID: <000601c4db29$8c133e70$657ba8c0@Hippo> To learn Python, I'm adapting a board game to a network based games with server and clients. It took a while, but with a little help, I've learned about wxPython, wxglade, SPE so that I now have a prototype GUI up and running. Now to get the network part up and running... The network will be sending commands, responses, and random queries. I'm thinking about 3 approaches, but rather than beat my head against the wall, I was hoping to find out if any of these are workable: 1) use sockets lib. Do socket send/recv generate any kind of event with an event id that can used with the wxPython window events? That is, I want to just sit and receive events such as OnPaint, OnButton, in the same loop as I receive "OnReceiveSocket" (or whatever it might be called). 2) create a separate thread which does a select then sends a wxPython compatible event which can be intermixed with OnPaint, etc (similar to option 1) 3) use SocketServer. I noticed the SocketServer class refers to "request handler class" and "handle" functions. Do these generate any events which are wxPython compatible You probably noticed I'm a little confused about what a wxPython compatible event is. I'm not sure if these events and their event handling are part of Python or something added by and unique to wxPython. Thanks, Mike -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041205/8625f0ad/attachment.htm From cyresse at gmail.com Mon Dec 6 01:25:38 2004 From: cyresse at gmail.com (Liam Clarke) Date: Mon Dec 6 01:25:41 2004 Subject: [Tutor] Could I have used time or datetime modules here? In-Reply-To: <6.1.2.0.2.20041205112204.04e9d100@rcblue.com> References: <6.1.2.0.2.20041205075719.02377370@rcblue.com> <41B34B55.1010208@po-box.mcgill.ca> <6.1.2.0.2.20041205112204.04e9d100@rcblue.com> Message-ID: Hi Dick, import datetime OK = 0 while not OK: wakeup=raw_input( "enter time in 24 hour format for alarm - in this format HH:MM:SS") wakeup=wakeup.split(":") if len(wakeup) == 3: if -1 < int(wakeup[0]) < 24 and -1 < int(wakeup[1]) < 60 and -1 < int(wakeup[2]) < 60: OK = 1 # Above loops until valid input is received. secIncre = datetime.timedelta(seconds=1) workingObj = datetime.datetime.now() idealTimeObj=datetime.time(int(wakeup[0]),int(wakeup[1]),int(wakeup[2])) #Inits datetime.time(hours, minutes, seconds) seconds = 0 while workingObj.time() ! = idealTimeObj: workingObj += secIncre #Increase workingObj by one second seconds += 1 print seconds That should, in theory, give the number of seconds between the current time, and the desired time. Of course, if you used a datetime.datetime object, and asked your user to set the desired date, you could use - nowDateTime=datetime.datetime.now() desiredDateTime = datetime.datetime(year, month, day, hours, minutes seconds) difference = desiredDateTime - nowDateTime print difference x days, y hours, q minutes, r seconds. totalSec = (x*86400)+(y*3600)+(q*60)+r Of course, getting x, y, q, and r is a bit finicky, Or, for your purposes - curDateTime = datetime.datetime.now() wakeup=raw_input( "enter time in 24 hour format for alarm - in this format HH:MM:SS") wakeup=wakeup.split(":") #Going to assume that valid input was entered timeinfo=[] for element in wakeup: t = int(element) timeinfo.append(t) desiredDateTime = curDateTime.replace(t[0], t[1], t[2]) #hours, minutes, seconds if curDateTime > = desiredDateTime: #As both times will be on same day, if desired time is previous to current date, then make it #time for next day. dayIncre=datetime.timedelta(days=1) desiredDateTime += dayIncre difference = desiredDateTime - curDateTime #Now do some sort of split of difference, as difference will be in x days, y hours, m minutes, #s seconds format. As I said, I have no interpreter so I can't check this out. So yeah, that's a couple of different ways I'd do it using datetime, but someone else will no doubt do it better and simpler. HTH Liam Clarke From cyresse at gmail.com Mon Dec 6 01:27:30 2004 From: cyresse at gmail.com (Liam Clarke) Date: Mon Dec 6 01:27:34 2004 Subject: [Tutor] gzip (fwd) In-Reply-To: <009901c4db16$a694a760$4d5328cf@JSLAPTOP> References: <82c0f73b041203011670566c48@mail.gmail.com> <009901c4db16$a694a760$4d5328cf@JSLAPTOP> Message-ID: Heh, I was just pointing out his missing separator was causing his function to fail. : ) On Sun, 5 Dec 2004 17:06:17 -0500, Jacob S. wrote: > Hello! > > > > > >target_dir = 'D:\\backup' > > >target = target_dir +"Zipnametoreplacestrftimeformatstring"+ '.zip' > > > > Just noticed this - > > > > target_dir("D:\\backup") + "Zipnametoreplacestrftimeformatstring"+ '.zip' > > > > = D:\\backupZipnametoreplacestrftimeformatstring.zip > > > > No wonder it doesn't work. > > > > Try > > > > target=target_dir+'\\'+time.strftime('%Y%m%d%H%M%S') + '.zip' > > Instead of doing this, use os.path.join to make it more platform > independent. > > target = os.path.join(target_dir,time.strftime('%Y%m%d%H%M%S')+'.zip') > > > > > > > Regards, > > > > Liam Clarke > > > > PS Yes, do use reply to all > > > > > > > > > > On Fri, 3 Dec 2004 15:16:27 +0600, Ramkumar Parimal Alagan > > wrote: > > > I have only 2 word documents in both the directories, i tried removing > > > '-qr' too, but no change, no zip files formed. i'm using windows XP. > > > > > > On Thu, 2 Dec 2004 23:54:11 -0800 (PST), Danny Yoo > > > > > > > > > wrote: > > > > Hi Ramkumar, > > > > > > > > I'm forwarding your message to Python-tutor; in your replies, please > make > > > > sure that you are using the "reply-to-all" feature in your email > client. > > > > This will allow your response to reach the others on the tutor list. > > > > Don't rely on me alone: give the community the chance to help you. > > > > > > > > I don't have enough information to pinpoint what the problem is yet. > I'll > > > > have to ask more questions, and others on the Tutor list will probably > > > > also ask a few questions. Please try to answer them, because that > will > > > > help us give a better idea of what the problem is. > > > > > > > > It looks like you are trying to zip up whole directories. Does the > > > > program work if you zip up single files? > > > > > > > > It also appears that you're using the '-q' and '-r' options of the > 'zip' > > > > command line utility. '-q' stands for 'quiet' mode, and although > that's > > > > nice when the command is working properly, it's not helpful when > you're > > > > debugging a situation. Try turning quiet mode off, so that you have a > > > > better chance of getting good error output from the zip command. Even > > > > better, try enabling verbose mode, so you can see better what 'zip' is > > > > attempting to do. > > > > > > > > Do you see anything else when you execute the program? Does anything > else > > > > come out of standard error? > > > > > > > > Good luck to you. > > > > > > > > ---------- Forwarded message ---------- > > > > Date: Fri, 3 Dec 2004 10:24:15 +0600 > > > > From: Ramkumar Parimal Alagan > > > > To: Danny Yoo > > > > Subject: Re: [Tutor] gzip > > > > > > > > This is what i intend to do: > > > > > > > > 1. The files and directories to be backed up are given in a list. > > > > 2. The backup must be stored in a main backup directory. > > > > 3. The files are backed up into a zip file. > > > > 4. The name of the zip archive is the current date and time. > > > > > > > > the coding: > > > > > > > > ______________ > > > > > > > > import os > > > > import time > > > > > > > > source = ['D:\\down', 'D:\\Pics'] > > > > > > > > target_dir = 'D:\\backup' > > > > > > > > target = target_dir + time.strftime('%Y%m%d%H%M%S') + '.zip' > > > > > > > > zip_command = "zip -qr '%s' %s" % (target, ' '.join(source)) > > > > > > > > if os.system(zip_command) == 0: > > > > print 'Successful backup to', target > > > > else: > > > > print 'Backup FAILED' > > > > > > > > _____________________________ > > > > > > > > result : Backup FAILED > > > > > > > > whats wrong ? > > > > > > > > > > > > > > > > > -- > > > > > > << The end depends upon the beginning. >> > > > > > > > > > _______________________________________________ > > > Tutor maillist - Tutor@python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > -- > > 'There is only one basic human right, and that is to do as you damn well > please. > > And with it comes the only basic human duty, to take the consequences. > > _______________________________________________ > > > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From cyresse at gmail.com Mon Dec 6 01:40:29 2004 From: cyresse at gmail.com (Liam Clarke) Date: Mon Dec 6 01:40:33 2004 Subject: [Tutor] CGI Video collection application File I/O troubles In-Reply-To: <00de01c4db1c$4ab85c60$4d5328cf@JSLAPTOP> References: <1102284490.41b386cac3033@mail.online.ie> <00ba01c4db18$a53d1bc0$4d5328cf@JSLAPTOP> <1102285829.41b38c05994f0@mail.online.ie> <00de01c4db1c$4ab85c60$4d5328cf@JSLAPTOP> Message-ID: Try an intermediate step videodb={'title':title,'year':year,'director':director} x=videodb['title'] #Sometimes this helps print type(x) #Check x is a string print x #see if it's got stuff #save to database try: f=open(filename,'w') except TypeError: print "the error is occurring on opening the file, which would mean that it's variable filename which is causing the problem." try: f.write(x) except TypeError: print "The error is occurring on writing to the file, which means the written values need to be checked." f.close() Good luck, Liam Clarke On Sun, 5 Dec 2004 17:46:39 -0500, Jacob S. wrote: > Your error message says that you are getting an empty string from your cgi > variable. I IMHO would suggest printing videodb['title'] before writing it > to a file to see what the variable contains. Or you might print out videodb > to see what the dictionary looks like. My off the wall guess is that 1) Your > cgi variables are not returning the value from the actual object that you > want 2) The script is running and assigning values to title, etc. before the > afore mentioned object is given a value. IOW, maybe you haven't assigned > values to the form before you try to read them. > Another suggestion. Comment out the file writing part and print everything > to the screen to verify that the output is what you want. "When in doubt, > print it out." - Jacob Schmidt > > HTH, > Jacob > > > > > Quoting "Jacob S." : > > > > > Hi! > > > > > > Can I ask a few questions? (Other than this one...) > > > What output did you expect? A string, tuple, or what? > > > > A string output. When I create a dictionary variable from > > the python shell like this: > > videodb={'title':'Crash','year':'1996','director':'David Cronenberg'} > > > > and type in videodb['title'] afterwards python spits out the > > value 'Crash'. That's fine I get a string as expected. > > But when I try to write the value of videodb['title'] to > > a file nothing gets written. > > I hope I clarified the issue somewhat. > > > > > I'm not strong with > > > cgi stuff. > > > Also, you don't need the string module 1) because you don't use it 2) > > > because you can use string methods. > > > > > > Jacob Schmidt > > > > ok. I'll remove it. thanx. > > > > [snip] > > > > -- > > The lady on the call box in Monkey Island 2 > > Guybrush: I'm lost in the Inky Island Jungle in Monkey 2 > > Lady: Just walk off the edge of the screen > > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From dyoo at hkn.eecs.berkeley.edu Mon Dec 6 01:45:41 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Dec 6 01:46:01 2004 Subject: [Tutor] eval and exec In-Reply-To: <021901c4db23$f4ee4210$c6ca8751@xp> Message-ID: On Sun, 5 Dec 2004, Alan Gauld wrote: > > And I can't see the security problem, unless there's a security > > problem already, like if I allowed incoming email to dictate the > > parameters that I send through the socket. The email provides data > > for argv[1:] but argv[0] is hard-coded. > > > > And I don't see how web traffic can get there at all. > > You can generate a CGI call b by typing the GET string straight into the > address bar of the browser. If a smart user realises that some of the > parameters are being interpreted they can (and often will) try to fake > what the page genersates, this could involve putting python commands, > such as 'import os;os.system("rm -f /")' into the escape string... > > Equally if you embed Python in a program and allow users to type strings > whoich are then exec() or eval()'d they could type a similar os.system() > command. Or they might use print and dir to find variable names and > manipulate those. Hi Marilyn, It pays to see a concrete example of an exploit that has occurred because of exec/eval misuse. For example, here's an old one from July 2002: http://www.securityfocus.com/bid/5255/discussion/ Note that this one was in the Standard Library! We'd expect that the folks who implement the Standard Library should know what they are doing. And if the Python implementors can have trouble using eval() safely, then how much more should we be wary! If you or your students are interested in security stuff, you may find David Wheeler's guide on "Secure Programming for Linux and Unix HOWTO" a good start: http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/index.html It contains a small section specifically for Python: http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/python.html I don't think that we should go completely crazy over security issues: this issues are often so subtle that even experts get caught. But even so, I think we still have a responsibility to make sure the most egregrious security problems never come to fruition. So that's why most of us here will say eval() and exec() are evil. *grin* I hope this helps! From bvande at po-box.mcgill.ca Mon Dec 6 01:53:01 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Mon Dec 6 01:53:10 2004 Subject: [Tutor] Could I have used time or datetime modules here? In-Reply-To: <6.1.2.0.2.20041205112204.04e9d100@rcblue.com> References: <6.1.2.0.2.20041205075719.02377370@rcblue.com> <6.1.2.0.2.20041205112204.04e9d100@rcblue.com> Message-ID: <41B3AD6D.8060603@po-box.mcgill.ca> Dick Moores said unto the world upon 2004-12-05 15:03: > Thanks, Brian. I looked at your code a long time, and also read the > 11/26 thread you started. I can see how I could use datetime() and your > t2 - t1 to get the seconds for time.sleep(), but the resulting code I > have in mind is more convoluted than the heart of my timer3.py, which I > quote below. (I don't need the alarm time to be more than 24 hours from > current time--therefore I want to ignore the year, month, and day.) > > ======================================= > import time > > alarm = raw_input("Enter alarm time as hhmm: ") > > now = time.strftime("%X") # produces current time in format hh:mm:ss > nowSecond = int(now[6:]) > nowMinute = int(now[3:5]) > nowHour = int(now[0:2]) > > alarmMinute = int(alarm[2:4]) > alarmHour = int(alarm[0:2]) > > hoursDiff = alarmHour - nowHour > minutesDiff = alarmMinute - nowMinute > > if hoursDiff < 0 or (hoursDiff == 0 and minutesDiff <= 0): > hoursDiff = hoursDiff + 24 # add a day > > sleepSeconds = hoursDiff*3600 + minutesDiff*60 - nowSecond > > time.sleep(sleepSeconds) > ==================================== > If I'm wrong, could someone please set me right? > > Dick > Hi Dick and all, sorry I was too lazy to follow your link before, Dick. Thanks for posting the relevant portions. I took another run, but my code is a lot longer as I put in some error checking on the input request -- hope you don't mind ;-) (I might have gone overboard -- I did it to learn how as much as anything else.) I suspect that my way is easier than yours. (I don't know about Liam's. His came in as I was writing mine, and I've not read his closely yet.) In mine, the key bit is that if you have two datetime objects, d1 and d2, d1 - d2 gives a timedelta object expressing the time difference between them in the form (days, seconds, microseconds). So, the datetime module seems to do the work you want -- just make the current time a datetime object, use the user input to get a datetime object in the future and then find their timedelta and ask it for its seconds attribute. This disregards any difference in days and gives only the hour + minute + seconds difference expressed in seconds. That logic is near the bottom, though, as first you've got to read through my error checking code ;-) I tested it pretty well, but as always, undetected errors entitle you to a full refund of purchase price. (Minus a reasonable handling fee, of course.) I hope this is of some use to you. Best to all, Brian vdB CODE: import datetime import time def get_alarm_time(): '''Asks user for a time in the form 'hh:mm' and return tuple of ints. Includes error checking to make sure user input really is of form 'hh:mm' where the values of 'hh' and 'mm' are appropriate. ''' while True: alarm_time = raw_input("Enter alarm time as hh:mm") er_msg = ''' An alarm time must be entered in the format 'hh:mm' where 'hh' is a number between 0 and 23 inclusive and mm is a number between 0 and 59 inclusive. You entered: '%s', which is not of that form. Please try again. ''' %alarm_time alarm_time_list = alarm_time.split(':') # yields a list with first element the characters from before # the ':' and second from after. try: alarm_hour, alarm_minute = (int(alarm_time_list[0]), int(alarm_time_list[1]) ) except ValueError: # raised if the user entered something like "silly:input" print er_msg continue if len(str(alarm_minute)) == 1: alarm_minute_string = '0' + str(alarm_minute) # if the user entered, say, 12:05, str(alarm_minute) would # give '5' rather than the needed '05'. else: alarm_minute_string = str(alarm_minute) if ( (alarm_hour > 24 or alarm_hour < 0) or (alarm_minute > 59 or alarm_minute < 0) or str(alarm_hour) + ':' + alarm_minute_string != alarm_time): # The first two clauses check that minutes and hours are # within the expected ranges. The final clause checks that # the inputs were string representations of integers. # (Without it, the user could have entered something like # 16.845:57.0000343.) print er_msg else: return alarm_hour, alarm_minute alarm_hour, alarm_minute = get_alarm_time() now = datetime.datetime.now() alarm_datetime = datetime.datetime(now.year + 4, now.month, now.day, alarm_hour, alarm_minute) # now.year + 4 to ensure that the alarm_datetime represents a time in # the future. I used a multiple of 4 to avoid leap year issues. + 44 # would work equally well. (This ignores the additional correction every # 100 or 400 years -- I forget which. But what do you want for free ;-) alarm_in_seconds = (alarm_datetime - now).seconds # a_datetime_object - another_datetime_object gives a_timedelta_object. # a_timedelta_object.seconds returns only the hour and minute difference # (discarding days) expressed in seconds. It has to be the future time # minus the current time for the .seconds to give the wanted result. print "I should wake up in %d seconds" %alarm_in_seconds time.sleep(alarm_in_seconds) print "I'm awake!" From michael.j.eve at gmail.com Mon Dec 6 01:59:46 2004 From: michael.j.eve at gmail.com (Mike in Seattle) Date: Mon Dec 6 01:59:50 2004 Subject: [Tutor] Simple RPN calculator In-Reply-To: <20041204115419.6172.qmail@web54402.mail.yahoo.com> References: <20041204115419.6172.qmail@web54402.mail.yahoo.com> Message-ID: Check out "How to think like a computer scientist", chap 20. He uses trees to evaluate expressions. http://www.ibiblio.org/obp/thinkCSpy/index.htm From cyresse at gmail.com Mon Dec 6 02:08:14 2004 From: cyresse at gmail.com (Liam Clarke) Date: Mon Dec 6 02:08:18 2004 Subject: [Tutor] Address book sort of In-Reply-To: References: <003b01c4db12$1d709bf0$4d5328cf@JSLAPTOP> Message-ID: Oops I've got my own wee dictionary reader, writers. Very simple - So, you have a user Dave, who has a dictionary of {'address':'21 jump St', 'Number: 'One, the loneliest.'} So, you create a dictionary of dictionaries -myDict = {'Dave' : {'address':'21 jump St', 'Number: 'One, the loneliest.'} And then you have - def writeDict(file, diction): inp=file(file, 'w') for (key, item) in diction.items(): inp.write(key+'\n') inp.write(item+'\n') inp.close() return 1 Courtesy of Danny Yoo, the very helpful pair generating function below (it's indispensable this one, I use it so often) def groupAdjacentElements(someSequence, n = 2): """A little helper utility to group up adjacent elements.""" nextGroup = [] for element in someSequence: nextGroup.append(element) if len(nextGroup) == n: yield tuple(nextGroup) nextGroup = [] Goes with - def loadDict(filename): store2 = file(filename,'r') for (name, entry) in groupAdjacentElements(store2): name = name.strip() entry = entry.strip() book[name] = entry store2.close() return book So - to save myDict to saveddic.dct - writeDict('saveddic.dct', myDict) and to open it - myDictCopy=loadDict('saveddic.dct') And it saves in the format - dave {'address':'21 Jump St', 'number':'One, the loneliest'} key value key value Nice and plaintext. HTH On Sun, 5 Dec 2004 16:31:59 -0500, Jacob S. wrote: > I did something like this about three or four months ago... > This is what I did. Notice the use of the built-in str() and eval() > functions to write and receive data to and from Telephone.cfg... > > from __future__ import division > tel = {} > try: > file = open('Telephone.cfg', 'r') > except: > file = open('Telephone.cfg','w') > file.close() > file = open('Telephone.cfg','r') > try: > tel = eval(file.read()) > a = 0 > except: > a = 1 > print "No entries on file." > pass > print """\ > Commands are: > add > get > save > delete > quit > all is a wildcard > """ > > while 1: > ask = raw_input('Tell me what you wish to do. ') > if ask == "quit": > break > ask = ask.split(" ") > command = ask[0] > entity = ask[1:] > entity = " ".join(entity) > if entity == '': > entity = raw_input("Who do you want to %s? " % command) > if command == 'add': > person = entity > if tel.has_key(person): > print "That person is already in there. If you wish to edit the > file, please delete the record first." > else: > tel[person] = raw_input("What is their phone number? ") > if command == 'get': > if a == 1: > print "Sorry, there are no entries available." > else: > person = entity > if person == 'all': > key = tel.keys() > key.sort() > print > for x in key: > print "%s\n%s\n" % (x,tel[x]) > elif tel.has_key(person): > print "\n%s\n%s\n" % (person,tel[person]) > else: > print "%s is not in your records." % person > if command == 'save': > file=open('Telephone.cfg', 'w') > file.write(str(tel)) > file.close() > print 'Saved in Telephone.cfg' > if command == 'delete': > if a == 1: > print "Sorry, there are no entries available." > else: > person = entity > if person == 'all': > tel={} > newfile=open('Telephone.cfg', 'w') > newfile.close() > else: > if tel.has_key(person): > del tel[person] > else: > print "%s is not in your records." % person > file.close() > file = open('Telephone.cfg', 'w') > file.write(str(tel)) > file.close() > > As always, feel free to modify, use, and otherwise tear apart my code and > give me suggests on how to improve it. > Jacob Schmidt > > > > > Dear Tutor, > > > > I like to know what is the proper procedure (is algorithmn the right > > term?) in creating data in a program, write it to file, close the app > > then retrieve the data when run again. Basically, I'm trying to simulate > > a simple address book (well not really for the datas are just names for > > now) and so far have created the basic menu interface. It is console > > base so forget gui. I ask user input and store it in a list. There are > > menus to change, delete the data, and to save the data list in file. I > > use cPickle for this and have verified the file is created by checking > > in my $PWD. I want to retrieve that data when program is run again. What > > to add in my code? I thought not to post the code but explain it as > > above. > > > > What i want: when program is run again, the saved data is loaded when user > > selects option 1 below. Of course the first time it is run, the list is > > empty. > > > > def print_options(): > > print ''' > > Options: > > [1] - Print content of list > > [2] - Add name to list > > [3] - Delete name from list > > [4] - Change name in list > > [5] - Save list to file > > [P] - Print this menu > > [Q] - Quit > > ''' > > > > > > > > -- > > Regards, > > Eri Mendz > > Using PC-Pine 4.61 > > > > > > -- > > Using PC-Pine 4.61 > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From rdm at rcblue.com Mon Dec 6 04:02:39 2004 From: rdm at rcblue.com (Dick Moores) Date: Mon Dec 6 05:07:28 2004 Subject: [Tutor] Could I have used time or datetime modules here? In-Reply-To: <41B3AD6D.8060603@po-box.mcgill.ca> References: <6.1.2.0.2.20041205075719.02377370@rcblue.com> <6.1.2.0.2.20041205112204.04e9d100@rcblue.com> <41B3AD6D.8060603@po-box.mcgill.ca> Message-ID: <6.1.2.0.2.20041205185122.03434eb0@rcblue.com> Brian van den Broek wrote at 16:53 12/5/2004: >Dick Moores said unto the world upon 2004-12-05 15:03: >>Thanks, Brian. I looked at your code a long time, and also read the >>11/26 thread you started. I can see how I could use datetime() and your >>t2 - t1 to get the seconds for time.sleep(), but the resulting code I >>have in mind is more convoluted than the heart of my timer3.py, which I >>quote below. (I don't need the alarm time to be more than 24 hours >>from current time--therefore I want to ignore the year, month, and day.) >>======================================= >>import time >>alarm = raw_input("Enter alarm time as hhmm: ") >>now = time.strftime("%X") # produces current time in format hh:mm:ss >>nowSecond = int(now[6:]) >>nowMinute = int(now[3:5]) >>nowHour = int(now[0:2]) >>alarmMinute = int(alarm[2:4]) >>alarmHour = int(alarm[0:2]) >>hoursDiff = alarmHour - nowHour >>minutesDiff = alarmMinute - nowMinute >>if hoursDiff < 0 or (hoursDiff == 0 and minutesDiff <= 0): >> hoursDiff = hoursDiff + 24 # add a day >>sleepSeconds = hoursDiff*3600 + minutesDiff*60 - nowSecond >>time.sleep(sleepSeconds) >>==================================== >>If I'm wrong, could someone please set me right? >>Dick > >Hi Dick and all, > >sorry I was too lazy to follow your link before, Dick. Thanks for >posting the relevant portions. > >I took another run, but my code is a lot longer as I put in some error >checking on the input request -- hope you don't mind ;-) (I might have >gone overboard -- I did it to learn how as much as anything else.) > >I suspect that my way is easier than yours. (I don't know about Liam's. >His came in as I was writing mine, and I've not read his closely yet.) > >In mine, the key bit is that if you have two datetime objects, d1 and >d2, d1 - d2 gives a timedelta object expressing the time difference >between them in the form (days, seconds, microseconds). So, the datetime >module seems to do the work you want -- just make the current time a >datetime object, use the user input to get a datetime object in the >future and then find their timedelta and ask it for its seconds >attribute. This disregards any difference in days and gives only the >hour + minute + seconds difference expressed in seconds. > >That logic is near the bottom, though, as first you've got to read >through my error checking code ;-) > >I tested it pretty well, but as always, undetected errors entitle you to >a full refund of purchase price. (Minus a reasonable handling fee, of >course.) > >I hope this is of some use to you. > >Best to all, > >Brian vdB > >CODE: > >import datetime >import time > >def get_alarm_time(): > '''Asks user for a time in the form 'hh:mm' and return tuple of ints. > > Includes error checking to make sure user input really is of form > 'hh:mm' where the values of 'hh' and 'mm' are appropriate. > ''' > while True: > alarm_time = raw_input("Enter alarm time as hh:mm") > er_msg = ''' > An alarm time must be entered in the format 'hh:mm' where 'hh' > is a number between 0 and 23 inclusive and mm is a number > between 0 and 59 inclusive. > You entered: '%s', which is not of that form. > Please try again. > ''' %alarm_time > alarm_time_list = alarm_time.split(':') > # yields a list with first element the characters from before > # the ':' and second from after. > > try: > alarm_hour, alarm_minute = (int(alarm_time_list[0]), > int(alarm_time_list[1]) ) > except ValueError: > # raised if the user entered something like "silly:input" > print er_msg > continue > if len(str(alarm_minute)) == 1: > alarm_minute_string = '0' + str(alarm_minute) > # if the user entered, say, 12:05, str(alarm_minute) would > # give '5' rather than the needed '05'. > else: > alarm_minute_string = str(alarm_minute) > if ( (alarm_hour > 24 or alarm_hour < 0) > or (alarm_minute > 59 or alarm_minute < 0) > or str(alarm_hour) + ':' + alarm_minute_string != alarm_time): > # The first two clauses check that minutes and hours are > # within the expected ranges. The final clause checks that > # the inputs were string representations of integers. > # (Without it, the user could have entered something like > # 16.845:57.0000343.) > print er_msg > else: > return alarm_hour, alarm_minute > >alarm_hour, alarm_minute = get_alarm_time() >now = datetime.datetime.now() >alarm_datetime = datetime.datetime(now.year + 4, now.month, now.day, > alarm_hour, alarm_minute) ># now.year + 4 to ensure that the alarm_datetime represents a time in ># the future. I used a multiple of 4 to avoid leap year issues. + 44 ># would work equally well. (This ignores the additional correction every ># 100 or 400 years -- I forget which. But what do you want for free ;-) > >alarm_in_seconds = (alarm_datetime - now).seconds ># a_datetime_object - another_datetime_object gives a_timedelta_object. ># a_timedelta_object.seconds returns only the hour and minute difference ># (discarding days) expressed in seconds. It has to be the future time ># minus the current time for the .seconds to give the wanted result. > >print "I should wake up in %d seconds" %alarm_in_seconds >time.sleep(alarm_in_seconds) >print "I'm awake!" Brian, So yours can be boiled down to ==========Begin code================== alarm_time = raw_input("Enter alarm time as hh:mm") alarm_time_list = alarm_time.split(':') alarm_hour, alarm_minute = (int(alarm_time_list[0]), int(alarm_time_list[1])) now = datetime.datetime.now() alarm_datetime = datetime.datetime(now.year + 4, now.month, now.day, alarm_hour, alarm_minute) print alarm_datetime alarm_in_seconds = (alarm_datetime - now).seconds print "I should wake up in %d seconds" % alarm_in_seconds time.sleep(alarm_in_seconds) print "I'm awake!" ============End code================== Yes, I think yours is shorter, but not simpler. Mine doesn't need to consider the year or month, or leap years. On the other hand, mine doesn't take care of crossing the daylight time change borderline. But thanks very much. It gives me some understanding of the datetime module. As does Liam's code. BTW I found one omission in your error checking. The case where the user enters the time without a colon, e.g., 1234 instead of 12:34. Dick From jerimed at myrealbox.com Mon Dec 6 05:55:11 2004 From: jerimed at myrealbox.com (Eri Mendz) Date: Mon Dec 6 05:55:11 2004 Subject: [Tutor] Address book sort of In-Reply-To: <003b01c4db12$1d709bf0$4d5328cf@JSLAPTOP> References: <003b01c4db12$1d709bf0$4d5328cf@JSLAPTOP> Message-ID: On Sun, 5 Dec 2004, Jacob S. wrote: > I did something like this about three or four months ago... > This is what I did. Notice the use of the built-in str() and eval() > functions to write and receive data to and from Telephone.cfg... Thanks a lot Jacob, and to all who replied. I'll go through the code definitely. I started building that address book last night and its pretty crude. I hit a snag though: i was able to save the name/email address pairs and write to disk. But i cant get it to load on startup. My location is several dirs down my home directory. Of course the pickled file is in same directory as the code. Its something like: if select == '1' or select == 'v' or select == 'V': if file_in_disk in os.listdir('/home/jerimed'): # change??? fhandle = open(file_in_disk, 'r') # read mode cPickle.load(fhandle) # restore saved data fhandle.close() show_contacts() elif len(data_holder) > 0: show_contacts() else: is_empty() /home/jerimed should be changed and should be dynamic to match wherever the python script is. Can you guyz advise? And is that first if-statement right? I like to know if im doing the right thing. How do i pretty print output of dictionary container? Sort of tabular form or something, e.g., 1. name1 email address1 2. name2 email address2 Just for my learning experience :-). Thanks! -- Regards, Eri Mendz > > from __future__ import division > tel = {} > try: > file = open('Telephone.cfg', 'r') > except: > file = open('Telephone.cfg','w') > file.close() > file = open('Telephone.cfg','r') > try: > tel = eval(file.read()) > a = 0 > except: > a = 1 > print "No entries on file." > pass > print """\ > Commands are: > add > get > save > delete > quit > all is a wildcard > """ > > while 1: > ask = raw_input('Tell me what you wish to do. ') > if ask == "quit": > break > ask = ask.split(" ") > command = ask[0] > entity = ask[1:] > entity = " ".join(entity) > if entity == '': > entity = raw_input("Who do you want to %s? " % command) > if command == 'add': > person = entity > if tel.has_key(person): > print "That person is already in there. If you wish to edit the > file, please delete the record first." > else: > tel[person] = raw_input("What is their phone number? ") > if command == 'get': > if a == 1: > print "Sorry, there are no entries available." > else: > person = entity > if person == 'all': > key = tel.keys() > key.sort() > print > for x in key: > print "%s\n%s\n" % (x,tel[x]) > elif tel.has_key(person): > print "\n%s\n%s\n" % (person,tel[person]) > else: > print "%s is not in your records." % person > if command == 'save': > file=open('Telephone.cfg', 'w') > file.write(str(tel)) > file.close() > print 'Saved in Telephone.cfg' > if command == 'delete': > if a == 1: > print "Sorry, there are no entries available." > else: > person = entity > if person == 'all': > tel={} > newfile=open('Telephone.cfg', 'w') > newfile.close() > else: > if tel.has_key(person): > del tel[person] > else: > print "%s is not in your records." % person > file.close() > file = open('Telephone.cfg', 'w') > file.write(str(tel)) > file.close() > > > As always, feel free to modify, use, and otherwise tear apart my code and > give me suggests on how to improve it. > Jacob Schmidt > >> Dear Tutor, >> >> I like to know what is the proper procedure (is algorithmn the right >> term?) in creating data in a program, write it to file, close the app >> then retrieve the data when run again. Basically, I'm trying to simulate >> a simple address book (well not really for the datas are just names for >> now) and so far have created the basic menu interface. It is console >> base so forget gui. I ask user input and store it in a list. There are >> menus to change, delete the data, and to save the data list in file. I >> use cPickle for this and have verified the file is created by checking >> in my $PWD. I want to retrieve that data when program is run again. What >> to add in my code? I thought not to post the code but explain it as >> above. >> >> What i want: when program is run again, the saved data is loaded when user >> selects option 1 below. Of course the first time it is run, the list is >> empty. >> >> def print_options(): >> print ''' >> Options: >> [1] - Print content of list >> [2] - Add name to list >> [3] - Delete name from list >> [4] - Change name in list >> [5] - Save list to file >> [P] - Print this menu >> [Q] - Quit >> ''' >> >> >> >> -- >> Regards, >> Eri Mendz >> Using PC-Pine 4.61 >> >> >> -- >> Using PC-Pine 4.61 >> >> _______________________________________________ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From marilyn at deliberate.com Mon Dec 6 06:13:40 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Mon Dec 6 06:13:43 2004 Subject: [Tutor] eval and exec In-Reply-To: Message-ID: On Sun, 5 Dec 2004, Danny Yoo wrote: > > It pays to see a concrete example of an exploit that has occurred because > of exec/eval misuse. For example, here's an old one from July 2002: > > http://www.securityfocus.com/bid/5255/discussion/ > > Note that this one was in the Standard Library! We'd expect that the > folks who implement the Standard Library should know what they are doing. > And if the Python implementors can have trouble using eval() safely, then > how much more should we be wary! > Thank you. Goodness, pickle would execute this if it unpickled it, as I understand it: "S''*__import__('os').system('echo 0wn3d')\np0\n." Hmmmmm. Silly pickle. > > If you or your students are interested in security stuff, you may find > David Wheeler's guide on "Secure Programming for Linux and Unix HOWTO" a > good start: > > http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/index.html > Very interesting, thank you. And thank you everyone for your illuminations. In our case, where the socket isn't available from outside, and the call strings are hardcoded, in order to breech an eval() call in my code, they'd already have the machine in their lap and could do anything else. Our only ports that are open to the world are for exim, and apache. Otherwise we let ssh and rysnc through if they are coming from the right IP. So we're pretty tight. However, I think it's good engineering policy to keep things as tightly controlled as possible. So I think I'll take the good advice given here and use apply() and do all my importing up front. > > It contains a small section specifically for Python: > > http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/python.html > BTW, the author of the Python section doesn't seem to like the flexibility of Python's function calls. All these lovely powerful things are security vulnerabilities. Sigh. Marilyn > > I don't think that we should go completely crazy over security issues: > this issues are often so subtle that even experts get caught. But even > so, I think we still have a responsibility to make sure the most > egregrious security problems never come to fruition. So that's why most > of us here will say eval() and exec() are evil. *grin* > > > I hope this helps! > > -- From cyresse at gmail.com Mon Dec 6 06:28:53 2004 From: cyresse at gmail.com (Liam Clarke) Date: Mon Dec 6 06:28:56 2004 Subject: [Tutor] Could I have used time or datetime modules here? In-Reply-To: References: <6.1.2.0.2.20041205075719.02377370@rcblue.com> <6.1.2.0.2.20041205112204.04e9d100@rcblue.com> <41B3AD6D.8060603@po-box.mcgill.ca> <6.1.2.0.2.20041205185122.03434eb0@rcblue.com> Message-ID: Best thing in Python, I reckon, is an interpreter to check out your code. I find it hard to answer queries in this list when I don't have Pythonwin open to check what I'm suggesting works! On Mon, 6 Dec 2004 18:27:49 +1300, Liam Clarke wrote: > Ah, nope. : ) > > >>> x="1234" > >>> y=x.split(":") > >>> print y > ['1234'] > > And I'm checking for y having 3 items exactly. > > > > > On Sun, 05 Dec 2004 19:02:39 -0800, Dick Moores wrote: > > Brian van den Broek wrote at 16:53 12/5/2004: > > > > > > >Dick Moores said unto the world upon 2004-12-05 15:03: > > >>Thanks, Brian. I looked at your code a long time, and also read the > > >>11/26 thread you started. I can see how I could use datetime() and your > > >>t2 - t1 to get the seconds for time.sleep(), but the resulting code I > > >>have in mind is more convoluted than the heart of my timer3.py, which I > > >>quote below. (I don't need the alarm time to be more than 24 hours > > >>from current time--therefore I want to ignore the year, month, and day.) > > >>======================================= > > >>import time > > >>alarm = raw_input("Enter alarm time as hhmm: ") > > >>now = time.strftime("%X") # produces current time in format hh:mm:ss > > >>nowSecond = int(now[6:]) > > >>nowMinute = int(now[3:5]) > > >>nowHour = int(now[0:2]) > > >>alarmMinute = int(alarm[2:4]) > > >>alarmHour = int(alarm[0:2]) > > >>hoursDiff = alarmHour - nowHour > > >>minutesDiff = alarmMinute - nowMinute > > >>if hoursDiff < 0 or (hoursDiff == 0 and minutesDiff <= 0): > > >> hoursDiff = hoursDiff + 24 # add a day > > >>sleepSeconds = hoursDiff*3600 + minutesDiff*60 - nowSecond > > >>time.sleep(sleepSeconds) > > >>==================================== > > >>If I'm wrong, could someone please set me right? > > >>Dick > > > > > >Hi Dick and all, > > > > > >sorry I was too lazy to follow your link before, Dick. Thanks for > > >posting the relevant portions. > > > > > >I took another run, but my code is a lot longer as I put in some error > > >checking on the input request -- hope you don't mind ;-) (I might have > > >gone overboard -- I did it to learn how as much as anything else.) > > > > > >I suspect that my way is easier than yours. (I don't know about Liam's. > > >His came in as I was writing mine, and I've not read his closely yet.) > > > > > >In mine, the key bit is that if you have two datetime objects, d1 and > > >d2, d1 - d2 gives a timedelta object expressing the time difference > > >between them in the form (days, seconds, microseconds). So, the datetime > > >module seems to do the work you want -- just make the current time a > > >datetime object, use the user input to get a datetime object in the > > >future and then find their timedelta and ask it for its seconds > > >attribute. This disregards any difference in days and gives only the > > >hour + minute + seconds difference expressed in seconds. > > > > > >That logic is near the bottom, though, as first you've got to read > > >through my error checking code ;-) > > > > > >I tested it pretty well, but as always, undetected errors entitle you to > > >a full refund of purchase price. (Minus a reasonable handling fee, of > > >course.) > > > > > >I hope this is of some use to you. > > > > > >Best to all, > > > > > >Brian vdB > > > > > >CODE: > > > > > >import datetime > > >import time > > > > > >def get_alarm_time(): > > > '''Asks user for a time in the form 'hh:mm' and return tuple of ints. > > > > > > Includes error checking to make sure user input really is of form > > > 'hh:mm' where the values of 'hh' and 'mm' are appropriate. > > > ''' > > > while True: > > > alarm_time = raw_input("Enter alarm time as hh:mm") > > > er_msg = ''' > > > An alarm time must be entered in the format 'hh:mm' where 'hh' > > > is a number between 0 and 23 inclusive and mm is a number > > > between 0 and 59 inclusive. > > > You entered: '%s', which is not of that form. > > > Please try again. > > > ''' %alarm_time > > > alarm_time_list = alarm_time.split(':') > > > # yields a list with first element the characters from before > > > # the ':' and second from after. > > > > > > try: > > > alarm_hour, alarm_minute = (int(alarm_time_list[0]), > > > int(alarm_time_list[1]) ) > > > except ValueError: > > > # raised if the user entered something like "silly:input" > > > print er_msg > > > continue > > > if len(str(alarm_minute)) == 1: > > > alarm_minute_string = '0' + str(alarm_minute) > > > # if the user entered, say, 12:05, str(alarm_minute) would > > > # give '5' rather than the needed '05'. > > > else: > > > alarm_minute_string = str(alarm_minute) > > > if ( (alarm_hour > 24 or alarm_hour < 0) > > > or (alarm_minute > 59 or alarm_minute < 0) > > > or str(alarm_hour) + ':' + alarm_minute_string != alarm_time): > > > # The first two clauses check that minutes and hours are > > > # within the expected ranges. The final clause checks that > > > # the inputs were string representations of integers. > > > # (Without it, the user could have entered something like > > > # 16.845:57.0000343.) > > > print er_msg > > > else: > > > return alarm_hour, alarm_minute > > > > > >alarm_hour, alarm_minute = get_alarm_time() > > >now = datetime.datetime.now() > > >alarm_datetime = datetime.datetime(now.year + 4, now.month, now.day, > > > alarm_hour, alarm_minute) > > ># now.year + 4 to ensure that the alarm_datetime represents a time in > > ># the future. I used a multiple of 4 to avoid leap year issues. + 44 > > ># would work equally well. (This ignores the additional correction every > > ># 100 or 400 years -- I forget which. But what do you want for free ;-) > > > > > >alarm_in_seconds = (alarm_datetime - now).seconds > > ># a_datetime_object - another_datetime_object gives a_timedelta_object. > > ># a_timedelta_object.seconds returns only the hour and minute difference > > ># (discarding days) expressed in seconds. It has to be the future time > > ># minus the current time for the .seconds to give the wanted result. > > > > > >print "I should wake up in %d seconds" %alarm_in_seconds > > >time.sleep(alarm_in_seconds) > > >print "I'm awake!" > > > > Brian, > > > > So yours can be boiled down to > > ==========Begin code================== > > alarm_time = raw_input("Enter alarm time as hh:mm") > > alarm_time_list = alarm_time.split(':') > > alarm_hour, alarm_minute = (int(alarm_time_list[0]), > > int(alarm_time_list[1])) > > > > now = datetime.datetime.now() > > alarm_datetime = datetime.datetime(now.year + 4, now.month, now.day, > > alarm_hour, alarm_minute) > > print alarm_datetime > > > > > > alarm_in_seconds = (alarm_datetime - now).seconds > > print "I should wake up in %d seconds" % alarm_in_seconds > > time.sleep(alarm_in_seconds) > > print "I'm awake!" > > ============End code================== > > > > Yes, I think yours is shorter, but not simpler. Mine doesn't need to > > consider the year or month, or leap years. On the other hand, mine > > doesn't take care of crossing the daylight time change borderline. > > > > But thanks very much. It gives me some understanding of the datetime > > module. As does Liam's code. > > > > BTW I found one omission in your error checking. The case where the user > > enters the time without a colon, e.g., 1234 instead of 12:34. > > > > Dick > > > > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > -- > 'There is only one basic human right, and that is to do as you damn well please. > And with it comes the only basic human duty, to take the consequences. > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From cyresse at gmail.com Mon Dec 6 07:05:58 2004 From: cyresse at gmail.com (Liam Clarke) Date: Mon Dec 6 07:06:01 2004 Subject: [Tutor] Address book sort of In-Reply-To: References: <003b01c4db12$1d709bf0$4d5328cf@JSLAPTOP> Message-ID: [quote] if select == '1' or select == 'v' or select == 'V': if file_in_disk in os.listdir('/home/jerimed'): # change??? fhandle = open(file_in_disk, 'r') # read mode cPickle.load(fhandle) # restore saved data fhandle.close() show_contacts() elif len(data_holder) > 0: show_contacts() else: is_empty() [/quote] if file_in_disk in os.listdir('/home/jerimed'): - if os.path.exists('/home/jerimed/file_in_disk'): Oh, and if it's in a subdir off the current dir - if os.path.exists('./home/jerimed/file_in_disk'): "./' means current or you could use - path = os.path.join(os.getcwd(), 'home','jerimed','filename') [quote]How do i pretty print output of dictionary container? Sort of tabular form or something, e.g., 1. name1 email address1 2. name2 email address2[/quote] try this - index = 0 for (key, item) in myDict.items(): index += 1 print "%d. %s \t %s" % (index, key, item) Although you may find that the length of key will vary, making it look messy. So, find the max length of the keys (names) first - highLength=0 for element in myDict.keys(): if len(element) > highLength: highLength = len(element) index = 0 minimumSpaces= 5 for (key, item) in myDict.items(): index += 1 spaceMult=(highLength+minimumSpaces)-len(key) outString=str(index)+". "+key+(spaceMult * " ") + item print outString What this line spaceMult=(highLength+minimumSpaces)-len(key) does - So, say you have two names - Bob Bobalicious obviously one tab(which Python usually counts as four spaces) separating will be Bob Bob's email Bobalicious Bobalicious' email spaceMult=(highLength+minimumSpaces)-len(key) highLength is 11, the length of Bob. The minimum separation between key and item is 5 spaces, so we're looking for the item to be 16 chars away from the start of the line. so spaceMult=(11+5)-len('bob') spaceMult = 13 So, the function will pad 13 spaces between 'bob' and 'bob's email' whereas only the minimum 5 between Bobalicious and his email. Which should equal nicely laid out. Haven't tested this though... Standard disclaimer - There's probably an easier way to do it, and a more elegant way. Which someone will post shortly. Cheers, Liam Clarke On Mon, 6 Dec 2004 07:55:11 +0300 (Arab Standard Time), Eri Mendz wrote: > On Sun, 5 Dec 2004, Jacob S. wrote: > > > I did something like this about three or four months ago... > > This is what I did. Notice the use of the built-in str() and eval() > > functions to write and receive data to and from Telephone.cfg... > > Thanks a lot Jacob, and to all who replied. I'll go through the code > definitely. I started building that address book last night and its > pretty crude. I hit a snag though: i was able to save the name/email > address pairs and write to disk. But i cant get it to load on startup. My > location is several dirs down my home directory. Of course the pickled > file is in same directory as the code. Its something like: > > if select == '1' or select == 'v' or select == 'V': > if file_in_disk in os.listdir('/home/jerimed'): # change??? > fhandle = open(file_in_disk, 'r') # read mode > cPickle.load(fhandle) # restore saved data > fhandle.close() > show_contacts() > elif len(data_holder) > 0: > show_contacts() > else: > is_empty() > > /home/jerimed should be changed and should be dynamic to match wherever > the python script is. Can you guyz advise? And is that first > if-statement right? I like to know if im doing the right thing. > > How do i pretty print output of dictionary container? Sort of tabular > form or something, e.g., > > 1. name1 email address1 > 2. name2 email address2 > > Just for my learning experience :-). Thanks! > > -- > Regards, > Eri Mendz > > > > > > > > from __future__ import division > > tel = {} > > try: > > file = open('Telephone.cfg', 'r') > > except: > > file = open('Telephone.cfg','w') > > file.close() > > file = open('Telephone.cfg','r') > > try: > > tel = eval(file.read()) > > a = 0 > > except: > > a = 1 > > print "No entries on file." > > pass > > print """\ > > Commands are: > > add > > get > > save > > delete > > quit > > all is a wildcard > > """ > > > > while 1: > > ask = raw_input('Tell me what you wish to do. ') > > if ask == "quit": > > break > > ask = ask.split(" ") > > command = ask[0] > > entity = ask[1:] > > entity = " ".join(entity) > > if entity == '': > > entity = raw_input("Who do you want to %s? " % command) > > if command == 'add': > > person = entity > > if tel.has_key(person): > > print "That person is already in there. If you wish to edit the > > file, please delete the record first." > > else: > > tel[person] = raw_input("What is their phone number? ") > > if command == 'get': > > if a == 1: > > print "Sorry, there are no entries available." > > else: > > person = entity > > if person == 'all': > > key = tel.keys() > > key.sort() > > print > > for x in key: > > print "%s\n%s\n" % (x,tel[x]) > > elif tel.has_key(person): > > print "\n%s\n%s\n" % (person,tel[person]) > > else: > > print "%s is not in your records." % person > > if command == 'save': > > file=open('Telephone.cfg', 'w') > > file.write(str(tel)) > > file.close() > > print 'Saved in Telephone.cfg' > > if command == 'delete': > > if a == 1: > > print "Sorry, there are no entries available." > > else: > > person = entity > > if person == 'all': > > tel={} > > newfile=open('Telephone.cfg', 'w') > > newfile.close() > > else: > > if tel.has_key(person): > > del tel[person] > > else: > > print "%s is not in your records." % person > > file.close() > > file = open('Telephone.cfg', 'w') > > file.write(str(tel)) > > file.close() > > > > > > As always, feel free to modify, use, and otherwise tear apart my code and > > give me suggests on how to improve it. > > Jacob Schmidt > > > >> Dear Tutor, > >> > >> I like to know what is the proper procedure (is algorithmn the right > >> term?) in creating data in a program, write it to file, close the app > >> then retrieve the data when run again. Basically, I'm trying to simulate > >> a simple address book (well not really for the datas are just names for > >> now) and so far have created the basic menu interface. It is console > >> base so forget gui. I ask user input and store it in a list. There are > >> menus to change, delete the data, and to save the data list in file. I > >> use cPickle for this and have verified the file is created by checking > >> in my $PWD. I want to retrieve that data when program is run again. What > >> to add in my code? I thought not to post the code but explain it as > >> above. > >> > >> What i want: when program is run again, the saved data is loaded when user > >> selects option 1 below. Of course the first time it is run, the list is > >> empty. > >> > >> def print_options(): > >> print ''' > >> Options: > >> [1] - Print content of list > >> [2] - Add name to list > >> [3] - Delete name from list > >> [4] - Change name in list > >> [5] - Save list to file > >> [P] - Print this menu > >> [Q] - Quit > >> ''' > >> > >> > >> > >> -- > >> Regards, > >> Eri Mendz > >> Using PC-Pine 4.61 > >> > >> > >> -- > >> Using PC-Pine 4.61 > >> > >> _______________________________________________ > >> 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 > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From cyresse at gmail.com Mon Dec 6 07:08:36 2004 From: cyresse at gmail.com (Liam Clarke) Date: Mon Dec 6 07:08:39 2004 Subject: [Tutor] Address book sort of In-Reply-To: References: <003b01c4db12$1d709bf0$4d5328cf@JSLAPTOP> Message-ID: Just tested the setout thing. It works. Prolly a hack, but it works. On Mon, 6 Dec 2004 19:05:58 +1300, Liam Clarke wrote: > [quote] > > > if select == '1' or select == 'v' or select == 'V': > if file_in_disk in os.listdir('/home/jerimed'): # change??? > fhandle = open(file_in_disk, 'r') # read mode > cPickle.load(fhandle) # restore saved data > fhandle.close() > show_contacts() > elif len(data_holder) > 0: > show_contacts() > else: > is_empty() > [/quote] > > if file_in_disk in os.listdir('/home/jerimed'): - > > if os.path.exists('/home/jerimed/file_in_disk'): > > Oh, and if it's in a subdir off the current dir - > > if os.path.exists('./home/jerimed/file_in_disk'): > > "./' means current > > or you could use - > path = os.path.join(os.getcwd(), 'home','jerimed','filename') > > [quote]How do i pretty print output of dictionary container? Sort of tabular > form or something, e.g., > > 1. name1 email address1 > 2. name2 email address2[/quote] > > try this - > > index = 0 > for (key, item) in myDict.items(): > index += 1 > print "%d. %s \t %s" % (index, key, item) > > Although you may find that the length of key will vary, making it look messy. > > So, find the max length of the keys (names) first - > > highLength=0 > for element in myDict.keys(): > if len(element) > highLength: > highLength = len(element) > > index = 0 > minimumSpaces= 5 > for (key, item) in myDict.items(): > index += 1 > spaceMult=(highLength+minimumSpaces)-len(key) > outString=str(index)+". "+key+(spaceMult * " ") + item > print outString > > What this line spaceMult=(highLength+minimumSpaces)-len(key) does - > > So, say you have two names - > > Bob > Bobalicious > > obviously one tab(which Python usually counts as four spaces) > separating will be > > Bob Bob's email > Bobalicious Bobalicious' email > > spaceMult=(highLength+minimumSpaces)-len(key) > > highLength is 11, the length of Bob. The minimum separation between > key and item is 5 spaces, so we're looking for the item to be 16 chars > away from the start of the line. > > so spaceMult=(11+5)-len('bob') > spaceMult = 13 > > So, the function will pad 13 spaces between 'bob' and 'bob's email' > whereas only the minimum 5 between Bobalicious and his email. > > Which should equal nicely laid out. > > Haven't tested this though... > > Standard disclaimer - > > There's probably an easier way to do it, and a more elegant way. Which > someone will post shortly. > > Cheers, > > Liam Clarke > > > > > On Mon, 6 Dec 2004 07:55:11 +0300 (Arab Standard Time), Eri Mendz > wrote: > > On Sun, 5 Dec 2004, Jacob S. wrote: > > > > > I did something like this about three or four months ago... > > > This is what I did. Notice the use of the built-in str() and eval() > > > functions to write and receive data to and from Telephone.cfg... > > > > Thanks a lot Jacob, and to all who replied. I'll go through the code > > definitely. I started building that address book last night and its > > pretty crude. I hit a snag though: i was able to save the name/email > > address pairs and write to disk. But i cant get it to load on startup. My > > location is several dirs down my home directory. Of course the pickled > > file is in same directory as the code. Its something like: > > > > if select == '1' or select == 'v' or select == 'V': > > if file_in_disk in os.listdir('/home/jerimed'): # change??? > > fhandle = open(file_in_disk, 'r') # read mode > > cPickle.load(fhandle) # restore saved data > > fhandle.close() > > show_contacts() > > elif len(data_holder) > 0: > > show_contacts() > > else: > > is_empty() > > > > /home/jerimed should be changed and should be dynamic to match wherever > > the python script is. Can you guyz advise? And is that first > > if-statement right? I like to know if im doing the right thing. > > > > How do i pretty print output of dictionary container? Sort of tabular > > form or something, e.g., > > > > 1. name1 email address1 > > 2. name2 email address2 > > > > Just for my learning experience :-). Thanks! > > > > -- > > Regards, > > Eri Mendz > > > > > > > > > > > > > > from __future__ import division > > > tel = {} > > > try: > > > file = open('Telephone.cfg', 'r') > > > except: > > > file = open('Telephone.cfg','w') > > > file.close() > > > file = open('Telephone.cfg','r') > > > try: > > > tel = eval(file.read()) > > > a = 0 > > > except: > > > a = 1 > > > print "No entries on file." > > > pass > > > print """\ > > > Commands are: > > > add > > > get > > > save > > > delete > > > quit > > > all is a wildcard > > > """ > > > > > > while 1: > > > ask = raw_input('Tell me what you wish to do. ') > > > if ask == "quit": > > > break > > > ask = ask.split(" ") > > > command = ask[0] > > > entity = ask[1:] > > > entity = " ".join(entity) > > > if entity == '': > > > entity = raw_input("Who do you want to %s? " % command) > > > if command == 'add': > > > person = entity > > > if tel.has_key(person): > > > print "That person is already in there. If you wish to edit the > > > file, please delete the record first." > > > else: > > > tel[person] = raw_input("What is their phone number? ") > > > if command == 'get': > > > if a == 1: > > > print "Sorry, there are no entries available." > > > else: > > > person = entity > > > if person == 'all': > > > key = tel.keys() > > > key.sort() > > > print > > > for x in key: > > > print "%s\n%s\n" % (x,tel[x]) > > > elif tel.has_key(person): > > > print "\n%s\n%s\n" % (person,tel[person]) > > > else: > > > print "%s is not in your records." % person > > > if command == 'save': > > > file=open('Telephone.cfg', 'w') > > > file.write(str(tel)) > > > file.close() > > > print 'Saved in Telephone.cfg' > > > if command == 'delete': > > > if a == 1: > > > print "Sorry, there are no entries available." > > > else: > > > person = entity > > > if person == 'all': > > > tel={} > > > newfile=open('Telephone.cfg', 'w') > > > newfile.close() > > > else: > > > if tel.has_key(person): > > > del tel[person] > > > else: > > > print "%s is not in your records." % person > > > file.close() > > > file = open('Telephone.cfg', 'w') > > > file.write(str(tel)) > > > file.close() > > > > > > > > > As always, feel free to modify, use, and otherwise tear apart my code and > > > give me suggests on how to improve it. > > > Jacob Schmidt > > > > > >> Dear Tutor, > > >> > > >> I like to know what is the proper procedure (is algorithmn the right > > >> term?) in creating data in a program, write it to file, close the app > > >> then retrieve the data when run again. Basically, I'm trying to simulate > > >> a simple address book (well not really for the datas are just names for > > >> now) and so far have created the basic menu interface. It is console > > >> base so forget gui. I ask user input and store it in a list. There are > > >> menus to change, delete the data, and to save the data list in file. I > > >> use cPickle for this and have verified the file is created by checking > > >> in my $PWD. I want to retrieve that data when program is run again. What > > >> to add in my code? I thought not to post the code but explain it as > > >> above. > > >> > > >> What i want: when program is run again, the saved data is loaded when user > > >> selects option 1 below. Of course the first time it is run, the list is > > >> empty. > > >> > > >> def print_options(): > > >> print ''' > > >> Options: > > >> [1] - Print content of list > > >> [2] - Add name to list > > >> [3] - Delete name from list > > >> [4] - Change name in list > > >> [5] - Save list to file > > >> [P] - Print this menu > > >> [Q] - Quit > > >> ''' > > >> > > >> > > >> > > >> -- > > >> Regards, > > >> Eri Mendz > > >> Using PC-Pine 4.61 > > >> > > >> > > >> -- > > >> Using PC-Pine 4.61 > > >> > > >> _______________________________________________ > > >> 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 > > > > > -- > > > 'There is only one basic human right, and that is to do as you damn well please. > And with it comes the only basic human duty, to take the consequences. > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From cullennewsom at yahoo.com Mon Dec 6 07:41:49 2004 From: cullennewsom at yahoo.com (Cullen Newsom) Date: Mon Dec 6 07:41:53 2004 Subject: [Tutor] Simple RPN calculator In-Reply-To: Message-ID: <20041206064149.45967.qmail@web10803.mail.yahoo.com> Just thought I would throw this out there, and say that an AVR microcontroller and some small amount of hardware would make a neat RPN calc. http://www.hp.com/calculators/articles/rpn.html Cullen __________________________________ Do you Yahoo!? All your favorites on one personal page – Try My Yahoo! http://my.yahoo.com From jerimed at myrealbox.com Mon Dec 6 08:20:42 2004 From: jerimed at myrealbox.com (Eri Mendz) Date: Mon Dec 6 08:20:43 2004 Subject: [Tutor] Address book sort of In-Reply-To: References: <003b01c4db12$1d709bf0$4d5328cf@JSLAPTOP> Message-ID: On Mon, 6 Dec 2004, Liam Clarke wrote: hey thanks a lot Liam! didnt tried it yet but later i will. appreciate you all good people. > Just tested the setout thing. It works. Prolly a hack, but it works. > > > On Mon, 6 Dec 2004 19:05:58 +1300, Liam Clarke wrote: >> [quote] >> >> >> if select == '1' or select == 'v' or select == 'V': >> if file_in_disk in os.listdir('/home/jerimed'): # change??? >> fhandle = open(file_in_disk, 'r') # read mode >> cPickle.load(fhandle) # restore saved data >> fhandle.close() >> show_contacts() >> elif len(data_holder) > 0: >> show_contacts() >> else: >> is_empty() >> [/quote] >> >> if file_in_disk in os.listdir('/home/jerimed'): - >> >> if os.path.exists('/home/jerimed/file_in_disk'): >> >> Oh, and if it's in a subdir off the current dir - >> >> if os.path.exists('./home/jerimed/file_in_disk'): >> >> "./' means current >> >> or you could use - >> path = os.path.join(os.getcwd(), 'home','jerimed','filename') >> >> [quote]How do i pretty print output of dictionary container? Sort of tabular >> form or something, e.g., >> >> 1. name1 email address1 >> 2. name2 email address2[/quote] >> >> try this - >> >> index = 0 >> for (key, item) in myDict.items(): >> index += 1 >> print "%d. %s \t %s" % (index, key, item) >> >> Although you may find that the length of key will vary, making it look messy. >> >> So, find the max length of the keys (names) first - >> >> highLength=0 >> for element in myDict.keys(): >> if len(element) > highLength: >> highLength = len(element) >> >> index = 0 >> minimumSpaces= 5 >> for (key, item) in myDict.items(): >> index += 1 >> spaceMult=(highLength+minimumSpaces)-len(key) >> outString=str(index)+". "+key+(spaceMult * " ") + item >> print outString >> >> What this line spaceMult=(highLength+minimumSpaces)-len(key) does - >> >> So, say you have two names - >> >> Bob >> Bobalicious >> >> obviously one tab(which Python usually counts as four spaces) >> separating will be >> >> Bob Bob's email >> Bobalicious Bobalicious' email >> >> spaceMult=(highLength+minimumSpaces)-len(key) >> >> highLength is 11, the length of Bob. The minimum separation between >> key and item is 5 spaces, so we're looking for the item to be 16 chars >> away from the start of the line. >> >> so spaceMult=(11+5)-len('bob') >> spaceMult = 13 >> >> So, the function will pad 13 spaces between 'bob' and 'bob's email' >> whereas only the minimum 5 between Bobalicious and his email. >> >> Which should equal nicely laid out. >> >> Haven't tested this though... >> >> Standard disclaimer - >> >> There's probably an easier way to do it, and a more elegant way. Which >> someone will post shortly. >> >> Cheers, >> >> Liam Clarke >> >> >> >> >> On Mon, 6 Dec 2004 07:55:11 +0300 (Arab Standard Time), Eri Mendz >> wrote: >>> On Sun, 5 Dec 2004, Jacob S. wrote: >>> >>>> I did something like this about three or four months ago... >>>> This is what I did. Notice the use of the built-in str() and eval() >>>> functions to write and receive data to and from Telephone.cfg... >>> >>> Thanks a lot Jacob, and to all who replied. I'll go through the code >>> definitely. I started building that address book last night and its >>> pretty crude. I hit a snag though: i was able to save the name/email >>> address pairs and write to disk. But i cant get it to load on startup. My >>> location is several dirs down my home directory. Of course the pickled >>> file is in same directory as the code. Its something like: >>> >>> if select == '1' or select == 'v' or select == 'V': >>> if file_in_disk in os.listdir('/home/jerimed'): # change??? >>> fhandle = open(file_in_disk, 'r') # read mode >>> cPickle.load(fhandle) # restore saved data >>> fhandle.close() >>> show_contacts() >>> elif len(data_holder) > 0: >>> show_contacts() >>> else: >>> is_empty() >>> >>> /home/jerimed should be changed and should be dynamic to match wherever >>> the python script is. Can you guyz advise? And is that first >>> if-statement right? I like to know if im doing the right thing. >>> >>> How do i pretty print output of dictionary container? Sort of tabular >>> form or something, e.g., >>> >>> 1. name1 email address1 >>> 2. name2 email address2 >>> >>> Just for my learning experience :-). Thanks! >>> >>> -- >>> Regards, >>> Eri Mendz >>> >>> >>> >>> >>>> >>>> from __future__ import division >>>> tel = {} >>>> try: >>>> file = open('Telephone.cfg', 'r') >>>> except: >>>> file = open('Telephone.cfg','w') >>>> file.close() >>>> file = open('Telephone.cfg','r') >>>> try: >>>> tel = eval(file.read()) >>>> a = 0 >>>> except: >>>> a = 1 >>>> print "No entries on file." >>>> pass >>>> print """\ >>>> Commands are: >>>> add >>>> get >>>> save >>>> delete >>>> quit >>>> all is a wildcard >>>> """ >>>> >>>> while 1: >>>> ask = raw_input('Tell me what you wish to do. ') >>>> if ask == "quit": >>>> break >>>> ask = ask.split(" ") >>>> command = ask[0] >>>> entity = ask[1:] >>>> entity = " ".join(entity) >>>> if entity == '': >>>> entity = raw_input("Who do you want to %s? " % command) >>>> if command == 'add': >>>> person = entity >>>> if tel.has_key(person): >>>> print "That person is already in there. If you wish to edit the >>>> file, please delete the record first." >>>> else: >>>> tel[person] = raw_input("What is their phone number? ") >>>> if command == 'get': >>>> if a == 1: >>>> print "Sorry, there are no entries available." >>>> else: >>>> person = entity >>>> if person == 'all': >>>> key = tel.keys() >>>> key.sort() >>>> print >>>> for x in key: >>>> print "%s\n%s\n" % (x,tel[x]) >>>> elif tel.has_key(person): >>>> print "\n%s\n%s\n" % (person,tel[person]) >>>> else: >>>> print "%s is not in your records." % person >>>> if command == 'save': >>>> file=open('Telephone.cfg', 'w') >>>> file.write(str(tel)) >>>> file.close() >>>> print 'Saved in Telephone.cfg' >>>> if command == 'delete': >>>> if a == 1: >>>> print "Sorry, there are no entries available." >>>> else: >>>> person = entity >>>> if person == 'all': >>>> tel={} >>>> newfile=open('Telephone.cfg', 'w') >>>> newfile.close() >>>> else: >>>> if tel.has_key(person): >>>> del tel[person] >>>> else: >>>> print "%s is not in your records." % person >>>> file.close() >>>> file = open('Telephone.cfg', 'w') >>>> file.write(str(tel)) >>>> file.close() >>>> >>>> >>>> As always, feel free to modify, use, and otherwise tear apart my code and >>>> give me suggests on how to improve it. >>>> Jacob Schmidt >>>> >>>>> Dear Tutor, >>>>> >>>>> I like to know what is the proper procedure (is algorithmn the right >>>>> term?) in creating data in a program, write it to file, close the app >>>>> then retrieve the data when run again. Basically, I'm trying to simulate >>>>> a simple address book (well not really for the datas are just names for >>>>> now) and so far have created the basic menu interface. It is console >>>>> base so forget gui. I ask user input and store it in a list. There are >>>>> menus to change, delete the data, and to save the data list in file. I >>>>> use cPickle for this and have verified the file is created by checking >>>>> in my $PWD. I want to retrieve that data when program is run again. What >>>>> to add in my code? I thought not to post the code but explain it as >>>>> above. >>>>> >>>>> What i want: when program is run again, the saved data is loaded when user >>>>> selects option 1 below. Of course the first time it is run, the list is >>>>> empty. >>>>> >>>>> def print_options(): >>>>> print ''' >>>>> Options: >>>>> [1] - Print content of list >>>>> [2] - Add name to list >>>>> [3] - Delete name from list >>>>> [4] - Change name in list >>>>> [5] - Save list to file >>>>> [P] - Print this menu >>>>> [Q] - Quit >>>>> ''' >>>>> >>>>> >>>>> >>>>> -- >>>>> Regards, >>>>> Eri Mendz >>>>> Using PC-Pine 4.61 >>>>> >>>>> >>>>> -- >>>>> Using PC-Pine 4.61 >>>>> >>>>> _______________________________________________ >>>>> 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 >>> >> >> >> -- >> >> >> 'There is only one basic human right, and that is to do as you damn well please. >> And with it comes the only basic human duty, to take the consequences. >> > > > -- Regards, Eri Mendz From bvande at po-box.mcgill.ca Mon Dec 6 08:17:53 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Mon Dec 6 08:33:38 2004 Subject: [Tutor] eval and exec In-Reply-To: <021901c4db23$f4ee4210$c6ca8751@xp> References: <021901c4db23$f4ee4210$c6ca8751@xp> Message-ID: <41B407A1.6090402@po-box.mcgill.ca> Hi all, in a discussion of security risks with eval() and exec() Alan Gauld said unto the world upon 2004-12-05 18:41: > Even in a config file, if its plain text a hostile (or just > mischievous) user could add a dangerous line and when you try > to exec it bad things happen. Any time you allow users to > influence what code runs you have potential for trouble > - that is the principle behind all these "buffer overrun" > security errors as well as all the script kiddie attacks > - MS allows Outlook to run scripts when mail is open, if > those scripts are harmful we have a virus! I didn't know that about Outlook. Thanks for that; it makes me glad I run www.mozilla.org/products/thunderbird/ ! Danny Yoo said unto the world upon 2004-12-05 16:40: > Here is an example of a string that can cause a StackOverflow error to > happen: > > ### > s = "(lambda loop: loop(loop)) (lambda self: self(self))" > eval(s) > ### > > The string 's' here looks funky, but in effect, it's definition is an > infinite loop in heavy lambda disguise. (Well, it would have been > infinite if Python had tail call optimization... *grin*) That's a really useful example. Thanks for posting it, Danny. Best to all, Brian vdB From bvande at po-box.mcgill.ca Mon Dec 6 07:11:04 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Mon Dec 6 08:33:53 2004 Subject: [Tutor] Could I have used time or datetime modules here? In-Reply-To: <6.1.2.0.2.20041205185122.03434eb0@rcblue.com> References: <6.1.2.0.2.20041205075719.02377370@rcblue.com> <6.1.2.0.2.20041205112204.04e9d100@rcblue.com> <41B3AD6D.8060603@po-box.mcgill.ca> <6.1.2.0.2.20041205185122.03434eb0@rcblue.com> Message-ID: <41B3F7F8.7070005@po-box.mcgill.ca> Dick Moores said unto the world upon 2004-12-05 22:02: > Brian van den Broek wrote at 16:53 12/5/2004: > >> Dick Moores said unto the world upon 2004-12-05 15:03: >> >>> Thanks, Brian. I looked at your code a long time, and also read the >>> 11/26 thread you started. I can see how I could use datetime() and >>> your t2 - t1 to get the seconds for time.sleep(), but the resulting >>> code I have in mind is more convoluted than the heart of my >>> timer3.py, which I quote below. (I don't need the alarm time to be >>> more than 24 hours from current time--therefore I want to ignore the >>> year, month, and day.) >>> ======================================= >>> import time >>> alarm = raw_input("Enter alarm time as hhmm: ") >>> now = time.strftime("%X") # produces current time in format hh:mm:ss >>> nowSecond = int(now[6:]) >>> nowMinute = int(now[3:5]) >>> nowHour = int(now[0:2]) >>> alarmMinute = int(alarm[2:4]) >>> alarmHour = int(alarm[0:2]) >>> hoursDiff = alarmHour - nowHour >>> minutesDiff = alarmMinute - nowMinute >>> if hoursDiff < 0 or (hoursDiff == 0 and minutesDiff <= 0): >>> hoursDiff = hoursDiff + 24 # add a day >>> sleepSeconds = hoursDiff*3600 + minutesDiff*60 - nowSecond >>> time.sleep(sleepSeconds) >>> ==================================== >>> If I'm wrong, could someone please set me right? >>> Dick >> >> >> Hi Dick and all, >> >> sorry I was too lazy to follow your link before, Dick. Thanks for >> posting the relevant portions. >> >> I took another run, but my code is a lot longer as I put in some error >> checking on the input request -- hope you don't mind ;-) (I might have >> gone overboard -- I did it to learn how as much as anything else.) >> >> I suspect that my way is easier than yours. (I don't know about >> Liam's. His came in as I was writing mine, and I've not read his >> closely yet.) >> > > Brian, > > So yours can be boiled down to > ==========Begin code================== > alarm_time = raw_input("Enter alarm time as hh:mm") > alarm_time_list = alarm_time.split(':') > alarm_hour, alarm_minute = (int(alarm_time_list[0]), > int(alarm_time_list[1])) > now = datetime.datetime.now() > alarm_datetime = datetime.datetime(now.year + 4, now.month, now.day, > alarm_hour, alarm_minute) > print alarm_datetime > alarm_in_seconds = (alarm_datetime - now).seconds > print "I should wake up in %d seconds" % alarm_in_seconds > time.sleep(alarm_in_seconds) > print "I'm awake!" > ============End code================== > > Yes, I think yours is shorter, but not simpler. Mine doesn't need to > consider the year or month, or leap years. On the other hand, mine > doesn't take care of crossing the daylight time change borderline. I can see your point; you're right that it made me think about leap years, etc. in a way that your code avoids. > > But thanks very much. It gives me some understanding of the datetime > module. As does Liam's code. > > BTW I found one omission in your error checking. The case where the user > enters the time without a colon, e.g., 1234 instead of 12:34. > > Dick Thanks! You're right. I was going to move it over to one of my utility modules, so I'm glad to know about the bug. Best to all, Brian vdB From rdm at rcblue.com Mon Dec 6 08:49:03 2004 From: rdm at rcblue.com (Dick Moores) Date: Mon Dec 6 08:59:11 2004 Subject: [Tutor] psyco 1.3 is out, with support for Python 2.4 Message-ID: <6.1.2.0.2.20041205234514.04a5aeb0@rcblue.com> And "The Ultimate Psyco Guide" for 1.3 is at Dick Moores From cyresse at gmail.com Mon Dec 6 11:18:18 2004 From: cyresse at gmail.com (Liam Clarke) Date: Mon Dec 6 11:18:21 2004 Subject: [Tutor] psyco 1.3 is out, with support for Python 2.4 In-Reply-To: <6.1.2.0.2.20041205234514.04a5aeb0@rcblue.com> References: <6.1.2.0.2.20041205234514.04a5aeb0@rcblue.com> Message-ID: Have you used Pysco much Dick? Is it n00bie friendly? Or, to put it another way, at what point in a programme's size/speed does it become worthwhile to implement Pysco? Regards, Liam Clarke On Sun, 05 Dec 2004 23:49:03 -0800, Dick Moores wrote: > > > And "The Ultimate Psyco Guide" for 1.3 is at > > > Dick Moores > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From justinstraube at charter.net Mon Dec 6 12:23:07 2004 From: justinstraube at charter.net (justinstraube@charter.net) Date: Mon Dec 6 12:23:09 2004 Subject: [Tutor] Address book sort of Message-ID: <3k70j8$ip2s5p@mxip17a.cluster1.charter.net> >> How do i pretty print output of dictionary container? Sort of tabular >> form or something, e.g., >> >> 1. name1 email address1 >> 2. name2 email address2 >> >> Just for my learning experience :-). Thanks! [Liam Clarke] highLength=0 for element in myDict.keys(): if len(element) > highLength: highLength = len(element) index = 0 minimumSpaces= 5 for (key, item) in myDict.items(): index += 1 spaceMult=(highLength+minimumSpaces)-len(key) outString=str(index)+". "+key+(spaceMult * " ") + item print outString [/Liam Clarke] This is what I had come up with. Where 'd' is a dictionary. This also assumes that when the display_name is input, that it is less than 25 characters in length. #### def display_contacts(d): print '\nYou have %i contacts in your book.\n' % len(d) while 1: count = 0 for item in d: display_name = item while len(display_name) < 25: display_name += '.' count += 1 print count, display_name, d[item] raw_input('\nPress to continue.\n') break #### >>> x = {'Justin Straube': 'justinstraube@charter.net', 'Eri Mendz': 'jerimed@myrealbox.com', 'Python-Tutor': 'tutor@python.org', 'Hello': 'World'} >>> display_contacts(x) You have 4 contacts in your book. 1 Justin Straube........... justinstraube@charter.net 2 Hello.................... World 3 Eri Mendz................ jerimed@myrealbox.com 4 Python-Tutor............. tutor@python.org Press to continue. >>> regards, Justin --- Justin Straube justinstraube@charter.net http://www.angelfire.com/wi3/phosphorescent/ Whatever you have thought about the world before, forget it, now you are in this one From amonroe at columbus.rr.com Mon Dec 6 12:44:27 2004 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Mon Dec 6 12:44:49 2004 Subject: [Tutor] Address book sort of In-Reply-To: <3k70j8$ip2s5p@mxip17a.cluster1.charter.net> References: <3k70j8$ip2s5p@mxip17a.cluster1.charter.net> Message-ID: <5545366173.20041206064427@columbus.rr.com> > spaceMult=(highLength+minimumSpaces)-len(key) > outString=str(index)+". "+key+(spaceMult * " ") + item > print outString > while len(display_name) < 25: > display_name += '.' > count += 1 > print count, display_name, d[item] Rather than futzing with len()-based solutions, you might want to just specify lengths in format strings: >>> a='alan' >>> print '*%10s*%-10s*' % (a,a) * alan*alan * Alan From rdm at rcblue.com Mon Dec 6 12:46:30 2004 From: rdm at rcblue.com (Dick Moores) Date: Mon Dec 6 12:46:34 2004 Subject: [Tutor] psyco 1.3 is out, with support for Python 2.4 In-Reply-To: References: <6.1.2.0.2.20041205234514.04a5aeb0@rcblue.com> Message-ID: <6.1.2.0.2.20041206024158.023a4dc0@rcblue.com> Liam, Kent Johnson was of great help in getting me started with psyco. psyco's easy to implement, it seems, and can make an enormous difference in speed. The best example I've seen is my simple , where psyco speeds up the tiny while loop of spin(), while k < max: k += 1 by 2 orders of magnitude. (But keep max <= 2**31-1). In mine and Kent's psyco also makes an important, but much lesser, difference to the speed of the workhorse function, factorsOfInteger(n). Here's an example: for "400000000139252 400000000139300", my time using psyco is 22 seconds; without psyco, 34 seconds. Here's what I learned from Kent about installing psyco (for Windows): Download psyco from http://psyco.sourceforge.net. Unzip the zip file. Copy the folder psyco-1.3/psyco into Python24/Lib/site-packages. (Create site-packages if you don't already have it.) Should be good to go then. Dick Liam Clarke wrote at 02:18 12/6/2004: >Have you used Pysco much Dick? Is it n00bie friendly? > >Or, to put it another way, at what point in a programme's size/speed >does it become worthwhile to implement Pysco? > >Regards, > >Liam Clarke > >On Sun, 05 Dec 2004 23:49:03 -0800, Dick Moores wrote: > > > > > > And "The Ultimate Psyco Guide" for 1.3 is at > > > > > > Dick Moores From cyresse at gmail.com Mon Dec 6 12:56:37 2004 From: cyresse at gmail.com (Liam Clarke) Date: Mon Dec 6 12:56:40 2004 Subject: [Tutor] Re: Could I have used time or datetime modules here? In-Reply-To: References: <6.1.2.0.2.20041205075719.02377370@rcblue.com> <6.1.2.0.2.20041205112204.04e9d100@rcblue.com> <41B3AD6D.8060603@po-box.mcgill.ca> <6.1.2.0.2.20041205185122.03434eb0@rcblue.com> <6.1.2.0.2.20041205224631.08390ad0@rcblue.com> <6.1.2.0.2.20041206021510.03475770@rcblue.com> Message-ID: Hey Dick, don't know if anyone actually answered your original question. >IOW, is there an easier way to calculate the time difference between the >time now, say 08:51 and say, tomorrow at 03:45, to take an example of the >most difficult case? So, you need two datetime.datetime objects. >>>now = datetime.datetime(year, month, day, hours, minutes, seconds) >>>now = datetime.datetime(2004, 12, 7*, 8*, 51, 00) >>> later= datetime.datetime(2004, 12, 8*, 3*, 45, 00) *Can't start with zero. Must be 8 not 08 >>> difference = later - now >>> print difference 18:54:00 >>> type(difference) >>> timeList=str(difference).split(":") >>> print timeList ['18', '54', '00'] >>> timeinSecs=(int(timeList[0])*3600)+(int(timeList[1])*60)+int(timeList[2]) >>> print timeinSecs 68040 Now, to check if that's right... >>> timeChange=datetime.timedelta(seconds=68040) >>> checkVal=now + timeChange >>> print checkVal 2004-12-08 03:45:00 Looks good to me. So, to summarise the code part - now = datetime.datetime(2004, 12, 7, 8, 51, 00) later= datetime.datetime(2004, 12, 8, 3, 45, 00) difference = later - now timeList=str(difference).split(":") timeinSecs=(int(timeList[0])*3600)+(int(timeList[1])*60)+int(timeList[2]) And that's the easier way to find the difference between two times in seconds. HTH Liam Clarke P.S. If you're interested, here's a 20 line alarm clock I wrote because my one broke this morning. http://www.rafb.net/paste/results/ctOH1T36.html On Mon, 06 Dec 2004 02:15:55 -0800, Dick Moores wrote: > Hey, no problem. And thanks again for your help. > > Dick > > Liam Clarke wrote at 02:05 12/6/2004: > >Whoops, sorry. > > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From domain.admin at online.ie Mon Dec 6 13:45:43 2004 From: domain.admin at online.ie (Guybrush Threepwood) Date: Mon Dec 6 13:45:45 2004 Subject: [Tutor] CGI Video collection application File I/O troubles In-Reply-To: <00de01c4db1c$4ab85c60$4d5328cf@JSLAPTOP> References: <1102284490.41b386cac3033@mail.online.ie> <00ba01c4db18$a53d1bc0$4d5328cf@JSLAPTOP> <1102285829.41b38c05994f0@mail.online.ie> <00de01c4db1c$4ab85c60$4d5328cf@JSLAPTOP> Message-ID: <1102337143.41b454771a01d@mail.online.ie> Quoting "Jacob S." : > Your error message says that you are getting an empty string from your cgi > variable. I IMHO would suggest printing videodb['title'] before writing it > to a file to see what the variable contains. Or you might print out videodb > to see what the dictionary looks like. Right!! That were my thoughts exactly. I think I even wrote this in my email. Anyhoo, when I do a print videodb or print['videodb'] from the script it prints the correct values to a new HTML file. >My off the wall guess is that 1) Your > cgi variables are not returning the value from the actual object that you > want 2) The script is running and assigning values to title, etc. before the > afore mentioned object is given a value. IOW, maybe you haven't assigned > values to the form before you try to read them. > Another suggestion. Comment out the file writing part and print everything > to the screen to verify that the output is what you want. "When in doubt, > print it out." - Jacob Schmidt > > HTH, > Jacob > Ok. I tried running the script on my Apache server on Windows NT and IT WORKS!!!! The script saves the values of videodb keys correctly. DARN!!! I don't get it. Why does the exact same script work on Win and not on Linux. Oh, did I mention I am developing the application on Linux. And now I tried it on Win XP with Apache and it works. On Linux I have httpd too. [snip] -- The lady on the call box in Monkey Island 2 Guybrush: I'm lost in the Inky Island Jungle in Monkey 2 Lady: Just walk off the edge of the screen From kent37 at tds.net Mon Dec 6 13:55:14 2004 From: kent37 at tds.net (Kent Johnson) Date: Mon Dec 6 13:55:18 2004 Subject: [Tutor] psyco 1.3 is out, with support for Python 2.4 In-Reply-To: <6.1.2.0.2.20041206024158.023a4dc0@rcblue.com> References: <6.1.2.0.2.20041205234514.04a5aeb0@rcblue.com> <6.1.2.0.2.20041206024158.023a4dc0@rcblue.com> Message-ID: <41B456B2.3080407@tds.net> Dick Moores wrote: > Here's what I learned from Kent about installing psyco (for Windows): > Download psyco from http://psyco.sourceforge.net. Unzip the zip file. > Copy the folder psyco-1.3/psyco into Python24/Lib/site-packages. (Create > site-packages if you don't already have it.) Should be good to go then. Then to actually _use_ psyco, the simplest thing is just to add these two lines to your main program: import psyco psyco.full() Kent From flaxeater at yahoo.com Mon Dec 6 14:05:06 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Mon Dec 6 14:05:10 2004 Subject: [Tutor] Simple RPN calculator Message-ID: <20041206130506.47035.qmail@web54303.mail.yahoo.com> Bob Gailer wrote: > For grins I just wrote one that takes '1 2.3 - 3 4 5 + * /' as input > and prints -0.0481481.... 8 lines of Python. That indeed is less than > 100. Took about 7 minutes to code and test. I'm quite interested in seeing the sourcecode for that. __________________________________ Do you Yahoo!? Yahoo! Mail - 250MB free storage. Do more. Manage less. http://info.mail.yahoo.com/mail_250 From olli.s.rajala at tut.fi Mon Dec 6 15:06:00 2004 From: olli.s.rajala at tut.fi (Olli Rajala) Date: Mon Dec 6 15:06:04 2004 Subject: [Tutor] CGI Video collection application File I/O troubles In-Reply-To: <1102337143.41b454771a01d@mail.online.ie> References: <1102284490.41b386cac3033@mail.online.ie> <00ba01c4db18$a53d1bc0$4d5328cf@JSLAPTOP> <1102285829.41b38c05994f0@mail.online.ie> <00de01c4db1c$4ab85c60$4d5328cf@JSLAPTOP> <1102337143.41b454771a01d@mail.online.ie> Message-ID: <20041206140600.GA30408@students.cc.tut.fi> > Ok. I tried running the script on my Apache server on Windows NT and IT > WORKS!!!! The script saves the values of videodb keys correctly. DARN!!! > I don't get it. Why does the exact same script work on Win and not on Linux. > > Oh, did I mention I am developing the application on Linux. And now I tried > it on Win XP with Apache and it works. On Linux I have httpd too. Have you triplechecked that you really can write to the file. I don't know how python would react, if you can't write to the file (raise IOError perhaps) but it doesn't cost you anything to check that... :) Yours, -- Olli Rajala "In theory, Theory and Practice should be the same. But in practice, they aren't." - Murphy's Proverbs From flaxeater at yahoo.com Mon Dec 6 16:28:49 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Mon Dec 6 16:28:53 2004 Subject: [Tutor] CGI Video collection application File I/O troubles Message-ID: <20041206152849.85087.qmail@web54306.mail.yahoo.com> Olli Rajala wrote: > > > >>Ok. I tried running the script on my Apache server on Windows NT and IT >>WORKS!!!! The script saves the values of videodb keys correctly. DARN!!! >>I don't get it. Why does the exact same script work on Win and not on Linux. >> >>Oh, did I mention I am developing the application on Linux. And now I tried >>it on Win XP with Apache and it works. On Linux I have httpd too. >> >> > >Have you triplechecked that you really can write to the file. I don't >know how python would react, if you can't write to the file (raise >IOError perhaps) but it doesn't cost you anything to check that... :) > >Yours, > > You know. I that is what happened to me once. I could not for the life of me figure it out. I just chmod 777 it. __________________________________ Do you Yahoo!? Read only the mail you want - Yahoo! Mail SpamGuard. http://promotions.yahoo.com/new_mail From bgailer at alum.rpi.edu Mon Dec 6 17:44:58 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon Dec 6 17:44:10 2004 Subject: [Tutor] Re: Can I see it? In-Reply-To: <20041205210621.47043.qmail@web54402.mail.yahoo.com> References: <6.2.0.14.0.20041205045050.057bf8f8@mail.mric.net> <20041205210621.47043.qmail@web54402.mail.yahoo.com> Message-ID: <6.2.0.14.0.20041206093842.02ddadb8@mail.mric.net> At 02:06 PM 12/5/2004, Just Incase wrote: >Hi Bob, > >Yea, it is a homework and I would also like to do something on it to get >familiar with the program, so all I am asking for is if there are the >pionters to help me. Like I said I am new to python/programming but I have >limited time to turn-in the assignment as all these while I have been >trying to study the tutorials I thought would help and I guess I was not >looking in the right place. > >Here is what I have been trying to use: >Any help is welcome. Thank you. Exactly what help do you want? I don't want to read all your code in detail. What do you need next? Also please reply to all so this gets back to the tutor list. >#!/usr/bin/env python ># Reverse Polish Notation Calculator ># Justice > >import cmd, sys > >class rpn_calc(cmd.Cmd): > """RPN calculator""" > > def __init__(self, stacksize=4): > self.stack = [0]*stacksize > self.stacksize = len(self.stack) > self.lastregister = self.stacksize-1 > self.intro='Simple RPN Calculator\nJustice 29. Nov 2004' > self.lastx = 0 > > self.operations = { '+': self.do_add, > '-': self.do_subtract, > '*': self.do_multiply, > '/': self.do_divide, } > > > # Helper functions > > def _stacklift(self, new_x): > """Lift stack by one entry, last register is lost""" > > del self.stack[self.lastregister] > self.stack.insert(0, new_x) > > def _stackdrop(self, new_x): > """Drop stack by one entry, losing Y register entry, last register > is doubled""" > > self.stack.append(self.stack[self.lastregister]) > del self.stack[0] > self.stack[0]=new_x > > # Catch numbers and operators > > def default(self, entry): > """Catch numbers and operators and process them. If entry is > neither number nor operator, ignore and pass on to cmd > loop.""" > > # Catch numbers > try: > number = float(entry) > self.lastx = self.stack[0] > self._stacklift(number) > except ValueError: > pass > > # Catch operations > if entry in self.operations: > operation = self.operations[entry] > operation() > > > # Show X register after each command > > def postcmd(self, *dummy): > """Display the contents of the X register after each > command""" > print " %f" % self.stack[0] > > > # Calculator commands > > def do_add(self, dummy=None): > result = self.stack[1] + self.stack[0] > self._stackdrop(result) > > def do_clrx(self, rest): > """Clear X register""" > self.stack[0] = 0 > > def do_divide(self, dummy=None): > try: > result = self.stack[1] / self.stack[0] > self._stackdrop(result) > except ZeroDivisionError: > print "*** Division by Zero Error ***" > > def do_enter(self, dummy): > """Perform a stack lift; last register value is lost, > first (X) register value is pushed into the second (Y) > register""" > self._stacklift(self.stack[0]) > > def emptyline(self, dummy=None): > """An empty line is treated like hitting the ENTER key""" > self.do_enter(None) > > def do_lastx(self, dummy): > """Restore X register value from before the operation in the > X register, performing a stack lift""" > > self._stacklift(self.lastx) > > def do_multiply(self, dummy=None): > try: > result = self.stack[1] * self.stack[0] > self._stackdrop(result) > except OverflowError: > print '*** Overflow Error ***' > > def do_print(self, rest): > """Print stack. Mostly used for debugging""" > for i in range(self.stacksize-1, -1, -1): > print 'Reg %s: %f' % (i, self.stack[i]) > > def do_quit(self, dummy): > sys.exit() > > def do_rdown(self, dummy): > """Roll down stack""" > self.stack.append(self.stack[0]) > del self.stack[0] > > def do_rup(self, dummy): > """Roll up stack""" > self.stack.insert(0, self.stack[self.lastregister]) > del self.stack[self.lastregister+1] > > def do_subtract(self, dummy=None): > result = self.stack[1] - self.stack[0] > self._stackdrop(result) > > def do_xy(self, dummy): > """Swap X and Y registers""" > self.stack[0], self.stack[1] = self.stack[1], self.stack[0] > > > # Help texts > > def help_add(self): > print 'Add X and Y register. Use "+" key or "add" command' > def help_clrx(self): > print 'Clear X register' > def help_divide(self): > print 'Divide X by Y register. Use "/" key or "divide" command' > def help_enter(self): > print 'Push stack up by one, last register is lost' > def help_help(self): > print 'Prints list of commands' > def help_lastx(self): > print 'Retrieves value of the X register from before the last' > print 'operation and pushes it in the X register, lifting the' > print 'stack.' > def help_multiply(self): > print 'Multiply X by Y register. Use "*" key or "subtract" command' > def help_power(self): > print 'Take Y to the Xth power. Use "^" key or "power" command' > def help_print(self): > print 'Print stack. Used mostly for debugging' > def help_rdown(self): > print 'Rolls stack downwards' > def help_rup(self): > print 'Rolls stack upwards' > def help_quit(self): > print 'Quit program' > def help_subtract(self): > print 'Subtract X from Y register. Use "-" key or "subtract" cmd' > def help_xy(self): > print 'Swaps X and Y registers' Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From Christian.Wyglendowski at greenville.edu Mon Dec 6 18:42:02 2004 From: Christian.Wyglendowski at greenville.edu (Christian Wyglendowski) Date: Mon Dec 6 18:42:17 2004 Subject: [Tutor] Socket events and wxPython events? Message-ID: > -----Original Message----- > From: tutor-bounces@python.org > [mailto:tutor-bounces@python.org] On Behalf Of Mike Eve > Sent: Sunday, December 05, 2004 6:21 PM > To: tutor@python.org > Subject: [Tutor] Socket events and wxPython events? Hey Mike, > I'm thinking about 3 approaches, but rather than beat my head > against the wall, I was hoping to find out if any of these > are workable: Here are my thoughts. You might have better luck on the wxPython users mailing list if this doesn't help point you in the right direction. > 1) use sockets lib. Do socket send/recv generate any kind of > event with an event id that can used with the wxPython window > events? That is, I want to just sit and receive events such > as OnPaint, OnButton, in the same loop as I receive > "OnReceiveSocket" (or whatever it might be called). Python sockets are pretty basic, and do not tie in to wxPython as far as I know. > 2) create a separate thread which does a select then sends a > wxPython compatible event which can be intermixed with > OnPaint, etc (similar to option 1) This sounds doable - maybe combined with option 1 or 3. > 3) use SocketServer. I noticed the SocketServer class refers > to "request handler class" and "handle" functions. Do these > generate any events which are wxPython compatible By default, SocketServer will probably not interface with wxPython as far as generating events goes. > You probably noticed I'm a little confused about what a > wxPython compatible event is. I'm not sure if these events > and their event handling are part of Python or something > added by and unique to wxPython. wxPython provides the event processing framework. Using any of these approaches, it sounds like you want to create a custom event and have your network portion of the code fire that event. Check out the PythonEvents demo in the wxPython demo to see some sample code implementing a custom event. > Thanks, Mike > HTH, Christian http://www.dowski.com From ps_python at yahoo.com Mon Dec 6 18:57:11 2004 From: ps_python at yahoo.com (kumar s) Date: Mon Dec 6 18:57:14 2004 Subject: [Tutor] Finding a part of an element in a list Message-ID: <20041206175711.73388.qmail@web53709.mail.yahoo.com> Dear Group, I have a list that is: List1 = ['Tyres','windsheild','A\CUnit','Model=Toyota_Corolla'] In other list I have : List2= ['Corolla','Accord','Camry'] I want to see if Corolla is there in list 1: The code: for i in range(len(List1)): if i in range(len(List2): print i If I have 'Corolla' as an element in both list then it is easy to find. However, in List1 this element appears as 'Model=Toyota_Corolla'. How can I ask python to match both elements: 'Model=Toyota_Corolla' and 'Corolla', where a part of element is matching. please help. thanks __________________________________ Do you Yahoo!? All your favorites on one personal page – Try My Yahoo! http://my.yahoo.com From cyresse at gmail.com Mon Dec 6 19:20:15 2004 From: cyresse at gmail.com (Liam Clarke) Date: Mon Dec 6 19:20:19 2004 Subject: [Tutor] Finding a part of an element in a list In-Reply-To: <20041206175711.73388.qmail@web53709.mail.yahoo.com> References: <20041206175711.73388.qmail@web53709.mail.yahoo.com> Message-ID: Hey Kumar, nearly there - List1 = ['Tyres','windsheild','A\CUnit','Model=Toyota_Corolla'] In other list I have : List2= ['Corolla','Accord','Camry'] for element1 in List1: for element2 in List2: if element2 in element1: #Do something here, usually a break or continue clause (Incidentally,'for element in list' is an easier version of for i in range(len(list)) when you don't need to use index numbers. It just steps element by element.) 'if x in y' works for strings within strings as well. Regards, Liam Clarke On Mon, 6 Dec 2004 09:57:11 -0800 (PST), kumar s wrote: > Dear Group, > > I have a list that is: > > List1 = > ['Tyres','windsheild','A\CUnit','Model=Toyota_Corolla'] > > In other list I have : > List2= ['Corolla','Accord','Camry'] > > I want to see if Corolla is there in list 1: > > The code: > for i in range(len(List1)): > if i in range(len(List2): > print i > > If I have 'Corolla' as an element in both list then it > is easy to find. However, in List1 this element > appears as 'Model=Toyota_Corolla'. > > How can I ask python to match both elements: > 'Model=Toyota_Corolla' and 'Corolla', where a part of > element is matching. > > please help. > > thanks > > > __________________________________ > Do you Yahoo!? > All your favorites on one personal page ? Try My Yahoo! > http://my.yahoo.com > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From andreas at kostyrka.org Mon Dec 6 20:03:52 2004 From: andreas at kostyrka.org (Andreas Kostyrka) Date: Mon Dec 6 20:07:17 2004 Subject: [Tutor] Simple RPN calculator In-Reply-To: <20041206130506.47035.qmail@web54303.mail.yahoo.com> References: <20041206130506.47035.qmail@web54303.mail.yahoo.com> Message-ID: <1102359832.3162.88.camel@andi-lap> Am Mo, den 06.12.2004 schrieb Chad Crabtree um 14:05: > Bob Gailer wrote: > > > For grins I just wrote one that takes '1 2.3 - 3 4 5 + * /' as > input > > and prints -0.0481481.... 8 lines of Python. That indeed is less > than > > 100. Took about 7 minutes to code and test. > > I'm quite interested in seeing the sourcecode for that. Well, I'm down to 12 lines: import operator, sys st = [] while 1: s = raw_input("%s>" % [str(x) for x in st]).split() if not s: break for t in s: func = {'+':operator.add, '-':operator.sub, '*':operator.mul, '/':operator.div}.get(t, None) if func is None: st.append(float(t)) else: sec = st.pop() fir = st.pop() st.append(func(fir, sec)) Andreas -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: Dies ist ein digital signierter Nachrichtenteil Url : http://mail.python.org/pipermail/tutor/attachments/20041206/5fe2150f/attachment.pgp From ps_python at yahoo.com Mon Dec 6 21:27:13 2004 From: ps_python at yahoo.com (kumar s) Date: Mon Dec 6 21:27:17 2004 Subject: [Tutor] Removing a row from a tab delimitted text Message-ID: <20041206202713.20773.qmail@web53702.mail.yahoo.com> Dear group, I have a file, with Name identifier followed by two columns with numbers. Here is how my file looks: Name=3492_at Cell1=481 13 (The space between (481 and 13 is tab) Cell1=481 13 Cell1=481 13 Name=1001_at Cell1=481 13 Cell2=481 12 Cell1=481 13 Cell1=481 13 Cell2=481 12 Name=1002_at Cell3=482 12 Cell1=481 13 Cell1=481 13 Cell2=481 12 Cell3=482 12 Cell4=482 13 Cell1=481 13 My question: 1. How can I remove the line where Name identfier exists and get two columns of data. Thanks kumar. __________________________________ Do you Yahoo!? Yahoo! Mail - 250MB free storage. Do more. Manage less. http://info.mail.yahoo.com/mail_250 From askoose at sandia.gov Mon Dec 6 21:49:46 2004 From: askoose at sandia.gov (Kooser, Ara S) Date: Mon Dec 6 21:50:03 2004 Subject: [Tutor] Removing a row from a tab delimitted text Message-ID: <7BB911D90C4F384EAAFBB31DEFF990BE187807@ES21SNLNT.srn.sandia.gov> Alan Gauld tutorial at http://www.freenetpages.co.uk/hp/alan.gauld/ has some examples in python that will solve this problem. Happy Pythoning Ara "There is something to be learned from a rainstorm. When meeting with a sudden shower, you try not to get wet and run quickly along the road. But doing such things as passing under the eaves of houses, you still get wet. When you are resolved from the beginning, you will not be perplexed, though you still get the same soaking." - Yamamoto Tsunetomo -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of kumar s Sent: Monday, December 06, 2004 1:27 PM To: tutor@python.org Subject: [Tutor] Removing a row from a tab delimitted text Dear group, I have a file, with Name identifier followed by two columns with numbers. Here is how my file looks: Name=3492_at Cell1=481 13 (The space between (481 and 13 is tab) Cell1=481 13 Cell1=481 13 Name=1001_at Cell1=481 13 Cell2=481 12 Cell1=481 13 Cell1=481 13 Cell2=481 12 Name=1002_at Cell3=482 12 Cell1=481 13 Cell1=481 13 Cell2=481 12 Cell3=482 12 Cell4=482 13 Cell1=481 13 My question: 1. How can I remove the line where Name identfier exists and get two columns of data. Thanks kumar. __________________________________ Do you Yahoo!? Yahoo! Mail - 250MB free storage. Do more. Manage less. http://info.mail.yahoo.com/mail_250 _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From dyoo at hkn.eecs.berkeley.edu Mon Dec 6 22:28:17 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Dec 6 22:28:20 2004 Subject: [Tutor] Removing a row from a tab delimitted text In-Reply-To: <20041206202713.20773.qmail@web53702.mail.yahoo.com> Message-ID: On Mon, 6 Dec 2004, kumar s wrote: > Here is how my file looks: > > Name=3492_at > Cell1=481 13 (The space between (481 and 13 is tab) > Cell1=481 13 > Cell1=481 13 > Name=1001_at > Cell1=481 13 > Cell2=481 12 > Cell1=481 13 > Cell1=481 13 > Cell2=481 12 > Name=1002_at > Cell3=482 12 > Cell1=481 13 > Cell1=481 13 > Cell2=481 12 > Cell3=482 12 > Cell4=482 13 > Cell1=481 13 > > My question: > > 1. How can I remove the line where Name identfier > exists and get two columns of data. Hi Kumar, You may want to separate that question into two parts: 1. For a given file, how can I remove the lines where Name identfier exists? 2. For a given file, how can I get two columns of data? This separation means that you don't have to solve the whole thing at once to see progress. If you do problem 2 first, then you can "hardcode" the input to something that problem 2 can deal with. That is, you can take a smaller version of your input file, and manually remove the 'name' lines. That way, you can still do problem 2 without getting stuck on problem1. And when you do get problem 1 done, then you can just drop the 'hardcoded' test data. What parts are you stuck on, and what have you tried so far? Do you know about using 'if' statements yet? What do you know about list manipulation so far? What about string manipulation? Please feel free to ask more questions. Good luck! From alan.gauld at freenet.co.uk Tue Dec 7 00:16:31 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Dec 7 00:15:54 2004 Subject: [Tutor] eval and exec References: <021901c4db23$f4ee4210$c6ca8751@xp> <41B407A1.6090402@po-box.mcgill.ca> Message-ID: <029e01c4dbe9$9f9d5e10$c6ca8751@xp> > > - MS allows Outlook to run scripts when mail is open, if > > those scripts are harmful we have a virus! That is (was, they've improved it a lot) the number one cause of script kiddie virii. Simply viewing a mail message in the preview pane was enough to trigger a script. They have improved security greatly in the recent patches though. But HTML mail has similar issues. If someone handcrafts an HTML message with some Javascript code then you are relying on your browsers sandbox technology to protect you. And if its Windows and WSH is enabled the script can read/write the registry... The ability to script documrnts is powerful, but potentially dangerous, just like eval/exec (which are how such capabilities are typically implemented!) Alan G. From carroll at tjc.com Tue Dec 7 01:57:13 2004 From: carroll at tjc.com (Terry Carroll) Date: Tue Dec 7 01:57:23 2004 Subject: [Tutor] Simple RPN calculator In-Reply-To: <20041206130506.47035.qmail@web54303.mail.yahoo.com> Message-ID: On Mon, 6 Dec 2004, Chad Crabtree wrote: > Bob Gailer wrote: > > > For grins I just wrote one that takes '1 2.3 - 3 4 5 + * /' as > input > > and prints -0.0481481.... 8 lines of Python. That indeed is less > than > > 100. Took about 7 minutes to code and test. > > I'm quite interested in seeing the sourcecode for that. Me, too. I'm always interested in cool little Python examples. From isrgish at fastem.com Tue Dec 7 05:06:04 2004 From: isrgish at fastem.com (Isr Gish) Date: Tue Dec 7 05:06:19 2004 Subject: [Tutor] Address book sort of Message-ID: <20041207040616.A072C1E4003@bag.python.org> It was posted recently that pickleing should use binary mode. See changes in code. Rick Muller wrote: > >from cPickle import load, dump > >def save(fname,addressbook): > file = open(filename,'w') file = open(filename,'wb') > dump(addressbook,file) > file.close() > return > >def read(fname): > file = open(filename) file = open(filename, 'rb') > addressbook = load(file) > file.close() > return addressbook All the best Isr From jinlin555 at msn.com Tue Dec 7 05:37:20 2004 From: jinlin555 at msn.com (Lin Jin) Date: Tue Dec 7 05:38:04 2004 Subject: [Tutor] about recursion code Message-ID: hello,tutors: i am working on the recursion of selection sort,and my code is: def selection_sort(lst,start,end): """sort the lst from selection start to end""" if len(lst)==1: return lst elif lst=="": return "" else: return lst[:start]+selection_sort(lst,start+1,end) a=[1,3,5,2] b=1 c=3 print selection_sort(a,b,c) but it seems not working when i call the function,anyone could tell me that what i did wrong with my code? _________________________________________________________________ ÏíÓÃÊÀ½çÉÏ×î´óµÄµç×ÓÓʼþϵͳ¡ª MSN Hotmail¡£ http://www.hotmail.com From guillermo.fernandez.castellanos at gmail.com Tue Dec 7 06:25:55 2004 From: guillermo.fernandez.castellanos at gmail.com (Guillermo Fernandez Castellanos) Date: Tue Dec 7 06:25:58 2004 Subject: [Tutor] about recursion code In-Reply-To: References: Message-ID: <7d7029e70412062125465690d2@mail.gmail.com> Usually, in case of doubt, use a debugger or print statements: def selection_sort(lst,start,end): """sort the lst from selection start to end""" print lst, start, end if len(lst)==1: print "list of size 1" return lst elif lst=="": print "list is an emtpy string" return "" else: print "selection_sort(",lst,start+1,end,")" return lst[:start]+selection_sort(lst,start+1,end) Let's see what happens: >>> a=[1,3,5,2] >>> b=1 >>> c=3 >>> selection_sort(a,b,c) [1, 3, 5, 2] 1 3 selection_sort( [1, 3, 5, 2] 2 3 ) [1, 3, 5, 2] 2 3 selection_sort( [1, 3, 5, 2] 3 3 ) [1, 3, 5, 2] 3 3 selection_sort( [1, 3, 5, 2] 4 3 ) [1, 3, 5, 2] 4 3 selection_sort( [1, 3, 5, 2] 5 3 ) [1, 3, 5, 2] 5 3 selection_sort( [1, 3, 5, 2] 6 3 ) [1, 3, 5, 2] 6 3 selection_sort( [1, 3, 5, 2] 7 3 ) [1, 3, 5, 2] 7 3 Etc,etc,etc It seems that you are incrementing the start variable. This is done in the line of code: return lst[:start]+selection_sort(lst,start+1,end) If we arrive to this line of code is because of the conditions of the two previous "if": - The list is not of size 1. - The list is not an empty string. Actually, when you do a recursion function you must make sure you have an exit condition. And your function does not have. If you want your function to end, it must arrive at one point to a size of 1 or to be an empty string. I did this by changing the line: return lst[:start]+selection_sort(lst,start+1,end) into the line: return lst[:start]+selection_sort(lst[start:],start+1,end) Oh... I am also wandering why you look for an empty string. You would be better off by substituing "" by an empty list [] elif lst==[]: print "list is emtpy" return [] You can even put togheter this line with the if len(lst)==1: line: if len(lst)==1: print "list of size 1" return lst elif lst==[]: print "list is emtpy" return [] becomes if 0>> def selection_sort(lst,start,end): """sort the lst from selection start to end""" print lst, start, end if 0<=len(lst)<2: print "list of size 1 or less" return lst else: print "selection_sort(",lst,start+1,end,")" return lst[:start]+selection_sort(lst[start:],start+1,end) >>> selection_sort_modified(a,b,c) [1, 3, 5, 2] 1 3 selection_sort( [1, 3, 5, 2] 2 3 ) [3, 5, 2] 2 3 selection_sort( [3, 5, 2] 3 3 ) [2] 3 3 list of size 1 [1, 3, 5, 2] >>> a=[1,6,2,2,5,3,9,0,3,4] >>> b=3 >>> c=8 >>> selection_sort(a,b,c) [1, 6, 2, 2, 5, 3, 9, 0, 3, 4] 3 8 selection_sort( [1, 6, 2, 2, 5, 3, 9, 0, 3, 4] 4 8 ) [2, 5, 3, 9, 0, 3, 4] 4 8 selection_sort( [2, 5, 3, 9, 0, 3, 4] 5 8 ) [0, 3, 4] 5 8 selection_sort( [0, 3, 4] 6 8 ) [] 6 8 list of size 1 or less [1, 6, 2, 2, 5, 3, 9, 0, 3, 4] Hope that helps, G On Tue, 07 Dec 2004 12:37:20 +0800, Lin Jin wrote: > hello,tutors: > i am working on the recursion of selection sort,and my code is: > def selection_sort(lst,start,end): > """sort the lst from selection start to end""" > if len(lst)==1: > return lst > elif lst=="": > return "" > else: > return lst[:start]+selection_sort(lst,start+1,end) > a=[1,3,5,2] > b=1 > c=3 > print selection_sort(a,b,c) > > but it seems not working when i call the function,anyone could tell me that > what i did wrong with my code? > > _________________________________________________________________ > ??????????????? MSN Hotmail? http://www.hotmail.com > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From rdm at rcblue.com Tue Dec 7 10:41:05 2004 From: rdm at rcblue.com (Dick Moores) Date: Tue Dec 7 10:41:16 2004 Subject: [Tutor] Python 2.3.5 out in January?? Message-ID: <6.1.2.0.2.20041207012905.049ac550@rcblue.com> Just saw this on comp.lang.python.announce. I don't understand this. Why is a new version of 2.3 being worked on after 2.4 has been released? I see Tim Peters has said this on python-list: ===========begin Tim Peters' post=========== [Brett C] >> Anthony Baxter, our ever-diligent release manager, mentioned this past week >> that Python 2.3.5 will most likely come to fruition some time in January >> (this is not guaranteed date). [Roy Smith] > Interesting. Does that mean that 2.3 and 2.4 will be maintained in > parallel for a while? That would be awesome. They'll be maintained in parallel through 2.3.5 in January, which is all Brett said. If history is a guide, after 2.3.5 nobody will volunteer to work on a 2.3.6, and 2.3.5 will be the last release in the 2.3 line. It's *possible* that volunteers for 2.3.6 will appear. That would be unprecedented, but not impossible ... ============end TP's post================ I ask here because I'm sure it's a newbie question. It's got me wondering if Microsoft is still working on Windows 3.1.. ;-) Thanks, Dick Moores rdm@rcblue.com From cyresse at gmail.com Tue Dec 7 11:26:31 2004 From: cyresse at gmail.com (Liam Clarke) Date: Tue Dec 7 11:26:34 2004 Subject: [Tutor] Python 2.3.5 out in January?? In-Reply-To: <6.1.2.0.2.20041207012905.049ac550@rcblue.com> References: <6.1.2.0.2.20041207012905.049ac550@rcblue.com> Message-ID: Sometimes I suspect XP is the latest 3.11 beta. ;) On Tue, 07 Dec 2004 01:41:05 -0800, Dick Moores wrote: > Just saw this on comp.lang.python.announce. > > > I don't understand this. Why is a new version of 2.3 being worked on > after 2.4 has been released? > > I see Tim Peters has said this on python-list: > ===========begin Tim Peters' post=========== > [Brett C] > >> Anthony Baxter, our ever-diligent release manager, mentioned this > past week > >> that Python 2.3.5 will most likely come to fruition some time in January > >> (this is not guaranteed date). > > [Roy Smith] > > Interesting. Does that mean that 2.3 and 2.4 will be maintained in > > parallel for a while? That would be awesome. > > They'll be maintained in parallel through 2.3.5 in January, which is > all Brett said. If history is a guide, after 2.3.5 nobody will > volunteer to work on a 2.3.6, and 2.3.5 will be the last release in > the 2.3 line. It's *possible* that volunteers for 2.3.6 will appear. > That would be unprecedented, but not impossible ... > ============end TP's post================ > > I ask here because I'm sure it's a newbie question. It's got me wondering > if Microsoft is still working on Windows 3.1.. ;-) > > Thanks, > > Dick Moores > rdm@rcblue.com > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From kent37 at tds.net Tue Dec 7 11:54:01 2004 From: kent37 at tds.net (Kent Johnson) Date: Tue Dec 7 11:54:01 2004 Subject: [Tutor] Python 2.3.5 out in January?? In-Reply-To: <6.1.2.0.2.20041207012905.049ac550@rcblue.com> References: <6.1.2.0.2.20041207012905.049ac550@rcblue.com> Message-ID: <41B58BC9.8090703@tds.net> I think the idea is to back-port bugfixes from 2.4 to 2.3. Then that is the end of the line for 2.3. Kent Dick Moores wrote: > Just saw this on comp.lang.python.announce. > > > I don't understand this. Why is a new version of 2.3 being worked on > after 2.4 has been released? > > I see Tim Peters has said this on python-list: > ===========begin Tim Peters' post=========== > [Brett C] > >> Anthony Baxter, our ever-diligent release manager, mentioned this > past week > >> that Python 2.3.5 will most likely come to fruition some time in > January > >> (this is not guaranteed date). > > [Roy Smith] > > Interesting. Does that mean that 2.3 and 2.4 will be maintained in > > parallel for a while? That would be awesome. > > They'll be maintained in parallel through 2.3.5 in January, which is > all Brett said. If history is a guide, after 2.3.5 nobody will > volunteer to work on a 2.3.6, and 2.3.5 will be the last release in > the 2.3 line. It's *possible* that volunteers for 2.3.6 will appear. > That would be unprecedented, but not impossible ... > ============end TP's post================ > > I ask here because I'm sure it's a newbie question. It's got me > wondering if Microsoft is still working on Windows 3.1.. ;-) > > Thanks, > > Dick Moores > rdm@rcblue.com > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From cyresse at gmail.com Tue Dec 7 12:03:15 2004 From: cyresse at gmail.com (Liam Clarke) Date: Tue Dec 7 12:03:18 2004 Subject: [Tutor] String matching? Message-ID: Hi all, I have a large amount of HTML that a previous person has liberally sprinkled a huge amount of applets through, instead of html links, which kills my browser to open. So, want to go through and replace all applets with nice simple links, and want to use Python to find the applet, extract a name and an URL, and create the link. My problem is, somewhere in my copying and pasting into the text file that the HTMl currently resides in, it got all messed up it would seem, and there's a bunch of strange '=' all through it. (Someone said that the code had been generated in Frontpage. Is that a good thing or bad thing?) So, I want to search for To Liam and Brian, Liam, actually, Brian did Sunday. See his post in this thread of Date: Sun, 05 Dec 2004 19:53:01 -0500. But you've done is interesting, and I thank you. Here's Brian's script in it's bare bones, without the input error checking and his extensive and helpful comments: ===============begin code==================== import datetime import time alarm_time = raw_input("Enter alarm time as hh:mm ") alarm_time_list = alarm_time.split(':') alarm_hour, alarm_minute = (int(alarm_time_list[0]), int(alarm_time_list[1])) now = datetime.datetime.now() alarm_datetime = datetime.datetime(now.year+4, now.month, now.day, alarm_hour, alarm_minute) print alarm_datetime alarm_in_seconds = (alarm_datetime - now).seconds print "I should wake up in %d seconds" % alarm_in_seconds time.sleep(alarm_in_seconds) print "I'm awake!" ================end code===================== You can see that he gets the number-of-seconds difference directly with the line, "alarm_in_seconds = (alarm_datetime - now).seconds", and doesn't need to compute the seconds to sleep from the difference expressed as hours, minutes and seconds. I like your alarm clock a lot, . I first tried to run it with IDLE, then remembered that mscvrt won't catch keypresses if run with IDLE. Works fine in the console! Instead of your beeps in the second while loop, I think I'd need winsound.PlaySound('SystemAsterisk', winsound.SND_ALIAS) winsound.PlaySound('SystemHand', winsound.SND_ALIAS) and turn my speakers way up! Brian, where did you learn about the ".seconds". And the .year, .month, .day of "alarm_datetime = datetime.datetime(now.year + 4, now.month, now.day, alarm_hour, alarm_minute)"? Does this come from a general knowledge of OOP, or is it somewhere in the Python docs? The only thing I've seen, and it's not an explanation, is in note (1) on http://docs.python.org/lib/datetime-date.html It seems I've missed out on something important BTW I'm not sure you need the +4 of "now.year + 4". I've run this without the +4 and it doesn't seem to be needed. And notes (1) and (4) on that page seem to say this, as far as I understand them. Dick Liam Clarke wrote at 03:56 12/6/2004: >Hey Dick, don't know if anyone actually answered your original question. > > >IOW, is there an easier way to calculate the time difference between the > >time now, say 08:51 and say, tomorrow at 03:45, to take an example of the > >most difficult case? > >So, you need two datetime.datetime objects. > > >>>now = datetime.datetime(year, month, day, hours, minutes, seconds) > >>>now = datetime.datetime(2004, 12, 7*, 8*, 51, 00) > >>> later= datetime.datetime(2004, 12, 8*, 3*, 45, 00) > > *Can't start with zero. Must be 8 not 08 > > >>> difference = later - now > >>> print difference >18:54:00 > >>> type(difference) > > >>> timeList=str(difference).split(":") > >>> print timeList >['18', '54', '00'] > >>> > timeinSecs=(int(timeList[0])*3600)+(int(timeList[1])*60)+int(timeList[2]) > >>> print timeinSecs >68040 > >Now, to check if that's right... > > >>> timeChange=datetime.timedelta(seconds=68040) > >>> checkVal=now + timeChange > >>> print checkVal >2004-12-08 03:45:00 > >Looks good to me. > >So, to summarise the code part - > >now = datetime.datetime(2004, 12, 7, 8, 51, 00) >later= datetime.datetime(2004, 12, 8, 3, 45, 00) >difference = later - now >timeList=str(difference).split(":") >timeinSecs=(int(timeList[0])*3600)+(int(timeList[1])*60)+int(timeList[2]) > >And that's the easier way to find the difference between two times in >seconds. > >HTH > >Liam Clarke > >P.S. If you're interested, here's a 20 line alarm clock I wrote >because my one broke this morning. > >http://www.rafb.net/paste/results/ctOH1T36.html From kent37 at tds.net Tue Dec 7 13:58:37 2004 From: kent37 at tds.net (Kent Johnson) Date: Tue Dec 7 13:58:46 2004 Subject: [Tutor] String matching? In-Reply-To: References: Message-ID: <41B5A8FD.6030006@tds.net> Regular expressions are a bit tricky to understand but well worth the trouble - they are a powerful tool. The Regex HOW-TO is one place to start: http://www.amk.ca/python/howto/regex/ Of course, Jamie Zawinsky famously said, "Some people, when confronted with a problem, think 'I know, I'll use regular expressions.' Now they have two problems." You can do a lot of cleanup with a few simple string substitutions: test = ''' a(=\n)?p(=\n)?p(=\n)?l(=\n)?e(=\n)?t The (=\n)? between each pair of letters means, optionally match =\n here. You can use re.finditer to show all the matches: import re for match in re.finditer(appRe, test): print print match.group(0) => app= let applet ap= plet A couple other options: elementtidy reads HTML, cleans it up and creates a tree model of the source. You can easily modify the tree model and write it out again. This has the bonus of giving you well-formed XHTML at the end of the process. It is based on HTML Tidy and Fredrik Lundh's elementtree package which is very easy to use. http://www.effbot.org/zone/element-tidylib.htm Beautiful Soup is an HTML parser that is designed to read bad HTML and give access to the tags. I'm not sure if it gives you any help for rewriting, though. http://www.crummy.com/software/BeautifulSoup/ HTH Kent Liam Clarke wrote: > Hi all, > > I have a large amount of HTML that a previous person has liberally > sprinkled a huge amount of applets through, instead of html links, > which kills my browser to open. > > So, want to go through and replace all applets with nice simple links, > and want to use Python to find the applet, extract a name and an URL, > and create the link. > > My problem is, somewhere in my copying and pasting into the text file > that the HTMl currently resides in, it got all messed up it would > seem, and there's a bunch of strange '=' all through it. (Someone said > that the code had been generated in Frontpage. Is that a good thing or > bad thing?) > > So, I want to search for > let > code > > or code > > or plet > > etc. etc. (Full example of yuck here > http://www.rafb.net/paste/results/WcKPCy64.html) > > So, I want to be write a search that will match > I was thinking the re module is for this sort of stuff? Truth is, I > wouldn't know where to begin with it, it seems somewhat powerful. > > Or, there's a much easier way, which I'm missing totally. If there is, > I'd be very grateful for pointers. > > Thanks for any help you can offer. > > Liam Clarke > From orbitz at ezabel.com Tue Dec 7 15:03:45 2004 From: orbitz at ezabel.com (orbitz) Date: Tue Dec 7 15:03:55 2004 Subject: [Tutor] String matching? In-Reply-To: References: Message-ID: <41B5B841.2060408@ezabel.com> Instead of copying and pasting and then just doing a simple match, why not use urllib2 to download the html and then run through it with HTMLParse? Liam Clarke wrote: >Hi all, > >I have a large amount of HTML that a previous person has liberally >sprinkled a huge amount of applets through, instead of html links, >which kills my browser to open. > >So, want to go through and replace all applets with nice simple links, >and want to use Python to find the applet, extract a name and an URL, >and create the link. > >My problem is, somewhere in my copying and pasting into the text file >that the HTMl currently resides in, it got all messed up it would >seem, and there's a bunch of strange '=' all through it. (Someone said >that the code had been generated in Frontpage. Is that a good thing or >bad thing?) > >So, I want to search for >let > code > >or code > >or plet > >etc. etc. (Full example of yuck here >http://www.rafb.net/paste/results/WcKPCy64.html) > >So, I want to be write a search that will match >I was thinking the re module is for this sort of stuff? Truth is, I >wouldn't know where to begin with it, it seems somewhat powerful. > >Or, there's a much easier way, which I'm missing totally. If there is, >I'd be very grateful for pointers. > >Thanks for any help you can offer. > >Liam Clarke > > > From ps_python at yahoo.com Tue Dec 7 16:22:29 2004 From: ps_python at yahoo.com (kumar s) Date: Tue Dec 7 16:22:33 2004 Subject: [Tutor] Printing two elements in a list Message-ID: <20041207152230.68855.qmail@web53703.mail.yahoo.com> Dear group, I have two lists names x and seq. I am trying to find element of x in element of seq. I find them. However, I want to print element in seq that contains element of x and also the next element in seq. So I tried this piece of code and get and error that str and int cannot be concatenated >>> for ele1 in x: for ele2 in seq: if ele1 in ele2: print (seq[ele1+1]) Traceback (most recent call last): File "", line 4, in -toplevel- print (seq[ele1+1]) TypeError: cannot concatenate 'str' and 'int' objects 2. TRIAL TWO: >>> for ele1 in x: for ele2 in seq: if ele2 in range(len(seq)): if ele1 in ele2: print seq[ele2+1] This is taking forever and I am not getting an answer. 3. TRIAL 3: I just asked to print the element in seq that matched element 1 in X. It prints only that element, however I want to print the next element too and I cannot get it. >>> for ele1 in x: for ele2 in seq: if ele1 in ele2: print ele2 >probe:HG-U95Av2:31358_at:454:493; Interrogation_Position=132; Antisense; >probe:HG-U95Av2:31358_at:319:607; Interrogation_Position=144; Antisense; >>> len(x) 4504 >>> x[1:10] ['454:494', '319:607', '319:608', '322:289', '322:290', '183:330', '183:329', '364:95', '364:96'] >>> len(seq) 398169 >>> seq[0:4] ['>probe:HG-U95Av2:1000_at:399:559; Interrogation_Position=1367; Antisense;', 'TCTCCTTTGCTGAGGCCTCCAGCTT', '>probe:HG-U95Av2:1000_at:544:185; Interrogation_Position=1379; Antisense;', 'AGGCCTCCAGCTTCAGGCAGGCCAA'] >>> for ele1 in x: for ele2 in seq: if ele1 in ele2: print ele2 >probe:HG-U95Av2:31358_at:454:493; Interrogation_Position=132; Antisense; >probe:HG-U95Av2:31358_at:319:607; Interrogation_Position=144; Antisense; How Do I WANT: I want to print get an output like this: >probe:HG-U95Av2:1000_at:399:559; Interrogation_Position=1367; Antisense;' TCTCCTTTGCTGAGGCCTCCAGCTT >probe:HG-U95Av2:1000_at:544:185; Interrogation_Position=1379; Antisense; AGGCCTCCAGCTTCAGGCAGGCCAA can any one please suggest what is going wrong in my statements and how can I get it. Thank you. Kumar __________________________________ Do you Yahoo!? Yahoo! Mail - 250MB free storage. Do more. Manage less. http://info.mail.yahoo.com/mail_250 From tim.peters at gmail.com Tue Dec 7 16:33:59 2004 From: tim.peters at gmail.com (Tim Peters) Date: Tue Dec 7 16:34:03 2004 Subject: [Tutor] Re: Could I have used time or datetime modules here? In-Reply-To: <6.1.2.0.2.20041207040419.0480a490@rcblue.com> References: <6.1.2.0.2.20041207040419.0480a490@rcblue.com> Message-ID: <1f7befae041207073326bcec8a@mail.gmail.com> [Dick Moores] ... > Brian, where did you learn about the ".seconds". And > the .year, .month,.day of > > "alarm_datetime = datetime.datetime(now.year + 4, now.month, > now.day, alarm_hour, alarm_minute)"? > > Does this come from a general knowledge of OOP, or is it > somewhere in the Python docs? The only thing I've seen, and it's > not an explanation, is in note (1) on > http://docs.python.org/lib/datetime-date.html On that very page, the instance attributes of datetime objects are documented: """ Instance attributes (read-only): year Between MINYEAR and MAXYEAR inclusive. month Between 1 and 12 inclusive. day Between 1 and the number of days in the given month of the given year. """ That's how you know that a datetime instance d has d.year, d.month and d.day attributes, and how you know what they mean. The docs for the other datetime module objects have similar sections. From bvande at po-box.mcgill.ca Tue Dec 7 16:50:49 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Tue Dec 7 16:54:46 2004 Subject: [Tutor] Re: Could I have used time or datetime modules here? In-Reply-To: <6.1.2.0.2.20041207040419.0480a490@rcblue.com> References: <6.1.2.0.2.20041207040419.0480a490@rcblue.com> Message-ID: <41B5D159.3030809@po-box.mcgill.ca> Dick Moores said unto the world upon 2004-12-07 07:04: > To Liam and Brian, > Here's Brian's script in it's bare bones, without the input error > checking and his extensive and helpful comments: > > ===============begin code==================== > import datetime > import time > > alarm_time = raw_input("Enter alarm time as hh:mm ") > alarm_time_list = alarm_time.split(':') > alarm_hour, alarm_minute = (int(alarm_time_list[0]), > int(alarm_time_list[1])) > now = datetime.datetime.now() > alarm_datetime = datetime.datetime(now.year+4, now.month, now.day, > alarm_hour, alarm_minute) > print alarm_datetime > alarm_in_seconds = (alarm_datetime - now).seconds > print "I should wake up in %d seconds" % alarm_in_seconds > time.sleep(alarm_in_seconds) > print "I'm awake!" > ================end code===================== > > Brian, where did you learn about the ".seconds". And the .year, .month, > .day of > > "alarm_datetime = datetime.datetime(now.year + 4, now.month, now.day, > alarm_hour, alarm_minute)"? > > Does this come from a general knowledge of OOP, or is it somewhere in > the Python docs? The only thing I've seen, and it's not an explanation, > is in note (1) on http://docs.python.org/lib/datetime-date.html Oh Sir, you flatter me! My general knowledge of OOP is about the same as my general knowledge of the migration patterns of Siberian water-fowl. ;-) After Anna, Gon?alo, and Liam encouraged me to explore the datetime module, I read (OK, skimmed) the docs. For my original purpose, I just needed to test two times with '>', but I recalled something about timedelta objects being returned by subtracting one datetime from another. I hadn't used them before I wrote my script in reply to you. I learned about the handy for your purposes .seconds attribute in the Library Reference -- 6.10.2 timedelta Objects. (That's the section name in the 2.4 installed docs; I'm typing off line so can't [OK, won't] get a link.) > It seems I've missed out on something important > > BTW I'm not sure you need the +4 of "now.year + 4". I've run this > without the +4 and it doesn't seem to be needed. And notes (1) and (4) > on that page seem to say this, as far as I understand them. I'm not sure I do either :-) Here's why I did it: I discovered that in order to get the right "seconds until alarm" value from the datetime for now and the alarm datetime by subtracting one datetime object from another, I needed the alarm datetime to be in the future. But, since you can set an alarm for 09:00 tomorrow at 22:00 today, I needed the alarm datetime to not use today's date. (If you use today's, you end up with seconds *since* 09:00 this morning, not the desired seconds *until* 09:00 tomorrow morning.) Since timedelta_object.seconds discards all difference save the seconds save those from the hours, minutes, and seconds difference in the two datetime objects, it doesn't matter what date the alarm datetime is set to. (The day information is in timedelta_object.days.) Or, so I thought. I'd first tried getting the alarm datetime by simply taking the date component of datetime.datetime.now() and adding to the day value. That works fine, provided you are not on the last day of the month. But, when checking boundary cases before posting the code I sent, I discovered this sort of thing: >>> last_day_of_june = datetime.datetime(2004, 6, 30) # long for clarity >>> ldj = last_day_of_june # short for typing >>> new_day = datetime.datetime(ldj.year, ldj.month, ldj.day + 1) Traceback (most recent call last): File "", line 1, in -toplevel- new_day = datetime.datetime(ldj.year, ldj.month, ldj.day + 1) ValueError: day is out of range for month >>> So, adding to the day or the month was out, unless I wanted elaborate code to determine which to add to under what circumstances. So then I thought, "Well, just change from now.day + 1 to now.year + 1, and all problems go away". And then I thought "Ah, but what if I try to run the script on Feb. 29? So, that's why I used now.year + 4. It still leaves open the possibility of getting bit by the every so often further correction to the calender, but, I *believe* the next one is due in 2100, so I think I can live with it. ;-) I'm not saying it isn't hackish, though. Better ways surely exist. Best to all, Brian vdB From kent37 at tds.net Tue Dec 7 16:59:53 2004 From: kent37 at tds.net (Kent Johnson) Date: Tue Dec 7 16:59:58 2004 Subject: [Tutor] Printing two elements in a list In-Reply-To: <20041207152230.68855.qmail@web53703.mail.yahoo.com> References: <20041207152230.68855.qmail@web53703.mail.yahoo.com> Message-ID: <41B5D379.1040700@tds.net> kumar s wrote: > Dear group, > I have two lists names x and seq. > > I am trying to find element of x in element of seq. I > find them. However, I want to print element in seq > that contains element of x and also the next element > in seq. > > > So I tried this piece of code and get and error that > str and int cannot be concatenated > >>>>for ele1 in x: > > for ele2 in seq: > if ele1 in ele2: > print (seq[ele1+1]) You are confusing the elements themselves with their indices. The problem here is that ele1 is a string - an element of x - not a number, which is what you need for an index. >>>>for ele1 in x: > > for ele2 in seq: > if ele2 in range(len(seq)): > if ele1 in ele2: > print seq[ele2+1] Now ele2 is a number, so 'if ele1 in ele2' is never true. > 3. TRIAL 3: > I just asked to print the element in seq that matched > element 1 in X. It prints only that element, however > I want to print the next element too and I cannot get > it. > >>>>for ele1 in x: > > for ele2 in seq: > if ele1 in ele2: > print ele2 The enumerate function is useful here. enumerate(seq) returns a sequence of (index, element) pairs. So you could write for ele1 in x: for index, ele2 in enumerate(seq): if ele1 in ele2: print ele2 print seq[index+1] Kent From mhansen at cso.atmel.com Tue Dec 7 17:27:27 2004 From: mhansen at cso.atmel.com (Mike Hansen) Date: Tue Dec 7 17:28:04 2004 Subject: [Tutor] Python 2.4 IDLE Windows 2000 In-Reply-To: References: Message-ID: <41B5D9EF.1090003@cso.atmel.com> Danny Yoo wrote: >On Fri, 3 Dec 2004, Mike Hansen wrote: > > > >>That rooted out the problem. A while ago, I changed the colors to kind >>of match my VIM color theme(ps_color). When I did >>idlelib.PyShell.main(), IDLE came up with my custom color theme. >>However, there was a bunch of warnings about my theme. From IDLE, I >>deleted the theme. Now IDLE will launch normally. I'll set up the color >>theme later. Maybe older color themes aren't compatible with the newer >>IDLE? The color theme must have been laying around. I didn't brute force >>it in or anything like that. >> >> > > >Hi Mike, > >Ah, whew, I'm glad that actually worked. *grin* > >The information about the color theme problem is valuable to know: can you >send a message to the IDLE developers with a summary of the situation? >It's possible that a lot of other folks might be running into a similar >startup problem. Let's make sure that no one else has to go through hoops >to get IDLE working again. The IDLE development list is: > > http://mail.python.org/mailman/listinfo/idle-dev > >Good luck to you! > > > Hi Danny, I put in a bug report on the python sourceforge site. The idle-dev mail list didn't seem appropriate. It seems like a mail list for idle developers to discuss the IDLE development plan not for users to post about bugs. Thanks again for your help on this issue. Mike From tim.peters at gmail.com Tue Dec 7 17:45:55 2004 From: tim.peters at gmail.com (Tim Peters) Date: Tue Dec 7 17:45:58 2004 Subject: [Tutor] Re: Could I have used time or datetime modules here? In-Reply-To: <41B5D159.3030809@po-box.mcgill.ca> References: <6.1.2.0.2.20041207040419.0480a490@rcblue.com> <41B5D159.3030809@po-box.mcgill.ca> Message-ID: <1f7befae0412070845213959db@mail.gmail.com> [Brian van den Broek] ... > Or, so I thought. I'd first tried getting the alarm datetime by simply > taking the date component of datetime.datetime.now() and adding > to the day value. That works fine, provided you are not on the last > day of the month. But, when checking boundary cases before > posting the code I sent, I discovered this sort of thing: > > >>> last_day_of_june = datetime.datetime(2004, 6, 30) # long for clarity > >>> ldj = last_day_of_june # short for typing > >>> new_day = datetime.datetime(ldj.year, ldj.month, ldj.day + 1) > > Traceback (most recent call last): > File "", line 1, in -toplevel- > new_day = datetime.datetime(ldj.year, ldj.month, ldj.day + 1) > ValueError: day is out of range for month > >>> > > So, adding to the day or the month was out, unless I wanted > elaborate code to determine which to add to under what > circumstances. Actually, you needed simpler code : >>> import datetime >>> ldj = datetime.datetime(2004, 6, 30) >>> new_day = ldj + datetime.timedelta(days=1) >>> print new_day 2004-07-01 00:00:00 or even >>> ldy = datetime.datetime(2004, 12, 31) >>> new_day = ldy + datetime.timedelta(days=1) >>> print new_day 2005-01-01 00:00:00 In other words, if you want to move to the next day, add one day! That always does the right thing. Subtracting one day moves to the previous day, and so on. From rdm at rcblue.com Tue Dec 7 18:04:46 2004 From: rdm at rcblue.com (Dick Moores) Date: Tue Dec 7 18:04:56 2004 Subject: [Tutor] Re: Could I have used time or datetime modules here? In-Reply-To: <41B5D159.3030809@po-box.mcgill.ca> References: <6.1.2.0.2.20041207040419.0480a490@rcblue.com> <41B5D159.3030809@po-box.mcgill.ca> Message-ID: <6.1.2.0.2.20041130082123.07ab1270@rcblue.com> Brian van den Broek wrote at 07:50 12/7/2004: >Dick Moores said unto the world upon 2004-12-07 07:04: >>To Liam and Brian, > > > >>Here's Brian's script in it's bare bones, without the input error >>checking and his extensive and helpful comments: >>===============begin code==================== >>import datetime >>import time >>alarm_time = raw_input("Enter alarm time as hh:mm ") >>alarm_time_list = alarm_time.split(':') >>alarm_hour, alarm_minute = (int(alarm_time_list[0]), >> int(alarm_time_list[1])) >>now = datetime.datetime.now() >>alarm_datetime = datetime.datetime(now.year+4, now.month, now.day, >> alarm_hour, alarm_minute) >>print alarm_datetime >>alarm_in_seconds = (alarm_datetime - now).seconds >>print "I should wake up in %d seconds" % alarm_in_seconds >>time.sleep(alarm_in_seconds) >>print "I'm awake!" >>================end code===================== > > > >>Brian, where did you learn about the ".seconds". And the .year, .month, >>.day of >>"alarm_datetime = datetime.datetime(now.year + 4, now.month, now.day, >> alarm_hour, alarm_minute)"? >>Does this come from a general knowledge of OOP, or is it somewhere in >>the Python docs? The only thing I've seen, and it's not an explanation, >>is in note (1) on http://docs.python.org/lib/datetime-date.html > >Oh Sir, you flatter me! My general knowledge of OOP is about the same as >my general knowledge of the migration patterns of Siberian water-fowl. ;-) > >After Anna, Gon?alo, and Liam encouraged me to explore the datetime >module, I read (OK, skimmed) the docs. For my original purpose, I just >needed to test two times with '>', but I recalled something about >timedelta objects being returned by subtracting one datetime from >another. I hadn't used them before I wrote my script in reply to you. I >learned about the handy for your purposes .seconds attribute in the >Library Reference -- 6.10.2 timedelta Objects. (That's the section name >in the 2.4 installed docs; I'm typing off line so can't [OK, won't] get >a link.) > >>It seems I've missed out on something important >>BTW I'm not sure you need the +4 of "now.year + 4". I've run this >>without the +4 and it doesn't seem to be needed. And notes (1) and (4) >>on that page seem to say this, as far as I understand them. > >I'm not sure I do either :-) > >Here's why I did it: > >I discovered that in order to get the right "seconds until alarm" value >from the datetime for now and the alarm datetime by subtracting one >datetime object from another, I needed the alarm datetime to be in the >future. But, since you can set an alarm for 09:00 tomorrow at 22:00 >today, I needed the alarm datetime to not use today's date. (If you use >today's, you end up with seconds *since* 09:00 this morning, not the >desired seconds *until* 09:00 tomorrow morning.) Since >timedelta_object.seconds discards all difference save the seconds save >those from the hours, minutes, and seconds difference in the two >datetime objects, it doesn't matter what date the alarm datetime is set >to. (The day information is in timedelta_object.days.) > >Or, so I thought. I'd first tried getting the alarm datetime by simply >taking the date component of datetime.datetime.now() and adding to the >day value. That works fine, provided you are not on the last day of the >month. But, when checking boundary cases before posting the code I sent, >I discovered this sort of thing: > > >>> last_day_of_june = datetime.datetime(2004, 6, 30) # long for clarity > >>> ldj = last_day_of_june # short for typing > >>> new_day = datetime.datetime(ldj.year, ldj.month, ldj.day + 1) > >Traceback (most recent call last): > File "", line 1, in -toplevel- > new_day = datetime.datetime(ldj.year, ldj.month, ldj.day + 1) >ValueError: day is out of range for month > >>> > >So, adding to the day or the month was out, unless I wanted elaborate >code to determine which to add to under what circumstances. So then I >thought, "Well, just change from now.day + 1 to now.year + 1, and all >problems go away". And then I thought "Ah, but what if I try to run the >script on Feb. 29? > >So, that's why I used now.year + 4. It still leaves open the possibility >of getting bit by the every so often further correction to the calender, >but, I *believe* the next one is due in 2100, so I think I can live with >it. ;-) > >I'm not saying it isn't hackish, though. Better ways surely exist. Brian, I just can't succeed in reproducing the problems with the boundary cases with the +4 removed. I've tried setting my computer's clock to Nov 30, Feb 29, 2004, and Dec 31, 2004 (without changing the time). It's now about 9 am where I am, and setting the alarm time to 0700 (i.e., on the next day) works fine in all 3 cases. And of course no problem at today's date with setting the alarm time to 07:00. Isn't that what that note (1) on implies? I did the testing with , by remarking out the time.sleep() line and noting what the print_hms(sleepSeconds) function prints. Dick From bgailer at alum.rpi.edu Tue Dec 7 18:29:51 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue Dec 7 18:28:56 2004 Subject: [Tutor] Printing two elements in a list In-Reply-To: <20041207152230.68855.qmail@web53703.mail.yahoo.com> References: <20041207152230.68855.qmail@web53703.mail.yahoo.com> Message-ID: <6.2.0.14.0.20041207101837.0667c008@mail.mric.net> At 08:22 AM 12/7/2004, kumar s wrote: >Dear group, > I have two lists names x and seq. > >I am trying to find element of x in element of seq. I >find them. However, I want to print element in seq >that contains element of x and also the next element >in seq. > > >So I tried this piece of code and get and error that >str and int cannot be concatenated > >>> for ele1 in x: > for ele2 in seq: > if ele1 in ele2: > print (seq[ele1+1]) The problem here is that ele1 is a string, not an index into the list. There are a couple ways to fix this. match = False for ele1 in x: for ele2 in seq: if match: print ele2 match = False if ele1 in ele2: print ele2 match = True OR for ele1 in x: for index, ele2 in enumerate(seq): if ele1 in ele2: print ele2, seq[index+1] >[snip] Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From cyresse at gmail.com Tue Dec 7 18:50:22 2004 From: cyresse at gmail.com (Liam Clarke) Date: Tue Dec 7 18:50:26 2004 Subject: [Tutor] Re: Could I have used time or datetime modules here? In-Reply-To: <6.1.2.0.2.20041130082123.07ab1270@rcblue.com> References: <6.1.2.0.2.20041207040419.0480a490@rcblue.com> <41B5D159.3030809@po-box.mcgill.ca> <6.1.2.0.2.20041130082123.07ab1270@rcblue.com> Message-ID: Hi all, >I like your alarm clock a lot, >. I first tried to run >it with IDLE, then remembered that mscvrt won't catch keypresses if run >with IDLE. Works fine in the console! >Instead of your beeps in the second while loop, I think I'd need >winsound.PlaySound('SystemAsterisk', winsound.SND_ALIAS) >winsound.PlaySound('SystemHand', winsound.SND_ALIAS) >and turn my speakers way up! Heh, I use headphones, but speakers would be better. I'm sure you could play an mp3 also. But, I actually made a mistake in my alarm clock in that desiredTime.datetime.time(6,00,00) is now desiredTime=datetime.datetime(2004,12,8,6, 00, 00) while nowTime.time < desiredTime: is now while nowTime < desiredTime: because, I wrote the alarm clock after midnight! If I had run it before 11:59pm my while condition would've been True immediately, so I changed desiredTime to a datetime object. Alternatively, I could have just changed checkPeriod=5 #minutes nowTime=datetime.datetime.now() startTime=nowTime while nowTime.time() < desiredTime or nowTime.time() > startTime.time(): But Occam's Razor works better. >Brian, where did you learn about the ".seconds". And the .year, .month, >.day of What's funny, is that after I'd gone to bed that night, I suddenly woke up and thought "Hang on, what about the attribute .seconds of a datetime object? I better check that out." Which I promptly forgot about until your last reply. Heh. Liam Clarke On Tue, 07 Dec 2004 09:04:46 -0800, Dick Moores wrote: > Brian van den Broek wrote at 07:50 12/7/2004: > > > >Dick Moores said unto the world upon 2004-12-07 07:04: > >>To Liam and Brian, > > > > > > > >>Here's Brian's script in it's bare bones, without the input error > >>checking and his extensive and helpful comments: > >>===============begin code==================== > >>import datetime > >>import time > >>alarm_time = raw_input("Enter alarm time as hh:mm ") > >>alarm_time_list = alarm_time.split(':') > >>alarm_hour, alarm_minute = (int(alarm_time_list[0]), > >> int(alarm_time_list[1])) > >>now = datetime.datetime.now() > >>alarm_datetime = datetime.datetime(now.year+4, now.month, now.day, > >> alarm_hour, alarm_minute) > >>print alarm_datetime > >>alarm_in_seconds = (alarm_datetime - now).seconds > >>print "I should wake up in %d seconds" % alarm_in_seconds > >>time.sleep(alarm_in_seconds) > >>print "I'm awake!" > >>================end code===================== > > > > > > > >>Brian, where did you learn about the ".seconds". And the .year, .month, > >>.day of > >>"alarm_datetime = datetime.datetime(now.year + 4, now.month, now.day, > >> alarm_hour, alarm_minute)"? > >>Does this come from a general knowledge of OOP, or is it somewhere in > >>the Python docs? The only thing I've seen, and it's not an explanation, > >>is in note (1) on http://docs.python.org/lib/datetime-date.html > > > >Oh Sir, you flatter me! My general knowledge of OOP is about the same as > >my general knowledge of the migration patterns of Siberian water-fowl. ;-) > > > >After Anna, Gon?alo, and Liam encouraged me to explore the datetime > >module, I read (OK, skimmed) the docs. For my original purpose, I just > >needed to test two times with '>', but I recalled something about > >timedelta objects being returned by subtracting one datetime from > >another. I hadn't used them before I wrote my script in reply to you. I > >learned about the handy for your purposes .seconds attribute in the > >Library Reference -- 6.10.2 timedelta Objects. (That's the section name > >in the 2.4 installed docs; I'm typing off line so can't [OK, won't] get > >a link.) > > > >>It seems I've missed out on something important > >>BTW I'm not sure you need the +4 of "now.year + 4". I've run this > >>without the +4 and it doesn't seem to be needed. And notes (1) and (4) > >>on that page seem to say this, as far as I understand them. > > > >I'm not sure I do either :-) > > > >Here's why I did it: > > > >I discovered that in order to get the right "seconds until alarm" value > >from the datetime for now and the alarm datetime by subtracting one > >datetime object from another, I needed the alarm datetime to be in the > >future. But, since you can set an alarm for 09:00 tomorrow at 22:00 > >today, I needed the alarm datetime to not use today's date. (If you use > >today's, you end up with seconds *since* 09:00 this morning, not the > >desired seconds *until* 09:00 tomorrow morning.) Since > >timedelta_object.seconds discards all difference save the seconds save > >those from the hours, minutes, and seconds difference in the two > >datetime objects, it doesn't matter what date the alarm datetime is set > >to. (The day information is in timedelta_object.days.) > > > >Or, so I thought. I'd first tried getting the alarm datetime by simply > >taking the date component of datetime.datetime.now() and adding to the > >day value. That works fine, provided you are not on the last day of the > >month. But, when checking boundary cases before posting the code I sent, > >I discovered this sort of thing: > > > > >>> last_day_of_june = datetime.datetime(2004, 6, 30) # long for clarity > > >>> ldj = last_day_of_june # short for typing > > >>> new_day = datetime.datetime(ldj.year, ldj.month, ldj.day + 1) > > > >Traceback (most recent call last): > > File "", line 1, in -toplevel- > > new_day = datetime.datetime(ldj.year, ldj.month, ldj.day + 1) > >ValueError: day is out of range for month > > >>> > > > >So, adding to the day or the month was out, unless I wanted elaborate > >code to determine which to add to under what circumstances. So then I > >thought, "Well, just change from now.day + 1 to now.year + 1, and all > >problems go away". And then I thought "Ah, but what if I try to run the > >script on Feb. 29? > > > >So, that's why I used now.year + 4. It still leaves open the possibility > >of getting bit by the every so often further correction to the calender, > >but, I *believe* the next one is due in 2100, so I think I can live with > >it. ;-) > > > >I'm not saying it isn't hackish, though. Better ways surely exist. > > Brian, > > I just can't succeed in reproducing the problems with the boundary > cases with the +4 removed. I've tried setting my computer's clock to Nov > 30, Feb 29, 2004, and Dec 31, 2004 (without changing the time). It's now > about 9 am where I am, and setting the alarm time to 0700 (i.e., on the > next day) works fine in all 3 cases. And of course no problem at today's > date with setting the alarm time to 07:00. > > Isn't that what that note (1) on > implies? > > I did the testing with , > by remarking out the time.sleep() line and noting what the > print_hms(sleepSeconds) function prints. > > Dick > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only ba.>sic human duty, to take the consequences. From cyresse at gmail.com Tue Dec 7 18:52:21 2004 From: cyresse at gmail.com (Liam Clarke) Date: Tue Dec 7 18:52:25 2004 Subject: [Tutor] Re: Could I have used time or datetime modules here? In-Reply-To: References: <6.1.2.0.2.20041207040419.0480a490@rcblue.com> <41B5D159.3030809@po-box.mcgill.ca> <6.1.2.0.2.20041130082123.07ab1270@rcblue.com> Message-ID: False, I meant false. Ack, need coffee. >while nowTime < desiredTime: >because, I wrote the alarm clock after midnight! If I had run it >before 11:59pm my while condition would've been True immediately, so I >changed desiredTime to a datetime object. On Wed, 8 Dec 2004 06:50:22 +1300, Liam Clarke wrote: > Hi all, > > > > >I like your alarm clock a lot, > >. I first tried to run > >it with IDLE, then remembered that mscvrt won't catch keypresses if run > >with IDLE. Works fine in the console! > > >Instead of your beeps in the second while loop, I think I'd need > > >winsound.PlaySound('SystemAsterisk', winsound.SND_ALIAS) > >winsound.PlaySound('SystemHand', winsound.SND_ALIAS) > > >and turn my speakers way up! > > > Heh, I use headphones, but speakers would be better. I'm sure you > could play an mp3 also. > > But, I actually made a mistake in my alarm clock in that > > desiredTime.datetime.time(6,00,00) > is now desiredTime=datetime.datetime(2004,12,8,6, 00, 00) > > while nowTime.time < desiredTime: > > is now > > while nowTime < desiredTime: > > because, I wrote the alarm clock after midnight! If I had run it > before 11:59pm my while condition would've been True immediately, so I > changed desiredTime to a datetime object. > > Alternatively, I could have just changed > > checkPeriod=5 #minutes > nowTime=datetime.datetime.now() > startTime=nowTime > > while nowTime.time() < desiredTime or nowTime.time() > startTime.time(): > > But Occam's Razor works better. > > >Brian, where did you learn about the ".seconds". And the .year, .month, > >.day of > > What's funny, is that after I'd gone to bed that night, I suddenly > woke up and thought "Hang on, what about the attribute .seconds of a > datetime object? I better check that out." > > Which I promptly forgot about until your last reply. > > Heh. > > Liam Clarke > > > > On Tue, 07 Dec 2004 09:04:46 -0800, Dick Moores wrote: > > Brian van den Broek wrote at 07:50 12/7/2004: > > > > > > >Dick Moores said unto the world upon 2004-12-07 07:04: > > >>To Liam and Brian, > > > > > > > > > > > >>Here's Brian's script in it's bare bones, without the input error > > >>checking and his extensive and helpful comments: > > >>===============begin code==================== > > >>import datetime > > >>import time > > >>alarm_time = raw_input("Enter alarm time as hh:mm ") > > >>alarm_time_list = alarm_time.split(':') > > >>alarm_hour, alarm_minute = (int(alarm_time_list[0]), > > >> int(alarm_time_list[1])) > > >>now = datetime.datetime.now() > > >>alarm_datetime = datetime.datetime(now.year+4, now.month, now.day, > > >> alarm_hour, alarm_minute) > > >>print alarm_datetime > > >>alarm_in_seconds = (alarm_datetime - now).seconds > > >>print "I should wake up in %d seconds" % alarm_in_seconds > > >>time.sleep(alarm_in_seconds) > > >>print "I'm awake!" > > >>================end code===================== > > > > > > > > > > > >>Brian, where did you learn about the ".seconds". And the .year, .month, > > >>.day of > > >>"alarm_datetime = datetime.datetime(now.year + 4, now.month, now.day, > > >> alarm_hour, alarm_minute)"? > > >>Does this come from a general knowledge of OOP, or is it somewhere in > > >>the Python docs? The only thing I've seen, and it's not an explanation, > > >>is in note (1) on http://docs.python.org/lib/datetime-date.html > > > > > >Oh Sir, you flatter me! My general knowledge of OOP is about the same as > > >my general knowledge of the migration patterns of Siberian water-fowl. ;-) > > > > > >After Anna, Gon?alo, and Liam encouraged me to explore the datetime > > >module, I read (OK, skimmed) the docs. For my original purpose, I just > > >needed to test two times with '>', but I recalled something about > > >timedelta objects being returned by subtracting one datetime from > > >another. I hadn't used them before I wrote my script in reply to you. I > > >learned about the handy for your purposes .seconds attribute in the > > >Library Reference -- 6.10.2 timedelta Objects. (That's the section name > > >in the 2.4 installed docs; I'm typing off line so can't [OK, won't] get > > >a link.) > > > > > >>It seems I've missed out on something important > > >>BTW I'm not sure you need the +4 of "now.year + 4". I've run this > > >>without the +4 and it doesn't seem to be needed. And notes (1) and (4) > > >>on that page seem to say this, as far as I understand them. > > > > > >I'm not sure I do either :-) > > > > > >Here's why I did it: > > > > > >I discovered that in order to get the right "seconds until alarm" value > > >from the datetime for now and the alarm datetime by subtracting one > > >datetime object from another, I needed the alarm datetime to be in the > > >future. But, since you can set an alarm for 09:00 tomorrow at 22:00 > > >today, I needed the alarm datetime to not use today's date. (If you use > > >today's, you end up with seconds *since* 09:00 this morning, not the > > >desired seconds *until* 09:00 tomorrow morning.) Since > > >timedelta_object.seconds discards all difference save the seconds save > > >those from the hours, minutes, and seconds difference in the two > > >datetime objects, it doesn't matter what date the alarm datetime is set > > >to. (The day information is in timedelta_object.days.) > > > > > >Or, so I thought. I'd first tried getting the alarm datetime by simply > > >taking the date component of datetime.datetime.now() and adding to the > > >day value. That works fine, provided you are not on the last day of the > > >month. But, when checking boundary cases before posting the code I sent, > > >I discovered this sort of thing: > > > > > > >>> last_day_of_june = datetime.datetime(2004, 6, 30) # long for clarity > > > >>> ldj = last_day_of_june # short for typing > > > >>> new_day = datetime.datetime(ldj.year, ldj.month, ldj.day + 1) > > > > > >Traceback (most recent call last): > > > File "", line 1, in -toplevel- > > > new_day = datetime.datetime(ldj.year, ldj.month, ldj.day + 1) > > >ValueError: day is out of range for month > > > >>> > > > > > >So, adding to the day or the month was out, unless I wanted elaborate > > >code to determine which to add to under what circumstances. So then I > > >thought, "Well, just change from now.day + 1 to now.year + 1, and all > > >problems go away". And then I thought "Ah, but what if I try to run the > > >script on Feb. 29? > > > > > >So, that's why I used now.year + 4. It still leaves open the possibility > > >of getting bit by the every so often further correction to the calender, > > >but, I *believe* the next one is due in 2100, so I think I can live with > > >it. ;-) > > > > > >I'm not saying it isn't hackish, though. Better ways surely exist. > > > > Brian, > > > > I just can't succeed in reproducing the problems with the boundary > > cases with the +4 removed. I've tried setting my computer's clock to Nov > > 30, Feb 29, 2004, and Dec 31, 2004 (without changing the time). It's now > > about 9 am where I am, and setting the alarm time to 0700 (i.e., on the > > next day) works fine in all 3 cases. And of course no problem at today's > > date with setting the alarm time to 07:00. > > > > Isn't that what that note (1) on > > implies? > > > > I did the testing with , > > by remarking out the time.sleep() line and noting what the > > print_hms(sleepSeconds) function prints. > > > > Dick > > > > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > -- > 'There is only one basic human right, and that is to do as you damn well please. > And with it comes the only ba.>sic human duty, to take the consequences. > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From cyresse at gmail.com Tue Dec 7 19:12:36 2004 From: cyresse at gmail.com (Liam Clarke) Date: Tue Dec 7 19:12:40 2004 Subject: [Tutor] String matching? In-Reply-To: <41B5B841.2060408@ezabel.com> References: <41B5B841.2060408@ezabel.com> Message-ID: Hi all, It's a messy situation - basically, the HTML is from a tool used at work, which was, ahem, 'maintained' by someone who loved the flashy bits. Like animated gifs of the bad CG baby from Ally McBeal playing soccer with itself. So, yeah, instead of using href links, he used Java applets. 272 of them. Which takes appx. 2- 5min to open in Mozilla on all the older work boxes. So someone who knows HTML has taken over, and I'm helping out. So, I have to email changes backwards and forth, because heaven forbid they install Python. I mean, they've already got Perl, Java, and Visual Basic sitting there. Luckily the 'hackers' are waiting for Python. So, all I want to do is rip the urls from the applet, and replace it. >test2 = test.replace('=\n', '') >test2 = test2.replace('=3D"', '="') Thanks, Kent, for some reason I totally missed that. And thanks for the re, hopefully I won't have to use it, but it gives me a starting point to poke the re module from. Regards, Liam Clarke On Tue, 07 Dec 2004 09:03:45 -0500, orbitz wrote: > Instead of copying and pasting and then just doing a simple match, why > not use urllib2 to download the html and then run through it with HTMLParse? > > > > Liam Clarke wrote: > > >Hi all, > > > >I have a large amount of HTML that a previous person has liberally > >sprinkled a huge amount of applets through, instead of html links, > >which kills my browser to open. > > > >So, want to go through and replace all applets with nice simple links, > >and want to use Python to find the applet, extract a name and an URL, > >and create the link. > > > >My problem is, somewhere in my copying and pasting into the text file > >that the HTMl currently resides in, it got all messed up it would > >seem, and there's a bunch of strange '=' all through it. (Someone said > >that the code had been generated in Frontpage. Is that a good thing or > >bad thing?) > > > >So, I want to search for > > > >let > > code > > > >or > code > > > >or >plet > > > >etc. etc. (Full example of yuck here > >http://www.rafb.net/paste/results/WcKPCy64.html) > > > >So, I want to be write a search that will match > > > >I was thinking the re module is for this sort of stuff? Truth is, I > >wouldn't know where to begin with it, it seems somewhat powerful. > > > >Or, there's a much easier way, which I'm missing totally. If there is, > >I'd be very grateful for pointers. > > > >Thanks for any help you can offer. > > > >Liam Clarke > > > > > > > > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From jasonchild at cnsp.com Tue Dec 7 19:13:50 2004 From: jasonchild at cnsp.com (Jason Child) Date: Tue Dec 7 19:13:54 2004 Subject: [Tutor] test Message-ID: Jason Christopher Child Computer Network Services Professionals Tech Support 505-986-1669 1-877-321-9165 jasonchild@cnsp.com VOZ Online VOIP Install Tech 505-428-7500 1-877-428-7550 From jasonchild at cnsp.com Tue Dec 7 19:26:31 2004 From: jasonchild at cnsp.com (Jason Child) Date: Tue Dec 7 19:26:33 2004 Subject: [Tutor] embedding python in a C app on a linux box... Message-ID: Ok, so I have a decent grasp of python and have coded quite a few scripts. I must say that the language rocks. I would like to embed python into a C app to provide some scripting support. It would seem that my problem lies with not understanding the environment (linux) well enough. First off, I must include the Python.h header escplicitly (via #include "/usr/include/python2.3/Python.h"). How do I add the correct dir to the search path for the <> format? Second, when I call Py_Initialize() I get: /tmp/ccXZxNHZ.o(.text+0x11): In function `main': : undefined reference to `Py_Initialize' collect2: ld returned 1 exit status Now, I think it is because the linker isnt finding the right lib to attach. Is there a switch to use for gcc for make it? -L /path/to/libs perhaps? Any and all advice/help is welcome. flames >/dev/null Jason Christopher Child Computer Network Services Professionals Tech Support 505-986-1669 1-877-321-9165 jasonchild@cnsp.com VOZ Online VOIP Install Tech 505-428-7500 1-877-428-7550 From dyoo at hkn.eecs.berkeley.edu Tue Dec 7 19:49:46 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Dec 7 19:49:53 2004 Subject: [Tutor] Python 2.3.5 out in January?? In-Reply-To: <41B58BC9.8090703@tds.net> Message-ID: On Tue, 7 Dec 2004, Kent Johnson wrote: > I think the idea is to back-port bugfixes from 2.4 to 2.3. Then that is > the end of the line for 2.3. Yes. The policy for bugfix releases is in PEP 6: http://www.python.org/peps/pep-0006.html Here's what they say about bugfix releases: """ Bug fix releases are expected to occur at an interval of roughly six months. This is only a guideline, however - obviously, if a major bug is found, a bugfix release may be appropriate sooner. In general, only the N-1 release will be under active maintenance at any time. That is, during Python 2.4's development, Python 2.3 gets bugfix releases. If, however, someone qualified wishes to continue the work to maintain an older release, they should be encouraged. """ So that should help to explain Python 2.3.5 --- the Python developers just want to make sure that the people who still use Python 2.3 are happy campers. *grin* From dyoo at hkn.eecs.berkeley.edu Tue Dec 7 20:18:02 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Dec 7 20:18:07 2004 Subject: [Tutor] embedding python in a C app on a linux box... In-Reply-To: Message-ID: On Tue, 7 Dec 2004, Jason Child wrote: > Ok, so I have a decent grasp of python and have coded quite a few > scripts. I must say that the language rocks. I would like to embed > python into a C app to provide some scripting support. Hi Jason, We have to first mention that most of us here are beginning Python programmers; few of us have done Python/C integration, so we're probably not the best people to ask for help. You may want to ask your extension-building questions on comp.lang.python; I'm sure the experts there will be happy to help you. That being said, we'll do what we can. > It would seem that my problem lies with not understanding the > environment (linux) well enough. First off, I must include the Python.h > header escplicitly (via #include "/usr/include/python2.3/Python.h"). How > do I add the correct dir to the search path for the <> format? This is controlled by adding a '-I/usr/include/python2.3' flag argument to gcc, so that gcc adds that as part of its include path search. Second, when I call Py_Initialize() I get: > > /tmp/ccXZxNHZ.o(.text+0x11): In function `main': > : undefined reference to `Py_Initialize' > collect2: ld returned 1 exit status > > Now, I think it is because the linker isnt finding the right lib to > attach. Is there a switch to use for gcc for make it? -L /path/to/libs > perhaps? You'll probably need '-lpython' so that it links Python to your executable. The uppercase '-L' flag is something else: it controls where gcc looks for additional libraries, and I think it automatically include '/usr/lib' by default. You may find the stuff near the bottom of: http://docs.python.org/ext/building.html useful: it shows an example 'gcc' call that has all the flags that one needs to get an extension built in Linux. There's also an example of an embedded application that's in the Python source tree. It's under the Demo/embed directory, and may be a good starting-off point. But again, try asking your question on comp.lang.python. I have to admit that I haven't done embedding much, so there may be a better way to infer those 'gcc' flags without hardcoded them in some kind of Makefile. Good luck to you! From jasonchild at cnsp.com Tue Dec 7 20:22:16 2004 From: jasonchild at cnsp.com (Jason Child) Date: Tue Dec 7 20:22:17 2004 Subject: [Tutor] embedding python in a C app on a linux box... In-Reply-To: Message-ID: thanks. i got the linker to work, and with your -I switch the include works. thanks again! Jason Christopher Child Computer Network Services Professionals Tech Support 505-986-1669 1-877-321-9165 jasonchild@cnsp.com VOZ Online VOIP Install Tech 505-428-7500 1-877-428-7550 -----Original Message----- From: Danny Yoo [mailto:dyoo@hkn.eecs.berkeley.edu] Sent: Tuesday, December 07, 2004 12:18 PM To: Jason Child Cc: tutor@python.org Subject: Re: [Tutor] embedding python in a C app on a linux box... On Tue, 7 Dec 2004, Jason Child wrote: > Ok, so I have a decent grasp of python and have coded quite a few > scripts. I must say that the language rocks. I would like to embed > python into a C app to provide some scripting support. Hi Jason, We have to first mention that most of us here are beginning Python programmers; few of us have done Python/C integration, so we're probably not the best people to ask for help. You may want to ask your extension-building questions on comp.lang.python; I'm sure the experts there will be happy to help you. That being said, we'll do what we can. > It would seem that my problem lies with not understanding the > environment (linux) well enough. First off, I must include the Python.h > header escplicitly (via #include "/usr/include/python2.3/Python.h"). How > do I add the correct dir to the search path for the <> format? This is controlled by adding a '-I/usr/include/python2.3' flag argument to gcc, so that gcc adds that as part of its include path search. Second, when I call Py_Initialize() I get: > > /tmp/ccXZxNHZ.o(.text+0x11): In function `main': > : undefined reference to `Py_Initialize' > collect2: ld returned 1 exit status > > Now, I think it is because the linker isnt finding the right lib to > attach. Is there a switch to use for gcc for make it? -L /path/to/libs > perhaps? You'll probably need '-lpython' so that it links Python to your executable. The uppercase '-L' flag is something else: it controls where gcc looks for additional libraries, and I think it automatically include '/usr/lib' by default. You may find the stuff near the bottom of: http://docs.python.org/ext/building.html useful: it shows an example 'gcc' call that has all the flags that one needs to get an extension built in Linux. There's also an example of an embedded application that's in the Python source tree. It's under the Demo/embed directory, and may be a good starting-off point. But again, try asking your question on comp.lang.python. I have to admit that I haven't done embedding much, so there may be a better way to infer those 'gcc' flags without hardcoded them in some kind of Makefile. Good luck to you! From v-nijs at kellogg.northwestern.edu Tue Dec 7 20:38:13 2004 From: v-nijs at kellogg.northwestern.edu (Vincent Nijs) Date: Tue Dec 7 20:40:22 2004 Subject: [Tutor] Connecting to interactive program In-Reply-To: Message-ID: Has anyone ever tried to send commands to a running interactive python session from, say, the command line or another app? If so, please let me know how you achieved this. Vincent On 12/1/04 4:10 PM, "Vincent Nijs" wrote: > Hi, > > I am trying to send information from an editor (vim) to an interative > program (say the Python commandline, R, Matlab, etc.). > > I have tried to connect a named pipe to the interactive program using > mkfifo. For some reason this doesn't work properly however ( seems to > be the first thing sent). > > Could anyone provide a very very simple example where from a terminal > command line I could send, say, 'x=3' to an open interactive python session? > I'd like to have something that works on WinXP and Mac (or Linux). > > Thanks! > > Vincent -- From ARobert at MFS.com Tue Dec 7 20:54:48 2004 From: ARobert at MFS.com (Robert, Andrew) Date: Tue Dec 7 20:55:08 2004 Subject: [Tutor] Connecting to interactive program Message-ID: <968452DD78695147AA4A369C3DF9E40A02139A5C@BOSMAILBOX3.corp.mfs.com> Have you considered redirecting input from the terminal session itself? On Linux, I think you can test against sys.stdin.isatty() and assign a variable to /dev/tty. The methodology is similar on Windows but you need to import msvcrt and grab msvcrt.getche(). Thank you, Andrew Robert Systems Architect Information Technology - OpenVMS Massachusetts Financial Services Phone: 617-954-5882 Pager: 781-764-7321 E-mail: arobert@mfs.com Linux User Number: #201204 -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of Vincent Nijs Sent: Tuesday, December 07, 2004 2:38 PM To: tutor@python.org Subject: Re: [Tutor] Connecting to interactive program Has anyone ever tried to send commands to a running interactive python session from, say, the command line or another app? If so, please let me know how you achieved this. Vincent On 12/1/04 4:10 PM, "Vincent Nijs" wrote: > Hi, > > I am trying to send information from an editor (vim) to an interative > program (say the Python commandline, R, Matlab, etc.). > > I have tried to connect a named pipe to the interactive program using > mkfifo. For some reason this doesn't work properly however ( seems to > be the first thing sent). > > Could anyone provide a very very simple example where from a terminal > command line I could send, say, 'x=3' to an open interactive python session? > I'd like to have something that works on WinXP and Mac (or Linux). > > Thanks! > > Vincent -- _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor "MFS Relay Service" made the following annotations on 12/07/2004 03:00:42 PM ------------------------------------------------------------------------------ This email communication and any attachments may contain proprietary, confidential, or privileged information. If you are not the intended recipient, you are hereby notified that you have received this email in error and that any review, disclosure, dissemination, distribution or copying of it or its contents is prohibited. The sender does not waive confidentiality or any privilege by mistransmission. If you have received this email in error, please notify the sender immediately, delete this email, and destroy all copies and any attachments. ============================================================================== From alan.gauld at freenet.co.uk Tue Dec 7 21:39:21 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Dec 7 21:38:59 2004 Subject: [Tutor] about recursion code References: Message-ID: <030101c4dc9c$d5242060$c6ca8751@xp> > def selection_sort(lst,start,end): > """sort the lst from selection start to end""" > if len(lst)==1: > return lst > elif lst=="": > return "" > else: > return lst[:start]+selection_sort(lst,start+1,end) This doesn't appear to do any actual sorting? And the recursive call always passes in the original list so I assume it never terminates? Alan G. From alan.gauld at freenet.co.uk Tue Dec 7 21:47:01 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Dec 7 21:46:16 2004 Subject: [Tutor] Python 2.3.5 out in January?? References: <6.1.2.0.2.20041207012905.049ac550@rcblue.com> Message-ID: <030801c4dc9d$e74fa830$c6ca8751@xp> > the 2.3 line. It's *possible* that volunteers for 2.3.6 will appear. > That would be unprecedented, but not impossible ... > ============end TP's post================ > > I ask here because I'm sure it's a newbie question. It's got me wondering > if Microsoft is still working on Windows 3.1.. ;-) Its not at all unusual for commercial vendors to support an old line of releases long after the new version goes out. Patches for Windows NT4 are still potentially available up till the end of this month... So not 3.1 but NT4 and Win2000 are both currently supported and developers are working on them - but usually only for bug fixes etc. Part of the reason for this is that many users - particularly in big companies - rely on automated delivery mechanisms to upgrade their applications "on the fly" and it takes time to develop the delivery configurations. Also versions might require hardware upgrades- extra RAM for example - and the cost of those upgrades may not be available in this years budget so you have to wait till next year... In other cases its legacy code - for example we have delayed moving some of our PCS off NT4 because they use bespoke hardware that needs an ISA bus - which isn't supported in XP... The cost of redeveloping the hardware has proved extortionate! So yes, vendors do support old and new in parallel. Typically for two full releases or two full years depending on which is soonest... Alan G. From sigurd at 12move.de Tue Dec 7 21:47:32 2004 From: sigurd at 12move.de (Karl =?iso-8859-1?Q?Pfl=E4sterer?=) Date: Tue Dec 7 21:52:46 2004 Subject: [Tutor] Printing two elements in a list In-Reply-To: <20041207152230.68855.qmail@web53703.mail.yahoo.com> (kumar s.'s message of "Tue, 7 Dec 2004 07:22:29 -0800 (PST)") References: <20041207152230.68855.qmail@web53703.mail.yahoo.com> Message-ID: On 7 Dez 2004, ps_python@yahoo.com wrote: > I have two lists names x and seq. > > I am trying to find element of x in element of seq. I > find them. However, I want to print element in seq > that contains element of x and also the next element > in seq. [...] > 3. TRIAL 3: > I just asked to print the element in seq that matched > element 1 in X. It prints only that element, however > I want to print the next element too and I cannot get > it. >>>> for ele1 in x: > for ele2 in seq: > if ele1 in ele2: > print ele2 > [...] >>>> len(x) > 4504 >>>> x[1:10] > ['454:494', '319:607', '319:608', '322:289', > '322:290', '183:330', '183:329', '364:95', '364:96'] >>>> len(seq) > 398169 >>>> seq[0:4] > ['>probe:HG-U95Av2:1000_at:399:559; > Interrogation_Position=1367; Antisense;', > 'TCTCCTTTGCTGAGGCCTCCAGCTT', > '>probe:HG-U95Av2:1000_at:544:185; > Interrogation_Position=1379; Antisense;', > 'AGGCCTCCAGCTTCAGGCAGGCCAA'] [...] > How Do I WANT: > > I want to print get an output like this: > > >>probe:HG-U95Av2:1000_at:399:559; > Interrogation_Position=1367; Antisense;' > TCTCCTTTGCTGAGGCCTCCAGCTT > >>probe:HG-U95Av2:1000_at:544:185; > Interrogation_Position=1379; Antisense; > AGGCCTCCAGCTTCAGGCAGGCCAA Hi, you got some replies how to do it, but IMO there are two other possibilities: (a) Turn seq into a dictionary with the parts of the string that are matched against from list x as keys. Since seq is long that may be much faster. def list_to_dict (lst): d = {} reg = re.compile(':.+?:.+?:(.+?:.+?);') for val1, val2 in lst: key = reg.search(val1).group(1) d[key] = val1 + val2 return d import re seq_dic = list_to_dict(zip(seq[::2], seq[1::2])) for key in x: val = seq_dic.get(key) if val: print val The above function uses a regular expression to extract the part of the string you are interested in and uses it as key in a dictionary. To find the corrresponding list entries `zip(seq[::2], seq[1::2])' is used; seq[::2] is the first, the third, the fifth ... entry of the list and seq[1::2] is the second, the fourth, the sixth entry of the list. zip() packs them together in a tuple. (b) If you care about memory iterate about seq with izip (from itertools). from itertools import izip as izip reg = re.compile(':.+?:.+?:(.+?:.+?);') for val1, val2 in izip(seq[::2], seq[1::2]): if reg.search(val1).group(1) in x: print val1, val2 Instead of zip() izip() is here used (it does not create the whole list at once). Al?so no dictionary is used. What's better for you shows only testing. Karl -- Please do *not* send copies of replies to me. I read the list From kent37 at tds.net Tue Dec 7 21:57:22 2004 From: kent37 at tds.net (Kent Johnson) Date: Tue Dec 7 21:57:18 2004 Subject: [Tutor] Printing two elements in a list In-Reply-To: <20041207152230.68855.qmail@web53703.mail.yahoo.com> References: <20041207152230.68855.qmail@web53703.mail.yahoo.com> Message-ID: <41B61932.1000205@tds.net> kumar, Looking at the quantity and structure of your data I think the search you are doing is going to be pretty slow - you will be doing 4504 * 398169 = 1,793,353,176 string searches. Where does the seq data come from? Could you consolidate the pairs of lines into a single record? If you do that and extract the '399:559' portion, you could build a dict that maps '399:559' to the full record. Looking up '399:559' in the dictionary would be much, much faster than searching the entire list. If you have multiple entries for '399:559' you could have the dict map to a list. Kent kumar s wrote: > >>>>len(x) > > 4504 > >>>>x[1:10] > > ['454:494', '319:607', '319:608', '322:289', > '322:290', '183:330', '183:329', '364:95', '364:96'] > >>>>len(seq) > > 398169 > >>>>seq[0:4] > > ['>probe:HG-U95Av2:1000_at:399:559; > Interrogation_Position=1367; Antisense;', > 'TCTCCTTTGCTGAGGCCTCCAGCTT', > '>probe:HG-U95Av2:1000_at:544:185; > Interrogation_Position=1379; Antisense;', > 'AGGCCTCCAGCTTCAGGCAGGCCAA'] > > > >>>>for ele1 in x: > > for ele2 in seq: > if ele1 in ele2: > print ele2 > > > >>probe:HG-U95Av2:31358_at:454:493; > > Interrogation_Position=132; Antisense; > >>probe:HG-U95Av2:31358_at:319:607; > > Interrogation_Position=144; Antisense; > > > > > > > How Do I WANT: > > I want to print get an output like this: > > > >>probe:HG-U95Av2:1000_at:399:559; > > Interrogation_Position=1367; Antisense;' > TCTCCTTTGCTGAGGCCTCCAGCTT > > >>probe:HG-U95Av2:1000_at:544:185; > > Interrogation_Position=1379; Antisense; > AGGCCTCCAGCTTCAGGCAGGCCAA > > > can any one please suggest what is going wrong in my > statements and how can I get it. > > Thank you. > Kumar > > > > __________________________________ > Do you Yahoo!? > Yahoo! Mail - 250MB free storage. Do more. Manage less. > http://info.mail.yahoo.com/mail_250 > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From v-nijs at kellogg.northwestern.edu Tue Dec 7 22:04:28 2004 From: v-nijs at kellogg.northwestern.edu (Vincent Nijs) Date: Tue Dec 7 22:06:34 2004 Subject: [Tutor] Connecting to interactive program In-Reply-To: <968452DD78695147AA4A369C3DF9E40A02139A5C@BOSMAILBOX3.corp.mfs.com> Message-ID: I am very much a python novice so I am not really sure what you are suggesting. I would like to create a python script that would function as follows. ./script.py intpy Where the scipt setsup the comminication to 'intpy' which would be an interactive python sessions (or some other interactive program). Could this be done with sys.stdin.isatty()? Thanks, Vincent On 12/7/04 1:54 PM, "Robert, Andrew" wrote: > > Have you considered redirecting input from the terminal session itself? > > > On Linux, I think you can test against sys.stdin.isatty() and assign a > variable to /dev/tty. > > The methodology is similar on Windows but you need to import msvcrt and > grab msvcrt.getche(). > > > Thank you, > Andrew Robert > Systems Architect > Information Technology - OpenVMS > Massachusetts Financial Services > Phone: 617-954-5882 > Pager: 781-764-7321 > E-mail: arobert@mfs.com > Linux User Number: #201204 > > -----Original Message----- > From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On > Behalf Of Vincent Nijs > Sent: Tuesday, December 07, 2004 2:38 PM > To: tutor@python.org > Subject: Re: [Tutor] Connecting to interactive program > > Has anyone ever tried to send commands to a running interactive python > session from, say, the command line or another app? > > If so, please let me know how you achieved this. > > Vincent > > > On 12/1/04 4:10 PM, "Vincent Nijs" > wrote: > >> Hi, >> >> I am trying to send information from an editor (vim) to an interative >> program (say the Python commandline, R, Matlab, etc.). >> >> I have tried to connect a named pipe to the interactive program using >> mkfifo. For some reason this doesn't work properly however ( > seems to >> be the first thing sent). >> >> Could anyone provide a very very simple example where from a terminal >> command line I could send, say, 'x=3' to an open interactive python > session? >> I'd like to have something that works on WinXP and Mac (or Linux). >> >> Thanks! >> >> Vincent -- From dyoo at hkn.eecs.berkeley.edu Tue Dec 7 23:02:57 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Dec 7 23:03:03 2004 Subject: [Tutor] Connecting to interactive program In-Reply-To: Message-ID: On Tue, 7 Dec 2004, Vincent Nijs wrote: > Has anyone ever tried to send commands to a running interactive python > session from, say, the command line or another app? Yes. This sort of thing can be done through an "expect" script. http://expect.nist.gov/ There's a port of expect for Python: http://pexpect.sourceforge.net/ Out of curiosity though, do you really need to run Python interactively? From ps_python at yahoo.com Tue Dec 7 23:09:32 2004 From: ps_python at yahoo.com (kumar s) Date: Tue Dec 7 23:09:38 2004 Subject: [Tutor] Printing two elements in a list In-Reply-To: <41B61932.1000205@tds.net> Message-ID: <20041207220932.9164.qmail@web53703.mail.yahoo.com> Hello group, Thank you very much for your kind replies. In fact I survived to pull out what I needed by going with Kent's tip by enumerating on iterator. The problem with me is suddenly I embarked on something big problem and I am surviving it in pieces by writing pieces of code. I have another question: To be brief: My list contains some elements that I do not want and I want to remove unwanted elements in my list: My TEXT file looks like this: Name=32972_at Cell1=xxx xxx N control 32972_at Cell1=xxx xxx N control 32972_at Cell1=xxx xxx N control 32972_at Cell1=xxx xxx N control 32972_at Name=3456_at Cell1=xxx xxx N control 3456_at Cell1=xxx xxx N control 3456_at Cell1=xxx xxx N control 3456_at Cell1=xxx xxx N control 3456_at ......... ... x xxxxxxxxxxxxxxx (34K lines) I want to remove Name=Xxxx_at identifiers. My List: ['Name=32972_at', 'Cell1=432\t118\tN\tcontrol\t32972_at\t0\t13\tA\tA\tA\t0\t75952\t-1\t-1\t99\t', 'Cell2=432\t117\tN\tcontrol\t32972_at\t0\t13\tA\tT\tA\t0\t75312\t-1\t-1\t99\t', 'Cell3=499\t632\tN\tcontrol\t32972_at\t1\t13\tC\tC\tC\t1\t404979\t-1\t-1\t99\t'] I tried to resolve in this way: >>>pat = re.compile('Name') >>> for i in range(len(cord)): x = pat.search(cord[i]) cord.remove(x) I know I am wrong here because I do not know how to search and remove an element in a list. Can any one please help me. on Page 98, chapter Lists and dictionaries of mark lutz's learning python. It is mentioned in table 6-1 : L2.append(4) Methods: grow,sort,search,reverse etc. Although not much is covered on this aspect in this book, I failed to do more operations on list. Looking forward for help from tutors. Thank you. Kumar. --- Kent Johnson wrote: > kumar, > > Looking at the quantity and structure of your data I > think the search you are doing is going to be > pretty slow - you will be doing 4504 * 398169 = > 1,793,353,176 string searches. > > Where does the seq data come from? Could you > consolidate the pairs of lines into a single record? > If > you do that and extract the '399:559' portion, you > could build a dict that maps '399:559' to the > full record. Looking up '399:559' in the dictionary > would be much, much faster than searching the > entire list. > > If you have multiple entries for '399:559' you could > have the dict map to a list. > > Kent > > kumar s wrote: > > > >>>>len(x) > > > > 4504 > > > >>>>x[1:10] > > > > ['454:494', '319:607', '319:608', '322:289', > > '322:290', '183:330', '183:329', '364:95', > '364:96'] > > > >>>>len(seq) > > > > 398169 > > > >>>>seq[0:4] > > > > ['>probe:HG-U95Av2:1000_at:399:559; > > Interrogation_Position=1367; Antisense;', > > 'TCTCCTTTGCTGAGGCCTCCAGCTT', > > '>probe:HG-U95Av2:1000_at:544:185; > > Interrogation_Position=1379; Antisense;', > > 'AGGCCTCCAGCTTCAGGCAGGCCAA'] > > > > > > > >>>>for ele1 in x: > > > > for ele2 in seq: > > if ele1 in ele2: > > print ele2 > > > > > > > >>probe:HG-U95Av2:31358_at:454:493; > > > > Interrogation_Position=132; Antisense; > > > >>probe:HG-U95Av2:31358_at:319:607; > > > > Interrogation_Position=144; Antisense; > > > > > > > > > > > > > > How Do I WANT: > > > > I want to print get an output like this: > > > > > > > >>probe:HG-U95Av2:1000_at:399:559; > > > > Interrogation_Position=1367; Antisense;' > > TCTCCTTTGCTGAGGCCTCCAGCTT > > > > > >>probe:HG-U95Av2:1000_at:544:185; > > > > Interrogation_Position=1379; Antisense; > > AGGCCTCCAGCTTCAGGCAGGCCAA > > > > > > can any one please suggest what is going wrong in > my > > statements and how can I get it. > > > > Thank you. > > Kumar > > > > > > > > __________________________________ > > Do you Yahoo!? > > Yahoo! Mail - 250MB free storage. Do more. Manage > less. > > http://info.mail.yahoo.com/mail_250 > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > __________________________________ Do you Yahoo!? Yahoo! Mail - now with 250MB free storage. Learn more. http://info.mail.yahoo.com/mail_250 From v-nijs at kellogg.northwestern.edu Tue Dec 7 23:14:33 2004 From: v-nijs at kellogg.northwestern.edu (Vincent Nijs) Date: Tue Dec 7 23:16:39 2004 Subject: [Tutor] Connecting to interactive program In-Reply-To: Message-ID: It is not actually python that I am most interested in. I'd like this to work for different interactive programs but specifically R, Matlab, and a debugger for Ox. Pexpect seemed to come close to what I wanted but it still seemed very complex and not very well documented (for me anyway). I'd want to have the interactive program open so that I can input things directly and also allow to send commands from vim. I can figure out how to send commands from vim. Just not how to get them to reach the interactive program :) If can figure out how to send commands from the command line (e.g., echo 'x=3') then I'd be pretty much set. Do you have any very simple examples you might be willing to share? Thanks, Vincent On 12/7/04 4:02 PM, "Danny Yoo" wrote: > > > On Tue, 7 Dec 2004, Vincent Nijs wrote: > >> Has anyone ever tried to send commands to a running interactive python >> session from, say, the command line or another app? > > Yes. This sort of thing can be done through an "expect" script. > > http://expect.nist.gov/ > > There's a port of expect for Python: > > http://pexpect.sourceforge.net/ > > Out of curiosity though, do you really need to run Python interactively? > -- From alan.gauld at freenet.co.uk Tue Dec 7 23:33:50 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Dec 7 23:32:54 2004 Subject: [Tutor] Connecting to interactive program References: Message-ID: <034801c4dcac$d378c710$c6ca8751@xp> > Has anyone ever tried to send commands to a running interactive python > session from, say, the command line or another app? This isn't too hard if you use stdin/stdout. But it does depend on what you mean by send commands from the command line. If the process is a daemon for example and it isn't stopped waiting for input then its going to be hard! If its waiting on a socket then its a standard ipc issue. > If so, please let me know how you achieved this. Assuming you mean something that normally interacts with a human user then you can use things like expect to simulate user input. Is that what you mean? Alan G. From alan.gauld at freenet.co.uk Tue Dec 7 23:38:10 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Dec 7 23:37:45 2004 Subject: [Tutor] Connecting to interactive program References: Message-ID: <035301c4dcad$6e96dc50$c6ca8751@xp> > I would like to create a python script that would function as follows. > > ./script.py intpy > > Where the scipt setsup the comminication to 'intpy' which would be an > interactive python sessions (or some other interactive program). OK, two steps back here I think. Can you show us an imaginary user session explaining just what is happening. > ./script.py intpy That is the user running a python program called script.py which is taking a single commandline argument, the string "intpy". script.py can read intpy via the sys.argv list. But what exactly does intpy represent? And where does the "other program" that you refer to come into the picture? You will need to explain your requirements in a bit more detail I think. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Tue Dec 7 23:42:50 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Dec 7 23:42:22 2004 Subject: Removing list elements - was:: [Tutor] Printing two elements in a list References: <20041207220932.9164.qmail@web53703.mail.yahoo.com> Message-ID: <035a01c4dcae$159f05e0$c6ca8751@xp> > I know I am wrong here because I do not know how to > search and remove an element in a list. Can any one > please help me. This is what the filter function is for... But you can use list comprehensions too: [element for element in list if element not foo] so in your case: lst = f.readlines() # get file into a list lst = [line for line in lst if not line.startswith('Name=')] Or something very similar. For more control use a regular expression to filter the lines Alan G. From alan.gauld at freenet.co.uk Wed Dec 8 00:41:16 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed Dec 8 00:40:25 2004 Subject: [Tutor] Connecting to interactive program References: Message-ID: <035f01c4dcb6$3f504400$c6ca8751@xp> CC'd back to tutor list. ----- Original Message ----- From: "Vincent Nijs" To: "Alan Gauld" Sent: Tuesday, December 07, 2004 10:56 PM Subject: Re: [Tutor] Connecting to interactive program > Alan, > > Sorry if I was unclear. > > I would like to have python program that will (1) start an interactive > session of python, r, matlab or some other program and (2) allow the user to > pass commands to that interactive session from a shell command line (e.g., > echo 'x=3'). If the python program opens the interactive session that will > also allow direct input into the interactive program by the user. That sounds pretty much what pyexpect will allow you to do. Certainly plain ol' expect does that kind of thing. Basically anything that reads stdin and displays on stdout or stderr can be driven by expect and therefore by pyexpect. > If I can get the interactive program to accept commands from a shell command > line I can figure out how to send commands from my favorite editor (VIM). Now that might be interesting :-) I assume you have the version of vim that uses python as its scripting language? Alan G. From cyresse at gmail.com Wed Dec 8 02:47:27 2004 From: cyresse at gmail.com (Liam Clarke) Date: Wed Dec 8 02:47:32 2004 Subject: [Tutor] Printing two elements in a list In-Reply-To: <20041207220932.9164.qmail@web53703.mail.yahoo.com> References: <41B61932.1000205@tds.net> <20041207220932.9164.qmail@web53703.mail.yahoo.com> Message-ID: Hi Kumar, I've been studiously avoiding re, and I think you can too for this problem - >I want to remove Name=Xxxx_at identifiers. >My List: >['Name=32972_at', >'Cell1=432\t118\tN\tcontrol\t32972_at\t0\t13\tA\tA\tA\t0\t75952\t-1\t-1\t99\t', >'Cell2=432\t117\tN\tcontrol\t32972_at\t0\t13\tA\tT\tA\t0\t75312\t-1\t-1\t99\t', >'Cell3=499\t632\tN\tcontrol\t32972_at\t1\t13\tC\tC\tC\t1\t404979\t-1\t-1\t99\t'] so - hasName=[] for indexNum in range(len(myList): if "Name=" in myList[indexNum]: hasName.append(indexNum) hasName.reverse() for element in hasName: del myList(element) Might be able to do it hasName=[] for indexNum in myList.index(): #??? if "Name=" in indexNum: hasName.append(indexNum) hasName.reverse() for element in hasName: del myList(element) But, you need a list of the index numbers of the list members to be deleted, and then you need to reverse it... why? aList=['b','c','d'] indexes=[0,1,2] for element in indexes: del aList[element] Watch what happens as it runs. element=0 del aList[0] aList=['c','d'] element = 1 del aList[1] aList=['c'] element = 2 del aList[2] IndexError - value out of range. Whereas - aList=['b','c','d'] indexes=[0,1,2] indexes.reverse() for element in indexes: del aList[element] element=2 del aList[2] aList=['b','c'] element = 1 del aList[1] aList=['b'] element=0 del aList[0] aList=[] HTH Liam Clarke On Tue, 7 Dec 2004 14:09:32 -0800 (PST), kumar s wrote: > Hello group, > Thank you very much for your kind replies. In fact I > survived to pull out what I needed by going with > Kent's tip by enumerating on iterator. > > The problem with me is suddenly I embarked on > something big problem and I am surviving it in pieces > by writing pieces of code. > > I have another question: > To be brief: > > My list contains some elements that I do not want and > I want to remove unwanted elements in my list: > > My TEXT file looks like this: > > Name=32972_at > Cell1=xxx xxx N control 32972_at > Cell1=xxx xxx N control 32972_at > Cell1=xxx xxx N control 32972_at > Cell1=xxx xxx N control 32972_at > Name=3456_at > Cell1=xxx xxx N control 3456_at > Cell1=xxx xxx N control 3456_at > Cell1=xxx xxx N control 3456_at > Cell1=xxx xxx N control 3456_at > ......... ... x xxxxxxxxxxxxxxx > (34K lines) > > I want to remove Name=Xxxx_at identifiers. > > My List: > ['Name=32972_at', > 'Cell1=432\t118\tN\tcontrol\t32972_at\t0\t13\tA\tA\tA\t0\t75952\t-1\t-1\t99\t', > 'Cell2=432\t117\tN\tcontrol\t32972_at\t0\t13\tA\tT\tA\t0\t75312\t-1\t-1\t99\t', > 'Cell3=499\t632\tN\tcontrol\t32972_at\t1\t13\tC\tC\tC\t1\t404979\t-1\t-1\t99\t'] > > I tried to resolve in this way: > > >>>pat = re.compile('Name') > >>> for i in range(len(cord)): > x = pat.search(cord[i]) > cord.remove(x) > > I know I am wrong here because I do not know how to > search and remove an element in a list. Can any one > please help me. > > on Page 98, chapter Lists and dictionaries of mark > lutz's learning python. It is mentioned in table 6-1 : > L2.append(4) Methods: grow,sort,search,reverse etc. > > Although not much is covered on this aspect in this > book, I failed to do more operations on list. > > Looking forward for help from tutors. > > Thank you. > Kumar. > > > > > --- Kent Johnson wrote: > > > kumar, > > > > Looking at the quantity and structure of your data I > > think the search you are doing is going to be > > pretty slow - you will be doing 4504 * 398169 = > > 1,793,353,176 string searches. > > > > Where does the seq data come from? Could you > > consolidate the pairs of lines into a single record? > > If > > you do that and extract the '399:559' portion, you > > could build a dict that maps '399:559' to the > > full record. Looking up '399:559' in the dictionary > > would be much, much faster than searching the > > entire list. > > > > If you have multiple entries for '399:559' you could > > have the dict map to a list. > > > > Kent > > > > kumar s wrote: > > > > > >>>>len(x) > > > > > > 4504 > > > > > >>>>x[1:10] > > > > > > ['454:494', '319:607', '319:608', '322:289', > > > '322:290', '183:330', '183:329', '364:95', > > '364:96'] > > > > > >>>>len(seq) > > > > > > 398169 > > > > > >>>>seq[0:4] > > > > > > ['>probe:HG-U95Av2:1000_at:399:559; > > > Interrogation_Position=1367; Antisense;', > > > 'TCTCCTTTGCTGAGGCCTCCAGCTT', > > > '>probe:HG-U95Av2:1000_at:544:185; > > > Interrogation_Position=1379; Antisense;', > > > 'AGGCCTCCAGCTTCAGGCAGGCCAA'] > > > > > > > > > > > >>>>for ele1 in x: > > > > > > for ele2 in seq: > > > if ele1 in ele2: > > > print ele2 > > > > > > > > > > > >>probe:HG-U95Av2:31358_at:454:493; > > > > > > Interrogation_Position=132; Antisense; > > > > > >>probe:HG-U95Av2:31358_at:319:607; > > > > > > Interrogation_Position=144; Antisense; > > > > > > > > > > > > > > > > > > > > > How Do I WANT: > > > > > > I want to print get an output like this: > > > > > > > > > > > >>probe:HG-U95Av2:1000_at:399:559; > > > > > > Interrogation_Position=1367; Antisense;' > > > TCTCCTTTGCTGAGGCCTCCAGCTT > > > > > > > > >>probe:HG-U95Av2:1000_at:544:185; > > > > > > Interrogation_Position=1379; Antisense; > > > AGGCCTCCAGCTTCAGGCAGGCCAA > > > > > > > > > can any one please suggest what is going wrong in > > my > > > statements and how can I get it. > > > > > > Thank you. > > > Kumar > > > > > > > > > > > > __________________________________ > > > Do you Yahoo!? > > > Yahoo! Mail - 250MB free storage. Do more. Manage > > less. > > > http://info.mail.yahoo.com/mail_250 > > > _______________________________________________ > > > Tutor maillist - Tutor@python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > __________________________________ > Do you Yahoo!? > Yahoo! Mail - now with 250MB free storage. Learn more. > > > http://info.mail.yahoo.com/mail_250 > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From kent37 at tds.net Wed Dec 8 03:06:34 2004 From: kent37 at tds.net (Kent Johnson) Date: Wed Dec 8 03:06:39 2004 Subject: [Tutor] String matching? In-Reply-To: References: <41B5B841.2060408@ezabel.com> Message-ID: <41B661AA.8040700@tds.net> Liam Clarke wrote: > And thanks for the re, hopefully I won't have to use it, but it gives > me a starting point to poke the re module from. BTW Python comes with a nice tool for experimenting with regular expressions. Try running Python23\Tools\Scripts\redemo.py Kent From singingxduck at gmail.com Wed Dec 8 03:13:41 2004 From: singingxduck at gmail.com (Orri Ganel) Date: Wed Dec 8 03:13:49 2004 Subject: [Tutor] Import Statement Failing With IDLE? Message-ID: <3449428f04120718132bbe8dc8@mail.gmail.com> Hello all, I recently downloaded Psyco and put it in the site-packages folder. Now, when i tried to use it to optimize a program, IDLE says it can't find it: Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. **************************************************************** Personal firewall software may warn about the connection IDLE makes to its subprocess using this computer's internal loopback interface. This connection is not visible on any external interface and no data is sent to or received from the Internet. **************************************************************** IDLE 1.1 >>> import os >>> os.chdir(r"c:\python24\lib\site-packes\psyco-1.3") >>> import psyco Traceback (most recent call last): File "", line 1, in -toplevel- import psyco ImportError: No module named psyco ... However, when using the Command Prompt: Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> os.getcwd() 'C:\\Python24' >>> os.chdir(r"c:\python24\lib\site-packages\psyco-1.3") >>> import psyco >>> Anyone know why this is? . . . Thanks in advance, Orri -- Email: dragonfirebane@aol.com AIM: singingxduck Programming Python for the fun of it. From kent37 at tds.net Wed Dec 8 03:27:37 2004 From: kent37 at tds.net (Kent Johnson) Date: Wed Dec 8 03:27:50 2004 Subject: [Tutor] Import Statement Failing With IDLE? In-Reply-To: <3449428f04120718132bbe8dc8@mail.gmail.com> References: <3449428f04120718132bbe8dc8@mail.gmail.com> Message-ID: <41B66699.1060902@tds.net> I don't know why you are getting different results, but I do know that you aren't supposed to put the whole psyco-1.3 folder inside site-packages. Just put the psyco folder (from inside psyco-1.3) into site-packages. Also the os.chdir() doesn't have any effect on import. You could compare sys.path in the two different environments and see what is different between them. >>> import sys >>> sys.path ['', 'C:\\Python24\\python24.zip', 'D:\\Projects', 'C:\\Python24\\DLLs', 'C:\\Python24\\lib', 'C:\\Python24\\lib\\plat-win', 'C:\\Python24\\lib\\lib-t k', 'C:\\Python24', 'C:\\Python24\\lib\\site-packages', 'C:\\Python24\\lib\\site-packages\\win32', 'C:\\Python24\\lib\\site-packages\\win32\\lib', 'C: \\Python24\\lib\\site-packages\\Pythonwin'] You can also find out where psyco is being found by printing the module's __file__ attribute: >>> import psyco >>> psyco.__file__ 'C:\\Python24\\lib\\site-packages\\psyco\\__init__.py' Kent Orri Ganel wrote: > Hello all, > I recently downloaded Psyco and put it in the site-packages folder. > Now, when i tried to use it to optimize a program, IDLE says it can't > find it: > > Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32 > Type "copyright", "credits" or "license()" for more information. > > **************************************************************** > Personal firewall software may warn about the connection IDLE > makes to its subprocess using this computer's internal loopback > interface. This connection is not visible on any external > interface and no data is sent to or received from the Internet. > **************************************************************** > > IDLE 1.1 > >>>>import os >>>>os.chdir(r"c:\python24\lib\site-packes\psyco-1.3") >>>>import psyco > > > Traceback (most recent call last): > File "", line 1, in -toplevel- > import psyco > ImportError: No module named psyco > > ... However, when using the Command Prompt: > > Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > >>>>import os >>>>os.getcwd() > > 'C:\\Python24' > >>>>os.chdir(r"c:\python24\lib\site-packages\psyco-1.3") >>>>import psyco >>>> > > > Anyone know why this is? . . . > > Thanks in advance, > Orri > From bvande at po-box.mcgill.ca Wed Dec 8 05:44:50 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Wed Dec 8 05:49:23 2004 Subject: [Tutor] Re: Could I have used time or datetime modules here? In-Reply-To: <1f7befae0412070845213959db@mail.gmail.com> References: <6.1.2.0.2.20041207040419.0480a490@rcblue.com> <41B5D159.3030809@po-box.mcgill.ca> <1f7befae0412070845213959db@mail.gmail.com> Message-ID: <41B686C2.7050405@po-box.mcgill.ca> Tim Peters said unto the world upon 2004-12-07 11:45: > [Brian van den Broek] > ... > >>Or, so I thought. I'd first tried getting the alarm datetime by simply >>taking the date component of datetime.datetime.now() and adding >>to the day value. That works fine, provided you are not on the last >>day of the month. But, when checking boundary cases before >>posting the code I sent, I discovered this sort of thing: >> >> >>>>>last_day_of_june = datetime.datetime(2004, 6, 30) # long for clarity >>>>>ldj = last_day_of_june # short for typing >>>>>new_day = datetime.datetime(ldj.year, ldj.month, ldj.day + 1) >> >>Traceback (most recent call last): >> File "", line 1, in -toplevel- >> new_day = datetime.datetime(ldj.year, ldj.month, ldj.day + 1) >>ValueError: day is out of range for month >> >>So, adding to the day or the month was out, unless I wanted >>elaborate code to determine which to add to under what >>circumstances. > > > Actually, you needed simpler code : > > >>>>import datetime >>>>ldj = datetime.datetime(2004, 6, 30) >>>>new_day = ldj + datetime.timedelta(days=1) >>>>print new_day > > 2004-07-01 00:00:00 > > or even > > >>>>ldy = datetime.datetime(2004, 12, 31) >>>>new_day = ldy + datetime.timedelta(days=1) >>>>print new_day > > 2005-01-01 00:00:00 > > In other words, if you want to move to the next day, add one day! > That always does the right thing. Subtracting one day moves to the > previous day, and so on. Hi Tim and all, thanks! Since I last posted, I'd found a better way to do what I wanted than what I'd been using. But it was still clumsy. Your way is of much better than any work-aroundish thing. It does, however, prove my claim up-thread that I'd only skimmed the datetime docs! Best to all, Brian From bvande at po-box.mcgill.ca Wed Dec 8 05:57:59 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Wed Dec 8 05:59:40 2004 Subject: [Tutor] Re: Could I have used time or datetime modules here? In-Reply-To: <6.1.2.0.2.20041130082123.07ab1270@rcblue.com> References: <6.1.2.0.2.20041207040419.0480a490@rcblue.com> <41B5D159.3030809@po-box.mcgill.ca> <6.1.2.0.2.20041130082123.07ab1270@rcblue.com> Message-ID: <41B689D7.10200@po-box.mcgill.ca> Dick Moores said unto the world upon 2004-12-07 12:04: > Brian van den Broek wrote at 07:50 12/7/2004: > >>> It seems I've missed out on something important >>> BTW I'm not sure you need the +4 of "now.year + 4". I've run this >>> without the +4 and it doesn't seem to be needed. And notes (1) and >>> (4) on that page seem to say this, as far as I understand them. >> >> >> I'm not sure I do either :-) >> >> Here's why I did it: >> >> I discovered that in order to get the right "seconds until alarm" >> value from the datetime for now and the alarm datetime by subtracting >> one datetime object from another, I needed the alarm datetime to be in >> the future. But, since you can set an alarm for 09:00 tomorrow at >> 22:00 today, I needed the alarm datetime to not use today's date. (If >> you use today's, you end up with seconds *since* 09:00 this morning, >> not the desired seconds *until* 09:00 tomorrow morning.) Since >> timedelta_object.seconds discards all difference save the seconds save >> those from the hours, minutes, and seconds difference in the two >> datetime objects, it doesn't matter what date the alarm datetime is >> set to. (The day information is in timedelta_object.days.) >> >> Or, so I thought. I'd first tried getting the alarm datetime by simply >> taking the date component of datetime.datetime.now() and adding to the >> day value. That works fine, provided you are not on the last day of >> the month. But, when checking boundary cases before posting the code I >> sent, I discovered this sort of thing: >> >> >>> last_day_of_june = datetime.datetime(2004, 6, 30) # long for clarity >> >>> ldj = last_day_of_june # short for typing >> >>> new_day = datetime.datetime(ldj.year, ldj.month, ldj.day + 1) >> >> Traceback (most recent call last): >> File "", line 1, in -toplevel- >> new_day = datetime.datetime(ldj.year, ldj.month, ldj.day + 1) >> ValueError: day is out of range for month >> >>> >> >> So, adding to the day or the month was out, unless I wanted elaborate >> code to determine which to add to under what circumstances. So then I >> thought, "Well, just change from now.day + 1 to now.year + 1, and all >> problems go away". And then I thought "Ah, but what if I try to run >> the script on Feb. 29? >> >> So, that's why I used now.year + 4. It still leaves open the >> possibility of getting bit by the every so often further correction to >> the calender, but, I *believe* the next one is due in 2100, so I think >> I can live with it. ;-) >> >> I'm not saying it isn't hackish, though. Better ways surely exist. > > > Brian, > > I just can't succeed in reproducing the problems with the boundary > cases with the +4 removed. I've tried setting my computer's clock to > Nov 30, Feb 29, 2004, and Dec 31, 2004 (without changing the time). It's > now about 9 am where I am, and setting the alarm time to 0700 (i.e., on > the next day) works fine in all 3 cases. And of course no problem at > today's date with setting the alarm time to 07:00. > > Isn't that what that note (1) on > implies? > > I did the testing with , > by remarking out the time.sleep() line and noting what the > print_hms(sleepSeconds) function prints. > > Dick Hi Dick and all, I haven't checked your link yet, but thanks for it. (It's in the 'follow when I've time' file.) I think this is all moot in light of Tim's post explaining: > > Actually, you needed simpler code : > > >>>>>>> import datetime >>>>>>> ldj = datetime.datetime(2004, 6, 30) >>>>>>> new_day = ldj + datetime.timedelta(days=1) >>>>>>> print new_day > > 2004-07-01 00:00:00 Why I thought I needed it was that I was trying to do datetime's work for it :-) I'd done: alarm_datetime = datetime.datetime(now.year+4, now.month, now.day, alarm_hour, alarm_minute) after trying: alarm_datetime = datetime.datetime(now.year, now.month, now.day+1, alarm_hour, alarm_minute) That did cause problems if the now datetime was the last day of a month (see last_day_of_june example for proof). (If you aren't getting the same problem is similar circumstances, well, I'm out of ideas on that one.) This was all to the end of constructing an alarm_datetime guaranteed to be in the future from the user supplied alarm_hour, alarm_minute. On the bus today (great place for ideas, the bus ;-), I figured out I could avoid the whole +4 because of leap years by doing something like alarm_datetime = datetime.datetime(now.year+1, 1, 1, alarm_hour, alarm_minute) thus making the new datetime on Jan. 1 and skirting all month-end and leap year issues. But, that is still a kludge, compared to Tim's way. In light of Tim's post (and without having thought about possible further improvements to my approach given this new knowledge) I'd now do: >>> import datetime >>> alarm_hour = 13 # skipping actual user >>> alarm_minute = 25 # input part for ease >>> now = datetime.datetime.now() >>> alarm_datetime = datetime.datetime(now.year, now.month, now.day, alarm_hour, alarm_minute) >>> # I wouldn't be surprised if this can be done more smoothly. >>> # It is likely residue of my original and wrong approach. >>> # I will check and post back if I see the suspicion is right. >>> # But, not before the weekend, I don't think. >>> alarm_datetime = alarm_datetime + datetime.timedelta(days=1) >>> print now 2004-12-07 23:24:58.050000 >>> print alarm_datetime 2004-12-08 13:25:00 >>> And, all is in order :-) (The worry that goes "But wait, what if I want my alarm later today, and not tomorrow?" is what using .seconds is for: >>> alarm_in_seconds = (alarm_datetime - now).seconds >>> alarm_in_seconds 50401 >>> _ / ( 60 * 60.0) 14.000277777777777 Which is what's wanted, as the alarm_datetime is just a midge over 14 hours ahead of the now datetime. The .seconds discards the difference in days, and handles only the difference in seconds.) The note you reference: date2 is moved forward in time if timedelta.days > 0, or backward if timedelta.days < 0. Afterward date2 - date1 == timedelta.days. timedelta.seconds and timedelta.microseconds are ignored. OverflowError is raised if date2.year would be smaller than MINYEAR or larger than MAXYEAR. presupposes you are adding a timedelta to a datetime as in Tim's suggestion. It makes no promises if you were doing something goofy like I was. (If that is what you were trying to get me to see, sorry, but I missed it.) I hope this clarifies things some :-) Thanks, Dick, Liam, and Tim. I've learned a good deal off this thread. Best to all, Brian vdB From cyresse at gmail.com Wed Dec 8 07:12:31 2004 From: cyresse at gmail.com (Liam Clarke) Date: Wed Dec 8 07:12:36 2004 Subject: [Tutor] Re: Could I have used time or datetime modules here? In-Reply-To: <41B689D7.10200@po-box.mcgill.ca> References: <6.1.2.0.2.20041207040419.0480a490@rcblue.com> <41B5D159.3030809@po-box.mcgill.ca> <6.1.2.0.2.20041130082123.07ab1270@rcblue.com> <41B689D7.10200@po-box.mcgill.ca> Message-ID: >alarm_datetime = datetime.datetime(now.year, now.month, now.day, alarm_hour, alarm_minute) Now that's clever. I too, have learnt a large amount from this thread. On Tue, 07 Dec 2004 23:57:59 -0500, Brian van den Broek wrote: > Dick Moores said unto the world upon 2004-12-07 12:04: > > > > Brian van den Broek wrote at 07:50 12/7/2004: > > > >>> It seems I've missed out on something important > >>> BTW I'm not sure you need the +4 of "now.year + 4". I've run this > >>> without the +4 and it doesn't seem to be needed. And notes (1) and > >>> (4) on that page seem to say this, as far as I understand them. > >> > >> > >> I'm not sure I do either :-) > >> > >> Here's why I did it: > >> > >> I discovered that in order to get the right "seconds until alarm" > >> value from the datetime for now and the alarm datetime by subtracting > >> one datetime object from another, I needed the alarm datetime to be in > >> the future. But, since you can set an alarm for 09:00 tomorrow at > >> 22:00 today, I needed the alarm datetime to not use today's date. (If > >> you use today's, you end up with seconds *since* 09:00 this morning, > >> not the desired seconds *until* 09:00 tomorrow morning.) Since > >> timedelta_object.seconds discards all difference save the seconds save > >> those from the hours, minutes, and seconds difference in the two > >> datetime objects, it doesn't matter what date the alarm datetime is > >> set to. (The day information is in timedelta_object.days.) > >> > >> Or, so I thought. I'd first tried getting the alarm datetime by simply > >> taking the date component of datetime.datetime.now() and adding to the > >> day value. That works fine, provided you are not on the last day of > >> the month. But, when checking boundary cases before posting the code I > >> sent, I discovered this sort of thing: > >> > >> >>> last_day_of_june = datetime.datetime(2004, 6, 30) # long for clarity > >> >>> ldj = last_day_of_june # short for typing > >> >>> new_day = datetime.datetime(ldj.year, ldj.month, ldj.day + 1) > >> > >> Traceback (most recent call last): > >> File "", line 1, in -toplevel- > >> new_day = datetime.datetime(ldj.year, ldj.month, ldj.day + 1) > >> ValueError: day is out of range for month > >> >>> > >> > >> So, adding to the day or the month was out, unless I wanted elaborate > >> code to determine which to add to under what circumstances. So then I > >> thought, "Well, just change from now.day + 1 to now.year + 1, and all > >> problems go away". And then I thought "Ah, but what if I try to run > >> the script on Feb. 29? > >> > >> So, that's why I used now.year + 4. It still leaves open the > >> possibility of getting bit by the every so often further correction to > >> the calender, but, I *believe* the next one is due in 2100, so I think > >> I can live with it. ;-) > >> > >> I'm not saying it isn't hackish, though. Better ways surely exist. > > > > > > Brian, > > > > I just can't succeed in reproducing the problems with the boundary > > cases with the +4 removed. I've tried setting my computer's clock to > > Nov 30, Feb 29, 2004, and Dec 31, 2004 (without changing the time). It's > > now about 9 am where I am, and setting the alarm time to 0700 (i.e., on > > the next day) works fine in all 3 cases. And of course no problem at > > today's date with setting the alarm time to 07:00. > > > > Isn't that what that note (1) on > > implies? > > > > I did the testing with , > > by remarking out the time.sleep() line and noting what the > > print_hms(sleepSeconds) function prints. > > > > Dick > > Hi Dick and all, > > I haven't checked your link yet, but thanks for it. (It's in the 'follow > when I've time' file.) > > I think this is all moot in light of Tim's post explaining: > > > > > Actually, you needed simpler code : > > > > > >>>>>>> import datetime > >>>>>>> ldj = datetime.datetime(2004, 6, 30) > >>>>>>> new_day = ldj + datetime.timedelta(days=1) > >>>>>>> print new_day > > > > 2004-07-01 00:00:00 > > Why I thought I needed it was that I was trying to do datetime's work > for it :-) > > I'd done: > alarm_datetime = datetime.datetime(now.year+4, now.month, now.day, > alarm_hour, alarm_minute) > > after trying: > alarm_datetime = datetime.datetime(now.year, now.month, now.day+1, > alarm_hour, alarm_minute) > > That did cause problems if the now datetime was the last day of a month > (see last_day_of_june example for proof). (If you aren't getting the > same problem is similar circumstances, well, I'm out of ideas on that one.) > > This was all to the end of constructing an alarm_datetime guaranteed to > be in the future from the user supplied alarm_hour, alarm_minute. > > On the bus today (great place for ideas, the bus ;-), I figured out I > could avoid the whole +4 because of leap years by doing something like > > alarm_datetime = datetime.datetime(now.year+1, 1, 1, > alarm_hour, alarm_minute) > > thus making the new datetime on Jan. 1 and skirting all month-end and > leap year issues. But, that is still a kludge, compared to Tim's way. > > In light of Tim's post (and without having thought about possible > further improvements to my approach given this new knowledge) I'd now do: > > >>> import datetime > >>> alarm_hour = 13 # skipping actual user > >>> alarm_minute = 25 # input part for ease > >>> now = datetime.datetime.now() > >>> alarm_datetime = datetime.datetime(now.year, now.month, now.day, > alarm_hour, alarm_minute) > >>> # I wouldn't be surprised if this can be done more smoothly. > >>> # It is likely residue of my original and wrong approach. > >>> # I will check and post back if I see the suspicion is right. > >>> # But, not before the weekend, I don't think. > >>> alarm_datetime = alarm_datetime + datetime.timedelta(days=1) > >>> print now > 2004-12-07 23:24:58.050000 > >>> print alarm_datetime > 2004-12-08 13:25:00 > >>> > > And, all is in order :-) > > (The worry that goes "But wait, what if I want my alarm later today, and > not tomorrow?" is what using .seconds is for: > > >>> alarm_in_seconds = (alarm_datetime - now).seconds > >>> alarm_in_seconds > 50401 > >>> _ / ( 60 * 60.0) > 14.000277777777777 > > Which is what's wanted, as the alarm_datetime is just a midge over 14 > hours ahead of the now datetime. The .seconds discards the difference in > days, and handles only the difference in seconds.) > > The note you reference: > > date2 is moved forward in time if timedelta.days > 0, or backward if > timedelta.days < 0. Afterward date2 - date1 == timedelta.days. > timedelta.seconds and timedelta.microseconds are ignored. OverflowError > is raised if date2.year would be smaller than MINYEAR or larger than > MAXYEAR. > > presupposes you are adding a timedelta to a datetime as in Tim's > suggestion. It makes no promises if you were doing something goofy like > I was. (If that is what you were trying to get me to see, sorry, but I > missed it.) > > I hope this clarifies things some :-) > > Thanks, Dick, Liam, and Tim. I've learned a good deal off this thread. > > > > Best to all, > > Brian vdB > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From cyresse at gmail.com Wed Dec 8 11:29:38 2004 From: cyresse at gmail.com (Liam Clarke) Date: Wed Dec 8 11:29:41 2004 Subject: [Tutor] MemoryError Message-ID: Hi all, I'm playing with a file, and attempting to replace a section with a string, and using the following command - seg=codeSt[element:endInd+len(endStr] codeSt=codeSt.replace(seg, hrefString) At the replace, I get a MemoryError. It's part of a for loop, but it gives the error the first time around. The Python docs say - "Raised when an operation runs out of memory but the situation may still be rescued (by deleting some objects). The associated value is a string indicating what kind of (internal) operation ran out of memory. Note that because of the underlying memory management architecture (C's malloc() function), the interpreter may not always be able to completely recover from this situation; it nevertheless raises an exception so that a stack traceback can be printed, in case a run-away program was the cause. " codeSt is a loaded text file that's 228Kb in size. The for loop that the above code is embedded in, generates a slightly new codeSt each time. Now, I had imagined that codeSt=codeSt+10 would destroy the old codeSt in memory and create a new codeSt. Am I right? Because, even if the for loop (which will iterate 267 times) were to keep a new copy of codeSt in memory, it should only need 59Mb of RAM, when I've got near half a gig of RAM and virtual memory. So yeah, I don't know how to troubleshoot this one. Full code is here - http://www.rafb.net/paste/results/ZflMyz31.html Any help that can be offered gratefully appreciated. I don't want to to have to learn C++? Malloc has an evil reputation. Oh, and Python 2.3.4, Windows XP Pro SP1, Athlon 650MHz, 256Mb RAM 20Gb HD, which has 1.6Gb free. In case any of that infos relevant. : ) Regards Liam Clarke -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From mi.janssen at gmail.com Wed Dec 8 14:41:56 2004 From: mi.janssen at gmail.com (Michael Janssen) Date: Wed Dec 8 14:41:59 2004 Subject: [Tutor] MemoryError In-Reply-To: <1ff2dfbf041208054010e4245a@mail.gmail.com> References: <1ff2dfbf041208054010e4245a@mail.gmail.com> Message-ID: <1ff2dfbf041208054154a7414d@mail.gmail.com> [forgot to cc to the list] ---------- Forwarded message ---------- From: Michael Janssen Date: Wed, 8 Dec 2004 14:40:46 +0100 Subject: Re: [Tutor] MemoryError To: Liam Clarke On Wed, 8 Dec 2004 23:29:38 +1300, Liam Clarke wrote: > I'm playing with a file, and attempting to replace a section with a > string, and using the following command - > > seg=codeSt[element:endInd+len(endStr] > codeSt=codeSt.replace(seg, hrefString) > > At the replace, I get a MemoryError. It's part of a for loop, but it > gives the error the first time around. Hello Liam, You might try to narrow the code in where the error happen. Read the file and replace a dummy-seq-string and see what happens. Does this work: "test string".replace("st st", "?") When it works, what is bad with your file? Consider asking comp.lang.python for a greater audience. BTW: some time past the base64 module (base64 is a mail attachment encoding) has a bug leading to a MemoryError when undecoding an empty base64 string. Any free GB of ram did not help. You can allways work arround the replace: new = old[:start] + relace_string + old[end:] which is ugly but perhaps makes your script running. regards Michael From jnoller at gmail.com Wed Dec 8 15:42:20 2004 From: jnoller at gmail.com (Jesse Noller) Date: Wed Dec 8 15:42:22 2004 Subject: [Tutor] Removing/Handing large blocks of text Message-ID: <4222a84904120806426dfc0c5b@mail.gmail.com> Hello, I'm trying to do some text processing with python on a farily large text file (actually, XML, but I am handling it as plaintext as all I need to do is find/replace/move) and I am having problems with trying to identify two lines in the text file, and remove everything in between those two lines (but not the two lines) and then write the file back (I know the file IO part). I'm trying to do this with the re module - the two tags looks like: ... a bunch of text (~1500 lines) ... I need to identify the first tag, and the second, and unconditionally strip out everything in between those two tags, making it look like: I'm familiar with using read/readlines to pull the file into memory and alter the contents via string.replace(str, newstr) but I am not sure where to begin with this other than the typical open/readlines. I'd start with something like: re1 = re.compile('^\') re2 = re.compile('^\<\/foo\>') f = open('foobar.txt', 'r') for lines in f.readlines() match = re.match(re1, line) But I'm lost after this point really, as I can identify the two lines, but I am not sure how to do the processing. thank you -jesse From maxnoel_fr at yahoo.fr Wed Dec 8 16:11:55 2004 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Wed Dec 8 16:13:55 2004 Subject: [Tutor] Removing/Handing large blocks of text In-Reply-To: <4222a84904120806426dfc0c5b@mail.gmail.com> References: <4222a84904120806426dfc0c5b@mail.gmail.com> Message-ID: <7FB370CF-492B-11D9-BFEA-000393CBC88E@yahoo.fr> On Dec 8, 2004, at 14:42, Jesse Noller wrote: > Hello, > > I'm trying to do some text processing with python on a farily large > text file (actually, XML, but I am handling it as plaintext as all I > need to do is find/replace/move) and I am having problems with trying > to identify two lines in the text file, and remove everything in > between those two lines (but not the two lines) and then write the > file back (I know the file IO part). Okay, here are some hints: you need to identify when you enter a block and when you exit a block, keeping in mind that this may happen on the same line (e.g. blah). The rest is trivial. The rest of your message is included as a spoiler space if you want to find the solution by yourself -- however, a 17-line program that does that is included at the end of this message. It prints the resulting file to the standard out, for added flexibility: if you want the result to be in a file, just redirect stdout (python blah.py > out.txt). Oh, one last thing: don't use readlines(), it uses up a lot of memory (especially with big files), and you don't need it since you're reading the file sequentially. Use the file iterator instead. > I'm trying to do this with the re module - the two tags looks like: > > > ... > a bunch of text (~1500 lines) > ... > > > I need to identify the first tag, and the second, and unconditionally > strip out everything in between those two tags, making it look like: > > > > > I'm familiar with using read/readlines to pull the file into memory > and alter the contents via string.replace(str, newstr) but I am not > sure where to begin with this other than the typical open/readlines. > > I'd start with something like: > > re1 = re.compile('^\') > re2 = re.compile('^\<\/foo\>') > > f = open('foobar.txt', 'r') > for lines in f.readlines() > match = re.match(re1, line) > > But I'm lost after this point really, as I can identify the two lines, > but I am not sure how to do the processing. > > thank you > -jesse > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor #!/usr/bin/env python import sre reStart = sre.compile('^\s*\') reEnd = sre.compile('\\s*$') inBlock = False fileSource = open('foobar.txt') for line in fileSource: if reStart.match(line): inBlock = True if not inBlock: print line if reEnd.match(line): inBlock = False fileSource.close() -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From kent37 at tds.net Wed Dec 8 16:15:13 2004 From: kent37 at tds.net (Kent Johnson) Date: Wed Dec 8 16:15:18 2004 Subject: [Tutor] Removing/Handing large blocks of text In-Reply-To: <4222a84904120806426dfc0c5b@mail.gmail.com> References: <4222a84904120806426dfc0c5b@mail.gmail.com> Message-ID: <41B71A81.2050904@tds.net> I would use a loop with a flag to indicate whether you are in the block or not. If the tags are always and on a line by themselves you don't need an re: lines = [] appending = True f = open('foobar.txt', 'r') for line in f: if appending: lines.append(line) if line.strip() == '': appending = False elif line.strip() == '': appending = True lines.append(line) f.close() At the end of this loop lines will have the lines you want to write back. Kent Jesse Noller wrote: > Hello, > > I'm trying to do some text processing with python on a farily large > text file (actually, XML, but I am handling it as plaintext as all I > need to do is find/replace/move) and I am having problems with trying > to identify two lines in the text file, and remove everything in > between those two lines (but not the two lines) and then write the > file back (I know the file IO part). > > I'm trying to do this with the re module - the two tags looks like: > > > ... > a bunch of text (~1500 lines) > ... > > > I need to identify the first tag, and the second, and unconditionally > strip out everything in between those two tags, making it look like: > > > > > I'm familiar with using read/readlines to pull the file into memory > and alter the contents via string.replace(str, newstr) but I am not > sure where to begin with this other than the typical open/readlines. > > I'd start with something like: > > re1 = re.compile('^\') > re2 = re.compile('^\<\/foo\>') > > f = open('foobar.txt', 'r') > for lines in f.readlines() > match = re.match(re1, line) > > But I'm lost after this point really, as I can identify the two lines, > but I am not sure how to do the processing. > > thank you > -jesse > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From rdm at rcblue.com Wed Dec 8 18:01:37 2004 From: rdm at rcblue.com (Dick Moores) Date: Wed Dec 8 18:04:37 2004 Subject: [Tutor] "TypeError: 'int' object is not callable"?? Message-ID: <6.1.2.0.2.20041208085701.04d62ca0@rcblue.com> I got this error msg for this line of code: n = -(2(a**3.0)/27.0 - a*b/3.0 + c) (where a = 1, b = 2, c = 3) And was baffled until I realized the line should be n = -(2*(a**3.0)/27.0 - a*b/3.0 + c) But I still don't understand what "callable" means. Can someone help? Thanks, Dick Moores rdm@rcblue.com From maxnoel_fr at yahoo.fr Wed Dec 8 18:11:42 2004 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Wed Dec 8 18:11:46 2004 Subject: [Tutor] "TypeError: 'int' object is not callable"?? In-Reply-To: <6.1.2.0.2.20041208085701.04d62ca0@rcblue.com> References: <6.1.2.0.2.20041208085701.04d62ca0@rcblue.com> Message-ID: <3B6BB305-493C-11D9-BFEA-000393CBC88E@yahoo.fr> On Dec 8, 2004, at 17:01, Dick Moores wrote: > I got this error msg for this line of code: > > n = -(2(a**3.0)/27.0 - a*b/3.0 + c) > (where a = 1, b = 2, c = 3) > > And was baffled until I realized the line should be > n = -(2*(a**3.0)/27.0 - a*b/3.0 + c) > > But I still don't understand what "callable" means. Can someone help? Basically, when you try to execute your first line, the program tries to call the function 2 on the argument (a**3.0). Which of course fails, because 2 is an int, not a "callable" object (function, method, lambda or class). Hence "'int' object is not callable". -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From kent37 at tds.net Wed Dec 8 18:32:13 2004 From: kent37 at tds.net (Kent Johnson) Date: Wed Dec 8 18:32:16 2004 Subject: [Tutor] "TypeError: 'int' object is not callable"?? In-Reply-To: <6.1.2.0.2.20041208085701.04d62ca0@rcblue.com> References: <6.1.2.0.2.20041208085701.04d62ca0@rcblue.com> Message-ID: <41B73A9D.8050008@tds.net> A callable is something that can be called with functional notation. It can be a function, a class, or in some cases a class instance. In general, any object that has a __call__() special method is callable. The callable() built-in tells you if an object is callable, though you can also just try it. For example, the built-in len is callable and has a __call__ attribute: >>> callable(len) True >>> dir(len) ['__call__', ... ] 1 is not callable and does not have a __call__ attribute: >>> callable(1) False >>> dir(1) [ ] As you discovered, trying to call 1 as a function doesn't work: >>> 1() Traceback (most recent call last): File "", line 1, in ? TypeError: 'int' object is not callable A user-defined function is callable and has a __call__ attribute: >>> def f(): pass ... >>> callable(f) True >>> dir(f) ['__call__', ... ] >>> A class is callable (you call it to create an instance): >>> class C: ... pass ... >>> callable(C) True Instances of a class, in general, are not callable: >>> c=C() >>> callable(c) False You can make a class whose instances are callable by defining a __call__ method on the class. This allows you to make a class whose instances behave like functions, which is sometimes handy. (This behaviour is built-in to Python - __call__() is called a special method. There are many special methods that let you customize the behaviour of a class.) >>> class D: ... def __call__(self, x): ... print 'x =', x ... >>> d=D() # Calling the class creates an instance >>> callable(d) True >>> d(3) # Calling the instance ends up in the __call__() method of the class x = 3 Kent Dick Moores wrote: > I got this error msg for this line of code: > > n = -(2(a**3.0)/27.0 - a*b/3.0 + c) > (where a = 1, b = 2, c = 3) > > And was baffled until I realized the line should be > n = -(2*(a**3.0)/27.0 - a*b/3.0 + c) > > But I still don't understand what "callable" means. Can someone help? > > Thanks, > > Dick Moores > rdm@rcblue.com > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From askoose at sandia.gov Wed Dec 8 19:07:16 2004 From: askoose at sandia.gov (Kooser, Ara S) Date: Wed Dec 8 19:07:36 2004 Subject: [Tutor] Another ? on large text files Message-ID: <7BB911D90C4F384EAAFBB31DEFF990BE187819@ES21SNLNT.srn.sandia.gov> I have a large file (4.1 MB, 2600 pgs) of simulated power spectrums. The problem is that there are 6 separated files all combined into this large file. I know how to read the file in and then remove the header information but how would I go about separating the 6 sections into separate files? The program I have so far reads in the data and then removes the header and footer information (most likely in a very inefficient fashion). The data looks something like this and I just want the numbers. CERIUS Grapher File ! Start of definition for XY graph Power Spectrum component XX A^4/ps^2 v1 >PLOT XY DATA: "Power Spectrum component XX A^4/ps^2" 1 0.0000000E+00 3.1251088E-04 ..PLOT XY METHOD: "Power Spectrum component YY A^4/ps^2" 1 COLOUR RED ....... The footer continues and then runs into the header of the next set of data (no space between them) Thanks, Ara From rdm at rcblue.com Wed Dec 8 19:27:35 2004 From: rdm at rcblue.com (Dick Moores) Date: Wed Dec 8 19:28:32 2004 Subject: [Tutor] "TypeError: 'int' object is not callable"?? In-Reply-To: <3B6BB305-493C-11D9-BFEA-000393CBC88E@yahoo.fr> References: <6.1.2.0.2.20041208085701.04d62ca0@rcblue.com> <3B6BB305-493C-11D9-BFEA-000393CBC88E@yahoo.fr> Message-ID: <6.1.2.0.2.20041208102458.06181d20@rcblue.com> My thanks to both Max and Kent. So Python tries, and fails, to see 2() as a function! I also got some help from Dick From glingl at aon.at Wed Dec 8 19:52:20 2004 From: glingl at aon.at (Gregor Lingl) Date: Wed Dec 8 19:52:02 2004 Subject: [Tutor] Simple RPN calculator In-Reply-To: References: Message-ID: <41B74D64.6000802@aon.at> Terry Carroll schrieb: >On Mon, 6 Dec 2004, Chad Crabtree wrote: > > > >>Bob Gailer wrote: >> >> >> >>>For grins I just wrote one that takes '1 2.3 - 3 4 5 + * /' as >>> >>> >>input >> >> >>>and prints -0.0481481.... 8 lines of Python. That indeed is less >>> >>> >>than >> >> >>>100. Took about 7 minutes to code and test. >>> >>> >>I'm quite interested in seeing the sourcecode for that. >> >> > >Me, too. I'm always interested in cool little Python examples. > > > Not having read the thread, this script prints the same result: inp = raw_input("Gimmi an RPN-expression: ").split() i=0 while len(inp)>1: while inp[i] not in "+-*/": i+=1 print "**", i, inp #1 inp[i-2:i+1] = [str(eval(inp[i-2]+inp[i]+inp[i-1]))] i-=1 print "***", i, inp #2 print inp[0] If you delete the two numbered print statements it also has 8 lines of code. (They are inserted to show what's going on!) Excuse me if this posting suffers from redundancy. I'm very interested in Bob's solution, too Gregor >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > From bgailer at alum.rpi.edu Wed Dec 8 20:39:29 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed Dec 8 20:37:53 2004 Subject: [Tutor] "TypeError: 'int' object is not callable"?? In-Reply-To: <6.1.2.0.2.20041208102458.06181d20@rcblue.com> References: <6.1.2.0.2.20041208085701.04d62ca0@rcblue.com> <3B6BB305-493C-11D9-BFEA-000393CBC88E@yahoo.fr> <6.1.2.0.2.20041208102458.06181d20@rcblue.com> Message-ID: <6.2.0.14.0.20041208123542.030f8d38@mail.mric.net> At 11:27 AM 12/8/2004, Dick Moores wrote: >My thanks to both Max and Kent. So Python tries, and fails, to see 2() as >a function! > >I also got some help from Note that SOME languages use () for call. There are other call constructs, such as: DO function WITH parameters (FoxPro, similar in COBOL) function parameter or parameter1 function parameter2 (APL) Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From bgailer at alum.rpi.edu Wed Dec 8 20:49:11 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed Dec 8 20:47:22 2004 Subject: [Tutor] "TypeError: 'int' object is not callable"?? In-Reply-To: <6.2.0.14.0.20041208123542.030f8d38@mail.mric.net> References: <6.1.2.0.2.20041208085701.04d62ca0@rcblue.com> <3B6BB305-493C-11D9-BFEA-000393CBC88E@yahoo.fr> <6.1.2.0.2.20041208102458.06181d20@rcblue.com> <6.2.0.14.0.20041208123542.030f8d38@mail.mric.net> Message-ID: <6.2.0.14.0.20041208124624.02e073e8@mail.mric.net> At 12:39 PM 12/8/2004, Bob Gailer wrote: >At 11:27 AM 12/8/2004, Dick Moores wrote: >>My thanks to both Max and Kent. So Python tries, and fails, to see 2() as >>a function! >> >>I also got some help from > >Note that SOME languages use () for call. There are other call constructs, >such as: > >DO function WITH parameters (FoxPro, similar in COBOL) > >function parameter or parameter1 function parameter2 (APL) I should add the Python builtin function apply: apply(function, parameters...) Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From jeff at ccvcorp.com Wed Dec 8 21:29:10 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed Dec 8 21:25:16 2004 Subject: [Tutor] MemoryError In-Reply-To: References: Message-ID: <41B76416.6020403@ccvcorp.com> Liam Clarke wrote: > Hi all, > > I'm playing with a file, and attempting to replace a section with a > string, and using the following command - > > seg=codeSt[element:endInd+len(endStr] > codeSt=codeSt.replace(seg, hrefString) > > At the replace, I get a MemoryError. It's part of a for loop, but it > gives the error the first time around. I'm not sure why you're getting the MemoryError, but it'd be easier to figure out if you posted the entire text of the traceback. A few other pointers -- You'll probably get better performance if you put all of this code inside of a function. Even if you're only running it once, putting it in a function allows the interpreter to do some optimization tricks on locals() which can't be done at the module-global level (where you're running now). It's just barely possible that just doing this will help with your MemoryError problem. (You would probably benefit from splitting it into multiple functions, actually. I'd have the code that finds text and url values each in their own function, for example.) Try adding a line in between those two that prints out the value of element and endInd, and then check that those numbers really are valid indexes into codeSt. While you're at it, print out hrefString and make sure it looks like it's supposed to. At the start of your program, you have the following: inp=file("toolkit.txt","r") codeSt=inp.readlines() inp.close() codeSt="".join(codeSt) Since you're not processing by lines, and are explicitly joining all the lines together, why have Python separate them for you? It would be much more efficient to simply use 'codeSt = inp.read()', with no need to join() afterwards. The readlines() method effectively does a read() followed by splitting the result into lines; for your purposes, there's no point in splitting the lines if you're just going to join() them immediately. Instead of finding the start and end index of the segment you want to replace, making a copy of that segment, and then scanning your original string to replace that segment with a new chunk, it would probably make more sense to simply grab codeSt before the segment and after the segment and concatenate them with the new chunk. Thus, your two lines above become codeSt = codeSt[:element] + hrefString \ + codeSt[endInd+len(endStr)] Once again, this would avoid doing the same work twice. > Now, I had imagined that codeSt=codeSt+10 would destroy the old codeSt > in memory and create a new codeSt. Am I right? Actually, this will probably raise a TypeError (cannot concatenate 'str' and 'int' objects). ;) But yes, rebinding codeSt to a new string should allow the old string to be destroyed (if there are no other references to it). Hope that this helps. Jeff Shannon Technician/Programmer Credit International From alan.gauld at freenet.co.uk Wed Dec 8 22:42:14 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed Dec 8 22:42:04 2004 Subject: [Tutor] Removing/Handing large blocks of text References: <4222a84904120806426dfc0c5b@mail.gmail.com> Message-ID: <002101c4dd6e$c8445900$daad8651@xp> > I'm trying to do this with the re module - the two tags looks like: > > > ... > a bunch of text (~1500 lines) > ... > > > I need to identify the first tag, and the second, and unconditionally > strip out everything in between those two tags, making it look like: > > > A very simplistic approach uses a flag: atTag = 0 f = open(...) while not atTag: line = f.readline() if line == '': atTag = True break outFile.write(line) # + \n, I can't remember... while atTag: line = f.readline() if line == '': atTag = False while f: outfile.write(f.readline()) This flag approach is sometimes called a sentinal... I'm sure somebody can find better ways of doing this but I'm too tired to bother right now! :-( The sentinel approach will work... Alan G. From ps_python at yahoo.com Wed Dec 8 22:51:53 2004 From: ps_python at yahoo.com (kumar s) Date: Wed Dec 8 22:51:56 2004 Subject: [Tutor] Please help matching elements from two lists and printing them Message-ID: <20041208215153.20590.qmail@web53704.mail.yahoo.com> Dear group, I have two tables: First table: spot_cor: 432 117 499 631 10 0 326 83 62 197 0 0 37 551 Second table: spot_int 0 0 98 1 0 5470 2 0 113 3 0 5240 4 0 82.5 5 0 92 6 0 5012 7 0 111 8 0 4612 9 0 115 10 0 4676.5 I stored these two tables as lists: >>> spot_cor[0:5] ['432\t117', '499\t631', 10\t0', '326\t83', '62\t197'] >>> spot_int[0:5] [' 0\t 0\t18.9', ' 1\t 0\t649.4', ' 10\t 0\t37.3', ' 3\t 0\t901.6', ' 4\t 0\t14.9'] I want to take each element from spot_cor and search in spot_int, if they match, I want to write all the three columns of spot_int. I did the following way to see what happens when I print element1 and element 2 as tab delim. text: code: >>> for ele1 in spot_cor: for ele2 in spot_int: if ele1 in ele2: print (ele1+'\t'+ele2) 432 117 432 117 17.3 432 117 7 432 117.9 432 117 554 432 117.7 499 631 499 631 23.1 12 185 12 185 19.6 12 185 112 185 42.6 12 185 212 185 26.3 12 185 312 185 111.9 12 185 412 185 193.1 12 185 512 185 21.9 12 185 612 185 22.0 326 83 169 326 83.7 62 197 62 197 18.9 The problem with this script is that it is printing all unwanted element of spot_int list. This is simply crap for me. I want to print the columns only if first two columns of both tables match. The simple reason here I asked it to see if 12 and 185 are contained in two columns and pythons tells me, yes they are present in 112 and 185 and this is a wrong result. Can you please suggest a better method for comparing these two elements and then printing the third column. thank you very much. Cheers K __________________________________ Do you Yahoo!? The all-new My Yahoo! - What will yours do? http://my.yahoo.com From cyresse at gmail.com Wed Dec 8 23:31:40 2004 From: cyresse at gmail.com (Liam Clarke) Date: Wed Dec 8 23:31:44 2004 Subject: [Tutor] MemoryError In-Reply-To: <41B76416.6020403@ccvcorp.com> References: <41B76416.6020403@ccvcorp.com> Message-ID: > I'm not sure why you're getting the MemoryError, but it'd be easier to > figure out if you posted the entire text of the traceback. Traceback: Line 39: seg=codeSt[element:endInd+len(endStr] MemoryError Hehe. Helpful, no? I think I'll sprinkle print statements throughout as suggested, and wrap it in a function for that optimization Jeff mentioned. Thanks for the advice, I'll let you know how it goes. Regards, Liam Clarke I didn't think to On Wed, 08 Dec 2004 12:29:10 -0800, Jeff Shannon wrote: > Liam Clarke wrote: > > > Hi all, > > > > I'm playing with a file, and attempting to replace a section with a > > string, and using the following command - > > > > seg=codeSt[element:endInd+len(endStr] > > codeSt=codeSt.replace(seg, hrefString) > > > > At the replace, I get a MemoryError. It's part of a for loop, but it > > gives the error the first time around. > > > I'm not sure why you're getting the MemoryError, but it'd be easier to > figure out if you posted the entire text of the traceback. > > A few other pointers -- > > You'll probably get better performance if you put all of this code > inside of a function. Even if you're only running it once, putting it > in a function allows the interpreter to do some optimization tricks on > locals() which can't be done at the module-global level (where you're > running now). It's just barely possible that just doing this will > help with your MemoryError problem. (You would probably benefit from > splitting it into multiple functions, actually. I'd have the code > that finds text and url values each in their own function, for example.) > > Try adding a line in between those two that prints out the value of > element and endInd, and then check that those numbers really are valid > indexes into codeSt. While you're at it, print out hrefString and > make sure it looks like it's supposed to. > > At the start of your program, you have the following: > > inp=file("toolkit.txt","r") > codeSt=inp.readlines() > inp.close() > codeSt="".join(codeSt) > > Since you're not processing by lines, and are explicitly joining all > the lines together, why have Python separate them for you? It would > be much more efficient to simply use 'codeSt = inp.read()', with no > need to join() afterwards. The readlines() method effectively does a > read() followed by splitting the result into lines; for your purposes, > there's no point in splitting the lines if you're just going to join() > them immediately. > > Instead of finding the start and end index of the segment you want to > replace, making a copy of that segment, and then scanning your > original string to replace that segment with a new chunk, it would > probably make more sense to simply grab codeSt before the segment and > after the segment and concatenate them with the new chunk. Thus, your > two lines above become > > codeSt = codeSt[:element] + hrefString \ > + codeSt[endInd+len(endStr)] > > Once again, this would avoid doing the same work twice. > > > Now, I had imagined that codeSt=codeSt+10 would destroy the old codeSt > > in memory and create a new codeSt. Am I right? > > Actually, this will probably raise a TypeError (cannot concatenate > 'str' and 'int' objects). ;) But yes, rebinding codeSt to a new > string should allow the old string to be destroyed (if there are no > other references to it). > > Hope that this helps. > > Jeff Shannon > Technician/Programmer > Credit International > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From cyresse at gmail.com Wed Dec 8 23:32:35 2004 From: cyresse at gmail.com (Liam Clarke) Date: Wed Dec 8 23:32:41 2004 Subject: [Tutor] MemoryError In-Reply-To: References: <41B76416.6020403@ccvcorp.com> Message-ID: Oh, and I never knew about .read() for a file object. I always just used readline/readlines. Silly, really. On Thu, 9 Dec 2004 11:31:40 +1300, Liam Clarke wrote: > > I'm not sure why you're getting the MemoryError, but it'd be easier to > > figure out if you posted the entire text of the traceback. > > > Traceback: > > Line 39: seg=codeSt[element:endInd+len(endStr] > MemoryError > > Hehe. Helpful, no? > > I think I'll sprinkle print statements throughout as suggested, and > wrap it in a function for that optimization Jeff mentioned. > > Thanks for the advice, I'll let you know how it goes. > > Regards, > > Liam Clarke > > I didn't think to > > > On Wed, 08 Dec 2004 12:29:10 -0800, Jeff Shannon wrote: > > Liam Clarke wrote: > > > > > Hi all, > > > > > > I'm playing with a file, and attempting to replace a section with a > > > string, and using the following command - > > > > > > seg=codeSt[element:endInd+len(endStr] > > > codeSt=codeSt.replace(seg, hrefString) > > > > > > At the replace, I get a MemoryError. It's part of a for loop, but it > > > gives the error the first time around. > > > > > > I'm not sure why you're getting the MemoryError, but it'd be easier to > > figure out if you posted the entire text of the traceback. > > > > A few other pointers -- > > > > You'll probably get better performance if you put all of this code > > inside of a function. Even if you're only running it once, putting it > > in a function allows the interpreter to do some optimization tricks on > > locals() which can't be done at the module-global level (where you're > > running now). It's just barely possible that just doing this will > > help with your MemoryError problem. (You would probably benefit from > > splitting it into multiple functions, actually. I'd have the code > > that finds text and url values each in their own function, for example.) > > > > Try adding a line in between those two that prints out the value of > > element and endInd, and then check that those numbers really are valid > > indexes into codeSt. While you're at it, print out hrefString and > > make sure it looks like it's supposed to. > > > > At the start of your program, you have the following: > > > > inp=file("toolkit.txt","r") > > codeSt=inp.readlines() > > inp.close() > > codeSt="".join(codeSt) > > > > Since you're not processing by lines, and are explicitly joining all > > the lines together, why have Python separate them for you? It would > > be much more efficient to simply use 'codeSt = inp.read()', with no > > need to join() afterwards. The readlines() method effectively does a > > read() followed by splitting the result into lines; for your purposes, > > there's no point in splitting the lines if you're just going to join() > > them immediately. > > > > Instead of finding the start and end index of the segment you want to > > replace, making a copy of that segment, and then scanning your > > original string to replace that segment with a new chunk, it would > > probably make more sense to simply grab codeSt before the segment and > > after the segment and concatenate them with the new chunk. Thus, your > > two lines above become > > > > codeSt = codeSt[:element] + hrefString \ > > + codeSt[endInd+len(endStr)] > > > > Once again, this would avoid doing the same work twice. > > > > > Now, I had imagined that codeSt=codeSt+10 would destroy the old codeSt > > > in memory and create a new codeSt. Am I right? > > > > Actually, this will probably raise a TypeError (cannot concatenate > > 'str' and 'int' objects). ;) But yes, rebinding codeSt to a new > > string should allow the old string to be destroyed (if there are no > > other references to it). > > > > Hope that this helps. > > > > Jeff Shannon > > Technician/Programmer > > Credit International > > > > > > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > -- > 'There is only one basic human right, and that is to do as you damn well please. > And with it comes the only basic human duty, to take the consequences. > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From bgailer at alum.rpi.edu Wed Dec 8 23:57:43 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed Dec 8 23:55:56 2004 Subject: [Tutor] Please help matching elements from two lists and printing them In-Reply-To: <20041208215153.20590.qmail@web53704.mail.yahoo.com> References: <20041208215153.20590.qmail@web53704.mail.yahoo.com> Message-ID: <6.2.0.14.0.20041208152900.02c9d538@mail.mric.net> At 02:51 PM 12/8/2004, kumar s wrote: >Dear group, > > I have two tables: > >First table: spot_cor: >432 117 >499 631 >10 0 >326 83 >62 197 >0 0 >37 551 > > > >Second table: spot_int >0 0 98 >1 0 5470 >2 0 113 >3 0 5240 >4 0 82.5 >5 0 92 >6 0 5012 >7 0 111 >8 0 4612 >9 0 115 >10 0 4676.5 > > > >I stored these two tables as lists: > > >>> spot_cor[0:5] >['432\t117', '499\t631', 10\t0', '326\t83', '62\t197'] Note there is no ' before the 10. That won't fly' > >>> spot_int[0:5] >[' 0\t 0\t18.9', ' 1\t 0\t649.4', ' 10\t >0\t37.3', ' 3\t 0\t901.6', ' 4\t 0\t14.9'] It would be a lot easier to work with if the lists looked like (assumes all data are numeric): [(432,117), (499,631), (10,0), (326,83), (62,197)] [(0,0,18.9), (1,0,649.4), (10,0,37.3), (3,0,901.6), (4,0,14.9)] What is the source for this data? Is it a tab-delimited file? If so the CSV module can help make this translation. I also assume that you want the first 2 elements of a spot_int element to match a spot_cor element. Then (for the subset of data you've provided): >>> for ele1 in spot_cor: ... for ele2 in spot_int: ... if ele1 == ele2[:2]: ... print "%8s %8s %8s" % ele2 ... 10 0 37.3 >I want to write all the three columns of spot_int. >[snip] Hope that helps. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From alan.gauld at freenet.co.uk Wed Dec 8 23:56:39 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed Dec 8 23:56:30 2004 Subject: [Tutor] "TypeError: 'int' object is not callable"?? References: <6.1.2.0.2.20041208085701.04d62ca0@rcblue.com><3B6BB305-493C-11D9-BFEA-000393CBC88E@yahoo.fr><6.1.2.0.2.20041208102458.06181d20@rcblue.com> <6.2.0.14.0.20041208123542.030f8d38@mail.mric.net> Message-ID: <003801c4dd79$2db8bec0$daad8651@xp> > Note that SOME languages use () for call. There are other call constructs, > such as: > > DO function WITH parameters (FoxPro, similar in COBOL) > > function parameter or parameter1 function parameter2 (APL) And in Smalltalk: object message: parameter1 : parameter2 : parameter3 Or as an example of a message and one descriptor. myArray put: foo at: 5 The array method is known as "put:at:" No parens to be seen (they have a completely different meaning in Smalltalk) Alan G. From alan.gauld at freenet.co.uk Thu Dec 9 00:02:18 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Dec 9 00:02:06 2004 Subject: [Tutor] MemoryError References: <41B76416.6020403@ccvcorp.com> Message-ID: <004301c4dd79$f8064bc0$daad8651@xp> > Traceback: > > Line 39: seg=codeSt[element:endInd+len(endStr] > MemoryError > > Hehe. Helpful, no? Sometimes seeing the whole traceback gives clues as to whats throwing the wobbly, without the full stack its hard to tell. However before worrying about that I'd add a print statement to print out all those values: codeStr element, endInd len(endstr) I suspect the memory error might be an indexing error, running off the end of the string or similar... But lets see those values at the point of failure. For your own benefit it might be easier just to use the debugger, just set a breakpoint on the line then check the values when the debugger stops... Alan G. From jeff at ccvcorp.com Thu Dec 9 00:25:30 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu Dec 9 00:21:36 2004 Subject: [Tutor] MemoryError In-Reply-To: References: <41B76416.6020403@ccvcorp.com> Message-ID: <41B78D6A.7040107@ccvcorp.com> Liam Clarke wrote: >>I'm not sure why you're getting the MemoryError, but it'd be easier to >>figure out if you posted the entire text of the traceback. > > Traceback: > > Line 39: seg=codeSt[element:endInd+len(endStr] > MemoryError > > Hehe. Helpful, no? Actually, it was the "usual bit about in module" that might *be* helpful. ;) Often, something can be determined by the sequence of function calls listed there. Though I suppose, now that I think of it, that since your code is all module-level, there wouldn't be any function stack in this case... Still, in general, when asking for help with something that throws an exception, it's always best to copy & paste the entire text of the exception. One thing that I've noticed, which I thought was just a typo in your original email but which is duplicated again here (it's not present on the web page you linked to) -- you have a mismatched parenthesis in your len() call. It's "[ ... len(endstr]" -- there's no ')' to close the function call. Given that this typo isn't on the web page, I'm not sure whether it's actually there in the code you're running or not. I'd have *thought*, however, that if it *is* present, you'd get a syntax error rather than a memory error, so it's probably not there but you should check it anyhow. :) Jeff Shannon Technician/Programmer Credit International From bgailer at alum.rpi.edu Mon Dec 6 23:03:07 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu Dec 9 02:49:54 2004 Subject: [Tutor] Simple RPN calculator Message-ID: <6.2.0.14.0.20041206145220.05a574d0@mail.mric.net> At 06:05 AM 12/6/2004, you wrote: >Bob Gailer wrote: > > > For grins I just wrote one that takes '1 2.3 - 3 4 5 + * /' as input > > and prints -0.0481481.... 8 lines of Python. That indeed is less than > > 100. Took about 7 minutes to code and test. > >I'm quite interested in seeing the sourcecode for that. I've made it interactive (enter an operand or operator and hit enter); it displays the top of the stack. I added . ^ and %. No error checking. import operator as op def rpn(o,stack = [],d = {'*':op.mul, '+':op.add, '/':op.truediv, '%':op.mod, '-':op.sub, '^':op.pow, '.':lambda x,y:x+.1*y}): if o in d: stack[-2:] = [d[o](stack[-2], stack[-1])] elif o: stack.append(float(o)) # could bomb here if input not floatable! else: return 1 print stack[-1] while 1: if rpn(raw_input('>')): break Let me know what you think. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From bigpimpin10451 at earthlink.net Thu Dec 9 04:05:31 2004 From: bigpimpin10451 at earthlink.net (bigpimpin10451@earthlink.net) Date: Thu Dec 9 04:06:18 2004 Subject: [Tutor] Vpython Message-ID: <12329567.1102561531889.JavaMail.root@daisy.psp.pas.earthlink.net> I was wondering were can I find some Vpython graphics program codes that are readily available. From guillermo.fernandez.castellanos at gmail.com Thu Dec 9 04:25:55 2004 From: guillermo.fernandez.castellanos at gmail.com (Guillermo Fernandez Castellanos) Date: Thu Dec 9 04:26:02 2004 Subject: [Tutor] Vpython In-Reply-To: <12329567.1102561531889.JavaMail.root@daisy.psp.pas.earthlink.net> References: <12329567.1102561531889.JavaMail.root@daisy.psp.pas.earthlink.net> Message-ID: <7d7029e7041208192533496db5@mail.gmail.com> Hi, On the Vpython homepage they have links to quite a few programs: http://vpython.org/contributed.html http://www.physics.syr.edu/%7Esalgado/software/vpython/ Should be enough for a start. Enjoy, Guille On Wed, 8 Dec 2004 22:05:31 -0500 (GMT-05:00), bigpimpin10451@earthlink.net wrote: > I was wondering were can I find some Vpython graphics program codes that are readily available. > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From ps_python at yahoo.com Thu Dec 9 04:52:38 2004 From: ps_python at yahoo.com (kumar s) Date: Thu Dec 9 04:52:41 2004 Subject: [Tutor] Please help matching elements from two lists and printing them In-Reply-To: <6.2.0.14.0.20041208152900.02c9d538@mail.mric.net> Message-ID: <20041209035238.72830.qmail@web53708.mail.yahoo.com> Hi, thank you very much for suggesting a way. In fact I tried and I found another way to do it. could you please suggest if something is wrong because I have false positive results in the output. That means I getting more that the values I have in spot_cor. For example I have 2500 elements in spot_cor list. I am searching each element if it is in spot_init. IF it is there then I am writing it to a file. What I expect is to get 2500 elements. However I am getting 500 elements extra. I do not understand how is this possible. Code: >>> out = open('sa_int_2.txt','w') >>> for ele1 in range(len(spot_cor)): x = spot_cor[ele1] for ele2 in range(len(spot_int)): cols = split(spot_int[ele2],'\t') y = (cols[0]+'\t'+cols[1]) if x == y: for ele3 in spot_int: if y in ele3: out.write(ele3) out.write('\n') On top of this this process is VERY SLOW on high end server too. I think its just the way it is to deal with string processing. As you asked I am all parsing out the pieces for a tab-delimitted text. I can get the values as CSV instead of tab delimitted. But what is the way using CSV to deal with this situation. thanks Kumar --- Bob Gailer wrote: > At 02:51 PM 12/8/2004, kumar s wrote: > >Dear group, > > > > I have two tables: > > > >First table: spot_cor: > >432 117 > >499 631 > >10 0 > >326 83 > >62 197 > >0 0 > >37 551 > > > > > > > >Second table: spot_int > >0 0 98 > >1 0 5470 > >2 0 113 > >3 0 5240 > >4 0 82.5 > >5 0 92 > >6 0 5012 > >7 0 111 > >8 0 4612 > >9 0 115 > >10 0 4676.5 > > > > > > > >I stored these two tables as lists: > > > > >>> spot_cor[0:5] > >['432\t117', '499\t631', 10\t0', '326\t83', > '62\t197'] > > Note there is no ' before the 10. That won't fly' > > > >>> spot_int[0:5] > >[' 0\t 0\t18.9', ' 1\t 0\t649.4', ' 10\t > >0\t37.3', ' 3\t 0\t901.6', ' 4\t 0\t14.9'] > > It would be a lot easier to work with if the lists > looked like (assumes all > data are numeric): > [(432,117), (499,631), (10,0), (326,83), (62,197)] > [(0,0,18.9), (1,0,649.4), (10,0,37.3), (3,0,901.6), > (4,0,14.9)] > > What is the source for this data? Is it a > tab-delimited file? If so the CSV > module can help make this translation. > > I also assume that you want the first 2 elements of > a spot_int element to > match a spot_cor element. > > Then (for the subset of data you've provided): > > >>> for ele1 in spot_cor: > ... for ele2 in spot_int: > ... if ele1 == ele2[:2]: > ... print "%8s %8s %8s" % ele2 > ... > 10 0 37.3 > > >I want to write all the three columns of spot_int. > >[snip] > > Hope that helps. > > Bob Gailer > bgailer@alum.rpi.edu > 303 442 2625 home > 720 938 2625 cell > > __________________________________ Do you Yahoo!? Yahoo! Mail - 250MB free storage. Do more. Manage less. http://info.mail.yahoo.com/mail_250 From bvande at po-box.mcgill.ca Thu Dec 9 06:12:04 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Thu Dec 9 06:12:42 2004 Subject: [Tutor] Re: Could I have used time or datetime modules here? In-Reply-To: <41B689D7.10200@po-box.mcgill.ca> References: <6.1.2.0.2.20041207040419.0480a490@rcblue.com> <41B5D159.3030809@po-box.mcgill.ca> <6.1.2.0.2.20041130082123.07ab1270@rcblue.com> <41B689D7.10200@po-box.mcgill.ca> Message-ID: <41B7DEA4.8060909@po-box.mcgill.ca> Brian van den Broek said unto the world upon 2004-12-07 23:57: > Dick Moores said unto the world upon 2004-12-07 12:04: > > The note you reference: > > date2 is moved forward in time if timedelta.days > 0, or backward if > timedelta.days < 0. Afterward date2 - date1 == timedelta.days. > timedelta.seconds and timedelta.microseconds are ignored. OverflowError > is raised if date2.year would be smaller than MINYEAR or larger than > MAXYEAR. > > presupposes you are adding a timedelta to a datetime as in Tim's > suggestion. It makes no promises if you were doing something goofy like > I was. (If that is what you were trying to get me to see, sorry, but I > missed it.) Hey Dick and all, I've taken a look at your code and finally seen what you meant, Dick. You were trusting datetime (along the same lines that Tim suggested to me) and thus weren't facing the problems I'd caused for myself. Sorry for missing your point before. Thanks, Brian vdB > > I hope this clarifies things some :-) Ah, irony! From cyresse at gmail.com Thu Dec 9 10:30:32 2004 From: cyresse at gmail.com (Liam Clarke) Date: Thu Dec 9 10:30:36 2004 Subject: [Tutor] Re: Could I have used time or datetime modules here? In-Reply-To: <41B7DEA4.8060909@po-box.mcgill.ca> References: <6.1.2.0.2.20041207040419.0480a490@rcblue.com> <41B5D159.3030809@po-box.mcgill.ca> <6.1.2.0.2.20041130082123.07ab1270@rcblue.com> <41B689D7.10200@po-box.mcgill.ca> <41B7DEA4.8060909@po-box.mcgill.ca> Message-ID: Hi Brian and Dick, I for one have learnt a lot from this combined poke around the workings of datetime. The datetime.year thing never occurred to me, yet it was so obvious when I saw it being used. I give you, my python alarm clock timing mechanism, final version! http://www.rafb.net/paste/results/qur2Pw95.html It works on the cmd line - python alarm.py 17:30 Sets the alarm for the next occurrence of 17:30, using nothing but datetime.datetime objects, and one timedelta (maybe). 'Twas a good discussion. : ) Liam Clarke On Thu, 09 Dec 2004 00:12:04 -0500, Brian van den Broek wrote: > Brian van den Broek said unto the world upon 2004-12-07 23:57: > > Dick Moores said unto the world upon 2004-12-07 12:04: > > > > > > > > > The note you reference: > > > > date2 is moved forward in time if timedelta.days > 0, or backward if > > timedelta.days < 0. Afterward date2 - date1 == timedelta.days. > > timedelta.seconds and timedelta.microseconds are ignored. OverflowError > > is raised if date2.year would be smaller than MINYEAR or larger than > > MAXYEAR. > > > > presupposes you are adding a timedelta to a datetime as in Tim's > > suggestion. It makes no promises if you were doing something goofy like > > I was. (If that is what you were trying to get me to see, sorry, but I > > missed it.) > > Hey Dick and all, > > I've taken a look at your code and finally seen what you meant, Dick. > You were trusting datetime (along the same lines that Tim suggested to > me) and thus weren't facing the problems I'd caused for myself. Sorry > for missing your point before. Thanks, > > Brian vdB > > > > > I hope this clarifies things some :-) > > Ah, irony! > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From cyresse at gmail.com Thu Dec 9 11:04:04 2004 From: cyresse at gmail.com (Liam Clarke) Date: Thu Dec 9 11:04:08 2004 Subject: [Tutor] MemoryError In-Reply-To: <41B78D6A.7040107@ccvcorp.com> References: <41B76416.6020403@ccvcorp.com> <41B78D6A.7040107@ccvcorp.com> Message-ID: Well, I figured out the memory error relatively easily once I poked some stuff, I was using codeSt.find instead of codeSt.index, so it was returning no matches as -1, index raises an error for me, and I wasn't catering for that -1. The MemoryError occurred when Python wanted to slice from 160,000 to -1 or 0. Was quite funny watching 1 Gb of paging file disappear in seconds. But, I give up. Now, I've got several more bugs pop up. I've got an index of integers that has the occasional index stored as a string. I have indexes that start pointing at the right place, but when it comes time to slice, the right place has moved. Unsure why, I'm specifically moving from highest to lowest to avoid messing with the index values. Even if nothing changes, my stored indexes go off course. This is yuck. So, I'm going to throw caution to the wind, and try an re approach. It can't be any more unwieldy and ugly than what I've got going at the moment. Thanks for all the help, I'm off to get myself another problem. Regards, Liam Clarke On Wed, 08 Dec 2004 15:25:30 -0800, Jeff Shannon wrote: > Liam Clarke wrote: > > >>I'm not sure why you're getting the MemoryError, but it'd be easier to > >>figure out if you posted the entire text of the traceback. > > > > Traceback: > > > > Line 39: seg=codeSt[element:endInd+len(endStr] > > MemoryError > > > > Hehe. Helpful, no? > > Actually, it was the "usual bit about in module" that might *be* > helpful. ;) Often, something can be determined by the sequence of > function calls listed there. Though I suppose, now that I think of > it, that since your code is all module-level, there wouldn't be any > function stack in this case... Still, in general, when asking for > help with something that throws an exception, it's always best to copy > & paste the entire text of the exception. > > One thing that I've noticed, which I thought was just a typo in your > original email but which is duplicated again here (it's not present on > the web page you linked to) -- you have a mismatched parenthesis in > your len() call. It's "[ ... len(endstr]" -- there's no ')' to close > the function call. Given that this typo isn't on the web page, I'm > not sure whether it's actually there in the code you're running or > not. I'd have *thought*, however, that if it *is* present, you'd get > a syntax error rather than a memory error, so it's probably not there > but you should check it anyhow. :) > > > > Jeff Shannon > Technician/Programmer > Credit International > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From alan.gauld at freenet.co.uk Thu Dec 9 11:35:13 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Dec 9 11:34:53 2004 Subject: [Tutor] Please help matching elements from two lists and printingthem References: <20041209035238.72830.qmail@web53708.mail.yahoo.com> Message-ID: <007201c4ddda$c4a82760$daad8651@xp> > >>> out = open('sa_int_2.txt','w') > >>> for ele1 in range(len(spot_cor)): > x = spot_cor[ele1] replace this with for x in spot_cor: > for ele2 in range(len(spot_int)): > cols = split(spot_int[ele2],'\t') and this with for item in spot_int: cols = split(item,'\t') > y = (cols[0]+'\t'+cols[1]) > if x == y: > for ele3 in spot_int: > if y in ele3: > out.write(ele3) > out.write('\n') But that doesn't fix the problem, it just simplifies the code! > On top of this this process is VERY SLOW on high end > server too. I think its just the way it is to deal > with string processing. It looks like you have 3 (4?!) levels of nested loops (altho' I can't really tell because the indentation got lost) , and that is usually going to be slow! > As you asked I am all parsing out the pieces for a > tab-delimitted text. I can get the values as CSV > instead of tab delimitted. But what is the way using > CSV to deal with this situation. There is a CSV module which means you have standard, tested code to start with... Sounds like a good place to start from. Alan G. From rdm at rcblue.com Thu Dec 9 11:58:34 2004 From: rdm at rcblue.com (Dick Moores) Date: Thu Dec 9 11:58:39 2004 Subject: [Tutor] How to get the 2 complex cube roots of 1? Message-ID: <6.1.2.0.2.20041209024617.03506eb0@rcblue.com> My trusty $10 Casio calculator tells me that the 3 cube roots of 1 are: 1, (-.5 +0.866025403j), and (-.5 -0.866025403j), or thereabouts. Is there a way to do this in Python? Checking the Casio results with Python: >>> 1**3 1 >>> (-.5 + .866025403j)**3 (0.99999999796196859+1.1766579932626087e-009j) >>> (-.5 - .866025403j)**3 (0.99999999796196859-1.1766579932626087e-009j) Thanks, Dick Moores rdm@rcblue.com From kent37 at tds.net Thu Dec 9 11:58:52 2004 From: kent37 at tds.net (Kent Johnson) Date: Thu Dec 9 11:58:54 2004 Subject: [Tutor] Re: Could I have used time or datetime modules here? In-Reply-To: References: <6.1.2.0.2.20041207040419.0480a490@rcblue.com> <41B5D159.3030809@po-box.mcgill.ca> <6.1.2.0.2.20041130082123.07ab1270@rcblue.com> <41B689D7.10200@po-box.mcgill.ca> <41B7DEA4.8060909@po-box.mcgill.ca> Message-ID: <41B82FEC.6080807@tds.net> Liam Clarke wrote: > Hi Brian and Dick, > > I for one have learnt a lot from this combined poke around the > workings of datetime. The datetime.year thing never occurred to me, > yet it was so obvious when I saw it being used. > > I give you, my python alarm clock timing mechanism, final version! > > http://www.rafb.net/paste/results/qur2Pw95.html Excuse me for butting in at the last minute, but you can use datetime for the date comparison as well. If you create desiredTime first, you can directly compare it with nowTime and increment it if necessary. Also note you can give better names to the hour and minute strings by using tuple assignment: ja=sys.argv[1] hh, mm=ja.split(':') nowTime=datetime.datetime.now() desiredTime=nowTime.replace(hour=int(hh), minute=int(mm),second=0) if desiredTime <= nowTime: desiredTime += datetime.timedelta(days=1) Kent > > It works on the cmd line - > > python alarm.py 17:30 > > Sets the alarm for the next occurrence of 17:30, using nothing but > datetime.datetime objects, and one timedelta (maybe). > > 'Twas a good discussion. : ) > > Liam Clarke > > On Thu, 09 Dec 2004 00:12:04 -0500, Brian van den Broek > wrote: > >>Brian van den Broek said unto the world upon 2004-12-07 23:57: >> >>>Dick Moores said unto the world upon 2004-12-07 12:04: >>> >> >> >> >> >> >>>The note you reference: >>> >>>date2 is moved forward in time if timedelta.days > 0, or backward if >>>timedelta.days < 0. Afterward date2 - date1 == timedelta.days. >>>timedelta.seconds and timedelta.microseconds are ignored. OverflowError >>>is raised if date2.year would be smaller than MINYEAR or larger than >>>MAXYEAR. >>> >>>presupposes you are adding a timedelta to a datetime as in Tim's >>>suggestion. It makes no promises if you were doing something goofy like >>>I was. (If that is what you were trying to get me to see, sorry, but I >>>missed it.) >> >>Hey Dick and all, >> >>I've taken a look at your code and finally seen what you meant, Dick. >>You were trusting datetime (along the same lines that Tim suggested to >>me) and thus weren't facing the problems I'd caused for myself. Sorry >>for missing your point before. Thanks, >> >>Brian vdB >> >> >>>I hope this clarifies things some :-) >> >>Ah, irony! >> >> >> >> >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor >> > > > From cyresse at gmail.com Thu Dec 9 12:11:56 2004 From: cyresse at gmail.com (Liam Clarke) Date: Thu Dec 9 12:14:16 2004 Subject: [Tutor] String matching? In-Reply-To: <41B661AA.8040700@tds.net> References: <41B5B841.2060408@ezabel.com> <41B661AA.8040700@tds.net> Message-ID: Hi Kent, Just wanted to say thanks for the advice on the regular expressions. I've just created a regular expression which finds all 267 applets, my .index iterations were producing some cockeyed results, so I tried re in desperation, and it works, so simply. Looks pretty menacing, but it's good. Got to say, that re is very powerful, but that redemo.py you recommended is brilliant for a beginner. I just wrote my re pattern in there, and used it to troubleshoot. So yeah, thanks again. Regards, Liam Clarke On Tue, 07 Dec 2004 21:06:34 -0500, Kent Johnson wrote: > Liam Clarke wrote: > > And thanks for the re, hopefully I won't have to use it, but it gives > > me a starting point to poke the re module from. > > BTW Python comes with a nice tool for experimenting with regular expressions. Try running > Python23\Tools\Scripts\redemo.py > > Kent > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From matthew.williams at cancer.org.uk Thu Dec 9 12:21:20 2004 From: matthew.williams at cancer.org.uk (Matt Williams) Date: Thu Dec 9 12:21:51 2004 Subject: [Tutor] How to find complex roots Message-ID: <1102591279.6535.33.camel@dhcp0320.acl.icnet.uk> Dick Mores wrote: My trusty $10 Casio calculator tells me that the 3 cube roots of 1 are: 1, (-.5 +0.866025403j), and (-.5 -0.866025403j), or thereabouts. Is there a way to do this in Python? I think the neatest approach might be to consider that the n-complex roots form at equal angle around the origin on an Argand diagram (basically a cartesian plane) - here the points (in "standard") cartesian notation are at (1,0), (-0.5, 0.86) and (-0.5, -0.86). The whole effect looks a bit like a Mercedes-Benz symbol rotated clockwise by 90 degrees. The points, in this case, lie on the unit circle. As a result, I think you could just divide 360 by n (for the n-roots), set the 1st root at (1,0) and then position the others around the circle, incrementing by the required number of degrees. If I've remembered correctly, for c where |c| <>1, the argument is the same, but you need to take the nth root of the absolute value of c (this can be ignored when we're doing it for 1, as of course the nth root of 1 is 1). Obviously I haven't included any code....but I hope this helps a bit. Matt P.S. Thrilled to be able to answer something on the tutor list, instead of just asking dumb questions! -- Dr. M. Williams MRCP(UK) Clinical Research Fellow,Cancer Research UK +44 (0)207 269 2953 +44 (0)7834 899570 The views, opinions and judgements expressed in this message are solely those of the author. The message may not have been reviewed or approved by Cancer Research UK From pierre.barbier at cirad.fr Thu Dec 9 12:25:32 2004 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Thu Dec 9 12:24:36 2004 Subject: [Tutor] How to get the 2 complex cube roots of 1? In-Reply-To: <6.1.2.0.2.20041209024617.03506eb0@rcblue.com> References: <6.1.2.0.2.20041209024617.03506eb0@rcblue.com> Message-ID: <41B8362C.5080506@cirad.fr> Do you want : the roots of 1 ? or something more general ? Because the nth-roots of 1 are defined by : r = exp(2*i*pi*k/n) with k = {0,1,...n-1} If it's more complex ... then I don't know :) Pierre Dick Moores a ?crit : > My trusty $10 Casio calculator tells me that the 3 cube roots of 1 are: > 1, (-.5 +0.866025403j), and (-.5 -0.866025403j), or thereabouts. Is > there a way to do this in Python? > > Checking the Casio results with Python: > >>> 1**3 > 1 > >>> (-.5 + .866025403j)**3 > (0.99999999796196859+1.1766579932626087e-009j) > >>> (-.5 - .866025403j)**3 > (0.99999999796196859-1.1766579932626087e-009j) > > > Thanks, > > Dick Moores > rdm@rcblue.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 77 fax : (33) 4 67 61 56 68 From kent37 at tds.net Thu Dec 9 12:33:05 2004 From: kent37 at tds.net (Kent Johnson) Date: Thu Dec 9 12:33:06 2004 Subject: [Tutor] MemoryError In-Reply-To: References: <41B76416.6020403@ccvcorp.com> <41B78D6A.7040107@ccvcorp.com> Message-ID: <41B837F1.8030801@tds.net> Liam, I'm sorry to hear you so discouraged. It sourds like your program has gotten too big for you to clearly understand what it is doing. An earlier poster suggested that you break your program up into functions. This is a very good idea, especially if you do it from the start. A very powerful technique for developing a complex program is to start with small pieces and build up from them. The pieces can be coded *and tested* independently. Because they are known to work, you can confidently build larger pieces by hooking together the small ones. In your case, a very simple place to start would be a function to get rid of the '=\n' and '=3D' strings: def cleanup(codeSt): codeSt=codeSt.replace("=\n",'') codeSt=codeSt.replace('=3D','=') return codeSt Using the unittest module you could write a test like this: import unittest class CodeFixTest(unittest.TestCase): def test_cleanup(self): self.assertEquals('', cleanup('')) if __name__ == '__main__': unittest.main() That's pretty simple. Now move on to a function that, given an applet tag, figures out the corresponding link tag. Write tests for that function using examples from your actual data. You could have another function that finds the applet tags. Finally a function that puts it all together. Still you can have unit tests that make sure it is working correctly. When you are done you have a working, well-tested program and a suite of unit tests for it. Keep the tests - they will be handy if you ever want to make a change. HTH Kent Liam Clarke wrote: > Well, I figured out the memory error relatively easily once I poked > some stuff, I was using codeSt.find instead of codeSt.index, so it was > returning no matches as -1, index raises an error for me, and I wasn't > catering for that -1. The MemoryError occurred when Python wanted to > slice from 160,000 to -1 or 0. > > Was quite funny watching 1 Gb of paging file disappear in seconds. > > But, I give up. Now, I've got several more bugs pop up. I've got an > index of integers that has the occasional index stored as a string. I > have indexes that start pointing at the right place, but when it comes > time to slice, the right place has moved. Unsure why, I'm specifically > moving from highest to lowest to avoid messing with the index values. > Even if nothing changes, my stored indexes go off course. This is > yuck. > > So, I'm going to throw caution to the wind, and try an re approach. It > can't be any more unwieldy and ugly than what I've got going at the > moment. > > Thanks for all the help, I'm off to get myself another problem. > > Regards, > > Liam Clarke > > On Wed, 08 Dec 2004 15:25:30 -0800, Jeff Shannon wrote: > >>Liam Clarke wrote: >> >> >>>>I'm not sure why you're getting the MemoryError, but it'd be easier to >>>>figure out if you posted the entire text of the traceback. >>> >>>Traceback: >>> >>>Line 39: seg=codeSt[element:endInd+len(endStr] >>>MemoryError >>> >>>Hehe. Helpful, no? >> >>Actually, it was the "usual bit about in module" that might *be* >>helpful. ;) Often, something can be determined by the sequence of >>function calls listed there. Though I suppose, now that I think of >>it, that since your code is all module-level, there wouldn't be any >>function stack in this case... Still, in general, when asking for >>help with something that throws an exception, it's always best to copy >>& paste the entire text of the exception. >> >>One thing that I've noticed, which I thought was just a typo in your >>original email but which is duplicated again here (it's not present on >>the web page you linked to) -- you have a mismatched parenthesis in >>your len() call. It's "[ ... len(endstr]" -- there's no ')' to close >>the function call. Given that this typo isn't on the web page, I'm >>not sure whether it's actually there in the code you're running or >>not. I'd have *thought*, however, that if it *is* present, you'd get >>a syntax error rather than a memory error, so it's probably not there >>but you should check it anyhow. :) >> >> >> >>Jeff Shannon >>Technician/Programmer >>Credit International >> >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor >> > > > From matthew.williams at cancer.org.uk Thu Dec 9 12:52:15 2004 From: matthew.williams at cancer.org.uk (Matt Williams) Date: Thu Dec 9 13:29:36 2004 Subject: [Tutor] Complex roots In-Reply-To: <20041209110126.2DD251E400D@bag.python.org> References: <20041209110126.2DD251E400D@bag.python.org> Message-ID: <1102593135.6535.37.camel@dhcp0320.acl.icnet.uk> Further to my previous post, please find some code below: Hope this helps, Matt #Complex number Roots #Matt Williams 9.12.04 import math number=complex(0.5,0) n=float(3) size=math.sqrt((number.real**2)+(number.imag**2)) arg=math.radians(360/n) root=1/n modulus=size**root theta=float(0) roots={} i=0 while i Message-ID: <008501c4ddeb$7d004800$daad8651@xp> > My trusty $10 Casio calculator tells me that the 3 cube roots of 1 are: > 1, (-.5 +0.866025403j), and (-.5 -0.866025403j), or thereabouts. Is there > a way to do this in Python? Sorry the power operation in Python will only return 1+0j You need to dig out the math books and write a function to return all the roots. Or hunt google to see if somebody else has already done one... Alan G From domain.admin at online.ie Thu Dec 9 13:39:17 2004 From: domain.admin at online.ie (Guybrush Threepwood) Date: Thu Dec 9 13:39:24 2004 Subject: [Tutor] CGI Video collection application File I/O troubles In-Reply-To: <20041206152849.85087.qmail@web54306.mail.yahoo.com> References: <20041206152849.85087.qmail@web54306.mail.yahoo.com> Message-ID: <1102595957.41b847751fb97@mail.online.ie> Quoting Chad Crabtree : > Olli Rajala wrote: > > > > > > > > >>Ok. I tried running the script on my Apache server on Windows NT > and IT > >>WORKS!!!! The script saves the values of videodb keys correctly. > DARN!!! > >>I don't get it. Why does the exact same script work on Win and not > on Linux. > >> > >>Oh, did I mention I am developing the application on Linux. And now > I tried > >>it on Win XP with Apache and it works. On Linux I have httpd too. > >> > >> > > > >Have you triplechecked that you really can write to the file. I > don't > >know how python would react, if you can't write to the file (raise > >IOError perhaps) but it doesn't cost you anything to check that... > :) > > > >Yours, Sorry for the delay but I was busy with soemthing else. The script prints the values of the variables fine in the browser so there must be a problem with the file writing part. When I run the script from my bash shell it creates the videodb database file, but when I run it from the browser it doesn't create no file whatsoever. At first I ran the script as a regular user and then I tried as root, I don't understand how the scripts writes the file from the shell when I am root but produces no output when I run it from the browser(as root also). > > > > > You know. I that is what happened to me once. I could not for the > life > of me figure it out. I just chmod 777 it. > -- The lady on the call box in Monkey Island 2 Guybrush: I'm lost in the Inky Island Jungle in Monkey 2 Lady: Just walk off the edge of the screen From rdmoores at gmail.com Thu Dec 9 14:42:09 2004 From: rdmoores at gmail.com (Dick Moores) Date: Thu Dec 9 14:42:11 2004 Subject: [Tutor] Complex roots In-Reply-To: <1102593135.6535.37.camel@dhcp0320.acl.icnet.uk> References: <20041209110126.2DD251E400D@bag.python.org> <1102593135.6535.37.camel@dhcp0320.acl.icnet.uk> Message-ID: VERY helpful, Matt. Thanks. One question: This seems to not compute accurately at all when the imaginary part of number=complex() is other than 0. For example, number=complex(5,5): With number=complex(5,5) n=float(4) the code produces {0: (1.631, 0.0), 1: (0.0, 1.631), 2: (-1.631, 0.0), 3: (0.0, -1.631)} And testing: >>> (0.0 + 1.631j)**4 (7.0764565459210003+0j) If that's the case, why the line size=math.sqrt((number.real**2)+(number.imag**2)) ? Dick On Thu, 09 Dec 2004 11:52:15 +0000, Matt Williams wrote: > Further to my previous post, please find some code below: > > Hope this helps, > Matt > > #Complex number Roots > #Matt Williams 9.12.04 > > import math > > number=complex(0.5,0) > n=float(3) > > size=math.sqrt((number.real**2)+(number.imag**2)) > > arg=math.radians(360/n) > > root=1/n > > modulus=size**root > > theta=float(0) > roots={} > i=0 > while i y=round(modulus*(math.sin(theta)),3) > x=round(modulus*(math.cos(theta)),3) > roots[i]=(x,y) > theta=theta+arg > i=i+1 > > print roots > From RPhillips at engineer.co.summit.oh.us Thu Dec 9 15:34:17 2004 From: RPhillips at engineer.co.summit.oh.us (Ron Phillips) Date: Thu Dec 9 15:34:47 2004 Subject: [Tutor] Graphics coordinates Message-ID: I work for a Civil Engineering organization. I need to give our users a means to generate geographic coordinates for our projects and structures. I plan to do this by making a viewer which will accept a graphic file and two points (pixels) in that image for which geographic coordinates are given. Users can then click on the image where appropriate to generate a list of geographic points of interest for their work. The list will be saveable as an xml file or a shp file (a widely used geographic binary format.) In addition, other programs that I write will use the viewer as a dialog box: will call the viewer directly and get the points from it, just like a color picker dialog. What I am looking for: thoughts on which Python modules are most appropriate and generally applicable for this. PIL? Piddle? PyGIS? some of Hobu's modules? I believe I can write the glue-code, but I don't want to reinvent the wheel if there are existing modules that do almost (or even better, exactly) what I need. I work on WinXp, Linux, and WindowsCE. WindowsCE has a fairly plain-vanilla Python build, so it's better if I stick to the core modules as far as possible. Ron Phillips -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041209/872c5650/attachment.htm From tim.peters at gmail.com Thu Dec 9 16:41:52 2004 From: tim.peters at gmail.com (Tim Peters) Date: Thu Dec 9 16:41:55 2004 Subject: [Tutor] Complex roots In-Reply-To: References: <20041209110126.2DD251E400D@bag.python.org> <1102593135.6535.37.camel@dhcp0320.acl.icnet.uk> Message-ID: <1f7befae041209074162bedff9@mail.gmail.com> [Dick Moores] > VERY helpful, Matt. Thanks. > > One question: This seems to not compute accurately at all > when the imaginary part of number=complex() is other than 0. That's just because the math was wrong . Starting with theta = 0.0 *assumed* the imaginary part is 0, although I can't guess whether that was by accident or design. Try this instead: def croots(c, n): """Return list of the n n'th roots of complex c.""" from math import sin, cos, atan2, pi arg = abs(c)**(1.0/n) theta = atan2(c.imag, c.real) result = [] for i in range(n): theta2 = (theta + 2*pi*i)/n x = arg * cos(theta2) y = arg * sin(theta2) result.append(complex(x, y)) return result From patric at usa.net Thu Dec 9 16:45:34 2004 From: patric at usa.net (Patric Michael) Date: Thu Dec 9 16:44:24 2004 Subject: [Tutor] CGI Video collection application File I/O troubles In-Reply-To: <1102595957.41b847751fb97@mail.online.ie> References: <20041206152849.85087.qmail@web54306.mail.yahoo.com> Message-ID: <41B8029E.32238.D508AE9@localhost> <> > Sorry for the delay but I was busy with soemthing else. > The script prints the values of the variables fine in the > browser so there must be a problem with the file writing part. > When I run the script from my bash shell it creates the videodb > database file, but when I run it from the browser it doesn't > create no file whatsoever. > At first I ran the script as a regular user and then I tried > as root, I don't understand how the scripts writes the file > from the shell when I am root but produces no output when > I run it from the browser(as root also). Just out of curiosity, does the directory where the file is to be written have write permission for others? Since the server (hopefully!) isnt running as root, not only the destination file, but the directory where it is stored must have permissions to allow everyone (or at least the user the server is running as) to write there in the first place. Also, did you check your webservers error log? Patric > > > > > > > > You know. I that is what happened to me once. I could not for the > > life of me figure it out. I just chmod 777 it. > > > > > > -- > The lady on the call box in Monkey Island 2 > Guybrush: I'm lost in the Inky Island Jungle in Monkey 2 > Lady: Just walk off the edge of the screen > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at freenet.co.uk Thu Dec 9 17:08:37 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Dec 9 17:08:11 2004 Subject: [Tutor] CGI Video collection application File I/O troubles References: <20041206152849.85087.qmail@web54306.mail.yahoo.com> <1102595957.41b847751fb97@mail.online.ie> Message-ID: <00a701c4de09$57aca260$daad8651@xp> > When I run the script from my bash shell it creates the videodb > database file, but when I run it from the browser it doesn't > create no file whatsoever. This is usually due to wrong file permissions. The script runs under the web server and this usually has restricted access for security reasons. You need to get your sys admin (who may be you! :-) to set things up so your script can write OK. Alan G. From ps_python at yahoo.com Thu Dec 9 17:50:46 2004 From: ps_python at yahoo.com (kumar s) Date: Thu Dec 9 17:50:49 2004 Subject: [Tutor] Difference between for i in range(len(object)) and for i in object In-Reply-To: <7d7029e704120820382c733fcc@mail.gmail.com> Message-ID: <20041209165046.31539.qmail@web53709.mail.yahoo.com> Dear group, My Tab delimited text looks like this: HG-U95Av2 32972_at 432 117 HG-U95Av2 32972_at 499 631 HG-U95Av2 32972_at 12 185 HG-U95Av2 32972_at 326 83 HG-U95Av2 32972_at 62 197 I want to capture: columns 2 and 3 as tab delim. text: Here is my code: >>> spot_cor=[] >>> for m in cor: ... cols = split(cor,'\t') ... spot_cor.append(cols[2]+'\t'+cols[3]) ... ... Traceback (most recent call last): File "", line 2, in ? File "/usr/local/lib/python2.3/string.py", line 121, in split return s.split(sep, maxsplit) AttributeError: 'list' object has no attribute 'split' Here is 2nd way: >>> test_cor=[] >>> for m in cor: ... cols = split(cor,'\t') ... x = (cols[2]+'\t'+cols[3]) ... test_cor.append(x) ... Traceback (most recent call last): File "", line 2, in ? File "/usr/local/lib/python2.3/string.py", line 121, in split return s.split(sep, maxsplit) AttributeError: 'list' object has no attribute 'split' Here is my 3rd way of doing this thing: >>> for m in range(len(cor)): ... cols = split(cor[m],'\t') ... spot_cor.append(cols[2]+'\t'+cols[3]) ... >>> >>> len(spot_cor) 2252 >>> My question: Many people suggested me to avoid iteration over a object using (range(len)) its index and use instead 'Python's power' by using for i in object, instead. However, when I tried that using some data, as demonstrated above, I get error because append method does not work on list. In method 2, i tried to append an object instead of string elements. In both ways the execution failed because 'List object has no attribute split'. Can you help me making me clear about his dogma. Thank you. Kumar. --- Guillermo Fernandez Castellanos wrote: > Cheers, > > I think your mistake is here: > if x == y: > for ele3 in spot_int: > if y in ele3: > > out.write(ele3) > > out.write('\n') > Each time you find an element that is the same > (x==y) you don't write > only y, you write *all* the elements that are in > spot_init instead > only the matching one! And it's not what you are > looking for! :-) > > I'll also change a bit your code to make it look > more "pythonic" :-) > > > for ele1 in spot_cor: > > for ele2 in spot_int: > > cols = split(ele2,'\t') > > y = (cols[0]+'\t'+cols[1]) > > if ele1 == y: > > for ele3 in spot_int: > > if y in ele3: > > > out.write(ele3) > > > out.write('\n') > > What changes I did: > > for ele1 in range(len(spot_cor)): > x = spot_cor[ele1] > > can be writen like: > for ele1 in spot_cor: > x = ele1 > > Furthermore, as you only use x once, I changed: > if x == y: > > with > if ele1 == y: > > and deleted the line: > x = ele1 > > I also don't understand why you do this: > cols = split(ele2,'\t') > y = (cols[0]+'\t'+cols[1]) > > It seems to me that you are separating something to > put it again > together. I don't really see why... > > Enjoy, > > Guille > __________________________________ Do you Yahoo!? Yahoo! Mail - now with 250MB free storage. Learn more. http://info.mail.yahoo.com/mail_250 From ARobert at MFS.com Thu Dec 9 17:59:53 2004 From: ARobert at MFS.com (Robert, Andrew) Date: Thu Dec 9 18:00:15 2004 Subject: [Tutor] Difference between for i in range(len(object)) and for i in object Message-ID: <968452DD78695147AA4A369C3DF9E40A021B437A@BOSMAILBOX3.corp.mfs.com> Good morning Kumar, I believe you need to do something like: # # Read from command line supplied input file # for line in open(sys.argv[1]).xreadlines(): # # Remove \n from end of line # line=line[:-1] # # Break line by tab delimiter and feed to list # split_line_by_tab=line.split('\t') You should then be able to print out list items relatively easily. Thank you, Andrew Robert Systems Architect Information Technology - OpenVMS Massachusetts Financial Services Phone: 617-954-5882 Pager: 781-764-7321 E-mail: arobert@mfs.com Linux User Number: #201204 -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of kumar s Sent: Thursday, December 09, 2004 11:51 AM To: tutor@python.org Subject: [Tutor] Difference between for i in range(len(object)) and for i in object Dear group, My Tab delimited text looks like this: HG-U95Av2 32972_at 432 117 HG-U95Av2 32972_at 499 631 HG-U95Av2 32972_at 12 185 HG-U95Av2 32972_at 326 83 HG-U95Av2 32972_at 62 197 I want to capture: columns 2 and 3 as tab delim. text: Here is my code: >>> spot_cor=[] >>> for m in cor: ... cols = split(cor,'\t') ... spot_cor.append(cols[2]+'\t'+cols[3]) ... ... Traceback (most recent call last): File "", line 2, in ? File "/usr/local/lib/python2.3/string.py", line 121, in split return s.split(sep, maxsplit) AttributeError: 'list' object has no attribute 'split' Here is 2nd way: >>> test_cor=[] >>> for m in cor: ... cols = split(cor,'\t') ... x = (cols[2]+'\t'+cols[3]) ... test_cor.append(x) ... Traceback (most recent call last): File "", line 2, in ? File "/usr/local/lib/python2.3/string.py", line 121, in split return s.split(sep, maxsplit) AttributeError: 'list' object has no attribute 'split' Here is my 3rd way of doing this thing: >>> for m in range(len(cor)): ... cols = split(cor[m],'\t') ... spot_cor.append(cols[2]+'\t'+cols[3]) ... >>> >>> len(spot_cor) 2252 >>> My question: Many people suggested me to avoid iteration over a object using (range(len)) its index and use instead 'Python's power' by using for i in object, instead. However, when I tried that using some data, as demonstrated above, I get error because append method does not work on list. In method 2, i tried to append an object instead of string elements. In both ways the execution failed because 'List object has no attribute split'. Can you help me making me clear about his dogma. Thank you. Kumar. --- Guillermo Fernandez Castellanos wrote: > Cheers, > > I think your mistake is here: > if x == y: > for ele3 in spot_int: > if y in ele3: > > out.write(ele3) > > out.write('\n') > Each time you find an element that is the same > (x==y) you don't write > only y, you write *all* the elements that are in > spot_init instead > only the matching one! And it's not what you are > looking for! :-) > > I'll also change a bit your code to make it look > more "pythonic" :-) > > > for ele1 in spot_cor: > > for ele2 in spot_int: > > cols = split(ele2,'\t') > > y = (cols[0]+'\t'+cols[1]) > > if ele1 == y: > > for ele3 in spot_int: > > if y in ele3: > > > out.write(ele3) > > > out.write('\n') > > What changes I did: > > for ele1 in range(len(spot_cor)): > x = spot_cor[ele1] > > can be writen like: > for ele1 in spot_cor: > x = ele1 > > Furthermore, as you only use x once, I changed: > if x == y: > > with > if ele1 == y: > > and deleted the line: > x = ele1 > > I also don't understand why you do this: > cols = split(ele2,'\t') > y = (cols[0]+'\t'+cols[1]) > > It seems to me that you are separating something to > put it again > together. I don't really see why... > > Enjoy, > > Guille > __________________________________ Do you Yahoo!? Yahoo! Mail - now with 250MB free storage. Learn more. http://info.mail.yahoo.com/mail_250 _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor "MFS Relay Service" made the following annotations on 12/09/2004 12:05:50 PM ------------------------------------------------------------------------------ This email communication and any attachments may contain proprietary, confidential, or privileged information. If you are not the intended recipient, you are hereby notified that you have received this email in error and that any review, disclosure, dissemination, distribution or copying of it or its contents is prohibited. The sender does not waive confidentiality or any privilege by mistransmission. If you have received this email in error, please notify the sender immediately, delete this email, and destroy all copies and any attachments. ============================================================================== From bgailer at alum.rpi.edu Thu Dec 9 18:11:30 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu Dec 9 18:10:36 2004 Subject: [Tutor] Difference between for i in range(len(object)) and for i in object In-Reply-To: <20041209165046.31539.qmail@web53709.mail.yahoo.com> References: <7d7029e704120820382c733fcc@mail.gmail.com> <20041209165046.31539.qmail@web53709.mail.yahoo.com> Message-ID: <6.2.0.14.0.20041209100759.05f95f10@mail.mric.net> At 09:50 AM 12/9/2004, kumar s wrote: >[snip] Personally I am getting weary of a lot of requests that to me seem to come from a lack of understanding of Python.. Would you be willing to take a good tutorial so you understand basic Python concepts and apply them to your code. I also despair that you don't seem to benefit from some of our suggestions. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From phil at xfr.co.uk Thu Dec 9 18:28:56 2004 From: phil at xfr.co.uk (Philip Kilner) Date: Thu Dec 9 18:29:44 2004 Subject: [Tutor] Capturing Logfile data in Windows Message-ID: <41B88B58.1030007@xfr.co.uk> Hi List, I have a closed-source application which creates log files. I'd like to capture this logfile data as it is crated, and do clever things with it! Is this possible? I guess it must be, because there are "tail" type utilities for Windows... Is it possible in Python? I'd be grateful for any pointers! BTW, it doesn't matter either way whether I can somehow pipe the log output to my program /without/ the file actually being created, or if I can capture it /as/ it is created - I just need to get my mitts on the data as it is generated...it would be better if I had the file as well, but it is not essential... Thanks in Anticipation! -- Regards, PhilK Email: phil@xfr.co.uk / Voicemail & Facsimile: 07092 070518 "Work as if you lived in the early days of a better nation." - Alasdair Gray From ljholish at speakeasy.net Thu Dec 9 19:07:50 2004 From: ljholish at speakeasy.net (Larry Holish) Date: Thu Dec 9 19:07:03 2004 Subject: [Tutor] sorting a list of dictionaries Message-ID: <20041209180750.GA26490@localhost> Hello, I have a list of dictionaries, each representing info about a file, something like: [{'name':'foo.txt','size':35}, {'name':'bar.txt','size':35}, ...] I want to present a sorted list of all the files' data, sorting on the keys 'name' or 'size'. The file 'name' s should be unique (I'm hoping) across all the dictionaries. Can someone point me towards an efficient solution for accomplishing the sort? (The list has 1000s of files). Thanks in advance, -- Larry Holish From iqbala-python at qwestip.net Thu Dec 9 19:16:30 2004 From: iqbala-python at qwestip.net (Asif Iqbal) Date: Thu Dec 9 19:16:33 2004 Subject: [Tutor] Lock down windows with python+usb Message-ID: <20041209181630.GC28586@qwestip.net> Hi All Has anyone done any script like this? Use a python script for Windows XP that will continuosly check if my USB is plugged in. So if I unplug my USB flashdrive it will fork a screensaver with password lock. Thanks for any idea/suggestion -- Asif Iqbal PGP Key: 0xE62693C5 KeyServer: pgp.mit.edu "...it said: Install Windows XP or better...so I installed Solaris..." From kent37 at tds.net Thu Dec 9 19:40:14 2004 From: kent37 at tds.net (Kent Johnson) Date: Thu Dec 9 19:40:21 2004 Subject: [Tutor] sorting a list of dictionaries In-Reply-To: <20041209180750.GA26490@localhost> References: <20041209180750.GA26490@localhost> Message-ID: <41B89C0E.5070100@tds.net> If you can use Python 2.4 it is very simple using the new key= parameter to sort and operator.itemgetter: >>> import operator >>> ds = [{'name':'foo.txt','size':35}, {'name':'bar.txt','size':36}] >>> ds.sort(key=operator.itemgetter('name')) >>> ds [{'name': 'bar.txt', 'size': 36}, {'name': 'foo.txt', 'size': 35}] >>> ds.sort(key=operator.itemgetter('size')) >>> ds [{'name': 'foo.txt', 'size': 35}, {'name': 'bar.txt', 'size': 36}] Otherwise you should use decorate - sort - undecorate. The idea here is to make a new list whose values are pairs of (key, item) for each data item in the original list. The new list is sorted, then a final list is extracted containing only the items in the desired order: >>> d2 = [ (d['name'], d) for d in ds ] >>> d2.sort() >>> ds = [ d for (name, d) in d2 ] >>> ds [{'name': 'bar.txt', 'size': 36}, {'name': 'foo.txt', 'size': 35}] Kent Larry Holish wrote: > Hello, > > I have a list of dictionaries, each representing info about a file, > something like: > > [{'name':'foo.txt','size':35}, {'name':'bar.txt','size':35}, ...] > > I want to present a sorted list of all the files' data, sorting on the > keys 'name' or 'size'. The file 'name' s should be unique (I'm hoping) > across all the dictionaries. Can someone point me towards an efficient > solution for accomplishing the sort? (The list has 1000s of files). > > Thanks in advance, > From sigurd at 12move.de Thu Dec 9 20:18:54 2004 From: sigurd at 12move.de (Karl =?iso-8859-1?Q?Pfl=E4sterer?=) Date: Thu Dec 9 20:22:26 2004 Subject: [Tutor] sorting a list of dictionaries In-Reply-To: <20041209180750.GA26490@localhost> (Larry Holish's message of "Thu, 9 Dec 2004 12:07:50 -0600") References: <20041209180750.GA26490@localhost> Message-ID: On 9 Dez 2004, ljholish@speakeasy.net wrote: > I have a list of dictionaries, each representing info about a file, > something like: > > [{'name':'foo.txt','size':35}, {'name':'bar.txt','size':35}, ...] > > I want to present a sorted list of all the files' data, sorting on the > keys 'name' or 'size'. The file 'name' s should be unique (I'm hoping) > across all the dictionaries. Can someone point me towards an efficient > solution for accomplishing the sort? (The list has 1000s of files). That's easy to achieve, since sort takes a custom sort function as optional argument. Now you need only a function which takes the values of the fileds and compares them. E.g. lst.sort(lambda m, n: cmp(m.get(field), n.get(field))) where field is either 'name' or 'size'. As a function: def sort_it (lst, field): lst.sort(lambda m, n: cmp(m.get(field), n.get(field))) Karl -- Please do *not* send copies of replies to me. I read the list From jeff at ccvcorp.com Thu Dec 9 20:46:24 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu Dec 9 20:42:36 2004 Subject: [Tutor] Please help matching elements from two lists and printing them In-Reply-To: <20041209035238.72830.qmail@web53708.mail.yahoo.com> References: <20041209035238.72830.qmail@web53708.mail.yahoo.com> Message-ID: <41B8AB90.8070409@ccvcorp.com> kumar s wrote: > On top of this this process is VERY SLOW on high end > server too. That's because, for each line in spot_cor, you're examining every item in spot_int, and if there's a match, you examine every element in spot_int again! If I'm remembering my big-O notation correctly, that makes this O(n*m + m) -- even if it simplifies to O(n*m) (which I think it may), that's still quadratic time -- as the length of your lists grows, your performance will degrade *very* rapidly. Here's a simplified version of your code. I've changed the for loops so that they iterate over the lists directly, instead of iterating over a range and then using that number to index into the list -- the result is the same, but this way is less extra work and easier to read. out = open('sa_int_2.txt','w') for cor_ele in spot_cor: for int_ele in spot_int: cols = split(int_ele, '\t') y = cols[0] + '\t' + cols[1] if x == y: for int_ele2 in spot_int: if y in int_ele2: out.write(int_ele2 + '\n') Remember, every time you use 'in', it means traversing the entire list. Multiple levels of nesting statements that use 'in' causes a polynomial expansion of work. Now, here's how I'd rewrite your code. out = open('sa_int_2.txt','w') element_dict = {} for line in spot_int: cols = split(line,'\t') key = '\t'.join(cols[:2]) element_dict[key] = line for cor in spot_cor: try: value = element_dict[cor] out.write(value + '\n') except KeyError: pass out.close() Note that I iterate through each list only once, so my timing should be O(n + m). First, I preprocess spot_int by putting it into a dictionary. I create keys for the dictionary that are identical to what will be in spot_cor. Then I iterate through spot_cor, and match each element with what's in the dictionary I've made. If I find something that matches, I write it out; if I don't, then I simply move on to the next item in spot_cor. This does make several assumptions. First, it assumes that every line in spot_int will be unique in the first two columns -- that is, I'm assuming that nowhere in the file would you find lines like the following: 5 0 123 5 0 456 If these cases *do* happen, then all but the last such line would be lost, and only the last one would be left in the dictionary (and thus found and written out). In your version, all lines whose first two columns match will be written out. (This may be the source of your "extra" results.) If you *do* need to handle lines like this, then it wouldn't be hard to modify my code for it. Each value in the dictionary would become a list, and matching lines are appended to that list. The line 'element_dict[key] = line' becomes 'element_dict.setdefault(key, []).append(line)', and writing to the file becomes a for-loop instead of a single write. The other assumption that I make is that these files are all of reasonable size to fit into memory. Your code makes this same assumption, too, of course. This assumption should be valid for up to a few tens of thousands (maybe even hundreds of thousands, depending on your hardware) of items. If you have more than this, then your best bet would be to start using a real database. (I've heard good things about mysql and sqlite support in Python...) Jeff Shannon Technician/Programmer Credit International From jeff at ccvcorp.com Thu Dec 9 20:53:46 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu Dec 9 20:49:56 2004 Subject: [Tutor] MemoryError In-Reply-To: References: <41B76416.6020403@ccvcorp.com> <41B78D6A.7040107@ccvcorp.com> Message-ID: <41B8AD4A.5050206@ccvcorp.com> Liam Clarke wrote: > So, I'm going to throw caution to the wind, and try an re approach. It > can't be any more unwieldy and ugly than what I've got going at the > moment. If you're going to try a new approach, I'd strongly suggest using a proper html/xml parser instead of re's. You'll almost certainly have an easier time using a tool that's designed for your specific problem domain than you will trying to force a more general tool to work. Since you're specifically trying to find (and replace) certain html tags and attributes, and that's exactly what html parsers *do*, well, the conclusions seems obvious (to me at least). ;) There are lots of html parsing tools available in Python (though I've never needed one myself). I've heard lots of good things about BeautifulSoup... Jeff Shannon Technician/Programmer Credit International From jeff at ccvcorp.com Thu Dec 9 21:07:41 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu Dec 9 21:03:47 2004 Subject: [Tutor] Difference between for i in range(len(object)) and for i in object In-Reply-To: <20041209165046.31539.qmail@web53709.mail.yahoo.com> References: <20041209165046.31539.qmail@web53709.mail.yahoo.com> Message-ID: <41B8B08D.6010802@ccvcorp.com> kumar s wrote: > Here is my code: > >>>>spot_cor=[] Create an empty list... >>>>for m in cor: Now, for each element in some other list from somewhere else, > ... cols = split(cor,'\t') Ignore the element we've just isolated and try to split the entire list on '\t' ... > Traceback (most recent call last): > File "", line 2, in ? > File "/usr/local/lib/python2.3/string.py", line 121, > in split > return s.split(sep, maxsplit) > AttributeError: 'list' object has no attribute 'split' Yup, the list 'cor' doesn't have a split() method. The string that presumably should be in 'm' would have such a method, though. > Here is 2nd way: > > > >>>>test_cor=[] >>>>for m in cor: > ... cols = split(cor,'\t') Once again, you're operating on the list, not the element of the list. > Here is my 3rd way of doing this thing: > >>>>for m in range(len(cor)): > ... cols = split(cor[m],'\t') Here, you *are* operating on an element of the list. But if I were to write this segment to be parallel to your previous two attempts, it would be: cols = split(cor[cor],'\t') which probably wouldn't surprise you when it doesn't work... > My question: > Many people suggested me to avoid iteration over a > object using (range(len)) its index and use instead > 'Python's power' by using for i in object, instead. > > However, when I tried that using some data, as > demonstrated above, I get error because append method > does not work on list. No -- look carefully at the tracebacks, and you'll see that nowhere does it complain about append(), nor does it give the line numbers in which the append() takes place. It complains about split(), and tells you exactly which line the problem is on ('File "", line 2, in ?' -- since you're doing this in an interpreter, there's no filename or function name). Jeff Shannon Technician/Programmer Credit International From kent37 at tds.net Thu Dec 9 21:22:29 2004 From: kent37 at tds.net (Kent Johnson) Date: Thu Dec 9 21:22:36 2004 Subject: [Tutor] sorting a list of dictionaries In-Reply-To: References: <20041209180750.GA26490@localhost> Message-ID: <41B8B405.2060707@tds.net> Using sort() with a user compare function is not recommended when you care about performance. The problem is that the sort function has to call back into Python code for every compare, of which there are many. The decorate - sort - undecorate idiom is the preferred way to do this in Python < 2.4. Python 2.4 adds the key= parameter to sort() and does the DSU internally. Ironically, the best way to speed up Python code is often to eliminate it - the more work you can do in the C runtime, the faster your code will run. Sometimes an approach that seems to do more work - like DSU, which builds two extra lists - is actually faster because it does more in C code. Here is a program to time the three methods. On my machine, the ratio of times of sort1 : sort2 : sort3 is pretty consistently about 1 : 2 : 6-7, i.e. sort with key parameter is twice as fast as DSU which is three times faster than sort with cmp. A couple of interesting observations: - The ratio of sort times is independent of the length of the list. I expected that the performance of sort3 would get progressively worse as the list got longer because I expect that the cmp function would be called a number of times that is O(n*logn). Apparently this is not the case. - If the list is large and already sorted, sort3 is significantly faster than sort2 - it takes about 2/3 the time of sort2. You can try this by taking out the call to random.shuffle(). Kent import operator, random, timeit a = range(10000) random.shuffle(a) dlist = [ {'name':str(i), 'size':i} for i in a ] def sort1(ds): ''' Sort using Python 2.4 key argument ''' ds.sort(key=operator.itemgetter('size')) def sort2(ds): ''' Sort using DSU ''' d2 = [ (d['size'], d) for d in ds ] d2.sort() ds[:] = [ d for (name, d) in d2 ] def sort3(ds): ''' Sort using cmp argument to sort ''' ds.sort(lambda m, n: cmp(m['size'], n['size'])) def timeOne(fn): setup = "from __main__ import " + fn.__name__ + ',dlist' stmt = fn.__name__ + '(dlist[:])' t = timeit.Timer(stmt, setup) secs = min(t.repeat(3, 10)) print '%s: %f secs' % (fn.__name__, secs) # Make sure they all give the same answer a1=dlist[:] sort1(a1) a2=dlist[:] sort2(a2) a3=dlist[:] sort3(a3) assert a1 == a2 assert a3 == a2 timeOne(sort1) timeOne(sort2) timeOne(sort3) Karl Pfl?sterer wrote: > On 9 Dez 2004, ljholish@speakeasy.net wrote: > > >>I have a list of dictionaries, each representing info about a file, >>something like: >> >>[{'name':'foo.txt','size':35}, {'name':'bar.txt','size':35}, ...] >> >>I want to present a sorted list of all the files' data, sorting on the >>keys 'name' or 'size'. The file 'name' s should be unique (I'm hoping) >>across all the dictionaries. Can someone point me towards an efficient >>solution for accomplishing the sort? (The list has 1000s of files). > > > That's easy to achieve, since sort takes a custom sort function as > optional argument. Now you need only a function which takes the values > of the fileds and compares them. > > E.g. > > lst.sort(lambda m, n: cmp(m.get(field), n.get(field))) > where field is either 'name' or 'size'. > > As a function: > > def sort_it (lst, field): > lst.sort(lambda m, n: cmp(m.get(field), n.get(field))) > > > Karl From jnoller at gmail.com Thu Dec 9 21:37:25 2004 From: jnoller at gmail.com (Jesse Noller) Date: Thu Dec 9 21:37:28 2004 Subject: [Tutor] Removing/Handing large blocks of text In-Reply-To: <7FB370CF-492B-11D9-BFEA-000393CBC88E@yahoo.fr> References: <4222a84904120806426dfc0c5b@mail.gmail.com> <7FB370CF-492B-11D9-BFEA-000393CBC88E@yahoo.fr> Message-ID: <4222a849041209123743289cbc@mail.gmail.com> On Wed, 8 Dec 2004 15:11:55 +0000, Max Noel wrote: > > > > On Dec 8, 2004, at 14:42, Jesse Noller wrote: > > > Hello, > > > > I'm trying to do some text processing with python on a farily large > > text file (actually, XML, but I am handling it as plaintext as all I > > need to do is find/replace/move) and I am having problems with trying > > to identify two lines in the text file, and remove everything in > > between those two lines (but not the two lines) and then write the > > file back (I know the file IO part). > > Okay, here are some hints: you need to identify when you enter a > block and when you exit a block, keeping in mind that this may > happen on the same line (e.g. blah). The rest is trivial. > The rest of your message is included as a spoiler space if you want to > find the solution by yourself -- however, a 17-line program that does > that is included at the end of this message. It prints the resulting > file to the standard out, for added flexibility: if you want the result > to be in a file, just redirect stdout (python blah.py > out.txt). > > Oh, one last thing: don't use readlines(), it uses up a lot of memory > (especially with big files), and you don't need it since you're reading > the file sequentially. Use the file iterator instead. > > > > > I'm trying to do this with the re module - the two tags looks like: > > > > > > ... > > a bunch of text (~1500 lines) > > ... > > > > > > I need to identify the first tag, and the second, and unconditionally > > strip out everything in between those two tags, making it look like: > > > > > > > > > > I'm familiar with using read/readlines to pull the file into memory > > and alter the contents via string.replace(str, newstr) but I am not > > sure where to begin with this other than the typical open/readlines. > > > > I'd start with something like: > > > > re1 = re.compile('^\') > > re2 = re.compile('^\<\/foo\>') > > > > f = open('foobar.txt', 'r') > > for lines in f.readlines() > > match = re.match(re1, line) > > > > But I'm lost after this point really, as I can identify the two lines, > > but I am not sure how to do the processing. > > > > thank you > > -jesse > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > #!/usr/bin/env python > > import sre > > reStart = sre.compile('^\s*\') > reEnd = sre.compile('\\s*$') > > inBlock = False > > fileSource = open('foobar.txt') > > for line in fileSource: > if reStart.match(line): inBlock = True > if not inBlock: print line > if reEnd.match(line): inBlock = False > > fileSource.close() > > -- Max > maxnoel_fr at yahoo dot fr -- ICQ #85274019 > "Look at you hacker... A pathetic creature of meat and bone, panting > and sweating as you run through my corridors... How can you challenge a > perfect, immortal machine?" > > Thanks a bunch for all of your fast responses, they helped a lot - I'll post what I cook up back to the list as soon as I complete it. Thanks! -jesse From ljholish at speakeasy.net Thu Dec 9 23:39:56 2004 From: ljholish at speakeasy.net (Larry Holish) Date: Thu Dec 9 23:39:08 2004 Subject: [Tutor] sorting a list of dictionaries In-Reply-To: <41B8B405.2060707@tds.net> References: <20041209180750.GA26490@localhost> <41B8B405.2060707@tds.net> Message-ID: <20041209223956.GA31372@localhost> On Thu, Dec 09, 2004 at 03:22:29PM -0500, Kent Johnson wrote: > Using sort() with a user compare function is not recommended when you > care about performance. The problem is that the sort function has to > call back into Python code for every compare, of which there are many. > The decorate - sort - undecorate idiom is the preferred way to do this > in Python < 2.4. Python 2.4 adds the key= parameter to sort() and > does the DSU internally. Karl, Kent, thanks for your prompt responses. I'm running python 2.3, and the DSU method performs nicely. Regards, Larry -- Larry Holish From cyresse at gmail.com Fri Dec 10 00:09:57 2004 From: cyresse at gmail.com (Liam Clarke) Date: Fri Dec 10 00:10:02 2004 Subject: [Tutor] MemoryError In-Reply-To: <41B8AD4A.5050206@ccvcorp.com> References: <41B76416.6020403@ccvcorp.com> <41B78D6A.7040107@ccvcorp.com> <41B8AD4A.5050206@ccvcorp.com> Message-ID: Hi all, Yeah, I should've written this in functions from the get go, but I thought it would be a simple script. :/ I'll come back to that script when I've had some sleep, my son was recently born and it's amazing how dramatically lack of sleep affects my acuity. But, I want to figure out what's going wrong. That said, the re path is bearing fruit. I love the method finditer(), as I can reduce my overly complicated string methods from my original code to x=file("toolkit.txt",'r') s=x.read() x.close() appList=[] regExIter=reObj.finditer(s) #Here's a re obj I compiled earlier. for item in regExIter: text=gettextFunc(item.group()) #Will try and stick to string method for this, but I'll see. if not text: text="Default" #Will give a text value for the href, so some lucky human can change it url=geturlFunc(item.group()) # The simpler the better, and so far re has been the simplest if not url: href = '"" #This will delete the applet, as there are applet's acting as placeholders else: href='%s' % (url, text) appList.append(item.span(), href) appList.reverse() for ((start, end), href) in appList: codeSt=codeSt.replace(codeSt[start:end], href) Of course, that's just a rought draft, but it seems a whole lot simpler to me. S'pose code needs a modicum of planning. Oh, and I d/led BeautifulSoup, but I couldn't work it right, so I tried re, and it suits my needs. Thanks for all the help. Regards, Liam Clarke On Thu, 09 Dec 2004 11:53:46 -0800, Jeff Shannon wrote: > Liam Clarke wrote: > > > So, I'm going to throw caution to the wind, and try an re approach. It > > can't be any more unwieldy and ugly than what I've got going at the > > moment. > > If you're going to try a new approach, I'd strongly suggest using a > proper html/xml parser instead of re's. You'll almost certainly have > an easier time using a tool that's designed for your specific problem > domain than you will trying to force a more general tool to work. > Since you're specifically trying to find (and replace) certain html > tags and attributes, and that's exactly what html parsers *do*, well, > the conclusions seems obvious (to me at least). ;) > > There are lots of html parsing tools available in Python (though I've > never needed one myself). I've heard lots of good things about > BeautifulSoup... > > > > Jeff Shannon > Technician/Programmer > Credit International > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From cyresse at gmail.com Fri Dec 10 00:23:22 2004 From: cyresse at gmail.com (Liam Clarke) Date: Fri Dec 10 00:23:26 2004 Subject: [Tutor] Capturing Logfile data in Windows In-Reply-To: <41B88B58.1030007@xfr.co.uk> References: <41B88B58.1030007@xfr.co.uk> Message-ID: You could have something along the lines of - import os.path import time curTime = os.path.getmtime('log.txt') #Or whatever it's called. while 1: #or some other loop time.sleep(10) #Check logfile every ten seconds. if os.path.getmtime('log.txt') != curTime: curTime = os.path.getmtime('log.txt') x=file('log.txt','r')... So basically, just check the modification time. If the modification time has changed, then the file's been updated. It's one way to do it. : ) Liam Clarke On Thu, 09 Dec 2004 17:28:56 +0000, Philip Kilner wrote: > Hi List, > > I have a closed-source application which creates log files. I'd like to > capture this logfile data as it is crated, and do clever things with it! > > Is this possible? I guess it must be, because there are "tail" type > utilities for Windows... > > Is it possible in Python? I'd be grateful for any pointers! > > BTW, it doesn't matter either way whether I can somehow pipe the log > output to my program /without/ the file actually being created, or if I > can capture it /as/ it is created - I just need to get my mitts on the > data as it is generated...it would be better if I had the file as well, > but it is not essential... > > Thanks in Anticipation! > > -- > > Regards, > > PhilK > > Email: phil@xfr.co.uk / Voicemail & Facsimile: 07092 070518 > > "Work as if you lived in the early days of a better nation." - Alasdair Gray > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From flaxeater at yahoo.com Fri Dec 10 00:58:55 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Fri Dec 10 00:58:58 2004 Subject: [Tutor] Lock down windows with python+usb Message-ID: <20041209235855.79126.qmail@web54309.mail.yahoo.com> Asif Iqbal wrote: >Hi All > >Has anyone done any script like this? Use a python script for Windows XP >that will continuosly check if my USB is plugged in. So if I unplug my >USB flashdrive it will fork a screensaver with password lock. > >Thanks for any idea/suggestion > > > You could make screensaver program that is placed in the taskbar that periodicly check for the usbkey. I would look at wxwindows or pygame, you would makea full screen ap, that somehow captures all the key presses except username password thing. HTH __________________________________ Do you Yahoo!? Read only the mail you want - Yahoo! Mail SpamGuard. http://promotions.yahoo.com/new_mail From alan.gauld at freenet.co.uk Fri Dec 10 01:26:05 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Dec 10 01:25:36 2004 Subject: [Tutor] Difference between for i in range(len(object)) and for i inobject References: <20041209165046.31539.qmail@web53709.mail.yahoo.com> Message-ID: <002701c4de4e$d69c9d60$67d98751@xp> > Here is my code: > >>> spot_cor=[] > >>> for m in cor: > ... cols = split(cor,'\t') You are splitting the list not the item cols = split(m, '\t') Better to use a meaningful name too: for line in cor: would probably have made the mistake more obvious. > However, when I tried that using some data, as > demonstrated above, I get error because append method No its the spil method that doesn't exist and that was because you were passing the list instead of the object. Once you get used to the "foreach" semantics of "for" it really is a better way of working than messing around with indexes. Alan G. From alan.gauld at freenet.co.uk Fri Dec 10 01:30:17 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Dec 10 01:29:48 2004 Subject: [Tutor] Difference between for i in range(len(object)) andfor i in object References: <7d7029e704120820382c733fcc@mail.gmail.com><20041209165046.31539.qmail@web53709.mail.yahoo.com> <6.2.0.14.0.20041209100759.05f95f10@mail.mric.net> Message-ID: <002e01c4de4f$6cf2a340$67d98751@xp> > Personally I am getting weary of a lot of requests that to me seem to come > from a lack of understanding of Python.. To be fair that is what the tutor list is for - learning Python. > Would you be willing to take a good tutorial so you understand > basic Python concepts and apply them to your code. But as a tutor author I do agree that I am often tempted (and sometimes succumb) to just point at the relevant topic in my tutorial. Particularly since the latest version tries to answer all of the most common questions asked here, but still they come up... > I also despair that you don't seem to benefit from some of our suggestions. And this too can be frustrating but sometimes it is the case that the "student" simply didn't fully appreciate the significance of what was offered. I'm feeling generous tonight! :-) Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Fri Dec 10 01:33:28 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Dec 10 01:32:59 2004 Subject: [Tutor] Capturing Logfile data in Windows References: <41B88B58.1030007@xfr.co.uk> Message-ID: <003301c4de4f$de63c680$67d98751@xp> > I have a closed-source application which creates log files. I'd like to > capture this logfile data as it is crated, and do clever things with it! > > Is this possible? I guess it must be, because there are "tail" type > utilities for Windows... Depends on whether the output goes to stdout or stderr or a hard coded file. Usually log files are hard coded so you need to write a tail like utility. You could do this but why not just download a free one such as that from cygwin? If you must write your own start off by looking at the C source code for the standard Linux/Cygwin tail program to see how they do it. Its probably easy to convert that to Python and safer than guessing the best approach... Alan G. From keridee at jayco.net Fri Dec 10 01:31:22 2004 From: keridee at jayco.net (Jacob S.) Date: Fri Dec 10 01:33:05 2004 Subject: [Tutor] Problem with python2.4. Message-ID: <000501c4de4f$cbbb7820$955428cf@JSLAPTOP> Hi all. Nothing I can do can fix my problem. It appears as though pythonw.exe is not working properly in the python 2.4 distribution. I have tried numerous things to try and fix it. The only way I can run Tk scripts and the like is to use the pythonw.exe from the 2.3 distribution. This includes idle. I am running Windows XP and I still can't figure out what's wrong. Nothing has changed with it since the release version of python2.4 to the final version. Can anyone help me with my predicament? The symptoms: I click on edit with idle--which runs the command "C:\python24\pythonw.exe" "C:\python24\lib\idlelib\idle.pyw" -n -e "%1" --then the computer thinks for a bit and is silent. I hit Ctrl-Alt-Del and the task manager pops up. I look in processes, and nothing about pythonw.exe is in there like it should be. What should I do? From jasonchild at cnsp.com Fri Dec 10 01:37:23 2004 From: jasonchild at cnsp.com (Jason Child) Date: Fri Dec 10 01:37:25 2004 Subject: [Tutor] PDF and Python Message-ID: Hey there. Does anyone know of a way to output PDFs with python? I have some data that I have processed from a series of textfiles that I would like to provide PDF format reports for.. Jason Christopher Child Computer Network Services Professionals Tech Support 505-986-1669 1-877-321-9165 jasonchild@cnsp.com VOZ Online VOIP Install Tech 505-428-7500 1-877-428-7550 From kent37 at tds.net Fri Dec 10 01:38:12 2004 From: kent37 at tds.net (Kent Johnson) Date: Fri Dec 10 01:38:19 2004 Subject: [Tutor] MemoryError In-Reply-To: References: <41B76416.6020403@ccvcorp.com> <41B78D6A.7040107@ccvcorp.com> <41B8AD4A.5050206@ccvcorp.com> Message-ID: <41B8EFF4.6050309@tds.net> Liam, Here's a nifty re trick for you. The sub() method can take a function as the replacement parameter. Instead of replacing with a fixed string, the function is called with the match object. Whatever string the function returns, is substituted for the match. So you can simplify your code a bit, something like this: def replaceTag(item): # item is a match object # This is exactly your code text=gettextFunc(item.group()) #Will try and stick to string method for this, but I'll see. if not text: text="Default" #Will give a text value for the href, so some lucky human can change it url=geturlFunc(item.group()) # The simpler the better, and so far re has been the simplest if not url: href = '"" #This will delete the applet, as there are applet's acting as placeholders else: href='%s' % (url, text) # Now return href return href now your loop and replacements get replaced by the single line codeSt = reObj.sub(replaceTag, codeSt) :-) Kent Liam Clarke wrote: > Hi all, > > Yeah, I should've written this in functions from the get go, but I > thought it would be a simple script. :/ > > I'll come back to that script when I've had some sleep, my son was > recently born and it's amazing how dramatically lack of sleep affects > my acuity. But, I want to figure out what's going wrong. > > That said, the re path is bearing fruit. I love the method finditer(), > as I can reduce my overly complicated string methods from my original > code to > > x=file("toolkit.txt",'r') > s=x.read() > x.close() > appList=[] > > regExIter=reObj.finditer(s) #Here's a re obj I compiled earlier. > > for item in regExIter: > text=gettextFunc(item.group()) #Will try and stick to string method > for this, but I'll see. > if not text: > text="Default" #Will give a text value for the href, so some > lucky human can change it > url=geturlFunc(item.group()) # The simpler the better, and so far > re has been the simplest > if not url: > href = '"" #This will delete the applet, as there are applet's > acting as placeholders > else: > href='%s' % (url, text) > > appList.append(item.span(), href) > > appList.reverse() > > for ((start, end), href) in appList: > > codeSt=codeSt.replace(codeSt[start:end], href) > > > Of course, that's just a rought draft, but it seems a whole lot > simpler to me. S'pose code needs a modicum of planning. > > Oh, and I d/led BeautifulSoup, but I couldn't work it right, so I > tried re, and it suits my needs. > > Thanks for all the help. > > Regards, > > Liam Clarke > On Thu, 09 Dec 2004 11:53:46 -0800, Jeff Shannon wrote: > >>Liam Clarke wrote: >> >> >>>So, I'm going to throw caution to the wind, and try an re approach. It >>>can't be any more unwieldy and ugly than what I've got going at the >>>moment. >> >>If you're going to try a new approach, I'd strongly suggest using a >>proper html/xml parser instead of re's. You'll almost certainly have >>an easier time using a tool that's designed for your specific problem >>domain than you will trying to force a more general tool to work. >>Since you're specifically trying to find (and replace) certain html >>tags and attributes, and that's exactly what html parsers *do*, well, >>the conclusions seems obvious (to me at least). ;) >> >>There are lots of html parsing tools available in Python (though I've >>never needed one myself). I've heard lots of good things about >>BeautifulSoup... >> >> >> >>Jeff Shannon >>Technician/Programmer >>Credit International >> >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor >> > > > From singingxduck at gmail.com Fri Dec 10 01:40:09 2004 From: singingxduck at gmail.com (Orri Ganel) Date: Fri Dec 10 01:40:14 2004 Subject: [Tutor] Problem with python2.4. In-Reply-To: <000501c4de4f$cbbb7820$955428cf@JSLAPTOP> References: <000501c4de4f$cbbb7820$955428cf@JSLAPTOP> Message-ID: <3449428f0412091640264de926@mail.gmail.com> On Thu, 9 Dec 2004 19:31:22 -0500, Jacob S. wrote: > Hi all. > > Nothing I can do can fix my problem. It appears as though pythonw.exe is > not working properly in the python 2.4 distribution. I have tried numerous > things to try and fix it. The only way I can run Tk scripts and the like is > to use the pythonw.exe from the 2.3 distribution. This includes idle. I am > running Windows XP and I still can't figure out what's wrong. Nothing has > changed with it since the release version of python2.4 to the final version. > Can anyone help me with my predicament? The symptoms: I click on edit with > idle--which runs the command "C:\python24\pythonw.exe" > "C:\python24\lib\idlelib\idle.pyw" -n -e "%1" --then the computer thinks for > a bit and is silent. I hit Ctrl-Alt-Del and the task manager pops up. I look > in processes, and nothing about pythonw.exe is in there like it should be. > What should I do? > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > I had a similar problem with some of the early versions of 2.4 (beta, release candidate), and it seems to me, looking back, that some of the other programs I had running simultaneously blocked the sockets or something . . . In any case, I usually made sure I wasn't running any other programs when *opening* IDLE, and, if that didn't help, I restarted the computer. However, even when the IDLE shell didn't work properly, the "Edit with IDLE" functioned operated smoothly, so I can't say for sure that it will help. Have you tried emailing the idle-dev mailing list? HTH, Orri -- Email: dragonfirebane@aol.com AIM: singingxduck Programming Python for the fun of it. From jasonchild at cnsp.com Fri Dec 10 01:41:27 2004 From: jasonchild at cnsp.com (Jason Child) Date: Fri Dec 10 01:41:26 2004 Subject: [Tutor] test Message-ID: test Jason Christopher Child Computer Network Services Professionals Tech Support 505-986-1669 1-877-321-9165 jasonchild@cnsp.com VOZ Online VOIP Install Tech 505-428-7500 1-877-428-7550 From dyoo at hkn.eecs.berkeley.edu Fri Dec 10 01:43:06 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Dec 10 01:43:09 2004 Subject: [Tutor] Problem with python2.4. In-Reply-To: <000501c4de4f$cbbb7820$955428cf@JSLAPTOP> Message-ID: On Thu, 9 Dec 2004, Jacob S. wrote: > Nothing I can do can fix my problem. It appears as though > pythonw.exe is not working properly in the python 2.4 distribution. [some text cut] > The symptoms: I click on edit with > idle--which runs the command "C:\python24\pythonw.exe" > "C:\python24\lib\idlelib\idle.pyw" -n -e "%1" --then the computer thinks for > a bit and is silent. Hi Jacob, >From the symptom report, I would not automatically suspect pythonw: I'd instead look at IDLE. You might be running into the same kind of issue that Mike Hansen was running into just a few days ago: http://mail.python.org/pipermail/tutor/2004-December/033672.html We were able to diagnose the problem by doing this: http://mail.python.org/pipermail/tutor/2004-December/033726.html Can you try the same procedure? Even if it doesn't work, the information that Python responses with should give us a better idea of what is going on. Try opening up a regular console version of Python, and see what happens when you do: ### >>> import idlelib.PyShell >>> idlelib.PyShell.main() ### Good luck to you! From jeff at ccvcorp.com Fri Dec 10 01:54:07 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri Dec 10 01:50:11 2004 Subject: [Tutor] Problem with python2.4. In-Reply-To: <3449428f0412091640264de926@mail.gmail.com> References: <000501c4de4f$cbbb7820$955428cf@JSLAPTOP> <3449428f0412091640264de926@mail.gmail.com> Message-ID: <41B8F3AF.4060909@ccvcorp.com> Orri Ganel wrote: > On Thu, 9 Dec 2004 19:31:22 -0500, Jacob S. wrote: > >> [...] It appears as though pythonw.exe is >>not working properly in the python 2.4 distribution. > I had a similar problem with some of the early versions of 2.4 (beta, > release candidate), and it seems to me, looking back, that some of the > other programs I had running simultaneously blocked the sockets or > something . . . Seeing this comment reminded me of some conversations I've seen in comp.lang.python recently. Apparently newer versions of IDLE create a subprocess to run user-code in (so that IDLE runs in a different interpreter than the code you type into IDLE), and communicates with that subprocess through sockets on the loopback interface (that is, the 'network connection' that connects only to itself). Overly aggressive firewall programs may block those socket operations. I'd check whether XP's built-in firewall is enabled, and if so, check whether it might be blocking connections to loopback / localhost / 127.0.0.1 (all of these indicate the same thing). Jeff Shannon Technician/Programmer Credit International From kent37 at tds.net Fri Dec 10 02:29:35 2004 From: kent37 at tds.net (Kent Johnson) Date: Fri Dec 10 02:29:40 2004 Subject: [Tutor] PDF and Python In-Reply-To: References: Message-ID: <41B8FBFF.8040801@tds.net> The reportlab toolkit is frequently recommended, though I haven't tried it myself. http://www.reportlab.org/ Kent Jason Child wrote: > Hey there. Does anyone know of a way to output PDFs with python? I have some > data that I have processed from a series of textfiles that I would like to > provide PDF format reports for.. > > Jason Christopher Child > > Computer Network Services Professionals > Tech Support > 505-986-1669 > 1-877-321-9165 > jasonchild@cnsp.com > > VOZ Online > VOIP Install Tech > 505-428-7500 > 1-877-428-7550 > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From guillermo.fernandez.castellanos at gmail.com Fri Dec 10 03:23:21 2004 From: guillermo.fernandez.castellanos at gmail.com (Guillermo Fernandez Castellanos) Date: Fri Dec 10 03:23:24 2004 Subject: [Tutor] Capturing Logfile data in Windows In-Reply-To: <41B88B58.1030007@xfr.co.uk> References: <41B88B58.1030007@xfr.co.uk> Message-ID: <7d7029e704120918236f30f3af@mail.gmail.com> Hi, If you want an easy way of iterating over stdin, you may be interested in using this module: http://www.python.org/dev/doc/devel/lib/module-fileinput.html I've used it with some of my scripts to do something similar. It will not work for a growing file though... Otherwise, you can always try something like this (I also use this method): import sys if a_file_has_been_passed_as_an_argument : myinput=file(os.path.expanduser(args[0]),'r') elif otherwise: myinput=sys.stdin # I have to admit I did not know how to code the EOF, so I used the # 'while line != ""' instead of 'while not EOF' line="a" while line!="": line = myinput.readline() print line[:-1] Enjoy, Guille On Thu, 09 Dec 2004 17:28:56 +0000, Philip Kilner wrote: > Hi List, > > I have a closed-source application which creates log files. I'd like to > capture this logfile data as it is crated, and do clever things with it! > > Is this possible? I guess it must be, because there are "tail" type > utilities for Windows... > > Is it possible in Python? I'd be grateful for any pointers! > > BTW, it doesn't matter either way whether I can somehow pipe the log > output to my program /without/ the file actually being created, or if I > can capture it /as/ it is created - I just need to get my mitts on the > data as it is generated...it would be better if I had the file as well, > but it is not essential... > > Thanks in Anticipation! > > -- > > Regards, > > PhilK > > Email: phil@xfr.co.uk / Voicemail & Facsimile: 07092 070518 > > "Work as if you lived in the early days of a better nation." - Alasdair Gray > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at freenet.co.uk Fri Dec 10 07:41:32 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Dec 10 07:44:40 2004 Subject: [Tutor] PDF and Python References: Message-ID: <007b01c4de83$cde36390$67d98751@xp> > Hey there. Does anyone know of a way to output PDFs with python? I have some > data that I have processed from a series of textfiles that I would like to > provide PDF format reports for.. I can't recall what its called but a couple of years ago I found a module on the Parnassus site for processing PDFs. It was really for extracting data from a PDF but it might be able to write them too. HTH, Alan g. From nick at javacat.f2s.com Fri Dec 10 11:08:49 2004 From: nick at javacat.f2s.com (nick@javacat.f2s.com) Date: Fri Dec 10 11:08:51 2004 Subject: [Tutor] PDF and Python In-Reply-To: <41B8FBFF.8040801@tds.net> References: <41B8FBFF.8040801@tds.net> Message-ID: <1102673329.41b975b12073a@webmail.freedom2surf.net> Quoting Kent Johnson : > The reportlab toolkit is frequently recommended, though I haven't tried it > myself. > http://www.reportlab.org/ > > Kent Whoa ! Just has a play with that ReportLab toolkit and it looks well funky. It makes creating simple PDF's a doddle. Thanks for the link Kent :) Nick . From rdm at rcblue.com Fri Dec 10 11:15:57 2004 From: rdm at rcblue.com (Dick Moores) Date: Fri Dec 10 11:21:40 2004 Subject: [Tutor] Complex roots In-Reply-To: <1f7befae041209074162bedff9@mail.gmail.com> References: <20041209110126.2DD251E400D@bag.python.org> <1102593135.6535.37.camel@dhcp0320.acl.icnet.uk> <1f7befae041209074162bedff9@mail.gmail.com> Message-ID: <6.1.2.0.2.20041210012337.047ccb00@rcblue.com> Aw, that's just amazing. I put your function in http://www.rcblue.com/Python/croots.py, which gets c and n from user and adds a test function. Here's what one run produces: ==================================== Enter either a complex number in form x + yj, or a real number: 3.1 -1j Enter an integer n, to find the n'th roots: 5 c is (3.1-1j); n is 5 root1 is (1.26393645827-0.0789828505298j) root1 to the 5 power is (3.1-1j) root2 is (0.465695000088+1.17766796174j) root2 to the 5 power is (3.1-1j) root3 is (-0.976121119826+0.806821678349j) root3 to the 5 power is (3.1-1j) root4 is (-1.06897102928-0.679024741664j) root4 to the 5 power is (3.1-1j) root5 is (0.315460690744-1.2264820479j) root5 to the 5 power is (3.1-1j) ====================================== Actually, I'm trying to write a Python script that computes all 3 roots of a cubic equation. Do you happen to have one tucked away in your store of wisdom and tricks? (One for real coefficients will do). Anyway, thought it wouldn't hurt to ask.. Dick Tim Peters wrote at 07:41 12/9/2004: >Try this instead: > >def croots(c, n): > """Return list of the n n'th roots of complex c.""" > from math import sin, cos, atan2, pi > > arg = abs(c)**(1.0/n) > theta = atan2(c.imag, c.real) > result = [] > for i in range(n): > theta2 = (theta + 2*pi*i)/n > x = arg * cos(theta2) > y = arg * sin(theta2) > result.append(complex(x, y)) > return result From cyresse at gmail.com Fri Dec 10 13:07:06 2004 From: cyresse at gmail.com (Liam Clarke) Date: Fri Dec 10 13:07:08 2004 Subject: [Tutor] MemoryError In-Reply-To: <41B8EFF4.6050309@tds.net> References: <41B76416.6020403@ccvcorp.com> <41B78D6A.7040107@ccvcorp.com> <41B8AD4A.5050206@ccvcorp.com> <41B8EFF4.6050309@tds.net> Message-ID: Hi Kent, Thanks for the help, it worked third time around! The final product is here if you have an interest - http://www.rafb.net/paste/results/XCYthC70.html But, I think I found a new best friend for this sort of thing - (?P.*?) Being able to label stuff is brilliant. But yeah, thanks for the help, especially that sub method. Regards, Liam Clarke On Thu, 09 Dec 2004 19:38:12 -0500, Kent Johnson wrote: > Liam, > > Here's a nifty re trick for you. The sub() method can take a function as the replacement parameter. > Instead of replacing with a fixed string, the function is called with the match object. Whatever > string the function returns, is substituted for the match. So you can simplify your code a bit, > something like this: > > def replaceTag(item): # item is a match object > # This is exactly your code > > > text=gettextFunc(item.group()) #Will try and stick to string method > for this, but I'll see. > if not text: > text="Default" #Will give a text value for the href, so some > lucky human can change it > url=geturlFunc(item.group()) # The simpler the better, and so far > re has been the simplest > if not url: > href = '"" #This will delete the applet, as there are applet's > acting as placeholders > else: > href='%s' % (url, text) > > # Now return href > return href > > now your loop and replacements get replaced by the single line > codeSt = reObj.sub(replaceTag, codeSt) > > :-) > > Kent > > > > > Liam Clarke wrote: > > Hi all, > > > > Yeah, I should've written this in functions from the get go, but I > > thought it would be a simple script. :/ > > > > I'll come back to that script when I've had some sleep, my son was > > recently born and it's amazing how dramatically lack of sleep affects > > my acuity. But, I want to figure out what's going wrong. > > > > That said, the re path is bearing fruit. I love the method finditer(), > > as I can reduce my overly complicated string methods from my original > > code to > > > > x=file("toolkit.txt",'r') > > s=x.read() > > x.close() > > appList=[] > > > > regExIter=reObj.finditer(s) #Here's a re obj I compiled earlier. > > > > for item in regExIter: > > text=gettextFunc(item.group()) #Will try and stick to string method > > for this, but I'll see. > > if not text: > > text="Default" #Will give a text value for the href, so some > > lucky human can change it > > url=geturlFunc(item.group()) # The simpler the better, and so far > > re has been the simplest > > if not url: > > href = '"" #This will delete the applet, as there are applet's > > acting as placeholders > > else: > > href='%s' % (url, text) > > > > appList.append(item.span(), href) > > > > appList.reverse() > > > > for ((start, end), href) in appList: > > > > codeSt=codeSt.replace(codeSt[start:end], href) > > > > > > Of course, that's just a rought draft, but it seems a whole lot > > simpler to me. S'pose code needs a modicum of planning. > > > > Oh, and I d/led BeautifulSoup, but I couldn't work it right, so I > > tried re, and it suits my needs. > > > > Thanks for all the help. > > > > Regards, > > > > Liam Clarke > > On Thu, 09 Dec 2004 11:53:46 -0800, Jeff Shannon wrote: > > > >>Liam Clarke wrote: > >> > >> > >>>So, I'm going to throw caution to the wind, and try an re approach. It > >>>can't be any more unwieldy and ugly than what I've got going at the > >>>moment. > >> > >>If you're going to try a new approach, I'd strongly suggest using a > >>proper html/xml parser instead of re's. You'll almost certainly have > >>an easier time using a tool that's designed for your specific problem > >>domain than you will trying to force a more general tool to work. > >>Since you're specifically trying to find (and replace) certain html > >>tags and attributes, and that's exactly what html parsers *do*, well, > >>the conclusions seems obvious (to me at least). ;) > >> > >>There are lots of html parsing tools available in Python (though I've > >>never needed one myself). I've heard lots of good things about > >>BeautifulSoup... > >> > >> > >> > >>Jeff Shannon > >>Technician/Programmer > >>Credit International > >> > >>_______________________________________________ > >>Tutor maillist - Tutor@python.org > >>http://mail.python.org/mailman/listinfo/tutor > >> > > > > > > > _______________________________________________ > > > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From RPhillips at engineer.co.summit.oh.us Fri Dec 10 12:54:41 2004 From: RPhillips at engineer.co.summit.oh.us (Ron Phillips) Date: Fri Dec 10 13:15:23 2004 Subject: [Tutor] Re: PDF and Python Message-ID: I just happened across an answer yesterday. PIL writes PDF s. http://www.pythonware.com/products/pil/ Ron -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041210/062f7ea9/attachment.htm From mark.kels at gmail.com Fri Dec 10 13:39:02 2004 From: mark.kels at gmail.com (Mark Kels) Date: Fri Dec 10 13:39:04 2004 Subject: [Tutor] How to get input from Tkinter app ? Message-ID: Hi all, I got 2 questions: 1. How to get input from Tkinter widgets like Text, Entry, Checkbutton, Scale etc (almost any widget that isn't a button) ? for some reason its not explained clearly in any tutor I looked in... 2. How to print text using python ( through the printer ) ? From kent37 at tds.net Fri Dec 10 13:50:25 2004 From: kent37 at tds.net (Kent Johnson) Date: Fri Dec 10 13:50:29 2004 Subject: [Tutor] MemoryError In-Reply-To: References: <41B76416.6020403@ccvcorp.com> <41B78D6A.7040107@ccvcorp.com> <41B8AD4A.5050206@ccvcorp.com> <41B8EFF4.6050309@tds.net> Message-ID: <41B99B91.4050803@tds.net> Well, that's a regex only a mother could love. :-) I can see why you were happy to find the (?P) form of grouping. You should compile textObj and urlObj outside of getVals. You could just pull the four lines that create textObj and urlObj outside of the function (into global scope). You just have to compile a regex once, then you can use it multiple times. Compiling is relatively slow so pulling it out of the loop is an optimization. Congrats on getting this working! Kent Liam Clarke wrote: > Hi Kent, > > Thanks for the help, it worked third time around! > > The final product is here if you have an interest - > http://www.rafb.net/paste/results/XCYthC70.html > > But, I think I found a new best friend for this sort of thing - > (?P.*?) > > Being able to label stuff is brilliant. > > But yeah, thanks for the help, especially that sub method. > > Regards, > > Liam Clarke From RPhillips at engineer.co.summit.oh.us Fri Dec 10 14:02:06 2004 From: RPhillips at engineer.co.summit.oh.us (Ron Phillips) Date: Fri Dec 10 14:02:43 2004 Subject: [Tutor] Graphics coordinates (bump?) Message-ID: I sent the following yesterday, but since it was my first request to the list, I got an autoreply. It never showed up in my digest of the list, and I haven't seen a response. It's in the archives, but I am thinking that archiving/autoreply was all that happened (no actual posting.) Anyway, I am looking hard at PIL, and a little at PyGame. Still looking for suggestions, though. :::::::::::::::: I work for a Civil Engineering organization. I need to give our users a means to generate geographic coordinates for our projects and structures. I plan to do this by making a viewer which will accept a graphic file (png or jpg) and two points (pixels) in that image for which geographic coordinates are given. Users can then click on the image where appropriate to generate a list of geographic points of interest for their work. The list will be saveable as an xml file or a shp file (a widely used geographic binary format.) In addition, other programs that I write will use the viewer as a dialog box: will call the viewer directly and get the points from it, just like a color picker dialog. What I am looking for: thoughts on which Python modules are most appropriate and generally applicable for this. PIL? Piddle? PyGIS? some of Hobu's modules? I believe I can write the glue-code, but I don't want to reinvent the wheel if there are existing modules that do almost (or even better, exactly) what I need. I work on WinXp, Linux, and WindowsCE. WindowsCE has a fairly plain-vanilla Python build, so it's better if I stick to the core modules as far as possible. Ron Phillips -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041210/f9e362e2/attachment.htm From cyresse at gmail.com Fri Dec 10 14:10:33 2004 From: cyresse at gmail.com (Liam Clarke) Date: Fri Dec 10 14:10:36 2004 Subject: [Tutor] MemoryError In-Reply-To: <41B99B91.4050803@tds.net> References: <41B76416.6020403@ccvcorp.com> <41B78D6A.7040107@ccvcorp.com> <41B8AD4A.5050206@ccvcorp.com> <41B8EFF4.6050309@tds.net> <41B99B91.4050803@tds.net> Message-ID: Yeah, that's a bit of a brute force approach alright. Mainly all the (\n)?(=\n)?... I, personally, intend to have words with a Mr William Gates regarding just what horrors Frontpage inflicts. I also intend to discuss this with gmail.google.com, as they parsed the text attachment I sent myself, added it to the message body, (it seems),unattached it, and added to the mess a wee bit. My emails always seem strangely formatted, so yes... But, that said, I've been shown far more horrific regexe's. I saw one to parse an ISO-8601 date string (in PHP, I think?) Made mine look elegant and simple... But, it was good to learn a wee bit about the re module. Now that I've actually done this, I probably won't need to do it again, but I'll know a bit more about the appropriate use of re's. I still prefer string methods for the simple stuff. It did start off as a way to avoid cutting & pasting, ended up as a pursuit of knowledge. Oh well. Thanks to all for the assistance. Regards, Liam Clarke On Fri, 10 Dec 2004 07:50:25 -0500, Kent Johnson wrote: > Well, that's a regex only a mother could love. :-) I can see why you were happy to find the > (?P) form of grouping. > > You should compile textObj and urlObj outside of getVals. You could just pull the four lines that > create textObj and urlObj outside of the function (into global scope). You just have to compile a > regex once, then you can use it multiple times. Compiling is relatively slow so pulling it out of > the loop is an optimization. > > Congrats on getting this working! > > > Kent > > Liam Clarke wrote: > > Hi Kent, > > > > Thanks for the help, it worked third time around! > > > > The final product is here if you have an interest - > > http://www.rafb.net/paste/results/XCYthC70.html > > > > But, I think I found a new best friend for this sort of thing - > > (?P.*?) > > > > Being able to label stuff is brilliant. > > > > But yeah, thanks for the help, especially that sub method. > > > > Regards, > > > > Liam Clarke > _______________________________________________ > > > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From rdm at rcblue.com Fri Dec 10 16:38:06 2004 From: rdm at rcblue.com (Dick Moores) Date: Fri Dec 10 16:38:10 2004 Subject: [Tutor] Complex roots In-Reply-To: <6.1.2.0.2.20041210012337.047ccb00@rcblue.com> References: <20041209110126.2DD251E400D@bag.python.org> <1102593135.6535.37.camel@dhcp0320.acl.icnet.uk> <1f7befae041209074162bedff9@mail.gmail.com> <6.1.2.0.2.20041210012337.047ccb00@rcblue.com> Message-ID: <6.1.2.0.2.20041210072810.0894bbe0@rcblue.com> I've modified croots.py to croots2.py () The only changes are in the testCrootsResult function. It will ignore very small .imag or .real when printing. Thus this result: ================================ Enter either a complex number in form x + yj, or a real number: 4 Enter an integer n, to find the n'th roots of that number: 3 c is (4+0j); n is 3 root1 is 1.58740105197, adjusted from (1.58740105197+0j) root1 to the 3 power is 4.0, adjusted from (4+0j) root2 is (-0.793700525984+1.374729637j) root2 to the 3 power is 4.0, adjusted from (4-2.6645352591e-015j) root3 is (-0.793700525984-1.374729637j) root3 to the 3 power is 4.0, adjusted from (4-5.55111512313e-015j) ==================================== Dick Dick Moores wrote at 02:15 12/10/2004: >Aw, that's just amazing. > >I put your function in http://www.rcblue.com/Python/croots.py, which >gets c and n from user and adds a test function. > >Here's what one run produces: > >==================================== >Enter either a complex number in form x + yj, or a real number: 3.1 -1j >Enter an integer n, to find the n'th roots: 5 >c is (3.1-1j); n is 5 > >root1 is (1.26393645827-0.0789828505298j) >root1 to the 5 power is (3.1-1j) > >root2 is (0.465695000088+1.17766796174j) >root2 to the 5 power is (3.1-1j) > >root3 is (-0.976121119826+0.806821678349j) >root3 to the 5 power is (3.1-1j) > >root4 is (-1.06897102928-0.679024741664j) >root4 to the 5 power is (3.1-1j) > >root5 is (0.315460690744-1.2264820479j) >root5 to the 5 power is (3.1-1j) >====================================== > >Actually, I'm trying to write a Python script that computes all 3 roots >of a cubic equation. Do you happen to have one tucked away in your store >of wisdom and tricks? (One for real coefficients will do). > >Anyway, thought it wouldn't hurt to ask.. > >Dick > >Tim Peters wrote at 07:41 12/9/2004: >>Try this instead: >> >>def croots(c, n): >> """Return list of the n n'th roots of complex c.""" >> from math import sin, cos, atan2, pi >> >> arg = abs(c)**(1.0/n) >> theta = atan2(c.imag, c.real) >> result = [] >> for i in range(n): >> theta2 = (theta + 2*pi*i)/n >> x = arg * cos(theta2) >> y = arg * sin(theta2) >> result.append(complex(x, y)) >> return result From rdm at rcblue.com Fri Dec 10 17:35:47 2004 From: rdm at rcblue.com (Dick Moores) Date: Fri Dec 10 17:35:51 2004 Subject: [Tutor] Complex roots In-Reply-To: <6.1.2.0.2.20041210072810.0894bbe0@rcblue.com> References: <20041209110126.2DD251E400D@bag.python.org> <1102593135.6535.37.camel@dhcp0320.acl.icnet.uk> <1f7befae041209074162bedff9@mail.gmail.com> <6.1.2.0.2.20041210012337.047ccb00@rcblue.com> <6.1.2.0.2.20041210072810.0894bbe0@rcblue.com> Message-ID: <6.1.2.0.2.20041210083210.058a8a80@rcblue.com> Oops. Make that croots3.py (). I forgot a couple of abs's. For example, "if n.imag < 1e-13:" is changed to "if abs(n.imag) < 1e-13:" Dick Dick Moores wrote at 07:38 12/10/2004: >I've modified croots.py to croots2.py >() > >The only changes are in the testCrootsResult function. It will ignore >very small .imag or .real when printing. > >Thus this result: >================================ >Enter either a complex number in form x + yj, or a real number: 4 >Enter an integer n, to find the n'th roots of that number: 3 >c is (4+0j); n is 3 > >root1 is 1.58740105197, adjusted from (1.58740105197+0j) >root1 to the 3 power is 4.0, adjusted from (4+0j) > >root2 is (-0.793700525984+1.374729637j) >root2 to the 3 power is 4.0, adjusted from (4-2.6645352591e-015j) > >root3 is (-0.793700525984-1.374729637j) >root3 to the 3 power is 4.0, adjusted from (4-5.55111512313e-015j) >==================================== > >Dick > >Dick Moores wrote at 02:15 12/10/2004: >>Aw, that's just amazing. >> >>I put your function in http://www.rcblue.com/Python/croots.py, which >>gets c and n from user and adds a test function. >> >>Here's what one run produces: >> >>==================================== >>Enter either a complex number in form x + yj, or a real number: 3.1 -1j >>Enter an integer n, to find the n'th roots: 5 >>c is (3.1-1j); n is 5 >> >>root1 is (1.26393645827-0.0789828505298j) >>root1 to the 5 power is (3.1-1j) >> >>root2 is (0.465695000088+1.17766796174j) >>root2 to the 5 power is (3.1-1j) >> >>root3 is (-0.976121119826+0.806821678349j) >>root3 to the 5 power is (3.1-1j) >> >>root4 is (-1.06897102928-0.679024741664j) >>root4 to the 5 power is (3.1-1j) >> >>root5 is (0.315460690744-1.2264820479j) >>root5 to the 5 power is (3.1-1j) >>====================================== >> >>Actually, I'm trying to write a Python script that computes all 3 roots >>of a cubic equation. Do you happen to have one tucked away in your >>store of wisdom and tricks? (One for real coefficients will do). >> >>Anyway, thought it wouldn't hurt to ask.. >> >>Dick >> >>Tim Peters wrote at 07:41 12/9/2004: >>>Try this instead: >>> >>>def croots(c, n): >>> """Return list of the n n'th roots of complex c.""" >>> from math import sin, cos, atan2, pi >>> >>> arg = abs(c)**(1.0/n) >>> theta = atan2(c.imag, c.real) >>> result = [] >>> for i in range(n): >>> theta2 = (theta + 2*pi*i)/n >>> x = arg * cos(theta2) >>> y = arg * sin(theta2) >>> result.append(complex(x, y)) >>> return result > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From davholla2002 at yahoo.co.uk Fri Dec 10 18:28:41 2004 From: davholla2002 at yahoo.co.uk (David Holland) Date: Fri Dec 10 18:28:44 2004 Subject: [Tutor] How to get input from Tkinter app ? In-Reply-To: <20041210153815.A0EAC1E4014@bag.python.org> Message-ID: <20041210172841.71277.qmail@web25406.mail.ukl.yahoo.com> Here is an example create a function eg createwidgets(self) with code like self.question_ent = Entry(self) self.question_ent.grid(row=0, column = 4, columnspan = 2, sticky = W) Then in another function eg getinfo(self) which is fired off by a button or something write code like :- question = self.question_ent.get() this will get the info that the user had put in. Put some error handling code in case the user puts something stupid in (or nothing). Which will return to screen any mistakes. I hope this makes sense this is the first time I have helped anyone ! --------------------------------- Win a castle for NYE with your mates and Yahoo! Messenger -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041210/32d4faf1/attachment.htm From bagchee at cse.ohio-state.edu Fri Dec 10 19:17:20 2004 From: bagchee at cse.ohio-state.edu (Nandan) Date: Fri Dec 10 19:17:23 2004 Subject: [Tutor] os.listdir fn Message-ID: Hello I need to get the equivalent of 'ls script.icons/*.script' I looked around in the os module but can't find anything appropriate. That is, filename globbing doesn't seem to work. Looks like I'll have to use map/filter to do this. Is there a better way? Thanks, N -- Nandan Bagchee Patriots don't use Linux. -- c.o.l.a From kent37 at tds.net Fri Dec 10 19:32:18 2004 From: kent37 at tds.net (Kent Johnson) Date: Fri Dec 10 19:32:21 2004 Subject: [Tutor] os.listdir fn In-Reply-To: References: Message-ID: <41B9EBB2.4060403@tds.net> Have you looked at the glob module? >>> import glob >>> glob.glob('src/*.properties') ['src\\jdbc.properties', 'src\\jdbc_local.properties', 'src\\jdbc_qa.properties', 'src\\jdbc_test.properties', 'src\\log4j.jnlp.properties', 'src\\log4j.properties', 'src\\version.properties'] Kent Nandan wrote: > Hello > > I need to get the equivalent of 'ls script.icons/*.script' > I looked around in the os module but can't find anything appropriate. > > That is, filename globbing doesn't seem to work. Looks like I'll have to > use map/filter to do this. Is there a better way? > > Thanks, > N > From john.ertl at fnmoc.navy.mil Fri Dec 10 19:34:41 2004 From: john.ertl at fnmoc.navy.mil (Ertl, John) Date: Fri Dec 10 19:35:07 2004 Subject: [Tutor] maximum value in a Numeric array Message-ID: All, I am trying to get the maximum value in a 2-D array. I can use max but it returns the 1-D array that the max value is in and I then I need to do max again on that array to get the single max value. There has to be a more straightforward way...I have just not found it. >>> b = array([[1,2],[3,4]]) >>> max(b) array([3, 4]) >>> c = max(b) >>> max(c) 4 >>> I could also flatten the array to 1 D first then do max but the array I am going to be working with is fairly large. Thanks From dbroadwell at mindspring.com Fri Dec 10 19:58:12 2004 From: dbroadwell at mindspring.com (David Broadwell) Date: Fri Dec 10 19:56:48 2004 Subject: [Tutor] (Self resolved) os.spawn behavior issue Message-ID: Further note: widen the window, this has long strings in it ... and is PURELY for edification. To work around a problem between my ISP and my router, I have to make my router RELogin the PPPoE every time the wan ip changes. Which is not hard, it's a http string in a browser to log in, followed by a pause and a second http string to make the magic internet return, and my DDNS client is very good at telling when it ceases to work. While I am a relative code noob, this with a sleep.py was hacked out in 30 minutes (after some testing). But being a perfectionist, I want to do it entirely in python. First with controlling the browser, than maybe later socket connections to the router itself. import os,time os.spawn(os.P_NOWAIT,browser,[logincommand]) time.sleep(20) os.spawn(os.P_NOWAIT,browser,[relogcommand]) exit I have been hacking at getting os.spawnv to do what I want it to, with no luck. The 'want' is a simple one, open a browser (in this case IE) to a given URL. Like; YOUR PROMPT HERE> "C:/Program Files/Internet Explorer/Iexplore.exe" http://www.yahoo.com Which functions as expected. Even os.system('"C:\Program Files\Internet Explorer\Iexplore.exe" http://www.yahoo.com') Works, but waits for the browser to close to return, and I need an immediate return. Here are some things I've tried ... Which to simplify for a tutor posting # Yields: Just Opens IE Successfully As expected! # os.spawnv(os.P_NOWAIT,"C:/Program Files/Internet Explorer/Iexplore.exe", []) # os.spawnv(os.P_NOWAIT,'C:/Program Files/Internet Explorer/Iexplore.exe', []) # Yields: Invalid Argument - forward slash, full command string # os.spawnv(os.P_NOWAIT,'"C:/Program Files/Internet Explorer/Iexplore.exe" www.yahoo.com',[]) # os.spawnv(os.P_NOWAIT,'C:/Program Files/Internet Explorer/Iexplore.exe http://www.yahoo.com',[]) # os.spawnv(os.P_NOWAIT,'"C:/Program Files/Internet Explorer/Iexplore.exe" http://www.yahoo.com',[]) # os.spawnv(os.P_NOWAIT,'"C:/Program Files/Internet Explorer/Iexplore.exe" http:////www.yahoo.com',[]) # os.spawnv(os.P_NOWAIT,r'C:/Program Files/Internet Explorer/Iexplore.exe http://www.yahoo.com',[]) # os.spawnv(os.P_NOWAIT,r'"C:/Program Files/Internet Explorer/Iexplore.exe" http://www.yahoo.com',[]) # Yields: No such file or directory # os.spawnv(os.P_NOWAIT,'C:/Program Files/Internet Explorer/Iexplore.exe www.yahoo.com',[]) # Yields: Opens IE Successfully - Yet No ARG Passed to browser # os.spawnv(os.P_NOWAIT,"C:/Program Files/Internet Explorer/Iexplore.exe", ['www.yahoo.com']) # os.spawnv(os.P_NOWAIT,"C:/Program Files/Internet Explorer/Iexplore.exe", ["www.yahoo.com"]) # os.spawnv(os.P_NOWAIT,"C:/Program Files/Internet Explorer/Iexplore.exe", ['"www.yahoo.com"']) # os.spawnv(os.P_NOWAIT,"C:/Program Files/Internet Explorer/Iexplore.exe", [r'www.yahoo.com']) # os.spawnv(os.P_NOWAIT,"C:/Program Files/Internet Explorer/Iexplore.exe", [r"www.yahoo.com"]) # os.spawnv(os.P_NOWAIT,"C:/Program Files/Internet Explorer/Iexplore.exe", [r'"www.yahoo.com"']) # os.spawnv(os.P_NOWAIT,"C:/Program Files/Internet Explorer/Iexplore.exe", ['"http://www.yahoo.com"']) # os.spawnv(os.P_NOWAIT,"C:/Program Files/Internet Explorer/Iexplore.exe", ["http://www.yahoo.com"]) # os.spawnv(os.P_NOWAIT,"C:/Program Files/Internet Explorer/Iexplore.exe", ['http://www.yahoo.com']) # os.spawnv(os.P_NOWAIT,"C:/Program Files/Internet Explorer/Iexplore.exe", ['"http:////www.yahoo.com"']) # os.spawnv(os.P_NOWAIT,"C:/Program Files/Internet Explorer/Iexplore.exe", ["http:////www.yahoo.com"]) # os.spawnv(os.P_NOWAIT,"C:/Program Files/Internet Explorer/Iexplore.exe", ['http:////www.yahoo.com']) # os.spawnv(os.P_NOWAIT,"C:/Program Files/Internet Explorer/Iexplore.exe", [r'"http://www.yahoo.com"']) # os.spawnv(os.P_NOWAIT,"C:/Program Files/Internet Explorer/Iexplore.exe", [r"http://www.yahoo.com"]) # os.spawnv(os.P_NOWAIT,"C:/Program Files/Internet Explorer/Iexplore.exe", [r'http://www.yahoo.com']) # os.spawnv(os.P_NOWAIT,'C:/Program Files/Internet Explorer/Iexplore.exe', ['www.yahoo.com']) # os.spawnv(os.P_NOWAIT,'C:/Program Files/Internet Explorer/Iexplore.exe', ["www.yahoo.com"]) # os.spawnv(os.P_NOWAIT,'C:/Program Files/Internet Explorer/Iexplore.exe', ['"www.yahoo.com"']) # os.spawnv(os.P_NOWAIT,'C:/Program Files/Internet Explorer/Iexplore.exe', [r'www.yahoo.com']) # os.spawnv(os.P_NOWAIT,'C:/Program Files/Internet Explorer/Iexplore.exe', [r"www.yahoo.com"]) # os.spawnv(os.P_NOWAIT,'C:/Program Files/Internet Explorer/Iexplore.exe', [r'"www.yahoo.com"']) # os.spawnv(os.P_NOWAIT,'C:/Program Files/Internet Explorer/Iexplore.exe', ['"http://www.yahoo.com"']) # os.spawnv(os.P_NOWAIT,'C:/Program Files/Internet Explorer/Iexplore.exe', ["http://www.yahoo.com"]) # os.spawnv(os.P_NOWAIT,'C:/Program Files/Internet Explorer/Iexplore.exe', ['http://www.yahoo.com']) # os.spawnv(os.P_NOWAIT,'C:/Program Files/Internet Explorer/Iexplore.exe', ['"http:////www.yahoo.com"']) # os.spawnv(os.P_NOWAIT,'C:/Program Files/Internet Explorer/Iexplore.exe', ["http:////www.yahoo.com"]) # os.spawnv(os.P_NOWAIT,'C:/Program Files/Internet Explorer/Iexplore.exe', ['http:////www.yahoo.com']) # os.spawnv(os.P_NOWAIT,'C:/Program Files/Internet Explorer/Iexplore.exe', [r'"http://www.yahoo.com"']) # os.spawnv(os.P_NOWAIT,'C:/Program Files/Internet Explorer/Iexplore.exe', [r"http://www.yahoo.com"]) # os.spawnv(os.P_NOWAIT,'C:/Program Files/Internet Explorer/Iexplore.exe', [r'http://www.yahoo.com']) The issue seems to be passing the [argument] to the program .. Even example source I've found on the net has Sorry about the widthspam, any suggestions? -- AND as I always search after I've completely written my message, I found a tip from Richard Chamberlain in July of 2000 http://mail.python.org/pipermail/tutor/2000-July/001759.html. # Yields Browser with 'http://files/Internet%20Explorer/Iexplore.exe%20www.yahoo.com' string in it. # os.spawnv(os.P_NOWAIT,"C:/Program Files/Internet Explorer/Iexplore.exe", ["C:/Program Files/Internet Explorer/Iexplore.exe", 'www.yahoo.com']) # os.spawnv(os.P_NOWAIT,"C:/Program Files/Internet Explorer/Iexplore.exe", [r"C:/Program Files/Internet Explorer/Iexplore.exe", 'www.yahoo.com']) # Yields Browser with 'http://explorer/Iexplore.exe%20www.yahoo.com' # os.spawnv(os.P_NOWAIT,"C:/Program Files/Internet Explorer/Iexplore.exe", ["C:/Progra~1/Internet Explorer/Iexplore.exe", 'www.yahoo.com']) # Finally! Yields browser with www.yahoo.com in it!! os.spawnv(os.P_NOWAIT,"C:/Program Files/Internet Explorer/Iexplore.exe", ["C:/Progra~1/Intern~1/Iexplore.exe", 'www.yahoo.com']) Man was this unpythonesque. Why in the world doesn't the http://www.python.org/doc/2.4/lib/os-process.html state that the program name is required twice? Ok, the example DOES show it, but that is it ... it's left unsaid. Aside form that, that the list cannot handle Long File Names, does ~seem~ to need to be addressed, I'm not the one to say that it is wrong as it is. -- David Broadwell OT: Fun with spellchecker in this message; RELogin = Religion PPPoE = Pope IP = imp psucodoce = pseudopodia sleep.py = sloppy os,time = costume From kent37 at tds.net Fri Dec 10 20:19:08 2004 From: kent37 at tds.net (Kent Johnson) Date: Fri Dec 10 20:19:10 2004 Subject: [Tutor] maximum value in a Numeric array In-Reply-To: References: Message-ID: <41B9F6AC.6050903@tds.net> Are you using numarray? If so, there appears to be a max method of an array, so you can try b = array([[1,2],[3,4]]) b.max() Note that your method of finding the max row, then finding the max in the row, will not in general give the correct result. Sequences are compared lexicographically - the first elements are compared, and only if they match will the second elements be compared. Using plain lists: >>> b=[ [3,2], [1,4] ] >>> max(b) [3, 2] >>> max(max(b)) 3 You can use a list comprehension to do what you want >>> max([max(l) for l in b]) 4 or in Python 2.4 you can use a generator expression and avoid creating the intermediate list: >>> max(max(l) for l in b) 4 Kent Ertl, John wrote: > All, > > I am trying to get the maximum value in a 2-D array. I can use max but it > returns the 1-D array that the max value is in and I then I need to do max > again on that array to get the single max value. > > There has to be a more straightforward way...I have just not found it. > > >>>>b = array([[1,2],[3,4]]) >>>>max(b) > > array([3, 4]) > >>>>c = max(b) >>>>max(c) > > 4 > > > I could also flatten the array to 1 D first then do max but the array I am > going to be working with is fairly large. > > Thanks > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From dyoo at hkn.eecs.berkeley.edu Fri Dec 10 20:25:38 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Dec 10 20:25:42 2004 Subject: [Tutor] maximum value in a Numeric array In-Reply-To: Message-ID: On Fri, 10 Dec 2004, Ertl, John wrote: > I am trying to get the maximum value in a 2-D array. I can use max but > it returns the 1-D array that the max value is in and I then I need to > do max again on that array to get the single max value. > > There has to be a more straightforward way...I have just not found it. > > >>> b = array([[1,2],[3,4]]) > >>> max(b) > array([3, 4]) > >>> c = max(b) > >>> max(c) > 4 Hi John, According to: http://stsdas.stsci.edu/numarray/numarray-1.1.html/node35.html#l2h-108 you can use the 'max()' method of an array: ### >>> import numarray >>> b = numarray.array([[1,2],[3,4]]) >>> b.max() 4 ### Hope this helps! From john.ertl at fnmoc.navy.mil Fri Dec 10 22:36:49 2004 From: john.ertl at fnmoc.navy.mil (Ertl, John) Date: Fri Dec 10 22:37:22 2004 Subject: [Tutor] maximum value in a Numeric array Message-ID: All, Thanks for the help...I am using the older Numeric 23.4. I have some stuff that cannot use Numarray yet. Numeric does not seam to have the same functionality. Happy Holidays. John Ertl -----Original Message----- From: Danny Yoo [mailto:dyoo@hkn.eecs.berkeley.edu] Sent: Friday, December 10, 2004 11:26 To: Ertl, John Cc: tutor@python.org Subject: Re: [Tutor] maximum value in a Numeric array On Fri, 10 Dec 2004, Ertl, John wrote: > I am trying to get the maximum value in a 2-D array. I can use max but > it returns the 1-D array that the max value is in and I then I need to > do max again on that array to get the single max value. > > There has to be a more straightforward way...I have just not found it. > > >>> b = array([[1,2],[3,4]]) > >>> max(b) > array([3, 4]) > >>> c = max(b) > >>> max(c) > 4 Hi John, According to: http://stsdas.stsci.edu/numarray/numarray-1.1.html/node35.html#l2h-108 you can use the 'max()' method of an array: ### >>> import numarray >>> b = numarray.array([[1,2],[3,4]]) >>> b.max() 4 ### Hope this helps! From alan.gauld at freenet.co.uk Sat Dec 11 01:01:05 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat Dec 11 01:00:19 2004 Subject: [Tutor] os.listdir fn References: Message-ID: <004f01c4df14$83130be0$9c8f8651@xp> > That is, filename globbing doesn't seem to work. Looks like I'll have to > use map/filter to do this. Is there a better way? It does if you use the glob module :-) Python, with batteries included. But sometimes finding the right battery can be challenging... Alan G. > > Thanks, > N > > -- > Nandan Bagchee > > > Patriots don't use Linux. > > -- c.o.l.a > > > From alan.gauld at freenet.co.uk Sat Dec 11 01:11:04 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat Dec 11 01:10:19 2004 Subject: [Tutor] maximum value in a Numeric array References: Message-ID: <005601c4df15$e82320a0$9c8f8651@xp> > I am trying to get the maximum value in a 2-D array. I can use max but it > returns the 1-D array that the max value is in and I then I need to do max > again on that array to get the single max value. > > There has to be a more straightforward way...I have just not found it. > I could also flatten the array to 1 D first then do max but the array I am > going to be working with is fairly large. Two max() calls seems pretty straightforward to me! It probably is possible to be slightly more efficient, but you will have to look at every value in the array at least once whatever you do. The simple brute force approach is probably the best here: # NOTE: untested code... def maximum(matrix): max = None # not 0 to cope with negative matrices for col in matrix: for elem in col: if not max or (elem > max): max = elem return max This only touches each element once and you can't break out till the end because you don't know that the last elemement won't be biggest. However it might be possible to make it faster by sorting the colums and just comparing the first elements. This is because the sort will be in C rather than Python... But premature optimisation would be pointless if the above works... Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From cyresse at gmail.com Sat Dec 11 02:48:33 2004 From: cyresse at gmail.com (Liam Clarke) Date: Sat Dec 11 02:48:36 2004 Subject: [Tutor] Re: Could I have used time or datetime modules here? In-Reply-To: <6.1.2.0.2.20041210062534.07e9da00@rcblue.com> References: <6.1.2.0.2.20041207040419.0480a490@rcblue.com> <6.1.2.0.2.20041208151719.049b2eb0@rcblue.com> <6.1.2.0.2.20041210022806.047cbeb0@rcblue.com> <6.1.2.0.2.20041210035325.05c06100@rcblue.com> <6.1.2.0.2.20041210051216.03240aa0@rcblue.com> <6.1.2.0.2.20041210062534.07e9da00@rcblue.com> Message-ID: Hi Dick, I'm ccing this to the list, for the experienced people to comment on . Traceback (most recent call last): > File "", line 1, in -toplevel- > import pygame > File "C:\Python24\lib\site-packages\pygame\__init__.py", line 64, in > -toplevel- > from pygame.base import * > ImportError: Module use of python23.dll conflicts with this version of > Python. As far as I know, you'll either have to - run Python 2.3 or - run Python 2.3 until they release a new version of Pygame, Tutors? Regards, Liam Clarke On Fri, 10 Dec 2004 06:38:21 -0800, Dick Moores wrote: > Liam, > > Glad to find a searchable archive of tutor. > > Searched on PHYTHONPATH there, read a bunch and tried this (pygame is at > C:\Python23\Lib\site-packages\pygame) > >>> import sys > >>> sys.path.append('C:\Python23\Lib\site-packages\pygame') > >>> import pygame > Traceback (most recent call last): > File "", line 1, in -toplevel- > import pygame > ImportError: No module named pygame > > and > > >>> print sys.path > ['C:\\Python24\\Lib\\idlelib', 'C:\\Python23', > 'C:\\WINDOWS\\system32\\python24.zip', 'C:\\Documents and > Settings\\Dick', 'C:\\Python24\\DLLs', 'C:\\Python24\\lib', > 'C:\\Python24\\lib\\plat-win', 'C:\\Python24\\lib\\lib-tk', > 'C:\\Python24', 'C:\\Python24\\lib\\site-packages', > 'C:\\Python24\\lib\\site-packages\\win32', > 'C:\\Python24\\lib\\site-packages\\win32\\lib', > 'C:\\Python24\\lib\\site-packages\\Pythonwin'] > > Could the problem be that I've installed Python 2.4? pygame installed > itself at C:\Python23\Lib\site-packages\pygame. > > Just now I copied pygame to C:\Python24\Lib\site-packages and now get > >>> import pygame > > Traceback (most recent call last): > File "", line 1, in -toplevel- > import pygame > File "C:\Python24\lib\site-packages\pygame\__init__.py", line 64, in > -toplevel- > from pygame.base import * > ImportError: Module use of python23.dll conflicts with this version of > Python. > > Dick > > Liam Clarke wrote at 05:17 12/10/2004: > > > >Nevermind. Don't need it. > > > >Just fire up your interpreter and check out sys.path. Search the tutor > >list's archives for at ActiveState for PYTHONPATH. > > > >Good luck, > > > >Liam > > > > > >On Fri, 10 Dec 2004 05:13:05 -0800, Dick Moores wrote: > > > Don't know. Never used it, anyway. What's the filename, and I'll search > > > for it on my hard drive. > > > > > > Thanks > > > > > > Liam Clarke wrote at 04:20 12/10/2004: > > > > > > > > > >Dick, > > > > > > > >Do you have MSN Messenger at all? > > > > > > > >Liam > > > > > > > > > > > >-- > >'There is only one basic human right, and that is to do as you damn well > >please. > >And with it comes the only basic human duty, to take the consequences. > > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From dbroadwell at mindspring.com Sat Dec 11 05:08:56 2004 From: dbroadwell at mindspring.com (David Broadwell) Date: Sat Dec 11 05:07:35 2004 Subject: [Tutor] (Self resolved) os.spawn behaviorism issue In-Reply-To: Message-ID: Further note: widen the window, this has long strings in it ... and is PURELY for edification. To work around a problem between my ISP and my router, I have to make my router RELogin the PPPoE every time the wan ip changes. Which is not hard, it's a http string in a browser to log in, followed by a pause and a second http string to make the magic internet return, and my DDNS client is very good at telling when the internet ceases to work. While I am a relative code noob, this with a sleep.py was hacked out in 30 minutes (after some testing). But being a perfectionist, I wanted to do it entirely in python. import os,time os.spawn(os.P_NOWAIT,browser,[logincommand]) time.sleep(20) os.spawn(os.P_NOWAIT,browser,[relogcommand]) exit I have been hacking at getting os.spawnv to do what I want it to, with no luck. The 'want' is a simple one, open a browser (in this case IE) to a given URL. Like; YOUR PROMPT HERE> "C:/Program Files/Internet Explorer/Iexplore.exe" http://www.yahoo.com Which functions as expected. Even os.system('"C:\Program Files\Internet Explorer\Iexplore.exe" http://www.yahoo.com') Works, but waits for the browser to close to return, and I need an immediate return. Here are some things I've tried ... # Yields: Just Opens IE Successfully As expected! # os.spawnv(os.P_NOWAIT,"C:/Program Files/Internet Explorer/Iexplore.exe", []) # os.spawnv(os.P_NOWAIT,'C:/Program Files/Internet Explorer/Iexplore.exe', []) # Yields: Invalid Argument - forward slash, full command string # os.spawnv(os.P_NOWAIT,'"C:/Program Files/Internet Explorer/Iexplore.exe" www.yahoo.com',[]) # os.spawnv(os.P_NOWAIT,'C:/Program Files/Internet Explorer/Iexplore.exe http://www.yahoo.com',[]) # os.spawnv(os.P_NOWAIT,'"C:/Program Files/Internet Explorer/Iexplore.exe" http://www.yahoo.com',[]) # os.spawnv(os.P_NOWAIT,'"C:/Program Files/Internet Explorer/Iexplore.exe" http:////www.yahoo.com',[]) # os.spawnv(os.P_NOWAIT,r'C:/Program Files/Internet Explorer/Iexplore.exe http://www.yahoo.com',[]) # os.spawnv(os.P_NOWAIT,r'"C:/Program Files/Internet Explorer/Iexplore.exe" http://www.yahoo.com',[]) # Yields: No such file or directory # os.spawnv(os.P_NOWAIT,'C:/Program Files/Internet Explorer/Iexplore.exe www.yahoo.com',[]) # Yields: Opens IE Successfully - Yet No ARG Passed to browser # os.spawnv(os.P_NOWAIT,"C:/Program Files/Internet Explorer/Iexplore.exe", ['www.yahoo.com']) # os.spawnv(os.P_NOWAIT,"C:/Program Files/Internet Explorer/Iexplore.exe", ["www.yahoo.com"]) # os.spawnv(os.P_NOWAIT,"C:/Program Files/Internet Explorer/Iexplore.exe", ['"www.yahoo.com"']) # os.spawnv(os.P_NOWAIT,"C:/Program Files/Internet Explorer/Iexplore.exe", [r'www.yahoo.com']) # os.spawnv(os.P_NOWAIT,"C:/Program Files/Internet Explorer/Iexplore.exe", [r"www.yahoo.com"]) # os.spawnv(os.P_NOWAIT,"C:/Program Files/Internet Explorer/Iexplore.exe", [r'"www.yahoo.com"']) # os.spawnv(os.P_NOWAIT,"C:/Program Files/Internet Explorer/Iexplore.exe", ['"http://www.yahoo.com"']) # os.spawnv(os.P_NOWAIT,"C:/Program Files/Internet Explorer/Iexplore.exe", ["http://www.yahoo.com"]) # os.spawnv(os.P_NOWAIT,"C:/Program Files/Internet Explorer/Iexplore.exe", ['http://www.yahoo.com']) # os.spawnv(os.P_NOWAIT,"C:/Program Files/Internet Explorer/Iexplore.exe", ['"http:////www.yahoo.com"']) # os.spawnv(os.P_NOWAIT,"C:/Program Files/Internet Explorer/Iexplore.exe", ["http:////www.yahoo.com"]) # os.spawnv(os.P_NOWAIT,"C:/Program Files/Internet Explorer/Iexplore.exe", ['http:////www.yahoo.com']) # os.spawnv(os.P_NOWAIT,"C:/Program Files/Internet Explorer/Iexplore.exe", [r'"http://www.yahoo.com"']) # os.spawnv(os.P_NOWAIT,"C:/Program Files/Internet Explorer/Iexplore.exe", [r"http://www.yahoo.com"]) # os.spawnv(os.P_NOWAIT,"C:/Program Files/Internet Explorer/Iexplore.exe", [r'http://www.yahoo.com']) # os.spawnv(os.P_NOWAIT,'C:/Program Files/Internet Explorer/Iexplore.exe', ['www.yahoo.com']) # os.spawnv(os.P_NOWAIT,'C:/Program Files/Internet Explorer/Iexplore.exe', ["www.yahoo.com"]) # os.spawnv(os.P_NOWAIT,'C:/Program Files/Internet Explorer/Iexplore.exe', ['"www.yahoo.com"']) # os.spawnv(os.P_NOWAIT,'C:/Program Files/Internet Explorer/Iexplore.exe', [r'www.yahoo.com']) # os.spawnv(os.P_NOWAIT,'C:/Program Files/Internet Explorer/Iexplore.exe', [r"www.yahoo.com"]) # os.spawnv(os.P_NOWAIT,'C:/Program Files/Internet Explorer/Iexplore.exe', [r'"www.yahoo.com"']) # os.spawnv(os.P_NOWAIT,'C:/Program Files/Internet Explorer/Iexplore.exe', ['"http://www.yahoo.com"']) # os.spawnv(os.P_NOWAIT,'C:/Program Files/Internet Explorer/Iexplore.exe', ["http://www.yahoo.com"]) # os.spawnv(os.P_NOWAIT,'C:/Program Files/Internet Explorer/Iexplore.exe', ['http://www.yahoo.com']) # os.spawnv(os.P_NOWAIT,'C:/Program Files/Internet Explorer/Iexplore.exe', ['"http:////www.yahoo.com"']) # os.spawnv(os.P_NOWAIT,'C:/Program Files/Internet Explorer/Iexplore.exe', ["http:////www.yahoo.com"]) # os.spawnv(os.P_NOWAIT,'C:/Program Files/Internet Explorer/Iexplore.exe', ['http:////www.yahoo.com']) # os.spawnv(os.P_NOWAIT,'C:/Program Files/Internet Explorer/Iexplore.exe', [r'"http://www.yahoo.com"']) # os.spawnv(os.P_NOWAIT,'C:/Program Files/Internet Explorer/Iexplore.exe', [r"http://www.yahoo.com"]) # os.spawnv(os.P_NOWAIT,'C:/Program Files/Internet Explorer/Iexplore.exe', [r'http://www.yahoo.com']) The issue seems to be passing the [argument] to the program .. Even example source I've found on the net has Sorry about the widthspam, any suggestions? -- AND as I always search after I've completely written my message, I found a tip from Richard Chamberlain in July of 2000 http://mail.python.org/pipermail/tutor/2000-July/001759.html. Says the path/file has to be in the list. # Yields Browser with 'http://files/Internet%20Explorer/Iexplore.exe%20www.yahoo.com' string in it. # os.spawnv(os.P_NOWAIT,"C:/Program Files/Internet Explorer/Iexplore.exe", ["C:/Program Files/Internet Explorer/Iexplore.exe", 'www.yahoo.com']) # same as above, But WHY can't it take long file names? # os.spawnv(os.P_NOWAIT,"C:/Program Files/Internet Explorer/Iexplore.exe", [r"C:/Program Files/Internet Explorer/Iexplore.exe", 'www.yahoo.com']) # Yields Browser with 'http://explorer/Iexplore.exe%20www.yahoo.com' # os.spawnv(os.P_NOWAIT,"C:/Program Files/Internet Explorer/Iexplore.exe", ["C:/Progra~1/Internet Explorer/Iexplore.exe", 'www.yahoo.com']) # Finally! Yields browser with www.yahoo.com in it, but took 8.3 format in the list. os.spawnv(os.P_NOWAIT,"C:/Program Files/Internet Explorer/Iexplore.exe", ["C:/Progra~1/Intern~1/Iexplore.exe", 'www.yahoo.com']) Man was this the most unpythonesque oddity I've seen in python. Why in the world doesn't the http://www.python.org/doc/2.4/lib/os-process.html state that the program name is required twice? Ok, the example DOES show it, but that is it ... it's left unsaid. AND it functions with an empty list if there are no arguments ... # Interesting guess it's just a syntaxism of os.spawnv os.spawnv(os.P_NOWAIT,'C:/Program Files/Internet Explorer/Iexplore.exe',['foob',r'http://www.yahoo.com']) -- To sum it up; import os,time os.spawn(os.P_NOWAIT,browser,["ignorethis",logincommand]) time.sleep(20) os.spawn(os.P_NOWAIT,browser,["ignorethis",relogcommand]) -- OT: Fun with spellchecker in this message; RELogin = Religion PPPoE = Pope IP = imp psucodoce = pseudopodia sleep.py = sloppy os,time = costume -- Programmer's mantra; Observe, Brainstorm, Prototype, Repeat David Broadwell From ejp at zomething.com Sat Dec 11 05:28:15 2004 From: ejp at zomething.com (EJP) Date: Sat Dec 11 05:28:10 2004 Subject: [Tutor] Python 2.4 IDLE Windows 2000 In-Reply-To: <41B07DA6.1030703@cso.atmel.com> References: <41B07DA6.1030703@cso.atmel.com> Message-ID: <20041210202815.833898538.ejp@zomething.com> Mike Hansen wrote of an idle IDLE: > That rooted out the problem. A while ago, I changed the colors to kind > of match my VIM color theme(ps_color). When I did > idlelib.PyShell.main(), IDLE came up with my custom color theme. > However, there was a bunch of warnings about my theme. From IDLE, I > deleted the theme. Now IDLE will launch normally. I'll set up the color > > theme later. Maybe older color themes aren't compatible with the newer > IDLE? The color theme must have been laying around. I didn't brute > force > it in or anything like that. > > >IDLE is a > >part of the Standard Library, so it's actually possible to try turning > on > >individual pieces of it, one after the other. Maybe that will help us > >debug what's going on. > > > >Start up your console version of Python, and try: > > > > > >>>>import idlelib.PyShell > >>>>idlelib.PyShell.main() > >>>> Just a +1 to Mike's problem (and the solution). For sake of Googlers searching on error output (which I've done before), here are the errors I was getting on my machine when trying to launch IDLE. Note, when I tried to open a .py file with IDLE the file would not open at all (and there were no error messages) - interesting that the whole process failed - is the missing error handling on the win or python side (no reason for these to have been fatal errors...) Ah, now I can enjoy 2.4. Thanks! my error output (win32): >>> import idlelib.PyShell >>> idlelib.PyShell.main() Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-background' from theme 'sagecomments'. returning default value: '#ffffff' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-foreground' from theme 'sagecomments'. returning default value: '#000000' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-background' from theme 'sagecomments'. returning default value: '#ffffff' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-foreground' from theme 'sagecomments'. returning default value: '#000000' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-background' from theme 'sagecomments'. returning default value: '#ffffff' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-foreground' from theme 'sagecomments'. returning default value: '#000000' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-background' from theme 'sagecomments'. returning default value: '#ffffff' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-foreground' from theme 'sagecomments'. returning default value: '#000000' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-background' from theme 'sagecomments'. returning default value: '#ffffff' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-foreground' from theme 'sagecomments'. returning default value: '#000000' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-background' from theme 'sagecomments'. returning default value: '#ffffff' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-foreground' from theme 'sagecomments'. returning default value: '#000000' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-background' from theme 'sagecomments'. returning default value: '#ffffff' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-foreground' from theme 'sagecomments'. returning default value: '#000000' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-background' from theme 'sagecomments'. returning default value: '#ffffff' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-foreground' from theme 'sagecomments'. returning default value: '#000000' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-background' from theme 'sagecomments'. returning default value: '#ffffff' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-foreground' from theme 'sagecomments'. returning default value: '#000000' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-background' from theme 'sagecomments'. returning default value: '#ffffff' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-foreground' from theme 'sagecomments'. returning default value: '#000000' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-background' from theme 'sagecomments'. returning default value: '#ffffff' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-foreground' from theme 'sagecomments'. returning default value: '#000000' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-background' from theme 'sagecomments'. returning default value: '#ffffff' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-foreground' from theme 'sagecomments'. returning default value: '#000000' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-background' from theme 'sagecomments'. returning default value: '#ffffff' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-foreground' from theme 'sagecomments'. returning default value: '#000000' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-background' from theme 'sagecomments'. returning default value: '#ffffff' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-foreground' from theme 'sagecomments'. returning default value: '#000000' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-background' from theme 'sagecomments'. returning default value: '#ffffff' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-foreground' from theme 'sagecomments'. returning default value: '#000000' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-background' from theme 'sagecomments'. returning default value: '#ffffff' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-foreground' from theme 'sagecomments'. returning default value: '#000000' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-background' from theme 'sagecomments'. returning default value: '#ffffff' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-foreground' from theme 'sagecomments'. returning default value: '#000000' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-background' from theme 'sagecomments'. returning default value: '#ffffff' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-foreground' from theme 'sagecomments'. returning default value: '#000000' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-background' from theme 'sagecomments'. returning default value: '#ffffff' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-foreground' from theme 'sagecomments'. returning default value: '#000000' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-background' from theme 'sagecomments'. returning default value: '#ffffff' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-foreground' from theme 'sagecomments'. returning default value: '#000000' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-background' from theme 'sagecomments'. returning default value: '#ffffff' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-foreground' from theme 'sagecomments'. returning default value: '#000000' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-background' from theme 'sagecomments'. returning default value: '#ffffff' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-foreground' from theme 'sagecomments'. returning default value: '#000000' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-background' from theme 'sagecomments'. returning default value: '#ffffff' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-foreground' from theme 'sagecomments'. returning default value: '#000000' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-background' from theme 'sagecomments'. returning default value: '#ffffff' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-foreground' from theme 'sagecomments'. returning default value: '#000000' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-background' from theme 'sagecomments'. returning default value: '#ffffff' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-foreground' from theme 'sagecomments'. returning default value: '#000000' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-background' from theme 'sagecomments'. returning default value: '#ffffff' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-foreground' from theme 'sagecomments'. returning default value: '#000000' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-background' from theme 'sagecomments'. returning default value: '#ffffff' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-foreground' from theme 'sagecomments'. returning default value: '#000000' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-background' from theme 'sagecomments'. returning default value: '#ffffff' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-foreground' from theme 'sagecomments'. returning default value: '#000000' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-background' from theme 'sagecomments'. returning default value: '#ffffff' Warning: configHandler.py - IdleConf.GetThemeDict - problem retrieving theme element 'builtin-foreground' from theme 'sagecomments'. returning default value: '#000000' From tim.peters at gmail.com Sat Dec 11 05:45:00 2004 From: tim.peters at gmail.com (Tim Peters) Date: Sat Dec 11 05:45:09 2004 Subject: [Tutor] Complex roots In-Reply-To: <6.1.2.0.2.20041210012337.047ccb00@rcblue.com> References: <20041209110126.2DD251E400D@bag.python.org> <1102593135.6535.37.camel@dhcp0320.acl.icnet.uk> <1f7befae041209074162bedff9@mail.gmail.com> <6.1.2.0.2.20041210012337.047ccb00@rcblue.com> Message-ID: <1f7befae04121020454136d1bc@mail.gmail.com> [Dick Moores] > Aw, that's just amazing. Well, complex numbers are amazing in many ways. The code is actually obvious, if you understand the motivation. Polar coordinates are more natural for complex * / and **. If you a view a complex number c as a vector in the complex plane (from the origin to c), then c's n'th roots are just n equally spaced spokes on a wheel, with one of the spokes coinciding with c's "natural" angle divided by n. That determines the angles of all the spokes, since there are n spokes altogether and the angular difference between adjacent spokes is constant (2*pi/n). All the seeming obscurity in the code is really just due to converting between rectangular (x, y) and polar (length, angle) representations. If we worked with polar coordinates all along, the input would be given as a magnitude and angle, say r and a. The n n'th roots then (still in polar coordinates) all have magnitude r**(1./n), and the n angles are a/n, a/n + b, a/n + 2*b, ..., and a/n + (n-1)*b where b=2*pi/n. Piece o' cake! > I put your function in http://www.rcblue.com/Python/croots.py, That's fine by me -- but I'd appreciate it if you stopped claiming there that my name is Bill . ... > Actually, I'm trying to write a Python script that computes all 3 > roots of a cubic equation. Do you happen to have one tucked > away in your store of wisdom and tricks? (One for real coefficients > will do). I don't, no. You can code one for cubics from Cardano's formula, e.g., http://mathworld.wolfram.com/CubicFormula.html but it's rarely worth the bother -- it's complicated and doesn't generalize. In practice, roots for polynomials beyond quadratics are usually obtained by numerical approximation methods that don't care much about the polynomial's degree. From bagchee at cse.ohio-state.edu Sat Dec 11 06:32:39 2004 From: bagchee at cse.ohio-state.edu (Nandan) Date: Sat Dec 11 06:32:44 2004 Subject: [Tutor] os.listdir fn In-Reply-To: <004f01c4df14$83130be0$9c8f8651@xp> Message-ID: > It does if you use the glob module :-) > > Python, with batteries included. > But sometimes finding the right battery can be challenging... > Muttering 'globbing is a Perl concept, listing dirs must be in file ops' I turned first to the Files section of the Nutshell book :-) But I came up with this code, which I'm happy with for several reasons: def createaproposjlist(opname): filelist=os.listdir('./icon.scripts/'+opname) spltnames=map(os.path.splitext,filelist) scripts=filter(lambda x: x[1]=='.script', spltnames) filenames=map(''.join,scripts) filebases=map(lambda x: x[0], spltnames) return filebases; Cheers, Nandan From kent37 at tds.net Sat Dec 11 13:42:03 2004 From: kent37 at tds.net (Kent Johnson) Date: Sat Dec 11 13:42:08 2004 Subject: [Tutor] os.listdir fn In-Reply-To: References: Message-ID: <41BAEB1B.1090906@tds.net> Are you sure this does what you want? You compute 'scripts' and 'filenames' and throw them away. I think this function will return the base name of all the files *and folders* in ./icon.scripts/opname. If you are trying to return the base name of every file or directory whose extension is '.script', you can use a list comprehension to filter the list: def createaproposjlist(opname): filelist=os.listdir('./icon.scripts/'+opname) spltnames=map(os.path.splitext,filelist) return [ name for name, ext in spltnames if ext == '.script' ] If you are concerned about directories with names ending in '.script' then add another filter using os.path.isdir: def createaproposjlist(opname): basedir = './icon.scripts/'+opname filelist=os.listdir(basedir) filelist = [ f for f in filelist if os.path.isfile(os.path.join(basedir, f)) ] spltnames=map(os.path.splitext,filelist) return [ name for name, ext in spltnames if ext == '.script' ] Kent Nandan wrote: >>It does if you use the glob module :-) >> >>Python, with batteries included. >>But sometimes finding the right battery can be challenging... >> > > > Muttering 'globbing is a Perl concept, listing dirs must be in file ops' I > turned first to the Files section of the Nutshell book :-) But I came up with > this code, which I'm happy with for several reasons: > > def createaproposjlist(opname): > filelist=os.listdir('./icon.scripts/'+opname) > spltnames=map(os.path.splitext,filelist) > scripts=filter(lambda x: x[1]=='.script', spltnames) > filenames=map(''.join,scripts) > filebases=map(lambda x: x[0], spltnames) > return filebases; > > Cheers, > Nandan > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From harm.kirchhoff at web.de Sat Dec 11 14:00:51 2004 From: harm.kirchhoff at web.de (Harm Kirchhoff) Date: Sat Dec 11 14:05:50 2004 Subject: [Tutor] Any Math Modules ? Message-ID: <41BAEF83.5050802@web.de> I am currently updating the DMOZ section of: http://www.dmoz.org/Computers/Programming/Languages/Python/Modules/Math_and_Calculations/ If anyone has some useful python packages for math that are not listed in DMOZ, please let me know. It makes life much easier if your code can be found by search engines. From aztech1200 at yahoo.com Sat Dec 11 15:18:30 2004 From: aztech1200 at yahoo.com (Aztech Guy) Date: Sat Dec 11 15:18:34 2004 Subject: [Tutor] PDF and Python In-Reply-To: Message-ID: <20041211141830.65947.qmail@web53303.mail.yahoo.com> Hi, If you only want to convert text files, this tool I wrote may be even easier than using ReportLab: http://sourceforge.net/projects/xtopdf It is based on ReportLab. You can use it both as a standalone command-line tool, to convert a single text file to PDF. Run PDFWriter.py. You can easily modify the code to convert more than one file, or just write a shell script / .BAT/.CMD file to call it in a loop). You can also use it progammatically from your Python programs. Both procedural and object-oriented versions are available. Look at WritePDF.py and PDFWriter.py. Look at PDFBook.py for an example of usage of this tool to create a simple PDF book from a set of text files representing chapters. HTH Az --- Jason Child wrote: > Hey there. Does anyone know of a way to output PDFs > with python? I have some > data that I have processed from a series of > textfiles that I would like to > provide PDF format reports for.. > > Jason Christopher Child > > Computer Network Services Professionals > Tech Support > 505-986-1669 > 1-877-321-9165 > jasonchild@cnsp.com > > VOZ Online > VOIP Install Tech > 505-428-7500 > 1-877-428-7550 > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From kent37 at tds.net Sat Dec 11 17:03:55 2004 From: kent37 at tds.net (Kent Johnson) Date: Sat Dec 11 17:04:02 2004 Subject: [Tutor] Re: Could I have used time or datetime modules here? In-Reply-To: References: <6.1.2.0.2.20041207040419.0480a490@rcblue.com> <6.1.2.0.2.20041208151719.049b2eb0@rcblue.com> <6.1.2.0.2.20041210022806.047cbeb0@rcblue.com> <6.1.2.0.2.20041210035325.05c06100@rcblue.com> <6.1.2.0.2.20041210051216.03240aa0@rcblue.com> <6.1.2.0.2.20041210062534.07e9da00@rcblue.com> Message-ID: <41BB1A6B.2030605@tds.net> Liam Clarke wrote: > As far as I know, you'll either have to - run Python 2.3 or - run > Python 2.3 until they release a new version of Pygame, Yes, any Python addon that uses .pyd or .dll files has to be recompiled for Python2.4. Pygame has many .pyd files so you have to use Python 2.3. Here is a thread on comp.lang.python that explains why... http://tinyurl.com/659mk Kent From bagchee at cse.ohio-state.edu Sat Dec 11 17:32:43 2004 From: bagchee at cse.ohio-state.edu (Nandan) Date: Sat Dec 11 17:32:49 2004 Subject: [Tutor] function that returns a fn Message-ID: I'm looking for resources to help me with a fn that returns a fn after binding one of its arguments (aka currying, like the bind1st of C++) Considering Python syntax is quite straightforward, this is my first try: def getjlistrenderer(opname): def listrender(): # use opname, eg ops=getlist(opname) # or set local fn variable return renderer; return listrender; #?or f=listrender(); return f; Is it really as simple as this? Or will I always return the same function definition? I need it to return a 'new' function for each call to getjlistrender() .. do I need to create a new fn with f=listrender() ? Any pointers to pages/books etc. appreciated. I am looking through my books too, but thought I'd get some more pointers as well. Web searching so far only shows lambda, which is one-liner, and that won't do. Thanks! -- Nandan Bagchee We need a language that lets us scribble and smudge and smear, not a language where you have to sit with a teacup of types balanced on your knee and make polite conversation with a strict old aunt of a compiler. -- Paul Graham From davholla2002 at yahoo.co.uk Sat Dec 11 17:41:41 2004 From: davholla2002 at yahoo.co.uk (David Holland) Date: Sat Dec 11 17:41:44 2004 Subject: [Tutor] Pygame problems In-Reply-To: <20041211110057.14AEB1E401F@bag.python.org> Message-ID: <20041211164141.11000.qmail@web25401.mail.ukl.yahoo.com> I am not sure if this is the right place, apologies if not. Anyway in a game I wrote using pygame, I would like to increase the initial message so it is over several lines. This is the code in the example game if pygame.font: font = pygame.font.Font(None, 36) text = font.render("Pummel The Chimp, And Win $$$", 1, (10, 10, 10)) textpos = text.get_rect(centerx=background.get_width()/2) background.blit(text, textpos) Now how can I get this to be on more than one line and bigger (for my simple game I need a much more detailed explanation). ___________________________________________________________ Win a castle for NYE with your mates and Yahoo! Messenger http://uk.messenger.yahoo.com From kent37 at tds.net Sat Dec 11 20:34:18 2004 From: kent37 at tds.net (Kent Johnson) Date: Sat Dec 11 20:34:22 2004 Subject: [Tutor] function that returns a fn In-Reply-To: References: Message-ID: <41BB4BBA.2050202@tds.net> Yes, it really is that simple. :-) A common example is a function that makes a function which adds a constant to its argument: >>> def makeadder(n): ... def adder(x): ... return x + n ... return adder ... Make a function that adds 3 to its argument...note there is no special syntax for the return, just assign to a name >>> add3 = makeadder(3) add3 is a function: >>> add3 >>> add3(4) 7 Make another function to add 5: >>> add5 = makeadder(5) >>> add5(10) 15 add3 still works, it is a separate function with its own binding of n: >>> add3(2) 5 Kent Nandan wrote: > I'm looking for resources to help me with a fn that returns a fn after > binding one of its arguments (aka currying, like the bind1st of C++) > > Considering Python syntax is quite straightforward, this is my first try: > > def getjlistrenderer(opname): > def listrender(): > # use opname, eg ops=getlist(opname) > # or set local fn variable > return renderer; > return listrender; > #?or f=listrender(); return f; > > Is it really as simple as this? Or will I always return the same function > definition? I need it to return a 'new' function for each call to > getjlistrender() .. do I need to create a new fn with f=listrender() ? No, this is a call to listrender, it will return the renderer object not a function. > > Any pointers to pages/books etc. appreciated. I am looking through my > books too, but thought I'd get some more pointers as well. Web searching > so far only shows lambda, which is one-liner, and that won't do. There are several currying recipes in the Python Cookbook: http://aspn.activestate.com/ASPN/search?query=curry&x=0&y=0§ion=PYTHONCKBK&type=Subsection Searching the cookbook for 'closure' also gives some recipes that might be of interest. Kent > > Thanks! From missive at hotmail.com Sat Dec 11 21:52:58 2004 From: missive at hotmail.com (Lee Harr) Date: Sat Dec 11 21:53:11 2004 Subject: [Tutor] Re: Pygame problems Message-ID: >I am not sure if this is the right place, apologies if >not. http://pygame.org/ http://pygame.org/info.shtml#maillist >Now how can I get this to be on more than one line and >bigger (for my simple game I need a much more detailed explanation). http://mu.arete.cc/pcr/ http://mu.arete.cc/pcr/proj/textrect I also have a wrapped-text object in pygsear: http://www.nongnu.org/pygsear/ http://www.nongnu.org/pygsear/doc/api_html/public/pygsear.Util-module.html#render_textrect _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From rdm at rcblue.com Sun Dec 12 09:33:20 2004 From: rdm at rcblue.com (Dick Moores) Date: Sun Dec 12 09:33:22 2004 Subject: [Tutor] Complex roots In-Reply-To: <1f7befae04121020454136d1bc@mail.gmail.com> References: <20041209110126.2DD251E400D@bag.python.org> <1102593135.6535.37.camel@dhcp0320.acl.icnet.uk> <1f7befae041209074162bedff9@mail.gmail.com> <6.1.2.0.2.20041210012337.047ccb00@rcblue.com> <1f7befae04121020454136d1bc@mail.gmail.com> Message-ID: <6.1.2.0.2.20041212002158.046ebb90@rcblue.com> Tim (was: Bill) Peters wrote at 20:45 12/10/2004: >[Dick Moores] > > Aw, that's just amazing. > > I put your function in http://www.rcblue.com/Python/croots.py, > >That's fine by me -- but I'd appreciate it if you stopped claiming >there that my name is Bill . Are you sure? Well, OK. Tim it is. > > Actually, I'm trying to write a Python script that computes all 3 > > roots of a cubic equation. Do you happen to have one tucked > > away in your store of wisdom and tricks? (One for real coefficients > > will do). > >I don't, no. You can code one for cubics from Cardano's formula, e.g., > > http://mathworld.wolfram.com/CubicFormula.html > >but it's rarely worth the bother -- it's complicated and doesn't >generalize. I accept this challenge to write a complicated script of little value. >In practice, roots for polynomials beyond quadratics are >usually obtained by numerical approximation methods that don't care >much about the polynomial's degree. Are these "numerical approximation methods" pythonically possible? Dick (AKA George) Moores rdm@rcblue.com From ps_python at yahoo.com Sun Dec 12 16:27:45 2004 From: ps_python at yahoo.com (kumar s) Date: Sun Dec 12 16:27:48 2004 Subject: [Tutor] Difference between for i in range(len(object)) andfor i in object In-Reply-To: <002e01c4de4f$6cf2a340$67d98751@xp> Message-ID: <20041212152745.67072.qmail@web53708.mail.yahoo.com> Thank you for clearing up some mist here. In fact I was depressed by that e-mail because there are not many tutorials that clearly explains the issues that one faces while trying to code in python. Also, due to lack of people who are proficient in python around our univ. campus in baltimore, i am very much relying on tutors mailing list. I am poor enough to go to Mark Lutz's python training course(~ $1000 for 2 days and 3.5K for 5 days at a python bootcamp) and helpless to the fact that there is no one offering a python course on the campus. I am very much depended on this list and I cannot tell you people, how much I respect and appreciate the help from tutors. I cannot finish my Ph.D. thesis without tutors help and tutors will always be praised in my thesis acknowledgements. Thank you again for a supportive e-mail Mr.Gauld. P.S: My intention is not to hurt tutor's opinion and it is their right to express their opinion freely. kumar. --- Alan Gauld wrote: > > Personally I am getting weary of a lot of requests > that to me seem > to come > > from a lack of understanding of Python.. > > To be fair that is what the tutor list is for - > learning Python. > > > Would you be willing to take a good tutorial so > you understand > > basic Python concepts and apply them to your code. > > But as a tutor author I do agree that I am often > tempted > (and sometimes succumb) to just point at the > relevant topic > in my tutorial. Particularly since the latest > version tries > to answer all of the most common questions asked > here, but > still they come up... > > > I also despair that you don't seem to benefit from > some of our > suggestions. > > And this too can be frustrating but sometimes it is > the case > that the "student" simply didn't fully appreciate > the > significance of what was offered. I'm feeling > generous tonight! > > :-) > > Alan G > Author of the Learn to Program web tutor > http://www.freenetpages.co.uk/hp/alan.gauld > > __________________________________ Do you Yahoo!? Send holiday email and support a worthy cause. Do good. http://celebrity.mail.yahoo.com From bgailer at alum.rpi.edu Sun Dec 12 17:31:15 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sun Dec 12 17:30:07 2004 Subject: [Tutor] Difference between for i in range(len(object)) andfor i in object In-Reply-To: <20041212152745.67072.qmail@web53708.mail.yahoo.com> References: <002e01c4de4f$6cf2a340$67d98751@xp> <20041212152745.67072.qmail@web53708.mail.yahoo.com> Message-ID: <6.2.0.14.0.20041212092209.030d10a0@mail.mric.net> At 08:27 AM 12/12/2004, kumar s wrote: >Thank you for clearing up some mist here. In fact I was depressed by that >e-mail I appreciate Alan's response and yours. I forgot that this was the Tutor list, as I see so many Python e-mails it is easy to get confused. Please resume seeing this list and me as resources. I regret my comments that led to your depression. >because there are not many tutorials that clearly explains the issues that >one faces while trying to code in python. So what can we do as a community to provide tutorials that help students like you to more easily "get it". Can you give us some ideas as to what is missing? Also I 'd be interested in knowing a bit about your academic background and field of study. Would you give us a brief CV? I taught programming for the Boeing Company. I always wondered "what are these students doing here? Why don't they just read the book?" That's how I learned almost everything I know about programming. So it can be hard for me to understand your struggle. Nuf said for now... [snip] Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From rdm at rcblue.com Sun Dec 12 17:53:55 2004 From: rdm at rcblue.com (Dick Moores) Date: Sun Dec 12 17:54:00 2004 Subject: [Tutor] OT?: how to google just the 2.4 tutorial? Message-ID: <6.1.2.0.2.20041212084653.056d9ab0@rcblue.com> I know how to limit google search results to a single site, but is it possible to google just one section of a site? I'd like to be able to search just the 2.4 tutorial, http://www.python.org/doc/2.4/tut/tut.html Possible? And if so, how to? Thanks, Dick Moores rdm@rcblue.com From alan.gauld at freenet.co.uk Sun Dec 12 18:20:55 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Dec 12 18:20:52 2004 Subject: [Tutor] function that returns a fn References: Message-ID: <00c301c4e06e$f0de2050$9c8f8651@xp> > def getjlistrenderer(opname): > def listrender(): > # use opname, eg ops=getlist(opname) > # or set local fn variable > return renderer; > return listrender; > #?or f=listrender(); return f; > > Is it really as simple as this? Assuming your indentation is actually OK then yes, it is as easy as that. > books too, but thought I'd get some more pointers as well. Web searching > so far only shows lambda, which is one-liner, and that won't do. Lambda is actually a single *expression* which may cross several lines. But with nested functions available lambda is the wrong way to go for higher order programming in Python. Alan g. From alan.gauld at freenet.co.uk Sun Dec 12 18:25:54 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Dec 12 18:25:47 2004 Subject: [Tutor] Complex roots References: <20041209110126.2DD251E400D@bag.python.org><1102593135.6535.37.camel@dhcp0320.acl.icnet.uk><1f7befae041209074162bedff9@mail.gmail.com><6.1.2.0.2.20041210012337.047ccb00@rcblue.com><1f7befae04121020454136d1bc@mail.gmail.com> <6.1.2.0.2.20041212002158.046ebb90@rcblue.com> Message-ID: <00ca01c4e06f$a38e9a40$9c8f8651@xp> > Are these "numerical approximation methods" pythonically possible? > Yes and that's how they are normally found - not necessarily with Python, but by applying computer simulations of the equations. Generally you calculate values in ever decreasing increments until you get enough accuracy. eg you discover a zero crossingh between 3 and 4, then between 3.3 and 3.4 then between 3.36 and 3.37 and so on... Caveat: You also need to look out for double crossings within a single step change, so don't make the steps too big. And check the number of roots you expect versus the number you get as an error detection scheme. Alan G. From bvande at po-box.mcgill.ca Sun Dec 12 19:43:06 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sun Dec 12 19:43:07 2004 Subject: [Tutor] OT?: how to google just the 2.4 tutorial? In-Reply-To: <6.1.2.0.2.20041212084653.056d9ab0@rcblue.com> References: <6.1.2.0.2.20041212084653.056d9ab0@rcblue.com> Message-ID: <41BC913A.3050907@po-box.mcgill.ca> Dick Moores said unto the world upon 2004-12-12 11:53: > I know how to limit google search results to a single site, but is it > possible to google just one section of a site? > > I'd like to be able to search just the 2.4 tutorial, > http://www.python.org/doc/2.4/tut/tut.html > Possible? And if so, how to? > > Thanks, > > Dick Moores > rdm@rcblue.com > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > Hey Dick and all, that's odd. I tried searching with site:www.python.org/doc/ and site:www.python.org/doc but neither gave hits. :-( From the "Department of there has to be a better way, but . . . ", try entering something like this into the google search box: site:www.python.org inurl:tut string That will search www.python.org pages with 'tut' in the url that have 'string' in the page body. That doesn't restrict it to 2.4, or non-dev docs. My best attempt: site:www.python.org inurl:tut -inurl:dev inurl:current string still pulls up hits like which don't have 'current' in the url. And, adding inurl:node to the suggested search yields no results, either. I'm not sure why. :-| So, none of this gets you there, but it does get you closer. shows how to use some of the more esoteric google operators. You might also check out (and maybe improve) . Best, Brian vdB From billk at fastmail.fm Sun Dec 12 21:51:56 2004 From: billk at fastmail.fm (Bill Kranec) Date: Sun Dec 12 21:52:00 2004 Subject: [Tutor] listing all combinations of elements of a list Message-ID: <41BCAF6C.4060607@fastmail.fm> Is there a module containing a function for listing the unique k-element subsets of an n-item list? I have written some code (right now I only need it for 2 element subsets): def combination(items) list = [] for i in range(0,len(items)): for j in range(0,len(items)): if j > i: list.append((list[i],list[j])) return list My problems with this code being that a) code I write is usually pretty inefficient, b) it doesn't extend to subsets of size > 2, and c) it uses nested loops, which I have gathered from some previous discussions on this list to be less than ideal. Any thoughts on how to improve / replace this code would be appreciated. Thanks, Bill From missive at hotmail.com Sun Dec 12 23:15:09 2004 From: missive at hotmail.com (Lee Harr) Date: Sun Dec 12 23:16:04 2004 Subject: [Tutor] Re: listing all combinations of elements of a list Message-ID: >Is there a module containing a function for listing the unique k-element >subsets of an n-item list? I have written some code (right now I only >need it for 2 element subsets): Apparently not, but maybe this will help: http://www.google.com/search?q=python+recipe+list+combinations http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/190465 _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From rdm at rcblue.com Mon Dec 13 00:27:21 2004 From: rdm at rcblue.com (Dick Moores) Date: Mon Dec 13 00:43:40 2004 Subject: [Tutor] OT?: how to google just the 2.4 tutorial? In-Reply-To: <41BC913A.3050907@po-box.mcgill.ca> References: <6.1.2.0.2.20041212084653.056d9ab0@rcblue.com> <41BC913A.3050907@po-box.mcgill.ca> Message-ID: <6.1.2.0.2.20041212150112.082ab100@rcblue.com> Brian van den Broek wrote at 10:43 12/12/2004: >Dick Moores said unto the world upon 2004-12-12 11:53: >>I know how to limit google search results to a single site, but is it >>possible to google just one section of a site? >>I'd like to be able to search just the 2.4 tutorial, >>http://www.python.org/doc/2.4/tut/tut.html >>Possible? And if so, how to? >>Thanks, >>Dick Moores >>rdm@rcblue.com >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor > >Hey Dick and all, > >that's odd. I tried searching with > site:www.python.org/doc/ >and > site:www.python.org/doc >but neither gave hits. :-( > > From the "Department of there has to be a better way, but . . . ", >try entering something like this into the google search box: > site:www.python.org inurl:tut string > >That will search www.python.org pages with 'tut' in the url that have >'string' in the page body. That doesn't restrict it to 2.4, or non-dev docs. > >My best attempt: > site:www.python.org inurl:tut -inurl:dev inurl:current string >still pulls up hits like >which don't have 'current' in the url. And, adding inurl:node to the >suggested search yields no results, either. I'm not sure why. :-| > >So, none of this gets you there, but it does get you closer. > > shows how to use some of the >more esoteric google operators. > >You might also check out (and maybe improve) >. Thanks, Brian. I stumbled across http://docs.python.org as a site, so at least searching within Python docs (which include the tutorial) is possible. For example, site:http://docs.python.org "complex number" This finds 23 results, compared to the 334 returned by site:http://www.python.org "complex number" To find the results for the tutorial, search the results page for site:http://docs.python.org "complex number" and search the page on "/tut/". These will be for the tutorial. There are just 2 for "complex number" A much simpler way to find things in the tutorial (after all) seems to be to use the "Python Documentation" help file that comes with 2.4. I searched on "complex number" tutorial and got 3 hits, the 2 found with the method of the paragraph immediately above, plus one more in the index of the tutorial. Dick From andre.roberge at ns.sympatico.ca Mon Dec 13 03:14:29 2004 From: andre.roberge at ns.sympatico.ca (=?ISO-8859-1?Q?Andr=E9_Roberge?=) Date: Mon Dec 13 03:14:25 2004 Subject: [Tutor] [ANN] RUR: a Python Learning Environment (alpha) Message-ID: <41BCFB05.4080806@ns.sympatico.ca> RUR: a Python Learning Environment is a successor of Karel the Robot, PyRobot and Guido van Robot. Its purpose is to provide an environment for beginners, including children, to learn python. (Note that Guido van Robot still exists and has been upgraded recently.) Source for the program (python files; requires wxPython 2.4) can be found on SourceForge.net at https://sourceforge.net/projects/rur-ple/ The current (first) release has been tested under Windows and everything (except the "radio box") should work. For those using a platform other than Windows, I have been told that a much earlier version had problems displaying the robot world properly. If you're interested in trying and encounter problems, I suggest changing the window size, or clicking in the middle panel (the robot's world). Do not hesitate to give me some feedback. To my knowledge, no one (other than myself!) has tested it yet. The project's home page is located at: http://rur-ple.sourceforge.net/index.html It features a number of lessons, with an outline for future lessons. It should give you an idea of what this program is about, without having to try it. Note: This is my very first Python program (other than some very simple ones) and the first program I share with anyone. Comments, suggestions, criticisms are most welcome. Andr? Roberge From bagchee at cse.ohio-state.edu Mon Dec 13 03:55:58 2004 From: bagchee at cse.ohio-state.edu (Nandan) Date: Mon Dec 13 03:56:01 2004 Subject: Subject: Re: [Tutor] os.listdir fn In-Reply-To: <20041212110048.569FB1E40CE@bag.python.org> Message-ID: > Message-ID: <41BAEB1B.1090906@tds.net> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Are you sure this does what you want? You compute 'scripts' and 'filenames' and throw them away. I > think this function will return the base name of all the files *and folders* in ./icon.scripts/opname. I meant to keep the x.script version, but realised I could append '.script' to the basename anytime. > If you are trying to return the base name of every file or directory whose extension is '.script', > you can use a list comprehension to filter the list: > > def createaproposjlist(opname): > filelist=os.listdir('./icon.scripts/'+opname) > spltnames=map(os.path.splitext,filelist) > return [ name for name, ext in spltnames if ext == '.script' ] The list comp is much nicer! thanks. > If you are concerned about directories with names ending in '.script' then add another filter using > os.path.isdir: No, I'm keeping a list of icons and associated scripts in the directory, and I know there won't be any subdirs. But I'll keep isdir in mind. Cheers, Nandan From tim.peters at gmail.com Mon Dec 13 05:37:52 2004 From: tim.peters at gmail.com (Tim Peters) Date: Mon Dec 13 05:37:55 2004 Subject: [Tutor] Complex roots In-Reply-To: <6.1.2.0.2.20041212002158.046ebb90@rcblue.com> References: <20041209110126.2DD251E400D@bag.python.org> <1102593135.6535.37.camel@dhcp0320.acl.icnet.uk> <1f7befae041209074162bedff9@mail.gmail.com> <6.1.2.0.2.20041210012337.047ccb00@rcblue.com> <1f7befae04121020454136d1bc@mail.gmail.com> <6.1.2.0.2.20041212002158.046ebb90@rcblue.com> Message-ID: <1f7befae0412122037e2be81@mail.gmail.com> [Dick Moores] >>> Actually, I'm trying to write a Python script that computes all 3 >>> roots of a cubic equation. Do you happen to have one tucked >>> away in your store of wisdom and tricks? (One for real coefficients >>> will do). [Tim Peters] >> I don't, no. You can code one for cubics from Cardano's formula, e.g., >> >> http://mathworld.wolfram.com/CubicFormula.html >> >> but it's rarely worth the bother -- it's complicated and doesn't >> generalize. [Dick] > I accept this challenge to write a complicated script of little value. Cool! If it's just for fun, it's fun. >> In practice, roots for polynomials beyond quadratics are >> usually obtained by numerical approximation methods that don't care >> much about the polynomial's degree. > Are these "numerical approximation methods" pythonically possible? Of course, but coding general-purpose root finders-- even if "general" is limited to just polynomials --requires mathematical and numeric expertise. If it interests you, there are book-length treatments of the subject, and there's really no easy reliable approach. Good online sources for numeric algorithms include: http://www.netlib.org/ Just Googling on polynomial roots Python will point you to http://www.scipy.org/ From rdm at rcblue.com Mon Dec 13 05:41:12 2004 From: rdm at rcblue.com (Dick Moores) Date: Mon Dec 13 05:41:14 2004 Subject: [Tutor] Complex roots In-Reply-To: <00ca01c4e06f$a38e9a40$9c8f8651@xp> References: <20041209110126.2DD251E400D@bag.python.org> <1102593135.6535.37.camel@dhcp0320.acl.icnet.uk> <1f7befae041209074162bedff9@mail.gmail.com> <6.1.2.0.2.20041210012337.047ccb00@rcblue.com> <1f7befae04121020454136d1bc@mail.gmail.com> <6.1.2.0.2.20041212002158.046ebb90@rcblue.com> <00ca01c4e06f$a38e9a40$9c8f8651@xp> Message-ID: <6.1.2.0.2.20041212201649.03e60470@rcblue.com> Hmm, sounds like something to sink my teeth into for a while. Thanks for just enough of a hint as to how to go about it. But on second thought, how about another hint. How are imaginary roots approximated? For each root, do you try to approximate root.real and root.imag simultaneously, or what? Sounds mind-boggling. Maybe I should start by approximating real roots, if they exist; and cut my teeth on quadratic equations where b**2 - 4*a*c >= 0! Or linear equations. Thank you. Dick Moores Alan Gauld wrote at 09:25 12/12/2004: > > Are these "numerical approximation methods" pythonically possible? > > > >Yes and that's how they are normally found - not necessarily with >Python, >but by applying computer simulations of the equations. Generally you >calculate values in ever decreasing increments until you get enough >accuracy. eg you discover a zero crossingh between 3 and 4, then >between 3.3 and 3.4 then between 3.36 and 3.37 and so on... > >Caveat: >You also need to look out for double crossings within a single step >change, so don't make the steps too big. And check the number of >roots you expect versus the number you get as an error detection >scheme. > >Alan G. From rdm at rcblue.com Mon Dec 13 05:50:05 2004 From: rdm at rcblue.com (Dick Moores) Date: Mon Dec 13 05:50:08 2004 Subject: [Tutor] Complex roots In-Reply-To: <1f7befae0412122037e2be81@mail.gmail.com> References: <20041209110126.2DD251E400D@bag.python.org> <1102593135.6535.37.camel@dhcp0320.acl.icnet.uk> <1f7befae041209074162bedff9@mail.gmail.com> <6.1.2.0.2.20041210012337.047ccb00@rcblue.com> <1f7befae04121020454136d1bc@mail.gmail.com> <6.1.2.0.2.20041212002158.046ebb90@rcblue.com> <1f7befae0412122037e2be81@mail.gmail.com> Message-ID: <6.1.2.0.2.20041212204602.0543dde0@rcblue.com> Thanks for the sobering advice, and for the two sites I knew nothing about. So there's a SciPy! Dick Tim Peters wrote at 20:37 12/12/2004: > > Are these "numerical approximation methods" pythonically possible? > >Of course, but coding general-purpose root finders-- even if "general" >is limited to just polynomials --requires mathematical and numeric >expertise. If it interests you, there are book-length treatments of >the subject, and there's really no easy reliable approach. Good >online sources for numeric algorithms include: > > http://www.netlib.org/ > >Just Googling on > > polynomial roots Python > >will point you to > > http://www.scipy.org/ From michael.j.eve at gmail.com Mon Dec 13 06:03:43 2004 From: michael.j.eve at gmail.com (Mike in Seattle) Date: Mon Dec 13 06:03:46 2004 Subject: [Tutor] How to launch multiple processes from script? Message-ID: I'm working my way through the sockets module. To test my simple server and clients, I'd like a way to launch the server and multiple clients from one script or batch file,all running simultaneously. Each server/client should run as it's own process and have a console window. I've briefly played with spawn and forkpty with no success. Running WinXP right now. I am hoping that there is something as simple as this psuedo code: for i in range(1..10): run_with_console("client.py " + arg0[i] +" " +arg1[i]) My question is what is pythonese for run_with_console? Thanks, Mike From justinstraube at charter.net Mon Dec 13 10:53:51 2004 From: justinstraube at charter.net (justinstraube@charter.net) Date: Mon Dec 13 10:53:52 2004 Subject: [Tutor] using a function as a dictionary value? Message-ID: <3khdin$ejuvb8@mxip02a.cluster1.charter.net> When I run this, regardless of which option I select all three functions are called. Is there a way I can do this where only the option selcted is called? Im using 2.3.3 if that matters any. Thanks. ##### def spam(): print 'Hello world' def breakfast(): print 'Spam, Spam, Chips, and Spam' def bridgekeeper(): print 'Ask me your questions, Bridgekeeper. I am not afraid.' select = raw_input('Chose an option [1|2|3]: ') options = ['1', '2', '3'] command = {'1': spam(), '2': breakfast(), '3': bridgekeeper() } if select in options: command[select] else: print 'Selection not recognized.' ##### >>> chose an option [1|2|3]: 3 Hello world Spam, Spam, Chips, and Spam Ask me your questions, Bridgekeeper. I am not afraid. >>> regards, Justin --- From cyresse at gmail.com Mon Dec 13 11:44:08 2004 From: cyresse at gmail.com (Liam Clarke) Date: Mon Dec 13 11:44:12 2004 Subject: [Tutor] using a function as a dictionary value? In-Reply-To: <3khdin$ejuvb8@mxip02a.cluster1.charter.net> References: <3khdin$ejuvb8@mxip02a.cluster1.charter.net> Message-ID: Hey Justin, Tricky one this.. as far as I know, and I'm a beginner myself, a dictionary stores a reference to the function, not the actual function. So - > command = {'1': spam(), > '2': breakfast(), > '3': bridgekeeper() > } Try this instead - command = {'1': spam, '2':breakfast, '3': bridgekeeper} and > select = raw_input('Chose an option [1|2|3]: ') > > options = ['1', '2', '3'] > > if select in options: > command[select] change this to - select = raw_input('Chose an option [1|2|3]: ') if select in command.keys(): command[select]() That one had me going round in circles when I first met it. AFAIK, everything is stored in dictionaries apparently. If you have a function called 'dude()' you could probably call it as a dictionary of 'dude' from the namespace... Standard disclaimer - Someone more knowledgable would probably be along shortly to point out a simpler, elegant way to do it, but my way works. Mostly. HTH Liam Clarke > ##### > def spam(): > print 'Hello world' > > def breakfast(): > print 'Spam, Spam, Chips, and Spam' > > def bridgekeeper(): > print 'Ask me your questions, Bridgekeeper. I am not afraid.' > > select = raw_input('Chose an option [1|2|3]: ') > > options = ['1', '2', '3'] > > if select in options: > command[select] > > else: > print 'Selection not recognized.' > ##### > 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From cyresse at gmail.com Mon Dec 13 12:00:42 2004 From: cyresse at gmail.com (Liam Clarke) Date: Mon Dec 13 12:00:48 2004 Subject: [Tutor] Difference between for i in range(len(object)) andfor i in object In-Reply-To: <6.2.0.14.0.20041212092209.030d10a0@mail.mric.net> References: <002e01c4de4f$6cf2a340$67d98751@xp> <20041212152745.67072.qmail@web53708.mail.yahoo.com> <6.2.0.14.0.20041212092209.030d10a0@mail.mric.net> Message-ID: Good luck trying to find a decent Python book for beginners. I haven't been able to source Alan Gauld's book yet, (I'm saving for Amazon's shipping... I live in the Antipodes.), but afaik that's about the best one out, if his online tutorial (which I highly recommend Kumar, link at end.) is indicative. I have the O'Reilly Python in a Nutshell beside me, but it's a reference only, and sometimes a confusing reference. Took me ages to figure out what exactly serialization/deserialization meant in reference to pickling. For my intents, tunring it into a saved thing. Sure, maybe in binary format or something. But yeah, once I'd worked my way through 80% of Alan's tutorial, I found this list, and I'd attribute 75% of my progress since the tutorial to the amazing help I've received here, and the other 25% to messing around in the interpreter or writing code and trying to make it work. Thing is, for people like me, you generally either don't know that a question is a dumb one until someone tells you the answer, (the 'of course' moment), or until 5 minutes after you emailed your query, you find the answer you were looking for... Kumar, if I may, I have some recommendations for resources to check out. http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/index.htm In my opinion, the best way to familiarise one's self with the fundamentals of Python. http://aspn.activestate.com/ASPN/Mail/Browse/Threaded/python-Tutor A searchable archive of the Tutor group http://www.ibiblio.org/obp/thinkCSpy/index.htm A good tutorial on writing code, which happens to use Python Good luck, Liam Clarke On Sun, 12 Dec 2004 09:31:15 -0700, Bob Gailer wrote: > At 08:27 AM 12/12/2004, kumar s wrote: > >Thank you for clearing up some mist here. In fact I was depressed by that > >e-mail > > I appreciate Alan's response and yours. I forgot that this was the Tutor > list, as I see so many Python e-mails it is easy to get confused. Please > resume seeing this list and me as resources. I regret my comments that led > to your depression. > > >because there are not many tutorials that clearly explains the issues that > >one faces while trying to code in python. > > So what can we do as a community to provide tutorials that help students > like you to more easily "get it". Can you give us some ideas as to what is > missing? Also I 'd be interested in knowing a bit about your academic > background and field of study. Would you give us a brief CV? > > I taught programming for the Boeing Company. I always wondered "what are > these students doing here? Why don't they just read the book?" That's how I > learned almost everything I know about programming. So it can be hard for > me to understand your struggle. > > Nuf said for now... > [snip] > > Bob Gailer > bgailer@alum.rpi.edu > 303 442 2625 home > 720 938 2625 cell > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From kent37 at tds.net Mon Dec 13 13:57:45 2004 From: kent37 at tds.net (Kent Johnson) Date: Mon Dec 13 13:57:50 2004 Subject: [Tutor] using a function as a dictionary value? In-Reply-To: References: <3khdin$ejuvb8@mxip02a.cluster1.charter.net> Message-ID: <41BD91C9.7090303@tds.net> Liam Clarke wrote: > Hey Justin, > > Tricky one this.. > > as far as I know, and I'm a beginner myself, a dictionary stores a > reference to the function, not the actual function. Yes. In fact this is a good way to think about all variables in Python. A variable stores a reference to a value, not the value itself. I think of variables as somehow pointing at the value. Some people like to think of the variable as a sticky note stuck on the value with its name. Pythonistas say that the name is 'bound' to the value; the assignment 'x = 2' binds the name 'x' to the value '2'. The *wrong* way to think about variables in Python is to think of them as containers that hold a value. This is appropriate for some languages but it is not a helpful model for Python. > So - > > >>command = {'1': spam(), >> '2': breakfast(), >> '3': bridgekeeper() >> } > > > Try this instead - > > command = {'1': spam, '2':breakfast, '3': bridgekeeper} Yes. The difference is, you are storing a reference to the actual function object, rather than the result of calling the function. >>> def foo(): ... return 3 ... The function name is actually a variable which is bound to a function object. When you use the bare variable name, you are referring to this object: >>> foo On the other hand when you use the function name with parentheses, you call the function. The value of this expression is the return value of the function. >>> foo() 3 Here is a dictionary with both usages: >>> d = { 'foo':foo, 'value':foo() } >>> d {'foo': , 'value': 3} If you put foo in the dict, you have access to the function. If you put foo() in the dict, you have access to the result of calling the function. If I store a reference to the function, I can retrieve it and call it like this: >>> d['foo']() 3 Kent >>if select in options: >> command[select] > > > change this to - > > select = raw_input('Chose an option [1|2|3]: ') > > if select in command.keys(): > command[select]() > > > > That one had me going round in circles when I first met it. > AFAIK, everything is stored in dictionaries apparently. If you have a > function called 'dude()' you could probably call it as a dictionary of > 'dude' from the namespace... Yes, under the hood, binding a name to a value turns into adding a mapping to a special dictionary. For variables with global scope, you can access this dictionary with the globals function. Both the dict d and the function foo are in my globals: >>> globals() {'__builtins__': , '__name__': '__main__', 'foo': , '__doc__': None, 'd': {'foo': , 'value': 3}} >>> globals()['d'] {'foo': , 'value': 3} > > Standard disclaimer - > > Someone more knowledgable would probably be along shortly to point out > a simpler, elegant way to do it, but my way works. Mostly. Actually you got the code right :-) I just thought the explanation needed a little fleshing out. Kent From pathall at gmail.com Mon Dec 13 14:15:30 2004 From: pathall at gmail.com (Patrick Hall) Date: Mon Dec 13 14:15:33 2004 Subject: [Tutor] Non-escaped utf-8 rendering in the interactive shell under XP? Message-ID: <6465924d04121305156c4cb684@mail.gmail.com> Hi folks, Being a Linux guy, I don't know my way around Windows software too well. I've been trying to help some friends learn a bit of Python, and they use OSX and XP. OSX is close enough to Linux that I've not run into many barriers, but I'm having a specific problem with the XP users: Is there an IDE out there that supports Unicode (utf-8) text? I've set sitecustomize.py to 'utf-8', such that sys.getdefaultencoding() will return 'utf-8', and everything seems to be working ok interms of reading, writing, and processing data in utf-8. The problem is that the text itself is escaped in the interactive shell, rather than being rendered. It's not a font thing, since if they write out the data to a file and open it in a browser, the text is readable. The Gnome terminal under Linux seems to do this fine once I've made that change in sitecustomize.py, and OSX seems to behave similarly. I've suggested my friends try SciTE, Idle, and Activestate's PythonWin, and as far as I can tell none of these IDEs solve the problem. The people I'm trying aren't going to be interested in wading into something like any flavor of Emacs or vim. After all, they want to learn Python because it's friendly, and those editors are great, but they're not friendly. Am I missing any options or misunderstanding any of these IDEs? Thanks kindly, Patrick From RPhillips at engineer.co.summit.oh.us Mon Dec 13 14:43:45 2004 From: RPhillips at engineer.co.summit.oh.us (Ron Phillips) Date: Mon Dec 13 14:44:16 2004 Subject: [Tutor] Re: [ANN] RUR: a Python Learning Environment (alpha) Message-ID: This looks like a very nice effort -- I am trying to get it running, since I am working with some other newbies to learn more Python. I wish there were a link from http://rur-ple.sourceforge.net/index.html to the download page! And I am not sure which of the downloaded files to run. I thought maybe WorldDisplay.py, or RURmain.py? Anyway, I really like the concept, and the screenshots look intriguing. You have a nice writing style in English, by the way -- I think kids will pick right up on the "fix the robot" metaphor. Which program do I start? Ron -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041213/18f873db/attachment.htm From alan.gauld at freenet.co.uk Mon Dec 13 14:55:15 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Dec 13 14:54:43 2004 Subject: [Tutor] OT?: how to google just the 2.4 tutorial? References: <6.1.2.0.2.20041212084653.056d9ab0@rcblue.com> Message-ID: <00df01c4e11b$604a38a0$9c8f8651@xp> > I know how to limit google search results to a single site, but is it > possible to google just one section of a site? Can't speak for Google but... > I'd like to be able to search just the 2.4 tutorial, > http://www.python.org/doc/2.4/tut/tut.html > Possible? And if so, how to? Have you tried using the Python site search tool, it covers the whole of python.org but thats much narrower than a general web search on Google... By typing: tutorial lists I got the first 5 hits from the tutor... OTOH By just typing: python tutorial lists into Google the first two hits were both from the official tutorial so plain google works pretty well too. Alan G. From alan.gauld at freenet.co.uk Mon Dec 13 15:07:35 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Dec 13 15:07:06 2004 Subject: [Tutor] listing all combinations of elements of a list References: <41BCAF6C.4060607@fastmail.fm> Message-ID: <00ea01c4e11d$191f4f40$9c8f8651@xp> > def combination(items) > list = [] > for i in range(0,len(items)): > for j in range(0,len(items)): for i in items: for j in items: Is both shorter and faster - no len() function calls. Or if you want to use indices: size = len(items) # only calculate once, it won't change! lst = [] # don't use builtin function names for variables for i in range(0,size) for j in range(i+1,size) lst.append(....) return lst That saves a lot of len() calls and a comparison. Also it avoids iterating over the whole list each time. > My problems with this code being that a) code I write is usually pretty > inefficient, b) it doesn't extend to subsets of size > 2, and c) it uses > nested loops, which I have gathered from some previous discussions on > this list to be less than ideal. I've tidied up a little but I think nested loops are a necessary evil in this case - although somebody is sure to prove me wrong! :-) HTH, Alan G. From andre.roberge at ns.sympatico.ca Mon Dec 13 15:15:16 2004 From: andre.roberge at ns.sympatico.ca (=?ISO-8859-1?Q?Andr=E9_Roberge?=) Date: Mon Dec 13 15:15:17 2004 Subject: [Tutor] Re: [ANN] RUR: a Python Learning Environment (alpha) Message-ID: <41BDA3F4.9040905@ns.sympatico.ca> >This looks like a very nice effort -- I am trying to get it running, >since I am working with some other newbies to learn more Python. >I wish there were a link from http://rur-ple.sourceforge.net/index.html >to the download page! I will fix that; thanks. >And I am not sure which of the downloaded files to >run. I thought maybe WorldDisplay.py, or RURmain.py? Oops! RURmain.py >Anyway, I really like the concept, and the screenshots look intriguing. >You have a nice writing style in English, by the way -- I think kids >will pick right up on the "fix the robot" metaphor. Thanks! Andre From loptr.chaote at gmail.com Mon Dec 13 18:11:57 2004 From: loptr.chaote at gmail.com (Loptr Chaote) Date: Mon Dec 13 18:12:01 2004 Subject: [Tutor] Problems with unsigned integers Message-ID: <76912af804121309113db6b205@mail.gmail.com> Hello everyone! I'm having problems with signed/unsigned (32bit) integers in python. Example code: seq = 0L seq = socket.ntohl(struct.unpack("L", data[38:42])[0]) print seq This sometimes produces a negative output, how is that possible since I booth initialized seq with "0L" and also specified "L" in unpack()? -L.C From loptr.chaote at gmail.com Mon Dec 13 18:52:14 2004 From: loptr.chaote at gmail.com (Loptr Chaote) Date: Mon Dec 13 18:52:17 2004 Subject: [Tutor] Problems with unsigned integers In-Reply-To: References: <76912af804121309113db6b205@mail.gmail.com> Message-ID: <76912af8041213095266b2af02@mail.gmail.com> On Mon, 13 Dec 2004 12:43:17 -0500, QoD SEC wrote: > I do not believe that python has anything like signed and unsigned > integers. The 'L' after an integer makes the number a type long (which > is not the same as C's long). Also in your code you do this seq = > socket.ntohl(struct.unpack("L", data[38:42])[0]) which overwrites > whatever you assigned it before and returns an integer, in your case a > -1 which might be that the functions is returning an error. > Thanks for the reply. I forgot to say that I have also tried without the socket.ntohl(), making sure that it's not what messes things up. Python clearly has _some_ kind of sense for signed vs unsigned if you check the list* of available fmt-characters. And the values I get are mixed high ["correct"] values and negative values, so error return codes does not seem to be an option. * http://docs.python.org/lib/module-struct.html -L.C From RPhillips at engineer.co.summit.oh.us Mon Dec 13 19:14:39 2004 From: RPhillips at engineer.co.summit.oh.us (Ron Phillips) Date: Mon Dec 13 19:15:06 2004 Subject: [Tutor] Re: [ANN] RUR: a Python Learning Environment (alpha) Message-ID: Can't get it running -- it keeps saying: Traceback (most recent call last): File "C:/source/RUR/RURmain.py", line 28, in ? messenger.loadImages() # load them up here after initialising Handlers File "C:\source\RUR\messenger.py", line 27, in loadImages HIT_WALL_IMAGE = wxImage('ouch2.png').ConvertToBitmap() File "C:\Python23\Lib\site-packages\wx\_core.py", line 2282, in ConvertToBitmap return _core_.Image_ConvertToBitmap(*args, **kwargs) wx._core.PyNoAppError: The wx.App object must be created first! Ron -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041213/f15de802/attachment.html From justinstraube at charter.net Mon Dec 13 19:16:33 2004 From: justinstraube at charter.net (justinstraube@charter.net) Date: Mon Dec 13 19:16:36 2004 Subject: [Tutor] using a function as a dictionary value? Message-ID: <3khe4g$dmasvs@mxip01a.cluster1.charter.net> Thanks Liam and Kent! Regards, Justin On Mon, 13 Dec 2004 07:57:45 -0500, you wrote: > >Liam Clarke wrote: >> Hey Justin, >> >> Tricky one this.. >> >> as far as I know, and I'm a beginner myself, a dictionary stores a >> reference to the function, not the actual function. > >Yes. In fact this is a good way to think about all variables in Python. A variable stores a >reference to a value, not the value itself. I think of variables as somehow pointing at the value. >Some people like to think of the variable as a sticky note stuck on the value with its name. >Pythonistas say that the name is 'bound' to the value; the assignment 'x = 2' binds the name 'x' to >the value '2'. > >The *wrong* way to think about variables in Python is to think of them as containers that hold a >value. This is appropriate for some languages but it is not a helpful model for Python. > >> So - >> >> >>>command = {'1': spam(), >>> '2': breakfast(), >>> '3': bridgekeeper() >>> } >> >> >> Try this instead - >> >> command = {'1': spam, '2':breakfast, '3': bridgekeeper} > >Yes. The difference is, you are storing a reference to the actual function object, rather than the >result of calling the function. > > >>> def foo(): >... return 3 >... > >The function name is actually a variable which is bound to a function object. When you use the bare >variable name, you are referring to this object: > >>> foo > > >On the other hand when you use the function name with parentheses, you call the function. The value >of this expression is the return value of the function. > > >>> foo() >3 > >Here is a dictionary with both usages: > >>> d = { 'foo':foo, 'value':foo() } > >>> d >{'foo': , 'value': 3} > >If you put foo in the dict, you have access to the function. If you put foo() in the dict, you have >access to the result of calling the function. If I store a reference to the function, I can retrieve >it and call it like this: > >>> d['foo']() >3 > >Kent > >>>if select in options: >>> command[select] >> >> >> change this to - >> >> select = raw_input('Chose an option [1|2|3]: ') >> >> if select in command.keys(): >> command[select]() >> >> >> >> That one had me going round in circles when I first met it. >> AFAIK, everything is stored in dictionaries apparently. If you have a >> function called 'dude()' you could probably call it as a dictionary of >> 'dude' from the namespace... > >Yes, under the hood, binding a name to a value turns into adding a mapping to a special dictionary. >For variables with global scope, you can access this dictionary with the globals function. Both the >dict d and the function foo are in my globals: > > >>> globals() >{'__builtins__': , '__name__': '__main__', 'foo': 0x008D6670>, '__doc__': None, 'd': {'foo': on foo at 0x008D6670>, 'value': 3}} > >>> globals()['d'] >{'foo': , 'value': 3} > >> >> Standard disclaimer - >> >> Someone more knowledgable would probably be along shortly to point out >> a simpler, elegant way to do it, but my way works. Mostly. > >Actually you got the code right :-) I just thought the explanation needed a little fleshing out. > >Kent >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor regards, Justin --- You may have noticed, Im not all there myself. -Cheshire Cat From kent37 at tds.net Mon Dec 13 19:27:25 2004 From: kent37 at tds.net (Kent Johnson) Date: Mon Dec 13 19:27:27 2004 Subject: [Tutor] Problems with unsigned integers In-Reply-To: <76912af804121309113db6b205@mail.gmail.com> References: <76912af804121309113db6b205@mail.gmail.com> Message-ID: <41BDDF0D.1030106@tds.net> It seems that ntohl doesn't understand about unsigned values, at least on Win32: Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from struct import pack, unpack >>> pack('L', -1) '\xff\xff\xff\xff' >>> unpack('L', '\xff\xff\xff\xff') (4294967295L,) >>> from socket import ntohl >>> ntohl(4294967295L) -1 Kent Loptr Chaote wrote: > Hello everyone! > > I'm having problems with signed/unsigned (32bit) integers in python. > Example code: > > seq = 0L > seq = socket.ntohl(struct.unpack("L", data[38:42])[0]) > print seq > > This sometimes produces a negative output, how is that possible since > I booth initialized seq with "0L" and also specified "L" in unpack()? > > -L.C > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From loptr.chaote at gmail.com Mon Dec 13 19:38:28 2004 From: loptr.chaote at gmail.com (Loptr Chaote) Date: Mon Dec 13 19:38:31 2004 Subject: [Tutor] Problems with unsigned integers In-Reply-To: <41BDDF0D.1030106@tds.net> References: <76912af804121309113db6b205@mail.gmail.com> <41BDDF0D.1030106@tds.net> Message-ID: <76912af80412131038535c3fa5@mail.gmail.com> On Mon, 13 Dec 2004 13:27:25 -0500, Kent Johnson wrote: > It seems that ntohl doesn't understand about unsigned values, at least on Win32: > Wow, I've never actually considered using the interpreter/CLI like that. Thank you! I'm writing my own u_ntohl() now which checks to see if the socket-module ntohl()-function does something with the value, and if so reorders 0xAABBCCDD to 0xDDCCBBAA and if not it returns same value as the one sent as argument. This should be enough, right? -L.C PS. Obviously I was wrong regarding ntohl() not being the source of the error, and I'm not sure any longer how I came to the conclusion that it wasn't. From andre.roberge at ns.sympatico.ca Mon Dec 13 19:42:44 2004 From: andre.roberge at ns.sympatico.ca (=?ISO-8859-1?Q?Andr=E9_Roberge?=) Date: Mon Dec 13 19:42:46 2004 Subject: [Tutor] Re: [ANN] RUR: a Python Learning Environment (alpha) Message-ID: <41BDE2A4.4070308@ns.sympatico.ca> This is weird (to me, anyways) as it works well on my computer. However, I remember that I had to create "loadImages()" to initialize the handlers early on, otherwise it was complaining that it couldn't "ConvertToBitmap". I'll have to see if I can move this statement elsewhere; I will reply privately when I do it (so as not to clutter the list) and will report to the list when the problem is solved. Just to clarify: are you using wxpython 2.4.x under Windows? Andre ====================================== Can't get it running -- it keeps saying: Traceback (most recent call last): File "C:/source/RUR/RURmain.py", line 28, in ? messenger.loadImages() # load them up here after initialising Handlers File "C:\source\RUR\messenger.py", line 27, in loadImages HIT_WALL_IMAGE = wxImage('ouch2.png').ConvertToBitmap() File "C:\Python23\Lib\site-packages\wx\_core.py", line 2282, in ConvertToBitmap return _core_.Image_ConvertToBitmap(*args, **kwargs) wx._core.PyNoAppError: The wx.App object must be created first! Ron -------------- next part ------- From andre1 at yandex.ru Mon Dec 13 20:23:01 2004 From: andre1 at yandex.ru (Andrey Ivanov) Date: Mon Dec 13 20:38:44 2004 Subject: [Tutor] Re: How to launch multiple processes from script? Message-ID: <431220317.20041213222301@yandex.ru> > I'm working my way through the sockets module. To test my simple > server and clients, I'd like a way to launch the server and multiple > clients from one script or batch file,all running simultaneously. Each > server/client should run as it's own process and have a console > window. I've briefly played with spawn and forkpty with no success. > Running WinXP right now. > > I am hoping that there is something as simple as this psuedo code: > > for i in range(1..10): > run_with_console("client.py " + arg0[i] +" " +arg1[i]) > > My question is what is pythonese for run_with_console? > > Thanks, > Mike There is a Windows command called 'start' which will start an application and then exit. So you can do the required thing this way: for i in range(10): os.system("start python client.py " + arg0[i] + " " + arg1[i]) On my system it works just the way you want. From mymailinglists at neuf.fr Tue Dec 14 13:21:34 2004 From: mymailinglists at neuf.fr (Nik) Date: Tue Dec 14 13:21:37 2004 Subject: [Tutor] cgi with system calls Message-ID: <41BEDACE.805@neuf.fr> hi, I'm trying to write a python cgi script that can control certain processes on my server, but I'm having some trouble. The script is; #!/usr/bin/python import cgitb; cgitb.enable() print "Content-type: text/plain\n\n" import os cmd = "/bin/ps" status = os.system(cmd) print status which seems straight forward, but I get a server error, and malformed header from script. Bad header= PID TTY TIME CMD: appears in the apache logs. The PID TTY etc indicates it's getting the ps response, but why won't it display (even with text/plain)? Ultimately I'll have the content type as html, and I'm going to preprocess the output of ps so it probably won't cause any problems, but I just don't understand why this isn't working in its simple form? btw, the final idea is to list the processes corresponding to a certain name, and allow users to stop them or create new ones. I'm assuming this should be do-able? nik From kent37 at tds.net Tue Dec 14 13:34:29 2004 From: kent37 at tds.net (Kent Johnson) Date: Tue Dec 14 13:34:32 2004 Subject: [Tutor] cgi with system calls In-Reply-To: <41BEDACE.805@neuf.fr> References: <41BEDACE.805@neuf.fr> Message-ID: <41BEDDD5.5060903@tds.net> Nik wrote: > hi, > > I'm trying to write a python cgi script that can control certain > processes on my server, but I'm having some trouble. > The script is; > > #!/usr/bin/python > > import cgitb; cgitb.enable() > > print "Content-type: text/plain\n\n" You may need explicit \r\n here, I'm not sure: print "Content-type: text/plain\r\n\r\n" Kent > import os > cmd = "/bin/ps" > status = os.system(cmd) > print status > > which seems straight forward, but I get a server error, and > malformed header from script. Bad header= PID TTY TIME CMD: > appears in the apache logs. The PID TTY etc indicates it's getting the > ps response, but why won't it display (even with text/plain)? > > Ultimately I'll have the content type as html, and I'm going to > preprocess the output of ps so it probably won't cause any problems, but > I just don't understand why this isn't working in its simple form? > > btw, the final idea is to list the processes corresponding to a certain > name, and allow users to stop them or create new ones. I'm assuming this > should be do-able? > > nik > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From johan at accesstel.co.za Tue Dec 14 14:18:52 2004 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Tue Dec 14 14:21:31 2004 Subject: [Tutor] Opening and reading .cvs files in Python Message-ID: <1103030331.4567.10.camel@KMA.accesstel> Hi, I want to find out how to open a .cvs file on a remote Windows machine and get file to my local linux folder. Any help would be appreciated. -- Johan -- This E-Mail has been scanned. Enjoy Your Day. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041214/58bfe4e7/attachment.htm From mymailinglists at neuf.fr Tue Dec 14 14:26:44 2004 From: mymailinglists at neuf.fr (Nik) Date: Tue Dec 14 14:26:47 2004 Subject: [Tutor] cgi with system calls In-Reply-To: <41BEDDD5.5060903@tds.net> References: <41BEDACE.805@neuf.fr> <41BEDDD5.5060903@tds.net> Message-ID: <41BEEA14.9090302@neuf.fr> no luck I'm afraid. Also, to make it even more annoying, omitting the os call and going for #!/usr/bin/python import cgitb; cgitb.enable() print "Content-type: text/plain\n\n" import os status = """PID TTY TIME CMD 3649 pts0 00:00:00 su 3652 pts0 00:00:00 bash 5197 pts0 00:00:00 ps """ print status works fine. I've already half a dozen other scripts happily querying a database but this is the first one to have an error outside the usual brain fart stuff. nik Kent Johnson wrote: > Nik wrote: > >> hi, >> >> I'm trying to write a python cgi script that can control certain >> processes on my server, but I'm having some trouble. >> The script is; >> >> #!/usr/bin/python >> >> import cgitb; cgitb.enable() >> >> print "Content-type: text/plain\n\n" > > > You may need explicit \r\n here, I'm not sure: > > print "Content-type: text/plain\r\n\r\n" > > Kent > >> import os >> cmd = "/bin/ps" >> status = os.system(cmd) >> print status >> >> which seems straight forward, but I get a server error, and >> malformed header from script. Bad header= PID TTY TIME CMD: >> appears in the apache logs. The PID TTY etc indicates it's getting >> the ps response, but why won't it display (even with text/plain)? >> >> Ultimately I'll have the content type as html, and I'm going to >> preprocess the output of ps so it probably won't cause any problems, >> but I just don't understand why this isn't working in its simple form? >> >> btw, the final idea is to list the processes corresponding to a >> certain name, and allow users to stop them or create new ones. I'm >> assuming this should be do-able? >> >> nik >> _______________________________________________ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor >> > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From John.Gooch at echostar.com Tue Dec 14 18:15:32 2004 From: John.Gooch at echostar.com (Gooch, John) Date: Tue Dec 14 18:15:37 2004 Subject: [Tutor] Regexp Not Matching on Numbers? Message-ID: <15A1FDA26DAD524DA7A7AF77313EBA8F07BC01AC@riv-excha5.echostar.com> This is weird. I have a script that checks walks through directories, checks to see if their name matches a certain format ( regular expression ), and then prints out what it finds. However, it refuses to ever match on numbers unless the regexp is ".*". So far I have tried the following regular expressions: "\d+" "\d*" "\W+" "\W*" "[1-9]+" and more... Here is an example of the output: No Match on partners80_access_log.1102723200 Checking on type= Name = some_access_log.1102896000 Here is the code: import os,sys import re #define the file mask to identify web log files regexp = re.compile( r"\." ) startdir = "C:/Documents and Settings/John.Gooch/My Documents/chaser/" #define global functions def delFile(arg, dirname, names): found = 0 for name in names: print "Checking on type="+str(type( name ) )+" Name = "+str(name) matches = re.compile(r"([\w]+)").match( name ) if matches: print "Match on "+str(matches.groups()) found = 1 else: print "No Match on "+name if not found: print "No matches found in "+dirname else: print "Match found in "+dirname os.path.walk( startdir, delFile, "" ) Any thoughts? From kent37 at tds.net Tue Dec 14 18:41:03 2004 From: kent37 at tds.net (Kent Johnson) Date: Tue Dec 14 18:41:09 2004 Subject: [Tutor] Regexp Not Matching on Numbers? In-Reply-To: <15A1FDA26DAD524DA7A7AF77313EBA8F07BC01AC@riv-excha5.echostar.com> References: <15A1FDA26DAD524DA7A7AF77313EBA8F07BC01AC@riv-excha5.echostar.com> Message-ID: <41BF25AF.2050005@tds.net> I'm not too sure what you are trying to do here, but the re in your code matches the names in your example data: >>> import re >>> name = 'partners80_access_log.1102723200' >>> re.compile(r"([\w]+)").match( name ).groups() ('partners80_access_log',) One thing that may be tripping you up is that re.match() only matches at the *start* of a string, as if the regex starts with '^'. For matching anywhere in the string use re.search() instead. Another possible problem is that you are defining regexp but not using it - have you been trying to change the value of regexp and wondering why the program doesn't change? If you are looking for file names that end in log.ddd then try re.search(r'log\.\d+$', name) If this doesn't help please be more specific about the format of the names you want to match and exclude. Kent Gooch, John wrote: > This is weird. I have a script that checks walks through directories, checks > to see if their name matches a certain format ( regular expression ), and > then prints out what it finds. However, it refuses to ever match on numbers > unless the regexp is ".*". So far I have tried the following regular > expressions: > "\d+" > "\d*" > "\W+" > "\W*" > "[1-9]+" > and more... > > > Here is an example of the output: > No Match on partners80_access_log.1102723200 > Checking on type= Name = some_access_log.1102896000 > > > Here is the code: > import os,sys > import re > #define the file mask to identify web log files > regexp = re.compile( r"\." ) > > startdir = "C:/Documents and Settings/John.Gooch/My Documents/chaser/" > #define global functions > def delFile(arg, dirname, names): > found = 0 > for name in names: > print "Checking on type="+str(type( name ) )+" Name = "+str(name) > matches = re.compile(r"([\w]+)").match( name ) > if matches: > print "Match on "+str(matches.groups()) > found = 1 > else: > print "No Match on "+name > if not found: > print "No matches found in "+dirname > else: > print "Match found in "+dirname > os.path.walk( startdir, delFile, "" ) > > > > > Any thoughts? > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From maxnoel_fr at yahoo.fr Tue Dec 14 18:42:17 2004 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Tue Dec 14 18:42:24 2004 Subject: [Tutor] Regexp Not Matching on Numbers? In-Reply-To: <15A1FDA26DAD524DA7A7AF77313EBA8F07BC01AC@riv-excha5.echostar.com> References: <15A1FDA26DAD524DA7A7AF77313EBA8F07BC01AC@riv-excha5.echostar.com> Message-ID: <7FB6B72A-4DF7-11D9-A24B-000393CBC88E@yahoo.fr> On Dec 14, 2004, at 18:15, Gooch, John wrote: > This is weird. I have a script that checks walks through directories, > checks > to see if their name matches a certain format ( regular expression ), > and > then prints out what it finds. However, it refuses to ever match on > numbers > unless the regexp is ".*". So far I have tried the following regular > expressions: > "\d+" > "\d*" > "\W+" > "\W*" > "[1-9]+" > and more... I think you have to escape the backslashes. -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From kent37 at tds.net Tue Dec 14 19:16:32 2004 From: kent37 at tds.net (Kent Johnson) Date: Tue Dec 14 19:16:35 2004 Subject: [Tutor] Regexp Not Matching on Numbers? In-Reply-To: <7FB6B72A-4DF7-11D9-A24B-000393CBC88E@yahoo.fr> References: <15A1FDA26DAD524DA7A7AF77313EBA8F07BC01AC@riv-excha5.echostar.com> <7FB6B72A-4DF7-11D9-A24B-000393CBC88E@yahoo.fr> Message-ID: <41BF2E00.9060305@tds.net> Max Noel wrote: > On Dec 14, 2004, at 18:15, Gooch, John wrote: >> So far I have tried the following regular >> expressions: >> "\d+" >> "\d*" >> "\W+" >> "\W*" >> "[1-9]+" >> and more... > > > I think you have to escape the backslashes. or use raw strings like r"\d+" which is what is in the sample code... Kent From mymailinglists at neuf.fr Tue Dec 14 15:09:26 2004 From: mymailinglists at neuf.fr (Nik) Date: Tue Dec 14 19:19:26 2004 Subject: [Tutor] cgi with system calls In-Reply-To: <41BEEA14.9090302@neuf.fr> References: <41BEDACE.805@neuf.fr> <41BEDDD5.5060903@tds.net> <41BEEA14.9090302@neuf.fr> Message-ID: <41BEF416.6030303@neuf.fr> ok, problem solved (well, partly - at least as much as I need it to be). status = os.system('ps') doesn't set status equal to the output text, it sets it to the return of the call (in this case '0'). What I really want to do is status = os.popen('ps').read() print status which works fine. However, why the first version confused the web server I don't know, I guess the output from ps went somewhere it wasn't supposed to. nik Nik wrote: > no luck I'm afraid. > > Also, to make it even more annoying, omitting the os call and going for > > #!/usr/bin/python > > import cgitb; cgitb.enable() > > print "Content-type: text/plain\n\n" > import os > > status = """PID TTY TIME CMD > 3649 pts0 00:00:00 su > 3652 pts0 00:00:00 bash > 5197 pts0 00:00:00 ps > """ > print status > > > works fine. > > I've already half a dozen other scripts happily querying a database but > this is the first one to have an error outside the usual brain fart stuff. > > nik > > Kent Johnson wrote: > >> Nik wrote: >> >>> hi, >>> >>> I'm trying to write a python cgi script that can control certain >>> processes on my server, but I'm having some trouble. >>> The script is; >>> >>> #!/usr/bin/python >>> >>> import cgitb; cgitb.enable() >>> >>> print "Content-type: text/plain\n\n" >> >> >> >> You may need explicit \r\n here, I'm not sure: >> >> print "Content-type: text/plain\r\n\r\n" >> >> Kent >> >>> import os >>> cmd = "/bin/ps" >>> status = os.system(cmd) >>> print status >>> >>> which seems straight forward, but I get a server error, and >>> malformed header from script. Bad header= PID TTY TIME CMD: >>> appears in the apache logs. The PID TTY etc indicates it's getting >>> the ps response, but why won't it display (even with text/plain)? >>> >>> Ultimately I'll have the content type as html, and I'm going to >>> preprocess the output of ps so it probably won't cause any problems, >>> but I just don't understand why this isn't working in its simple form? >>> >>> btw, the final idea is to list the processes corresponding to a >>> certain name, and allow users to stop them or create new ones. I'm >>> assuming this should be do-able? >>> >>> nik >>> _______________________________________________ >>> 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 > From dyoo at hkn.eecs.berkeley.edu Tue Dec 14 19:57:02 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Dec 14 19:57:08 2004 Subject: [Tutor] cgi with system calls In-Reply-To: <41BEF416.6030303@neuf.fr> Message-ID: On Tue, 14 Dec 2004, Nik wrote: > ok, problem solved (well, partly - at least as much as I need it to be). > > status = os.system('ps') doesn't set status equal to the output text, it > sets it to the return of the call (in this case '0'). What I really want > to do is > > status = os.popen('ps').read() > print status > > which works fine. However, why the first version confused the web server > I don't know, I guess the output from ps went somewhere it wasn't > supposed to. Hi Nik, Yes, the output from 'ps' went to standard output. In fact, it turns out that Python does some internal buffering on its output. The external commands, though, flush their own output when they're done. That's at the heart of the problem you were seeing. With the program: ### print "Content-type: text/plain\n\n" status = os.system(cmd) ### The output from the os.system() came out first, and then the content-type header. So your web server got to see something like: ### PID TTY TIME CMD 3649 pts0 00:00:00 su 3652 pts0 00:00:00 bash 5197 pts0 00:00:00 ps Content-type: text/plain ### Hope this helps! From John.Gooch at echostar.com Tue Dec 14 21:47:17 2004 From: John.Gooch at echostar.com (Gooch, John) Date: Tue Dec 14 21:47:31 2004 Subject: [Tutor] Regexp Not Matching on Numbers? Message-ID: <15A1FDA26DAD524DA7A7AF77313EBA8F07BC01AF@riv-excha5.echostar.com> I am used to ( in Perl ) the entire string being searched for a match when using RegExp's. I assumed this was the way Python would do it do, as Java/Javascript/VbScript all behaved in this manner. However, I found that I had to add ".*" in front of my regular expression object before it would search the entire string for a match. This seems a bit unusual from my past experience, but it solved the issue I was experiencing. Thank you for your help. John Gooch -----Original Message----- From: Kent Johnson [mailto:kent37@tds.net] Sent: Tuesday, December 14, 2004 10:41 AM To: Gooch, John Cc: 'tutor@python.org' Subject: Re: [Tutor] Regexp Not Matching on Numbers? I'm not too sure what you are trying to do here, but the re in your code matches the names in your example data: >>> import re >>> name = 'partners80_access_log.1102723200' >>> re.compile(r"([\w]+)").match( name ).groups() ('partners80_access_log',) One thing that may be tripping you up is that re.match() only matches at the *start* of a string, as if the regex starts with '^'. For matching anywhere in the string use re.search() instead. Another possible problem is that you are defining regexp but not using it - have you been trying to change the value of regexp and wondering why the program doesn't change? If you are looking for file names that end in log.ddd then try re.search(r'log\.\d+$', name) If this doesn't help please be more specific about the format of the names you want to match and exclude. Kent Gooch, John wrote: > This is weird. I have a script that checks walks through directories, > checks to see if their name matches a certain format ( regular > expression ), and then prints out what it finds. However, it refuses > to ever match on numbers unless the regexp is ".*". So far I have > tried the following regular > expressions: > "\d+" > "\d*" > "\W+" > "\W*" > "[1-9]+" > and more... > > > Here is an example of the output: > No Match on partners80_access_log.1102723200 > Checking on type= Name = some_access_log.1102896000 > > > Here is the code: > import os,sys > import re > #define the file mask to identify web log files > regexp = re.compile( r"\." ) > > startdir = "C:/Documents and Settings/John.Gooch/My Documents/chaser/" > #define global functions def delFile(arg, dirname, names): > found = 0 > for name in names: > print "Checking on type="+str(type( name ) )+" Name = "+str(name) > matches = re.compile(r"([\w]+)").match( name ) > if matches: > print "Match on "+str(matches.groups()) > found = 1 > else: > print "No Match on "+name > if not found: > print "No matches found in "+dirname > else: > print "Match found in "+dirname > os.path.walk( startdir, delFile, "" ) > > > > > Any thoughts? > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From dyoo at hkn.eecs.berkeley.edu Tue Dec 14 22:24:43 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Dec 14 22:24:49 2004 Subject: [Tutor] Regexp Not Matching on Numbers? In-Reply-To: <15A1FDA26DAD524DA7A7AF77313EBA8F07BC01AF@riv-excha5.echostar.com> Message-ID: On Tue, 14 Dec 2004, Gooch, John wrote: > I am used to ( in Perl ) the entire string being searched for a match > when using RegExp's. I assumed this was the way Python would do it do, > as Java/Javascript/VbScript all behaved in this manner. However, I found > that I had to add ".*" in front of my regular expression object before > it would search the entire string for a match. This seems a bit unusual > from my past experience, but it solved the issue I was experiencing. Hi John, The question actually comes up a lot. *grin* If you're interested, here are two more references that talk about "match() vs search()": Python Standard Library docs on 're' module: http://www.python.org/doc/lib/matching-searching.html Regular Expression HOWTO: http://www.amk.ca/python/howto/regex/regex.html#SECTION000720000000000000000 Good luck to you! From cyresse at gmail.com Tue Dec 14 22:47:04 2004 From: cyresse at gmail.com (Liam Clarke) Date: Tue Dec 14 22:47:07 2004 Subject: [Tutor] Opening and reading .cvs files in Python In-Reply-To: <1103030331.4567.10.camel@KMA.accesstel> References: <1103030331.4567.10.camel@KMA.accesstel> Message-ID: That's a very broad question. You could email it to yourself, check out the IMAP, POP3, SMTP modules. Alternatively, you could create an FTP session. Check out ftplib. Once you've got it you can use the CSV module to read & parse it. Have fun. Liam Clarke, On Tue, 14 Dec 2004 15:18:52 +0200, Johan Geldenhuys wrote: > Hi, > I want to find out how to open a .cvs file on a remote Windows machine and > get file to my local linux folder. > > Any help would be appreciated. > > -- Johan > -- > This E-Mail has been scanned > Enjoy your day > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From gartler at express.cites.uiuc.edu Wed Dec 15 00:12:22 2004 From: gartler at express.cites.uiuc.edu (Marc Gartler) Date: Wed Dec 15 00:12:26 2004 Subject: [Tutor] check_range In-Reply-To: <450A2166-4E24-11D9-8CF0-000A95C4E51C@express.cites.uiuc.edu> Message-ID: <9C39650A-4E25-11D9-8CF0-000A95C4E51C@express.cites.uiuc.edu> Hi all, I am fairly new to both Python & programming, and am attempting to create a function that will test whether some user input is an integer between 10 and 89, but the check isn't happening... def check_range(myrange): if range(myrange) != range(10,89): return "False" else: return "True" ...this gets called later via: if check_range(input): done = "True" return int(input) What am I doing wrong? Thanks! From amonroe at columbus.rr.com Wed Dec 15 00:27:47 2004 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Wed Dec 15 00:28:11 2004 Subject: [Tutor] check_range In-Reply-To: <9C39650A-4E25-11D9-8CF0-000A95C4E51C@express.cites.uiuc.edu> References: <9C39650A-4E25-11D9-8CF0-000A95C4E51C@express.cites.uiuc.edu> Message-ID: <44778765705.20041214182747@columbus.rr.com> > def check_range(myrange): > if range(myrange) != range(10,89): > return "False" > else: > return "True" For this to work out, the user's input would have to be a giant string containing 10, 11, 12, 13, etc. Unless I mistunderstood your requirements, what you're probably looking for is: if myrange in range(10,90): # "in" is the key word here return True else return False From kent37 at tds.net Wed Dec 15 00:46:26 2004 From: kent37 at tds.net (Kent Johnson) Date: Wed Dec 15 00:46:32 2004 Subject: [Tutor] check_range In-Reply-To: <9C39650A-4E25-11D9-8CF0-000A95C4E51C@express.cites.uiuc.edu> References: <9C39650A-4E25-11D9-8CF0-000A95C4E51C@express.cites.uiuc.edu> Message-ID: <41BF7B52.6000805@tds.net> You misunderstand what range() does. It returns a list of numbers starting with the lower one and up to but not including the upper one: >>> range(5) [0, 1, 2, 3, 4] >>> range(5, 10) [5, 6, 7, 8, 9] To test for a number in a range you can use 10 < n < 90: >>> x = 1 >>> 10 < x < 90 False >>> x = 15 >>> 10 < x < 90 True >>> x = 100 >>> 10 < x < 90 False Kent Marc Gartler wrote: > Hi all, > > I am fairly new to both Python & programming, and am attempting to > create a function that will test whether some user input is an integer > between 10 and 89, but the check isn't happening... > > def check_range(myrange): > if range(myrange) != range(10,89): > return "False" > else: > return "True" > > ...this gets called later via: > if check_range(input): > done = "True" > return int(input) > > > What am I doing wrong? > > Thanks! > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From jeff at ccvcorp.com Wed Dec 15 00:58:38 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed Dec 15 00:54:50 2004 Subject: [Tutor] check_range In-Reply-To: <44778765705.20041214182747@columbus.rr.com> References: <9C39650A-4E25-11D9-8CF0-000A95C4E51C@express.cites.uiuc.edu> <44778765705.20041214182747@columbus.rr.com> Message-ID: <41BF7E2E.7040104@ccvcorp.com> R. Alan Monroe wrote: >>def check_range(myrange): >> if range(myrange) != range(10,89): >> return "False" >> else: >> return "True" > > > For this to work out, the user's input would have to be a giant string > containing 10, 11, 12, 13, etc. Not quite, actually. Presuming that myrange is an integer, range(myrange) will generate a list of integers starting with 0 and continuing up to (but not including) myrange, while range(10,89) generates a list of integers starting with 10 and continuing up to (but not including) 89. These lists can never be equal, because range(10,89) will never include the integers 0-9 but range(myrange) will (unless myrange is less than 10). > Unless I mistunderstood your requirements, what you're probably looking for is: > > if myrange in range(10,90): # "in" is the key word here > return True > else > return False This is, however, the correct solution. :) Presuming again, of course, that myrange is an integer -- but be aware that user input normally comes in the form of strings, so it will be necessary, at some point, to create an integer from that string using int(). Jeff Shannon Technician/Programmer Credit International From cyresse at gmail.com Wed Dec 15 01:09:10 2004 From: cyresse at gmail.com (Liam Clarke) Date: Wed Dec 15 01:09:13 2004 Subject: [Tutor] check_range In-Reply-To: <41BF7B52.6000805@tds.net> References: <9C39650A-4E25-11D9-8CF0-000A95C4E51C@express.cites.uiuc.edu> <41BF7B52.6000805@tds.net> Message-ID: Oh, and you can return True and False without quotation marks. >f check_range(input): > done = "True" > return int(input) You wil also hit problems with this, unless you're using input() to get the integer, which causes even more issues. Apparently, input() evaluates the value returned, so someone who knows Python could enter a Python to delete your HD... It's recommended to get all values with raw_input(), which returns all values as a string, hence the problem with check_range, as it's comparing a string to a integer. The way to make sure that an integer gets entered is as follows - while 1: try: input=int(raw_input("Enter number here ") except TypeError: print "Please enter a number only" print else: print 'Thanks' print 'You entered %d' % input break if check_range(input): done = True return input That will infinitely loop until an integer is entered. raw_input gets the string, and int() tries to convert it to an integer. Obviously you can't convert a non-numeric character to an integer, x=int('s') will raise an error, TypeError, hence the try/except/else error catching clauses. It'll look like this when running - Enter number here David Please enter a number only Enter number here Henry Please enter a number only Enter number here 1.0111010010101010 Thanks You entered 1 #1.01101001 is a floating number, so int would change '1.00101' to 1 HTH Liam Clarke On Tue, 14 Dec 2004 18:46:26 -0500, Kent Johnson wrote: > You misunderstand what range() does. It returns a list of numbers starting with the lower one and up > to but not including the upper one: > >>> range(5) > [0, 1, 2, 3, 4] > >>> range(5, 10) > [5, 6, 7, 8, 9] > > To test for a number in a range you can use 10 < n < 90: > >>> x = 1 > >>> 10 < x < 90 > False > >>> x = 15 > >>> 10 < x < 90 > True > >>> x = 100 > >>> 10 < x < 90 > False > > Kent > > > Marc Gartler wrote: > > Hi all, > > > > I am fairly new to both Python & programming, and am attempting to > > create a function that will test whether some user input is an integer > > between 10 and 89, but the check isn't happening... > > > > def check_range(myrange): > > if range(myrange) != range(10,89): > > return "False" > > else: > > return "True" > > > > ...this gets called later via: > > if check_range(input): > > done = "True" > > return int(input) > > > > > > What am I doing wrong? > > > > Thanks! > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only ba sic human duty, to take the consequences. From jeff at ccvcorp.com Wed Dec 15 01:23:39 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed Dec 15 01:19:51 2004 Subject: [Tutor] check_range In-Reply-To: <41BF7E2E.7040104@ccvcorp.com> References: <9C39650A-4E25-11D9-8CF0-000A95C4E51C@express.cites.uiuc.edu> <44778765705.20041214182747@columbus.rr.com> <41BF7E2E.7040104@ccvcorp.com> Message-ID: <41BF840B.20908@ccvcorp.com> Jeff Shannon wrote: >> if myrange in range(10,90): # "in" is the key word here >> return True >> else >> return False > > > This is, however, the correct solution. :) Or I *should* say, rather, that this is *a* correct solution, in that it will yield the expected answer. Kent Johnson's '10 < x < 90' is a better solution, however -- 'if x in range(...)' creates a list of numbers, and then steps through that list comparing x to each one in turn, while Kent's version makes only two comparisons and no object creations. While one should never prematurely optimize, it's also good to be aware of how much work is done by different options, and in this case 'if x in range()' isn't any clearer than the direct comparisons. I'd think nothing of the extra cost of using range() if it *did* make the code easier to read, but there's no sense in going to extra work for no benefit. :) Jeff Shannon Technician/Programmer Credit International From bvande at po-box.mcgill.ca Wed Dec 15 01:39:06 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Wed Dec 15 01:39:18 2004 Subject: [Tutor] check_range In-Reply-To: <9C39650A-4E25-11D9-8CF0-000A95C4E51C@express.cites.uiuc.edu> References: <9C39650A-4E25-11D9-8CF0-000A95C4E51C@express.cites.uiuc.edu> Message-ID: <41BF87AA.7050400@po-box.mcgill.ca> Marc Gartler said unto the world upon 2004-12-14 18:12: > Hi all, > > I am fairly new to both Python & programming, and am attempting to > create a function that will test whether some user input is an integer > between 10 and 89, but the check isn't happening... > > def check_range(myrange): > if range(myrange) != range(10,89): > return "False" > else: > return "True" > > ...this gets called later via: > if check_range(input): > done = "True" > return int(input) > > > What am I doing wrong? > > Thanks! Hi Marc, Welcome to Python and the list. :-) Others have pointed out how to solve your immediate problem with in or a comparison, and that you can just return True and False unquoted. (They are special builtin objects, so making strings for them isn't needed.) A minor correction to Kent's suggestion, though. He suggested to use 10 < x < 90, but since I gather you want 10 to return True, you need 9 < x < 90: >>> 10 < 10 < 90 False >>> 9 < 10 < 90 True This sort of thing is an "off by 1 error" and will happen to you all the time :-( I have a some style suggestions for you, too. Try it this way: >>> def check_in_range(value): in_range = False if 9 < value < 90: in_range = True return in_range >>> check_in_range(35) True This way, by setting a name to point to False, and over-riding that when the test is met, there is only a single return statement. That is often considered a good thing. This function is too small for it to matter lots, but have multiple returns can make the debugging a bit harder. Another tip is that for debugging such things it often helps to use print statements when things don't go as expected. If you'd added them to your original function like so: >>> def check_range(myrange): print range(myrange) print range(2,5) if range(myrange) != range(2,5): return "False" else: return "True" >>> check_range(3) [0, 1, 2] [2, 3, 4] 'False' The problem would have likely been much more clear. HTH, Brian vdB From gartler at express.cites.uiuc.edu Wed Dec 15 03:00:05 2004 From: gartler at express.cites.uiuc.edu (Marc Gartler) Date: Wed Dec 15 03:00:12 2004 Subject: [Tutor] check_range In-Reply-To: <41BF87AA.7050400@po-box.mcgill.ca> Message-ID: <0A3E8B36-4E3D-11D9-8CF0-000A95C4E51C@express.cites.uiuc.edu> Thanks all, that was very helpful! On Tuesday, December 14, 2004, at 06:39 PM, Brian van den Broek wrote: > Marc Gartler said unto the world upon 2004-12-14 18:12: >> Hi all, >> I am fairly new to both Python & programming, and am attempting to >> create a function that will test whether some user input is an >> integer between 10 and 89, but the check isn't happening... >> def check_range(myrange): >> if range(myrange) != range(10,89): >> return "False" >> else: >> return "True" >> ...this gets called later via: >> if check_range(input): >> done = "True" >> return int(input) >> What am I doing wrong? >> Thanks! > > Hi Marc, > > Welcome to Python and the list. :-) > > Others have pointed out how to solve your immediate problem with in or > a comparison, and that you can just return True and False unquoted. > (They are special builtin objects, so making strings for them isn't > needed.) > > A minor correction to Kent's suggestion, though. He suggested to use > 10 < x < 90, but since I gather you want 10 to return True, you need > 9 < x < 90: > > >>> 10 < 10 < 90 > False > >>> 9 < 10 < 90 > True > > This sort of thing is an "off by 1 error" and will happen to you all > the time :-( > > I have a some style suggestions for you, too. > > Try it this way: > > >>> def check_in_range(value): > in_range = False > if 9 < value < 90: > in_range = True > return in_range > > >>> check_in_range(35) > True > > This way, by setting a name to point to False, and over-riding that > when the test is met, there is only a single return statement. That is > often considered a good thing. This function is too small for it to > matter lots, but have multiple returns can make the debugging a bit > harder. > > Another tip is that for debugging such things it often helps to use > print statements when things don't go as expected. If you'd added them > to your original function like so: > > >>> def check_range(myrange): > print range(myrange) > print range(2,5) > if range(myrange) != range(2,5): > return "False" > else: > return "True" > > >>> check_range(3) > [0, 1, 2] > [2, 3, 4] > 'False' > > The problem would have likely been much more clear. > > HTH, > > Brian vdB > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From gartler at express.cites.uiuc.edu Wed Dec 15 04:13:00 2004 From: gartler at express.cites.uiuc.edu (Marc Gartler) Date: Wed Dec 15 04:13:04 2004 Subject: [Tutor] User selection as both string and int Message-ID: <3A225427-4E47-11D9-8CF0-000A95C4E51C@express.cites.uiuc.edu> I am trying to have a user select from amongst a list of items, and then make use of that choice later on as both a string (e.g. "you chose _____"). My function currently allows for a numerical choice, but I am not sure how to return it as the item (e.g. apple) rather than the integer corresponding to the position in the list: def get_material(mylist): mycount = 1 for item in mylist: print mycount, item mycount = mycount + 1 material = raw_input("Please select material:") myposition = int(material) - 1 return myposition fruit_list = ['apple', 'orange', 'banana'] fruit = get_material(fruit_list) From bvande at po-box.mcgill.ca Wed Dec 15 04:44:50 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Wed Dec 15 04:44:57 2004 Subject: [Tutor] User selection as both string and int In-Reply-To: <3A225427-4E47-11D9-8CF0-000A95C4E51C@express.cites.uiuc.edu> References: <3A225427-4E47-11D9-8CF0-000A95C4E51C@express.cites.uiuc.edu> Message-ID: <41BFB332.1000909@po-box.mcgill.ca> Marc Gartler said unto the world upon 2004-12-14 22:13: > I am trying to have a user select from amongst a list of items, and then > make use of that choice later on as both a string (e.g. "you chose > _____"). My function currently allows for a numerical choice, but I am > not sure how to return it as the item (e.g. apple) rather than the > integer corresponding to the position in the list: > > def get_material(mylist): > mycount = 1 > for item in mylist: > print mycount, item > mycount = mycount + 1 > material = raw_input("Please select material:") > myposition = int(material) - 1 > return myposition > > fruit_list = ['apple', 'orange', 'banana'] > > fruit = get_material(fruit_list) > Hi Marc, Since fruit_list is a list, you can 'fetch' an element out of it like so: fruit_list[index] where index is an integer. Your function returns an integer. So, for the minimal change to get what you want done, try replacing your last line with these two: fruit = fruit_list[get_material(fruit_list)] print fruit Best, Brian vdB From gartler at express.cites.uiuc.edu Wed Dec 15 04:50:30 2004 From: gartler at express.cites.uiuc.edu (Marc Gartler) Date: Wed Dec 15 04:50:34 2004 Subject: [Tutor] User selection as both string and int In-Reply-To: <76912af80412141918c9f0b29@mail.gmail.com> Message-ID: <76D3C2D1-4E4C-11D9-8CF0-000A95C4E51C@express.cites.uiuc.edu> Thanks. That was pretty basic... On Tuesday, December 14, 2004, at 09:18 PM, Loptr Chaote wrote: > On Tue, 14 Dec 2004 21:13:00 -0600, Marc Gartler > wrote: >> I am trying to have a user select from amongst a list of items, and >> then make use of that choice later on as both a string (e.g. "you >> chose >> _____"). My function currently allows for a numerical choice, but I >> am >> not sure how to return it as the item (e.g. apple) rather than the >> integer corresponding to the position in the list: >> > > It looks like all you need is a > > print 'You selected: ', fruit_list[fruit] > > after the get_material() call. > This accesses the position >fruit< (i.e. the value in fruit) in the > array fruit_list. > Try > > print fruit_list[0], fruit_list[1], fruit_list[2] > > and you'll understand how it works. > > -L.C > From gartler at express.cites.uiuc.edu Wed Dec 15 04:53:03 2004 From: gartler at express.cites.uiuc.edu (Marc Gartler) Date: Wed Dec 15 04:53:06 2004 Subject: [Tutor] User selection as both string and int In-Reply-To: <41BFB332.1000909@po-box.mcgill.ca> Message-ID: Better still. Thanks Brian. On Tuesday, December 14, 2004, at 09:44 PM, Brian van den Broek wrote: > Marc Gartler said unto the world upon 2004-12-14 22:13: >> I am trying to have a user select from amongst a list of items, and >> then make use of that choice later on as both a string (e.g. "you >> chose _____"). My function currently allows for a numerical choice, >> but I am not sure how to return it as the item (e.g. apple) rather >> than the integer corresponding to the position in the list: >> def get_material(mylist): >> mycount = 1 >> for item in mylist: >> print mycount, item >> mycount = mycount + 1 >> material = raw_input("Please select material:") >> myposition = int(material) - 1 >> return myposition >> fruit_list = ['apple', 'orange', 'banana'] >> fruit = get_material(fruit_list) > > Hi Marc, > > Since fruit_list is a list, you can 'fetch' an element out of it like > so: > fruit_list[index] > where index is an integer. > > Your function returns an integer. So, for the minimal change to get > what you want done, try replacing your last line with these two: > fruit = fruit_list[get_material(fruit_list)] > print fruit > > Best, > > Brian vdB > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From forestiero at qwest.net Wed Dec 15 06:32:31 2004 From: forestiero at qwest.net (DogWalker) Date: Wed Dec 15 06:33:04 2004 Subject: [Tutor] check_range In-Reply-To: <41BF87AA.7050400@po-box.mcgill.ca> References: <9C39650A-4E25-11D9-8CF0-000A95C4E51C@express.cites.uiuc.edu> <41BF87AA.7050400@po-box.mcgill.ca> Message-ID: <20041215052624.8659.72391@linux.local> "Brian van den Broek" said: >Marc Gartler said unto the world upon 2004-12-14 18:12: >> Hi all, >> >> I am fairly new to both Python & programming, and am attempting to >> create a function that will test whether some user input is an integer >> between 10 and 89, but the check isn't happening... >> >> def check_range(myrange): >> if range(myrange) != range(10,89): >> return "False" >> else: >> return "True" >> >> ...this gets called later via: >> if check_range(input): >> done = "True" >> return int(input) >> [...] >I have a some style suggestions for you, too. > >Try it this way: > > >>> def check_in_range(value): > in_range = False > if 9 < value < 90: > in_range = True > return in_range > > >>> check_in_range(35) >True > Shorter: def check_in_range(value): return 9 < value < 90 [...] From bvande at po-box.mcgill.ca Wed Dec 15 08:59:00 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Wed Dec 15 09:05:21 2004 Subject: [Tutor] check_range In-Reply-To: <20041215052624.8659.72391@linux.local> References: <9C39650A-4E25-11D9-8CF0-000A95C4E51C@express.cites.uiuc.edu> <41BF87AA.7050400@po-box.mcgill.ca> <20041215052624.8659.72391@linux.local> Message-ID: <41BFEEC4.605@po-box.mcgill.ca> DogWalker said unto the world upon 2004-12-15 00:32: > "Brian van den Broek" said: > >>Marc Gartler said unto the world upon 2004-12-14 18:12: >> >>>Hi all, >>> >>>I am fairly new to both Python & programming, and am attempting to >>>create a function that will test whether some user input is an integer >>>between 10 and 89, but the check isn't happening... >>> >>>def check_range(myrange): >>> if range(myrange) != range(10,89): >>> return "False" >>> else: >>> return "True" >>> >>>...this gets called later via: >>> if check_range(input): >>> done = "True" >>> return int(input) > > [...] > >>I have a some style suggestions for you, too. >> >>Try it this way: >> >>>>>def check_in_range(value): >> >> in_range = False >> if 9 < value < 90: >> in_range = True >> return in_range > > > Shorter: > def check_in_range(value): > return 9 < value < 90 Indeed. Good one. I never seem to think of such very direct ways, but there you have it. It might say more about my psychology than anything else, but I think I'd be tempted to put a brief comment on that code. (Such as # returns True if the test, False otherwise.) My guess is that if I had to read it more than twice, the time spent writing the comment would be more than regained in spending less time scratching my head. This might also be a matter of little experience, too. At any rate, I certainly would agree that yours is bound to be better in any situation where speed of execution mattered a lot. Best, Brian vdB From kent37 at tds.net Wed Dec 15 13:43:57 2004 From: kent37 at tds.net (Kent Johnson) Date: Wed Dec 15 13:44:00 2004 Subject: [Tutor] check_range In-Reply-To: <41BFEEC4.605@po-box.mcgill.ca> References: <9C39650A-4E25-11D9-8CF0-000A95C4E51C@express.cites.uiuc.edu> <41BF87AA.7050400@po-box.mcgill.ca> <20041215052624.8659.72391@linux.local> <41BFEEC4.605@po-box.mcgill.ca> Message-ID: <41C0318D.3000909@tds.net> Brian van den Broek wrote: > DogWalker said unto the world upon 2004-12-15 00:32: > >> "Brian van den Broek" said: >>> I have a some style suggestions for you, too. >>> >>> Try it this way: >>> >>> def check_in_range(value): >>> in_range = False >>> if 9 < value < 90: >>> in_range = True >>> return in_range >> >> Shorter: >> def check_in_range(value): >> return 9 < value < 90 > > > Indeed. Good one. I never seem to think of such very direct ways, but > there you have it. It might say more about my psychology than anything > else, but I think I'd be tempted to put a brief comment on that code. > (Such as # returns True if the test, False otherwise.) My guess is that > if I had to read it more than twice, the time spent writing the comment > would be more than regained in spending less time scratching my head. > This might also be a matter of little experience, too. Of course put a comment if you like, but this is very concise, idiomatic code and I hope you will get used to it so the comment is not needed. The value of the expression '9 < value < 90' is actually a boolean True or False, so testing the expression and explicitly returning True or False is redundant. You are using four lines of code to do the work of one. In general, Python's flexibility with boolean values is a strength of the language and I recommend you try to get comfortable with it. > > At any rate, I certainly would agree that yours is bound to be better in > any situation where speed of execution mattered a lot. Or readability, IMO. Kent > > Best, > > Brian vdB > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From cyresse at gmail.com Wed Dec 15 14:00:19 2004 From: cyresse at gmail.com (Liam Clarke) Date: Wed Dec 15 14:00:22 2004 Subject: [Tutor] check_range In-Reply-To: <41C0318D.3000909@tds.net> References: <9C39650A-4E25-11D9-8CF0-000A95C4E51C@express.cites.uiuc.edu> <41BF87AA.7050400@po-box.mcgill.ca> <20041215052624.8659.72391@linux.local> <41BFEEC4.605@po-box.mcgill.ca> <41C0318D.3000909@tds.net> Message-ID: I'll second this - > In general, Python's flexibility with boolean values is a strength of the language and I recommend > you try to get comfortable with it. If you come across something, and you're not sure if it'll evaluate true or false, fire up IDLE or similar intepreter, and test it! I'd call that another strength of Python. Liam Clarke On Wed, 15 Dec 2004 07:43:57 -0500, Kent Johnson wrote: > Brian van den Broek wrote: > > DogWalker said unto the world upon 2004-12-15 00:32: > > > >> "Brian van den Broek" said: > >>> I have a some style suggestions for you, too. > >>> > >>> Try it this way: > >>> > >>> def check_in_range(value): > >>> in_range = False > >>> if 9 < value < 90: > >>> in_range = True > >>> return in_range > >> > >> Shorter: > >> def check_in_range(value): > >> return 9 < value < 90 > > > > > > Indeed. Good one. I never seem to think of such very direct ways, but > > there you have it. It might say more about my psychology than anything > > else, but I think I'd be tempted to put a brief comment on that code. > > (Such as # returns True if the test, False otherwise.) My guess is that > > if I had to read it more than twice, the time spent writing the comment > > would be more than regained in spending less time scratching my head. > > This might also be a matter of little experience, too. > > Of course put a comment if you like, but this is very concise, idiomatic code and I hope you will > get used to it so the comment is not needed. > > The value of the expression '9 < value < 90' is actually a boolean True or False, so testing the > expression and explicitly returning True or False is redundant. You are using four lines of code to > do the work of one. > > In general, Python's flexibility with boolean values is a strength of the language and I recommend > you try to get comfortable with it. > > > > > At any rate, I certainly would agree that yours is bound to be better in > > any situation where speed of execution mattered a lot. > > Or readability, IMO. > > Kent > > > > > Best, > > > > Brian vdB > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From orion_val at 163.com Wed Dec 15 14:51:44 2004 From: orion_val at 163.com (Juan Shen) Date: Wed Dec 15 15:00:20 2004 Subject: [Tutor] check_range In-Reply-To: <41C0318D.3000909@tds.net> References: <9C39650A-4E25-11D9-8CF0-000A95C4E51C@express.cites.uiuc.edu> <41BF87AA.7050400@po-box.mcgill.ca> <20041215052624.8659.72391@linux.local> <41BFEEC4.605@po-box.mcgill.ca> <41C0318D.3000909@tds.net> Message-ID: <1103118704.3863.6.camel@juan.sjtu.edu.cn> I agree with Kent's opinion. A boolean statement, like 9>> ( 9 < value ) and ( value < 90 ) , maybe a good sense of boolean type will be made, because 'and' operation is always associating with boolean. Juan Shen ÔÚ 2004-12-15ÈýµÄ 07:43 -0500£¬Kent JohnsonдµÀ£º > Brian van den Broek wrote: > > DogWalker said unto the world upon 2004-12-15 00:32: > > > >> "Brian van den Broek" said: > >>> I have a some style suggestions for you, too. > >>> > >>> Try it this way: > >>> > >>> def check_in_range(value): > >>> in_range = False > >>> if 9 < value < 90: > >>> in_range = True > >>> return in_range > >> > >> Shorter: > >> def check_in_range(value): > >> return 9 < value < 90 > > > > > > Indeed. Good one. I never seem to think of such very direct ways, but > > there you have it. It might say more about my psychology than anything > > else, but I think I'd be tempted to put a brief comment on that code. > > (Such as # returns True if the test, False otherwise.) My guess is that > > if I had to read it more than twice, the time spent writing the comment > > would be more than regained in spending less time scratching my head. > > This might also be a matter of little experience, too. > > Of course put a comment if you like, but this is very concise, idiomatic code and I hope you will > get used to it so the comment is not needed. > > The value of the expression '9 < value < 90' is actually a boolean True or False, so testing the > expression and explicitly returning True or False is redundant. You are using four lines of code to > do the work of one. > > In general, Python's flexibility with boolean values is a strength of the language and I recommend > you try to get comfortable with it. > > > > > At any rate, I certainly would agree that yours is bound to be better in > > any situation where speed of execution mattered a lot. > > Or readability, IMO. > > Kent > > > > > Best, > > > > Brian vdB > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From john.ertl at fnmoc.navy.mil Wed Dec 15 20:59:31 2004 From: john.ertl at fnmoc.navy.mil (Ertl, John) Date: Wed Dec 15 20:59:46 2004 Subject: [Tutor] turning a number into a formated string Message-ID: I need to take a number and turn it into a formatted string. The final output needs to look like XXXXYYYY when the X is the integer part padded on the left and Y is the decimal part padded on the right. I figured I could split the number at "." and then use zfill or something like this (LEVEL1 = "%04d" % LEVEL1) for the XXXX part but I am not sure how to right pad the decimal part of the number. Example. 1 and 1.0 needs to look like 00010000 ( I figured I would have to check the length of the list made from the split to see if a decimal portion existed) 1.1 needs to look like 00011000 22.33 needs to look like 00223330 4444.22 needs to look like 44442200 Any ideas on the right padding the decimal side using "0" Thanks, John From marilyn at deliberate.com Wed Dec 15 21:11:30 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Wed Dec 15 21:11:33 2004 Subject: [Tutor] turning a number into a formated string In-Reply-To: Message-ID: Here's one way: left, right = str(number).split('.') output = "%04d%d" % (int(left), int(right)) + (4 - len(right)) * '0' Maybe someone has a more elegant way. Hope it helps, Marilyn Davis On Wed, 15 Dec 2004, Ertl, John wrote: > I need to take a number and turn it into a formatted string. > The final output needs to look like XXXXYYYY when the X is the integer > part padded on the left and Y is the decimal part padded on the right. > I figured I could split the number at "." and then use zfill or something > like this (LEVEL1 = "%04d" % LEVEL1) for the XXXX part but I am not sure > how to right pad the decimal part of the number. > Example. > 1 and 1.0 needs to look like 00010000 ( I figured I would have to check the > length of the list made from the split to see if a decimal portion existed) > 1.1 needs to look like 00011000 > 22.33 needs to look like 00223330 > 4444.22 needs to look like 44442200 > Any ideas on the right padding the decimal side using "0" > Thanks, > John > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- From tim.peters at gmail.com Wed Dec 15 21:15:27 2004 From: tim.peters at gmail.com (Tim Peters) Date: Wed Dec 15 21:15:31 2004 Subject: [Tutor] turning a number into a formated string In-Reply-To: References: Message-ID: <1f7befae04121512153aa7ae67@mail.gmail.com> [Ertl, John] > I need to take a number and turn it into a formatted string. > The final output needs to look like XXXXYYYY when the X is the > integer part padded on the left and Y is the decimal part padded > on the right. > I figured I could split the number at "." and then use zfill or > something like this (LEVEL1 = "%04d" % LEVEL1) for the XXXX > part but I am not sure how to right pad the decimal part of the > number. > Example. > 1 and 1.0 needs to look like 00010000 ( I figured I would have to > check the length of the list made from the split to see if a decimal > portion existed) > 1.1 needs to look like 00011000 > 22.33 needs to look like 00223330 Really? The input has two digits 3, but the output has three digits 3. I'll assume you meant 00223300 instead. > 4444.22 needs to look like 44442200 > Any ideas on the right padding the decimal side using "0" I expect that a "%09.4f" format does everything you asked for, except that it contains a period. So let's try to repair that: >>> def johnpad(n): ... return ("%09.4f" % n).replace('.', '') Then: >>> johnpad(1) '00010000' >>> johnpad(1.0) '00010000' >>> johnpad(1.1) '00011000' >>> johnpad(22.33) '00223300' >>> johnpad(4444.22) '44442200' >>> From marilyn at deliberate.com Wed Dec 15 21:22:33 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Wed Dec 15 21:22:37 2004 Subject: [Tutor] turning a number into a formated string In-Reply-To: <1f7befae04121512153aa7ae67@mail.gmail.com> Message-ID: On Wed, 15 Dec 2004, Tim Peters wrote: > ... return ("%09.4f" % n).replace('.', '') Totally cool. Marilyn From john.ertl at fnmoc.navy.mil Wed Dec 15 22:25:46 2004 From: john.ertl at fnmoc.navy.mil (Ertl, John) Date: Wed Dec 15 22:25:59 2004 Subject: [Tutor] turning a number into a formated string Message-ID: Very elegant, It makes me feel like "I should have thought of that". Thanks for the help and the reminder to think of the simplistic approach. John -----Original Message----- From: Tim Peters [mailto:tim.peters@gmail.com] Sent: Wednesday, December 15, 2004 12:15 To: Ertl, John Cc: tutor-list (Python) Subject: Re: [Tutor] turning a number into a formated string [Ertl, John] > I need to take a number and turn it into a formatted string. > The final output needs to look like XXXXYYYY when the X is the > integer part padded on the left and Y is the decimal part padded > on the right. > I figured I could split the number at "." and then use zfill or > something like this (LEVEL1 = "%04d" % LEVEL1) for the XXXX > part but I am not sure how to right pad the decimal part of the > number. > Example. > 1 and 1.0 needs to look like 00010000 ( I figured I would have to > check the length of the list made from the split to see if a decimal > portion existed) > 1.1 needs to look like 00011000 > 22.33 needs to look like 00223330 Really? The input has two digits 3, but the output has three digits 3. I'll assume you meant 00223300 instead. > 4444.22 needs to look like 44442200 > Any ideas on the right padding the decimal side using "0" I expect that a "%09.4f" format does everything you asked for, except that it contains a period. So let's try to repair that: >>> def johnpad(n): ... return ("%09.4f" % n).replace('.', '') Then: >>> johnpad(1) '00010000' >>> johnpad(1.0) '00010000' >>> johnpad(1.1) '00011000' >>> johnpad(22.33) '00223300' >>> johnpad(4444.22) '44442200' >>> From marilyn at deliberate.com Wed Dec 15 22:51:58 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Wed Dec 15 22:52:02 2004 Subject: [Tutor] A little Tkinter question Message-ID: Hi Tutors, I'm reviewing GUIs and wondering: When you pack a component, and you specify fill = BOTH, how is this different from expand = YES? Thank you for any insight. Marilyn Davis From glingl at aon.at Wed Dec 15 23:59:28 2004 From: glingl at aon.at (Gregor Lingl) Date: Wed Dec 15 23:59:23 2004 Subject: [Tutor] A little Tkinter question In-Reply-To: References: Message-ID: <41C0C1D0.40002@aon.at> Marilyn Davis schrieb: > Hi Tutors, > > I'm reviewing GUIs and wondering: > > When you pack a component, and you specify fill = BOTH, how is this > different from expand = YES? > Hi Marilyn, This is a bit tricky and hard to explain, so I recommend playing around with this little program from John Grayson's Tkinter book: from Tkinter import * class App: def __init__(self, master): master.geometry("300x200") fm = Frame(master) Button(fm, text='Left').pack(side=LEFT, fill=BOTH, expand=1) Button(fm, text='Center').pack(side=LEFT, fill=BOTH, expand=1) Button(fm, text='Right').pack(side=LEFT, fill=BOTH, expand=1) fm.pack(fill=BOTH, expand=YES) root = Tk() root.option_add('*font', ('verdana', 12, 'bold')) root.title("Pack - Example 9") display = App(root) root.mainloop() Modify the three lines with Button(....).pack(...) for instance by setting expand = 0 (which is the default value) Button(fm, text='Left').pack(side=LEFT, fill=BOTH, expand=0) Button(fm, text='Center').pack(side=LEFT, fill=BOTH, expand=0) Button(fm, text='Right').pack(side=LEFT, fill=BOTH, expand=0) or by tropping the fill option: Button(fm, text='Left').pack(side=LEFT, expand=1) Button(fm, text='Center').pack(side=LEFT, expand=1) Button(fm, text='Right').pack(side=LEFT, expand=1) and so on. These Examples are from Chapter 5, several others concerning the packer can be found at: https://secure.manning.com/catalog/view.php?book=grayson&item=source Hope this helps Gregor > Thank you for any insight. > > Marilyn Davis > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > -- Gregor Lingl Reisnerstrasse 3/19 A-1030 Wien Telefon: +43 1 713 33 98 Mobil: +43 664 140 35 27 Autor von "Python f?r Kids" Website: python4kids.net From pythontut at pusspaws.net Thu Dec 16 00:03:26 2004 From: pythontut at pusspaws.net (Dave S) Date: Thu Dec 16 00:03:35 2004 Subject: [Tutor] Python structure advice ? Message-ID: <41C0C2BE.2020107@pusspaws.net> Im sorry to bang on about Python structure, but I do struggle with it, having in the past got into very bad habits with loads of BASIC where everything was global, and Forth, and hand coded 8031, 8051, 6502 .... I cant get my head round how you guys handle a modern structured language :-) (PS before anyone flames me - I think Python is great and am determined to learn it ;-) ) I have ended up with my application in several separate directories. I have 'live_datad' a demon that extracts web data, at preset times and archives it, this will be run as a thread, and possible using a queue ... (still digesting info from query about IPCing) I have a 'data_core' which accepts data from either live_datad real time or the archive for testing, it builds up a large multi dimensional array with various pointers into the array. I have a statistical module 'data_stats' which analises the array pulling various stats. And finally I have an analytical module 'data_predict' which using the output from 'data_stats' & data directly from the 'data_core' outputs statistical predictions of future data. I have written my 'live_datad', I have written my 'data_core' & have a fairly good idea how to write the rest. My problem is that pretty much all the modules need to fix where they are when they exit and pick up from that point later on, ie more data comes from live_datad, it is passed to 'data_core' which updates the matrix, then 'data_stats' then 'data_predict' all called form the main script. This OK till the main script realizes that more data is avalible from 'live_datad', passes it to 'data_core' which must remember where it was and move on, and the same for the rest of the modules. To make the problem more acute the modules may not be called in exactly the same order depending on what I am trying to achieve. The 'remembering where is was' seems a continuous stumbling block for me. I have though of coding each module as a class but this seems like a cheat. I could declare copious globals, this seems messy, I could define each module as a thread & get them talking via queues, given this serious thought but heeded warning in previous posts. I have thought about returning an list of saved 'pointers' which would be re-submitted when the function is called. I don't know which way to turn. With my code now running to a few hundred lines (Don't laugh this is BIG for me :-D ) I am going to have to make a structure decision and any suggestions would be appreciated. How would you approach it ? Dave From bvande at po-box.mcgill.ca Thu Dec 16 01:58:56 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Thu Dec 16 01:58:57 2004 Subject: [Tutor] am I missing another simpler structure? Message-ID: <41C0DDCF.9040002@po-box.mcgill.ca> Hi all, in Marc's check_range thread, I had proposed: def check_in_range(value): in_range = False if 9 < value < 90: in_range = True return in_range and DogWalker suggested the better: def check_in_range(value): return 9 < value < 90 As I mentioned, I feel as though I have a mental block getting in the way of coming up with code in the smoother fashion of the second snippet above. As I have been making a lot of use of a construct (pattern?) similar to my code above, wherein I try something, and return True if it works, False if it doesn't, I've begun to wonder if I am overlooking a improvement similar to that in DogWalker's suggestion. As an example of the sort of thing I have been doing: import datetime def is_leap_year(year): '''-> boolean Returns True or False as year is, or is not, a leap year. ''' is_leap = True try: datetime.date(year, 2, 29) except ValueError: is_leap = False return is_leap Please ignore that there is a function in the calendar module to do exactly this, and that, as that library function does, it could be done by simply testing if the leap year conditions are met. In the general case, it doesn't seem that there will always be an easy conditional test. This function here was written so as to illustrate the structure I'm interested in, without the complications of the details of actual cases I have used. (I hope that's clear enough--it felt much clearer before I'd spent the time drafting a post.) Best to all, Brian vdB From r2b2 at myway.com Thu Dec 16 02:10:12 2004 From: r2b2 at myway.com (Rene Bourgoin) Date: Thu Dec 16 02:10:32 2004 Subject: [Tutor] dbcp module Message-ID: <20041216011012.4A741398B@mprdmxin.myway.com> Anyone know where I can download the dbcp module for Python???? _______________________________________________ No banners. No pop-ups. No kidding. Make My Way your home on the Web - http://www.myway.com From kent37 at tds.net Thu Dec 16 02:16:47 2004 From: kent37 at tds.net (Kent Johnson) Date: Thu Dec 16 02:16:52 2004 Subject: [Tutor] am I missing another simpler structure? In-Reply-To: <41C0DDCF.9040002@po-box.mcgill.ca> References: <41C0DDCF.9040002@po-box.mcgill.ca> Message-ID: <41C0E1FF.1060504@tds.net> Brian van den Broek wrote: > I've begun to wonder if I am overlooking a > improvement similar to that in DogWalker's suggestion. As an example of > the sort of thing I have been doing: > > import datetime > def is_leap_year(year): > '''-> boolean > > Returns True or False as year is, or is not, a leap year. > ''' > is_leap = True > try: > datetime.date(year, 2, 29) > except ValueError: > is_leap = False > return is_leap I would write def is_leap_year(year): try: datetime.date(year, 2, 29) return True except ValueError: return False Kent From kent37 at tds.net Thu Dec 16 02:19:22 2004 From: kent37 at tds.net (Kent Johnson) Date: Thu Dec 16 02:19:29 2004 Subject: [Tutor] dbcp module In-Reply-To: <20041216011012.4A741398B@mprdmxin.myway.com> References: <20041216011012.4A741398B@mprdmxin.myway.com> Message-ID: <41C0E29A.2090305@tds.net> Googling for 'python dbcp' turns up this recipe, is this what you are looking for? http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81189 Kent Rene Bourgoin wrote: > Anyone know where I can download the dbcp module for Python???? > > > > > > > _______________________________________________ > No banners. No pop-ups. No kidding. > Make My Way your home on the Web - http://www.myway.com > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From tony at tcapp.com Thu Dec 16 02:47:58 2004 From: tony at tcapp.com (Tony Cappellini) Date: Thu Dec 16 02:33:26 2004 Subject: [Tutor] Leading zero for hex numbers Message-ID: <20041215174212.J64331@yamato.yamato.com> I'm trying to get Python to automatically print a leading 0 for hex numbers, but it only seems to work for for decimal numbers. print "0x%0X" % 12345 displays 0x3039 instead of 0x03039 The Python docs state The conversion will be zero padded for numeric values, when a 0 is used as a flag between the % and the conversion type. Is this expected Python behaviour, or a mistake? Sure, I can add some code to calculate the length of the current string to decide if a leading 0 is needed., but if I don't have to, I'd rather not. From rdm at rcblue.com Thu Dec 16 02:34:23 2004 From: rdm at rcblue.com (Dick Moores) Date: Thu Dec 16 02:34:34 2004 Subject: [Tutor] OT?: how to google just the 2.4 tutorial? In-Reply-To: <6.1.2.0.2.20041212084653.056d9ab0@rcblue.com> References: <6.1.2.0.2.20041212084653.056d9ab0@rcblue.com> Message-ID: <6.1.2.0.2.20041215173218.04d659a0@rcblue.com> Just got this reply from help@google.com. --Dick Regrettably, we don't currently offer a way to limit your search to a specific section of a site. We really appreciate your thoughtful feedback, and we'll keep it in mind as we work to improve Google. Regards, The Google Team Dick Moores wrote at 08:53 12/12/2004: >I know how to limit google search results to a single site, but is it >possible to google just one section of a site? > >I'd like to be able to search just the 2.4 tutorial, >http://www.python.org/doc/2.4/tut/tut.html >Possible? And if so, how to? From amonroe at columbus.rr.com Thu Dec 16 02:40:40 2004 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Thu Dec 16 02:41:06 2004 Subject: [Tutor] Leading zero for hex numbers In-Reply-To: <20041215174212.J64331@yamato.yamato.com> References: <20041215174212.J64331@yamato.yamato.com> Message-ID: <142075354.20041215204040@columbus.rr.com> > print "0x%0X" % 12345 > displays > 0x3039 > instead of 0x03039 >>> "%05x" % (12345,) '03039' >>> "0x%05x" % (12345,) '0x03039' From singingxduck at gmail.com Thu Dec 16 02:44:29 2004 From: singingxduck at gmail.com (Orri Ganel) Date: Thu Dec 16 02:45:45 2004 Subject: [Tutor] Leading zero for hex numbers In-Reply-To: <20041215174212.J64331@yamato.yamato.com> References: <20041215174212.J64331@yamato.yamato.com> Message-ID: <3449428f04121517442201d9b1@mail.gmail.com> On Wed, 15 Dec 2004 17:47:58 -0800 (PST), Tony Cappellini wrote: > > I'm trying to get Python to automatically print a leading 0 for hex > numbers, but it only > seems to work for for decimal numbers. > > print "0x%0X" % 12345 > > displays > 0x3039 > > instead of 0x03039 > > The Python docs state > The conversion will be zero padded for numeric values, when a 0 is used as > a flag between the % and the conversion type. > > Is this expected Python behaviour, or a mistake? > > Sure, I can add some code to calculate the length of the current string to > decide if a leading 0 is needed., but if I don't have to, I'd rather not. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > >>> print "0x%0X" % 12345 0x3039 >>> print "0x%0.X" % 12345 0x3039 >>> print "0x%1X" % 12345 0x3039 >>> print "0x%10X" % 12345 0x 3039 >>> print "0x%2X" % 12345 0x3039 >>> print "0x%3X" % 12345 0x3039 >>> print "0x%0.10X" % 12345 0x0000003039 >>> print "0x%0.5X" % 12345 0x03039 >>> print "0x%0.5X" % 123456 0x1E240 >>> print "0x%0X" % 123456 0x1E240 >>> print "0x%0.5X" % 2222 0x008AE >>> print "0x%0.5X" % 22222 0x056CE >>> print "0x%0.5X" % 122222 0x1DD6E Ok, so the character after the % and before the . is the padding character, and the number after the . and before the X is the minimum size for the string to be. So print "0x%0.5X" % 12345 seems to do what you want. -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. From singingxduck at gmail.com Thu Dec 16 02:46:21 2004 From: singingxduck at gmail.com (Orri Ganel) Date: Thu Dec 16 02:46:25 2004 Subject: [Tutor] Leading zero for hex numbers In-Reply-To: <142075354.20041215204040@columbus.rr.com> References: <20041215174212.J64331@yamato.yamato.com> <142075354.20041215204040@columbus.rr.com> Message-ID: <3449428f0412151746717a9be2@mail.gmail.com> On Wed, 15 Dec 2004 20:40:40 -0500, R. Alan Monroe wrote: > > print "0x%0X" % 12345 > > > displays > > 0x3039 > > > instead of 0x03039 > > > >>> "%05x" % (12345,) > '03039' > > >>> "0x%05x" % (12345,) > '0x03039' > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > My mistake . . . the "." I entered was unnecessary. -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. From bgailer at alum.rpi.edu Thu Dec 16 02:48:09 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu Dec 16 02:46:55 2004 Subject: [Tutor] Leading zero for hex numbers In-Reply-To: <20041215174212.J64331@yamato.yamato.com> References: <20041215174212.J64331@yamato.yamato.com> Message-ID: <6.1.2.0.0.20041215184342.033a9288@mail.mric.net> At 06:47 PM 12/15/2004, Tony Cappellini wrote: >I'm trying to get Python to automatically print a leading 0 for hex >numbers, but it only seems to work for for decimal numbers. Oh? print "%0d" % 12345 gives me 12345 - no leading 0 >print "0x%0X" % 12345 > >displays 0x3039 which it should >instead of 0x03039 and print "0x%05X" % 12345 displays 0x03039 >The Python docs state >The conversion will be zero padded for numeric values, when a 0 is used as >a flag between the % and the conversion type. If you continue in the documentation right after 3 Conversion flags comes 4 Minimum field width Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From gartler at express.cites.uiuc.edu Thu Dec 16 03:56:58 2004 From: gartler at express.cites.uiuc.edu (Marc Gartler) Date: Thu Dec 16 03:57:02 2004 Subject: [Tutor] AttributeError: instance has no __call__ method In-Reply-To: <1103118704.3863.6.camel@juan.sjtu.edu.cn> Message-ID: <2727DAEE-4F0E-11D9-9FAE-000A95C4E51C@express.cites.uiuc.edu> Hi everybody, Prior to this chunk of code 'glass' has been chosen from a list of colors via user input, and I now want to have that choice connect to one of several possible classes: def glass_type(glasstype): if glasstype == 'Red': myglass = RedGlassCost() elif glasstype == 'Blue': myglass = BlueGlassCost() elif glasstype == 'Yellow': myglass = YellowGlassCost() return myglass glasschoice = glass_type(glass) myglass = glasschoice() I've tried various approaches and keep getting different errors. But this one seems closest to my goal, as I know it is at least passing 'glass' into the function: AttributeError: RedGlassCost instance has no __call__ method What is this trying to tell me? Or is that irrelevant as I would be better off trying some other approach altogether? From rdm at rcblue.com Thu Dec 16 04:00:24 2004 From: rdm at rcblue.com (Dick Moores) Date: Thu Dec 16 04:00:37 2004 Subject: [Tutor] Complex roots In-Reply-To: <00ca01c4e06f$a38e9a40$9c8f8651@xp> References: <20041209110126.2DD251E400D@bag.python.org> <1102593135.6535.37.camel@dhcp0320.acl.icnet.uk> <1f7befae041209074162bedff9@mail.gmail.com> <6.1.2.0.2.20041210012337.047ccb00@rcblue.com> <1f7befae04121020454136d1bc@mail.gmail.com> <6.1.2.0.2.20041212002158.046ebb90@rcblue.com> <00ca01c4e06f$a38e9a40$9c8f8651@xp> Message-ID: <6.1.2.0.2.20041215184418.04edabc0@rcblue.com> Alan Gauld wrote at 09:25 12/12/2004: > > Are these "numerical approximation methods" pythonically possible? > > > >Yes and that's how they are normally found - not necessarily with >Python, >but by applying computer simulations of the equations. Generally you >calculate values in ever decreasing increments until you get enough >accuracy. eg you discover a zero crossingh between 3 and 4, then >between 3.3 and 3.4 then between 3.36 and 3.37 and so on... > >Caveat: >You also need to look out for double crossings within a single step >change, so don't make the steps too big. And check the number of >roots you expect versus the number you get as an error detection >scheme. I tried to follow your tips, and came up with pinchCubic.py for approximating the real roots of cubic equations. I'd appreciate any guidance. Dick Moores rdm@rcblue.com From carroll at tjc.com Thu Dec 16 04:19:56 2004 From: carroll at tjc.com (Terry Carroll) Date: Thu Dec 16 04:20:00 2004 Subject: [Tutor] AttributeError: instance has no __call__ method In-Reply-To: <2727DAEE-4F0E-11D9-9FAE-000A95C4E51C@express.cites.uiuc.edu> Message-ID: On Wed, 15 Dec 2004, Marc Gartler wrote: > Hi everybody, > > Prior to this chunk of code 'glass' has been chosen from a list of > colors via user input, and I now want to have that choice connect to > one of several possible classes: > > def glass_type(glasstype): > if glasstype == 'Red': > myglass = RedGlassCost() > elif glasstype == 'Blue': > myglass = BlueGlassCost() > elif glasstype == 'Yellow': > myglass = YellowGlassCost() > return myglass > > glasschoice = glass_type(glass) At this point, glasschoice is set to glass_type(glass), which in turn is something like RedGlassCost(). > AttributeError: RedGlassCost instance has no __call__ method Right; it sounds like you're using RedGlassCost as a function, but it wasn't defined as a function. Can you show us how RedGlassCost is defined? > I've tried various approaches and keep getting different errors. But > this one seems closest to my goal, as I know it is at least passing > 'glass' into the function: My mother always told me to apologize after passing glass. From maxnoel_fr at yahoo.fr Thu Dec 16 04:20:32 2004 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Thu Dec 16 04:20:45 2004 Subject: [Tutor] AttributeError: instance has no __call__ method In-Reply-To: <2727DAEE-4F0E-11D9-9FAE-000A95C4E51C@express.cites.uiuc.edu> References: <2727DAEE-4F0E-11D9-9FAE-000A95C4E51C@express.cites.uiuc.edu> Message-ID: <71992F60-4F11-11D9-9412-000393CBC88E@yahoo.fr> On Dec 16, 2004, at 03:56, Marc Gartler wrote: > Hi everybody, > > Prior to this chunk of code 'glass' has been chosen from a list of > colors via user input, and I now want to have that choice connect to > one of several possible classes: > > def glass_type(glasstype): > if glasstype == 'Red': > myglass = RedGlassCost() > elif glasstype == 'Blue': > myglass = BlueGlassCost() > elif glasstype == 'Yellow': > myglass = YellowGlassCost() > return myglass > > glasschoice = glass_type(glass) > myglass = glasschoice() > > > I've tried various approaches and keep getting different errors. But > this one seems closest to my goal, as I know it is at least passing > 'glass' into the function: > > AttributeError: RedGlassCost instance has no __call__ method > > What is this trying to tell me? Or is that irrelevant as I would be > better off trying some other approach altogether? Can we see your code for the *GlassCost classes? -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" -- maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From maxnoel_fr at yahoo.fr Thu Dec 16 04:28:47 2004 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Thu Dec 16 04:29:01 2004 Subject: [Tutor] AttributeError: instance has no __call__ method In-Reply-To: <71992F60-4F11-11D9-9412-000393CBC88E@yahoo.fr> References: <2727DAEE-4F0E-11D9-9FAE-000A95C4E51C@express.cites.uiuc.edu> <71992F60-4F11-11D9-9412-000393CBC88E@yahoo.fr> Message-ID: <98E9FD2C-4F12-11D9-9412-000393CBC88E@yahoo.fr> On Dec 16, 2004, at 04:20, Max Noel wrote: >> def glass_type(glasstype): >> if glasstype == 'Red': >> myglass = RedGlassCost() >> elif glasstype == 'Blue': >> myglass = BlueGlassCost() >> elif glasstype == 'Yellow': >> myglass = YellowGlassCost() >> return myglass >> >> glasschoice = glass_type(glass) >> myglass = glasschoice() > > Can we see your code for the *GlassCost classes? Nevermind, I just figured out the problem. RedGlassCost() returns an instance of the RedGlassCost class, whereas RedGlassCost is the class itself. Thus, you need to remove the parentheses either in the def_glasstype function (you then return a class, affect it to glasschoice and then create an instance of it by instanciating glasschoice) or in your last line (glass_type returns an instance of the class you want). -- Max From gartler at express.cites.uiuc.edu Thu Dec 16 04:32:29 2004 From: gartler at express.cites.uiuc.edu (Marc Gartler) Date: Thu Dec 16 04:32:32 2004 Subject: [Tutor] AttributeError: instance has no __call__ method In-Reply-To: <71992F60-4F11-11D9-9412-000393CBC88E@yahoo.fr> Message-ID: <1D381C52-4F13-11D9-9FAE-000A95C4E51C@express.cites.uiuc.edu> # --superclass-- class FrameCost: def __init__(self): self.width = int(0) self.length = int(0) # Calculate cost per square foot def Cost_per_sqft(self, cost): return (((self.width) * (self.length) / 144.00) * (cost)) # Calculate cost per linear foot def Cost_per_ft(self, cost): return (((((self.width) * 2.00) + ((self.length) * 2.00)) / 12.00) * (cost)) def Width(self, argt): self.width = argt def Length(self, argt): self.length = argt # --Three subclasses for glass -- class RegGlassCost(FrameCost): def Cost(self): self.cost = 3 # Define costs in dollars return (self.Cost_per_sqft(self.cost)) class BlueGlassCost(FrameCost): def Cost(self): self.cost = 4 return (self.Cost_per_sqft(self.cost)) class YellowGlassCost(FrameCost): def Cost(self): self.cost = 5 return (self.Cost_per_sqft(self.cost)) # -- Another Subclass for Labor -- class LaborCost(FrameCost): def Cost(self): self.cost = 5.25 return (self.Cost_per_sqft(self.cost)) On Wednesday, December 15, 2004, at 09:20 PM, Max Noel wrote: > > Can we see your code for the *GlassCost classes? From gartler at express.cites.uiuc.edu Thu Dec 16 04:50:35 2004 From: gartler at express.cites.uiuc.edu (Marc Gartler) Date: Thu Dec 16 04:50:38 2004 Subject: [Tutor] AttributeError: instance has no __call__ method In-Reply-To: <98E9FD2C-4F12-11D9-9412-000393CBC88E@yahoo.fr> Message-ID: That did it. Thanks, Max. On Wednesday, December 15, 2004, at 09:28 PM, Max Noel wrote: > > On Dec 16, 2004, at 04:20, Max Noel wrote: > >>> def glass_type(glasstype): >>> if glasstype == 'Red': >>> myglass = RedGlassCost() >>> elif glasstype == 'Blue': >>> myglass = BlueGlassCost() >>> elif glasstype == 'Yellow': >>> myglass = YellowGlassCost() >>> return myglass >>> >>> glasschoice = glass_type(glass) >>> myglass = glasschoice() >> >> Can we see your code for the *GlassCost classes? > > Nevermind, I just figured out the problem. RedGlassCost() returns an > instance of the RedGlassCost class, whereas RedGlassCost is the class > itself. Thus, you need to remove the parentheses either in the > def_glasstype function (you then return a class, affect it to > glasschoice and then create an instance of it by instanciating > glasschoice) or in your last line (glass_type returns an instance of > the class you want). > > -- Max > From tim.peters at gmail.com Thu Dec 16 05:14:40 2004 From: tim.peters at gmail.com (Tim Peters) Date: Thu Dec 16 05:14:42 2004 Subject: [Tutor] am I missing another simpler structure? In-Reply-To: <41C0DDCF.9040002@po-box.mcgill.ca> References: <41C0DDCF.9040002@po-box.mcgill.ca> Message-ID: <1f7befae04121520143bf65017@mail.gmail.com> [Brian van den Broek] > in Marc's check_range thread, I had proposed: > > def check_in_range(value): > > in_range = False > if 9 < value < 90: > in_range = True > return in_range > > and DogWalker suggested the better: > > def check_in_range(value): > return 9 < value < 90 > > As I mentioned, I feel as though I have a mental block getting in the > way of coming up with code in the smoother fashion of the second snippet > above. Don't feel frustrated -- using Boolean expressions idiomatically is very much a learned skill. So is adding integers, but *that* got drilled into you over years, and years, and years. It won't take quite as long to sling bools . The worst abuse is one you're perhaps not prone to: having a Boolean expression e, and then writing if e == True: instead of if e: For some reason, that's extremely common in code written by newcomers to Pascal. I haven't seen it nearly as often in Python code, but don't have a theory as to why not. > As I have been making a lot of use of a construct (pattern?) > similar to my code above, wherein I try something, and return True if it > works, False if it doesn't, I've begun to wonder if I am overlooking a > improvement similar to that in DogWalker's suggestion. As an example of > the sort of thing I have been doing: > > import datetime > def is_leap_year(year): > '''-> boolean > > Returns True or False as year is, or is not, a leap year. > ''' > is_leap = True > try: > datetime.date(year, 2, 29) > except ValueError: > is_leap = False > return is_leap > > Please ignore that there is a function in the calendar module to do > exactly this, and that, as that library function does, it could be done > by simply testing if the leap year conditions are met. In the general > case, it doesn't seem that there will always be an easy conditional > test. That's true! You shouldn't work too hard to contrive one either, or the clarity of your code will suffer. > This function here was written so as to illustrate the structure > I'm interested in, without the complications of the details of actual > cases I have used. > > (I hope that's clear enough--it felt much clearer before I'd spent the > time drafting a post.) So far as leap years go, the obvious difference is that February has 29 days in leap years, but only 28 otherwise. You exploit that above by checking whether trying to construct "February 29th" raises an exception. That's fine. At least an equally good way is to note that the difference between March 1 and Februrary 28 is 2 days only in a leap year, so: from datetime import date, timedelta def isleap(year): return (date(3, 1, year) - date(2, 28, year)).days == 2 is another clear way to do it, and so is def isleap(year): return (date(year, 2, 28) + timedelta(1)).month == 2 and so is def isleap(year): return (date(year, 3, 1) - date(year, 2, 1)).days == 29 or even, keying off the observation that only leap years contain 366 days, def isleap(year): return (date(year+1, 1, 1) - date(year, 1, 1)).days == 366 IOW, if you can think of one way to do it with a Boolean expression, it's common to think of more. And, of course, that's the kind of practice that makes it feel natural, over time. From bgailer at alum.rpi.edu Thu Dec 16 05:58:53 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Thu Dec 16 05:57:40 2004 Subject: [Tutor] am I missing another simpler structure? In-Reply-To: <1f7befae04121520143bf65017@mail.gmail.com> References: <41C0DDCF.9040002@po-box.mcgill.ca> <1f7befae04121520143bf65017@mail.gmail.com> Message-ID: <6.1.2.0.0.20041215215806.03376630@mail.mric.net> At 09:14 PM 12/15/2004, Tim Peters wrote: >[Brian van den Broek] > > in Marc's check_range thread, I had proposed: > > > > def check_in_range(value): > > > > in_range = False > > if 9 < value < 90: > > in_range = True > > return in_range > > > > and DogWalker suggested the better: > > > > def check_in_range(value): > > return 9 < value < 90 > > > > As I mentioned, I feel as though I have a mental block getting in the > > way of coming up with code in the smoother fashion of the second snippet > > above. > >Don't feel frustrated -- using Boolean expressions idiomatically is >very much a learned skill. So is adding integers, but *that* got >drilled into you over years, and years, and years. It won't take >quite as long to sling bools . > >The worst abuse is one you're perhaps not prone to: having a Boolean >expression e, and then writing > > if e == True: > >instead of > > if e: > >For some reason, that's extremely common in code written by newcomers >to Pascal. Not to mention coding examples provided by Microsoft in some help topics! [snip] Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From bvande at po-box.mcgill.ca Thu Dec 16 07:06:58 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Thu Dec 16 07:07:04 2004 Subject: [Tutor] am I missing another simpler structure? In-Reply-To: <1f7befae04121520143bf65017@mail.gmail.com> References: <41C0DDCF.9040002@po-box.mcgill.ca> <1f7befae04121520143bf65017@mail.gmail.com> Message-ID: <41C12602.60409@po-box.mcgill.ca> [Brian van den Broek] >>import datetime >>def is_leap_year(year): >> '''-> boolean >> >> Returns True or False as year is, or is not, a leap year. >> ''' >> is_leap = True >> try: >> datetime.date(year, 2, 29) >> except ValueError: >> is_leap = False >> return is_leap Kent Johnson said unto the world upon 2004-12-15 20:16: > I would write > def is_leap_year(year): > try: > datetime.date(year, 2, 29) > return True > except ValueError: > return False Not an adherent of the "only one exit point" doctrine then, hey? I spent a while a few weeks ago with a bug in a function that happened because I'd not noticed that I had two return statements, so I'm leery of this at the moment. (I concede if the function was long enough to hide that from me, it was probably too long.) I also like the conceptual purity of one way in and one way out. But, in my code above, that is indeed purchased at the cost of the ugly and a bit anomalous assignment of True. Tim Peters said unto the world upon 2004-12-15 23:14: > So far as leap years go, the obvious difference is that February has > 29 days in leap years, but only 28 otherwise. You exploit that above > by checking whether trying to construct "February 29th" raises an > exception. That's fine. At least an equally good way is to note that > the difference between March 1 and Februrary 28 is 2 days only in a > leap year, so: > > from datetime import date, timedelta > def isleap(year): > return (date(3, 1, year) - date(2, 28, year)).days == 2 > def isleap(year): > return (date(year+1, 1, 1) - date(year, 1, 1)).days == 366 > > IOW, if you can think of one way to do it with a Boolean expression, > it's common to think of more. And, of course, that's the kind of > practice that makes it feel natural, over time. 4 ways all shorter than mine; well, thank goodness I wasn't asking about this in Perl ;-) Thanks for the examples. Pretty and concise often go together, but they seem not to be want to be seen with me. Implausible though my posting history may make it sound, I've done a fair bit of work in set theory and math. logic. While my proofs work, they are almost never pretty or concise. Seems like my code has similar tendencies. I appreciate the pushes in a better direction. At least I won't be stuck for things to do when it comes time to refactor! Thanks to both, Brian vdB From cyresse at gmail.com Thu Dec 16 07:41:24 2004 From: cyresse at gmail.com (Liam Clarke) Date: Thu Dec 16 07:41:28 2004 Subject: [Tutor] am I missing another simpler structure? In-Reply-To: <41C12602.60409@po-box.mcgill.ca> References: <41C0DDCF.9040002@po-box.mcgill.ca> <1f7befae04121520143bf65017@mail.gmail.com> <41C12602.60409@po-box.mcgill.ca> Message-ID: I find multiple returns to be rather useful - def isOdd(x): if not x % 2: return False return True On Thu, 16 Dec 2004 01:06:58 -0500, Brian van den Broek wrote: > [Brian van den Broek] > > complicated with:> > > >>import datetime > >>def is_leap_year(year): > >> '''-> boolean > >> > >> Returns True or False as year is, or is not, a leap year. > >> ''' > >> is_leap = True > >> try: > >> datetime.date(year, 2, 29) > >> except ValueError: > >> is_leap = False > >> return is_leap > > Kent Johnson said unto the world upon 2004-12-15 20:16: > > I would write > > def is_leap_year(year): > > try: > > datetime.date(year, 2, 29) > > return True > > except ValueError: > > return False > > Not an adherent of the "only one exit point" doctrine then, hey? I spent > a while a few weeks ago with a bug in a function that happened because > I'd not noticed that I had two return statements, so I'm leery of this > at the moment. (I concede if the function was long enough to hide that > from me, it was probably too long.) I also like the conceptual purity of > one way in and one way out. But, in my code above, that is indeed > purchased at the cost of the ugly and a bit anomalous assignment of True. > > Tim Peters said unto the world upon 2004-12-15 23:14: > > > So far as leap years go, the obvious difference is that February has > > 29 days in leap years, but only 28 otherwise. You exploit that above > > by checking whether trying to construct "February 29th" raises an > > exception. That's fine. At least an equally good way is to note that > > the difference between March 1 and Februrary 28 is 2 days only in a > > leap year, so: > > > > from datetime import date, timedelta > > def isleap(year): > > return (date(3, 1, year) - date(2, 28, year)).days == 2 > > > > > def isleap(year): > > return (date(year+1, 1, 1) - date(year, 1, 1)).days == 366 > > > > IOW, if you can think of one way to do it with a Boolean expression, > > it's common to think of more. And, of course, that's the kind of > > practice that makes it feel natural, over time. > > 4 ways all shorter than mine; well, thank goodness I wasn't asking about > this in Perl ;-) > > Thanks for the examples. Pretty and concise often go together, but they > seem not to be want to be seen with me. Implausible though my posting > history may make it sound, I've done a fair bit of work in set theory > and math. logic. While my proofs work, they are almost never pretty or > concise. Seems like my code has similar tendencies. I appreciate the > pushes in a better direction. > > At least I won't be stuck for things to do when it comes time to refactor! > > Thanks to both, > > Brian vdB > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From cyresse at gmail.com Thu Dec 16 08:05:11 2004 From: cyresse at gmail.com (Liam Clarke) Date: Thu Dec 16 08:05:13 2004 Subject: [Tutor] am I missing another simpler structure? In-Reply-To: <7d7029e7041215225855cb2e2d@mail.gmail.com> References: <41C0DDCF.9040002@po-box.mcgill.ca> <1f7befae04121520143bf65017@mail.gmail.com> <41C12602.60409@po-box.mcgill.ca> <7d7029e7041215225855cb2e2d@mail.gmail.com> Message-ID: Alright, so that was a quick example, but.... >return not x % 2 A light dawns. On Thu, 16 Dec 2004 15:58:38 +0900, Guillermo Fernandez Castellanos wrote: > Well... > > > I find multiple returns to be rather useful > > def isOdd(x): > > if not x % 2: return False > > return True > > I find this easier though... > > def isOdd(x): > return not x % 2 > > Enjoy, > > Guille > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From glingl at aon.at Thu Dec 16 08:08:23 2004 From: glingl at aon.at (Gregor Lingl) Date: Thu Dec 16 08:08:18 2004 Subject: [Tutor] A little Tkinter question In-Reply-To: <41C0C1D0.40002@aon.at> References: <41C0C1D0.40002@aon.at> Message-ID: <41C13467.7040003@aon.at> Gregor Lingl schrieb: > > > Marilyn Davis schrieb: > >> Hi Tutors, >> >> I'm reviewing GUIs and wondering: >> >> When you pack a component, and you specify fill = BOTH, how is this >> different from expand = YES? >> > Hi Marilyn, > This is a bit tricky and hard to explain, so I recommend playing around > with this little program from John Grayson's Tkinter book: .... > > and so on. > I forgot to mention, that you should also experiment with resizing the App-Window and see what different results you get with those different options. Regards, Gregor -- Gregor Lingl Reisnerstrasse 3/19 A-1030 Wien Telefon: +43 1 713 33 98 Mobil: +43 664 140 35 27 Autor von "Python f?r Kids" Website: python4kids.net From cyresse at gmail.com Thu Dec 16 09:24:45 2004 From: cyresse at gmail.com (Liam Clarke) Date: Thu Dec 16 09:24:47 2004 Subject: [Tutor] A simpler mousetrap Message-ID: Hi all, I'm writing some code, and I want to take a given path + filename, and change the file extension to *.bak. In doing so, (entirely internal this function), I am assuming - That the file will always have an extension Thathe extension will vary But, it will follow the general DOS format of name.ext So, I came up with this - a="./tc/arc/gab.pct" x=a.replace(a[a.rfind('.'):len(a)],'.bak') x="./tc/arc/gab.bak" So, it works, but it feels a bit, well, hacky to me. Not nearly hacky as using an regex though ; ) I thought about a="./tc/arc/gab.pct" aList=a.split('.') aList[-1]='bak' a=".".join(aList) but I'm wondering if there's a simpler way, as there usually seems to be, and it's always so obvious once I'm shown it, like 6 down - Six on vehicle live in the manse (VI + car). Obvious once you know. Regards, Liam Clarke -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From kraus at hagen-partner.de Thu Dec 16 09:44:03 2004 From: kraus at hagen-partner.de (Wolfram Kraus) Date: Thu Dec 16 09:42:22 2004 Subject: [Tutor] Re: A simpler mousetrap In-Reply-To: References: Message-ID: Liam Clarke wrote: > Hi all, > > I'm writing some code, and I want to take a given path + filename, and > change the file extension to *.bak. > > In doing so, (entirely internal this function), I am assuming - > > That the file will always have an extension > Thathe extension will vary > But, it will follow the general DOS format of name.ext > > So, I came up with this - > > a="./tc/arc/gab.pct" > > x=a.replace(a[a.rfind('.'):len(a)],'.bak') > > x="./tc/arc/gab.bak" > > So, it works, but it feels a bit, well, hacky to me. Not nearly hacky > as using an regex though ; ) > > I thought about > > a="./tc/arc/gab.pct" > > aList=a.split('.') > aList[-1]='bak' > a=".".join(aList) > > but I'm wondering if there's a simpler way, as there usually seems to > be, and it's always so obvious once I'm shown it, like 6 down - Six on > vehicle live in the manse (VI + car). Obvious once you know. > > Regards, > > Liam Clarke Hey Liam! The os.path module is your friend, especially split and splitext: http://docs.python.org/lib/module-os.path.html HTH, Wolfram From bvande at po-box.mcgill.ca Thu Dec 16 09:54:12 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Thu Dec 16 09:54:12 2004 Subject: [Tutor] am I missing another simpler structure? In-Reply-To: References: <41C0DDCF.9040002@po-box.mcgill.ca> <1f7befae04121520143bf65017@mail.gmail.com> <41C12602.60409@po-box.mcgill.ca> <7d7029e7041215225855cb2e2d@mail.gmail.com> Message-ID: <41C14D34.4040704@po-box.mcgill.ca> Liam Clarke said unto the world upon 2004-12-16 02:05: > Alright, so that was a quick example, but.... > > >>return not x % 2 > > > A light dawns. > > On Thu, 16 Dec 2004 15:58:38 +0900, Guillermo Fernandez Castellanos > wrote: > >>Well... >> >> >>>I find multiple returns to be rather useful >>>def isOdd(x): >>> if not x % 2: return False >>> return True >> >>I find this easier though... >> >>def isOdd(x): >> return not x % 2 >> >>Enjoy, >> >>Guille Hi Liam, Guille, and all, Liam, the relationship between the code you put up and the suggestion Guille made closely parallel the my code from Marc's check_range thread and the suggestion DogWalker made. Thinking that our common slip in these two chucks might be more common in my code than I can currently recognize is what moved me to start the present thread. If my original bit of code, the structure was like: output_value = False if condition: output_value = True return output_value Mine would be like yours if transformed to: if condition: return True return False It seems to me that the two structures are inter-substitutable without difference to outcome (speed, readability, and other 'pragmatics' aside -- my structure will be slower for the assignments, for instance). What makes me lean toward mine still? I'd encountered a general injunction to avoid multiple exit point somewhere on the wild web (cannot recall where). At the time, it didn't make sense to me. But, as I posted earlier today in reply to Kent, I was burned by multiple exits a while ago. (To be fair, by multiple exits and overlong functions which obscured the multiplicity from me -- stupid low res monitor!) The best discussion I found with a quick google was . Much of the anti-multiple-exits rational there only applies to languages like C that make the coder manage the memory. But "Having MultipleReturns is the 21 century equivalent of GotoConsideredHarmful" resonates with me. The idea is that multiple returns, particularly when separated by numerous lines of code, makes for spaghetti code. ('Goto Considered Harmful' is a famous short and fairly accessible paper [no math or code] by Dijkstra arguing that the use of Goto's makes code hard to follow . When I first started with Python, I'd not programmed in a decade or so after some highschool BASIC. My first reaction was "where's the bleedin' goto?". Once I coded some and noticed substantially less frustration than I recall from managing my gotos, I learned to appreciate that there wasn't a goto after all.) Anyway, that's plenty of ramble for ce soir. But, Liam, this is the first post I've made in your direction since I read you mention it: congrats for your new son! Best to all, Brian vdB From cyresse at gmail.com Thu Dec 16 10:05:19 2004 From: cyresse at gmail.com (Liam Clarke) Date: Thu Dec 16 10:05:23 2004 Subject: [Tutor] Re: A simpler mousetrap In-Reply-To: References: Message-ID: x=os.path.splitext(a)[0]+'.bak' Ah, jolly good, looks a bit simpler. Thanks! Regards, Liam Clarke On Thu, 16 Dec 2004 09:44:03 +0100, Wolfram Kraus wrote: > Liam Clarke wrote: > > Hi all, > > > > I'm writing some code, and I want to take a given path + filename, and > > change the file extension to *.bak. > > > > In doing so, (entirely internal this function), I am assuming - > > > > That the file will always have an extension > > Thathe extension will vary > > But, it will follow the general DOS format of name.ext > > > > So, I came up with this - > > > > a="./tc/arc/gab.pct" > > > > x=a.replace(a[a.rfind('.'):len(a)],'.bak') > > > > x="./tc/arc/gab.bak" > > > > So, it works, but it feels a bit, well, hacky to me. Not nearly hacky > > as using an regex though ; ) > > > > I thought about > > > > a="./tc/arc/gab.pct" > > > > aList=a.split('.') > > aList[-1]='bak' > > a=".".join(aList) > > > > but I'm wondering if there's a simpler way, as there usually seems to > > be, and it's always so obvious once I'm shown it, like 6 down - Six on > > vehicle live in the manse (VI + car). Obvious once you know. > > > > Regards, > > > > Liam Clarke > > Hey Liam! > > The os.path module is your friend, especially split and splitext: > http://docs.python.org/lib/module-os.path.html > > HTH, > Wolfram > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From glingl at aon.at Thu Dec 16 10:14:45 2004 From: glingl at aon.at (Gregor Lingl) Date: Thu Dec 16 10:14:41 2004 Subject: [Tutor] am I missing another simpler structure? In-Reply-To: <41C14D34.4040704@po-box.mcgill.ca> References: <41C0DDCF.9040002@po-box.mcgill.ca> <1f7befae04121520143bf65017@mail.gmail.com> <41C12602.60409@po-box.mcgill.ca> <7d7029e7041215225855cb2e2d@mail.gmail.com> <41C14D34.4040704@po-box.mcgill.ca> Message-ID: <41C15205.1070400@aon.at> Brian van den Broek schrieb: > If my original bit of code, the structure was like: > > output_value = False > if condition: > output_value = True > return output_value > > Mine would be like yours if transformed to: > > if condition: > return True > return False > Hi Brian! Do you mean, that condition is something which is True od False? And if condition is True you want to return True? And if condition is False you want to return False? So why not simlpy: return condition ? Regards, Gregor From kent37 at tds.net Thu Dec 16 11:48:14 2004 From: kent37 at tds.net (Kent Johnson) Date: Thu Dec 16 11:48:20 2004 Subject: [Tutor] A simpler mousetrap In-Reply-To: References: Message-ID: <41C167EE.8010703@tds.net> As Wolfram pointed out, os.path.splitext() is a good way to do this. It is also more robust than the other solutions because it does the right thing if there is no extension on the original file name. I just want to say that your first solution can be written much more simply as x=a[:a.rfind('.')] + '.bak' Kent Liam Clarke wrote: > Hi all, > > I'm writing some code, and I want to take a given path + filename, and > change the file extension to *.bak. > > In doing so, (entirely internal this function), I am assuming - > > That the file will always have an extension > Thathe extension will vary > But, it will follow the general DOS format of name.ext > > So, I came up with this - > > a="./tc/arc/gab.pct" > > x=a.replace(a[a.rfind('.'):len(a)],'.bak') > > x="./tc/arc/gab.bak" > > So, it works, but it feels a bit, well, hacky to me. Not nearly hacky > as using an regex though ; ) > > I thought about > > a="./tc/arc/gab.pct" > > aList=a.split('.') > aList[-1]='bak' > a=".".join(aList) > > but I'm wondering if there's a simpler way, as there usually seems to > be, and it's always so obvious once I'm shown it, like 6 down - Six on > vehicle live in the manse (VI + car). Obvious once you know. > > Regards, > > Liam Clarke From orion_val at 163.com Thu Dec 16 11:40:01 2004 From: orion_val at 163.com (Juan Shen) Date: Thu Dec 16 11:48:37 2004 Subject: [Tutor] am I missing another simpler structure? In-Reply-To: <41C0E1FF.1060504@tds.net> References: <41C0DDCF.9040002@po-box.mcgill.ca> <41C0E1FF.1060504@tds.net> Message-ID: <41C16601.5080807@163.com> Kent Johnson wrote: > Brian van den Broek wrote: > >> I've begun to wonder if I am overlooking a improvement similar to >> that in DogWalker's suggestion. As an example of the sort of thing I >> have been doing: >> >> import datetime >> def is_leap_year(year): >> '''-> boolean >> >> Returns True or False as year is, or is not, a leap year. >> ''' >> is_leap = True >> try: >> datetime.date(year, 2, 29) >> except ValueError: >> is_leap = False >> return is_leap > > > I would write > def is_leap_year(year): > try: > datetime.date(year, 2, 29) > return True > except ValueError: > return False > > Kent > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > Yeah, I support Kent. Brian's code is obviously C style, define a variable and give it an origin value, then use it, modify its value and so on. If you choose Python, you should adapt to it that variable needn't to be defined specificly before being used! Juan Shen From kent37 at tds.net Thu Dec 16 12:09:12 2004 From: kent37 at tds.net (Kent Johnson) Date: Thu Dec 16 12:09:20 2004 Subject: [Tutor] Multiple returns in a function In-Reply-To: <41C12602.60409@po-box.mcgill.ca> References: <41C0DDCF.9040002@po-box.mcgill.ca> <1f7befae04121520143bf65017@mail.gmail.com> <41C12602.60409@po-box.mcgill.ca> Message-ID: <41C16CD8.7080407@tds.net> Brian van den Broek wrote: > Kent Johnson said unto the world upon 2004-12-15 20:16: > > I would write > > def is_leap_year(year): > > try: > > datetime.date(year, 2, 29) > > return True > > except ValueError: > > return False > > Not an adherent of the "only one exit point" doctrine then, hey? I spent > a while a few weeks ago with a bug in a function that happened because > I'd not noticed that I had two return statements, so I'm leery of this > at the moment. (I concede if the function was long enough to hide that > from me, it was probably too long.) I also like the conceptual purity of > one way in and one way out. But, in my code above, that is indeed > purchased at the cost of the ugly and a bit anomalous assignment of True. Right you are. I wondered if anyone would notice :-) I find multiple returns very handy. They can often reduce the indentation of a block or eliminate the need for flag variables. And I don't see any benefit from having a single return. One simple use of multiple returns is to handle different conditions in a function. Especially for error conditions. I like to handle special cases early in a function. (This is the GuardClause idiom from the web page you cited: http://c2.com/cgi/wiki?GuardClause) For example something like def fn(a, b): if not a: return None if b == 0: return 0 # Calculate result from a and b return result Without the multiple returns this might look like def fn(a, b): if not a: result = None elif b == 0: result = 0 else: # Calculate result return result To me the first version is cleaner and clearer. The exceptional cases are handled unambiguously at the start of the fn, the rest of the code just handles the normal case. Kent From melnyk at gmail.com Thu Dec 16 12:15:18 2004 From: melnyk at gmail.com (Scott Melnyk) Date: Thu Dec 16 12:15:38 2004 Subject: [Tutor] sorting and editing large data files Message-ID: Hello! I recently suffered a loss of programming files (and I had been putting off my backups...) The project I am working on involved the use of programs which I had been assisted with by some of the group. I am rewritten the programs however my results are not what I expected. I would appreciate anyone who could follow through the steps and programs below and tell me if it seems correct, which it does to me. It could be the error is based on a flaw that I had made before. I will give very simplified explanations of the data to help. Starting a file with genetic data about 95 mb A sample of the file format is: >ENSE00001384652.1|ENSG00000166157.5|ENST00000359693.1 assembly=NCBI35|chr=21|strand=reverse|bases 10012801 to 10012624|exons plus upstream and downstream regions for exon GCGGCCGTTCAAGGCAGGGGGCGGGGCGTCTCCGAGCGGCGGGGCCAAGGGAGGGCACAACAGCTGCTACCTGAACAGTTTCTGACCCAACAGTTACCCAGCGCCGGACTCGCTGCGCCCCGGCGGCTCTAGGGACCCCCGGCGCCTACACTTAGCTCCGCGCCCGAGGTGAGCCCAG It is hard to tell due to email formating however from the ">" to the words "regions for exon" is one line, all the GCATs are on one line. ENSExxxxxxx is an exon id tag followed by a ENSGxxxxxgene id tag then a ENSTxxxxxxx transcript id tag followed by information about the location of exon. the letters GCTA are the actually exon sequence. 1 gene can have different versions, these are called transcripts and each transcript contains a number of exons In order to visually understand the data better I made a script to organize it into sections with Gene ID, then Trancript ID followed by the different Exon IDs like so: NEW GENE ENSG00000166157.5 ENST00000359693.1 ENSE00001384652.1 ENSE00001365174.1 ENSE00001372282.1 ENSE00001369818.1 ENSE00001371166.1 ENSE00001369770.1 ENSE00001122873.3 ENSE00001156126.1 ENSE00001156118.1 ENSE00001378322.1 ENSE00001156105.1 ENSE00001156099.1 ENSE00001156092.1 ENSE00001156083.1 ENSE00001156075.1 ENSE00001156069.1 ENSE00001156063.1 ENSE00001156057.1 ENSE00001100323.1 ENSE00001156046.1 ENSE00001126180.1 ENSE00001100365.1 ENSE00001156031.1 ENSE00001231719.5 NEW TRANSCRIPT ENSG00000166157.5 ENST00000298232.4 ENSE00001384652.1 ENSE00001365174.1 ENSE00001372282.1 ENSE00001369818.1 ENSE00001371166.1 ENSE00001369770.1 ENSE00001156126.1 ENSE00001156118.1 ENSE00001378322.1 ENSE00001156105.1 ENSE00001156099.1 ENSE00001156092.1 ENSE00001156083.1 ENSE00001156075.1 ENSE00001156069.1 ENSE00001156063.1 ENSE00001156057.1 ENSE00001100323.1 ENSE00001156046.1 ENSE00001126180.1 ENSE00001100365.1 ENSE00001156031.1 ENSE00001231719.5 NEW TRANSCRIPT ENSG00000166157.5 ENST00000342420.2 ENSE00001384652.1 ENSE00001365174.1 ENSE00001372282.1 ENSE00001369818.1 ENSE00001371166.1 ENSE00001369770.1 ENSE00001156118.1 ENSE00001378322.1 ENSE00001156105.1 ENSE00001156099.1 ENSE00001156092.1 ENSE00001156083.1 ENSE00001156075.1 ENSE00001156069.1 ENSE00001156063.1 ENSE00001156057.1 ENSE00001100323.1 ENSE00001156046.1 ENSE00001126180.1 ENSE00001100365.1 ENSE00001156031.1 ENSE00001231719.5 NEW TRANSCRIPT ENSG00000166157.5 ENST00000339704.2 ENSE00001384652.1 ENSE00001364671.1 ENSE00001387876.1 ENSE00001384389.1 ENSE00001156111.1 ENSE00001156105.1 ENSE00001156099.1 ENSE00001156092.1 ENSE00001156083.1 ENSE00001156075.1 ENSE00001156069.1 ENSE00001156063.1 ENSE00001156057.1 ENSE00001100323.1 ENSE00001156046.1 ENSE00001126180.1 ENSE00001100365.1 ENSE00001156031.1 ENSE00001231719.5 end of gene group NEW GENE ENSG00000187172.4 ENST00000335369.2 ENSE00001428001.1 ENSE00001331994.3 ENSE00001398768.1 ENSE00001429773.1 etc. This was accomplished with the following program I called OrganizeData.py #########################################################3 #execute with python datafile outputfile import re,sys,string #regular expression to pull out gene, transcript and exon ids info=re.compile('^>(ENSE\d+\.\d).+(ENSG\d+\.\d).+(ENST\d+\.\d)') # sample from the file #>>ENSE00001373825.1|ENSG00000187908.1|ENST00000344467.1 file = open( sys.argv[1], 'r' ) #file to read from WriteFile=open(sys.argv[2], 'w') #file to write to #initialize some variables GENEID is the name of the gene, TRANSID is name of the transcript etc sOldGene="" sGENEID="" sOldTrans="" sTRANSID="" sEXONID="" for line in file: if info.match(line): Matched= info.match(line) sEXONID=Matched.group(1) sGENEID=Matched.group(2) sTRANSID=Matched.group(3) if sOldGene==sGENEID: #if current line is the same gene as last line if sOldTrans == sTRANSID: #if current line is same transcript as last line print >> WriteFile, sEXONID, #add new exon to the current transcript line else: print >> WriteFile,"\n\n\tNEW TRANSCRIPT\n", sGENEID, sTRANSID, sEXONID, #new transcript of same gene print 2 #lines down else: print >> WriteFile,"\nend of gene group\n\nNEW GENE\n", sGENEID , sTRANSID, sEXONID, #new gene drop down 4 lines for #readability sOldGene=sGENEID sOldTrans=sTRANSID ########################################################## Within each gene if an exon is present in each transcript it is non informative for my purposes and with help I wrote a script to create two files, a list 1 exonID per line of the exons that are present in each transcript and another that let me look at the data in a different way, namely the gene with the set of redundant exons. THe script is as follows: ##########################################################3 # exon editing script #use set to use calculus style editing import sys, string # #split it up so each exon is checked against the other transcripts for the same gene #if the exon occurs in all transcripts write it to file # #use the format on a line in the file of # NEW GENE # ENSG00000184895.2 ENST00000327563.1 ENSE00001299380.1 # NEW TRANSCRIPT # ENSG00000184895.2 ENST00000341596.1 ENSE00001366589.1 ENSE00001364470.1 # end of gene group # NEW GENE # ENSG00000099715.5 ENST00000333703.3 ENSE00001324247.1 ENSE00001300317.1 ENSE00001317536.1 ENSE00000981568.3 ENSE00000652232.1 ENSE00001091626.2 # NEW TRANSCRIPT # ENSG00000099715.5 ENST00000342434.1 ENSE00001365337.1 ENSE00001387281.1 ENSE00001368624.1 ENSE00001389148.1 ENSE00000981568.3 ENSE00000652232.1 ENSE00001377109.1 #regular expression to pull out gene, transcript and exon ids info=re.compile('^(ENSG\d+\.\d).+(ENST\d+\.\d).+(ENSE\d+\.\d)+') #above is match gene, transcript, then one or more exons #TFILE = open(sys.argv[1], 'r' ) #read the various transcripts from WFILE=open(sys.argv[1], 'w') # file to write 2 careful with 'w' will overwrite old info in file W2FILE=open(sys.argv[2], 'w') #this file will have the names of redundant exons import sets def getintersections(fname='Z:\datasets\h35GroupedDec15b.txt'): exonSets = {} f = open(fname) for line in f: if line.startswith('ENS'): parts = line.split() gene = parts[0] transcript = parts[1] exons = parts[2:] exonSets.setdefault(gene, sets.Set(exons)).intersection(sets.Set(exons)) return exonSets if __name__ == '__main__': es = getintersections('Z:\datasets\h35GroupedDec15b.txt') for k,v in es.items(): print >> WFILE, k,v,"\n\n" for Rexon in v: print >> W2FILE, Rexon #################################################################### The ouput files look like so: First is: ENSG00000160818.4 Set(['ENSE00001054700.1', 'ENSE00001054696.4', 'ENSE00001054703.1', 'ENSE00001377097.1', 'ENSE00001376166.1', 'ENSE00001363386.1', 'ENSE00001054698.3', 'ENSE00001054701.1']) ENSG00000102081.4 Set(['ENSE00000677348.1', 'ENSE00000677356.1', 'ENSE00000677362.1', 'ENSE00000677344.1', 'ENSE00000677352.1', 'ENSE00001256572.2', 'ENSE00001378539.2', 'ENSE00001378572.1', 'ENSE00000677358.1', 'ENSE00001385529.1', 'ENSE00000677354.1', 'ENSE00000677346.1', 'ENSE00000677350.1', 'ENSE00000677366.2', 'ENSE00000677364.1', 'ENSE00000677360.1', 'ENSE00001023649.1']) ENSG00000124159.4 Set(['ENSE00001401662.1', 'ENSE00001366493.2', 'ENSE00000844941.1', 'ENSE00001306994.2', 'ENSE00000844932.1', 'ENSE00000844938.1', 'ENSE00000844930.1', 'ENSE00000906910.1', 'ENSE00000906908.1', 'ENSE00001430846.1', 'ENSE00001224295.6']) etc the gene with the set of what should be exons found in each transcript, ie if there are 4 transcripts the exon must be in all four to be included in the set the second output file should be exons only found in each transcript: ENSE00001054700.1 ENSE00001054696.4 ENSE00001054703.1 ENSE00001377097.1 ENSE00001376166.1 ENSE00001363386.1 ENSE00001054698.3 ENSE00001054701.1 etc. First problem. When I look at the dataset from which these two outputs are created the exons are not present in all transcripts. When I look at the first gene listed in the first output file the first exon ENSE00001054700.1 is present in both the transcripts listed in Z:\datasets\h35GroupedDec15b.txt however the second exon in that list (ENSE00001054696.4) is only found in the first of the two transcripts. as below: NEW GENE ENSG00000160818.4 ENST00000292338.3 ENSE00001363386.1 ENSE00001054698.3 ***ENSE00001054700.1*** ENSE00001054701.1 ENSE00001054703.1 ENSE00001377097.1 ENSE00001376166.1 ***ENSE00001054696.4**** NEW TRANSCRIPT ENSG00000160818.4 ENST00000334588.2 ENSE00001434292.1 ENSE00001054698.3 ***ENSE00001054700.1*** ENSE00001054701.1 ENSE00001054703.1 ENSE00001336475.3 end of gene group Any suggestions on where I am going wrong? Scott From orion_val at 163.com Thu Dec 16 12:16:18 2004 From: orion_val at 163.com (Juan Shen) Date: Thu Dec 16 12:24:53 2004 Subject: [Tutor] AttributeError: instance has no __call__ method In-Reply-To: <2727DAEE-4F0E-11D9-9FAE-000A95C4E51C@express.cites.uiuc.edu> References: <2727DAEE-4F0E-11D9-9FAE-000A95C4E51C@express.cites.uiuc.edu> Message-ID: <41C16E82.20107@163.com> Marc Gartler wrote: > Hi everybody, > > Prior to this chunk of code 'glass' has been chosen from a list of > colors via user input, and I now want to have that choice connect to > one of several possible classes: > > def glass_type(glasstype): > if glasstype == 'Red': > myglass = RedGlassCost() > elif glasstype == 'Blue': > myglass = BlueGlassCost() > elif glasstype == 'Yellow': > myglass = YellowGlassCost() > return myglass > > glasschoice = glass_type(glass) > myglass = glasschoice() > > > I've tried various approaches and keep getting different errors. But > this one seems closest to my goal, as I know it is at least passing > 'glass' into the function: > > AttributeError: RedGlassCost instance has no __call__ method > > What is this trying to tell me? Or is that irrelevant as I would be > better off trying some other approach altogether? > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > I have guessed your meaning by that code. Try the following: glasstype={\ 'Red':RedGlassCost,\ 'Blue':BlueGlassCost,\ 'Yellow':YellowGlassCost} # RedGlassCost ... are types.FunctionType myglass=glasstype[glass]() From orion_val at 163.com Thu Dec 16 12:23:34 2004 From: orion_val at 163.com (Juan Shen) Date: Thu Dec 16 12:32:04 2004 Subject: [Tutor] AttributeError: instance has no __call__ method In-Reply-To: <41C16E82.20107@163.com> References: <2727DAEE-4F0E-11D9-9FAE-000A95C4E51C@express.cites.uiuc.edu> <41C16E82.20107@163.com> Message-ID: <41C17036.2040403@163.com> Juan Shen wrote: > Marc Gartler wrote: > >> Hi everybody, >> >> Prior to this chunk of code 'glass' has been chosen from a list of >> colors via user input, and I now want to have that choice connect to >> one of several possible classes: >> >> def glass_type(glasstype): >> if glasstype == 'Red': >> myglass = RedGlassCost() >> elif glasstype == 'Blue': >> myglass = BlueGlassCost() >> elif glasstype == 'Yellow': >> myglass = YellowGlassCost() >> return myglass >> >> glasschoice = glass_type(glass) >> myglass = glasschoice() >> >> >> I've tried various approaches and keep getting different errors. But >> this one seems closest to my goal, as I know it is at least passing >> 'glass' into the function: >> >> AttributeError: RedGlassCost instance has no __call__ method >> >> What is this trying to tell me? Or is that irrelevant as I would be >> better off trying some other approach altogether? >> >> _______________________________________________ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> > I have guessed your meaning by that code. Try the following: > > glasstype={\ > 'Red':RedGlassCost,\ > 'Blue':BlueGlassCost,\ > 'Yellow':YellowGlassCost} > # RedGlassCost ... are types.FunctionType > myglass=glasstype[glass]() > BTW, if RedGlassCost is types.ClassType, my code also sounds. Juan Shen From kent37 at tds.net Thu Dec 16 13:57:12 2004 From: kent37 at tds.net (Kent Johnson) Date: Thu Dec 16 13:57:20 2004 Subject: [Tutor] am I missing another simpler structure? In-Reply-To: <41C15205.1070400@aon.at> References: <41C0DDCF.9040002@po-box.mcgill.ca> <1f7befae04121520143bf65017@mail.gmail.com> <41C12602.60409@po-box.mcgill.ca> <7d7029e7041215225855cb2e2d@mail.gmail.com> <41C14D34.4040704@po-box.mcgill.ca> <41C15205.1070400@aon.at> Message-ID: <41C18628.8080806@tds.net> It's probably worth pointing out that these two functions are not entirely equivalent: def t1(): if condition: return True return False def t2(): return condition because 'condition' does not have to evaluate to a boolean value, it can be any Python value. Here is a simple example where 'condition' is just the value of a parameter: >>> def t1(a): ... if a: ... return True ... return False ... >>> def t2(a): ... return a ... If a is actually True or False these two functions return the same value: >>> a=True; print t1(a), t2(a) True True >>> a=False; print t1(a), t2(a) False False For other values of a they return different values; t1 will always return True or False, while t2, obviously, returns a: >>> a=1; print t1(a), t2(a) True 1 >>> a=None; print t1(a), t2(a) False None >>> a=[]; print t1(a), t2(a) False [] Usually this is fine; code such as if t1(a): print 'a is True' will work the same with t1 or t2. OTOH, if you explicitly test the return value (which is *not* recommended practice), you will get different results: >>> if t1(100) == True: print '100 is True' ... 100 is True >>> if t2(100) == True: print '100 is True' ... (nothing prints) I recommend *not* testing explicitly for True, and I recommend the t2() form. Then Python will do what you expect. But I thought it was worth pointing out the difference. Kent Gregor Lingl wrote: > > > Brian van den Broek schrieb: > >> If my original bit of code, the structure was like: >> >> output_value = False >> if condition: >> output_value = True >> return output_value >> >> Mine would be like yours if transformed to: >> >> if condition: >> return True >> return False >> > > Hi Brian! > Do you mean, that condition is something which is > True od False? > And if condition is True you want to return True? > And if condition is False you want to return False? > > So why not simlpy: > > return condition > > ? > > Regards, > Gregor > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From loptr.chaote at gmail.com Thu Dec 16 14:42:29 2004 From: loptr.chaote at gmail.com (Loptr Chaote) Date: Thu Dec 16 14:42:32 2004 Subject: [Tutor] am I missing another simpler structure? In-Reply-To: <41C0DDCF.9040002@po-box.mcgill.ca> References: <41C0DDCF.9040002@po-box.mcgill.ca> Message-ID: <76912af8041216054256bb2a6b@mail.gmail.com> On Wed, 15 Dec 2004 19:58:56 -0500, Brian van den Broek wrote: > As I mentioned, I feel as though I have a mental block getting in the > way of coming up with code in the smoother fashion of the second snippet > above. As I have been making a lot of use of a construct (pattern?) > similar to my code above, wherein I try something, and return True if it > works, False if it doesn't, I've begun to wonder if I am overlooking a > improvement similar to that in DogWalker's suggestion. As an example of > the sort of thing I have been doing: This reply might seem embarassingly short compared to the other answers you got. But I would like to point out two things that could be worth thinking about and that could help you "tune in" to a more direct line of thinking. 1) Every operation has a return value [unless purposefully left out] This includes, but is not limited to; mathematical operations (of course), variable assignment, compare blocks, etc.. 2) If you collect the value first, and then use the collect-variable for checking things, chances are you might be able to exclude the collect-variable completely. This also applies to "state flag"-variables (like in_range in your own solution suggestion). Might not be much worth, but it's my two cents. ;) -L.C From orion_val at 163.com Thu Dec 16 14:42:06 2004 From: orion_val at 163.com (Juan Shen) Date: Thu Dec 16 14:50:39 2004 Subject: [Tutor] am I missing another simpler structure? In-Reply-To: <41C18628.8080806@tds.net> References: <41C0DDCF.9040002@po-box.mcgill.ca> <1f7befae04121520143bf65017@mail.gmail.com> <41C12602.60409@po-box.mcgill.ca> <7d7029e7041215225855cb2e2d@mail.gmail.com> <41C14D34.4040704@po-box.mcgill.ca> <41C15205.1070400@aon.at> <41C18628.8080806@tds.net> Message-ID: <41C190AE.6040009@163.com> Kent, Bingle! Python's 'and' and 'or' operation only returns the right value (any kind of value: integer, string, list, excuting a function and so on) not Boolean value (True or False). It's a real fuzzy tip for beginners. See Chapter 4.6 of Dive into Python for futher reading Juan Shen Kent Johnson wrote: > It's probably worth pointing out that these two functions are not > entirely equivalent: > def t1(): > if condition: > return True > return False > > def t2(): > return condition > > because 'condition' does not have to evaluate to a boolean value, it > can be any Python value. > > Here is a simple example where 'condition' is just the value of a > parameter: > >>> def t1(a): > ... if a: > ... return True > ... return False > ... > >>> def t2(a): > ... return a > ... > > If a is actually True or False these two functions return the same value: > >>> a=True; print t1(a), t2(a) > True True > >>> a=False; print t1(a), t2(a) > False False > > For other values of a they return different values; t1 will always > return True or False, while t2, obviously, returns a: > >>> a=1; print t1(a), t2(a) > True 1 > >>> a=None; print t1(a), t2(a) > False None > >>> a=[]; print t1(a), t2(a) > False [] > > Usually this is fine; code such as > if t1(a): print 'a is True' > > will work the same with t1 or t2. OTOH, if you explicitly test the > return value (which is *not* recommended practice), you will get > different results: > >>> if t1(100) == True: print '100 is True' > ... > 100 is True > > >>> if t2(100) == True: print '100 is True' > ... > (nothing prints) > > I recommend *not* testing explicitly for True, and I recommend the > t2() form. Then Python will do what you expect. But I thought it was > worth pointing out the difference. > > Kent > > Gregor Lingl wrote: > >> >> >> Brian van den Broek schrieb: >> >>> If my original bit of code, the structure was like: >>> >>> output_value = False >>> if condition: >>> output_value = True >>> return output_value >>> >>> Mine would be like yours if transformed to: >>> >>> if condition: >>> return True >>> return False >>> >> >> Hi Brian! >> Do you mean, that condition is something which is >> True od False? >> And if condition is True you want to return True? >> And if condition is False you want to return False? >> >> So why not simlpy: >> >> return condition >> >> ? >> >> Regards, >> Gregor >> >> _______________________________________________ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor >> > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From rmkrauter at yahoo.com Thu Dec 16 14:53:11 2004 From: rmkrauter at yahoo.com (Rich Krauter) Date: Thu Dec 16 14:53:12 2004 Subject: [Tutor] sorting and editing large data files In-Reply-To: References: Message-ID: <41C19347.9090506@yahoo.com> Scott Melnyk wrote: > Hello! > > I recently suffered a loss of programming files (and I had been > putting off my backups...) > [snip] > > #regular expression to pull out gene, transcript and exon ids > > info=re.compile('^(ENSG\d+\.\d).+(ENST\d+\.\d).+(ENSE\d+\.\d)+') > #above is match gene, transcript, then one or more exons > > > #TFILE = open(sys.argv[1], 'r' ) #read the various transcripts from > WFILE=open(sys.argv[1], 'w') # file to write 2 careful with 'w' > will overwrite old info in file > W2FILE=open(sys.argv[2], 'w') #this file will have the names of > redundant exons > import sets > def getintersections(fname='Z:\datasets\h35GroupedDec15b.txt'): > exonSets = {} > f = open(fname) > for line in f: > if line.startswith('ENS'): > parts = line.split() > gene = parts[0] > transcript = parts[1] > exons = parts[2:] > exonSets.setdefault(gene, > sets.Set(exons)).intersection(sets.Set(exons)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ > return exonSets Hi Scott, There may be other problems, but here's one thing I noticed: exonSets.setdefault(gene, sets.Set(exons)).intersection(sets.Set(exons)) should be exonSets.setdefault(gene, sets.Set(exons)).intersection_update(sets.Set(exons)) Hope that helps. Rich From glingl at aon.at Thu Dec 16 14:57:32 2004 From: glingl at aon.at (Gregor Lingl) Date: Thu Dec 16 14:57:26 2004 Subject: [Tutor] am I missing another simpler structure? In-Reply-To: <41C18628.8080806@tds.net> References: <41C0DDCF.9040002@po-box.mcgill.ca> <1f7befae04121520143bf65017@mail.gmail.com> <41C12602.60409@po-box.mcgill.ca> <7d7029e7041215225855cb2e2d@mail.gmail.com> <41C14D34.4040704@po-box.mcgill.ca> <41C15205.1070400@aon.at> <41C18628.8080806@tds.net> Message-ID: <41C1944C.9080604@aon.at> Kent Johnson schrieb: > It's probably worth pointing out that these two functions are not > entirely equivalent: > def t1(): > if condition: > return True > return False > > def t2(): > return condition ... > >>> if t1(100) == True: print '100 is True' > ... > 100 is True > > >>> if t2(100) == True: print '100 is True' > ... > (nothing prints) > If you really need this property, you may use type-conversion with bool: >>> t2(100) 100 >>> bool(t2(100)) True >>> So in this case def t3(a): return bool(a) should work correctly Regards, Gregor Remark for Brian: Please note, that Kent wrote about a feature specific to Python, whereas the main part of this thread contains considerations concerning boolean expressions in general. From bwinton at latte.ca Thu Dec 16 15:20:41 2004 From: bwinton at latte.ca (Blake Winton) Date: Thu Dec 16 15:20:44 2004 Subject: [Tutor] am I missing another simpler structure? In-Reply-To: <41C16601.5080807@163.com> References: <41C0DDCF.9040002@po-box.mcgill.ca> <41C0E1FF.1060504@tds.net> <41C16601.5080807@163.com> Message-ID: <41C199B9.6070803@latte.ca> Juan Shen wrote: >>> def is_leap_year(year): >>> is_leap = True >>> try: >>> datetime.date(year, 2, 29) >>> except ValueError: >>> is_leap = False >>> return is_leap >> >> I would write >> def is_leap_year(year): >> try: >> datetime.date(year, 2, 29) >> return True >> except ValueError: >> return False >> > Yeah, I support Kent. Brian's code is obviously C style, define a > variable and give it an origin value, then use it, modify its value and > so on. If you choose Python, you should adapt to it that variable > needn't to be defined specificly before being used! I far prefer the Brian's version, because it lets me set a single breakpoint while I'm debugging, and I can look at the return value before returning it, instead of having to set n breakpoints (or, usually n-1 because I've overlooked the one that's actually being executed) and looking at what's being returned on each line. (Yes, I do the same thing in C and C++, but I originally started using it in Java, and after a few debugging sessions it makes a lot of sense.) Only having one return point from a function is a long-standing convention that is supposed to make programs easier to read/debug/optimize/prove correct. Later, Blake. From op73418 at mail.telepac.pt Thu Dec 16 15:30:22 2004 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Thu Dec 16 15:27:00 2004 Subject: [Tutor] am I missing another simpler structure? In-Reply-To: <76912af8041216054256bb2a6b@mail.gmail.com> References: <41C0DDCF.9040002@po-box.mcgill.ca> <76912af8041216054256bb2a6b@mail.gmail.com> Message-ID: <41C19BFE.8090701@mail.telepac.pt> Loptr Chaote wrote: > On Wed, 15 Dec 2004 19:58:56 -0500, Brian van den Broek > > 1) Every operation has a return value [unless purposefully left out] > This includes, but is not limited to; mathematical operations (of > course), variable assignment, compare blocks, etc.. A small correction: every function has a return value. If left out (that is, no return statement) then it returns None. E.g. >>> def noret(): ... 2 + 2 ... >>> print noret() None >>> Statements have no return value, e.g. >>> a = 1 >>> print a = 1 Traceback ( File "", line 1 print a = 1 ^ SyntaxError: invalid syntax Like the above shows, assigment has no return value -- it's a statement. This is precisely the distinction between a *statement* (like assignment) and an expression (like a function call). Python has this distinction like most languages. A language like Scheme doesn't since everything is an expression. With my best regards, G. Rodrigues From bvande at po-box.mcgill.ca Thu Dec 16 16:23:29 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Thu Dec 16 16:24:47 2004 Subject: [Tutor] am I missing another simpler structure? In-Reply-To: <41C15205.1070400@aon.at> References: <41C0DDCF.9040002@po-box.mcgill.ca> <1f7befae04121520143bf65017@mail.gmail.com> <41C12602.60409@po-box.mcgill.ca> <7d7029e7041215225855cb2e2d@mail.gmail.com> <41C14D34.4040704@po-box.mcgill.ca> <41C15205.1070400@aon.at> Message-ID: <41C1A871.7010800@po-box.mcgill.ca> Gregor Lingl said unto the world upon 2004-12-16 04:14: > Brian van den Broek schrieb: > >> If my original bit of code, the structure was like: >> >> output_value = False >> if condition: >> output_value = True >> return output_value >> >> Mine would be like yours if transformed to: >> >> if condition: >> return True >> return False >> > > Hi Brian! > Do you mean, that condition is something which is > True od False? > And if condition is True you want to return True? > And if condition is False you want to return False? > > So why not simlpy: > > return condition > > ? > > Regards, > Gregor Hi Gregor, why not indeed? As I see what I've been blithering on about, there are two issues in the air: 1) single exit versus multiple exit functions, and 2) my seemingly entrenched tendency to overlook that I can do just what you point out. The above was reply to Liam's: > I find multiple returns to be rather useful - > > def isOdd(x): > > if not x % 2: return False > > return True *If* one isn't doing what you suggest (through a dogged determination to fail to learn from the past, I imagine ;-), I still prefer the single exit point way I give above. But, as Guille pointed out to Liam, neither of these ways are needed when your way is available, too. So, I like my way of being foolish and inefficient better, given a commitment to foolish inefficiency ;-) (FWIW, I did manage to start this thread with code where the condition was of the form "this try block doesn't raise an exception" so, unless using one of Tim's helpful suggestions, no function with a single line that returns would do.) On the plus side, publicly getting the same style of correction multiple times in a few days greatly increases the chance that some of this might actually making it into my own practise! So, thanks to all who've responded. Best, Brian vdB From bvande at po-box.mcgill.ca Thu Dec 16 16:55:56 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Thu Dec 16 16:57:15 2004 Subject: [Tutor] am I missing another simpler structure? In-Reply-To: <41C199B9.6070803@latte.ca> References: <41C0DDCF.9040002@po-box.mcgill.ca> <41C0E1FF.1060504@tds.net> <41C16601.5080807@163.com> <41C199B9.6070803@latte.ca> Message-ID: <41C1B00C.4080306@po-box.mcgill.ca> Blake Winton said unto the world upon 2004-12-16 09:20: > Juan Shen wrote: > >>> >> Yeah, I support Kent. Brian's code is obviously C style, define a >> variable and give it an origin value, then use it, modify its value >> and so on. If you choose Python, you should adapt to it that variable >> needn't to be defined specificly before being used! Hi Juan and Blake, Juan: I wish my problem were coming from competency in C infecting my approach to Python! Apart from some happily ill-remembered BASIC, I am unlingual as a programmer. > I far prefer the Brian's version, because it lets me set a single > breakpoint while I'm debugging, and I can look at the return value > before returning it, instead of having to set n breakpoints (or, usually > n-1 because I've overlooked the one that's actually being executed) and > looking at what's being returned on each line. (Yes, I do the same > thing in C and C++, but I originally started using it in Java, and after > a few debugging sessions it makes a lot of sense.) Only having one > return point from a function is a long-standing convention that is > supposed to make programs easier to read/debug/optimize/prove correct. Blake, the point about making debugging easier is what I was (trying to be) pointing towards. Thanks for making it clearly, unencumbered by the sort of basic efficiency error (of overlooking that I can just return the boolean result of some condition) that I keep putting into my examples ;-) Best to all, Brian vdB From pythontut at pusspaws.net Thu Dec 16 19:43:52 2004 From: pythontut at pusspaws.net (Dave S) Date: Thu Dec 16 19:44:00 2004 Subject: [Tutor] Python structure advice ? In-Reply-To: <41C0C2BE.2020107@pusspaws.net> References: <41C0C2BE.2020107@pusspaws.net> Message-ID: <41C1D768.4060203@pusspaws.net> Dave S wrote: > Im sorry to bang on about Python structure, but I do struggle with it, > having in the past got into very bad habits with loads of BASIC where > everything was global, and Forth, and hand coded 8031, 8051, 6502 .... > I cant get my head round how you guys handle a modern structured > language :-) > (PS before anyone flames me - I think Python is great and am > determined to learn it ;-) ) > > I have ended up with my application in several separate directories. > > I have 'live_datad' a demon that extracts web data, at preset times > and archives it, this will be run as a thread, and possible using a > queue ... (still digesting info from query about IPCing) > > I have a 'data_core' which accepts data from either live_datad real > time or the archive for testing, it builds up a large multi > dimensional array with various pointers into the array. > > I have a statistical module 'data_stats' which analises the array > pulling various stats. > > And finally I have an analytical module 'data_predict' which using the > output from 'data_stats' & data directly from the 'data_core' outputs > statistical predictions of future data. > > I have written my 'live_datad', I have written my 'data_core' & have a > fairly good idea how to write the rest. > > My problem is that pretty much all the modules need to fix where they > are when they exit and pick up from that point later on, ie more data > comes from live_datad, it is passed to 'data_core' which updates the > matrix, then 'data_stats' then 'data_predict' all called form the > main script. This OK till the main script realizes that more data is > avalible from 'live_datad', passes it to 'data_core' which must > remember where it was and move on, and the same for the rest of the > modules. To make the problem more acute the modules may not be called > in exactly the same order depending on what I am trying to achieve. > > The 'remembering where is was' seems a continuous stumbling block for > me. I have though of coding each module as a class but this seems like > a cheat. I could declare copious globals, this seems messy, I could > define each module as a thread & get them talking via queues, given > this serious thought but heeded warning in previous posts. I have > thought about returning an list of saved 'pointers' which would be > re-submitted when the function is called. I don't know which way to turn. > > With my code now running to a few hundred lines (Don't laugh this is > BIG for me :-D ) I am going to have to make a structure decision and > any suggestions would be appreciated. > > How would you approach it ? > > Dave > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > Having written this email, it has put my thoughts in order, though it seems a bit cheaty, wouldn't defining all modules that have to remember their internal state as classes be the best bet ? Dave From kent37 at tds.net Thu Dec 16 20:08:24 2004 From: kent37 at tds.net (Kent Johnson) Date: Thu Dec 16 20:08:20 2004 Subject: [Tutor] Python structure advice ? In-Reply-To: <41C1D768.4060203@pusspaws.net> References: <41C0C2BE.2020107@pusspaws.net> <41C1D768.4060203@pusspaws.net> Message-ID: <41C1DD28.6090504@tds.net> Dave S wrote: > Dave S wrote: >> The 'remembering where is was' seems a continuous stumbling block for >> me. I have though of coding each module as a class but this seems like >> a cheat. I could declare copious globals, this seems messy, I could >> define each module as a thread & get them talking via queues, given >> this serious thought but heeded warning in previous posts. I have >> thought about returning an list of saved 'pointers' which would be >> re-submitted when the function is called. I don't know which way to turn. >> > Having written this email, it has put my thoughts in order, though it > seems a bit cheaty, wouldn't defining all modules that have to remember > their internal state as classes be the best bet ? > > Dave Why do you say this is 'cheaty'? A class is basically a collection of data (state) and functions to operate on that state. You might be interested in this essay: http://www.pycs.net/users/0000323/stories/15.html It might well make sense to organize your program as a collection of cooperating classes, or maybe a collection of classes with a top-level function that stitches them all together. You might also want to learn about iterator classes and generator functions, they are a technique for returning a bit of data at a time while maintaining state. You might be able to structure your input stage as an iterator or generator. http://docs.python.org/tut/node11.html#SECTION0011900000000000000000 http://docs.python.org/lib/typeiter.html Kent From aslyfox100 at yahoo.co.uk Thu Dec 16 20:24:37 2004 From: aslyfox100 at yahoo.co.uk (alex biggerstaff) Date: Thu Dec 16 20:24:40 2004 Subject: [Tutor] hello i need help Message-ID: <20041216192437.1931.qmail@web26104.mail.ukl.yahoo.com> is it possible 2 write a script for wordpad or something, i only started so i dont know much i do know a little about if ($1 == hi) && (?2 == m8) but im not sure how 2 make this apply to other programs. i can only write scripts on a thing called mIRC. ne help would b great thnxs --------------------------------- ALL-NEW Yahoo! Messenger - all new features - even more fun! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041216/1b4414f2/attachment-0001.htm From dyoo at hkn.eecs.berkeley.edu Thu Dec 16 20:40:02 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Dec 16 20:40:14 2004 Subject: [Tutor] sorting and editing large data files In-Reply-To: Message-ID: On Thu, 16 Dec 2004, Scott Melnyk wrote: > I recently suffered a loss of programming files (and I had been > putting off my backups...) Hi Scott, [Side note that's not really related to Python: if you don't use a version control system to manage your software yet, please learn to use one. There's a very good one called Subversion: http://subversion.tigris.org/ A good version control system is invaluable to programmers, since many programs are not really written once, but are rather maintained and revised for a long time.] Rich Krauter already caught the bug that was occurring: the intersection() method of sets produces a brand new set, rather than do a mutation on the old set. Here are some more comments on the programs you've shown us: > A sample of the file format is: > > >ENSE00001384652.1|ENSG00000166157.5|ENST00000359693.1 > assembly=NCBI35|chr=21|strand=reverse|bases 10012801 to 10012624|exons > plus upstream and downstream regions for exon > GCGGCCGTTCAAGGCAGGGGGCGGGGCGTCTCCGAGCGGCGGGGCCAAGGGAGGGCACAACAGCTGCTACCTGAACAGTTTCTGACCCAACAGTTACCCAGCGCCGGACTCGCTGCGCCCCGGCGGCTCTAGGGACCCCCGGCGCCTACACTTAGCTCCGCGCCCGAGGTGAGCCCAG Ah, ok, so this is a FASTA file. (For others on the list, see: http://ngfnblast.gbf.de/docs/fasta.html for a description of the BLAST format.) > ENSExxxxxxx is an exon id tag followed by a ENSGxxxxxgene id tag then > a ENSTxxxxxxx transcript id tag followed by information about the > location of exon. [text cut] Ok, so it sounds like your program will mostly pay attention to each description line in the FASTA file. > In order to visually understand the data better I made a script to > organize it into sections with Gene ID, then Trancript ID followed by > the different Exon IDs like so: [lots of text cut] There's one big assumption in the code to OrganizeData.py that may need to be explicitely stated: the code appears to assume that the sequences are already sorted and grouped in order, since the code maintains a variable named 'sOldGene' and maintains some state on the last FASTA sequence that has been seen. Is your data already sorted? As a long term suggestion: you may find it easier to write the extracted data out as something that will be easy to work with for the next stages of your pipeline. Human readability is important too, of course, so there's a balance necessary between machine and numan convenience. If possible, you may want to make every record a single line, rather than have a record spread across several lines. Your program does do this in some part, but it also adds other output, like announcements to signal the start of new genes. That can complicates later stages of your analysis. Eric Raymond has summarized the rules-of-thumb that the Unix utitilies try to follow: http://www.faqs.org/docs/artu/ch05s02.html#id2907428 As a concrete counterexample, the 'BLAST' utility that bioinformaticians use has a default output that's very human readable, but so ad-hoc that programs that try to use BLAST output often have to resort to fragile, hand-crafted BLAST parsers. The situation's a lot better now, since newer versions of BLAST finally support a structured format. So I'd strongly recommend dropping the "NEW GENE", "end of gene group", and "NEW TRANSCRIPT" lines out of your output. And if you really want to keep them, you can write a separate program that adds those notes back into the output of OrganizeData.py for a human reader. If you drop those decorations out, then the other parts of your pipeline can be simplified, since you can assume that each line of the input file is data. The other stages of your analysis pipeline appear to try to ignore those lines anyway, so why put them in? *grin* From jasonchild at cnsp.com Thu Dec 16 20:42:46 2004 From: jasonchild at cnsp.com (Jason Child) Date: Thu Dec 16 20:42:48 2004 Subject: [Tutor] hello i need help In-Reply-To: <20041216192437.1931.qmail@web26104.mail.ukl.yahoo.com> References: <20041216192437.1931.qmail@web26104.mail.ukl.yahoo.com> Message-ID: <41C1E536.3000303@cnsp.com> alex biggerstaff wrote: > is it possible 2 write a script for wordpad or something, i only > started so i dont know much > i do know a little about if ($1 == hi) && (?2 == m8) > but im not sure how 2 make this apply to other programs. i can only > write scripts on a thing called mIRC. > ne help would b great > thnxs > > * ALL-NEW Yahoo! Messenger * > * - > all new features - even more fun!* * * > >------------------------------------------------------------------------ > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > I do not belive that Notepad supports scripting. Take a look at: http://www.python.org/moin/PythonEditors in particular you may want to look at JeXt, Syn or Zues. From ARobert at MFS.com Thu Dec 16 20:54:57 2004 From: ARobert at MFS.com (Robert, Andrew) Date: Thu Dec 16 20:55:29 2004 Subject: [Tutor] hello i need help Message-ID: <968452DD78695147AA4A369C3DF9E40A0239C5C7@BOSMAILBOX3.corp.mfs.com> I recommend you use vim. You can get it at http://www.vim.org/download.php Thank you, Andrew Robert Systems Architect Information Technology - OpenVMS Massachusetts Financial Services Phone: 617-954-5882 Pager: 781-764-7321 E-mail: arobert@mfs.com Linux User Number: #201204 -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of Jason Child Sent: Thursday, December 16, 2004 2:43 PM To: tutor@python.org Subject: Re: [Tutor] hello i need help alex biggerstaff wrote: > is it possible 2 write a script for wordpad or something, i only > started so i dont know much > i do know a little about if ($1 == hi) && (?2 == m8) > but im not sure how 2 make this apply to other programs. i can only > write scripts on a thing called mIRC. > ne help would b great > thnxs > > * ALL-NEW Yahoo! Messenger * > * - > all new features - even more fun!* * * > >------------------------------------------------------------------------ > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > I do not belive that Notepad supports scripting. Take a look at: http://www.python.org/moin/PythonEditors in particular you may want to look at JeXt, Syn or Zues. _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor "MFS Relay Service" made the following annotations on 12/16/2004 03:01:08 PM ------------------------------------------------------------------------------ This email communication and any attachments may contain proprietary, confidential, or privileged information. If you are not the intended recipient, you are hereby notified that you have received this email in error and that any review, disclosure, dissemination, distribution or copying of it or its contents is prohibited. The sender does not waive confidentiality or any privilege by mistransmission. If you have received this email in error, please notify the sender immediately, delete this email, and destroy all copies and any attachments. ============================================================================== From jeff at ccvcorp.com Thu Dec 16 21:07:54 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu Dec 16 21:04:09 2004 Subject: [Tutor] am I missing another simpler structure? In-Reply-To: <41C199B9.6070803@latte.ca> References: <41C0DDCF.9040002@po-box.mcgill.ca> <41C0E1FF.1060504@tds.net> <41C16601.5080807@163.com> <41C199B9.6070803@latte.ca> Message-ID: <41C1EB1A.3020909@ccvcorp.com> Blake Winton wrote: >>>> def is_leap_year(year): >>>> is_leap = True >>>> try: >>>> datetime.date(year, 2, 29) >>>> except ValueError: >>>> is_leap = False >>>> return is_leap >>> >>> >>> I would write >>> def is_leap_year(year): >>> try: >>> datetime.date(year, 2, 29) >>> return True >>> except ValueError: >>> return False >>> If one insists on single-return style, then I'd prefer to do it this way: def is_leap_year(year): try: datetime.date(year, 2, 29) is_leap = True except ValueError: is_leap = False return is_leap You still have to type 'is_leap' multiple times, but at least it's a little bit more clear which conditions will result in it being True or False. > [...] Only having one > return point from a function is a long-standing convention that is > supposed to make programs easier to read/debug/optimize/prove correct. Indeed, it is supposed (by some) to be better, and is thought by others to sometimes make things more complicated. In the above code, a single return point gives you one place to set breakpoints during debugging, etc, but it also means that you introduce a new variable that you must type at least three times, introducing multiple opportunities for typos. As with most programming choices, single-return has both a benefit and a cost. In some situations the cost can be very large relative to the benefit; in others the cost is very small. I find it best not to be too dogmatic about most such stylistic questions -- I try to stay aware of the costs of a particular approach, but I'll happily use it when the net effect is to make the code simpler and more understandable. Similar to the example that Kent later points out, in my work life I often find myself writing functions (to use as the body of a loop) where a number of unrelated tests must be done before proceeding with processing. (This is actually in an old, crufty dialect of Basic, but the same principle applies) I have a few choices in this case. I can simply write the loop body in-line and use gotos to skip segments if the tests fail (ew). I can write the loop body in-line and use multiply nested if/else statements, but it can get difficult to track what nesting level I'm at. I can use nested functions, each with just one test in it, something like this: def func1(data): result = None if test1: result = func2(data) return result def func2(data): result = None if test2: result = func3(data) return result def func3(data): [...] This gets pretty darn ugly to trace through, especially when I've got six or eight different tests. Or, I can simply use multiple returns: def func(data) if not test1: return if not test2: return if not test3: return # do stuff with data... It really does make it much simpler to track through the code, since I don't care, later in the function, about the specific results of each test, only about whether I should continue afterwards or not. In this case, I'm weighing the cost of multiple returns against the cost of multiple nestings or of using flag variables, and I find multiple returns to be the lowest-cost option. Jeff Shannon Technician/Programmer Credit International From john.ertl at fnmoc.navy.mil Thu Dec 16 21:26:13 2004 From: john.ertl at fnmoc.navy.mil (Ertl, John) Date: Thu Dec 16 21:26:27 2004 Subject: [Tutor] removedirs ? Message-ID: I am trying to remove a directory that has other directories and files in it. I thought removedirs was supposed to do a recursive remove of files and directories. When I try it I get >>> os.removedirs("DAF") Traceback (most recent call last): File "", line 1, in -toplevel- os.removedirs("DAF") File "/home/ertlj/ertljVersion/lib/python2.3/os.py", line 167, in removedirs rmdir(name) OSError: [Errno 17] File exists: 'DAF' Thanks, John Ertl From jasonchild at cnsp.com Thu Dec 16 21:36:15 2004 From: jasonchild at cnsp.com (Jason Child) Date: Thu Dec 16 21:36:17 2004 Subject: [Tutor] removedirs ? In-Reply-To: References: Message-ID: <41C1F1BF.1050100@cnsp.com> Ertl, John wrote: >I am trying to remove a directory that has other directories and files in >it. I thought removedirs was supposed to do a recursive remove of files and >directories. > >When I try it I get > > > >>>>os.removedirs("DAF") >>>> >>>> > >Traceback (most recent call last): > File "", line 1, in -toplevel- > os.removedirs("DAF") > File "/home/ertlj/ertljVersion/lib/python2.3/os.py", line 167, in >removedirs > rmdir(name) >OSError: [Errno 17] File exists: 'DAF' > >Thanks, > >John Ertl > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > it seems to me that if its on a *nix box you could use the shell command rm -rf From john.ertl at fnmoc.navy.mil Thu Dec 16 21:42:46 2004 From: john.ertl at fnmoc.navy.mil (Ertl, John) Date: Thu Dec 16 21:42:58 2004 Subject: [Tutor] removedirs ? Message-ID: Jason, I could...That is the exact feature I am trying to replicate, but I would just like to do it in Python if I can (in a simple way). I am writing this code in Python to avoid some funny scripting that I would need to do. To go back to combing shell and Python again would be a bit deflating...but the straight forward path might be the best. Thanks, John Ertl -----Original Message----- From: Jason Child [mailto:jasonchild@cnsp.com] Sent: Thursday, December 16, 2004 12:36 Cc: tutor@python.org Subject: Re: [Tutor] removedirs ? Ertl, John wrote: >I am trying to remove a directory that has other directories and files in >it. I thought removedirs was supposed to do a recursive remove of files and >directories. > >When I try it I get > > > >>>>os.removedirs("DAF") >>>> >>>> > >Traceback (most recent call last): > File "", line 1, in -toplevel- > os.removedirs("DAF") > File "/home/ertlj/ertljVersion/lib/python2.3/os.py", line 167, in >removedirs > rmdir(name) >OSError: [Errno 17] File exists: 'DAF' > >Thanks, > >John Ertl > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > it seems to me that if its on a *nix box you could use the shell command rm -rf _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From kent37 at tds.net Thu Dec 16 21:50:23 2004 From: kent37 at tds.net (Kent Johnson) Date: Thu Dec 16 21:50:27 2004 Subject: [Tutor] removedirs ? In-Reply-To: References: Message-ID: <41C1F50F.1070905@tds.net> You misunderstand what removedirs does. It removes an empty directory; then, if the removed directory's parent is now empty, it removes that, too, and so on until it finds a directory with something in it or gets up to the root. Try shutil.rmtree() or this recipe: http://aspn.activestate.com/ASPN/docs/ActivePython/2.2/PyWin32/Recursive_directory_deletes_and_special_files.html Kent Ertl, John wrote: > I am trying to remove a directory that has other directories and files in > it. I thought removedirs was supposed to do a recursive remove of files and > directories. > > When I try it I get > > >>>>os.removedirs("DAF") > > > Traceback (most recent call last): > File "", line 1, in -toplevel- > os.removedirs("DAF") > File "/home/ertlj/ertljVersion/lib/python2.3/os.py", line 167, in > removedirs > rmdir(name) > OSError: [Errno 17] File exists: 'DAF' > > Thanks, > > John Ertl > From jasonchild at cnsp.com Thu Dec 16 22:10:44 2004 From: jasonchild at cnsp.com (Jason Child) Date: Thu Dec 16 22:10:45 2004 Subject: [Tutor] removedirs ? In-Reply-To: References: Message-ID: <41C1F9D3.7040701@cnsp.com> is this what you want to do? import os from os.path import join # Delete everything reachable from the directory named in 'top'. # CAUTION: This is dangerous! For example, if top == '/', it # could delete all your disk files. for root, dirs, files in os.walk(top, topdown=False): for name in files: os.remove(join(root, name)) for name in dirs: os.rmdir(join(root, name)) I cant take credit for the code, as I found it when I was trying to hack together a recirsive file remover script. It was in the help files for the os module, under walk(). Go figure; when you try to do things the "hard way" python keeps it simple! Peace Jason Ertl, John wrote: >Jason, > >I could...That is the exact feature I am trying to replicate, but I would >just like to do it in Python if I can (in a simple way). I am writing this >code in Python to avoid some funny scripting that I would need to do. To go >back to combing shell and Python again would be a bit deflating...but the >straight forward path might be the best. > >Thanks, > >John Ertl > > >-----Original Message----- >From: Jason Child [mailto:jasonchild@cnsp.com] >Sent: Thursday, December 16, 2004 12:36 >Cc: tutor@python.org >Subject: Re: [Tutor] removedirs ? > >Ertl, John wrote: > > > >>I am trying to remove a directory that has other directories and files in >>it. I thought removedirs was supposed to do a recursive remove of files >> >> >and > > >>directories. >> >>When I try it I get >> >> >> >> >> >>>>>os.removedirs("DAF") >>>>> >>>>> >>>>> >>>>> >>Traceback (most recent call last): >> File "", line 1, in -toplevel- >> os.removedirs("DAF") >> File "/home/ertlj/ertljVersion/lib/python2.3/os.py", line 167, in >>removedirs >> rmdir(name) >>OSError: [Errno 17] File exists: 'DAF' >> >>Thanks, >> >>John Ertl >> >> >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor >> >> >> >> >> >it seems to me that if its on a *nix box you could use the shell command >rm -rf >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > From mdcooper at uvic.ca Thu Dec 16 22:21:54 2004 From: mdcooper at uvic.ca (mdcooper) Date: Thu Dec 16 22:21:58 2004 Subject: [Tutor] least squares Message-ID: <41C427B6@wm2.uvic.ca> Hi there, I am trying to run a least squares program (written by Konrad Hinsen) but I would like to only have positive values returned. Can anyone help is altering the code to do this? Thanks, matthew From dyoo at hkn.eecs.berkeley.edu Thu Dec 16 22:34:26 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Dec 16 22:34:34 2004 Subject: [Tutor] least squares In-Reply-To: <41C427B6@wm2.uvic.ca> Message-ID: On Thu, 16 Dec 2004, mdcooper wrote: > I am trying to run a least squares program (written by Konrad Hinsen) Hi Matthew, You're assuming that we know who Konrad Hinsen is. *grin* Ok, when you're referring to the least-squared code, are you referring to a module in Scientific Python? Please point us to the code that you're running, and we can give better help. Most of us are just learning Python, so many of us may not really be familiar with the tools that you are using. Make it easier for us to help you! *grin* > but I would like to only have positive values returned. Can anyone help > is altering the code to do this? This shouldn't be too bad: it sounds like a filtering of the return value is what you're looking for. Show us a concrete example of what you're getting so far, and what you want to get. Good luck to you. From jasonchild at cnsp.com Thu Dec 16 22:42:30 2004 From: jasonchild at cnsp.com (Jason Child) Date: Thu Dec 16 22:42:32 2004 Subject: [Tutor] least squares In-Reply-To: <41C427B6@wm2.uvic.ca> References: <41C427B6@wm2.uvic.ca> Message-ID: <41C20146.8070803@cnsp.com> well, not sure if there is a module with the function you are looking for, but... #sloppy as hell method: #... if str(my_returned_value).find("-") != -1: return my_returned_value #or whatever you want to do with it #... #slightly less sloppy as hell method: if my_returned_value < 0: return my_returned_value mdcooper wrote: >Hi there, > >I am trying to run a least squares program (written by Konrad Hinsen) but I >would like to only have positive values returned. Can anyone help is altering >the code to do this? > >Thanks, > >matthew > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > From mdcooper at uvic.ca Thu Dec 16 23:23:57 2004 From: mdcooper at uvic.ca (mdcooper) Date: Thu Dec 16 23:24:07 2004 Subject: [Tutor] least squares Message-ID: <41C4631D@wm2.uvic.ca> Hi Danny, Thanks for the reply - I was purposely vague just to see what people would ask for. The code uses LinearAlgebra.py from Numeric and LeastSquares.py from Scientific. I am trying to get a corrolation between a large number of variables and for many similar equations : (Ca1 * xa^2) + (Ca2 * ya^2) + (Ca3 * za^2) + ... = ta (Cb1 * xb^2) + (Cb2 * yb^2) + (Cb3 * zb^2) + ... = tb which is solved to get: (C1 * x^2) + (C2 * y^2) + (C3 * z^2) + ... = t where the submitted values of x,y, and z should give the correct t and I am using the code to get C1, C2, C3, .... These constants are not allowed to be negative and the submitted equations are such that there is no reason for the values to be negative, and although a good fit may allow them to be negative, another good fit will be found if they are all positive. I need them to be all positive but also all to exist, so filtering out the negative numbers is not sufficient. Thanks, Matt >===== Original Message From Danny Yoo ===== >On Thu, 16 Dec 2004, mdcooper wrote: > >> I am trying to run a least squares program (written by Konrad Hinsen) > >Hi Matthew, > >You're assuming that we know who Konrad Hinsen is. *grin* Ok, when you're >referring to the least-squared code, are you referring to a module in >Scientific Python? > >Please point us to the code that you're running, and we can give better >help. Most of us are just learning Python, so many of us may not really >be familiar with the tools that you are using. Make it easier for us to >help you! *grin* > > >> but I would like to only have positive values returned. Can anyone help >> is altering the code to do this? > >This shouldn't be too bad: it sounds like a filtering of the return value >is what you're looking for. Show us a concrete example of what you're >getting so far, and what you want to get. > > > >Good luck to you. From mdcooper at uvic.ca Thu Dec 16 23:24:14 2004 From: mdcooper at uvic.ca (mdcooper) Date: Thu Dec 16 23:24:22 2004 Subject: [Tutor] least squares Message-ID: <41C46364@wm2.uvic.ca> Hi Danny, Thanks for the reply - I was purposely vague just to see what people would ask for. The code uses LinearAlgebra.py from Numeric and LeastSquares.py from Scientific. I am trying to get a corrolation between a large number of variables and for many similar equations : (Ca1 * xa^2) + (Ca2 * ya^2) + (Ca3 * za^2) + ... = ta (Cb1 * xb^2) + (Cb2 * yb^2) + (Cb3 * zb^2) + ... = tb which is solved to get: (C1 * x^2) + (C2 * y^2) + (C3 * z^2) + ... = t where the submitted values of x,y, and z should give the correct t and I am using the code to get C1, C2, C3, .... These constants are not allowed to be negative and the submitted equations are such that there is no reason for the values to be negative, and although a good fit may allow them to be negative, another good fit will be found if they are all positive. I need them to be all positive but also all to exist, so filtering out the negative numbers is not sufficient. Thanks, Matt >===== Original Message From Danny Yoo ===== >On Thu, 16 Dec 2004, mdcooper wrote: > >> I am trying to run a least squares program (written by Konrad Hinsen) > >Hi Matthew, > >You're assuming that we know who Konrad Hinsen is. *grin* Ok, when you're >referring to the least-squared code, are you referring to a module in >Scientific Python? > >Please point us to the code that you're running, and we can give better >help. Most of us are just learning Python, so many of us may not really >be familiar with the tools that you are using. Make it easier for us to >help you! *grin* > > >> but I would like to only have positive values returned. Can anyone help >> is altering the code to do this? > >This shouldn't be too bad: it sounds like a filtering of the return value >is what you're looking for. Show us a concrete example of what you're >getting so far, and what you want to get. > > > >Good luck to you. From keridee at jayco.net Thu Dec 16 02:46:04 2004 From: keridee at jayco.net (Jacob S.) Date: Fri Dec 17 00:03:13 2004 Subject: [Tutor] "TypeError: 'int' object is not callable"?? References: <6.1.2.0.2.20041208085701.04d62ca0@rcblue.com><3B6BB305-493C-11D9-BFEA-000393CBC88E@yahoo.fr><6.1.2.0.2.20041208102458.06181d20@rcblue.com><6.2.0.14.0.20041208123542.030f8d38@mail.mric.net> <6.2.0.14.0.20041208124624.02e073e8@mail.mric.net> Message-ID: <000101c4e3c3$69cbd370$a95328cf@JSLAPTOP> Ha! That's what I was looking for! The builtin apply function! The only way I could send the *args to the function was through a list, and function calls see a list as one argument. The apply argument doesn't! Thanks Bob. Jacob Schmidt > At 12:39 PM 12/8/2004, Bob Gailer wrote: > >At 11:27 AM 12/8/2004, Dick Moores wrote: > >>My thanks to both Max and Kent. So Python tries, and fails, to see 2() as > >>a function! > >> > >>I also got some help from > > > >Note that SOME languages use () for call. There are other call constructs, > >such as: > > > >DO function WITH parameters (FoxPro, similar in COBOL) > > > >function parameter or parameter1 function parameter2 (APL) > > I should add the Python builtin function apply: apply(function, parameters...) > > Bob Gailer > bgailer@alum.rpi.edu > 303 442 2625 home > 720 938 2625 cell > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From keridee at jayco.net Thu Dec 16 03:13:36 2004 From: keridee at jayco.net (Jacob S.) Date: Fri Dec 17 00:03:19 2004 Subject: [Tutor] Address book sort of References: <003b01c4db12$1d709bf0$4d5328cf@JSLAPTOP> Message-ID: <000201c4e3c3$6ac4d970$a95328cf@JSLAPTOP> You know, instead of that long or thing you've set up, you could do this. if select in [ 'l', 'v', 'V' ]: > [quote] > if select == '1' or select == 'v' or select == 'V': > if file_in_disk in os.listdir('/home/jerimed'): # change??? > fhandle = open(file_in_disk, 'r') # read mode > cPickle.load(fhandle) # restore saved data > fhandle.close() > show_contacts() > elif len(data_holder) > 0: > show_contacts() > else: > is_empty() > [/quote] I'd swear that your standard disclaimer changes weekly. : ) Happy Holidays, Jacob > Standard disclaimer - > > There's probably an easier way to do it, and a more elegant way. Which > someone will post shortly. > > Cheers, > > Liam Clarke From keridee at jayco.net Thu Dec 16 03:36:12 2004 From: keridee at jayco.net (Jacob S.) Date: Fri Dec 17 00:03:23 2004 Subject: [Tutor] Address book sort of References: <003b01c4db12$1d709bf0$4d5328cf@JSLAPTOP> Message-ID: <000301c4e3c3$6e816c40$a95328cf@JSLAPTOP> Hey, I made some changes to my address book, with help from.... Oh darn, well whoever you are, I haven't forgotten the help you gave me in changing my if/if/if/if/if/else things into mapping objects.... Anyway, if anybody wants a look, here it is. P.S. I made some changes to the file reading part too. Got rid of some unnecessary code. [start] from os.path import exists as ex tel = {} tempname = "Telephone.cfg" if not ex(tempname): open(tempname,"w").close() file = open(tempname,"r") stuff = file.read() file.close() if stuff == '': a = 1 print "No entries on file." else: tel = eval(stuff) a = 0 print """\ Commands are: add get save delete quit all is a wildcard """ def dispatch(command,entity,tel): tfunct = functs[command] tfunct(entity,tel) def add(person,tel): if tel.has_key(person): print "That person is already in there. If you wish to edit the file, please delete the record first." else: tel[person] = raw_input("What is their phone number? ") def get(person,tel): if a == 1: print "Sorry, there are no entries available." else: if person == 'all': key = tel.keys() key.sort() print for x in key: print "%s\n%s\n" % (x,tel[x]) elif tel.has_key(person): print "\n%s\n%s\n" % (person,tel[person]) else: print "%s is not in your records." % person def delete(person,tel): if not a: if person == 'all': tel={} open('Telephone.cfg', 'w').close() else: if tel.has_key(person): del tel[person] else: print "%s is not in your records." % person else: print "There is no one to delete." def save(entitynotneeded,tel): file=open('Telephone.cfg', 'w') file.write(str(tel)) file.close() print 'Saved in Telephone.cfg' functs = {'add':add,'get':get,'save':save,'delete':delete} while 1: ask = raw_input('Tell me what you wish to do. ') if ask == "quit": break ask = ask.split(" ") command = ask[0] entity = " ".join(ask[1:]) if entity == '' and command != 'save': entity = raw_input("Who do you want to %s? " % command) dispatch(command,entity,tel) file = open('Telephone.cfg', 'w') file.write(str(tel)) file.close() [end] Jacob Schmidt From keridee at jayco.net Thu Dec 16 04:27:25 2004 From: keridee at jayco.net (Jacob S.) Date: Fri Dec 17 00:03:29 2004 Subject: [Tutor] Complex roots References: <20041209110126.2DD251E400D@bag.python.org><1102593135.6535.37.camel@dhcp0320.acl.icnet.uk><1f7befae041209074162bedff9@mail.gmail.com><6.1.2.0.2.20041210012337.047ccb00@rcblue.com><1f7befae04121020454136d1bc@mail.gmail.com><6.1.2.0.2.20041212002158.046ebb90@rcblue.com><1f7befae0412122037e2be81@mail.gmail.com> <6.1.2.0.2.20041212204602.0543dde0@rcblue.com> Message-ID: <000401c4e3c3$72f9fc10$a95328cf@JSLAPTOP> Finding the all the roots of a complex number shouldn't be too difficult. I tend to do it on paper sometimes. Maybe I can write a script to do it for me instead. I stongly caution you though. The methods that I show below are unstable and should be verified by a math web site as it has been quite a few months since I last used the equations. In fact, I'll almost bet they're wrong. If you want me to check them, I'll gladly google for the right equations if you want. where i == sqrt(-1) [pseudo-code] p = (a+bi)**n n = polar(p) ## polar is a function that converts rectangular coordinates to polar coordinates. radius = n[0] angle = n[1] 1st root radius**n cis (angle/(180*n)) ## Where cis is short for (cos(angle) + i*sin(angle)) 2nd root radius**n cis (angle/(360*n)) ... qth root radius**n cis (angle/(180*q*n)) [/pseudo-code] So saying, I would set a for i in range loop for n times to run these root finders through. Note unless you call some sort of polar to rectangular function on the roots, they will still be in polar. HTH as always, Jacob Schmidt From keridee at jayco.net Thu Dec 16 04:42:03 2004 From: keridee at jayco.net (Jacob S.) Date: Fri Dec 17 00:03:36 2004 Subject: [Tutor] Problem with python2.4. References: <000501c4de4f$cbbb7820$955428cf@JSLAPTOP><3449428f0412091640264de926@mail.gmail.com> <41B8F3AF.4060909@ccvcorp.com> Message-ID: <000601c4e3c3$7587f9f0$a95328cf@JSLAPTOP> If you mean the "Internet Connection Firewall" thingy that you access from the network connection options, then Nope, that's not the problem, because it's disabled. Thanks for your help, Jacob > > Seeing this comment reminded me of some conversations I've seen in > comp.lang.python recently. Apparently newer versions of IDLE create a > subprocess to run user-code in (so that IDLE runs in a different > interpreter than the code you type into IDLE), and communicates with > that subprocess through sockets on the loopback interface (that is, > the 'network connection' that connects only to itself). Overly > aggressive firewall programs may block those socket operations. > > I'd check whether XP's built-in firewall is enabled, and if so, check > whether it might be blocking connections to loopback / localhost / > 127.0.0.1 (all of these indicate the same thing). > > Jeff Shannon > Technician/Programmer > Credit International > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at freenet.co.uk Fri Dec 17 00:13:28 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Dec 17 00:12:29 2004 Subject: [Tutor] Python structure advice ? References: <41C0C2BE.2020107@pusspaws.net> Message-ID: <004301c4e3c4$dab5f6f0$b4bc8651@xp> > everything was global, ....how you guys handle a modern structured > language Don't worry this is one of the hardest bad habits to break. You are not alone. The easiest way is to just pass the data from function to function in the function parameters. Its not at all unusual for functions to have lots of parameters, "global" programmers tend to panic when they have more than a couple, but its not at all bad to have 5 or 6 - more than that gets unweildy I admit and is usually time to start thinking about classes and objects. > I have ended up with my application in several separate directories. Separate modules is good. Separate directories for anything other than big programs (say 20 or more files?) is more hassle than its worth. The files are better kept in a single directory IMHO. The exception being modules designed for reuse... It just makes life simpler! > My problem is that pretty much all the modules need to fix where they > are when they exit and pick up from that point later on, There are two "classic" approaches to this kind of problem: 1) batch oriented - each step of the process produces its own output file or data structure and this gets picked up by the next stage. Tis usually involved processing data in chunks - writing the first dump after every 10th set of input say. This is a very efficient way of processing large chuinks of data and avoids any problems of synchronisation since the output chunks form the self contained input to the next step. And the input stage can run ahead of the processing or the processing aghead of the input. This is classic mainframe strategy, ideal for big volumes. BUT it introduces delays in the end to end process time, its not instant. 2) Real time serial processing, typically constructs a processing chain in a single process. Has a separate thread reading the input data and kicks off a separate processing thread (or process) for each bit of data received. Each thread then processes the data to completion and writes the output. A third process or thread then assembles the outputs into a single report. This produces results quickly but can overload the computer if data starts to arrive so fast that the threads start to back up on each other. Also error handling is harder since with the batch job data errors can be fixed at the intermediate files but with this an error anywhere means that whole data processing chain will be broken with no way to fix it other than resubmitting the initial data. > With my code now running to a few hundred lines > (Don't laugh this is BIG for me :-D ) Its big for me in Python, I've only writtenone program with more than a thousand lines of Python wheras I've written many C/C++ programs in ecess of 10,000 lines and worked on several of more than a million lines. But few if any Python programs get to those sizes. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Fri Dec 17 00:37:03 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Dec 17 00:37:08 2004 Subject: [Tutor] am I missing another simpler structure? References: <41C0DDCF.9040002@po-box.mcgill.ca><1f7befae04121520143bf65017@mail.gmail.com><41C12602.60409@po-box.mcgill.ca><7d7029e7041215225855cb2e2d@mail.gmail.com> <41C14D34.4040704@po-box.mcgill.ca> Message-ID: <007c01c4e3c8$264de520$b4bc8651@xp> > What makes me lean toward mine still? I'd encountered a general > injunction to avoid multiple exit point somewhere on the wild web This goes back to Djikstra's original paper on structured programming (and he was really thinking about assembler!) Multiple returns are a source of bugs, especially in maintenance, but with the advent and popularity of C they have become a standard ttechnique and with reasonable care they are OK in practice. The trick is to minimise them or to keep them collected together in similar patterns. For example in C it is common to see production code that looks like: void someFunc(int p1,p2, char* p3) { // validate the inputs if (p1 <0) return BAD_INPUT; if (p2 > 1000) return BUFFER_ERROR; if (!p3 or strlen(p3) < MIN_STR) return BAD_STRING; // real function code here return result; } So there are lots of return statements but they are used for a very clear purpose and are co-located at the top of the function. In more modern languages we avoid this kind of checking with try/except constructs so we would write something like: def someFunct(p1,p2,p3): try: # do some clever stuff except anError: raise AttributeError except anOther: raise ValueError etc. This leaves the if/else construct as the other likely place to have multiple returns, and there it is usually a matter of personal preference. A try/finally construct will remove the problem of not freeing resources that used to happen in C etc. So in summary, while multiple retirns we a real problem in the 70's and 80's they have been brought under control in modern languages such that they are not frowned upon too much nowadays. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From r2b2 at myway.com Fri Dec 17 00:39:49 2004 From: r2b2 at myway.com (Rene Bourgoin) Date: Fri Dec 17 00:39:56 2004 Subject: [Tutor] dbcp module Message-ID: <20041216233949.27B923973@mprdmxin.myway.com> Yah i came across that site and was trying to learn from that code. I just cant seem to find a download for a python version. i came across this site while searching. http://jakarta.apache.org/ --- On Wed 12/15, Kent Johnson < kent37@tds.net > wrote: From: Kent Johnson [mailto: kent37@tds.net] To: Cc: tutor@python.org Date: Wed, 15 Dec 2004 20:19:22 -0500 Subject: Re: [Tutor] dbcp module Googling for 'python dbcp' turns up this recipe, is this what you are looking for?
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81189

Kent


Rene Bourgoin wrote:
> Anyone know where I can download the dbcp module for Python????
>
>
>
>
>
>
> _______________________________________________
> No banners. No pop-ups. No kidding.
> Make My Way your home on the Web - http://www.myway.com
> _______________________________________________
> Tutor maillist - Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
_______________________________________________
Tutor maillist - Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
_______________________________________________ No banners. No pop-ups. No kidding. Make My Way your home on the Web - http://www.myway.com From alan.gauld at freenet.co.uk Fri Dec 17 00:46:54 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Dec 17 00:45:57 2004 Subject: [Tutor] am I missing another simpler structure? References: <41C0DDCF.9040002@po-box.mcgill.ca> <41C0E1FF.1060504@tds.net><41C16601.5080807@163.com> <41C199B9.6070803@latte.ca> Message-ID: <00b401c4e3c9$8644e450$b4bc8651@xp> > I far prefer the Brian's version, because it lets me set a single > breakpoint while I'm debugging, and I can look at the return value > before returning it, In most debiggers(including Pythons) you can still do that with a boolean condition provided the condition does not itself contain a function call. Simply evaluate the condition in the debugger - eg using the print command. But if the condition has a function in it this is not wise since the function may have side-effects so every time you call it may result in a different result. So my advise is to ony use the return trick on side-effect free simple expressions, otherwise go with the more verbose options. Same applies to the C ?: operator or the python shortcuts using 'and' and 'or'... Alan G. From alan.gauld at freenet.co.uk Fri Dec 17 00:50:03 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Dec 17 00:49:07 2004 Subject: [Tutor] Python structure advice ? References: <41C0C2BE.2020107@pusspaws.net> <41C1D768.4060203@pusspaws.net> Message-ID: <00bf01c4e3c9$f69fdca0$b4bc8651@xp> > Having written this email, it has put my thoughts in order, though it > seems a bit cheaty, wouldn't defining all modules that have to remember > their internal state as classes be the best bet ? Its one solution certainly, creeate objects and the objects carry their state with them. But the problem can be tackled as per my earlier post without delving into the world of objects. Alan G. From alan.gauld at freenet.co.uk Fri Dec 17 00:54:53 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Dec 17 00:53:54 2004 Subject: [Tutor] hello i need help References: <20041216192437.1931.qmail@web26104.mail.ukl.yahoo.com> Message-ID: <00cf01c4e3ca$a3a64ba0$b4bc8651@xp> > is it possible 2 write a script for wordpad or something, Yes it is, using the COM interface. But frankly the interface to Wordpad is pretty basic. Word has much more powerful COM facilities. But... > i only started so i dont know much You probably need to do a bit of reading on the fundamentals first because using COM is not a trivial programming task. Its not rocket science but its not trivial either. > i do know a little about if ($1 == hi) && (#2 == m8) Thats more than I do, I don;t recognoise that line at all. Is that really supposed to be a pound sign in the second parens? Try one of the beginner tutorials on the Python web site, one of which is mine :-) And it has a few elementary bits of COM code too... Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From rdm at rcblue.com Fri Dec 17 02:01:42 2004 From: rdm at rcblue.com (Dick Moores) Date: Fri Dec 17 02:02:32 2004 Subject: [Tutor] Complex roots In-Reply-To: <000401c4e3c3$72f9fc10$a95328cf@JSLAPTOP> References: <20041209110126.2DD251E400D@bag.python.org> <1102593135.6535.37.camel@dhcp0320.acl.icnet.uk> <1f7befae041209074162bedff9@mail.gmail.com> <6.1.2.0.2.20041210012337.047ccb00@rcblue.com> <1f7befae04121020454136d1bc@mail.gmail.com> <6.1.2.0.2.20041212002158.046ebb90@rcblue.com> <1f7befae0412122037e2be81@mail.gmail.com> <6.1.2.0.2.20041212204602.0543dde0@rcblue.com> <000401c4e3c3$72f9fc10$a95328cf@JSLAPTOP> Message-ID: <6.1.2.0.2.20041216165844.023dea60@rcblue.com> Thanks. Tim Peters helped me out with his answer of 12/9. Dick Moores Jacob S. wrote at 19:27 12/15/2004: >Finding the all the roots of a complex number shouldn't be too difficult. I >tend to do it on paper sometimes. Maybe I can write a script to do it for me >instead. I stongly caution you though. The methods that I show below are >unstable and should be verified by a math web site as it has been quite a >few months since I last used the equations. In fact, I'll almost bet they're >wrong. If you want me to check them, I'll gladly google for the right >equations if you want. > >where i == sqrt(-1) > >[pseudo-code] >p = (a+bi)**n >n = polar(p) ## polar is a function that converts rectangular coordinates >to polar coordinates. >radius = n[0] >angle = n[1] > >1st root radius**n cis (angle/(180*n)) ## Where cis is short for >(cos(angle) + i*sin(angle)) >2nd root radius**n cis (angle/(360*n)) >... >qth root radius**n cis (angle/(180*q*n)) >[/pseudo-code] > >So saying, I would set a for i in range loop for n times to run these root >finders through. Note unless you call some sort of polar to rectangular >function on the roots, they will still be in polar. > >HTH as always, >Jacob Schmidt > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From orion_val at 163.com Fri Dec 17 02:16:11 2004 From: orion_val at 163.com (Juan Shen) Date: Fri Dec 17 02:24:31 2004 Subject: [Tutor] removedirs ? In-Reply-To: <41C1F50F.1070905@tds.net> References: <41C1F50F.1070905@tds.net> Message-ID: <41C2335B.6060709@163.com> Of course, shutil.rmtree() is a fast and direct method, but still a little warning, it could be dangerous. No warning and ensure will be raised while removing a tree of files. Juan Shen Kent Johnson wrote: > You misunderstand what removedirs does. It removes an empty directory; > then, if the removed directory's parent is now empty, it removes that, > too, and so on until it finds a directory with something in it or gets > up to the root. > > Try shutil.rmtree() or this recipe: > http://aspn.activestate.com/ASPN/docs/ActivePython/2.2/PyWin32/Recursive_directory_deletes_and_special_files.html > > > Kent > > Ertl, John wrote: > >> I am trying to remove a directory that has other directories and >> files in >> it. I thought removedirs was supposed to do a recursive remove of >> files and >> directories. >> >> When I try it I get >> >>>>> os.removedirs("DAF") >>>> >> >> >> Traceback (most recent call last): >> File "", line 1, in -toplevel- >> os.removedirs("DAF") >> File "/home/ertlj/ertljVersion/lib/python2.3/os.py", line 167, in >> removedirs >> rmdir(name) >> OSError: [Errno 17] File exists: 'DAF' >> >> Thanks, >> >> John Ertl >> > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From orion_val at 163.com Fri Dec 17 04:32:07 2004 From: orion_val at 163.com (Juan Shen) Date: Fri Dec 17 04:40:32 2004 Subject: [Tutor] removedirs ? In-Reply-To: <41C1F9D3.7040701@cnsp.com> References: <41C1F9D3.7040701@cnsp.com> Message-ID: <41C25337.1010009@163.com> This is an iterative method, although much slower than shutil.rmtree(), which can be useful sometimes, while some stdout/in is added: #!/usr/bin/python #Filename: myrmtree.py import os,sys,shutil def rmtree(top): uncleandir=[] for (root,dirs,files) in os.walk(top,topdown=False): for name in dirs+files: item=os.path.join(root,name) if item in uncleandir: uncleandir.append(root) continue print 'Delete %s : (Yes or No or All or Cancel)' %(item,), v=raw_input() if v=='Y' or v=='y': (os.path.isfile(item) and os.remove or os.rmdir)(item) elif v=='N' or v=='n': uncleandir.append(root) continue elif v=='A' or v=='a': shutil.rmtree(top) return 1 elif v=='C' or v=='c': return 2 else: print 'Take your input as No.' continue return 0 >>>from myrmtree import tree >>>top='/home/juan/test' #Your dir need to be removed here >>>rmtree(top) Just try it and give suggestions and comments please, Hehe Juan Shen Jason Child wrote: > is this what you want to do? > > import os > from os.path import join > # Delete everything reachable from the directory named in 'top'. > # CAUTION: This is dangerous! For example, if top == '/', it > # could delete all your disk files. > > for root, dirs, files in os.walk(top, topdown=False): > for name in files: > os.remove(join(root, name)) > for name in dirs: > os.rmdir(join(root, name)) > > I cant take credit for the code, as I found it when I was trying to > hack together a recirsive file remover script. It was in the help > files for the os module, under walk(). Go figure; when you try to do > things the "hard way" python keeps it simple! > > Peace > > Jason > > Ertl, John wrote: > >> Jason, >> >> I could...That is the exact feature I am trying to replicate, but I >> would >> just like to do it in Python if I can (in a simple way). I am >> writing this >> code in Python to avoid some funny scripting that I would need to do. >> To go >> back to combing shell and Python again would be a bit deflating...but >> the >> straight forward path might be the best. >> >> Thanks, >> >> John Ertl >> >> -----Original Message----- >> From: Jason Child [mailto:jasonchild@cnsp.com] >> Sent: Thursday, December 16, 2004 12:36 >> Cc: tutor@python.org >> Subject: Re: [Tutor] removedirs ? >> >> Ertl, John wrote: >> >> >> >>> I am trying to remove a directory that has other directories and >>> files in >>> it. I thought removedirs was supposed to do a recursive remove of >>> files >>> >> >> and >> >> >>> directories. >>> >>> When I try it I get >>> >>> >>> >>> >>> >>>>>> os.removedirs("DAF") >>>>>> >>>>>> >>>>> >>> Traceback (most recent call last): >>> File "", line 1, in -toplevel- >>> os.removedirs("DAF") >>> File "/home/ertlj/ertljVersion/lib/python2.3/os.py", line 167, in >>> removedirs >>> rmdir(name) >>> OSError: [Errno 17] File exists: 'DAF' >>> >>> Thanks, >>> >>> John Ertl >>> >>> >>> _______________________________________________ >>> Tutor maillist - Tutor@python.org >>> http://mail.python.org/mailman/listinfo/tutor >>> >>> >>> >>> >> >> it seems to me that if its on a *nix box you could use the shell command >> rm -rf >> _______________________________________________ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> >> > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From bvande at po-box.mcgill.ca Fri Dec 17 11:12:40 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Fri Dec 17 11:13:59 2004 Subject: [Tutor] suggestion for group project Message-ID: <41C2B118.8090105@po-box.mcgill.ca> Hi all, A while ago, in a response: Danny Yoo said unto the world upon 2004-11-29 17:14: > > I just got in contact with Nick Parlante of the Nifty Assignments > project; he's been collecting material on fun projects: > > http://nifty.stanford.edu/ > > The projects there look pretty nice. In fact, I'm thinking of > adapting material on that page for us here on Python-Tutor. > > Is there a particular project that sounds interesting to folks? > Personally, I'm interested in: > > http://nifty.stanford.edu/catandmouse/html/ > > But that's only because I helped tutor it back when I was at > Berkeley's Self-Paced Center... *grin* But if people want, I'd be > happy to convert Professor Clancy's support code from C++ to Python. I've got a suggestion: would there be any interest among list members in picking one of the assignments, working on it, and then doing a code comparison/critique? When Danny posted, I did . I thought about posting what I had done to the list and inviting such comment/criticism, but was dissuaded by two things: 1) once I'd got my code to a reasonable polish, with docstrings and all, it seemed a bit long to just plunk onto the list, and, 2) I suspect much of the interest, fun, and learning might well emerge from having a go at the task and then seeing what others came up with. If I posted mine unannounced, others wouldn't have the chance to go at the problem fresh. What do others think? I wonder if the length of code, the possible undesirability of a bunch of answers to a collection of homework problems getting posted, and other considerations might make this better as an off-list endeavour. I'd be interested in doing it either here or on private channels. (If there was interest and we opt for private, I could probably get my uni to let me set up an unarchived listserv for the purpose.) Best to all, Brian vdB From kent37 at tds.net Fri Dec 17 12:00:08 2004 From: kent37 at tds.net (Kent Johnson) Date: Fri Dec 17 12:00:13 2004 Subject: [Tutor] "TypeError: 'int' object is not callable"?? In-Reply-To: <000101c4e3c3$69cbd370$a95328cf@JSLAPTOP> References: <6.1.2.0.2.20041208085701.04d62ca0@rcblue.com><3B6BB305-493C-11D9-BFEA-000393CBC88E@yahoo.fr><6.1.2.0.2.20041208102458.06181d20@rcblue.com><6.2.0.14.0.20041208123542.030f8d38@mail.mric.net> <6.2.0.14.0.20041208124624.02e073e8@mail.mric.net> <000101c4e3c3$69cbd370$a95328cf@JSLAPTOP> Message-ID: <41C2BC38.70907@tds.net> Jacob S. wrote: > Ha! That's what I was looking for! The builtin apply function! The only way > I could send the *args to the function was through a list, and function > calls see a list as one argument. The apply argument doesn't! Thanks Bob. apply() is deprecated; it has been replaced by 'extended call syntax'. Instead of apply(fn, args, kwds) you can now write fn(*args, **kwds) Kent From kent37 at tds.net Fri Dec 17 13:12:40 2004 From: kent37 at tds.net (Kent Johnson) Date: Fri Dec 17 13:12:45 2004 Subject: [Tutor] dbcp module In-Reply-To: <20041216233949.27B923973@mprdmxin.myway.com> References: <20041216233949.27B923973@mprdmxin.myway.com> Message-ID: <41C2CD38.2070103@tds.net> Please describe what you are looking for. A python version of the Jakarta Database Connection Pool? Kent Rene Bourgoin wrote: > Yah i came across that site and was trying to learn from that code. > > I just cant seem to find a download for a python version. > > > > i came across this site while searching. > > > > http://jakarta.apache.org/ > > > > > > > > > > > > > > --- On Wed 12/15, Kent Johnson < kent37@tds.net > wrote: > > From: Kent Johnson [mailto: kent37@tds.net] > > To: > > Cc: tutor@python.org > > Date: Wed, 15 Dec 2004 20:19:22 -0500 > > Subject: Re: [Tutor] dbcp module > > > > Googling for 'python dbcp' turns up this recipe, is this what you are looking for?
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81189

Kent


Rene Bourgoin wrote:
> Anyone know where I can download the dbcp module for Python????
>
>
>
>
>
>
> _______________________________________________
> No banners. No pop-ups. No kidding.
> Make My Way your home on the Web - http://www.myway.com
> _______________________________________________
> Tutor maillist - Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
_______________________________________________
Tutor maillist - Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
> > _______________________________________________ > No banners. No pop-ups. No kidding. > Make My Way your home on the Web - http://www.myway.com > From matthew.williams at cancer.org.uk Fri Dec 17 14:08:33 2004 From: matthew.williams at cancer.org.uk (Matt Williams) Date: Fri Dec 17 14:09:15 2004 Subject: [Tutor] Nifty In-Reply-To: <20041217110104.D3E071E400F@bag.python.org> References: <20041217110104.D3E071E400F@bag.python.org> Message-ID: <1103288913.2957.10.camel@dhcp0320.acl.icnet.uk> I'd be interested, Matt On Fri, 2004-12-17 at 11:01, tutor-request@python.org wrote: > Send Tutor mailing list submissions to > tutor@python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/tutor > or, via email, send a message with subject or body 'help' to > tutor-request@python.org > > You can reach the person managing the list at > tutor-owner@python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Tutor digest..." > > > Today's Topics: > > 1. suggestion for group project (Brian van den Broek) > > > ---------------------------------------------------------------------- > > Message: 1 > Date: Fri, 17 Dec 2004 05:12:40 -0500 > From: Brian van den Broek > Subject: [Tutor] suggestion for group project > To: Tutor > Message-ID: <41C2B118.8090105@po-box.mcgill.ca> > Content-Type: text/plain; charset=ISO-8859-1; format=flowed > > Hi all, > > A while ago, in a response: > > Danny Yoo said unto the world upon 2004-11-29 17:14: > > > > I just got in contact with Nick Parlante of the Nifty Assignments > > project; he's been collecting material on fun projects: > > > > http://nifty.stanford.edu/ > > > > The projects there look pretty nice. In fact, I'm thinking of > > adapting material on that page for us here on Python-Tutor. > > > > Is there a particular project that sounds interesting to folks? > > Personally, I'm interested in: > > > > http://nifty.stanford.edu/catandmouse/html/ > > > > But that's only because I helped tutor it back when I was at > > Berkeley's Self-Paced Center... *grin* But if people want, I'd be > > happy to convert Professor Clancy's support code from C++ to Python. > > > I've got a suggestion: would there be any interest among list members in > picking one of the assignments, working on it, and then doing a code > comparison/critique? > > When Danny posted, I did . > I thought about posting what I had done to the list and inviting such > comment/criticism, but was dissuaded by two things: 1) once I'd got my > code to a reasonable polish, with docstrings and all, it seemed a bit > long to just plunk onto the list, and, 2) I suspect much of the > interest, fun, and learning might well emerge from having a go at the > task and then seeing what others came up with. If I posted mine > unannounced, others wouldn't have the chance to go at the problem fresh. > > What do others think? > > I wonder if the length of code, the possible undesirability of a bunch > of answers to a collection of homework problems getting posted, and > other considerations might make this better as an off-list endeavour. > I'd be interested in doing it either here or on private channels. (If > there was interest and we opt for private, I could probably get my uni > to let me set up an unarchived listserv for the purpose.) > > Best to all, > > Brian vdB > > > > ------------------------------ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > > End of Tutor Digest, Vol 10, Issue 72 > ************************************* From dbroadwell at mindspring.com Fri Dec 17 16:52:53 2004 From: dbroadwell at mindspring.com (David Broadwell) Date: Fri Dec 17 16:53:17 2004 Subject: [Tutor] Nifty In-Reply-To: <41C2B118.8090105@po-box.mcgill.ca> Message-ID: >> I just got in contact with Nick Parlante of the Nifty >> Assignments project; he's been collecting material on fun >> projects: >> >> http://nifty.stanford.edu/ > What do others think? Private channel or not, I'm in. (at least until classes spike up again in early February) Sounds like a good way to burn through a winter. Heck I don't even know if I CAN convert C++ to Python but I've never let a problem like language stop me from playing Chinese chess on boats in china ... So even if I lack the ability, I'm for the idea of having running 'projects' for the tutor list to do. That way it's driven a bit less by homework problems. -- Programmer's mantra; Observe, Brainstorm, Prototype, Repeat David Broadwell From marilyn at deliberate.com Fri Dec 17 18:26:40 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Fri Dec 17 18:26:47 2004 Subject: [Tutor] A little Tkinter question In-Reply-To: <41C0C1D0.40002@aon.at> Message-ID: On Wed, 15 Dec 2004, Gregor Lingl wrote: > > > Marilyn Davis schrieb: > > Hi Tutors, > > > > I'm reviewing GUIs and wondering: > > > > When you pack a component, and you specify fill = BOTH, how is this > > different from expand = YES? > > > Hi Marilyn, > This is a bit tricky and hard to explain, so I recommend playing around > with this little program from John Grayson's Tkinter book: > > from Tkinter import * > > class App: > def __init__(self, master): > master.geometry("300x200") > fm = Frame(master) > Button(fm, text='Left').pack(side=LEFT, fill=BOTH, expand=1) > Button(fm, text='Center').pack(side=LEFT, fill=BOTH, expand=1) > Button(fm, text='Right').pack(side=LEFT, fill=BOTH, expand=1) > fm.pack(fill=BOTH, expand=YES) > > > root = Tk() > root.option_add('*font', ('verdana', 12, 'bold')) > root.title("Pack - Example 9") > display = App(root) > root.mainloop() > > Modify the three lines with Button(....).pack(...) > for instance by setting expand = 0 (which is the default value) > > Button(fm, text='Left').pack(side=LEFT, fill=BOTH, expand=0) > Button(fm, text='Center').pack(side=LEFT, fill=BOTH, expand=0) > Button(fm, text='Right').pack(side=LEFT, fill=BOTH, expand=0) > > or by tropping the fill option: > > Button(fm, text='Left').pack(side=LEFT, expand=1) > Button(fm, text='Center').pack(side=LEFT, expand=1) > Button(fm, text='Right').pack(side=LEFT, expand=1) > > and so on. > > These Examples are from Chapter 5, several others concerning the packer > can be found at: > > https://secure.manning.com/catalog/view.php?book=grayson&item=source Thanks for the pointer, Gregor. I guess that the jist of it is that fill fills all available space. And expand is about what happens to the widget when its master expands. But, the bit of the book I was looking at, I'm afraid, I found to be difficult to follow. There seemed to be outputs without matching code, and the numbering system confused me. And he pointed out the difference between fill alone and fill with expand and they looked the same. I guess you are right. One needs to experiment to get the desired effect. I have no desired effect. I was just looking for intellectual understanding. Thank you. Marilyn > > Hope this helps > Gregor > > > > Thank you for any insight. > > > > Marilyn Davis > > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > -- From jeffpeery at yahoo.com Fri Dec 17 18:52:25 2004 From: jeffpeery at yahoo.com (Jeff Peery) Date: Fri Dec 17 18:52:28 2004 Subject: [Tutor] boa constructor font? Message-ID: <20041217175226.61362.qmail@web60106.mail.yahoo.com> my eyes are going bad... anyone know how to change the font size in the editor window of the boa constructor? this seems to be a simple but not easy thing to do. thanks! Jeff -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041217/3846a919/attachment.htm From pythontut at pusspaws.net Fri Dec 17 20:16:07 2004 From: pythontut at pusspaws.net (Dave S) Date: Fri Dec 17 20:16:18 2004 Subject: [Tutor] Python structure advice ? In-Reply-To: <41C1DD28.6090504@tds.net> References: <41C0C2BE.2020107@pusspaws.net> <41C1D768.4060203@pusspaws.net> <41C1DD28.6090504@tds.net> Message-ID: <41C33077.9020108@pusspaws.net> Kent Johnson wrote: > Dave S wrote: > >> Dave S wrote: >> >>> The 'remembering where is was' seems a continuous stumbling block >>> for me. I have though of coding each module as a class but this >>> seems like a cheat. I could declare copious globals, this seems >>> messy, I could define each module as a thread & get them talking via >>> queues, given this serious thought but heeded warning in previous >>> posts. I have thought about returning an list of saved 'pointers' >>> which would be re-submitted when the function is called. I don't >>> know which way to turn. >>> >> Having written this email, it has put my thoughts in order, though it >> seems a bit cheaty, wouldn't defining all modules that have to >> remember their internal state as classes be the best bet ? >> >> Dave > > > Why do you say this is 'cheaty'? A class is basically a collection of > data (state) and functions to operate on that state. Sorry for the delay, real world work got in the way ... Well I understand classes to be used when multiple instances are required, I will only need one instance and as such it seemed a bit of a cheat, The trouble is I now pretty well understand the tools, but don't know how you guys use them in the real world. > > You might be interested in this essay: > http://www.pycs.net/users/0000323/stories/15.html I found this particularly usefull, > > It might well make sense to organize your program as a collection of > cooperating classes, or maybe a collection of classes with a top-level > function that stitches them all together. Yes, this is the way I see things progressing, from 20,000ft this makes a lot of sense. > > You might also want to learn about iterator classes and generator > functions, they are a technique for returning a bit of data at a time > while maintaining state. You might be able to structure your input > stage as an iterator or generator. > http://docs.python.org/tut/node11.html#SECTION0011900000000000000000 > http://docs.python.org/lib/typeiter.html I remeber iterators from 'learning python', I was concerned about several modules all 'having a iterator' to the next, debuging would be scary ! I think I will go the class route. > > Kent > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From dyoo at hkn.eecs.berkeley.edu Fri Dec 17 20:22:50 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Dec 17 20:23:01 2004 Subject: [Tutor] least squares In-Reply-To: <41C4631D@wm2.uvic.ca> Message-ID: On Thu, 16 Dec 2004, mdcooper wrote: > I am trying to get a corrolation between a large number of variables and for > many similar equations : > (Ca1 * xa^2) + (Ca2 * ya^2) + (Ca3 * za^2) + ... = ta > (Cb1 * xb^2) + (Cb2 * yb^2) + (Cb3 * zb^2) + ... = tb > > which is solved to get: > (C1 * x^2) + (C2 * y^2) + (C3 * z^2) + ... = t > > where the submitted values of x,y, and z should give the correct t > > and I am using the code to get C1, C2, C3, .... These constants are not > allowed to be negative and the submitted equations are such that there > is no reason for the values to be negative, and although a good fit may > allow them to be negative, another good fit will be found if they are > all positive. Hi Matt, Ok. I have to admit that my mathematical maturity is actually a little low, but I'll try to follow along. But this really doesn't sounds like a problem specific to Python though, but more of a math problem. So you may actually want to talk with folks with a real math background; I would not be mathematically mature enough to know if your code is correct. I'd strongly recommend talking to folks on the 'sci.math' or 'sci.math.num-analysis' newsgroups. I haven't seen your code, so I'm still in the dark about how it works or what its capabilities are. I'll make a few assumptions that might not be right, but I have to start somewhere. *grin* Does your code provide a way at getting at all possible solutions, or only one particular solution? If so, then you can just filter out for solutions that satisfy the property you want. For example, we can produce a function that generates all squares in the world: ### >>> import itertools >>> def allSquares(): ... for i in itertools.count(): ... yield i*i ... >>> squares = allSquares() >>> squares.next() 0 >>> squares.next() 1 >>> squares.next() 4 >>> squares.next() 9 >>> squares.next() 16 >>> squares.next() 25 ### I can keep calling 'next()' on my 'squares' iteration, and keep getting squares. Even though this can produce an infinite sequence of answers, we can still apply a filter on this sequence, and pick out the ones that are "palindromic" in terms of their digits: ### >>> def palindromic(n): ... "Returns true if n is 'palindromic'." ... return str(n) == str(n)[::-1] ... >>> filteredSquares = itertools.ifilter(palindromic, allSquares()) >>> filteredSquares.next() 0 >>> filteredSquares.next() 1 >>> filteredSquares.next() 4 >>> filteredSquares.next() 9 >>> filteredSquares.next() 121 >>> filteredSquares.next() 484 >>> filteredSquares.next() 676 ### This sequence-filtering approach takes advantage of Python's ability to work on a iteration of answers. If your program can be written to produce an infinite stream of answers, and if a solution set with all positive coefficients is inevitable in that stream, then you can take this filtering approach, and just capture the first solution that matches your constraints. Similarly, if your program only produces a single solution, does it do so through an "iterative" algorithm? By iterative, I mean: does it start off with an initial guess and apply a process to improve that guess until the solution is satisfactory? For others on the Tutor list, here is an "iterative" way to produce the square root of a number: ### def mysqrt(x): guess = 1.0 ## initial guess while not goodEnough(guess, x): guess = improve(guess, x) return guess def improve(guess, x): """Improves the guess of the square root of x.""" return average(guess, x / guess) def average(x, y): return (x + y) / 2.0 def goodEnough(guess, x): """Returns true if guess is close enough to the square root of x.""" return abs(guess**2 - x) < 0.00001 ### (adapted/ripped off from material in SICP: http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-10.html#%_sec_1.1.7) If your program tries to solve the problem through an iterative process, then, again, does it inevitably produce a solution where all the constant coefficients 'Cn' are positive? If so, maybe you can just continue to produce better and better solutions until its satisfactory, until all the coefficients are positive. Otherwise, without looking at your code, I'm stuck. *grin* And even if I do see your code, I might be stuck still. If your code is short, feel free to post it up, and we'll see how far we can get. But you really may want to talk with someone who has a stronger math background. Good luck to you! From jeff at ccvcorp.com Fri Dec 17 20:33:00 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri Dec 17 20:29:16 2004 Subject: [Tutor] Python structure advice ? In-Reply-To: <41C33077.9020108@pusspaws.net> References: <41C0C2BE.2020107@pusspaws.net> <41C1D768.4060203@pusspaws.net> <41C1DD28.6090504@tds.net> <41C33077.9020108@pusspaws.net> Message-ID: <41C3346C.9060003@ccvcorp.com> Dave S wrote: > Kent Johnson wrote: > >> Why do you say this is 'cheaty'? A class is basically a collection of >> data (state) and functions to operate on that state. > > > Sorry for the delay, real world work got in the way ... > > Well I understand classes to be used when multiple instances are > required, I will only need one instance and as such it seemed a bit of a > cheat, The trouble is I now pretty well understand the tools, but don't > know how you guys use them in the real world. For what it's worth, it seems to me to be perfectly normal to have classes that are only ever intended to have a single instance. For example, you're never likely to need more than one HTML parser, and yet htmllib.HTMLParser is a class... As Kent said, the main point of a class is that you have a collection of data and operations on that data bundled together. Whether you have one set of data to operate on, or many such sets, is mostly irrelevant (though classes are even more valuable when there *are* many sets of data). Defining a class isn't so much a statement that "I want lots of things like this", as it is a declaration of modularity -- "This stuff all belongs together as a unit". Jeff Shannon Technician/Programmer Credit International From python at dhumketu.cjb.net Fri Dec 17 20:57:48 2004 From: python at dhumketu.cjb.net (Shantanoo Mahajan) Date: Fri Dec 17 20:57:57 2004 Subject: [Tutor] Re: Opening and reading .cvs files in Python In-Reply-To: <1103030331.4567.10.camel@KMA.accesstel> References: <1103030331.4567.10.camel@KMA.accesstel> Message-ID: <20041217195748.GA11320@dhumketu.homeunix.net> +++ Johan Geldenhuys [14-12-04 15:18 +0200]: | Hi, | I want to find out how to open a .cvs file on a remote Windows machine | and get file to my local linux folder. .cvs file?? | | Any help would be appreciated. | -- | Johan | | -- | This E-Mail has been scanned. | Enjoy Your Day. | | -------------- next part -------------- | An HTML attachment was scrubbed... | URL: http://mail.python.org/pipermail/tutor/attachments/20041214/58bfe4e7/attachment-0001.htm | | ------------------------------ From alan.gauld at freenet.co.uk Fri Dec 17 20:59:45 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Dec 17 20:59:31 2004 Subject: [Tutor] Polish translation of my tutor Message-ID: <000501c4e472$f52da330$05be8651@xp> Are there any Polish speakers on the tutor list who would like to check a new version of my tutorial? There are no formal links to it yet as there are only a few pages but it can be found at: http://www.freenetpages.co.uk/hp/alan.gauld/polish/ And any feedback can be sent to me and I'll forward to the translator. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From mohamed at your-site.com Fri Dec 17 21:04:05 2004 From: mohamed at your-site.com (Mohamed Lrhazi) Date: Fri Dec 17 21:04:13 2004 Subject: [Tutor] About Perl's Integer module Message-ID: <43050046.1103295845@[192.168.1.76]> Hello all, I ported to python a little Perl script that applies some math algorithm that I do not understand... My version seems to give the same results as the Perl version... but just to make sure I am asking the following: The Perl version starts by testing whether Perl is in integer mode or not, and if not it exists! Is there an equivalent module in Python? >From what I gathered, in Integer mode, Perl convert (floors) all numbers to integers while doing any arithmetic (+ - * / bit shifting...) Should I simply wrap every number involved in any arithmetic calculation with calls to floor()? My python script, and the Perl original, follow. What it does is create a hash of the input string (which is supposed to be a DNS domain name) and returns the two layer directory tree where the domain should live in my filesystem : site.company.com --> X3/32/site.company.com site2.company.com --> 6U/zv/site2.company.com Given the lack of "use integer" from my code... can anyone tell these two programs are equivalent? def complex(domain): h=0 res="" domain=domain.lower() prefix=['x','x','/','x','x','/'] conv=[ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_' ] for i in range(0,len(domain)): h*=129 h+=ord(domain[i]) h+=987654321 if h == 0: h=1 prefix[0] = conv[ h & 0x3f ]; h = h >> 6 prefix[1] = conv[ h & 0x3f ]; h = h >> 6 prefix[3] = conv[ h & 0x3f ]; h = h >> 6 prefix[4] = conv[ h & 0x3f ]; return "".join(prefix) + domain print complex(sys.argv[1]) """ The Perl version : # ---------------------------------------------------------- # Returns the complex hash of the website. sub complex { my $site = shift; my $h = 0; my $res = ""; $site = lc $site; my @prefix = ( 'x','x','/','x','x','/' ); my @conv = ( 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_' ); my @chars = split //, $site; my $i; for( $i = 0; $i < $#chars + 1; $i++ ) { $h *= 129; $h += ord( $chars[$i] ); $h += 987654321; } if( $h == 0 ) { $h = 1; } $prefix[0] = $conv[$h & 0x3f]; $h = $h >> 6; $prefix[1] = $conv[$h & 0x3f]; $h = $h >> 6; $prefix[3] = $conv[$h & 0x3f]; $h = $h >> 6; $prefix[4] = $conv[$h & 0x3f]; return (join '', @prefix) . "$site"; } """ From pythontut at pusspaws.net Fri Dec 17 21:29:00 2004 From: pythontut at pusspaws.net (Dave S) Date: Fri Dec 17 21:29:08 2004 Subject: [Tutor] Python structure advice ? In-Reply-To: <004301c4e3c4$dab5f6f0$b4bc8651@xp> References: <41C0C2BE.2020107@pusspaws.net> <004301c4e3c4$dab5f6f0$b4bc8651@xp> Message-ID: <41C3418C.4020407@pusspaws.net> Sorry for the delay, real world work took me away ... >>everything was global, ....how you guys handle a modern structured >>language >> >> > >Don't worry this is one of the hardest bad habits to break. >You are not alone. The easiest way is to just pass the data >from function to function in the function parameters. Its not >at all unusual for functions to have lots of parameters, "global" >programmers tend to panic when they have more than a couple, > > yep ! >but its not at all bad to have 5 or 6 - more than that gets >unweildy I admit and is usually time to start thinking about >classes and objects. > > > >>I have ended up with my application in several separate directories. >> >> > >Separate modules is good. Separate directories for anything >other than big programs (say 20 or more files?) is more hassle >than its worth. The files are better kept in a single directory >IMHO. The exception being modules designed for reuse... >It just makes life simpler! > > Ive tried to be hyper organized and added my dirs in /usr/lib/python2.3/site-packages/mypath.pth /home/dave/mygg/gg1.3/live_datad /home/dave/mygg/gg1.3/logger /home/dave/mygg/gg1.3/utils /home/dave/mygg/gg1.3/datacore /home/dave/mygg/gg1.3 /home/dave/mygg/gg1.3/configs This works OK but I sometimes have to search around a bit to find where the modules are. Probarby part of the problem is I tend to write lots of small modules, debug them & then import them into one controlling script, It works OK but I start to drown in files, eg my live_datad contains ... exact_sleep.py garbage_collect.py gg ftsed.e3p html_strip.py live_datad.py valid_day.pyc exact_sleep.pyc garbage_collect.pyc gg ftsed.e3s html_strip.pyc valid_day.py When I get more experienced I will try & write fewer, bigger modules :-) > > >>My problem is that pretty much all the modules need to fix where >> >> >they > > >>are when they exit and pick up from that point later on, >> >> > >There are two "classic" approaches to this kind of problem: > >1) batch oriented - each step of the process produces its own >output file or data structure and this gets picked up by the >next stage. Tis usually involved processing data in chunks >- writing the first dump after every 10th set of input say. >This is a very efficient way of processing large chuinks of >data and avoids any problems of synchronisation since the >output chunks form the self contained input to the next step. >And the input stage can run ahead of the processing or the >processing aghead of the input. This is classic mainframe >strategy, ideal for big volumes. BUT it introduces delays >in the end to end process time, its not instant. > > I see your point, like a static chain, one calling the next & passing data, the problem being that the links of the chain will need to remember their previous state when called again, so their output is a function of previous data + fresh data. I guess their state could be written to a file, then re-read. >2) Real time serial processing, typically constructs a >processing chain in a single process. Has a separate thread >reading the input data > Got that working live_datad ... >and kicks off a separate processing >thread (or process) for each bit of data received. Each >thread then processes the data to completion and writes >the output. > OK > A third process or thread then assembles the >outputs into a single report. > > > Interesting ... >This produces results quickly but can overload the computer >if data starts to arrive so fast that the threads start to >back up on each other. Also error handling is harder since >with the batch job data errors can be fixed at the >intermediate files but with this an error anywhere means >that whole data processing chain will be broken with no way >to fix it other than resubmitting the initial data. > > > An interesting idea, I had not thought of this approach as an option even with its stated drawbacks. Its given me an idea for some scripting I have to do later on ... >>With my code now running to a few hundred lines >>(Don't laugh this is BIG for me :-D ) >> >> > >Its big for me in Python, I've only writtenone program with >more than a thousand lines of Python wheras I've written >many C/C++ programs in ecess of 10,000 lines > Boy am I glad I chose to learn Python rather than C++, probarbly still be at 'hello world' ;-) >and worked >on several of more than a million lines. But few if any >Python programs get to those sizes. > >HTH, > >Alan G >Author of the Learn to Program web tutor >http://www.freenetpages.co.uk/hp/alan.gauld > > > > > From pythontut at pusspaws.net Fri Dec 17 21:31:45 2004 From: pythontut at pusspaws.net (Dave S) Date: Fri Dec 17 21:31:51 2004 Subject: [Tutor] Python structure advice ? In-Reply-To: <41C3346C.9060003@ccvcorp.com> References: <41C0C2BE.2020107@pusspaws.net> <41C1D768.4060203@pusspaws.net> <41C1DD28.6090504@tds.net> <41C33077.9020108@pusspaws.net> <41C3346C.9060003@ccvcorp.com> Message-ID: <41C34231.6030908@pusspaws.net> Jeff Shannon wrote: > Dave S wrote: > >> Kent Johnson wrote: >> >>> Why do you say this is 'cheaty'? A class is basically a collection >>> of data (state) and functions to operate on that state. >> >> >> >> Sorry for the delay, real world work got in the way ... >> >> Well I understand classes to be used when multiple instances are >> required, I will only need one instance and as such it seemed a bit >> of a cheat, The trouble is I now pretty well understand the tools, >> but don't know how you guys use them in the real world. > > > For what it's worth, it seems to me to be perfectly normal to have > classes that are only ever intended to have a single instance. For > example, you're never likely to need more than one HTML parser, and > yet htmllib.HTMLParser is a class... Well if its good enough for a Python lib ... > > As Kent said, the main point of a class is that you have a collection > of data and operations on that data bundled together. Whether you > have one set of data to operate on, or many such sets, is mostly > irrelevant (though classes are even more valuable when there *are* > many sets of data). Defining a class isn't so much a statement that > "I want lots of things like this", as it is a declaration of > modularity -- "This stuff all belongs together as a unit". OK Im a reformed ('L' plate programmer) its going to be classes :-) > > Jeff Shannon > Technician/Programmer > Credit International > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From jeff at ccvcorp.com Fri Dec 17 22:49:35 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Fri Dec 17 22:45:53 2004 Subject: [Tutor] About Perl's Integer module In-Reply-To: <43050046.1103295845@[192.168.1.76]> References: <43050046.1103295845@[192.168.1.76]> Message-ID: <41C3546F.3060504@ccvcorp.com> Mohamed Lrhazi wrote: > Hello all, > > I ported to python a little Perl script that applies some math algorithm > that I do not understand... My version seems to give the same results as > the Perl version... but just to make sure I am asking the following: > > The Perl version starts by testing whether Perl is in integer mode or > not, and if not it exists! Is there an equivalent module in Python? No, there isn't. However, the only operation in Python that should convert an integer into a float is division, and you should be able to use // (a double slash) to indicate integer division. But there's no division in your script, so it shouldn't matter... (Integers *will* automatically be converted to longs if they get too large, but this should be harmless unless you specifically need ints to 'wrap around'.) > Given the lack of "use integer" from my code... can anyone tell these > two programs are equivalent? I don't know perl, so I can't tell for certain, but I think so. However, there are many ways in which this could become more idiomatic Python code, and more efficient. > def complex(domain): > h=0 > res="" > domain=domain.lower() > prefix=['x','x','/','x','x','/'] > conv=[ > 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', > 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', > 'Y', 'Z', > 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', > 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', > 'y', 'z', > '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', > '-', '_' > ] In Python, strings are sequences, so you can index and slice and iterate over them. This means that you can replace these lists of single characters with one string, instead. Not only that, but given that you're using all letters and numbers, you can just get them from predefined lists in the string module -- .>> import string .>> string.ascii_uppercase 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' .>> string.ascii_lowercase 'abcdefghijklmnopqrstuvwxyz' .>> string.digits '0123456789' .>> With that in mind, the above line can be changed to: conv = string.uppercase + string.lowercase + \ string.digits + '-_' (There's also a string.letters which contains both uppercase and lowercase, but it has the lowercase first while you have the uppercase first. This will yield different, but equally valid, characters.) > > for i in range(0,len(domain)): > h*=129 > h+=ord(domain[i]) > h+=987654321 Because you can iterate over strings, you can do this simpler by dropping the integer index and the range(). You can even chain the earlier call to lower() in-line here: for ch in domain.lower(): h *= 129 h += ord(ch) h += 987654321 > if h == 0: > h=1 > prefix[0] = conv[ h & 0x3f ]; h = h >> 6 > prefix[1] = conv[ h & 0x3f ]; h = h >> 6 > prefix[3] = conv[ h & 0x3f ]; h = h >> 6 > prefix[4] = conv[ h & 0x3f ]; Here, instead of predefining prefix list and then replacing certain elements, I'd just create a blank list and append to it. Given that your operation is identical each time (except when you need a /), I'd put it into a loop. prefix = [] for i in range(6): if i in (2, 5): prefix.append('/') else: prefix.append(conv[ h & 0x3f ]) h = h >> 6 > > return "".join(prefix) + domain > > print complex(sys.argv[1]) So, once more, all together: .>> def complex(domain): ... h = 0 ... conv = string.uppercase + string.lowercase + \ ... string.digits + '-_' ... for ch in domain.lower(): ... h *= 129 ... h += ord(ch) ... h += 987654321 ... if h == 0: ... h = 1 ... prefix = [] ... for i in range(6): ... if i in (2, 5): ... prefix.append('/') ... else: ... prefix.append(conv[ h & 0x3f ]) ... h = h >> 6 ... return "".join(prefix) + domain ... .>> So, let's see how this works: .>> complex('site.company.com') 'X3/32/site.company.com' .>> complex('site2.company.com') '6U/zv/site2.company.com' .>> complex('www.python.org') 'ZF/4R/www.python.org' .>> So, each character is generated by looking at the hash (h), grabbing the least-significant six bits, and using the resulting number (which will be 0-63) to look up a character in conv. The hash is then shifted six bits to drop the 'used' bits before grabbing the next chunk. Two of these generated characters are used for each of two directory names. Any given sitename will consistently produce the same four characters. Now, here's a 'batteries-included' function that does much the same thing (though it'll be different characters). .>> def complex2(domain): ... import md5 ... digest = md5.new(domain) ... digeststring = digest.hexdigest() ... names = (digeststring[:2], digeststring[2:4], domain) ... return '/'.join(names) ... .>> complex2('site.company.com') 'b2/37/site.company.com' .>> complex2('site2.company.com') '75/5c/site2.company.com' .>> complex2('www.python.org') '16/95/www.python.org' .>> This uses the md5 module to generate a 'fingerprint' for each domain name. It gets that fingerprint as a long hexadecimal number, and then slices off the first few characters to make the directory names. Now, this method is going to be heavily weighted towards numbers instead of letters, and it can create a maximum of 16^4 (65,536) different directories instead of 64^4 (16,777,216), so you're somewhat more likely to have collisions (multiple sites in a single directory), but it's still not very likely. (That chance can be reduced by using longer names, too. Using three-character directory names gives 16^6 possibilities -- which is equal to 64^4, the same as your perl script.) Jeff Shannon Technician/Programmer Credit International From mark.kels at gmail.com Fri Dec 17 22:48:18 2004 From: mark.kels at gmail.com (Mark Kels) Date: Fri Dec 17 22:48:21 2004 Subject: [Tutor] Tkinter questions Message-ID: Hi all , I got some Tkinter related questions for a project that I'm making: 1. How to add an image to a button ? 2. How can I print text using Tkinter (I want it to be cross platform, so I cant use modules like win32print ) ? 3. How to I make the program to always open in a full window ? Thanks allot. -- 1. The day Microsoft makes something that doesn't suck is probably the day they start making vacuum cleaners. 2. Unix is user friendly - it's just picky about it's friends. 3. Documentation is like sex: when it is good, it is very, very good. And when it is bad, it is better than nothing. - Dick Brandon From keridee at jayco.net Fri Dec 17 22:54:17 2004 From: keridee at jayco.net (Jacob S.) Date: Fri Dec 17 22:54:41 2004 Subject: [Tutor] "TypeError: 'int' object is not callable"?? References: <6.1.2.0.2.20041208085701.04d62ca0@rcblue.com><3B6BB305-493C-11D9-BFEA-000393CBC88E@yahoo.fr><6.1.2.0.2.20041208102458.06181d20@rcblue.com><6.2.0.14.0.20041208123542.030f8d38@mail.mric.net> <6.2.0.14.0.20041208124624.02e073e8@mail.mric.net><000101c4e3c3$69cbd370$a95328cf@JSLAPTOP> <41C2BC38.70907@tds.net> Message-ID: <006a01c4e483$02dad100$a95328cf@JSLAPTOP> Hey, could you give an example? Thanks, Jacob > > apply() is deprecated; it has been replaced by 'extended call syntax'. Instead of > apply(fn, args, kwds) > you can now write > fn(*args, **kwds) > > Kent > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From Christian.Wyglendowski at greenville.edu Fri Dec 17 23:15:49 2004 From: Christian.Wyglendowski at greenville.edu (Christian Wyglendowski) Date: Fri Dec 17 23:15:58 2004 Subject: [Tutor] "TypeError: 'int' object is not callable"?? Message-ID: > -----Original Message----- > From: tutor-bounces@python.org > [mailto:tutor-bounces@python.org] On Behalf Of Jacob S. > Sent: Friday, December 17, 2004 3:54 PM > To: Kent Johnson > Cc: tutor@python.org > Subject: Re: [Tutor] "TypeError: 'int' object is not callable"?? > > Hey, could you give an example? > Thanks, > Jacob > > > > > apply() is deprecated; it has been replaced by 'extended > call syntax'. > Instead of > > apply(fn, args, kwds) > > you can now write > > fn(*args, **kwds) > > > > Kent Here is a quick example I came up with: >>> def spam(*args, **kwargs): ... print "Here are the args you supplied:" ... for item in args: ... print item ... print ... print "Here are the kwargs you supplied:" ... for key,value in kwargs.items(): ... print key, '=', value ... >>> spam(1,'a','eggs',s=0, p=1, a=2, m=3) Here are the args you supplied: 1 a eggs Here are the kwargs you supplied: a = 2 p = 1 s = 0 m = 3 In the case of the spam() function, 1, 'a', and 'eggs' are all put into the sequence args (not sure if it is a list or tuple). The key/value pairs are bundled into the dictionary kwargs. The arguments have to be given in the right order though: >>> spam(t=1, b=1, 'this', 'will', 'fail') Traceback (SyntaxError: non-keyword arg after keyword arg HTH! Christian http://www.dowski.com From kent37 at tds.net Fri Dec 17 23:30:38 2004 From: kent37 at tds.net (Kent Johnson) Date: Fri Dec 17 23:30:42 2004 Subject: [Tutor] Python structure advice ? In-Reply-To: <41C3418C.4020407@pusspaws.net> References: <41C0C2BE.2020107@pusspaws.net> <004301c4e3c4$dab5f6f0$b4bc8651@xp> <41C3418C.4020407@pusspaws.net> Message-ID: <41C35E0E.6030205@tds.net> Dave S wrote: >> Separate modules is good. Separate directories for anything >> other than big programs (say 20 or more files?) is more hassle >> than its worth. The files are better kept in a single directory >> IMHO. The exception being modules designed for reuse... >> It just makes life simpler! >> >> > Ive tried to be hyper organized and added my dirs in > /usr/lib/python2.3/site-packages/mypath.pth > > /home/dave/mygg/gg1.3/live_datad > /home/dave/mygg/gg1.3/logger > /home/dave/mygg/gg1.3/utils > /home/dave/mygg/gg1.3/datacore > /home/dave/mygg/gg1.3 > /home/dave/mygg/gg1.3/configs > > This works OK but I sometimes have to search around a bit to find where > the modules are. > > Probarby part of the problem is I tend to write lots of small modules, > debug them & then import them into one controlling script, It works OK > but I start to drown in files, eg my live_datad contains ... > > exact_sleep.py garbage_collect.py gg ftsed.e3p html_strip.py > live_datad.py valid_day.pyc > exact_sleep.pyc garbage_collect.pyc gg ftsed.e3s html_strip.pyc > valid_day.py > > When I get more experienced I will try & write fewer, bigger modules :-) It's just a guess from the filenames, but it looks like your live_datad package (directory) contains everything needed by live_datad.py. I would like to suggest a different organization. I tend to organize packages around a single functional area, and by looking at the dependencies of the modules in the package on other packages. For example, in my current project some of the packages are: - common.util - this is a catchall for modules that are not specific to this application, and don't depend on any other packages - common.db - low-level database access modules - cb.data - application-specific database access - the data objects and data access objects that the application works with - cb.import - modules that import legacy data into the application - cb.writer - modules that generate files - cb.gui - GUI components - cb.app - application-level drivers and helpers Anyway, the point is, if you organize your modules according to what they do, rather than by who uses them, you might make a structure that is less chaotic. HTH Kent From Pawel_Kraszewski at wp.pl Fri Dec 17 23:41:43 2004 From: Pawel_Kraszewski at wp.pl (Pawel Kraszewski) Date: Fri Dec 17 23:41:48 2004 Subject: [Tutor] Polish translation of my tutor In-Reply-To: <000501c4e472$f52da330$05be8651@xp> References: <000501c4e472$f52da330$05be8651@xp> Message-ID: <200412172341.43588.Pawel_Kraszewski@wp.pl> Dnia pi?tek, 17 grudnia 2004 20:59, Alan Gauld napisa?: |Are there any Polish speakers on the tutor list who would like |to check a new version of my tutorial? There are no formal links |to it yet as there are only a few pages but it can be found at: That would be me. First of all content="text/html; charset=ISO-6682" Ehm... Never heard of ISO-6682... Already contacted the author. The page looks OK, when you force Windows CP 1250. -- Pawel Kraszewski FreeBSD/Linux E-Mail/Jabber Phone ICQ GG Pawel_Kraszewski@wp.pl +48 604 777447 45615564 69381 From kent37 at tds.net Fri Dec 17 23:43:58 2004 From: kent37 at tds.net (Kent Johnson) Date: Fri Dec 17 23:44:02 2004 Subject: [Tutor] "TypeError: 'int' object is not callable"?? In-Reply-To: <006a01c4e483$02dad100$a95328cf@JSLAPTOP> References: <6.1.2.0.2.20041208085701.04d62ca0@rcblue.com><3B6BB305-493C-11D9-BFEA-000393CBC88E@yahoo.fr><6.1.2.0.2.20041208102458.06181d20@rcblue.com><6.2.0.14.0.20041208123542.030f8d38@mail.mric.net> <6.2.0.14.0.20041208124624.02e073e8@mail.mric.net><000101c4e3c3$69cbd370$a95328cf@JSLAPTOP> <41C2BC38.70907@tds.net> <006a01c4e483$02dad100$a95328cf@JSLAPTOP> Message-ID: <41C3612E.10202@tds.net> Jacob S. wrote: > Hey, could you give an example? I'll try... Here is range with three explicit arguments >>> range(1, 10, 2) [1, 3, 5, 7, 9] Here is range with the arguments supplied in a list; it does the same thing >>> args = [1, 10, 2] >>> range(*args) [1, 3, 5, 7, 9] Here is an example with zip(). zip() normally takes multiple arguments, this makes it use elements of a single list: >>> l=[ [1,2], [3,4], [5,6] ] >>> zip(*l) [(1, 3, 5), (2, 4, 6)] Kent > Thanks, > Jacob > > >>apply() is deprecated; it has been replaced by 'extended call syntax'. > > Instead of > >> apply(fn, args, kwds) >>you can now write >> fn(*args, **kwds) >> >>Kent >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor >> >> > > > From keridee at jayco.net Fri Dec 17 23:52:20 2004 From: keridee at jayco.net (Jacob S.) Date: Fri Dec 17 23:53:07 2004 Subject: [Tutor] "TypeError: 'int' object is not callable"?? References: Message-ID: <008c01c4e48b$2907f170$a95328cf@JSLAPTOP> Thank you! Wait, though. How do I do this? def differentnoofvars(*args,**kwargs): ## By the way, is it **kwargs or **kwds? print kwargs another(kwargs) def another(**kwargs): for x,y in kwagrs.items(): print "%s = %s" % (x,y) a = ['a=2','f=3','t=[1,2,3]'] ## A list of kwargs that I want to send individually to differentnoofvars differentnoofvars(a) > > Hey, could you give an example? > > Thanks, > > Jacob > > > > > > > > apply() is deprecated; it has been replaced by 'extended > > call syntax'. > > Instead of > > > apply(fn, args, kwds) > > > you can now write > > > fn(*args, **kwds) > > > > > > Kent > > Here is a quick example I came up with: > > >>> def spam(*args, **kwargs): > ... print "Here are the args you supplied:" > ... for item in args: > ... print item > ... print > ... print "Here are the kwargs you supplied:" > ... for key,value in kwargs.items(): > ... print key, '=', value > ... > >>> spam(1,'a','eggs',s=0, p=1, a=2, m=3) > Here are the args you supplied: > 1 > a > eggs > > Here are the kwargs you supplied: > a = 2 > p = 1 > s = 0 > m = 3 > > In the case of the spam() function, 1, 'a', and 'eggs' are all put into > the sequence args (not sure if it is a list or tuple). The key/value > pairs are bundled into the dictionary kwargs. The arguments have to be > given in the right order though: > > >>> spam(t=1, b=1, 'this', 'will', 'fail') > Traceback (SyntaxError: non-keyword arg after keyword arg > > HTH! > > Christian > http://www.dowski.com > > > > From keridee at jayco.net Fri Dec 17 23:55:04 2004 From: keridee at jayco.net (Jacob S.) Date: Fri Dec 17 23:55:14 2004 Subject: [Tutor] "TypeError: 'int' object is not callable"?? References: Message-ID: <009201c4e48b$750a68a0$a95328cf@JSLAPTOP> Sorry about that last message. Kent just posted and answered my question with his example. Thank you all! Jacob > > -----Original Message----- > > From: tutor-bounces@python.org > > [mailto:tutor-bounces@python.org] On Behalf Of Jacob S. > > Sent: Friday, December 17, 2004 3:54 PM > > To: Kent Johnson > > Cc: tutor@python.org > > Subject: Re: [Tutor] "TypeError: 'int' object is not callable"?? > > > > Hey, could you give an example? > > Thanks, > > Jacob > > > > > > > > apply() is deprecated; it has been replaced by 'extended > > call syntax'. > > Instead of > > > apply(fn, args, kwds) > > > you can now write > > > fn(*args, **kwds) > > > > > > Kent > > Here is a quick example I came up with: > > >>> def spam(*args, **kwargs): > ... print "Here are the args you supplied:" > ... for item in args: > ... print item > ... print > ... print "Here are the kwargs you supplied:" > ... for key,value in kwargs.items(): > ... print key, '=', value > ... > >>> spam(1,'a','eggs',s=0, p=1, a=2, m=3) > Here are the args you supplied: > 1 > a > eggs > > Here are the kwargs you supplied: > a = 2 > p = 1 > s = 0 > m = 3 > > In the case of the spam() function, 1, 'a', and 'eggs' are all put into > the sequence args (not sure if it is a list or tuple). The key/value > pairs are bundled into the dictionary kwargs. The arguments have to be > given in the right order though: > > >>> spam(t=1, b=1, 'this', 'will', 'fail') > Traceback (SyntaxError: non-keyword arg after keyword arg > > HTH! > > Christian > http://www.dowski.com > > > > From kent37 at tds.net Sat Dec 18 00:21:11 2004 From: kent37 at tds.net (Kent Johnson) Date: Sat Dec 18 00:21:16 2004 Subject: [Tutor] "TypeError: 'int' object is not callable"?? In-Reply-To: <008c01c4e48b$2907f170$a95328cf@JSLAPTOP> References: <008c01c4e48b$2907f170$a95328cf@JSLAPTOP> Message-ID: <41C369E7.2080109@tds.net> Jacob S. wrote: > Thank you! > > Wait, though. > > How do I do this? > > def differentnoofvars(*args,**kwargs): ## By the way, is it **kwargs or > **kwds? Call it what you like, it's an ordinary function parameter. kwds is commonly used but you can use kwargs. > print kwargs > another(kwargs) Should be another(**kwargs). If you call another(kwargs) then kwargs will be an ordinary parameter of another and another would be defined as def another(kwargs): ... > > def another(**kwargs): > for x,y in kwagrs.items(): > print "%s = %s" % (x,y) > > a = ['a=2','f=3','t=[1,2,3]'] ## A list of kwargs that I want to send Should be a dict, the **kwds parameter is a dict mapping keywords to values a = {'a':2, 'f':3, 't':[1,2,3]} There really are two different and complementary things going on here, at the point of call and at the point of function definition. At the point of call, you can pass a dictionary instead of using explicit, named parameters. For example, given a function test() defined like this: >>> def test(a, b): ... print a, b you can call it with ordinary named arguments: >>> test(a='foo', b='bar') foo bar Or you can pass it a dictionary with the named arguments, using extended calling syntax: >>> d= {'a':'foo', 'b':'bar'} >>> test(**d) foo bar Inside the function, if you have a **kwds parameter, it will receive a dict containing any keyword arguments not explicitly declared. This allows you to pass keyword parameters that you don't anticipate when the function is defined. For example, >>> def test2(a, **kwds): ... print a ... for k,v in kwds.items(): ... print k,v >>> test2(1) # No keywords 1 >>> test2(a=1) # a is a declared parameter so kwds is empty 1 >>> test2(1, b=2, c=3) # b and c are passed in kwds 1 c 3 b 2 Kent > individually to differentnoofvars > differentnoofvars(a) > > > >>>Hey, could you give an example? >>>Thanks, >>>Jacob >>> >>> >>>>apply() is deprecated; it has been replaced by 'extended >>> >>>call syntax'. >>>Instead of >>> >>>> apply(fn, args, kwds) >>>>you can now write >>>> fn(*args, **kwds) >>>> >>>>Kent >> >>Here is a quick example I came up with: >> >> >>>>>def spam(*args, **kwargs): >> >>... print "Here are the args you supplied:" >>... for item in args: >>... print item >>... print >>... print "Here are the kwargs you supplied:" >>... for key,value in kwargs.items(): >>... print key, '=', value >>... >> >>>>>spam(1,'a','eggs',s=0, p=1, a=2, m=3) >> >>Here are the args you supplied: >>1 >>a >>eggs >> >>Here are the kwargs you supplied: >>a = 2 >>p = 1 >>s = 0 >>m = 3 >> >>In the case of the spam() function, 1, 'a', and 'eggs' are all put into >>the sequence args (not sure if it is a list or tuple). The key/value >>pairs are bundled into the dictionary kwargs. The arguments have to be >>given in the right order though: >> >> >>>>>spam(t=1, b=1, 'this', 'will', 'fail') >> >>Traceback (SyntaxError: non-keyword arg after keyword arg >> >>HTH! >> >>Christian >>http://www.dowski.com >> >> >> >> > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at freenet.co.uk Sat Dec 18 00:31:41 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat Dec 18 00:31:24 2004 Subject: [Tutor] Python structure advice ? References: <41C0C2BE.2020107@pusspaws.net><41C1D768.4060203@pusspaws.net> <41C1DD28.6090504@tds.net><41C33077.9020108@pusspaws.net> <41C3346C.9060003@ccvcorp.com> Message-ID: <001d01c4e490$91196280$05be8651@xp> > For what it's worth, it seems to me to be perfectly normal to have > classes that are only ever intended to have a single instance. For > example, you're never likely to need more than one HTML parser, and > yet htmllib.HTMLParser is a class... That's true but the argument for a class in that case is that we can subclass it for more specialized purposes. If there is only to be a single instance and it will not be specialized by sub classing then a simple module will do the job just nicely. > As Kent said, the main point of a class is that you have a collection > of data and operations on that data bundled together. Dunno if I'd agree that that was the *main point* of classes, the main point I'd say was to act as a template for objects. The fact that there might only be one instance is a side issue. But creating classes that only have a single instance is certainly OK, after all the original design patterns book by the GoF has a singleton pattern to ensure that only one oinstance can be created! > "I want lots of things like this", as it is a declaration of > modularity -- "This stuff all belongs together as a unit". So use a module... Python is blessed with both constructs and we should use whichever is most appropriate. IMHO of course! :-) Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From r2b2 at myway.com Sat Dec 18 00:35:57 2004 From: r2b2 at myway.com (Rene Bourgoin) Date: Sat Dec 18 00:36:04 2004 Subject: [Tutor] dbcp module Message-ID: <20041217233557.302A9395E@mprdmxin.myway.com> Yes i believe im looking for the python version of the Jakarta databse connection pool!! --- On Fri 12/17, Kent Johnson < kent37@tds.net > wrote: From: Kent Johnson [mailto: kent37@tds.net] To: Cc: tutor@python.org Date: Fri, 17 Dec 2004 07:12:40 -0500 Subject: Re: [Tutor] dbcp module Please describe what you are looking for. A python version of the Jakarta Database Connection Pool?

Kent


Rene Bourgoin wrote:
> Yah i came across that site and was trying to learn from that code.
>
> I just cant seem to find a download for a python version.
>
>
>
> i came across this site while searching.
>
>
>
> http://jakarta.apache.org/
>
>
>
>
>
>
>
>
>
>
>
>
>
> --- On Wed 12/15, Kent Johnson < kent37@tds.net > wrote:
>
> From: Kent Johnson [mailto: kent37@tds.net]
>
> To:
>
> Cc: tutor@python.org
>
> Date: Wed, 15 Dec 2004 20:19:22 -0500
>
> Subject: Re: [Tutor] dbcp module
>
>
>
> Googling for 'python dbcp' turns up this recipe, is this what you are looking for?
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81189

Kent


Rene Bourgoin wrote:
> Anyone know where I can download the dbcp module for Python????
>
>
>
>
>
>
> _______________________________________________
> No banners. No pop-ups. No kidding.
> Make My Way your home on the Web - http://www.myway.com
> _______________________________________________
> Tutor maillist - Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
_______________________________________________
Tutor maillist - Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

>
> _______________________________________________
> No banners. No pop-ups. No kidding.
> Make My Way your home on the Web - http://www.myway.com
>
_______________________________________________
Tutor maillist - Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
_______________________________________________ No banners. No pop-ups. No kidding. Make My Way your home on the Web - http://www.myway.com From alan.gauld at freenet.co.uk Sat Dec 18 00:45:58 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat Dec 18 00:45:47 2004 Subject: [Tutor] Python structure advice ? References: <41C0C2BE.2020107@pusspaws.net> <004301c4e3c4$dab5f6f0$b4bc8651@xp> <41C3418C.4020407@pusspaws.net> Message-ID: <002401c4e492$8fc97800$05be8651@xp> > >1) batch oriented - each step of the process produces its own > >output file or data structure and this gets picked up by the > >next stage. Tis usually involved processing data in chunks > >- writing the first dump after every 10th set of input say. > > > I see your point, like a static chain, one calling the next & passing > data, the problem being that the links of the chain will need to > remember their previous state when called again, so their output is a > function of previous data + fresh data. I guess their state could be > written to a file, then re-read. Yes. Just to expand: the typical processing involves three files: 1) the input which is the output of the preceding stage 2) the output which will form input to the next stage 3) the job log. This will contain references to any input data items that failed to process - typically these will be manually inspected, corrected and a new file created and submitted at the end of the batch run. BUT 3) will also contain the sequence number of the last file and/or last data item processed so that when the next cycle runs it knows where to start. It is this belt and braces approach to data processing and error recovery that makes mainframes so reliable, not just the hardware, but the whole culture there is geared to handling failure and being able to *recover* not just report on it. After all its the mainframes where the really mission critical software of any large enterprise runs! As an ex Unix head I learned an awful lot about reliable computing from the 18 months I spent working on a mainframe project. These guys mostly live in a highly specialised microcosm of their own but they have learned a lot of powerful tricks over the last 40 years that the rest of us ignore at our peril. I strongly recommend that anyone who gets the chance of *a short* contract in mainframe land, with training, to grab the opportunity with both hands! < Steps off soapbox now :-) > Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Sat Dec 18 01:04:10 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat Dec 18 01:05:17 2004 Subject: [Tutor] Tkinter questions References: Message-ID: <003a01c4e495$1a407b30$05be8651@xp> > I got some Tkinter related questions for a project that I'm making: > 1. How to add an image to a button ? I find the easiest way is to create an PhotoImage object attach the graphic file(jpg,bmp,gif) to that and assign the PhotoImage object to the Button.image property. You can "animate" the image by simply reassigning the file to the underlying PhotoImage onject. > 2. How can I print text using Tkinter (I want it to be cross platform, > so I cant use modules like win32print ) ? You mean print as in to a printer? Personally I tend to generate an HTML file and use the native OS Tools to print that. You can get fancy and use the native OS priniting libraries but since its very OS specific I find HTML is easier! OUtside Tkinter you may well find the GUI libraries have done the cross platform stuff for you, but not in Tkinter. > 3. How to I make the program to always open in a full window ? Define a full window? You mean full screen? Thats usually better done as a parameter that the user can set unless there is a very good reason not to. (Personally I refuse to use any program that insists on opening full screen!) If OTOH you mean that you don't want the DOS box in the background thats easy, just rename the .py file to .pyw. But I suspect, since you talk abouit cross platform you mean full screen. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From dyoo at hkn.eecs.berkeley.edu Sat Dec 18 01:13:57 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Dec 18 01:14:05 2004 Subject: [Tutor] dbcp module In-Reply-To: <20041217233557.302A9395E@mprdmxin.myway.com> Message-ID: On Fri, 17 Dec 2004, Rene Bourgoin wrote: > Yes i believe im looking for the python version of the Jakarta databse > connection pool!! Hi Rene, I haven't looked at this too closely yet, but there are projects out there for connection pools. For example: http://sqlrelay.sourceforge.net/ Some prominent Python projects, though, appear to use their own homebrewed connection pools. Zope appears to do this: http://zdp.zope.org/projects/zfaq/faq/DatabaseIntegration/954522163 SQLObject maintains its own database pool: http://wiki.sqlobject.org/connections but also refers to 'DBPool.py': http://jonpy.sourceforge.net/dbpool.html I'm not sure if one database pooling solution has emerged as a dominant one yet, though. Good luck to you! From pythontut at pusspaws.net Sat Dec 18 02:10:15 2004 From: pythontut at pusspaws.net (Dave S) Date: Sat Dec 18 02:10:23 2004 Subject: [Tutor] Python structure advice ? In-Reply-To: <002401c4e492$8fc97800$05be8651@xp> References: <41C0C2BE.2020107@pusspaws.net> <004301c4e3c4$dab5f6f0$b4bc8651@xp> <41C3418C.4020407@pusspaws.net> <002401c4e492$8fc97800$05be8651@xp> Message-ID: <41C38377.6010405@pusspaws.net> Alan Gauld wrote: >>>1) batch oriented - each step of the process produces its own >>>output file or data structure and this gets picked up by the >>>next stage. Tis usually involved processing data in chunks >>>- writing the first dump after every 10th set of input say. >>> >>> >>> >>I see your point, like a static chain, one calling the next & >> >> >passing > > >>data, the problem being that the links of the chain will need to >>remember their previous state when called again, so their output is >> >> >a > > >>function of previous data + fresh data. I guess their state could be >>written to a file, then re-read. >> >> > >Yes. Just to expand: the typical processing involves three files: >1) the input which is the output of the preceding stage >2) the output which will form input to the next stage >3) the job log. This will contain references to any input data >items that failed to process - typically these will be manually >inspected, corrected and a new file created and submitted at the >end of the batch run. > >BUT 3) will also contain the sequence number of the last file and/or >last data item processed so that when the next cycle runs it knows >where to start. It is this belt and braces approach to data >processing and error recovery that makes mainframes so reliable, >not just the hardware, but the whole culture there is geared to >handling failure and being able to *recover* not just report on it. >After all its the mainframes where the really mission critical >software of any large enterprise runs! > >As an ex Unix head I learned an awful lot about reliable computing >from the 18 months I spent working on a mainframe project. These >guys mostly live in a highly specialised microcosm of their own >but they have learned a lot of powerful tricks over the last 40 >years that the rest of us ignore at our peril. I strongly >recommend that anyone who gets the chance of *a short* contract >in mainframe land, with training, to grab the opportunity with >both hands! > >< Steps off soapbox now :-) > > >Alan G >Author of the Learn to Program web tutor >http://www.freenetpages.co.uk/hp/alan.gauld > > > > > You get on that soapbox whenever you want :-) , its good to hear a range of views ! Dave From pythontut at pusspaws.net Sat Dec 18 02:21:09 2004 From: pythontut at pusspaws.net (Dave S) Date: Sat Dec 18 02:21:16 2004 Subject: [Tutor] Python structure advice ? In-Reply-To: <41C35E0E.6030205@tds.net> References: <41C0C2BE.2020107@pusspaws.net> <004301c4e3c4$dab5f6f0$b4bc8651@xp> <41C3418C.4020407@pusspaws.net> <41C35E0E.6030205@tds.net> Message-ID: <41C38605.6040600@pusspaws.net> Kent Johnson wrote: > Dave S wrote: > >>> Separate modules is good. Separate directories for anything >>> other than big programs (say 20 or more files?) is more hassle >>> than its worth. The files are better kept in a single directory >>> IMHO. The exception being modules designed for reuse... >>> It just makes life simpler! >>> >>> >> Ive tried to be hyper organized and added my dirs in >> /usr/lib/python2.3/site-packages/mypath.pth >> >> /home/dave/mygg/gg1.3/live_datad >> /home/dave/mygg/gg1.3/logger >> /home/dave/mygg/gg1.3/utils >> /home/dave/mygg/gg1.3/datacore >> /home/dave/mygg/gg1.3 >> /home/dave/mygg/gg1.3/configs >> >> This works OK but I sometimes have to search around a bit to find >> where the modules are. >> >> Probarby part of the problem is I tend to write lots of small >> modules, debug them & then import them into one controlling script, >> It works OK but I start to drown in files, eg my live_datad contains ... >> >> exact_sleep.py garbage_collect.py gg ftsed.e3p html_strip.py >> live_datad.py valid_day.pyc >> exact_sleep.pyc garbage_collect.pyc gg ftsed.e3s html_strip.pyc >> valid_day.py >> >> When I get more experienced I will try & write fewer, bigger modules :-) > > > It's just a guess from the filenames, but it looks like your > live_datad package (directory) contains everything needed by > live_datad.py. Spot on > I would like to suggest a different organization. > > I tend to organize packages around a single functional area, and by > looking at the dependencies of the modules in the package on other > packages. > > For example, in my current project some of the packages are: > - common.util - this is a catchall for modules that are not specific > to this application, and don't depend on any other packages > - common.db - low-level database access modules > - cb.data - application-specific database access - the data objects > and data access objects that the application works with > - cb.import - modules that import legacy data into the application > - cb.writer - modules that generate files > - cb.gui - GUI components > - cb.app - application-level drivers and helpers > I have been getting in a muddle, html_strip.py, strips HTML, mines for data & when it finds specific patterns returns a dictionary containing them. However I also use one of its functions in a utility convert_data.py reading in archived semi-processed HTML files. This cross dependance has occured several times and is getting messy, yours is an interesting approach, Its started me thinking... > Anyway, the point is, if you organize your modules according to what > they do, rather than by who uses them, you might make a structure that > is less chaotic. > > HTH > Kent > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From mohamed at your-site.com Sat Dec 18 02:34:57 2004 From: mohamed at your-site.com (Mohamed Lrhazi) Date: Sat Dec 18 02:35:01 2004 Subject: [Tutor] About Perl's Integer module In-Reply-To: <41C3546F.3060504@ccvcorp.com> References: <43050046.1103295845@[192.168.1.76]> <41C3546F.3060504@ccvcorp.com> Message-ID: <62901765.1103315697@[192.168.1.102]> --On Friday, December 17, 2004 1:49 PM -0800 Jeff Shannon wrote: > > I don't know perl, so I can't tell for certain, but I think so. However, > there are many ways in which this could become more idiomatic Python > code, and more efficient. > Thanks so much for all the comments and the valuable tips and the explanation of the actual algorithm. The Perl code come with the web server I am using: Zeus. I won't be able to use your improved md5 implementation because my own scripts to manage the web sites would need to agree with Zeus's idea of where a domain's root directory is :) Thanks a lot. Mohamed~ From r2b2 at myway.com Sat Dec 18 03:00:21 2004 From: r2b2 at myway.com (Rene Bourgoin) Date: Sat Dec 18 03:00:29 2004 Subject: [Tutor] dbcp module Message-ID: <20041218020021.545423A27@mprdmxin.myway.com> Ive been learning to interact with databases using python and i was looking for ways to return a SELECT query result in a plain format. what i mean by plain format is : name number address Fred Smith 2125553243 1 main st All the pratices ive done return the results in tuples or tuples within tuples. (('fred smith','2125553243','1 main st')) I saw some examples on activestate that use the dbcp module and import the pp ( pretty print ) function and the results from the examples were in the format i was looking for. just straight strings in a tabular format. no tuples. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81189 --- On Fri 12/17, Danny Yoo < dyoo@hkn.eecs.berkeley.edu > wrote: From: Danny Yoo [mailto: dyoo@hkn.eecs.berkeley.edu] To: r2b2@myway.com Cc: kent37@tds.net, tutor@python.org Date: Fri, 17 Dec 2004 16:13:57 -0800 (PST) Subject: Re: [Tutor] dbcp module

On Fri, 17 Dec 2004, Rene Bourgoin wrote:

> Yes i believe im looking for the python version of the Jakarta databse
> connection pool!!

Hi Rene,


I haven't looked at this too closely yet, but there are projects out there
for connection pools. For example:

http://sqlrelay.sourceforge.net/


Some prominent Python projects, though, appear to use their own homebrewed
connection pools. Zope appears to do this:

http://zdp.zope.org/projects/zfaq/faq/DatabaseIntegration/954522163

SQLObject maintains its own database pool:

http://wiki.sqlobject.org/connections

but also refers to 'DBPool.py':

http://jonpy.sourceforge.net/dbpool.html

I'm not sure if one database pooling solution has emerged as a dominant
one yet, though.


Good luck to you!

_______________________________________________ No banners. No pop-ups. No kidding. Make My Way your home on the Web - http://www.myway.com From kent37 at tds.net Sat Dec 18 03:12:37 2004 From: kent37 at tds.net (Kent Johnson) Date: Sat Dec 18 03:12:42 2004 Subject: [Tutor] dbcp module In-Reply-To: <20041218020021.545423A27@mprdmxin.myway.com> References: <20041218020021.545423A27@mprdmxin.myway.com> Message-ID: <41C39215.9020404@tds.net> The recipe you cite has the pp() function and an example of its use. It sounds like that is what you want. Kent Rene Bourgoin wrote: > Ive been learning to interact with databases using python and i was looking for ways to return a SELECT query result in a plain format. what i mean by plain format is : > > > > name number address > > Fred Smith 2125553243 1 main st > > > > All the pratices ive done return the results in tuples or tuples within tuples. > > (('fred smith','2125553243','1 main st')) > > > > I saw some examples on activestate that use the dbcp module and import the pp ( pretty print ) function and the results from the examples were in the format i was looking for. just straight strings in a tabular format. no tuples. > > > > > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81189 > > > > --- On Fri 12/17, Danny Yoo < dyoo@hkn.eecs.berkeley.edu > wrote: > > From: Danny Yoo [mailto: dyoo@hkn.eecs.berkeley.edu] > > To: r2b2@myway.com > > Cc: kent37@tds.net, tutor@python.org > > Date: Fri, 17 Dec 2004 16:13:57 -0800 (PST) > > Subject: Re: [Tutor] dbcp module > > > >

On Fri, 17 Dec 2004, Rene Bourgoin wrote:

> Yes i believe im looking for the python version of the Jakarta databse
> connection pool!!

Hi Rene,


I haven't looked at this too closely yet, but there are projects out there
for connection pools. For example:

http://sqlrelay.sourceforge.net/


Some prominent Python projects, though, appear to use their own homebrewed
connection pools. Zope appears to do this:

http://zdp.zope.org/projects/zfaq/faq/DatabaseIntegration/954522163

SQLObject maintains its own database pool:

http://wiki.sqlobject.org/connections

but also refers to 'DBPool.py':

http://jonpy.sourceforge.net/dbpool.html

I'm not sure if one database pooling solution has emerged as a dominant
one yet, though.


Good luck to you!

> > _______________________________________________ > No banners. No pop-ups. No kidding. > Make My Way your home on the Web - http://www.myway.com > From kent37 at tds.net Sat Dec 18 03:22:26 2004 From: kent37 at tds.net (Kent Johnson) Date: Sat Dec 18 03:22:31 2004 Subject: [Tutor] least squares In-Reply-To: <41C46364@wm2.uvic.ca> References: <41C46364@wm2.uvic.ca> Message-ID: <41C39462.1000200@tds.net> Have you tried contacting the author of the Scientific package? His email address is on the main web page. Kent mdcooper wrote: > Hi Danny, > > Thanks for the reply - I was purposely vague just to see what people would ask > for. > > The code uses LinearAlgebra.py from Numeric and LeastSquares.py from > Scientific. From dyoo at hkn.eecs.berkeley.edu Sat Dec 18 03:32:05 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Dec 18 03:32:08 2004 Subject: [Tutor] dbcp module In-Reply-To: <20041218020021.545423A27@mprdmxin.myway.com> Message-ID: On Fri, 17 Dec 2004, Rene Bourgoin wrote: > Ive been learning to interact with databases using python and i was > looking for ways to return a SELECT query result in a plain format. what > i mean by plain format is : > > name number address > Fred Smith 2125553243 1 main st > > All the pratices ive done return the results in tuples or tuples within tuples. > (('fred smith','2125553243','1 main st')) > > I saw some examples on activestate that use the dbcp module Hi Rene, Ok, let's pause for a moment. I think I understand where all the confusion is coming from: it's a namespace issue, as well as a case of really really bad naming. You mentioned earlier that: > Yes i believe im looking for the python version of the Jakarta > database connection pool However, that is probably not what you're looking for. 'dbcp' in the context of the recipe that you've shown us: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81189 has nothing to do with connection pools! The author of that recipe has unfortunatetly named their module so as to make it easy to confuse it with the Apache Commons DBCP project: http://jakarta.apache.org/commons/dbcp/ But this is NOT the same 'dbcp' thing that the Python Cookbook recipe is talking about. The 'dbcp' Python Cookbook module refers to this snippet of code at the beginning of the recipe: ###### """This is dbcp.py, a module for printing out a cursor's output.""" def pp(cursor, data=None, rowlens=0): d = cursor.description if not d: return "#### NO RESULTS ###" names = [] lengths = [] rules = [] if not data: t = cursor.fetchall() for dd in d: # iterate over description l = dd[1] if not l: l = 12 # or default arg ... l = max(l, len(dd[0])) # handle long names names.append(dd[0]) lengths.append(l) for col in range(len(lengths)): if rowlens: rls = [len(str(row[col])) for row in data if row[col]] lengths[col] = max([lengths[col]]+rls) rules.append("-"*lengths[col]) format = " ".join(["%%-%ss" % l for l in lengths]) result = [format % tuple(names)] result.append(format % tuple(rules)) for row in data: result.append(format % row) return "\n".join(result) ###### So I think the confusion here is just more anecdotal support to how much a short, badly named variable name can damage a program. What bothers me is that the code in the recipe itself shows a disregard for good variable names. What the heck does 't', 'pp', 'dd', or 'l' stand for, anyway? *grin* From dyoo at hkn.eecs.berkeley.edu Sat Dec 18 03:42:02 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Dec 18 03:42:10 2004 Subject: [Tutor] dbcp module In-Reply-To: <41C39215.9020404@tds.net> Message-ID: On Fri, 17 Dec 2004, Kent Johnson wrote: > The recipe you cite has the pp() function and an example of its use. It > sounds like that is what you want. Part of the pandemonium was my fault. I completely missed your earlier post here: http://mail.python.org/pipermail/tutor/2004-December/034107.html where, if I had been reading your initial response more closely, I would have been able to catch the real reason why Rene and I were getting so confused. Sorry about that. From carroll at tjc.com Sat Dec 18 08:15:44 2004 From: carroll at tjc.com (Terry Carroll) Date: Sat Dec 18 08:15:49 2004 Subject: [Tutor] am I missing another simpler structure? In-Reply-To: <00b401c4e3c9$8644e450$b4bc8651@xp> Message-ID: On Thu, 16 Dec 2004, Alan Gauld wrote: > In most debiggers ... So *that's* the trick to writing compact code! From bvande at po-box.mcgill.ca Sat Dec 18 14:31:22 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat Dec 18 14:31:30 2004 Subject: [Tutor] class overriding question Message-ID: <41C4312A.6030909@po-box.mcgill.ca> Hi all, instead of sleeping, I've been up all night finally attacking my apprehension about classes. I think I'm mostly getting the hang of it -- I managed to convert a 300 line procedural script into (what I think is) a fully object-oriented approach. :-) I made a lot of use of Mark Pilgrim's Dive Into Python , but Pilgrim said something that I'd like to check my understanding of. In section 5.5 he writes: > Guido, the original author of Python, explains method overriding this > way: "Derived classes may override methods of their base classes. > Because methods have no special privileges when calling other methods > of the same object, a method of a base class that calls another > method defined in the same base class, may in fact end up calling a > method of a derived class that overrides it. (For C++ programmers: > all methods in Python are effectively virtual.)" If that doesn't make > sense to you (it confuses the hell out of me), feel free to ignore > it. I just thought I'd pass it along. I think I get this, but my inexperience with classes and Pilgrim's rhetorical flourish make me doubt myself. I think the following three ways of saying it all say the same thing (to a greater or lesser degree of precision) as the quote from Guido above. Do I have the idea? Say class spam defines a method ham, and a method eggs, where ham calls eggs. Further say class foo is derived from spam and overrides its eggs method, but not its ham method. Then calling the ham method of an instance bar of foo (and thus calling the ham method of spam, as foo is a spam), will call the eggs method of foo, despite the fact that ham is a method of spam, and within spam points originally to spam's version of the eggs method. Alternatively, when calling bar.ham(), Python essentially says "OK, bar's a foo. Does foo have a ham method? No, but it is derived from spam. Does spam have a ham method? Yes, and it calls an eggs method. Since bar's a foo, I should first look to see if foo has an eggs method. (Nevermind that it was code in spam that started me off looking for eggs.) Golly good, it does. So I will use that and not even bother to look at spam's version of eggs." One other way: if we represent class inheritance as a tree, an a given instance is of a class at level n in the tree, any search for a method begins with the instance class and works up the tree to the ultimate base class at level 1, no matter how high up the tree the search for the method was initiated. And, in that search up the tree, the first correctly named method to be found will be used. (I'm using the mathematician's notion of trees with roots at the top.) Anyway, I hope I've both made sense and have got the idea right. Best to all, Brian vdB From kent37 at tds.net Sat Dec 18 14:53:18 2004 From: kent37 at tds.net (Kent Johnson) Date: Sat Dec 18 14:53:28 2004 Subject: [Tutor] class overriding question In-Reply-To: <41C4312A.6030909@po-box.mcgill.ca> References: <41C4312A.6030909@po-box.mcgill.ca> Message-ID: <41C4364E.2000804@tds.net> Yup, that's right! Attribute access (the dot operator '.') is an operation that happens at runtime, and each attribute access stands alone. Every attribute access goes through the same search path, starting with self, then the class (type) of self, finally the base classes. So, in your example, self.foo is found in the class of bar, while self.ham is found in the base class of the class of bar. Kent Brian van den Broek wrote: > Hi all, > > instead of sleeping, I've been up all night finally attacking my > apprehension about classes. I think I'm mostly getting the hang of it -- > I managed to convert a 300 line procedural script into (what I think is) > a fully object-oriented approach. :-) > > I made a lot of use of Mark Pilgrim's Dive Into Python > , but Pilgrim said something that I'd like > to check my understanding of. In section 5.5 > he > writes: > >> Guido, the original author of Python, explains method overriding this >> way: "Derived classes may override methods of their base classes. >> Because methods have no special privileges when calling other methods >> of the same object, a method of a base class that calls another >> method defined in the same base class, may in fact end up calling a >> method of a derived class that overrides it. (For C++ programmers: >> all methods in Python are effectively virtual.)" If that doesn't make >> sense to you (it confuses the hell out of me), feel free to ignore >> it. I just thought I'd pass it along. > > > I think I get this, but my inexperience with classes and Pilgrim's > rhetorical flourish make me doubt myself. I think the following three > ways of saying it all say the same thing (to a greater or lesser degree > of precision) as the quote from Guido above. Do I have the idea? > > Say class spam defines a method ham, and a method eggs, where ham calls > eggs. Further say class foo is derived from spam and overrides its eggs > method, but not its ham method. Then calling the ham method of an > instance bar of foo (and thus calling the ham method of spam, as foo is > a spam), will call the eggs method of foo, despite the fact that ham is > a method of spam, and within spam points originally to spam's version of > the eggs method. > > Alternatively, when calling bar.ham(), Python essentially says "OK, > bar's a foo. Does foo have a ham method? No, but it is derived from > spam. Does spam have a ham method? Yes, and it calls an eggs method. > Since bar's a foo, I should first look to see if foo has an eggs method. > (Nevermind that it was code in spam that started me off looking for > eggs.) Golly good, it does. So I will use that and not even bother to > look at spam's version of eggs." > > One other way: if we represent class inheritance as a tree, an a given > instance is of a class at level n in the tree, any search for a method > begins with the instance class and works up the tree to the ultimate > base class at level 1, no matter how high up the tree the search for the > method was initiated. And, in that search up the tree, the first > correctly named method to be found will be used. (I'm using the > mathematician's notion of trees with roots at the top.) > > Anyway, I hope I've both made sense and have got the idea right. > > Best to all, > > Brian vdB > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From mark.kels at gmail.com Sat Dec 18 17:03:10 2004 From: mark.kels at gmail.com (Mark Kels) Date: Sat Dec 18 17:03:13 2004 Subject: [Tutor] Tkinter questions In-Reply-To: <003a01c4e495$1a407b30$05be8651@xp> References: <003a01c4e495$1a407b30$05be8651@xp> Message-ID: > I find the easiest way is to create an PhotoImage object attach > the graphic file(jpg,bmp,gif) to that and assign the PhotoImage > object to the Button.image property. You can "animate" the image > by simply reassigning the file to the underlying PhotoImage onject. Thanks, but a practical explanation will be more helpful. > You mean print as in to a printer? > Personally I tend to generate an HTML file and use the > native OS Tools to print that. You can get fancy and > use the native OS priniting libraries but since its > very OS specific I find HTML is easier! OUtside Tkinter > you may well find the GUI libraries have done the cross > platform stuff for you, but not in Tkinter. Again, a practical explanation will be more helpful... > Define a full window? You mean full screen? > Thats usually better done as a parameter that the user can > set unless there is a very good reason not to. (Personally > I refuse to use any program that insists on opening full screen!) Full window or full screen is when the window of the program is all over the screen except the start bar (or whatever the blue line in the bottom of a windows xp called). And why you refuse to use any program that insists on opening full screen ? If it does then there must be a good reason for that... > If OTOH you mean that you don't want the DOS box in the background > thats easy, just rename the .py file to .pyw. But I suspect, > since you talk about cross platform you mean full screen. I did wanted a full screen, but this is very helpful too :) . Thanks allot . -- 1. The day Microsoft makes something that doesn't suck is probably the day they start making vacuum cleaners. 2. Unix is user friendly - it's just picky about it's friends. 3. Documentation is like sex: when it is good, it is very, very good. And when it is bad, it is better than nothing. - Dick Brandon From bvande at po-box.mcgill.ca Sat Dec 18 20:24:24 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sat Dec 18 20:26:06 2004 Subject: [Tutor] class overriding question In-Reply-To: <41C4364E.2000804@tds.net> References: <41C4312A.6030909@po-box.mcgill.ca> <41C4364E.2000804@tds.net> Message-ID: <41C483E8.7030400@po-box.mcgill.ca> Kent Johnson said unto the world upon 2004-12-18 08:53: > Yup, that's right! > > Attribute access (the dot operator '.') is an operation that happens at > runtime, and each attribute access stands alone. Every attribute access > goes through the same search path, starting with self, then the class > (type) of self, finally the base classes. So, in your example, self.foo > is found in the class of bar, while self.ham is found in the base class > of the class of bar. > > Kent > > Brian van den Broek wrote: Thanks Kent! I appreciate the external check. (The way Guido made the point was a bit gnostic, but not perhaps so much as Pilgrim's comment made it out.) Best to all, Brian vdB From keridee at jayco.net Sat Dec 18 21:58:54 2004 From: keridee at jayco.net (Jacob S.) Date: Sat Dec 18 23:20:15 2004 Subject: [Tutor] "TypeError: 'int' object is not callable"?? References: <008c01c4e48b$2907f170$a95328cf@JSLAPTOP> <41C369E7.2080109@tds.net> Message-ID: <008501c4e54f$bae7ff80$a75328cf@JSLAPTOP> Thanks for the explanation! Jacob Schmidt > Jacob S. wrote: > > Thank you! > > > > Wait, though. > > > > How do I do this? > > > > def differentnoofvars(*args,**kwargs): ## By the way, is it **kwargs or > > **kwds? > > Call it what you like, it's an ordinary function parameter. kwds is commonly used but you can use > kwargs. > > print kwargs > > another(kwargs) > > Should be another(**kwargs). If you call another(kwargs) then kwargs will be an ordinary parameter > of another and another would be defined as > def another(kwargs): > ... > > > > > def another(**kwargs): > > for x,y in kwagrs.items(): > > print "%s = %s" % (x,y) > > > > a = ['a=2','f=3','t=[1,2,3]'] ## A list of kwargs that I want to send > > Should be a dict, the **kwds parameter is a dict mapping keywords to values > a = {'a':2, 'f':3, 't':[1,2,3]} > > There really are two different and complementary things going on here, at the point of call and at > the point of function definition. > > At the point of call, you can pass a dictionary instead of using explicit, named parameters. For > example, given a function test() defined like this: > >>> def test(a, b): > ... print a, b > > you can call it with ordinary named arguments: > >>> test(a='foo', b='bar') > foo bar > > Or you can pass it a dictionary with the named arguments, using extended calling syntax: > >>> d= {'a':'foo', 'b':'bar'} > >>> test(**d) > foo bar > > > Inside the function, if you have a **kwds parameter, it will receive a dict containing any keyword > arguments not explicitly declared. This allows you to pass keyword parameters that you don't > anticipate when the function is defined. For example, > > >>> def test2(a, **kwds): > ... print a > ... for k,v in kwds.items(): > ... print k,v > > >>> test2(1) # No keywords > 1 > >>> test2(a=1) # a is a declared parameter so kwds is empty > 1 > >>> test2(1, b=2, c=3) # b and c are passed in kwds > 1 > c 3 > b 2 > > Kent > > > individually to differentnoofvars > > differentnoofvars(a) > > > > > > > >>>Hey, could you give an example? > >>>Thanks, > >>>Jacob > >>> > >>> > >>>>apply() is deprecated; it has been replaced by 'extended > >>> > >>>call syntax'. > >>>Instead of > >>> > >>>> apply(fn, args, kwds) > >>>>you can now write > >>>> fn(*args, **kwds) > >>>> > >>>>Kent > >> > >>Here is a quick example I came up with: > >> > >> > >>>>>def spam(*args, **kwargs): > >> > >>... print "Here are the args you supplied:" > >>... for item in args: > >>... print item > >>... print > >>... print "Here are the kwargs you supplied:" > >>... for key,value in kwargs.items(): > >>... print key, '=', value > >>... > >> > >>>>>spam(1,'a','eggs',s=0, p=1, a=2, m=3) > >> > >>Here are the args you supplied: > >>1 > >>a > >>eggs > >> > >>Here are the kwargs you supplied: > >>a = 2 > >>p = 1 > >>s = 0 > >>m = 3 > >> > >>In the case of the spam() function, 1, 'a', and 'eggs' are all put into > >>the sequence args (not sure if it is a list or tuple). The key/value > >>pairs are bundled into the dictionary kwargs. The arguments have to be > >>given in the right order though: > >> > >> > >>>>>spam(t=1, b=1, 'this', 'will', 'fail') > >> > >>Traceback (SyntaxError: non-keyword arg after keyword arg > >> > >>HTH! > >> > >>Christian > >>http://www.dowski.com > >> > >> > >> > >> > > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From keridee at jayco.net Sat Dec 18 23:19:21 2004 From: keridee at jayco.net (Jacob S.) Date: Sat Dec 18 23:20:25 2004 Subject: [Tutor] Python 2.4 IDLE Windows 2000 References: <41B07DA6.1030703@cso.atmel.com> <20041210202815.833898538.ejp@zomething.com> Message-ID: <008701c4e54f$c1915200$a75328cf@JSLAPTOP> Gee, I think I'm going to burst out in tears. Mike Hansen gave the solution to the very problem I'm having, yet, when I used the console version and deleted the custom color theme, it stopped giving me error messages, but it still won't start up without the console. I'm am still stunted of my python 2.4 experience. Help, please!!! Desperate, Jacob > Mike Hansen wrote of an idle IDLE: > > > That rooted out the problem. A while ago, I changed the colors to kind > > of match my VIM color theme(ps_color). When I did > > idlelib.PyShell.main(), IDLE came up with my custom color theme. > > However, there was a bunch of warnings about my theme. From IDLE, I > > deleted the theme. Now IDLE will launch normally. I'll set up the color > > > > theme later. Maybe older color themes aren't compatible with the newer > > IDLE? The color theme must have been laying around. I didn't brute > > force > > it in or anything like that. > > > > > >IDLE is a > > >part of the Standard Library, so it's actually possible to try turning > > on > > >individual pieces of it, one after the other. Maybe that will help us > > >debug what's going on. > > > > > >Start up your console version of Python, and try: > > > > > > > > >>>>import idlelib.PyShell > > >>>>idlelib.PyShell.main() > > >>>> > > > Just a +1 to Mike's problem (and the solution). For sake of Googlers searching on error output (which I've done before), here are the errors I was getting on my machine when trying to launch IDLE. Note, when I tried to open a .py file with IDLE the file would not open at all (and there were no error messages) - interesting that the whole process failed - is the missing error handling on the win or python side (no reason for these to have been fatal errors...) > > Ah, now I can enjoy 2.4. Thanks! > > my error output (win32): > > > >>> import idlelib.PyShell > >>> idlelib.PyShell.main() > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-background' > from theme 'sagecomments'. > returning default value: '#ffffff' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-foreground' > from theme 'sagecomments'. > returning default value: '#000000' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-background' > from theme 'sagecomments'. > returning default value: '#ffffff' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-foreground' > from theme 'sagecomments'. > returning default value: '#000000' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-background' > from theme 'sagecomments'. > returning default value: '#ffffff' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-foreground' > from theme 'sagecomments'. > returning default value: '#000000' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-background' > from theme 'sagecomments'. > returning default value: '#ffffff' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-foreground' > from theme 'sagecomments'. > returning default value: '#000000' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-background' > from theme 'sagecomments'. > returning default value: '#ffffff' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-foreground' > from theme 'sagecomments'. > returning default value: '#000000' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-background' > from theme 'sagecomments'. > returning default value: '#ffffff' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-foreground' > from theme 'sagecomments'. > returning default value: '#000000' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-background' > from theme 'sagecomments'. > returning default value: '#ffffff' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-foreground' > from theme 'sagecomments'. > returning default value: '#000000' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-background' > from theme 'sagecomments'. > returning default value: '#ffffff' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-foreground' > from theme 'sagecomments'. > returning default value: '#000000' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-background' > from theme 'sagecomments'. > returning default value: '#ffffff' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-foreground' > from theme 'sagecomments'. > returning default value: '#000000' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-background' > from theme 'sagecomments'. > returning default value: '#ffffff' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-foreground' > from theme 'sagecomments'. > returning default value: '#000000' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-background' > from theme 'sagecomments'. > returning default value: '#ffffff' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-foreground' > from theme 'sagecomments'. > returning default value: '#000000' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-background' > from theme 'sagecomments'. > returning default value: '#ffffff' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-foreground' > from theme 'sagecomments'. > returning default value: '#000000' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-background' > from theme 'sagecomments'. > returning default value: '#ffffff' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-foreground' > from theme 'sagecomments'. > returning default value: '#000000' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-background' > from theme 'sagecomments'. > returning default value: '#ffffff' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-foreground' > from theme 'sagecomments'. > returning default value: '#000000' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-background' > from theme 'sagecomments'. > returning default value: '#ffffff' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-foreground' > from theme 'sagecomments'. > returning default value: '#000000' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-background' > from theme 'sagecomments'. > returning default value: '#ffffff' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-foreground' > from theme 'sagecomments'. > returning default value: '#000000' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-background' > from theme 'sagecomments'. > returning default value: '#ffffff' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-foreground' > from theme 'sagecomments'. > returning default value: '#000000' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-background' > from theme 'sagecomments'. > returning default value: '#ffffff' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-foreground' > from theme 'sagecomments'. > returning default value: '#000000' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-background' > from theme 'sagecomments'. > returning default value: '#ffffff' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-foreground' > from theme 'sagecomments'. > returning default value: '#000000' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-background' > from theme 'sagecomments'. > returning default value: '#ffffff' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-foreground' > from theme 'sagecomments'. > returning default value: '#000000' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-background' > from theme 'sagecomments'. > returning default value: '#ffffff' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-foreground' > from theme 'sagecomments'. > returning default value: '#000000' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-background' > from theme 'sagecomments'. > returning default value: '#ffffff' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-foreground' > from theme 'sagecomments'. > returning default value: '#000000' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-background' > from theme 'sagecomments'. > returning default value: '#ffffff' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-foreground' > from theme 'sagecomments'. > returning default value: '#000000' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-background' > from theme 'sagecomments'. > returning default value: '#ffffff' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-foreground' > from theme 'sagecomments'. > returning default value: '#000000' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-background' > from theme 'sagecomments'. > returning default value: '#ffffff' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-foreground' > from theme 'sagecomments'. > returning default value: '#000000' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-background' > from theme 'sagecomments'. > returning default value: '#ffffff' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-foreground' > from theme 'sagecomments'. > returning default value: '#000000' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-background' > from theme 'sagecomments'. > returning default value: '#ffffff' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-foreground' > from theme 'sagecomments'. > returning default value: '#000000' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-background' > from theme 'sagecomments'. > returning default value: '#ffffff' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-foreground' > from theme 'sagecomments'. > returning default value: '#000000' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-background' > from theme 'sagecomments'. > returning default value: '#ffffff' > > Warning: configHandler.py - IdleConf.GetThemeDict - > problem retrieving theme element 'builtin-foreground' > from theme 'sagecomments'. > returning default value: '#000000' > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From keridee at jayco.net Sat Dec 18 22:35:20 2004 From: keridee at jayco.net (Jacob S.) Date: Sat Dec 18 23:20:33 2004 Subject: [Tutor] Difference between for i in range(len(object)) andfor iin object References: <002e01c4de4f$6cf2a340$67d98751@xp><20041212152745.67072.qmail@web53708.mail.yahoo.com><6.2.0.14.0.20041212092209.030d10a0@mail.mric.net> Message-ID: <008601c4e54f$be25c560$a75328cf@JSLAPTOP> > Thing is, for people like me, you generally either don't know that a > question is a dumb one until someone tells you the answer, (the 'of > course' moment), or until 5 minutes after you emailed > your query, you find the answer you were looking for... Amen! My life's story! Also, to Kumar. This is what you want. test_cor = [] for line in cor: test_cor.append(line.split('\t',1)[1]) ## This only works if there are only 3 columns Or, even simpler: test_cor = [line.split('\t',1)[1] for line in cor] HTH, Jacob From davholla2002 at yahoo.co.uk Sat Dec 18 23:21:08 2004 From: davholla2002 at yahoo.co.uk (David Holland) Date: Sat Dec 18 23:21:14 2004 Subject: [Tutor] Mainframe experience In-Reply-To: <20041218020034.04A161E400A@bag.python.org> Message-ID: <20041218222108.4355.qmail@web25406.mail.ukl.yahoo.com> Sadly in my IT company (which I better not name), mainframe experience seems to be a route to redundancy ! Fortunately I work with Oracle. === message truncated === ___________________________________________________________ ALL-NEW Yahoo! Messenger - all new features - even more fun! http://uk.messenger.yahoo.com From keridee at jayco.net Sat Dec 18 23:28:09 2004 From: keridee at jayco.net (Jacob S.) Date: Sat Dec 18 23:28:27 2004 Subject: [Tutor] Re: A simpler mousetrap References: Message-ID: <009201c4e550$e0105e50$a75328cf@JSLAPTOP> Also, just as interesting, yet probably less reliable: a = list(a) a[-3:] = 'bak' a = "".join(a) OR a = a.rstrip('pct') a = a+'bak' OR a = a.rstrip('pct')+'bak' ## Which is essentially the same thing OR a = a[:-3]+'bak' ETC. HTH, Jacob > x=os.path.splitext(a)[0]+'.bak' > > Ah, jolly good, looks a bit simpler. Thanks! > > Regards, > > Liam Clarke > > On Thu, 16 Dec 2004 09:44:03 +0100, Wolfram Kraus > wrote: > > Liam Clarke wrote: > > > Hi all, > > > > > > I'm writing some code, and I want to take a given path + filename, and > > > change the file extension to *.bak. > > > > > > In doing so, (entirely internal this function), I am assuming - > > > > > > That the file will always have an extension > > > Thathe extension will vary > > > But, it will follow the general DOS format of name.ext > > > > > > So, I came up with this - > > > > > > a="./tc/arc/gab.pct" > > > > > > x=a.replace(a[a.rfind('.'):len(a)],'.bak') > > > > > > x="./tc/arc/gab.bak" > > > > > > So, it works, but it feels a bit, well, hacky to me. Not nearly hacky > > > as using an regex though ; ) > > > > > > I thought about > > > > > > a="./tc/arc/gab.pct" > > > > > > aList=a.split('.') > > > aList[-1]='bak' > > > a=".".join(aList) > > > > > > but I'm wondering if there's a simpler way, as there usually seems to > > > be, and it's always so obvious once I'm shown it, like 6 down - Six on > > > vehicle live in the manse (VI + car). Obvious once you know. > > > > > > Regards, > > > > > > Liam Clarke > > > > Hey Liam! > > > > The os.path module is your friend, especially split and splitext: > > http://docs.python.org/lib/module-os.path.html > > > > HTH, > > Wolfram > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > -- > 'There is only one basic human right, and that is to do as you damn well please. > And with it comes the only basic human duty, to take the consequences. > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From keridee at jayco.net Sun Dec 19 01:21:41 2004 From: keridee at jayco.net (Jacob S.) Date: Sun Dec 19 01:23:17 2004 Subject: [Tutor] Vpython References: <12329567.1102561531889.JavaMail.root@daisy.psp.pas.earthlink.net> <7d7029e7041208192533496db5@mail.gmail.com> Message-ID: <00d801c4e560$dce590f0$a75328cf@JSLAPTOP> > > I was wondering were can I find some Vpython graphics program codes that are readily available. I have 2 that I am proud of. A simple function grapher Usage: >0.125*x**2 Graphs y = 1/8*x**2 >y = 1/x Graphs y = 1/x >clear Clears display window >r = t**2 Graphs polar function r = t**2 >remove lines Removes all axes, including polar axes, should a polar function be graphed after >return lines Returns all lines, so that they appear when appropriate. >x = sin(x**2)+log(x**2) Graphs the function... ------------------------------------------------------ from __future__ import division from visual import * import os from math import * ja = 0 def start(): for objects in scene.objects: objects.visible = 0 scene.title = "Function Grapher by Jacob, Inc." tem = raw_input('Are you on a desktop, or a notebook? ') if tem == 'desktop': scene.x = 365 if tem == 'notebook': scene.x = 574 scene.visible=1 scene.exit=0 scene.userspin = 0 scene.range=(10,10,1) scene.background=(1,1,1) global xaxis global yaxis xaxis = curve(color=color.black) xaxis.append(pos=(100,0,0)) xaxis.append(pos=(-100,0,0)) yaxis = curve(color=color.black) yaxis.append(pos=(0,100,0)) yaxis.append(pos=(0,-100,0)) global radiusaxis global radiusaxis2 radiusaxis = curve(pos=[(-100,-100),(100,100)],color=color.black) radiusaxis2 = curve(pos=[(-100,100),(100,-100)],color=color.black) radiusaxis.visible = 0 radiusaxis2.visible = 0 start() y = 3 m = 0 t = 0 d = 1 print """\ List of Commands: clear quit remove lines return lines Function Syntax: var = funct a,b where var = what and funct = f(what) and a,b = range """ print 'Please type in functions in below. ' while y != "": lists=[] y = raw_input('>') if y == 'clear': scene.visible=0 start() print "-"*36 continue elif y == 'quit': scene.visible = 0 del scene break elif y == 'remove lines': a = [radiusaxis,radiusaxis2,xaxis,yaxis] for x in a: x.visible = 0 d = 0 continue elif y == 'return lines': a = [radiusaxis,radiusaxis2,xaxis,yaxis] for x in a: x.visible = 1 d = 1 continue if y.count('=') == 1: y = y.split(' = ') type = y[0].lower() y = y[1] y = y.replace("y","x") if type == 'r': y = y.replace('x','t') if d == 1: radiusaxis.visible = 1 radiusaxis2.visible = 1 else: type = 'y' y = y.split(" ") if len(y) > 1: pass else: if type == 'r': y.append('0,5*pi') else: y.append('-10,10') range = y[1] y = y[0] range = range.split(",") min = float(eval(range[0])) max = float(eval(range[1])) lists.append(curve(color=(1,0,1))) x = min if type == 'y' or type == 'x': radiusaxis.visible = 0 radiusaxis2.visible = 0 while x >= min and x <= max: x = x+0.005 try: if eval(y) <= 15 and eval(y) >= -15: if type == 'y': lists[-1].append(pos=(x,eval(y),0)) elif type == 'x': lists[-1].append(pos=(eval(y),x,0)) else: lists.append(curve(color=(1,0,1))) except: pass elif type == 'r': m = 'eval(y)*cos(t)' n = 'eval(y)*sin(t)' t = min while t >= min and t <= max: try: lists[-1].append(pos=(eval(m),eval(n),0)) except: lists.append(curve(color=(1,0,1))) t = t+0.005 From keridee at jayco.net Sun Dec 19 03:06:09 2004 From: keridee at jayco.net (Jacob S.) Date: Sun Dec 19 03:08:19 2004 Subject: [Tutor] Nifty References: Message-ID: <005001c4e56f$9c4366d0$a55328cf@JSLAPTOP> I probably wouldn't be any help on projects, but I would probably learn stuff from it. I'm okay with it. Jacob Schmidt > >> I just got in contact with Nick Parlante of the Nifty > >> Assignments project; he's been collecting material on fun > >> projects: > >> > >> http://nifty.stanford.edu/ > > > What do others think? > Private channel or not, I'm in. (at least until classes spike up again in > early February) Sounds like a good way to burn through a winter. > > Heck I don't even know if I CAN convert C++ to Python but I've never let a > problem like language stop me from playing Chinese chess on boats in china > ... So even if I lack the ability, I'm for the idea of having running > 'projects' for the tutor list to do. That way it's driven a bit less by > homework problems. > > -- > > Programmer's mantra; Observe, Brainstorm, Prototype, Repeat > > David Broadwell > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From keridee at jayco.net Sun Dec 19 03:54:12 2004 From: keridee at jayco.net (Jacob S.) Date: Sun Dec 19 03:56:18 2004 Subject: [Tutor] least squares References: Message-ID: <008301c4e576$3dd33510$a55328cf@JSLAPTOP> Hey, now. I know that some of us are newbies to python, but that doesn't mean that we're all newbies to math concepts. (Even advanced ones.) Having said that, I will shut my fat mouth now because it will be my luck that the math is beyond what I can handle. I wouldn't mind seeing the code. Even if it is long, I wouldn't mind seeing it. A private message is acceptable for something too lengthy for the tutor list. Jacob > Hi Matt, > > > Ok. I have to admit that my mathematical maturity is actually a little > low, but I'll try to follow along. But this really doesn't sounds like a > problem specific to Python though, but more of a math problem. > > So you may actually want to talk with folks with a real math background; I > would not be mathematically mature enough to know if your code is correct. > I'd strongly recommend talking to folks on the 'sci.math' or > 'sci.math.num-analysis' newsgroups. > > > I haven't seen your code, so I'm still in the dark about how it works or > what its capabilities are. I'll make a few assumptions that might not be > right, but I have to start somewhere. *grin* > > Does your code provide a way at getting at all possible solutions, or only > one particular solution? If so, then you can just filter out for > solutions that satisfy the property you want. > > For example, we can produce a function that generates all squares in the > world: > > ### > >>> import itertools > >>> def allSquares(): > ... for i in itertools.count(): > ... yield i*i > ... > >>> squares = allSquares() > >>> squares.next() > 0 > >>> squares.next() > 1 > >>> squares.next() > 4 > >>> squares.next() > 9 > >>> squares.next() > 16 > >>> squares.next() > 25 > ### > > > I can keep calling 'next()' on my 'squares' iteration, and keep getting > squares. Even though this can produce an infinite sequence of answers, we > can still apply a filter on this sequence, and pick out the ones that are > "palindromic" in terms of their digits: > > ### > >>> def palindromic(n): > ... "Returns true if n is 'palindromic'." > ... return str(n) == str(n)[::-1] > ... > >>> filteredSquares = itertools.ifilter(palindromic, allSquares()) > >>> filteredSquares.next() > 0 > >>> filteredSquares.next() > 1 > >>> filteredSquares.next() > 4 > >>> filteredSquares.next() > 9 > >>> filteredSquares.next() > 121 > >>> filteredSquares.next() > 484 > >>> filteredSquares.next() > 676 > ### > > > This sequence-filtering approach takes advantage of Python's ability to > work on a iteration of answers. If your program can be written to produce > an infinite stream of answers, and if a solution set with all positive > coefficients is inevitable in that stream, then you can take this > filtering approach, and just capture the first solution that matches your > constraints. > > > > Similarly, if your program only produces a single solution, does it do so > through an "iterative" algorithm? By iterative, I mean: does it start off > with an initial guess and apply a process to improve that guess until the > solution is satisfactory? > > For others on the Tutor list, here is an "iterative" way to produce the > square root of a number: > > ### > def mysqrt(x): > guess = 1.0 ## initial guess > while not goodEnough(guess, x): > guess = improve(guess, x) > return guess > > def improve(guess, x): > """Improves the guess of the square root of x.""" > return average(guess, x / guess) > > def average(x, y): > return (x + y) / 2.0 > > def goodEnough(guess, x): > """Returns true if guess is close enough to the square root of x.""" > return abs(guess**2 - x) < 0.00001 > ### > > (adapted/ripped off from material in SICP: > http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-10.html#%_sec_1.1.7) > > > > If your program tries to solve the problem through an iterative process, > then, again, does it inevitably produce a solution where all the constant > coefficients 'Cn' are positive? If so, maybe you can just continue to > produce better and better solutions until its satisfactory, until all the > coefficients are positive. > > > Otherwise, without looking at your code, I'm stuck. *grin* And even if I > do see your code, I might be stuck still. If your code is short, feel > free to post it up, and we'll see how far we can get. But you really may > want to talk with someone who has a stronger math background. > > Good luck to you! > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From bvande at po-box.mcgill.ca Sun Dec 19 03:58:05 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sun Dec 19 04:13:32 2004 Subject: [Tutor] Nifty In-Reply-To: <005001c4e56f$9c4366d0$a55328cf@JSLAPTOP> References: <005001c4e56f$9c4366d0$a55328cf@JSLAPTOP> Message-ID: <41C4EE3D.3090806@po-box.mcgill.ca> Jacob S. said unto the world upon 2004-12-18 21:06: > I probably wouldn't be any help on projects, but I would probably learn > stuff from it. > I'm okay with it. > Jacob Schmidt > > >>>>I just got in contact with Nick Parlante of the Nifty >>>>Assignments project; he's been collecting material on fun >>>>projects: >>>> >>>>http://nifty.stanford.edu/ >> >>>What do others think? >> >>Private channel or not, I'm in. (at least until classes spike up again in >>early February) Sounds like a good way to burn through a winter. >> >>David Broadwell Hi Jacob, I've privately sent you what correspondence there has been amongst those who expressed interest. If/once we pick a common project to undertake, I will post an announcement here. (We will also likely put up a wiki page somewhere.) Best to all, Brian vdB From keridee at jayco.net Sun Dec 19 04:16:21 2004 From: keridee at jayco.net (Jacob S.) Date: Sun Dec 19 04:16:43 2004 Subject: [Tutor] listing all combinations of elements of a list References: <41BCAF6C.4060607@fastmail.fm> <00ea01c4e11d$191f4f40$9c8f8651@xp> Message-ID: <008c01c4e579$28845060$a55328cf@JSLAPTOP> Am I wrong, or is that what the module sets is for? I don't remember if python 2.3 has it, but python2.4 has it available. >>> import sets >>> s = sets.Set >>> a = s([1,2,3]) >>> a Set([1, 2, 3]) >>> a.update([1,1,2,2,3,3,4,4,5,5]) >>> a Set([1, 2, 3, 4, 5]) >>> HTH, Jacob Schmidt > > def combination(items) > > list = [] > > for i in range(0,len(items)): > > for j in range(0,len(items)): > > for i in items: > for j in items: > > Is both shorter and faster - no len() function calls. > > Or if you want to use indices: > > size = len(items) # only calculate once, it won't change! > lst = [] # don't use builtin function names for > variables > for i in range(0,size) > for j in range(i+1,size) > lst.append(....) > return lst > > That saves a lot of len() calls and a comparison. > Also it avoids iterating over the whole list each time. > > > > My problems with this code being that a) code I write is usually > pretty > > inefficient, b) it doesn't extend to subsets of size > 2, and c) it > uses > > nested loops, which I have gathered from some previous discussions > on > > this list to be less than ideal. > > I've tidied up a little but I think nested loops are a necessary evil > in > this case - although somebody is sure to prove me wrong! :-) > > HTH, > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From flaxeater at yahoo.com Sun Dec 19 06:07:28 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Sun Dec 19 06:07:31 2004 Subject: [Tutor] Nifty Message-ID: <20041219050728.53559.qmail@web54301.mail.yahoo.com> I think it's a great idea, I would like to participate also. Brian van den Broek wrote: > Jacob S. said unto the world upon 2004-12-18 21:06: > >> I probably wouldn't be any help on projects, but I would probably learn >> stuff from it. >> I'm okay with it. >> Jacob Schmidt >> >> >>>>> I just got in contact with Nick Parlante of the Nifty >>>>> Assignments project; he's been collecting material on fun >>>>> projects: >>>>> >>>>> http://nifty.stanford.edu/ >>>> >>> >>>> What do others think? >>> >>> >>> Private channel or not, I'm in. (at least until classes spike up >>> again in >>> early February) Sounds like a good way to burn through a winter. >> > > >>> >>> David Broadwell >> > > Hi Jacob, > > I've privately sent you what correspondence there has been amongst > those who expressed interest. > > If/once we pick a common project to undertake, I will post an > announcement here. (We will also likely put up a wiki page somewhere.) > > Best to all, > > Brian vdB > __________________________________ Do you Yahoo!? Send a seasonal email greeting and help others. Do good. http://celebrity.mail.yahoo.com From alan.gauld at freenet.co.uk Sun Dec 19 09:42:37 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Dec 19 09:42:29 2004 Subject: [Tutor] Re: A simpler mousetrap Message-ID: <006701c4e5a6$b1f45c50$aeaa8851@xp> Rats, a premature posting sorry. > > Also, just as interesting, yet probably less reliable: > > > > a = list(a) > > a[-3:] = 'bak' > > a = "".join(a) > > > The problem with all of these versions is they assume the > extension will be three characters long. In DOS it could be *up to* > three characters, but in Windows post 95 the extension can be longer, > eg .html is often seen. And on non Windows platforms loing extensions > are common. > > > x=os.path.splitext(a)[0]+'.bak' Whereas this technique handles the different size extensions safely. Alan G. From alan.gauld at freenet.co.uk Sun Dec 19 09:40:36 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Dec 19 09:45:33 2004 Subject: [Tutor] Re: A simpler mousetrap References: <009201c4e550$e0105e50$a75328cf@JSLAPTOP> Message-ID: <006201c4e5a6$69ff5710$aeaa8851@xp> > Also, just as interesting, yet probably less reliable: > > a = list(a) > a[-3:] = 'bak' > a = "".join(a) > The problem with all of these versions is they assume the extension will be three characters long. In DOS it could be *up to* three characters, but in Windows post 95 the extension can be longer, eg .html is often seen. And on non Windows platforms loing extensions are common. > OR > > a = a.rstrip('pct') > a = a+'bak' > > OR > > a = a.rstrip('pct')+'bak' ## Which is essentially the same thing > > OR > > a = a[:-3]+'bak' > > ETC. > > HTH, > Jacob > > > x=os.path.splitext(a)[0]+'.bak' > > > > Ah, jolly good, looks a bit simpler. Thanks! > > > > Regards, > > > > Liam Clarke > > > > On Thu, 16 Dec 2004 09:44:03 +0100, Wolfram Kraus > > wrote: > > > Liam Clarke wrote: > > > > Hi all, > > > > > > > > I'm writing some code, and I want to take a given path + filename, and > > > > change the file extension to *.bak. > > > > > > > > In doing so, (entirely internal this function), I am assuming - > > > > > > > > That the file will always have an extension > > > > Thathe extension will vary > > > > But, it will follow the general DOS format of name.ext > > > > > > > > So, I came up with this - > > > > > > > > a="./tc/arc/gab.pct" > > > > > > > > x=a.replace(a[a.rfind('.'):len(a)],'.bak') > > > > > > > > x="./tc/arc/gab.bak" > > > > > > > > So, it works, but it feels a bit, well, hacky to me. Not nearly hacky > > > > as using an regex though ; ) > > > > > > > > I thought about > > > > > > > > a="./tc/arc/gab.pct" > > > > > > > > aList=a.split('.') > > > > aList[-1]='bak' > > > > a=".".join(aList) > > > > > > > > but I'm wondering if there's a simpler way, as there usually seems to > > > > be, and it's always so obvious once I'm shown it, like 6 down - Six on > > > > vehicle live in the manse (VI + car). Obvious once you know. > > > > > > > > Regards, > > > > > > > > Liam Clarke > > > > > > Hey Liam! > > > > > > The os.path module is your friend, especially split and splitext: > > > http://docs.python.org/lib/module-os.path.html > > > > > > HTH, > > > Wolfram > > > > > > _______________________________________________ > > > Tutor maillist - Tutor@python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > -- > > 'There is only one basic human right, and that is to do as you damn well > please. > > And with it comes the only basic human duty, to take the consequences. > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > From jerimed at myrealbox.com Sun Dec 19 11:35:04 2004 From: jerimed at myrealbox.com (Eri Mendz) Date: Sun Dec 19 11:35:06 2004 Subject: [Tutor] OT: Flow chart Message-ID: <1103452504.92b04ebcjerimed@myrealbox.com> Hello All, I'm looking for any good link or tutorial of flow charting i can use related for programming. Maybe having symbols and similar stuffs. This may sound old-fashion or antiquated to you but i feel this may help me with the logic and flow controls when i do code in python. Anyone pointing me to the right direction is appreciated. -- regards, erimendz -- regards, eri mendz From godoy at ieee.org Sun Dec 19 12:07:23 2004 From: godoy at ieee.org (Jorge Luiz Godoy Filho) Date: Sun Dec 19 12:10:42 2004 Subject: [Tutor] Re: OT: Flow chart References: <1103452504.92b04ebcjerimed@myrealbox.com> Message-ID: <1660356.SpbNPBx9Iz@strongwill.g2ctech> Eri Mendz, Domingo 19 Dezembro 2004 08:35, wrote: > Hello All, > > I'm looking for any good link or tutorial of flow charting i can use > related for programming. Maybe having symbols and similar stuffs. This may > sound old-fashion or antiquated to you but i feel this may help me with > the logic and flow controls when i do code in python. > > Anyone pointing me to the right direction is appreciated. Take a look at UML. It has several diagrams that help a lot and, depending on the tool you're using, you can even generate the skeleton of the code from the diagrams. If you're on a *nix platform, take a look at Umbrello. Be seeing you, Godoy. From pythontut at pusspaws.net Sun Dec 19 13:11:35 2004 From: pythontut at pusspaws.net (Dave S) Date: Sun Dec 19 13:11:42 2004 Subject: [Tutor] Problems with class, no output Message-ID: <41C56FF7.4030005@pusspaws.net> Hello again :-) , This script is very much a work in progress, and I think only the second time I have tried classes. What I expected it to do was to at least print 'hi there' so I know its alive, then dump some status info to my log program. It does zip, executes OK but no output. I just know you guys are going to tell me I have missed a () or . somewhere Any help gratefully appreciated Dave #!/usr/bin/env python # -*- coding: iso8859_1 -*- """ arch_data.py 1.0 This is the read archive data script """ from os import listdir from cPickle import load from logger import log from config import data_dir debug=True class Arch_data: def __init__(self): self.file_names=listdir(data_dir) self.file_names.sort() self.file_name_ptr=0 def read_next(): """ when executed reads next data file from data_dir extracts date, time,julian day,sequence count & flag from the file name. Also adds last_file flag and contents of file to the list of returned parameters """ print 'hi there' file_name=self.file_names[self.file_name_ptr] # Ignore the archive_read.py utility script in the data dir ## if file_name=='archive_read.py': ## if debug: ## log('II','arch_data','Ignoring "archive_read.py"') ## self.file_name_ptr+=1 ## read.next() ## return # Extract info from the encoded filename :-) file_yy=file_name[:4] file_mm=file_name[4:6] file_dd=file_name[6:8] file_HH=file_name[9:11] file_MM=file_name[11:13] file_jj=file_name[14:17] file_seq=file_name[18:21] file_flag=file_name[22:24] if debug: log('II','arch_data','unpickling '+file_name) pickle_file=open(data_dir+file_name,'r') file=load(pickle_file) pickle_file.close() print file_yy,file_mm,file_dd,file_HH,file_MM,file_jj,file_seq,file_flag self.file_name_ptr+=1 arch_data=Arch_data() arch_data.read_next From pythontut at pusspaws.net Sun Dec 19 13:27:01 2004 From: pythontut at pusspaws.net (Dave S) Date: Sun Dec 19 13:27:08 2004 Subject: [Tutor] Problems with class, no output In-Reply-To: <41C56FF7.4030005@pusspaws.net> References: <41C56FF7.4030005@pusspaws.net> Message-ID: <41C57395.6090300@pusspaws.net> Dave S wrote: > Hello again :-) , > > This script is very much a work in progress, and I think only the > second time I have tried classes. What I expected it to do was to at > least print 'hi there' so I know its alive, then dump some status info > to my log program. It does zip, executes OK but no output. > > I just know you guys are going to tell me I have missed a () or . > somewhere > > Any help gratefully appreciated > Dave > > > > > > #!/usr/bin/env python > # -*- coding: iso8859_1 -*- > > """ > arch_data.py 1.0 This is the read archive data script > """ > > from os import listdir > from cPickle import load > from logger import log > > from config import data_dir > > debug=True > class Arch_data: > def __init__(self): > self.file_names=listdir(data_dir) > self.file_names.sort() > self.file_name_ptr=0 > def read_next(): > """ > when executed reads next data file from data_dir extracts date, > time,julian day,sequence count & flag from the file name. > Also adds last_file flag and contents of file to the > list of returned > parameters > """ > print 'hi there' > file_name=self.file_names[self.file_name_ptr] > # Ignore the archive_read.py utility script in the data dir > ## if file_name=='archive_read.py': > ## if debug: > ## log('II','arch_data','Ignoring "archive_read.py"') > ## self.file_name_ptr+=1 > ## read.next() > ## return > # Extract info from the encoded filename :-) > file_yy=file_name[:4] > file_mm=file_name[4:6] > file_dd=file_name[6:8] > file_HH=file_name[9:11] > file_MM=file_name[11:13] > file_jj=file_name[14:17] > file_seq=file_name[18:21] > file_flag=file_name[22:24] > if debug: > log('II','arch_data','unpickling '+file_name) > pickle_file=open(data_dir+file_name,'r') > file=load(pickle_file) > pickle_file.close() > print > file_yy,file_mm,file_dd,file_HH,file_MM,file_jj,file_seq,file_flag > > self.file_name_ptr+=1 > arch_data=Arch_data() > arch_data.read_next > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > Dope, too quick to ask for help - sorry def read_next(self): and arch_data.read_next() sorted it :-[ From kent37 at tds.net Sun Dec 19 14:25:33 2004 From: kent37 at tds.net (Kent Johnson) Date: Sun Dec 19 14:25:40 2004 Subject: [Tutor] Problems with class, no output In-Reply-To: <41C56FF7.4030005@pusspaws.net> References: <41C56FF7.4030005@pusspaws.net> Message-ID: <41C5814D.6090204@tds.net> Dave, For some reason the indentation is very strange in this code. I think it must have something to do with how you posted it (or my mailer is messing it up?), as it would be a syntax error at runtime. If you can have more consistent indentation in your posts it will make them much easier to read. Glad you got it working! Kent Dave S wrote: > Hello again :-) , > > This script is very much a work in progress, and I think only the second > time I have tried classes. What I expected it to do was to at least > print 'hi there' so I know its alive, then dump some status info to my > log program. It does zip, executes OK but no output. > > I just know you guys are going to tell me I have missed a () or . somewhere > > Any help gratefully appreciated > Dave > > > > > > #!/usr/bin/env python > # -*- coding: iso8859_1 -*- > > """ > arch_data.py 1.0 This is the read archive data script > """ > > from os import listdir > from cPickle import load > from logger import log > > from config import data_dir > > debug=True > class Arch_data: > def __init__(self): > self.file_names=listdir(data_dir) > self.file_names.sort() > self.file_name_ptr=0 > def read_next(): > """ > when executed reads next data file from data_dir extracts date, > time,julian day,sequence count & flag from the file name. > Also adds last_file flag and contents of file to the list > of returned > parameters > """ > print 'hi there' > file_name=self.file_names[self.file_name_ptr] > # Ignore the archive_read.py utility script in the data dir > ## if file_name=='archive_read.py': > ## if debug: > ## log('II','arch_data','Ignoring "archive_read.py"') > ## self.file_name_ptr+=1 > ## read.next() > ## return > # Extract info from the encoded filename :-) > file_yy=file_name[:4] > file_mm=file_name[4:6] > file_dd=file_name[6:8] > file_HH=file_name[9:11] > file_MM=file_name[11:13] > file_jj=file_name[14:17] > file_seq=file_name[18:21] > file_flag=file_name[22:24] > if debug: > log('II','arch_data','unpickling '+file_name) > pickle_file=open(data_dir+file_name,'r') > file=load(pickle_file) > pickle_file.close() > print > file_yy,file_mm,file_dd,file_HH,file_MM,file_jj,file_seq,file_flag > > self.file_name_ptr+=1 > arch_data=Arch_data() > arch_data.read_next > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From bugracakir at gmail.com Sun Dec 19 16:33:19 2004 From: bugracakir at gmail.com (Bugra Cakir) Date: Sun Dec 19 16:33:23 2004 Subject: [Tutor] Matrix Message-ID: <5a00f624041219073357d58e88@mail.gmail.com> hi, I want to create a matrix in Python. For example 3x4 how can i create this? thanks From aztech1200 at yahoo.com Sun Dec 19 16:52:37 2004 From: aztech1200 at yahoo.com (Aztech Guy) Date: Sun Dec 19 16:52:40 2004 Subject: [Tutor] Vpython In-Reply-To: <00d801c4e560$dce590f0$a75328cf@JSLAPTOP> Message-ID: <20041219155237.5138.qmail@web53304.mail.yahoo.com> Hey, that's pretty good. Tried it out. VPython is cool too. --- "Jacob S." wrote: > > > I was wondering were can I find some Vpython > graphics program codes that > are readily available. > > I have 2 that I am proud of. > > A simple function grapher > Usage: > >0.125*x**2 > > Graphs y = 1/8*x**2 > > >y = 1/x > > Graphs y = 1/x > > >clear > > Clears display window > > >r = t**2 > > Graphs polar function r = t**2 > > >remove lines > > Removes all axes, including polar axes, should a > polar function be graphed > after > > >return lines > > Returns all lines, so that they appear when > appropriate. > > >x = sin(x**2)+log(x**2) > > Graphs the function... > > > ------------------------------------------------------ > > from __future__ import division > from visual import * > import os > from math import * > ja = 0 > > def start(): > for objects in scene.objects: > objects.visible = 0 > scene.title = "Function Grapher by Jacob, Inc." > tem = raw_input('Are you on a desktop, or a > notebook? ') > if tem == 'desktop': > scene.x = 365 > if tem == 'notebook': > scene.x = 574 > scene.visible=1 > scene.exit=0 > scene.userspin = 0 > scene.range=(10,10,1) > scene.background=(1,1,1) > global xaxis > global yaxis > xaxis = curve(color=color.black) > xaxis.append(pos=(100,0,0)) > xaxis.append(pos=(-100,0,0)) > yaxis = curve(color=color.black) > yaxis.append(pos=(0,100,0)) > yaxis.append(pos=(0,-100,0)) > global radiusaxis > global radiusaxis2 > radiusaxis = > curve(pos=[(-100,-100),(100,100)],color=color.black) > radiusaxis2 = > curve(pos=[(-100,100),(100,-100)],color=color.black) > radiusaxis.visible = 0 > radiusaxis2.visible = 0 > > start() > y = 3 > m = 0 > t = 0 > d = 1 > print """\ > List of Commands: > clear > quit > remove lines > return lines > > Function Syntax: > var = funct a,b > where var = what > and funct = f(what) > and a,b = range > """ > > print 'Please type in functions in below. ' > while y != "": > lists=[] > y = raw_input('>') > if y == 'clear': > scene.visible=0 > start() > print "-"*36 > continue > elif y == 'quit': > scene.visible = 0 > del scene > break > elif y == 'remove lines': > a = [radiusaxis,radiusaxis2,xaxis,yaxis] > for x in a: > x.visible = 0 > d = 0 > continue > elif y == 'return lines': > a = [radiusaxis,radiusaxis2,xaxis,yaxis] > for x in a: > x.visible = 1 > d = 1 > continue > if y.count('=') == 1: > y = y.split(' = ') > type = y[0].lower() > y = y[1] > y = y.replace("y","x") > if type == 'r': > y = y.replace('x','t') > if d == 1: > radiusaxis.visible = 1 > radiusaxis2.visible = 1 > else: > type = 'y' > y = y.split(" ") > if len(y) > 1: > pass > else: > if type == 'r': > y.append('0,5*pi') > else: > y.append('-10,10') > range = y[1] > y = y[0] > range = range.split(",") > min = float(eval(range[0])) > max = float(eval(range[1])) > lists.append(curve(color=(1,0,1))) > x = min > if type == 'y' or type == 'x': > radiusaxis.visible = 0 > radiusaxis2.visible = 0 > while x >= min and x <= max: > x = x+0.005 > try: > if eval(y) <= 15 and eval(y) >= -15: > if type == 'y': > > lists[-1].append(pos=(x,eval(y),0)) > elif type == 'x': > > lists[-1].append(pos=(eval(y),x,0)) > else: > > lists.append(curve(color=(1,0,1))) > except: > pass > elif type == 'r': > m = 'eval(y)*cos(t)' > n = 'eval(y)*sin(t)' > t = min > while t >= min and t <= max: > try: > > lists[-1].append(pos=(eval(m),eval(n),0)) > except: > lists.append(curve(color=(1,0,1))) > t = t+0.005 > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > __________________________________ Do you Yahoo!? Send holiday email and support a worthy cause. Do good. http://celebrity.mail.yahoo.com From alan.gauld at freenet.co.uk Sun Dec 19 18:23:49 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Dec 19 18:23:32 2004 Subject: [Tutor] OT: Flow chart References: <1103452504.92b04ebcjerimed@myrealbox.com> Message-ID: <007e01c4e5ef$81442dd0$aeaa8851@xp> > I'm looking for any good link or tutorial of flow charting A good resource for all notations related to software design is at smartdraw.com: http://www.smartdraw.com/exp/tec/tutorials/software.htm But flow charts are more generic so info about them can be found here: http://www.smartdraw.com/tutorials/flowcharts/resources.htm Not entirely unbiased since I do use their tool for my personal use and prefer it to Visio, but the diagram tutorials are free. And one flowchartoing tutor I can recommend is: http://home.att.net/~dexter.a.hansen/flowchart/flowchart.htm Downloadable as PDF too. Alan G. From keridee at jayco.net Sun Dec 19 06:16:06 2004 From: keridee at jayco.net (Jacob S.) Date: Sun Dec 19 18:42:52 2004 Subject: [Tutor] Printing two elements in a list References: <20041207220932.9164.qmail@web53703.mail.yahoo.com> Message-ID: <000301c4e5f2$270323a0$d25328cf@JSLAPTOP> Would this work for you? a = ['Name = stuff','CGTATAGCTAGCTA','Name = stuff','CGATATGCCGGCTA'] for index,thing in enumerate(a): if "Name=" in thing: del a[index] I know, that it might be slow, but I thought that maybe it would hold its own because it doesn't have to import the re module, everything's builtin, etc. HTH, Jacob Hello group, > Thank you very much for your kind replies. In fact I > survived to pull out what I needed by going with > Kent's tip by enumerating on iterator. > > The problem with me is suddenly I embarked on > something big problem and I am surviving it in pieces > by writing pieces of code. > > > I have another question: > To be brief: > > My list contains some elements that I do not want and > I want to remove unwanted elements in my list: > > My TEXT file looks like this: > > Name=32972_at > Cell1=xxx xxx N control 32972_at > Cell1=xxx xxx N control 32972_at > Cell1=xxx xxx N control 32972_at > Cell1=xxx xxx N control 32972_at > Name=3456_at > Cell1=xxx xxx N control 3456_at > Cell1=xxx xxx N control 3456_at > Cell1=xxx xxx N control 3456_at > Cell1=xxx xxx N control 3456_at > ......... ... x xxxxxxxxxxxxxxx > (34K lines) > > I want to remove Name=Xxxx_at identifiers. > > > My List: > ['Name=32972_at', > 'Cell1=432\t118\tN\tcontrol\t32972_at\t0\t13\tA\tA\tA\t0\t75952\t-1\t-1\t99\ t', > 'Cell2=432\t117\tN\tcontrol\t32972_at\t0\t13\tA\tT\tA\t0\t75312\t-1\t-1\t99\ t', > 'Cell3=499\t632\tN\tcontrol\t32972_at\t1\t13\tC\tC\tC\t1\t404979\t-1\t-1\t99 \t'] > > > I tried to resolve in this way: > > >>>pat = re.compile('Name') > >>> for i in range(len(cord)): > x = pat.search(cord[i]) > cord.remove(x) > > I know I am wrong here because I do not know how to > search and remove an element in a list. Can any one > please help me. > > on Page 98, chapter Lists and dictionaries of mark > lutz's learning python. It is mentioned in table 6-1 : > L2.append(4) Methods: grow,sort,search,reverse etc. > > > Although not much is covered on this aspect in this > book, I failed to do more operations on list. > > Looking forward for help from tutors. > > Thank you. > Kumar. > > > > > > > --- Kent Johnson wrote: > > > kumar, > > > > Looking at the quantity and structure of your data I > > think the search you are doing is going to be > > pretty slow - you will be doing 4504 * 398169 = > > 1,793,353,176 string searches. > > > > Where does the seq data come from? Could you > > consolidate the pairs of lines into a single record? > > If > > you do that and extract the '399:559' portion, you > > could build a dict that maps '399:559' to the > > full record. Looking up '399:559' in the dictionary > > would be much, much faster than searching the > > entire list. > > > > If you have multiple entries for '399:559' you could > > have the dict map to a list. > > > > Kent > > > > kumar s wrote: > > > > > >>>>len(x) > > > > > > 4504 > > > > > >>>>x[1:10] > > > > > > ['454:494', '319:607', '319:608', '322:289', > > > '322:290', '183:330', '183:329', '364:95', > > '364:96'] > > > > > >>>>len(seq) > > > > > > 398169 > > > > > >>>>seq[0:4] > > > > > > ['>probe:HG-U95Av2:1000_at:399:559; > > > Interrogation_Position=1367; Antisense;', > > > 'TCTCCTTTGCTGAGGCCTCCAGCTT', > > > '>probe:HG-U95Av2:1000_at:544:185; > > > Interrogation_Position=1379; Antisense;', > > > 'AGGCCTCCAGCTTCAGGCAGGCCAA'] > > > > > > > > > > > >>>>for ele1 in x: > > > > > > for ele2 in seq: > > > if ele1 in ele2: > > > print ele2 > > > > > > > > > > > >>probe:HG-U95Av2:31358_at:454:493; > > > > > > Interrogation_Position=132; Antisense; > > > > > >>probe:HG-U95Av2:31358_at:319:607; > > > > > > Interrogation_Position=144; Antisense; > > > > > > > > > > > > > > > > > > > > > How Do I WANT: > > > > > > I want to print get an output like this: > > > > > > > > > > > >>probe:HG-U95Av2:1000_at:399:559; > > > > > > Interrogation_Position=1367; Antisense;' > > > TCTCCTTTGCTGAGGCCTCCAGCTT > > > > > > > > >>probe:HG-U95Av2:1000_at:544:185; > > > > > > Interrogation_Position=1379; Antisense; > > > AGGCCTCCAGCTTCAGGCAGGCCAA > > > > > > > > > can any one please suggest what is going wrong in > > my > > > statements and how can I get it. > > > > > > Thank you. > > > Kumar > > > > > > > > > > > > __________________________________ > > > Do you Yahoo!? > > > Yahoo! Mail - 250MB free storage. Do more. Manage > > less. > > > http://info.mail.yahoo.com/mail_250 > > > _______________________________________________ > > > Tutor maillist - Tutor@python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > __________________________________ > Do you Yahoo!? > Yahoo! Mail - now with 250MB free storage. Learn more. > http://info.mail.yahoo.com/mail_250 > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From pythontut at pusspaws.net Sun Dec 19 20:04:50 2004 From: pythontut at pusspaws.net (Dave S) Date: Sun Dec 19 20:04:57 2004 Subject: [Tutor] Problems with class, no output In-Reply-To: <41C5814D.6090204@tds.net> References: <41C56FF7.4030005@pusspaws.net> <41C5814D.6090204@tds.net> Message-ID: <41C5D0D2.6060601@pusspaws.net> Kent Johnson wrote: > Dave, > > For some reason the indentation is very strange in this code. I think > it must have something to do with how you posted it (or my mailer is > messing it up?), as it would be a syntax error at runtime. If you can > have more consistent indentation in your posts it will make them much > easier to read. > > Glad you got it working! > > Kent > > Point taken, I had copied & pasted into my email, looked OK when I pasted it, but on re-opening my own email, Yuk. I will attatch file in future, Cheers Dave From bvande at po-box.mcgill.ca Sun Dec 19 20:31:01 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sun Dec 19 20:31:15 2004 Subject: [Tutor] Matrix In-Reply-To: <5a00f624041219073357d58e88@mail.gmail.com> References: <5a00f624041219073357d58e88@mail.gmail.com> Message-ID: <41C5D6F5.3050804@po-box.mcgill.ca> Bugra Cakir said unto the world upon 2004-12-19 10:33: > hi, > > I want to create a matrix in Python. For example 3x4 how can i > create this? thanks > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > Hi, at least two ways using only builtins occur to me: 1) A list of lists: .>>> row1 = [4, 6, 8, 1] .>>> row2 = [2, 5, 1, 3] .>>> row3 = [2, 1, 2, 8] .>>> my_matrix_as_lists = [row1, row2, row3] .>>> print my_matrix_as_lists[1][1] 5 Note that >>> row1[1] 6 since indicies start at 0. 2) To get around that, and be more efficient with matricies with many empty cells: .>>> my_matrix_as_dict = {(1,1):4, (1,2):6, (1,3):8, (2,1):56, (2,3):12, (3,1):3, (3,2):3} .>>> my_matrix_as_dict[(3,1)] 3 .>>> my_matrix_as_dict[(2,1)] 56 So, you just can use the tuple co-ordinates you've defined in order to access cells. Note also that the list way you'd have to represent empty cells with a standard null value -- None is the usual choice. But this way, you just don't define some tuples as keys, as I didn't define (2,2) as a key. Thus: .>>> my_matrix_as_dict[(2,2)] Traceback (most recent call last): File "", line 1, in -toplevel- my_matrix_as_dict[(2,2)] KeyError: (2, 2) You can make that more graceful with a try/except block: .>>> try: my_matrix_as_dict[(2,2)] except KeyError: print "That cell is empty" That cell is empty .>>> HTH, Brian vdB From bvande at po-box.mcgill.ca Sun Dec 19 21:29:53 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Sun Dec 19 21:29:59 2004 Subject: [Tutor] OT: Flow chart In-Reply-To: <007e01c4e5ef$81442dd0$aeaa8851@xp> References: <1103452504.92b04ebcjerimed@myrealbox.com> <007e01c4e5ef$81442dd0$aeaa8851@xp> Message-ID: <41C5E4C1.3040909@po-box.mcgill.ca> Alan Gauld said unto the world upon 2004-12-19 12:23: >>I'm looking for any good link or tutorial of flow charting > > > A good resource for all notations related to software design > is at smartdraw.com: > > http://www.smartdraw.com/exp/tec/tutorials/software.htm > > But flow charts are more generic so info about them can > be found here: > > http://www.smartdraw.com/tutorials/flowcharts/resources.htm > > Not entirely unbiased since I do use their tool for my personal > use and prefer it to Visio, but the diagram tutorials are free. > > And one flowchartoing tutor I can recommend is: > > http://home.att.net/~dexter.a.hansen/flowchart/flowchart.htm > > Downloadable as PDF too. > > Alan G. Hi all, thanks for sending those links, Alan. It got me curious, and I googled around a bit. I found the GPL'ed Dia , which says it aims to be Visio like and is working on including Python scriptability. Just thought I'd flag that. Best to all, Brian vdB From orion_val at 163.com Mon Dec 20 02:44:05 2004 From: orion_val at 163.com (Juan Shen) Date: Mon Dec 20 02:52:13 2004 Subject: [Tutor] OT: Flow chart In-Reply-To: <41C5E4C1.3040909@po-box.mcgill.ca> References: <1103452504.92b04ebcjerimed@myrealbox.com> <007e01c4e5ef$81442dd0$aeaa8851@xp> <41C5E4C1.3040909@po-box.mcgill.ca> Message-ID: <41C62E65.1080405@163.com> Brian van den Broek wrote: > Alan Gauld said unto the world upon 2004-12-19 12:23: > >>> I'm looking for any good link or tutorial of flow charting >> >> >> >> A good resource for all notations related to software design is at >> smartdraw.com: >> >> http://www.smartdraw.com/exp/tec/tutorials/software.htm >> >> But flow charts are more generic so info about them can be found here: >> >> http://www.smartdraw.com/tutorials/flowcharts/resources.htm >> >> Not entirely unbiased since I do use their tool for my personal use >> and prefer it to Visio, but the diagram tutorials are free. >> >> And one flowchartoing tutor I can recommend is: >> >> http://home.att.net/~dexter.a.hansen/flowchart/flowchart.htm >> >> Downloadable as PDF too. >> >> Alan G. > > > Hi all, > > thanks for sending those links, Alan. It got me curious, and I googled > around a bit. > > I found the GPL'ed Dia , which > says it aims to be Visio like and is working on including Python > scriptability. > > Just thought I'd flag that. > > Best to all, > > Brian vdB > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor Maybe Dia is not stronger than Visio or SmartDraw, far to be improved. But after all, it's GPL not commercial. Juan From orion_val at 163.com Mon Dec 20 02:59:53 2004 From: orion_val at 163.com (Juan Shen) Date: Mon Dec 20 03:08:07 2004 Subject: [Tutor] Vpython In-Reply-To: <20041219155237.5138.qmail@web53304.mail.yahoo.com> References: <20041219155237.5138.qmail@web53304.mail.yahoo.com> Message-ID: <41C63219.20007@163.com> If you need to plot many math pictures, try SciPy http://www.scipy.org/ I have galanced VPython's website and tutorial. It seems it handles 3D-Plotting even better. Juan Aztech Guy wrote: >Hey, that's pretty good. Tried it out. VPython is cool >too. > >--- "Jacob S." wrote: > > > >>>>I was wondering were can I find some Vpython >>>> >>>> >>graphics program codes that >>are readily available. >> >>I have 2 that I am proud of. >> >>A simple function grapher >>Usage: >> >> >>>0.125*x**2 >>> >>> >>Graphs y = 1/8*x**2 >> >> >> >>>y = 1/x >>> >>> >>Graphs y = 1/x >> >> >> >>>clear >>> >>> >>Clears display window >> >> >> >>>r = t**2 >>> >>> >>Graphs polar function r = t**2 >> >> >> >>>remove lines >>> >>> >>Removes all axes, including polar axes, should a >>polar function be graphed >>after >> >> >> >>>return lines >>> >>> >>Returns all lines, so that they appear when >>appropriate. >> >> >> >>>x = sin(x**2)+log(x**2) >>> >>> >>Graphs the function... >> >> >> >> >> >------------------------------------------------------ > > >>from __future__ import division >>from visual import * >>import os >>from math import * >>ja = 0 >> >>def start(): >> for objects in scene.objects: >> objects.visible = 0 >> scene.title = "Function Grapher by Jacob, Inc." >> tem = raw_input('Are you on a desktop, or a >>notebook? ') >> if tem == 'desktop': >> scene.x = 365 >> if tem == 'notebook': >> scene.x = 574 >> scene.visible=1 >> scene.exit=0 >> scene.userspin = 0 >> scene.range=(10,10,1) >> scene.background=(1,1,1) >> global xaxis >> global yaxis >> xaxis = curve(color=color.black) >> xaxis.append(pos=(100,0,0)) >> xaxis.append(pos=(-100,0,0)) >> yaxis = curve(color=color.black) >> yaxis.append(pos=(0,100,0)) >> yaxis.append(pos=(0,-100,0)) >> global radiusaxis >> global radiusaxis2 >> radiusaxis = >>curve(pos=[(-100,-100),(100,100)],color=color.black) >> radiusaxis2 = >>curve(pos=[(-100,100),(100,-100)],color=color.black) >> radiusaxis.visible = 0 >> radiusaxis2.visible = 0 >> >>start() >>y = 3 >>m = 0 >>t = 0 >>d = 1 >>print """\ >>List of Commands: >>clear >>quit >>remove lines >>return lines >> >>Function Syntax: >>var = funct a,b >>where var = what >>and funct = f(what) >>and a,b = range >>""" >> >>print 'Please type in functions in below. ' >>while y != "": >> lists=[] >> y = raw_input('>') >> if y == 'clear': >> scene.visible=0 >> start() >> print "-"*36 >> continue >> elif y == 'quit': >> scene.visible = 0 >> del scene >> break >> elif y == 'remove lines': >> a = [radiusaxis,radiusaxis2,xaxis,yaxis] >> for x in a: >> x.visible = 0 >> d = 0 >> continue >> elif y == 'return lines': >> a = [radiusaxis,radiusaxis2,xaxis,yaxis] >> for x in a: >> x.visible = 1 >> d = 1 >> continue >> if y.count('=') == 1: >> y = y.split(' = ') >> type = y[0].lower() >> y = y[1] >> y = y.replace("y","x") >> if type == 'r': >> y = y.replace('x','t') >> if d == 1: >> radiusaxis.visible = 1 >> radiusaxis2.visible = 1 >> else: >> type = 'y' >> y = y.split(" ") >> if len(y) > 1: >> pass >> else: >> if type == 'r': >> y.append('0,5*pi') >> else: >> y.append('-10,10') >> range = y[1] >> y = y[0] >> range = range.split(",") >> min = float(eval(range[0])) >> max = float(eval(range[1])) >> lists.append(curve(color=(1,0,1))) >> x = min >> if type == 'y' or type == 'x': >> radiusaxis.visible = 0 >> radiusaxis2.visible = 0 >> while x >= min and x <= max: >> x = x+0.005 >> try: >> if eval(y) <= 15 and eval(y) >= -15: >> if type == 'y': >> >>lists[-1].append(pos=(x,eval(y),0)) >> elif type == 'x': >> >>lists[-1].append(pos=(eval(y),x,0)) >> else: >> >>lists.append(curve(color=(1,0,1))) >> except: >> pass >> elif type == 'r': >> m = 'eval(y)*cos(t)' >> n = 'eval(y)*sin(t)' >> t = min >> while t >= min and t <= max: >> try: >> >>lists[-1].append(pos=(eval(m),eval(n),0)) >> except: >> lists.append(curve(color=(1,0,1))) >> t = t+0.005 >> >> >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor >> >> >> > > > > >__________________________________ >Do you Yahoo!? >Send holiday email and support a worthy cause. Do good. >http://celebrity.mail.yahoo.com >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041220/334a1c0a/attachment.html From orion_val at 163.com Mon Dec 20 03:01:15 2004 From: orion_val at 163.com (Juan Shen) Date: Mon Dec 20 03:09:29 2004 Subject: [Tutor] Matrix In-Reply-To: <5a00f624041219073357d58e88@mail.gmail.com> References: <5a00f624041219073357d58e88@mail.gmail.com> Message-ID: <41C6326B.30205@163.com> Try SciPy. http://www.scipy.org/ It has mat class to handle matrix and much else. Juan Bugra Cakir wrote: >hi, > >I want to create a matrix in Python. For example 3x4 how can i >create this? thanks >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > From 12345671 at comcast.net Mon Dec 20 04:44:03 2004 From: 12345671 at comcast.net (Rob Kapteyn) Date: Mon Dec 20 04:44:17 2004 Subject: [Tutor] Matrix In-Reply-To: <41C5D6F5.3050804@po-box.mcgill.ca> References: <5a00f624041219073357d58e88@mail.gmail.com> <41C5D6F5.3050804@po-box.mcgill.ca> Message-ID: <648CE0F0-5239-11D9-A917-000D93C0B37A@comcast.net> Hello to the list ! A list of lists is the most logical construction. But -- you don't need to assemble the rows separately -- this works too: >>> my_matrix_as_lists = [ [4, 6, 8, 1],\ ... [2, 5, 1, 3],\ ... [2, 1, 2, 8] ] >>> print my_matrix_as_lists[1][1] 5 Rob On Dec 19, 2004, at 1:31 PM, Brian van den Broek wrote: > Bugra Cakir said unto the world upon 2004-12-19 10:33: >> hi, >> I want to create a matrix in Python. For example 3x4 how can i >> create this? thanks >> _______________________________________________ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor > > Hi, > > at least two ways using only builtins occur to me: > > 1) A list of lists: > > .>>> row1 = [4, 6, 8, 1] > .>>> row2 = [2, 5, 1, 3] > .>>> row3 = [2, 1, 2, 8] > .>>> my_matrix_as_lists = [row1, row2, row3] > .>>> print my_matrix_as_lists[1][1] > 5 > > Note that > >>> row1[1] > 6 > > since indicies start at 0. > > 2) To get around that, and be more efficient with matricies with many > empty cells: > .>>> my_matrix_as_dict = {(1,1):4, (1,2):6, (1,3):8, > (2,1):56, (2,3):12, > (3,1):3, (3,2):3} > > .>>> my_matrix_as_dict[(3,1)] > 3 > .>>> my_matrix_as_dict[(2,1)] > 56 > > So, you just can use the tuple co-ordinates you've defined in order to > access cells. Note also that the list way you'd have to represent > empty cells with a standard null value -- None is the usual choice. > But this way, you just don't define some tuples as keys, as I didn't > define (2,2) as a key. Thus: > > .>>> my_matrix_as_dict[(2,2)] > > Traceback (most recent call last): > File "", line 1, in -toplevel- > my_matrix_as_dict[(2,2)] > KeyError: (2, 2) > > You can make that more graceful with a try/except block: > > .>>> try: > my_matrix_as_dict[(2,2)] > except KeyError: > print "That cell is empty" > > That cell is empty > .>>> > > HTH, > > Brian vdB > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From 12345671 at comcast.net Mon Dec 20 04:47:05 2004 From: 12345671 at comcast.net (Rob Kapteyn) Date: Mon Dec 20 04:47:11 2004 Subject: [Tutor] Matrix In-Reply-To: <41C6326B.30205@163.com> References: <5a00f624041219073357d58e88@mail.gmail.com> <41C6326B.30205@163.com> Message-ID: Juan: Thanks for the tip, but the correct address seems to be: http://www.scipy.com/ the .org does not answer. Now I have to check out the graphing tools they have:-) Rob On Dec 19, 2004, at 8:01 PM, Juan Shen wrote: > Try SciPy. > http://www.scipy.org/ > It has mat class to handle matrix and much else. > Juan > > Bugra Cakir wrote: > >> hi, >> >> I want to create a matrix in Python. For example 3x4 how can i >> create this? thanks >> _______________________________________________ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor >> >> >> > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From bvande at po-box.mcgill.ca Mon Dec 20 05:18:10 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Mon Dec 20 05:18:16 2004 Subject: [Tutor] Matrix In-Reply-To: <648CE0F0-5239-11D9-A917-000D93C0B37A@comcast.net> References: <5a00f624041219073357d58e88@mail.gmail.com> <41C5D6F5.3050804@po-box.mcgill.ca> <648CE0F0-5239-11D9-A917-000D93C0B37A@comcast.net> Message-ID: <41C65282.5030406@po-box.mcgill.ca> Rob Kapteyn said unto the world upon 2004-12-19 22:44: > Hello to the list ! > > A list of lists is the most logical construction. > But -- you don't need to assemble the rows separately -- > this works too: > >>> my_matrix_as_lists = [ [4, 6, 8, 1],\ > ... [2, 5, 1, 3],\ > ... [2, 1, 2, 8] ] > > >>> print my_matrix_as_lists[1][1] > 5 > > Rob > > On Dec 19, 2004, at 1:31 PM, Brian van den Broek wrote: > >> Bugra Cakir said unto the world upon 2004-12-19 10:33: >> >>> hi, >>> I want to create a matrix in Python. For example 3x4 how can i >>> create this? thanks >> >> Hi, >> >> at least two ways using only builtins occur to me: >> >> 1) A list of lists: >> >> .>>> row1 = [4, 6, 8, 1] >> .>>> row2 = [2, 5, 1, 3] >> .>>> row3 = [2, 1, 2, 8] >> .>>> my_matrix_as_lists = [row1, row2, row3] >> .>>> print my_matrix_as_lists[1][1] >> 5 >> HTH, >> >> Brian vdB Sure, there's no need to assemble the rows separately. But, if you collapse it as you did, there is no need for the line continuations, either. Since all the lines are enclosed within brackets, if you want to span multiple lines, you can just as well do: .>>> my_matrix_as_lists = [ [4, 6, 8, 1], [2, 5, 1, 3], [2, 1, 2, 8] ] Best to all, Brian vdB From smichr at hotmail.com Mon Dec 20 06:29:22 2004 From: smichr at hotmail.com (C Smith) Date: Mon Dec 20 06:31:04 2004 Subject: [Tutor] Re: Printing two elements in a list Message-ID: Jacob S. wrote: > Would this work for you? > > a = ['Name = stuff','CGTATAGCTAGCTA','Name = stuff','CGATATGCCGGCTA'] > for index,thing in enumerate(a): > if "Name=" in thing: > del a[index] > > I know, that it might be slow, but I thought that maybe it would hold > its > own because it doesn't have to import the re module, everything's > builtin, > etc. > Be careful here, the above code will miss deleting an element containing "Name=" if there are two in a row. Look at this simple example where we attempt to delete elements equal to 2: ### >>> a=[1,2,1,2] >>> for i,x in enumerate(a): .. if x==2:del a[i] .. >>> a [1, 1] >>> # >>> # ok that looks right, but watch this >>> # >>> b=[2,2,1,1] >>> for i,x in enumerate(b): .. if x==2: del b[i] .. >>> b [2, 1, 1] ### After deleting element 0 in b, all the elements "slid down" one place and the 2nd 2 that was in b is now in position 0...but you are moving on to index 1 with the enumerate loop: [2, 2, 1, 1] ^ enumerate is at index 0 we delete element 0 [2, 1, 1] ^ enumerate is at index 1 and the 2 that was at position 1 is now at position 0 An alternative is to use a list comprehension, keeping only the elements that are not 2. As is shown, you can replace the list you are filtering with the filtered result: ### >>> b=[2,2,1,1] >>> b=[x for x in b if not(x==2)] >>> b [1, 1] ### /c From alan.gauld at freenet.co.uk Mon Dec 20 09:24:48 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Dec 20 09:24:40 2004 Subject: [Tutor] Matrix References: <5a00f624041219073357d58e88@mail.gmail.com><41C5D6F5.3050804@po-box.mcgill.ca> <648CE0F0-5239-11D9-A917-000D93C0B37A@comcast.net> Message-ID: <00e101c4e66d$5f859430$aeaa8851@xp> > A list of lists is the most logical construction. > But -- you don't need to assemble the rows separately -- > this works too: > >>> my_matrix_as_lists = [ [4, 6, 8, 1],\ > ... [2, 5, 1, 3],\ > ... [2, 1, 2, 8] ] And you don't need the line continuation characters either. Because Python can tell that the brackets don't match you can just add the newlines directly: >>> mx = [ [1,2,3,4], ... [5,6,7,8] ] >>> Alan g From maxnoel_fr at yahoo.fr Mon Dec 20 09:36:42 2004 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Mon Dec 20 09:36:56 2004 Subject: [Tutor] Printing two elements in a list In-Reply-To: <000301c4e5f2$270323a0$d25328cf@JSLAPTOP> References: <20041207220932.9164.qmail@web53703.mail.yahoo.com> <000301c4e5f2$270323a0$d25328cf@JSLAPTOP> Message-ID: <4640AD3F-5262-11D9-AF6F-000393CBC88E@yahoo.fr> On Dec 19, 2004, at 06:16, Jacob S. wrote: > Would this work for you? > > a = ['Name = stuff','CGTATAGCTAGCTA','Name = stuff','CGATATGCCGGCTA'] > for index,thing in enumerate(a): > if "Name=" in thing: > del a[index] > > I know, that it might be slow, but I thought that maybe it would hold > its > own because it doesn't have to import the re module, everything's > builtin, > etc. > > HTH, > Jacob A faster way to do this would be to use something like: if thing.beginswith("Name"): del a[index] -- Max -- maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From kent37 at tds.net Mon Dec 20 14:04:32 2004 From: kent37 at tds.net (Kent Johnson) Date: Mon Dec 20 14:04:39 2004 Subject: [Tutor] Printing two elements in a list In-Reply-To: <4640AD3F-5262-11D9-AF6F-000393CBC88E@yahoo.fr> References: <20041207220932.9164.qmail@web53703.mail.yahoo.com> <000301c4e5f2$270323a0$d25328cf@JSLAPTOP> <4640AD3F-5262-11D9-AF6F-000393CBC88E@yahoo.fr> Message-ID: <41C6CDE0.4000505@tds.net> Max Noel wrote: > > On Dec 19, 2004, at 06:16, Jacob S. wrote: > >> Would this work for you? >> >> a = ['Name = stuff','CGTATAGCTAGCTA','Name = stuff','CGATATGCCGGCTA'] >> for index,thing in enumerate(a): >> if "Name=" in thing: >> del a[index] >> > > A faster way to do this would be to use something like: > > if thing.beginswith("Name"): del a[index] Like, maybe, if thing.startswith('Name')... ;) Kent From alan.gauld at freenet.co.uk Mon Dec 20 15:12:08 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Dec 20 15:11:37 2004 Subject: [Tutor] Tkinter questions References: <003a01c4e495$1a407b30$05be8651@xp> Message-ID: <00ea01c4e69d$e503c520$aeaa8851@xp> > > I find the easiest way is to create an PhotoImage object attach > > the graphic file(jpg,bmp,gif) to that and assign the PhotoImage > > object to the Button.image property. You can "animate" the image > > by simply reassigning the file to the underlying PhotoImage onject. > Thanks, but a practical explanation will be more helpful. OK, I assume you mean code? :-) Here is an example modified from some experiments using the >>> prompt. It should work but might need a tweak along the way... ################ from Tkinter import * state = 0 def changeIt(img, fname): global state if state == 0: img['file']='img0.gif' state = 1 else: img['file'] = 'img1.gif' state=0 top = Tk() # now create an image object and a button theImg = PhotoImage(file='spam.gif') b = Button(top, command = changeIt, image=theImg) b.pack() top.mainloop() ################# You'll need to provide your own image files :-) You can also see this in action with a Text box in my book chapter on building a games framework, the commented code for which is on the Useless Python website as hmgui.zip > > You mean print as in to a printer? > > Personally I tend to generate an HTML file and use the > > native OS Tools to print that. You can get fancy and > > use the native OS printing libraries but since its > > very OS specific I find HTML is easier! OUtside Tkinter > > you may well find the GUI libraries have done the cross > > platform stuff for you, but not in Tkinter. > Again, a practical explanation will be more helpful... HTML generation is just a case of creating a text file with appropriate HTML tags inserted. There are some modules around that can help. Printing the file then becomes a matter of finding the appropriate commands in your OS and using the os.system() call to execute them. For example Windows explorer uses this command to print HTML on my system: "D:\msoffice\OFFICE11\msohtmed.exe" /p %1 You'll need to look to find whats in use on yours... > > Define a full window? You mean full screen? > > Thats usually better done as a parameter that the user can > > set unless there is a very good reason not to. (Personally > > I refuse to use any program that insists on opening full screen!) > Full window or full screen is when the window of the program is all > over the screen except the start bar Nope, Full Window means that something fills the current window, which could be any size. Since that didn't fit your explanation I asked for clarity. Full screen is where a single window fills the currently available screen. > And why you refuse to use any program that insists on opening full screen ? > If it does then there must be a good reason for that... No, quite often its simply a fascist minded programmer who thinks his application is so important that I won't want to do anything else while it's running - games programmers are bad for this. But since I very rarely do only one thing at a time on my PC I want control of the window size thankyou very much - that's why I have a 21 inch monitor running at 1600x1200! There are very few valid situations for an application taking over the whole screen univited! Normally the user should be able to make that choice. (For example when editing video I usually do go full screen, but I decide, not the program!) HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Mon Dec 20 15:27:01 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Dec 20 15:42:45 2004 Subject: [Tutor] class overriding question References: <41C4312A.6030909@po-box.mcgill.ca> Message-ID: <010801c4e6a2$3636ada0$aeaa8851@xp> You've got it right Brian. It is this ability to change the way *existing* code works that makes OOP more than a neat way to package data and functions. This is polymorphism at its most powerful. Its why in a C++/Java world the convention is to write hook methods that are called by the public methods. Thus sub classes can override the hook methods and change the behaviour of the public methods, without changing the basic sequence of processing. The common example here is a shape heirarchy: Shape defines a move method. move() calls delete() and draw() hooks. New classes override delete and draw and get move for free because it will always call the hooks in the right sequence and each subclass will actually do the appropriate work. Its another reason why you should never refer to an object or method *calling* another method (as Pilgrim does). Rather think of the method sending a *message* to the self object which invokes the appropriate method. This decoupling of message from method is a vitally important concept in OO and onvce you understand the concept of messages being sent resulting in methods being invoked OOD becomes much easier to grasp. This is explicit in Lisp, Smalltalk and Objective C where methods may have completely different names to messages, and multiple messages may invoke the same method - possibly with different default parameters - a very powerful technique! it's just about possible to do this in Python with lambdas etc but its messy. Alan G. ----- Original Message ----- From: "Brian van den Broek" To: "Tutor" Sent: Saturday, December 18, 2004 1:31 PM Subject: [Tutor] class overriding question > Hi all, > > instead of sleeping, I've been up all night finally attacking my > apprehension about classes. I think I'm mostly getting the hang of it -- > I managed to convert a 300 line procedural script into (what I think is) > a fully object-oriented approach. :-) > > I made a lot of use of Mark Pilgrim's Dive Into Python > , but Pilgrim said something that I'd like > to check my understanding of. In section 5.5 > he > writes: > > > Guido, the original author of Python, explains method overriding this > > way: "Derived classes may override methods of their base classes. > > Because methods have no special privileges when calling other methods > > of the same object, a method of a base class that calls another > > method defined in the same base class, may in fact end up calling a > > method of a derived class that overrides it. (For C++ programmers: > > all methods in Python are effectively virtual.)" If that doesn't make > > sense to you (it confuses the hell out of me), feel free to ignore > > it. I just thought I'd pass it along. > > I think I get this, but my inexperience with classes and Pilgrim's > rhetorical flourish make me doubt myself. I think the following three > ways of saying it all say the same thing (to a greater or lesser degree > of precision) as the quote from Guido above. Do I have the idea? > > Say class spam defines a method ham, and a method eggs, where ham calls > eggs. Further say class foo is derived from spam and overrides its eggs > method, but not its ham method. Then calling the ham method of an > instance bar of foo (and thus calling the ham method of spam, as foo is > a spam), will call the eggs method of foo, despite the fact that ham is > a method of spam, and within spam points originally to spam's version of > the eggs method. > > Alternatively, when calling bar.ham(), Python essentially says "OK, > bar's a foo. Does foo have a ham method? No, but it is derived from > spam. Does spam have a ham method? Yes, and it calls an eggs method. > Since bar's a foo, I should first look to see if foo has an eggs method. > (Nevermind that it was code in spam that started me off looking for > eggs.) Golly good, it does. So I will use that and not even bother to > look at spam's version of eggs." > > One other way: if we represent class inheritance as a tree, an a given > instance is of a class at level n in the tree, any search for a method > begins with the instance class and works up the tree to the ultimate > base class at level 1, no matter how high up the tree the search for the > method was initiated. And, in that search up the tree, the first > correctly named method to be found will be used. (I'm using the > mathematician's notion of trees with roots at the top.) > > Anyway, I hope I've both made sense and have got the idea right. > > Best to all, > > Brian vdB > > From mark.kels at gmail.com Mon Dec 20 15:47:30 2004 From: mark.kels at gmail.com (Mark Kels) Date: Mon Dec 20 15:47:33 2004 Subject: [Tutor] Tkinter questions In-Reply-To: References: <003a01c4e495$1a407b30$05be8651@xp> Message-ID: On Mon, 20 Dec 2004 18:21:13 +1300, Liam Clarke wrote: > from Tkinter import * > import Image, ImageTk > root = Tk() > img = Image.open('SonicCruiser.gif') > phi = ImageTk.PhotoImage(img) > button = Button(root, image=phi) > button.pack() > root.mainloop() Thank you !! But I don't have the Image module... Is it a part of the PIL toolkit ? If not, where can I get it ? > > > Again, a practical explanation will be more helpful... > > Cross platform easy printing? wxPython, which is totally different to Tkinter. > > http://mail.python.org/pipermail/python-list/2004-January/205116.html > > >Printing is not easy, it is a complicated matter. > > >You can find 4 simplifications: > > >1) wxPython has a print-framework, wxPython is cross platform (alas, I only > used it in win32) > > >2) print postscript. Ghostscript is available on "every" platform. > (printing on PDAs and watches is really different). Postscript is > documented > > >3) create PDF. PDF viewers & printers are available on "every" platform. > PDF can be created by (free) ReportLab toolkit, and I'm sure there are more > PDF-Classes > > >4) create XHTML & a Print.CSS. HTML viewers are available on every > Plattform, .CSS allows fairly good styling of printouts. > Is it so hard if I only want to print plain text ? Because I don't need anything special (only black text on white paper...). > You mean like IE's really good reasons to insist on being my default > browser for everything? You're putting a lot of faith in software > developers. Maybe I do... =) > You do realise that - > > no-one here is paid to answer queries? > Alan Gauld is a very knowledgable person? > Any knowledge is good knowledge? > If at first you don't succeed, rephrase or Google? Yes, I do. Actually, I don't understand why you don't think its obvious to me ( must be because of my bad English =). Thanks allot ! -- 1. The day Microsoft makes something that doesn't suck is probably the day they start making vacuum cleaners. 2. Unix is user friendly - it's just picky about it's friends. 3. Documentation is like sex: when it is good, it is very, very good. And when it is bad, it is better than nothing. - Dick Brandon From bvande at po-box.mcgill.ca Mon Dec 20 19:50:45 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Mon Dec 20 20:06:51 2004 Subject: [Tutor] class overriding question In-Reply-To: <010801c4e6a2$3636ada0$aeaa8851@xp> References: <41C4312A.6030909@po-box.mcgill.ca> <010801c4e6a2$3636ada0$aeaa8851@xp> Message-ID: <41C71F05.3060302@po-box.mcgill.ca> Alan Gauld said unto the world upon 2004-12-20 09:27: > Its another reason why you should never refer to > an object or method *calling* another method > (as Pilgrim does). Rather think of the method > sending a *message* to the self object which > invokes the appropriate method. This decoupling > of message from method is a vitally important > concept in OO and onvce you understand the concept > of messages being sent resulting in methods > being invoked OOD becomes much easier to grasp. > This is explicit in Lisp, Smalltalk and Objective C > where methods may have completely different names > to messages, and multiple messages may invoke the > same method - possibly with different default > parameters - a very powerful technique! it's just > about possible to do this in Python with lambdas > etc but its messy. > > Alan G. Thanks Alan. I appreciate the confirmation of my stumblings towards understanding. On the plus side, after a few evenings of serious effort, I can't quite understand what about OOP and classes had me so intimidated before :-) (That said, I'm a long way off from having these things down.) The contrast you suggest between calling a method and sending a message to an object isn't immediately clear to me. I'll put on my puzzling cap. But do you suggest it to emphasize that it is features of the object that determine which method gets invoked by the object.method() notation, or for some other reason? (By "features of the object" I mean things like facts about where the class that the object is a primary instance of falls in an inheritance tree.) Thanks again, Brian vdB From keridee at jayco.net Mon Dec 20 20:18:53 2004 From: keridee at jayco.net (Jacob S.) Date: Mon Dec 20 20:19:32 2004 Subject: [Tutor] A better way to do it. Message-ID: <000501c4e6c8$d663f820$425428cf@JSLAPTOP> Okay, here's the code. I am completely open to suggestions as this is my first dabbling in Tk. Please look over it when you have time. I have a couple of questions. 1) How do I change the title of the window? 2) Why does a window pop up saying something like error, the memory could not be "read". I'm running Windows XP, the script window disappears, and everything, just this message pops up. Jacob Schmidt ---------------------------------------------------------------------------- - from Tkinter import * import tkMessageBox import os from filecmp import cmpfiles class Copying: def __init__(self,action,var,err): self.action = action self.pri = var self.err = err self.j = os.path.join self.r = os.path.isdir self.e = os.path.isfile #################################################################### # These are the default values for the directories. To make it simpler you could... ## ## pseudo ## self.usbdrive = remote folder ## self.desktop = localer folder #################################################################### dirlist = os.listdir("c:\\") if 'Jacob Laptop' in dirlist: self.usbdrive = 'E:\\Working Python Programs' self.desktop = 'C:\\documents and settings\\jacob\\desktop\\Working Python Programs' elif 'Home Computer' in dirlist: self.usbdrive = 'F:\\Working Python Programs' self.desktop = 'C:\\documents and settings\\owner\\desktop\\Working Python Programs' elif 'Sissy Computer' in dirlist: self.usbdrive = '' ## Need to fill in self.desktop = '' ## Need to fill in elif 'Michael Laptop' in dirlist: self.usbdrive = 'E:\\Working Python Programs' self.desktop = 'C:\\documents and settings\\michael\\desktop\\Working Python Programs' elif 'Office Computer' in dirlist: self.usbdrive = 'D:\\Working Python Programs' self.desktop = 'C:\\windows\\desktop\\Working Python Programs' elif 'School Auction Laptop' in dirlist: self.usbdrive = '' ## Need to fill in self.desktop = 'C:\\windows\\desktop\\Working Python Programs' else: print 'Hey you need to put a folder in this computer!. ' print '''Folders include: Jacob Laptop Home Computer Sissy Computer Michael Laptop Office Computer School Auction Laptop ''' folder = raw_input('Which computer is this? ') folder = "C:\\"+folder os.mkdir(folder) self.usbdrive = raw_input('What is the usb drive on this computer? ') self.desktop = raw_input('What is the desktop on this computer? ') # ################################################# # if not os.path.exists(self.desktop): os.mkdir(self.desktop) m = {'receiving':self.receiving,'sending':self.sending} m[self.action]() def copyfile(self,src,des): x = open(src,'rb').read() y = open(des,'wb') y.write(x) y.close() def receiving(self): chiplist = os.listdir(self.usbdrive) pclist = os.listdir(self.desktop) filechange = cmpfiles(self.usbdrive,self.desktop,chiplist)[1] tot = 0 for x in chiplist: if x not in pclist: filechange.append(x) for x in filechange: fullname = self.j(self.usbdrive,x) if self.e(fullname): self.copyfile(fullname,self.j(self.desktop, x)) self.pri.set("Copying %s." % x) self.err.insert(END,"%s copied from chip to computer.\n" % x) tot = tot + 1 elif self.r(fullname): self.err.insert(END,"%s is a directory. It has not been copied.\n" % fullname) self.err.insert(END,"%s file(s) copied.\n"%tot) self.pri.set("") pclist.sort() chiplist.sort() newlist = [x for x in pclist if x not in chiplist] for x in newlist: if tkMessageBox.askokcancel('Delete?',"Do you wish to delete %s? " % x): filename = self.j(self.desktop, x) if self.e(filename): os.remove(filename) self.err.insert(END,"%s has been removed from your chip.\n"%x) elif self.r(filename): os.rmdir(filename) self.err.insert(END,"%s has been removed from your chip.\n"%x) else: self.err.insert(END,"Did not remove %s\n"%x) def sending(self): pclist = os.listdir(self.desktop) chiplist = os.listdir(self.usbdrive) filechange = cmpfiles(self.desktop,self.usbdrive,pclist)[1] tot = 0 for x in pclist: if x not in chiplist: filechange.append(x) for x in filechange: fullname = self.j(self.desktop,x) if self.e(fullname): self.copyfile(fullname,self.j(self.usbdrive,x)) self.pri.set("Copying %s. " % x) self.err.insert(END,"%s copied from computer to chip.\n" % x) tot = tot + 1 elif self.r(fullname): self.err.insert(END,"%s is a directory. It has not been copied.\n" % x) self.err.insert(END,"%s file(s) copied.\n"%tot) self.pri.set("") chiplist.sort() pclist.sort() newlist = [x for x in chiplist if x not in pclist] for x in newlist: if tkMessageBox.askokcancel('Delete?',"Do you wish to delete %s? " % x): filename = self.j(self.usbdrive, x) if self.e(filename): os.remove(filename) self.err.insert(END,"%s has been removed from your chip.\n"%x) elif self.r(filename): os.rmdir(filename) self.err.insert(END,"%s has been removed from your chip.\n"%x) else: self.err.insert(END,"Did not remove %s\n"%x) class Application(Frame): def s(self): Copying(action='sending',var=self.pri,err=self.error) def r(self): Copying(action='receiving',var=self.pri,err=self.error) def createWidgets(self): self.QUIT = Button(self) self.QUIT["text"] = "QUIT" self.QUIT["fg"] = "red" self.QUIT["command"] = self.quit self.QUIT.grid(row=1,column=1) self.hi_there = Button(self) self.hi_there["text"] = "Sending", self.hi_there["command"] = self.s self.hi_there.grid(row=1,column=2) self.REC = Button(self) self.REC['text'] = "Receiving" self.REC['command'] = self.r self.REC.grid(row=1,column=3) self.pri = StringVar() self.TEXT = Label(self,textvariable=self.pri) self.TEXT.grid(row=2,column=1,columnspan=3) self.error = Text(self,fg='blue',height=10) self.error.grid(row = 3,column = 1,columnspan = 3) def __init__(self, master=None): Frame.__init__(self,master) self.title = "Copying" self.pack() self.createWidgets() app = Application() app.mainloop() From keridee at jayco.net Mon Dec 20 20:27:05 2004 From: keridee at jayco.net (Jacob S.) Date: Mon Dec 20 20:27:11 2004 Subject: [Tutor] Printing two elements in a list References: <20041207220932.9164.qmail@web53703.mail.yahoo.com><000301c4e5f2$270323a0$d25328cf@JSLAPTOP><4640AD3F-5262-11D9-AF6F-000393CBC88E@yahoo.fr> <41C6CDE0.4000505@tds.net> Message-ID: <001d01c4e6c9$e78a44f0$425428cf@JSLAPTOP> Duh, whack myself on the head a few times. Thanks, Jacob > Max Noel wrote: > > > > On Dec 19, 2004, at 06:16, Jacob S. wrote: > > > >> Would this work for you? > >> > >> a = ['Name = stuff','CGTATAGCTAGCTA','Name = stuff','CGATATGCCGGCTA'] > >> for index,thing in enumerate(a): > >> if "Name=" in thing: > >> del a[index] > >> > > > > A faster way to do this would be to use something like: > > > > if thing.beginswith("Name"): del a[index] > > Like, maybe, > if thing.startswith('Name')... > > ;) > > Kent > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From keridee at jayco.net Mon Dec 20 20:29:42 2004 From: keridee at jayco.net (Jacob S.) Date: Mon Dec 20 20:29:47 2004 Subject: [Tutor] Re: Printing two elements in a list References: Message-ID: <002301c4e6ca$449452d0$425428cf@JSLAPTOP> That's interesting, I hadn't thought of that! Jacob > Jacob S. wrote: > > > Would this work for you? > > > > a = ['Name = stuff','CGTATAGCTAGCTA','Name = stuff','CGATATGCCGGCTA'] > > for index,thing in enumerate(a): > > if "Name=" in thing: > > del a[index] > > > > I know, that it might be slow, but I thought that maybe it would hold > > its > > own because it doesn't have to import the re module, everything's > > builtin, > > etc. > > > Be careful here, the above code will miss deleting an element > containing "Name=" if there are two in a row. Look at this simple > example where we attempt to delete elements equal to 2: > > ### > > >>> a=[1,2,1,2] > >>> for i,x in enumerate(a): > .. if x==2:del a[i] > .. > >>> a > [1, 1] > >>> # > >>> # ok that looks right, but watch this > >>> # > >>> b=[2,2,1,1] > >>> for i,x in enumerate(b): > .. if x==2: del b[i] > .. > >>> b > [2, 1, 1] > > ### > > After deleting element 0 in b, all the elements "slid down" one place > and the 2nd 2 that was in b is now in position 0...but you are moving > on to index 1 with the enumerate loop: > > [2, 2, 1, 1] > ^ > enumerate is at index 0 > > we delete element 0 > > [2, 1, 1] > ^ > enumerate is at index 1 and the 2 that was at position 1 is now at > position 0 > > An alternative is to use a list comprehension, keeping only the > elements that are not 2. As is shown, you can replace the list you are > filtering with the filtered result: > > ### > > >>> b=[2,2,1,1] > >>> b=[x for x in b if not(x==2)] > >>> b > [1, 1] > > ### > > /c > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From dyoo at hkn.eecs.berkeley.edu Mon Dec 20 20:36:31 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Dec 20 20:36:40 2004 Subject: [Tutor] Python 2.4 IDLE Windows 2000 In-Reply-To: <008701c4e54f$c1915200$a75328cf@JSLAPTOP> Message-ID: On Sat, 18 Dec 2004, Jacob S. wrote: > I think I'm going to burst out in tears. Mike Hansen gave the solution > to the very problem I'm having, yet, when I used the console version and > deleted the custom color theme, it stopped giving me error messages, but > it still won't start up without the console. > > I'm am still stunted of my python 2.4 experience. Hi Jacob, Mike's bug submission into Sourceforge is getting attention; it's bug 1080387: http://sourceforge.net/tracker/index.php?func=detail&aid=1080387&group_id=5470&atid=105470 I'm still concerned, though, about your case, since you're saying that there are no error messages, but it's still not starting up from the icon in your Start menu. There should be a '.idlerc' directory in your home directory; can you try moving or renaming it somewhere else temporarily? Afterwards, try starting IDLE. But don't wipe that '.idlerc' out yet, because if it turns out that this actually works, then we should take a closer look at the .idlerc directory, and send it off to the bug hunters. Good luck to you! From ejp at zomething.com Mon Dec 20 20:39:28 2004 From: ejp at zomething.com (EJP) Date: Mon Dec 20 20:39:22 2004 Subject: [Tutor] Python 2.4 IDLE Windows 2000 In-Reply-To: <008701c4e54f$c1915200$a75328cf@JSLAPTOP> References: <41B07DA6.1030703@cso.atmel.com> <20041210202815.833898538.ejp@zomething.com> <008701c4e54f$c1915200$a75328cf@JSLAPTOP> Message-ID: <20041220113928.1358534734.ejp@zomething.com> "Jacob S." > Gee, > I think I'm going to burst out in tears. > Mike Hansen gave the solution to the very problem I'm having, yet, when > I > used the console version and deleted the custom color theme, it stopped > giving me error messages, but it still won't start up without the > console. > > I'm am still stunted of my python 2.4 experience. > Help, please!!! > > Desperate, > Jacob Can you open IDLE and reset the color options to the defaults? I believe that's how I solved it. If not, there should be some configuration files, plain text files with names like "*.def" in your idlelib directory. Here's the path to one of several on my machine: C:\Python23\Lib\idlelib\config-highlight.def I am not sure if you can safely delete these, but reverting them to the default configuration should work (I think). Caution: I am not an expert in IDLE, Python, or... even life. EJP From dyoo at hkn.eecs.berkeley.edu Mon Dec 20 20:46:57 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Dec 20 20:47:02 2004 Subject: [Tutor] Matrix In-Reply-To: <5a00f624041219073357d58e88@mail.gmail.com> Message-ID: On Sun, 19 Dec 2004, Bugra Cakir wrote: > I want to create a matrix in Python. For example 3x4 how can i > create this? thanks Hi Bugra, Just for reference, here's the relevant FAQ about how to do matrices in Python: http://python.org/doc/faq/programming.html#how-do-i-create-a-multidimensional-list If you're planning to do a lot of matrix-y stuff, you may want to look into the 'numarray' third-module: http://www.stsci.edu/resources/software_hardware/numarray The package adds powerful matrix operations to Python. Good luck to you! From cmeesters at ucdavis.edu Mon Dec 20 21:16:25 2004 From: cmeesters at ucdavis.edu (Christian Meesters) Date: Mon Dec 20 21:16:30 2004 Subject: [Tutor] unittesting and nested functions Message-ID: <06486176-52C4-11D9-AAFE-000393D8EC3A@ucdavis.edu> Hi I've written some unittests using the unittest module for my 'DNA-class'. This class can cope with almost every input, but with no 'numbers' whatsoever. Well, one of the tests is: class TestFunctions(unittest.TestCase): ... def test__init__(self): """testing whether __init__ will fail if nonsense data are passed for initialization""" self.failUnlessRaises(IOError,DNA('1 ATG')) Now, if 'nonsense data' are passed to the testing function I expect an IOError to be raised. And this happens indeed. Still this test fails (actually it doesn't: only an error occurs), but why? This is the Traceback I get: ====================================================================== ERROR: testing whether __init__ will fail if nonsense data are passed for initialization ---------------------------------------------------------------------- Traceback (most recent call last): File "src/DNA.py", line 862, in test__init__ self.failUnlessRaises(IOError,DNA('1 ATG')) File "src/DNA.py", line 100, in __init__ raise IOError IOError ---------------------------------------------------------------------- Ran 35 tests in 0.485s FAILED (errors=1) According to the documentation everything should be just fine: ---------- 5.3.5 TestCase Objects ... failUnlessRaises(exception, callable, ...) Test that an exception is raised when callable is called with any positional or keyword arguments that are also passed to assertRaises(). The test passes if exception is raised, is an error if another exception is raised, or fails if no exception is raised. To catch any of a group of exceptions, a tuple containing the exception classes may be passed as exception. ---------- So, any idea, where my mistake is? (Before I get comments about having the unittest in the same file as the file to be tested: I'll change that! ;-) ) Thanks a lot in advance. Cheers Christian From bgailer at alum.rpi.edu Mon Dec 20 21:28:05 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon Dec 20 21:26:14 2004 Subject: [Tutor] Matrix In-Reply-To: References: <5a00f624041219073357d58e88@mail.gmail.com> Message-ID: <6.1.2.0.0.20041220132645.032badf0@mail.mric.net> >On Sun, 19 Dec 2004, Bugra Cakir wrote: > > > I want to create a matrix in Python. For example 3x4 how can i > > create this? thanks Just for the heck of it would you tell us what you want to do with the matrix? Sometimes there are interesting alternate ways to do things that might not be obvious to a relatively new Pythoneer. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From kent37 at tds.net Mon Dec 20 21:29:22 2004 From: kent37 at tds.net (Kent Johnson) Date: Mon Dec 20 21:29:28 2004 Subject: [Tutor] unittesting and nested functions In-Reply-To: <06486176-52C4-11D9-AAFE-000393D8EC3A@ucdavis.edu> References: <06486176-52C4-11D9-AAFE-000393D8EC3A@ucdavis.edu> Message-ID: <41C73622.9020802@tds.net> Christian Meesters wrote: > Hi > > I've written some unittests using the unittest module for my > 'DNA-class'. This class can cope with almost every input, but with no > 'numbers' whatsoever. Well, one of the tests is: > > class TestFunctions(unittest.TestCase): > ... > def test__init__(self): > """testing whether __init__ will fail if nonsense data are > passed for initialization""" > self.failUnlessRaises(IOError,DNA('1 ATG')) This should be self.failUnlessRaises(IOError, DNA, '1 ATG') In your usage, you are calling DNA() and passing the result of the call to failUnlessRaises(). The call to DNA raises IOError. This happens *before* the call to failUnlessRaises(), so it is interpreted as an error. In my version, I pass the DNA function itself to failUnlessRaises(), along with the arguments. The actual call to DNA() will be wrapped by a try/except block in failUnlessRaises(). The expected error is received and the test passes. BTW, failUnlessRaises() is implemented using the extended call syntax that came up recently in another thread, and it is a good example of why this syntax is useful. It's also interesting that the except: statement uses the class that was passed in; I had no idea an except was dynamic in this way. Here is the source for failUnlessRaises(): def failUnlessRaises(self, excClass, callableObj, *args, **kwargs): try: callableObj(*args, **kwargs) except excClass: return else: if hasattr(excClass,'__name__'): excName = excClass.__name__ else: excName = str(excClass) raise self.failureException, "%s not raised" % excName Kent > > Now, if 'nonsense data' are passed to the testing function I expect an > IOError to be raised. And this happens indeed. Still this test fails > (actually it doesn't: only an error occurs), but why? > > This is the Traceback I get: > > ====================================================================== > ERROR: testing whether __init__ will fail if nonsense data are passed > for initialization > ---------------------------------------------------------------------- > Traceback (most recent call last): > File "src/DNA.py", line 862, in test__init__ > self.failUnlessRaises(IOError,DNA('1 ATG')) > File "src/DNA.py", line 100, in __init__ > raise IOError > IOError > > ---------------------------------------------------------------------- > Ran 35 tests in 0.485s > > FAILED (errors=1) > > According to the documentation everything should be just fine: > ---------- > 5.3.5 TestCase Objects > ... > failUnlessRaises(exception, callable, ...) > Test that an exception is raised when callable is called with any > positional or keyword arguments that are also passed to assertRaises(). > The test passes if exception is raised, is an error if another > exception is raised, or fails if no exception is raised. To catch any > of a group of exceptions, a tuple containing the exception classes may > be passed as exception. > ---------- > > So, any idea, where my mistake is? > > (Before I get comments about having the unittest in the same file as the > file to be tested: I'll change that! ;-) ) > > Thanks a lot in advance. > Cheers > Christian > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at freenet.co.uk Mon Dec 20 21:51:40 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Dec 20 21:54:38 2004 Subject: [Tutor] class overriding question References: <41C4312A.6030909@po-box.mcgill.ca><010801c4e6a2$3636ada0$aeaa8851@xp> <41C71F05.3060302@po-box.mcgill.ca> Message-ID: <015601c4e6d5$b5212f90$aeaa8851@xp> > > Its another reason why you should never refer to > > an object or method *calling* another method > > (as Pilgrim does). Rather think of the method > > sending a *message* to the self object which > > invokes the appropriate method. > The contrast you suggest between calling a method and sending a message > to an object isn't immediately clear to me. I'll put on my puzzling cap. In classical OOP theory - ie all the early OOP languages (except probably Simula which was Algol based!) - the metaphor was of a set of independant objects floating around in cyberspace. These objects communicated by sending messages to each other. How the receiving object responded to a message was known as its method, and the resolution of the message into appropriate method was the job of the receiving object (or class). In (pseudo and simplified python-like) Lisp, for example, you can do things like: def methodOne(self, p1): # code here def methodTwo(self, fmt): # code here def class MyClass myClass.addMessage("help", methodOne) myClass.addMessage("print",methodTwo) myClass.addMessage("display", methodTwo) myObject = MyClass.makeInstance() myObject.send("print", 'txt') myObject.send("display", 'scrn') Thus I bind the same method to two different messages. Because I always use send() (a class function) I pass the message name as strings and the class does a lookup (usually in a dictionary) and calls the associated method. THus there is explicit separation of concept. Unfortunately this was slow so most later OOP languages opted for a more direct translation with message name equalling method name. This in turn lost the theoretical purity of the concept of objects being independant concurrent processes and starte the idea that you could directly call a *method* which theoretically is impossible. But conceptually it helps to see the difference between objects and data structures to imagine that every object is an independant process and they communicate by sending IPC messages to one another. ( For the mathematically inclined this idea of concurrent sequential (state) machines is a very powerful formal model that can be analysed mathematically. Many of the theoretical underpinnings of computer science stem from this idea.) > But do you suggest it to emphasize that it is features of the object > that determine which method gets invoked by the object.method() In essence yes. The programmer has no control over the code that gets executed when he "sends a message" to an object, that is determined in the class. And it can be a dangerous mistake to think otherwise - after all what if someone subclasses your original class and then passes one of the new objects into your code. If you assume that you can send a message and execute a specific method you might be in for a nasty surprise! As a specific example, lets say you have a set of blodgets. One method of the blodget superclass defines a save method which writes to a fixed data file. You write code that accepts a blodget (or any subclass thereof) and saves it then reads the data file to access some aspect of the object - really bad practice anyway but it happens! Now I come along and define a subclass of blodget that saves by writing to a serial comms port, now your code "saves" my blodget but when it reads the data file it actually picks up the last blodget details not mine - oops! I hope that short history of OOP clarifies rather than confuses! :-) Alan G. From bvande at po-box.mcgill.ca Tue Dec 21 00:07:31 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Tue Dec 21 00:21:33 2004 Subject: [Tutor] class overriding question In-Reply-To: <015601c4e6d5$b5212f90$aeaa8851@xp> References: <41C4312A.6030909@po-box.mcgill.ca> <010801c4e6a2$3636ada0$aeaa8851@xp> <41C71F05.3060302@po-box.mcgill.ca> <015601c4e6d5$b5212f90$aeaa8851@xp> Message-ID: <41C75B33.7050502@po-box.mcgill.ca> Alan Gauld said unto the world upon 2004-12-20 15:51: > > I hope that short history of OOP clarifies rather than > confuses! :-) > > Alan G. Thanks for that Alan. Seems to clarify thing to me ;-) Best, Brian vdB From keridee at jayco.net Tue Dec 21 01:53:26 2004 From: keridee at jayco.net (Jacob S.) Date: Tue Dec 21 01:55:02 2004 Subject: [Tutor] Python 2.4 IDLE Windows 2000 References: <41B07DA6.1030703@cso.atmel.com> <20041210202815.833898538.ejp@zomething.com> <008701c4e54f$c1915200$a75328cf@JSLAPTOP> <20041220113928.1358534734.ejp@zomething.com> Message-ID: <000f01c4e6f7$b5ab75c0$b45428cf@JSLAPTOP> Ah, hah! Okay, everyone! It took two things. 1) Delete .idlerc directory 2) Uninstall and reinstall python2.4 Why I had to do step two is beyond me, but I've got it settled now! Thank you, Jacob Schmidt > > "Jacob S." > > > Gee, > > I think I'm going to burst out in tears. > > Mike Hansen gave the solution to the very problem I'm having, yet, when > > I > > used the console version and deleted the custom color theme, it stopped > > giving me error messages, but it still won't start up without the > > console. > > > > I'm am still stunted of my python 2.4 experience. > > Help, please!!! > > > > Desperate, > > Jacob > > > Can you open IDLE and reset the color options to the defaults? I believe that's how I solved it. > > If not, there should be some configuration files, plain text files with names like "*.def" in your idlelib directory. Here's the path to one of several on my machine: > C:\Python23\Lib\idlelib\config-highlight.def > > I am not sure if you can safely delete these, but reverting them to the default configuration should work (I think). > > Caution: I am not an expert in IDLE, Python, or... even life. > > EJP > > > From dyoo at hkn.eecs.berkeley.edu Tue Dec 21 01:59:42 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Dec 21 01:59:46 2004 Subject: [Tutor] Python 2.4 IDLE Windows 2000 In-Reply-To: <000f01c4e6f7$b5ab75c0$b45428cf@JSLAPTOP> Message-ID: On Mon, 20 Dec 2004, Jacob S. wrote: > 1) Delete .idlerc directory > 2) Uninstall and reinstall python2.4 Hi Jacob, Ok, so there was probably something really screwy with the stuff in .idlerc. Can you send me a tarball or zip of it in private email? I just want to make sure that the issue that you were hitting is the same as Mike's. If this is something new, we'd better make sure the IDLE developers know that it's something other than a previous color configuration that is causing IDLE to break. Talk to you later! From guillermo.fernandez.castellanos at gmail.com Tue Dec 21 06:16:56 2004 From: guillermo.fernandez.castellanos at gmail.com (Guillermo Fernandez Castellanos) Date: Tue Dec 21 06:17:00 2004 Subject: [Tutor] Tix NoteBook programming problem Message-ID: <7d7029e70412202116483adb6a@mail.gmail.com> Hi, I'm trying to figure out how to work with Tix. The lack of examples and avalaibility of documentation for TCL only do not help :-( It does not work because when I start the program, the red and gren buttons start blinking betweeb 2 or 3 different places, no matter what the tab is. Here is the code: import Tix root = Tix.Tk() nb=Tix.NoteBook(root) nb.add('hd',label="hard disk",underline=0) nb.add('gf',label="soft disk",underline=0) hd = nb.subwidget('hd') gf = nb.subwidget('gf') button1 = Tix.Button(hd) button1["text"]= "Hello, World!" button1["background"] = "green" button1.pack() button1 = Tix.Button(gf) button1["text"]= "Bye, World!" button1["background"] = "red" button1.pack() hd.pack() gf.pack() nb.pack() nb.mainloop() My experience in Gui programming is pretty low, any help would be apreciated. Thanks! Guille From thomi at imail.net.nz Tue Dec 21 07:43:22 2004 From: thomi at imail.net.nz (Thomas Clive Richards) Date: Tue Dec 21 07:43:27 2004 Subject: [Tutor] implementing a table data structure in python? Message-ID: <200412211943.22571.thomi@imail.net.nz> Hi, I'm trying to implement a reasonably efficient table data structure, but ith a few quirks... The application I'm building is a CGI program which allows users to view a large table of data. In addition, users can restrict the data shown. Some sample data might look like this: (note you'll need a fixed width font for this) D x y z val q ------------------------------------- 1 | 1 2 3 23 0.1 13 | 2 3 4 24 0.15 24 | 1 1 2 12 0.2 45 | 2 3 5 1 0.12 116 | 6 2 7 27 0.18 211 | 9 4 6 28 0.45 Actually, the real data I'm using is very different - but this is easy to type :) The entire table is stored in a plain text file, and could contain up to 500 KB of data. Every time my CGI script is run, it must read this file from disk, and return a 2D array of values; However, I need to be able to restrict the columns shown. For example, user A might not want to see the D & val columns - I need a way of trimming these easily.. Normally I'd use a database like mysql, postgreSQL, or even SQLite for this sort of application, but the server I'm working on (which is outside my control) does not have any of these installed. The CGI will not see heavy use, and I'm not very worried about race conditions or collisions... Does anyone have any advice for me? implementing this as a simple 2D array (or list of lists) seems a little silly - surely there's a better way? Actually, python bindings to the STL (or something similar) would be useful in many situations.... Thanks, -- Thomi Richards, thomi@once.net.nz From kent37 at tds.net Tue Dec 21 12:01:28 2004 From: kent37 at tds.net (Kent Johnson) Date: Tue Dec 21 12:01:35 2004 Subject: [Tutor] implementing a table data structure in python? In-Reply-To: <200412211943.22571.thomi@imail.net.nz> References: <200412211943.22571.thomi@imail.net.nz> Message-ID: <41C80288.9060206@tds.net> Thomas Clive Richards wrote: > Hi, > > I'm trying to implement a reasonably efficient table data structure, but ith a > few quirks... > > The application I'm building is a CGI program which allows users to view a > large table of data. In addition, users can restrict the data shown. Some > sample data might look like this: (note you'll need a fixed width font for > this) > > D x y z val q > ------------------------------------- > 1 | 1 2 3 23 0.1 > 13 | 2 3 4 24 0.15 > 24 | 1 1 2 12 0.2 > 45 | 2 3 5 1 0.12 > 116 | 6 2 7 27 0.18 > 211 | 9 4 6 28 0.45 > > Actually, the real data I'm using is very different - but this is easy to > type :) > > The entire table is stored in a plain text file, and could contain up to 500 > KB of data. > > Every time my CGI script is run, it must read this file from disk, and return > a 2D array of values; However, I need to be able to restrict the columns > shown. > > For example, user A might not want to see the D & val columns - I need a way > of trimming these easily.. > > > Normally I'd use a database like mysql, postgreSQL, or even SQLite for this > sort of application, but the server I'm working on (which is outside my > control) does not have any of these installed. You could use a pure Python database such as gadfly or KirbyBase . But for your needs it may be overkill. > The CGI will not see heavy use, and I'm not very worried about race conditions > or collisions... > > > Does anyone have any advice for me? implementing this as a simple 2D array (or > list of lists) seems a little silly - surely there's a better way? A list of lists is the simple way to implement a 2D array and not silly at all. But really you only need one line at a time. I would try something like columns = [1,3,4] # Column numbers to show, 0-based f = open('mydata.txt') for line in f: data = line.split() # Assuming your data is tab- or space-delimited data = [ item for i, item in data if i in columns ] # Filter out unwanted columns print data # Output one row of text - put your formatting here There are probably more efficient ways to extract the data but this should get you started. > Actually, python bindings to the STL (or something similar) would be useful in > many situations.... It's been a long time since I've used STL, but I think Python lists and dicts provide similar functionality to STL containers with *much* simpler syntax. And many of the STL algorithms can probably be found scattered about the Python standard library. Let us know specifically what you are missing and we can show you the Python way. If you truly think a list of lists is 'silly' I suspect you are missing out on a lot of Python's power. Kent > > > > Thanks, From yduppen at xs4all.nl Tue Dec 21 12:43:18 2004 From: yduppen at xs4all.nl (Yigal Duppen) Date: Tue Dec 21 12:43:21 2004 Subject: [Tutor] unittesting and nested functions In-Reply-To: <06486176-52C4-11D9-AAFE-000393D8EC3A@ucdavis.edu> References: <06486176-52C4-11D9-AAFE-000393D8EC3A@ucdavis.edu> Message-ID: <200412211243.18485.yduppen@xs4all.nl> On Monday 20 December 2004 21:16, Christian Meesters wrote: > Hi > > I've written some unittests using the unittest module for my > 'DNA-class'. This class can cope with almost every input, but with no > 'numbers' whatsoever. Well, one of the tests is: > > class TestFunctions(unittest.TestCase): > ... > def test__init__(self): > """testing whether __init__ will fail if nonsense data are > passed for initialization""" > self.failUnlessRaises(IOError,DNA('1 ATG')) Apart from the correct answer given by Kent Johnson, I personally prefer to code such tests like this: def test_stuff(self): try: my_function("silly argument") self.fail("my_function succeeded, even though I passed silly argument") except IOError: # and this was expected pass The reason for this is easy: I always make stupid mistakes in calls to failUnlessRaises; and I find this approach much more readable. I hope this helps, Yigal Duppen From cmeesters at ucdavis.edu Tue Dec 21 15:04:31 2004 From: cmeesters at ucdavis.edu (Christian Meesters) Date: Tue Dec 21 15:04:37 2004 Subject: [Tutor] unittesting and nested functions In-Reply-To: <20041220205437.DE79C1E4014@bag.python.org> References: <20041220205437.DE79C1E4014@bag.python.org> Message-ID: <3C22A901-5359-11D9-AAFE-000393D8EC3A@ucdavis.edu> > Ken Johnson wrote: > This should be > self.failUnlessRaises(IOError, DNA, '1 ATG') > > In your usage, you are calling DNA() and passing the result of the > call to failUnlessRaises(). The > call to DNA raises IOError. This happens *before* the call to > failUnlessRaises(), so it is > interpreted as an error. Ah, I see. > > BTW, failUnlessRaises() is implemented using the extended call syntax > that came up recently in > another thread, and it is a good example of why this syntax is useful. > It's also interesting that > the except: statement uses the class that was passed in; I had no idea > an except was dynamic in this > way. > Indeed, this is remarkable. Perhaps it's time for me to look into this once? Anyway, thank you Kent, now everything is working just fine. Everybody a Merry Christmas! Christian From maarten at dds.nl Tue Dec 21 15:27:13 2004 From: maarten at dds.nl (Maarten) Date: Tue Dec 21 15:27:20 2004 Subject: [Tutor] implementing a table data structure in python? In-Reply-To: <41C80288.9060206@tds.net> References: <200412211943.22571.thomi@imail.net.nz> <41C80288.9060206@tds.net> Message-ID: <41C832C1.8010202@dds.nl> Hello tutors, As i'm new to this mailing list so i shall introduce myself. My name is Maarten and except for some shell scripting I have little practical experience in programming (I'm a Linux/Solaris sys-admin). I've doing (mostly) reading about Python. But now trying, despite of my lack of talent for programming, to do write some stuff in Python (i don't call them programs yet;). So maybe a bit bold for a newbie to start posting a correction but i wanted the code to work: Kent Johnson wrote: > columns = [1,3,4] # Column numbers to show, 0-based > > f = open('mydata.txt') > for line in f: > data = line.split() # Assuming your data is tab- or space-delimited > data = [ item for i, item in data if i in columns ] # Filter out unwanted columns > print data # Output one row of text - put your formatting here > > There are probably more efficient ways to extract the data but this > should get you started. guess Kent forgot one line after: data = line.split() adding next line after it: data = enumerate(data) makes it work for me. Assuming: $ cat mydata.txt 1 1 2 3 23 0.1 13 2 3 4 24 0.15 24 1 1 2 12 0.2 45 2 3 5 1 0.12 116 6 2 7 27 0.18 211 9 4 6 28 0.45 Please correct my correction if i'm wrong. Still got a question. This notation/syntax of the list: [ item for i, item in data if i in columns ] is quite new for me. Can someone point me to more examples of this use Or give me the name of it (it must have a name) so i can google it? thx Maarten From juliusctw at gmail.com Tue Dec 21 16:00:51 2004 From: juliusctw at gmail.com (Julius) Date: Tue Dec 21 16:00:55 2004 Subject: [Tutor] Hi I made a mistake Message-ID: I am a beginner with Python, I originally tried to sign up to "GET" help, not to become a tutor, now i have alot of email everyday of people asking me questions, please take my name off the list, i won't be able to help, and please let me know how to sign up to get help :) -- Julius From kent37 at tds.net Tue Dec 21 16:12:28 2004 From: kent37 at tds.net (Kent Johnson) Date: Tue Dec 21 16:12:31 2004 Subject: [Tutor] implementing a table data structure in python? In-Reply-To: <41C832C1.8010202@dds.nl> References: <200412211943.22571.thomi@imail.net.nz> <41C80288.9060206@tds.net> <41C832C1.8010202@dds.nl> Message-ID: <41C83D5C.1010904@tds.net> Maarten wrote: > So maybe a bit bold for a newbie to start posting a correction but i > wanted the code to work: > > Kent Johnson wrote: > > >> columns = [1,3,4] # Column numbers to show, 0-based >> >> f = open('mydata.txt') >> for line in f: >> data = line.split() # Assuming your data is tab- or space-delimited >> data = [ item for i, item in data if i in columns ] # Filter out >> unwanted columns >> print data # Output one row of text - put your formatting here > > guess Kent forgot one line after: > > data = line.split() > > adding next line after it: > > data = enumerate(data) > > makes it work for me. Ah, right you are. I should know better than to post code without trying it! Actually I meant to write data = [ item for i, item in enumerate(data) if i in columns ] which is just a more compact way of saying the same thing. > Still got a question. This notation/syntax of the list: > > [ item for i, item in data if i in columns ] > > is quite new for me. Can someone point me to more examples of this use > Or give me the name of it (it must have a name) so i can google it? It's called a 'list comprehension'. It is a handy shortcut for a loop that builds a list from another list. You can read more about them here: http://docs.python.org/tut/node7.html#SECTION007140000000000000000 The line data = [ item for i, item in enumerate(data) if i in columns ] is equivalent to temp = [] for i, item in enumerate(data): if i in columns: temp.append(item) data = temp List comprehensions are generally more concise, easier to read (once you understand the syntax) and faster running than the equivalent spelled-out loop. Kent From kent37 at tds.net Tue Dec 21 16:15:32 2004 From: kent37 at tds.net (Kent Johnson) Date: Tue Dec 21 16:15:36 2004 Subject: [Tutor] Hi I made a mistake In-Reply-To: References: Message-ID: <41C83E14.8050408@tds.net> To get help on a specific topic, send a question to this list. (See, it's working already! :-) ) To learn about other topics, read the answers that others post. To unsubscribe, go to http://mail.python.org/mailman/listinfo/tutor and follow the directions. Kent Julius wrote: > I am a beginner with Python, I originally tried to sign up to "GET" > help, not to become a tutor, now i have alot of email everyday of > people asking me questions, please take my name off the list, i won't > be able to help, and please let me know how to sign up to get help :) From ARobert at MFS.com Tue Dec 21 16:16:43 2004 From: ARobert at MFS.com (Robert, Andrew) Date: Tue Dec 21 16:17:21 2004 Subject: [Tutor] Hi I made a mistake Message-ID: <968452DD78695147AA4A369C3DF9E40A024255DC@BOSMAILBOX3.corp.mfs.com> Good morning Julias, The python tutor list is a give and take of python information. If can contribute to an explanation or resolve a problem, then please do so. Additionally, you can read the e-mail messages and learn from others on how they handle things. Thank you, Andrew Robert Systems Architect Information Technologies Massachusetts Financial Services Phone: 617-954-5882 Pager: 781-764-7321 E-mail: arobert@mfs.com Linux User Number: #201204 -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of Julius Sent: Tuesday, December 21, 2004 10:01 AM To: Tutor@python.org Subject: [Tutor] Hi I made a mistake I am a beginner with Python, I originally tried to sign up to "GET" help, not to become a tutor, now i have alot of email everyday of people asking me questions, please take my name off the list, i won't be able to help, and please let me know how to sign up to get help :) -- Julius _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor "MFS Relay Service" made the following annotations on 12/21/2004 10:23:04 AM ------------------------------------------------------------------------------ This email communication and any attachments may contain proprietary, confidential, or privileged information. If you are not the intended recipient, you are hereby notified that you have received this email in error and that any review, disclosure, dissemination, distribution or copying of it or its contents is prohibited. The sender does not waive confidentiality or any privilege by mistransmission. If you have received this email in error, please notify the sender immediately, delete this email, and destroy all copies and any attachments. ============================================================================== From bds at waywood.co.uk Tue Dec 21 16:38:18 2004 From: bds at waywood.co.uk (Barnaby Scott) Date: Tue Dec 21 16:39:40 2004 Subject: [Tutor] Hi I made a mistake In-Reply-To: Message-ID: <001001c4e773$188f0d20$7c00a8c0@frankbruno> You *have* signed up to get help, it's just that you see all the mail to the mailing list. The requests for help go to all subscribers, not just a select group of 'tutors' - obviously you won't be offering solutions just yet, but maybe one day you will! This behaviour is the whole point of a mailing list, and you will find reading selected questions and answers very helpful if you are serious about learning Python. However if you want to suspend mail delivery, visit the list info page, and sign in at the bottom of the screen with the password you were given. Once signed in you can change all sorts of settings: stopping list mail, receiving it as a daily digest, unsubscribing, etc. You could for example stop mail delivery and just look for answers to your questions in the archive. (Again, see list info page: http://mail.python.org/mailman/listinfo/tutor). > -----Original Message----- > From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On > Behalf Of Julius > Sent: 21 December 2004 15:01 > To: Tutor@python.org > Subject: [Tutor] Hi I made a mistake > > > I am a beginner with Python, I originally tried to sign up to "GET" > help, not to become a tutor, now i have alot of email everyday of > people asking me questions, please take my name off the > list, i won't > be able to help, and please let me know how to sign up to > get help :) > -- > Julius > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From orion_val at 163.com Tue Dec 21 16:49:32 2004 From: orion_val at 163.com (Juan Shen) Date: Tue Dec 21 16:49:58 2004 Subject: [Tutor] implementing a table data structure in python? In-Reply-To: <41C832C1.8010202@dds.nl> References: <200412211943.22571.thomi@imail.net.nz> <41C80288.9060206@tds.net> <41C832C1.8010202@dds.nl> Message-ID: <41C8460C.103@163.com> Maarten, First of all, welcome to tutor@python.org I've done a little modification on Kent's code to make it more sensible. Please try it. Assuming the data file is 'mydata' $cat mydata 1 1 2 3 23 0.1 13 2 3 4 24 0.15 24 1 1 2 12 0.2 45 2 3 5 1 0.12 116 6 2 7 27 0.18 211 9 4 6 28 0.45 My python code: #!/usr/bin/python #Filename: selectcolumn.py import sys datafile='mydata' #Your datafile columns=[1,2,3,5] #Columns which you'd like to print try: f=open(datafile) except IOError: print "Can't open data file." sys.exit() for line in list(f): data=line.split() try: data=[data[i] for i in columns] except IndexError: print 'Column index out of range.' f.close() sys.exit() print '\t'.join(data) f.close() Maarten wrote: > Hello tutors, > > As i'm new to this mailing list so i shall introduce myself. My name > is Maarten and except for some shell scripting I have little practical > experience in programming (I'm a Linux/Solaris sys-admin). I've doing > (mostly) reading about Python. But now trying, despite of my lack of > talent for programming, to do write some stuff in Python (i don't call > them programs yet;). > > So maybe a bit bold for a newbie to start posting a correction but i > wanted the code to work: > > Kent Johnson wrote: > > >> columns = [1,3,4] # Column numbers to show, 0-based >> >> f = open('mydata.txt') >> for line in f: >> data = line.split() # Assuming your data is tab- or space-delimited >> data = [ item for i, item in data if i in columns ] # Filter out >> unwanted columns >> print data # Output one row of text - put your formatting here >> >> There are probably more efficient ways to extract the data but this >> should get you started. > > > guess Kent forgot one line after: > > data = line.split() > > adding next line after it: > > data = enumerate(data) > > makes it work for me. > > Assuming: > $ cat mydata.txt > 1 1 2 3 23 0.1 > 13 2 3 4 24 0.15 > 24 1 1 2 12 0.2 > 45 2 3 5 1 0.12 > 116 6 2 7 27 0.18 > 211 9 4 6 28 0.45 > > Please correct my correction if i'm wrong. > > Still got a question. This notation/syntax of the list: > > [ item for i, item in data if i in columns ] > > is quite new for me. Can someone point me to more examples of this use > Or give me the name of it (it must have a name) so i can google it? > > thx > Maarten > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From kent37 at tds.net Tue Dec 21 16:59:49 2004 From: kent37 at tds.net (Kent Johnson) Date: Tue Dec 21 16:59:53 2004 Subject: [Tutor] implementing a table data structure in python? In-Reply-To: <41C8460C.103@163.com> References: <200412211943.22571.thomi@imail.net.nz> <41C80288.9060206@tds.net> <41C832C1.8010202@dds.nl> <41C8460C.103@163.com> Message-ID: <41C84875.2070004@tds.net> Juan Shen wrote: > My python code: > #!/usr/bin/python > #Filename: selectcolumn.py > import sys > datafile='mydata' #Your datafile > columns=[1,2,3,5] #Columns which you'd like to print > try: > f=open(datafile) > except IOError: > print "Can't open data file." > sys.exit() > for line in list(f): > data=line.split() > try: > data=[data[i] for i in columns] (Sound of smacking forehead with hand) Thanks! I knew there had to be a better way than what I wrote! Kent > except IndexError: > print 'Column index out of range.' > f.close() > sys.exit() > print '\t'.join(data) > f.close() > From klappnase at freenet.de Tue Dec 21 21:28:40 2004 From: klappnase at freenet.de (Michael Lange) Date: Tue Dec 21 21:27:31 2004 Subject: [Tutor] Tix NoteBook programming problem In-Reply-To: <7d7029e70412202116483adb6a@mail.gmail.com> References: <7d7029e70412202116483adb6a@mail.gmail.com> Message-ID: <20041221212840.521fc4d1.klappnase@freenet.de> On Tue, 21 Dec 2004 14:16:56 +0900 Guillermo Fernandez Castellanos wrote: Hi Guille, thats a classic case of geometry manager conflicts. You dont need to pack the notebook pages explicitely, tix does this automagically for you and *tix does not use pack()*, so when you try to pack() the pages with > hd.pack() > gf.pack() tix doesnt know what to do; by the way, instead of writing > nb.add('hd',label="hard disk",underline=0) > hd = nb.subwidget('hd') you can simply do: hd = nb.add('hd',label="hard disk",underline=0) I hope this helps Michael From maarten at dds.nl Tue Dec 21 23:55:11 2004 From: maarten at dds.nl (Maarten) Date: Tue Dec 21 23:55:16 2004 Subject: [Tutor] implementing a table data structure in python? In-Reply-To: <41C8460C.103@163.com> References: <200412211943.22571.thomi@imail.net.nz> <41C80288.9060206@tds.net> <41C832C1.8010202@dds.nl> <41C8460C.103@163.com> Message-ID: <41C8A9CF.1010605@dds.nl> Juan Shen wrote: > Maarten, > First of all, welcome to tutor@python.org > I've done a little modification on Kent's code to make it more > sensible. Please try it. > Thx, And how nice it is to learn Python from other people's problems and again other people's solutions :) Maarten From alan.gauld at freenet.co.uk Tue Dec 21 23:58:54 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Dec 21 23:58:01 2004 Subject: [Tutor] implementing a table data structure in python? References: <200412211943.22571.thomi@imail.net.nz> Message-ID: <003f01c4e7b0$a5c380d0$b3b88651@xp> > Normally I'd use a database like mysql, postgreSQL, or even SQLite for this > sort of application, but the server I'm working on (which is outside my > control) does not have any of these installed. > > The CGI will not see heavy use, and I'm not very worried about race conditions > or collisions... > > > Does anyone have any advice for me? implementing this as a simple 2D array (or > list of lists) seems a little silly - surely there's a better way? Hows about a dictionary of lists. A key per column. The users pick which columns and you retrieve the lists. And of course shelve will treat a file like a dictionary... HTH, Alan G. From alan.gauld at freenet.co.uk Wed Dec 22 00:06:14 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed Dec 22 00:06:42 2004 Subject: [Tutor] implementing a table data structure in python? References: <200412211943.22571.thomi@imail.net.nz> <41C80288.9060206@tds.net> <41C832C1.8010202@dds.nl> Message-ID: <005801c4e7b1$abfa6d00$b3b88651@xp> > Still got a question. This notation/syntax of the list: > > [ item for i, item in data if i in columns ] > > is quite new for me. Can someone point me to more examples of this use > Or give me the name of it (it must have a name) so i can google it? Its a list comprehension, and theres a short explanation of them in the functional programming topic of my tutor. But there is one twist in this one, the comma after i: item for i,item in data... that makes the i,item a tuple. Normally we see a single thing there: [n for n in list] But if the list is a list of pairs(tuples) we can unpack the tuple into the two names: L = [(1,2),(3,4),(5,6)] print [i for i,j in L] should print [1,3,5] The first element of each tuple. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From thomi at imail.net.nz Wed Dec 22 02:06:44 2004 From: thomi at imail.net.nz (Thomas Clive Richards) Date: Wed Dec 22 02:06:52 2004 Subject: [Tutor] implementing a table data structure in python? In-Reply-To: <003f01c4e7b0$a5c380d0$b3b88651@xp> References: <200412211943.22571.thomi@imail.net.nz> <003f01c4e7b0$a5c380d0$b3b88651@xp> Message-ID: <200412221406.44830.thomi@imail.net.nz> On Wednesday December 22 2004 11:58 am, Alan Gauld wrote: > > Hows about a dictionary of lists. A key per column. The > users pick which columns and you retrieve the lists. And > of course shelve will treat a file like a dictionary... > Ahhh.... that's better.. I guess I should clarify: it's not lists per se that I find "silly" (a poor choice of words), just their use for this particular problem... Anyway, I took a look at KirbyBase, and decided to use that... it does almost exactly what I was trying to write myself, and does it reasonably quickly too! Thanks for all your help. -- Thomi Richards, thomi@once.net.nz From tegmine at gmail.com Wed Dec 22 02:06:22 2004 From: tegmine at gmail.com (Luis N) Date: Wed Dec 22 02:07:31 2004 Subject: [Tutor] Comments appreciated Message-ID: <77bfa81a04122117067ab205b@mail.gmail.com> This is the most meaningful thing this newbie has ever done. Comments are appreciated: #!/usr/local/bin/python trashcan = "/home/anewby/.trashcan" import os, sys, shutil junk = [] for arg in sys.argv: junk.append(arg) junk = junk[1:] empty = False if "-e" in junk: empty = True junk.remove("-e") if not os.path.exists(trashcan): os.mkdir(trashcan) def trash(junk): for i in junk: toss = trashcan + "/" + i if os.path.exists(toss): if os.path.isdir(toss): shutil.rmtree(toss) if os.path.isfile(toss): os.remove(toss) os.rename(i, toss) def can(): for j in os.listdir(trashcan): if os.path.isdir(j): shutil.rmtree(j) if os.path.isfile(j): os.remove(j) if len(junk) is 0 and empty == False: sys.exit() else: if len(junk) > 0: trash(junk) if empty == True: can() From jeff at ccvcorp.com Wed Dec 22 03:06:02 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed Dec 22 03:01:21 2004 Subject: [Tutor] Comments appreciated In-Reply-To: <77bfa81a04122117067ab205b@mail.gmail.com> References: <77bfa81a04122117067ab205b@mail.gmail.com> Message-ID: <41C8D68A.9020906@ccvcorp.com> Luis N wrote: > This is the most meaningful thing this newbie has ever done. Comments > are appreciated: Okay, here's a few thoughts... > junk = [] > for arg in sys.argv: > junk.append(arg) > > junk = junk[1:] You can write these four lines much simpler as: junk = sys.argv[1:] > if len(junk) is 0 and empty == False: > sys.exit() > else: > if len(junk) > 0: > trash(junk) > if empty == True: > can() You can simplify this, too. If empty is True, then you want to call can() regardless of whether you're doing anything else. You can handle that first, and *then* see whether there's junk to delete. This also means that, if you don't have junk to delete, you can simply do nothing, instead of explicitly calling sys.exit(). In addition, you don't need to explicitly test against True -- empty will already be true or false on its own, so comparing it inside an if statement doesn't gain you anything. if empty: can() if len(junk) > 0: trash(junk) Also, even though this is intended to be a quick shell script, it's not a bad idea to make everything except function defs into a little main() function, and call it in a script-only section. This gives you a bit more modularity, pulls all of your actions into a single place, and lets you avoid using global variables. def main(junk): trashcan = os.path.expanduser("~/.trashcan") empty = False if "-e" in junk: empty = True junk.remove("-e") if not os.path.exists(trashcan): os.mkdir(trashcan) if empty: can() if len(junk) > 0: trash(junk) if __name__ == '__main__': main(sys.argv[1:]) Notice that I've also changed your trashcan from explicitly stating a home directory to getting the home directory for whoever the current user is. You can refine main() further, too -- for instance, instead of setting an empty flag, you could just call can() as soon as you find the -e option. Jeff Shannon Technician/Programmer Credit International From guillermo.fernandez.castellanos at gmail.com Wed Dec 22 03:37:57 2004 From: guillermo.fernandez.castellanos at gmail.com (Guillermo Fernandez Castellanos) Date: Wed Dec 22 03:38:26 2004 Subject: Tix Select programming problem + Re: [Tutor] Tix NoteBook programming problem In-Reply-To: <20041221212840.521fc4d1.klappnase@freenet.de> References: <7d7029e70412202116483adb6a@mail.gmail.com> <20041221212840.521fc4d1.klappnase@freenet.de> Message-ID: <7d7029e704122118373f5dfc09@mail.gmail.com> Hi, Thanks for the answer. The intial code works indeed as soon as I put out the lines: hd.pack() gf.pack() I'm playing now with the Select buttons: import Tix def prtS(): print fruits.cget('value') def prtC(val): print val print sel.cget('value') root = Tix.Tk() fruits=Tix.Select(root,label="Fruits:", orientation='horizontal') fruits.add('orange',text="Orange",width=6,command=prtS) fruits.add('lemon',text="Lemon",width=6,command=prtS) fruits.add('apple',text="Apple",width=6,command=prtS) fruits.pack() sel=Tix.Control(root, label="X Coordinates", max=10, min=3, integer=True,command=prtC) sel.pack() root.mainloop() First of all, the prt is supposed to take an argument to work, as it's the case with Tix.Control. Then, the fruits.cget('value') is supposed to return the name of the button pressed. But it returns each time with an empty line! I've readed the doc, and it seems to me an unusual behaviour, as the doc says: """ The TixSelect widget supports same set of options as the TixControl widget for you to access its value""" http://tix.sourceforge.net/dist/current/docs/tix-book/intro.tex.html#1-11 Thanks, G On Tue, 21 Dec 2004 21:28:40 +0100, Michael Lange wrote: > On Tue, 21 Dec 2004 14:16:56 +0900 > Guillermo Fernandez Castellanos wrote: > > Hi Guille, > > thats a classic case of geometry manager conflicts. > You dont need to pack the notebook pages explicitely, tix does this > automagically for you and *tix does not use pack()*, so when > you try to pack() the pages with > > > hd.pack() > > gf.pack() > > tix doesnt know what to do; by the way, instead of writing > > > nb.add('hd',label="hard disk",underline=0) > > hd = nb.subwidget('hd') > > you can simply do: > > hd = nb.add('hd',label="hard disk",underline=0) > > I hope this helps > > Michael > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From keridee at jayco.net Wed Dec 22 06:45:51 2004 From: keridee at jayco.net (Jacob S.) Date: Wed Dec 22 06:45:52 2004 Subject: [Tutor] Registry Stuff Message-ID: <000501c4e7e9$8041d210$615428cf@JSLAPTOP> Hi, A little while ago, someone posted a message about an error and something about modifying the windows registry key HKEY_CURRENT_USER\Control Panel\Desktop so that the value Wallpaper was changed periodically. I wonder if anyone could tell me how to do that? I tried something, and it didn't work, and the documentation on _winreg is not very helpful to me. Any help is appreciated. : ) Jacob Schmidt From klappnase at freenet.de Wed Dec 22 11:33:41 2004 From: klappnase at freenet.de (Michael Lange) Date: Wed Dec 22 11:32:28 2004 Subject: [Tutor] Re: Tix Select programming problem In-Reply-To: <7d7029e704122118373f5dfc09@mail.gmail.com> References: <7d7029e70412202116483adb6a@mail.gmail.com> <20041221212840.521fc4d1.klappnase@freenet.de> <7d7029e704122118373f5dfc09@mail.gmail.com> Message-ID: <20041222113341.259407f8.klappnase@freenet.de> On Wed, 22 Dec 2004 11:37:57 +0900 Guillermo Fernandez Castellanos wrote: Hi Guille, > > I'm playing now with the Select buttons: > > import Tix > > def prtS(): > print fruits.cget('value') > > def prtC(val): > print val > print sel.cget('value') > > root = Tix.Tk() > fruits=Tix.Select(root,label="Fruits:", orientation='horizontal') > fruits.add('orange',text="Orange",width=6,command=prtS) > fruits.add('lemon',text="Lemon",width=6,command=prtS) > fruits.add('apple',text="Apple",width=6,command=prtS) > fruits.pack() > > sel=Tix.Control(root, label="X Coordinates", max=10, min=3, > integer=True,command=prtC) > sel.pack() > > root.mainloop() > The "command" option should be assigned to the Select widget itself, not to the added buttons. It takes two arguments then (from the tixSelect man page): Command-Line Name:-command Database Name: command Database Class: Command Specifies the TCL command to be executed when the -value of the Select widget is changed. This command will be invoked with two arguments. The first is the name of the button subwidget that has toggled. The second is a boolean value indicating whether the button subwidget is selected. This command is executed only when the -disableCallback option is set to false. So I changed your code a little to make it work: import Tix def prtS(*args): print args print fruits.cget('value') def prtC(val): print val print sel.cget('value') root = Tix.Tk() fruits=Tix.Select(root,label="Fruits:", orientation='horizontal',command=prtS) fruits.add('orange',text="Orange",width=6) fruits.add('lemon',text="Lemon",width=6) fruits.add('apple',text="Apple",width=6) fruits.pack() sel=Tix.Control(root, label="X Coordinates", max=10, min=3, integer=True,command=prtC) sel.pack() root.mainloop() Hope this helped Michael From alan.gauld at freenet.co.uk Wed Dec 22 12:31:34 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed Dec 22 12:30:48 2004 Subject: [Tutor] Comments appreciated References: <77bfa81a04122117067ab205b@mail.gmail.com> Message-ID: <001d01c4e819$cc484010$b3b88651@xp> > junk = [] > for arg in sys.argv: > junk.append(arg) > > junk = junk[1:] Why not for arg in sys.argv[1:]: junk.append(arg) Or even easier and faster: junk = sys.argv[1:] All I had time to look at, sorry. Alan G. From alan.gauld at freenet.co.uk Wed Dec 22 12:33:51 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed Dec 22 12:32:48 2004 Subject: [Tutor] Registry Stuff References: <000501c4e7e9$8041d210$615428cf@JSLAPTOP> Message-ID: <002401c4e81a$1cf72850$b3b88651@xp> > A little while ago, someone posted a message about an error and > something about modifying the windows registry key HKEY_CURRENT_USER\Control > Panel\Desktop so that the value Wallpaper was changed periodically. I wonder > if anyone could tell me how to do that? I tried something, and it didn't > work, and the documentation on _winreg is not very helpful to me. Any help > is appreciated. : ) I find it easiest to manipulate the Registry via WSH. THe Registry object can be instantiated from Python via the winall extensions. I find it much more intuitive than the native API route, YMMV. Search MSDN for the WSH object model documents Alan G. From ai2009 at yandex.ru Wed Dec 22 12:42:22 2004 From: ai2009 at yandex.ru (Andrey Ivanov) Date: Wed Dec 22 13:08:02 2004 Subject: [Tutor] Registry Stuff In-Reply-To: <000501c4e7e9$8041d210$615428cf@JSLAPTOP> References: <000501c4e7e9$8041d210$615428cf@JSLAPTOP> Message-ID: <666651947.20041222144222@yandex.ru> [Jacob S.] > Hi, > A little while ago, someone posted a message about an error and > something about modifying the windows registry key HKEY_CURRENT_USER\Control > Panel\Desktop so that the value Wallpaper was changed periodically. I wonder > if anyone could tell me how to do that? I tried something, and it didn't > work, and the documentation on _winreg is not very helpful to me. Any help > is appreciated. : ) > Jacob Schmidt > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor Here's the code: import sys import os import _winreg key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, \ r"Control Panel\Desktop", 0, _winreg.KEY_ALL_ACCESS) _winreg.SetValueEx(key, "Wallpaper", 0,_winreg.REG_SZ, \ os.path.abspath(sys.argv[1])) It has one defect though. You'll need to logout/login or restart Windows to apply the changes. I don't know how to apply them immediately. -- Andrey From john.ertl at fnmoc.navy.mil Wed Dec 22 18:49:11 2004 From: john.ertl at fnmoc.navy.mil (Ertl, John) Date: Wed Dec 22 18:49:21 2004 Subject: [Tutor] Popen? or something else Message-ID: All, I hate to ask this but I have just installed 2.4 and I need to get some info from a subprocess (I think that is correct term). At the Linux command line if I input dtg I get back a string representing a date time group. How do I do this in Python? I would think Popen but I just don't see it. $ dtg 2004122212 Thanks, John Ertl From zmerch at 30below.com Wed Dec 22 19:25:05 2004 From: zmerch at 30below.com (Roger Merchberger) Date: Wed Dec 22 19:24:42 2004 Subject: [Tutor] Popen? or something else In-Reply-To: Message-ID: <5.1.0.14.2.20041222131920.00b06298@mail.30below.com> Rumor has it that Ertl, John may have mentioned these words: >All, > >I hate to ask this but I have just installed 2.4 and I need to get some info >from a subprocess (I think that is correct term). > >At the Linux command line if I input dtg I get back a string representing a >date time group. How do I do this in Python? I would think Popen but I >just don't see it. It could, but there's also a better (IMHO), 'pythonic' way, something like this: def gettoday(): import time today = time.strftime('%Y%m%d%H',time.localtime(time.time())) return (today) >$ dtg >2004122212 If you wanted to use popen, it would look rather like this: import os dtg_s = os.popen("/path/to/dtg").readlines()[0] But this may use more system resources (spawning child shells & whatnot) than doing everything internally with the time module in Python. HTH, Roger "Merch" Merchberger -- Roger "Merch" Merchberger | A new truth in advertising slogan SysAdmin, Iceberg Computers | for MicroSoft: "We're not the oxy... zmerch@30below.com | ...in oxymoron!" From john.ertl at fnmoc.navy.mil Wed Dec 22 20:10:13 2004 From: john.ertl at fnmoc.navy.mil (Ertl, John) Date: Wed Dec 22 20:10:18 2004 Subject: [Tutor] Popen? or something else Message-ID: Roger, I have been doing it the Pythonic way (that is why I have no idea about how Popen works) but I need to make sure (the systems guys called me on it) I use the same dtg as everyone else...it is possible (has not happened yet in 20 years) it could be set to something else. Is the example you gave using the new 2.4 Popen? It looks like the older popen. I can get the older popen to work but not Popen. Thanks again. John Ertl -----Original Message----- From: Roger Merchberger [mailto:zmerch@30below.com] Sent: Wednesday, December 22, 2004 10:25 To: tutor@python.org Subject: Re: [Tutor] Popen? or something else Rumor has it that Ertl, John may have mentioned these words: >All, > >I hate to ask this but I have just installed 2.4 and I need to get some info >from a subprocess (I think that is correct term). > >At the Linux command line if I input dtg I get back a string representing a >date time group. How do I do this in Python? I would think Popen but I >just don't see it. It could, but there's also a better (IMHO), 'pythonic' way, something like this: def gettoday(): import time today = time.strftime('%Y%m%d%H',time.localtime(time.time())) return (today) >$ dtg >2004122212 If you wanted to use popen, it would look rather like this: import os dtg_s = os.popen("/path/to/dtg").readlines()[0] But this may use more system resources (spawning child shells & whatnot) than doing everything internally with the time module in Python. HTH, Roger "Merch" Merchberger -- Roger "Merch" Merchberger | A new truth in advertising slogan SysAdmin, Iceberg Computers | for MicroSoft: "We're not the oxy... zmerch@30below.com | ...in oxymoron!" _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From jasonchild at cnsp.com Wed Dec 22 21:02:06 2004 From: jasonchild at cnsp.com (Jason Child) Date: Wed Dec 22 21:02:08 2004 Subject: [Tutor] silly question Message-ID: <41C9D2BE.7040303@cnsp.com> I've got a silly question. ####################### P1 = "prefix1" P2 = "prefix2" def my_func(list, items): s = 0 out = "" for i in range(len(list)): if s == 0: p = P1 else: p = P2 for j in range(len(items)): out += p +items[j] return out ######################## now what i was expecting was the output to alternate prefixes for each item set in list. so: list = ["set1","set2"] items = ["car","truke",skateboard"] would yield: prefix1carprefix1truckprefix1skateboardprefix2carprefix2truckprefix2skateboard but i am not getting that. I do feel stupid for this, as I usually have an easy time picking up programming languages... -- Jason Christopher Child Computer Network Service Professionals VOZ Online From jasonchild at cnsp.com Wed Dec 22 21:14:32 2004 From: jasonchild at cnsp.com (Jason Child) Date: Wed Dec 22 21:14:36 2004 Subject: [Tutor] silly question In-Reply-To: <41C9D2BE.7040303@cnsp.com> References: <41C9D2BE.7040303@cnsp.com> Message-ID: <41C9D5A8.2010403@cnsp.com> Jason Child wrote: > I've got a silly question. > ####################### > P1 = "prefix1" > P2 = "prefix2" > > def my_func(list, items): > s = 0 > out = "" > for i in range(len(list)): > if s == 0: > p = P1 > else: > p = P2 > for j in range(len(items)): > out += p +items[j] > return out > ######################## > now what i was expecting was the output to alternate prefixes for each > item set in list. so: > > list = ["set1","set2"] > items = ["car","truke",skateboard"] > > would yield: > > prefix1carprefix1truckprefix1skateboardprefix2carprefix2truckprefix2skateboard > > > but i am not getting that. I do feel stupid for this, as I usually > have an easy time picking up programming languages... > > oops, I forgot to add the s = 1 and s=0 lines to the example code i posted... -- Jason Christopher Child Computer Network Service Professionals VOZ Online From john.ertl at fnmoc.navy.mil Wed Dec 22 21:39:37 2004 From: john.ertl at fnmoc.navy.mil (Ertl, John) Date: Wed Dec 22 21:39:39 2004 Subject: [Tutor] Is there a "better" way to do this? Message-ID: I am trying to do the usual thing of asking for an input and then checking it to see if it is valid. If the entry is not valid then ask again until you get the correct answer. I have come up with this class. I am trying to make a transition from procedural programming to object oriented. Is this a good approach for such a check? It seems to me this is more work then needed. (I can put in a counter also to break out if you try too many times). Please comment if you have the time. class greating: def __init__(self): self.OK = False self.lowValue = 1 self.highValue = 6 def opening(self): print """ Please choose from the following options. 1) - Normal Unit test with static data. 2) - Normal Unit test with missing data. 3) - Integration test with current DTG. 4) - Integration test with missing data. 5) - Clean directory 6) - Exit """ self.choice = raw_input("Choice(1-6) ") def check(self): try: self.choice = int(self.choice) except ValueError: print "Please enter a number from ",self.lowValue," to ",self.highValue pass if self.choice > self.highValue or self.choice < self.lowValue: print "You have entered an invalid entry. Please try again" else: self.OK = True a = greating() while a.OK != True: a.opening() a.check() print a.choice From hugonz-lists at h-lab.net Wed Dec 22 21:41:14 2004 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Wed Dec 22 21:41:45 2004 Subject: [Tutor] Popen? or something else In-Reply-To: References: Message-ID: <41C9DBEA.8010800@h-lab.net> You may use the 'commands' module, if your subprocess should return right away, then you can use: ## import commands mystring = commands.getoutput("dtg") ## then mystring should have "2004122212" (and possibly '\n', but you'll have to check that out, not sure about your command)in it... Hope it helps, it sure is quicker than popen (I only use popen if I need to keep reading the output, for a one-time capture, I personally prefer the "commands" module...) Hugo Ertl, John wrote: > Roger, > > I have been doing it the Pythonic way (that is why I have no idea about how > Popen works) but I need to make sure (the systems guys called me on it) I > use the same dtg as everyone else...it is possible (has not happened yet in > 20 years) it could be set to something else. > From john.ertl at fnmoc.navy.mil Wed Dec 22 21:43:13 2004 From: john.ertl at fnmoc.navy.mil (Ertl, John) Date: Wed Dec 22 21:43:15 2004 Subject: [Tutor] Popen? or something else Message-ID: Hugo, That looks like it will work great. Thanks, John -----Original Message----- From: Hugo Gonz?lez Monteverde [mailto:hugonz-lists@h-lab.net] Sent: Wednesday, December 22, 2004 12:41 To: tutor@python.org Cc: Ertl, John Subject: Re: [Tutor] Popen? or something else You may use the 'commands' module, if your subprocess should return right away, then you can use: ## import commands mystring = commands.getoutput("dtg") ## then mystring should have "2004122212" (and possibly '\n', but you'll have to check that out, not sure about your command)in it... Hope it helps, it sure is quicker than popen (I only use popen if I need to keep reading the output, for a one-time capture, I personally prefer the "commands" module...) Hugo Ertl, John wrote: > Roger, > > I have been doing it the Pythonic way (that is why I have no idea about how > Popen works) but I need to make sure (the systems guys called me on it) I > use the same dtg as everyone else...it is possible (has not happened yet in > 20 years) it could be set to something else. > From zmerch at 30below.com Wed Dec 22 21:47:45 2004 From: zmerch at 30below.com (Roger Merchberger) Date: Wed Dec 22 21:46:47 2004 Subject: [Tutor] Popen? or something else In-Reply-To: Message-ID: <5.1.0.14.2.20041222154130.04cb7178@mail.30below.com> Rumor has it that Ertl, John may have mentioned these words: >Roger, > >I have been doing it the Pythonic way (that is why I have no idea about how >Popen works) but I need to make sure (the systems guys called me on it) I >use the same dtg as everyone else...it is possible (has not happened yet in >20 years) it could be set to something else. > >Is the example you gave using the new 2.4 Popen? It looks like the older >popen. I can get the older popen to work but not Popen. My newest is 2.3.3 - I had no idea they modified popen for 2.4, but try this: dtg_s = Popen("/path/to/dtg", shell=True, stdout=PIPE).stdout If I've read the dox for 2.4 correctly, this has almost a fair chance of working... ;-) I cannot test this, however, as I don't have 2.4. (Glad I didn't upgrade, either -- I have several programs that rely on the present os.popen() ) here's a good page with how the new Popen works: http://www.python.org/peps/pep-0324.html with examples on how to replace os.popen[234]() and os.system(). HTH, Roger "Merch" Merchberger -- Roger "Merch" Merchberger -- SysAdmin, Iceberg Computers zmerch@30below.com Hi! I am a .signature virus. Copy me into your .signature to join in! From israel at uandmedance.com Wed Dec 22 22:24:21 2004 From: israel at uandmedance.com (Israel C. Evans) Date: Wed Dec 22 22:24:34 2004 Subject: [Tutor] Popen? or something else In-Reply-To: References: Message-ID: <41C9E605.7080504@uandmedance.com> Fun! testo = [line for line in commands.getoutput('ls -la').split('\n')] for line in testo: print line spits out nicely formatted ls data. It's Shelly! Ertl, John wrote: >Hugo, > >That looks like it will work great. > >Thanks, > >John > >-----Original Message----- >From: Hugo Gonz?lez Monteverde [mailto:hugonz-lists@h-lab.net] >Sent: Wednesday, December 22, 2004 12:41 >To: tutor@python.org >Cc: Ertl, John >Subject: Re: [Tutor] Popen? or something else > >You may use the 'commands' module, if your subprocess should return >right away, then you can use: > >## >import commands > >mystring = commands.getoutput("dtg") > >## > >then mystring should have "2004122212" (and possibly '\n', but you'll >have to check that out, not sure about your command)in it... > >Hope it helps, it sure is quicker than popen (I only use popen if I need >to keep reading the output, for a one-time capture, I personally prefer >the "commands" module...) > >Hugo > > >Ertl, John wrote: > > >>Roger, >> >>I have been doing it the Pythonic way (that is why I have no idea about >> >> >how > > >>Popen works) but I need to make sure (the systems guys called me on it) I >>use the same dtg as everyone else...it is possible (has not happened yet >> >> >in > > >>20 years) it could be set to something else. >> >> >> >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > > > From missive at hotmail.com Wed Dec 22 23:50:58 2004 From: missive at hotmail.com (Lee Harr) Date: Wed Dec 22 23:51:05 2004 Subject: [Tutor] Re: Is there a "better" way to do this? Message-ID: class greating: # I think the word you are looking for is # "greeting" def __init__(self): self.OK = False self.lowValue = 1 self.highValue = 6 def opening(self): print """ Please choose from the following options. 1) - Normal Unit test with static data. 2) - Normal Unit test with missing data. 3) - Integration test with current DTG. 4) - Integration test with missing data. 5) - Clean directory 6) - Exit """ self.choice = raw_input("Choice(1-6) ") # I would probably do this more like ... def set_options(self): self.options = ['Normal Unit test with static data', 'Normal Unit test with missing data', # ... etc ] def opening2(self): for i, option in self.options: print '%s) - %s', (i+1, option) # it makes the code marginally more complex now # but think about what will happen when you go to # rearrange the options or add new ones ... # # also, think about what you are going to "do" with # the choice made ... you might make the options # list a list of tuples and handle it all in one place ... def normal_with_static(self): pass def normal_with_missing(self): pass def set_options2(self): self.options = [('Normal Unit test with static data', self.normal_with_static), ('Normal Unit test with missing data', self.normal_with_missing), # ... etc ] # Or if you want "object oriented" practice... how about # an "Option" class with "description" and "method" # attributes? Just a thought ... _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From alan.gauld at freenet.co.uk Wed Dec 22 23:56:57 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed Dec 22 23:56:46 2004 Subject: [Tutor] silly question References: <41C9D2BE.7040303@cnsp.com> <41C9D5A8.2010403@cnsp.com> Message-ID: <004c01c4e879$8a3da880$b3b88651@xp> > oops, I forgot to add the s = 1 and s=0 lines to the example code i > posted... OK, To save us guessing, why don't you post it with the s=1/0 and also the actual output pattern you get? Seeing the error is a very powerful technique for guessing what may be at fault. A second hand description is never as precise. Alan G From jasonchild at cnsp.com Thu Dec 23 00:05:44 2004 From: jasonchild at cnsp.com (Jason Child) Date: Thu Dec 23 00:05:53 2004 Subject: [Tutor] silly question In-Reply-To: <004c01c4e879$8a3da880$b3b88651@xp> References: <41C9D2BE.7040303@cnsp.com> <41C9D5A8.2010403@cnsp.com> <004c01c4e879$8a3da880$b3b88651@xp> Message-ID: <41C9FDC8.6040707@cnsp.com> An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041222/d7b4ec62/attachment.html From jasonchild at cnsp.com Thu Dec 23 00:16:59 2004 From: jasonchild at cnsp.com (Jason Child) Date: Thu Dec 23 00:17:03 2004 Subject: [Tutor] silly question In-Reply-To: <41C9FDC8.6040707@cnsp.com> References: <41C9D2BE.7040303@cnsp.com> <41C9D5A8.2010403@cnsp.com> <004c01c4e879$8a3da880$b3b88651@xp> <41C9FDC8.6040707@cnsp.com> Message-ID: <41CA006B.4030803@cnsp.com> sorry everyone, I figured it out on my own ;) Jason Child wrote: > Alan Gauld wrote: > >>>oops, I forgot to add the s = 1 and s=0 lines to the example code i >>>posted... >>> >>> >> >>OK, To save us guessing, why don't you post it with the s=1/0 and >>also the actual output pattern you get? >> >>Seeing the error is a very powerful technique for guessing what may >>be at fault. A second hand description is never as precise. >> >>Alan G >> >> >> > I've got a silly question. > ####################### > P1 = "prefix1" > P2 = "prefix2" > > def my_func(list, items): > s = 0 > out = "" > for i in range(len(list)): > if s == 0: > p = P1 > s = 1 > else: > p = P2 > s = 0 > for j in range(len(items)): > out += p +items[j] > return out > ######################## > > If my input was: > list = ["car list 1","car list 2"] > items = ["torino","mustang","elantra"] > > for output I get: > prefix1torinoprefix1mustangprefix1elantraprefix1torinoprefix1mustangprefix1elantra > > when I expect: > prefix1torinoprefix1mustangprefix1elantra*prefix2*torino*prefix2*mustang*prefix2*elantra > > >-- >Jason Christopher Child > >Computer Network Service Professionals >VOZ Online > > >------------------------------------------------------------------------ > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > -- Jason Christopher Child Computer Network Service Professionals VOZ Online From alan.gauld at freenet.co.uk Thu Dec 23 00:16:20 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Dec 23 00:17:26 2004 Subject: [Tutor] Is there a "better" way to do this? References: Message-ID: <005101c4e87c$3f5329a0$b3b88651@xp> > procedural programming to object oriented. Is this a good approach for > such a check? It seems to me this is more work then needed. Its a valid approach but whether its the best approach depends on what else you intend to do. For example will there be multiple types of greeting? or several instances of greeting? Or will you use this same greeting in many programs? I suspect not because the menu is embedded, but if you could parameterise the init method, then you could pass the menu string in along with high and low values and then you might have a reusable text menu class? class Menu: def __init__(self, menu, prompt, high, low=1): # lots of self assignments here def opening(self): print self.menu self.choice = raw_input(self.prompt) def validateChoice(self): # this method overriden in subbclasses if need be... return self.low < int(self.choice) < self.high But thats just soome personal musings. Comments on your code follow: > class greating: Its conventional to make class names start with a capital letter, instances with a lower. Python doesn't case but its easier on the reader... > def __init__(self): > self.OK = False > self.lowValue = 1 > self.highValue = 6 > > def opening(self): > print """ > Please choose from the following options. > 1) - Normal Unit test with static data. > 2) - Normal Unit test with missing data. > 3) - Integration test with current DTG. > 4) - Integration test with missing data. > 5) - Clean directory > 6) - Exit > """ > self.choice = raw_input("Choice(1-6) ") See comments above about making menu a configurable item. > def check(self): > try: > self.choice = int(self.choice) > except ValueError: > print "Please enter a number from ",self.lowValue," to > ",self.highValue > pass pass does nothing. It is only used to indicate that something should go here sometime. But since you are doing something, you don't need pass here. Maybe you meant return? > if self.choice > self.highValue or self.choice < self.lowValue: > print "You have entered an invalid entry. Please try again" python allows a shortened version of this like if x < value < y: # checks that value is between x and y. > else: > self.OK = True As well as printing the errors you probably want to set self.OK to False in the other cases. Just because you did it in the init() is not enough, if you call opening() more than once and the user types valid input first time but not second time OK will be set to True when it should be False. The way you use it in the test case is OK but in other scenarios... > a = greating() > > while a.OK != True: > a.opening() > a.check() Try this test loop instead: while a.choice not in '123456': # ie an invalid value a.opening() a.check() OOPS! IT won;t work because a.choice doesn't exist until after calling a.opening(). This is one reason you are better to initialise all instance variables in the init method IMHO. HTH Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From zmerch at 30below.com Thu Dec 23 00:30:54 2004 From: zmerch at 30below.com (Roger Merchberger) Date: Thu Dec 23 00:30:31 2004 Subject: [Tutor] silly question In-Reply-To: <41C9FDC8.6040707@cnsp.com> References: <004c01c4e879$8a3da880$b3b88651@xp> <41C9D2BE.7040303@cnsp.com> <41C9D5A8.2010403@cnsp.com> <004c01c4e879$8a3da880$b3b88651@xp> Message-ID: <5.1.0.14.2.20041222182026.04cbf978@mail.30below.com> Rumor has it that Jason Child may have mentioned these words: >## I've got a silly question. >####################### >P1 = "prefix1" >P2 = "prefix2" > >def my_func(list, items): > s = 0 > out = "" > for i in range(len(list)): > if s == 0: > p = P1 > s = 1 > else: > p = P2 > s = 0 > for j in range(len(items)): > out += p +items[j] > return out >######################## > >If my input was: >list = ["car list 1","car list 2"] >items = ["torino","mustang","elantra"] > >for output I get: >prefix1torinoprefix1mustangprefix1elantraprefix1torinoprefix1mustangprefix1elantra > >when I expect: >prefix1torinoprefix1mustangprefix1elantraprefix2torinoprefix2mustangprefix2elantra Why not just do this: ####################### prefixes = ["prefix1" , "prefix2" ] def my_func(list, items): out = "" for prefixloop in prefixes: for itemloop in items: out += prefixloop + itemloop return out ######################## It's what's called a 'nested loop' - and that way if you had to add a 3rd prefix, it would "just work" instead of having to add yet another variable to the loop you'd designed. By the way, other than getting the length of 'list' you don't use anything in that list. Another thing (which might also be a problem in your code) using 'list' as a variable name is not a good idea, as it's a reserved word, if I'm not mistaken. Consider this snippet: Python 2.2.2 (#1, Feb 24 2003, 19:13:11) [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> q = (1,2,3) >>> print list(q) [1, 2, 3] Hope this helps, Roger "Merch" Merchberger -- Roger "Merch" Merchberger | "Profile, don't speculate." SysAdmin, Iceberg Computers | Daniel J. Bernstein zmerch@30below.com | From jasonchild at cnsp.com Thu Dec 23 01:52:53 2004 From: jasonchild at cnsp.com (Jason Child) Date: Thu Dec 23 01:52:55 2004 Subject: [Tutor] silly question In-Reply-To: <5.1.0.14.2.20041222182026.04cbf978@mail.30below.com> References: <004c01c4e879$8a3da880$b3b88651@xp> <41C9D2BE.7040303@cnsp.com> <41C9D5A8.2010403@cnsp.com> <004c01c4e879$8a3da880$b3b88651@xp> <5.1.0.14.2.20041222182026.04cbf978@mail.30below.com> Message-ID: <41CA16E5.6050605@cnsp.com> Ok, I guess my question (now) is: how do I change global variables within a function: ################################## VAR = "TEST" def m(): VAR="no test" ################################## when I do this (from the interactive editor): ################################## >>>print VAR TEST >>>m() >>> >>>print VAR TEST >>> ################################## any advice? From singingxduck at gmail.com Thu Dec 23 01:58:55 2004 From: singingxduck at gmail.com (Orri Ganel) Date: Thu Dec 23 01:59:01 2004 Subject: [Tutor] silly question In-Reply-To: <41CA16E5.6050605@cnsp.com> References: <41C9D2BE.7040303@cnsp.com> <41C9D5A8.2010403@cnsp.com> <004c01c4e879$8a3da880$b3b88651@xp> <5.1.0.14.2.20041222182026.04cbf978@mail.30below.com> <41CA16E5.6050605@cnsp.com> Message-ID: <3449428f0412221658b093e68@mail.gmail.com> On Wed, 22 Dec 2004 17:52:53 -0700, Jason Child wrote: > Ok, I guess my question (now) is: > > how do I change global variables within a function: > > ################################## > VAR = "TEST" > > def m(): > VAR="no test" > ################################## > > when I do this (from the interactive editor): > > ################################## > >>>print VAR > TEST > >>>m() > >>> > >>>print VAR > TEST > >>> > ################################## > > any advice? > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > >>> VAR = "TEST" >>> def m(): global VAR ## <- this is what you were missing . . . basically, this means VAR = "no test" ## that, instead of assigning to a new variable VAR in the local ## namespace of m(), you are assigning to the variable VAR that ## was defined on the global level >>> print VAR TEST >>> m() >>> print VAR no test HTH, Orri -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. From maxnoel_fr at yahoo.fr Thu Dec 23 02:05:57 2004 From: maxnoel_fr at yahoo.fr (Max Noel) Date: Thu Dec 23 02:06:10 2004 Subject: [Tutor] Popen? or something else In-Reply-To: <41C9E605.7080504@uandmedance.com> References: <41C9E605.7080504@uandmedance.com> Message-ID: On Dec 22, 2004, at 22:24, Israel C. Evans wrote: > Fun! > > testo = [line for line in commands.getoutput('ls -la').split('\n')] > for line in testo: > print line > > spits out nicely formatted ls data. > > It's Shelly! I haven't tried it, but the above code looks like it could be simplified to: for line in commands.getoutput('ls -la').split('\n'): print line Or, of course, the obvious: print commands.getoutput('ls -la') -- Max maxnoel_fr at yahoo dot fr -- ICQ #85274019 "Look at you hacker... A pathetic creature of meat and bone, panting and sweating as you run through my corridors... How can you challenge a perfect, immortal machine?" From keridee at jayco.net Thu Dec 23 02:55:27 2004 From: keridee at jayco.net (Jacob S.) Date: Thu Dec 23 02:55:55 2004 Subject: [Tutor] Popen? or something else References: <5.1.0.14.2.20041222131920.00b06298@mail.30below.com> Message-ID: <004d01c4e892$7b84b360$cc5328cf@JSLAPTOP> Hi! I just wondered why you included the time.localtime(time.time()) in the defining of today. Doesn't the default time.gmtime() work okay? def gettoday(): import time today = time.strftime('%Y%m%d%H') return today Jacob Schmidt > Rumor has it that Ertl, John may have mentioned these words: > >All, > > > >I hate to ask this but I have just installed 2.4 and I need to get some info > >from a subprocess (I think that is correct term). > > > >At the Linux command line if I input dtg I get back a string representing a > >date time group. How do I do this in Python? I would think Popen but I > >just don't see it. > > It could, but there's also a better (IMHO), 'pythonic' way, something like > this: > > def gettoday(): > > import time > today = time.strftime('%Y%m%d%H',time.localtime(time.time())) > return (today) > > >$ dtg > >2004122212 > > If you wanted to use popen, it would look rather like this: > > import os > dtg_s = os.popen("/path/to/dtg").readlines()[0] > > But this may use more system resources (spawning child shells & whatnot) > than doing everything internally with the time module in Python. > > HTH, > Roger "Merch" Merchberger > > -- > Roger "Merch" Merchberger | A new truth in advertising slogan > SysAdmin, Iceberg Computers | for MicroSoft: "We're not the oxy... > zmerch@30below.com | ...in oxymoron!" > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From kent37 at tds.net Thu Dec 23 03:57:34 2004 From: kent37 at tds.net (Kent Johnson) Date: Thu Dec 23 03:57:38 2004 Subject: [Tutor] Is there a "better" way to do this? In-Reply-To: References: Message-ID: <41CA341E.1020306@tds.net> John, In this case I think using a class is overkill. You can write a simple procedural version like this: def getOption(): while True: print """ Please choose from the following options. 1) - Normal Unit test with static data. 2) - Normal Unit test with missing data. 3) - Integration test with current DTG. 4) - Integration test with missing data. 5) - Clean directory 6) - Exit """ choice = raw_input("Choice(1-6) ") try: choice = int(choice) except ValueError: print "Please enter a number from 1 to 6" if 1 <= choice <= 6: return choice print "You have entered an invalid entry. Please try again" option = getOption() print "You chose", option If you have multiple clients you could parameterize it so it becomes def getOption(prompt, low, high) I try to do the simplest thing that could possibly work. Sometimes that is just straight line code, with maybe a few functions mixed in. Sometimes a procedural approach works fine. Sometimes classes and objects are the right way to go, but I don't introduce classes until I need them. Don't get me wrong, I am a huge fan of OOP, but sometimes it is a bigger hammer than you need. Kent Ertl, John wrote: > I am trying to do the usual thing of asking for an input and then checking > it to see if it is valid. If the entry is not valid then ask again until > you get the correct answer. > > I have come up with this class. I am trying to make a transition from > procedural programming to object oriented. Is this a good approach for > such a check? It seems to me this is more work then needed. (I can put in a > counter also to break out if you try too many times). > > Please comment if you have the time. > > class greating: > > def __init__(self): > self.OK = False > self.lowValue = 1 > self.highValue = 6 > > def opening(self): > print """ > Please choose from the following options. > 1) - Normal Unit test with static data. > 2) - Normal Unit test with missing data. > 3) - Integration test with current DTG. > 4) - Integration test with missing data. > 5) - Clean directory > 6) - Exit > """ > self.choice = raw_input("Choice(1-6) ") > > def check(self): > try: > self.choice = int(self.choice) > except ValueError: > print "Please enter a number from ",self.lowValue," to > ",self.highValue > pass > > if self.choice > self.highValue or self.choice < self.lowValue: > print "You have entered an invalid entry. Please try again" > else: > self.OK = True > > > a = greating() > > while a.OK != True: > a.opening() > a.check() > > print a.choice > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From alan.gauld at freenet.co.uk Thu Dec 23 09:24:47 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Dec 23 09:24:52 2004 Subject: [Tutor] silly question References: <004c01c4e879$8a3da880$b3b88651@xp><41C9D2BE.7040303@cnsp.com> <41C9D5A8.2010403@cnsp.com><004c01c4e879$8a3da880$b3b88651@xp><5.1.0.14.2.20041222182026.04cbf978@mail.30below.com> <41CA16E5.6050605@cnsp.com> Message-ID: <007901c4e8c8$dd743420$b3b88651@xp> > how do I change global variables within a function: > by declaring them as global. See my tutorial topic: "Whats in a Name?" for a discussion of this. > ################################## > VAR = "TEST" > > def m(): > VAR="no test" creates a new variable insidethe function. def m(): global VAR VAR = 'no test' now changes the global(or at least module scope) VAR. Alan G. From alan.gauld at freenet.co.uk Thu Dec 23 09:29:52 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Dec 23 09:29:43 2004 Subject: [Tutor] silly question References: <41C9D2BE.7040303@cnsp.com><41C9D5A8.2010403@cnsp.com> <004c01c4e879$8a3da880$b3b88651@xp><41C9FDC8.6040707@cnsp.com> <41CA006B.4030803@cnsp.com> Message-ID: <008401c4e8c9$9374c370$b3b88651@xp> > sorry everyone, I figured it out on my own ;) So having made it a tutor topic, please close the discussion by telling us what was wrong. That way the rest of us don't spend the rest of the day worrying about it, saying "I wonder what Jason did wrong?" :-) Sorry if I appear to nag but its how these mailing lists work - someone posts a problem, everyone looks at it and everyone should see the answer. That way *everyone* improves their chances of not making the same mistake. Alan G. > > > > Jason Child wrote: > > > Alan Gauld wrote: > > > >>>oops, I forgot to add the s = 1 and s=0 lines to the example code i > >>>posted... > >>> > >>> > >> > >>OK, To save us guessing, why don't you post it with the s=1/0 and > >>also the actual output pattern you get? > >> > >>Seeing the error is a very powerful technique for guessing what may > >>be at fault. A second hand description is never as precise. > >> > >>Alan G > >> > >> > >> > > I've got a silly question. > > ####################### > > P1 = "prefix1" > > P2 = "prefix2" > > > > def my_func(list, items): > > s = 0 > > out = "" > > for i in range(len(list)): > > if s == 0: > > p = P1 > > s = 1 > > else: > > p = P2 > > s = 0 > > for j in range(len(items)): > > out += p +items[j] > > return out > > ######################## > > > > If my input was: > > list = ["car list 1","car list 2"] > > items = ["torino","mustang","elantra"] > > > > for output I get: > > prefix1torinoprefix1mustangprefix1elantraprefix1torinoprefix1mustangpr efix1elantra > > > > when I expect: > > prefix1torinoprefix1mustangprefix1elantra*prefix2*torino*prefix2*musta ng*prefix2*elantra > > > > > >-- > >Jason Christopher Child > > > >Computer Network Service Professionals > >VOZ Online > > > > > >--------------------------------------------------------------------- --- > > > >_______________________________________________ > >Tutor maillist - Tutor@python.org > >http://mail.python.org/mailman/listinfo/tutor > > > > > > > -- > Jason Christopher Child > > Computer Network Service Professionals > VOZ Online > > > From orion_val at 163.com Thu Dec 23 13:42:50 2004 From: orion_val at 163.com (Juan Shen) Date: Thu Dec 23 13:43:11 2004 Subject: [Tutor] Is there an easy way to conduct binary numbers? Message-ID: <41CABD4A.4080006@163.com> I have found there are easy functions and options to do basic octal and hexadecimal number operation. oct(...) oct(number) -> string Return the octal representation of an integer or long integer. hex(...) hex(number) -> string Return the hexadecimal representation of an integer or long integer. print '%o' %number Print a decimal number in octal format. print '%X' %number Print a decimal number in hexadecimal format. However, I can't find their binary counterpart, something like bin(...) or print '%b'. Binary integer is extremely useful in my electronic-related job. So...I need help. Is there any function to transform between binary and decimal integers in python's library? If not, what's the solution to binary? Juan From bwinton at latte.ca Thu Dec 23 14:36:31 2004 From: bwinton at latte.ca (Blake Winton) Date: Thu Dec 23 14:36:33 2004 Subject: [Tutor] Is there an easy way to conduct binary numbers? In-Reply-To: <41CABD4A.4080006@163.com> References: <41CABD4A.4080006@163.com> Message-ID: <41CAC9DF.9090902@latte.ca> Juan Shen wrote: > Binary integer is extremely useful in my > electronic-related job. So...I need help. Is there any function to > transform between binary and decimal integers in python's library? If > not, what's the solution to binary? I can't speak for everyone, but most of the people I've met who wrok with binary learn how to read hex and translate it to binary in their heads. (It's slow at first, but it gets really quick with a bit of practice.) You could, if you needed to, write a bin function yourself. I would recommend calling the oct function, and replacing the characters in the string. (If you need help getting that working, give it a good try, and post what you have, and I'll be happy to assist you.) Later, Blake. From ken at kenwstevens.net Thu Dec 23 18:32:46 2004 From: ken at kenwstevens.net (Ken Stevens) Date: Thu Dec 23 18:32:49 2004 Subject: [Tutor] What am I doing wrong... Message-ID: <20041223173246.GG10016@kenwstevens.net> I am a elative new comer to python. I wrote the following test snippet. #!/usr/bin/env python def main (): play_test() def play_test (): print "Hi! -- in play test" When I do "python test.py" absolutely nothing happens. I expect it to do the print statement. Thanks in advance for your help. Ken -- The horizon of many people is a circle with a radius of zero. They call this their point of view. -- Albert Einstein From zmerch at 30below.com Thu Dec 23 18:50:20 2004 From: zmerch at 30below.com (Roger Merchberger) Date: Thu Dec 23 18:49:27 2004 Subject: [Tutor] What am I doing wrong... In-Reply-To: <20041223173246.GG10016@kenwstevens.net> Message-ID: <5.1.0.14.2.20041223124605.03bf0e50@mail.30below.com> Rumor has it that Ken Stevens may have mentioned these words: >I am a elative new comer to python. I wrote the following test >snippet. > >#!/usr/bin/env python > >def main (): > play_test() > >def play_test (): > print "Hi! -- in play test" > >When I do "python test.py" absolutely nothing happens. Correct. >I expect it to do the print statement. >Thanks in advance for your help. You defined functions, but not the main code of the program, therefore it does nothing. Appended to your program, you need this: ### This defines where the actual program starts... if __name__ == '__main__': main() ### Now the program is done. ;-) Hope this Helps! Roger "Merch" Merchberger -- Roger "Merch" Merchberger | Anarchy doesn't scale well. -- Me zmerch@30below.com. | SysAdmin, Iceberg Computers From johnp at milwaukielumber.com Thu Dec 23 18:50:41 2004 From: johnp at milwaukielumber.com (John Purser) Date: Thu Dec 23 18:50:44 2004 Subject: [Tutor] What am I doing wrong... In-Reply-To: <20041223173246.GG10016@kenwstevens.net> Message-ID: <200412231750.iBNHoe7s001887@mail.morseintranet.com> The basic problem is you never told Python to DO anything except define what it would do if anyone asked it to. If you add the line "main()" to the bottom you'll get your message printed. I'm not sure if this is your code or my mail agent (outlook) but as you can see below there's a space between the function name (main) and the parenthesis. I don't believe that's supposed to be there. Good Luck. John Purser -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of Ken Stevens Sent: Thursday, December 23, 2004 09:33 To: tutor@python.org Subject: [Tutor] What am I doing wrong... I am a elative new comer to python. I wrote the following test snippet. #!/usr/bin/env python def main (): play_test() def play_test (): print "Hi! -- in play test" When I do "python test.py" absolutely nothing happens. I expect it to do the print statement. Thanks in advance for your help. Ken -- The horizon of many people is a circle with a radius of zero. They call this their point of view. -- Albert Einstein _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From marilyn at deliberate.com Thu Dec 23 18:55:10 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Thu Dec 23 18:55:17 2004 Subject: [Tutor] What am I doing wrong... In-Reply-To: <20041223173246.GG10016@kenwstevens.net> Message-ID: Hi Ken, Welcome to python! Adding one line should do it for you: On Thu, 23 Dec 2004, Ken Stevens wrote: > I am a elative new comer to python. I wrote the following test > snippet. > > #!/usr/bin/env python > > def main (): > play_test() > > def play_test (): > print "Hi! -- in play test" main() > > When I do "python test.py" absolutely nothing happens. > > I expect it to do the print statement. > > Thanks in advance for your help. > > Ken > > > > -- From kent37 at tds.net Thu Dec 23 20:48:03 2004 From: kent37 at tds.net (Kent Johnson) Date: Thu Dec 23 20:48:08 2004 Subject: [Tutor] Is there an easy way to conduct binary numbers? In-Reply-To: <41CABD4A.4080006@163.com> References: <41CABD4A.4080006@163.com> Message-ID: <41CB20F3.8090109@tds.net> Googling in comp.lang.python for "convert binary" gives several solutions including the ones in this thread: http://tinyurl.com/6dwom Juan Shen wrote: > I have found there are easy functions and options to do basic octal and > hexadecimal number operation. > > oct(...) > oct(number) -> string > > Return the octal representation of an integer or long integer. > > hex(...) > hex(number) -> string > > Return the hexadecimal representation of an integer or long integer. > > print '%o' %number > Print a decimal number in octal format. > > print '%X' %number > Print a decimal number in hexadecimal format. > > However, I can't find their binary counterpart, something like bin(...) > or print '%b'. Binary integer is extremely useful in my > electronic-related job. So...I need help. Is there any function to > transform between binary and decimal integers in python's library? If > not, what's the solution to binary? > Juan > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From marilyn at deliberate.com Thu Dec 23 23:17:12 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Thu Dec 23 23:17:18 2004 Subject: [Tutor] tempfile Message-ID: Hello Python Tutors, I'm using tempfile. The doc says it is opened 'w+b' so that it can be read and written without closing and reopening. But, for the life of me, I can't find any way to rewind it so I can read what I wrote. tempfile.mkstemp gives me the file descriptor. Is there a way to make a file object from a file descriptor? Or, is there something in os or fcntl that allows me to rewind from a file descriptor? Thank you for any help you can give. Marilyn Davis From singingxduck at gmail.com Thu Dec 23 23:14:51 2004 From: singingxduck at gmail.com (Orri Ganel) Date: Thu Dec 23 23:22:07 2004 Subject: [Tutor] Is there an easy way to conduct binary numbers? In-Reply-To: <41CABD4A.4080006@163.com> References: <41CABD4A.4080006@163.com> Message-ID: <3449428f041223141471fc16c0@mail.gmail.com> On Thu, 23 Dec 2004 20:42:50 +0800, Juan Shen wrote: > I have found there are easy functions and options to do basic octal and > hexadecimal number operation. > > oct(...) > oct(number) -> string > > Return the octal representation of an integer or long integer. > > hex(...) > hex(number) -> string > > Return the hexadecimal representation of an integer or long integer. > > print '%o' %number > Print a decimal number in octal format. > > print '%X' %number > Print a decimal number in hexadecimal format. > > However, I can't find their binary counterpart, something like bin(...) > or print '%b'. Binary integer is extremely useful in my > electronic-related job. So...I need help. Is there any function to > transform between binary and decimal integers in python's library? If > not, what's the solution to binary? > Juan > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > Here's a possible conversion function to be used in much the same way as oct and hex: def bin(integer, returnType=str): bin = {'0':'000','1':'001','2':'010','3':'011','4':'100','5':'101','6':'110','7':'111'} if returnType == int: return int(''.join([bin[i] for i in oct(integer)])) elif returnType == long: return long(''.join([bin[i] for i in oct(integer)]),10) else: return (''.join([bin[i] for i in oct(integer)])).lstrip("0") Just define this in the program you are writing and use bin as you would use oct or hex, making sure to specify int or long as the return type if you don't want a str. -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. From missive at hotmail.com Thu Dec 23 23:39:31 2004 From: missive at hotmail.com (Lee Harr) Date: Thu Dec 23 23:40:07 2004 Subject: [Tutor] Re: tempfile Message-ID: >I'm using tempfile. The doc says it is opened 'w+b' so that it can be >read and written without closing and reopening. > >But, for the life of me, I can't find any way to rewind it so I can >read what I wrote. > >>>import tempfile >>>import os >>>fd, name = tempfile.mkstemp() >>>os.write(fd, 'foo') 3 >>>os.lseek(fd, 0, 0) 0L >>>os.read(fd, 10) 'foo' >tempfile.mkstemp gives me the file descriptor. Is there a way to make >a file object from a file descriptor? > Not that I can see: http://docs.python.org/lib/os-fd-ops.html ... except maybe this, which is not quite the same: >>>import tempfile >>>import os >>>fd, name = tempfile.mkstemp() >>>os.write(fd, 'foo') 3 >>>f = open(name) >>>f.read() 'foo' _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From marilyn at deliberate.com Fri Dec 24 00:11:53 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Fri Dec 24 00:12:01 2004 Subject: [Tutor] tempfile (fwd) Message-ID: Ooops. I forgot to send to the list. ---------- Forwarded message ---------- Date: Thu, 23 Dec 2004 14:53:18 -0800 (PST) From: Marilyn Davis To: QoD SEC Subject: Re: [Tutor] tempfile On Thu, 23 Dec 2004, QoD SEC wrote: > you could use the seek method of the file object to go to the > beginning of the file: Thank you. But my problem was that I had a "file descriptor", a low-level thing, and not a "file object", a high-level thing. A file descriptor doesn't have a seek. But I found the os.fdopen(fd) call. It makes a file object from a file descriptor. So I can do: #!/usr/bin/env python import tempfile import os def do_test(): tmp_fp, tmp_name = tempfile.mkstemp() os.write(tmp_fp, "stuff") file_obj = os.fdopen(tmp_fp) file_obj.seek(0) print os.read(tmp_fp,10) os.close(tmp_fp) do_test() --- and "stuff" comes out. But, the mystery now is: def do_test(): tmp_fp, tmp_name = tempfile.mkstemp() os.write(tmp_fp, "stuff") os.fdopen(tmp_fp).seek(0) print os.read(tmp_fp,10) os.close(tmp_fp) --- gets an OSError: [Errno 9] Bad File Descriptor on os.read(tmp_fp,10) I'm thinking that, if I don't keep a reference to the file object, it gets automatically closed. How pythonic. Thank you for your thoughts. Marilyn > here is what the library reference says about it: > > seek( offset[, whence]) > Set the file's current position, like stdio's fseek(). The whence > argument is optional and defaults to 0 (absolute file positioning); > other values are 1 (seek relative to the current position) and 2 (seek > relative to the file's end). There is no return value. Note that if > the file is opened for appending (mode 'a' or 'a+'), any seek() > operations will be undone at the next write. If the file is only > opened for writing in append mode (mode 'a'), this method is > essentially a no-op, but it remains useful for files opened in append > mode with reading enabled (mode 'a+'). If the file is opened in text > mode (mode 't'), only offsets returned by tell() are legal. Use of > other offsets causes undefined behavior. > > Note that not all file objects are seekable. > > from http://docs.python.org/lib/bltin-file-objects.html > > > On Thu, 23 Dec 2004 14:17:12 -0800 (PST), Marilyn Davis > wrote: > > Hello Python Tutors, > > > > I'm using tempfile. The doc says it is opened 'w+b' so that it can be > > read and written without closing and reopening. > > > > But, for the life of me, I can't find any way to rewind it so I can > > read what I wrote. > > > > tempfile.mkstemp gives me the file descriptor. Is there a way to make > > a file object from a file descriptor? > > > > Or, is there something in os or fcntl that allows me to rewind from a > > file descriptor? > > > > Thank you for any help you can give. > > > > Marilyn Davis > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > -- From cyresse at gmail.com Fri Dec 24 00:11:58 2004 From: cyresse at gmail.com (Liam Clarke) Date: Fri Dec 24 00:12:06 2004 Subject: [Tutor] Re: tempfile In-Reply-To: References: Message-ID: fileObj=... fileObj.seek()? Is what I use, although that's for specific byte positions I believe. On Fri, 24 Dec 2004 03:09:31 +0430, Lee Harr wrote: > >I'm using tempfile. The doc says it is opened 'w+b' so that it can be > >read and written without closing and reopening. > > > >But, for the life of me, I can't find any way to rewind it so I can > >read what I wrote. > > > > >>>import tempfile > >>>import os > >>>fd, name = tempfile.mkstemp() > >>>os.write(fd, 'foo') > 3 > >>>os.lseek(fd, 0, 0) > 0L > >>>os.read(fd, 10) > 'foo' > > > >tempfile.mkstemp gives me the file descriptor. Is there a way to make > >a file object from a file descriptor? > > > > Not that I can see: > http://docs.python.org/lib/os-fd-ops.html > > ... except maybe this, which is not quite the same: > > >>>import tempfile > >>>import os > >>>fd, name = tempfile.mkstemp() > >>>os.write(fd, 'foo') > 3 > >>>f = open(name) > >>>f.read() > 'foo' > > _________________________________________________________________ > Express yourself instantly with MSN Messenger! Download today it's FREE! > http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From marilyn at deliberate.com Fri Dec 24 00:12:15 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Fri Dec 24 00:12:22 2004 Subject: [Tutor] Re: tempfile (fwd) Message-ID: And again. ---------- Forwarded message ---------- Date: Thu, 23 Dec 2004 14:55:15 -0800 (PST) From: Marilyn Davis To: Lee Harr Subject: Re: [Tutor] Re: tempfile os.lseek! How did I not find that. Thank you. I'm set. Marilyn On Fri, 24 Dec 2004, Lee Harr wrote: > >I'm using tempfile. The doc says it is opened 'w+b' so that it can be > >read and written without closing and reopening. > > > >But, for the life of me, I can't find any way to rewind it so I can > >read what I wrote. > > > > >>>import tempfile > >>>import os > >>>fd, name = tempfile.mkstemp() > >>>os.write(fd, 'foo') > 3 > >>>os.lseek(fd, 0, 0) > 0L > >>>os.read(fd, 10) > 'foo' > > > > >tempfile.mkstemp gives me the file descriptor. Is there a way to make > >a file object from a file descriptor? > > > > Not that I can see: > http://docs.python.org/lib/os-fd-ops.html > > ... except maybe this, which is not quite the same: > > >>>import tempfile > >>>import os > >>>fd, name = tempfile.mkstemp() > >>>os.write(fd, 'foo') > 3 > >>>f = open(name) > >>>f.read() > 'foo' > > _________________________________________________________________ > Express yourself instantly with MSN Messenger! Download today it's FREE! > http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- From isrgish at fastem.com Fri Dec 24 01:01:00 2004 From: isrgish at fastem.com (Isr Gish) Date: Fri Dec 24 01:01:11 2004 Subject: [Tutor] What am I doing wrong... Message-ID: <20041224000109.9F5C01E4006@bag.python.org> John Purser wrote: [snip] >I'm not sure if this is your code or my mail agent (outlook) but as you can >see below there's a space between the function name (main) and the >parenthesis. I don't believe that's supposed to be there. I don't think there is any problem with adding space before the parenthesis. All the best, Isr > >Good Luck. > >John Purser > > >#!/usr/bin/env python > >def main (): > play_test() > >def play_test (): > print "Hi! -- in play test" > From alan.gauld at freenet.co.uk Fri Dec 24 09:08:04 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Dec 24 09:07:36 2004 Subject: [Tutor] tempfile (fwd) References: Message-ID: <00c601c4e98f$b25a1620$b3b88651@xp> > gets an OSError: [Errno 9] Bad File Descriptor > > on os.read(tmp_fp,10) > > I'm thinking that, if I don't keep a reference to the file object, > it gets automatically closed. > > How pythonic. Yes it is. After all that's how garbage collection works for all objects in Python, when nothing is using it, it gets deleted. But on a general note it's usually a bad idea to mix file descriptor and file object references to the same file at the same time. Things can get very confused at the OS level! Most things(everything?) you want to do with a file object can be done with a descriptor, albeit with a little more effort. Someone already showed you the lseek() function which saves you doing the conversion, I'd recommend keeping things in one format or the other. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From kent37 at tds.net Fri Dec 24 15:21:09 2004 From: kent37 at tds.net (Kent Johnson) Date: Fri Dec 24 15:21:17 2004 Subject: [Tutor] tempfile In-Reply-To: References: Message-ID: <41CC25D5.2040900@tds.net> Marilyn Davis wrote: > Hello Python Tutors, > > I'm using tempfile. The doc says it is opened 'w+b' so that it can be > read and written without closing and reopening. > > But, for the life of me, I can't find any way to rewind it so I can > read what I wrote. > > tempfile.mkstemp gives me the file descriptor. Is there a way to make > a file object from a file descriptor? Hmm, let's take a look at the docs. tempfile.TemporaryFile() gives you a file object. Can you use that? Maybe you are using mkstemp() because you want the file to persist after it is closed? Ok, the docs say TemporaryFile() uses mkstemp() to create its file. So how does it get a file object? Is the soure available? Sure, in Python24\Lid\tempfile.py. It uses os.fdopen() to convert a file descriptor to a file object. Will that work for you? Kent > > Or, is there something in os or fcntl that allows me to rewind from a > file descriptor? > > Thank you for any help you can give. > > Marilyn Davis > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From jasonchild at cnsp.com Fri Dec 24 17:53:00 2004 From: jasonchild at cnsp.com (Jason Child) Date: Fri Dec 24 18:16:35 2004 Subject: [Tutor] happy holidays! Message-ID: <41CC496C.7040907@cnsp.com> Just wanted to extend warm feelings to all the list members! Have a safe and happy season. -- Jason Christopher Child Computer Network Service Professionals VOZ Online From python.programming at gmail.com Fri Dec 24 18:35:42 2004 From: python.programming at gmail.com (python programming) Date: Fri Dec 24 18:35:49 2004 Subject: [Tutor] happy holidays! In-Reply-To: <41CC496C.7040907@cnsp.com> References: <41CC496C.7040907@cnsp.com> Message-ID: I am new to the list and wanted to wish everyone happy holidays. On Fri, 24 Dec 2004 09:53:00 -0700, Jason Child wrote: > Just wanted to extend warm feelings to all the list members! Have a safe > and happy season. > > -- > Jason Christopher Child > > Computer Network Service Professionals > VOZ Online > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From marilyn at deliberate.com Fri Dec 24 19:18:24 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Fri Dec 24 19:18:33 2004 Subject: [Tutor] tempfile In-Reply-To: <41CC25D5.2040900@tds.net> Message-ID: On Fri, 24 Dec 2004, Kent Johnson wrote: > Marilyn Davis wrote: > > Hello Python Tutors, > > > > I'm using tempfile. The doc says it is opened 'w+b' so that it can be > > read and written without closing and reopening. > > > > But, for the life of me, I can't find any way to rewind it so I can > > read what I wrote. > > > > tempfile.mkstemp gives me the file descriptor. Is there a way to make > > a file object from a file descriptor? > > Hmm, let's take a look at the docs. > tempfile.TemporaryFile() gives you a file object. Can you use that? Maybe you are using mkstemp() > because you want the file to persist after it is closed? Right. > > Ok, the docs say TemporaryFile() uses mkstemp() to create its file. So how does it get a file > object? Is the soure available? Sure, in Python24\Lid\tempfile.py. It uses os.fdopen() to convert a > file descriptor to a file object. Will that work for you? Looking at the source was a good idea. I'll try to remember that next time I'm stuck. Thank you. Marilyn > > Kent > > > > > Or, is there something in os or fcntl that allows me to rewind from a > > file descriptor? > > > > Thank you for any help you can give. > > > > Marilyn Davis > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- From bgailer at alum.rpi.edu Fri Dec 24 19:32:11 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Fri Dec 24 19:30:21 2004 Subject: [Tutor] happy holidays! In-Reply-To: References: <41CC496C.7040907@cnsp.com> Message-ID: <6.1.2.0.0.20041224112407.0362c340@mail.mric.net> My holiday (and everyday) wish is that we be in touch with our deepest needs (love, contribution, autonomy, creativity, recognition, etc). That we notice in what ways our holiday customs, habits, behaviors meet or fail to meet these needs. That we communicate our needs honestly to those in our lives and ask them the questions above. It might be that we discover that parties, gifts, cooking, decorating, spending, etc. doesn't meet anyone's deepest needs. It might be that open honest communication will go much further to satisfying our needs. Invite your friends and loved ones to debrief the holidays in this light and to create next year's in a way that is more satisfying, Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From israel at uandmedance.com Fri Dec 24 19:42:18 2004 From: israel at uandmedance.com (Israel C. Evans) Date: Fri Dec 24 19:42:26 2004 Subject: [Tutor] happy holidays! In-Reply-To: <6.1.2.0.0.20041224112407.0362c340@mail.mric.net> References: <41CC496C.7040907@cnsp.com> <6.1.2.0.0.20041224112407.0362c340@mail.mric.net> Message-ID: <41CC630A.3060308@uandmedance.com> 100 foot tall mashed potato sculptures representing the common roots to all belief systems is my holiday wish. That, and a really neat spaceship. Seriously though, I think the best part about "happy holidays" is the Happy. Spread Happy wherever you go. Make it the great plague of the new age. But plaguey in a... good way. Not the bad, everybody is afraid of it and dies from it sort of way.. that's not happy... not really. amusing in monty python flics, but not in real life.. no. ~Israel~ ps.. I'm all for honest communication too.. That kicks patooti! Bob Gailer wrote: > My holiday (and everyday) wish is that we be in touch with our deepest > needs (love, contribution, autonomy, creativity, recognition, etc). > > That we notice in what ways our holiday customs, habits, behaviors > meet or fail to meet these needs. > > That we communicate our needs honestly to those in our lives and ask > them the questions above. > > It might be that we discover that parties, gifts, cooking, decorating, > spending, etc. doesn't meet anyone's deepest needs. > > It might be that open honest communication will go much further to > satisfying our needs. > > Invite your friends and loved ones to debrief the holidays in this > light and to create next year's in a way that is more satisfying, > > Bob Gailer > bgailer@alum.rpi.edu > 303 442 2625 home > 720 938 2625 cell > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > > From johnp at milwaukielumber.com Fri Dec 24 20:01:13 2004 From: johnp at milwaukielumber.com (John Purser) Date: Fri Dec 24 20:02:04 2004 Subject: [Tutor] happy holidays! In-Reply-To: <41CC630A.3060308@uandmedance.com> Message-ID: <200412241901.iBOJ1D7s000377@mail.morseintranet.com> I'm in on the Spaceship but off potatoes because of the carbs. And can we modify that to "reasonable honest communication" please? "No, you're not fat", "This is delicious", "No, I don't think you're mother is insane." all have their rightful place in a peaceful community! And I got my Christmas wish when UPS delivered my very own RS/6000! Happiness is being root on your very own 'nix box! Merry Solstice Season everybody! John Purser -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of Israel C. Evans Sent: Friday, December 24, 2004 10:42 To: Bob Gailer Cc: tutor@python.org Subject: Re: [Tutor] happy holidays! 100 foot tall mashed potato sculptures representing the common roots to all belief systems is my holiday wish. That, and a really neat spaceship. Seriously though, I think the best part about "happy holidays" is the Happy. Spread Happy wherever you go. Make it the great plague of the new age. But plaguey in a... good way. Not the bad, everybody is afraid of it and dies from it sort of way.. that's not happy... not really. amusing in monty python flics, but not in real life.. no. ~Israel~ ps.. I'm all for honest communication too.. That kicks patooti! Bob Gailer wrote: > My holiday (and everyday) wish is that we be in touch with our deepest > needs (love, contribution, autonomy, creativity, recognition, etc). > > That we notice in what ways our holiday customs, habits, behaviors > meet or fail to meet these needs. > > That we communicate our needs honestly to those in our lives and ask > them the questions above. > > It might be that we discover that parties, gifts, cooking, decorating, > spending, etc. doesn't meet anyone's deepest needs. > > It might be that open honest communication will go much further to > satisfying our needs. > > Invite your friends and loved ones to debrief the holidays in this > light and to create next year's in a way that is more satisfying, > > Bob Gailer > bgailer@alum.rpi.edu > 303 442 2625 home > 720 938 2625 cell > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > > _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From jasonchild at cnsp.com Fri Dec 24 20:10:51 2004 From: jasonchild at cnsp.com (Jason Child) Date: Fri Dec 24 20:10:57 2004 Subject: [Tutor] happy holidays! In-Reply-To: <200412241901.iBOJ1D7s000377@mail.morseintranet.com> References: <200412241901.iBOJ1D7s000377@mail.morseintranet.com> Message-ID: <41CC69BB.2030209@cnsp.com> John Purser wrote: >And I got my Christmas wish when UPS delivered my very own RS/6000! >Happiness is being root on your very own 'nix box! > > > No, happiness is being root on someone else's *nix box *grin*. -- Jason Christopher Child Computer Network Service Professionals VOZ Online From pythontut at pusspaws.net Fri Dec 24 21:19:47 2004 From: pythontut at pusspaws.net (Dave S) Date: Fri Dec 24 21:19:58 2004 Subject: [Tutor] Marry Xmas + httplib.py problem :) Message-ID: <41CC79E3.6080108@pusspaws.net> First, merry Xmas everyone, wishing you all well, :-) While my head is still clear ;-) , I have an unexpected problem. One of my apps which tracks a ftse website all day has suddenly popped up with an exception & exited somewhat ungraciously. This is the second time this has occured (512KB Broadband) bash-2.05b$ ./live_datad.py Traceback (most recent call last): File "./live_datad.py", line 196, in ? live_datad() File "./live_datad.py", line 189, in live_datad ftse_day() File "./live_datad.py", line 142, in ftse_day new_data=html_strip(load_webpage()) File "./live_datad.py", line 33, in load_webpage url_data=urlopen(HTML_addr) File "/usr/lib/python2.3/urllib.py", line 76, in urlopen return opener.open(url) File "/usr/lib/python2.3/urllib.py", line 181, in open return getattr(self, name)(url) File "/usr/lib/python2.3/urllib.py", line 297, in open_http h.endheaders() File "/usr/lib/python2.3/httplib.py", line 712, in endheaders self._send_output() File "/usr/lib/python2.3/httplib.py", line 597, in _send_output self.send(msg) File "/usr/lib/python2.3/httplib.py", line 564, in send self.connect() File "/usr/lib/python2.3/httplib.py", line 532, in connect socket.SOCK_STREAM): IOError: [Errno socket error] (-3, 'Temporary failure in name resolution') bash-2.05b$ Is this is a DNS problem, if so its very strange since my app has downloaded approx 60 web pages from this location today just before the exception occured ?, or maybe something else ? Should I check for this exception when I ... new_data=html_strip(load_webpage()) & if it occures, try again ? Any comments gratefully recieved. Cheers (Hik!) Dave From ewe2 at aardvark.net.au Fri Dec 24 22:57:54 2004 From: ewe2 at aardvark.net.au (sean dwyer) Date: Fri Dec 24 22:58:09 2004 Subject: [Tutor] happy holidays! In-Reply-To: <200412241901.iBOJ1D7s000377@mail.morseintranet.com> References: <41CC630A.3060308@uandmedance.com> <200412241901.iBOJ1D7s000377@mail.morseintranet.com> Message-ID: <20041224215754.GN4183@aardvark.net.au> On Fri, Dec 24, 2004 at 11:01:13AM -0800, John Purser wrote: > And I got my Christmas wish when UPS delivered my very own RS/6000! > Happiness is being root on your very own 'nix box! I've been lurking so long I almost forgot I could email, but I HAVE to ask, what the santa do you need an RS/6000 for?! The biggest python script ever??! The couriers won't let me have MY pressies till next week, bah humbug. > Merry Solstice Season everybody! Ho ho ho! -- Ancient C64 curses #201: A HEX on 53294! From jmpurser at gmail.com Sat Dec 25 01:52:31 2004 From: jmpurser at gmail.com (John Purser) Date: Sat Dec 25 01:51:53 2004 Subject: [Tutor] happy holidays! In-Reply-To: <20041224215754.GN4183@aardvark.net.au> References: <41CC630A.3060308@uandmedance.com> <200412241901.iBOJ1D7s000377@mail.morseintranet.com> <20041224215754.GN4183@aardvark.net.au> Message-ID: <41CCB9CF.8030000@gmail.com> sean dwyer wrote: >On Fri, Dec 24, 2004 at 11:01:13AM -0800, John Purser wrote: > > > >>And I got my Christmas wish when UPS delivered my very own RS/6000! >>Happiness is being root on your very own 'nix box! >> >> > >I've been lurking so long I almost forgot I could email, but I HAVE to ask, >what the santa do you need an RS/6000 for?! The biggest python script ever??! > >The couriers won't let me have MY pressies till next week, bah humbug. > > > >>Merry Solstice Season everybody! >> >> > >Ho ho ho! > > > Working on my AIX certification so I picked up a cheap RS/6000 of ebay. Amazing what you can find there! From carroll at tjc.com Sat Dec 25 03:06:33 2004 From: carroll at tjc.com (Terry Carroll) Date: Sat Dec 25 03:06:36 2004 Subject: [Tutor] Sample Tkinter data entry screen? Message-ID: I haven't played with Tkinter in months, and always find it a frustrating experience (GUI stuff is non-intuitive to me). Taking the lazy way out, can anyone point me to a simple sample app that just puts up a data entry screen with a small (4 or 5) number of simple text-entry fields and lets me pull in variables from those fields? From harm.kirchhoff at web.de Sat Dec 25 13:43:15 2004 From: harm.kirchhoff at web.de (Harm Kirchhoff) Date: Sat Dec 25 13:48:24 2004 Subject: [Tutor] Sample Tkinter data entry screen? Message-ID: <41CD6063.10804@web.de> Hi Carrol, What really helped me get going were the Tk inter chapters in 'Programming Python' by Mark Lutz. Now I am producing Tk inter scripts very often and it is relatively simple, but it took some time to get used to it. Hope the following helps: # Example just for Carrol from Tkinter import * class gui: def __init__(self, root): """Implements the graphical surface.""" self.root = root self.dir = [] # Frame to contain the fields f = Frame(root) ; f.pack(side=TOP, fill=X) # Text field for entry: self.t1 = Text(f, width=20, height=1) self.t1.pack(side=TOP,expand=YES,fill=X) self.t2 = Text(f, width=20, height=1) self.t2.pack(side=TOP,expand=YES,fill=X) # Button self.button = Button(root, text = 'Show me input', command = self.show_it ) self.button.pack(side=TOP) return def show_it(self): # get whatever was entered and put it onto the screen print 't1:',self.t1.get('0.0',END) print 't2:',self.t2.get('0.0',END) self.root.destroy() self.root.quit() return if __name__ == '__main__': # If run as stand alone ... root = Tk() gui( root ) mainloop() -- Kind Regards, Harm KIRCHHOFF Private: Tel. +81-72-297 -2536 Mob. +81-70-5653-8220 Eml: hk@web.de From aztech1200 at yahoo.com Sat Dec 25 16:51:09 2004 From: aztech1200 at yahoo.com (Aztech Guy) Date: Sat Dec 25 16:51:11 2004 Subject: [Tutor] A better way to do it. In-Reply-To: <000501c4e6c8$d663f820$425428cf@JSLAPTOP> Message-ID: <20041225155109.42087.qmail@web53308.mail.yahoo.com> Hi Jacob, Since your class derives from Frame, check Frame for methods to change the title. If that doesn't work, try this: Tkinter is based on Tk (which works with TCL). So try posting your question on comp.lang.tcl. You can do this via Google Groups: groups.google.com. You need to register once, its free. HTH Az --- "Jacob S." wrote: > Okay, here's the code. > > I am completely open to suggestions as this is my > first dabbling in Tk. > Please look over it when you have time. > > I have a couple of questions. > 1) How do I change the title of the window? > 2) Why does a window pop up saying something like > error, the memory could > not be "read". I'm running > Windows XP, the script window disappears, and > everything, just this message > pops up. > > > Jacob Schmidt > > ---------------------------------------------------------------------------- > - > from Tkinter import * > import tkMessageBox > import os > from filecmp import cmpfiles > > class Copying: > def __init__(self,action,var,err): > self.action = action > self.pri = var > self.err = err > > self.j = os.path.join > self.r = os.path.isdir > self.e = os.path.isfile > > > #################################################################### > # These are the default values for the > directories. To make it > simpler you could... ## > ## pseudo > ## self.usbdrive = remote folder > ## self.desktop = localer folder > > #################################################################### > dirlist = os.listdir("c:\\") > if 'Jacob Laptop' in dirlist: > self.usbdrive = 'E:\\Working Python > Programs' > self.desktop = 'C:\\documents and > settings\\jacob\\desktop\\Working Python Programs' > elif 'Home Computer' in dirlist: > self.usbdrive = 'F:\\Working Python > Programs' > self.desktop = 'C:\\documents and > settings\\owner\\desktop\\Working Python Programs' > elif 'Sissy Computer' in dirlist: > self.usbdrive = '' ## Need to fill in > self.desktop = '' ## Need to fill in > elif 'Michael Laptop' in dirlist: > self.usbdrive = 'E:\\Working Python > Programs' > self.desktop = 'C:\\documents and > settings\\michael\\desktop\\Working Python Programs' > elif 'Office Computer' in dirlist: > self.usbdrive = 'D:\\Working Python > Programs' > self.desktop = > 'C:\\windows\\desktop\\Working Python Programs' > elif 'School Auction Laptop' in dirlist: > self.usbdrive = '' ## Need to fill in > self.desktop = > 'C:\\windows\\desktop\\Working Python Programs' > else: > print 'Hey you need to put a folder in > this computer!. ' > print '''Folders include: > Jacob Laptop > Home Computer > Sissy Computer > Michael Laptop > Office Computer > School Auction Laptop > ''' > folder = raw_input('Which computer is > this? ') > folder = "C:\\"+folder > os.mkdir(folder) > self.usbdrive = raw_input('What is the > usb drive on this > computer? ') > self.desktop = raw_input('What is the > desktop on this computer? > ') > > # > ################################################# # > if not os.path.exists(self.desktop): > os.mkdir(self.desktop) > m = > {'receiving':self.receiving,'sending':self.sending} > m[self.action]() > > > def copyfile(self,src,des): > x = open(src,'rb').read() > y = open(des,'wb') > y.write(x) > y.close() > > > def receiving(self): > chiplist = os.listdir(self.usbdrive) > pclist = os.listdir(self.desktop) > filechange = > cmpfiles(self.usbdrive,self.desktop,chiplist)[1] > tot = 0 > for x in chiplist: > if x not in pclist: > filechange.append(x) > for x in filechange: > fullname = self.j(self.usbdrive,x) > if self.e(fullname): > > self.copyfile(fullname,self.j(self.desktop, x)) > self.pri.set("Copying %s." % x) > self.err.insert(END,"%s copied from > chip to computer.\n" % > x) > tot = tot + 1 > elif self.r(fullname): > self.err.insert(END,"%s is a > directory. It has not been > copied.\n" % fullname) > self.err.insert(END,"%s file(s) > copied.\n"%tot) > self.pri.set("") > pclist.sort() > chiplist.sort() > newlist = [x for x in pclist if x not in > chiplist] > for x in newlist: > if > tkMessageBox.askokcancel('Delete?',"Do you wish to > delete %s? > " % x): > filename = self.j(self.desktop, x) > if self.e(filename): > os.remove(filename) > self.err.insert(END,"%s has been > removed from your > chip.\n"%x) > elif self.r(filename): > os.rmdir(filename) > self.err.insert(END,"%s has been > removed from your > chip.\n"%x) > else: > self.err.insert(END,"Did not remove > %s\n"%x) > > def sending(self): > pclist = os.listdir(self.desktop) > chiplist = os.listdir(self.usbdrive) > filechange = > cmpfiles(self.desktop,self.usbdrive,pclist)[1] > tot = 0 > for x in pclist: > if x not in chiplist: > filechange.append(x) > for x in filechange: > fullname = self.j(self.desktop,x) > if self.e(fullname): > > self.copyfile(fullname,self.j(self.usbdrive,x)) > self.pri.set("Copying %s. " % x) > self.err.insert(END,"%s copied from > computer to chip.\n" % > x) > tot = tot + 1 > elif self.r(fullname): > self.err.insert(END,"%s is a > directory. It has not been > copied.\n" % x) > self.err.insert(END,"%s file(s) > copied.\n"%tot) > self.pri.set("") > chiplist.sort() > pclist.sort() > newlist = [x for x in chiplist if x not in > pclist] > for x in newlist: > if > tkMessageBox.askokcancel('Delete?',"Do you wish to > delete %s? > " % x): > filename = self.j(self.usbdrive, x) > if self.e(filename): > os.remove(filename) > self.err.insert(END,"%s has been > removed from your > === message truncated === __________________________________ Do you Yahoo!? Yahoo! Mail - now with 250MB free storage. Learn more. http://info.mail.yahoo.com/mail_250 From hugonz-lists at h-lab.net Sat Dec 25 19:14:57 2004 From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Sat Dec 25 19:15:20 2004 Subject: [Tutor] A better way to do it. In-Reply-To: <000501c4e6c8$d663f820$425428cf@JSLAPTOP> References: <000501c4e6c8$d663f820$425428cf@JSLAPTOP> Message-ID: <41CDAE21.5040303@h-lab.net> The title can be changed with a method of the root window. >>> help (Tkinter.Tk.wm_title) Help on method wm_title in module Tkinter: wm_title(self, string=None) unbound Tkinter.Tk method Set the title of this widget. so you can do: mainwin.wm_title("Mytitle") Jacob S. wrote: > Okay, here's the code. > > I am completely open to suggestions as this is my first dabbling in Tk. > Please look over it when you have time. > > I have a couple of questions. > 1) How do I change the title of the window? > 2) Why does a window pop up saying something like error, the memory could > not be "read". I'm running > Windows XP, the script window disappears, and everything, just this message > pops up. > > > Jacob Schmidt From carroll at tjc.com Sat Dec 25 20:53:35 2004 From: carroll at tjc.com (Terry Carroll) Date: Sat Dec 25 20:53:37 2004 Subject: [Tutor] Sample Tkinter data entry screen? In-Reply-To: <41CD6063.10804@web.de> Message-ID: Thanks, Harm. On Sat, 25 Dec 2004, Harm Kirchhoff wrote: > What really helped me get going were the Tk inter chapters in > 'Programming Python' by Mark Lutz. I'll take a closer look at it. I don't find this book very helpful, because it assumes you've been following all the previous parts of the book, so, for example, when you open to the Tk section, if you haven't been following all the "packer" stuff in the previous chapters, it's hard to tell what's got to do with Tk and what's got to do with the other stuff. > Hope the following helps: [snip] Thanks, I'll give this a try and use it as a base. I really appreciate it. Merry Christmas! Terry From alan.gauld at freenet.co.uk Sat Dec 25 21:12:54 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sat Dec 25 21:12:56 2004 Subject: [Tutor] Sample Tkinter data entry screen? References: Message-ID: <010a01c4eabe$1eedc000$b3b88651@xp> > Taking the lazy way out, can anyone point me to a simple sample app that > just puts up a data entry screen with a small (4 or 5) number of simple > text-entry fields and lets me pull in variables from those fields? The case study in my tutor shows a text entry and set of radio buttons and a Text field for outbut, along with some buttons. Is that enough? The only caveat is that I don't use the Tcl magic which auto binds a text field to a variable, I prefer to hard code it in the tutor to demonstrate the lowest common denominator. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From carroll at tjc.com Sat Dec 25 21:35:14 2004 From: carroll at tjc.com (Terry Carroll) Date: Sat Dec 25 21:35:16 2004 Subject: [Tutor] Sample Tkinter data entry screen? In-Reply-To: <010a01c4eabe$1eedc000$b3b88651@xp> Message-ID: On Sat, 25 Dec 2004, Alan Gauld wrote: > The case study in my tutor shows a text entry and set of radio buttons > and a Text field for outbut, along with some buttons. Is that enough? I'll have a look at it (printing a copy now); I expect it will be very helpful. Thanks, Alan. From alan.gauld at freenet.co.uk Sun Dec 26 15:53:09 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Sun Dec 26 15:52:52 2004 Subject: [Tutor] A better way to do it. References: <20041225155109.42087.qmail@web53308.mail.yahoo.com> Message-ID: <012401c4eb5a$9e0d9210$b3b88651@xp> > --- "Jacob S." wrote: > > I have a couple of questions. > > 1) How do I change the title of the window? My tutors case study shows this, the critical but of code is here: class GrammarApp(Frame): def __init__(self, parent=0): Frame.__init__(self,parent) self.type = 2 # create variable with default value self.master.title('Grammar counter') self.buildUI()Note the second last line.HTH,Alan GAuthor of the Learn to Program web tutorhttp://www.freenetpages.co.uk/hp/alan.gauld From mark.kels at gmail.com Sun Dec 26 16:42:42 2004 From: mark.kels at gmail.com (Mark Kels) Date: Sun Dec 26 16:42:45 2004 Subject: [Tutor] Environment Variables On Windows Message-ID: Hello to all :-) I'm writing a CGI script (one of my first ever CGI programs and I'm using this tutor to learn CGI: http://www.oreilly.com/openbook/cgi/ This isn't a python tutor, but the introductions says that any language will be good for this tutor. Anyway, I got to the Using Environment Variables chapter that is in this page: http://www.oreilly.com/openbook/cgi/ch02_02.html. This is UNIX environment variables (as I understand), and I guess they will not work on Windows... So what are the Windows environment variables and how can I use them with python (like any other variable or in a special way?) ? Thanks! -- 1. The day Microsoft makes something that doesn't suck is probably the day they start making vacuum cleaners. 2. Unix is user friendly - it's just picky about it's friends. 3. Documentation is like sex: when it is good, it is very, very good. And when it is bad, it is better than nothing. - Dick Brandon From tegmine at gmail.com Sun Dec 26 18:56:01 2004 From: tegmine at gmail.com (Luis N) Date: Sun Dec 26 18:56:05 2004 Subject: [Tutor] Comments appreciated In-Reply-To: <41C8D68A.9020906@ccvcorp.com> References: <77bfa81a04122117067ab205b@mail.gmail.com> <41C8D68A.9020906@ccvcorp.com> Message-ID: <77bfa81a04122609561edfa3e7@mail.gmail.com> Hi, Jeff Shanon, thanks for your help. I was wondering if there was a function to automatically get the user on a *nix system, and had tried the if __name__ == __main__ but didn't really get it until your example. The only thing I'm not clear about is how 'trashcan' can be a local variable inside main() when it's required by both trash() and can() The only thing that's missing is that this script can't handle paths like ~/dir/junkthis Would a regular expression be the best way of finding the last / followed by some text to be able to chdir to junk files from another location? #!/usr/local/bin/python import os.path from os import mkdir, remove from sys import argv from shutil import rmtree trashcan = os.path.expanduser("~/.trashcan") def main(junk): empty = False if "-e" in junk: empty = True junk.remove("-e") if not os.path.exists(trashcan): os.mkdir(trashcan) if len(junk) > 0: trash(junk) if empty: can() def trash(junk): for i in junk: toss = trashcan + "/" + i if os.path.exists(toss): if os.path.isdir(toss): rmtree(toss) if os.path.isfile(toss): os.remove(toss) os.rename(i, toss) def can(): for j in os.listdir(trashcan): toss = trashcan + "/" + j if os.path.isdir(toss): rmtree(toss) if os.path.isfile(toss): os.remove(toss) if __name__ == '__main__': main(argv[1:]) From jmpurser at gmail.com Sun Dec 26 18:56:51 2004 From: jmpurser at gmail.com (John Purser) Date: Sun Dec 26 18:56:19 2004 Subject: [Tutor] Environment Variables On Windows In-Reply-To: References: Message-ID: <41CEFB63.4060006@gmail.com> Mark Kels wrote: >Hello to all :-) > >I'm writing a CGI script (one of my first ever CGI programs and I'm >using this tutor to learn CGI: http://www.oreilly.com/openbook/cgi/ >This isn't a python tutor, but the introductions says that any >language will be good for this tutor. >Anyway, I got to the Using Environment Variables chapter that is in >this page: http://www.oreilly.com/openbook/cgi/ch02_02.html. >This is UNIX environment variables (as I understand), and I guess they >will not work on Windows... >So what are the Windows environment variables and how can I use them >with python (like any other variable or in a special way?) ? > >Thanks! > > > Morning Mark, Happy New Year, Merry Christmas, and a jolly Winter Solstice Season! Whenever you're talking about how to do something in Windows it REALLY helps when you include WHICH windows you're working with. I believe the following will allow you to manipulate windows environmental variables. If anyone sees I'm wrong I know they'll speak up. The "set" command when run in a command window without parameters lists your current environmental variables. You can also use it as: c:\> set hello=Hi there Mark which will set the variable "HELLO" to "Hi there Mark". c:\> echo %HELLO% or c:\> echo %hello% will now print "Hi there Mark" without the quotes. Note that quoting, case sensitivity, and white spaces can all react differently under windows than they do in Python. If you need to set an environmental variable to a value every time you start windows then you can either store the above set command (no spaces around that "=" remember) in the autoexec.bat file or on Windows 2000, XP and (I believe) NT you can right click on the desktop icon "My Computer" and select "Properties". Now you're looking for the "Advanced" tab and the environmental variables button in Windows 2000. I THINK it's under the "System Performance" tab and advanced button in XP and you'll have to dig in NT. I'm not sure you can do this here under the win 95/98/ME family. Sorry, right now the only windows product I'm running at home is 2000. You can also set Windows environmental variables from within your python script of course. FYI being a coward myself before I go changing my setup I like to document things. Say running "set > Environment-Before.txt" in a nice safe directory. This will output your current setup so if things get weird you can at least bring things back to you starting point. Have a good one, John Purser From marilyn at deliberate.com Sun Dec 26 20:54:10 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Sun Dec 26 20:54:26 2004 Subject: [Tutor] Debugging in emacs In-Reply-To: <211F78EFD1D870409CC3E4158F4881DA08B32E27@xcww01.riv.csu.edu.au> Message-ID: Hi Toby, You still here? I'm finally trying (again) to get debugging going. On Mon, 22 Nov 2004, McLaughlin, Toby wrote: > Thanks Marilyn, > > Debugging in emacs is obviously not the hottest topic around here. > > Luckily, I have something working now. For anyone who is interested, > here is the trick: > > 1. Add the following to your program: > import pdb > pdb.set_trace() > 2. Start an interactive Python buffer (C-c !) This doesn't seem to do anything. But, when I run my program, after following step 1., I'm in the debugger. And it is a beautiful sight. > 3. Run your program (I use C-c C-c) > > Emacs picks up the line numbers from set_trace() and marks the > appropriate line in the source buffer. You can now type 'n' to single > step, as well as issue any of the pdb commands mentioned here: > http://tinyurl.com/3na4u . If I set a breakpoint, then 'c'/'continue' doesn't work. Instead of continuing, it only goes one step. If I don't set a breakpoint, then continue does work. But that's no use. > > The only trouble I have now is that the Python buffer and my source code > keep switching places from top to bottom. A minor annoyance that > hopefully I will rectify soon. This doesn't happen to me. I am using regular ole raw emacs, on a plain terminal, no X. Are you? How are you doing with this? I could sure use a debugger. Marilyn > > Toby McLaughlin. > > > -----Original Message----- > > From: Marilyn Davis [mailto:marilyn@deliberate.com] > > Sent: Saturday, 20 November 2004 9:28 AM > > To: McLaughlin, Toby > > Cc: tutor@python.org > > Subject: Re: [Tutor] Debugging in emacs > > > > > > On Fri, 19 Nov 2004, McLaughlin, Toby wrote: > > > > > Hi All, > > > > > > Could somebody suggest a way to debug python in emacs? I'd > > like to be > > > able to single-step while seeing the code marked in some way and > > > possiblly set breakpoints. I read about using pdb from the > > command line > > > but would love to have debugging integrated in emacs. > > Perhaps I should > > > make life easy for myself and use one of the fancy GUI > > editors, but I > > > think it's character building for me to learn emacs. > > > > Boy, you could hear a pin drop on this topic. > > > > I use emacs, even though I have spent some time with idle, because I > > like it much better. I'm real handy in emacs though, and I don't like > > mousing. Mice cause lots of repetitive stress injury. > > > > I spent some time and some email conversations trying to make use of > > the debugger in any environment. I don't remember what happened > > exactly but I gave up. > > > > The thing about an interpreted language is that you can say "print > > my_var" in the code instead of in the debugger. And with emacs, I go > > back and forth between my code and the emacs shell to run it. I'm > > pretty efficient that way. > > > > If anyone has any suggestions about debugging, in idle or anywhere, I > > too would love to hear them. > > > > Thank you. > > > > Marilyn Davis > > > > > > > > > > Thanks, > > > Toby McLaughlin. > > > _______________________________________________ > > > Tutor maillist - Tutor@python.org > > > http://mail.python.org/mailman/listinfo/tutor > > > > > > > -- > > > > > -- From mark.kels at gmail.com Sun Dec 26 20:57:58 2004 From: mark.kels at gmail.com (Mark Kels) Date: Sun Dec 26 20:58:01 2004 Subject: [Tutor] Environment Variables On Windows In-Reply-To: <41CEFB63.4060006@gmail.com> References: <41CEFB63.4060006@gmail.com> Message-ID: > Morning Mark, > > Happy New Year, Merry Christmas, and a jolly Winter Solstice Season! > > Whenever you're talking about how to do something in Windows it REALLY > helps when you include WHICH windows you're working with. > > I believe the following will allow you to manipulate windows > environmental variables. If anyone sees I'm wrong I know they'll speak > up. The "set" command when run in a command window without parameters > lists your current environmental variables. You can also use it as: > c:\> set hello=Hi there Mark > which will set the variable "HELLO" to "Hi there Mark". > c:\> echo %HELLO% or > c:\> echo %hello% > will now print "Hi there Mark" without the quotes. > > Note that quoting, case sensitivity, and white spaces can all react > differently under windows than they do in Python. > > If you need to set an environmental variable to a value every time you > start windows then you can either store the above set command (no spaces > around that "=" remember) in the autoexec.bat file or on Windows 2000, > XP and (I believe) NT you can right click on the desktop icon "My > Computer" and select "Properties". Now you're looking for the > "Advanced" tab and the environmental variables button in Windows 2000. > I THINK it's under the "System Performance" tab and advanced button in > XP and you'll have to dig in NT. I'm not sure you can do this here > under the win 95/98/ME family. Sorry, right now the only windows > product I'm running at home is 2000. > > You can also set Windows environmental variables from within your python > script of course. > > FYI being a coward myself before I go changing my setup I like to > document things. Say running "set > Environment-Before.txt" in a nice > safe directory. This will output your current setup so if things get > weird you can at least bring things back to you starting point. > > Have a good one, > > John Purser > Thanks allot !! But I don't understand how to use the environment variables in the script itself... I tried to do this: import os import cgitb; cgitb.enable() print "Content-type: text/html\n\n" print "Hi there, ",os.system("echo %USERNAME%") But I don't get anything in the browser (500 error - Internal Server Error) and when I run the script in IDLE I get: Hi there, 0 I guess its not the way to print them, but it's the only way I came up with. And I got another question: In my server program I have "User CGI Environment Variables" list that should have pares of Name:Value in it... Whats that? (I guess its the same in all server programs). Thanks! BTW, I'm running Windows XP and Abyss Web Server on my PC. -- 1. The day Microsoft makes something that doesn't suck is probably the day they start making vacuum cleaners. 2. Unix is user friendly - it's just picky about it's friends. 3. Documentation is like sex: when it is good, it is very, very good. And when it is bad, it is better than nothing. - Dick Brandon From jmpurser at gmail.com Sun Dec 26 22:04:42 2004 From: jmpurser at gmail.com (John Purser) Date: Sun Dec 26 22:04:10 2004 Subject: [Tutor] Environment Variables On Windows In-Reply-To: References: <41CEFB63.4060006@gmail.com> Message-ID: <41CF276A.8020106@gmail.com> >script itself... >I tried to do this: > >import os >import cgitb; cgitb.enable() >print "Content-type: text/html\n\n" >print "Hi there, ",os.system("echo %USERNAME%") > >But I don't get anything in the browser (500 error - Internal Server >Error) and when I run the script in IDLE I get: > >Hi there, 0 > >I guess its not the way to print them, but it's the only way I came up with. >And I got another question: >In my server program I have "User CGI Environment Variables" list that >should have pares of Name:Value in it... >Whats that? (I guess its the same in all server programs). > >Thanks! > >BTW, I'm running Windows XP and Abyss Web Server on my PC. > > Mark, What you're seeing there is the exit code of the command "echo %USERNAME%" and not the value in the variable our the output of the command. Try: print "Hi there, ",os.environ["USERNAME"] Sorry, haven't done any CGI stuff with any languages. Can't help you there. John Purser From keridee at jayco.net Mon Dec 27 03:39:04 2004 From: keridee at jayco.net (Jacob S.) Date: Mon Dec 27 03:40:01 2004 Subject: [Tutor] Comments appreciated References: <77bfa81a04122117067ab205b@mail.gmail.com><41C8D68A.9020906@ccvcorp.com> <77bfa81a04122609561edfa3e7@mail.gmail.com> Message-ID: <001f01c4ebbd$5b33e350$d35428cf@JSLAPTOP> > The only thing that's missing is that this script can't handle paths > like ~/dir/junkthis I believe you're looking for os.path.expanduser("~/dir/junkthis") BTW, trashcan IS a module level variable because it's defined at the module level. Why it says it's local is beyond me. HTH, Jacob Schmidt From dyoo at hkn.eecs.berkeley.edu Mon Dec 27 09:25:58 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Dec 27 09:26:05 2004 Subject: [Tutor] Comments appreciated In-Reply-To: <001f01c4ebbd$5b33e350$d35428cf@JSLAPTOP> Message-ID: On Sun, 26 Dec 2004, Jacob S. wrote: > > The only thing that's missing is that this script can't handle paths > > like ~/dir/junkthis > > I believe you're looking for os.path.expanduser("~/dir/junkthis") > > BTW, trashcan IS a module level variable because it's defined at the module > level. Why it says it's local is beyond me. Hi Jacob, Ah, you must be running into the global/local gotcha. This one is notorious. Let's work with a few simplified examples to clear up the situation. For the sake of simplification, my variable names will suck. *grin* Anyway, here's the first example: ### y = 0 def inc(x): y = x + 1 return y ### We know that when we assign to variables in functions, those variables are locally scoped. This is a fairly unique feature in Python: to assign to a variable is the same thing as declaration in the Python language. So in the example above, 'y' in the line: y = x + 1 is a local variable, since it's assigned within the function. And if we play with this in the interactive interpreter, we'll see that calling inc() doesn't touch the value of the module-level 'y' variable. ### >>> y = 0 >>> def inc(x): ... y = x + 1 ... return y ... >>> inc(3) 4 >>> y 0 >>> y = 2 >>> inc(7) 8 >>> y 2 ### Hope that made sense so far: assignment in a function causes the assigned variable to be treated as local to that function. Now let's look at a slightly different example which highlights the problem: ### y = 42 def inc_y(): ## buggy y = y + 1 ### The issue is the one brought up by the first example: assignment causes a variable to be local. But if 'y' is local, then what does: y = y + 1 mean, if 'y' hasn't been assigned to yet? ### >>> y = 42 >>> def inc_y(): ... y = y + 1 ... >>> inc_y() Traceback (most recent call last): File "", line 1, in ? File "", line 2, in inc_y UnboundLocalError: local variable 'y' referenced before assignment ### And this is actually something that could --- and probably should! --- be handled at "definition" time rather than at "run" time. We really shouldn't have to call inc_y() to know that something's already wrong with it. [Advanced: In general, it'd be impossible to do it in full generality, since Python's behavior is so dynamic. As a hideous example: ### y = 42 def degenerate_case(): if some_strange_runtime_condition_was_true(): y = 42 y = y + 1 ### Depending on the definition of some_strange_runtime_condition_was_true(), we'd either die and get a UnboundLocalError, or the function would run to completion. But in this case, I would promptly yell at anyone who would write code like this. *grin*] Anyway, to fix the problem, that is, to be able to write a function that does an assignment to a global, we then have to declare the variable as 'global': ### y = 42 def inc_y_fixed(): global y ## fix for scoping issue y = y + 1 ### so that Python knows up front that 'y' in inc_y_fixed is meant to refer to the module-level 'y'. All of this is a consequence of Python's approach to variable declaration. For the common case, we get to save a lot of lines, since we don't have to write things like var x, y, z int x; at the head of every one of our functions. But, consequently, we do hit this slightly odd and ugly situation when we want to assign to module-level variables. For more information, you may want to look at Tim Peters's nice FAQTS entry on this subject, linked here: http://www.faqts.com/knowledge_base/view.phtml/aid/4722/fid/241 This is also in AMK's "Python Warts" page: http://www.amk.ca/python/writing/warts.html under the header "Local Variable Optimization". If you have more questions, please feel free to ask. Hope this helps! From dyoo at hkn.eecs.berkeley.edu Mon Dec 27 10:00:35 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Dec 27 10:00:39 2004 Subject: [Tutor] Comments appreciated In-Reply-To: Message-ID: [Jacob] > > BTW, trashcan IS a module level variable because it's defined at the > > module level. Why it says it's local is beyond me. [Danny] > Ah, you must be running into the global/local gotcha. [long rambling text cut] Wait, wait. Forget everything I said. *grin* I should have read the question more closely before going crazy with the explanation. I think I screwed up again. Luis, please forgive me for not reading that more closely. Let me read Luis's message again... ok. I think I understand where I got confused. Let's start over. Let me write another rambling post. Let's repeat the conversation, starting from Jeff's response: [Jeff] > Also, even though this is intended to be a quick shell script, it's > not a bad idea to make everything except function defs into a little > main() function, and call it in a script-only section. [Luis] > The only thing I'm not clear about is how 'trashcan' can be a > local variable inside main() when it's required by both trash() and > can() What Jeff is trying to say is that it's possible to pass 'trashcan' around as yet another parameter to both trash() and can(). That is, we can avoid global variables altogether, and just work with parameter passing. As a concrete example, the following program: ### password = "elbereth" def guess(): msg = raw_input("try to guess: ") if msg == password: print "You got it!" else: print "nope" def main(): guess() if __name__ == '__main__': main() ### can be transformed so that it uses no global variables. We can do this by making guess() take in 'password' as a parameter too: ### def guess(password): msg = raw_input("try to guess: ") if msg == password: print "You got it!" else: print "nope" def main(): pword = 'elbereth' guess(pword) if __name__ == '__main__': main() ### No more globals. The password is now explicitely passed between the main() and the guess(). An advantage here is that this guess() function is less tied to outside global resources, and is, in theory, more easily reused. If we wanted to rewrite the program so that we take three different passwords, the version without global variables is easy to write: guess("elbereth") guess("open sesame") guess("42") But the one with the global variable use is something much uglier on our hands: password = "elbereth" guess() password = "open sesame" guess() password = "42" guess() Anyway, sorry about the confusion. I have to read threads more carefully! Best of wishes! From alan.gauld at freenet.co.uk Mon Dec 27 12:02:33 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Dec 27 12:02:07 2004 Subject: [Tutor] Environment Variables On Windows References: Message-ID: <015101c4ec03$91bc72c0$b3b88651@xp> > Anyway, I got to the Using Environment Variables chapter that is in > this page: http://www.oreilly.com/openbook/cgi/ch02_02.html. > This is UNIX environment variables (as I understand), and I guess they > will not work on Windows... They should work on both. THere are some variables that are different but the CGI type ones should be pretty much identical I think. > So what are the Windows environment variables and how can I use them > with python (like any other variable or in a special way?) ? You can see the environment variables currently set on your PC by opening a DOS box and typing SET On NT/W2K/XP you can also find them via the System Properties applet Alan G. From alan.gauld at freenet.co.uk Mon Dec 27 12:07:12 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Dec 27 12:06:45 2004 Subject: [Tutor] Comments appreciated References: <77bfa81a04122117067ab205b@mail.gmail.com><41C8D68A.9020906@ccvcorp.com> <77bfa81a04122609561edfa3e7@mail.gmail.com> Message-ID: <015601c4ec04$37ed2810$b3b88651@xp> > example. The only thing I'm not clear about is how 'trashcan' can be a > local variable inside main() when it's required by both trash() and > can() It's not local. It is a global variable. It is defined outside of any of the functions. > The only thing that's missing is that this script can't handle paths > like ~/dir/junkthis Why not? What is so different between that path and the one in the code below? > Would a regular expression be the best way of finding the last / > followed by some text to be able to chdir to junk files from another > location? No, there are functions for manipulating paths that should be able to do that for you without resrting to regular expressions. And those functions should be platform independant too! > > #!/usr/local/bin/python > > import os.path > from os import mkdir, remove > from sys import argv > from shutil import rmtree > > trashcan = os.path.expanduser("~/.trashcan") This is where trashcan is defined. > > def main(junk): > empty = False > if "-e" in junk: > empty = True > junk.remove("-e") > > if not os.path.exists(trashcan): > os.mkdir(trashcan) THis uses the definition above... > > if len(junk) > 0: > trash(junk) > > if empty: > can() > > def trash(junk): > for i in junk: > toss = trashcan + "/" + i as does this... > if os.path.exists(toss): > if os.path.isdir(toss): > rmtree(toss) > if os.path.isfile(toss): > os.remove(toss) > os.rename(i, toss) > > def can(): > for j in os.listdir(trashcan): and this... > toss = trashcan + "/" + j > if os.path.isdir(toss): > rmtree(toss) > if os.path.isfile(toss): > os.remove(toss) > > if __name__ == '__main__': > main(argv[1:]) > > From alan.gauld at freenet.co.uk Mon Dec 27 12:23:03 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Dec 27 12:22:36 2004 Subject: [Tutor] Debugging in emacs References: Message-ID: <015d01c4ec06$6ece76c0$b3b88651@xp> Marilyn, I seemed to have missed the start of this one, but which debugger are you trying to use? There is plain ole Python pdb, the IDLE debugger and the Pythonwin debugger (and probably more!) The pdb debugger is fashioned on the gdb debugger and works very like that if you've ever sen it before? THe pdb help system works that way too. > > Debugging in emacs is obviously not the hottest topic around here. You should be able to use the standard pdb features, and the emacs shortcuts are just that - shortcuts. So try the long hand commands first. > > 1. Add the following to your program: > > import pdb > > pdb.set_trace() > > 2. Start an interactive Python buffer (C-c !) I'd go with the import but set_trace isn't necessary to use pdb. My normal way of using pdb is to ipport both it and my module, then *run* the module. >>> import pdb, mymodule >>> pdb.run('mymodule.myfunction(aParameter)') (pdb) > If I set a breakpoint, then 'c'/'continue' doesn't work. Instead of > continuing, it only goes one step. Set the breakpoint using b and a function name (pdb) b mymodule.somefunc notice no parems, just the name then c for contnue (usually a few times (2 or 3) to get past the internal pdb bits) (pdb) c (pdb) Now you can start using the print command to check state etc, up to navigate the call stack, 'step' into functions and 'next' over them etc... > I am using regular ole raw emacs, on a plain terminal, no X. Are you? > > How are you doing with this? I could sure use a debugger. pdb is OK, although IDLE is better and Pythonwin is better still - they are graphical debuggers... FWIW there is a very short intro to both pdb and IDLE in my book... I seem to recall that Mark Lutz has a chapter onpdb in Programming Python too. Alan G. From alan.gauld at freenet.co.uk Mon Dec 27 12:27:58 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Dec 27 12:27:30 2004 Subject: [Tutor] Environment Variables On Windows References: <41CEFB63.4060006@gmail.com> Message-ID: <016201c4ec07$1ee33730$b3b88651@xp> > I tried to do this: > > import os > import cgitb; cgitb.enable() > print "Content-type: text/html\n\n" > print "Hi there, ",os.system("echo %USERNAME%") If you ignore the environment variable bit, does it work with a hard coded name? If so then try using the function os.getenv() to fetch the variable, better than os.system anyway! os.system return an error code not the string, so you'd wind up printing either 0 or some error number! > But I don't get anything in the browser (500 error - Internal Server > Error) and when I run the script in IDLE I get: But this looks like a more fundamental error. Try to get it working without the env var first. BTW Since you are using Python have you looked at the python cgi tutoprial using the cgi module? THe O'REilly one ois fine if you want to understand what cgi module does under the covers, but using cgi is much easier... HTH Alan G. From alan.gauld at freenet.co.uk Mon Dec 27 12:34:28 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Mon Dec 27 12:33:58 2004 Subject: [Tutor] Environment Variables On Windows References: <41CEFB63.4060006@gmail.com> <41CF276A.8020106@gmail.com> Message-ID: <016e01c4ec08$073ba760$b3b88651@xp> > print "Hi there, ",os.environ["USERNAME"] Oops, sorry, I said os.getenv(), looks like my C background showing through :-) Alan g. From jasonchild at cnsp.com Mon Dec 27 15:50:06 2004 From: jasonchild at cnsp.com (jasonchild@cnsp.com) Date: Mon Dec 27 15:50:11 2004 Subject: [Tutor] Comments appreciated In-Reply-To: References: Message-ID: <1122.208.3.80.117.1104159006.squirrel@208.3.80.117> [edited for sanity] > An advantage here is that this guess() function is less tied to outside > global resources, and is, in theory, more easily reused. If we wanted to > rewrite the program so that we take three different passwords, the version > without global variables is easy to write: > > guess("elbereth") > guess("open sesame") > guess("42") > > But the one with the global variable use is something much uglier on our > hands: > > password = "elbereth" > guess() > password = "open sesame" > guess() > password = "42" > guess() > > > Anyway, sorry about the confusion. I have to read threads more carefully! > > > indeed. I recently wresteled with the pros and cons of global variables. What I did was to create a class that stores (via access funcs) important data for my application. Said data is populated at startup from a text file. This allows me to pass a single object that contains loads of conf data to the important init functions (which my, indeed, change the data depending on various factors). Now, memory wise this may not be the best thing to do. Another alternative I considered would be to pass a sequence type (mapping, array, tupple, whatever) from func to func (where it is needed that is). Needless to say that at this point I am not overtly concerned with optimizing my script, as I actually have another script that sorts my data sources every 4 hours or so (to keep from parsing HUGE files at every user request the script sorts and saves seperate files for each user). From markboydell at gmail.com Mon Dec 27 19:18:50 2004 From: markboydell at gmail.com (Mark Boydell) Date: Mon Dec 27 19:18:54 2004 Subject: [Tutor] re.compile and objects - what am doing wrong? Message-ID: <253f641104122710187c23668d@mail.gmail.com> Been a long time since I last posted to the list so this is only my third program in as many years :( Anyway the basic idea is to look through two csv files (seperated by tabs) enter both of them into dictionaries and compare the keys of the "polished" version with the "rough" one. If I've already dealt with that entry in some form or way in the polished version, I want to bin that entry in the rough dictionary. So, for example, if I already have an entry called "Woody Allen" in the polished version, I'd want to bin any entry in rough version I have that contains the text Woody Allen in it (like *Woody Allen* ). I got pretty close I think but I'm stumbling with re.compile which seems to only take hard wired text. Can't I assign the object key to it? Here's my code so far (and yes my aesthetics of my code has not improved much over the last few years - I guess I'm a slow learner). Any ideas what I should do here? #! /usr/bin/python import string, re dict1={} dict2={} inputFile1 = open("rough.txt", "rb") inputFile2 = open("polished.txt", "rb") for row in inputFile1.readlines(): words = string.split(row,"\t") dict1[words[0]]=words[1] for row in inputFile2.readlines(): words = string.split(row,"\t") dict2[words[0]]=words[1] outFile1 = open ("rough.out", "w") outFile2 = open ("polish.out", "w") polishKeys=dict2.keys() roughKeys=dict1.keys() for key in polishKeys: searchPat=re.compile("%s") % key # Doesn't work for rKey in roughKeys: if searchPat.match(rKey): print key+"----"+rKey outFile1.close() outFile2.close() inputFile1.close() inputFile2.close() From keridee at jayco.net Mon Dec 27 20:39:25 2004 From: keridee at jayco.net (Jacob S.) Date: Mon Dec 27 20:39:39 2004 Subject: [Tutor] re.compile and objects - what am doing wrong? References: <253f641104122710187c23668d@mail.gmail.com> Message-ID: <000601c4ec4b$cc990820$f25328cf@JSLAPTOP> Hi, [Blah,blah,blah,text cut] > > #! /usr/bin/python > import string, re First, I like to use string methods instead of importing the string module, so let's get rid of that. > dict1={} > dict2={} > inputFile1 = open("rough.txt", "rb") > inputFile2 = open("polished.txt", "rb") > for row in inputFile1.readlines(): Next, in some recent python version, they have made files iterators, so you don't have to call the method readlines() on the file--you can just use for row in inputFile1: > words = string.split(row,"\t") We change this to use string methods-- words = row.split("\t") > dict1[words[0]]=words[1] > > for row in inputFile2.readlines(): > words = string.split(row,"\t") > dict2[words[0]]=words[1] Do all of the same stuff we just did to the above section. > outFile1 = open ("rough.out", "w") > outFile2 = open ("polish.out", "w") > polishKeys=dict2.keys() > roughKeys=dict1.keys() > for key in polishKeys: > searchPat=re.compile("%s") % key # Doesn't work Now, what you seem to be using here is % formatting. The first thing I see wrong -- you should put the % key inside the parenthesis with the string so it reads re.compile("%s" % key) The next thing, I'm not so sure of because of the lost indentation, but I think that you are looking through all of roughKeys for each polishKey and seeing if a particular string is in the roughKeys and print it. Right? Having said that, I suggest we get rid of the re module and again use string methods. So, we use this. # I get rid of % formatting because key is already a string! for searchPat in polishKeys: for rKey in roughKeys: if searchPat in rKey: print searchPat+"----"+rKey > outFile1.close() > outFile2.close() > inputFile1.close() > inputFile2.close() Having said all of that, I see one more thing--Why on earth use dictionaries if all you're using is the list of keys? Why not just use lists? So, the script as I see it is: #! /usr/bin/python roughkeys = [] polishkeys = [] inputFile1 = open("rough.txt", "rb") inputFile2 = open("polished.txt", "rb") for row in inputFile1: roughkeys.append(row.split("\t")[0]) for row in inputFile2: polishkeys.append(row.split("\t")[0]) outFile1 = open ("rough.out", "w") outFile2 = open ("polish.out", "w") for key in polishkeys: for rkey in roughkeys: if key in rkey: print key+"----"+rkey outFile1.close() outFile2.close() inputFile1.close() inputFile2.close() But!!!! Even better. As I ramble on, I see that list comprhensions can make things easier! #! /usr/bin/python inputFile1 = open("rough.txt", "rb") inputFile2 = open("polished.txt", "rb") roughkeys = [row.split("\t")[0] for row in inputFile1] polishkeys = [row.split("\t")[0] for row in inputFile2] outFile1 = open ("rough.out", "w") outFile2 = open ("polish.out", "w") for key in polishkeys: for rkey in roughkeys: if key in rkey: print key+"----"+rkey outFile1.close() outFile2.close() inputFile1.close() inputFile2.close() Does this work? Does it help? It was fun! Jacob Schmidt From keridee at jayco.net Mon Dec 27 22:31:28 2004 From: keridee at jayco.net (Jacob S.) Date: Mon Dec 27 22:54:09 2004 Subject: [Tutor] O.T. Message-ID: <000501c4ec5b$6ec59c80$8c5428cf@JSLAPTOP> I hate to sound weird... But who are you all, what are you're ages, what do you do, marriage status, etc? You obviously don't have to answer, I'm just curious who I'm boldly sending emails to. Jacob Schmidt P.S. I'm a student. 14 years. Play the piano better than I write scripts. Single. etc. From jasonchild at cnsp.com Mon Dec 27 22:57:28 2004 From: jasonchild at cnsp.com (Jason Child) Date: Mon Dec 27 22:57:29 2004 Subject: [Tutor] O.T. In-Reply-To: <000501c4ec5b$6ec59c80$8c5428cf@JSLAPTOP> References: <000501c4ec5b$6ec59c80$8c5428cf@JSLAPTOP> Message-ID: <41D08548.7030906@cnsp.com> Jacob S. wrote: >I hate to sound weird... > >But who are you all, what are you're ages, what do you do, marriage status, >etc? >You obviously don't have to answer, I'm just curious who I'm boldly sending >emails to. > >Jacob Schmidt > >P.S. >I'm a student. 14 years. Play the piano better than I write scripts. Single. >etc. > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > I am a premed student, 23, do web programming (CGI)/tech support/VOIP installation/what-ever-the-boss-wants-the-geek-to-do, single. As for piano? Well, lets just say that I couldnt play my way outta a cardboard box. Get me behind a pair of turntables however... -- Jason Christopher Child Computer Network Service Professionals VOZ Online From johnp at milwaukielumber.com Mon Dec 27 22:59:41 2004 From: johnp at milwaukielumber.com (John Purser) Date: Mon Dec 27 22:59:46 2004 Subject: [Tutor] O.T. In-Reply-To: <000501c4ec5b$6ec59c80$8c5428cf@JSLAPTOP> Message-ID: <200412272159.iBRLxf7s021641@mail.morseintranet.com> Wow. An actual ASL post. I haven't seen one of these since I left AOL. I'm a 44 year old IT jack of all trades with a background in accounting. Right now I work for a company creating and automating management reports. I've programmed in a half dozen languages, done networking, have some certifications in Unix and Windows. I guess my status would be "involved". Nice to meet you Jacob. John Purser -----Original Message----- From: tutor-bounces+johnp=milwaukielumber.com@python.org [mailto:tutor-bounces+johnp=milwaukielumber.com@python.org] On Behalf Of Jacob S. Sent: Monday, December 27, 2004 13:31 To: tutor@python.org Subject: [Tutor] O.T. I hate to sound weird... But who are you all, what are you're ages, what do you do, marriage status, etc? You obviously don't have to answer, I'm just curious who I'm boldly sending emails to. Jacob Schmidt P.S. I'm a student. 14 years. Play the piano better than I write scripts. Single. etc. _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From dbroadwell at mindspring.com Mon Dec 27 23:42:41 2004 From: dbroadwell at mindspring.com (David Broadwell) Date: Mon Dec 27 23:43:06 2004 Subject: [Tutor] O.T. In-Reply-To: <200412272159.iBRLxf7s021641@mail.morseintranet.com> Message-ID: As the sig says, I'm David Broadwell. I'm 29, 30 this July. Married in hurricane alley (Florida), with a 18 month old daughter. I'm a student as well, finishing my AA.ENGR and heading to USF for a Dual Bachelors of CS and EE. I'm instrumentally challenged as far as making music, but as far as carving or other buildcraft I can make tools sing. Python is my first functional language since I retired my BASIC interpreter on my Atari 800XL, mostly because of the interpreter ... Sure I've dabbled over the years, but after having to play with C*'s malloc or Java's Private function Psychotic Data crud, dropped them like hot rocks to go back to shells and batch files. I've been a TechnoGeek these last years, and understand doing(whatEverTheHeckTheBossWants) and explaining(whyTheEmailBoxCan'tBeOver2gb), I'm moving into something more relaxing ... Now why that's NOT Computer Engineering is a story in itself. My little mantra below is very close to the scientific method, for a reason. -- Programmer's mantra; Observe, Brainstorm, Prototype, Repeat David Broadwell From alan.gauld at freenet.co.uk Tue Dec 28 00:08:02 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Dec 28 00:07:58 2004 Subject: [Tutor] Comments appreciated References: <1122.208.3.80.117.1104159006.squirrel@208.3.80.117> Message-ID: <002501c4ec68$eaeed0d0$f7b08851@xp> > file. This allows me to pass a single object that contains loads of conf > data to the important init functions (which my, indeed, change the data > depending on various factors). Now, memory wise this may not be the best > thing to do. As a matter of interest why do you think its a problem memory wise? You don't create copies when you pass the object, you only pass a reference to the original - and indeed the only - copy. Alan G. From rschroev_nospam_ml at fastmail.fm Tue Dec 28 00:17:45 2004 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Tue Dec 28 00:17:53 2004 Subject: [Tutor] Re: O.T. In-Reply-To: <000501c4ec5b$6ec59c80$8c5428cf@JSLAPTOP> References: <000501c4ec5b$6ec59c80$8c5428cf@JSLAPTOP> Message-ID: Jacob S. wrote: > I hate to sound weird... > > But who are you all, what are you're ages, what do you do, marriage status, > etc? > You obviously don't have to answer, I'm just curious who I'm boldly sending > emails to. A similar thread ran a while ago on comp.lang.python (search for "age of python programmers" on Google groups). The main focus there was on the age; I summarized the age distribution on http://www.roelschroeven.net/pythonages/. I'm 30 years old, live in Belgium, single. My job is C++ development. -- "Codito ergo sum" Roel Schroeven From alan.gauld at freenet.co.uk Tue Dec 28 00:48:14 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Dec 28 00:48:00 2004 Subject: [Tutor] re.compile and objects - what am doing wrong? References: <253f641104122710187c23668d@mail.gmail.com> Message-ID: <002a01c4ec6e$88cb0260$f7b08851@xp> Hi Mark, > for key in polishKeys: > searchPat=re.compile("%s") % key # Doesn't work > for rKey in roughKeys: > if searchPat.match(rKey): print key+"----"+rKey It should work, but it may be a bad string - ie not a valid regular expression? What errors do you get? What does the key string look like? (try inserting a print command before the compile) We need a wee bit more detail on what's going wrong. Alan G. "Show me your flowcharts and conceal your tables, and I'll continue to be mystified. Show me your tables, and I won't usually need your flowcharts" - Fred Brooks, The Mythical Man Month From alan.gauld at freenet.co.uk Tue Dec 28 00:50:47 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Dec 28 00:50:37 2004 Subject: [Tutor] re.compile and objects - what am doing wrong? References: <253f641104122710187c23668d@mail.gmail.com> <000601c4ec4b$cc990820$f25328cf@JSLAPTOP> Message-ID: <003101c4ec6e$e48362f0$f7b08851@xp> From: "Jacob S." > > searchPat=re.compile("%s") % key # Doesn't work > Now, what you seem to be using here is % formatting. > The first thing I see wrong -- you should put the % key inside the > parenthesis Doh! I missed that one completely! Well done Jacob. Alan G. Too much egg nog? From guillermo.fernandez.castellanos at gmail.com Tue Dec 28 01:01:01 2004 From: guillermo.fernandez.castellanos at gmail.com (Guillermo Fernandez Castellanos) Date: Tue Dec 28 01:01:07 2004 Subject: [Tutor] O.T. In-Reply-To: <000501c4ec5b$6ec59c80$8c5428cf@JSLAPTOP> References: <000501c4ec5b$6ec59c80$8c5428cf@JSLAPTOP> Message-ID: <7d7029e704122716016b5e0647@mail.gmail.com> Hi, 26 years, single, spanish but having lived around Europe, communication systems engineer, working in Japan now for a year, going back to europe in April and looking for a job. I've done mainly network stuff, from system conception to network programming in C. I've worked in VoIP (SIP, Megaco, ...), wireless networks, ... I use Python mainly for my personal pleasure and for testing programs written in other languages (with SWIG). Cheers, Guille On Mon, 27 Dec 2004 16:31:28 -0500, Jacob S. wrote: > I hate to sound weird... > > But who are you all, what are you're ages, what do you do, marriage status, > etc? > You obviously don't have to answer, I'm just curious who I'm boldly sending > emails to. > > Jacob Schmidt > > P.S. > I'm a student. 14 years. Play the piano better than I write scripts. Single. > etc. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From jasonchild at cnsp.com Tue Dec 28 01:05:08 2004 From: jasonchild at cnsp.com (Jason Child) Date: Tue Dec 28 01:05:09 2004 Subject: [Tutor] Polish translation of my tutor In-Reply-To: <200412172341.43588.Pawel_Kraszewski@wp.pl> References: <000501c4e472$f52da330$05be8651@xp> <200412172341.43588.Pawel_Kraszewski@wp.pl> Message-ID: <41D0A334.7020602@cnsp.com> Pawel Kraszewski wrote: >Dnia pi?tek, 17 grudnia 2004 20:59, Alan Gauld napisa?: > >|Are there any Polish speakers on the tutor list who would like >|to check a new version of my tutorial? There are no formal links >|to it yet as there are only a few pages but it can be found at: > > Wish I spoke Polish. I had the opertunity to work with some Polish folks this past summer. After 3 months of work all I could pick up were some choice words (that I dont think are appropriate to list here) and some fairly easy expressions. -- Jason Christopher Child Computer Network Service Professionals VOZ Online From rschroev_nospam_ml at fastmail.fm Tue Dec 28 01:07:35 2004 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Tue Dec 28 01:07:41 2004 Subject: [Tutor] Re: O.T. In-Reply-To: References: <000501c4ec5b$6ec59c80$8c5428cf@JSLAPTOP> Message-ID: Roel Schroeven wrote: > A similar thread ran a while ago on comp.lang.python (search for "age of > python programmers" on Google groups). The main focus there was on the > age; I summarized the age distribution on > http://www.roelschroeven.net/pythonages/. For those interested, you can find the code I used to do that at http://roelschroeven.net/pythonages/ages.py and the data at http://roelschroeven.net/pythonages/python_ages. It's quick and dirty code though; I don't think you should take it as an example of clear code. -- "Codito ergo sum" Roel Schroeven From singingxduck at gmail.com Tue Dec 28 01:08:14 2004 From: singingxduck at gmail.com (Orri Ganel) Date: Tue Dec 28 01:08:21 2004 Subject: [Tutor] O.T. In-Reply-To: <7d7029e704122716016b5e0647@mail.gmail.com> References: <000501c4ec5b$6ec59c80$8c5428cf@JSLAPTOP> <7d7029e704122716016b5e0647@mail.gmail.com> Message-ID: <3449428f04122716086b7886db@mail.gmail.com> Hello, 15, taught myself Python last year, attend high school in Maryland (USA), born in Israel, moved to Texas at 3, and to MD in 3rd grade . . . Currently learning Java in school, so those are the only languages I'm (semi)comfortable with. Orri -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. From budr at netride.net Tue Dec 28 01:25:04 2004 From: budr at netride.net (Bud Rogers) Date: Tue Dec 28 01:25:23 2004 Subject: [Tutor] O.T. In-Reply-To: <000501c4ec5b$6ec59c80$8c5428cf@JSLAPTOP> References: <000501c4ec5b$6ec59c80$8c5428cf@JSLAPTOP> Message-ID: <200412271825.04932.budr@netride.net> I'm 53, married, father of two. I work for a power company. My title is systems analyst, but the work I do is mostly system administration. I've gotten a lot of mileage out of perl, mostly small ad hoc scripts for one thing or another. Just beginning serious study of python, partly because of ESR's article "Why Python?", which I thought was on his website but apparently is only available at the Linux Journal website: http://www.linuxjournal.com/article.php?sid=3882 I would be grateful for a less restrictive link. -- Bud Rogers Nine words the Eclectic Rede attest: Steal what works. Fix what's broke. Fake the rest. From bgibson at us.ibm.com Tue Dec 28 01:33:26 2004 From: bgibson at us.ibm.com (Bob Gibson) Date: Tue Dec 28 01:33:33 2004 Subject: [Tutor] O.T. In-Reply-To: <20041228000825.AD1B51E4010@bag.python.org> Message-ID: Jacob: Age: 50 (ooh, I don't feel "that" old :-) Status: Married for 25 years (last Sept). Kids: 5 (all adopted) - ages: 20, 18, 6.5, 6.5, 6.5 Languages: "American" English only Programming Languages: (note, some are "forgotten" - i.e., haven't used in > 10 years) ---------------------------------------------------------------------- Ada, ALGOL, APL, Assembly (4), AWK, bash, BASIC, C, C++, COBOL, EXEC, EXEC2, Forth, Fortran, Java, JavaScript, JCL, Jython, ksh, LotusScript, Modula-2, Object Pascal, Pascal, Perl, PL/S (3), Python, REXX, sed, sh, Smalltalk, Snowball, SPITBOL, SQL, Tcl, Turbo Pascal, VBA, VBScript, Visual Basic ---------------------------------------------------------------------- Employment: More than fully employed for 27 years - same employer (IBM) What do I do? Currently, I'm in customer (technical) support. Bob -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041227/17e3a62e/attachment.htm From rschroev_nospam_ml at fastmail.fm Tue Dec 28 01:49:30 2004 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Tue Dec 28 01:49:37 2004 Subject: [Tutor] Re: O.T. In-Reply-To: <200412271825.04932.budr@netride.net> References: <000501c4ec5b$6ec59c80$8c5428cf@JSLAPTOP> <200412271825.04932.budr@netride.net> Message-ID: Bud Rogers wrote: > Just beginning serious study of python, partly because of ESR's article > "Why Python?", which I thought was on his website but apparently is > only available at the Linux Journal website: > > http://www.linuxjournal.com/article.php?sid=3882 > > I would be grateful for a less restrictive link. http://pythonology.org/success&story=esr -- "Codito ergo sum" Roel Schroeven From guillermo.fernandez.castellanos at gmail.com Tue Dec 28 02:55:09 2004 From: guillermo.fernandez.castellanos at gmail.com (Guillermo Fernandez Castellanos) Date: Tue Dec 28 02:55:12 2004 Subject: [Tutor] Re: Tix Select programming problem In-Reply-To: <20041222113341.259407f8.klappnase@freenet.de> References: <7d7029e70412202116483adb6a@mail.gmail.com> <20041221212840.521fc4d1.klappnase@freenet.de> <7d7029e704122118373f5dfc09@mail.gmail.com> <20041222113341.259407f8.klappnase@freenet.de> Message-ID: <7d7029e70412271755313a47b1@mail.gmail.com> Hi, Indeed it works. It's that kind of little details that get me crazy. I am still not used to read the tcl Tix documentation, and sometimes I step over otherwise evident things. Thanks a lot, Guille On Wed, 22 Dec 2004 11:33:41 +0100, Michael Lange wrote: > On Wed, 22 Dec 2004 11:37:57 +0900 > Guillermo Fernandez Castellanos wrote: > Hi Guille, > The "command" option should be assigned to the Select widget itself, not to the added buttons. > It takes two arguments then (from the tixSelect man page): > > Command-Line Name:-command > Database Name: command > Database Class: Command > > Specifies the TCL command to be executed when the -value of the > Select widget is changed. This command will be invoked with two > arguments. The first is the name of the button subwidget that > has toggled. The second is a boolean value indicating whether > the button subwidget is selected. This command is executed only > when the -disableCallback option is set to false. > > So I changed your code a little to make it work: > > import Tix > > def prtS(*args): > print args > print fruits.cget('value') > > def prtC(val): > print val > print sel.cget('value') > > root = Tix.Tk() > fruits=Tix.Select(root,label="Fruits:", orientation='horizontal',command=prtS) > fruits.add('orange',text="Orange",width=6) > fruits.add('lemon',text="Lemon",width=6) > fruits.add('apple',text="Apple",width=6) > fruits.pack() > > sel=Tix.Control(root, label="X Coordinates", max=10, min=3, > integer=True,command=prtC) > sel.pack() > > root.mainloop() > > Hope this helped > > Michael > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From python at bernardlebel.com Tue Dec 28 02:59:59 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Tue Dec 28 03:00:18 2004 Subject: [Tutor] O.T. In-Reply-To: <7d7029e704122716016b5e0647@mail.gmail.com> References: <000501c4ec5b$6ec59c80$8c5428cf@JSLAPTOP> <7d7029e704122716016b5e0647@mail.gmail.com> Message-ID: <41D0BE1F.2010400@bernardlebel.com> 29 years, in Montreal (Canada), friggin' geek, 3D artist and techical director. Been in 3D animation for 4 years. Use Python because it's one of the implemented langages in Softimage|XSI (a 3D software), but now use it for other stuff, generally related to 3D production. I like beer (favoring German pilsners and European lagers), WWE wrestling, boxing, wuxia and saber movies, choppers, role-playing games, used to be a black-dressed guy with long hairs listening death and black metal and playing bass guitar, now my hairs are short and I don't play bass anymore because I'm too geek :-( Here is my site: http://www.bernardlebel.com Btw I'm single as well so if your sister looks like Salma Hayek please send her my gorgeous picture. Cheers Bernard Guillermo Fernandez Castellanos wrote: > Hi, > > 26 years, single, spanish but having lived around Europe, > communication systems engineer, working in Japan now for a year, going > back to europe in April and looking for a job. > > I've done mainly network stuff, from system conception to network > programming in C. I've worked in VoIP (SIP, Megaco, ...), wireless > networks, ... I use Python mainly for my personal pleasure and for > testing programs written in other languages (with SWIG). > > Cheers, > > Guille > > On Mon, 27 Dec 2004 16:31:28 -0500, Jacob S. wrote: > >>I hate to sound weird... >> >>But who are you all, what are you're ages, what do you do, marriage status, >>etc? >>You obviously don't have to answer, I'm just curious who I'm boldly sending >>emails to. >> >>Jacob Schmidt >> >>P.S. >>I'm a student. 14 years. Play the piano better than I write scripts. Single. >>etc. >> >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor >> > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > > From keridee at jayco.net Tue Dec 28 03:11:29 2004 From: keridee at jayco.net (Jacob S.) Date: Tue Dec 28 03:12:24 2004 Subject: [Tutor] O.T. References: <000501c4ec5b$6ec59c80$8c5428cf@JSLAPTOP><7d7029e704122716016b5e0647@mail.gmail.com> <41D0BE1F.2010400@bernardlebel.com> Message-ID: <003e01c4ec82$ab7f3240$eb5428cf@JSLAPTOP> > Btw I'm single as well so if your sister looks like Salma Hayek please > send her my gorgeous picture. giggle,giggle,giggle... I don't know who Salma Hayek is or what she looks like, but I can almost assure you that my sister doesn't look like her. My sister is 29 as well, but I think she's had enough of men and has decided to stay single for the rest of her life. She now lives in my mother's house with rent money over due, several credit cards that have more on them than they should, and 3 dogs and 3 cats. Somehow, I don't think that would work... :) Thanks, Jacob Schmidt PS - Gorgeous? No offense, but..... I'll have to show her your picture anyway.... From soulse at gmail.com Mon Dec 27 22:22:47 2004 From: soulse at gmail.com (Marco) Date: Tue Dec 28 03:24:19 2004 Subject: [Tutor] networking In-Reply-To: References: Message-ID: <20041227212247.71cb9b7f.soulse@gmail.com> Hi python tutors, Im interested on learning python but i would like to focus in a specific topic, networking, where can i find documention networking in python? sockets and all that stuff? i looked for some information but all of them were just vague. thanks in advance, Marco -- "If knowledge can create problems, it is not through ignorance that we can solve them." - Isaac Asimov http://soulse.blogspot.com From markboydell at gmail.com Tue Dec 28 03:35:24 2004 From: markboydell at gmail.com (Mark Boydell) Date: Tue Dec 28 03:35:28 2004 Subject: [Tutor] re.compile and objects - what am doing wrong? In-Reply-To: <000601c4ec4b$cc990820$f25328cf@JSLAPTOP> References: <253f641104122710187c23668d@mail.gmail.com> <000601c4ec4b$cc990820$f25328cf@JSLAPTOP> Message-ID: <253f6411041227183540ad710f@mail.gmail.com> Wow - List comprehensions does make the problem one heck of a lot easier on the eye and doesn't really remove much of it's comprhension. Thanks for the tips Jacob and Alan - It's always fascinating to see what seems like complicated problems set out so neatly and clearly on the list :) From orion_val at 163.com Tue Dec 28 03:58:30 2004 From: orion_val at 163.com (=?UTF-8?B?5rKI5rSB5YWD?=) Date: Tue Dec 28 03:59:08 2004 Subject: [Tutor] networking In-Reply-To: <20041227212247.71cb9b7f.soulse@gmail.com> References: <20041227212247.71cb9b7f.soulse@gmail.com> Message-ID: <41D0CBD6.8000109@163.com> Hi, I think you can try the mailing-list WEB-SIG http://mail.python.org/mailman/listinfo/web-sig Juan Marco wrote: >Hi python tutors, >Im interested on learning python but i would like to focus in a specific topic, networking, where can i find documention networking in python? sockets and all that stuff? i looked for some information but all of them were just vague. >thanks in advance, >Marco > From orion_val at 163.com Tue Dec 28 04:14:14 2004 From: orion_val at 163.com (=?UTF-8?B?5rKI5rSB5YWD?=) Date: Tue Dec 28 04:29:48 2004 Subject: [Tutor] O.T. In-Reply-To: <000501c4ec5b$6ec59c80$8c5428cf@JSLAPTOP> References: <000501c4ec5b$6ec59c80$8c5428cf@JSLAPTOP> Message-ID: <41D0CF86.6090006@163.com> :) Hello I'm a postgradute student, 24 years old. May you can guess, I'm from Shanghai, China, PR., pacing on my single life studing and researching on wireless telecommunication (military products, if specified). I took up Python just one month and a half earlier, for leisure fun. I studied it by myself through and , and due to time-zone problem, I read this mailing-list every early morning from the other half world, mostly USA. And I'm going to translate the former book into Chinese in the coming winter vacation. I wonder whether there is any fellowman also having interest on it. Best wishes, Juan Shen Jacob S. wrote: >I hate to sound weird... > >But who are you all, what are you're ages, what do you do, marriage status, >etc? >You obviously don't have to answer, I'm just curious who I'm boldly sending >emails to. > >Jacob Schmidt > >P.S. >I'm a student. 14 years. Play the piano better than I write scripts. Single. >etc. > > From kilovh at gmail.com Tue Dec 28 04:51:17 2004 From: kilovh at gmail.com (kilovh) Date: Tue Dec 28 04:50:43 2004 Subject: [Tutor] Soem list operation questions? Message-ID: <001001c4ec90$7c631310$2002a8c0@TSVI> I have two questions, both relating to lists. 1. Is there any easy way to compeltely reverse a list so that the last index becomes the first, etc.? 2. Is there any way to take seperate integers in a list and combine them into digits of one number? (e.g. changing [1,2,3,4] into 1234) Thank you for your time. ~kilovh -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041227/7e8c660b/attachment.htm From budr at netride.net Tue Dec 28 05:01:09 2004 From: budr at netride.net (Bud Rogers) Date: Tue Dec 28 05:01:22 2004 Subject: [Tutor] Re: O.T. In-Reply-To: References: <000501c4ec5b$6ec59c80$8c5428cf@JSLAPTOP> <200412271825.04932.budr@netride.net> Message-ID: <200412272201.09655.budr@netride.net> On Monday 27 December 2004 18:49, Roel Schroeven wrote: > > I would be grateful for a less restrictive link. > > http://pythonology.org/success&story=esr Thanks for the link. -- Bud Rogers KD5SZ From guillermo.fernandez.castellanos at gmail.com Tue Dec 28 05:19:35 2004 From: guillermo.fernandez.castellanos at gmail.com (Guillermo Fernandez Castellanos) Date: Tue Dec 28 05:19:39 2004 Subject: [Tutor] Soem list operation questions? In-Reply-To: <001001c4ec90$7c631310$2002a8c0@TSVI> References: <001001c4ec90$7c631310$2002a8c0@TSVI> Message-ID: <7d7029e704122720193e948e05@mail.gmail.com> hi! > 1. Is there any easy way to compeltely reverse a list so that the last index > becomes the first, etc.? The doc is your friend :-) http://www.python.org/dev/doc/maint24/lib/typesseq-mutable.html """s.reverse() reverses the items of s in place""" >>> a=[1,2,3,4] >>> a.reverse() >>> a [4, 3, 2, 1] > 2. Is there any way to take seperate integers in a list and combine them > into digits of one number? (e.g. changing [1,2,3,4] into 1234) Mmm... Well, there is a way: lambda l: int("".join([str(x) for x in l])) >>> a=[1,2,3,4] >>> c=lambda l: int("".join([str(x) for x in l])) >>> c(a) 1234 Let's have a more detailed of what I do by writting the non-ofuscated equivalent code: def c(l): # Converting all elements of the list into strings a=[str(x) for x in l] # Joigning all those strings into a single string s="".join(a) # Converting the new string into an integer int(s) There's probably a better way to do it, but in the meantime you can start using this. Enjoy! Guille From singingxduck at gmail.com Tue Dec 28 05:24:38 2004 From: singingxduck at gmail.com (Orri Ganel) Date: Tue Dec 28 05:24:41 2004 Subject: [Tutor] Soem list operation questions? In-Reply-To: <001001c4ec90$7c631310$2002a8c0@TSVI> References: <001001c4ec90$7c631310$2002a8c0@TSVI> Message-ID: <3449428f04122720242f53f0cb@mail.gmail.com> Hello kilovh. > 1. Is there any easy way to compeltely reverse a list so that the last index > becomes the first, etc.? Why, yes. It's the 'reverse' method of lists. ie: >>> li = [1,2,3,4] >>> li.reverse() >>> li [4, 3, 2, 1] >>> > 2. Is there any way to take seperate integers in a list and combine them > into digits of one number? (e.g. changing [1,2,3,4] into 1234) It depends on what you're trying to do. If you want a string, then you have to do the following: >>> lista = [1,2,3,4] >>> lin = ''.join([str(i) for i in li]) >>> lin '1234' Similarly, to make an int, just int() it: >>> lista = [1,2,3,4] >>> lin = int(''.join([str(i) for i in lista])) >>> lin 1234 Now, let's look at the line that does all the work. lin = ''.join([str(i) for i in li]) First things first. The expression: str.join(sequence) is a builtin of strings which puts together all the elements of a sequence (assuming the elements are strings), separated by str. In other words, ''.join(["a","b","c"]) returns "abc" (str in this case is an empty string). Now, even though lista is already a sequence, it is a sequence of integers, so join won't work on it as is. Which is why we use the list comprehension. [str(i) for i in lista] does a number of things. First, it makes a list (because it is between brackets), which is a sequence, for join to work on. Secondly, it fixes the problem with lista: it makes a sequence of strings, not integers ( [str(i) for i in lista] makes a new list with the elements of lista, but stringified (that would be the technical term :-) )). HTH, Orri > Thank you for your time. > > ~kilovh > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > > -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. From anadem at gmail.com Tue Dec 28 05:58:38 2004 From: anadem at gmail.com (alan sinclair) Date: Tue Dec 28 05:58:43 2004 Subject: [Tutor] Re: O.T. In-Reply-To: <20041228000825.AD1B51E4010@bag.python.org> References: <20041228000825.AD1B51E4010@bag.python.org> Message-ID: > From: Jacob S. > Sent: Monday, December 27, 2004 13:31 > To: tutor@python.org > Subject: [Tutor] O.T. > > I hate to sound weird... > I'm a student. 14 years. Play the piano better than I write scripts. Single. Season's Greetings Jacob and all the circus. Not to be nosy, Jacob, but is that 14 years old (or 14 yrs a student)? Married at 14 might be a little wierd! I'm 60, been 25 years a-programming from 6502 asm through COBOL via Java ... now doing Windows Installer packages and perl scripting, from which i hope Python will be an escape or at least a diversion. Alan From simon at evilgenius.dk Tue Dec 28 06:09:08 2004 From: simon at evilgenius.dk (=?ISO-8859-1?Q?Simon_Kongsh=F8j?=) Date: Tue Dec 28 06:09:22 2004 Subject: [Tutor] networking In-Reply-To: <20041227212247.71cb9b7f.soulse@gmail.com> References: <20041227212247.71cb9b7f.soulse@gmail.com> Message-ID: <41D0EA74.5060100@evilgenius.dk> Hello Marco, Here are a few good places to start when going into networking with Python: Socket Programming in Python HOWTO: http://www.amk.ca/python/howto/sockets/ Documentation for the Python socket module: http://docs.python.org/lib/module-socket.html O'Reilly Network articles about Python networking: http://www.onlamp.com/pub/a/python/2003/11/06/python_nio.html http://www.onlamp.com/pub/a/python/2004/02/12/advanced_nio.html Apart from these, if you're new to network programming, I'd suggest you take a look at these non-Python-specific sockets docs as well (very useful to get to understand sockets): Beej's guide to network programming: http://www.ecst.csuchico.edu/~beej/guide/net/html/ The C10K Problem (studies in networking scalability) http://www.kegel.com/c10k.html From tanja.pislar at gmail.com Tue Dec 28 08:12:13 2004 From: tanja.pislar at gmail.com (tanja pislar) Date: Tue Dec 28 08:12:16 2004 Subject: [Tutor] O.T. In-Reply-To: <000501c4ec5b$6ec59c80$8c5428cf@JSLAPTOP> References: <000501c4ec5b$6ec59c80$8c5428cf@JSLAPTOP> Message-ID: hi, ok i don't think i've ever written to this list before (although i've been a subscriber for quite some time) so here's a chance to introduce myself properly (and not sounding a complete idiot ;)) Tanya, 30, Slovenia (europe), single, student again (computer science, software engeneering) after a long time off making money - it didn't work out as i planned so i went back to school. studied piano for 8 years, switched it for chemistry, discovered that chem is a total bore, tried my luck in painting and drawing and textile design, got bored again, discovered computers and flash, liked actionscript a lot, got introduced to java and though i found the love of my life.. till i bumped into Python. On Mon, 27 Dec 2004 16:31:28 -0500, Jacob S. wrote: > I hate to sound weird... > > But who are you all, what are you're ages, what do you do, marriage status, > etc? > You obviously don't have to answer, I'm just curious who I'm boldly sending > emails to. > > Jacob Schmidt > > P.S. > I'm a student. 14 years. Play the piano better than I write scripts. Single. > etc. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- www.klaustrofobik.org From carroll at tjc.com Tue Dec 28 08:13:26 2004 From: carroll at tjc.com (Terry Carroll) Date: Tue Dec 28 08:13:31 2004 Subject: [Tutor] Tkinter packing confusion Message-ID: First, thanks for the responses on my questions on using Tkinter for data entry from last week. Alan's and Harm's responses were very helpful. I'm now playing with a tiny application that does nothing except allow the user to enter a variable for processing. It provides a default value, and three buttons: if the user hits CANCEL, the app terminates; if he hits OK, it prints out the entered variable; if he hts RESET, the data entered is reset to the default it had to start. The program logic works, but I'm totally lost on the pakcer layout manager. What I want to see is a window with something like this (bear with my ascii art): URL: [ http://www.somewhere.com/default ] +--------+ +-------+ +----+ | Cancel | | Reset | | OK | +--------+ +-------+ +----+ What I'm getting is: URL: +--------+ | Cancel | +--------+ [ http://www.somewhere.co ] +-------++----+ | Reset || OK + +-------++----+ I'm sure my error lies in the packing, but I don't get it. I'm probably thinking abou it wrong, but my logic is this: I create a master frame, with two sub-frames, fBaseURL for the URL label and entry, and fButtons for the three buttons. In the fBaseURL frame, I pack the label widget to the top, and then the entry widget right (i.e., the entry widget to the right of the label widget). Then I pack in the fBaseURL frame. In the fButtons frame, I pack in the "Cancel" button as the top of fButtons; then "Reset" to its right, and "OK" to its right. Then I pack in the fButtons frame. Finally, I pack the parent frame. Well, I'm lost. I'm trying dozens of variations, but just don't get it. Can someone explain to me how to pack in more simple terms? Here's my code: import Tkinter as tk class DEApp: def __init__(self): top=tk.Tk() self.DefaultBaseURL = "http://www.somewhere.com/default/" self.tvDefaultBaseURL=tk.StringVar() self.tvDefaultBaseURL.set(self.DefaultBaseURL) self.F=tk.Frame(top) fBaseURL=tk.Frame(self.F) lBaseURL=tk.Label(self.F, text="URL:") eBaseURL=tk.Entry(textvariable=self.tvDefaultBaseURL) lBaseURL.pack(side="top") eBaseURL.pack(side="right") fBaseURL.pack(side="top") fButtons=tk.Frame(self.F) bCancel=tk.Button(fButtons, text="Cancel", command=self.evCancel) bReset=tk.Button(fButtons, text="Reset", command=self.evReset) bOK=tk.Button(fButtons, text="OK", command=self.evOK) bCancel.pack(side="top") bReset.pack(side="right") bOK.pack(side="right") fButtons.pack(side="left") self.F.pack(side="top") def evCancel(self): print "Cancel hit" self.F.quit() return def evReset(self): print "Reset hit" self.tvDefaultBaseURL.set(self.DefaultBaseURL) return def evOK(self): print "OK hit" print "BaseURL is now", self.tvDefaultBaseURL.get() self.F.quit() return app = DEApp() app.F.mainloop() From carroll at tjc.com Tue Dec 28 08:45:16 2004 From: carroll at tjc.com (Terry Carroll) Date: Tue Dec 28 08:45:19 2004 Subject: [Tutor] Tkinter packing confusion In-Reply-To: Message-ID: On Mon, 27 Dec 2004, Terry Carroll wrote: > The program logic works, but I'm totally lost on the pakcer layout > manager. Never mind; I'm an idiot. > self.F=tk.Frame(top) > > fBaseURL=tk.Frame(self.F) > lBaseURL=tk.Label(self.F, text="URL:") > eBaseURL=tk.Entry(textvariable=self.tvDefaultBaseURL) This is my problem. I created the fBaseURL Frame, but never used it. The last two lines should read: > lBaseURL=tk.Label(fBaseURL, text="URL:") > eBaseURL=tk.Entry(fBaseURL, textvariable=self.tvDefaultBaseURL) No wonder it not only didn't pack the way I expected, but that no variation in the pack() calls would fix it. I was putting the widgets directly into the master frame. From alan.gauld at freenet.co.uk Tue Dec 28 10:49:38 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Dec 28 10:49:55 2004 Subject: [Tutor] O.T. Message-ID: <007101c4ecc2$8c461430$f7b08851@xp> It was late last night and I messed up sending this. I'll try again in the cold light of day... :-( > But who are you all, what are you're ages, > what do you do, marriage status, 46, married, no kids, new house, big mortgage :-( I am an IT architect for the UK national telecomms company, BT, and am responsible for the architecture and design of all the systems used in our call centres (about 40 sites, 15000 agents and 250 systems). My background is as an electronics engineer and I worked 10 years as a professional software engineer (using Lisp, SQL, Pascal, C and C++) before moving into architecture. I use Python for my own research and also as a prototyping language for things that will eventually be coded in Java. I am increasingly using Jython to test Java components built by my developers and exposed as web services. More info on my likes, dislikes and views on professional topics at: http://www.freenetpages.co.uk/hp/alan.gauld/computing.htm http://www.freenetpages.co.uk/hp/alan.gauld/complang.htm When not programming I enjoy photography(still & video), music/HiFi, climbing mountains (and skiing back down). And don't tell my wife, but I actually quite enjoy working in our garden! More about by hiking escapades here: http://www.freenetpages.co.uk/hp/alan.gauld/hills/ HTH, Alan G. PS Several of the links on the pages above May be broken... the mountain site is still under construction. From alan.gauld at freenet.co.uk Tue Dec 28 11:07:36 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Dec 28 11:07:17 2004 Subject: [Tutor] networking References: <20041227212247.71cb9b7f.soulse@gmail.com> Message-ID: <009e01c4ecc5$10943f80$f7b08851@xp> > Im interested on learning python but i would like to focus in > a specific topic, networking, where can i find documention > networking in python? sockets and all that stuff? Look at the sockets module documentation. If you know how to use sockets in C or Perl then it should be obvious. Also there is a HowTo document for a basic tutorial. http://www.amk.ca/python/howto/sockets/ Then check out the higher level networking modiles: email, smtp, pop, http, urllib, mime, etc... > i looked for some information but all of them were just vague. Also try the library FAQ: http://www.python.org/doc/faq/library.html It has a few networking topics. Finally, the Active State cookbook can be searched by keyword: http://aspn.activestate.com/ASPN/Python/Cookbook/ Hopefully there are enough specifics there to get you started. Networking is a relatively advanced topic for the tutor list, you might find you get better responses on the comp.lang.python usenet group. But you can try here first if you like! :-) Alan G. From rschroev_nospam_ml at fastmail.fm Tue Dec 28 11:09:33 2004 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Tue Dec 28 11:09:40 2004 Subject: [Tutor] Re: Soem list operation questions? In-Reply-To: <001001c4ec90$7c631310$2002a8c0@TSVI> References: <001001c4ec90$7c631310$2002a8c0@TSVI> Message-ID: kilovh wrote: > 2. Is there any way to take seperate integers in a list and combine them > into digits of one number? (e.g. changing [1,2,3,4] into 1234) Instead of using strings as in the other replies, it's also possible to take the math approach: def listtoint(digits): result = 0 for digit in digits: result *= 10 result += digit return result -- "Codito ergo sum" Roel Schroeven From alan.gauld at freenet.co.uk Tue Dec 28 11:15:57 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Dec 28 11:15:40 2004 Subject: [Tutor] Tkinter packing confusion References: Message-ID: <00ca01c4ecc6$390b2d10$f7b08851@xp> > manager. What I want to see is a window with something like this (bear > with my ascii art): > > URL: [ http://www.somewhere.com/default ] > > +--------+ +-------+ +----+ > | Cancel | | Reset | | OK | > +--------+ +-------+ +----+ > > What I'm getting is: > > URL: > +--------+ > | Cancel | > +--------+ [ http://www.somewhere.co ] > +-------++----+ > | Reset || OK + > +-------++----+ > > > In the fButtons frame, I pack in the "Cancel" button as the top of Top means you want packer to have a vertical arrangement. > fButtons; then "Reset" to its right, and "OK" to its right. Then I pack > in the fButtons frame. right means a horizontal alignment. So packer obediently puts the first button centre top, and the other two horizontally spread out below it. Simply use Right, (or left) for all the button packing and it should be grand. Alan G. From luc.saffre at gmx.net Tue Dec 28 15:58:33 2004 From: luc.saffre at gmx.net (Luc Saffre) Date: Tue Dec 28 15:58:42 2004 Subject: [Tutor] Output to a printer In-Reply-To: <002401c43394$cf8c95d0$6401a8c0@xp> References: <3.0.3.32.20040502215231.00ae0860@pop3.eskimo.com> <002401c43394$cf8c95d0$6401a8c0@xp> Message-ID: <41D17499.5050003@gmx.net> On 06.05.2004 21:06, Alan Gauld wrote: > THis is a problem in all programming languages on Windows because > basically Windows treats documents to be printed as graphics, so > you have to convert your document into something windows can print. > Its possible but painful (unless you find a module somewhere, > in which case let me know!) I wrote a module that permits something like: d = Win32PrinterDocument(printerName,spoolFile) f = file(inputfile) for line in f.readlines(): d.PrintLine(line.rstrip()) d.endDoc() Output will go to the specified Windows printer. Unfortunately I'll need some time to make it ready for the public. Tell me if you are interested. Luc From keridee at jayco.net Tue Dec 28 16:26:43 2004 From: keridee at jayco.net (Jacob S.) Date: Tue Dec 28 16:26:58 2004 Subject: [Tutor] Re: O.T. References: <20041228000825.AD1B51E4010@bag.python.org> Message-ID: <001301c4ecf1$a9111900$315328cf@JSLAPTOP> > Season's Greetings Jacob and all the circus. > Not to be nosy, Jacob, but is that 14 years old (or 14 yrs a student)? > Married at 14 might be a little wierd! 14 years old. I should have put " single (obviously) ", or something like that. However, where I live--Portland, IN--the high school kids are already engaged. As for me, I couldn't get a girl if she even liked me. ; ) Jacob Schmidt > I'm 60, been 25 years a-programming from 6502 asm through COBOL via > Java ... now doing Windows Installer packages and perl scripting, from > which i hope Python will be an escape or at least a diversion. > Alan From bgailer at alum.rpi.edu Tue Dec 28 17:10:58 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Tue Dec 28 17:07:33 2004 Subject: [Tutor] O.T. In-Reply-To: <007101c4ecc2$8c461430$f7b08851@xp> References: <007101c4ecc2$8c461430$f7b08851@xp> Message-ID: <6.1.2.0.0.20041228090049.03741008@mail.mric.net> I'm 64. Degrees in EE and MDiv. Career a mixture of engineering, computers, minister, teacher, .... Just started a new romantic relationship! Programmed in more languages than I care to recall. The more interesting/arcane include IBM 650: machine language (my first), SOAP, CLASSMATE GE 415: FORTRAN, Assembler Singer 10: Assembler, Machine language PDP 8: FOCAL PL/I, APL, 370 Assembler and Machine language Motorola 8080? Assembler and Machine language CMS Pipelines And finally Python. Sorta like discovering APL. And I have some desire to integrate some APL features into Python. Anyone else want to join me in that effort? Hot topics for me: African Marimba Music (I teach it, design & build instruments). I'm also a DJ on public radio for African Music, as well as a talk show host. Nonviolent Communication as taught by Marshall Rosenberg. A most life-transforming process! I highly recommend it. www.cnvc.org. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From singingxduck at gmail.com Tue Dec 28 17:18:56 2004 From: singingxduck at gmail.com (Orri Ganel) Date: Tue Dec 28 17:19:02 2004 Subject: [Tutor] Re: Soem list operation questions? In-Reply-To: References: <001001c4ec90$7c631310$2002a8c0@TSVI> Message-ID: <3449428f041228081860ae61b1@mail.gmail.com> Yes, but your way only works when the numbers in the list are single digit: >>> def listtoint(digits): result = 0 for digit in digits: result *= 10 result += digit return result >>> listtoint([1,2,3,4]) 1234 >>> listtoint([11,22,33,44]) 13574 -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. From keridee at jayco.net Tue Dec 28 17:24:55 2004 From: keridee at jayco.net (Jacob S.) Date: Tue Dec 28 17:25:22 2004 Subject: [Tutor] Tkinter packing confusion References: Message-ID: <003301c4ecf9$d34d3200$315328cf@JSLAPTOP> And this, right here, is why I like the grid method. ; ) I can easily place everything into a grid that I lay out before hand. I'm used to coordinate systems. I just don't have a firm grasp on the way pack works. Jacob Schmidt > First, thanks for the responses on my questions on using Tkinter for data > entry from last week. Alan's and Harm's responses were very helpful. > > I'm now playing with a tiny application that does nothing except allow the > user to enter a variable for processing. It provides a default value, and > three buttons: if the user hits CANCEL, the app terminates; if he hits OK, > it prints out the entered variable; if he hts RESET, the data entered is > reset to the default it had to start. > > The program logic works, but I'm totally lost on the pakcer layout > manager. What I want to see is a window with something like this (bear > with my ascii art): > > URL: [ http://www.somewhere.com/default ] > > +--------+ +-------+ +----+ > | Cancel | | Reset | | OK | > +--------+ +-------+ +----+ > > What I'm getting is: > > URL: > +--------+ > | Cancel | > +--------+ [ http://www.somewhere.co ] > +-------++----+ > | Reset || OK + > +-------++----+ > > > I'm sure my error lies in the packing, but I don't get it. > > I'm probably thinking abou it wrong, but my logic is this: > > I create a master frame, with two sub-frames, fBaseURL for the URL label > and entry, and fButtons for the three buttons. > > In the fBaseURL frame, I pack the label widget to the top, and then the > entry widget right (i.e., the entry widget to the right of the label > widget). Then I pack in the fBaseURL frame. > > In the fButtons frame, I pack in the "Cancel" button as the top of > fButtons; then "Reset" to its right, and "OK" to its right. Then I pack > in the fButtons frame. > > Finally, I pack the parent frame. > > Well, I'm lost. I'm trying dozens of variations, but just don't get it. > Can someone explain to me how to pack in more simple terms? > > Here's my code: > > import Tkinter as tk > > class DEApp: > def __init__(self): > > top=tk.Tk() > > self.DefaultBaseURL = "http://www.somewhere.com/default/" > self.tvDefaultBaseURL=tk.StringVar() > self.tvDefaultBaseURL.set(self.DefaultBaseURL) > > self.F=tk.Frame(top) > > fBaseURL=tk.Frame(self.F) > lBaseURL=tk.Label(self.F, text="URL:") > eBaseURL=tk.Entry(textvariable=self.tvDefaultBaseURL) > lBaseURL.pack(side="top") > eBaseURL.pack(side="right") > fBaseURL.pack(side="top") > > fButtons=tk.Frame(self.F) > bCancel=tk.Button(fButtons, text="Cancel", command=self.evCancel) > bReset=tk.Button(fButtons, text="Reset", command=self.evReset) > bOK=tk.Button(fButtons, text="OK", command=self.evOK) > bCancel.pack(side="top") > bReset.pack(side="right") > bOK.pack(side="right") > fButtons.pack(side="left") > > self.F.pack(side="top") > > def evCancel(self): > print "Cancel hit" > self.F.quit() > return > > def evReset(self): > print "Reset hit" > self.tvDefaultBaseURL.set(self.DefaultBaseURL) > return > > def evOK(self): > print "OK hit" > print "BaseURL is now", self.tvDefaultBaseURL.get() > self.F.quit() > return > > app = DEApp() > app.F.mainloop() > > > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From singingxduck at gmail.com Tue Dec 28 17:26:52 2004 From: singingxduck at gmail.com (Orri Ganel) Date: Tue Dec 28 17:26:56 2004 Subject: [Tutor] Re: Soem list operation questions? In-Reply-To: <3449428f041228081860ae61b1@mail.gmail.com> References: <001001c4ec90$7c631310$2002a8c0@TSVI> <3449428f041228081860ae61b1@mail.gmail.com> Message-ID: <3449428f041228082640267dc8@mail.gmail.com> Though, of course, by modifying your way (using str() ), it will still work: >>> def listtoint(digits): result = 0 for digit in digits: result *= (10**len(str(digit))) ## just multiply it by 10 result += digit ## to the power of the number of digits return result >>> listtoint([11,22,33,44]) 11223344 >>> listtoint([1,2,3,4]) 1234 -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. From keridee at jayco.net Tue Dec 28 17:27:24 2004 From: keridee at jayco.net (Jacob S.) Date: Tue Dec 28 17:27:40 2004 Subject: [Tutor] Output to a printer References: <3.0.3.32.20040502215231.00ae0860@pop3.eskimo.com><002401c43394$cf8c95d0$6401a8c0@xp> <41D17499.5050003@gmx.net> Message-ID: <003a01c4ecfa$236817a0$315328cf@JSLAPTOP> I'm definitely interested. Jacob S. > On 06.05.2004 21:06, Alan Gauld wrote: > > THis is a problem in all programming languages on Windows because > > basically Windows treats documents to be printed as graphics, so > > you have to convert your document into something windows can print. > > Its possible but painful (unless you find a module somewhere, > > in which case let me know!) > > I wrote a module that permits something like: > > d = Win32PrinterDocument(printerName,spoolFile) > f = file(inputfile) > for line in f.readlines(): > d.PrintLine(line.rstrip()) > d.endDoc() > > Output will go to the specified Windows printer. Unfortunately I'll need > some time to make it ready for the public. Tell me if you are interested. > > Luc > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From rschroev_nospam_ml at fastmail.fm Tue Dec 28 17:28:26 2004 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Tue Dec 28 17:28:32 2004 Subject: [Tutor] Re: Soem list operation questions? In-Reply-To: <3449428f041228081860ae61b1@mail.gmail.com> References: <001001c4ec90$7c631310$2002a8c0@TSVI> <3449428f041228081860ae61b1@mail.gmail.com> Message-ID: Orri Ganel wrote: > Yes, but your way only works when the numbers in the list are single digit: True, but I think (I could be wrong of course) that is what kilovh intended: "...and combine them into digits of one number". -- "Codito ergo sum" Roel Schroeven From rschroev_nospam_ml at fastmail.fm Tue Dec 28 17:47:23 2004 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Tue Dec 28 17:47:31 2004 Subject: [Tutor] Re: Soem list operation questions? In-Reply-To: <3449428f041228082640267dc8@mail.gmail.com> References: <001001c4ec90$7c631310$2002a8c0@TSVI> <3449428f041228081860ae61b1@mail.gmail.com> <3449428f041228082640267dc8@mail.gmail.com> Message-ID: Orri Ganel wrote: > Though, of course, by modifying your way (using str() ), it will still work: > > >>>>def listtoint(digits): > > result = 0 > for digit in digits: > result *= (10**len(str(digit))) ## just multiply it by 10 > result += digit ## to the power of the number of digits > return result That's much more robust indeed. I was trying to make it as simple as possible; perhaps I made it a bit too simple. -- "Codito ergo sum" Roel Schroeven From sigurd at 12move.de Tue Dec 28 19:43:11 2004 From: sigurd at 12move.de (Karl =?iso-8859-1?Q?Pfl=E4sterer?=) Date: Tue Dec 28 19:45:18 2004 Subject: [Tutor] Re: Soem list operation questions? In-Reply-To: <3449428f041228082640267dc8@mail.gmail.com> (Orri Ganel's message of "Tue, 28 Dec 2004 11:26:52 -0500") References: <001001c4ec90$7c631310$2002a8c0@TSVI> <3449428f041228081860ae61b1@mail.gmail.com> <3449428f041228082640267dc8@mail.gmail.com> Message-ID: On 28 Dez 2004, singingxduck@gmail.com wrote: > Though, of course, by modifying your way (using str() ), it will still work: > >>>> def listtoint(digits): > result = 0 > for digit in digits: > result *= (10**len(str(digit))) ## just multiply it by 10 > result += digit ## to the power of the number of digits > return result >>>> listtoint([11,22,33,44]) > 11223344 >>>> listtoint([1,2,3,4]) > 1234 Sorry but IMO the above is too much complicated for such a simple task. Either convert the digits to a string and concatenate them with: def intlist_to_string (lst): return ''.join(map(str, lst)) or use something (suboptimal) like: def intlist_to_string_red (lst): return reduce(lambda r, d: r + str(d), lst, '') The first solution is IMO clear. It's also the fastest solution. If you time the functions you will see that if intlist_to_string needs 1 second intlist_to_string_red needs 2.3 seconds and your solution listtoint needs 3.5 seconds. To time the functions you could use something like: import timeit def time_it (funs, num=1000): for fun in funs: call = '%s(range(100))' % fun imp = 'from __main__ import %s' % fun t = timeit.Timer(call, imp) print call print t.timeit(number=num) print '*'*50 and run it like: .>>> time_it(('intlist_to_string', 'listtoint', 'intlist_to_string_red'), num=10000) intlist_to_string(range(100)) 1.04783373306 ************************************************** listtoint(range(100)) 3.52167831386 ************************************************** intlist_to_string_red(range(100)) 2.31726015457 ************************************************** .>>> Karl -- Please do *not* send copies of replies to me. I read the list From singingxduck at gmail.com Tue Dec 28 19:48:29 2004 From: singingxduck at gmail.com (Orri Ganel) Date: Tue Dec 28 19:48:33 2004 Subject: [Tutor] Re: Soem list operation questions? In-Reply-To: References: <001001c4ec90$7c631310$2002a8c0@TSVI> <3449428f041228081860ae61b1@mail.gmail.com> <3449428f041228082640267dc8@mail.gmail.com> Message-ID: <3449428f0412281048769a8b36@mail.gmail.com> Karl, The ''.join() method was the first one suggested. Roel then suggested a math-based method, which I attempted to improve upon. -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. From rschroev_nospam_ml at fastmail.fm Tue Dec 28 20:27:29 2004 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Tue Dec 28 20:27:43 2004 Subject: [Tutor] Re: Soem list operation questions? In-Reply-To: References: <001001c4ec90$7c631310$2002a8c0@TSVI> <3449428f041228081860ae61b1@mail.gmail.com> <3449428f041228082640267dc8@mail.gmail.com> Message-ID: Karl Pfl?sterer wrote: > Sorry but IMO the above is too much complicated for such a simple task. That depends on your point of view, I think; I find it conceptually at least as easy only to think in terms of numbers when both input and output are numbers. Our assumptions are different too: I assume the input consists of digits and the output is an integer, you allow for bigger numbers as input and assume the output is a string. > Either convert the digits to a string and concatenate them with: > > def intlist_to_string (lst): > return ''.join(map(str, lst)) As Orri said, other posts already showed that approach. I just wanted to point out an alternative. > The first solution is IMO clear. It's also the fastest solution. If > you time the functions you will see that if intlist_to_string needs 1 > second intlist_to_string_red needs 2.3 seconds and your solution > listtoint needs 3.5 seconds. Depends. > import timeit > def time_it (funs, num=1000): > for fun in funs: > call = '%s(range(100))' % fun > imp = 'from __main__ import %s' % fun > t = timeit.Timer(call, imp) > print call > print t.timeit(number=num) > print '*'*50 I changed it somewhat, to make it work according to my (admittely possibly wrong) assumptions: def time_it(funs, num=1000): for fun in funs: call = '%s(range(1,10)*10)' % fun imp = 'from __main__ import %s' % fun t = timeit.Timer(call, imp) print call print t.timeit(number=num) print '*'*50 and I used my version, without Orri's adaption to allow for non-digit inputs. I also changed your function to make it return an int instead of a string, and ran it like: time_it(('intlist_to_int', 'listtoint'), num=10000) intlist_to_int(range(1,10)*10) 1.02976551489 ************************************************** listtoint(range(1,10)*10) 0.929201057676 ************************************************** Not that much difference, but mine seems to be somewhat faster in that case. I guess it's because yours need (after I made it return an int, assuming that's what kilovh wanted) to convert the string back to an int. The algorithm to do that looks a lot like my function. With Orri's adaption, listtoint slows down a lot, which explains your results. I think different approaches are possible, and which one is best depends on the circumstances. Karl Pfl?sterer wrote: > Please do *not* send copies of replies to me. > I read the list I agree, but I got a copy of your reply in my inbox. Either gmane.org screwed up or you inadvertently cc-ed me. -- "Codito ergo sum" Roel Schroeven From sigurd at 12move.de Tue Dec 28 21:29:46 2004 From: sigurd at 12move.de (Karl =?iso-8859-1?Q?Pfl=E4sterer?=) Date: Tue Dec 28 21:33:50 2004 Subject: [Tutor] Re: Soem list operation questions? In-Reply-To: <3449428f0412281048769a8b36@mail.gmail.com> (Orri Ganel's message of "Tue, 28 Dec 2004 13:48:29 -0500") References: <001001c4ec90$7c631310$2002a8c0@TSVI> <3449428f041228081860ae61b1@mail.gmail.com> <3449428f041228082640267dc8@mail.gmail.com> <3449428f0412281048769a8b36@mail.gmail.com> Message-ID: On 28 Dez 2004, singingxduck@gmail.com wrote: > Karl, > The ''.join() method was the first one suggested. Roel then suggested > a math-based method, which I attempted to improve upon. I know. I read it all; ''.join() was suggested together with a list comprehension (in such simple situations map() is IMO nicer to read so I used that). '.join(...) is for that problem a perfekt solution: it's short, easy to read and understand and scales well. Why searching for a more complicated solution if such a good one exists? It may be a nice lecture but then you should put a big exclamation mark near it, so Python beginners (we are on a Tutor list) do not pick up wrong habits. Karl -- Please do *not* send copies of replies to me. I read the list From rschroev_nospam_ml at fastmail.fm Tue Dec 28 21:52:58 2004 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Tue Dec 28 21:53:14 2004 Subject: [Tutor] Re: Soem list operation questions? In-Reply-To: References: <001001c4ec90$7c631310$2002a8c0@TSVI> <3449428f041228081860ae61b1@mail.gmail.com> <3449428f041228082640267dc8@mail.gmail.com> <3449428f0412281048769a8b36@mail.gmail.com> Message-ID: Karl Pfl?sterer wrote: > Why searching for a more complicated solution if such a good one > exists? It may be a nice lecture but then you should put a big > exclamation mark near it, so Python beginners (we are on a Tutor > list) do not pick up wrong habits. I guess you have a point there. -- "Codito ergo sum" Roel Schroeven From alan.gauld at freenet.co.uk Tue Dec 28 23:09:15 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Tue Dec 28 23:08:57 2004 Subject: [Tutor] Output to a printer References: <3.0.3.32.20040502215231.00ae0860@pop3.eskimo.com><002401c43394$cf8c95d0$6401a8c0@xp> <41D17499.5050003@gmx.net> Message-ID: <011201c4ed29$defad8c0$f7b08851@xp> Hi Luc, I'm interested. Does it handle more than plain text - although even that would be good! > I wrote a module that permits something like: > > d = Win32PrinterDocument(printerName,spoolFile) > f = file(inputfile) > for line in f.readlines(): > d.PrintLine(line.rstrip()) > d.endDoc() > > Output will go to the specified Windows printer. Unfortunately I'll need > some time to make it ready for the public. Tell me if you are interested. I was going to try doing something similar (if I ever get time!) using the WSH objects. What approach are you taking? It looks (from the EndDoc reference) that you are using the native GDI? Alan G. From davholla2002 at yahoo.co.uk Tue Dec 28 23:21:22 2004 From: davholla2002 at yahoo.co.uk (David Holland) Date: Tue Dec 28 23:21:25 2004 Subject: [Tutor] =?iso-8859-1?q?Using_the_=A3_symbol?= In-Reply-To: <20041228184539.4D3E91E4012@bag.python.org> Message-ID: <20041228222122.6757.qmail@web25404.mail.ukl.yahoo.com> I am trying to use a program that usea s '?' symbolon the pygame screen and I get this message :- 'sys:1: DeprecationWarning: Non-ASCII character '\xc2' in file birdgame29e.py on line 88, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details line 86 ' Now I did look that however I am not sure a) how to do this and b) what encoding to use. Can anyone help ? ___________________________________________________________ ALL-NEW Yahoo! Messenger - all new features - even more fun! http://uk.messenger.yahoo.com From cyresse at gmail.com Wed Dec 29 04:23:43 2004 From: cyresse at gmail.com (Liam Clarke) Date: Wed Dec 29 04:23:46 2004 Subject: [Tutor] O.T. In-Reply-To: <6.1.2.0.0.20041228090049.03741008@mail.mric.net> References: <007101c4ecc2$8c461430$f7b08851@xp> <6.1.2.0.0.20041228090049.03741008@mail.mric.net> Message-ID: I'm 23, married, 3 month old son, employed in New Zealand's social welfare department, in a totally non IT role, learning Python purely out of personal interest and a desire to stop working for New Zealand's social welfare department someday. I too climb mountains, having previously been based in a village of 50 people deep in the Southern Alps. I can't ski. On Tue, 28 Dec 2004 09:10:58 -0700, Bob Gailer wrote: > I'm 64. Degrees in EE and MDiv. Career a mixture of engineering, computers, > minister, teacher, .... > Just started a new romantic relationship! > Programmed in more languages than I care to recall. The more > interesting/arcane include > IBM 650: machine language (my first), SOAP, CLASSMATE > GE 415: FORTRAN, Assembler > Singer 10: Assembler, Machine language > PDP 8: FOCAL > PL/I, APL, 370 Assembler and Machine language > Motorola 8080? Assembler and Machine language > CMS Pipelines > And finally Python. Sorta like discovering APL. And I have some desire to > integrate some APL features into Python. Anyone else want to join me in > that effort? > > Hot topics for me: African Marimba Music (I teach it, design & build > instruments). I'm also a DJ on public radio for African Music, as well as a > talk show host. > Nonviolent Communication as taught by Marshall Rosenberg. A most > life-transforming process! I highly recommend it. www.cnvc.org. > > Bob Gailer > bgailer@alum.rpi.edu > 303 442 2625 home > 720 938 2625 cell > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. From billburns at pennswoods.net Wed Dec 29 05:15:05 2004 From: billburns at pennswoods.net (Bill Burns) Date: Wed Dec 29 05:05:38 2004 Subject: [Tutor] networking In-Reply-To: <20041227212247.71cb9b7f.soulse@gmail.com> References: <20041227212247.71cb9b7f.soulse@gmail.com> Message-ID: <200412282315.05680.billburns@pennswoods.net> On Monday 27 December 2004 4:22 pm, Marco wrote: > Hi python tutors, > Im interested on learning python but i would like to focus in a specific > topic, networking, where can i find documention networking in python? > sockets and all that stuff? i looked for some information but all of them > were just vague. thanks in advance, > Marco Hi Marco, You may want to take a look at Pyro which you can find here: http://pyro.sourceforge.net/ And you can find the mailing-list here: http://lists.sourceforge.net/lists/listinfo/pyro-core I've downloaded & installed it but I've not had a chance to try it out yet. HTH Bill From chriscox at bcctv.com Wed Dec 29 12:51:47 2004 From: chriscox at bcctv.com (Chris Cox) Date: Wed Dec 29 12:51:47 2004 Subject: [Tutor] Re: Tutor Digest, Vol 10, Issue 105 References: <20041229110038.903271E4008@bag.python.org> Message-ID: <000b01c4ed9c$c748e1e0$14140a0a@yourw04gtxld67> No longer required. ----- Original Message ----- From: To: Sent: Wednesday, December 29, 2004 6:00 AM Subject: Tutor Digest, Vol 10, Issue 105 Send Tutor mailing list submissions to tutor@python.org To subscribe or unsubscribe via the World Wide Web, visit http://mail.python.org/mailman/listinfo/tutor or, via email, send a message with subject or body 'help' to tutor-request@python.org You can reach the person managing the list at tutor-owner@python.org When replying, please edit your Subject line so it is more specific than "Re: Contents of Tutor digest..." Today's Topics: 1. Re: Re: Soem list operation questions? (Orri Ganel) 2. Re: Soem list operation questions? (Roel Schroeven) 3. Re: Re: Soem list operation questions? (Karl Pfl?sterer ) 4. Re: Soem list operation questions? (Roel Schroeven) 5. Re: Output to a printer (Alan Gauld) 6. Using the ? symbol (David Holland) 7. Re: O.T. (Liam Clarke) 8. Re: networking (Bill Burns) ---------------------------------------------------------------------- Message: 1 Date: Tue, 28 Dec 2004 13:48:29 -0500 From: Orri Ganel Subject: Re: [Tutor] Re: Soem list operation questions? To: tutor@python.org Message-ID: <3449428f0412281048769a8b36@mail.gmail.com> Content-Type: text/plain; charset=US-ASCII Karl, The ''.join() method was the first one suggested. Roel then suggested a math-based method, which I attempted to improve upon. -- Email: singingxduck AT gmail DOT com AIM: singingxduck Programming Python for the fun of it. ------------------------------ Message: 2 Date: Tue, 28 Dec 2004 20:27:29 +0100 From: Roel Schroeven Subject: [Tutor] Re: Soem list operation questions? To: tutor@python.org Message-ID: Content-Type: text/plain; charset=ISO-8859-1; format=flowed Karl Pfldsterer wrote: > Sorry but IMO the above is too much complicated for such a simple task. That depends on your point of view, I think; I find it conceptually at least as easy only to think in terms of numbers when both input and output are numbers. Our assumptions are different too: I assume the input consists of digits and the output is an integer, you allow for bigger numbers as input and assume the output is a string. > Either convert the digits to a string and concatenate them with: > > def intlist_to_string (lst): > return ''.join(map(str, lst)) As Orri said, other posts already showed that approach. I just wanted to point out an alternative. > The first solution is IMO clear. It's also the fastest solution. If > you time the functions you will see that if intlist_to_string needs 1 > second intlist_to_string_red needs 2.3 seconds and your solution > listtoint needs 3.5 seconds. Depends. > import timeit > def time_it (funs, num=1000): > for fun in funs: > call = '%s(range(100))' % fun > imp = 'from __main__ import %s' % fun > t = timeit.Timer(call, imp) > print call > print t.timeit(number=num) > print '*'*50 I changed it somewhat, to make it work according to my (admittely possibly wrong) assumptions: def time_it(funs, num=1000): for fun in funs: call = '%s(range(1,10)*10)' % fun imp = 'from __main__ import %s' % fun t = timeit.Timer(call, imp) print call print t.timeit(number=num) print '*'*50 and I used my version, without Orri's adaption to allow for non-digit inputs. I also changed your function to make it return an int instead of a string, and ran it like: time_it(('intlist_to_int', 'listtoint'), num=10000) intlist_to_int(range(1,10)*10) 1.02976551489 ************************************************** listtoint(range(1,10)*10) 0.929201057676 ************************************************** Not that much difference, but mine seems to be somewhat faster in that case. I guess it's because yours need (after I made it return an int, assuming that's what kilovh wanted) to convert the string back to an int. The algorithm to do that looks a lot like my function. With Orri's adaption, listtoint slows down a lot, which explains your results. I think different approaches are possible, and which one is best depends on the circumstances. Karl Pfldsterer wrote: > Please do *not* send copies of replies to me. > I read the list I agree, but I got a copy of your reply in my inbox. Either gmane.org screwed up or you inadvertently cc-ed me. -- "Codito ergo sum" Roel Schroeven ------------------------------ Message: 3 Date: Tue, 28 Dec 2004 21:29:46 +0100 From: sigurd@12move.de (Karl Pfl?sterer ) Subject: Re: [Tutor] Re: Soem list operation questions? To: Orri Ganel Cc: tutor@python.org Message-ID: Content-Type: text/plain; charset=us-ascii On 28 Dez 2004, singingxduck@gmail.com wrote: > Karl, > The ''.join() method was the first one suggested. Roel then suggested > a math-based method, which I attempted to improve upon. I know. I read it all; ''.join() was suggested together with a list comprehension (in such simple situations map() is IMO nicer to read so I used that). '.join(...) is for that problem a perfekt solution: it's short, easy to read and understand and scales well. Why searching for a more complicated solution if such a good one exists? It may be a nice lecture but then you should put a big exclamation mark near it, so Python beginners (we are on a Tutor list) do not pick up wrong habits. Karl -- Please do *not* send copies of replies to me. I read the list ------------------------------ Message: 4 Date: Tue, 28 Dec 2004 21:52:58 +0100 From: Roel Schroeven Subject: [Tutor] Re: Soem list operation questions? To: tutor@python.org Message-ID: Content-Type: text/plain; charset=ISO-8859-1; format=flowed Karl Pfldsterer wrote: > Why searching for a more complicated solution if such a good one > exists? It may be a nice lecture but then you should put a big > exclamation mark near it, so Python beginners (we are on a Tutor > list) do not pick up wrong habits. I guess you have a point there. -- "Codito ergo sum" Roel Schroeven ------------------------------ Message: 5 Date: Tue, 28 Dec 2004 22:09:15 -0000 From: "Alan Gauld" Subject: Re: [Tutor] Output to a printer To: "Luc Saffre" , "Alan Gauld" Cc: Bob Fleming , tutor@python.org Message-ID: <011201c4ed29$defad8c0$f7b08851@xp> Content-Type: text/plain; charset="iso-8859-1" Hi Luc, I'm interested. Does it handle more than plain text - although even that would be good! > I wrote a module that permits something like: > > d = Win32PrinterDocument(printerName,spoolFile) > f = file(inputfile) > for line in f.readlines(): > d.PrintLine(line.rstrip()) > d.endDoc() > > Output will go to the specified Windows printer. Unfortunately I'll need > some time to make it ready for the public. Tell me if you are interested. I was going to try doing something similar (if I ever get time!) using the WSH objects. What approach are you taking? It looks (from the EndDoc reference) that you are using the native GDI? Alan G. ------------------------------ Message: 6 Date: Tue, 28 Dec 2004 22:21:22 +0000 (GMT) From: David Holland Subject: [Tutor] Using the ? symbol To: tutor@python.org Message-ID: <20041228222122.6757.qmail@web25404.mail.ukl.yahoo.com> Content-Type: text/plain; charset=iso-8859-1 I am trying to use a program that usea s '#' symbolon the pygame screen and I get this message :- 'sys:1: DeprecationWarning: Non-ASCII character '\xc2' in file birdgame29e.py on line 88, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details line 86 ' Now I did look that however I am not sure a) how to do this and b) what encoding to use. Can anyone help ? ___________________________________________________________ ALL-NEW Yahoo! Messenger - all new features - even more fun! http://uk.messenger.yahoo.com ------------------------------ Message: 7 Date: Wed, 29 Dec 2004 16:23:43 +1300 From: Liam Clarke Subject: Re: [Tutor] O.T. To: Tutor Message-ID: Content-Type: text/plain; charset=US-ASCII I'm 23, married, 3 month old son, employed in New Zealand's social welfare department, in a totally non IT role, learning Python purely out of personal interest and a desire to stop working for New Zealand's social welfare department someday. I too climb mountains, having previously been based in a village of 50 people deep in the Southern Alps. I can't ski. On Tue, 28 Dec 2004 09:10:58 -0700, Bob Gailer wrote: > I'm 64. Degrees in EE and MDiv. Career a mixture of engineering, > computers, > minister, teacher, .... > Just started a new romantic relationship! > Programmed in more languages than I care to recall. The more > interesting/arcane include > IBM 650: machine language (my first), SOAP, CLASSMATE > GE 415: FORTRAN, Assembler > Singer 10: Assembler, Machine language > PDP 8: FOCAL > PL/I, APL, 370 Assembler and Machine language > Motorola 8080? Assembler and Machine language > CMS Pipelines > And finally Python. Sorta like discovering APL. And I have some desire to > integrate some APL features into Python. Anyone else want to join me in > that effort? > > Hot topics for me: African Marimba Music (I teach it, design & build > instruments). I'm also a DJ on public radio for African Music, as well as > a > talk show host. > Nonviolent Communication as taught by Marshall Rosenberg. A most > life-transforming process! I highly recommend it. www.cnvc.org. > > Bob Gailer > bgailer@alum.rpi.edu > 303 442 2625 home > 720 938 2625 cell > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > -- 'There is only one basic human right, and that is to do as you damn well please. And with it comes the only basic human duty, to take the consequences. ------------------------------ Message: 8 Date: Tue, 28 Dec 2004 23:15:05 -0500 From: Bill Burns Subject: Re: [Tutor] networking To: tutor@python.org Message-ID: <200412282315.05680.billburns@pennswoods.net> Content-Type: text/plain; charset="iso-8859-1" On Monday 27 December 2004 4:22 pm, Marco wrote: > Hi python tutors, > Im interested on learning python but i would like to focus in a specific > topic, networking, where can i find documention networking in python? > sockets and all that stuff? i looked for some information but all of them > were just vague. thanks in advance, > Marco Hi Marco, You may want to take a look at Pyro which you can find here: http://pyro.sourceforge.net/ And you can find the mailing-list here: http://lists.sourceforge.net/lists/listinfo/pyro-core I've downloaded & installed it but I've not had a chance to try it out yet. HTH Bill ------------------------------ _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor End of Tutor Digest, Vol 10, Issue 105 ************************************** From xemonerdx at gmail.com Wed Dec 29 13:15:39 2004 From: xemonerdx at gmail.com (XemonerdX) Date: Wed Dec 29 13:15:42 2004 Subject: [Tutor] O.T. In-Reply-To: References: <007101c4ecc2$8c461430$f7b08851@xp> <6.1.2.0.0.20041228090049.03741008@mail.mric.net> Message-ID: <90eeed710412290415358fcf81@mail.gmail.com> I'm 31, male, living in the Netherlands, with the love of my life (not married tho). I work as a web developer for a small web agency, doing mostly Flash ActionScript, ColdFusion, PHP, MySQL and (X)HTML. Also involved as a moderator on several Flash communities and heavily intrigued by mathematics, nature & code (all coming together perfectly in the numerous types of fractals). Am diving into Python out of personal interest, and hopefully I'll be able to contribute to this list some day soon :) -- Edwin PoeticTerror.Com From erimendz at gmail.com Wed Dec 29 13:31:28 2004 From: erimendz at gmail.com (Eri Mendz) Date: Wed Dec 29 13:31:27 2004 Subject: [Tutor] O.T. References: <007101c4ecc2$8c461430$f7b08851@xp><6.1.2.0.0.20041228090049.03741008@mail.mric.net> <90eeed710412290415358fcf81@mail.gmail.com> Message-ID: <005501c4eda2$56b0aac0$0f00000a@aqpct.com> joining in this ASL thread..... i'm my kids dad, father of 2, an expat workin in saudi arabia. a newbie trying to learn python to see how far i could go... know a bit of shell scripting, tried Perl but never went far. i like Python's clear syntax, so close to basic english. but of course there's much more to Python than just clear syntax. it's powerful enough to be at par with other mainstream languages. -- Regards, erimendz ----- Original Message ----- From: "XemonerdX" To: "Tutor" Sent: Wednesday, December 29, 2004 3:15 PM Subject: Re: [Tutor] O.T. > I'm 31, male, living in the Netherlands, with the love of my life (not > married tho). > I work as a web developer for a small web agency, doing mostly Flash > ActionScript, ColdFusion, PHP, MySQL and (X)HTML. Also involved as a > moderator on several Flash communities and heavily intrigued by > mathematics, nature & code (all coming together perfectly in the > numerous types of fractals). > > Am diving into Python out of personal interest, and hopefully I'll be > able to contribute to this list some day soon :) > > -- > Edwin > PoeticTerror.Com > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From op73418 at mail.telepac.pt Wed Dec 29 13:38:45 2004 From: op73418 at mail.telepac.pt (=?ISO-8859-1?Q?Gon=E7alo_Rodrigues?=) Date: Wed Dec 29 13:35:17 2004 Subject: [Tutor] O.T. In-Reply-To: <000501c4ec5b$6ec59c80$8c5428cf@JSLAPTOP> References: <000501c4ec5b$6ec59c80$8c5428cf@JSLAPTOP> Message-ID: <41D2A555.90107@mail.telepac.pt> Jacob S. wrote: > I hate to sound weird... > > But who are you all, what are you're ages, what do you do, marriage status, > etc? > You obviously don't have to answer, I'm just curious who I'm boldly sending > emails to. > > Jacob Schmidt > > P.S. > I'm a student. 14 years. Play the piano better than I write scripts. Single. > etc. > G. Rodrigues, 32 years, single and available. I'm a Mathematician, doing research and teaching (but more of the first). My general area of expertise is Category Theory although, since I'm working on things related to theoretical physics I end up meddling in a lot of other stuff. So how did I end up in Python Tutor's list, hein? Well, I have done here and there some small programming jobs and since I had the freedom I ended up choosing Python. I also know Java, C++ and Scheme, but it really is Python where I'm most comfortable. One thing led to another and well, I ended up here answering this or that email. Oh, btw, living in Portugal and planning to go to Australia for a postdoc. Best regards, G. Rodrigues From ARobert at MFS.com Wed Dec 29 13:55:40 2004 From: ARobert at MFS.com (Robert, Andrew) Date: Wed Dec 29 13:56:25 2004 Subject: [Tutor] O.T. Message-ID: <968452DD78695147AA4A369C3DF9E40A02563087@BOSMAILBOX3.corp.mfs.com> I'm a father of two girls, living in Massachusetts. Professionally, I've been a VMS/Unix Systems Admin for the last 17 years. This includes designing high availability, fault tolerant configurations and management of disparate fiber storage area networking solutions. As an admin, I do a good amount of DCL, shell/Perl scripting and C/C++ development in support of production cycles. Recently, I've been doing work with IBM's WebSphere MQSI messaging but that's still in its infancy. I hope to use Python as the scripting language to interface with this. A module called pymqi, http://pymqi.sourceforge.net/, will be the step off point for much of this. Thank you, Andrew Robert Systems Architect Information Technology - OpenVMS Massachusetts Financial Services Phone: 617-954-5882 Pager: 781-764-7321 E-mail: arobert@mfs.com Linux User Number: #201204 -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of Gon?alo Rodrigues Sent: Wednesday, December 29, 2004 7:39 AM Cc: tutor@python.org Subject: Re: [Tutor] O.T. Jacob S. wrote: > I hate to sound weird... > > But who are you all, what are you're ages, what do you do, marriage status, > etc? > You obviously don't have to answer, I'm just curious who I'm boldly sending > emails to. > > Jacob Schmidt > > P.S. > I'm a student. 14 years. Play the piano better than I write scripts. Single. > etc. > G. Rodrigues, 32 years, single and available. I'm a Mathematician, doing research and teaching (but more of the first). My general area of expertise is Category Theory although, since I'm working on things related to theoretical physics I end up meddling in a lot of other stuff. So how did I end up in Python Tutor's list, hein? Well, I have done here and there some small programming jobs and since I had the freedom I ended up choosing Python. I also know Java, C++ and Scheme, but it really is Python where I'm most comfortable. One thing led to another and well, I ended up here answering this or that email. Oh, btw, living in Portugal and planning to go to Australia for a postdoc. Best regards, G. Rodrigues _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor "MFS Relay Service" made the following annotations on 12/29/2004 08:02:16 AM ------------------------------------------------------------------------------ This email communication and any attachments may contain proprietary, confidential, or privileged information. If you are not the intended recipient, you are hereby notified that you have received this email in error and that any review, disclosure, dissemination, distribution or copying of it or its contents is prohibited. The sender does not waive confidentiality or any privilege by mistransmission. If you have received this email in error, please notify the sender immediately, delete this email, and destroy all copies and any attachments. ============================================================================== From pcarey at lexmark.com Wed Dec 29 14:22:53 2004 From: pcarey at lexmark.com (pcarey@lexmark.com) Date: Wed Dec 29 14:22:11 2004 Subject: [Tutor] O.T. Message-ID: 27, married, have a 6-month-old boy. After an MA in literature, I went back to school for a CS degree (about halfway finished now). Java and XSLT/XML pay the bills, but I would use python if I could. I enjoy Faulkner, Bach, algorithms, and swimming. I got interested in computer science because (to me) writing programs feels a lot like writing short stories or poetry. Likewise (to me), some algorithms (heapsort, quicksort) really seem to sound like fugues. |---------+----------------------------> | | "Robert, Andrew" | | | | | | Sent by: | | | tutor-bounces@pyt| | | hon.org | | | | | | | | | 12/29/2004 07:55 | | | AM | | | | |---------+----------------------------> >------------------------------------------------------------------------------------------------------------------------------| | | | To: tutor@python.org | | cc: | | Subject: RE: [Tutor] O.T. | >------------------------------------------------------------------------------------------------------------------------------| I'm a father of two girls, living in Massachusetts. Professionally, I've been a VMS/Unix Systems Admin for the last 17 years. This includes designing high availability, fault tolerant configurations and management of disparate fiber storage area networking solutions. As an admin, I do a good amount of DCL, shell/Perl scripting and C/C++ development in support of production cycles. Recently, I've been doing work with IBM's WebSphere MQSI messaging but that's still in its infancy. I hope to use Python as the scripting language to interface with this. A module called pymqi, http://pymqi.sourceforge.net/, will be the step off point for much of this. Thank you, Andrew Robert Systems Architect Information Technology - OpenVMS Massachusetts Financial Services Phone: 617-954-5882 Pager: 781-764-7321 E-mail: arobert@mfs.com Linux User Number: #201204 -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of Gon?alo Rodrigues Sent: Wednesday, December 29, 2004 7:39 AM Cc: tutor@python.org Subject: Re: [Tutor] O.T. Jacob S. wrote: > I hate to sound weird... > > But who are you all, what are you're ages, what do you do, marriage status, > etc? > You obviously don't have to answer, I'm just curious who I'm boldly sending > emails to. > > Jacob Schmidt > > P.S. > I'm a student. 14 years. Play the piano better than I write scripts. Single. > etc. > G. Rodrigues, 32 years, single and available. I'm a Mathematician, doing research and teaching (but more of the first). My general area of expertise is Category Theory although, since I'm working on things related to theoretical physics I end up meddling in a lot of other stuff. So how did I end up in Python Tutor's list, hein? Well, I have done here and there some small programming jobs and since I had the freedom I ended up choosing Python. I also know Java, C++ and Scheme, but it really is Python where I'm most comfortable. One thing led to another and well, I ended up here answering this or that email. Oh, btw, living in Portugal and planning to go to Australia for a postdoc. Best regards, G. Rodrigues _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor "MFS Relay Service" made the following annotations on 12/29/2004 08:02:16 AM ------------------------------------------------------------------------------ This email communication and any attachments may contain proprietary, confidential, or privileged information. If you are not the intended recipient, you are hereby notified that you have received this email in error and that any review, disclosure, dissemination, distribution or copying of it or its contents is prohibited. The sender does not waive confidentiality or any privilege by mistransmission. If you have received this email in error, please notify the sender immediately, delete this email, and destroy all copies and any attachments. ============================================================================== _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From RPhillips at engineer.co.summit.oh.us Wed Dec 29 14:51:02 2004 From: RPhillips at engineer.co.summit.oh.us (Ron Phillips) Date: Wed Dec 29 14:51:32 2004 Subject: [Tutor] Re:OT Message-ID: 54 years old -- father of 3, grandfather of 4 (and counting.) I started Pythoning because I work for a governmental agency that does Civil Engineering. To support mapping, I needed a wrapper for ESRI products (Python, AML, VBA), to support drafting, I needed a wrapper for AutoDesk products (Python, LISP, VBA), and to support IT, I needed languages for Linux servers (Python, C, etc.) and Windows servers and desktops (Python, VB, C#, etc.) and WindowsCE(Python, VBCE). What option did I really have, then? Besides, it's just so COOL. Ron -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041229/87e8f20a/attachment.html From alan.gauld at freenet.co.uk Wed Dec 29 14:58:51 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed Dec 29 14:58:23 2004 Subject: [Tutor] O.T. References: Message-ID: <017b01c4edae$89f713e0$f7b08851@xp> > interested in computer science because (to me) writing programs > feels a lot like writing short stories or poetry. Hmm, given that several of the programs I've worked on have had more words in them than the bible, I'm not so sure about *short* stories. But I think I know what you mean... :-) Alan G From kent37 at tds.net Wed Dec 29 15:56:00 2004 From: kent37 at tds.net (Kent Johnson) Date: Wed Dec 29 15:56:16 2004 Subject: [Tutor] O.T. In-Reply-To: <000501c4ec5b$6ec59c80$8c5428cf@JSLAPTOP> References: <000501c4ec5b$6ec59c80$8c5428cf@JSLAPTOP> Message-ID: <41D2C580.5090903@tds.net> Age 49, two children, getting divorced :-( Live in New Hampshire (US) with one daughter. In love with computers and programming since forever (well, maybe only since 1968 or so...) Working as a professional programmer mostly since 1977. Languages I have actually been paid to program in include Assembler for PDP-11, Z80, 8086 family FORTRAN C / C++ Java Jython The company I work for now is mostly Java, but I have managed to introduce Jython to a couple of project and most of my work has been in Jython for the last year or so (hooray!!). Programming in Python is a lot of fun. The downside of that is that it makes Java and C++ (both of which I used to like a lot) look like a lot of work for little result. I taught an Introduction to Programming with Python course for a local adult ed program last fall and I will be teaching Python for Programmers in the spring. I like answering questions on the Tutor list because - They are like little puzzles to solve, and I like puzzles - I learn a lot - many times a question will be about a part of Python that I don't know, so I learn enough to answer the questions - OK I admit it, it makes me feel smart :-) If you really want to know more about me see my web site http://www.kentsjohnson.com Kent Jacob S. wrote: > I hate to sound weird... > > But who are you all, what are you're ages, what do you do, marriage status, > etc? > You obviously don't have to answer, I'm just curious who I'm boldly sending > emails to. > > Jacob Schmidt > > P.S. > I'm a student. 14 years. Play the piano better than I write scripts. Single. > etc. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From jeff at ccvcorp.com Wed Dec 29 19:02:03 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed Dec 29 18:57:27 2004 Subject: [Tutor] O.T. In-Reply-To: <000501c4ec5b$6ec59c80$8c5428cf@JSLAPTOP> References: <000501c4ec5b$6ec59c80$8c5428cf@JSLAPTOP> Message-ID: <41D2F11B.5070501@ccvcorp.com> I'm 36, unmarried, male, and live in Seattle, Washington (USA). I've dabbled with computers and programming on and off since junior high (around 1980), but have only gotten serious about it in the last 10 years or so (almost entirely self-taught), and have only been employed in the field for about 5 years. I had two years of college (nominally majoring in chemistry) at the University of Alaska (the state where I grew up) before dropping out, moving to Seattle, and frittering away my young adulthood. ;) I work for a small company that does electronic payment processing and check management. Our system is built around an old Pick database (ugh), and most of my programming is in Pick Proc (a shell-script-like, but truly horrible, language) and Pick's dialect of Basic (which is only 20 years out of date...). As we're moving more towards integrating our server with desktop PCs, though, I've been able to use Python for a few projects, and I often use it for interactively exploring data files and doing sysadmin-type work. Jeff Shannon Technician/Programmer Credit International From hugonz at h-lab.net Wed Dec 1 01:46:43 2004 From: hugonz at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Wed Dec 29 20:08:27 2004 Subject: [Tutor] how to check if a file is being used by another person or application before writing to it? In-Reply-To: <20041130195146.8537.qmail@web60107.mail.yahoo.com> References: <20041130195146.8537.qmail@web60107.mail.yahoo.com> Message-ID: <41ACF165.6000603@h-lab.net> Maybe you can accomplish this using the stat function in the os module. say: import os filename = "foo.txt" mystat = os.stat(filename) #Stat has a number of attributes, such as mystat.st_atime #time of most recent access atime = time.ctime(mystat.st_atime) print atime 'Wed Nov 17 23:51:11 2004' The size of the file is in the st_size attribute of the stat object. It is in bytes... You may use this, but I guess st_atime is a better parameter to check for that. You could keep the last access time and then check if it has changed. As for the "how to know if the file has already been opened by another process" I really do not know. I guess that's what file locking if for... maybe someone can step in and clarify a bit... Hugo > > similarly is there a way to check if a file has been written to? I > suppose I would do something like periodically check the size of a > particular file and if it increased then I would know it was written to. > I didn't see anything in the python documentation for geting the size of > a file. how is this normally performed? > > thanks. > > Jeff > > > ------------------------------------------------------------------------ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From cm012b5105 at blueyonder.co.uk Fri Dec 3 18:10:55 2004 From: cm012b5105 at blueyonder.co.uk (cm012b5105) Date: Wed Dec 29 20:08:35 2004 Subject: [Tutor] text programme in graphical box Message-ID: <200412031714.00081.cm012b5105@blueyonder.co.uk> Hello i want to put an interactive text programme in to a graphical box this is a small section of my text programme s = raw_input ("Hello whats your name? ") if s=='melvyn': print "your my boss's Dad the one they call in indian language DEEP THOUGHT LITTLE HORSE" if s=='carol': print "ahhh you are my boss's mom the one they call WREATH WOMAN" if s=='rebecca': print "you must be the FLORIST WOMAN" if s=='gareth': print "you must be the one they call the TRUCKER" if s=='carmel': print "you must be my boss's wife" s = raw_input ("what do you do for a living? ") print "Ahh thats easy you dont do much then",s,"my boss is a Truck driver." these are the instructions for a graphical boxfrom Tkinter import * root = Tk() cv = Canvas(root, width=400, height=300, bg="blue") cv.pack() cv.create_rectangle(50,30,320,290,outline="yellow",fill="red",width=10) mainloop() any way what i would like to do is create a programme that would run my text programme from this graphical box i tried to add the code for the box to the top of my text programme but when i run it i get the graphical box come up and my text programme will not work untill i kill the box. i would be graet full if some body can help me acheive this. thanks nige From jasonchild at cnsp.com Thu Dec 23 15:21:24 2004 From: jasonchild at cnsp.com (jasonchild@cnsp.com) Date: Wed Dec 29 20:08:41 2004 Subject: [Tutor] silly question In-Reply-To: <007901c4e8c8$dd743420$b3b88651@xp> References: <004c01c4e879$8a3da880$b3b88651@xp><41C9D2BE.7040303@cnsp.com> <41C9D5A8.2010403@cnsp.com><004c01c4e879$8a3da880$b3b88651@xp><5.1.0.14.2.20041222182026.04cbf978@mail.30below.com> <41CA16E5.6050605@cnsp.com> <007901c4e8c8$dd743420$b3b88651@xp> Message-ID: <1083.208.3.80.91.1103811684.squirrel@208.3.80.91> awesome. thanks for the advice! >> how do I change global variables within a function: >> > > by declaring them as global. > See my tutorial topic: "Whats in a Name?" for a discussion of this. > >> ################################## >> VAR = "TEST" >> >> def m(): >> VAR="no test" > > creates a new variable insidethe function. > > def m(): > global VAR > VAR = 'no test' > > now changes the global(or at least module scope) VAR. > > Alan G. > From hugonz at h-lab.net Wed Dec 8 23:26:06 2004 From: hugonz at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Wed Dec 29 20:08:44 2004 Subject: [Tutor] Another ? on large text files In-Reply-To: <7BB911D90C4F384EAAFBB31DEFF990BE187819@ES21SNLNT.srn.sandia.gov> References: <7BB911D90C4F384EAAFBB31DEFF990BE187819@ES21SNLNT.srn.sandia.gov> Message-ID: <41B77F72.80308@h-lab.net> Hi Ara, I'd go something like this: filep = open("myfile") in_data = False output_files = ["file1.txt", "file2.txt" ..... ] for i in output_files: while True: dataline = filep.readline() if not dataline: break if not in_data: if dataline.startswith("CERIUS Grapher File"): ofilep = open(i,"w") #say there are 5 more lines in header for i in range(6): filep.readline() in_data=True continue else: if dataline.startswith( "PLOT XY METHOD:\"Power"): ofilep.close() break else: ofilep.write(filep.readline()) I basically detect start of header and start of footer, and intepret thus if I'm inside a bunch of data. This is very fragile to malformed input and will likely block or lose data if the file is not strictly set. But it should work... Hugo Kooser, Ara S wrote: > I have a large file (4.1 MB, 2600 pgs) of simulated power spectrums. The > problem is that there are 6 separated files all combined into this large > file. I know how to read the file in and then remove the header > information but how would I go about separating the 6 sections into > separate files? > > The program I have so far reads in the data and then removes the header > and footer information (most likely in a very inefficient fashion). > > The data looks something like this and I just want the numbers. > > > CERIUS Grapher File > ! Start of definition for XY graph Power Spectrum component XX A^4/ps^2 > v1 > >>PLOT XY DATA: "Power Spectrum component XX A^4/ps^2" 1 > > 0.0000000E+00 3.1251088E-04 > .. 3333.167 2.2011892E-07 > >>PLOT XY METHOD: "Power Spectrum component YY A^4/ps^2" 1 > > COLOUR RED > ....... > The footer continues and then runs into the header of the next set of > data (no space between them) > > Thanks, > Ara > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From mdcooper at uvic.ca Thu Dec 16 21:32:53 2004 From: mdcooper at uvic.ca (mdcooper) Date: Wed Dec 29 20:08:48 2004 Subject: [Tutor] leastsquares.py Message-ID: <41C3F92B@wm2.uvic.ca> Hello all, I am trying to use a least squares method (the one written by Konrad Hinsen), but I do not want the method to be able to generate negative values. Is there a way to stop least squares programs from doing so? I have probably not included enough information but I am not sure what people need so I will wait for a response. Thanks, Matt mdcooper at uvic dot ca From anil_6755 at sify.com Thu Dec 23 06:16:54 2004 From: anil_6755 at sify.com (anil arvind) Date: Wed Dec 29 20:08:52 2004 Subject: [Tutor] jpg to doc Message-ID: <1103780814.41ca5bce96d4d@webmail1.maa.sify.net> dear sir We have some jpg files. Please help us for converting in m.s. word. I attched one of the file for the needful with regards, anil -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041223/03bce687/attachment-0001.html -------------- next part -------------- A non-text attachment was scrubbed... Name: 00180.jpg Type: image/pjpeg Size: 504815 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20041223/03bce687/00180-0001.bin From ktprktpr at yahoo.com Sun Dec 12 06:55:06 2004 From: ktprktpr at yahoo.com (ktpr) Date: Wed Dec 29 20:11:08 2004 Subject: [Tutor] (no subject) Message-ID: <20041212055504.6630.qmail@web50709.mail.yahoo.com> Hi all, I am trying to supply input to another program using pipes. I can read from it just fine, but writing to its stdin doesn't seem to be working. foo.py (gets pipe to listen.py) --- from popen2 import popen2 cmd = "listen.py" #stdout, stdin r, w = popen2(cmd) w.write("Message sent") w.close() got = r.readlines() r.close() for line in got: print line --- listen.py --- import sys # wrote to this stdin, so uh should have message uh = raw_input("why doesn't it") if "" != uh: print "go here?" if "" == uh: print "or even here?" --- I know I'm missing something conceptual... I only get "why doesn't it" printed to the screen and the message didn't seem to transfer across the pipe, as listen.py aborted before the if statement somehow. Any and all help would be appreciated; popen2._test() works fine ... cheers ktpr __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From member at jhandrew.fsnet.co.uk Sat Dec 18 21:43:08 2004 From: member at jhandrew.fsnet.co.uk (Chris Andrew) Date: Wed Dec 29 20:11:32 2004 Subject: [Tutor] Hi. Message-ID: <1087550.1103402588974.JavaMail.www@wwinf3102> Hi, everybody. I've just subscribed to the list, and am armed with O'Reilly's "Learning Python" book. I don't have any programming experience, but have been knocking around with linux for about 6 years. After much consideration, I inally decided Python looked like the best place to start. I look forward to collaberating with you all. Regards, Chris_Andrew. -- Whatever you Wanadoo: http://www.wanadoo.co.uk/time/ This email has been checked for most known viruses - find out more at: http://www.wanadoo.co.uk/help/id/7098.htm -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041218/03ac7037/attachment.html From sean_mcilroy at yahoo.com Thu Dec 9 06:06:12 2004 From: sean_mcilroy at yahoo.com (Sean McIlroy) Date: Wed Dec 29 20:11:40 2004 Subject: [Tutor] moving widgets around Message-ID: <20041209050611.4231.qmail@web54401.mail.yahoo.com> I'd like to get some example code showing how to move widgets around in drag-and-drop fashion. I've tried looking at tkDND.py (I think that's what it's called) but that was a little involved - what I want to know is the barest of bare bones. Any help would be majorly fabulous. Merci beaucoup. STM __________________________________ Do you Yahoo!? Yahoo! Mail - Easier than ever with enhanced search. Learn more. http://info.mail.yahoo.com/mail_250 From mohamed at your-site.com Wed Dec 29 20:08:23 2004 From: mohamed at your-site.com (Mohamed Lrhazi) Date: Wed Dec 29 20:15:08 2004 Subject: [Tutor] How to put my functions in an array Message-ID: <1104347290.31902.28.camel@6-allhosts> def addvirt(): pass def remvirt(): pass PROVISION_ACTIONS=[('addvirt','Add Virt'),('remvirt','Remove Virt'),] formhandlers={} # this works formhandlers["addvirt"]=addvirt formhandlers["remvirt"]=remvirt # this does not work: for verb,verb_desc in PROVISION_ACTIONS: if callable(verb): formhandlers[verb]=verb I tried a few different syntaxes but to no avail... do I need things like: getattr()? Thanks alot Mohamed~ From jasonchild at cnsp.com Wed Dec 29 20:17:30 2004 From: jasonchild at cnsp.com (Jason Child) Date: Wed Dec 29 20:17:32 2004 Subject: [Tutor] leastsquares.py In-Reply-To: <41C3F92B@wm2.uvic.ca> References: <41C3F92B@wm2.uvic.ca> Message-ID: <41D302CA.8020005@cnsp.com> mdcooper wrote: >Hello all, > >I am trying to use a least squares method (the one written by Konrad Hinsen), >but I do not want the method to be able to generate negative values. Is there >a way to stop least squares programs from doing so? > >I have probably not included enough information but I am not sure what people >need so I will wait for a response. > >Thanks, > >Matt >mdcooper at uvic dot ca > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > i seem to recal a recent thread about this.... the short answer (imo): check for negitive values in the output: ############################## if output < 0: #is it a neg num? print 'err: output would be negitive!' #if so, then display some sort of error msg else: #otherwise its a valid value print str(output) #and we convert to a string and display ############################## now, I am not sure what you are doing with the code, or what it looks like. a simple if check should let you do something with negitive numbers (at the least show an err msg). I guess another (retarded) option would be to abs(output) and get the non-signed version (if abs() is the absolute-value func...never used it myself).... -- Jason Christopher Child Computer Network Service Professionals VOZ Online From luc.saffre at gmx.net Wed Dec 29 20:30:15 2004 From: luc.saffre at gmx.net (Luc Saffre) Date: Wed Dec 29 20:30:27 2004 Subject: [Tutor] Output to a printer In-Reply-To: <011201c4ed29$defad8c0$f7b08851@xp> References: <3.0.3.32.20040502215231.00ae0860@pop3.eskimo.com><002401c43394$cf8c95d0$6401a8c0@xp> <41D17499.5050003@gmx.net> <011201c4ed29$defad8c0$f7b08851@xp> Message-ID: <41D305C7.1020202@gmx.net> Hello Alan and Bob, wow, two interested people! This gave me the necessary motivation to work today on getting the thing published ;-) First look here for a more complete example: http://lsaffre.dyndns.org/~luc/timwebs/lino/26.htm The textprinter package is a part of "Lino", and I'm afraid you will have to install the whole project --- even though you're interested only in a small part of it. Sorry, but Lino is my personal all-in-one metaproject and at the current stage I don't plan to split. The website is very new and not yet, er... optimal, but I hope you'll get what you want by following the instructions on http://lsaffre.dyndns.org/~luc/timwebs/lino/4.htm Otherwise just ask the author (I certainly won't answer "RTFM"). Luc On 29.12.2004 00:09, Alan Gauld wrote: > Hi Luc, > > I'm interested. > Does it handle more than plain text - although even that would be > good! > > >>I wrote a module that permits something like: >> >> d = Win32PrinterDocument(printerName,spoolFile) >> f = file(inputfile) >> for line in f.readlines(): >> d.PrintLine(line.rstrip()) >> d.endDoc() >> >>Output will go to the specified Windows printer. Unfortunately I'll > > need > >>some time to make it ready for the public. Tell me if you are > > interested. > > I was going to try doing something similar (if I ever get time!) > using the WSH objects. What approach are you taking? It looks > (from the EndDoc reference) that you are using the native GDI? > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From jeff at ccvcorp.com Wed Dec 29 20:37:14 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed Dec 29 20:32:41 2004 Subject: [Tutor] How to put my functions in an array In-Reply-To: <1104347290.31902.28.camel@6-allhosts> References: <1104347290.31902.28.camel@6-allhosts> Message-ID: <41D3076A.6030600@ccvcorp.com> Mohamed Lrhazi wrote: > def addvirt(): > pass > def remvirt(): > pass > > PROVISION_ACTIONS=[('addvirt','Add Virt'),('remvirt','Remove Virt'),] > formhandlers={} > > # this works > formhandlers["addvirt"]=addvirt > formhandlers["remvirt"]=remvirt > > # this does not work: > for verb,verb_desc in PROVISION_ACTIONS: > if callable(verb): > formhandlers[verb]=verb > > I tried a few different syntaxes but to no avail... do I need things > like: getattr()? You don't say how this fails, which would be very helpful to know. But I think I can guess what's happening. When you're calling 'callable(verb)', at this point verb contains a string which is a function's name. It is *not* the function itself. The string is, of course, not callable, so nothing gets added to formhandlers. Even if you took out that test, though, you'd end up with a dictionary where for a given key, the value is the same string that was used for the key, because verb is only a string. For this to work, you need to have two separate things -- a string by which to identify the function, and a reference to the function object itself. In the working code, you do this. By putting the name (that you're using as the dictionary key) in quotes, you're specifying a string, and by *not* putting the value (on the right of the = sign) in quotes, you're referring to the function object. There's a couple of ways you can do this. One is by adding a reference to the function to your list, something like this: PROVISION_ACTIONS = [('addvirt', "Add Virt", addvirt), ...] for verb, verb_desc, func in PROVISION_ACTIONS: if callable(func): formhandlers[verb] = func If you can't make that change to PROVISION_ACTIONS, then you may be able to use the name strings to pull function references from your module's global dictionary -- for verb, verb_desc in PROVISION_ACTIONS: func = globals()[verb] if callable(func): formhandlers[verb] = func though you'd probably want to put that globals() lookup in a try/except block to catch any KeyErrors. Note that if the functions were in a different module, you could retrieve them from that module with getattr(), rather than using the globals() dict. import func_module # ... for ... func = getattr(func_module, verb) # ... Once again, you should probably wrap that in a try/except block (this time looking for AttributeErrors). Jeff Shannon Technician/Programmer Credit International From mohamed at your-site.com Wed Dec 29 20:50:22 2004 From: mohamed at your-site.com (Mohamed Lrhazi) Date: Wed Dec 29 20:56:59 2004 Subject: [Tutor] How to put my functions in an array In-Reply-To: <41D3076A.6030600@ccvcorp.com> References: <1104347290.31902.28.camel@6-allhosts> <41D3076A.6030600@ccvcorp.com> Message-ID: <1104349822.31902.37.camel@6-allhosts> Thanks alot Jeff. This worked for me: formhandlers={} for verb,verb_desc in PROVISION_ACTIONS: try: formhandlers[verb]=globals()[verb] except KeyError: pass On Wed, 2004-12-29 at 14:37, Jeff Shannon wrote: > If you can't make that change to PROVISION_ACTIONS, then you may be > able to use the name strings to pull function references from your > module's global dictionary -- > > for verb, verb_desc in PROVISION_ACTIONS: > func = globals()[verb] > if callable(func): > formhandlers[verb] = func > > though you'd probably want to put that globals() lookup in a > try/except block to catch any KeyErrors. From zugravu_gheorghe at list.ru Wed Dec 29 21:40:32 2004 From: zugravu_gheorghe at list.ru (Gheorghe Zugravu) Date: Wed Dec 29 21:40:36 2004 Subject: [Tutor] hello form moldova In-Reply-To: <001301c4ecf1$a9111900$315328cf@JSLAPTOP> Message-ID: hello to everybody,, mu name is george and I am from Moldova, for those who dont know, a small country placed between Romania and Ukraine. in order to respect the subject of this mail list I wannt to say that I just discovered the python and I can not say to much about it, but i just wait to work with it and to be able to take part deeper in the discussions. And of Course with Happy New Year!!!! Gheorghe Zugravu -----Original Message----- From: "Jacob S." To: "alan sinclair" , Date: Tue, 28 Dec 2004 10:26:43 -0500 Subject: Re: [Tutor] Re: O.T. > > > Season's Greetings Jacob and all the circus. > > Not to be nosy, Jacob, but is that 14 years old (or 14 yrs a student)? > > Married at 14 might be a little wierd! > > 14 years old. I should have put " single (obviously) ", or something like > that. > However, where I live--Portland, IN--the high school kids are already > engaged. > As for me, I couldn't get a girl if she even liked me. ; ) > > Jacob Schmidt > > > > I'm 60, been 25 years a-programming from 6502 asm through COBOL via > > Java ... now doing Windows Installer packages and perl scripting, from > > which i hope Python will be an escape or at least a diversion. > > Alan > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From tegmine at gmail.com Wed Dec 29 21:51:29 2004 From: tegmine at gmail.com (Luis N) Date: Wed Dec 29 22:25:48 2004 Subject: [Tutor] Comments appreciated In-Reply-To: References: Message-ID: <77bfa81a0412291251350fe4e9@mail.gmail.com> > [Jeff] > > Also, even though this is intended to be a quick shell script, it's > > not a bad idea to make everything except function defs into a little > > main() function, and call it in a script-only section. > > > [Luis] > > > The only thing I'm not clear about is how 'trashcan' can be a > > local variable inside main() when it's required by both trash() and > > can() > > > What Jeff is trying to say is that it's possible to pass 'trashcan' around > as yet another parameter to both trash() and can(). That is, we can avoid > global variables altogether, and just work with parameter passing. > Lovely, thank you. I started a project that is for learning spanish on-line, of currently 300 lines or so, that is proceeding rapidly thanks to these lessons learned. Thank you Python Tutors, and thank you Python! Cheers, Luis From rha207 at worldnet.att.net Wed Dec 29 22:51:33 2004 From: rha207 at worldnet.att.net (Ron Alvarado) Date: Wed Dec 29 22:48:32 2004 Subject: [Tutor] try here for tkinter lessons Message-ID: <000501c4edf0$90eb7320$fe384b0c@computer> I've had problems getting started with tkinter, but since reading these lessons everything is beginning to make sense. If anyone is interested this is the link. http://bembry.org/tech/python/index.php Ron A From johnp at milwaukielumber.com Wed Dec 29 22:55:56 2004 From: johnp at milwaukielumber.com (John Purser) Date: Wed Dec 29 22:56:00 2004 Subject: [Tutor] try here for tkinter lessons In-Reply-To: <000501c4edf0$90eb7320$fe384b0c@computer> Message-ID: <200412292155.iBTLtu7s022612@mail.morseintranet.com> Thanks. I've bounced off tkinter several times and have been looking for a new approach. I'll check it out as soon as I can. John Purser -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of Ron Alvarado Sent: Wednesday, December 29, 2004 13:52 To: tutor@python.org Subject: [Tutor] try here for tkinter lessons I've had problems getting started with tkinter, but since reading these lessons everything is beginning to make sense. If anyone is interested this is the link. http://bembry.org/tech/python/index.php Ron A _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From alan.gauld at freenet.co.uk Wed Dec 29 23:24:39 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed Dec 29 23:24:05 2004 Subject: [Tutor] text programme in graphical box References: <200412031714.00081.cm012b5105@blueyonder.co.uk> Message-ID: <019d01c4edf5$38adc820$f7b08851@xp> > root = Tk() > cv = Canvas(root, width=400, height=300, bg="blue") > cv.pack() > cv.create_rectangle(50,30,320,290,outline="yellow",fill="red",width=10 ) > > mainloop() > > any way what i would like to do is create a programme that would run my text > programme from this graphical box You need to use a Text box not a Canvas. Canvas is for drawing shapes and displaying images etc. If you use a Text box you can simply convert your print messages into insertions into the text box. Alternatrively use a simple label but change the text each time. That way you only see the latest message... Your prompts and inputs can be a label and Text Entry pair, simply change the contents of the label and read the contents of the entry box. Examples of all of this can be found in the GUI and Case Study topics in my tutorial. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Wed Dec 29 23:31:18 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed Dec 29 23:31:06 2004 Subject: [Tutor] leastsquares.py References: <41C3F92B@wm2.uvic.ca> Message-ID: <01a601c4edf6$1e953850$f7b08851@xp> > I am trying to use a least squares method (the one written by Konrad Hinsen), > but I do not want the method to be able to generate negative values. Is there > a way to stop least squares programs from doing so? def _leastSquare(): # do the thing that might generate negatives def leastSquare(): firstTry = _leastSquare() if firstTry < 0: return leastSquare() # try again else: return firstTry Primitive but it works. If you want more a efficient/elegant solution show us what you have... Alan G. From alan.gauld at freenet.co.uk Wed Dec 29 23:35:36 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Wed Dec 29 23:34:51 2004 Subject: [Tutor] jpg to doc References: <1103780814.41ca5bce96d4d@webmail1.maa.sify.net> Message-ID: <01bc01c4edf6$b7bcadb0$f7b08851@xp> This has been asked before, please try searching the archives on ActiveState web site. The short answer is that you probably are better off finding a good OCR program than trying to do it yourself, coz it's hard! Once you get the text out of the image it's not so hard to put it into Word, either using Python or any other means - even manually! Sorry this isn't the answer you are probably looking for, but what you ask is non trivial, Alan G. ----- Original Message ----- From: "anil arvind" To: Sent: Thursday, December 23, 2004 5:16 AM Subject: [Tutor] jpg to doc > dear sir > We have some jpg files. Please help us for converting in m.s. word. I attched one of the file for the needful > with regards, > anil ---------------------------------------------------------------------- ---------- > ---------------------------------------------------------------------- ---------- From zmerch at 30below.com Thu Dec 30 01:11:33 2004 From: zmerch at 30below.com (Roger Merchberger) Date: Thu Dec 30 01:10:49 2004 Subject: [Tutor] O.T. In-Reply-To: <6.1.2.0.0.20041228090049.03741008@mail.mric.net> References: <007101c4ecc2$8c461430$f7b08851@xp> <007101c4ecc2$8c461430$f7b08851@xp> Message-ID: <5.1.0.14.2.20041229180948.03d1c388@mail.30below.com> Rumor has it that Bob Gailer may have mentioned these words: [snip] >Programmed in more languages than I care to recall. The more >interesting/arcane include >Motorola 8080? Assembler and Machine language Yup - that sure is arcane -- It's either an Intel 8080 or a Motorola 6800. ;-) Me: 37, married 12 years, 3 kids (2 personally crafted ;-) one dog, and live in one of the oldest cities in the US. Been interested in computers since '76, but didn't get a chance to really work on them until '84. First computer: Tandy Color Computer 2. My computer languages: APL, COBOL, Basic09 (which is 1/2 Pascal), umpteen other dialects of Basic (for most 8-bitters on up), Logo, Moto6800/6809 Assembler & Machine Language, Atmel AVR Assembler, Pascal, Lisp (mostly AutoLisp), JCL, ColdFusion, some C, some PHP, enough Java to know I don't much care for it... and was a devout Perl follower until I found Python. If it isn't listed above, I prolly forgot I ever learned it! ;-) Interests: Old computers, still photography, cooking, I'm starting to teach myself woodworking, and if you consider it an interest: construction. My house is ancient, and sucks. I'm interested in making it "suck less," therefore, I'm interested in construction. ;-) Happy Hollydaze, Roger "Merch" Merchberger -- Roger "Merch" Merchberger -- SysAdmin, Iceberg Computers zmerch@30below.com Hi! I am a .signature virus. Copy me into your .signature to join in! From ps_python at yahoo.com Thu Dec 30 02:01:23 2004 From: ps_python at yahoo.com (kumar s) Date: Thu Dec 30 02:01:27 2004 Subject: [Tutor] How to substitute an element of a list as a pattern for re.compile() Message-ID: <20041230010123.91028.qmail@web53709.mail.yahoo.com> Hi Group: I have Question: How can I substitute an object as a pattern in making a pattern. >>> x = 30 >>> pattern = re.compile(x) My situation: I have a list of numbers that I have to match in another list and write them to a new file: List 1: range_cors >>> range_cors[1:5] ['161:378', '334:3', '334:4', '65:436'] List 2: seq >>> seq[0:2] ['>probe:HG-U133A_2:1007_s_at:416:177; Interrogation_Position=3330; Antisense;', 'CACCCAGCTGGTCCTGTGGATGGGA'] A slow method: >>> sequences = [] >>> for elem1 in range_cors: for index,elem2 in enumerate(seq): if elem1 in elem2: sequences.append(elem2) sequences.append(seq[index+1]) This process is very slow and it is taking a lot of time. I am not happy. A faster method (probably): >>> for i in range(len(range_cors)): for index,m in enumerate(seq): pat = re.compile(i) if re.search(pat,seq[m]): p.append(seq[m]) p.append(seq[index+1]) I am getting errors, because I am trying to create an element as a pattern in re.compile(). Questions: 1. Is it possible to do this. If so, how can I do this. Can any one help correcting my piece of code and suggesting where I went wrong. Thank you in advance. -K __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From ps_python at yahoo.com Thu Dec 30 02:24:33 2004 From: ps_python at yahoo.com (kumar s) Date: Thu Dec 30 02:24:38 2004 Subject: [Tutor] O.T. In-Reply-To: <000501c4ec5b$6ec59c80$8c5428cf@JSLAPTOP> Message-ID: <20041230012433.97553.qmail@web53709.mail.yahoo.com> 30, Married, will soon be a dad., Live in Baltimore, U.S.A. and I am a Ph.D. student I lived in Denmark and Israel in the past as a part of my research life. Will finish my Ph.D., in Bioinformatics. Got introduced to computers at the age of 25 :-( and more happy it is not 52 :-) Programming lang: Python and R, Bioconductor, PHP (I have not mastered but WANT TO) DB: PostgreSQL I earn my bread by doing research and in a way I get paid for my interests in life. -K --- "Jacob S." wrote: > I hate to sound weird... > > But who are you all, what are you're ages, what do > you do, marriage status, > etc? > You obviously don't have to answer, I'm just curious > who I'm boldly sending > emails to. > > Jacob Schmidt > > P.S. > I'm a student. 14 years. Play the piano better than > I write scripts. Single. > etc. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From isrgish at fastem.com Thu Dec 30 03:53:26 2004 From: isrgish at fastem.com (Isr Gish) Date: Thu Dec 30 03:55:20 2004 Subject: [Tutor] C mailing list Message-ID: <20041230025507.30A591E4007@bag.python.org> I finally found a C mailing list. But it seems to have a verl low traffic. The email address is c@snippets.org. You can sign up somewhere on: Www.snippets.org Here is some text from there site: As a lightly moderated conference, the C conference has some rules. You can read these at http://c.snippets.org/c-rules.html. Subscribe at http://snippets.org/mailman/listinfo/c. All the best, Isr -----Original Message----- >From: "Marilyn Davis" >Sent: 11/10/04 3:40:43 PM >To: "Isr Gish" >Cc: "tutor@python.org" >Subject: Re: [Tutor] C mailing list > >I couldn't find a beginner's C list from Googling. I didn't spend >much time because I've looked before. > >As far as I know, this list is the only nice place for beginners. > >So Isr, if you find anything, please report back. > >Marilyn Davis > > From orion_val at 163.com Thu Dec 30 04:28:33 2004 From: orion_val at 163.com (=?UTF-8?B?5rKI5rSB5YWD?=) Date: Thu Dec 30 04:28:47 2004 Subject: [Tutor] (no subject)(About Pipe) In-Reply-To: <20041212055504.6630.qmail@web50709.mail.yahoo.com> References: <20041212055504.6630.qmail@web50709.mail.yahoo.com> Message-ID: <41D375E1.5050206@163.com> Hello, KTPR I've read your code. May the main problem locates at "cmd". Assume that foo.py and listen.py are at the same directory. It should look like: cmd='python listen.py' or if you included '#!/usr/bin/python' (Linux) or '#!/usr/local/bin/python' (FreeBSD) as the first line in listen.py and you changed mode of listen.py to a+x cmd='./listen.py' or even if you are now in some one of PATH cmd='listen.py Maybe it hits the point. Just maybe, because you didn't give your output. Here is an example code, it really works at least. -----------foo.py-------------- import popen2 cmd='python listen.py' (pout,pin)=popen2.popen2(cmd) pin.write('Here is a message from pipe.') pin.close() got=pout.readlines() pout.close() print '\n'.join(got) ---------listen.py----------- try: uh=raw_input("Write this through pipe: ") #Write this to stdin, so uh should have message except EOFError: print 'No message.' else: print uh ---------------------------------- Juan Shen ktpr wrote: >Hi all, > >I am trying to supply input to another program using >pipes. I can read from it just fine, but writing to >its stdin doesn't seem to be working. > >foo.py (gets pipe to listen.py) >--- >from popen2 import popen2 > >cmd = "listen.py" > >#stdout, stdin >r, w = popen2(cmd) > >w.write("Message sent") > >w.close() > >got = r.readlines() >r.close() > >for line in got: > print line > >--- >listen.py >--- >import sys > ># wrote to this stdin, so uh should have message >uh = raw_input("why doesn't it") > >if "" != uh: > print "go here?" > >if "" == uh: > print "or even here?" > >--- > >I know I'm missing something conceptual... > >I only get "why doesn't it" printed to the screen and >the message didn't seem to transfer across the pipe, >as listen.py aborted before the if statement somehow. >Any and all help would be appreciated; popen2._test() >works fine ... > >cheers >ktpr > >__________________________________________________ >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 > > > > From orion_val at 163.com Thu Dec 30 05:12:35 2004 From: orion_val at 163.com (=?GB2312?B?yfK94NSq?=) Date: Thu Dec 30 05:13:03 2004 Subject: [Tutor] How to put my functions in an array In-Reply-To: <1104347290.31902.28.camel@6-allhosts> References: <1104347290.31902.28.camel@6-allhosts> Message-ID: <41D38033.1090501@163.com> Hello, Mohamed Lrhazi wrote: >def addvirt(): > pass >def remvirt(): > pass > >PROVISION_ACTIONS=[('addvirt','Add Virt'),('remvirt','Remove Virt'),] >formhandlers={} > ># this works >formhandlers["addvirt"]=addvirt >formhandlers["remvirt"]=remvirt > ># this does not work: >for verb,verb_desc in PROVISION_ACTIONS: > if callable(verb): > > #### Here is the bug, verb here is a string, not a function entry. callable(Function) will return True. callable(String) always returns False. > formhandlers[verb]=verb > >I tried a few different syntaxes but to no avail... do I need things >like: getattr()? > >Thanks alot >Mohamed~ > I hope this will meet your needs in a clear way: def addvirt(): pass def remvirt(): pass PROVISION_ACTIONS=[(addvirt,'Add Virt'),(remvirt,'Remove Virt')] formhandlers={} for (verb,verb_descr) in PROVISION_ACTIONS: if callable(verb): formhandlers[verb.__name__]=verb From rmkrauter at yahoo.com Thu Dec 30 07:06:10 2004 From: rmkrauter at yahoo.com (Rich Krauter) Date: Thu Dec 30 07:06:14 2004 Subject: [Tutor] How to substitute an element of a list as a pattern for re.compile() Message-ID: <41D39AD2.9030506@yahoo.com> kumar s wrote: > I have Question: > How can I substitute an object as a pattern in making > a pattern. > >>>> x = 30 >>>> pattern = re.compile(x) > Kumar, You can use string interpolation to insert x into a string, which can then be compiled into a pattern: x = 30 pat = re.compile('%s'%x) I really doubt regular expressions will speed up your current searching algorithm. You probably need to reconsider the data structures you are using to represent your data. > I have a list of numbers that I have to match in > another list and write them to a new file: > > List 1: range_cors >>>> range_cors[1:5] > ['161:378', '334:3', '334:4', '65:436'] > > List 2: seq >>>> seq[0:2] > ['>probe:HG-U133A_2:1007_s_at:416:177; > Interrogation_Position=3330; Antisense;', > 'CACCCAGCTGGTCCTGTGGATGGGA'] > > Can you re-process your second list? One option might be to store that list instead as a dict, where the keys are what you want to search by (maybe a string like '12:34' or a tuple like (12,34)). Maybe something like the following: >>> range_cors = ['12:34','34:56'] >>> seq = {'12:34': ['some 12:34 data'], ... '34:56': ['some 34:56'data','more 34:56 data']} >>> for item in range_cors: ... print seq[item] ... ['some 12:34 data'] ['some 34:56 data','more 34:56 data'] Why is this better? If you have m lines of data and n patterns to search for, then using either of your methods you perform n searches per line, totalling approx. m*n operations. You have to complete approx. m*n operations whether you use the string searching version, or re searching version. If you pre-process the data so that it can be stored in and retrieved from a dict, pre-processing to get your data into that dict costs you roughly m operations, but your n pattern lookups into that dict cost you only n operations, so you only have to complete approx. m+n operations. > A slow method: >>>> sequences = [] >>>> for elem1 in range_cors: > for index,elem2 in enumerate(seq): > if elem1 in elem2: > sequences.append(elem2) > sequences.append(seq[index+1]) > > A faster method (probably): > >>>> for i in range(len(range_cors)): > for index,m in enumerate(seq): > pat = re.compile(i) > if re.search(pat,seq[m]): > p.append(seq[m]) > p.append(seq[index+1]) > > I am getting errors, because I am trying to create an > element as a pattern in re.compile(). > pat = re.compile('%s'%i) would probably get rid of the error message, but that's probably still not what you want. > > Questions: > > 1. Is it possible to do this. If so, how can I do this. You can try, but I doubt regular expressions will help; that approach will probably be even slower. > Can any one help correcting my piece of code and > suggesting where I went wrong. I would scrap what you have and try using a better data structure. I don't know enough about your data to make more specific processing recommendations; but you can probably avoid those nested loops with some careful data pre-processing. You'll likely get better suggestions if you post a more representative sample of your data, and explain exactly what you want as output. Good luck. Rich From alan.gauld at freenet.co.uk Thu Dec 30 09:00:41 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Dec 30 08:59:47 2004 Subject: [Tutor] How to put my functions in an array References: <1104347290.31902.28.camel@6-allhosts> Message-ID: <01e101c4ee45$a9d3ca40$f7b08851@xp> I'm not sure what exa ctly you are trying to do here, but I'll take a guess. > def addvirt(): pass > def remvirt(): pass > PROVISION_ACTIONS=[('addvirt','Add Virt'),('remvirt','Remove Virt'),] Not sure why you have the list of tuples of strings, but it shouldn't be a problem. > formhandlers={} > > # this works > formhandlers["addvirt"]=addvirt > formhandlers["remvirt"]=remvirt So now you have a dictionary keyed by verb and holding the functions. > # this does not work: > for verb,verb_desc in PROVISION_ACTIONS: > if callable(verb): your verbs are strings so they won't be callable. > formhandlers[verb]=verb and this overwrites the function with the string??? I think what you might want is: for verb,verb_desc in PROVISION_ACTIONS: formhandlers[verb]() which calls each of the functions in turn. However considering the message subject says you want the functions in an array, you could do that with: myarray = [addvirt, remvirt] and iterate over it with: for action in myarray: action() I'm not sure I've answered your question but I hope it helps! Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld From alan.gauld at freenet.co.uk Thu Dec 30 09:08:05 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Dec 30 09:07:10 2004 Subject: [Tutor] How to put my functions in an array References: <1104347290.31902.28.camel@6-allhosts><41D3076A.6030600@ccvcorp.com> <1104349822.31902.37.camel@6-allhosts> Message-ID: <01ea01c4ee46$b12e9d00$f7b08851@xp> > Thanks alot Jeff. This worked for me: > > formhandlers={} > for verb,verb_desc in PROVISION_ACTIONS: > try: > formhandlers[verb]=globals()[verb] > except KeyError: > pass I'm slightly confused about why you need to do this? You create a list of names (PROVISION_ACTIONS), then you add the corresponding functions to a dictionary by looking the names up in the globals dictionary. But since uyou know the names of the functions why not just add them to the actions list in the first place? PROVISION_ACTIONS = [('foo',foo),('bar',bar)] formhandlers = {} for name,action in PROVISION_ACTIONS: formhandlers[name] = action Or even easier do it all in one step: formhandlers = { 'foo':foo, 'bar',bar, etc... } Why do you need the globals lookup when you know the names of the functions already? I'm missing something... Alan G. From alan.gauld at freenet.co.uk Thu Dec 30 09:15:10 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Thu Dec 30 09:14:36 2004 Subject: [Tutor] (no subject) References: <20041212055504.6630.qmail@web50709.mail.yahoo.com> Message-ID: <01fb01c4ee47$b6e07ab0$f7b08851@xp> > I am trying to supply input to another program using > pipes. I can read from it just fine, but writing to > its stdin doesn't seem to be working. I'm guessing here so take with a pinch of salt... > cmd = "listen.py" > > #stdout, stdin > r, w = popen2(cmd) > > w.write("Message sent") I think you need a newline on the end otherwise raw_input will not see it. HTH, Alan G. From ewald.ertl at hartter.com Thu Dec 30 09:46:43 2004 From: ewald.ertl at hartter.com (Ewald Ertl) Date: Thu Dec 30 09:46:46 2004 Subject: [Tutor] O.T. In-Reply-To: <000501c4ec5b$6ec59c80$8c5428cf@JSLAPTOP> References: <000501c4ec5b$6ec59c80$8c5428cf@JSLAPTOP> Message-ID: <20041230094643.00000669@sunray1> Hi! I#m 33, married, 2 Children ( 9 months old girl & 3 year old boy ). We are living in the south of Burgenland in Austria. My mother tounge is german. I attended a secondary technical school studed electronics. After school I started working for a big company creating a power system control system delivering all over the world. There I had my first contact to SunOS/Unix. Now I work for a small company delivering software for the financial sector. I'm using SunRay's in work. programming languages: C/C++, a little bit java, ksh and very long ago asm, Turbo Pascal, fortran, perl I'm doing Sys-Admin, network-admin, mail-admin and also development in our own middle-ware, providing the access to corebanking-system and other low-level technical connections and functions. Wish you all a happy new year Ewald From revanna at mn.rr.com Thu Dec 30 11:10:52 2004 From: revanna at mn.rr.com (Anna Ravenscroft) Date: Thu Dec 30 11:11:00 2004 Subject: [Tutor] O.T. In-Reply-To: <000501c4ec5b$6ec59c80$8c5428cf@JSLAPTOP> References: <000501c4ec5b$6ec59c80$8c5428cf@JSLAPTOP> Message-ID: <41D3D42C.4080401@mn.rr.com> Jacob S. wrote: > I hate to sound weird... Too late. ;-) Join the crowd! Anna Martelli Ravenscroft 42, 2 children (13 and 11) live with their dad Married this July to the martelli-bot (we read The Zen of Python at our wedding!). We currently live in Bologna, Italy. Started learning Python in 2002 because I was bored to tears at my job as an Instruction Administrator. I'm not a progammer - I just use Python to get stuff done (and cuz it's fun!) I love that it is useful without having to become a hermit for 4 years studying the syntax. Before that, I had worked with computers as a "power" user and NT admin, and long long ago had programmed a little in Basic (on my beloved Commodore 64) and even learned a little Pascal back in College... My background is in training and coaching, as well as office administration to pay the bills. I do presentations and editing as well. Other interests include weightlifting, bicycling, reading, cooking. We went hiking in the Italian Alps for our honeymoon and I fell in love with the mountains! Great question. Nice to get to know the other folks on the list a little. From mohamed at your-site.com Thu Dec 30 14:40:25 2004 From: mohamed at your-site.com (Mohamed Lrhazi) Date: Thu Dec 30 14:47:09 2004 Subject: [Tutor] How to put my functions in an array In-Reply-To: <01ea01c4ee46$b12e9d00$f7b08851@xp> References: <1104347290.31902.28.camel@6-allhosts> <41D3076A.6030600@ccvcorp.com> <1104349822.31902.37.camel@6-allhosts> <01ea01c4ee46$b12e9d00$f7b08851@xp> Message-ID: <1104414025.4554.188.camel@6-allhosts> On Thu, 2004-12-30 at 03:08, Alan Gauld wrote: > > I'm slightly confused about why you need to do this? > You create a list of names (PROVISION_ACTIONS), then > you add the corresponding functions to a dictionary > by looking the names up in the globals dictionary. > But since uyou know the names of the functions why > not just add them to the actions list in the first place? Alan, I know I know... I dont know what am doing :) I am writing a little web application, with my PHP brain... uri's like: ?action=addvirt ?action=remvirt and so on.... In PHP, I'd have a swtich action, case 'addvirt': addvirt() I know Python can do better, so I wanted to replace that huge if elif elif... with: if we have a handler for the action, duh, call the action... so in a module (a file) I have all these functions defined... at the end of that file, I have: formhandlers={} for verb in ('addvirt','remvirt',): try: formhandlers[verb]=globals()[verb] except KeyError pass Now in my Nevow code where I handle the incoming request: if action: try: return formhandlers[action](context) except KeyError: return T.div(_class='error')['Unsupported Action Requested: %s'%action] I realize now that I dont even need a array(dictionary) to hold the references to my fucntions... they are always there, and I can try to access them anytime, except for KeyErrors where I'd know I did not write that handler yet :) Thanks all... Mohamed~ From AKolinski at nriindustries.com Thu Dec 30 16:03:44 2004 From: AKolinski at nriindustries.com (Andrzej Kolinski) Date: Thu Dec 30 16:04:04 2004 Subject: [Tutor] O.T. In-Reply-To: <007101c4ecc2$8c461430$f7b08851@xp> Message-ID: I'm 60 years old living in Toronto in a very happy relationship with my second wife, 3 children, 2 grandchildren from the first marriage. Never programmed before hoping that I will sometimes in the (near) future. I love Python, but my problem is that I have never gone through the rigid logic of the computer programming. Nevertheless I am using Python to process our bridge club (www.blotka.ca - beware, in Polish) documentation. The way I've done it so far is that I have "stolen"/adopted/modified existing and available Python scripts. Hobbies: duplicate bridge, music (piano, flute - classical, jazz), old house renovation :-(. Work: a midsize rubber company (product/process engineering - finite element analysis). Background: M. Chem Eng. from the Gdansk Technical University, PhD. (Mechanics of Polymers) from the Institute of Fundamental Technical Research in Warsaw. _/_/ _/ _/ _/ _/ _/ _/ _/_/_/_/ _/_/ _/ _/ _/ _/ _/ _/ _/ _/ Andrzej Kolinski -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20041230/18985d63/attachment.html From pierre.barbier at cirad.fr Thu Dec 30 17:41:21 2004 From: pierre.barbier at cirad.fr (Pierre Barbier de Reuille) Date: Thu Dec 30 17:39:31 2004 Subject: [Tutor] leastsquares.py In-Reply-To: <01a601c4edf6$1e953850$f7b08851@xp> References: <41C3F92B@wm2.uvic.ca> <01a601c4edf6$1e953850$f7b08851@xp> Message-ID: <41D42FB1.3090804@cirad.fr> Alan Gauld a ?crit : >>I am trying to use a least squares method (the one written by Konrad > > Hinsen), > >>but I do not want the method to be able to generate negative values. > > Is there > >>a way to stop least squares programs from doing so? > > > def _leastSquare(): > # do the thing that might generate negatives > > def leastSquare(): > firstTry = _leastSquare() > if firstTry < 0: > return leastSquare() # try again > else: > return firstTry > > Primitive but it works. If you want more a efficient/elegant solution > show us what you have... How is this suppose to work ? Most of the least square algorithm find the nearest local minimum of the distance function. So, if you call many times the least square function without changing the initial values it will do absolutely nothing ! Or what do you suppose for your least square method ? > > Alan G. > > _______________________________________________ > 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 77 fax : (33) 4 67 61 56 68 From kent37 at tds.net Thu Dec 30 19:02:35 2004 From: kent37 at tds.net (Kent Johnson) Date: Thu Dec 30 19:02:43 2004 Subject: [Tutor] Using the =?ISO-8859-1?Q?=A3_symbol?= In-Reply-To: <20041228222122.6757.qmail@web25404.mail.ukl.yahoo.com> References: <20041228222122.6757.qmail@web25404.mail.ukl.yahoo.com> Message-ID: <41D442BB.1060201@tds.net> The problem is that you typed an actual '?' into your program text. The compiler is complaining because, absent an explicit encoding declaration, it expects the text to be ascii. I think there are two ways to solve this: - write the string with '\xc2' instead of '?'; it has the same meaning - put the coding declaration as described in PEP 263 You don't say what OS or locale you are using, but since your email is in UK probably you want # -*- coding: iso-8859-1 -*- Kent David Holland wrote: > I am trying to use a program that usea s '?' symbolon > the pygame screen and I get this message :- > 'sys:1: DeprecationWarning: Non-ASCII character '\xc2' > in file birdgame29e.py on line 88, but no encoding > declared; see http://www.python.org/peps/pep-0263.html > for details > line 86 > ' > > Now I did look that however I am not sure a) how to do > this and b) what encoding to use. Can anyone help ? > > > > > > ___________________________________________________________ > ALL-NEW Yahoo! Messenger - all new features - even more fun! http://uk.messenger.yahoo.com > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From kent37 at tds.net Thu Dec 30 19:28:16 2004 From: kent37 at tds.net (Kent Johnson) Date: Thu Dec 30 19:28:23 2004 Subject: [Tutor] How to substitute an element of a list as a pattern for re.compile() In-Reply-To: <20041230010123.91028.qmail@web53709.mail.yahoo.com> References: <20041230010123.91028.qmail@web53709.mail.yahoo.com> Message-ID: <41D448C0.1090405@tds.net> kumar s wrote: > My situation: > > I have a list of numbers that I have to match in > another list and write them to a new file: > > List 1: range_cors > >>>>range_cors[1:5] > > ['161:378', '334:3', '334:4', '65:436'] > > List 2: seq > >>>>seq[0:2] > > ['>probe:HG-U133A_2:1007_s_at:416:177; > Interrogation_Position=3330; Antisense;', > 'CACCCAGCTGGTCCTGTGGATGGGA'] > > > A slow method: > >>>>sequences = [] >>>>for elem1 in range_cors: > > for index,elem2 in enumerate(seq): > if elem1 in elem2: > sequences.append(elem2) > sequences.append(seq[index+1]) > > This process is very slow and it is taking a lot of > time. I am not happy. It looks like you really only want to search every other element of seq. You could speed your loop up by using an explicit iterator: for elem1 in range_cors: i = iter(seq) try: tag, data = i.next(), i.next() if elem1 in tag: sequences.append(tag) sequences.append(data) except StopIteration: pass You don't say how long the sequences are. If range_cors is short enough you can use a single regex to do the search. (I don't actually know how short range_cors has to be or how this will break down if it is too long; this will probably work with 100 items in range_cors; it may only be limited by available memory; it may become slow to compile the regex when range_cors gets too big...) This will eliminate your outer loop entirely and I expect a substantial speedup. The code would look like this: >>> range_cors = ['161:378', '334:3', '334:4', '65:436'] Make a pattern by escaping special characters in the search string, and joining them with '|': >>> pat = '|'.join(map(re.escape, range_cors)) >>> pat '161\\:378|334\\:3|334\\:4|65\\:436' >>> pat = re.compile(pat) Now you can use pat.search() to find matches: >>> pat.search('123:456') >>> pat.search('aaa161:378') <_sre.SRE_Match object at 0x008DC8E0> The complete search loop would look like this: i = iter(seq) try: tag, data = i.next(), i.next() if pat.search(tag): sequences.append(tag) sequences.append(data) except StopIteration: pass Kent > > > > A faster method (probably): > > >>>>for i in range(len(range_cors)): > > for index,m in enumerate(seq): > pat = re.compile(i) > if re.search(pat,seq[m]): > p.append(seq[m]) > p.append(seq[index+1]) > > > I am getting errors, because I am trying to create an > element as a pattern in re.compile(). > > > Questions: > > 1. Is it possible to do this. If so, how can I do > this. > > Can any one help correcting my piece of code and > suggesting where I went wrong. > > Thank you in advance. > > > -K > > > __________________________________________________ > 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 > From jmillr at umich.edu Thu Dec 30 19:31:11 2004 From: jmillr at umich.edu (John Miller) Date: Thu Dec 30 19:31:19 2004 Subject: [Tutor] moving widgets around In-Reply-To: <20041229212548.2D4C61E400C@bag.python.org> References: <20041229212548.2D4C61E400C@bag.python.org> Message-ID: I recently had occasion for drag 'n drop functionality in Tkinter, and after much searching around decided that tkdnd.py was the only viable solution (at least, that I could find). The code is actually quite understandable (well, at the 'large chunks' level). In the directory where tkdnd.py is located simply type: pythonw tkdnd.py and it will work. If you find anything simpler or more bare bones, please let us know. John Miller On Dec 29, 2004, at 4:25 PM, Sean McIlroy wrote: > I'd like to get some example code showing how to move > widgets around in drag-and-drop fashion. I've tried > looking at tkDND.py (I think that's what it's called) > but that was a little involved - what I want to know > is the barest of bare bones. Any help would be majorly > fabulous. Merci beaucoup. > > STM From mdcooper at uvic.ca Thu Dec 30 22:20:02 2004 From: mdcooper at uvic.ca (mdcooper) Date: Thu Dec 30 22:20:38 2004 Subject: [Tutor] leastsquares.py Message-ID: <41D477C3@wm2.uvic.ca> Hi Pierre, you are correct - the methods that simply refuse negative results will not be sufficient. The code I have so far is attached as *.py files. Thanks, Matt Be aware that I have adusted _lsq2.py so that it can be shown to the world - it still contains a basic outline of what should be done but it may not look too efficient. >===== Original Message From Pierre Barbier de Reuille ===== >Alan Gauld a ?crit : >>>I am trying to use a least squares method (the one written by Konrad >> >> Hinsen), >> >>>but I do not want the method to be able to generate negative values. >> >> Is there >> >>>a way to stop least squares programs from doing so? >> >> >> def _leastSquare(): >> # do the thing that might generate negatives >> >> def leastSquare(): >> firstTry = _leastSquare() >> if firstTry < 0: >> return leastSquare() # try again >> else: >> return firstTry >> >> Primitive but it works. If you want more a efficient/elegant solution >> show us what you have... > >How is this suppose to work ? Most of the least square algorithm find >the nearest local minimum of the distance function. So, if you call many >times the least square function without changing the initial values it >will do absolutely nothing ! Or what do you suppose for your least >square method ? > >> >> Alan G. >> >> _______________________________________________ >> 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 77 fax : (33) 4 67 61 56 68 > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor -------------- next part -------------- A non-text attachment was scrubbed... Name: _lsq2.py Type: application/octet-stream Size: 2052 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20041230/03292787/_lsq2-0001.obj -------------- next part -------------- A non-text attachment was scrubbed... Name: LeastSquares.py Type: application/octet-stream Size: 4139 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20041230/03292787/LeastSquares-0001.obj From alan.gauld at freenet.co.uk Fri Dec 31 00:54:34 2004 From: alan.gauld at freenet.co.uk (Alan Gauld) Date: Fri Dec 31 00:54:24 2004 Subject: [Tutor] leastsquares.py References: <41C3F92B@wm2.uvic.ca> <01a601c4edf6$1e953850$f7b08851@xp> <41D42FB1.3090804@cirad.fr> Message-ID: <002701c4eeca$ea36a230$b0928651@xp> > > def _leastSquare(): > > # do the thing that might generate negatives > > > > def leastSquare(): > > firstTry = _leastSquare() > > if firstTry < 0: > > return leastSquare() # try again > > else: > > return firstTry > > > > Primitive but it works. If you want more a efficient/elegant solution > > show us what you have... > > How is this suppose to work ? Most of the least square algorithm find > the nearest local minimum of the distance function. So, if you call many > times the least square function without changing the initial values it > will do absolutely nothing ! The _leastSquare() function is whatever you do at the moment that generates negative values. How it gets the data to produce those values is up to you, they could be parameters, global or from a file. The leastSquare() function simply keeps on calling _leastSquare until a positive value is returned. It assumes that _leastSquare is somehow modifying its environment(eg by changing the data set) to return different values... > Or what do you suppose for your least square method ? Its not mine, its yours! :-) The point was that without knowing exactly how you have coded your algorithm we can't give sensible solutions to avoiding negatives! Alan G. From tegmine at gmail.com Fri Dec 31 02:00:14 2004 From: tegmine at gmail.com (Luis N) Date: Fri Dec 31 02:02:12 2004 Subject: [Tutor] cgi.FieldStorage and dictionary.get(' ') Message-ID: <77bfa81a04123017004205e7de@mail.gmail.com> Hi, I've passed this through the interperter line-by-line, yet still can't get it to work right. The first time the cgi driver script initiates it runs the login function which renders a zpt. Upon submission of their vitals, the user is authenticated via sqlobject, and if they pass the chapters function should run. However, what I get is zip, zilch, nada. Just a blank page, with the query string appended to the url. def main(form): if form.has_key('author') and form.has_key('password'): q = Users.select(AND(Users.q.author==form.get('author'), Users.q.password==form.get('password'))) if len(list(q))>0: chapters(author=form.get('author')) else: login(failure=True) else: login(failure=False) Out of curiosity I wrote a simple test cgi. #!/usr/local/bin/python print 'Content-type: text/plain\n\n' import cgi form = cgi.FieldStorage() if form.has_key('author') and form.has_key('password'): print form.keys() print form.get('author') print form.get('password') Strangely, the calls to print form.get('author') and form.get('password') don't appear in the output. Only the form.keys() appears. Additionally, why doesn't def main(form=cgi.FieldStorage()) work, I tried to do it as so, thinking it more graceful, and it floundered. From tim at johnsons-web.com Fri Dec 31 03:06:02 2004 From: tim at johnsons-web.com (Tim Johnson) Date: Fri Dec 31 03:01:48 2004 Subject: [Tutor] O.T. In-Reply-To: <000501c4ec5b$6ec59c80$8c5428cf@JSLAPTOP> References: <000501c4ec5b$6ec59c80$8c5428cf@JSLAPTOP> Message-ID: <20041231020602.GL2607@johnsons-web.com> * Jacob S. [041228 01:42]: > But who are you all, what are you're ages, what do you do, marriage status, > etc? I'm 55. 6 grown kids. 1 grandchild and another on the way. Been programming for 17 years, started in vax basic and assembler for the pdp-11. I've also worked as commercial fisherman, park ranger, agronomist and surveyor. I started learning python about 4 years ago, when I was asked to design and implement an online high school class on intro to programming and program design. I used rebol for the first semester and python for the second. Alan Gauld's book was (and I believe still is) the textbook for the second semester. I'm self-employed and work at home. My wife is a retired physical therapist. I use rebol and python about equally and C now only when I really have to. Lately have been learning lisp and emacs. Although I have no intentions of giving up python and vim. I run both linux and windows concurrently on my work station so I guess I "swing both ways" when it comes to OS'es. Hobbies are gardening, landscaping, brewing beer, hiking and generally puttering 'round my property. Happy New Year Jacob and the rest of you too. tim -- Tim Johnson http://www.alaska-internet-solutions.com From patric at usa.net Fri Dec 31 07:58:14 2004 From: patric at usa.net (Patric Michael) Date: Fri Dec 31 07:56:20 2004 Subject: [Tutor] cgi.FieldStorage and dictionary.get(' ') In-Reply-To: <77bfa81a04123017004205e7de@mail.gmail.com> Message-ID: <41D48806.21679.661FAA@localhost> > Hi, > > I've passed this through the interperter line-by-line, yet still can't > get it to work right. > > The first time the cgi driver script initiates it runs the login > function which renders a zpt. Upon submission of their vitals, the I'm not sure what a zpt is, but it sounds like the form to request the vitals, so that's a start. :) > user is authenticated via sqlobject, and if they pass the chapters > function should run. However, what I get is zip, zilch, nada. Just a > blank page, with the query string appended to the url. First off, make sure that you have the "Content-Type: text/html\n\n" line print before anything else whenever you send output to the web. Presumably it worked for the form display, but you have to keep resending it each time the page changes. > def main(form): > if form.has_key('author') and form.has_key('password'): > q = Users.select(AND(Users.q.author==form.get('author'), > Users.q.password==form.get('password'))) > if len(list(q))>0: > chapters(author=form.get('author')) > else: > login(failure=True) > else: > login(failure=False) Without seeing the def for login(failure), and not being familiar with SQL, I'll take a pass on these lines, but I am curious why you declare failure as true or false in the login function? > > Out of curiosity I wrote a simple test cgi. > > #!/usr/local/bin/python > > print 'Content-type: text/plain\n\n' > > import cgi > > form = cgi.FieldStorage() > if form.has_key('author') and form.has_key('password'): > print form.keys() > print form.get('author') > print form.get('password') Instead of form.get(), try this: print form['author'].value print form['password'].value Working with cgi scripts is always a bit tricky because of the added variable of the server displaying the page, so I define this little function on anything I am working on: from sys import stderr # Unix only! def s(msg): s = stderr.write # Sends messages to the error log via s() s(msg + '\n') # adds a carriage return :) Someone else more versed than I could probably tell you if there is a windows equivalent, but what I do is open another shell and tail -f the error log while I test the script. Any errors or tracebacks appear there anyway, and I can add little notes between functions to see where the thing breaks down. Especially handy to "pre-display" the expected output to make sure I get what I expect, and its not the web server that's eating the result or something. > > Strangely, the calls to print form.get('author') and > form.get('password') don't appear in the output. Only the form.keys() > appears. > > Additionally, why doesn't def main(form=cgi.FieldStorage()) work, I > tried to do it as so, thinking it more graceful, and it floundered. I am not sure about this, but I've always put the form = cgi.Fieldstorage in the global namespace so I could get at it with subsequent functions. I am guessing that your version didn't work because the form namespace isnt getting filled with cgi.Fieldstorage --before-- the function is defined. Remember python tries to look through all the defs and make sure they are syntactically correct before actually running the script. You probably got an AttributeError, right? Patric OBTW... the .value method might be superceded by newer versions of python. I am not well versed on all the changes in 2.4 yet. :) > _______________________________________________ Tutor maillist - > Tutor@python.org http://mail.python.org/mailman/listinfo/tutor > From patric at usa.net Fri Dec 31 08:12:55 2004 From: patric at usa.net (Patric Michael) Date: Fri Dec 31 08:10:59 2004 Subject: [Tutor] O.T. In-Reply-To: <000501c4ec5b$6ec59c80$8c5428cf@JSLAPTOP> Message-ID: <41D48B77.3724.738FC0@localhost> Hi Jacob... > But who are you all, what are you're ages, what do you do, marriage > status, etc? You obviously don't have to answer, I'm just curious who > I'm boldly sending emails to. I figure since I bit the bullet and actually posted a reply, I best answer this as well in the faint hope of why I don't answer much... :) I'm 43 (just), no kids, no wife, no life. I work in entertainment and you'll have seen any number of things I've worked on, but you wont ever see me in the credits. I barely survived high school so college was out of the question. I started in BASIC on a TI99 4a. Learned DOS on an IBM 8088. Unix was next and now I manage a few servers. I got into python (I am by no means fluent) because I tried writing cgi scripts in perl and got dizzy. It also reminds me of mushcode, which I am pretty good at. I know just enough LISP to get myself in trouble because I am utterly fascinated with the idea of AI. Cheers! Patric > > Jacob Schmidt > > P.S. > I'm a student. 14 years. Play the piano better than I write scripts. > Single. etc. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From klappnase at freenet.de Fri Dec 31 16:01:10 2004 From: klappnase at freenet.de (Michael Lange) Date: Fri Dec 31 15:59:41 2004 Subject: [Tutor] O.T. In-Reply-To: <20041231020602.GL2607@johnsons-web.com> References: <000501c4ec5b$6ec59c80$8c5428cf@JSLAPTOP> <20041231020602.GL2607@johnsons-web.com> Message-ID: <20041231160110.51e519e8.klappnase@freenet.de> > * Jacob S. [041228 01:42]: > > But who are you all, what are you're ages, what do you do, marriage status, > > etc? 37, no kids but a girlfriend with a cat. I work at a clinical laboratory in a hospital in germany. I'm just a hobby programmer and started with python about 2 years ago; I chose python as my first (and yet only) language because I happened to find a cheap german version of Ivan van Laningham's "Teach yourself python in 24 hours" in a local bookstore when I was looking for something to start with. The book had a sticker on it that said something like "No programming knowledge required!" which looked very promising to me back then. A happy new year to all of you Michael From davholla2002 at yahoo.co.uk Fri Dec 31 17:16:35 2004 From: davholla2002 at yahoo.co.uk (David Holland) Date: Fri Dec 31 17:16:37 2004 Subject: [Tutor] OT In-Reply-To: <20041231110122.3F2EF1E4011@bag.python.org> Message-ID: <20041231161635.52669.qmail@web25406.mail.ukl.yahoo.com> I am 31 married, living in London UK. I can play guitar but I am not that good. I work in IT as Oracle support but the only languages I know apart from basic python is basic PL/SQL and of course SQL. Of course I know how to use various Oracle applications. I studied Chemistry but sadly there were no jobs so I moved in IT. ___________________________________________________________ ALL-NEW Yahoo! Messenger - all new features - even more fun! http://uk.messenger.yahoo.com From davholla2002 at yahoo.co.uk Fri Dec 31 17:28:59 2004 From: davholla2002 at yahoo.co.uk (David Holland) Date: Fri Dec 31 17:29:02 2004 Subject: [Tutor] =?iso-8859-1?q?ASCII_encoding_for_a_=A3_sign?= In-Reply-To: <20041231110122.3F2EF1E4011@bag.python.org> Message-ID: <20041231162859.54839.qmail@web25406.mail.ukl.yahoo.com> I ran a program with a "?" sign, and I got this message :- "sys:1: DeprecationWarning: Non-ASCII character '\xc2' in file birdgame32a.py on line 93, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details' I looked at the message but I am not sure what encoding to use for "?". ___________________________________________________________ ALL-NEW Yahoo! Messenger - all new features - even more fun! http://uk.messenger.yahoo.com From davholla2002 at yahoo.co.uk Fri Dec 31 17:42:10 2004 From: davholla2002 at yahoo.co.uk (David Holland) Date: Fri Dec 31 17:42:12 2004 Subject: [Tutor] =?iso-8859-1?q?Fwd=3A_ASCII_encoding_for_a_=A3_sign?= Message-ID: <20041231164210.49306.qmail@web25403.mail.ukl.yahoo.com> Apologies, I did not see that Kent had already answered this ! Thanks Kent I put that encoding and it works fine. Although surprisingly the other idea :- write the string with '\xc2' did not work. --- David Holland wrote: > Date: Fri, 31 Dec 2004 16:28:59 +0000 (GMT) > From: David Holland > Subject: ASCII encoding for a ? sign > To: tutor@python.org > > I ran a program with a "?" sign, and I got this > message :- > > "sys:1: DeprecationWarning: Non-ASCII character > '\xc2' > in file birdgame32a.py on line 93, but no encoding > declared; see > http://www.python.org/peps/pep-0263.html > for details' > I looked at the message but I am not sure what > encoding to use for "?". > > > > > > ___________________________________________________________ > > ALL-NEW Yahoo! Messenger - all new features - even > more fun! http://uk.messenger.yahoo.com > ___________________________________________________________ ALL-NEW Yahoo! Messenger - all new features - even more fun! http://uk.messenger.yahoo.com From ps_python at yahoo.com Fri Dec 31 23:15:42 2004 From: ps_python at yahoo.com (kumar s) Date: Fri Dec 31 23:15:46 2004 Subject: [Tutor] Parsing a block of XML text Message-ID: <20041231221543.64372.qmail@web53707.mail.yahoo.com> Dear group: I am trying to parse BLAST output (Basic Local Alignment Search Tool, size around more than 250 KB ). - 1 gi|43442325|emb|BX956931.1| DKFZp781D1095_r1 781 (synonym: hlcc4) Homo sapiens cDNA clone DKFZp781D1095 5', mRNA sequence. BX956931 693 - - 1 1164.13 587 0 1 587 107 693 1 1 587 587 587 GGACCTCTCCAGAATCCGGATTGCTGAATCTTCCCTGTTGCCTAGAAGGGCTCCAAACCACCTCTTGACAATGGGAAACTGGGTGGTTAACCACTGGTTTTCAGTTTTGTTTCTGGTTGTTTGGTTAGGGCTGAATGTTTTCCTGTTTGTGGATGCCTTCCTGAAATATGAGAAGGCCGACAAATACTACTACACAAGAAAAATCCTTGGGTCAACATTGGCCTGTGCCCGAGCGTCTGCTCTCTGCTTGAATTTTAACAGCACGCTGATCCTGCTTCCTGTGTGTCGCAATCTGCTGTCCTTCCTGAGGGGCACCTGCTCATTTTGCAGCCGCACACTGAGAAAGCAATTGGATCACAACCTCACCTTCCACAAGCTGGTGGCCTATATGATCTGCCTACATACAGCTATTCACATCATTGCACACCTGTTTAACTTTGACTGCTATAGCAGAAGCCGACAGGCCACAGATGGCTCCCTTGCCTCCATTCTCTCCAGCCTATCTCATGATGAGAAAAAGGGGGGTTCTTGGCTAAATCCCATCCAGTCCCGAAACACGACAGTGGAGTATGTGACATTCACCAGCA GGACCTCTCCAGAATCCGGATTGCTGAATCTTCCCTGTTGCCTAGAAGGGCTCCAAACCACCTCTTGACAATGGGAAACTGGGTGGTTAACCACTGGTTTTCAGTTTTGTTTCTGGTTGTTTGGTTAGGGCTGAATGTTTTCCTGTTTGTGGATGCCTTCCTGAAATATGAGAAGGCCGACAAATACTACTACACAAGAAAAATCCTTGGGTCAACATTGGCCTGTGCCCGAGCGTCTGCTCTCTGCTTGAATTTTAACAGCACGCTGATCCTGCTTCCTGTGTGTCGCAATCTGCTGTCCTTCCTGAGGGGCACCTGCTCATTTTGCAGCCGCACACTGAGAAAGCAATTGGATCACAACCTCACCTTCCACAAGCTGGTGGCCTATATGATCTGCCTACATACAGCTATTCACATCATTGCACACCTGTTTAACTTTGACTGCTATAGCAGAAGCCGACAGGCCACAGATGGCTCCCTTGCCTCCATTCTCTCCAGCCTATCTCATGATGAGAAAAAGGGGGGTTCTTGGCTAAATCCCATCCAGTCCCGAAACACGACAGTGGAGTATGTGACATTCACCAGCA ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| - I wanted to parse out : I wrote a ver small 4 line code to obtain it. for bls in doc.getElementsByTagName('Hsp_num'): bls.normalize() if bls.firstChild.data >1: print bls.firstChild.data This is not sufficient for me to get anything doen. Could any one help me directing how to get the elements in that tag. Thanks. -K __________________________________ Do you Yahoo!? Send holiday email and support a worthy cause. Do good. http://celebrity.mail.yahoo.com From ps_python at yahoo.com Fri Dec 31 23:15:50 2004 From: ps_python at yahoo.com (kumar s) Date: Fri Dec 31 23:15:53 2004 Subject: [Tutor] Parsing a block of XML text Message-ID: <20041231221550.76950.qmail@web53705.mail.yahoo.com> Dear group: I am trying to parse BLAST output (Basic Local Alignment Search Tool, size around more than 250 KB ). - 1 gi|43442325|emb|BX956931.1| DKFZp781D1095_r1 781 (synonym: hlcc4) Homo sapiens cDNA clone DKFZp781D1095 5', mRNA sequence. BX956931 693 - - 1 1164.13 587 0 1 587 107 693 1 1 587 587 587 GGACCTCTCCAGAATCCGGATTGCTGAATCTTCCCTGTTGCCTAGAAGGGCTCCAAACCACCTCTTGACAATGGGAAACTGGGTGGTTAACCACTGGTTTTCAGTTTTGTTTCTGGTTGTTTGGTTAGGGCTGAATGTTTTCCTGTTTGTGGATGCCTTCCTGAAATATGAGAAGGCCGACAAATACTACTACACAAGAAAAATCCTTGGGTCAACATTGGCCTGTGCCCGAGCGTCTGCTCTCTGCTTGAATTTTAACAGCACGCTGATCCTGCTTCCTGTGTGTCGCAATCTGCTGTCCTTCCTGAGGGGCACCTGCTCATTTTGCAGCCGCACACTGAGAAAGCAATTGGATCACAACCTCACCTTCCACAAGCTGGTGGCCTATATGATCTGCCTACATACAGCTATTCACATCATTGCACACCTGTTTAACTTTGACTGCTATAGCAGAAGCCGACAGGCCACAGATGGCTCCCTTGCCTCCATTCTCTCCAGCCTATCTCATGATGAGAAAAAGGGGGGTTCTTGGCTAAATCCCATCCAGTCCCGAAACACGACAGTGGAGTATGTGACATTCACCAGCA GGACCTCTCCAGAATCCGGATTGCTGAATCTTCCCTGTTGCCTAGAAGGGCTCCAAACCACCTCTTGACAATGGGAAACTGGGTGGTTAACCACTGGTTTTCAGTTTTGTTTCTGGTTGTTTGGTTAGGGCTGAATGTTTTCCTGTTTGTGGATGCCTTCCTGAAATATGAGAAGGCCGACAAATACTACTACACAAGAAAAATCCTTGGGTCAACATTGGCCTGTGCCCGAGCGTCTGCTCTCTGCTTGAATTTTAACAGCACGCTGATCCTGCTTCCTGTGTGTCGCAATCTGCTGTCCTTCCTGAGGGGCACCTGCTCATTTTGCAGCCGCACACTGAGAAAGCAATTGGATCACAACCTCACCTTCCACAAGCTGGTGGCCTATATGATCTGCCTACATACAGCTATTCACATCATTGCACACCTGTTTAACTTTGACTGCTATAGCAGAAGCCGACAGGCCACAGATGGCTCCCTTGCCTCCATTCTCTCCAGCCTATCTCATGATGAGAAAAAGGGGGGTTCTTGGCTAAATCCCATCCAGTCCCGAAACACGACAGTGGAGTATGTGACATTCACCAGCA ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| - I wanted to parse out : I wrote a ver small 4 line code to obtain it. for bls in doc.getElementsByTagName('Hsp_num'): bls.normalize() if bls.firstChild.data >1: print bls.firstChild.data This is not sufficient for me to get anything doen. Could any one help me directing how to get the elements in that tag. Thanks. -K __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From patric at usa.net Fri Dec 31 23:41:13 2004 From: patric at usa.net (Patric Michael) Date: Fri Dec 31 23:39:17 2004 Subject: [Tutor] cgi.FieldStorage and dictionary.get(' ') In-Reply-To: <77bfa81a04123110296d12286@mail.gmail.com> References: <41D48806.21679.661FAA@localhost> Message-ID: <41D56509.30345.3C5952D@localhost> Forwarded to the list... > On Thu, 30 Dec 2004 22:58:14 -0800, Patric Michael > wrote: > > First off, make sure that you have the "Content-Type: > text/html\n\n" > line print before anything else whenever you send > output to the web. > Presumably it worked for the form display, but > you have to keep resending it > each time the page changes. > > > Without seeing the def for login(failure), and not being familiar with > SQL, I'll take > a pass on these lines, but I am curious why you > declare failure as true or false in > the login function? > > Instead > of form.get(), try this: > > print form['author'].value > > print form['password'].value > > > Hi, > > def main(form): > if form.has_key('author') and form.has_key('password'): > author = form['author'].value > password = form['password'].value > q = Users.select(AND(Users.q.author==author, > Users.q.password==password)) > if len(list(q))>0: > chapters(author) > else: > login(failure=True) > else: > login(failure=False) > > Using form['author'].value works so long as it's assigned to a > variable before being looked up by sqlobject. This is interesting > because, if I try this from the interperter: > > >>> author = form['author'].value > Traceback (most recent call last): > File "", line 1, in ? > AttributeError: 'str' object has no attribute 'value' Right. If I recall correctly, the .value method is specific to the cgi module since FieldStorage() is actually a bunch of dictionaries contained in a list. The .value method shortcuts the need to extract the dictionary from the list, then extract the key/value pair from the result and lets you grab the value directly. (Someone correct me if I misremember this, please!) > > I define login(failure) as True or False because the first time the > user reaches the login page they shouldn't be presented with a failure > message. The second time round they should. Oh cool. I hadnt thought of that. I usually use a try: statement to test for one of the keys to determine whether the script sends the initial login form, or the login form with appropriate error messages prepended. That way I can explicitly indicate which field(s) need attention. > > Everything happens through a driver script: > > #!/usr/local/bin/python > > print 'Content-type: text/html\n\n' > > import cgi > from spanishlabs.gui import * > > if __name__ == '__main__': > main(form=cgi.FieldStorage()) > > Thanks for your help! > No problem! Patric From hugonz at h-lab.net Thu Dec 30 19:13:31 2004 From: hugonz at h-lab.net (hugonz@h-lab.net) Date: Thu Jan 6 08:27:26 2005 Subject: [Tutor] Comments appreciated In-Reply-To: <77bfa81a0412291251350fe4e9@mail.gmail.com> References: <77bfa81a0412291251350fe4e9@mail.gmail.com> Message-ID: <1478.200.75.140.126.1104430411.spork@webmail.h-lab.net> and just work with parameter passing. >> > > Lovely, thank you. I started a project that is for learning spanish > on-line, of currently 300 lines or so, that is proceeding rapidly > thanks to these lessons learned. Thank you Python Tutors, and thank > you Python! Hola Luis, I'd like to help with that if possible, please let me know privately how can that be done. Thanks, Hugo Gonz?lez Monteverde > > Cheers, > > Luis > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From hugonz at h-lab.net Fri Dec 31 05:03:16 2004 From: hugonz at h-lab.net (hugonz@h-lab.net) Date: Thu Jan 6 08:27:30 2005 Subject: [Tutor] cgi.FieldStorage and dictionary.get(' ') In-Reply-To: <77bfa81a04123017004205e7de@mail.gmail.com> References: <77bfa81a04123017004205e7de@mail.gmail.com> Message-ID: <4088.200.75.140.126.1104465796.spork@webmail.h-lab.net> > Strangely, the calls to print form.get('author') and > form.get('password') don't appear in the output. Only the form.keys() > appears. I don't have this on the top of my head, but I'm pretty sure you have to get the 'value' attribute, as in: print form.get('password').value do a dir (form.get('password')) and see what attributes are available... Hugo