Re: [Tutor] Trying to extract the last line of a text file
> Danny Yoo wrote: > > > > file('filename.txt').readlines()[-1] > Not to hijack the thread, but what stops you from just putting a > file.close() after your example line? > >>> Which file should file.close() close? The problem is that we don't > >>> have a handle on the particular file we want to close off. > >>> > >> Oh wow.. I totally missed that... nevermind.. ignore that question =D > > > > > > Hi Chris, > > > Wow, that seems like overkill when you can just write > f = open('filename.txt') > f.readlines() > f.close() > In CPython (the regular Python that we usually talk about here, > implemented in C) a file will be closed automatically as soon as there > are no references to the file because CPython garbage collects objects > immediately. This behaviour is not guaranteed by the language though and > it is different in Jython. > > > > > > This is similar in spirit to the idea of "autorelease" memory pools used > > by the Objective C language. We use some resource "manager" that does > > keep a handle on resources. That manager then has the power and > > responsiblity to call close() at some point. So one might imagine doing > > something like: > > > In Python 2.5 you can use with: to do this: > with open('filename.txt') as f: > f.readlines() > > f is guaranteed to be closed when the block exits. > Kent I made a small test about, what could happen with a file object, that was opened for read, but left without closing. # we need to put something into the test file >>> fw1 = open(r'test.txt', 'w') >>> fw1.write('written by fw1') >>> fw1.close() # so we have the test file # we can open and read from it >>> fr1 = open(r'test.txt', 'r') >>> fr1.readlines() ['written by fw1'] # I left it opened. # Another instance could be opened for read again >>> fr2 = open(r'test.txt', 'r') >>> fr2.readlines() ['written by fw1'] # I left the second instance opened eighter # Someone rewrite the content of the file >>> fw2 = open(r'test.txt', 'w') >>> fw2.write('written by fw2') >>> fw2.close() # I closed it correctly after writing # The instance opened for reading could be reread >>> fr1.seek(0) >>> fr1.readlines() ['written by fw2'] >>> fr2.readlines() [] # I have extended it a little >>> fw2 = open(r'test.txt', 'w') >>> fw2.write('written by fw2 but it is extended later') >>> fw2.close() >>> fr2.read() ' but it is extended later' >>> I feel that, we can left opened files with open(filename).readlines() in a number of times, but would be problematic to do it 100 000 times in the same script. Yours sincerely, __ Janos Juhasz ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] How to get the width of teh button widget..??
Folks, Sorry for asking you such a trivial question.!!! But i want to size up all the buttons with the same size as the largest one in the interface.. And thats why I am asking this question.. Regards, Asrarahmed -- To HIM you shall return. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to get the width of teh button widget..??
Asrarahmed Kadri wrote: > > > > Folks, > > Sorry for asking you such a trivial question.!!! But i want to size up > all the buttons with the same size as the largest one in the > interface.. And thats why I am asking this question.. Oops, in your hurry to send the e-mail you seem to have forgotten to tell us what GUI package you're using! HTH, -Luke ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] I need a time object from the future
I've been looking into this, and I am not understanding how to get this task done. I need to be able to look at a time object and know if it si between now and a set point 120 days in the future. I can get a value for now (currently I am using datetime.datetime.now()), but I haven't found a way to get now + 120 days, or figured out how to test if a given datetime falls between the two. Any pointers would be appreciated. Thanks. -- yours, William ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] need some class / module help
Hey there,I am trying to create a module with one classthe module name is group.pyit looks like this so farimport DbConnectorclass Group(object): def __init__(self, id): self.id = id con = DbConnector.DbConnector() query = con.getOne("select `name`, `position` from `groups` where `id` = '"+id+"' ") self.name = query[0] self.position = query[1] def set_position(position): self.position = position con.update("update `groups` set `position` = '"+self.position+"' where `id` = '"+self.id"' ") now lets say i wanted to do mygroup = Group.group(12)position = mygroup.position() # gives me position of group where id = 12mygroup.set_position(13) # changes value of position to 13is this right? i would test it here, but the database is not available. I am writing this to implement an easier way to code something very long later.Just wanted to know if i am on the right track.if you have read this far, thanks ! sk ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] I need a time object from the future
On Fri, October 20, 2006 8:55 am, William O'Higgins Witteman wrote: > I've been looking into this, and I am not understanding how to get > this task done. I need to be able to look at a time object and know > if it si between now and a set point 120 days in the future. I can > get a value for now (currently I am using datetime.datetime.now()), > but I haven't found a way to get now + 120 days, or figured out how > to test if a given datetime falls between the two. Any pointers > would be appreciated. Thanks. -- The time() function returns the current time in seconds, so one idea is adding the number of seconds for 120 days: >>> from time import time, ctime >>> help(time) Help on built-in function time: time(...) time() -> floating point number Return the current time in seconds since the Epoch. Fractions of a second may be present if the system clock provides them. >>> t1 = time() >>> t2 = t1 + 120*24*60*60 >>> now = time() >>> now > t1 and now < t2 True >>> ctime(t1) 'Fri Oct 20 09:09:26 2006' >>> ctime(t2) 'Sat Feb 17 08:09:26 2007' >>> ctime(now) 'Fri Oct 20 09:10:14 2006' -- Carlos Hanson ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] I need a time object from the future
On Fri, Oct 20, 2006 at 11:55:39AM -0400, William O'Higgins Witteman wrote: > I've been looking into this, and I am not understanding how to get this > task done. I need to be able to look at a time object and know if it si > between now and a set point 120 days in the future. I can get a value > for now (currently I am using datetime.datetime.now()), but I haven't > found a way to get now + 120 days, or figured out how to test if a given > datetime falls between the two. Any pointers would be appreciated. > Thanks. Take a look at mxDateTime: http://www.egenix.com/files/python/mxDateTime.html It provides arithmetic and comparison operations. Dave -- Dave Kuhlman http://www.rexx.com/~dkuhlman ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] need some class / module help
shawn bright wrote: Hey there, I am trying to create a module with one class the module name is group.py it looks like this so far import DbConnector class Group(object): def __init__(self, id): self.id = id con = DbConnector.DbConnector() query = con.getOne("select `name`, `position` from `groups` where `id` = '"+id+"' ") self.name = query[0] self.position = query[1] def set_position(position): self.position = position con.update("update `groups` set `position` = '"+self.position+"' where `id` = '"+self.id"' ") now lets say i wanted to do mygroup = Group.group(12) position = mygroup.position() # gives me position of group where id = 12 mygroup.set_position(13) # changes value of position to 13 Is this code in another module? If so you need: import group and mygroup = Group.group(12) should be (module name followed by class name) mygroup = group.Group(12). mygroup.position() # this is a call, and position is not callable. should be mygroup.position "select `name`, `position` from `groups` where `id` = '"+id+"' " is OK but an easier to read version is: "select `name`, `position` from `groups` where `id` = '%s'" % (id,) is this right? i would test it here, but the database is not available. I am writing this to implement an easier way to code something very long later. Just wanted to know if i am on the right track. if you have read this far, thanks ! sk ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Bob Gailer 510-978-4454 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] need some class / module help
Hey thanks for the help, yes, the class in in another file called group. the class Group is the only class in the module. I am doing this because the script that will call it is not the only place in all our scripts where it can be used. I have been doing stuff with python for over a year now, thought i would take advantage of some stuff that might save me some time. thanks againshawnOn 10/20/06, Bob Gailer <[EMAIL PROTECTED]> wrote: shawn bright wrote: Hey there, I am trying to create a module with one class the module name is group.py it looks like this so far import DbConnector class Group(object): def __init__(self, id): self.id = id con = DbConnector.DbConnector() query = con.getOne("select `name`, `position` from `groups` where `id` = '"+id+"' ") self.name = query[0] self.position = query[1] def set_position(position): self.position = position con.update("update `groups` set `position` = '"+self.position+"' where `id` = '"+self.id"' ") now lets say i wanted to do mygroup = Group.group(12) position = mygroup.position() # gives me position of group where id = 12 mygroup.set_position(13) # changes value of position to 13 Is this code in another module? If so you need: import group and mygroup = Group.group(12) should be (module name followed by class name) mygroup = group.Group(12). mygroup.position() # this is a call, and position is not callable. should be mygroup.position "select `name`, `position` from `groups` where `id` = '"+id+"' " is OK but an easier to read version is: "select `name`, `position` from `groups` where `id` = '%s'" % (id,) is this right? i would test it here, but the database is not available. I am writing this to implement an easier way to code something very long later. Just wanted to know if i am on the right track. if you have read this far, thanks ! sk ___Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Bob Gailer510-978-4454 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] need some class / module help
oh, one more thing.these objects are going to be created at the rate of about 20 / minute in a thread.at some point is this going to be a problem ? do they go away over time?Or do i need to write something that will kill them? thanksskOn 10/20/06, shawn bright <[EMAIL PROTECTED]> wrote: Hey thanks for the help, yes, the class in in another file called group. the class Group is the only class in the module. I am doing this because the script that will call it is not the only place in all our scripts where it can be used. I have been doing stuff with python for over a year now, thought i would take advantage of some stuff that might save me some time. thanks againshawnOn 10/20/06, Bob Gailer < [EMAIL PROTECTED]> wrote: shawn bright wrote: Hey there, I am trying to create a module with one class the module name is group.py it looks like this so far import DbConnector class Group(object): def __init__(self, id): self.id = id con = DbConnector.DbConnector() query = con.getOne("select `name`, `position` from `groups` where `id` = '"+id+"' ") self.name = query[0] self.position = query[1] def set_position(position): self.position = position con.update("update `groups` set `position` = '"+self.position+"' where `id` = '"+self.id"' ") now lets say i wanted to do mygroup = Group.group(12) position = mygroup.position() # gives me position of group where id = 12 mygroup.set_position(13) # changes value of position to 13 Is this code in another module? If so you need: import group and mygroup = Group.group(12) should be (module name followed by class name) mygroup = group.Group(12). mygroup.position() # this is a call, and position is not callable. should be mygroup.position "select `name`, `position` from `groups` where `id` = '"+id+"' " is OK but an easier to read version is: "select `name`, `position` from `groups` where `id` = '%s'" % (id,) is this right? i would test it here, but the database is not available. I am writing this to implement an easier way to code something very long later. Just wanted to know if i am on the right track. if you have read this far, thanks ! sk ___Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor -- Bob Gailer510-978-4454 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] need some class / module help
On 10/20/06, shawn bright <[EMAIL PROTECTED]> wrote: > oh, one more thing. > these objects are going to be created at the rate of about 20 / minute in a > thread. > at some point is this going to be a problem ? do they go away over time? > Or do i need to write something that will kill them? If you don't keep references too them (i.e. by having names that are bound to them, or by keeping them in collections) then they'll go away - usually as soon as the last reference to them is gone. -- Cheers, Simon B [EMAIL PROTECTED] http://www.brunningonline.net/simon/blog/ ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] I need a time object from the future
William O'Higgins Witteman wrote: > I've been looking into this, and I am not understanding how to get this > task done. I need to be able to look at a time object and know if it si > between now and a set point 120 days in the future. I can get a value > for now (currently I am using datetime.datetime.now()), but I haven't > found a way to get now + 120 days, or figured out how to test if a given > datetime falls between the two. Any pointers would be appreciated. > Thanks. You can do this with datetime.timedelta: In [1]: from datetime import datetime, timedelta In [2]: n=datetime.now() In [3]: n Out[3]: datetime.datetime(2006, 10, 20, 14, 36, 44, 453000) In [4]: later = n + timedelta(days=120) In [5]: later Out[5]: datetime.datetime(2007, 2, 17, 14, 36, 44, 453000) In [6]: n < later Out[6]: True Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] need some class / module help
if i name them, like bob = group.Group(some_id) ?what is going to happen is that each time, the variable will create a different objectlike while 1: group = group.Group(some_id) do some stuff with group. so since it keeps getting replaced, it should be ok without some way to destroy it ?thanksOn 10/20/06, Simon Brunning < [EMAIL PROTECTED]> wrote:On 10/20/06, shawn bright < [EMAIL PROTECTED]> wrote:> oh, one more thing.> these objects are going to be created at the rate of about 20 / minute in a> thread.> at some point is this going to be a problem ? do they go away over time? > Or do i need to write something that will kill them?If you don't keep references too them (i.e. by having names that arebound to them, or by keeping them in collections) then they'll go away- usually as soon as the last reference to them is gone. --Cheers,Simon B[EMAIL PROTECTED]http://www.brunningonline.net/simon/blog/___ Tutor maillist - Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] need some class / module help
On Fri, 2006-10-20 at 13:44 -0500, shawn bright wrote: > if i name them, like bob = group.Group(some_id) ? > > what is going to happen is that each time, the variable will create a > different object > > like > while 1: > group = group.Group(some_id) > do some stuff with group. > > so since it keeps getting replaced, it should be ok without some way > to destroy it ? You can verify this by putting some kind of signal in the __del__ method. For instance: >>> class A: ... def __del__(self): print "destroyed" ... >>> bob = A() >>> bob = A() destroyed >>> dir() ['A', '__builtins__', '__doc__', '__name__', 'bob'] So you can see that binding the name "bob" to a different instance resulted in destroying the first one. > > > thanks > > > On 10/20/06, Simon Brunning <[EMAIL PROTECTED]> wrote: > On 10/20/06, shawn bright <[EMAIL PROTECTED]> wrote: > > oh, one more thing. > > these objects are going to be created at the rate of about > 20 / minute in a > > thread. > > at some point is this going to be a problem ? do they go > away over time? > > Or do i need to write something that will kill them? > > If you don't keep references too them (i.e. by having names > that are > bound to them, or by keeping them in collections) then they'll > go away > - usually as soon as the last reference to them is gone. > > -- > Cheers, > Simon B > [EMAIL PROTECTED] > http://www.brunningonline.net/simon/blog/ > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] need some class / module help
way cool, thanks much guys.skOn 10/20/06, Python <[EMAIL PROTECTED]> wrote: On Fri, 2006-10-20 at 13:44 -0500, shawn bright wrote:> if i name them, like bob = group.Group(some_id) ?>> what is going to happen is that each time, the variable will create a> different object >> like> while 1:> group = group.Group(some_id)> do some stuff with group.>> so since it keeps getting replaced, it should be ok without some way> to destroy it ? You can verify this by putting some kind of signal in the __del__method. For instance:>>> class A:... def __del__(self): print "destroyed"...>>> bob = A() >>> bob = A()destroyed>>> dir()['A', '__builtins__', '__doc__', '__name__', 'bob']So you can see that binding the name "bob" to a different instanceresulted in destroying the first one. >>> thanks>>> On 10/20/06, Simon Brunning <[EMAIL PROTECTED]> wrote:> On 10/20/06, shawn bright < [EMAIL PROTECTED]> wrote:> > oh, one more thing.> > these objects are going to be created at the rate of about> 20 / minute in a> > thread.> > at some point is this going to be a problem ? do they go > away over time?> > Or do i need to write something that will kill them?>> If you don't keep references too them (i.e. by having names> that are> bound to them, or by keeping them in collections) then they'll > go away> - usually as soon as the last reference to them is gone.>> --> Cheers,> Simon B> [EMAIL PROTECTED]> http://www.brunningonline.net/simon/blog/> ___> Tutor maillist - Tutor@python.org> http://mail.python.org/mailman/listinfo/tutor>> ___ > Tutor maillist - Tutor@python.org> http://mail.python.org/mailman/listinfo/tutor--Lloyd KvamVenix Corp ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Best way to replace items in a list.
I'm trying to build a little piece of code that replaces an item in a list. Here is a sample of what I'd like to do.str = "This was replaced"ff item in list: replace item with str I know I can do list.remove(item), but how do I place str back into that exact location?Is this how / best way?if item in list: loc = list.index(item) list.remove(item) list.insert(loc, str) Thanks. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Best way to replace items in a list.
Why not:if item in list: loc = list.index(item) list[loc] = strOn 10/20/06, Chris Hengge < [EMAIL PROTECTED]> wrote:I'm trying to build a little piece of code that replaces an item in a list. Here is a sample of what I'd like to do.str = "This was replaced"ff item in list: replace item with str I know I can do list.remove(item), but how do I place str back into that exact location?Is this how / best way?if item in list: loc = list.index(item) list.remove(item) list.insert(loc, str) 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
Re: [Tutor] Best way to replace items in a list.
Will that replace the location? or add to it? Thanks.On 10/20/06, Jason Massey <[EMAIL PROTECTED] > wrote:Why not:if item in list: loc = list.index(item) list[loc] = strOn 10/20/06, Chris Hengge < [EMAIL PROTECTED]> wrote: I'm trying to build a little piece of code that replaces an item in a list. Here is a sample of what I'd like to do.str = "This was replaced"ff item in list: replace item with str I know I can do list.remove(item), but how do I place str back into that exact location?Is this how / best way?if item in list: loc = list.index(item) list.remove(item) list.insert(loc, str) 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
Re: [Tutor] Best way to replace items in a list.
You can access and change the elements in a list by directly referencing their position in the list.Something like:>>> foo = [1,2,3]>>> foo[0]1>>> foo[0] = 'a'>>> foo ['a', 2, 3]On 10/20/06, Chris Hengge <[EMAIL PROTECTED]> wrote: Will that replace the location? or add to it? Thanks.On 10/20/06, Jason Massey < [EMAIL PROTECTED] > wrote:Why not:if item in list: loc = list.index(item) list[loc] = strOn 10/20/06, Chris Hengge < [EMAIL PROTECTED]> wrote: I'm trying to build a little piece of code that replaces an item in a list. Here is a sample of what I'd like to do.str = "This was replaced"ff item in list: replace item with str I know I can do list.remove(item), but how do I place str back into that exact location?Is this how / best way?if item in list: loc = list.index(item) list.remove(item) list.insert(loc, str) 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
Re: [Tutor] How to get the width of teh button widget..??
On Fri, 20 Oct 2006 11:55:10 +0100 "Asrarahmed Kadri" <[EMAIL PROTECTED]> wrote: > Folks, > > Sorry for asking you such a trivial question.!!! But i want to size up all > the buttons with the same size as the largest one in the interface.. And > thats why I am asking this question.. > Hi Asrarahmed, in case you use Tkinter, something like this should do the trick (untested): b1 = Button(master, text='Hi') b1.grid(row=0, column=0, sticky='ew') b2 = Button(master, text='Good-bye') b2.grid(row=0, column=1, sticky='ew') maxwidth = 0 for button in (b1, b2): w = button.winfo_reqwidth() if w > maxwidth: maxwidth = w master.grid_columnconfigure(0, minsize=maxwidth) master.grid_columnconfigure(1, minsize=maxwidth) or, if this is an option for you, use a Pmw.ButtonBox and call its alignbuttons() method. I hope this helps Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] PyAlsaAudio with Multiple Sound Cards?
Hi. I am pretty new to Python, but am trying to get up to speed so I move over to Python from Perl. One progam I wrote in Perl I am trying to re-write in Python. It controls the mixer settings on my sound card. I managed to rewrite most of it by borrowing and stealing from the mixertest.py included with PyAlsaAudio. I haven't been able to figure out on thing however. I know that normally when you assign the mixer with: mixer = alsaaudio.Mixer("Master") It seems to use the first card in the system. My system has two sound cards, and I can't figure out how to access the second card. Digging around online I found the following syntax: mixdev = alsaaudio.Mixer(mixer, id, device) I don't know what values it expects for id and device. I have tried using 0 for the id and using "hw:1" for the device to no avail. I am sure it is something simple, but after trying many different things I still haven't been able to figure out how to access my second sound card. Any help is apprecaited. Rick. _ Experience Live Search from your PC or mobile device today. http://www.live.com/?mkt=en-ca ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Resources for Tkinter...
"Asrarahmed Kadri" <[EMAIL PROTECTED]> wrote > I have the Tkinter book by Grayson (Python and Tkinter > Programming).. *But > I must say, its quite boring..* It is a bit dense. And it jumps from basic to advanced pretty quickly. But it is thorough and so far I've found very few mistakes. That makes it a *nice* book for me, I only use it as a reference, I dont normally try reading whole chapters... > Do you have any suggestions for a nice book or web resource..?? My other Tk resources are nearly all based on Tcl/Tk. The Tcl/Tk in a Nutshell is very useful(covers Tix too), but you do need to be happy translating Tcl/Tk into Python/Tkinter... For beginner level Ivor Lanningham's book "Teach Yourself Python in 24 Hours" has 3 or 4 chapters on Tkinter and a Mandelbrot case study that pulls it all together. Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to get the width of teh button widget..??
"Asrarahmed Kadri" <[EMAIL PROTECTED]> wrote > Sorry for asking you such a trivial question.!!! But i want to size > up all > the buttons with the same size as the largest one in the interface.. > And > thats why I am asking this question.. Assuming you mean in Tkinter(given yor other posts) it depends... You can specify the size when you create it, and if you use the placer layout manager it should keep that size. But if you use grid or packer managers then the size may change if the window is resized, depending on the options. However you should be able to read the size of the buttons back from the widget at runtime using dictionary syntax: def max(a,b): return (a>b) and a or b for button in mybuttons: max_size = max(max_size, button['width']) Or something very similar... Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Best way to replace items in a list.
Chris, > Will that replace the location? or add to it? > >> if item in list: >> loc = list.index(item) >> list[loc] = str Jason already showed you the answer, but significantly he also showed you how to find out for yourself. Use the >>> prompt. Its what its there for. For some reason people use the >>> prompt wehen starting out in Python then seem to forget it exists. But the ability to try out little bits of code interactively as you develop code is one of Pythons most powerful features. One that it shares with Lisp Ruby and Smalltalk but surprisingly few other languages... For those kinds of quiestions its usually much faster to just try it than it is to post a question to the list! -- Alan Gauld Author of the Learn to Program web site http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Best way to replace items in a list.
Chris Hengge wrote: > I'm trying to build a little piece of code that replaces an item in a > list. > > Here is a sample of what I'd like to do. > > str = "This was replaced" > > ff item in list: >replace item with str > > I know I can do list.remove(item), but how do I place str back into > that exact location? > > Is this how / best way? This is almost definitely not the best way to do that, though it depends what results you're looking for. This way will only replace the first occurrence of the item. I don't know why you like the 'if item in ...' syntax so much ( ;) ), but you could do this with a loop pretty easily. #example for index,item in enumerate(lst): if item == 'Item To Replace': lst[index] = 'Replaced!' # HTH, -Luke > > if item in list: >loc = list.index(item) >list.remove(item) >list.insert(loc, str) > > 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
Re: [Tutor] Best way to replace items in a list.
I like it because it different.. and it reads cleanly... =PAs far as the first occurance.. I'm not concerned about checking extra, because the first occurance is the only one I should ever need. On 10/20/06, Luke Paireepinart <[EMAIL PROTECTED]> wrote: Chris Hengge wrote:> I'm trying to build a little piece of code that replaces an item in a> list.>> Here is a sample of what I'd like to do.>> str = "This was replaced" >> ff item in list:>replace item with str>> I know I can do list.remove(item), but how do I place str back into> that exact location?>> Is this how / best way?This is almost definitely not the best way to do that, though it depends what results you're looking for.This way will only replace the first occurrence of the item.I don't know why you like the 'if item in ...' syntax so much ( ;) ),but you could do this with a loop pretty easily. #examplefor index,item in enumerate(lst):if item == 'Item To Replace': lst[index] = 'Replaced!'#HTH,-Luke>> if item in list:>loc = list.index(item) >list.remove(item)>list.insert(loc, str)>> 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
[Tutor] My first real python project: LOLLERSKATES
-BEGIN PGP SIGNED MESSAGE- Hash: SHA1 I have been a sysadmin for quite a while now and used to do a lot of perl. I haven't done much programming at all in the last couple of years but have been meaning to dump perl for python anyhow (for the usual reasons) and have finally gotten around to doing it. The first itch that I wanted to scratch was something to help me find anomalies in our system logs. We have a lot of servers and need some automation for watching over them including logfiles. I have used logwatch and logcheck but they are both too complicated for what I really need not to mention practically unmaintained these days. So I decided to write my own. Features I wanted were: 1. A basic grep -v sort of functionality on the logfile where I have a file full of regexes/lines to be ignored that are applied to the logfiles to filter everything uninteresting out and whatever is left gets emailed to the admin. 2. A sort of macro system where I can substitute nasty long commonly used regexes in my filter/ignore file with something more easily read and typed. 3. Simplicity. Logcheck had several different levels of logfile events which it could report back on and if you wanted something ignored you had to put it in the right config file for whatever level it was popping up in. This drove me nuts because I often got the wrong one. Logwatch tries to analyze your logs and provide various summaries and statistics and other things I don't care about. I just want to see the interesting lines from the logfile. My code seems to have all of the above and a silly name as well: http://ultraviolet.org/Members/treed/lollerskates It has a list of logfiles to look at, a list of regexes to compare to each line to know what is uninteresting and to filter out/ignore, and emails anything left to the admin, and a simple macro facility. I would appreciate it if anyone interested would download and critique my code. Am I doing anything terribly un-pythonic? Questions/problems/TODO's: This is a fairly simple structured programming implementation. No OO. Should I be using some classes somewhere? The config file is just a module which I import which causes all of my configs to become globals. Globals are bad. Is there a better way or would just about anything else be overkill? A singleton config class or something? Overkill? I have several loops in this code for processing the logfiles. I once tried to convert these for loops to list comprehensions and totally confused myself and backed out the change (yeay svn!). Is there any benefit to list comprehensions in this case? I would kinda like to play with unit tests. Not sure how I would construct unit tests for this. And again, perhaps overkill. But some people tell me you should write the unit tests before you even begin coding and code until the tests are satisfied. So even on a small project you would have tests. I run into a couple nasty bugs I created which caused the script to never return anything from the logfile (so you don't immediately realize something is broken) where I thought "It sure would be nice to have a test to catch that if it ever happens again." Stuff tends to build up in the ignore file. If a line is typo'd and never gets used/matched you will never know. If a service is no longer running that we had lines in the ignore file for they will be there forever unused. I don't like this sort of clutter. I am really tempted to somehow make it keep track of when a rule is matched and if it doesn't match in a whole month email the admin because it doesn't need to be there. I am wondering if this is needless complexity or something useful. I think it could be useful. If so, how to save the info on when each line was last matched? I am thinking maybe of just having a dictionary keyed on the compiled regex object and the value being a tuple of the uncompiled regex string from the ignore file and a date string containing when it was last matched and pickling this data structure to disk to be read in each start of the program. Comments? I am currently pushing this code to around 20 systems with cfengine using just one ignore file for them all. If I use the scheme mentioned in the previous paragraph to alert me of unused rules in the ignore file I will get tons of such messages from machines not running a service that other machines of mine are. I guess that means perhaps I should split my ignore file out into ignore.hostname.conf or something like that so there is a separate one for each host. Anyhow, I appreciate any feedback on this potentially very handy sysadmin tool. Thanks in advance! - -- Tracy R Reed http://ultraviolet.org -BEGIN PGP SIGNATURE- Version: GnuPG v1.4.5 (GNU/Linux) Comment: Using GnuPG with Fedora - http://enigmail.mozdev.org iD8DBQFFObPK9PIYKZYVAq0RAiflAJ9jprJgGnNRXkB+nKsljFUsAUGnFwCgiJg/ M3U24dNDtH+hAgSh7kZ40hQ= =nxQS -END PGP SIGNATURE- ___ Tutor maillist - Tutor@
Re: [Tutor] My first real python project: LOLLERSKATES
All I can say to this... LOLLERSKATES =DOn 10/20/06, Tracy R Reed <[EMAIL PROTECTED]> wrote: -BEGIN PGP SIGNED MESSAGE-Hash: SHA1I have been a sysadmin for quite a while now and used to do a lot of perl. I haven't done much programming at all in the last couple of yearsbut have been meaning to dump perl for python anyhow (for the usualreasons) and have finally gotten around to doing it.The first itch that I wanted to scratch was something to help me find anomalies in our system logs. We have a lot of servers and need someautomation for watching over them including logfiles. I have usedlogwatch and logcheck but they are both too complicated for what Ireally need not to mention practically unmaintained these days. So I decided to write my own.Features I wanted were:1. A basic grep -v sort of functionality on the logfile where I have afile full of regexes/lines to be ignored that are applied to thelogfiles to filter everything uninteresting out and whatever is left gets emailed to the admin.2. A sort of macro system where I can substitute nasty long commonlyused regexes in my filter/ignore file with something more easily readand typed.3. Simplicity. Logcheck had several different levels of logfile events which it could report back on and if you wanted something ignored youhad to put it in the right config file for whatever level it was poppingup in. This drove me nuts because I often got the wrong one. Logwatch tries to analyze your logs and provide various summaries and statisticsand other things I don't care about. I just want to see the interestinglines from the logfile.My code seems to have all of the above and a silly name as well: http://ultraviolet.org/Members/treed/lollerskatesIt has a list of logfiles to look at, a list of regexes to compare toeach line to know what is uninteresting and to filter out/ignore, and emails anything left to the admin, and a simple macro facility.I would appreciate it if anyone interested would download and critiquemy code. Am I doing anything terribly un-pythonic?Questions/problems/TODO's: This is a fairly simple structured programming implementation. No OO.Should I be using some classes somewhere?The config file is just a module which I import which causes all of myconfigs to become globals. Globals are bad. Is there a better way or would just about anything else be overkill? A singleton config class orsomething? Overkill?I have several loops in this code for processing the logfiles. I oncetried to convert these for loops to list comprehensions and totally confused myself and backed out the change (yeay svn!). Is there anybenefit to list comprehensions in this case?I would kinda like to play with unit tests. Not sure how I wouldconstruct unit tests for this. And again, perhaps overkill. But some people tell me you should write the unit tests before you even begincoding and code until the tests are satisfied. So even on a smallproject you would have tests. I run into a couple nasty bugs I createdwhich caused the script to never return anything from the logfile (so you don't immediately realize something is broken) where I thought "Itsure would be nice to have a test to catch that if it ever happens again."Stuff tends to build up in the ignore file. If a line is typo'd and never gets used/matched you will never know. If a service is no longerrunning that we had lines in the ignore file for they will be thereforever unused. I don't like this sort of clutter. I am really tempted to somehow make it keep track of when a rule is matched and if itdoesn't match in a whole month email the admin because it doesn't needto be there. I am wondering if this is needless complexity or somethinguseful. I think it could be useful. If so, how to save the info on when each line was last matched? I am thinking maybe of just having adictionary keyed on the compiled regex object and the value being atuple of the uncompiled regex string from the ignore file and a datestring containing when it was last matched and pickling this data structure to disk to be read in each start of the program. Comments?I am currently pushing this code to around 20 systems with cfengineusing just one ignore file for them all. If I use the scheme mentioned in the previous paragraph to alert me of unused rules in the ignore file I will get tons of such messages from machines not running a servicethat other machines of mine are. I guess that means perhaps I should split my ignore file out into ignore.hostname.conf or something likethat so there is a separate one for each host.Anyhow, I appreciate any feedback on this potentially very handysysadmin tool. Thanks in advance! - --Tracy R Reedhttp://ultraviolet.org-BEGIN PGP SIGNATURE-Version: GnuPG v1.4.5 (GNU/Linux)Comment: Using GnuPG with Fedora - http://enigmail.mozdev.orgiD8DBQFFObPK9PIYKZYVAq0RAiflAJ9jprJgGnNRXkB+nKsljFUsAUGnFwCgiJg/M3U24dNDtH+hAgSh7kZ40hQ==nxQS-END PGP SIGNATURE-___ Tutor mailli