Re: [Tutor] new topic draft
Alan, You may remember that I asked questions on killing a process, a while back, Sice this is relatedto the tutorial that yu are writing, this was the best solution that worked for me to killa process for a command that keeps on running like eg. 'tcpdump'. HTH Johan BTW, There will a be many a felllow Pythonists that will benefit from a tut like this, great work !! Alan Gauld wrote: I've just added an incomplete draft copy of my latest tutorial topic on using the Operating System from Python. The material that's there discusses the role of the OS and looks at file handling usng os/os.path/shutil etc. http://www.freenetpages.co.uk/hp/alan.gauld/tutos.htm If anyone would like to take a look and provide feedback on general direction/depth etc that'd be greatly appreciated. TIA, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor """ This class will execute the command, let it run for 5 seconds and kill the process. ::Author: Johan Geldenhuys [EMAIL PROTECTED] ::Version: 0.0.1 ::Date last updated: 2005-11-03 ::Changes: :: TODO: Capture the output from line 41 to a file. """ import os, signal, time class command(object): def __init__(self): pass def kill(self, pid, signal=signal.SIGTERM): try: print "trying to kill pid...", pid os.kill(pid, signal) #os.waitpid(pid, 0) print "Killed %d"%pid except: print "couldn't stop process" def main(self, interface): self.interface = interface self.pid = os.fork() if self.pid == 0: os.execvp('tcpdump', ['tcpdump', '-npi', self.interface]) print 'PID: ',self.pid print 'Let it run for 5 seconds...' time.sleep(5) self.kill(self.pid) if __name__ == '__main__': print "starting test" c = command() c.main('eth0') ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Invisible Raw Input
Hi All, Is there any trick to either not echo or obscure password from raw_input() function? -- fade2blac ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Tkinter mainloop (was Re: tkFileDialog.Directory)
Hello Michael, hello list, thanks for the info that pmw displays exceptions. What I don't understand is >> --- snip --- >> import Tix >> >> def raise_exception(): >> print 1/0 >> >> if __name__ == '__main__': >> root = Tix.Tk() >> root.title("Exception demo") >> >> Tix.Button(root, text = "Don't press", command = raise_exception).pack() >> >> try: >> root.mainloop() >> except: >> print "An error has occured." >> --- snip --- >> >> The except part gets never executed. > That's because the error isn't in the mainloop() method I thought the mainloop() function is something like def mainloop(): e= get_event() if e: for w in widgets: w.handle(e) but apparently it is not. It's not bad that the Tkinter windows don't destroy upon an exception, since it gives me the option to display an error window, but I feel unsafe unless I understand why it does not. -- Telefonieren Sie schon oder sparen Sie noch? NEU: GMX Phone_Flat http://www.gmx.net/de/go/telefonie ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Invisible Raw Input
On Wed, 2005-11-16 at 16:19 +0700, fade2blac wrote: > Hi All, > Is there any trick to either not echo or obscure password from raw_input() > function? > Yes, try this: import getpass password = getpass.unix_getpass("Enter your password:") print password -- Jan Martinek > -- > fade2blac ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Creating Tkinter Menubars
On Tue, 15 Nov 2005 16:17:53 -0500 Double Six <[EMAIL PROTECTED]> wrote: > Hi, > > I am testing the following Tkinter code (attached at the end of > this message) by Fredrik Lundh on a Mac OS X 10.4.2 with Python > version 2.3. I do get a root window, but it is totally blank > without the desirable menubars such as File and Edit. What am I > missing? > It works well for me (on linux, python-2.3), maybe a mac specific thing (sorry , I can't help then). Does the following, simpler code work for you? from Tkinter import * root = Tk() menubar = Menu(root) menu = Menu(menubar, tearoff=0) menubar.add_cascade(label="File", menu=menu) menu.add_command(label="New") menu = Menu(menubar, tearoff=0) menubar.add_cascade(label="Edit", menu=menu) menu.add_command(label="Cut") menu.add_command(label="Copy") menu.add_command(label="Paste") root.config(menu=menubar) root.mainloop() The only thing that looks a little starnge to me in the original code is that the menubar is created as a child of the AppUi class, which is basically a Frame, but then it is attached to that Frame's parent (the root window). Maybe the mac doesn't like this (just a thought)? Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tkinter mainloop (was Re: tkFileDialog.Directory)
On Wed, 16 Nov 2005 10:55:24 +0100 (MET) [EMAIL PROTECTED] wrote: Hi Karsten, > I thought the mainloop() function is something like > > def mainloop(): > e= get_event() > if e: > for w in widgets: w.handle(e) > > but apparently it is not. > > It's not bad that the Tkinter windows don't destroy upon an exception, > since it gives me the option to display an error window, but I feel unsafe > unless I understand why it does not. > I am not enough of an expert to give you a "complete" answer for that, so anyone please correct me if I am wrong. As far as I understand, the mainloop() command just starts a tk shell and Tkinter gives you an interface to communicate with this tk shell. In fact Tkinter "translates" any widget command into a tk command and sends it to the tk shell, which itself sends it to the associated Tk window (or the related widget). The tk shell will run as long as a - Python decides to close it for you (e.g. after the main (Tk()) window has been destroyed) b - you explicitely close it calling the widget's quit() method c - a fatal tk error occurs, so the tk shell decides to quit itself Now most of the errors that occur happen of course on the python level and are caught by the python interpreter (that shows you the traceback) and there is no reason for python to inform the tk shell that it should quit. I hope this makes sense Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] RTSP
On Tue, Nov 15, 2005 at 09:10:33PM -0200, Ismael Garrido wrote: > Hi > > Does anyone know if there's any module able to download rtsp? > Failing that, any command line app that could do the job? (Already tried > with mplayer, it didn't work) $ mplayer rtsp://ravi.br-online.de:5050/ravi/alpha/centauri/v/050803.rm works for me. -- innovate, v.: To annoy people. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tkinter mainloop (was Re: tkFileDialog.Directory)
[EMAIL PROTECTED] wrote: > What I don't understand is >>>import Tix >>> >>>def raise_exception(): >>> print 1/0 >>> >>>if __name__ == '__main__': >>>root = Tix.Tk() >>>root.title("Exception demo") >>> >>>Tix.Button(root, text = "Don't press", command = > > raise_exception).pack() > >>>try: >>> root.mainloop() >>>except: >>> print "An error has occured." >>>--- snip --- >>> >>>The except part gets never executed. > > I thought the mainloop() function is something like > > def mainloop(): > e= get_event() > if e: > for w in widgets: w.handle(e) > > but apparently it is not. The main loop is probably more like this: def mainloop(): e= get_event() if e: try: for w in widgets: w.handle(e) except: traceback.print_exc() It's pretty common for GUI toolkits to trap exceptions in the event handler. This can help make a more robust application - in my experience I don't really want a bug in a handler to crash the whole app. There is an undocumented hook that lets you change this - the function Tk.report_callback_exception() is called to actually report the error. You can redefine this function to do what you want. Here are a couple of examples: http://zephyrfalcon.org/weblog/arch_d7_2003_01_04.html http://groups.google.com/group/comp.lang.python/browse_thread/thread/ce0036f41da8a22f/c62177e5bb59b09c%23c62177e5bb59b09c?sa=X&oi=groupsr&start=1&num=3 Kent -- http://www.kentsjohnson.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Creating Tkinter Menubars
Hi Michael, Thank you very much for the help. I tried the simpler code you provided, but unfortunatly I still got a blank window without any trace of menubars. Any other insights? Thanks, Joe from Tkinter import * root = Tk() menubar = Menu(root) menu = Menu(menubar, tearoff=0) menubar.add_cascade(label="File", menu=menu) menu.add_command(label="New") menu = Menu(menubar, tearoff=0) menubar.add_cascade(label="Edit", menu=menu) menu.add_command(label="Cut") menu.add_command(label="Copy") menu.add_command(label="Paste") root.config(menu=menubar) root.mainloop() Get your own "800" number Voicemail, fax, email, and a lot more http://www.ureach.com/reg/tag On Wed, 16 Nov 2005, Michael Lange ([EMAIL PROTECTED]) wrote: > On Tue, 15 Nov 2005 16:17:53 -0500 > Double Six <[EMAIL PROTECTED]> wrote: > > > Hi, > > > > I am testing the following Tkinter code (attached at the end of > > this message) by Fredrik Lundh on a Mac OS X 10.4.2 with Python > > version 2.3. I do get a root window, but it is totally blank > > without the desirable menubars such as File and Edit. What am I > > missing? > > > > > It works well for me (on linux, python-2.3), maybe a mac specific thing (sorry , I can't help then). > Does the following, simpler code work for you? > > from Tkinter import * > > root = Tk() > menubar = Menu(root) > menu = Menu(menubar, tearoff=0) > menubar.add_cascade(label="File", menu=menu) > menu.add_command(label="New") > menu = Menu(menubar, tearoff=0) > menubar.add_cascade(label="Edit", menu=menu) > menu.add_command(label="Cut") > menu.add_command(label="Copy") > menu.add_command(label="Paste") > root.config(menu=menubar) > root.mainloop() > > The only thing that looks a little starnge to me in the original code is > that the menubar is created as a child of the AppUi class, which is basically a Frame, > but then it is attached to that Frame's parent (the root window). > Maybe the mac doesn't like this (just a thought)? > > Michael ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] class attributes
Hello, If I have some like the following: markersExp = ['big','boss','two','three'] for mark in markersExp: print y.mark Now I have an list of class objects that are in an outerloop. y is how I access it. The attributes names of the class objects match whats in markersExp. Can I do that print statement in a way to allow me to print the value of the class attribute? ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] class attributes
Eric Walker wrote: > Hello, > If I have some like the following: > > markersExp = ['big','boss','two','three'] > for mark in markersExp: > print y.mark > > Now I have an list of class objects that are in an outerloop. y is how I > access it. The attributes names of the class objects match whats in > markersExp. Can I do that print statement in a way to allow me to print the > value of the class attribute? Use getattr(): print getattr(y, mark) http://docs.python.org/lib/built-in-funcs.html#l2h-31 Kent -- http://www.kentsjohnson.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Favourite modules - Wiki Was Re: TurboGears - and some issues
Kent Johnson schrieb: >>And somewhere docutils belongs on that list, but i don't know where. Maybe >>source code documentation? But then you'd probably have to list epydoc, >>gendoc, >>etc. as well. > > > I think this page will be more useful as a list of favorites or things that > beginners might want to take a look at than as an encyclopedic list - there > are other places to list all the template engines, all the GUI toolkits, etc. Sorry, I wasn't suggesting to turn this into a comprehensive list of modules for every specific problem domain. But I don't see, why such a list would be only useful for beginners. Say, you're an experienced programmer, though not very seasoned in Python yet, it would be great to have a place were you can find answers for questions like "What do Python people normally use when handling x?" I was just saying, that for some domains there is a obivious choice and for some there isn't. Maybe it would be already helpful to include that information into the list, e.g. "There are many different GUI toolkits for Python and none seems to be vastly more favourite than the others. See a list of GUI modules here."* *Just an example, don't take this literally. Chris ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] lambda in a loop
Hi everyone, If I have this code: def doLambda(val): print "value 2:", val commands = [] for value in range(5): print "value 1:", value commands.append(lambda:doLambda(value)) for c in commands: c() -- my output is: value 1: 0 value 1: 1 value 1: 2 value 1: 3 value 1: 4 value 2: 4 value 2: 4 value 2: 4 value 2: 4 value 2: 4 Obviously, the lambda is using "value" at the end of the loop (4), rather than what I want, "value" during the loop (0,1,2,3). Is there any *simple* way around this? I'd prefer not to use a separate array with all the values ( i.e. commands.append(lambda:doLambda(values[commands.index(c)])) ) if possible. Thanks, Fred ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] How to convert a list to tuple
Dear all, Pardon me for asking a simple question. Sometimes brain gets blank and compells me to seek help from tutors. I have a list : >>>prcor ['933\t957', '955\t979', '969\t993', '1025\t1049', '1052\t1076', '1098\t1122', '1136\t1160', '1298\t1322', '1406\t1430', '1422\t1446', '1471\t1495'] >>> prc = () >>>for line in prcor: cols = line.split('\t') (x,y) = (int(cols[0]),int(cols[1])) prc = (x,y) >>>prc (1471, 1495) Because the resulting element is a tuple, append is not working. How can I push all these elements in this list: ['933\t957', '955\t979', '969\t993', '1025\t1049', '1052\t1076', '1098\t1122', '1136\t1160', '1298\t1322', '1406\t1430', '1422\t1446', '1471\t1495'] into a a big tuple : ((933,957),(955,979),(969,993),(1025,1049),(1052,1076),(1098,1122),(1136,1160), (1298,1322),(1406,1430),(1422,1446),(1471,1495)) Thank you. __ Yahoo! Mail - PC Magazine Editors' Choice 2005 http://mail.yahoo.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] new topic draft
Thanks, I may use that as one of the example programs if you don't mind? Alan G. - Original Message - From: "Johan Geldenhuys" <[EMAIL PROTECTED]> To: "Alan Gauld" <[EMAIL PROTECTED]> Cc: "Python Tutor list" Sent: Wednesday, November 16, 2005 8:12 AM Subject: Re: [Tutor] new topic draft > Alan, > > You may remember that I asked questions on killing a process, a while > back, > > Sice this is relatedto the tutorial that yu are writing, this was the > best solution that worked for me to killa process for a command that > keeps on running like eg. 'tcpdump'. > > HTH > > Johan > BTW, There will a be many a felllow Pythonists that will benefit from a > tut like this, great work !! > > > Alan Gauld wrote: > >>I've just added an incomplete draft copy of my latest tutorial topic >>on using the Operating System from Python. The material that's >>there discusses the role of the OS and looks at file handling >>usng os/os.path/shutil etc. >> >>http://www.freenetpages.co.uk/hp/alan.gauld/tutos.htm >> >>If anyone would like to take a look and provide feedback on >>general direction/depth etc that'd be greatly appreciated. >> >>TIA, >> >>Alan G >>Author of the learn to program web tutor >>http://www.freenetpages.co.uk/hp/alan.gauld >> >> >>___ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor >> >> >> > > """ > This class will execute the command, let it run for 5 seconds and kill > the process. > > ::Author: Johan Geldenhuys > [EMAIL PROTECTED] > > ::Version: 0.0.1 > > ::Date last updated: 2005-11-03 > > ::Changes: > > :: TODO: Capture the output from line 41 to a file. > """ > > import os, signal, time > > class command(object): > >def __init__(self): > >pass > > >def kill(self, pid, signal=signal.SIGTERM): >try: > >print "trying to kill pid...", pid >os.kill(pid, signal) >#os.waitpid(pid, 0) >print "Killed %d"%pid >except: > print "couldn't stop process" > >def main(self, interface): > >self.interface = interface >self.pid = os.fork() > >if self.pid == 0: > > os.execvp('tcpdump', ['tcpdump', '-npi', self.interface]) > >print 'PID: ',self.pid >print 'Let it run for 5 seconds...' >time.sleep(5) >self.kill(self.pid) > > > if __name__ == '__main__': > print "starting test" > c = command() > c.main('eth0') > > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Creating Tkinter Menubars
> version 2.3. I do get a root window, but it is totally blank > without the desirable menubars such as File and Edit. What am I > missing? At a guess you forgot to pack() the menu? Thats usually whats wrong when widgets fail to appear as expected! :-) Alan G. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Using lists as table-like structure
Hello, I am wondering if can do this: Let say I have a list of lists. Each individual lists have a bunch of elements. Now I would like to either get or set the first element of each individual list. I could do a loop and/or list comprehension, but I was wondering if it was possible with something like: aList = [ [1,1,1], [2,2,2,], [3,3,3] ] aList[:][0] = 10 If I print aList[:], I get the list with the nested sublists. >>> aList[:] [[1, 1, 1], [2, 2, 2], [3, 3, 3]] But as soon as I introduce the [0], in an attempt to access the first element of each sublist, I get the first sublist in its entirety: >>> aList[:][0] [1, 1, 1] I would have hoped to get something like [1, 2, 3] Is this possible at all? Thanks Bernard ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to convert a list to tuple
Does this work? (I can't check) listX = ['933\t957', '955\t979', '969\t993', '1025\t1049', '1052\t1076', '1098\t1122', '1136\t1160', '1298\t1322', '1406\t1430', '1422\t1446', '1471\t1495'] listY = [ tuple(item.split("\t")) for item in listX] tupleY = tuple(listY) Liam Clarke-Hutchinson| Contact Centre Advisor| Ministry of Economic Development DDI +64 3 962 2639 | Fax +64 3 962 6220 www.med.govt.nz -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Srinivas Iyyer Sent: Thursday, 17 November 2005 9:59 a.m. To: tutor@python.org Subject: [Tutor] How to convert a list to tuple Dear all, Pardon me for asking a simple question. Sometimes brain gets blank and compells me to seek help from tutors. I have a list : >>>prcor ['933\t957', '955\t979', '969\t993', '1025\t1049', '1052\t1076', '1098\t1122', '1136\t1160', '1298\t1322', '1406\t1430', '1422\t1446', '1471\t1495'] >>> prc = () >>>for line in prcor: cols = line.split('\t') (x,y) = (int(cols[0]),int(cols[1])) prc = (x,y) >>>prc (1471, 1495) Because the resulting element is a tuple, append is not working. How can I push all these elements in this list: ['933\t957', '955\t979', '969\t993', '1025\t1049', '1052\t1076', '1098\t1122', '1136\t1160', '1298\t1322', '1406\t1430', '1422\t1446', '1471\t1495'] into a a big tuple : ((933,957),(955,979),(969,993),(1025,1049),(1052,1076),(1098,1122),(1136,116 0), (1298,1322),(1406,1430),(1422,1446),(1471,1495)) Thank you. __ Yahoo! Mail - PC Magazine Editors' Choice 2005 http://mail.yahoo.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor A new monthly electronic newsletter covering all aspects of MED's work is now available. Subscribers can choose to receive news from any or all of seven categories, free of charge: Growth and Innovation, Strategic Directions, Energy and Resources, Business News, ICT, Consumer Issues and Tourism. See http://news.business.govt.nz for more details. http://www.govt.nz - connecting you to New Zealand central & local government services Any opinions expressed in this message are not necessarily those of the Ministry of Economic Development. This message and any files transmitted with it are confidential and solely for the use of the intended recipient. If you are not the intended recipient or the person responsible for delivery to the intended recipient, be advised that you have received this message in error and that any use is strictly prohibited. Please contact the sender and delete the message and any attachment from your computer. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] How to convert a list to tuple
Thanks. It works. Thanks for simplifying it in list comprehension. Srini --- Liam Clarke-Hutchinson <[EMAIL PROTECTED]> wrote: > Does this work? (I can't check) > > listX = ['933\t957', '955\t979', '969\t993', > '1025\t1049', '1052\t1076', > '1098\t1122', '1136\t1160', '1298\t1322', > '1406\t1430', '1422\t1446', > '1471\t1495'] > > listY = [ tuple(item.split("\t")) for item in listX] > tupleY = tuple(listY) > > Liam Clarke-Hutchinson| Contact Centre Advisor| > Ministry of Economic > Development > DDI +64 3 962 2639 | Fax +64 3 962 6220 > www.med.govt.nz > > > > -Original Message- > From: [EMAIL PROTECTED] > [mailto:[EMAIL PROTECTED] > On Behalf Of Srinivas > Iyyer > Sent: Thursday, 17 November 2005 9:59 a.m. > To: tutor@python.org > Subject: [Tutor] How to convert a list to tuple > > > Dear all, > Pardon me for asking a simple question. Sometimes > brain gets blank and compells me to seek help from > tutors. > > I have a list : > >>>prcor > ['933\t957', '955\t979', '969\t993', '1025\t1049', > '1052\t1076', > '1098\t1122', '1136\t1160', '1298\t1322', > '1406\t1430', '1422\t1446', > '1471\t1495'] > >>> prc = () > >>>for line in prcor: > cols = line.split('\t') > (x,y) = (int(cols[0]),int(cols[1])) > prc = (x,y) > >>>prc > (1471, 1495) > > Because the resulting element is a tuple, append is > not working. > > How can I push all these elements in this list: > ['933\t957', '955\t979', '969\t993', '1025\t1049', > '1052\t1076', > '1098\t1122', '1136\t1160', '1298\t1322', > '1406\t1430', '1422\t1446', > '1471\t1495'] > > into a a big tuple : > > ((933,957),(955,979),(969,993),(1025,1049),(1052,1076),(1098,1122),(1136,116 > 0), > (1298,1322),(1406,1430),(1422,1446),(1471,1495)) > > > Thank you. > > > > > > __ > Yahoo! Mail - PC Magazine Editors' Choice 2005 > http://mail.yahoo.com > ___ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > A new monthly electronic newsletter covering all > aspects of MED's work is now available. Subscribers > can choose to receive news from any or all of seven > categories, free of charge: Growth and Innovation, > Strategic Directions, Energy and Resources, Business > News, ICT, Consumer Issues and Tourism. See > http://news.business.govt.nz for more details. > > > > > http://www.govt.nz - connecting you to New Zealand > central & local government services > > Any opinions expressed in this message are not > necessarily those of the Ministry of Economic > Development. This message and any files transmitted > with it are confidential and solely for the use of > the intended recipient. If you are not the intended > recipient or the person responsible for delivery to > the intended recipient, be advised that you have > received this message in error and that any use is > strictly prohibited. Please contact the sender and > delete the message and any attachment from your > computer. > __ Yahoo! FareChase: Search multiple travel sites in one click. http://farechase.yahoo.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Using lists as table-like structure
Hi Bernard, You can do this with Numeric (http://numeric.scipy.org/) import Numeric aList = [ [1,1,1], [2,2,2,], [3,3,3] ] bList = Numeric.array(aList, "i") print bList[:,0] displays-> [1 2 3] you can convert the array back to a list if you want like this: bList.tolist() so... result = Numeric.array(aList, "i")[:,0].tolist() should do what you want in one line. Fred > aList = [ [1,1,1], [2,2,2,], [3,3,3] ] > aList[:][0] = 10 > > > If I print aList[:], I get the list with the nested sublists. > > >>> aList[:] > [[1, 1, 1], [2, 2, 2], [3, 3, 3]] > > > But as soon as I introduce the [0], in an attempt to access the first > element of each sublist, I get the first sublist in its entirety: > > >>> aList[:][0] > [1, 1, 1] > > > I would have hoped to get something like > [1, 2, 3] > > > Is this possible at all? > > Thanks > Bernard > ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Creating Tkinter Menubars
On 17/11/05, Alan Gauld <[EMAIL PROTECTED]> wrote: > At a guess you forgot to pack() the menu? Thats usually whats wrong > when widgets fail to appear as expected! :-) You don't pack() menus --- you attach them to a Tk() or a Toplevel() by calling .config() with the menu= option (like in Michael's post, which also works for me). ...wait, hang on. I don't own a Mac, but isn't the standard for Macintoshes to stick the menu bar along the top of the screen? Is it appearing up there instead? -- John. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] lambda in a loop
> -Original Message- > From: [EMAIL PROTECTED] > [mailto:[EMAIL PROTECTED] On Behalf Of Fred Lionetti > Sent: Wednesday, November 16, 2005 2:32 PM > To: tutor@python.org > Subject: [Tutor] lambda in a loop > > Hi everyone, Hello, > If I have this code: > > > def doLambda(val): >print "value 2:", val > > commands = [] > for value in range(5): >print "value 1:", value >commands.append(lambda:doLambda(value)) > > for c in commands: >c() > -- > > my output is: > value 1: 0 > value 1: 1 > value 1: 2 > value 1: 3 > value 1: 4 > value 2: 4 > value 2: 4 > value 2: 4 > value 2: 4 > value 2: 4 > > Obviously, the lambda is using "value" at the end of the loop (4), > rather than what I want, "value" during the loop (0,1,2,3). Right. I think the issue is that your lambda calls another funtion. However, the function isn't called until the lambda is called later, when value == 4. > Is there > any *simple* way around this? I'd prefer not to use a separate array > with all the values ( i.e. > commands.append(lambda:doLambda(values[commands.index(c)])) ) if > possible. I'd use a closure rather than a lambda. def wrapper(val): def inner(): print "value 2:", val return inner commands = [] for value in range(5): print "value 1:", value commands.append(wrapper(value)) for c in commands: c() That way each item in commands is an "inner" function that has its own local copy of value. So it is really a variable scope issue. > Thanks, > Fred HTH, sorry it isn't more clear. Christian ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] class attributes
> markersExp = ['big','boss','two','three'] > for mark in markersExp: > print y.mark > > Now I have an list of class objects that are in an outerloop. y is how I > access it. The attributes names of the class objects match whats in > markersExp. Do you have to use string versions of the class names? Why not: class Mark: mark = 42 class big(Mark): pass class boss(Mark): pass class two(Mark): pass class three(Mark): pass markersExp = [big,boss.two,three] for cls in markersExp: print cls.mark Classes are objects too! > Can I do that print statement in a way to allow me to print the > value of the class attribute? Or are we really talking about instances? In which case the usual solution is a dictionary. Alan g. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] lambda in a loop
> > def doLambda(val): >print "value 2:", val > > commands = [] > for value in range(5): >print "value 1:", value >commands.append(lambda:doLambda(value)) > > for c in commands: >c() Hi Fred, Ah, this one of those unfrequently asked questions. lambdas in Python's for loop are a little tricky because the for loop rebinds the element variable. That is, what's happening is that all those lambda functions are just resetting the same 'value' variable: the loop is merely rebinding value to the elements of range(5). All the lambdas are sharing the same name binding, and that explains why we see this kind of aliasing behavior. One possible fix is to do this: ## def makeDoLambda(value): def f(): return doLambda(value) return f ## Once we have this makeDoLambda() function, then we can use it: commands.append(makeDoLambda(value)) The act of calling the makeDoLambda() function makes a fresh name binding to 'value', so that none of the lambda functions share the same binding. Another way to do this is to force our lambda to make a fresh binding with a default parameter: commands.append(lambda v=value: doLambda(v)) This is subtle, so if you have more questions, please feel free to ask. Slightly off-topic footnote: if you're familiar with the Scheme programming language, then what's happening can be simulated like this: ;;; ;;; Simulates some of the essence of Python's for loop (define-syntax python-for-each (syntax-rules () ((_ (id list) e1 e2 ...) (let ((id #f)) (let loop ((L list)) (if (null? L) (void) (begin (set! id (car L)) e1 e2 ... (loop (cdr L) (begin (define commands '()) (python-for-each (i '(1 2 3 4 5)) (set! commands (cons (lambda () i) commands))) (for-each (lambda (f) (display (f)) (newline)) commands)) ;;; Python's loop has set!-ish behavior, and it's that rebinding behavior that causes the issues you are seeing. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] class attributes
ahh, you just blew smoke in my face. :) I have a class with attributes. These attributes eventually have the value of some lines in a file. I am now going back through my object list of that class and assigning values to the attributes depending on another variable that will change and be the same names like the class attribute names. I want to use that change in name to be able to access the attribute and set its value. Did I say that right On Wednesday 16 November 2005 02:53 pm, Alan Gauld wrote: > > markersExp = ['big','boss','two','three'] > > for mark in markersExp: > > print y.mark > > > > Now I have an list of class objects that are in an outerloop. y is how I > > access it. The attributes names of the class objects match whats in > > markersExp. > > Do you have to use string versions of the class names? > Why not: > > class Mark: mark = 42 > class big(Mark): pass > class boss(Mark): pass > class two(Mark): pass > class three(Mark): pass > > markersExp = [big,boss.two,three] > > for cls in markersExp: print cls.mark > > Classes are objects too! > > > Can I do that print statement in a way to allow me to print the > > value of the class attribute? > > Or are we really talking about instances? In which case the usual solution > is a dictionary. > > Alan g. -- Eric Walker EDA/CAD Engineer Work: 208-368-2573 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] new topic draft
Alan Gauld schrieb: > Thanks, I may use that as one of the example programs if > you don't mind? I took the liberty of refactoring Johan's example a bit, to make it more reusable. See attached file. Chris """Wrapper object for external commands, that allows to kill them after later.. ::Author: Johan Geldenhuys [EMAIL PROTECTED] ::Version: 0.0.2 ::Date last updated: 2005-11-16 ::Changes: - refactored by Christopher Arndt :: TODO: Capture the output from line 41 to a file. """ import os, signal, time class KillableCommand(object): def __init__(self, command, *args): self.pid = None self.command = command self.args = args def kill(self, signal=signal.SIGTERM): try: os.kill(self.pid, signal) except: raise OSError, "Could not kill process." def run(self, *args): self.pid = os.fork() args = list(self.args + args) if self.pid == 0: os.execvp(self.command, [self.command] + args) if __name__ == '__main__': cmdname = "ping" print "Starting", cmdname #cmd = KillableCommand('tcpdump', '-npi') cmd = KillableCommand(cmdname, '-c', '10') cmd.run('www.python.org') print "PID: ", cmd.pid print "Letting it run for 5 seconds..." time.sleep(5) try: print "Trying to kill pid %d..." % cmd.pid cmd.kill() except OSError, e: print e else: print "Killed pid %d." % cmd.pid ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] lambda in a loop
def doLambda(val): print "value 2:", val commands = [] for value in range(5): print "value 1:", value commands.append(lambda:doLambda(value)) Close but not quite. Try: commands.append(lambda v=value:doLambda(v)) value is a local variable in doLambda so when it executes it uses whatever the global 'value' is set at, which at the end of the loop will be 4. By using the default argument and passing that you freeze the value at whatever it is at the time of setting (a fortuitous by-product of how default parameters work!) HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Using lists as table-like structure
> But as soon as I introduce the [0], in an attempt to access the first > element of each sublist, I get the first sublist in its entirety: > aList[:][0] > [1, 1, 1] aList[:] is the shorthand way of taking a copy of aList thus aList[:][0] is the same as saying aList[0] except you get a new item. Thus you could change the content of this version of [1,1,1] without affecting the original. Handy, but not what you want. I don't know any easy way of getting the first items except maybe a list comprehension: [lst[0] for lst in aList] You could turn that into a parameterised function def getRow(n): return [lst[n] for lst in aList] Does that help? Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Using lists as table-like structure
On Wed, 16 Nov 2005, Bernard Lebel wrote: > Let say I have a list of lists. Each individual lists have a bunch of > elements. Now I would like to either get or set the first element of > each individual list. I could do a loop and/or list comprehension, but I > was wondering if it was possible with something like: > > aList = [ [1,1,1], [2,2,2,], [3,3,3] ] > aList[:][0] = 10 Hi Bernard, I think I see what you're trying to do; you're trying to clear the first column of each row in your matrix. Unfortunately, this is not done so easily in standard Python. However, if you use the third-party Numeric Python (numarray) package, you can use its array type to do what you want. > If I print aList[:], I get the list with the nested sublists. > > >>> aList[:] > [[1, 1, 1], [2, 2, 2], [3, 3, 3]] Yes, sounds good so far. > But as soon as I introduce the [0], in an attempt to access the first > element of each sublist, I get the first sublist in its entirety: > > >>> aList[:][0] > [1, 1, 1] Let's do a quick substitution model thing here. You mentioned earlier that: > >>> aList[:] > [[1, 1, 1], [2, 2, 2], [3, 3, 3]] So if we just plug that value into aList[:][0]: aList[:][0] ==> [[1, 1, 1,], [2, 2, 2], [3, 3, 3]] [0] then we see that we're just asking for the first element of aList[:], which is [1, 1, 1]. > I would have hoped to get something like [1, 2, 3] Take a look into Numeric Python: it'll give you the row/column slicing operations that you're expecting. As a concrete example: ## >>> import numarray >>> a = numarray.array([[1, 2, 3], ... [4, 5, 6], ... [7, 8, 9]]) >>> a[:, 0] array([1, 4, 7]) >>> a[:, 1] array([2, 5, 8]) >>> a[:, 2] array([3, 6, 9]) ## Best of wishes! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] class attributes
Eric Walker wrote: > ahh, you just blew smoke in my face. :) > > I have a class with attributes. These attributes eventually have the value of > some lines in a file. I am now going back through my object list of that > class and assigning values to the attributes depending on another variable > that will change and be the same names like the class attribute names. I > want to use that change in name to be able to access the attribute and set > its value. Did I say that right Use getattr() to read an attribute by name and setattr() to set it. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] class attributes
> I have a class with attributes Are they class attributes - shared by all instances of the class or are they instance attributes - unique values in each instance? > I am now going back through my object list of that > class So you have a list of all the instances of the class and modifying values. Since you do it on a per instance basis I assume that means the attributres are instance attributes(ie created inside an init method)? > assigning values to the attributes depending on another variable > that will change and be the same names like the class attribute names. So the names are names of attributes not names of classes? In that case I think you need to use setattr() I think... Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] lambda in a loop
Christian Wyglendowski wrote: >>-Original Message- >>From: [EMAIL PROTECTED] >> If I have this code: >> Obviously, the lambda is using "value" at the end of the loop (4), >>rather than what I want, "value" during the loop (0,1,2,3). > > Right. I think the issue is that your lambda calls another funtion. > However, the function isn't called until the lambda is called later, > when value == 4. No, the problem is not when the function is called, but when value is bound into the closure. > I'd use a closure rather than a lambda. The original solution does use a closure. The problem is that variables are not bound into a closure until the scope of the variable exits. That is why using a separate factory function works - the closure is bound when the factory function exits which happens each time through the loop. In the case of closures in a loop the closure is not bound until exiting the scope containing the loop and all the closures are bound to the same value. Kent -- http://www.kentsjohnson.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] class attributes
> Are they class attributes - shared by all instances of the class or are > they instance attributes - unique values in each instance? all instances of the class share these attributes. > So you have a list of all the instances of the class and modifying values. > Since you do it on a per instance basis I assume that means the attributres > are instance attributes(ie created inside an init method)? yes they are created with an __init__ method > > > assigning values to the attributes depending on another variable > > that will change and be the same names like the class attribute names. > > So the names are names of attributes not names of classes? > In that case I think you need to use setattr() Yes, they are names of the attributes, and yes I am using setattr and getattr now. thanks you all for your great advice -- Eric Walker EDA/CAD Engineer Work: 208-368-2573 ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] lambda in a loop
> The original solution does use a closure. The problem is that variables > are not bound into a closure until the scope of the variable exits. That > is why using a separate factory function works - the closure is bound > when the factory function exits which happens each time through the > loop. In the case of closures in a loop the closure is not bound until > exiting the scope containing the loop and all the closures are bound to > the same value. [Warning: really subtle concepts ahead. You should probably skip this if you're a newcomer to programming, because this is not really going to make sense at all. *grin* This message is also really long. Sorry, but I haven't figured out how to talk about this concisely yet.] Hi Kent, There's some confusion here. People are making an artificial distinction between the "closure" values built by lambda vs the function values built by 'def'. They're the same kind of thing. ## >>> commands = [] >>> def sayNumber(n): ... print n ... >>> for i in range(5): ... commands.append((lambda v: lambda: sayNumber(v))(i)) ... >>> >>> for c in commands: ... c() ... 0 1 2 3 4 ## Kent's explanation here: > In the case of closures in a loop the closure is not bound until exiting > the scope containing the loop and all the closures are bound to the same > value. makes it sounds like closures somehow twiddle their thumbs and wait till things go out of scope before closing on their environment. This is not what is happening. They capture the environment as soon as they're constructed. The issue, then, isn't "when" closures are constructed: it's "what": what's in the environment when we make a closure? Just to make sure we all have the same conceptual model: Python's toplevel environment can be seen as thing that attaches names to values --- a namespace. Let's dive into that model and make sure we understand how it works. [Side note: the following is adapted from material in SICP, http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-21.html#%_sec_3.2] We can see the keys of that namespace by doing dir(): ## >>> dir() ['__builtins__', '__doc__', '__name__'] ## Just to be able to talk about things, let's give a name to the global namespace as: "G". Whenever we call a function, we build a new environment that's chained up to the one we're in at the time of function construction. This corresponds to what people's ideas of the "stack frame" is. ## >>> def x(): ... print dir() ... >>> x() [] ## When we're calling x(), let's give a name to that environmental frame as "X". (I'm sorry for doing the uppercase-lowercase thing, but it makes it easier for me to remember what environment goes with what function!) "X" is empty, but that doesn't prevent our x function from calling global stuff, because "X" is chained up to "G". Let me use some funky notation to draw the state of the environments: [X | ] > [G | __builtins__=...] When we try to access a name in X, if the lookup fails, the hunt will continue down the chain of environments toward the global environment G. The above diagram using an ad-hoc bracket/pipe notation to try to visually what an environment frame might be. It tries to make it clear that G has bindings to things like __builtins__, and that the frames can be chained up together. Let's try a slightly different example: ## >>> def y(): ... someNumber = 42 ... print dir() ... >>> y() ['someNumber'] ## y() was also created at toplevel, so whenever we call y(), we'll create a new environment "Y" that get's chained up to the toplevel environment "G". We see that assigning local variables adds bindings to "Y", so at the end of calling y(), right before we return, our world looks like this: [Y | someNumber=42]>[G | __builtins__=...] Let's take a look at something that touches on what people think of as a closure: ## >>> def z(): ... someNumber = 5 ... def inner(): ... print someNumber ... return inner ... ## When we create z(), we're at the toplevel environment G again, so whenever Z gets called, it'll make a new environment frame whose parent is "G". Ok, let's call z(): ## >>> value = z() ## When we call z(), we create a fresh new environment frame "Z" that's attached to G. our environment looks like: [Z |] > [G | __builtins__=...] We then add the someNumber binding to "Z". Our environment now looks like: [Z | someNumber=5] > [G | __builtins__=...] Then we hit the 'def inner(): ...' call: that's a function construction. When we define inner(), that function will remember it's origin environment: [Z | someNumber=5] > [G | __builtins__=...] And whenever we call that inner() function, it'll make a fresh environment I attached to that origin environment. We captures that function in 'value', so let's call that now from the toplevel: ## >>> value() 5 ## When we call value(),
Re: [Tutor] lambda in a loop
> Just to be able to talk about things, let's give a name to the global > namespace as: "G". > > Whenever we call a function, we build a new environment that's chained up > to the one we're in at the time of function construction. This > corresponds to what people's ideas of the "stack frame" is. Argh. Scratch that last sentence in there; I thought I deleted that part. The environment model has nothing to do with the stack traceback; my apologies! ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] Passing HTTP commands through Telnet using Python for web site testing?
Hi, I just started learning Python and would like to try writing a monitoring script. What I would like to do is use Telnet to send a GET via port 80 to a status page in a directory to verify my site is up. Psuedo code: Connect = telnet website.com 80 Send = GET /folder/folder/test.asp HTTP/1.1 Host: website.com Pipe the Response to a file (overwriting it each time): HTTP/1.1 400 Bad Request Server: Server: Microsoft-IIS/5.0 Date: Wed, 16 Nov 2005 20:15:20 GMT X-Powered-By: ASP.NET Connection: close Server: website.com Content-Length: 102 Content-Type: text/html GREP "HTTP/1.1 400 Bad Request" from the file and | append >> it into a log. This tells me the connection was valid. Timestamping the line would be nice. The other error code could be "HTTP/1.1 404 Not Found" if the directory went missing or possibly "Cound not open connection" if the connection could not be made. If the above GREP is found in the file do nothing. If not send an email stating the error. End Anyway, Can someone point me in the right direction on getting the Telnet working? Or if you have a better way to get what I am trying to do accomplished. Is there a Python Telnet module? Thanks in advance ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Passing HTTP commands through Telnet using Python for web site testing?
So far this is what I have come up with doing some research. import urllib for line in urllib.urlopen('http://mywebsit.com/folder/folder/test.asp'): if '400 Bad Request' in line: text_file = open("mysite.log", "a") text_file.writelines(line) text_file.writelines("\n") text_file.close() This writes the to a new line each time the script is run. Now I have to figure out an "if then else" to write the other possible error codes and appending a timestamp followed by a space each time it runs. Thanks ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
[Tutor] split a tuple
Hi, I couldn't get idea how to make the next thing >>> n=4 #split into so long parts >>> l = (1,2,3,4,5,1,2,3,4,5,1,2,3,4,5) #this is the tuple to split >>> [l[i:i+n] for i in range(0,len(l),n)] [(1, 2, 3, 4), (5, 1, 2, 3), (4, 5, 1, 2), (3, 4, 5)] But I have to make it like this [(1, 2, 3, 4), (5, 1, 2, 3), (4, 5, 1, 2), (3, 4, 5, default)] because i use it later in this >>> result = [l[i:i+n] for i in range(0,len(l),n)] >>> zip(*result) [(1, 5, 4, 3), (2, 1, 5, 4), (3, 2, 1, 5)] and as you can see it, the last element is missing here. Yours sincerely, __ János Juhász ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor