From tpc at csua.berkeley.edu Wed Sep 1 08:35:02 2004 From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Wed Sep 1 08:35:07 2004 Subject: [Tutor] list of floats, strange behavior Message-ID: <20040831233251.F17091-100000@localhost.name> hi everybody, I was wondering if someone could help me understand why IDLE seems to expand the largest value in a series of floating points I decided to put in a list: >>> list01 = [.1028, .1248, .0998, .1101, .1062] >>> list01.sort() >>> list01 [0.0998, 0.1028, 0.1062, 0.1101, 0.12479999999999999] I don't particularly want that value expanded like that. From python at bernardlebel.com Wed Sep 1 10:18:34 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Wed Sep 1 10:18:55 2004 Subject: [Tutor] list of floats, strange behavior References: <20040831233251.F17091-100000@localhost.name> Message-ID: <005001c48ffc$4abe42d0$0d01a8c0@studioaction.local> Hi, In the tutorial (I think) from the Python docs there is an explanation about this problem, wich is inherent to floating point numbers in computers. Very interesting read. Cheers Bernard ----- Original Message ----- From: <tpc@csua.berkeley.edu> To: <tutor@python.org> Sent: Wednesday, September 01, 2004 8:35 AM Subject: [Tutor] list of floats, strange behavior > > hi everybody, I was wondering if someone could help me understand why IDLE > seems to expand the largest value in a series of floating points I decided > to put in a list: > > >>> list01 = [.1028, .1248, .0998, .1101, .1062] > >>> list01.sort() > >>> list01 > [0.0998, 0.1028, 0.1062, 0.1101, 0.12479999999999999] > > I don't particularly want that value expanded like that. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > > From kent_johnson at skillsoft.com Wed Sep 1 13:02:02 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Wed Sep 1 13:02:11 2004 Subject: [Tutor] Drive listing In-Reply-To: <000701c48f9e$40dac3a0$96c48f52@allmycore> References: <000701c48f9e$40dac3a0$96c48f52@allmycore> Message-ID: <6.1.0.6.0.20040901065949.028f3710@mail4.skillsoft.com> You need win32all, get it here http://starship.python.net/crew/mhammond/ Then see here http://groups.google.com/groups?selm=mailman.1011113008.15423.python-list%40python.org and here http://insom.me.uk/blog/Tech/Python/getdrives.writeback Kent At 11:05 PM 8/31/2004 +0200, Ole Jensen wrote: >How is it possiple to list the drives on a current system? is there som >module that will output this some thing like listdrives() ? I have >browsed the Global Module Index for relating functions but haven't found >anything. > >Or would I need to create my own function? something similiar to. > >Not testet: >from os.path import exists >from string import ascii_lowercase as lcase > >def drive(): > for i in lcase: > drive = i + ':/' > drives = [] > if exists(drive): > drives.append(drive) > return drives > > >Ole Jensen > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From padmaja at agere.com Wed Sep 1 13:50:28 2004 From: padmaja at agere.com (Jayanthi, Satya Padmaja (Satya Padmaja)) Date: Wed Sep 1 13:50:38 2004 Subject: [Tutor] Python - TCL Interaction Message-ID: <DFCB7C708B1AA94FABFBF6E1F7E984542E6E0B@iiex2ku01.agere.com> Hi : I am using Tkinker to interface Python to TCL. I am able to call tcl APIs, pass the input parameters as strings to the TCL APIs, fetch the return values from the TCL APIs etc... From the python code. Now, the problem is I have to pass a two dimensional list (the elements of the list are also lists) to the tcl file. How can I do it ? If I simply use the "%s" option, the error that is thrown is "_tkinter.TclError: invalid command name "'apple',"" import Tkinter root = Tkinter.Tk() root.tk.eval('source test_tcl_file.tcl') arr = [["apple", "mango", "orange"], ["rose", "jasmine", "marigold"]] root.tk.eval('test_tcl_func %s', %(list)) I have tried many tricks.Tried setting the array in the python file etc. root.tk.eval('global arr; lappend arr %s' %(s)). But nothing works. Can anyone of you please help me ? Thanks and Regards, Padmaja -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040901/b3378d2c/attachment.htm From python at pointcontrol.com Wed Sep 1 14:09:04 2004 From: python at pointcontrol.com (Barry Tice) Date: Wed Sep 1 14:09:07 2004 Subject: [Tutor] list of floats, strange behavior In-Reply-To: <005001c48ffc$4abe42d0$0d01a8c0@studioaction.local> References: <20040831233251.F17091-100000@localhost.name> <005001c48ffc$4abe42d0$0d01a8c0@studioaction.local> Message-ID: <1094040543.2430.5.camel@localhost.localdomain> Yes, the explanation of floating-point rounding errors is in Appendix B of the tutorial. The long and short of it is, floating point numbers are stored as binary fractions. Consider that in a base-three number system, the number that in decimal we refer to as 1/3 would be 0.1. In decimal, it's 0.3333333333(etc.). There is no exact value in base 10 for something that's easy to represent in base 3. Similarly, there are many things that can be represented in base 10 that can't be exactly specified in binary, base 2. (0.1, for example.) So based on the underlying C representation, Python makes its best guess and comes up with the closest number it can. -- b.r.t. On Wed, 2004-09-01 at 03:18, Bernard Lebel wrote: > Hi, > > In the tutorial (I think) from the Python docs there is an explanation about > this problem, wich is inherent to floating point numbers in computers. > Very interesting read. > > > Cheers > Bernard > > ----- Original Message ----- > From: <tpc@csua.berkeley.edu> > To: <tutor@python.org> > Sent: Wednesday, September 01, 2004 8:35 AM > Subject: [Tutor] list of floats, strange behavior > > > > > > hi everybody, I was wondering if someone could help me understand why IDLE > > seems to expand the largest value in a series of floating points I decided > > to put in a list: > > > > >>> list01 = [.1028, .1248, .0998, .1101, .1062] > > >>> list01.sort() > > >>> list01 > > [0.0998, 0.1028, 0.1062, 0.1101, 0.12479999999999999] > > > > I don't particularly want that value expanded like that. > > From alan.gauld at blueyonder.co.uk Wed Sep 1 14:23:54 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Sep 1 14:23:07 2004 Subject: [Tutor] list of floats, strange behavior References: <20040831233251.F17091-100000@localhost.name> Message-ID: <03be01c4901e$8c11c550$6401a8c0@xp> > hi everybody, I was wondering if someone could help me understand why IDLE > seems to expand the largest value in a series of floating points It doesn't expand the largest value as such it just expands to the best accuracy that it can provide. YThis is a problem with the way computers store floating point numbers. Its related to the fact that one third in decimal is 0.3333333...forever. In other words you can't exactly represent it in decimal. The same happens in binary. However if you want to print it out you have lots of options for tidying it up. The default print will tidy it a bit, and for more control you can use the format string: >>> print "%7.5f" % 0.12479999999999999 0.12480 ie 7 characters long with 5 decimal places... > >>> list01 > [0.0998, 0.1028, 0.1062, 0.1101, 0.12479999999999999] Trying print: >>> print list01[-1] 0.1248 HTH, Alan G From blk20 at cam.ac.uk Wed Sep 1 14:33:30 2004 From: blk20 at cam.ac.uk (blk20) Date: Wed Sep 1 14:25:16 2004 Subject: [Tutor] Introduction In-Reply-To: <1094040543.2430.5.camel@localhost.localdomain> References: <20040831233251.F17091-100000@localhost.name> <005001c48ffc$4abe42d0$0d01a8c0@studioaction.local> <1094040543.2430.5.camel@localhost.localdomain> Message-ID: <1094042010.2348.99.camel@localhost> Hi there, my name is Bernhard Krieger. I am a social anthropologist undertaking research on free software and people involved in free software. I want to start programming and was pointed to python as a good beginner's language. I am reading 'Learning Python' by Mark Luty and David Ascher. It is fascinating, even it sometimes takes me a while to keep all the information;) Is there anything else you would recommend me to learn Python? Cheers, --Bernhard From python at pointcontrol.com Wed Sep 1 14:37:57 2004 From: python at pointcontrol.com (Barry Tice) Date: Wed Sep 1 14:38:04 2004 Subject: [Tutor] Introduction In-Reply-To: <1094042010.2348.99.camel@localhost> References: <20040831233251.F17091-100000@localhost.name> <005001c48ffc$4abe42d0$0d01a8c0@studioaction.local> <1094040543.2430.5.camel@localhost.localdomain> <1094042010.2348.99.camel@localhost> Message-ID: <1094042276.2430.12.camel@localhost.localdomain> Guido's Python tutorial is a good place to start, though I imagine it's probably less complete than any book you purchased. From there, reading through the reference manual for the modules you expect to use the most, while keeping the interpreter running for experiments, will teach you a great deal. I've always found the best way to learn a language is to have a project you want to do and dive in and get your hands dirty. This sometimes involves coming up with smaller projects to accomplish first -- say if your main project requires XML, you might want to have a smaller starter-project devoted to working out the intricacies of XML before you spend too much time going in a misguided direction on your main project. -- b.r.t. On Wed, 2004-09-01 at 07:33, blk20 wrote: > Hi there, > > my name is Bernhard Krieger. I am a social anthropologist undertaking > research on free software and people involved in free software. > > I want to start programming and was pointed to python as a good > beginner's language. I am reading 'Learning Python' by Mark Luty and > David Ascher. It is fascinating, even it sometimes takes me a while to > keep all the information;) > > Is there anything else you would recommend me to learn Python? > > Cheers, > --Bernhard > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From T.Chern at unibas.ch Wed Sep 1 14:52:57 2004 From: T.Chern at unibas.ch (Tzu-Ming Chern) Date: Wed Sep 1 14:53:06 2004 Subject: [Tutor] Suggestions as to how to read a file in paragraphs Message-ID: <Pine.OSF.4.21L.0409011449190.7642-100000@igor.urz.unibas.ch> Dear Python tutors, What is a more efficient way to read a file and split it into paragraphs and just print those paragraphs which match a particular condition? The inefficient way is to read the whole file into one string and then split it, but this becomes problematic with larger files. Any suggestions on a more efficient approach or is there a module available? Cheers, tzuming From adam at monkeez.org Wed Sep 1 14:54:28 2004 From: adam at monkeez.org (adam) Date: Wed Sep 1 14:54:31 2004 Subject: [Tutor] String to integer? Message-ID: <27761.217.206.168.163.1094043268.spork@webmail.monkeez.org> I have a list which holds all the letters of the alphabet. I want to create a button (wxPython) for each of these letters and then give the button an ID (count - which is an integer). However, I would like the ID to be driven by the list (which is string). See code below. What's the easiest way of creating an integer which is based on a value of a letter? I really don't mind if it was based on the ascii code, or another equivalent. Thanks in advance. Adam alphabet = ['a','b','c','d','e' ... and so on. for i in alphabet: count = count + 1 bmp = wxBitmap('alphabet_graphics/' + i + '.bmp', wxBITMAP_TYPE_BMP) self.grafic =wxBitmapButton(self, count,bmp,wxPoint(160,20), wxSize(bmp.GetWidth()+10,bmp.GetHeight()+10)) self.sizer2.Add(self.grafic,1,wxEXPAND) EVT_BUTTON(self, count, self.ButtonPushed) From python at bernardlebel.com Wed Sep 1 15:00:36 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Wed Sep 1 15:00:44 2004 Subject: [Tutor] String to integer? References: <27761.217.206.168.163.1094043268.spork@webmail.monkeez.org> Message-ID: <00b201c49023$ad72bf10$0d01a8c0@studioaction.local> Personally I'd consider using a dictionary for that. Assign the letter (the key) to the number (the value). Cheers Bernard ----- Original Message ----- From: "adam" <adam@monkeez.org> To: <tutor@python.org> Sent: Wednesday, September 01, 2004 2:54 PM Subject: [Tutor] String to integer? > I have a list which holds all the letters of the alphabet. I want to > create a button (wxPython) for each of these letters and then give the > button an ID (count - which is an integer). However, I would like the ID > to be driven by the list (which is string). See code below. > > What's the easiest way of creating an integer which is based on a value of > a letter? I really don't mind if it was based on the ascii code, or > another equivalent. > > Thanks in advance. > > Adam > > alphabet = ['a','b','c','d','e' ... and so on. > for i in alphabet: > count = count + 1 > bmp = wxBitmap('alphabet_graphics/' + i + '.bmp', wxBITMAP_TYPE_BMP) > self.grafic =wxBitmapButton(self, count,bmp,wxPoint(160,20), > wxSize(bmp.GetWidth()+10,bmp.GetHeight()+10)) > self.sizer2.Add(self.grafic,1,wxEXPAND) > EVT_BUTTON(self, count, self.ButtonPushed) > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From python at bernardlebel.com Wed Sep 1 15:16:31 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Wed Sep 1 15:16:39 2004 Subject: [Tutor] Listing function arguments Message-ID: <00cb01c49025$e6b81570$0d01a8c0@studioaction.local> Hello, Is there a way to list the arguments that a variable is accepting? For instance, the first line of a function looks like this: def cmcopy( aClients = [], sSource = '', sTarget = '', iSource = 0 ): So I'd like to know the argument names, for 1- Know the order at wich the arguments must be passed 2- Know what variables to supply for arguments I don't know if I missed something in the documentation... Thanks Bernard From kent_johnson at skillsoft.com Wed Sep 1 15:16:48 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Wed Sep 1 15:16:52 2004 Subject: [Tutor] Introduction In-Reply-To: <1094042010.2348.99.camel@localhost> References: <20040831233251.F17091-100000@localhost.name> <005001c48ffc$4abe42d0$0d01a8c0@studioaction.local> <1094040543.2430.5.camel@localhost.localdomain> <1094042010.2348.99.camel@localhost> Message-ID: <6.1.0.6.0.20040901091604.0287c620@mail4.skillsoft.com> You can read my recommendations here: http://personalpages.tds.net/~kent37/Python/PythonResources.html Kent At 02:33 PM 9/1/2004 +0200, you wrote: >Hi there, > >my name is Bernhard Krieger. I am a social anthropologist undertaking >research on free software and people involved in free software. > >I want to start programming and was pointed to python as a good >beginner's language. I am reading 'Learning Python' by Mark Luty and >David Ascher. It is fascinating, even it sometimes takes me a while to >keep all the information;) > >Is there anything else you would recommend me to learn Python? > >Cheers, >--Bernhard > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From bwinton at latte.ca Wed Sep 1 15:27:12 2004 From: bwinton at latte.ca (Blake Winton) Date: Wed Sep 1 15:27:15 2004 Subject: [Tutor] String to integer? In-Reply-To: <27761.217.206.168.163.1094043268.spork@webmail.monkeez.org> References: <27761.217.206.168.163.1094043268.spork@webmail.monkeez.org> Message-ID: <4135CE30.3090207@latte.ca> adam wrote: > What's the easiest way of creating an integer which is based on a value of > a letter? I really don't mind if it was based on the ascii code, or > another equivalent. >>> ord('a') 97 >>> chr(97) 'a' >>> ord('ab') Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: ord() expected a character, but string of length 2 found (Putting on my user-hat for a second, you _really_ want 26 buttons on a single form?!? That's probably going to be confusing to look at. Is there another way you could get the user's input?) Later, Blake. From kent_johnson at skillsoft.com Wed Sep 1 15:30:12 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Wed Sep 1 15:30:15 2004 Subject: [Tutor] Suggestions as to how to read a file in paragraphs In-Reply-To: <Pine.OSF.4.21L.0409011449190.7642-100000@igor.urz.unibas.c h> References: <Pine.OSF.4.21L.0409011449190.7642-100000@igor.urz.unibas.ch> Message-ID: <6.1.0.6.0.20040901091752.0287c390@mail4.skillsoft.com> You could read the file by lines and accumulate lines in a list until you find a paragraph break. Then look at the accumulated lines and see if you want to print it. Something like this (assuming a blank line is a paragraph break): linesInPara = [] for line in f: if not line.strip(): processParagraph(linesInPara) linesInPara = [] else: linesInPara.append(line) if linesInPara: processParagraph(linesInPara) At 02:52 PM 9/1/2004 +0200, Tzu-Ming Chern wrote: >Dear Python tutors, > >What is a more efficient way to read a file and split it into paragraphs >and just print those paragraphs which match a particular condition? > >The inefficient way is to read the whole file into one string and then >split it, but this becomes problematic with larger files. Any suggestions >on a more efficient approach or is there a module available? > >Cheers, >tzuming > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From rha207 at yahoo.com Wed Sep 1 16:46:14 2004 From: rha207 at yahoo.com (Ron A) Date: Wed Sep 1 16:46:17 2004 Subject: [Tutor] help with __str__ Message-ID: <20040901144614.79255.qmail@web50906.mail.yahoo.com> In the small program below, I assume that rep is concantenated when a new object is created (instantiated?). If so, it seems that if you put a print statement in the string method it should be printed out when an object is created but it's not. I'm a little confused. Is there somewhere that explains this in a simple way so even I can understand it? class Names(object): def __init__(self, first, last): self.first = first self.last = last print self.first def __str__(self): rep = self.first + " " + self.last return rep Ron A _______________________________ Do you Yahoo!? Win 1 of 4,000 free domain names from Yahoo! Enter now. http://promotions.yahoo.com/goldrush From kent_johnson at skillsoft.com Wed Sep 1 17:15:06 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Wed Sep 1 17:15:15 2004 Subject: [Tutor] help with __str__ In-Reply-To: <20040901144614.79255.qmail@web50906.mail.yahoo.com> References: <20040901144614.79255.qmail@web50906.mail.yahoo.com> Message-ID: <6.1.0.6.0.20040901110953.0287b058@mail4.skillsoft.com> Ron, In Python, expressions are not evaluated until the flow of control actually reaches them. Names.__str__() will not be called until a Names object is printed. You can demonstrate this by changing the value of first or last: >>> class Names: ... def __init__(self, first, last): ... self.first = first ... self.last = last ... def __str__(self): ... rep = self.first + ' ' + self.last ... return rep ... >>> n=Names('Kent', 'Johnson') >>> print n Kent Johnson >>> n.first = 'Joe' >>> print n Joe Johnson (In your code, if you change "print self.first" to "print self" in __init__(), then __str__ will be called when the object is created.) Kent At 07:46 AM 9/1/2004 -0700, Ron A wrote: >In the small program below, I assume that rep is >concantenated when a new object is created >(instantiated?). >If so, it seems that if you put a print statement in >the string method it should be printed out when >an object is created but it's not. I'm a little >confused. Is there somewhere that explains this in a >simple way so even I can understand it? > >class Names(object): > def __init__(self, first, last): > self.first = first > self.last = last > print self.first > > def __str__(self): > rep = self.first + " " + self.last > return rep > >Ron A > > > >_______________________________ >Do you Yahoo!? >Win 1 of 4,000 free domain names from Yahoo! Enter now. >http://promotions.yahoo.com/goldrush >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From H.FANGOHR at soton.ac.uk Wed Sep 1 17:21:17 2004 From: H.FANGOHR at soton.ac.uk (Hans Fangohr) Date: Wed Sep 1 17:21:47 2004 Subject: [Tutor] assigning __doc__ strings (manually) Message-ID: <Pine.LNX.4.60.0409011609270.7963@binx.sesnet.soton.ac.uk> Greetings, I am facing the following problem and would like some advise: I have two functions, say for simplicity, real_f and f: def real_f(x): """this is my doc-string""" return x**2, x**3 def f(x): return real_f(x)[0] The actual work is done in real_f() and some users might be interested in x**3 and x**2. However, most of the users will only care about x**2 and are happy to use the function f() for this. (In the actual program I am working on there is of course more work involved than just computing x**2 and x**3 ...) Since the main computation is done in real_f(), I thought I'd create a doc-string in real_f() that explains the computation being implemented etc (as done above). The function f() does basically the same as real_f() and should provide the same docstring as real_f(). To avoid copying the information, I thought I could do this when defining f(): def f(x): real_f.__doc__ return real_f(x)[0] which -- I was hoping -- would provide real_f.__doc__ in f.__doc__. However, f.__doc__ is None. Can this be solved? Or am I on the wrong track here? Looking forward to hearing from you, Hans From my.mailing.lists at noos.fr Wed Sep 1 17:23:32 2004 From: my.mailing.lists at noos.fr (nik) Date: Wed Sep 1 17:23:51 2004 Subject: [Tutor] problem with threads and C app Message-ID: <4135E974.2030402@noos.fr> hi, I'm trying to call some python methods from C, where the python module is running some threads. The python code seems to be working when I call the methods from the python command line, but when called from my C app, the thread doesn't seem to be created. The code is below, and if it worked, I'd expect the text 'tested' to appear if the thread was created (plus changes to the global variable i). However, nothing appears... the python code is; import thread i = 0 myLock = thread.allocate_lock() def test(): global i, orderListLock, clientLock print "tested" myLock.acquire() i = 50 myLock.release() def initialiseModule(): global i, clientLock # thread.start_new_thread(test,()) <- original plan was to create thread here print "started" for a in range(200): pass myLock.acquire() print i # is = 50 if I run from command line, but = 0 by running C app myLock.release() thread.start_new_thread(test,()) and the C code is; int main(int argc, char ** argv) { PyObject * module; PyObject * function; PyObject * result; Py_Initialize(); char *path, *newpath; // allows locating module in current folder path=Py_GetPath(); newpath=strcat(path, ":."); PySys_SetPath(newpath); free(newpath); module = PyImport_ImportModule("testThread"); function = PyObject_GetAttrString(module, "initialiseModule"); result = PyObject_CallFunction(function, NULL, NULL); Py_Exit(0); } Can anyone see what I'm doing wrong? thanks, nik From kent_johnson at skillsoft.com Wed Sep 1 17:31:38 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Wed Sep 1 17:31:44 2004 Subject: [Tutor] assigning __doc__ strings (manually) In-Reply-To: <Pine.LNX.4.60.0409011609270.7963@binx.sesnet.soton.ac.uk> References: <Pine.LNX.4.60.0409011609270.7963@binx.sesnet.soton.ac.uk> Message-ID: <6.1.0.6.0.20040901112937.0283aac8@mail4.skillsoft.com> You can assign f.__doc__ after f is defined: >>> def real_f(x): ... """this is my doc-string""" ... return x**2, x**3 ... >>> def f(x): ... return real_f(x)[0] ... >>> f.__doc__ = real_f.__doc__ >>> f.__doc__ 'this is my doc-string' Kent At 04:21 PM 9/1/2004 +0100, Hans Fangohr wrote: >Greetings, > >I am facing the following problem and would like some advise: > >I have two functions, say for simplicity, real_f and f: > >def real_f(x): > """this is my doc-string""" > return x**2, x**3 > >def f(x): > return real_f(x)[0] > > >The actual work is done in real_f() and some users might be interested >in x**3 and x**2. However, most of the users will only care about x**2 >and are happy to use the function f() for this. > >(In the actual program I am working on there is of course more work >involved than just computing x**2 and x**3 ...) > >Since the main computation is done in real_f(), I thought I'd create a >doc-string in real_f() that explains the computation being implemented >etc (as done above). > >The function f() does basically the same as real_f() and should >provide the same docstring as real_f(). To avoid copying the >information, I thought I could do this when defining f(): > >def f(x): > real_f.__doc__ > > return real_f(x)[0] > > >which -- I was hoping -- would provide real_f.__doc__ in >f.__doc__. However, f.__doc__ is None. > >Can this be solved? Or am I on the wrong track here? Looking forward >to hearing from you, > >Hans > > > > > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From bvande at po-box.mcgill.ca Wed Sep 1 12:11:19 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Wed Sep 1 18:11:48 2004 Subject: [Tutor] assigning __doc__ strings (manually) In-Reply-To: <Pine.LNX.4.60.0409011609270.7963@binx.sesnet.soton.ac.uk> References: <Pine.LNX.4.60.0409011609270.7963@binx.sesnet.soton.ac.uk> Message-ID: <4135A047.4010100@po-box.mcgill.ca> Hans Fangohr said unto the world upon 2004-09-01 17:21: > Greetings, > > I am facing the following problem and would like some advise: > > I have two functions, say for simplicity, real_f and f: > > def real_f(x): > """this is my doc-string""" > return x**2, x**3 > > def f(x): > return real_f(x)[0] > > > The actual work is done in real_f() and some users might be interested > in x**3 and x**2. However, most of the users will only care about x**2 > and are happy to use the function f() for this. > > (In the actual program I am working on there is of course more work > involved than just computing x**2 and x**3 ...) > > Since the main computation is done in real_f(), I thought I'd create a > doc-string in real_f() that explains the computation being implemented > etc (as done above). > <SNIP> > Hans > Hi Hans, I get that your code description was simplified, but I've a question and possibly a suggestion about it. (All this is orthogonal to your posted question.) From what you say, it seems like you are expecting most of the time the function f() will be the one used, and real_f() will be directly called much less often. As you describe your setup, f() essentially runs real_f() and throws away half the work it produces. (Are there needed side-effects to the "thrown-away" part of real_f() that you didn't mention?) In that context, wouldn't it be more efficient to put the computational work in f() directly and have real_f() call f() and then itself do the other needed work? I mean something like def f(x): return x**2 def real_f(x): return f(x), x**3 (Obviously the names you posted are no longer the ones to use in that f() now really does something itself, but I'm keeping your names structure.) It won't matter much for such simple computations as the toy ones of your post, and I get the "premature optimization is the root of all evil" point. But still, to this relative newcomer's mind, your structure seems undesirable. So, this is either a request for an explanation of what is wrong with what I say, or a helpful observation. I leave it to those higher up the pythonic peaks to determine which ;-) Best to all, Brian vdB From adam at monkeez.org Wed Sep 1 19:49:48 2004 From: adam at monkeez.org (Adam) Date: Wed Sep 1 19:49:56 2004 Subject: [Tutor] String to integer? In-Reply-To: <4135CE30.3090207@latte.ca> References: <27761.217.206.168.163.1094043268.spork@webmail.monkeez.org> <4135CE30.3090207@latte.ca> Message-ID: <41360BBC.9040500@monkeez.org> Blake Winton wrote: > adam wrote: > >> What's the easiest way of creating an integer which is based on a >> value of >> a letter? I really don't mind if it was based on the ascii code, or >> another equivalent. > > > >>> ord('a') > 97 > >>> chr(97) > 'a' > >>> ord('ab') > Traceback (most recent call last): > File "<stdin>", line 1, in ? > TypeError: ord() expected a character, but string of length 2 found > > (Putting on my user-hat for a second, you _really_ want 26 buttons on a > single form?!? That's probably going to be confusing to look at. Is > there another way you could get the user's input?) > > Later, > Blake. Blake, As this is an application designed to teach kids the alphabet, then yes, putting 26 buttons on the screen is pretty desirable. Adam -- site: http://www.monkeez.org wiki: http://wiki.monkeez.org From project5 at redrival.net Wed Sep 1 19:58:36 2004 From: project5 at redrival.net (Andrei) Date: Wed Sep 1 19:59:31 2004 Subject: [Tutor] Re: Listing function arguments References: <00cb01c49025$e6b81570$0d01a8c0@studioaction.local> Message-ID: <1mt20uc7pj4t6$.b8pimx4duso2$.dlg@40tude.net> Bernard Lebel wrote on Wed, 1 Sep 2004 15:16:31 +0200: > For instance, the first line of a function looks like this: > def cmcopy( aClients = [], sSource = '', sTarget = '', iSource = 0 ): > > So I'd like to know the argument names, for > 1- Know the order at wich the arguments must be passed > 2- Know what variables to supply for arguments > > I don't know if I missed something in the documentation... 1. Yep, you missed the help() function. If you type in the interactive interpreter help(myfunction), you'll get the declaration of myfunction plus the docstring of that function (if it's present). There are also IDE's which give you auto-complete proposals. 2. That's what the docstrings are for, given the fact that Python has no type declarations. -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From juicebypi216 at yahoo.com Wed Sep 1 20:05:44 2004 From: juicebypi216 at yahoo.com (Bryan) Date: Wed Sep 1 20:05:47 2004 Subject: [Tutor] Editing files through Python In-Reply-To: <6.1.0.6.0.20040830144818.04897338@mail.mric.net> Message-ID: <20040901180544.52078.qmail@web51002.mail.yahoo.com> Hi Bob, I've been playing around with the advice you was sent me and have become a little confused about the ideas of the input_file (r) and the output_file (w). Can they be the same file? Do I have to close the input file before writing to the output file? Does this example show what always has to be done when using input and output files? Here is the program I wrote following your example, and an error that always appears, relating to the input file, that is perplexing me. I think it probably has a simple solution, but I just don't understand enough about input and output files to figure it out. Is there anything in the Python tutorial or elsewhere that I can read more about reading and writing to input and output files. Here is the program: input_file = file('C:\BryFolder\coherence.dat', 'r') lines = input_file.readlines() output_file = file('C:\BryFolder\coherence.dat', 'w') for line in lines: nums = line.split(" ") retain = nums[:5] new_line = ", ".join(retain)+"\n" output_file.write(new_line) output_file.close() Here is the error: Traceback (most recent call last): File "C:\BryFolder\cohprog3.py", line 1, in ? input_file = file('C:\BryFolder\kt.1.24.data.036rd.test.dat', 'r') # substitute your path to the file IOError: [Errno 2] No such file or directory: 'C:\\BryFolder\\kt.1.24.data.036rd.test.dat' Thanks for the help Bryan Bob Gailer <bgailer@alum.rpi.edu> wrote:At 01:38 PM 8/30/2004, Bryan wrote: > >I am a beginner in Python, and this is my first time using this list so I >hope my question is acceptable. We are here to help, but not just give answers. However your request seems to me to merit a program, which I hope you will study to enhance your understanding of Python. Please ask more questions., >Basically, my goal is to read data files that are already on my hard drive >into Python, and then edit them, deleting unneccesary portions of data. > >I have already figured out how to read the files into Python, I just >cannot figure out how to edit them. Here are the difficulties: > >How do I delete, cut, or paste portions of the data I am reading and how >do I tell the program to jump to that specific portion of data that I want >to alter? The usual approach is to read the file into a Python variable, process the variable and write a new file (which can have the same name as the input file, rather than to attempt to manipulate the file itself. It is a LOT easier this way. > Here is a somewhat complicated example, similar to what I want to do - > >I have two rows of numbers, as shown below. Each row has 10 numbers >(hopefully they will show up as two rows of numbers in the email (1-10 and >11-20). > >1, 2, 3, 4, 5, 6, 7, 8, 9, 10 >11, 12, 13, 14, 15, 16, 17, 18, 19, 20 > >What commands might I use to automatically go through each row, deleting >the 6th through 10th numbers in each row (6-10 in the first row and 16-20 >in the second row). I have written a complete program, just to avoid any ambiguities. input_file = file('num.txt', 'r') # substitute your path to the file lines = input_file.readlines() # list of lines output_file = file('num.txt', 'w') # substitute your path to the file for line in lines: nums = line.split(", ") # assumes numbers separated by ", ", gives list of numbers retain = nums[:5] # keep first 5 numbers new_line = ", ".join(retain)+"\n" # reassemble into a line output_file.write(new_line) # write to file output_file.close() Please note this depends on consistent number separators. If the separators vary, then the approach gets more complex. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell --------------------------------- Do you Yahoo!? Yahoo! Mail - 50x more storage than other providers! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040901/5463e69a/attachment.htm From kent_johnson at skillsoft.com Wed Sep 1 20:28:23 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Wed Sep 1 20:28:35 2004 Subject: [Tutor] Re: Listing function arguments In-Reply-To: <1mt20uc7pj4t6$.b8pimx4duso2$.dlg@40tude.net> References: <00cb01c49025$e6b81570$0d01a8c0@studioaction.local> <1mt20uc7pj4t6$.b8pimx4duso2$.dlg@40tude.net> Message-ID: <6.1.0.6.0.20040901142512.02879870@mail4.skillsoft.com> The help function gets its juice from the inspect module and the docstrings: >>> def foo(a=None, b=''): ... pass ... >>> help(foo) Help on function foo in module __main__: foo(a=None, b='') >>> import inspect >>> inspect.getargspec(foo) (['a', 'b'], None, None, (None, '')) >>> inspect.formatargspec(*inspect.getargspec(foo)) "(a=None, b='')" Inspect is looking at attributes of the function object, you can look at the module source for details. Pretty amazing what you can find out just by digging into an object! Kent At 07:58 PM 9/1/2004 +0200, Andrei wrote: >Bernard Lebel wrote on Wed, 1 Sep 2004 15:16:31 +0200: > > > For instance, the first line of a function looks like this: > > def cmcopy( aClients = [], sSource = '', sTarget = '', iSource = 0 ): > > > > So I'd like to know the argument names, for > > 1- Know the order at wich the arguments must be passed > > 2- Know what variables to supply for arguments > > > > I don't know if I missed something in the documentation... > >1. Yep, you missed the help() function. If you type in the interactive >interpreter help(myfunction), you'll get the declaration of myfunction plus >the docstring of that function (if it's present). There are also IDE's >which give you auto-complete proposals. > >2. That's what the docstrings are for, given the fact that Python has no >type declarations. > >-- >Yours, > >Andrei From flaxeater at yahoo.com Wed Sep 1 20:32:53 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Wed Sep 1 20:32:56 2004 Subject: [Tutor] String to integer? Message-ID: <20040901183253.25312.qmail@web52609.mail.yahoo.com> Blake Winton wrote: > adam wrote: > >> What's the easiest way of creating an integer which is based on a >> value of >> a letter? I really don't mind if it was based on the ascii code, or >> another equivalent. > > > >>> ord('a') > 97 > >>> chr(97) > 'a' > >>> ord('ab') > Traceback (most recent call last): > File "<stdin>", line 1, in ? > TypeError: ord() expected a character, but string of length 2 found > > (Putting on my user-hat for a second, you _really_ want 26 buttons on > a single form?!? That's probably going to be confusing to look at. > Is there another way you could get the user's input?) > Well how about using hash() for getting your integers. This way it can be a string of any length. This is kinda neat I will probably always use this method from here on out. However I do not know if wxwidgets can accept negative id's which has does return but that's not the end of the world. It can be worked around. >>> hash('a') -468864544 >>> help(hash) Help on built-in function hash: hash(...) hash(object) -> integer Return a hash value for the object. Two objects with the same value have the same hash value. The reverse is not necessarily true, but likely. >>> hash('b') -340864157 >>> b='b' >>> hash(b) -340864157 _______________________________ Do you Yahoo!? Express yourself with Y! Messenger! Free. Download now. http://messenger.yahoo.com From python at bernardlebel.com Wed Sep 1 21:38:01 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Wed Sep 1 20:35:37 2004 Subject: [Tutor] Re: Listing function arguments References: <00cb01c49025$e6b81570$0d01a8c0@studioaction.local><1mt20uc7pj4t6$.b8pimx4duso2$.dlg@40tude.net> <6.1.0.6.0.20040901142512.02879870@mail4.skillsoft.com> Message-ID: <001301c4905b$32ff6ac0$2901a8c0@atyss> Once again, thanks a heap everyone for the help, most useful. Bernard From jeff at ccvcorp.com Wed Sep 1 21:12:46 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed Sep 1 21:12:45 2004 Subject: [Tutor] String to integer? In-Reply-To: <27761.217.206.168.163.1094043268.spork@webmail.monkeez.org> References: <27761.217.206.168.163.1094043268.spork@webmail.monkeez.org> Message-ID: <41361F2E.5090709@ccvcorp.com> adam wrote: > I have a list which holds all the letters of the alphabet. I want to > create a button (wxPython) for each of these letters and then give the > button an ID (count - which is an integer). However, I would like the ID > to be driven by the list (which is string). See code below. > > What's the easiest way of creating an integer which is based on a value of > a letter? I really don't mind if it was based on the ascii code, or > another equivalent. The potential gotcha here, that hasn't been being addressed, is that if you're using these integers as IDs inside wxPython then you need to be careful to select numbers that won't conflict with *other* IDs. One way of doing this would be to select a base ID, near the beginning of a range that you know is clear, and then defining each button's ID to be base_id + ord(char). However, there's rarely any need, in wxPython, to explicitly specify widget IDs. You're better off using either wxNewId() (or just passing in -1). If you need the ID for something, you can get it with wxWidget.GetId(). This does mean that you need to keep object references to your widgets, but that's probably a good idea anyhow -- you can easily set up a dictionary which maps a letter to a wxButton instance, and store that dictionary either on your parent window or in the wxApp instance... Jeff Shannon Technician/Programmer Credit International From jeff at ccvcorp.com Wed Sep 1 21:29:42 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Wed Sep 1 21:28:29 2004 Subject: [Tutor] Editing files through Python In-Reply-To: <20040901180544.52078.qmail@web51002.mail.yahoo.com> References: <20040901180544.52078.qmail@web51002.mail.yahoo.com> Message-ID: <41362326.90703@ccvcorp.com> Bryan wrote: > Hi Bob, > > I've been playing around with the advice you was sent me and have become > a little confused about the ideas of the input_file (r) and the > output_file (w). Can they be the same file? Do I have to close the > input file before writing to the output file? Does this example show > what always has to be done when using input and output files? > > Here is the program I wrote following your example, and an error that > always appears, relating to the input file, that is perplexing me. I > think it probably has a simple solution, but I just don't understand > enough about input and output files to figure it out. Is there anything > in the Python tutorial or elsewhere that I can read more about reading > and writing to input and output files. First, read the error message carefully. No such file or directory: C:\\BryFolder\\kt.1.24.data.036rd.test.dat This error is coming from the operating system underneath Python, and is saying that it can't find that file. Are you sure that this file already exists? You will have a difficult time reading from a file you haven't created yet. ;) Now, to answer your actual question -- you (generally) can't have more than one active filehandle to a given file at once. This means that, if you open the file for reading, then you need to close it before you reopen it for writing. > input_file = file('C:\BryFolder\coherence.dat', 'r') > lines = input_file.readlines() # add following line: input_file.close() > output_file = file('C:\BryFolder\coherence.dat', 'w') > for line in lines: > nums = line.split(" ") > retain = nums[:5] > new_line = ", ".join(retain)+"\n" > output_file.write(new_line) > output_file.close() Keep in mind that the first thing that happens when you open the file for writing is that, if it already exists, the contents are discarded. This means that, if something does go wrong, you could lose all data in the file. If you have copies of the data elsewhere, this may not matter, but it might be a bit safer to write to a different file, just in case. (Writing to a different file would also make it a bit clearer whether a given file had already been processed or not...) There *is* also a read/write file mode, where you can have a single file object that can be both read from and written to. This can be a bit tricky, though -- writing is always "replace" rather than "insert", and it's usually necessary to seek() a particular location before writing and flush() after writing, even if you think that you're already at the right location in the file. (There's some "fun" side-effects of the underlying C library's file-buffering scheme...) And in your case, it would have little benefit anyhow -- you don't want to leave part of the file as it is, so you might as well let open() truncate the file to nothing for you instead of doing it yourself. Jeff Shannon Technician/Programmer Credit International From adam at monkeez.org Wed Sep 1 21:28:33 2004 From: adam at monkeez.org (Adam) Date: Wed Sep 1 21:29:01 2004 Subject: [Tutor] String to integer? In-Reply-To: <00b201c49023$ad72bf10$0d01a8c0@studioaction.local> References: <27761.217.206.168.163.1094043268.spork@webmail.monkeez.org> <00b201c49023$ad72bf10$0d01a8c0@studioaction.local> Message-ID: <413622E1.2020300@monkeez.org> Bernard Lebel wrote: > Personally I'd consider using a dictionary for that. Assign the letter (the > key) to the number (the value). > > > Cheers > Bernard > Bernard, The dictionary worked a treat (although I had to spend half an hour working it out). Many thanks Adam -- site: http://www.monkeez.org wiki: http://wiki.monkeez.org From python at bernardlebel.com Wed Sep 1 23:22:05 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Wed Sep 1 22:19:44 2004 Subject: [Tutor] String to integer? References: <27761.217.206.168.163.1094043268.spork@webmail.monkeez.org><00b201c49023$ad72bf10$0d01a8c0@studioaction.local> <413622E1.2020300@monkeez.org> Message-ID: <002201c49069$bcf7aa90$2901a8c0@atyss> Hi Adam, Sorry for the learning curve, I should have mentioned that the tutorial that comes with the documentation covers dictionaries. That would have saved you some time I guess. My bad. Cheers Bernard ----- Original Message ----- From: "Adam" <adam@monkeez.org> Cc: <tutor@python.org> Sent: Wednesday, September 01, 2004 8:28 PM Subject: Re: [Tutor] String to integer? > Bernard Lebel wrote: > > > Personally I'd consider using a dictionary for that. Assign the letter (the > > key) to the number (the value). > > > > > > Cheers > > Bernard > > > > Bernard, > > The dictionary worked a treat (although I had to spend half an hour > working it out). > > Many thanks > > Adam > > > -- > site: http://www.monkeez.org > wiki: http://wiki.monkeez.org > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From alan.gauld at blueyonder.co.uk Wed Sep 1 22:38:31 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Sep 1 22:37:39 2004 Subject: [Tutor] Python - TCL Interaction References: <DFCB7C708B1AA94FABFBF6E1F7E984542E6E0B@iiex2ku01.agere.com> Message-ID: <03eb01c49063$a55aa640$6401a8c0@xp> > I am using Tkinker to interface Python to TCL. I am able > to call tcl APIs, While this is possoble its not really a "documented feature" of Tkinter. ie it's not normal practice! > Now, the problem is I have to pass a two dimensional list Whatever you pass to tk.eval needs to be in Tcl speak. arr = [["apple", "mango", "orange"], ["rose", "jasmine", "marigold"]] root.tk.eval('test_tcl_func %s', %(list)) So you can't pass a Python list as a Python list, it will be interpreted as a Tcl bracketed expression. Instead you will need to convert the Python list into a Tcl style list expressed as a string. So the question is how would you create a multi dimensional array/list in Tcl? How do you convert a Python list into that structure? It's basically a string formatting exercise. So I'd aim to do it in stages: Basic Tcl List building code: "set L [list 1 2 3]" Python: L1 = [1, 2, 3] L2 = [4, 5, 6] tclstr = 'set L1 [list ' for elem in L1: tclstr += (str(elem) + ' ') tclstr2 = "sel L2 [list " for elem in L2: tclstr += (str(elem) + ' ') tclstr = tclstr1 + ';' + tclstr2 + ';' + 'set L [list L1 L2]' Tk.eval(tclstr) Or something like that, I haven't tested it :-) Would it really be much harder to convert the Tcl code to Python? Alan G. From alan.gauld at blueyonder.co.uk Wed Sep 1 22:41:37 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Sep 1 22:40:44 2004 Subject: [Tutor] Introduction References: <20040831233251.F17091-100000@localhost.name><005001c48ffc$4abe42d0$0d01a8c0@studioaction.local><1094040543.2430.5.camel@localhost.localdomain> <1094042010.2348.99.camel@localhost> Message-ID: <03f401c49064$13af9560$6401a8c0@xp> > I want to start programming and was pointed to python as a good > beginner's language. I am reading 'Learning Python' by Mark Luty and > David Ascher. It is fascinating, even it sometimes takes me a while to > keep all the information;) If you've never programmed before I'd recommend running through one of the non-programmers intros first, then go back to Lutz. It will be faster I think in the long term. There is a list of non programmers intros on the Python site, I am, of course, biased towards my own :-) Also don;t neglect the official tutor that comes with Python, but like Lutz it assumes some previous experience in other languages. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/ From alan.gauld at blueyonder.co.uk Wed Sep 1 22:47:33 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Sep 1 22:46:40 2004 Subject: [Tutor] Suggestions as to how to read a file in paragraphs References: <Pine.OSF.4.21L.0409011449190.7642-100000@igor.urz.unibas.ch> Message-ID: <03fb01c49064$e81b2940$6401a8c0@xp> > What is a more efficient way to read a file and split it into paragraphs > and just print those paragraphs which match a particular condition? First, do you need the efficiency? Is it actually causing a problem just now? > The inefficient way is to read the whole file into one string and then > split it, but this becomes problematic with larger files. You are going to have to read the whole file anyhow so this might well be an efficient route provided you have enough RAM. > Any suggestions on a more efficient approach or is there a module available? Lots of modules might help (re, parser, string, fileinput etc) but nothing specifically for splitting text files by paragraph. (And how do you define a paragraph separator? Is it a blank line or is it an indented first line? Both are valid...) My case study topic in my tutorial does separate by blank lines but it makes no attempt to optimise efficiency. For moderate length files (a few hundred lines) it is adequate. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/ From kent_johnson at skillsoft.com Wed Sep 1 22:46:38 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Wed Sep 1 22:46:52 2004 Subject: [Tutor] Python - TCL Interaction In-Reply-To: <DFCB7C708B1AA94FABFBF6E1F7E984542E6E0B@iiex2ku01.agere.com > References: <DFCB7C708B1AA94FABFBF6E1F7E984542E6E0B@iiex2ku01.agere.com> Message-ID: <6.1.0.6.0.20040901164528.029b87e0@mail4.skillsoft.com> I'm curious, can you tell us why you are using this architecture? Why not use Tcl/Tk or Tkinter/Python? Thanks, Kent At 05:20 PM 9/1/2004 +0530, Jayanthi, Satya Padmaja (Satya Padmaja) wrote: >content-class: urn:content-classes:message >Content-Type: multipart/alternative; > boundary="----_=_NextPart_001_01C49019.E02077E0" >Content-Transfer-Encoding: 7bit > >Hi : > >I am using Tkinker to interface Python to TCL. I am able to call tcl APIs, >pass the input parameters as strings to the TCL APIs, fetch the return >values from the TCL APIs etc... From the python code. > >Now, the problem is I have to pass a two dimensional list (the elements of >the list are also lists) to the tcl file. How can I do it ? If I simply >use the "%s" option, the error that is thrown is "_tkinter.TclError: >invalid command name "'apple',"" > > import Tkinter > > root = Tkinter.Tk() > root.tk.eval('source test_tcl_file.tcl') > > arr = [["apple", "mango", "orange"], ["rose", "jasmine", > "marigold"]] > root.tk.eval('test_tcl_func %s', %(list)) > >I have tried many tricks.Tried setting the array in the python file etc. >root.tk.eval('global arr; lappend arr %s' %(s)). But nothing works. Can >anyone of you please help me ? > >Thanks and Regards, >Padmaja > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From alan.gauld at blueyonder.co.uk Wed Sep 1 22:48:46 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Sep 1 22:47:54 2004 Subject: [Tutor] String to integer? References: <27761.217.206.168.163.1094043268.spork@webmail.monkeez.org> Message-ID: <040001c49065$13c6aa60$6401a8c0@xp> > What's the easiest way of creating an integer which is based on a value of > a letter? I really don't mind if it was based on the ascii code, or > another equivalent. ASCII code is found from ord(char). Seems as good a planas any :-) Alan G. From alan.gauld at blueyonder.co.uk Wed Sep 1 22:56:53 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Sep 1 22:56:00 2004 Subject: [Tutor] Listing function arguments References: <00cb01c49025$e6b81570$0d01a8c0@studioaction.local> Message-ID: <040701c49066$3603d020$6401a8c0@xp> > Is there a way to list the arguments that a variable is accepting? > > For instance, the first line of a function looks like this: > def cmcopy( aClients = [], sSource = '', sTarget = '', iSource = 0 ): > > So I'd like to know the argument names, for > 1- Know the order at wich the arguments must be passed > 2- Know what variables to supply for arguments Lets get our terminology straight first. aClients, aSource etc are the parameter names of the function cmcopy If I do: L = [1,2,3] s = 'fred' t = 'tom' src = 42 cmcopy(L,s,t,src) The variable names are: L, s, t, src but the *arguments* are just the values that those variables hold and they are assined the temporary names aClients, sSource, sTarget, iSource for the duration of the function call. Thus if I do: cmcopy([1,2,3],'fred','tom',42) There are no argument names, but the argument values are: [1,2,3,], 'fred','tom',42 Almost exactly as they were above (except that the lists are not also referenced by the variables!) Which names do you want? And what dso you think you can do with them? If we know what you are trying to achieve we might be able to offer a better solution. :-) Alan G. From T.Chern at unibas.ch Wed Sep 1 22:56:49 2004 From: T.Chern at unibas.ch (Tzu-Ming Chern) Date: Wed Sep 1 22:56:57 2004 Subject: [Tutor] Suggestions as to how to read a file in paragraphs In-Reply-To: <03fb01c49064$e81b2940$6401a8c0@xp> Message-ID: <Pine.OSF.4.21L.0409012249380.27040-100000@igor.urz.unibas.ch> Hi Alan, > First, do you need the efficiency? Is it actually causing a problem > just now? Before yes, but not now. The efficiency is needed when very large files are needed and not enough RAM is available to process huge files (eg. > 3 million lines) > Lots of modules might help (re, parser, string, fileinput etc) but > nothing > specifically for splitting text files by paragraph. (And how do you > define a paragraph separator? Is it a blank line or is it an indented > first line? Both are valid...) Depending on the biological sequence files, the paragraph separator could be a "//" or newlines or any string really. I know in perl there is an input record separator which by default is the newline and one can specify this to a specific delimiter. Is there one in python? Apologies for the confusion! cheers, tzuming From alan.gauld at blueyonder.co.uk Wed Sep 1 23:01:31 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Sep 1 23:00:38 2004 Subject: [Tutor] Suggestions as to how to read a file in paragraphs References: <Pine.OSF.4.21L.0409011449190.7642-100000@igor.urz.unibas.ch> <6.1.0.6.0.20040901091752.0287c390@mail4.skillsoft.com> Message-ID: <041e01c49066$dbd74a40$6401a8c0@xp> > You could read the file by lines and accumulate lines in a list until you > find a paragraph break. Then look at the accumulated lines and see if you > want to print it. Something like this (assuming a blank line is a paragraph > break): Thats what I do in my cae study but its almost certainly slower than reading the entire file in one gulp then splitting by '\n\n' (ie a blank line) to get a list of paragraphs. But if memory is tight a loop with xreadlines() is probably best. OTOH I haven't benchmarked any of this :-) Alan G. From bill at celestial.net Wed Sep 1 23:00:37 2004 From: bill at celestial.net (Bill Campbell) Date: Wed Sep 1 23:00:43 2004 Subject: [Tutor] Suggestions as to how to read a file in paragraphs In-Reply-To: <03fb01c49064$e81b2940$6401a8c0@xp> References: <Pine.OSF.4.21L.0409011449190.7642-100000@igor.urz.unibas.ch> <03fb01c49064$e81b2940$6401a8c0@xp> Message-ID: <20040901210037.GA3584@alexis.mi.celestial.com> On Wed, Sep 01, 2004, Alan Gauld wrote: >> What is a more efficient way to read a file and split it into >paragraphs >> and just print those paragraphs which match a particular condition? > >First, do you need the efficiency? Is it actually causing a problem >just now? This sounds like somebody who is accustomed to perl's ability to tweak a variable causing the read operation to suck in paragraph at a time. Every time I've wanted to use this in perl, I've had to either go back to the perlvars documentation or find an existing program that used it to figure out what the variable name is. 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/ Many companies that have made themselves dependent on [the equipment of a certain major manufacturer] (and in doing so have sold their soul to the devil) will collapse under the sheer weight of the unmastered complexity of their data processing systems. -- Edsger W. Dijkstra, SIGPLAN Notices, Volume 17, Number 5 From alan.gauld at blueyonder.co.uk Wed Sep 1 23:21:20 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Sep 1 23:20:27 2004 Subject: [Tutor] help with __str__ References: <20040901144614.79255.qmail@web50906.mail.yahoo.com> Message-ID: <042301c49069$a05c5cf0$6401a8c0@xp> > In the small program below, I assume that rep is > concantenated when a new object is created > (instantiated?). rep only exists while __str__ is being executed which is during a print operation. If it weren't then the print would only ever show the values the object had when created which is not what most users would expect! > If so, it seems that if you put a print statement in > the string method it should be printed out when > an object is created but it's not. If you print self then Names.__str__() will be called but if you print self.first then self.first.__str__() will be called which is not defined in the code you show us. > confused. Is there somewhere that explains this in a > simple way so even I can understand it? Its almost as you think it is but you aren't doing what you think you are doing! :-) You are printing out self.first. It is whatever oject you pass in and print will use whatever string representation it has. If you want to call your __str__ method you must print an instance of the Names class, ie self. > class Names(object): > def __init__(self, first, last): > self.first = first > self.last = last > print self.first > > def __str__(self): > rep = self.first + " " + self.last > return rep HTH, Alan G. From python at bernardlebel.com Thu Sep 2 00:32:30 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Wed Sep 1 23:30:13 2004 Subject: [Tutor] Listing function arguments References: <00cb01c49025$e6b81570$0d01a8c0@studioaction.local> <040701c49066$3603d020$6401a8c0@xp> Message-ID: <000c01c49073$94639710$2901a8c0@atyss> Hi Alan, I was simply looking at listing the function parameter names, nothing more. :-) I wanted to know what the funciton uses for paramter names, so I can assign values to variables of the same name and pass them to the function. In the example I gave I provide default values for these arguments, but sometimes you want to know before hand what to supply to the function. However, unless you're working in PythonWin, it's not obvious. Anyway the tips given by Kent and Andrei are exactly what I wanted: help( myfunction ) Cheers Bernard ----- Original Message ----- From: "Alan Gauld" <alan.gauld@blueyonder.co.uk> To: "Bernard Lebel" <python@bernardlebel.com>; <tutor@python.org> Sent: Wednesday, September 01, 2004 9:56 PM Subject: Re: [Tutor] Listing function arguments > > Is there a way to list the arguments that a variable is accepting? > > > > For instance, the first line of a function looks like this: > > def cmcopy( aClients = [], sSource = '', sTarget = '', iSource = > 0 ): > > > > So I'd like to know the argument names, for > > 1- Know the order at wich the arguments must be passed > > 2- Know what variables to supply for arguments > > Lets get our terminology straight first. > > aClients, aSource etc are the parameter names of the function cmcopy > > If I do: > > L = [1,2,3] > s = 'fred' > t = 'tom' > src = 42 > cmcopy(L,s,t,src) > > The variable names are: L, s, t, src > but the *arguments* are just the values that those variables hold > and they are assined the temporary names > > aClients, sSource, sTarget, iSource > > for the duration of the function call. > > > Thus if I do: > > cmcopy([1,2,3],'fred','tom',42) > > There are no argument names, but the argument values are: > [1,2,3,], 'fred','tom',42 > > Almost exactly as they were above (except that the lists are not > also referenced by the variables!) > > Which names do you want? And what dso you think you can do with them? > If we know what you are trying to achieve we might be able to offer > a better solution. :-) > > Alan G. > > > From alan.gauld at blueyonder.co.uk Wed Sep 1 23:48:58 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Sep 1 23:48:06 2004 Subject: [Tutor] Editing files through Python References: <20040901180544.52078.qmail@web51002.mail.yahoo.com> Message-ID: <045401c4906d$7c5d2290$6401a8c0@xp> > I've been playing around with the advice you was sent me > and have become a little confused about the ideas of the > input_file (r) and the output_file (w). Can they be the > same file? No. Actually what's being suggested is what Microsoft Word (and almost all other programs) do. They copy the original file(foo.doc) to a temp file (~foo.doc) and open the temporary copy and read it. When you do a save they overwrite the original file and rename ~foo.doc to foo.bak. Or some similar sequence, basically they create a new file so that they don't corrupt the original until an explicit save is done. It just looks like to the user as if it is opening and modifying the original file, in fact it is making copies and operating on two different files. (actually 3 if you include an auto-save recovery version!) > Do I have to close the input file before writing to the > output file? Not if you use the model above - ie operate on a copy of the original and don't overwrite it until you are ready. > Here is the program I wrote following your example, > and an error that always appears, relating to the input file, > that is perplexing me. This bit has been answered already :-) > IOError: [Errno 2] No such file or directory: 'C:\\BryFolder\\kt.1.24.data.036rd.test.dat' Alan G. From alan.gauld at blueyonder.co.uk Wed Sep 1 23:59:00 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Wed Sep 1 23:58:07 2004 Subject: [Tutor] Suggestions as to how to read a file in paragraphs References: <Pine.OSF.4.21L.0409012249380.27040-100000@igor.urz.unibas.ch> Message-ID: <047401c4906e$e36b7850$6401a8c0@xp> > Depending on the biological sequence files, the paragraph separator could > be a "//" or newlines or any string really. I know in perl there is an > input record separator which by default is the newline and one can specify > this to a specific delimiter. Is there one in python? OK, awk can do that trick too. Unfortunately I don't know of any way to do it in Python, I think you either need to check each line in a for/readline() loop or use a regex to extract the paras with findall() - which brings more memory issues with it... or use multiple applications of string.split() on the file.read() string. No simple answers for big files I'm afraid, and I checked the fileinput module and it has no way of defining a split either, and is slow anyway if speed is already an issue. Alan G. From bigapple631 at optonline.net Thu Sep 2 00:52:53 2004 From: bigapple631 at optonline.net (jason hochstein) Date: Thu Sep 2 00:56:04 2004 Subject: [Tutor] saving program Message-ID: <008201c49076$6a3c3d90$bc4ebb18@hochstein> good afternoon. I was wondering if there was a way to make a program save the info it gives so when you open it again it displays the information that was last inputed into the program. So you don't have to start fresh everytime you start the program. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040901/1873f311/attachment.htm From isrgish at fastem.com Thu Sep 2 02:29:47 2004 From: isrgish at fastem.com (Isr Gish) Date: Thu Sep 2 02:30:02 2004 Subject: [Tutor] Editing files through Python Message-ID: <20040902003000.739A11E4002@bag.python.org> Hi Bryan, -----Original Message----- >From: "Bryan"<juicebypi216@yahoo.com> >Sent: 9/1/04 2:05:44 PM >To: "Bob Gailer"<bgailer@alum.rpi.edu>, "tutor@python.org"<tutor@python.org> >Subject: Re: [Tutor] Editing files through Python > >Hi Bob, > [snip some text] >Here is the program: > >input_file = file('C:\BryFolder\coherence.dat', 'r') >lines = input_file.readlines() >output_file = file('C:\BryFolder\coherence.dat', 'w') >for line in lines: > nums = line.split(" ") > retain = nums[:5] > new_line = ", ".join(retain)+"\n" > output_file.write(new_line) >output_file.close() > >Here is the error: > >Traceback (most recent call last): > File "C:\BryFolder\cohprog3.py", line 1, in ? > input_file = file('C:\BryFolder\kt.1.24.data.036rd.test.dat', 'r') # substitute your path to the file >IOError: [Errno 2] No such file or directory: 'C:\\BryFolder\\kt.1.24.data.036rd.test.dat' > It seems that the file you give in the program is not the same file thatbis showing in the error. What the acttual error is saying, is that there is no such file. (which is brobebly related with that that you have a different file in the error) All the best, Isr >Thanks for the help >Bryan > > > > > >Bob Gailer <bgailer@alum.rpi.edu> wrote:At 01:38 PM 8/30/2004, Bryan wrote: >> >>I am a beginner in Python, and this is my first time using this list so I >>hope my question is acceptable. > >We are here to help, but not just give answers. However your request seems >to me to merit a program, which I hope you will study to enhance your >understanding of Python. Please ask more questions., > >>Basically, my goal is to read data files that are already on my hard drive >>into Python, and then edit them, deleting unneccesary portions of data. >> >>I have already figured out how to read the files into Python, I just >>cannot figure out how to edit them. Here are the difficulties: >> >>How do I delete, cut, or paste portions of the data I am reading and how >>do I tell the program to jump to that specific portion of data that I want >>to alter? > >The usual approach is to read the file into a Python variable, process the >variable and write a new file (which can have the same name as the input >file, rather than to attempt to manipulate the file itself. It is a LOT >easier this way. > >> Here is a somewhat complicated example, similar to what I want to do - >> >>I have two rows of numbers, as shown below. Each row has 10 numbers >>(hopefully they will show up as two rows of numbers in the email (1-10 and >>11-20). >> >>1, 2, 3, 4, 5, 6, 7, 8, 9, 10 >>11, 12, 13, 14, 15, 16, 17, 18, 19, 20 >> >>What commands might I use to automatically go through each row, deleting >>the 6th through 10th numbers in each row (6-10 in the first row and 16-20 >>in the second row). > >I have written a complete program, just to avoid any ambiguities. > >input_file = file('num.txt', 'r') # substitute your path to the file >lines = input_file.readlines() # list of lines >output_file = file('num.txt', 'w') # substitute your path to the file >for line in lines: >nums = line.split(", ") # assumes numbers separated by ", ", gives list >of numbers >retain = nums[:5] # keep first 5 numbers >new_line = ", ".join(retain)+"\n" # reassemble into a line >output_file.write(new_line) # write to file >output_file.close() > >Please note this depends on consistent number separators. If the separators >vary, then the approach gets more complex. > >Bob Gailer >bgailer@alum.rpi.edu >303 442 2625 home >720 938 2625 cell > > > > >--------------------------------- >Do you Yahoo!? >Yahoo! Mail - 50x more storage than other providers! From flaxeater at yahoo.com Thu Sep 2 04:20:25 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Thu Sep 2 04:20:28 2004 Subject: [Tutor] saving program Message-ID: <20040902022025.30672.qmail@web52608.mail.yahoo.com> jason hochstein wrote: >THANKS. GOOD JOB HELPING > > > > Sorry I was not trying to be snide. I meant this however. It can be a very complex thing, and it depends alot on how you structure the solution. If i where to do it I would serilize(persist) objects. However there are just tons of ways to do this. __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From str_kbs at sancharnet.in Wed Sep 1 04:23:46 2004 From: str_kbs at sancharnet.in (General Electronics,Phaltan) Date: Thu Sep 2 04:24:43 2004 Subject: [Tutor] help-Please help me to read Text From JPEG file Message-ID: <000001c49095$91365380$c762013d@h5e1d0> Hi, Please help me to write python code to read Text from JPEG file and store to standard TEXT file. Thanks Arvind Sidhaye From str_kbs at sancharnet.in Wed Sep 1 04:25:44 2004 From: str_kbs at sancharnet.in (General Electronics,Phaltan) Date: Thu Sep 2 04:24:49 2004 Subject: [Tutor] help-Please help me to write ODBC connection application Message-ID: <000101c49095$93ee2080$c762013d@h5e1d0> Hi, I have 'MYDATA' as DSN in my ODBC. How can i write code to read tables from this DSN. I am not famiilier with Python code. Arvind Sidhaye From dyoo at hkn.eecs.berkeley.edu Thu Sep 2 07:34:12 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Sep 2 07:34:23 2004 Subject: [Tutor] assigning __doc__ strings (manually) In-Reply-To: <Pine.LNX.4.60.0409011609270.7963@binx.sesnet.soton.ac.uk> Message-ID: <Pine.LNX.4.44.0409012224150.10119-100000@hkn.eecs.berkeley.edu> > Since the main computation is done in real_f(), I thought I'd create a > doc-string in real_f() that explains the computation being implemented > etc (as done above). [text cut] Hi Hans, Kent's solution, to manually assign to the function's __doc__ attribute, after the function is defined, should do the trick. The reason that: > def f(x): > real_f.__doc__ > return real_f(x)[0] didn't work is because Python looks for the first line in a function for a real string literal, and not just any expression that could be evaluated as a string. This is consistant with the way that Python doesn't do any evaluation of functions unless they're explicitely called. For example: ### >>> def testEvaluation(): ... print x ... ### would be invalid if 'x' weren't defined. But since Python doesn't evaluate function bodies on definition time, we're still fine until we actually start trying to use it: ### >>> testEvaluation() Traceback (most recent call last): File "<stdin>", line 1, in ? File "<stdin>", line 2, in testEvaluation NameError: global name 'x' is not defined ### As soon as we define an 'x', we're ok: ### >>> x = "hello sailor" >>> testEvaluation() hello sailor ### Anyway, I'd better try to tie this back to the original question. *grin* When we look at: > def f(x): > real_f.__doc__ > return real_f(x)[0] we now know that Python's not allowed to actually try evaluating expressions like 'real_f.__doc__'. At most, Python can do a quick scan for string literals, like: ### def f(x): "this is some docstring." return real_f(x)[0] ### For this reason, Python's automatic detection of documentation strings is limited to paying attention to literal strings, since finding those is technically trivial. It's easy to do, and doesn't really violate the "don't try to evaluate the function body until we're called" rule that functions follow. Hope that made some sense. *grin* Good luck! From dyoo at hkn.eecs.berkeley.edu Thu Sep 2 07:42:01 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Sep 2 07:42:07 2004 Subject: [Tutor] saving program In-Reply-To: <20040902022025.30672.qmail@web52608.mail.yahoo.com> Message-ID: <Pine.LNX.4.44.0409012237580.10119-100000@hkn.eecs.berkeley.edu> [some text cut] > It [saving program state] can be a very complex thing, and it depends > alot on how you structure the solution. If i where to do it I would > serilize(persist) objects. However there are just tons of ways to do > this. Hi Jason, Python comes with a Standard Library module called 'shelve' that acts like a dictionary, but is actually backed by a disk: http://www.python.org/doc/lib/module-shelve.html There are other serialization systems available, but for simple things, 'shelve' seems to be a nice way to save the state of your program. Try 'shelve' out; if you have questions, please feel free to bring them up. Good luck! From dyoo at hkn.eecs.berkeley.edu Thu Sep 2 07:44:48 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Sep 2 07:44:59 2004 Subject: [Tutor] help-Please help me to read Text From JPEG file In-Reply-To: <000001c49095$91365380$c762013d@h5e1d0> Message-ID: <Pine.LNX.4.44.0409012242110.10119-100000@hkn.eecs.berkeley.edu> On Wed, 1 Sep 2004, General Electronics,Phaltan wrote: > Please help me to write python code to read Text from JPEG file and > store to standard TEXT file. Hi Arvind, The question you're asking is slightly odd. JPEGs are binary: for the most part, they're not supposed to have text (except possibly some metadata). What are you trying to do? It might help if you could tell us why you're trying to do this. Are you trying to rewrite the standard 'strings' Unix shell command? Good luck to you. From dyoo at hkn.eecs.berkeley.edu Thu Sep 2 07:58:41 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Sep 2 07:58:58 2004 Subject: [Tutor] help-Please help me to write ODBC connection application In-Reply-To: <000101c49095$93ee2080$c762013d@h5e1d0> Message-ID: <Pine.LNX.4.44.0409012244580.10119-100000@hkn.eecs.berkeley.edu> On Wed, 1 Sep 2004, General Electronics,Phaltan wrote: > I have 'MYDATA' as DSN in my ODBC. How can i write code to read tables from > this DSN. Hi Arvind, Wait, wait: you're using some terms that may not be familiar to folks here on the Tutor list. DSN... ODBC... http://en.wikipedia.org/wiki/Database_Source_Name http://en.wikipedia.org/wiki/ODBC So you have a Database Source Name, and you're trying to connect to an ODBC database? Ok, you may want to look at the 'mxODBC' third-party module: http://www.egenix.com/files/python/mxODBC.html The examples on that page shows how to start up a connection, given a DSN: ### >>> import mx.ODBC.iODBC >>> db = mx.ODBC.iODBC.DriverConnect('DSN=database;UID=user;PWD=passwd') ### And by this time, we should have a 'db' connection that we can use to start querying the database. > I am not famiilier with Python code. Hmmm. That can be a problem. Are you sure you want to tackle databases before Python? You may want to get familiar with some Python basics, because otherwise, depending on your previous background, you're bound to run into issues that have nothing to do with databases, but have more to do with how Python works. It sounds like you've had some programming experience already. If that's the case, we strongly recommend you look at the Official Tutorial at: http://www.python.org/doc/tut/ to at least get you up to speed quickly. There are other guides in: http://www.python.org/topics/learn/ that may also be useful as reference material. If you have more questions, please feel free to ask. Good luck! From dyoo at hkn.eecs.berkeley.edu Thu Sep 2 08:31:56 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Sep 2 08:32:05 2004 Subject: [Tutor] Suggestions as to how to read a file in paragraphs In-Reply-To: <Pine.OSF.4.21L.0409012249380.27040-100000@igor.urz.unibas.ch> Message-ID: <Pine.LNX.4.44.0409012301340.10119-100000@hkn.eecs.berkeley.edu> > > First, do you need the efficiency? Is it actually causing a problem > > just now? > > Before yes, but not now. The efficiency is needed when very large files > are needed and not enough RAM is available to process huge files (eg. > > 3 million lines) > > > Lots of modules might help (re, parser, string, fileinput etc) but > > nothing specifically for splitting text files by paragraph. (And how > > do you define a paragraph separator? Is it a blank line or is it an > > indented first line? Both are valid...) > > Depending on the biological sequence files, the paragraph separator > could be a "//" or newlines or any string really. Hi Tzu-Ming, An iterator approach might work here. It's possible to do something like this: ### def breakIntoRecords(read, delimiter): """A generated that, given a read() function (like the one provided by files), will yield records, separated by the given delimiter.""" buffer = [] while True: nextChar = read(1) if not nextChar: break buffer.append(nextChar) if buffer[-len(delimiter):] == list(delimiter): yield ''.join(buffer) buffer = [] if buffer: yield ''.join(buffer) ### Forgive me for the ugly code; it's late. *grin* This uses Python's "generator" support, which allows us to easily write things that can yield chunks of data at a time. The function above will chunk up a file, based on the delimiter we give it. Let's test this function, by using the StringIO module to mimic a string as a file-like object: ### >>> from StringIO import StringIO >>> textFile = StringIO('hello world\nthis is a test\ncan you see this?') >>> print list(breakIntoRecords(textFile.read, '\n')) ['hello world\n', 'this is a test\n', 'can you see this?'] >>> textFile.seek(0) >>> print list(breakIntoRecords(textFile.read, ' ')) ['hello ', 'world\nthis ', 'is ', 'a ', 'test\ncan ', 'you ', 'see ', 'this?'] ### Here, we call 'list()' to make it easy to see how the system is breaking things into records: in reality, we would NOT call list() on the result of breakIntoRecords(), since that would suck everything into memory at once. And that would be bad. *grin* Instead, we'd read it piecemeal, probably in a for loop. Python will read the minimal characters necessary to see the next record, and requests the next chunk by calling next(): ### >>> iterator = breakIntoRecords(textText.read, 'i') >>> iterator.next() 'hello world\nthi' >>> iterator.next() 's i' >>> iterator.next() 's a test\ncan you see thi' >>> iterator.next() 's?' >>> iterator.next() Traceback (most recent call last): File "<stdin>", line 1, in ? StopIteration ### So just as long as your records aren't larger than system memory, this should be efficient. This solution assumes that your delimiters are static strings. (The function above can be improved: we could probably do better by reading the file as blocks of characters, rather than check for the delimiter on each character read.) > I know in perl there is an input record separator which by default is > the newline and one can specify this to a specific delimiter. Is there > one in python? Not certain. Python has adopted 'universal newlines' support, http://www.python.org/doc/2.3.4/whatsnew/node7.html This allows us to tell Python to guess between the three main standard ways to define a line. So there may be something in Python that we might be able to reuse, to redefine a "line" as something else. But I'm not sure how easily accessible this might be. Good luck to you! From alan.gauld at blueyonder.co.uk Thu Sep 2 08:59:16 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Sep 2 08:59:14 2004 Subject: [Tutor] Listing function arguments References: <00cb01c49025$e6b81570$0d01a8c0@studioaction.local><040701c49066$3603d020$6401a8c0@xp> <000c01c49073$94639710$2901a8c0@atyss> Message-ID: <001601c490ba$5cc1ad50$6401a8c0@xp> > I wanted to know what the funciton uses for paramter names, so I can assign > values to variables of the same name and pass them to the function. I'm still slightly confused about why you want to give the variables the parameter *names*. You shouldn't need to give the variables the same name as the parameters. For example: def f(x=0,y=1,z=2): return x+y+z a = 3 b = 7 c = 42 print f(a,b,c) # -> 52 What is important is the type and sequence of the parameters. The variables passed as arguments can have completely different "names". There is a slight tweak with named parameters where you have a many parameters and want to pass a subset not necessarily in the order specified, and I guess that's what you are trying to do? > Anyway the tips given by Kent and Andrei are exactly what I wanted: > help( myfunction ) And yes that would tell you the parameter names so that you can assign the arguments by name, but you still don't need to name your variables with the same names. Returning to our example: print f(z=b) we assign our variable b to the parameter named z. HTH, Alan G. From alan.gauld at blueyonder.co.uk Thu Sep 2 09:07:03 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Sep 2 09:07:01 2004 Subject: [Tutor] saving program References: <008201c49076$6a3c3d90$bc4ebb18@hochstein> Message-ID: <002201c490bb$7311d890$6401a8c0@xp> Hi Jason, > good afternoon. I was wondering if there was a way to make > a program save the info it gives so when you open it again > it displays the information that was last inputed into the > program. Hmm, there are a couple of possibilities here. Do you mean you want to save the data that the user of your program entered, ie that was captured via raw_input() say, or from reading a file? OR Do you mean you want to save the program commands that you have typed in at the >>> prompt iusing IDLE or Pythonwin?? If the first then you have to write code to save the data into a file and then read it back when your program restarts. If the second then you have to type your program into a new text file (with name ending in .py). IDLE can create those for you from the File->New menu, and you just save the file when you are finished. Next time you start IDLE use File->Open to read it again and carry on working from where you left off.. > So you don't have to start fresh everytime you start the program. I'm guessing from this you are meaning the second scenario but I'm not sure. If you are following my tutorial then I cover this in the "More Sequences" topic. I also cover saving data to files in the "Handling Files" topic! Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/ From alan.gauld at blueyonder.co.uk Thu Sep 2 09:14:27 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Sep 2 09:14:25 2004 Subject: [Tutor] help-Please help me to read Text From JPEG file References: <000001c49095$91365380$c762013d@h5e1d0> Message-ID: <003101c490bc$7be17100$6401a8c0@xp> > Please help me to write python code to read Text from JPEG file and store to > standard TEXT file. We had this request once before, a long time back, it might be worth searching the archives on ActiveState to see if there was an answer. But basically the "text" in a JPEG is just part of the bitmap pattern encoded using the JPEG compression rules, trying to extract text from a JPEG will be extremely difficult unless the JPEG is limited to a scanned image of a printed page, in which case an OCR program could be used and you might find a library of OCR functions somewhere. But if the text is in a mixed graphics picture - the name of a hotel in a photo say, it will be extremely difficult to extract it from the image. You might fare better if you post to the comp.lang.python group too - this is a bit advanced for the tutor list I suspect! HTH, Alan G. From kent_johnson at skillsoft.com Thu Sep 2 11:50:45 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Thu Sep 2 11:50:57 2004 Subject: [Tutor] Suggestions as to how to read a file in paragraphs In-Reply-To: <Pine.LNX.4.44.0409012301340.10119-100000@hkn.eecs.berkeley .edu> References: <Pine.OSF.4.21L.0409012249380.27040-100000@igor.urz.unibas.ch> <Pine.LNX.4.44.0409012301340.10119-100000@hkn.eecs.berkeley.edu> Message-ID: <6.1.0.6.0.20040902054756.029b1878@mail4.skillsoft.com> I took a look at the source code for reading lines from a file (in Objects/fileobject.c/get_line()). The three recognized line endings are hard-coded (the code looks specifically for \r, \n and \r\n) so you can't customize this. Kent At 11:31 PM 9/1/2004 -0700, Danny Yoo wrote: > > I know in perl there is an input record separator which by default is > > the newline and one can specify this to a specific delimiter. Is there > > one in python? > >Not certain. Python has adopted 'universal newlines' support, > > http://www.python.org/doc/2.3.4/whatsnew/node7.html > >This allows us to tell Python to guess between the three main standard >ways to define a line. So there may be something in Python that we might >be able to reuse, to redefine a "line" as something else. But I'm not >sure how easily accessible this might be. > > >Good luck to you! > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From my.mailing.lists at noos.fr Thu Sep 2 13:07:07 2004 From: my.mailing.lists at noos.fr (nik) Date: Thu Sep 2 13:07:16 2004 Subject: [Tutor] converting string to a number In-Reply-To: <6.1.0.6.0.20040902054756.029b1878@mail4.skillsoft.com> References: <Pine.OSF.4.21L.0409012249380.27040-100000@igor.urz.unibas.ch> <Pine.LNX.4.44.0409012301340.10119-100000@hkn.eecs.berkeley.edu> <6.1.0.6.0.20040902054756.029b1878@mail4.skillsoft.com> Message-ID: <4136FEDB.20400@noos.fr> hi, I have a string that could either be a number or text, and I'd like to test which it is. If I do try: number = string.atof(str) # do my number stuff except: text = str # do my string stuff then it's using the exception handling like an if statement. This feels kinda wrong (hacky or lazy). Is it, or is it an acceptable method in python? nik From s.e.murdock at soton.ac.uk Thu Sep 2 15:25:45 2004 From: s.e.murdock at soton.ac.uk (Stuart Murdock) Date: Thu Sep 2 15:25:57 2004 Subject: [Tutor] First few eigenvectors of Numeric Array Message-ID: <41371F59.5040607@soton.ac.uk> Hi I have a 10000 by 10000 square Numeric array which I have obtained using Numeric python. I need to obtain the first 10 eigenvalues and eigenvectors of this so I dont want to have to calculate all eigenvectors of the matrix. Is anyone aware of any pythonic packages which can calculate, lets say, the 10 eigenvectors corresponding to the top 10 eigenvalues of a Numeric array. Thanks Stuart -- Stuart Murdock Ph.D, Research Fellow, Dept. of Chemistry / E-Science, University of Southampton, Highfield, Southampton, SO17 1BJ, United Kingdom http://www.biosimgrid.org From H.FANGOHR at soton.ac.uk Thu Sep 2 15:35:23 2004 From: H.FANGOHR at soton.ac.uk (Hans Fangohr) Date: Thu Sep 2 15:42:54 2004 Subject: [Tutor] assigning __doc__ strings (manually) In-Reply-To: <4135A047.4010100@po-box.mcgill.ca> References: <Pine.LNX.4.60.0409011609270.7963@binx.sesnet.soton.ac.uk> <4135A047.4010100@po-box.mcgill.ca> Message-ID: <Pine.LNX.4.60.0409021415310.7963@binx.sesnet.soton.ac.uk> Hi Brian, Danny and Kent. Thanks to Kent and Danny for providing a solution and the corresponding explanation to my problem. Brian has responded with an 'orthogonal' question which I'll address above. > Hans Fangohr said unto the world upon 2004-09-01 17:21: >> Greetings, >> >> I am facing the following problem and would like some advise: >> >> I have two functions, say for simplicity, real_f and f: >> >> def real_f(x): >> """this is my doc-string""" >> return x**2, x**3 >> >> def f(x): >> return real_f(x)[0] >> >> >> The actual work is done in real_f() and some users might be interested >> in x**3 and x**2. However, most of the users will only care about x**2 >> and are happy to use the function f() for this. >> >> (In the actual program I am working on there is of course more work >> involved than just computing x**2 and x**3 ...) >> >> Since the main computation is done in real_f(), I thought I'd create a >> doc-string in real_f() that explains the computation being implemented >> etc (as done above). >> > > <SNIP> > >> Hans >> > > Hi Hans, > > I get that your code description was simplified, but I've a question and > possibly a suggestion about it. (All this is orthogonal to your posted > question.) Fair enough. > From what you say, it seems like you are expecting most of the time the > function f() will be the one used, and real_f() will be directly called > much less often. As you describe your setup, f() essentially runs real_f() > and throws away half the work it produces. (Are there needed side-effects > to the "thrown-away" part of real_f() that you didn't mention?) > > In that context, wouldn't it be more efficient to put the computational > work in f() directly and have real_f() call f() and then itself do the > other needed work? > > I mean something like > > def f(x): > return x**2 > > def real_f(x): > return f(x), x**3 > > (Obviously the names you posted are no longer the ones to use in that f() > now really does something itself, but I'm keeping your names structure.) > > It won't matter much for such simple computations as the toy ones of your > post, and I get the "premature optimization is the root of all evil" > point. But still, to this relative newcomer's mind, your structure seems > undesirable. > > So, this is either a request for an explanation of what is wrong with what > I say, or a helpful observation. I leave it to those higher up the > pythonic peaks to determine which ;-) The precise problem is this: the function which I called f is a Runge-Kutta-Fehlberg integrater for ordinary differential equations with adaptive stepsize. To solve the problem dy/dt=g(y,t) one would call the integrator and it returns a vector T and a vector Y (or n vectors if g(y,t) is a n-dimensional vector) and each entry corresponding to one time step. Usually, this information -- lets call it (T,Y) -- is sufficient. Sometimes however, one wants to know the step size (which, admittedly could be computed from T) and -- more importantly -- the error estimate for each integration step. (This is to be used in a teaching context and differs therefore slightly from what you would use in scientific 'production' computation.) The stepsize and errors are readily available when the computation is performed and are usually thrown away. So all in all, my approach outline above is not too far away from the actual problem ;-) However, let me rephrase the challenge: if my integrater function could return a varying number of objects, this would solve my problem very nicely. (I don't think one can do this in Python?) The ideal syntax to call the integrater function RKF would be this: T,Y = RKF( g, t0=0, tfinal=10 ) meaning that the function g(y,t) should be integrated from t=0 to t=10. If one wants to analyse the performance of the integration in more detail, then I'd like to call the function like this: T,Y,log = RKF( g, t0=0, tfinal=10 ) where log could be a dictionary containing all sorts of extra data, or a list of arrays or something along those lines. Does that make things clearer? With the approach I outlined initially, I would have two functions def RKF( g, t0, tfinal ): return RKFLog( g, t0, tfinal)[0:2] and def RKFLog( g, t0, tfinal ): #perform integration return T, Y, log With Kent's help I can synchronise the docstrings across the two functions. However, maybe there are better solutions out there. Cheers, Hans From kent_johnson at skillsoft.com Thu Sep 2 16:09:02 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Thu Sep 2 16:08:51 2004 Subject: [Tutor] assigning __doc__ strings (manually) In-Reply-To: <Pine.LNX.4.60.0409021415310.7963@binx.sesnet.soton.ac.uk> References: <Pine.LNX.4.60.0409011609270.7963@binx.sesnet.soton.ac.uk> <4135A047.4010100@po-box.mcgill.ca> <Pine.LNX.4.60.0409021415310.7963@binx.sesnet.soton.ac.uk> Message-ID: <6.1.0.6.0.20040902095343.0285bdd8@mail4.skillsoft.com> Hans, I don't know of any way for a python function to know how many results the caller is expecting and change its return value accordingly. OTOH a python function can easily return a different type of result depending on the inputs: >>> def evens(i): ... if i%2 == 0: ... return (i, i/2) ... else: ... return '%d is odd' % i ... >>> evens(1) '1 is odd' >>> evens(2) (2, 1) In your case, you could pass another argument to RKF that tells it whether to return the log data or not: def RKF( g, t0, tfinal, returnLog=0): # perform integration if returnLog: return T, Y, log else: return T, Y However, I think this is bad design - it will be confusing to users and error-prone; I think your solution is better. You could also use a class to store the results, then the client code would look something like rkf = RKF( g, t0=0, tfinal=10 ) a, b = rkf.solution log = rkf.log but this seems like overkill to me. Kent At 02:35 PM 9/2/2004 +0100, Hans Fangohr wrote: >> From what you say, it seems like you are expecting most of the time the >>function f() will be the one used, and real_f() will be directly called >>much less often. As you describe your setup, f() essentially runs real_f() >>and throws away half the work it produces. (Are there needed side-effects >>to the "thrown-away" part of real_f() that you didn't mention?) >> >>In that context, wouldn't it be more efficient to put the computational >>work in f() directly and have real_f() call f() and then itself do the >>other needed work? >> >>I mean something like >> >>def f(x): >>return x**2 >> >>def real_f(x): >>return f(x), x**3 >> >>(Obviously the names you posted are no longer the ones to use in that f() >>now really does something itself, but I'm keeping your names structure.) >> >>It won't matter much for such simple computations as the toy ones of your >>post, and I get the "premature optimization is the root of all evil" >>point. But still, to this relative newcomer's mind, your structure seems >>undesirable. >> >>So, this is either a request for an explanation of what is wrong with what >>I say, or a helpful observation. I leave it to those higher up the >>pythonic peaks to determine which ;-) > >The precise problem is this: the function which I called f is a >Runge-Kutta-Fehlberg integrater for ordinary differential equations >with adaptive stepsize. To solve the problem dy/dt=g(y,t) one would >call the integrator and it returns a vector T and a vector Y (or n >vectors if g(y,t) is a n-dimensional vector) and each entry >corresponding to one time step. Usually, this information -- lets call >it (T,Y) -- is sufficient. Sometimes however, one wants to know the >step size (which, admittedly could be computed from T) and -- more >importantly -- the error estimate for each integration step. (This is >to be used in a teaching context and differs therefore slightly from >what you would use in scientific 'production' computation.) > >The stepsize and errors are readily available when the computation is >performed and are usually thrown away. So all in all, my approach >outline above is not too far away from the actual problem ;-) > >However, let me rephrase the challenge: if my integrater function >could return a varying number of objects, this would solve my problem >very nicely. (I don't think one can do this in Python?) > >The ideal syntax to call the integrater function RKF would be this: > >T,Y = RKF( g, t0=0, tfinal=10 ) > >meaning that the function g(y,t) should be integrated from t=0 to t=10. > >If one wants to analyse the performance of the integration in more >detail, then I'd like to call the function like this: > >T,Y,log = RKF( g, t0=0, tfinal=10 ) > >where log could be a dictionary containing all sorts of extra data, or >a list of arrays or something along those lines. > >Does that make things clearer? > >With the approach I outlined initially, I would have two functions > >def RKF( g, t0, tfinal ): > return RKFLog( g, t0, tfinal)[0:2] > >and > >def RKFLog( g, t0, tfinal ): > #perform integration > > return T, Y, log > >With Kent's help I can synchronise the docstrings across the two >functions. However, maybe there are better solutions out there. > >Cheers, > >Hans > From project5 at redrival.net Thu Sep 2 16:39:08 2004 From: project5 at redrival.net (Andrei) Date: Thu Sep 2 16:39:14 2004 Subject: [Tutor] Re: converting string to a number References: <Pine.OSF.4.21L.0409012249380.27040-100000@igor.urz.unibas.ch> <Pine.LNX.4.44.0409012301340.10119-100000@hkn.eecs.berkeley.edu> <6.1.0.6.0.20040902054756.029b1878@mail4.skillsoft.com> <4136FEDB.20400@noos.fr> Message-ID: <loom.20040902T163027-354@post.gmane.org> nik <my.mailing.lists <at> noos.fr> writes: > I have a string that could either be a number or text, and I'd like to > test which it is. > > If I do > > try: > number = string.atof(str) Gaah, the string module again :). You can simply do: number = float(str) Also, don't use builtins for variable names. str is a builtin. What you do can get you into trouble, e.g. when you wish to convert a number to a string using str(mynumber). Use s instead: number = float(s) If you have doubts about something being a builtin, you can try it in the interactive interpreter, like this: >>> 'str' in dir(__builtins__) True >>> 'apples' in dir(__builtins__) False or like this: >>> help(str) Help on class str in module __builtin__: class str(basestring) | str(object) -> string <snip> > # do my number stuff > except: > text = str > # do my string stuff > > then it's using the exception handling like an if statement. This feels kinda wrong (hacky or lazy). It isn't wrong, it's in fact very good. I can't even think of a better way to do it. You'll just need to pay attention to the possibility that "do my number stuff" might cause an exception as well (e.g. if you try to divide something by your number and number happens to be 0, you'll get a ZeroDivisionError), thereby causing the code to interpret your number as a string anyway. Whether you want this or not, I don't know. Yours, Andrei From rob.benton at conwaycorp.net Thu Sep 2 17:04:15 2004 From: rob.benton at conwaycorp.net (Rob Benton) Date: Thu Sep 2 17:03:59 2004 Subject: [Tutor] static PyObject * or non-static Message-ID: <4137366F.5070006@conwaycorp.net> Hey I've been reading through the Extending and Embedding section of the python docs. One thing that keeps appearing is a chunk of code like this: Section 2.1.1 Adding Data and Methods to the Basic Example ================================================================= static PyObject * Noddy_name(Noddy* self) { static PyObject *format = NULL; PyObject *args, *result; if (format == NULL) { format = PyString_FromString("%s %s"); if (format == NULL) return NULL; } ... } ================================================================= I'm curious as to why the format PyObject * is made static. Should I make everything static that can be? I didn't know if maybe there was a reason for doing that. From kent_johnson at skillsoft.com Thu Sep 2 17:34:01 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Thu Sep 2 17:34:07 2004 Subject: [Tutor] Re: converting string to a number In-Reply-To: <loom.20040902T163027-354@post.gmane.org> References: <Pine.OSF.4.21L.0409012249380.27040-100000@igor.urz.unibas.ch> <Pine.LNX.4.44.0409012301340.10119-100000@hkn.eecs.berkeley.edu> <6.1.0.6.0.20040902054756.029b1878@mail4.skillsoft.com> <4136FEDB.20400@noos.fr> <loom.20040902T163027-354@post.gmane.org> Message-ID: <6.1.0.6.0.20040902105117.029f2ce0@mail4.skillsoft.com> At 02:39 PM 9/2/2004 +0000, Andrei wrote: >If you have doubts about something being a builtin, you can try it in the >interactive interpreter, like this: > > >>> 'str' in dir(__builtins__) > True > >>> 'apples' in dir(__builtins__) > False or just type the name itself: >>> str <type 'str'> >>> apples Traceback (most recent call last): File "<stdin>", line 1, in ? NameError: name 'apples' is not defined > > # do my number stuff > > except: > > text = str > > # do my string stuff > > > > then it's using the exception handling like an if statement. This feels > kinda >wrong (hacky or lazy). > >It isn't wrong, it's in fact very good. I can't even think of a better way >to do >it. You'll just need to pay attention to the possibility that "do my number >stuff" might cause an exception as well (e.g. if you try to divide >something by >your number and number happens to be 0, you'll get a ZeroDivisionError), >thereby >causing the code to interpret your number as a string anyway. Whether you want >this or not, I don't know. To guard against these possibilities, you can do two things: 1. Catch the actual exception that will be thrown (ValueError) instead of catching everything. 2. Use try / except / else to remove "do my number stuff" from the try block, so any exception thrown from it (even ValueError) will be propagated to the caller. Like this: >>> def maybeNumber(val): ... try: ... number = float(val) ... except ValueError: ... text = val ... print text, 'is a string' ... else: ... print number, 'is a number' ... >>> maybeNumber(1) 1.0 is a number >>> maybeNumber('ab') ab is a string Kent (who is finally starting to understand what try / except / else is good for...) From my.mailing.lists at noos.fr Thu Sep 2 18:01:24 2004 From: my.mailing.lists at noos.fr (nik) Date: Thu Sep 2 18:01:29 2004 Subject: [Tutor] Re: converting string to a number In-Reply-To: <6.1.0.6.0.20040902105117.029f2ce0@mail4.skillsoft.com> References: <Pine.OSF.4.21L.0409012249380.27040-100000@igor.urz.unibas.ch> <Pine.LNX.4.44.0409012301340.10119-100000@hkn.eecs.berkeley.edu> <6.1.0.6.0.20040902054756.029b1878@mail4.skillsoft.com> <4136FEDB.20400@noos.fr> <loom.20040902T163027-354@post.gmane.org> <6.1.0.6.0.20040902105117.029f2ce0@mail4.skillsoft.com> Message-ID: <413743D4.6050605@noos.fr> Kent Johnson wrote: > At 02:39 PM 9/2/2004 +0000, Andrei wrote: > >> If you have doubts about something being a builtin, you can try it in >> the >> interactive interpreter, like this: >> >> >>> 'str' in dir(__builtins__) >> True >> >>> 'apples' in dir(__builtins__) >> False > > > or just type the name itself: > >>> str > <type 'str'> > >>> apples > Traceback (most recent call last): > File "<stdin>", line 1, in ? > NameError: name 'apples' is not defined > >> > # do my number stuff >> > except: >> > text = str >> > # do my string stuff >> > >> > then it's using the exception handling like an if statement. This >> feels kinda >> wrong (hacky or lazy). >> >> It isn't wrong, it's in fact very good. I can't even think of a >> better way to do >> it. You'll just need to pay attention to the possibility that "do my >> number >> stuff" might cause an exception as well (e.g. if you try to divide >> something by >> your number and number happens to be 0, you'll get a >> ZeroDivisionError), thereby >> causing the code to interpret your number as a string anyway. Whether >> you want >> this or not, I don't know. > > > To guard against these possibilities, you can do two things: > 1. Catch the actual exception that will be thrown (ValueError) instead > of catching everything. > 2. Use try / except / else to remove "do my number stuff" from the try > block, so any exception thrown from it (even ValueError) will be > propagated to the caller. > > Like this: > >>> def maybeNumber(val): > ... try: > ... number = float(val) > ... except ValueError: > ... text = val > ... print text, 'is a string' > ... else: > ... print number, 'is a number' > ... > >>> maybeNumber(1) > 1.0 is a number > >>> maybeNumber('ab') > ab is a string > > Kent (who is finally starting to understand what try / except / else > is good for...) > > Thanks for the advice guys, I hadn't thought of what would happen if it wasn't the exception you were expecting. It still feels uncomfortable though, I've always felt an exception is *exceptional*, ie something that was outside your control. However, I'm happy enough now to go and use it... nik From alan.gauld at blueyonder.co.uk Thu Sep 2 18:29:30 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Sep 2 18:29:23 2004 Subject: [Tutor] static PyObject * or non-static References: <4137366F.5070006@conwaycorp.net> Message-ID: <00a501c4910a$06853470$6401a8c0@xp> > static PyObject * > Noddy_name(Noddy* self) > { > static PyObject *format = NULL; > PyObject *args, *result; > I'm curious as to why the format PyObject * is made static. One of the features of a static variable inside a function is that it retains its value between function calls. Basically static assigns storage on the heap rather than the stack. Most function data is on the stack so that when a function call ends all the data on the stack gets unwound and lost, but the heap data persists. > make everything static that can be? No that will only waste memory. temporary variables within functions should go on the stack so that they can be deleted. Alan G. From python at bernardlebel.com Thu Sep 2 20:36:31 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Thu Sep 2 19:34:09 2004 Subject: [Tutor] Listing function arguments References: <00cb01c49025$e6b81570$0d01a8c0@studioaction.local><040701c49066$3603d020$6401a8c0@xp> <000c01c49073$94639710$2901a8c0@atyss> <001601c490ba$5cc1ad50$6401a8c0@xp> Message-ID: <001301c4911b$c66181c0$2901a8c0@atyss> Hi Alan, The ultimate end to my question was to know the actual order of arguments. I know I can send a,b,c, as values for parameters x,y,z. However, I want to know in what order I have to supply values for the function to work. If I supply the wrong value to a given parameter, I won't go very far :-) In this case, I need to know if sSource is before or after sTarget, and on the same roll why not check if there are arguments I may have forgotten. Plus, the help() function is great, but I know document each parameter in the doc string, so I can see if I make a mistake. Thanks for the help! Bernard ----- Original Message ----- From: "Alan Gauld" <alan.gauld@blueyonder.co.uk> To: "Bernard Lebel" <python@bernardlebel.com>; <tutor@python.org> Sent: Thursday, September 02, 2004 7:59 AM Subject: Re: [Tutor] Listing function arguments > > I wanted to know what the funciton uses for paramter names, so I can > assign > > values to variables of the same name and pass them to the function. > > I'm still slightly confused about why you want to give the > variables the parameter *names*. You shouldn't need to give the > variables the same name as the parameters. > For example: > > def f(x=0,y=1,z=2): return x+y+z > > a = 3 > b = 7 > c = 42 > > print f(a,b,c) # -> 52 > > What is important is the type and sequence of the parameters. > The variables passed as arguments can have completely different > "names". There is a slight tweak with named parameters > where you have a many parameters and want to pass a subset > not necessarily in the order specified, and I guess that's what > you are trying to do? > > > Anyway the tips given by Kent and Andrei are exactly what I wanted: > > help( myfunction ) > > And yes that would tell you the parameter names so that you can > assign the arguments by name, but you still don't need to name > your variables with the same names. Returning to our example: > > print f(z=b) > > we assign our variable b to the parameter named z. > > HTH, > > Alan G. > > > From Mark.Kels at gmail.com Thu Sep 2 19:52:15 2004 From: Mark.Kels at gmail.com (Mark Kels) Date: Thu Sep 2 19:52:33 2004 Subject: [Tutor] A problem with saveing data for later use. Message-ID: <d12026530409021052747b851f@mail.gmail.com> Hello, first,I want to apologize for my bad english. I'm from a non-englishe country (israel) so I dont speak englise very wel. and now the problem: I want to make a simple personal organizer (no GUI) that have address book,calendar etc. The problem is that I dont know how to save the data that comes from the user. And a personal organizer cant work if it doest "remembers" the info that the user iputs... If anyone has an idea i'll be more then happy to read it. I'm sorry if you dont understand the question... let me know if you dont,and I'll try to rewrite it. thanks!! From askoose at sandia.gov Thu Sep 2 20:01:30 2004 From: askoose at sandia.gov (Kooser, Ara S) Date: Thu Sep 2 20:01:50 2004 Subject: [Tutor] beginner help!!!! Message-ID: <9A4B2157EFDBE546BECD68C62AC3B1C81738F457@es05snlnt.sandia.gov> Could you post the code and the error message. Thanks "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: Jill and Paul [mailto:bear4@zoominternet.net] Sent: Saturday, August 28, 2004 7:04 PM To: tutor@python.org Subject: [Tutor] beginner help!!!! I am very new at learning Python and I am trying to type in a program for practice. It has "else:" in it and I keep getting either a syntax error message or an indentation error no matter what I do. HELP!!!!! Jill -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040902/d1cea46a/attachment.htm From dyoo at hkn.eecs.berkeley.edu Thu Sep 2 20:17:14 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Sep 2 20:17:19 2004 Subject: [Tutor] beginner help!!!! In-Reply-To: <9A4B2157EFDBE546BECD68C62AC3B1C81738F457@es05snlnt.sandia.gov> Message-ID: <Pine.LNX.4.44.0409021106250.12532-100000@hkn.eecs.berkeley.edu> On Thu, 2 Sep 2004, Kooser, Ara S wrote: > Could you post the code and the error message. Thanks Hi Jill, Yes, we need to see your code. I suspect it might be an indentation problem, but without seeing your code, I can't make any solid remarks either. Feel free to just copy and paste it in your reply. About the error message stuff: don't parapharse the error: show it to us as it comes. For example, here's the kind of error message we like to see: ### Traceback (most recent call last): File "<stdin>", line 1, in ? NameError: name 'oracle' is not defined ### In contrast, if we paraphrase the error message to just: "There's a Name Error somewhere in my program", then that's not as helpful to us. The real error message itself has told us what appears to be undefined, and on what line the problems appear to start. The paraphrase, on the other hand, just tells us that something's wrong, but doesn't tell us where to look. In this case, originality is not a good thing: it's good not to suppress that information in paraphrase. Instead, just copy-and-paste the error, around where the "Traceback" starts. Good luck! From dyoo at hkn.eecs.berkeley.edu Thu Sep 2 20:22:34 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Sep 2 20:23:40 2004 Subject: [Tutor] names In-Reply-To: <000601c48ece$2e2f3770$121c8645@oemcomputer> Message-ID: <Pine.LNX.4.44.0409021118380.12532-100000@hkn.eecs.berkeley.edu> On Mon, 30 Aug 2004, Diana Furr wrote: > How do you get Python to let name=(anyone's name) > > I saw some posts on this subject but didn't find an answer. Hi Diana, Can you point us to one of those posts? I'm not quite sure what you mean yet, and maybe the context will help. Are you trying to do something like this? ### >>> game = "frogger" >>> game 'frogger' ### Here, we can assign the string value "frogger" to the variable name 'game'. Is this what you're looking for? From kent_johnson at skillsoft.com Thu Sep 2 20:31:33 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Thu Sep 2 20:31:40 2004 Subject: [Tutor] names In-Reply-To: <000601c48ece$2e2f3770$121c8645@oemcomputer> References: <000601c48ece$2e2f3770$121c8645@oemcomputer> Message-ID: <6.1.0.6.0.20040902143025.028a54c0@mail4.skillsoft.com> If you want the user to be able to type in her name, use raw_input(): >>> name = raw_input('What is your name? ') What is your name? Kent >>> name 'Kent' At 04:16 PM 8/30/2004 -0400, Diana Furr wrote: >How do you get Python to let name=(anyone's name) >I saw some posts on this subject but didn't find an answer. >Thank you, >Diana >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From dyoo at hkn.eecs.berkeley.edu Thu Sep 2 20:36:06 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Sep 2 20:36:12 2004 Subject: [Tutor] First few eigenvectors of Numeric Array In-Reply-To: <41371F59.5040607@soton.ac.uk> Message-ID: <Pine.LNX.4.44.0409021125340.12532-100000@hkn.eecs.berkeley.edu> On Thu, 2 Sep 2004, Stuart Murdock wrote: > I have a 10000 by 10000 square Numeric array which I have obtained using > Numeric python. I need to obtain the first 10 eigenvalues and > eigenvectors of this so I dont want to have to calculate all > eigenvectors of the matrix. Is anyone aware of any pythonic packages > which can calculate, lets say, the 10 eigenvectors corresponding to the > top 10 eigenvalues of a Numeric array. Hi Stuart, Yikes! *grin* This sounds like a really specialized question; I'm not sure if many of us here can help. You may want to ask this question on the Scientific Python (SciPy) mailing list: http://www.scipy.org/ Isn't Numeric Python now deprecated in favor of the Numarray project, though? http://www.stsci.edu/resources/software_hardware/numarray Numarray does provide a function to grab eigenvalues and eigenvectors: http://stsdas.stsci.edu/numarray/Doc/node64.html and Numeric Python has similar functions: http://www.pfdubois.com/numpy/html2/numpy-18.html#pgfId-303058 but neither appear to allow a 'N max eigenvalues' style query. I don't personally have the math background to point out how to make that work. I'd ask on SciPy, where that community may be better equipped to help. Best of wishes to you! From kent_johnson at skillsoft.com Thu Sep 2 20:54:32 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Thu Sep 2 20:54:59 2004 Subject: [Tutor] python editor In-Reply-To: <4eb23360040822013612cc10c2@mail.gmail.com> References: <4eb23360040822013612cc10c2@mail.gmail.com> Message-ID: <6.1.0.6.0.20040902144737.02856ad0@mail4.skillsoft.com> There are many editors that work well with Python. Which one is best is a matter of (sometimes strong!) personal preference. If you have a text editor you like, it may well have Python support available. Here is a list to get you started. Many of the editors are free or have trial versions, so you can try a few and find one you like. http://www.python.org/moin/PythonEditors Python web programming is another big topic. If you can give us some idea what you want to do maybe we can help you better. For simple projects the cgi module might be all you need. For more complex projects there are many frameworks available. Here is a list: http://www.python.org/cgi-bin/moinmoin/WebProgramming HTH Kent At 12:06 PM 8/22/2004 +0330, Meisam GanjeAli wrote: >hello >what is the best pythin editor, and how can i extend my ability for >python programming for web? >thanks for your help. >bye. >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From bill at celestial.net Thu Sep 2 20:59:34 2004 From: bill at celestial.net (Bill Campbell) Date: Thu Sep 2 20:59:40 2004 Subject: [Tutor] spitshell for python Message-ID: <20040902185934.GB93162@alexis.mi.celestial.com> Someplace in the python.org documentation I saw something analagous to the perl idiom to start python from a script, but I couldn't find it recently when I wanted to use it. The main reason I use this is that I have a key mapping in vi[m] that does ``:!sh -x %'' to test scripts, and I would like to have the same think work for python as it now does for shell and perl. The perl version starts out something like: #!/usr/local/bin/perl eval ' exec /usr/local/bin/perl -....' 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/ It is necessary for the welfare of society that genius should be privileged to utter sedition, to blaspheme, to outrage good taste, to corrupt the youthful mind, and generally to scandalize one's uncles. -- George Bernard Shaw From kent_johnson at skillsoft.com Thu Sep 2 21:00:03 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Thu Sep 2 21:00:28 2004 Subject: [Tutor] A problem with saveing data for later use. In-Reply-To: <d12026530409021052747b851f@mail.gmail.com> References: <d12026530409021052747b851f@mail.gmail.com> Message-ID: <6.1.0.6.0.20040902145454.02a02de8@mail4.skillsoft.com> The shelve module might work for you. Here is a short article showing how to create a simple address book using shelve: http://www.wdvl.com/Authoring/Languages/Python/Quick/python6_3.html If shelve is not adequate you probably want to use a database such as MySQL to store the data. Kent At 07:52 PM 9/2/2004 +0200, Mark Kels wrote: >Hello, >first,I want to apologize for my bad english. >I'm from a non-englishe country (israel) so I dont speak englise very wel. > >and now the problem: >I want to make a simple personal organizer (no GUI) that have address >book,calendar etc. >The problem is that I dont know how to save the data that comes from the user. >And a personal organizer cant work if it doest "remembers" the info >that the user iputs... >If anyone has an idea i'll be more then happy to read it. > >I'm sorry if you dont understand the question... >let me know if you dont,and I'll try to rewrite it. > >thanks!! >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From pythonTutor at venix.com Thu Sep 2 21:05:14 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Thu Sep 2 21:05:23 2004 Subject: [Tutor] A problem with saveing data for later use. In-Reply-To: <d12026530409021052747b851f@mail.gmail.com> References: <d12026530409021052747b851f@mail.gmail.com> Message-ID: <1094151914.3782.8.camel@laptop.venix.com> The solution to how to save your data depends upon the data and how it is used. The tutorials will teach you how to use files. A file is the basic tool for saving data. There is a good chance that the shelve module can help with saving data for a personal organizer. You can read about shelve in the Library Reference Manual. Your first step is to figure out what your data looks like and how it will be used. This can be a tough first project, depending upon how fancy you need this organizer to be. On Thu, 2004-09-02 at 13:52, Mark Kels wrote: > Hello, > first,I want to apologize for my bad english. > I'm from a non-englishe country (israel) so I dont speak englise very wel. > > and now the problem: > I want to make a simple personal organizer (no GUI) that have address > book,calendar etc. > The problem is that I dont know how to save the data that comes from the user. > And a personal organizer cant work if it doest "remembers" the info > that the user iputs... > If anyone has an idea i'll be more then happy to read it. > > I'm sorry if you dont understand the question... > let me know if you dont,and I'll try to rewrite it. > > thanks!! > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 320-210-3409 (changed Aug 26, 2004) From mhansen at cso.atmel.com Thu Sep 2 21:07:34 2004 From: mhansen at cso.atmel.com (Mike Hansen) Date: Thu Sep 2 21:07:30 2004 Subject: [Tutor] beginner help!!!! In-Reply-To: <20040902181722.433451E4016@bag.python.org> References: <20040902181722.433451E4016@bag.python.org> Message-ID: <41376F76.3040003@cso.atmel.com> Are you using IDLE's Python Shell to type in your program? If so, you can get a little hung up with typing if else statements. IDLE 1.0.3 >>> x = 1 >>> if x == 1: print "something" else: SyntaxError: invalid syntax >>> if x == 1: print "something" else: print "something else" something >>> I had to type a backspace at the line I wanted the else clause to be placed. You need to assume the >>> prompt isn't there when getting the indentation lined up when using the Python Shell. If you aren't using the Python Shell, then ignore this post. Mike > -----Original Message----- > *From:* Jill and Paul [mailto:bear4@zoominternet.net] > *Sent:* Saturday, August 28, 2004 7:04 PM > *To:* tutor@python.org > *Subject:* [Tutor] beginner help!!!! > > I am very new at learning Python and I am trying to type in a > program for practice. It has "else:" in it and I keep getting > either a syntax error message or an indentation error no matter > what I do. HELP!!!!! > > Jill > > From jeff at ccvcorp.com Thu Sep 2 21:18:13 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu Sep 2 21:16:58 2004 Subject: [Tutor] assigning __doc__ strings (manually) In-Reply-To: <6.1.0.6.0.20040902095343.0285bdd8@mail4.skillsoft.com> References: <Pine.LNX.4.60.0409011609270.7963@binx.sesnet.soton.ac.uk> <4135A047.4010100@po-box.mcgill.ca> <Pine.LNX.4.60.0409021415310.7963@binx.sesnet.soton.ac.uk> <6.1.0.6.0.20040902095343.0285bdd8@mail4.skillsoft.com> Message-ID: <413771F5.3000109@ccvcorp.com> > At 02:35 PM 9/2/2004 +0100, Hans Fangohr wrote: > >> The ideal syntax to call the integrater function RKF would be this: >> >> T,Y = RKF( g, t0=0, tfinal=10 ) >> >> meaning that the function g(y,t) should be integrated from t=0 to t=10. >> >> If one wants to analyse the performance of the integration in more >> detail, then I'd like to call the function like this: >> >> T,Y,log = RKF( g, t0=0, tfinal=10 ) >> >> where log could be a dictionary containing all sorts of extra data, or >> a list of arrays or something along those lines. Depending on your particular usage, it may also be reasonable to simply always return the extra data, and leave it up to the calling code to either use it or discard it: T, Y = RKF( g, t0= 0, tfinal=10 )[:2] or T, Y, _ = RKF( g, t0= 0, tfinal=10 ) I'm thinking in particular of the standard library function os.path.splitext(), which splits a file extension from a path/file name. It returns both the base name (without the extension) and the extension even though most of the time that this is used, the extension itself is all that's needed and the base name is just thrown away. This does suffer from feeling a bit less "clean", since you're constantly throwing stuff away. On the other hand, it spares you having two very-similar-purpose functions, and makes the act of discarding unneeded data more explicit. Jeff Shannon Technician/Programmer Credit International From jeff at ccvcorp.com Thu Sep 2 21:27:07 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu Sep 2 21:25:52 2004 Subject: [Tutor] Re: converting string to a number In-Reply-To: <413743D4.6050605@noos.fr> References: <Pine.OSF.4.21L.0409012249380.27040-100000@igor.urz.unibas.ch> <Pine.LNX.4.44.0409012301340.10119-100000@hkn.eecs.berkeley.edu> <6.1.0.6.0.20040902054756.029b1878@mail4.skillsoft.com> <4136FEDB.20400@noos.fr> <loom.20040902T163027-354@post.gmane.org> <6.1.0.6.0.20040902105117.029f2ce0@mail4.skillsoft.com> <413743D4.6050605@noos.fr> Message-ID: <4137740B.1080202@ccvcorp.com> nik wrote: > Thanks for the advice guys, I hadn't thought of what would happen if it > wasn't the exception you were expecting. It still feels uncomfortable > though, I've always felt an exception is *exceptional*, ie something > that was outside your control. The feeling you have is consistent with how *most* languages use exceptions, so it's entirely understandable. However, Python exceptions are less costly than many other languages' exceptions, so it's a fairly standard control-flow mechanism in Python. Indeed, you may not realize it, but even basic control structures are built on top of exceptions. As an example, for and while loops use a StopIteration exception to indicate that they are done. The handling for this is automatically created in the bytecode and is thus hidden from the normal user, but if you peek under the covers, it's there. So yes, this is a perfectly acceptable usage of exceptions -- Python tends to follow the old truism that "It's easier to ask for forgiveness than for permission" -- in most cases, it's more straightforward to try an action and catch the exception if it doesn't work, than it is to check ahead of time whether the action will work. Jeff Shannon Technician/Programmer Credit International From alan.gauld at blueyonder.co.uk Thu Sep 2 22:32:35 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Sep 2 22:32:25 2004 Subject: [Tutor] A problem with saveing data for later use. References: <d12026530409021052747b851f@mail.gmail.com> Message-ID: <00c001c4912b$fb5e9ec0$6401a8c0@xp> > I want to make a simple personal organizer (no GUI) that have address > book,calendar etc. > The problem is that I dont know how to save the data that comes from the user. Take a look at the new Handling Files topic in my tutor, it has an example of a simple address book complete with saving and restoring the data. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/ From alan.gauld at blueyonder.co.uk Thu Sep 2 22:39:36 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Sep 2 22:39:27 2004 Subject: [Tutor] Static Variables References: <Pine.LNX.4.50.0408281340180.8324-100000@pasargad.cse.shirazu.ac.ir> Message-ID: <00c501c4912c$f67b49c0$6401a8c0@xp> > By the way, would anyone guide me how to become a pro in C Experience. As the guy who looks after the lawns at Wimbledon tennis court says when asked how to get the same quality of lawn: "Water regularly, Cut regularly, Feed rgularly and repeat for 300 years... " C programming doesn't take so long but it does take experience. Reading a lot of code of different types helps - try the Python source code, and other sourceforge projects. Look at the Linux kernel code. Working in partnership with experienced programmers helps too but is hard for a casual programmer to do in practice. There aren't any magic books but a few to consider are: Programming Pearls by Jon Bentley - not all C but sound programming practice The Practice of Programming - Kernighan & Pike The Pragmatic Programmer. All of these are quite short but packed full of advise to lift the amateur up towards pro standards. And finally a book every coder should read: Code Complete by McConnell - possibly the best thing to ever come from Microsoft! :-) If you were doing C++ I'd also recommend Herb Sutter's pair of books. Alan G. From dyoo at hkn.eecs.berkeley.edu Thu Sep 2 22:41:19 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Sep 2 22:43:28 2004 Subject: [Tutor] Static Variables In-Reply-To: <Pine.LNX.4.50.0408281340180.8324-100000@pasargad.cse.shirazu.ac.ir> Message-ID: <Pine.LNX.4.44.0409021332240.7408-100000@hkn.eecs.berkeley.edu> > By the way, would anyone guide me how to become a pro in C (an e-book, > some maillists, some hints or just whatever you think may be helpful)? Hi Ashkan, Read Python's C implementation. *grin* I'm actually a little serious about this: I learned quite a bit about C by seeing how Python was implemented in it. It's amazing how much work goes into some of the features in Python; it makes me all the more glad that I don't have to work at that level... usually. In general, read other people's code, and write good programs: I think that's a pretty steady way to get better at programming in any language. There's an abundance of Open Source code out there: I'd recommend taking advantage of it. > I read Kernighan and Ritchie's "THE C PROGRAMMING LANGUAGE", but I need > something that makes me a real man!! If reading K&R doesn't improve your macho rating, I don't know what will. *grin* But if you want to read another book, I'd recommend 'Programming Pearls': http://www.cs.bell-labs.com/cm/cs/pearls/ One can only go so far with just reading, though: to get better, you'll need to apply what you've read. Pick a project that you like to work on, and go with it. Good luckt oyou! From alan.gauld at blueyonder.co.uk Thu Sep 2 23:44:32 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Sep 2 23:44:21 2004 Subject: [Tutor] How can I catch a Windows event? References: <1093770234.16895@gar.st.nograd.net> Message-ID: <00d401c49136$08c7f480$6401a8c0@xp> > I am new in computing and python. My problem is during > switching off/ restaring Win 98 the phyton script written by me > doesn?t stop. (in Win XP. no problem) Caveat: The following are personal observations which are not based on deep knowledge but my own painful experience. OK, How are you running the program? Is it starting as a service or as a regular program from the start menu or Startup group? Also how are you switching Windows off? Windows 98 is not very well behaved at the best of times and doesn't like threads much at all, barely tolerates them some would say! So unless your main program keeps track of all the threads you start and closes them down properly you will have problems, especially if somebody just hits the off switch.. > I guess it is because of a thread. By checking from the internet > I found the WM_QUERYENDSESSION should be caught for regular > stopping, but I do not understand how. Are you running a GUI or console application? Console apps don't get windows events like Windows apps do under '98 - they do in XP since the console is really a windows app, but in '9x they are glorified DOS boxes so you need to pick up the DOS interrupt handler. Unfortunately this is difficult from normal code! > I am also not sure, which I should use win 32all or wxPython. Win32all is the package if you want to mess with low level windows events. OTOH wxPython should trap the message for you and close down cleanly. > The following script stops the win98 shutdown process > if I start the script from consol. That should be because Windows sees the console running a background process and knows it can't stop it so it just kind of gives up and asks you to kill it. This regularly happens to me if I run Cygwin with background jobs! It's what's supposed to happen and is "A Good Thing" IMHO. The alternative would be fore Windows to just kill the application outright when it migt be in the middle of a major file operation and thus destroy reams of data... If you want better behaviour you need to turn your app into a proper GUI and catch the events from Windows. I'mn not sure if that clarifies or confuses further! Alan G. From rha207 at yahoo.com Thu Sep 2 23:45:56 2004 From: rha207 at yahoo.com (Ron A) Date: Thu Sep 2 23:45:58 2004 Subject: [Tutor] help with __str__ Message-ID: <20040902214556.63574.qmail@web50906.mail.yahoo.com> This is from the book "Python Programming for the absolute beginner" slightly modified. It's concantenating rank and suit each time you create a new card and it seems to be doing it without having to use print card each time. How is the str method being used without using print? I'm really getting confused now. Ron A # Playing Cards # Demonstrates combining objects # Michael Dawson - 4/9/03 class Card(object): """ A playing card. """ def __init__(self, rank, suit): self.rank = rank self.suit = suit def __str__(self): rep = self.rank + self.suit return rep class Hand(object): """ A hand of playing cards. """ def __init__(self): self.cards = [] def __str__(self): if self.cards: rep = "" for card in self.cards: rep += str(card) + " " else: rep = "<empty>" return rep def clear(self): self.cards = [] def add(self, card): self.cards.append(card) def give(self, card, other_hand): self.cards.remove(card) other_hand.add(card) # main card1 = Card(rank = "A", suit = "c") card2 = Card(rank = "2", suit = "c") card3 = Card(rank = "3", suit = "c") card4 = Card(rank = "4", suit = "c") card5 = Card(rank = "5", suit = "c") my_hand = Hand() my_hand.add(card1) my_hand.add(card2) my_hand.add(card3) my_hand.add(card4) my_hand.add(card5) print "\nPrinting my hand after adding 5 cards:" print my_hand your_hand = Hand() my_hand.give(card1, your_hand) my_hand.give(card2, your_hand) print "\nGave the first two cards from my hand to your hand." print "Your hand:" print your_hand print "My hand:" print my_hand my_hand.clear() print "\nMy hand after clearing it:" print my_hand raw_input("\n\nPress the enter key to exit.") __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From alan.gauld at blueyonder.co.uk Thu Sep 2 23:47:58 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Sep 2 23:47:46 2004 Subject: [Tutor] spitshell for python References: <20040902185934.GB93162@alexis.mi.celestial.com> Message-ID: <00f201c49136$83706820$6401a8c0@xp> > mapping in vi[m] that does ``:!sh -x %'' to test scripts, and I would like > to have the same think work for python as it now does for shell and perl. > > The perl version starts out something like: > > #!/usr/local/bin/perl > eval ' exec /usr/local/bin/perl -....' I'm no perl hacker but does execfile() do what you need? Alan G From alan.gauld at blueyonder.co.uk Thu Sep 2 23:50:54 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Sep 2 23:50:49 2004 Subject: [Tutor] Re: converting string to a number References: <Pine.OSF.4.21L.0409012249380.27040-100000@igor.urz.unibas.ch> <Pine.LNX.4.44.0409012301340.10119-100000@hkn.eecs.berkeley.edu> <6.1.0.6.0.20040902054756.029b1878@mail4.skillsoft.com> <4136FEDB.20400@noos.fr> <loom.20040902T163027-354@post.gmane.org> <6.1.0.6.0.20040902105117.029f2ce0@mail4.skillsoft.com><413743D4.6050605@noos.fr> <4137740B.1080202@ccvcorp.com> Message-ID: <00ff01c49136$ecb409e0$6401a8c0@xp> > Indeed, you may not realize it, but even basic control structures are > built on top of exceptions. As an example, for and while loops use a > StopIteration exception to indicate that they are done. I didn't realize it! Thanks for that bit of insight Jeff. Interesting indeed! Alan G. From adam at monkeez.org Thu Sep 2 23:53:05 2004 From: adam at monkeez.org (Adam) Date: Thu Sep 2 23:53:12 2004 Subject: [Tutor] String to integer? In-Reply-To: <002201c49069$bcf7aa90$2901a8c0@atyss> References: <27761.217.206.168.163.1094043268.spork@webmail.monkeez.org><00b201c49023$ad72bf10$0d01a8c0@studioaction.local> <413622E1.2020300@monkeez.org> <002201c49069$bcf7aa90$2901a8c0@atyss> Message-ID: <41379641.2030102@monkeez.org> Bernard Lebel wrote: > Hi Adam, > > Sorry for the learning curve, I should have mentioned that the tutorial that > comes with the documentation covers dictionaries. That would have saved you > some time I guess. My bad. > > Cheers > Bernard > > > ----- Original Message ----- > From: "Adam" <adam@monkeez.org> > Cc: <tutor@python.org> > Sent: Wednesday, September 01, 2004 8:28 PM > Subject: Re: [Tutor] String to integer? > > > >>Bernard Lebel wrote: >> >> >>>Personally I'd consider using a dictionary for that. Assign the letter > > (the > >>>key) to the number (the value). >>> >>> >>>Cheers >>>Bernard >>> >> >>Bernard, >> >>The dictionary worked a treat (although I had to spend half an hour >>working it out). >> >>Many thanks >> >>Adam Bernard, Not your bad at all - it's just my cranky brain trying to get back in to programming after such a long time away. Thanks again. Adam -- site: http://www.monkeez.org wiki: http://wiki.monkeez.org From alan.gauld at blueyonder.co.uk Thu Sep 2 23:56:24 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Thu Sep 2 23:56:12 2004 Subject: [Tutor] My tutorial Message-ID: <010701c49137$b0dbcc40$6401a8c0@xp> For those who are interested I just uploaded the final installment of the re-wtritten tutor. (Its not quite done because I need to do a brand new topic on regular expressions, which I now use in the case study). I will be tidying up loose ends and reorganising the site over the next few weeks so that the rewrite and original tutors effectively swap position. After that I intend to add a new section with topics on practical applications of Python - the os module, XML and CGI programming, some sockets and urllib etc. But as it stands now the new version is effectively completely rewritten wrt the original. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/ From dyoo at hkn.eecs.berkeley.edu Fri Sep 3 00:07:28 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Sep 3 00:07:32 2004 Subject: [Tutor] help with __str__ In-Reply-To: <20040902214556.63574.qmail@web50906.mail.yahoo.com> Message-ID: <Pine.LNX.4.44.0409021450300.19030-100000@hkn.eecs.berkeley.edu> On Thu, 2 Sep 2004, Ron A wrote: > This is from the book "Python Programming for the absolute beginner" > slightly modified. It's concantenating rank and suit each time you > create a new card and it seems to be doing it without having to use > print card each time. How is the str method being used without using > print? I'm really getting confused now. Hi Ron, The '__str__' method of a method does fire off when we print out a thing... but it also fires off if we call the str() "string conversion" on something. For example: ### >>> class TestStr: ... def __str__(self): ... print "*** DEBUG: __str__ is firing off!***" ... return "TestStr instance" ... >>> t = TestStr() >>> print t *** DEBUG: __str__ is firing off!*** TestStr instance >>> value = str(t) *** DEBUG: __str__ is firing off!*** >>> ### Does this make sense? __str__() is used by both Python's "print" statement and the 'str()' builtin function, and your code is calling str() on things. We'd use str() if we want to get at the string value, but not necessarily print out to screen. For example, there are other things we can do to a string value besides print it out directly: ### >>> str(t) * 3 *** DEBUG: __str__ is firing off!*** 'TestStr instanceTestStr instanceTestStr instance' >>> len(str(t)) *** DEBUG: __str__ is firing off!*** 16 ### One thing to realize is that 'print' itself does not give us a value. It's something that works as a "side-effect": we see the thing that's being printed, but otherwise, printing doesn't have a "value". Here are things that have values: ### >>> 3 * 4 12 >>> 'ha' * 7 'hahahahahahaha' ### These things are "expressions": they're calculations that result in a new value. We usually try to write our functions so that they return values. ### >>> def square(x): ... return x * x ... >>> result = square(42) >>> result 1764 ### 'print' is different: it just prints to screen, but has no real value: ### >>> def printSquare(x): ... print x * x ... >>> result = printSquare(42) 1764 >>> print result None ### We'd say that printSquare() has a "side-effect" of displaying the square of a number on screen, but doesn't give back a useful value to us. That's what 'None' is about. The main different between the two here is that square() can easily be used in some larger computation, but printSquare() can't: ### >>> (square(3) + square(4)) ** 0.5 5.0 >>> (printSquare(3) + printSquare(4)) ** 0.5 9 16 Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: unsupported operand type(s) for +: 'NoneType' and 'NoneType' ### So that's why all of the functions in your program try not to just "print" their computation: rather, they actually try to "return" the value to the caller. Most people try to get their functions to 'return' values because such functions often end up being more useful than ones that only print to screen. If you have more questions, please feel free to ask. Good luck! From kent_johnson at skillsoft.com Fri Sep 3 00:16:40 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Sep 3 00:16:49 2004 Subject: [Tutor] help with __str__ In-Reply-To: <20040902214556.63574.qmail@web50906.mail.yahoo.com> References: <20040902214556.63574.qmail@web50906.mail.yahoo.com> Message-ID: <6.1.0.6.0.20040902180128.02899e10@mail4.skillsoft.com> Ron, Class methods whose names start and end with __ are called "special methods". They allow you to customize the way python uses your class. One thing you might want to customize is the string representation of your class. This is the string you get when you call str(xx) where xx is an instance of the class. It is also the string that prints when you say "print xx". On its own, Python is pretty simple-minded about how to display an instance of a class - it will just show you the module and class names and the actual memory address of the instance: >>> class A: ... pass ... >>> a=A() >>> print a <__main__.A instance at 0x007CF9E0> If the class defines a __str__ method, Python will call it when you call str() or print: >>> class B: ... def __str__(self): ... return "I'm a B!" ... >>> b=B() >>> print b I'm a B! To recap: when you tell Python to "print b", Python calls str(b) to get the string representation of b. If the class of b has a __str__ method, str(b) becomes a call to b.__str__(). This returns the string to print. You can get the string representation yourself by calling str() directly. This is what is happening in Hand.__str__() - it calls str() for each of the cards in the hand (which becomes a call to Card.__str__()), puts all the card strings together into one string, and uses that as the string for the whole hand. Kent At 02:45 PM 9/2/2004 -0700, Ron A wrote: >This is from the book "Python Programming for the >absolute beginner" >slightly modified. It's concantenating rank and suit >each time you create a >new card and it seems to be doing it without having to >use print card each >time. >How is the str method being used without using >print? I'm really >getting confused now. > >Ron A > ># Playing Cards ># Demonstrates combining objects ># Michael Dawson - 4/9/03 > >class Card(object): > """ A playing card. """ > def __init__(self, rank, suit): > self.rank = rank > self.suit = suit > > def __str__(self): > rep = self.rank + self.suit > return rep > > >class Hand(object): > """ A hand of playing cards. """ > def __init__(self): > self.cards = [] > > def __str__(self): > if self.cards: > rep = "" > for card in self.cards: > rep += str(card) + " " > else: > rep = "<empty>" > return rep > > def clear(self): > self.cards = [] > > def add(self, card): > self.cards.append(card) > > def give(self, card, other_hand): > self.cards.remove(card) > other_hand.add(card) > > ># main >card1 = Card(rank = "A", suit = "c") >card2 = Card(rank = "2", suit = "c") >card3 = Card(rank = "3", suit = "c") >card4 = Card(rank = "4", suit = "c") >card5 = Card(rank = "5", suit = "c") > > >my_hand = Hand() >my_hand.add(card1) >my_hand.add(card2) >my_hand.add(card3) >my_hand.add(card4) >my_hand.add(card5) >print "\nPrinting my hand after adding 5 cards:" >print my_hand > >your_hand = Hand() >my_hand.give(card1, your_hand) >my_hand.give(card2, your_hand) >print "\nGave the first two cards from my hand to your >hand." >print "Your hand:" >print your_hand >print "My hand:" >print my_hand > >my_hand.clear() >print "\nMy hand after clearing it:" >print my_hand > >raw_input("\n\nPress the enter key to exit.") > > > > >__________________________________________________ >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 amonroe at columbus.rr.com Fri Sep 3 00:28:18 2004 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Fri Sep 3 00:28:24 2004 Subject: [Tutor] names In-Reply-To: <000601c48ece$2e2f3770$121c8645@oemcomputer> References: <000601c48ece$2e2f3770$121c8645@oemcomputer> Message-ID: <116676944534.20040902182818@columbus.rr.com> > How do you get Python to let name=(anyone's name) > I saw some posts on this subject but didn't find an answer. Put quotation marks around the name. Alan From alan.gauld at blueyonder.co.uk Fri Sep 3 00:39:23 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Sep 3 00:39:11 2004 Subject: [Tutor] help with __str__ References: <20040902214556.63574.qmail@web50906.mail.yahoo.com> Message-ID: <012601c4913d$b2098f20$6401a8c0@xp> > slightly modified. It's concantenating rank and suit > each time you create a new card and it seems to be > doing it without having to use print card each > time. How is the str method being used without using > print? I'm really getting confused now. What makes you think its concatenating anything? The only time they get concatenated is when they get printed which is when the __str__ gets called. And it only concatenates for the duration of the print. What makes you think its doing anything else? > class Card(object): > """ A playing card. """ > def __init__(self, rank, suit): > self.rank = rank > self.suit = suit > > def __str__(self): > rep = self.rank + self.suit > return rep > Actually this is a pretty dumb class, a tuple would work just as well! > class Hand(object): > """ A hand of playing cards. """ > def __init__(self): > self.cards = [] > > def __str__(self): > if self.cards: > rep = "" > for card in self.cards: > rep += str(card) + " " Note that the call to str() here will also call the __str__ method of each card. But that only applies when printing a hand. The concatenation is still only temporary. > else: > rep = "<empty>" > return rep > print my_hand So within this call the individual card __str__() methods get called. HTH, Alan G. From fathimajaveed at hotmail.com Fri Sep 3 04:20:04 2004 From: fathimajaveed at hotmail.com (Fathima Javeed) Date: Fri Sep 3 04:20:10 2004 Subject: [Tutor] drawing a graph Message-ID: <BAY14-F5qdGSyMp69YD00056ee4@hotmail.com> Hi, I have managed to get distances between sequnces at each P value, using randomization, so now i have a html output file where there are two set of values one is different distance percentage and another P values from 1 to 100, How would i draw a graph in Python i.e. distance against P values for each sequence, Completely lost now, really would appreciate help, would it be helpful to paste my code here? Cheers Fuzzi >From: Kent Johnson <kent_johnson@skillsoft.com> >To: tutor@python.org >Subject: Re: [Tutor] need help with comparing list of sequences in >Python!! >Date: Tue, 31 Aug 2004 07:04:09 -0400 > >Fuzzi, > >Here is one way to do this: >- Use zip() to pair up elements from the two sequences > >>> s1='aaabbbbcccc' > >>> s2='aaaccccbcccccccccc' > >>> zip(s1, s2) >[('a', 'a'), ('a', 'a'), ('a', 'a'), ('b', 'c'), ('b', 'c'), ('b', 'c'), >('b', 'c'), ('c', 'b'), ('c', 'c'), ('c', 'c'), ('c', 'c')] > >- Use a list comprehension to compare the elements of the pair and put the >results in a new list. I'm not sure if you want to count the matches or the >mismatches - your original post says mismatches, but in your example you >count matches. This example counts matches but it is easy to change. > >>> [a == b for a, b in zip(s1, s2)] >[True, True, True, False, False, False, False, False, True, True, True] > >- In Python, True has a value of 1 and False has a value of 0, so adding up >the elements of this list gives the number of matches: > >>> sum([a == b for a, b in zip(s1, s2)]) >6 > >- min() and len() give you the length of the shortest sequence: > >>> min(len(s1), len(s2)) >11 > >- When you divide, you have to convert one of the numbers to a float or >Python will use integer division! > >>> 6/11 >0 > >>> float(6)/11 >0.54545454545454541 > >Put this together with the framework that Alan gave you to create a program >that calculates distances. Then you can start on the randomization part. > >Kent > > >At 04:03 AM 8/31/2004 +0100, Fathima Javeed wrote: >>Hi Kent >> >>To awnser your question: >>well here is how it works >>sequence one = aaabbbbcccc >>length = 11 >> >>seq 2 = aaaccccbcccccccccc >>length = 18 >> >>to get the pairwise similarity of this score the program compares the >>letters >>of the two sequences upto length = 11, the length of the shorter sequence. >> >>so a match gets a score of 1, therefore using + for match and x for >>mismatch >> >>aaabbbbcccc >>aaaccccbcccccccccc >>+++xxxxx+++ >> >>there fore the score = 6/11 = 0.5454 or 54% >> >>so you only score the first 11 letters of each score and its is not >>required to compare the rest of the sequence 2. this is what the >>distance matrix is doing >> >>match score == 6 >> >>The spaces are deleted to make both of them the same length >> >> >>>From: Kent Johnson <kent_johnson@skillsoft.com> >>>To: "Fathima Javeed" <fathimajaveed@hotmail.com>, tutor@python.org >>>Subject: Re: [Tutor] need help with comparing list of sequences in >>>Python!! >>>Date: Mon, 30 Aug 2004 13:53:19 -0400 >>> >>>Fuzzi, >>> >>>How do you count mismatches if the lengths of the sequences are >>>different? Do you start from the front of both sequences or do you look >>>for a best match? Do you count the extra characters in the longer string >>>as mismatches or do you ignore them? An example or two would help. >>> >>>For example if >>>s1=ABCD >>>s2=XABDDYY >>>how many characters do you count as different? >>> >>>Kent >>> >>>At 07:00 PM 8/29/2004 +0100, Fathima Javeed wrote: >>>>Hi, >>>>would really appreciate it if someone could help me in Python as i am >>>>new to the language. >>>> >>>>Well i have a list of protein sequences in a text file, e.g. (dummy >>>>data) >>>> >>>>MVEIGEKAPEIELVDTDLKKVKIPSDFKGKVVVLAFYPAAFTSVCTKEMCTFRDSMAKFNEVNAVVIGISVDP >>>>PFS >>>> >>>>MAPITVGDVVPDGTISFFDENDQLQTVSVHSIAAGKKVILFGVPGAFTPTCSMSHVPGFIGKAEELKSKG >>>> >>>>APIKVGDAIPAVEVFEGEPGNKVNLAELFKGKKGVLFGVPGAFTPGCSKTHLPGFVEQAEALKAKGVQVVACL >>>>SVND >>>> >>>>HGFRFKLVSDEKGEIGMKYGVVRGEGSNLAAERVTFIIDREGNIRAILRNI >>>> >>>>etc etc >>>> >>>>They are not always of the same length, >>>> >>>>The first sequence is always the reference sequence which i am tring to >>>>investigate, basically to reach the objective, i need to compare each >>>>sequence with the first one, starting with the the comparison of the >>>>reference sequence by itself. >>>> >>>>The objective of the program, is to manupulate each sequence i.e. >>>>randomly change characters and calculate the distance (Distance: Number >>>>of letters between a pair of sequnces that dont match DIVIDED by the >>>>length of the shortest sequence) between the sequence in question >>>>against the reference sequence. So therefore need a program code where >>>>it takes the first sequence as a reference sequence (constant which is >>>>on top of the list), first it compares it with itself, then it compares >>>>with the second sequence, then with the third sequence etc etc each at >>>>a time, >>>> >>>>for the first comparison, you take a copy of the ref sequnce and >>>>manupulate the copied sequence) i.e. randomly changing the letters in >>>>the sequence, and calculating the distances between them. >>>>(the letters that are used for this are: A R N D C E Q G H I L K M F P S >>>>T W Y V) >>>> >>>>The reference sequence is never altered or manupulated, for the first >>>>comparison, its the copied version of the reference sequence thats >>>>altered. >>>> >>>>Randomization is done using different P values >>>>e.g for example (P = probability of change) >>>>if P = 0 no random change has been done >>>>if P = 1.0 all the letters in that particular sequence has been >>>>randomly changed, therefore p=1.0 equals to the length of the sequence >>>> >>>>So its calculating the distance each time between two sequences ( first >>>>is always the reference sequnce and another second sequence) at each P >>>>value ( starting from 0, then 0.1, 0.2, ....... 1.0). >>>> >>>>Note: Number of sequnces to be compared could be any number and of any >>>>length >>>> >>>>I dont know how to compare each sequence with the first sequnce and how >>>>to do randomization of the characters in the sequnce therefore to >>>>calculate the distance for each pair of sequnce , if someone can give me >>>>any guidance, I would be greatful >>>> >>>>Cheers >>>>Fuzzi >>>> >>>>_________________________________________________________________ >>>>Stay in touch with absent friends - get MSN Messenger >>>>http://www.msn.co.uk/messenger >>>> >>>>_______________________________________________ >>>>Tutor maillist - Tutor@python.org >>>>http://mail.python.org/mailman/listinfo/tutor >> >>_________________________________________________________________ >>It's fast, it's easy and it's free. Get MSN Messenger today! >>http://www.msn.co.uk/messenger > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor _________________________________________________________________ Express yourself with cool new emoticons http://www.msn.co.uk/specials/myemo From kent_johnson at skillsoft.com Fri Sep 3 04:31:57 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Sep 3 04:32:02 2004 Subject: [Tutor] Module for fixed decimal arithmetic - followup Message-ID: <6.1.0.6.0.20040902222954.02a0bae0@mail4.skillsoft.com> Recently someone requested a python module for fixed point arithmetic. It turns out that python 2.4 includes the decimal module which does just that. See PEP 327 for details: http://www.python.org/peps/pep-0327.html Kent From rha207 at yahoo.com Fri Sep 3 05:37:36 2004 From: rha207 at yahoo.com (Ron A) Date: Fri Sep 3 05:37:37 2004 Subject: [Tutor] help with __str__ Thanks Message-ID: <20040903033736.42655.qmail@web50904.mail.yahoo.com> I think I have it now. Thanks everybody. Ron A ---------------------------------- So that's why all of the functions in your program try not to just "print" their computation: rather, they actually try to "return" the value to the caller. Most people try to get their functions to 'return' values because such functions often end up being more useful than ones that only print to screen. If you have more questions, please feel free to ask. Good luck! __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From klas.martelleur at telia.com Fri Sep 3 07:55:19 2004 From: klas.martelleur at telia.com (Klas Marteleur) Date: Fri Sep 3 07:55:21 2004 Subject: [Tutor] My tutorial In-Reply-To: <010701c49137$b0dbcc40$6401a8c0@xp> References: <010701c49137$b0dbcc40$6401a8c0@xp> Message-ID: <200409030755.19141.klas.martelleur@telia.com> Thanks for a great piece of work! > After that I intend to add a > new section with topics on practical applications of Python > - the os module, XML and CGI programming, some sockets and > urllib etc. I am looking forward to the new section. Klas From dyoo at hkn.eecs.berkeley.edu Fri Sep 3 08:17:34 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Sep 3 08:17:37 2004 Subject: [Tutor] names (fwd) Message-ID: <Pine.LNX.4.44.0409022314280.14461-100000@hkn.eecs.berkeley.edu> ---------- Forwarded message ---------- Date: Thu, 2 Sep 2004 20:12:25 -0400 From: Diana Furr <dleigh0@carolina.rr.com> To: Danny Yoo <dyoo@hkn.eecs.berkeley.edu> Subject: Re: [Tutor] names I would like to say thank you to Danny Yoo, Kent Johnson, and R. Alan Monroe for trying to answer my question. I spent 2 days trying to find the answer to that question and stumbled on the answer about 30mins after I gave up looking. name = raw_input('What is your name?') was the answer that I was looking for. I do have 1 more question though. I am trying to learn this but have no computer experience except being a user. Can anyone suggest book or something to help me out with the meaning of things like (), __str__ . Even the beginner stuff is way over my head at this point. Or is stuff something that you get used to in time? Again thank you for the help. ----- Original Message ----- From: "Danny Yoo" <dyoo@hkn.eecs.berkeley.edu> To: "Diana Furr" <dleigh0@carolina.rr.com> Cc: <Tutor@python.org> Sent: Thursday, September 02, 2004 2:22 PM Subject: Re: [Tutor] names > > > On Mon, 30 Aug 2004, Diana Furr wrote: > >> How do you get Python to let name=(anyone's name) >> >> I saw some posts on this subject but didn't find an answer. > > > Hi Diana, > > > Can you point us to one of those posts? I'm not quite sure what you mean > yet, and maybe the context will help. > > > Are you trying to do something like this? > > ### >>>> game = "frogger" >>>> game > 'frogger' > ### > > Here, we can assign the string value "frogger" to the variable name > 'game'. Is this what you're looking for? > From dyoo at hkn.eecs.berkeley.edu Fri Sep 3 08:47:54 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Sep 3 08:48:02 2004 Subject: [Tutor] drawing a graph In-Reply-To: <BAY14-F5qdGSyMp69YD00056ee4@hotmail.com> Message-ID: <Pine.LNX.4.44.0409022334530.14461-100000@hkn.eecs.berkeley.edu> On Fri, 3 Sep 2004, Fathima Javeed wrote: > I have managed to get distances between sequnces at each P value, using > randomization, so now i have a html output file where there are two set > of values one is different distance percentage and another P values from > 1 to 100, How would i draw a graph in Python i.e. distance against P > values for each sequence, Completely lost now, really would appreciate > help, would it be helpful to paste my code here? Hi Vuzzi, Can you give us a small example of what you'd like a graph to look like, for, say three small sequences? That may help us to point you toward the right graph-generating tools. There are graph tools from the 'graphviz' project: http://www.research.att.com/sw/tools/graphviz/ but I'm not sure if you mean this kind of graph. *grin* "Graph" is another one of those overloaded words. You might mean bar charts or line graphs instead. Perhaps you might be able to use HTMLGen to generate nice HTML bar charts: http://www.linuxjournal.com/article.php?sid=2986 But it sounds like you might want something more. There's a Python extension module the R statistics system, and since R has robust graphing, you can take advantage of it: http://rpy.sourceforge.net/ http://www.togaware.com/linux/survivor/Graphs.shtml Does this help? Good luck to you! From karthik at james.hut.fi Fri Sep 3 08:51:04 2004 From: karthik at james.hut.fi (Karthikesh Raju) Date: Fri Sep 3 08:51:13 2004 Subject: [Tutor] Help with regular expressions Message-ID: <Pine.SGI.4.58.0409030947080.3150222@james.hut.fi> Hi All, i am trying to craft a regular expression to do the following: in a file say a.txt a.txt 1 2 3 4 5 6 7 8 9 10 11 23 34 54 56 *** ( 3 5 ) *** -------------------------------- Now i want to match the *** ( 3 5 ) *** line and load 3 in rows and 5 in columns. Where should i start? i tried import re p = re.compile('\( [0-9]+ [0-9]+ \)') a = '( 3 5 )' p.match(a) didnt move a cm .... warm regards karthik ----------------------------------------------------------------------- Karthikesh Raju, email: karthik@james.hut.fi karthikesh.raju@gmail.com Researcher, http://www.cis.hut.fi/karthik Helsinki University of Technology, Tel: +358-9-451 5389 Laboratory of Comp. & Info. Sc., Fax: +358-9-451 3277 Department of Computer Sc., P.O Box 5400, FIN 02015 HUT, Espoo, FINLAND ----------------------------------------------------------------------- From alan.gauld at blueyonder.co.uk Fri Sep 3 09:17:09 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Sep 3 09:16:51 2004 Subject: [Tutor] spitshell for python References: <20040902185934.GB93162@alexis.mi.celestial.com> <00f201c49136$83706820$6401a8c0@xp> <20040902230828.GA9754@alexis.mi.celestial.com> Message-ID: <013701c49186$06f2b0f0$6401a8c0@xp> > I don't think so. Typically there's a commonly accepted way to > provide code that is legal under the shell and the language that > will be ignored by python, but cause the shell to exec python > with appropriate arguments. As an example, this works as the > first lines in a perl script: That doesn't help me I'm afraid. You are going to have to explain what's happening in the perl code > #!/usr/local/bin/perl This bit I understand - it runs the perl interpreter :-) > eval ' exec /usr/local/bin/perl -S $0 ${1+"$@"}' And this evaluates a string as a perl instruction, or is it as a shell instruction? hmm probably the latter. But what is inside the string? It looks like we are running another copy of perl to execute whatever the $0... arguments are? What is the -S option? > if $running_under_some_shell; And I assume this is a conditional that determines whether the eval gets executed depending on the shell, ie Bourne, Bash, csh etc? So I'm guessing that what you want is a bit of Python code that will figure out which shell is running and execute a shell command in that dialect? And the bit of shell to execute, in turn, runs some python script? Am I right? If so that sounds like it brings me back to execfile... so presumably I'm missing some magic in the line noise at the end of the eval statement... Alan G. From karthik at james.hut.fi Fri Sep 3 09:42:06 2004 From: karthik at james.hut.fi (Karthikesh Raju) Date: Fri Sep 3 09:42:11 2004 Subject: [Tutor] Help With Regular expression? - Partial solution Message-ID: <Pine.SGI.4.58.0409031039260.3150222@james.hut.fi> Hi All, i found a partial solution somthing like p = re.compile('\( [0-9]+ [0-9]+ \)') this will match (5 6), or any tuple with 2 indices, i want to put an optional part something like ('\( [0-9]+ ([0-9]?+) \)') so that i can match any thing of the form ( 5 ) ( 5 6 ) (5 6 7) and so on .. How should one craft it .. warm regards karthik ----------------------------------------------------------------------- Karthikesh Raju, email: karthik@james.hut.fi karthikesh.raju@gmail.com Researcher, http://www.cis.hut.fi/karthik Helsinki University of Technology, Tel: +358-9-451 5389 Laboratory of Comp. & Info. Sc., Fax: +358-9-451 3277 Department of Computer Sc., P.O Box 5400, FIN 02015 HUT, Espoo, FINLAND ----------------------------------------------------------------------- From alan.gauld at blueyonder.co.uk Fri Sep 3 09:45:05 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Sep 3 09:44:47 2004 Subject: [Tutor] names (fwd) References: <Pine.LNX.4.44.0409022314280.14461-100000@hkn.eecs.berkeley.edu> Message-ID: <015c01c49189$ed77e060$6401a8c0@xp> > was looking for. I do have 1 more question though. I am trying to learn this > but have no computer experience except being a user. Can anyone suggest > book or something to help me out with the meaning of things like (), __str__ OK, () is pretty fundamental, and most beginners tutorials should explain the use of parens. But __str__ is pretty advanced and not something you need to worry about for a long time yet. In fact I think that in 7 years of Python use I've only directly used __str__ once! While there are several tutorials for absolute beginners I am obviously most interested in the shortcomings of mine! So if you want to try using it let me know when you come across anything you don't think I have explained. I'll then add it and so the tutor gets better for everyone... :-) > . Even the beginner stuff is way over my head at this point. Or is stuff > something that you get used to in time? Again thank you for the help. You can get used to it but there's no reason you can't have it explained too. I certainly try to explain those kinds of basic concepts. As I say there are several other tutorials around but you do have the advantage that I read the tutor list! :-) Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/ From Janssen at rz.uni-frankfurt.de Fri Sep 3 11:14:11 2004 From: Janssen at rz.uni-frankfurt.de (Michael Janssen) Date: Fri Sep 3 11:14:17 2004 Subject: [Tutor] Help with regular expressions In-Reply-To: <Pine.SGI.4.58.0409030947080.3150222@james.hut.fi> References: <Pine.SGI.4.58.0409030947080.3150222@james.hut.fi> Message-ID: <Pine.A41.4.56.0409031110530.3219582@hermes-22.rz.uni-frankfurt.de> On Fri, 3 Sep 2004, Karthikesh Raju wrote: > p.match(a) > > didnt move a cm .... With match you will only find text starting at the beginning of "a". Try p.search to get matches from within "a". regards Michael From kent_johnson at skillsoft.com Fri Sep 3 11:54:10 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Sep 3 11:54:17 2004 Subject: [Tutor] names (fwd) In-Reply-To: <Pine.LNX.4.44.0409022314280.14461-100000@hkn.eecs.berkeley .edu> References: <Pine.LNX.4.44.0409022314280.14461-100000@hkn.eecs.berkeley.edu> Message-ID: <6.1.0.6.0.20040903055235.02986310@mail4.skillsoft.com> You can read my recommendations here: http://personalpages.tds.net/~kent37/Python/PythonResources.html Kent At 11:17 PM 9/2/2004 -0700, Danny Yoo wrote: >---------- Forwarded message ---------- >Date: Thu, 2 Sep 2004 20:12:25 -0400 >From: Diana Furr <dleigh0@carolina.rr.com> >To: Danny Yoo <dyoo@hkn.eecs.berkeley.edu> >Subject: Re: [Tutor] names > >I would like to say thank you to Danny Yoo, Kent Johnson, and R. Alan >Monroe for trying to answer my question. I spent 2 days trying to find the >answer to that question and stumbled on the answer about 30mins after I gave >up looking. name = raw_input('What is your name?') was the answer that I >was looking for. I do have 1 more question though. I am trying to learn this >but have no computer experience except being a user. Can anyone suggest >book or something to help me out with the meaning of things like (), __str__ >. Even the beginner stuff is way over my head at this point. Or is stuff >something that you get used to in time? Again thank you for the help. From kent_johnson at skillsoft.com Fri Sep 3 11:59:46 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Sep 3 11:59:56 2004 Subject: [Tutor] Re: drawing a graph In-Reply-To: <BAY14-F5qdGSyMp69YD00056ee4@hotmail.com> References: <BAY14-F5qdGSyMp69YD00056ee4@hotmail.com> Message-ID: <6.1.0.6.0.20040903055522.02933650@mail4.skillsoft.com> Fuzzi, I recently found the graphing module from VPython very easy to use to create a simple graph. Here is what I did: http://mail.python.org/pipermail/tutor/2004-August/031568.html http://vpython.org/ If you want more help with your existing program then posting the code to the list is a good idea, we can look at it and make suggestions or help you take the next step. Kent At 03:20 AM 9/3/2004 +0100, Fathima Javeed wrote: >Hi, > >I have managed to get distances between sequnces at each P value, using >randomization, so now i have a html output file where there are two set of >values one is different distance percentage and another P values from 1 to >100, How would i draw a graph in Python i.e. distance against P values for >each sequence, Completely lost now, really would appreciate help, would it >be helpful to paste my code here? > >Cheers >Fuzzi > >>From: Kent Johnson <kent_johnson@skillsoft.com> >>To: tutor@python.org >>Subject: Re: [Tutor] need help with comparing list of sequences in >>Python!! >>Date: Tue, 31 Aug 2004 07:04:09 -0400 >> >>Fuzzi, >> >>Here is one way to do this: >>- Use zip() to pair up elements from the two sequences >> >>> s1='aaabbbbcccc' >> >>> s2='aaaccccbcccccccccc' >> >>> zip(s1, s2) >>[('a', 'a'), ('a', 'a'), ('a', 'a'), ('b', 'c'), ('b', 'c'), ('b', 'c'), >>('b', 'c'), ('c', 'b'), ('c', 'c'), ('c', 'c'), ('c', 'c')] >> >>- Use a list comprehension to compare the elements of the pair and put >>the results in a new list. I'm not sure if you want to count the matches >>or the mismatches - your original post says mismatches, but in your >>example you count matches. This example counts matches but it is easy to >>change. >> >>> [a == b for a, b in zip(s1, s2)] >>[True, True, True, False, False, False, False, False, True, True, True] >> >>- In Python, True has a value of 1 and False has a value of 0, so adding >>up the elements of this list gives the number of matches: >> >>> sum([a == b for a, b in zip(s1, s2)]) >>6 >> >>- min() and len() give you the length of the shortest sequence: >> >>> min(len(s1), len(s2)) >>11 >> >>- When you divide, you have to convert one of the numbers to a float or >>Python will use integer division! >> >>> 6/11 >>0 >> >>> float(6)/11 >>0.54545454545454541 >> >>Put this together with the framework that Alan gave you to create a >>program that calculates distances. Then you can start on the >>randomization part. >> >>Kent >> >> >>At 04:03 AM 8/31/2004 +0100, Fathima Javeed wrote: >>>Hi Kent >>> >>>To awnser your question: >>>well here is how it works >>>sequence one = aaabbbbcccc >>>length = 11 >>> >>>seq 2 = aaaccccbcccccccccc >>>length = 18 >>> >>>to get the pairwise similarity of this score the program compares the >>>letters >>>of the two sequences upto length = 11, the length of the shorter sequence. >>> >>>so a match gets a score of 1, therefore using + for match and x for mismatch >>> >>>aaabbbbcccc >>>aaaccccbcccccccccc >>>+++xxxxx+++ >>> >>>there fore the score = 6/11 = 0.5454 or 54% >>> >>>so you only score the first 11 letters of each score and its is not >>>required to compare the rest of the sequence 2. this is what the >>>distance matrix is doing >>> >>>match score == 6 >>> >>>The spaces are deleted to make both of them the same length >>> >>> >>>>From: Kent Johnson <kent_johnson@skillsoft.com> >>>>To: "Fathima Javeed" <fathimajaveed@hotmail.com>, tutor@python.org >>>>Subject: Re: [Tutor] need help with comparing list of sequences in >>>>Python!! >>>>Date: Mon, 30 Aug 2004 13:53:19 -0400 >>>> >>>>Fuzzi, >>>> >>>>How do you count mismatches if the lengths of the sequences are >>>>different? Do you start from the front of both sequences or do you look >>>>for a best match? Do you count the extra characters in the longer >>>>string as mismatches or do you ignore them? An example or two would help. >>>> >>>>For example if >>>>s1=ABCD >>>>s2=XABDDYY >>>>how many characters do you count as different? >>>> >>>>Kent >>>> >>>>At 07:00 PM 8/29/2004 +0100, Fathima Javeed wrote: >>>>>Hi, >>>>>would really appreciate it if someone could help me in Python as i am >>>>>new to the language. >>>>> >>>>>Well i have a list of protein sequences in a text file, e.g. (dummy data) >>>>> >>>>>MVEIGEKAPEIELVDTDLKKVKIPSDFKGKVVVLAFYPAAFTSVCTKEMCTFRDSMAKFNEVNAVVIGISVDP >>>>>PFS >>>>> >>>>>MAPITVGDVVPDGTISFFDENDQLQTVSVHSIAAGKKVILFGVPGAFTPTCSMSHVPGFIGKAEELKSKG >>>>> >>>>>APIKVGDAIPAVEVFEGEPGNKVNLAELFKGKKGVLFGVPGAFTPGCSKTHLPGFVEQAEALKAKGVQVVACL >>>>>SVND >>>>> >>>>>HGFRFKLVSDEKGEIGMKYGVVRGEGSNLAAERVTFIIDREGNIRAILRNI >>>>> >>>>>etc etc >>>>> >>>>>They are not always of the same length, >>>>> >>>>>The first sequence is always the reference sequence which i am tring >>>>>to investigate, basically to reach the objective, i need to compare >>>>>each sequence with the first one, starting with the the comparison of >>>>>the reference sequence by itself. >>>>> >>>>>The objective of the program, is to manupulate each sequence i.e. >>>>>randomly change characters and calculate the distance (Distance: >>>>>Number of letters between a pair of sequnces that dont match DIVIDED >>>>>by the length of the shortest sequence) between the sequence in >>>>>question against the reference sequence. So therefore need a program >>>>>code where it takes the first sequence as a reference sequence >>>>>(constant which is on top of the list), first it compares it with >>>>>itself, then it compares with the second sequence, then with the third >>>>>sequence etc etc each at a time, >>>>> >>>>>for the first comparison, you take a copy of the ref sequnce and >>>>>manupulate the copied sequence) i.e. randomly changing the letters in >>>>>the sequence, and calculating the distances between them. >>>>>(the letters that are used for this are: A R N D C E Q G H I L K M F P >>>>>S T W Y V) >>>>> >>>>>The reference sequence is never altered or manupulated, for the first >>>>>comparison, its the copied version of the reference sequence thats altered. >>>>> >>>>>Randomization is done using different P values >>>>>e.g for example (P = probability of change) >>>>>if P = 0 no random change has been done >>>>>if P = 1.0 all the letters in that particular sequence has been >>>>>randomly changed, therefore p=1.0 equals to the length of the sequence >>>>> >>>>>So its calculating the distance each time between two sequences ( >>>>>first is always the reference sequnce and another second sequence) at >>>>>each P value ( starting from 0, then 0.1, 0.2, ....... 1.0). >>>>> >>>>>Note: Number of sequnces to be compared could be any number and of any >>>>>length >>>>> >>>>>I dont know how to compare each sequence with the first sequnce and >>>>>how to do randomization of the characters in the sequnce therefore to >>>>>calculate the distance for each pair of sequnce , if someone can give >>>>>me any guidance, I would be greatful >>>>> >>>>>Cheers >>>>>Fuzzi >>>>> >>>>>_________________________________________________________________ >>>>>Stay in touch with absent friends - get MSN Messenger >>>>>http://www.msn.co.uk/messenger >>>>> >>>>>_______________________________________________ >>>>>Tutor maillist - Tutor@python.org >>>>>http://mail.python.org/mailman/listinfo/tutor >>> >>>_________________________________________________________________ >>>It's fast, it's easy and it's free. Get MSN Messenger today! >>>http://www.msn.co.uk/messenger >> >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor > >_________________________________________________________________ >Express yourself with cool new emoticons http://www.msn.co.uk/specials/myemo > From project5 at redrival.net Fri Sep 3 13:07:51 2004 From: project5 at redrival.net (Andrei) Date: Fri Sep 3 13:08:02 2004 Subject: [Tutor] Re: converting string to a number References: <Pine.OSF.4.21L.0409012249380.27040-100000@igor.urz.unibas.ch> <Pine.LNX.4.44.0409012301340.10119-100000@hkn.eecs.berkeley.edu> <6.1.0.6.0.20040902054756.029b1878@mail4.skillsoft.com> <4136FEDB.20400@noos.fr> <loom.20040902T163027-354@post.gmane.org> <6.1.0.6.0.20040902105117.029f2ce0@mail4.skillsoft.com> <413743D4.6050605@noos.fr> Message-ID: <loom.20040903T125333-899@post.gmane.org> nik <my.mailing.lists <at> noos.fr> writes: > Thanks for the advice guys, I hadn't thought of what would happen if it > wasn't the exception you were expecting. It still feels uncomfortable > though, I've always felt an exception is *exceptional*, ie something > that was outside your control. The name is misleading :). You do need to be careful with them though, because they have the potential of hiding problems and/or making them difficult to solve when you use them *too* liberally (particularly generic try-excepts over large pieces of code). Yours, Andrei From kent_johnson at skillsoft.com Fri Sep 3 14:12:09 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Sep 3 14:12:12 2004 Subject: [Tutor] Help With Regular expression? - Partial solution In-Reply-To: <Pine.SGI.4.58.0409031039260.3150222@james.hut.fi> References: <Pine.SGI.4.58.0409031039260.3150222@james.hut.fi> Message-ID: <6.1.0.6.0.20040903080337.0288c6b8@mail4.skillsoft.com> If I understand you correctly, you want to match an open parenthesis followed by one or more digits, optionally followed by any number of (one or more whitespace followed by one or more digits) followed by a closing parenthesis This regex will do just that: \(\d+(\s+\d+)*\) Taking a closer look: \( - open paren \d+ - one or more digits (\s+\d+)* - one or more whitespace followed by one or more digits, repeated zero or more times \) - closing parenthesis This regex will recognize the line of interest, it won't help you extract the numbers. For that you could use re.findall, or maybe split() is enough. BTW Python includes a handy regex tester, it is in Python/Tools/Scripts/redemo.py Kent At 10:42 AM 9/3/2004 +0300, Karthikesh Raju wrote: >Hi All, > >i found a partial solution somthing like > >p = re.compile('\( [0-9]+ [0-9]+ \)') > >this will match (5 6), or any tuple with 2 indices, i want to put an >optional part something like > >('\( [0-9]+ ([0-9]?+) \)') >so that i can match any thing of the form >( 5 ) ( 5 6 ) (5 6 7) and so on .. > >How should one craft it .. > >warm regards > >karthik >----------------------------------------------------------------------- >Karthikesh Raju, email: karthik@james.hut.fi > karthikesh.raju@gmail.com >Researcher, http://www.cis.hut.fi/karthik >Helsinki University of Technology, Tel: +358-9-451 5389 >Laboratory of Comp. & Info. Sc., Fax: +358-9-451 3277 >Department of Computer Sc., >P.O Box 5400, FIN 02015 HUT, >Espoo, FINLAND >----------------------------------------------------------------------- >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From s.venter at ntlworld.com Fri Sep 3 17:53:16 2004 From: s.venter at ntlworld.com (Gerhard Venter) Date: Fri Sep 3 17:53:29 2004 Subject: [Tutor] CGI-version not working while similar command-line script is fine Message-ID: <4138936C.8060308@ntlworld.com> Hi all I'm trying to convert the following little code (which works fine if you have lynx installed) into CGI: #! /usr/bin/env python import os websitename = raw_input('enter a website: ') command = 'lynx --dump ' + websitename k=os.popen(command, 'r') for line in k.readlines(): print(line) ------------------------------------------------ My CGI version produces no errors, only a blank page. I have other Python CGI scripts, so it is not about web server config. I have also tested my HTML form, and was able to print the value of websitename to HTML, so I know the form passes the data to the script. import cgi, os import cgitb; cgitb.enable() <>form = cgi.FieldStorage() website = form["websitename"].value command = 'lynx --dump ' + websitename k=os.popen(command, 'r') <>print 'Content-type: text/plain' print for line in k.readlines(): print(line) ------------------------- I suspect there is a hint in the fact that I had to use raw_input instead of just input for the cmd-line version (just input causes a NameError). Maybe the CGI-module has its own version of this effect Any pointers welcome. Gerhard From kent_johnson at skillsoft.com Fri Sep 3 18:17:52 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Sep 3 18:17:57 2004 Subject: [Tutor] CGI-version not working while similar command-line script is fine In-Reply-To: <4138936C.8060308@ntlworld.com> References: <4138936C.8060308@ntlworld.com> Message-ID: <6.1.0.6.0.20040903121324.029ffa58@mail4.skillsoft.com> At 04:53 PM 9/3/2004 +0100, Gerhard Venter wrote: >I suspect there is a hint in the fact that I had to use raw_input instead >of just input for the cmd-line version (just input causes a >NameError). Maybe the CGI-module has its own version of this effect I don't know what is wrong with your CGI but this isn't it. When you just want to input a string, raw_input() is the correct method. input() _evaluates_ what you type, just as if you had typed it to the interpreter, and returns the result. That's why you get a NameError For example, using input() what I type is evaluated: >>> while 1: ... print input("What? ") ... What? 1 1 What? 1+2 3 What? str <type 'str'> What? foo Traceback (most recent call last): File "<stdin>", line 2, in ? File "<string>", line 0, in ? NameError: name 'foo' is not defined The same thing with raw_input() just echoes back exactly what I type: >>> while 1: ... print raw_input('What? ') ... What? 1 1 What? 1+2 1+2 What? str str What? foo foo Kent From dyoo at hkn.eecs.berkeley.edu Fri Sep 3 19:38:22 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Sep 3 19:38:43 2004 Subject: [Tutor] beginner help!!!! (fwd) Message-ID: <Pine.LNX.4.44.0409031028530.19073-100000@hkn.eecs.berkeley.edu> Hi Jill, Let me forward your response to Tutor too: please use "Reply-to-All" in your email client, so that your responses reach the Tutor list. We want to make sure you can get help from the whole group, and not just one person. Anyway, ok, let's take a look. Hmmm... from your printout below, I see that you can get the 'print' statements working ok, so that's good. When you saved your program, how did you save it? What does your saved file look like? Have you seen this page yet? http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/ The tutorial from that link should show how to save and run a program --- it also covers a few pitfalls that you might be running into. I have a vague feeling that you might be saving the "transcript" --- that is, the conversation you're having with the interpreter, but and not just program statements. Can you try the tutorial above and see if you can get that sample exercise working? Good luck to you. ---------- Forwarded message ---------- Date: Thu, 2 Sep 2004 21:02:11 -0400 From: Jill and Paul <bear4@zoominternet.net> To: Danny Yoo <dyoo@hkn.eecs.berkeley.edu> Subject: Re: [Tutor] beginner help!!!! Thanks Danny! I feel so out of it! Here is the sample exercise I typed: Python 2.3 (#46, Jul 29 2003, 18:54:32) [MSC v.1200 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.0 >>> print "Jack and Jill went up a hill" Jack and Jill went up a hill >>> print "to fetch a pail of water;" to fetch a pail of water; >>> print "Jack fell down, and broke his crown," Jack fell down, and broke his crown, >>> print "and Jill came tumbling after." and Jill came tumbling after. >>> After I save it and try to run it here comes the error. It says: Syntax error There's an error in your program: invalid syntax It has an OK button. Ugh! It does that every time I type an exercise. I can't run any of them! I have no idea what happened to the indentation error I asked about previously. How frustrating! Jill ----- Original Message ----- From: "Danny Yoo" <dyoo@hkn.eecs.berkeley.edu> To: "'Jill and Paul'" <bear4@zoominternet.net> Cc: "Tutor" <tutor@python.org> Sent: Thursday, September 02, 2004 2:17 PM Subject: RE: [Tutor] beginner help!!!! > > > On Thu, 2 Sep 2004, Kooser, Ara S wrote: > > > Could you post the code and the error message. Thanks > > > Hi Jill, > > > Yes, we need to see your code. I suspect it might be an indentation > problem, but without seeing your code, I can't make any solid remarks > either. Feel free to just copy and paste it in your reply. > > > About the error message stuff: don't parapharse the error: show it to us > as it comes. For example, here's the kind of error message we like to > see: > > > ### > Traceback (most recent call last): > File "<stdin>", line 1, in ? > NameError: name 'oracle' is not defined > ### > > > In contrast, if we paraphrase the error message to just: > > "There's a Name Error somewhere in my program", > > then that's not as helpful to us. The real error message itself has told > us what appears to be undefined, and on what line the problems appear to > start. The paraphrase, on the other hand, just tells us that something's > wrong, but doesn't tell us where to look. > > In this case, originality is not a good thing: it's good not to suppress > that information in paraphrase. Instead, just copy-and-paste the error, > around where the "Traceback" starts. > > > Good luck! > > From dactex at swbell.net Fri Sep 3 19:49:46 2004 From: dactex at swbell.net (David Carter) Date: Fri Sep 3 19:51:36 2004 Subject: [Tutor] FW: HTMLgen question Message-ID: <000101c491de$68a55750$2800005a@gobot> Hello All; I decided to try out the HTMLgen module today. First of all, let me preface by saying that my HTMLgen install is kludged together, since I have no "make" for Windows, and I had to sort of build it manually by reading the Readme and trying to grok the makefile.txt as best I could. I'm running Python 2.3.2 under Win2K Server with IIS as an ASP-type page. So I just tried the simplest thing I could think of: *******BEGIN CODE***************** <%@ LANGUAGE=PYTHON %> <% import HTMLgen a = HTMLgen.BasicDocument() Response.Write(a) %> *******END CODE******************* Browsing to the page returns: *******BEGIN RESPONSE***************** Python ActiveX Scripting Engine error '80020009' Traceback (most recent call last): File "<Script Block >", line 3, in ? Response.Write(a) File "<COMObject Response>", line 2, in Write TypeError: Objects for SAFEARRAYS must be sequences (of sequences), or a buffer object. /pyfile.asp, line 4 *******END RESPONSE******************* If I run this in IDLE, replacing the "Response.Write(a)" with "print a", I get a nice, complete HTML document, which I can view in my Browser. Anybody know what's up with this? David Carter From ps_python at yahoo.com Fri Sep 3 20:10:20 2004 From: ps_python at yahoo.com (kumar s) Date: Fri Sep 3 20:10:22 2004 Subject: [Tutor] split on tab and new line In-Reply-To: <000101c491de$68a55750$2800005a@gobot> Message-ID: <20040903181020.38644.qmail@web53702.mail.yahoo.com> Dear group, I have a file1: A 12 13 [please read one space is one tab here] B 24 90 C 34 45 File 2: A Apple B Boy Now I want to check if A in file2 is existing in File1, if then, I want to print corresponding element of A in File2, Apple and corresponding value of A in File1. Desired output: Apple 12 13 Boy 24 90 My plan: >f1 = open('file1.txt','r') >f2 = open('file2.txt','r') >x = f1.read() >y = f2.read() >list1 = split(x,'\t','\n') here I want to split f1 on both tab and new line just to get only column 1 of file1. In this case list1 = ['A','B','C'] Similar operation for list2. Now I have list1 and list2. m=[] n=[] >for i in list1: for s in list2: if i == s: m = m.append(i) else: print "i did not find i" My question: 1. Is it possinble to split a file on both tab and new line. This is to get only column 1 of any matrix. If there is some better method please suggest 2. Is my process good. I dont know myself. 3. How can I append the values of A in file 1 to names (column 2 of file 2). Apple 12 13 ( how can I make Apple print next to 12,13) Please help. Thank you. Kumar __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From dyoo at hkn.eecs.berkeley.edu Fri Sep 3 20:12:47 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Sep 3 20:12:53 2004 Subject: [Tutor] FW: HTMLgen question In-Reply-To: <000101c491de$68a55750$2800005a@gobot> Message-ID: <Pine.LNX.4.44.0409031107370.19073-100000@hkn.eecs.berkeley.edu> On Fri, 3 Sep 2004, David Carter wrote: > I decided to try out the HTMLgen module today. [some text cut] > I'm running Python 2.3.2 under Win2K Server with IIS as an ASP-type > page. So I just tried the simplest thing I could think of: > > *******BEGIN CODE***************** > <%@ LANGUAGE=PYTHON %> > <% > import HTMLgen > a = HTMLgen.BasicDocument() > Response.Write(a) > %> > *******END CODE******************* [error message cut] > If I run this in IDLE, replacing the "Response.Write(a)" with "print a", > I get a nice, complete HTML document, which I can view in my Browser. > Anybody know what's up with this? Hi David, One difference between: Response.Write(a) and: print a is that the 'print' statement implicitely turns whatever it's given into a string, by calling str() on its arguments. The error message that you're getting: > Traceback (most recent call last): > File "<Script Block >", line 3, in ? > Response.Write(a) > File "<COMObject Response>", line 2, > in Write TypeError: > Objects for SAFEARRAYS must be sequences (of sequences), or a buffer object. implies that Response.Write() function expects its argument to be a string already. So you may need to do something like: Response.Write(str(a)) Good luck to you! From dactex at swbell.net Fri Sep 3 21:24:15 2004 From: dactex at swbell.net (David Carter) Date: Fri Sep 3 21:24:22 2004 Subject: [Tutor] RE: HTMLgen question In-Reply-To: <Pine.LNX.4.44.0409031107370.19073-100000@hkn.eecs.berkeley.edu> Message-ID: <000701c491eb$9ae35bb0$2800005a@gobot> That worked! Thanks, Danny! David Carter Danny Yoo wrote: > Hi David, > > > One difference between: > > Response.Write(a) > > and: > > print a > > is that the 'print' statement implicitly turns whatever it's > given into a string, by calling str() on its arguments. > > > The error message that you're getting: > > > > Traceback (most recent call last): > > File "<Script Block >", line 3, in ? > > Response.Write(a) > > File "<COMObject Response>", line 2, > > in Write TypeError: > > Objects for SAFEARRAYS must be sequences (of sequences), or > a buffer > > object. > > > implies that Response.Write() function expects its argument > to be a string already. > > So you may need to do something like: > > Response.Write(str(a)) > From linux-user at softhome.net Fri Sep 3 10:08:28 2004 From: linux-user at softhome.net (Conrad) Date: Fri Sep 3 22:06:30 2004 Subject: [Tutor] Graphs In-Reply-To: <20040903100043.2F5C11E4032@bag.python.org> References: <20040903100043.2F5C11E4032@bag.python.org> Message-ID: <1094198908.6705.1.camel@radiol> While were on the topic of graphs, does anyone know a module that can graph equations (y = x*2). I've looked at SciPy, but that seems a little advanced. From kent_johnson at skillsoft.com Fri Sep 3 22:20:56 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Sep 3 22:21:02 2004 Subject: [Tutor] split on tab and new line In-Reply-To: <20040903181020.38644.qmail@web53702.mail.yahoo.com> References: <000101c491de$68a55750$2800005a@gobot> <20040903181020.38644.qmail@web53702.mail.yahoo.com> Message-ID: <6.1.0.6.0.20040903160535.029cff80@mail4.skillsoft.com> Kumar, You can't directly split the text from the file in two ways at once. You could iterate over the lines in the files and build the lists you want, but that isn't the approach I would take, for a couple of reasons - you are throwing away some data that you need - with a dictionary, you can keep the extra data from file1 and have easy lookup. I would try something like this: for each line in file1: split the line into the initial letter (the key) and everything else (data1) put the key and data into a dictionary for each line in file2: split the line into the initial letter (the key) and everything else (data2) look up the new key in the dictionary. If it is there, you will get the file1 data back. Now you have everything you need to print out what you want. (data1 and data2) If you need help with the individual steps, let us know. Kent At 11:10 AM 9/3/2004 -0700, kumar s wrote: >Dear group, > >I have a file1: > >A 12 13 [please read one space is one tab here] >B 24 90 >C 34 45 > >File 2: > >A Apple >B Boy > >Now I want to check if A in file2 is existing in >File1, if then, I want to print corresponding element >of A in File2, Apple and corresponding value of A in >File1. > >Desired output: > >Apple 12 13 >Boy 24 90 > > > >My plan: > >f1 = open('file1.txt','r') > >f2 = open('file2.txt','r') > > >x = f1.read() > >y = f2.read() > > >list1 = split(x,'\t','\n') > >here I want to split f1 on both tab and new line just >to get only column 1 of file1. In this case >list1 = ['A','B','C'] > > >Similar operation for list2. > >Now I have list1 and list2. >m=[] >n=[] > >for i in list1: > for s in list2: > if i == s: > m = m.append(i) > else: > print "i did not find i" > > >My question: >1. Is it possinble to split a file on both tab and new >line. This is to get only column 1 of any matrix. If >there is some better method please suggest > >2. Is my process good. I dont know myself. > >3. How can I append the values of A in file 1 to names >(column 2 of file 2). > >Apple 12 13 ( how can I make Apple print next to >12,13) > > >Please help. > >Thank you. > >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 From alipolatel at yahoo.com Fri Sep 3 22:32:02 2004 From: alipolatel at yahoo.com (Ali Polatel) Date: Fri Sep 3 22:32:05 2004 Subject: [Tutor] A few Questions Message-ID: <20040903203202.39063.qmail@web61003.mail.yahoo.com> Dear Tutors and Friends, Here are a few questions to test your knowledge :) 1.What command makes the python programme print out the file it is in? I mean for example if it is saved in c:\windows\system what command gives me this 2.I want the programme to understand and interprete the keyboard buttons.. For example when the user clicks "esc" the programme will shut down... or when he clicks any other button something other will happen etc.. 3.The last but not least ... when I am converting the python file to exe(with py2exe) I want to pack all files created(the exe file ,library.zip and others)into a one windows installer file... so that when user runs it he'll install the programme to his computer I hope you can manage to answer those questions :)) Thanks for all questions you have answered so far and Good luck for all that you'll try to answer :) You are simply great! Regards, Ali Polatel --------------------------------- Do you Yahoo!? Win 1 of 4,000 free domain names from Yahoo! Enter now. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040903/7bddcf73/attachment.html From alan.gauld at blueyonder.co.uk Fri Sep 3 22:41:47 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Sep 3 22:41:19 2004 Subject: [Tutor] split on tab and new line References: <20040903181020.38644.qmail@web53702.mail.yahoo.com> Message-ID: <01a501c491f6$6e9f4310$6401a8c0@xp> > I have a file1: > > A 12 13 [please read one space is one tab here] > File 2: > > A Apple > > Now I want to check if A in file2 is existing in > File1, if then, I want to print corresponding element > of A in File2, Apple and corresponding value of A in > File1. > > Desired output: > > Apple 12 13 I'd suggest using a pair of dictionaries loaded from the files (Might be a problem is very big files (>1MB)...). Then you can go: for key in File2.keys(): try: print File2[key], file1[key] except KeyError: continue HTH, Alan G. From alan.gauld at blueyonder.co.uk Fri Sep 3 22:45:30 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Fri Sep 3 22:45:03 2004 Subject: [Tutor] Graphs References: <20040903100043.2F5C11E4032@bag.python.org> <1094198908.6705.1.camel@radiol> Message-ID: <01b001c491f6$f39fe060$6401a8c0@xp> > While were on the topic of graphs, does anyone know a module that can > graph equations (y = x*2). I've looked at SciPy, but that seems a little > advanced. You could use a canvas in Tkinter for simple graph plotting. just store the inter,mediate results and use draw to go from one point to the next. Alternatively you could look at Visual Python, I believe it does simple graphics easily. Finally you could play with the standard turtle graphics module. Turtle graphics are quite good for drawing graphs although I confess I've mainly used them in Logo and Pascal... certainly no more than playing in Python. Alan G. From kabads at gmail.com Fri Sep 3 23:10:56 2004 From: kabads at gmail.com (Adam Cripps) Date: Fri Sep 3 23:11:06 2004 Subject: [Tutor] A few Questions In-Reply-To: <20040903203202.39063.qmail@web61003.mail.yahoo.com> References: <20040903203202.39063.qmail@web61003.mail.yahoo.com> Message-ID: <c7ff385504090314106c906dac@mail.gmail.com> ----- Original Message ----- From: Ali Polatel <alipolatel@yahoo.com> Date: Fri, 3 Sep 2004 13:32:02 -0700 (PDT) Subject: [Tutor] A few Questions To: tutor@python.org Dear Tutors and Friends, Here are a few questions to test your knowledge :) 1.What command makes the python programme print out the file it is in? I mean for example if it is saved in c:\windows\system what command gives me this This would be stored in the variable sys.argv[0] HTH Adam -- proj: http://jiletters.sf.net site: http://www.monkeez.org wiki: http://wiki.monkeez.org From dyoo at hkn.eecs.berkeley.edu Sat Sep 4 01:30:56 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat Sep 4 01:31:02 2004 Subject: [Tutor] split on tab and new line In-Reply-To: <20040903181020.38644.qmail@web53702.mail.yahoo.com> Message-ID: <Pine.LNX.4.44.0409031608130.28694-100000@hkn.eecs.berkeley.edu> On Fri, 3 Sep 2004, kumar s wrote: > A 12 13 [please read one space is one tab here] > B 24 90 > C 34 45 > > File 2: > > A Apple > B Boy > > Now I want to check if A in file2 is existing in File1, if then, I want > to print corresponding element of A in File2, Apple and corresponding > value of A in File1. > > Desired output: > > Apple 12 13 > Boy 24 90 Hi Kumar, I'd recommend breaking the problem into two independent subproblems. It looks like you're trying to juggle the whole problem, and that's hard. Make things a little easier on yourself. *grin* By making and solving smaller subproblems, you can make progress without having to do the whole thing all at once. Subproblem1 --- One subproblem might be something to take a "label" ("A"), and translate that into some value ("Apple"). In fact, we can hardcode something right now: ### def getLabelName(label): if label == 'A': return 'Apple' if label == 'B': return 'Boy' return 'I-Dont-Know-Yet' ### Yes, it's a simple definition, but that's ok! *grin* This does not yet read from File2, but that's fine for a start. Can you fix up getLabelName() so that it does read its input from File2? If it's not obvious how to do this yet, don't worry, because you can leave it until later, and attack the other Subproblem2 instead. Subproblem2 --- If you have some version of getLabelName(), you can concentrate on transforming the contents of: A 12 13 B 24 90 C 34 45 into: Apple 12 13 Boy 24 90 Candy 34 45 If you use getLabelName(), your second subproblem can just focus on looking at File1. And this part of the problem will kinda work even if Subproblem1 isn't perfectly working, since at the moment, getLabelName() is hardcoded to know that 'A' means 'Apple' and 'B' means 'Boy'. It just means that you might see something like: Apple 12 13 Boy 24 90 I-Dont-Know-Yet 34 45 Does this make sense? The subproblems here are designed so that you have a choice to attack one or the other, without having to manage both at the same time. If you have more questions, please feel free to ask. Good luck! From alan.gauld at blueyonder.co.uk Sat Sep 4 12:13:17 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Sep 4 12:13:08 2004 Subject: [Tutor] A few Questions References: <20040903203202.39063.qmail@web61003.mail.yahoo.com> Message-ID: <001101c49267$cc1ac610$6401a8c0@xp> > 1.What command makes the python programme print out the file it is in? The sys.argv[0] value should be the name of the python script. I don't think it provides the full path however. And what happens if you use py2exe I have no idea. > 2.I want the programme to understand and interprete the keyboard > buttons.. For example when the user clicks "esc" the programme will > shut down... If it's a GUI program you have to catch the keyboard events. If its a console program and you are using Windows then you must use the msvcrt.getch() function. There is some info on both methods in my event driven programming topic in my tutorial. Mouse clicks will only be available in a GUI program (unless you resort to some very deep magic using ctypes...) > 3.The last but not least ... when I am converting the python file > to exe(with py2exe) I want to pack all files created(the exe file , > library.zip and others)into a one windows installer file... Get any windows installer and it will do all of that. There are several available,. I believe a few are freeware although I use Installshield which I got bundled with Delphi. HTH, Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/ From alipolatel at yahoo.com Sat Sep 4 13:20:51 2004 From: alipolatel at yahoo.com (Ali Polatel) Date: Sat Sep 4 13:20:57 2004 Subject: [Tutor] A few Questions In-Reply-To: <001101c49267$cc1ac610$6401a8c0@xp> Message-ID: <20040904112051.65185.qmail@web61006.mail.yahoo.com> thanks for all answers... Last question is How to catch keyboard events in GUI? Regards --------------------------------- Do you Yahoo!? New and Improved Yahoo! Mail - Send 10MB messages! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040904/2a96df14/attachment.htm From kabads at gmail.com Sat Sep 4 13:39:24 2004 From: kabads at gmail.com (Adam Cripps) Date: Sat Sep 4 13:39:28 2004 Subject: [Tutor] A few Questions In-Reply-To: <001101c49267$cc1ac610$6401a8c0@xp> References: <20040903203202.39063.qmail@web61003.mail.yahoo.com> <001101c49267$cc1ac610$6401a8c0@xp> Message-ID: <c7ff385504090404393cabc415@mail.gmail.com> On Sat, 4 Sep 2004 11:13:17 +0100, Alan Gauld <alan.gauld@blueyonder.co.uk> wrote: > > 1.What command makes the python programme print out the file it is > in? > > The sys.argv[0] value should be the name of the python script. > I don't think it provides the full path however. > And what happens if you use py2exe I have no idea. I'm pretty sure that it does show the whole path on Windows - not sure for *nix. I used this a few days ago and remembered that I didn't need to use [0]. HTH Adam -- proj: http://jiletters.sf.net site: http://www.monkeez.org wiki: http://wiki.monkeez.org From kent_johnson at skillsoft.com Sat Sep 4 14:12:20 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sat Sep 4 14:12:27 2004 Subject: [Tutor] A few Questions In-Reply-To: <20040904112051.65185.qmail@web61006.mail.yahoo.com> References: <001101c49267$cc1ac610$6401a8c0@xp> <20040904112051.65185.qmail@web61006.mail.yahoo.com> Message-ID: <6.1.0.6.0.20040904080126.02a3cb78@mail4.skillsoft.com> This depends on the GUI framework. Most frameworks have a way to "bind" key events to a callback function. The function that is bound to the events will be called when an event occurs. In Tkinter, you can bind an event handler to a specific widget, to a window, to all instances of a widget class, or to the entire application. Which one you use depends on what you are trying to accomplish. For example if you want a text entry widget to respond in a special way to the enter key, you would bind to the specific widget with something like textField.bind("<Return>", myEnterHandler) where myEnterHandler is the name of your handler function. On the other hand if you want to make the F1 key bring up help for your application, you would bind to the entire application using bind_all. You can find more information on the event-handling page of Alan's tutorial or here: http://www.pythonware.com/library/tkinter/introduction/events-and-bindings.htm Kent At 04:20 AM 9/4/2004 -0700, Ali Polatel wrote: >thanks for all answers... >Last question is >How to catch keyboard events in GUI? >Regards > > >Do you Yahoo!? ><http://us.rd.yahoo.com/mail_us/taglines/10/*http://promotions.yahoo.com/new_mail/static/efficiency.html>New >and Improved Yahoo! Mail - Send 10MB messages! >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From alan.gauld at blueyonder.co.uk Sat Sep 4 14:36:05 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Sat Sep 4 14:35:57 2004 Subject: [Tutor] A few Questions References: <20040904112051.65185.qmail@web61006.mail.yahoo.com> Message-ID: <002b01c4927b$bf38a610$6401a8c0@xp> > Last question is > How to catch keyboard events in GUI? That's covered in my Event Driven Programming tutor page, both simple keystrokes and special keys like CTRL etc. Alan G Author of the Learn to Program web tutor http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/tutevent.htm From python at bernardlebel.com Sat Sep 4 17:36:21 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Sat Sep 4 17:37:25 2004 Subject: [Tutor] The thread module Message-ID: <000001c49295$0fab6650$0d01a8c0@studioaction.local> Hello, It is my first ever attempt at managing threads. And I must admit that I am absolutely lost! I don't know if I'm using the right approach at all for what I'm after, so if you have any suggestion, do not hesitate! What I'm looking for: I launch a command line shell, import a script, and the script runs forever. The watches two main things: 1- The accessibility of two shared locations on the network, so if one of them goes down (or both), an email is sent to various people. When one server goes down, it is no longer checked. When both server go down, none are checked. A check is performed every 5 minutes. 2- The remaining space on several network volumes, and if one goes under 5Gb, again, an email is sent. The check is performed no matter what, every hour. Currently I have two scripts that do the job very well. Now the problem is that I want to consolidate them into one, so I don't have two python shell running, but one. I figured that using child threads would be a good way to manage this, because each thread could manage task. Basically I am looking at doing two parallel loops. So I've messed a little bit with the thread module, and have read the pdf tutorial from Norman Matloff, but I'm still confused about the whole thing. Anyone can recommend tutorial or ressources for this? Or even a different approach for the problem? Thanks in advance Bernard From jonnorkol at yahoo.com Sat Sep 4 17:40:26 2004 From: jonnorkol at yahoo.com (Jon Kolbe) Date: Sat Sep 4 17:40:31 2004 Subject: [Tutor] (no subject) Message-ID: <20040904154026.37213.qmail@web53401.mail.yahoo.com> I'm new to python, and I'm having some trouble. I'm trying to write a program so people can make a character for a Risus game. Since the cliches (skills) of the character have to be user-defined, I can't make a list. I've gotten to where the user has to insert the name of the cliche, but I've ran into this error Traceback (most recent call last): File "<pyshell#38>", line 1, in -toplevel- risus() File "<pyshell#37>", line 15, in risus reply = input() File "<string>", line 0, in -toplevel- NameError: name 'cook' is not defined Here's my program #Risus Character Generator def risus(): cliches = {} player = {} player['Name'] = raw_input("What is the Character's name? ") dice = input("How many dice will your character have? ") player['Title'] = raw_input("What is the Character's title? ") while dice > 0: print "Do you want to add a cliche? " print "1 Yes " print "2 No " reply = input() if reply == 1: print "What is the name of the cliche? " reply = input() cliches = { 'cliche': "reply" } print "How many dice? " power = input() dice = dice-power cliches = { 'cliche': "power" } player[cliches] = power else: dice = 0 print "You're done!" print character If any one can give me a hint on how to add user-input to a list, thanks in advance Jon --------------------------------- Do you Yahoo!? Win 1 of 4,000 free domain names from Yahoo! Enter now. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040904/a975140f/attachment.html From kabads at gmail.com Sat Sep 4 17:49:22 2004 From: kabads at gmail.com (Adam Cripps) Date: Sat Sep 4 17:49:34 2004 Subject: [Tutor] (no subject) In-Reply-To: <20040904154026.37213.qmail@web53401.mail.yahoo.com> References: <20040904154026.37213.qmail@web53401.mail.yahoo.com> Message-ID: <c7ff385504090408493cfaa8d8@mail.gmail.com> ----- Original Message ----- From: Jon Kolbe <jonnorkol@yahoo.com> Date: Sat, 4 Sep 2004 08:40:26 -0700 (PDT) Subject: [Tutor] (no subject) To: tutor@python.org I'm new to python, and I'm having some trouble. I'm trying to write a program so people can make a character for a Risus game. Since the cliches (skills) of the character have to be user-defined, I can't make a list. I've gotten to where the user has to insert the name of the cliche, but I've ran into this error Traceback (most recent call last): File "<pyshell#38>", line 1, in -toplevel- risus() File "<pyshell#37>", line 15, in risus reply = input() File "<string>", line 0, in -toplevel- NameError: name 'cook' is not defined Here's my program #Risus Character Generator def risus(): cliches = {} player = {} player['Name'] = raw_input("What is the Character's name? ") dice = input("How many dice will your character have? ") player['Title'] = raw_input("What is the Character's title? ") while dice > 0: print "Do you want to add a cliche? " print "1 Yes " print "2 No " reply = input() if reply == 1: print "What is the name of the cliche? " reply = input() cliches = { 'cliche': "reply" } print "How many dice? " power = input() dice = dice-power cliches = { 'cliche': "power" } player[cliches] = power else: dice = 0 print "You're done!" print character If any one can give me a hint on how to add user-input to a list, thanks in advance Jon Something like this should get you the sort of thing you are aiming for: cliche = [] power = raw_input ("What power would you like?") cliche.Add(power) This would store the input into the first 'slot' of the list (in this case power[0]). However, to me it sounds like your problem would better resolved with an object oriented approach. Does anyone else think this might suit Jon better? Adam From amonroe at columbus.rr.com Sat Sep 4 18:02:54 2004 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sat Sep 4 18:03:00 2004 Subject: [Tutor] split on tab and new line In-Reply-To: <Pine.LNX.4.44.0409031608130.28694-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0409031608130.28694-100000@hkn.eecs.berkeley.edu> Message-ID: <123826620707.20040904120254@columbus.rr.com> > One subproblem might be something to take a "label" ("A"), and translate > that into some value ("Apple"). In fact, we can hardcode something right > now: > ### > def getLabelName(label): > if label == 'A': return 'Apple' > if label == 'B': return 'Boy' > return 'I-Dont-Know-Yet' > ### Rather than an if-tree, you could try a dictionary here... allmylabels = { 'A': 'Apple', 'B': 'Boy' } Alan From amonroe at columbus.rr.com Sat Sep 4 18:04:41 2004 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Sat Sep 4 18:04:51 2004 Subject: [Tutor] A few Questions In-Reply-To: <001101c49267$cc1ac610$6401a8c0@xp> References: <20040903203202.39063.qmail@web61003.mail.yahoo.com> <001101c49267$cc1ac610$6401a8c0@xp> Message-ID: <128826728142.20040904120441@columbus.rr.com> >> 3.The last but not least ... when I am converting the python file >> to exe(with py2exe) I want to pack all files created(the exe file , >> library.zip and others)into a one windows installer file... > Get any windows installer and it will do all of that. There are > several available,. I believe a few are freeware although I use > Installshield which I got bundled with Delphi. Innosetup is freeware and easy http://www.jrsoftware.org/isinfo.php Alan From kabads at gmail.com Sat Sep 4 20:05:34 2004 From: kabads at gmail.com (Adam Cripps) Date: Sat Sep 4 20:05:37 2004 Subject: [Tutor] (no subject) In-Reply-To: <20040904161506.57352.qmail@web53406.mail.yahoo.com> References: <c7ff385504090408493cfaa8d8@mail.gmail.com> <20040904161506.57352.qmail@web53406.mail.yahoo.com> Message-ID: <c7ff38550409041105758e84d0@mail.gmail.com> ----- Original Message ----- From: Jon Kolbe <jonnorkol@yahoo.com> Date: Sat, 4 Sep 2004 09:15:06 -0700 (PDT) Subject: Re: [Tutor] (no subject) To: Adam Cripps <kabads@gmail.com> Adam Cripps <kabads@gmail.com> wrote: Something like this should get you the sort of thing you are aiming for: cliche = [] power = raw_input ("What power would you like?") cliche.Add(power) This would store the input into the first 'slot' of the list (in this case power[0]). However, to me it sounds like your problem would better resolved with an object oriented approach. Does anyone else think this might suit Jon better? Adam Thanks, I didn't even consider using objects (They look scary). I'll try out that approach and see if it works. Jon I'm not sure if it will suit your problem, but I had a similar situation when I was trying to write a magazine catalogue system. To save myself entering information over and over again, I created objects and stored the data within objects. In fact, I was scared of Oo design until I wrote it in Python (my previous experience was Java). Python actually makes Oo very clear and easy to understand. Why not have a quick go - you've not got much to lose. Adam -- proj: http://jiletters.sf.net site: http://www.monkeez.org wiki: http://wiki.monkeez.org From kent_johnson at skillsoft.com Sat Sep 4 20:29:56 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sat Sep 4 20:30:07 2004 Subject: [Tutor] The thread module In-Reply-To: <000001c49295$0fab6650$0d01a8c0@studioaction.local> References: <000001c49295$0fab6650$0d01a8c0@studioaction.local> Message-ID: <6.1.0.6.0.20040904142353.02a1b228@mail4.skillsoft.com> Bernard, Thinking about threads can twist your brain in knots, but for simple uses its pretty easy. The threading module is simpler to use than thread. To start a new thread, create a Thread object passing a function to the constructor. Then call start() on the object. The thread will run until the function you pass it returns, or forever if the function doesn't return. Here is a simple example of creating two threads that run forever, this is similar to what you are trying to do: >>> from threading import Thread >>> import time Here are the two callback functions: >>> def f1(): ... while 1: ... print 'f1' ... time.sleep(1) ... >>> def f2(): ... while 1: ... print 'f2' ... time.sleep(3) ... Create the two threads and start them. You don't have to do this in one line from your program but from the console it is easier... >>> Thread(target=f1).start(); Thread(target=f2).start() f1 f2 >>> f1 f1 f2 f1 f1 f1 f2 f1 f1 etc. Another way you could write your program is to have one loop that checks to see if it is time to run any of the tasks. It could keep a list of scheduled tasks and check the list each time it wakes. Kent At 05:36 PM 9/4/2004 +0200, Bernard Lebel wrote: >Hello, > >It is my first ever attempt at managing threads. And I must admit that I am >absolutely lost! I don't know if I'm using the right approach at all for >what I'm after, so if you have any suggestion, do not hesitate! > >What I'm looking for: >I launch a command line shell, import a script, and the script runs forever. >The watches two main things: >1- The accessibility of two shared locations on the network, so if one of >them goes down (or both), an email is sent to various people. When one >server goes down, it is no longer checked. When both server go down, none >are checked. A check is performed every 5 minutes. >2- The remaining space on several network volumes, and if one goes under >5Gb, again, an email is sent. The check is performed no matter what, every >hour. > >Currently I have two scripts that do the job very well. > >Now the problem is that I want to consolidate them into one, so I don't have >two python shell running, but one. >I figured that using child threads would be a good way to manage this, >because each thread could manage task. Basically I am looking at doing two >parallel loops. > > >So I've messed a little bit with the thread module, and have read the pdf >tutorial from Norman Matloff, but I'm still confused about the whole thing. >Anyone can recommend tutorial or ressources for this? Or even a different >approach for the problem? > > >Thanks in advance >Bernard > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From kent_johnson at skillsoft.com Sat Sep 4 22:27:31 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sat Sep 4 22:27:37 2004 Subject: [Tutor] (no subject) In-Reply-To: <c7ff385504090408493cfaa8d8@mail.gmail.com> References: <20040904154026.37213.qmail@web53401.mail.yahoo.com> <c7ff385504090408493cfaa8d8@mail.gmail.com> Message-ID: <6.1.0.6.0.20040904161703.02a171b8@mail4.skillsoft.com> I can see two good ways to do this. The simplest would be to represent a cliche as a tuple of (name, power) and keep a list of tuples to hold all the cliches. There would be one loop to input the cliches and another loop to print them. If the program is not going to get much bigger than what you posted, that is probably a good solution. You could also make a class to represent a cliche. It would have attributes for name and power, a method to set its attributes from user input and a __str__() method to make a string representation for printing. This will be handy if your program is going to get bigger and make more use of cliches. For a learning exercise you might even want to write the program both ways to get a better feel for the advantages of each one. My guess is the tuple approach will be shorter but using classes will give the program a very clean design and a better starting point for a larger program. Kent At 04:49 PM 9/4/2004 +0100, Adam Cripps wrote: >----- Original Message ----- >From: Jon Kolbe <jonnorkol@yahoo.com> >Date: Sat, 4 Sep 2004 08:40:26 -0700 (PDT) >Here's my program > >#Risus Character Generator >def risus(): > cliches = {} > player = {} > player['Name'] = raw_input("What is the Character's name? ") > dice = input("How many dice will your character have? ") > player['Title'] = raw_input("What is the Character's title? ") > while dice > 0: > print "Do you want to add a cliche? " > print "1 Yes " > print "2 No " > reply = input() > if reply == 1: > print "What is the name of the cliche? " > reply = input() > cliches = { 'cliche': "reply" } > print "How many dice? " > power = input() > dice = dice-power > cliches = { 'cliche': "power" } > player[cliches] = power > else: > dice = 0 > print "You're done!" > print character > >However, to me it sounds like your problem would better resolved with >an object oriented approach. Does anyone else think this might suit >Jon better? > >Adam >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From klappnase at freenet.de Sat Sep 4 23:55:56 2004 From: klappnase at freenet.de (Michael Lange) Date: Sat Sep 4 23:56:13 2004 Subject: [Tutor] A few Questions In-Reply-To: <c7ff385504090404393cabc415@mail.gmail.com> References: <20040903203202.39063.qmail@web61003.mail.yahoo.com> <001101c49267$cc1ac610$6401a8c0@xp> <c7ff385504090404393cabc415@mail.gmail.com> Message-ID: <20040904235556.497da573.klappnase@freenet.de> On Sat, 4 Sep 2004 12:39:24 +0100 Adam Cripps <kabads@gmail.com> wrote: > On Sat, 4 Sep 2004 11:13:17 +0100, Alan Gauld > <alan.gauld@blueyonder.co.uk> wrote: > > > 1.What command makes the python programme print out the file it is > > in? > > > > The sys.argv[0] value should be the name of the python script. > > I don't think it provides the full path however. > > And what happens if you use py2exe I have no idea. > > I'm pretty sure that it does show the whole path on Windows - not sure > for *nix. I used this a few days ago and remembered that I didn't need > to use [0]. > > HTH > > Adam > On linux it shows the complete path, too, but in fact the path to the file that is called from the command line, which might cause confusion if you use a symbolic link to launch your program. Regards Michael From bill.mill at gmail.com Sun Sep 5 03:27:19 2004 From: bill.mill at gmail.com (Bill Mill) Date: Sun Sep 5 03:27:23 2004 Subject: [Tutor] Graphs In-Reply-To: <1094198908.6705.1.camel@radiol> References: <20040903100043.2F5C11E4032@bag.python.org> <1094198908.6705.1.camel@radiol> Message-ID: <797fe3d4040904182731baa2da@mail.gmail.com> Try the Gnuplot module (http://gnuplot-py.sourceforge.net/). Works on (at least) windows and linux. Here's how easy it is to graph y = x*2: In [1]: import Gnuplot In [2]: g = Gnuplot.Gnuplot() In [3]: g.plot('x**2') You can get from there to some really complicated graphics quickly and easily. I've used it extensively, and it's a joy to work with; the python module is easier than working with the native Gnuplot. Also, I think if you download IPython (http://ipython.scipy.org/), which you should, then Gnuplot comes with it. But I could be wrong. As always, RTFM when downloading stuff. Peace Bill Mill On Fri, 03 Sep 2004 01:08:28 -0700, Conrad <linux-user@softhome.net> wrote: > While were on the topic of graphs, does anyone know a module that can > graph equations (y = x*2). I've looked at SciPy, but that seems a little > advanced. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From kent_johnson at skillsoft.com Sun Sep 5 15:19:00 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sun Sep 5 15:19:10 2004 Subject: [Tutor] CGI-version not working while similar command-line script is fine In-Reply-To: <413A6F63.7040104@africonnect.com> References: <4138936C.8060308@ntlworld.com> <6.1.0.6.0.20040903121324.029ffa58@mail4.skillsoft.com> <413A6F63.7040104@africonnect.com> Message-ID: <6.1.0.6.0.20040905091038.02a47b48@mail4.skillsoft.com> At 02:44 AM 9/5/2004 +0100, Gerhard Venter wrote: >I now think that the URL doesn't get passed to lynx - this seems to be a >shortcoming of the Windows shell or whatever is being used to expand the >os.system command. This should work. My guess is you have an error in your script, maybe a problem with quoting or string substitution. Can you show us the script that is having trouble? >I would like to do it natively in Python, without lynx. I have expiernce >of urllib, but don't want raw html. Is there a way I can get interpreted >html as the output? I don't know of any Python package that will give you rendered HTML the way lynx does. There are several packages that will parse HTML and give easy access to the contents. They are designed for screen-scraping applications where you are accessing a specific part of the HTML but you could probably walk the tree they generate and pull out the text. The packages are Beautiful Soup: http://www.crummy.com/software/BeautifulSoup/ Scraper: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/286269 ElementTree Tidy: http://effbot.org/zone/element-tidylib.htm One thing these add to the built-in HTML parsers is better tolerance for badly-formed HTML. Kent From python at bernardlebel.com Sun Sep 5 18:53:48 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Sun Sep 5 17:51:33 2004 Subject: [Tutor] The thread module References: <000001c49295$0fab6650$0d01a8c0@studioaction.local> <6.1.0.6.0.20040904142353.02a1b228@mail4.skillsoft.com> Message-ID: <000a01c49368$ec27a700$2901a8c0@atyss> Thanks a bunch Kent, this is exactly what I was after. Bernard ----- Original Message ----- From: "Kent Johnson" <kent_johnson@skillsoft.com> To: <tutor@python.org> Sent: Saturday, September 04, 2004 7:29 PM Subject: Re: [Tutor] The thread module > Bernard, > > Thinking about threads can twist your brain in knots, but for simple uses > its pretty easy. The threading module is simpler to use than thread. To > start a new thread, create a Thread object passing a function to the > constructor. Then call start() on the object. The thread will run until the > function you pass it returns, or forever if the function doesn't return. > > Here is a simple example of creating two threads that run forever, this is > similar to what you are trying to do: > >>> from threading import Thread > >>> import time > > Here are the two callback functions: > >>> def f1(): > ... while 1: > ... print 'f1' > ... time.sleep(1) > ... > >>> def f2(): > ... while 1: > ... print 'f2' > ... time.sleep(3) > ... > > Create the two threads and start them. You don't have to do this in one > line from your program but from the console it is easier... > >>> Thread(target=f1).start(); Thread(target=f2).start() > f1 > f2 > >>> f1 > f1 > f2 > f1 > f1 > f1 > f2 > f1 > f1 > etc. > > Another way you could write your program is to have one loop that checks to > see if it is time to run any of the tasks. It could keep a list of > scheduled tasks and check the list each time it wakes. > > Kent > > At 05:36 PM 9/4/2004 +0200, Bernard Lebel wrote: > >Hello, > > > >It is my first ever attempt at managing threads. And I must admit that I am > >absolutely lost! I don't know if I'm using the right approach at all for > >what I'm after, so if you have any suggestion, do not hesitate! > > > >What I'm looking for: > >I launch a command line shell, import a script, and the script runs forever. > >The watches two main things: > >1- The accessibility of two shared locations on the network, so if one of > >them goes down (or both), an email is sent to various people. When one > >server goes down, it is no longer checked. When both server go down, none > >are checked. A check is performed every 5 minutes. > >2- The remaining space on several network volumes, and if one goes under > >5Gb, again, an email is sent. The check is performed no matter what, every > >hour. > > > >Currently I have two scripts that do the job very well. > > > >Now the problem is that I want to consolidate them into one, so I don't have > >two python shell running, but one. > >I figured that using child threads would be a good way to manage this, > >because each thread could manage task. Basically I am looking at doing two > >parallel loops. > > > > > >So I've messed a little bit with the thread module, and have read the pdf > >tutorial from Norman Matloff, but I'm still confused about the whole thing. > >Anyone can recommend tutorial or ressources for this? Or even a different > >approach for the problem? > > > > > >Thanks in advance > >Bernard From Mark.Kels at gmail.com Sun Sep 5 17:56:13 2004 From: Mark.Kels at gmail.com (Mark Kels) Date: Sun Sep 5 17:56:19 2004 Subject: [Tutor] A problem with the shelve module Message-ID: <d12026530409050856a974a3@mail.gmail.com> Hi all, Its my again (the guy with the bad english... :-/ ). I started to build a personal organizer useing the module "shelve". The problem is that I get an error in the module (?!) . here is the code of the function that makes the problem: [Start of code] #The adress book function def Address(): print print "1.Open a book" print "2.View a book" print "3.Add name" print "4.Delete name" print "5.Edit name" print "6.Back" print Achoice=raw_input(">>> ") book=shelve.open("Address book") if Achoice=="3": addname=raw_input("Name: ") phone=raw_input("Phone number(type 'none' if you wabt to add Phone number later): ") Addressnum=raw_input("Address(type 'none' if you wabt to add Address later): ") ICQ=raw_input("ICQ number(type 'none' if you want add ICQ later): ") book[addname]=(addname,phone,Addressnum,ICQ) Address() elif Achoice=="2": namecheck=raw_input("Enter the name you want to view: ") book[namecheck] Address() [End of code] And the error I get is: Traceback (most recent call last): [Start of code] Enter the name you want to view: MarkK File "C:\ab.py", line 57, in ? startmenu() File "C:\ab.py", line 45, in startmenu Address() File "C:\ab.py", line 28, in Address Address() File "C:\ab.py", line 28, in Address Address() File "C:\ab.py", line 32, in Address Address() File "C:\ab.py", line 28, in Address Address() File "C:\ab.py", line 31, in Address book[namecheck] File "C:\DOCUME~1\AMP-TECH\DESKTOP\MARK\program\lib\shelve.py", line 118, in _ _getitem__ f = StringIO(self.dict[key]) File "C:\DOCUME~1\AMP-TECH\DESKTOP\MARK\program\lib\bsddb\__init__.py", line 1 16, in __getitem__ return self.db[key] KeyError: 'MarkK' [End of code] Thanks!! From s.venter at ntlworld.com Sun Sep 5 18:08:27 2004 From: s.venter at ntlworld.com (Gerhard Venter) Date: Sun Sep 5 18:08:29 2004 Subject: [Tutor] CGI-version not working while similar command-line script is fine In-Reply-To: <6.1.0.6.0.20040905091038.02a47b48@mail4.skillsoft.com> References: <4138936C.8060308@ntlworld.com> <6.1.0.6.0.20040903121324.029ffa58@mail4.skillsoft.com> <413A6F63.7040104@africonnect.com> <6.1.0.6.0.20040905091038.02a47b48@mail4.skillsoft.com> Message-ID: <413B39FB.3060300@ntlworld.com> Hi Kent Thanks - my code is below. It should output a plain text version of any website G Kent Johnson wrote: > This should work. My guess is you have an error in your script, maybe > a problem with quoting or string substitution. Can you show us the > script that is having trouble? > import cgi, os import cgitb; cgitb.enable() form = cgi.FieldStorage() website = form["websitename"].value command = 'lynx --dump ' + website k=os.popen(command, 'r') print 'Content-type: text/plain' print #print command (this shows the right thing- for example lynx --dump www.google.com) for line in k.readlines(): print(line) From kent_johnson at skillsoft.com Sun Sep 5 18:26:49 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sun Sep 5 18:27:02 2004 Subject: [Tutor] CGI-version not working while similar command-line script is fine In-Reply-To: <413B39FB.3060300@ntlworld.com> References: <4138936C.8060308@ntlworld.com> <6.1.0.6.0.20040903121324.029ffa58@mail4.skillsoft.com> <413A6F63.7040104@africonnect.com> <6.1.0.6.0.20040905091038.02a47b48@mail4.skillsoft.com> <413B39FB.3060300@ntlworld.com> Message-ID: <6.1.0.6.0.20040905122314.02a5e728@mail4.skillsoft.com> I just tried this with Lynx Version 2.8.4rel.1-mirabilos: > lynx --dump www.google.com I didn't get any output. If I try > lynx --dump http://www.google.com then it works. Could it be that simple? Also this works for me: >>> import os >>> print os.popen(r'C:\Downloads\Apps\LYNX\LYNX.EXE -dump http://www.google.com').read() Kent At 05:08 PM 9/5/2004 +0100, Gerhard Venter wrote: >Hi Kent > >Thanks - my code is below. It should output a plain text version of any >website > >G > >Kent Johnson wrote: > >>This should work. My guess is you have an error in your script, maybe a >>problem with quoting or string substitution. Can you show us the script >>that is having trouble? >import cgi, os >import cgitb; cgitb.enable() > >form = cgi.FieldStorage() >website = form["websitename"].value >command = 'lynx --dump ' + website >k=os.popen(command, 'r') > >print 'Content-type: text/plain' >print > >#print command (this shows the right thing- for example lynx --dump >www.google.com) >for line in k.readlines(): > print(line) >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From kent_johnson at skillsoft.com Sun Sep 5 18:50:25 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sun Sep 5 18:50:32 2004 Subject: [Tutor] A problem with the shelve module In-Reply-To: <d12026530409050856a974a3@mail.gmail.com> References: <d12026530409050856a974a3@mail.gmail.com> Message-ID: <6.1.0.6.0.20040905123933.02a5af38@mail4.skillsoft.com> Mark, This is kind of a subtle problem with variable scoping and the way you are calling Address() recursively. I'm not sure I can explain it very well but I will try. Every time you call a function, it gets a new set of local variables. This is true even if you are calling the same function recursively. So every time you call Address(), you make a new book object. The book that you are using to lookup MarkK is not the same book that you added MarkK to because it is in a different invocation of Address()! So the lookup fails with a KeyError. I can see two ways to fix the problem. The simplest way is just to move the book creation outside the Address function. This makes book a global variable, so every call to Address uses the same book. This would look like this: book = shelve.open("Address book") def Address(): ... Another way to fix it would be to change Address from a recursive function to a looping function. This would look like this: def Address(): book = shelve.open("Address book") choice = -1 # dummy init for choice while choice != 6: # get the user input if choice == '1': # handle choice 1 #etc Kent PS A question for the other tutors - does this recursive style of user input make you nervous? I don't much like it but I don't know if it is just because it is unfamiliar...my gut feeling is you could get in trouble with it. I guess the OP is one example of how! At 05:56 PM 9/5/2004 +0200, Mark Kels wrote: >Hi all, >Its my again (the guy with the bad english... :-/ ). > >I started to build a personal organizer useing the module "shelve". >The problem is that I get an error in the module (?!) . >here is the code of the function that makes the problem: > >[Start of code] >#The adress book function >def Address(): > print > print "1.Open a book" > print "2.View a book" > print "3.Add name" > print "4.Delete name" > print "5.Edit name" > print "6.Back" > print > Achoice=raw_input(">>> ") > book=shelve.open("Address book") > if Achoice=="3": > addname=raw_input("Name: ") > phone=raw_input("Phone number(type 'none' if you wabt to add >Phone number later): ") > Addressnum=raw_input("Address(type 'none' if you wabt to add >Address later): ") > ICQ=raw_input("ICQ number(type 'none' if you want add ICQ later): ") > book[addname]=(addname,phone,Addressnum,ICQ) > Address() > elif Achoice=="2": > namecheck=raw_input("Enter the name you want to view: ") > book[namecheck] > Address() >[End of code] > >And the error I get is: >Traceback (most recent call last): >[Start of code] >Enter the name you want to view: MarkK > File "C:\ab.py", line 57, in ? > startmenu() > File "C:\ab.py", line 45, in startmenu > Address() > File "C:\ab.py", line 28, in Address > Address() > File "C:\ab.py", line 28, in Address > Address() > File "C:\ab.py", line 32, in Address > Address() > File "C:\ab.py", line 28, in Address > Address() > File "C:\ab.py", line 31, in Address > book[namecheck] > File "C:\DOCUME~1\AMP-TECH\DESKTOP\MARK\program\lib\shelve.py", line > 118, in _ >_getitem__ > f = StringIO(self.dict[key]) > File "C:\DOCUME~1\AMP-TECH\DESKTOP\MARK\program\lib\bsddb\__init__.py", > line 1 >16, in __getitem__ > return self.db[key] >KeyError: 'MarkK' >[End of code] > >Thanks!! >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From isrgish at fastem.com Sun Sep 5 20:30:25 2004 From: isrgish at fastem.com (Isr Gish) Date: Sun Sep 5 20:30:34 2004 Subject: [Tutor] A few Questions Message-ID: <20040905183032.9192A1E4003@bag.python.org> Adam Cripps Wrote: > Dear Tutors and Friends, > Here are a few questions to test your knowledge :) > 1.What command makes the python programme print out the file it is in? > I mean for example if it is saved in c:\windows\system what command >gives me this > >This would be stored in the variable sys.argv[0] There are another few options: print '__file__: ', __file__ import inspect print 'inspect.getsourcefile(...): ', inspect.getsourcefile(lambda:None) print 'inspect.getfile(...): ', inspect.getfile(lambda:None) All the best, Isr >HTH >Adam >-- >proj: http://jiletters.sf.net >site: http://www.monkeez.org >wiki: http://wiki.monkeez.org >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From csmwxl at bath.ac.uk Sun Sep 5 23:06:39 2004 From: csmwxl at bath.ac.uk (W X Liu) Date: Sun Sep 5 23:06:42 2004 Subject: [Tutor] A Telnet problem In-Reply-To: <20040815112835.43828.qmail@web61004.mail.yahoo.com> References: <20040815112835.43828.qmail@web61004.mail.yahoo.com> Message-ID: <1094418399.413b7fdf3d0ac@webmail.bath.ac.uk> Hi friends: I am writing a program to connect a MUD(Telnet) server, here is the program: import telnetlib a=telnetlib.Telnet(host='mudlib.anarres.org',port='5000') a.read_until('login:') b=str('abb'+chr(10)) a.write(b+ "\n") b=str('528950'+chr(10)) a.read_until('password:') a.write(b+ "\n") print a.read_until('abb@anarres') But it doesn't work, who can help me to fix it? Thanks a lot. Regards Wenxin Liu From zmerch at 30below.com Sun Sep 5 23:25:39 2004 From: zmerch at 30below.com (Roger Merchberger) Date: Sun Sep 5 23:26:53 2004 Subject: [Tutor] A Telnet problem In-Reply-To: <1094418399.413b7fdf3d0ac@webmail.bath.ac.uk> References: <20040815112835.43828.qmail@web61004.mail.yahoo.com> <20040815112835.43828.qmail@web61004.mail.yahoo.com> Message-ID: <5.1.0.14.2.20040905171940.04c5a848@mail.30below.com> Rumor has it that W X Liu may have mentioned these words: >Hi friends: > >I am writing a program to connect a MUD(Telnet) server, here is the program: > >import telnetlib >a=telnetlib.Telnet(host='mudlib.anarres.org',port='5000') >a.read_until('login:') ^ Are you sure they're lowercase? Case sensitivity will create havoc here... ;-) It's better to do this: >a.read_until('ogin:') A trick from the old BBS dayz... ;-) >b=str('abb'+chr(10)) Why are you adding this? >a.write(b+ "\n") And this... Are you *sure* that the server's hosted on a Winders PC & *requires* a Winders line-ending? Most telnet servers don't... >b=str('528950'+chr(10)) >a.read_until('password:') >a.write(b+ "\n") You know cleartext passwords are a security no-no, right? ;-) >But it doesn't work, who can help me to fix it? Thanks a lot. When I was working with telnetlib, I was connecting to a USRobotics modem server, but telnets being telnets, this is what I had to do to to get the computer to recognize the text: >b=str('528950') >a.read_until('assword:') >a.write(b+ "\r") ^^ Note the \r -> This is what worked for me for a line-ending when working with telnetlib, but I have never connected to anything else other than that USR box. HTH, Roger "Merch" Merchberger -- Roger "Merch" Merchberger --- sysadmin, Iceberg Computers Recycling is good, right??? Randomization is better!!! If at first you don't succeed, nuclear warhead disarmament should *not* be your first career choice. From csmwxl at bath.ac.uk Sun Sep 5 23:39:34 2004 From: csmwxl at bath.ac.uk (W X Liu) Date: Sun Sep 5 23:39:35 2004 Subject: [Tutor] A Telnet problem In-Reply-To: <5.1.0.14.2.20040905171940.04c5a848@mail.30below.com> References: <20040815112835.43828.qmail@web61004.mail.yahoo.com> <20040815112835.43828.qmail@web61004.mail.yahoo.com> <5.1.0.14.2.20040905171940.04c5a848@mail.30below.com> Message-ID: <1094420374.413b87961adc3@webmail.bath.ac.uk> Quoting Roger Merchberger <zmerch@30below.com>: > Rumor has it that W X Liu may have mentioned these words: > >Hi friends: > > > >I am writing a program to connect a MUD(Telnet) server, here is the > program: > > > >import telnetlib > >a=telnetlib.Telnet(host='mudlib.anarres.org',port='5000') > >a.read_until('login:') > ^ > Are you sure they're lowercase? Case sensitivity will create havoc here... > ;-) I am sure that "login" are lowcase. > It's better to do this: > > >a.read_until('ogin:') > > A trick from the old BBS dayz... ;-) > > >b=str('abb'+chr(10)) > > Why are you adding this? I have to 'enter' them after inputing. > >a.write(b+ "\n") > > And this... Are you *sure* that the server's hosted on a Winders PC & > *requires* a Winders line-ending? Most telnet servers don't... What's Winders line ending? > >b=str('528950'+chr(10)) > >a.read_until('password:') > >a.write(b+ "\n") > > You know cleartext passwords are a security no-no, right? ;-) > > >But it doesn't work, who can help me to fix it? Thanks a lot. > > When I was working with telnetlib, I was connecting to a USRobotics modem > server, but telnets being telnets, this is what I had to do to to get the > computer to recognize the text: > > >b=str('528950') > >a.read_until('assword:') > >a.write(b+ "\r") > ^^ > Note the \r -> This is what worked for me for a line-ending when working > with telnetlib, but I have never connected to anything else other than that > USR box. > Basically, there is a webpage to introduct this MUD, you may look at it...: http://docs.anarres.org/Playing%3AQuickStart From alan.gauld at blueyonder.co.uk Mon Sep 6 00:38:43 2004 From: alan.gauld at blueyonder.co.uk (Alan Gauld) Date: Mon Sep 6 00:35:06 2004 Subject: [Tutor] Re: Tutor Digest, Vol 7, Issue 18 In-Reply-To: <20040905212656.0FA661E4009@bag.python.org> Message-ID: <575B1FB4-FF8C-11D8-9EBA-0003937D2B12@blueyonder.co.uk> > Kent > > PS A question for the other tutors - does this recursive style of user > input make you nervous? I don't much like it but I don't know if it is > just because it is unfamiliar...my gut feeling is you could get in > trouble with it. I guess the OP is one example of how! I don't like it either. A recursion limit of 100 nseems like a lot but in fact it wouldn't take a long time to use that up, every single menu selection will use one extra level. Loops are definitely the preferred way to do iteration in Python. Alan G From zmerch at 30below.com Mon Sep 6 01:11:39 2004 From: zmerch at 30below.com (Roger Merchberger) Date: Mon Sep 6 01:39:29 2004 Subject: [Tutor] A Telnet problem In-Reply-To: <1094420374.413b87961adc3@webmail.bath.ac.uk> References: <5.1.0.14.2.20040905171940.04c5a848@mail.30below.com> <20040815112835.43828.qmail@web61004.mail.yahoo.com> <20040815112835.43828.qmail@web61004.mail.yahoo.com> <5.1.0.14.2.20040905171940.04c5a848@mail.30below.com> Message-ID: <5.1.0.14.2.20040905190624.04b1efc8@mail.30below.com> Rumor has it that W X Liu may have mentioned these words: >Quoting Roger Merchberger <zmerch@30below.com>: [snip] > > And this... Are you *sure* that the server's hosted on a Winders PC & > > *requires* a Winders line-ending? Most telnet servers don't... > >What's Winders line ending? Winders is slang for Microsoft Windows. The codes it uses to signify the end of a line are '\r\n'. Linux, on the other hand, only uses '\n' to signify the end of a line. MacOS 8/9/X use '\r', if I'm not mistaken, but it's been a *long* time since I worked on that platform, and have never programmed on one. (unless it was running Linux. ;-) ) >Basically, there is a webpage to introduct this MUD, you may look at it...: > >http://docs.anarres.org/Playing%3AQuickStart I may, or I may not. ;-) Seriously, you may want to see if there are any programming guides that come with your MUD (I've never played with a MUD, and highly doubt I ever will) and see if there are any special quirks or gotchas WRT programming clients for that platform. Google would probably be a good friend, too. Ask him, he knows a heck of a lot more than me! ;-) Laterz, Roger "Merch" Merchberger -- Roger "Merch" Merchberger | JC: "Like those people in Celeronville!" sysadmin, Iceberg Computers | Me: "Don't you mean Silicon Valley???" zmerch@30below.com | JC: "Yea, that's the place!" | JC == Jeremy Christian From csmwxl at bath.ac.uk Mon Sep 6 02:27:17 2004 From: csmwxl at bath.ac.uk (W X Liu) Date: Mon Sep 6 02:27:21 2004 Subject: [Tutor] a question in the Python Tutorial Message-ID: <1094430437.413baee5493f6@webmail.bath.ac.uk> I am studying the Python Tutorial, but I met a problem, in the Python Tutorial 3.1.1 there is a piece of code: >>> # This is a comment ... 2+2 4 I copy them into the Python shell, but cannot run: >>> # This is a comment ... 2+2 SyntaxError: invalid syntax So, anyone can help to tell me what's wrong? From dyoo at hkn.eecs.berkeley.edu Mon Sep 6 02:47:24 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Sep 6 02:47:29 2004 Subject: [Tutor] A problem with the shelve module In-Reply-To: <6.1.0.6.0.20040905123933.02a5af38@mail4.skillsoft.com> Message-ID: <Pine.LNX.4.44.0409051710420.28353-100000@hkn.eecs.berkeley.edu> On Sun, 5 Sep 2004, Kent Johnson wrote: > Every time you call a function, it gets a new set of local variables. > This is true even if you are calling the same function recursively. So > every time you call Address(), you make a new book object. The book that > you are using to lookup MarkK is not the same book that you added MarkK > to because it is in a different invocation of Address()! So the lookup > fails with a KeyError. Hi Kent, Yes, the scope of the book creation is in the wrong place: it needs to be outside of the loop, not within. The 'book' is scheduled to be flushed to disk when the Address() function exits. But by using recursion to reenter Address(), we don't give Python the chance to close the shelved dictionary. The wrong way to fix this, by the way, is to call close right before every recursive call: ICQ=raw_input("ICQ number(type 'none' if you want add ICQ later): ") book[addname]=(addname,phone,Addressnum,ICQ) book.close() Address() elif Achoice=="2": namecheck=raw_input("Enter the name you want to view: ") book[namecheck] book.close() Address() Although this will attack the symptom, this approach is probably a bad fix. The repetitive nature of the fix is hint enough that we may want to really go after the root cause: 'book' should be defined outside of the recursion. Mark, if you're uncomfortable about using globals, and if you still want to preserve the recursive structure of your code, you can use an inner function definition. Something like this: ### def Address(): book=shelve.open("Address book") def loop(): print_choices() Achoice = raw_input() if Achoice == '3': ... if Achoice == '2': ... ... loop() ### should also work. 'book' is visible within the loop() because of "lexical scoping". Mark's coding style feels a bit like Scheme, so he may understand this better than loops. But this structure can be easily transformed into a while loop: ### def Address(): book=shelve.open("Address book") while True: print_choices() Achoice = raw_input() if Achoice == '3': ... if Achoice == '2': ... ... ### and since we're programming in Python, I'd strongly recommending using an explicit loop here. > PS A question for the other tutors - does this recursive style of user > input make you nervous? I'm actually used to seeing this style: it is the style used by functional programmers to do loop iteration. In the Scheme or OCaml languages, it works perfectly well --- if we were tutoring those languages, I wouldn't have problems with it. Unfortunately, it doesn't work so well in Python because Python doesn't do tail call elimination. So I think we should encourage newcomers here to use loops in this particular kind of straightforward, "iterative" recursion. The majority of Python programmers are comfortable with loops: I think we should help new programmers write programs in a way that are easy for the Python community to read. > I don't much like it but I don't know if it is just because it is > unfamiliar...my gut feeling is you could get in trouble with it. One Python-specific problem has to do with Python's debugging facilities, in particular, the stack trace. The stack trace gets can get really huge if we use recursion to implement iteration, and this can make debugging recursive programs messy: > > File "C:\ab.py", line 57, in ? > > startmenu() > > File "C:\ab.py", line 45, in startmenu > > Address() > > File "C:\ab.py", line 28, in Address > > Address() > > File "C:\ab.py", line 28, in Address > > Address() > > File "C:\ab.py", line 32, in Address > > Address() > > File "C:\ab.py", line 28, in Address > > Address() > > File "C:\ab.py", line 31, in Address > > book[namecheck] Since we're in Python-tutor, I think we should encourage folks to use loops, if they can be obviously used: it'll make our own lives easier in reading tracebacks. *grin* From pythonTutor at venix.com Mon Sep 6 02:54:00 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Mon Sep 6 02:54:32 2004 Subject: [Tutor] a question in the Python Tutorial In-Reply-To: <1094430437.413baee5493f6@webmail.bath.ac.uk> References: <1094430437.413baee5493f6@webmail.bath.ac.uk> Message-ID: <1094432040.15998.32.camel@laptop.venix.com> I think you probably copied in a space before 2+2 Python syntax depends on the spaces at the beginning of each line to control blocks of code, much like braces {} in C, Java, Perl, and many other languages. So leading spaces mean that the line should be within an outer-block of code. If the outer-block does not exist, then there is a syntax error. >>> 2+2 4 >>> 2+2 File "<stdin>", line 1 2+2 ^ SyntaxError: invalid syntax On Sun, 2004-09-05 at 20:27, W X Liu wrote: > I am studying the Python Tutorial, but I met a problem, in the Python Tutorial > 3.1.1 > > there is a piece of code: > > >>> # This is a comment > ... 2+2 > 4 > > I copy them into the Python shell, but cannot run: > > >>> # This is a comment > ... 2+2 > SyntaxError: invalid syntax > > So, anyone can help to tell me what's wrong? > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 320-210-3409 (changed Aug 26, 2004) From dyoo at hkn.eecs.berkeley.edu Mon Sep 6 02:56:08 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Sep 6 02:56:18 2004 Subject: [Tutor] a question in the Python Tutorial In-Reply-To: <1094430437.413baee5493f6@webmail.bath.ac.uk> Message-ID: <Pine.LNX.4.44.0409051750000.28353-100000@hkn.eecs.berkeley.edu> > there is a piece of code: > > >>> # This is a comment > ... 2+2 > 4 > > I copy them into the Python shell, but cannot run: > > >>> # This is a comment > ... 2+2 > SyntaxError: invalid syntax Hello! This is strange. I can't duplicate this problem. What are the lines right before and after the "SyntaxError: invalid syntax" error message? It should point at the character where it gets mixed up. For example, if I type: ### >>> !blah! ### then Python responds with this: ### File "<stdin>", line 1 !blah! ^ SyntaxError: invalid syntax ### Here, Python points at the misplaced exclamation mark with a '^' caret symbol. Here's another example of an error message: ### >>> # This is a comment ... 2 + 2 File "<stdin>", line 2 2 + 2 ^ SyntaxError: invalid syntax ### This is an error because I put a single space right before the '2 + 2'. So Python's not perfect when it points out where problems start, but it tries. *grin* Can you try your example again? See if you can get Python to point out where it starts getting confused. Good luck to you! From dyoo at hkn.eecs.berkeley.edu Mon Sep 6 09:06:57 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Sep 6 09:07:02 2004 Subject: [Tutor] help-Please help me to read Text From JPEG file (fwd) Message-ID: <Pine.LNX.4.44.0409060002040.24322-100000@hkn.eecs.berkeley.edu> [Forwarding to tutor@python.org. When you reply, please make sure you're using "reply-to-all" in your email client. By doing so, you make sure that one of the volunteers on Tutor can help you.] ---------- Forwarded message ---------- Date: Fri, 03 Sep 2004 17:18:35 +0530 From: "General Electronics,Phaltan" <str_kbs@sancharnet.in> To: Danny Yoo <dyoo@hkn.eecs.berkeley.edu> Subject: Re: [Tutor] help-Please help me to read Text From JPEG file Hi Danny , I have near about 4000 JPEG images. The text in image is input data for some database activity program. The same number of images with different text will be collected for each month. So mannual OCR is not possible for me. So I need to read text. These image contains meter like counters e.g. in Electricity meter or Counter on Petrol Pump display. One option I am trying is comparing know digit image with each part of JPEG image. If match found put data in ASCII text format in my list. But it is very lazy process. Thanks Arvind Sidhaye ----- Original Message ----- From: "Danny Yoo" <dyoo@hkn.eecs.berkeley.edu> To: "General Electronics,Phaltan" <str_kbs@sancharnet.in> Cc: <tutor@python.org> Sent: Thursday, September 02, 2004 11:14 AM Subject: Re: [Tutor] help-Please help me to read Text From JPEG file > > > On Wed, 1 Sep 2004, General Electronics,Phaltan wrote: > > > Please help me to write python code to read Text from JPEG file and > > store to standard TEXT file. > > Hi Arvind, > > The question you're asking is slightly odd. JPEGs are binary: for the > most part, they're not supposed to have text (except possibly some > metadata). > > What are you trying to do? It might help if you could tell us why you're > trying to do this. Are you trying to rewrite the standard 'strings' Unix > shell command? > > Good luck to you. > From tpc at csua.berkeley.edu Mon Sep 6 09:42:56 2004 From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Mon Sep 6 09:43:26 2004 Subject: [Tutor] drawing a graph In-Reply-To: <Pine.LNX.4.44.0409022334530.14461-100000@hkn.eecs.berkeley.edu> Message-ID: <20040906003651.Y71240-100000@localhost.name> hi Danny, I tried using rpy to test graphing with Python, but I believe the documentation may be outdated and incomplete. I installed the win32 extensions and rpy-0.3.5.win32-py2.3.exe, and fired up IDLE to test generating a simple line and point graph using the examples from the page: http://www.togaware.com/linux/survivor/Graphs.shtml Right off the bat, the documentation fails to explain you must 'import rpy' before you can 'from rpy import *', else you get: error: (2, 'RegOpenKeyEx', 'The system cannot find the file specified.') So then I created the list, and when I try to execute the next line I get: >>> r.postscript("rplot01.eps") ... NameError: name 'r' is not defined The site: http://rpy.sourceforge.net/ says to make sure the R bin directory 'C:\Program Files\R\rw1061\bin\' is in your path, but that directory or another permutation doesn't seem to exist on my machine. I am looking for a simple line graph program and I tried Rpy at your recommendation but I can't seem to get beyond the error message above. On Thu, 2 Sep 2004, Danny Yoo wrote: > Hi Vuzzi, > > Can you give us a small example of what you'd like a graph to look like, > for, say three small sequences? That may help us to point you toward the > right graph-generating tools. > > > There are graph tools from the 'graphviz' project: > > http://www.research.att.com/sw/tools/graphviz/ > > but I'm not sure if you mean this kind of graph. *grin* "Graph" is > another one of those overloaded words. > > > You might mean bar charts or line graphs instead. Perhaps you might be > able to use HTMLGen to generate nice HTML bar charts: > > http://www.linuxjournal.com/article.php?sid=2986 > > But it sounds like you might want something more. There's a Python > extension module the R statistics system, and since R has robust graphing, > you can take advantage of it: > > http://rpy.sourceforge.net/ > http://www.togaware.com/linux/survivor/Graphs.shtml > > Does this help? > > > Good luck to you! > From dyoo at hkn.eecs.berkeley.edu Mon Sep 6 10:09:07 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Sep 6 10:09:22 2004 Subject: [Tutor] drawing a graph In-Reply-To: <20040906003651.Y71240-100000@localhost.name> Message-ID: <Pine.LNX.4.44.0409060057490.24551-100000@hkn.eecs.berkeley.edu> On Mon, 6 Sep 2004 tpc@csua.berkeley.edu wrote: > The site: > > http://rpy.sourceforge.net/ > > says to make sure the R bin directory 'C:\Program Files\R\rw1061\bin\' > is in your path, but that directory or another permutation doesn't seem > to exist on my machine. > > I am looking for a simple line graph program and I tried Rpy at your > recommendation but I can't seem to get beyond the error message above. Hi Tpc, 'rpy' has a few prerequisites. You need to first install R, because 'rpy' is a translator between R and Python. http://www.r-project.org/ It is Free Software, so you should be able to grab it from several mirrors. > Right off the bat, the documentation fails to explain you must 'import > rpy' before you can 'from rpy import *', else you get: > > error: (2, 'RegOpenKeyEx', 'The system cannot find the file specified.') This may be an issue with not having R installed: it sounds like the system is trying to do its best to find R, but without success. If you're having more problems with 'rpy', it might be best to bring them up on 'rpy-list': http://rpy.sourceforge.net/maillist.html Good luck! From s.venter at ntlworld.com Mon Sep 6 10:19:51 2004 From: s.venter at ntlworld.com (Gerhard Venter) Date: Mon Sep 6 10:19:57 2004 Subject: [Tutor] CGI-version not working while similar command-line script is fine In-Reply-To: <6.1.0.6.0.20040905122314.02a5e728@mail4.skillsoft.com> References: <4138936C.8060308@ntlworld.com> <6.1.0.6.0.20040903121324.029ffa58@mail4.skillsoft.com> <413A6F63.7040104@africonnect.com> <6.1.0.6.0.20040905091038.02a47b48@mail4.skillsoft.com> <413B39FB.3060300@ntlworld.com> <6.1.0.6.0.20040905122314.02a5e728@mail4.skillsoft.com> Message-ID: <413C1DA7.5080306@ntlworld.com> Hi Kent No, although I did not have the "http://" in my email, I did enter it in my web form. So it isn't that. (And my version of Lynx doesn't require it) But the interesting thing is that the line below which you suggested works in a Python command prompt, but not in Idle or Pythonwin. Perhaps CGI has the same limitation as these tools. print os.popen(r'c:\bin\lynx.exe -dump http://www.google.com').read() Likewise (I've resorted to using a temp file, but even that isn't working), the line below works in a Python command prompt but not in CGI. os.system(r'start /B c:\bin\lynx.exe -dump http://www.google.com > "F:\logs\temp.txt"') Gerhard Kent Johnson wrote: > I just tried this with Lynx Version 2.8.4rel.1-mirabilos: > > lynx --dump www.google.com > > I didn't get any output. If I try > > lynx --dump http://www.google.com > then it works. Could it be that simple? > > Also this works for me: > >>> import os > >>> print os.popen(r'C:\Downloads\Apps\LYNX\LYNX.EXE -dump > http://www.google.com').read() > > Kent > > At 05:08 PM 9/5/2004 +0100, Gerhard Venter wrote: > >> Hi Kent >> >> Thanks - my code is below. It should output a plain text version of >> any website >> >> G >> >> Kent Johnson wrote: >> >>> This should work. My guess is you have an error in your script, >>> maybe a problem with quoting or string substitution. Can you show us >>> the script that is having trouble? >> >> import cgi, os >> import cgitb; cgitb.enable() >> >> form = cgi.FieldStorage() >> website = form["websitename"].value >> command = 'lynx --dump ' + website >> k=os.popen(command, 'r') >> >> print 'Content-type: text/plain' >> print >> >> #print command (this shows the right thing- for example lynx --dump >> www.google.com) >> for line in k.readlines(): >> print(line) >> _______________________________________________ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor > > > From karthik at james.hut.fi Mon Sep 6 12:06:30 2004 From: karthik at james.hut.fi (Karthikesh Raju) Date: Mon Sep 6 12:06:31 2004 Subject: [Tutor] Question on converting a list per say Message-ID: <Pine.SGI.4.58.0409061301060.3150222@james.hut.fi> Hi All, Is it possible to directly convert a list to int/float or complex etc say a = ['1','2','3'] can i do an int(a) to get [1,2,3] or a float(a). Presenly i do: b = [] for vals in a b.append(int(a)) now my a's are quite big like something with 100000 elements? Isint it not a slow process to do it like i do? Warm regards karthik PS: Thankx for the regex question - it works with minor modifications ----------------------------------------------------------------------- Karthikesh Raju, email: karthik@james.hut.fi karthikesh.raju@gmail.com Researcher, http://www.cis.hut.fi/karthik Helsinki University of Technology, Tel: +358-9-451 5389 Laboratory of Comp. & Info. Sc., Fax: +358-9-451 3277 Department of Computer Sc., P.O Box 5400, FIN 02015 HUT, Espoo, FINLAND ----------------------------------------------------------------------- From H.FANGOHR at soton.ac.uk Mon Sep 6 12:31:42 2004 From: H.FANGOHR at soton.ac.uk (Hans Fangohr) Date: Mon Sep 6 12:35:12 2004 Subject: [Tutor] Question on converting a list per say In-Reply-To: <Pine.SGI.4.58.0409061301060.3150222@james.hut.fi> References: <Pine.SGI.4.58.0409061301060.3150222@james.hut.fi> Message-ID: <Pine.LNX.4.60.0409061130200.8234@binx.sesnet.soton.ac.uk> Hi Karthik, > Is it possible to directly convert a list to int/float or complex etc > > say a = ['1','2','3'] > > can i do an int(a) to get [1,2,3] or a float(a). > > Presenly i do: > b = [] > for vals in a > b.append(int(a)) Try b = map( int, a ) I don't know whether this is the fastest way to do it but at least the notation is concise ;-) Cheers, Hans > > > now my a's are quite big like something with 100000 elements? Isint it not > a slow process to do it like i do? > > Warm regards > > karthik > > PS: Thankx for the regex question - it works with minor modifications > > ----------------------------------------------------------------------- > Karthikesh Raju, email: karthik@james.hut.fi > karthikesh.raju@gmail.com > Researcher, http://www.cis.hut.fi/karthik > Helsinki University of Technology, Tel: +358-9-451 5389 > Laboratory of Comp. & Info. Sc., Fax: +358-9-451 3277 > Department of Computer Sc., > P.O Box 5400, FIN 02015 HUT, > Espoo, FINLAND > ----------------------------------------------------------------------- > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ------------------------------------------------- Dr Hans Fangohr Computational Engineering & Design Research Group School of Engineering Sciences University of Southampton Southampton, SO17 1BJ United Kingdom Location: Building 25, Room 1033 phone : +44 (0) 23 8059 8345 fax : +44 (0) 23 8059 7082 email : fangohr@soton.ac.uk ------------------------------------------------- From project5 at redrival.net Mon Sep 6 13:36:22 2004 From: project5 at redrival.net (Andrei) Date: Mon Sep 6 13:36:33 2004 Subject: [Tutor] Re: Question on converting a list per say References: <Pine.SGI.4.58.0409061301060.3150222@james.hut.fi> Message-ID: <loom.20040906T133345-411@post.gmane.org> Karthikesh Raju <karthik <at> james.hut.fi> writes: > can i do an int(a) to get [1,2,3] or a float(a). > > Presenly i do: > b = [] > for vals in a > b.append(int(a)) > > now my a's are quite big like something with 100000 elements? Isint it not > a slow process to do it like i do? It probably is, but is it slow enough for you notice it? You could try a list comprehension: b = [int(val) for val in a] I don't know how this compares speed-wise with the map() solution already offered, but I like list comprehensions better than map() anyway :). You could do a benchmark if this part of your application is critical. Yours, Andrei From johan at accesstel.co.za Mon Sep 6 14:19:15 2004 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Mon Sep 6 14:20:39 2004 Subject: [Tutor] Network programming Message-ID: <1094473155.4233.23.camel@linux.site> Hi, I am new to Python and would like to know more about network programming in particilar. I have a script that sets up a socket server and must wait for incoming connections. Once a call has been accepted, it must make another socket connection to a destination. Now, I want to let these two "talk" to each other. Once the server receives data it must be send out to the destination and when the destination has data, it must be send out to the connection that made the first call to the server. Does anybody have any examples or tips on how I can let this happen. My calls work for the first batch of data and then when new data is received, the calls break. Thanks -- Johan Geldenhuys Access Telecommunication Systems Mail to: johan@accesstel.co.za -- This message has been scanned for viruses and dangerous content by Azitech, and is believed to be clean. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040906/96b806fc/attachment.html From tpc at csua.berkeley.edu Mon Sep 6 14:33:51 2004 From: tpc at csua.berkeley.edu (tpc@csua.berkeley.edu) Date: Mon Sep 6 14:33:57 2004 Subject: [Tutor] drawing a graph In-Reply-To: <Pine.LNX.4.44.0409060057490.24551-100000@hkn.eecs.berkeley.edu> Message-ID: <20040906052307.E71240-100000@localhost.name> hi Danny, just an update, it seems that Rpy-0.3.5 is compiled only for R version 1.8.1 (in other words, you need the binary executable rw1081.exe) from the looks of this page: http://tolstoy.newcastle.edu.au/R/help/04/07/1872.html and frustratingly, if you go to CRAN: http://cran.r-project.org/mirrors.html the only binary executables available for download are rw1091.exe and rw1090.exe. After installing R version 1.9.1, putting 'C:\Program Files\R\rw1091\bin' in my path, and 'import rpy' I got the following error: >>> import rpy >>> degrees = 4 >>> grid = r.seq(0, 10, length=100) ... NameError: name 'r' is not defined On Mon, 6 Sep 2004, Danny Yoo wrote: > > Hi Tpc, > > 'rpy' has a few prerequisites. You need to first install R, because 'rpy' > is a translator between R and Python. > > http://www.r-project.org/ > > It is Free Software, so you should be able to grab it from several > mirrors. > > If you're having more problems with 'rpy', it might be best to bring them > up on 'rpy-list': > > http://rpy.sourceforge.net/maillist.html > > > Good luck! > > From kent_johnson at skillsoft.com Mon Sep 6 14:40:30 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Mon Sep 6 14:40:40 2004 Subject: [Tutor] Question on converting a list per say In-Reply-To: <Pine.LNX.4.60.0409061130200.8234@binx.sesnet.soton.ac.uk> References: <Pine.SGI.4.58.0409061301060.3150222@james.hut.fi> <Pine.LNX.4.60.0409061130200.8234@binx.sesnet.soton.ac.uk> Message-ID: <6.1.0.6.0.20040906083826.02a3db58@mail4.skillsoft.com> Map works in the blink of an eye for me... >>> a=range(100000) >>> a=map(str, a) >>> a[:10] ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] >>> a=map(int, a) >>> a[:10] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Kent At 11:31 AM 9/6/2004 +0100, Hans Fangohr wrote: >Hi Karthik, > >>Is it possible to directly convert a list to int/float or complex etc >> >>say a = ['1','2','3'] >> >>can i do an int(a) to get [1,2,3] or a float(a). >> >>Presenly i do: >>b = [] >>for vals in a >> b.append(int(a)) > >Try > >b = map( int, a ) > >I don't know whether this is the fastest way to do it but at least the >notation is concise ;-) > >Cheers, > >Hans > > >> >> >>now my a's are quite big like something with 100000 elements? Isint it not >>a slow process to do it like i do? >> >>Warm regards >> >>karthik >> >>PS: Thankx for the regex question - it works with minor modifications >> >>----------------------------------------------------------------------- >>Karthikesh Raju, email: karthik@james.hut.fi >> karthikesh.raju@gmail.com >>Researcher, http://www.cis.hut.fi/karthik >>Helsinki University of Technology, Tel: +358-9-451 5389 >>Laboratory of Comp. & Info. Sc., Fax: +358-9-451 3277 >>Department of Computer Sc., >>P.O Box 5400, FIN 02015 HUT, >>Espoo, FINLAND >>----------------------------------------------------------------------- >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor > >------------------------------------------------- >Dr Hans Fangohr > >Computational Engineering & Design Research Group >School of Engineering Sciences >University of Southampton >Southampton, SO17 1BJ >United Kingdom > >Location: Building 25, Room 1033 >phone : +44 (0) 23 8059 8345 >fax : +44 (0) 23 8059 7082 >email : fangohr@soton.ac.uk >------------------------------------------------- > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From kent_johnson at skillsoft.com Mon Sep 6 14:59:52 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Mon Sep 6 15:00:11 2004 Subject: [Tutor] CGI-version not working while similar command-line script is fine In-Reply-To: <413C1DA7.5080306@ntlworld.com> References: <4138936C.8060308@ntlworld.com> <6.1.0.6.0.20040903121324.029ffa58@mail4.skillsoft.com> <413A6F63.7040104@africonnect.com> <6.1.0.6.0.20040905091038.02a47b48@mail4.skillsoft.com> <413B39FB.3060300@ntlworld.com> <6.1.0.6.0.20040905122314.02a5e728@mail4.skillsoft.com> <413C1DA7.5080306@ntlworld.com> Message-ID: <6.1.0.6.0.20040906085722.02a1e030@mail4.skillsoft.com> Ah. I tried it in IDLE and had the same problem. Using popen4() to look at stderr, I found that lynx is not finding the .cfg file. Adding that to the command line made it work: >>> i,o=os.popen4(r'C:\Downloads\Apps\LYNX\LYNX.EXE -dump http://www.google.com') >>> o.read() '\nConfiguration file ./lynx.cfg is not available.\n\n' >>> os.popen(r'C:\Downloads\Apps\LYNX\LYNX.EXE -cfg=C:\Downloads\Apps\LYNX\LYNX.CFG -dump http://www.google.com').read() " Google\n\n Web [1]Images [2]Groups [3]News [4]Froogle [5]more \xaf\n\n [6]_______________________________________________________\n [7]Google Search [8]I'm Feeling Lucky [9]Advanced Search\n [10]Preferences\n [11]Language Tools\n\n [12]Advertising Programs - [13]Business Solutions - [14]About Google\n\n \xa92004 Google - Searching 4,285,199,774 web pages\n\nReferences\n\n 1. http://www.google.com/imghp?hl=en&tab=wi&ie=UTF-8\n 2. http://www.google.com/grphp?hl=en&tab=wg&ie=UTF-8\n 3. http://www.google.com/nwshp?hl=en&tab=wn&ie=UTF-8\n 4. http://www.google.com/froogle?hl=en&tab=wf&ie=UTF-8\n 5. http://www.google.com/options/index.html\n 6. form field = text entry field\n 7. form field = submit button\n 8. form field = submit button\n 9. http://www.google.com/advanced_search?hl=en\n 10. http://www.google.com/preferences?hl=en\n 11. http://www.google.com/language_tools?hl=en\n 12. http://www.google.com/ads/\n 13. http://www.google.com/services/\n 14. http://www.google.com/about.html\n" >>> So try adding the -cfg switch to specify your lynx.cfg. If that doesn't work use popen3 or popen4 to capture stderr and see what is there. Kent At 09:19 AM 9/6/2004 +0100, Gerhard Venter wrote: >Hi Kent > >No, although I did not have the "http://" in my email, I did enter it in >my web form. So it isn't that. (And my version of Lynx doesn't >require it) > >But the interesting thing is that the line below which you suggested >works in a Python command prompt, but not in Idle or Pythonwin. >Perhaps CGI has the same limitation as these tools. >print os.popen(r'c:\bin\lynx.exe -dump http://www.google.com').read() > >Likewise (I've resorted to using a temp file, but even that isn't >working), the line below works in a Python command prompt but not in CGI. >os.system(r'start /B c:\bin\lynx.exe -dump http://www.google.com > >"F:\logs\temp.txt"') > >Gerhard > > > >Kent Johnson wrote: > >>I just tried this with Lynx Version 2.8.4rel.1-mirabilos: >> > lynx --dump www.google.com >> >>I didn't get any output. If I try >> > lynx --dump http://www.google.com >>then it works. Could it be that simple? >> >>Also this works for me: >> >>> import os >> >>> print os.popen(r'C:\Downloads\Apps\LYNX\LYNX.EXE -dump >> http://www.google.com').read() >> >>Kent >> >>At 05:08 PM 9/5/2004 +0100, Gerhard Venter wrote: >> >>>Hi Kent >>> >>>Thanks - my code is below. It should output a plain text version of any >>>website >>> >>>G >>> >>>Kent Johnson wrote: >>> >>>>This should work. My guess is you have an error in your script, maybe a >>>>problem with quoting or string substitution. Can you show us the script >>>>that is having trouble? >>> >>>import cgi, os >>>import cgitb; cgitb.enable() >>> >>>form = cgi.FieldStorage() >>>website = form["websitename"].value >>>command = 'lynx --dump ' + website >>>k=os.popen(command, 'r') >>> >>>print 'Content-type: text/plain' >>>print >>> >>>#print command (this shows the right thing- for example lynx --dump >>>www.google.com) >>>for line in k.readlines(): >>> print(line) >>>_______________________________________________ >>>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 csmwxl at bath.ac.uk Mon Sep 6 15:13:04 2004 From: csmwxl at bath.ac.uk (W X Liu) Date: Mon Sep 6 15:13:11 2004 Subject: [Tutor] need help foe telnet!! Message-ID: <1094476384.413c626035bad@webmail.bath.ac.uk> Hi everyone, I am writing a program to connect a MUD(Telnet) server, here is the program: import telnetlib a=telnetlib.Telnet(host='mudlib.anarres.org',port='5000') a.read_until('login:') b=str('abb'+chr(10)) a.write(b+ "\n") b=str('528950'+chr(10)) a.read_until('password:') a.write(b+ "\n") print a.read_until('abb@anarres') it doesn't work, who can help me to fix it? Thanks a lot. BTW, does "\n" represent "enter"? Regards Wenxin Liu From csmwxl at bath.ac.uk Mon Sep 6 15:57:14 2004 From: csmwxl at bath.ac.uk (W X Liu) Date: Mon Sep 6 15:57:17 2004 Subject: [Tutor] Get confused by ... and >>> Message-ID: <1094479034.413c6cba30dc0@webmail.bath.ac.uk> Hello guys, I am learning python now, and I get confused by ... and >>>, who can give me some clues or examples in what situation the ... or >>> should be use. Regards Wenxin Liu From s.venter at ntlworld.com Mon Sep 6 16:05:44 2004 From: s.venter at ntlworld.com (Gerhard Venter) Date: Mon Sep 6 16:05:48 2004 Subject: [Tutor] CGI-version not working while similar command-line script is fine In-Reply-To: <6.1.0.6.0.20040906085722.02a1e030@mail4.skillsoft.com> References: <4138936C.8060308@ntlworld.com> <6.1.0.6.0.20040903121324.029ffa58@mail4.skillsoft.com> <413A6F63.7040104@africonnect.com> <6.1.0.6.0.20040905091038.02a47b48@mail4.skillsoft.com> <413B39FB.3060300@ntlworld.com> <6.1.0.6.0.20040905122314.02a5e728@mail4.skillsoft.com> <413C1DA7.5080306@ntlworld.com> <6.1.0.6.0.20040906085722.02a1e030@mail4.skillsoft.com> Message-ID: <413C6EB8.2020808@ntlworld.com> Yes, that's definitely it -thanks it works now. Also, I learned from your email how to look at stderr from Python. Gerhard Kent Johnson wrote: > Ah. I tried it in IDLE and had the same problem. Using popen4() to > look at stderr, I found that lynx is not finding the .cfg file. Adding > that to the command line made it work: > >>> i,o=os.popen4(r'C:\Downloads\Apps\LYNX\LYNX.EXE -dump > http://www.google.com') > >>> o.read() > '\nConfiguration file ./lynx.cfg is not available.\n\n' > > >>> os.popen(r'C:\Downloads\Apps\LYNX\LYNX.EXE > -cfg=C:\Downloads\Apps\LYNX\LYNX.CFG -dump http://www.google.com').read() From nick at javacat.f2s.com Mon Sep 6 16:25:49 2004 From: nick at javacat.f2s.com (nick@javacat.f2s.com) Date: Mon Sep 6 16:25:52 2004 Subject: [Tutor] Dodgey if loop ? Message-ID: <1094480749.413c736da2e63@webmail.freedom2surf.net> Hi folks, I've just wrote a little port scanner, and strangely enough I only have one problem with it lol . Here's the offending code: [code] pnumber = str(pnumber) #pnumber is 25 for example for line in f: # f is '/etc/services' open file if not line.startswith('#') and len(line) > 10: p = line.split()[1].split('/')[0] if p == pnumber: return line.split()[0] # would return 'smtp' #else: #return '?' [/code] As it stands this works fine. However, if I uncomment the else loop in the final if loop it will always return the '?'. Leaving the final else commented out (as above) if pnumber is not in /etc/services it returns 'None' which I can live with. Can anyone see why this is happening please ? Here's a brief session of running the program with the final else commented out: [nickl@netview socket]$ ./scan.py bishop1 1 1024 Trying bishop1 ... bishop1 is listening on port 7 (echo) bishop1 is listening on port 9 (discard) bishop1 is listening on port 13 (daytime) bishop1 is listening on port 19 (chargen) bishop1 is listening on port 21 (ftp) bishop1 is listening on port 23 (telnet) bishop1 is listening on port 25 (smtp) ... etc Here's what happens when I uncomment the final else: [nickl@netview socket]$ ./scan.py bishop1 1 1024 Trying bishop1 ... bishop1 is listening on port 7 (?) bishop1 is listening on port 9 (?) bishop1 is listening on port 13 (?) bishop1 is listening on port 19 (?) bishop1 is listening on port 21 (?) bishop1 is listening on port 23 (?) bishop1 is listening on port 25 (?) ... etc Many thanks Nick. ------------------------------------------------- Everyone should have http://www.freedom2surf.net/ From pythonTutor at venix.com Mon Sep 6 16:49:03 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Mon Sep 6 16:49:09 2004 Subject: [Tutor] Dodgey if loop ? In-Reply-To: <1094480749.413c736da2e63@webmail.freedom2surf.net> References: <1094480749.413c736da2e63@webmail.freedom2surf.net> Message-ID: <1094482143.2092.60.camel@laptop.venix.com> Your for loop reads through the whole services file. When p == pnumber, you have found your match. The else simply means you have not found your match (yet). The else is true for EVERY line except the line(s?) that matches pnumber. I think the rough pseudo code for what you want is: for line in f: if <matches pnumber>: break else: return '?' return <services label> This has the advantage of not reading the whole file for every pnumber. You might be better off parsing the services file once into a dictionary (or other map-like container), and then using pnumber to retrieve the label for the port. On Mon, 2004-09-06 at 10:25, nick@javacat.f2s.com wrote: > Hi folks, > > I've just wrote a little port scanner, and strangely enough I only have one > problem with it lol . > > Here's the offending code: > > [code] > pnumber = str(pnumber) #pnumber is 25 for example > for line in f: # f is '/etc/services' open file > if not line.startswith('#') and len(line) > 10: > p = line.split()[1].split('/')[0] > if p == pnumber: > return line.split()[0] # would return 'smtp' > #else: > #return '?' > [/code] > > As it stands this works fine. > However, if I uncomment the else loop in the final if loop it will always return > the '?'. Leaving the final else commented out (as above) if pnumber is not in > /etc/services it returns 'None' which I can live with. > > Can anyone see why this is happening please ? > > Here's a brief session of running the program with the final else commented out: > [nickl@netview socket]$ ./scan.py bishop1 1 1024 > Trying bishop1 ... > > bishop1 is listening on port 7 (echo) > bishop1 is listening on port 9 (discard) > bishop1 is listening on port 13 (daytime) > bishop1 is listening on port 19 (chargen) > bishop1 is listening on port 21 (ftp) > bishop1 is listening on port 23 (telnet) > bishop1 is listening on port 25 (smtp) ... etc > > Here's what happens when I uncomment the final else: > [nickl@netview socket]$ ./scan.py bishop1 1 1024 > Trying bishop1 ... > > bishop1 is listening on port 7 (?) > bishop1 is listening on port 9 (?) > bishop1 is listening on port 13 (?) > bishop1 is listening on port 19 (?) > bishop1 is listening on port 21 (?) > bishop1 is listening on port 23 (?) > bishop1 is listening on port 25 (?) ... etc > > Many thanks > Nick. > > > > > > > > > > ------------------------------------------------- > Everyone should have http://www.freedom2surf.net/ > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp. 1 Court Street, Suite 378 Lebanon, NH 03766-1358 voice: 603-653-8139 fax: 320-210-3409 (changed Aug 26, 2004) From kent_johnson at skillsoft.com Mon Sep 6 16:54:14 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Mon Sep 6 16:54:24 2004 Subject: [Tutor] Dodgey if loop ? In-Reply-To: <1094480749.413c736da2e63@webmail.freedom2surf.net> References: <1094480749.413c736da2e63@webmail.freedom2surf.net> Message-ID: <6.1.0.6.0.20040906104848.02a05c80@mail4.skillsoft.com> The problem is that you are returning too soon. The first time you find p != pnumber you will return ?. For example if /etc/services contains entries for ports 7 and 25, when you see the 7 you will return ?. You need to put the return '?' after the for loop finishes, so it won't be executed until the loop has completed without finding the pnumber you are looking for. Kent At 03:25 PM 9/6/2004 +0100, nick@javacat.f2s.com wrote: >Hi folks, > >I've just wrote a little port scanner, and strangely enough I only have one >problem with it lol . > >Here's the offending code: > >[code] >pnumber = str(pnumber) #pnumber is 25 for example >for line in f: # f is '/etc/services' open file > if not line.startswith('#') and len(line) > 10: > p = line.split()[1].split('/')[0] > if p == pnumber: > return line.split()[0] # would return 'smtp' > #else: > #return '?' >[/code] > >As it stands this works fine. >However, if I uncomment the else loop in the final if loop it will always >return >the '?'. Leaving the final else commented out (as above) if pnumber is not in >/etc/services it returns 'None' which I can live with. > >Can anyone see why this is happening please ? > >Here's a brief session of running the program with the final else >commented out: >[nickl@netview socket]$ ./scan.py bishop1 1 1024 >Trying bishop1 ... > >bishop1 is listening on port 7 (echo) >bishop1 is listening on port 9 (discard) >bishop1 is listening on port 13 (daytime) >bishop1 is listening on port 19 (chargen) >bishop1 is listening on port 21 (ftp) >bishop1 is listening on port 23 (telnet) >bishop1 is listening on port 25 (smtp) ... etc > >Here's what happens when I uncomment the final else: >[nickl@netview socket]$ ./scan.py bishop1 1 1024 >Trying bishop1 ... > >bishop1 is listening on port 7 (?) >bishop1 is listening on port 9 (?) >bishop1 is listening on port 13 (?) >bishop1 is listening on port 19 (?) >bishop1 is listening on port 21 (?) >bishop1 is listening on port 23 (?) >bishop1 is listening on port 25 (?) ... etc > >Many thanks >Nick. > > > > > > > > > >------------------------------------------------- >Everyone should have http://www.freedom2surf.net/ >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From kent_johnson at skillsoft.com Mon Sep 6 17:04:54 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Mon Sep 6 17:05:18 2004 Subject: [Tutor] Get confused by ... and >>> In-Reply-To: <1094479034.413c6cba30dc0@webmail.bath.ac.uk> References: <1094479034.413c6cba30dc0@webmail.bath.ac.uk> Message-ID: <6.1.0.6.0.20040906105424.029fcab0@mail4.skillsoft.com> >>> and ... are prompts written by the python interpreter when you run it from the command line. You shouldn't type them in yourself. >>> is the prompt used when the interpreter is expecting a new statement. ... is the 'secondary' prompt used when you have typed something incomplete and the interpreter is expecting something more. Using your previous example, >>> # This is a comment ... 2+2 4 what you type is # This is a comment<enter> 2+2<enter> The interpreter types the >>>, ... and 4 Note if you are using an IDLE shell window you will see the >>> but not the ... Kent At 02:57 PM 9/6/2004 +0100, W X Liu wrote: >Hello guys, > >I am learning python now, and I get confused by ... and >>>, who can give me >some clues or examples in what situation the ... or >>> should be use. > >Regards > >Wenxin Liu > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From nick at javacat.f2s.com Mon Sep 6 18:37:51 2004 From: nick at javacat.f2s.com (Nick Lunt) Date: Mon Sep 6 18:34:38 2004 Subject: [Tutor] Dodgey if loop ? In-Reply-To: <1094482143.2092.60.camel@laptop.venix.com> Message-ID: <FBEKICNGPAKNIMBBNHGKEEIOCBAA.nick@javacat.f2s.com> >-----Original Message----- >From: Lloyd Kvam [mailto:pythonTutor@venix.com] >Sent: 06 September 2004 15:49 >You might be better off parsing the services file once into a dictionary >(or other map-like container), and then using pnumber to retrieve the >label for the port. Thankyou, I agree with the dictionary way, and have now implemented that. >From: Kent Johnson [mailto:kent_johnson@skillsoft.com] >Sent: 06 September 2004 15:54 >The problem is that you are returning too soon. The first time you find p >!= pnumber you will return ?. For example if /etc/services contains entries >for ports 7 and 25, when you see the 7 you will return ?. Ahh, it's so clear when someone takes the time to explain it to you. Thanks. Many thanks to both of you for helping me out. Nick. --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.752 / Virus Database: 503 - Release Date: 03/09/2004 From anastasia at shutupandsitdown.com Mon Sep 6 20:26:56 2004 From: anastasia at shutupandsitdown.com (Anastasia Rohner) Date: Mon Sep 6 20:26:59 2004 Subject: [Tutor] questions from stupid n00b Message-ID: <20040906182656.713863936@sitemail.everyone.net> Hi! I'm new. I'm trying to learn Python by reading the tutorial that's in the help file that's downloaded w/ the interpretor. I really like how all the stuff in the tutorial is short, sweet, and to the point. However, since Creature is not a real programmer (yet), some stuff in the tutorial got her a bit confused: 1. Tutorial section 7.4.1 talks about default value arguments. In the 2 examples: " def f(a, L=[]): L.append(a) return L print f(1) print f(2) print f(3) This will print [1] [1, 2] [1, 2, 3] If you don't want the default to be shared between subsequent calls, you can write the function like this instead: def f(a, L=None): if L is None: L = [] L.append(a) return L " What exactly does the if statement change? I mean, if L is set to the default value defined in the arguments list only during the first run of the function (the way it seems to be in the first example), then on the second run of the second example, L should no longer be None, and bypass the if statement altogether. 2. (section 9.6) So the way to make a private variable is to put two underscores in front of the name? Or to do 'underscore, classname, two underscores, variable name'? Are those two used interchangebly for defining the private variable, or is the first one for defining and the second one for calling? 3. (9.8) What is the difference between these two: raise Class, instance raise instance (or raise instance.__class__, instance) 4. (also 9.8) How does this thing work: class B: pass class C(B): pass class D(C): pass for c in [B, C, D]: try: raise c() except D: print "D" except C: print "C" except B: print "B" I kind of get that in the top part C is a child class of B and D of C, but what does it do for the example? Also, is it just a coincidence that the lower case 'c' is both the loop controll variable and the non-existant function being called in the 'try' block, or are those two connected? 5. Creature's stupid question of the month: what does 'container object' mean? That's all for now. Sorry to ask so many questions at once :) Thanks in advance ^_^ Creature From kent_johnson at skillsoft.com Tue Sep 7 01:24:24 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Tue Sep 7 01:24:33 2004 Subject: [Tutor] questions from stupid n00b In-Reply-To: <20040906182656.713863936@sitemail.everyone.net> References: <20040906182656.713863936@sitemail.everyone.net> Message-ID: <6.1.0.6.0.20040906185346.02a89d28@mail4.skillsoft.com> At 11:26 AM 9/6/2004 -0700, Anastasia Rohner wrote: >1. Tutorial section 4.7.1 talks about default value arguments. ><snip> >What exactly does the if statement change? I mean, if L is set to the >default value defined in the arguments list only during the first run of >the function (the way it seems to be in the first example), then on the >second run of the second example, L should no longer be None, and bypass >the if statement altogether. In Python, two variables can refer to the same value. (This is called aliasing.) If the value is mutable, changing it for one variable changes it for both. For example, if I say >>> a=[] >>> b=a a and b now refer to the same list, so changing a changes b also: >>> a.append(1) >>> a [1] >>> b [1] This is similar to what happens when a list is used as a default value for a function parameter. When a function is created, the default values are created and stored as an attribute of the function object (f.func_defaults, actually). When the function is called, if a parameter is omitted, the default value for that parameter is bound to the parameter name. Now there are two variables that refer to the same default value - the function attribute containing the default values, and the variable in the function body. If the default value is mutable, like a list, and the function body changes it, the actual default value is changed. Finally, if the function is called again without the optional parameter, the _modified_ default parameter is bound to the new local variable. For example, >>> def f(a, l=[]): ... l.append(a) ... return l ... >>> f.func_defaults ([],) The default value is an empty list. Now call f and the default value will change: >>> f(1) [1] >>> f.func_defaults ([1],) Adding the if statement makes the function create a new list each time it is called, so the default value is not changed. >2. (section 9.6) So the way to make a private variable is to put two >underscores in front of the name? Or to do 'underscore, classname, two >underscores, variable name'? Are those two used interchangebly for >defining the private variable, or is the first one for defining and the >second one for calling? Just use two underscores. If for some reason you need to refer to the 'private' variable from outside the module it is defined in, use the longer form. These variables aren't really that private, but it is a little inconvenient to access them from outside and a strong hint that you shouldn't do so. >3. (9.8) What is the difference between these two: > >raise Class, instance > >raise instance (or raise instance.__class__, instance) I don't think there is any difference. >4. (also 9.8) How does this thing work: > >class B: > pass >class C(B): > pass >class D(C): > pass > >for c in [B, C, D]: > try: > raise c() > except D: > print "D" > except C: > print "C" > except B: > print "B" > >I kind of get that in the top part C is a child class of B and D of C, but >what does it do for the example? Also, is it just a coincidence that the >lower case 'c' is both the loop controll variable and the non-existant >function being called in the 'try' block, or are those two connected? This example is showing that you can have a hierarchy of exceptions. If you have multiple except clauses, they are tried in order until one matches. The loop binds the variable c to each of B, C and D in turn. Calling c() is the same as calling B(), C() or D() - a constructor call. B, C and D are the exception classes. When B is thrown, it is caught by 'except B', etc. >5. Creature's stupid question of the month: what does 'container object' mean? Well, in a general way it is an object that can contain other objects. For example a list or dictionary can contain strings, a Tkinter Frame can contain Buttons and Labels, an XML Element can contain other Elements... Kent >That's all for now. Sorry to ask so many questions at once :) > >Thanks in advance ^_^ > >Creature >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From isrgish at fastem.com Tue Sep 7 05:00:51 2004 From: isrgish at fastem.com (Isr Gish) Date: Tue Sep 7 05:00:57 2004 Subject: [Tutor] drawing a graph Message-ID: <20040907030056.0391B1E4005@bag.python.org> Hi Tpc, >From: "tpc@csua.berkeley.edu"<tpc@csua.berkeley.edu> >Sent: 9/6/04 8:33:51 AM >To: "Danny Yoo"<dyoo@hkn.eecs.berkeley.edu> >Cc: "Tutor"<tutor@python.org>, "alan.gauld@blueyonder.co.uk"<alan.gauld@blueyonder.co.uk> >Subject: Re: [Tutor] drawing a graph > > >hi Danny, just an update, it seems that Rpy-0.3.5 is compiled only for R >version 1.8.1 (in other words, you need the binary executable rw1081.exe) >from the looks of this page: > >http://tolstoy.newcastle.edu.au/R/help/04/07/1872.html > >and frustratingly, if you go to CRAN: > >http://cran.r-project.org/mirrors.html > >the only binary executables available for download are rw1091.exe and >rw1090.exe. After installing R version 1.9.1, putting 'C:\Program >Files\R\rw1091\bin' in my path, and 'import rpy' I got the following >error: > >>>> import rpy >>>> degrees = 4 >>>> grid = r.seq(0, 10, length=100) >... >NameError: name 'r' is not defined This error is saying exactly whats wrong. You never defined 'r' as anything. So python is complainig that its not defined. (I don't think this has anything to do with 'rpy'.) All the best, Isr > > >On Mon, 6 Sep 2004, Danny Yoo wrote: > >> >> Hi Tpc, >> >> 'rpy' has a few prerequisites. You need to first install R, because 'rpy' >> is a translator between R and Python. >> >> http://www.r-project.org/ >> >> It is Free Software, so you should be able to grab it from several >> mirrors. >> >> If you're having more problems with 'rpy', it might be best to bring them >> up on 'rpy-list': >> >> http://rpy.sourceforge.net/maillist.html >> >> >> Good luck! >> >> > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From cmeesters at ucdavis.edu Tue Sep 7 05:40:44 2004 From: cmeesters at ucdavis.edu (Christian Meesters) Date: Tue Sep 7 05:40:48 2004 Subject: [Tutor] concerning distutils: how to include additional files? Message-ID: <B2A7726E-007F-11D9-A39D-000393D8EC3A@ucdavis.edu> Hi I'd like to place a question concerning the distutils module. Or better: How is it possible to include files into a package which aren't Python modules (e.g. a README file)? If I understand the documentation correctly the following should work: #in a setup.py from distutils.core import setup setup(name="packagename", version="0.1a", author="me", author_email="my@e.mail", url="do_not_want_to_post_now", description="blah_blah", packages= ["packagedirectory","packagedirectory.src"], data_files=[("packagedirectory",["README"])] ) Calling with "$ python setup.py sdist --formats=gztar,zip", I see the following warnings: warning: sdist: manifest template 'MANIFEST.in' does not exist (using default file list) warning: sdist: standard file not found: should have one of README, README.txt And "README" is indeed not in the package, but the rest (all Python modules) is included. I tried various things to state the "packagedirectoy" - every time without success. What am I doing wrong? Or better: What do I have to correct, to include "README" or other files? (Somebody an example?) The paths have the following structure: /root with setup.py /root/packagedirectory with packagename.py and README /root/packagedirectory/src with other modules 'root' being the root directory of the package not my root directory. For the record: I'm using OS X 10.3.4 and python 2.3.3 (tried with the SGI at my work place where Python 2.3.4 is installed, too. So, I don't think an update will help). Perhaps my question is somewhat na?ve, but it's my first time with distutils ... Thanks a lot in advance, Christian From zmerch at 30below.com Tue Sep 7 06:53:48 2004 From: zmerch at 30below.com (Roger Merchberger) Date: Tue Sep 7 06:54:54 2004 Subject: [Tutor] Dodgey if loop ? In-Reply-To: <1094480749.413c736da2e63@webmail.freedom2surf.net> Message-ID: <5.1.0.14.2.20040907004957.046ed758@mail.30below.com> Rumor has it that nick@javacat.f2s.com may have mentioned these words: [snip] Others have mentioned a problem with your algorithm, but there is an indentation problem with your code: >Here's the offending code: > >[code] >pnumber = str(pnumber) #pnumber is 25 for example >for line in f: # f is '/etc/services' open file > if not line.startswith('#') and len(line) > 10: > p = line.split()[1].split('/')[0] > if p == pnumber: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ This line should not be indented -- and *might* cause problems, tho I did not test the code... > return line.split()[0] # would return 'smtp' > #else: > #return '?' >[/code] Hope this helps, 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 nick at javacat.f2s.com Tue Sep 7 10:04:23 2004 From: nick at javacat.f2s.com (nick@javacat.f2s.com) Date: Tue Sep 7 10:04:25 2004 Subject: [Tutor] Dodgey if loop ? In-Reply-To: <5.1.0.14.2.20040907004957.046ed758@mail.30below.com> References: <5.1.0.14.2.20040907004957.046ed758@mail.30below.com> Message-ID: <1094544263.413d6b8734ad6@webmail.freedom2surf.net> Thankyou. I have since changed the code to use a dict. However, I'm getting the same error, Im quite confused :( The dictionary portDict below is of the form {port_nr:port_name}. here's the code: [code] 78 for port in range(sport, eport): # ie range(10,51) 79 try: 80 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 81 s.settimeout(2) 82 s.connect((host, port)) 83 print "\n", host, 'is listening on port', port, 84 if portDict.has_key(port): 85 print "(%s)" %portDict[port], 86 else: 87 print "Unknown port", 88 s.close() 89 90 except socket.error: 91 nogood.append(port) [/code] The else: on line 86 is always true. Even if I get rid of the else and change it to 86 if not portDict.has_key(port): 87 print "Unknown port", It is still always returning "Unknown port". Here's a run with the 'else' or 'if not portDict.has_key()': [nickl@netview socket]$ ./scan.py bishop1 10 50 Trying bishop1 ... bishop1 is listening on port 13 Unknown port bishop1 is listening on port 19 Unknown port bishop1 is listening on port 21 Unknown port bishop1 is listening on port 23 Unknown port bishop1 is listening on port 25 Unknown port bishop1 is listening on port 37 Unknown port 35 ports were closed And here's a run with lines 86 and 87 just deleted: [nickl@netview socket]$ ./scan.py bishop1 10 50 Trying bishop1 ... bishop1 is listening on port 13 bishop1 is listening on port 19 bishop1 is listening on port 21 bishop1 is listening on port 23 bishop1 is listening on port 25 bishop1 is listening on port 37 35 ports were closed I believe the answer may of been given to me in a previous reply, but I still can't get it working. I apologise for not 'getting' this. Regards Nick. Quoting Roger Merchberger <zmerch@30below.com>: > Rumor has it that nick@javacat.f2s.com may have mentioned these words: > [snip] > > Others have mentioned a problem with your algorithm, but there is an > indentation problem with your code: > > >Here's the offending code: > > > >[code] > >pnumber = str(pnumber) #pnumber is 25 for example > >for line in f: # f is '/etc/services' open file > > if not line.startswith('#') and len(line) > 10: > > p = line.split()[1].split('/')[0] > > if p == pnumber: > > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ > This line should not be indented -- and *might* cause problems, tho > I did not test the code... > > > return line.split()[0] # would return 'smtp' > > #else: > > #return '?' > >[/code] > > Hope this helps, > 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 > ------------------------------------------------- Everyone should have http://www.freedom2surf.net/ From nick at javacat.f2s.com Tue Sep 7 10:32:12 2004 From: nick at javacat.f2s.com (nick@javacat.f2s.com) Date: Tue Sep 7 10:32:14 2004 Subject: [Tutor] Dodgey if loop ? FIXED In-Reply-To: <1094544263.413d6b8734ad6@webmail.freedom2surf.net> References: <5.1.0.14.2.20040907004957.046ed758@mail.30below.com> <1094544263.413d6b8734ad6@webmail.freedom2surf.net> Message-ID: <1094545932.413d720c669e5@webmail.freedom2surf.net> Thanks for everyones help, this is working now. The problem was with the keys in portDict. I was doing if portDict.has_key(port): when I should of been doing if portDict.has_key(str(port)): I won't be forgetting that for a while ;) Many thanks again. Nick. Quoting nick@javacat.f2s.com: > Thankyou. > > I have since changed the code to use a dict. > However, I'm getting the same error, Im quite confused :( > > The dictionary portDict below is of the form {port_nr:port_name}. > > here's the code: > [code] > 78 for port in range(sport, eport): # ie range(10,51) > 79 try: > 80 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > 81 s.settimeout(2) > 82 s.connect((host, port)) > 83 print "\n", host, 'is listening on port', port, > 84 if portDict.has_key(port): > 85 print "(%s)" %portDict[port], > 86 else: > 87 print "Unknown port", > 88 s.close() > 89 > 90 except socket.error: > 91 nogood.append(port) > [/code] > > The else: on line 86 is always true. > Even if I get rid of the else and change it to > > 86 if not portDict.has_key(port): > 87 print "Unknown port", > > It is still always returning "Unknown port". > > Here's a run with the 'else' or 'if not portDict.has_key()': > > [nickl@netview socket]$ ./scan.py bishop1 10 50 > Trying bishop1 ... > > bishop1 is listening on port 13 Unknown port > bishop1 is listening on port 19 Unknown port > bishop1 is listening on port 21 Unknown port > bishop1 is listening on port 23 Unknown port > bishop1 is listening on port 25 Unknown port > bishop1 is listening on port 37 Unknown port > 35 ports were closed > > And here's a run with lines 86 and 87 just deleted: > > [nickl@netview socket]$ ./scan.py bishop1 10 50 > Trying bishop1 ... > > bishop1 is listening on port 13 > bishop1 is listening on port 19 > bishop1 is listening on port 21 > bishop1 is listening on port 23 > bishop1 is listening on port 25 > bishop1 is listening on port 37 > 35 ports were closed > > I believe the answer may of been given to me in a previous reply, but I still > can't get it working. > > I apologise for not 'getting' this. > > Regards > Nick. > > > > > Quoting Roger Merchberger <zmerch@30below.com>: > > > Rumor has it that nick@javacat.f2s.com may have mentioned these words: > > [snip] > > > > Others have mentioned a problem with your algorithm, but there is an > > indentation problem with your code: > > > > >Here's the offending code: > > > > > >[code] > > >pnumber = str(pnumber) #pnumber is 25 for example > > >for line in f: # f is '/etc/services' open file > > > if not line.startswith('#') and len(line) > 10: > > > p = line.split()[1].split('/')[0] > > > if p == pnumber: > > > > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ > > This line should not be indented -- and *might* cause problems, tho > > I did not test the code... > > > > > return line.split()[0] # would return 'smtp' > > > #else: > > > #return '?' > > >[/code] > > > > Hope this helps, > > 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 > > > > > > > ------------------------------------------------- > Everyone should have http://www.freedom2surf.net/ > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > ------------------------------------------------- Everyone should have http://www.freedom2surf.net/ From abra9823 at mail.usyd.edu.au Tue Sep 7 14:13:34 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Tue Sep 7 14:13:40 2004 Subject: [Tutor] make_parser Message-ID: <1094559214.413da5ee715e6@www-mail.usyd.edu.au> hi! in my code, i am giving make_parser the name of the parser i'd like to use the code is below parser = make_parser(['xmlproc']) parser.setFeature(feature_namespaces, 0) dh = FindIssue() # Tell the parser to use our handler parser.setContentHandler(dh) # Parse the input f = open('\um\proxy\policy-eg1.xml') str = f.read() f.close() print "file read" parser.parseString(str) this throws an error saying ExpatParser instance has no attribute 'parseString' what am i doing wrong? i thought i was using xmlproc thanks cheers ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From kent_johnson at skillsoft.com Tue Sep 7 14:58:54 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Tue Sep 7 14:58:58 2004 Subject: [Tutor] Network programming In-Reply-To: <1094473155.4233.23.camel@linux.site> References: <1094473155.4233.23.camel@linux.site> Message-ID: <6.1.0.6.0.20040907085123.02869dd8@mail4.skillsoft.com> We might be better able to help if you post your code. Here is a list of HTTP proxy servers written in Python, you might find something helpful there: http://xhaus.com/alan/python/proxies.html Kent At 02:19 PM 9/6/2004 +0200, Johan Geldenhuys wrote: >Hi, > >I am new to Python and would like to know more about network programming >in particilar. > >I have a script that sets up a socket server and must wait for incoming >connections. Once a call has been accepted, it must make another socket >connection to a destination. > >Now, I want to let these two "talk" to each other. Once the server >receives data it must be send out to the destination and when the >destination has data, it must be send out to the connection that made the >first call to the server. > >Does anybody have any examples or tips on how I can let this happen. My >calls work for the first batch of data and then when new data is received, >the calls break. > >Thanks > >-- > Johan Geldenhuys >Access Telecommunication Systems > Mail to: johan@accesstel.co.za >-- >This message has been scanned for viruses and >dangerous content by <http://www.azitech.co.za>Azitech, and is >believed to be clean. >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From jbloss at alltel.net Tue Sep 7 18:00:03 2004 From: jbloss at alltel.net (Jeffrey F. Bloss) Date: Tue Sep 7 18:00:26 2004 Subject: [Tutor] Parsing string with variable length delimiter? Message-ID: <0BC90CB41EC4500DA08CFCAD@E9802E4EB924944511D1F6FE> In general, what's the "best" way to split() a series of strings such as... TEXT MORETEXT SOMEMORETEXT TEXT MORETEXT TEXT MORETEXT SOMEMORETEXT Text field lengths are variable as are numbers of delimiter characters. mystring.split(' ') yields a list including each individual space. Would it be best to parse that list and reject any spaces, or is there a regex way to modify the behavior of the .split() method? Or another method all together? Thanks in advance! From kent_johnson at skillsoft.com Tue Sep 7 18:10:26 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Tue Sep 7 18:10:32 2004 Subject: [Tutor] Parsing string with variable length delimiter? In-Reply-To: <0BC90CB41EC4500DA08CFCAD@E9802E4EB924944511D1F6FE> References: <0BC90CB41EC4500DA08CFCAD@E9802E4EB924944511D1F6FE> Message-ID: <6.1.0.6.0.20040907120909.0285d328@mail4.skillsoft.com> If you use string.split() with no arguments, it will treat runs of whitespace as a single separator. This is different behavior from string.split(' '), which treats each individual space as a separator: >>> 'a b c'.split() ['a', 'b', 'c'] >>> 'a b c'.split(' ') ['a', '', 'b', '', '', '', 'c'] Kent At 04:00 PM 9/7/2004 +0000, Jeffrey F. Bloss wrote: >In general, what's the "best" way to split() a series of strings such as... > >TEXT MORETEXT SOMEMORETEXT TEXT >MORETEXT TEXT MORETEXT SOMEMORETEXT > >Text field lengths are variable as are numbers of delimiter characters. >mystring.split(' ') yields a list including each individual space. Would >it be best to parse that list and reject any spaces, or is there a regex >way to modify the behavior of the .split() method? Or another method all >together? > >Thanks in advance! >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From jbloss at alltel.net Tue Sep 7 18:19:33 2004 From: jbloss at alltel.net (Jeffrey F. Bloss) Date: Tue Sep 7 18:19:52 2004 Subject: [Tutor] Parsing string with variable length delimiter? In-Reply-To: <6.1.0.6.0.20040907120909.0285d328@mail4.skillsoft.com> References: <0BC90CB41EC4500DA08CFCAD@E9802E4EB924944511D1F6FE> <6.1.0.6.0.20040907120909.0285d328@mail4.skillsoft.com> Message-ID: <69D5AA3EB32F5377F8420B90@E9802E4EB924944511D1F6FE> On 9/7/04 12:10 PM -0400, Kent Johnson wrote: > If you use string.split() with no arguments, it will treat runs of > whitespace as a single separator. This is different behavior from > string.split(' '), which treats each individual space as a separator: <snip> DOH! Simple and easy. Why didn't I try that when it's plain as day the separator is _optional_ in the docs?? ;) Thanks, Kent. From klas.martelleur at telia.com Tue Sep 7 19:28:42 2004 From: klas.martelleur at telia.com (Klas Marteleur) Date: Tue Sep 7 19:28:44 2004 Subject: [Tutor] Automate tasks performed in a web browser? Message-ID: <200409071928.42053.klas.martelleur@telia.com> Hi Is it possible to automate tasks performed in a web browser on a dynamic homepage using python. For example fill in forms and retrive outputs, sort of like an macro or something. I have some tasks at work which involves boring "clicking around" in a browser (a PDM system), waiting for windows to appear, writing some text in a form and then click OK.... write down the output on a piece of paper to remeber it... add that output to another box.... Unfortunatly there is no possiblity to "redesign" the PDMsystem/webbpage to make it easier... so it must be done from the clients. Yes i think you get the picture. Regards Klas From dyoo at hkn.eecs.berkeley.edu Tue Sep 7 20:16:36 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Sep 7 20:16:40 2004 Subject: [Tutor] Automate tasks performed in a web browser? In-Reply-To: <200409071928.42053.klas.martelleur@telia.com> Message-ID: <Pine.LNX.4.44.0409071115010.26249-100000@hkn.eecs.berkeley.edu> On Tue, 7 Sep 2004, Klas Marteleur wrote: > Is it possible to automate tasks performed in a web browser on a dynamic > homepage using python. For example fill in forms and retrive outputs, > sort of like an macro or something. Hi Klas, Yes, I think you're looking for the 'WebUnit' project: http://webunit.sourceforge.net/ Hope this helps! From dyoo at hkn.eecs.berkeley.edu Tue Sep 7 20:53:42 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Sep 7 20:53:47 2004 Subject: [Tutor] make_parser In-Reply-To: <1094559214.413da5ee715e6@www-mail.usyd.edu.au> Message-ID: <Pine.LNX.4.44.0409071117000.26249-100000@hkn.eecs.berkeley.edu> On Tue, 7 Sep 2004, Ajay wrote: > in my code, i am giving make_parser the name of the parser i'd like to > use the code is below > > parser = make_parser(['xmlproc']) Hi Ajay, Next time, also show us what imports you've done. There's no indication that you're using xml.sax.make_parser(), so folks who haven't played with the XML stuff would have a harder time to get your example to work. > this throws an error saying ExpatParser instance has no attribute > 'parseString' Ok, it sounds like the 'parser' instance that you're getting back isn't an xmlproc instance. It's very possible that the system isn't finding xmlproc. For example, if we pass something wacky to xml.sax.make_parser, it'll just give us an expat parser by default: ### >>> import xml >>> import xml.sax >>> xml.sax.make_parser(['foobar!!']) <xml.sax.expatreader.ExpatParser instance at 0x402fc3cc> ### Since xmlproc is not a part of the Standard Library, so I'd recommend check this first. Have you installed it from pyxml.sourceforge.net? I don't know why in the world there isn't good web-accessible documentation for PyXML. I was able to construct an XMLProc parser instance this way: ### >>> xml.sax.make_parser(['xml.sax.drivers2.drv_xmlproc']) <xml.sax.drivers2.drv_xmlproc.XmlprocDriver instance at 0x4038d80c> ### but this does not feel obvious at all to me. *sigh* Anyway, the error you're getting is actually an expected one: parseString() is a convenience function of the xml.sax package, but it's not a member of the XMLReader class. http://www.python.org/doc/lib/xmlreader-objects.html describes what methods you can pass to it. Use parser.parse(). For example: ### >>> p = xml.sax.make_parser(['xml.sax.drivers2.drv_xmlproc']) >>> from StringIO import StringIO >>> p.parse(StringIO("<hello>world</hello>")) >>> p.reset() >>> >>> >>> p.parse(StringIO("<hello>world</hi>")) Traceback (most recent call last): File "<stdin>", line 1, in ? File "/usr/lib/python2.3/site-packages/_xmlplus/sax/xmlreader.py", line 125, in parse self.close() File "/usr/lib/python2.3/site-packages/_xmlplus/sax/drivers2/drv_xmlproc.py", line 99, in close self._parser.flush() File "/usr/lib/python2.3/site-packages/_xmlplus/parsers/xmlproc/xmlutils.py", line 361, in flush self.do_parse() File "/usr/lib/python2.3/site-packages/_xmlplus/parsers/xmlproc/xmlproc.py", line 91, in do_parse self.parse_end_tag() File "/usr/lib/python2.3/site-packages/_xmlplus/parsers/xmlproc/xmlproc.py", line 344, in parse_end_tag self.report_error(3023,(name,elem)) File "/usr/lib/python2.3/site-packages/_xmlplus/parsers/xmlproc/xmlproc.py", line 63, in report_error EntityParser.report_error(self,number,args) File "/usr/lib/python2.3/site-packages/_xmlplus/parsers/xmlproc/xmlutils.py", line 524, in report_error self.err.fatal(msg) File "/usr/lib/python2.3/site-packages/_xmlplus/sax/drivers2/drv_xmlproc.py", line 229, in fatal self._err_handler.fatalError(saxlib.SAXParseException(msg, None, self)) File "/usr/lib/python2.3/site-packages/_xmlplus/sax/handler.py", line 38, in fatalError raise exception xml.sax._exceptions.SAXParseException: <unknown>:1:17: End tag for 'hi' seen, but 'hello' expected ### Hope this helps! From dyoo at hkn.eecs.berkeley.edu Tue Sep 7 22:08:07 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Sep 7 22:08:12 2004 Subject: [Tutor] concerning distutils: how to include additional files? In-Reply-To: <B2A7726E-007F-11D9-A39D-000393D8EC3A@ucdavis.edu> Message-ID: <Pine.LNX.4.44.0409071255360.26249-100000@hkn.eecs.berkeley.edu> On Mon, 6 Sep 2004, Christian Meesters wrote: > I'd like to place a question concerning the distutils module. Or better: > How is it possible to include files into a package which aren't Python > modules (e.g. a README file)? Hi Christian, I think you can do this through the 'MANIFEST.in' file: it allows us to tell Distutils what to include with a source distribution. http://docs.python.org/dist/source-dist.html#SECTION000510000000000000000 I'm not exactly sure how MANIFEST.in interacts with the other options in the setup() call, but perhaps when Distutils is run in 'sdist' mode, it doesn't look at the 'data_files' keyword parameter? I'm ignorant because I haven't looked closely at this yet... But If I have more time, I'll try to look into this and try to give a better explanation. And I do probably have to look at this: I need to polish up my personal 'pyscheme' program with Distutils this week. > Perhaps my question is somewhat na=EFve, but it's my first time with > distutils ... No, it's a good question. Feel free to ask more. *grin* Best of wishes to you! From cmeesters at ucdavis.edu Tue Sep 7 23:10:48 2004 From: cmeesters at ucdavis.edu (Christian Meesters) Date: Tue Sep 7 23:10:52 2004 Subject: [Tutor] concerning distutils: how to include additional files? In-Reply-To: <Pine.LNX.4.44.0409071255360.26249-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0409071255360.26249-100000@hkn.eecs.berkeley.edu> Message-ID: <63D7A202-0112-11D9-A81F-000393D8EC3A@ucdavis.edu> Hoi Danny, On Sep 7, 2004, at 1:08 PM, Danny Yoo wrote: > >> Perhaps my question is somewhat na?ve, but it's my first time with >> distutils ... > > No, it's a good question. Feel free to ask more. *grin* > Well, apparently it was a bit na?ve, for the answer is actually in the manual ... I must admit that I just read over this part and didn't really get it. Perhaps the documentation could be a bit clearer at this point, too? (I might try to summarize a few examples and submit to the documentation section (docs@python.org). Is that a good idea? Any suggestions?) Thanks a lot, Christian From abra9823 at mail.usyd.edu.au Wed Sep 8 02:41:02 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Wed Sep 8 02:41:11 2004 Subject: [Tutor] xml.dom.minidom key error Message-ID: <1094604062.413e551e9b1a9@www-mail.usyd.edu.au> hi! i am parsing the attached document. the code is from xml.sax import make_parser from xml.dom.minidom import parse parser = make_parser('xml.sax.drivers2.drv_xmlproc') ruleSet = parse(ruleSetFile, parser=parser) i am using python2.3.4 with PyXML version 0.8.1 i get the following error Traceback (most recent call last): File "evaluator.py", line 59, in ? ea = ae.evaluate("complywitheudirective.xml", "policy-eg1.xml", 0) File "evaluator.py", line 22, in evaluate ruleSet = parse(ruleSetFile, parser=parser) File "C:\PYTHON23\Lib\site-packages\_xmlplus\dom\minidom.py", line 1912, in pa rse {'parser': parser, 'bufsize': bufsize}) File "C:\PYTHON23\Lib\site-packages\_xmlplus\dom\minidom.py", line 1899, in _d o_pulldom_parse toktype, rootNode = events.getEvent() File "C:\PYTHON23\Lib\site-packages\_xmlplus\dom\pulldom.py", line 265, in get Event self.parser.feed(buf) File "C:\PYTHON23\Lib\site-packages\_xmlplus\sax\drivers2\drv_xmlproc.py", lin e 96, in feed self._parser.feed(data) File "C:\PYTHON23\Lib\site-packages\_xmlplus\parsers\xmlproc\xmlutils.py", lin e 332, in feed self.do_parse() File "C:\PYTHON23\Lib\site-packages\_xmlplus\parsers\xmlproc\xmlproc.py", line 93, in do_parse self.parse_start_tag() File "C:\PYTHON23\Lib\site-packages\_xmlplus\parsers\xmlproc\xmlproc.py", line 197, in parse_start_tag self.app.handle_start_tag(name,attrs) File "C:\PYTHON23\Lib\site-packages\_xmlplus\sax\drivers2\drv_xmlproc.py", lin e 368, in handle_start_tag AttributesNSImpl(attrs, rawnames)) File "C:\PYTHON23\Lib\site-packages\_xmlplus\dom\pulldom.py", line 98, in star tElementNS prefix = self._current_context[a_uri] KeyError: u'http://www.w3.org/2001/02/appelv1' any ideas why? thanks cheers ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. -------------- next part -------------- A non-text attachment was scrubbed... Name: complywitheudirective.xml Type: text/xml Size: 2973 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20040908/c9812b28/complywitheudirective-0001.xml From csmwxl at bath.ac.uk Wed Sep 8 20:56:44 2004 From: csmwxl at bath.ac.uk (W X Liu) Date: Wed Sep 8 20:56:46 2004 Subject: [Tutor] How to represent "enter" Message-ID: <1094669804.413f55ec57e7f@webmail.bath.ac.uk> Hi everyone, who can tell me that how to represent "enter" key in python? Many thanks Wenxin Liu From xecronix at yahoo.com Wed Sep 8 21:29:26 2004 From: xecronix at yahoo.com (Ron Weidner) Date: Wed Sep 8 21:29:31 2004 Subject: [Tutor] Network programming In-Reply-To: <1094473155.4233.23.camel@linux.site> Message-ID: <20040908192926.69144.qmail@web60601.mail.yahoo.com> --- Johan Geldenhuys <johan@accesstel.co.za> wrote: > Hi, > > I am new to Python and would like to know more about > network programming > in particilar. --- Johan Geldenhuys <johan@accesstel.co.za> wrote: > Hi, > > I am new to Python and would like to know more about > network programming > in particilar. Check out some of the source code found on the Useless Python site. The following is a URL to a page with links to lots of source code. The ones that might intrest you are DSserver and DSclient. http://www.uselesspython.com/uselesspython4.html If those examples are too simple, try the pudding server on for size. http://www.uselesspython.com/uselesspython1.html Good Luck... Ron_W __________________________________ Do you Yahoo!? Yahoo! Mail - 50x more storage than other providers! http://promotions.yahoo.com/new_mail From orbitz at ezabel.com Wed Sep 8 22:44:46 2004 From: orbitz at ezabel.com (orbitz) Date: Wed Sep 8 22:44:56 2004 Subject: [Tutor] How to represent "enter" In-Reply-To: <1094669804.413f55ec57e7f@webmail.bath.ac.uk> References: <1094669804.413f55ec57e7f@webmail.bath.ac.uk> Message-ID: <413F6F3E.3010704@ezabel.com> "\n" On some systems it may be "\r\n" but the stream shoudl convert "\n" to that if it's setup properly. W X Liu wrote: >Hi everyone, > >who can tell me that how to represent "enter" key in python? > >Many thanks > >Wenxin Liu > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > From dyoo at hkn.eecs.berkeley.edu Wed Sep 8 23:45:44 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Sep 8 23:46:08 2004 Subject: [Tutor] How to represent "enter" In-Reply-To: <413F6F3E.3010704@ezabel.com> Message-ID: <Pine.LNX.4.44.0409081442490.23999-100000@hkn.eecs.berkeley.edu> On Wed, 8 Sep 2004, orbitz wrote: > "\n" > > On some systems it may be "\r\n" but the stream shoudl convert "\n" to > that if it's setup properly. By the way, there's a reference table in the middle of: http://www.python.org/doc/ref/strings.html It tabulates a complete list of the "escape" sequences that we can embed in Python string literals. Good luck! From billk at fastmail.fm Thu Sep 9 04:59:55 2004 From: billk at fastmail.fm (Bill Kranec) Date: Thu Sep 9 04:59:58 2004 Subject: [Tutor] pysqlite overview Message-ID: <1094698795.9234.203987539@webmail.messagingengine.com> Hi, I'm interested in experimenting with some database programming in Python, and in particular I would like to try PySQLite. However, the documentation on the PySQLite site leaves something to be desired. Can anyone point me to a) some good overviews of database programming in Python? b) any particular pysqlite resources? Thanks for any help. Bill From flaxeater at yahoo.com Thu Sep 9 05:38:25 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Thu Sep 9 05:38:29 2004 Subject: [Tutor] pysqlite overview Message-ID: <20040909033825.41339.qmail@web52604.mail.yahoo.com> Bill Kranec wrote: >Hi, > >I'm interested in experimenting with some database programming in >Python, and in particular I would like to try PySQLite. However, the >documentation on the PySQLite site leaves something to be desired. Can >anyone point me to > >a) some good overviews of database programming in Python? >b) any particular pysqlite resources? > >Thanks for any help. > > I have done a fair amount of pysqlite hacking, there are three things that I found useful when working through this. First I looked at the source code, I found it quite small and understandable this gave me some inkling of it's behavior, the pysqlite documentation is like you said not very good but look at the examples closely. In addition it adheres closely to the python db api. Check out it's specs here http://www.python.org/peps/pep-0249.html Here's an article http://www.linuxjournal.com/article.php?sid=2605 and here's some db api example code http://www.linuxjournal.com/article.php?sid=2605 This should be helpful. the DB api makes it unnecessary to dwell overmuch on the underlying engine. __________________________________ Do you Yahoo!? Yahoo! Mail - 50x more storage than other providers! http://promotions.yahoo.com/new_mail From master_knight at fastmail.fm Thu Sep 9 09:54:25 2004 From: master_knight at fastmail.fm (Ashkan Aliabadi) Date: Thu Sep 9 09:54:29 2004 Subject: [Tutor] (no subject) Message-ID: <1094716465.25029.203999699@webmail.messagingengine.com> Skipped content of type multipart/alternative-------------- next part -------------- A non-text attachment was scrubbed... Name: NP.zip Type: application/x-zip-compressed Size: 743 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20040909/c1a47102/NP.bin From johan at accesstel.co.za Thu Sep 9 10:14:50 2004 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Thu Sep 9 10:16:37 2004 Subject: [Tutor] Network programming In-Reply-To: <6.1.0.6.0.20040907085123.02869dd8@mail4.skillsoft.com> References: <1094473155.4233.23.camel@linux.site> <6.1.0.6.0.20040907085123.02869dd8@mail4.skillsoft.com> Message-ID: <1094717689.4427.10.camel@linux.site> I still have trouble when I want to send data out as soon as it comes in from one side. My server listens and accepts the calls and then builds the client connection to the destination. Please see if you can assist. Thanks Johan #################################################### # we have an incoming socket connect newConn, addr = self._serverSocket.accept() self.log('Connection received from: %s:%s' % addr) #while connection is active on server: while 1: #self._ne1_id = '1234' #self._ne2_id = '1111' indata = newConn.recv(8192) self.log('First Data received from LCT:' + `indata`) if '\xff' in indata: continue if '\x01' in indata: continue #Look for string of 1234 in indata: if indata[0:4] == self._ne1_id: self.log('indata 0:4 is:' + `indata[0:4]`) self.sock = socket(AF_INET, SOCK_STREAM) #connect to this destination if the string is 1234 self.sock.connect((self._ne1_ip, self._ne1_port)) # This is previously defined self.log('Connection established to NE1: %s:%i' % (self._ne1_ip, self._ne1_port)) outdata = self.sock.recv(8192) #when connection to destination is up: while 1: if indata: self.sock.send(indata) self.log('indata send to NE, line 106: ' + `indata`) # If break sequence is received from server side, close the client connection if '\x11' in indata: self.log('Break character received') break self.sock.close() self.log('connection to NE1 now closed') if oudata: newConn.send(outdata) self.log('Data from NE:' + `outdata`) ########################################################### On Tue, 2004-09-07 at 14:58, Kent Johnson wrote: > We might be better able to help if you post your code. > > Here is a list of HTTP proxy servers written in Python, you might find > something helpful there: > http://xhaus.com/alan/python/proxies.html > > Kent > > At 02:19 PM 9/6/2004 +0200, Johan Geldenhuys wrote: > >Hi, > > > >I am new to Python and would like to know more about network programming > >in particilar. > > > >I have a script that sets up a socket server and must wait for incoming > >connections. Once a call has been accepted, it must make another socket > >connection to a destination. > > > >Now, I want to let these two "talk" to each other. Once the server > >receives data it must be send out to the destination and when the > >destination has data, it must be send out to the connection that made the > >first call to the server. > > > >Does anybody have any examples or tips on how I can let this happen. My > >calls work for the first batch of data and then when new data is received, > >the calls break. > > > >Thanks > > > >-- > > Johan Geldenhuys > >Access Telecommunication Systems > > Mail to: johan@accesstel.co.za > >-- > >This message has been scanned for viruses and > >dangerous content by <http://www.azitech.co.za>Azitech, and is > >believed to be clean. > >_______________________________________________ > >Tutor maillist - Tutor@python.org > >http://mail.python.org/mailman/listinfo/tutor -- Johan Geldenhuys Access Telecommunication Systems Mail to: johan@accesstel.co.za -- This message has been scanned for viruses and dangerous content by Azitech, and is believed to be clean. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040909/0a43af29/attachment-0001.htm From eric at digitalert.net Thu Sep 9 10:52:02 2004 From: eric at digitalert.net (Eric) Date: Thu Sep 9 10:51:14 2004 Subject: [Tutor] Search text file, perform action if a given item found in file Message-ID: <414019B2.8080807@digitalert.net> This is my first project that I am starting to work on, and what I want to create is a program that will alert me by sounding the system bell (beep) when a connection is established to a selected TCP, or UDP port. It may not be the most usefull thing, but the learning experience is what I'm after with all From eric at digitalert.net Thu Sep 9 10:59:56 2004 From: eric at digitalert.net (Eric) Date: Thu Sep 9 10:59:04 2004 Subject: [Tutor] Search text file, perform action if a given item found in file In-Reply-To: <414019B2.8080807@digitalert.net> References: <414019B2.8080807@digitalert.net> Message-ID: <41401B8C.1000708@digitalert.net> Eric wrote: > This is my first project that I am starting to work on, and what I > want to create is a program > that will alert me by sounding the system bell (beep) when a > connection is > established to a selected TCP, or UDP port. It may not be the most > usefull thing, but the > learning experience is what I'm after with all > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > Sent that email on accident without completing it.. Anyway so far I have come up with this.. import os PORT = int(raw_input("What tcp/udp should I watch for?: ")) os.popen('netstat -an>log.txt') LogFile = file('log.txt', 'r') logcontents = LogFile.read() inFile.close() print logcontents So far so good. The "print logcontents" will print the output from the netstat command. My question is this. I'm trying to figure out a way to search "logcontents" for the "PORT" variable then perfrom a action if it finds a match. Thanks From blk20 at cam.ac.uk Thu Sep 9 11:51:32 2004 From: blk20 at cam.ac.uk (blk20) Date: Thu Sep 9 11:42:57 2004 Subject: [Tutor] 'None' output after arbitrary agruments function In-Reply-To: <41401B8C.1000708@digitalert.net> References: <414019B2.8080807@digitalert.net> <41401B8C.1000708@digitalert.net> Message-ID: <1094723492.2362.51.camel@localhost> Hi there, This is probably a very basic question. I am learning about functions and do soem exercises. I do not understand why the following code def adder(*arg): x = arg[0] for y in arg[1:]: x = x + y print x print adder('abc', 'def') print adder(['aa', 'bb', 'cc'], ['dd', 'ee', 'ff']) print adder(3.23, 1.77, 3.32) has the following output when the file is launched on the command line: abcdef None ['aa', 'bb', 'cc', 'dd', 'ee', 'ff'] None 8.32 None Why do I always get the 'None' output? Thanks for any help. Best, --Bernhard From andre.roberge at ns.sympatico.ca Thu Sep 9 12:14:52 2004 From: andre.roberge at ns.sympatico.ca (=?ISO-8859-1?Q?Andr=E9_Roberge?=) Date: Thu Sep 9 12:15:06 2004 Subject: [Tutor] 'None' output after arbitrary agruments function In-Reply-To: <20040909100052.1E80A1E4039@bag.python.org> References: <20040909100052.1E80A1E4039@bag.python.org> Message-ID: <41402D1C.5060403@ns.sympatico.ca> adder doesn't return a value (hence, printing it returns none). Try the following (just calling adder, not printing it): def adder(*arg): x = arg[0] for y in arg[1:]: x = x + y print x adder('abc', 'def') adder(['aa', 'bb', 'cc'], ['dd', 'ee', 'ff']) adder(3.23, 1.77, 3.32) -- Andre Roberge (Warning: I'm a newbie; this is my first contribution to Tutor-list :-) > > This is probably a very basic question. I am learning about functions > and do soem exercises. I do not understand why the following code > > def adder(*arg): > x = arg[0] > for y in arg[1:]: > x = x + y > print x > > print adder('abc', 'def') > print adder(['aa', 'bb', 'cc'], ['dd', 'ee', 'ff']) > print adder(3.23, 1.77, 3.32) > From kent_johnson at skillsoft.com Thu Sep 9 14:24:21 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Thu Sep 9 14:24:30 2004 Subject: [Tutor] Search text file, perform action if a given item found in file In-Reply-To: <41401B8C.1000708@digitalert.net> References: <414019B2.8080807@digitalert.net> <41401B8C.1000708@digitalert.net> Message-ID: <6.1.0.6.0.20040909081224.028926a0@mail4.skillsoft.com> Eric, First, I suggest you read the output of popen directly, you don't have to pipe it to a temp file. If you read it by lines, then you can process each line looking for the data you want. For example: >>> import os >>> o=os.popen('netstat -an') >>> for l in o: ... print l, ... Active Connections Proto Local Address Foreign Address State TCP 0.0.0.0:25 0.0.0.0:0 LISTENING TCP 0.0.0.0:135 0.0.0.0:0 LISTENING TCP 0.0.0.0:445 0.0.0.0:0 LISTENING TCP 0.0.0.0:1052 0.0.0.0:0 LISTENING etc... >>> o.close() Next you probably want to split() the line to divide it into fields. Then you can look at the specific fields. You might be able to use endswith() or find() to search for the port; in my example endswith(':25') for example would find the line with port 25. The details depend on what your data looks like. Give this a try and let us know how far you get. Also it would be helpful to see an example of the output of netstat on your computer, it is different on Windows and MacOSX. Kent At 04:59 AM 9/9/2004 -0400, Eric wrote: >Eric wrote: > >>This is my first project that I am starting to work on, and what I want >>to create is a program >>that will alert me by sounding the system bell (beep) when a connection is >>established to a selected TCP, or UDP port. It may not be the most >>usefull thing, but the >>learning experience is what I'm after with all >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor >> > >Sent that email on accident without completing it.. > > >Anyway so far I have come up with this.. > > > >import os > >PORT = int(raw_input("What tcp/udp should I watch for?: ")) > >os.popen('netstat -an>log.txt') > >LogFile = file('log.txt', 'r') >logcontents = LogFile.read() >inFile.close() >print logcontents > > > > >So far so good. The "print logcontents" will print the output from the >netstat command. My question is this. >I'm trying to figure out a way to search "logcontents" for the "PORT" >variable then perfrom a action if it finds >a match. > >Thanks > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From mi.janssen at gmail.com Thu Sep 9 15:58:46 2004 From: mi.janssen at gmail.com (Michael Janssen) Date: Thu Sep 9 15:59:02 2004 Subject: [Tutor] Parsing string with variable length delimiter? In-Reply-To: <69D5AA3EB32F5377F8420B90@E9802E4EB924944511D1F6FE> References: <0BC90CB41EC4500DA08CFCAD@E9802E4EB924944511D1F6FE> <6.1.0.6.0.20040907120909.0285d328@mail4.skillsoft.com> <69D5AA3EB32F5377F8420B90@E9802E4EB924944511D1F6FE> Message-ID: <1ff2dfbf040909065847539b02@mail.gmail.com> > DOH! Simple and easy. Why didn't I try that when it's plain as day the > separator is _optional_ in the docs?? ;) even more: when you need the second optional argument maxsplit, you can reenable the nice default behaviour with None. Instead of a lame aString.split(" ", 1) you can do aString.split(None, 1) to keep any-number-of-whitespace-splitting & stripping behaviour. Michael From jbloss at alltel.net Thu Sep 9 17:46:40 2004 From: jbloss at alltel.net (Jeffrey F. Bloss) Date: Thu Sep 9 17:46:57 2004 Subject: [Tutor] Parsing string with variable length delimiter? In-Reply-To: <1ff2dfbf040909065847539b02@mail.gmail.com> References: <0BC90CB41EC4500DA08CFCAD@E9802E4EB924944511D1F6FE> <6.1.0.6.0.20040907120909.0285d328@mail4.skillsoft.com> <69D5AA3EB32F5377F8420B90@E9802E4EB924944511D1F6FE> <1ff2dfbf040909065847539b02@mail.gmail.com> Message-ID: <11DB72A15FE2D1112CE8148A@E9802E4EB924944511D1F6FE> On 9/9/04 3:58 PM +0200, Michael Janssen wrote: > even more: when you need the second optional argument maxsplit, you > can reenable the nice default behaviour with None. Instead of a lame > > aString.split(" ", 1) > > you can do > > aString.split(None, 1) for words in range(len(soapbox)): Ya' know, I've been a "hack" for a long time, using C and other odd script languages to automate this or simplify that, or just get some job done that nothing else seem to do the way I want it done. I picked up Python maybe two months ago and love it. Spent a bunch of hours cobbling together a few little projects, learning by trial and error, and searching the docs. But I honestly think I've gained more useful knowledge reading this list in a couple weeks than I could have in many more months of hit and miss. The None thing is a prime example. Sends my palm sailing towards my forehead and makes me mumble things like "should have known that and I bet that works over here... and here... and over there dummy". ;) Ok, enough wasted bandwidth. I just wanted to thank you Michael, and every other Snake-God who takes the time to hand hold us clueless newbies. I love you guys. <smooch> From csmwxl at bath.ac.uk Thu Sep 9 19:02:09 2004 From: csmwxl at bath.ac.uk (W X Liu) Date: Thu Sep 9 19:02:12 2004 Subject: [Tutor] (no subject) Message-ID: <1094749329.41408c91a876d@webmail.bath.ac.uk> Hi, everyone, I writed a program: import telnetlib import sys a=telnetlib.Telnet(host='mudlib.anarres.org',port='5000') a.open(host='mudlib.anarres.org',port='5000') # I don't if I should use it. a.read_until('Anarres II login:') b=str('user'+chr(10)) a.write(b+ "\n") b=str('password'+chr(10)) a.read_until('password:') a.write(b + "\n") print a.read_all() But I always get a result like this: >>> ================================ RESTART ================================ >>> in the Python shell(IDLE), and I cannot see any happening on that Telnet server? Who could teach me about this? Many thanks Wenxin Liu From csmwxl at bath.ac.uk Thu Sep 9 19:30:33 2004 From: csmwxl at bath.ac.uk (W X Liu) Date: Thu Sep 9 19:30:36 2004 Subject: [Tutor] (no subject) In-Reply-To: <1094749329.41408c91a876d@webmail.bath.ac.uk> References: <1094749329.41408c91a876d@webmail.bath.ac.uk> Message-ID: <1094751033.414093397a14e@webmail.bath.ac.uk> Now, I get a feedback on IDLE: Traceback (most recent call last): File "C:\Python23\1.py", line 15, in -toplevel- a.read_until('abb@anarres> ') File "C:\PYTHON23\lib\telnetlib.py", line 324, in read_until return self.read_very_lazy() File "C:\PYTHON23\lib\telnetlib.py", line 400, in read_very_lazy raise EOFError, 'telnet connection closed' EOFError: telnet connection closed So, How can I fix my code by this feedback? Wenxin > Hi, everyone, > > I writed a program: > > import telnetlib > import sys > > a=telnetlib.Telnet(host='mudlib.anarres.org',port='5000') > a.open(host='mudlib.anarres.org',port='5000') # I don't if I should use it. > a.read_until('Anarres II login:') > b=str('user'+chr(10)) > a.write(b+ "\n") > > b=str('password'+chr(10)) > a.read_until('password:') > a.write(b + "\n") > print a.read_all() > > But I always get a result like this: > > >>> ================================ RESTART > ================================ > >>> > > in the Python shell(IDLE), and I cannot see any happening on that Telnet > server? > Who could teach me about this? > > Many thanks > > Wenxin Liu > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From jeff at ccvcorp.com Thu Sep 9 19:56:45 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu Sep 9 19:55:41 2004 Subject: [Tutor] 'None' output after arbitrary agruments function In-Reply-To: <41402D1C.5060403@ns.sympatico.ca> References: <20040909100052.1E80A1E4039@bag.python.org> <41402D1C.5060403@ns.sympatico.ca> Message-ID: <4140995D.4080300@ccvcorp.com> Andr? Roberge wrote: > adder doesn't return a value (hence, printing it returns none). Or, more specifically, all functions return a value; if you don't specify what that value should be, it defaults to None. You (the O.P.) have already printed results within the function, and then you *also* print whatever's returned from the function; since you haven't specified what should be returned, what you get is None, and what you're seeing is Python dutifully printing None just as you've told it to do. :) > Try the following (just calling adder, not printing it): > > def adder(*arg): > x = arg[0] > for y in arg[1:]: > x = x + y > print x > > adder('abc', 'def') > adder(['aa', 'bb', 'cc'], ['dd', 'ee', 'ff']) > adder(3.23, 1.77, 3.32) Or, alternatively, since there's any number of things that you might want to do with the results of adder(), instead of just printing them... def adder(*arg): x = arg[0] for y in arg[1:]: x = x + y return x print adder('abc', 'def') print adder(['aa', 'bb', 'cc'], ['dd', 'ee', 'ff']) temp = adder(3.23, 1.77, 3.32) print temp, temp * 2 Note how this lets me do further manipulations on the sum that I get from adder(), or simply store the result for later use elsewhere. Usually it's considered better style to simply return calculated results from a function, rather than printing them there -- the exception to this being a function whose sole purpose is to print something in a meaningful way. The idea here is that a function should try to do only *one* thing; calculating a result is one thing, printing it is a different thing. Jeff Shannon Technician/Programmer Credit International From csmwxl at bath.ac.uk Thu Sep 9 19:58:49 2004 From: csmwxl at bath.ac.uk (W X Liu) Date: Thu Sep 9 19:58:53 2004 Subject: [Tutor] What's EOF? In-Reply-To: <1094749329.41408c91a876d@webmail.bath.ac.uk> References: <1094749329.41408c91a876d@webmail.bath.ac.uk> Message-ID: <1094752729.414099d907573@webmail.bath.ac.uk> read_all( ) Read all data until EOF; block until connection closed. So, what's EOF? Many thanks Wenxin From kent_johnson at skillsoft.com Thu Sep 9 20:10:23 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Thu Sep 9 20:10:31 2004 Subject: [Tutor] What's EOF? In-Reply-To: <1094752729.414099d907573@webmail.bath.ac.uk> References: <1094749329.41408c91a876d@webmail.bath.ac.uk> <1094752729.414099d907573@webmail.bath.ac.uk> Message-ID: <6.1.0.6.0.20040909140925.028755c8@mail4.skillsoft.com> End Of File - the condition when no more data is available from a file or stream. At 06:58 PM 9/9/2004 +0100, W X Liu wrote: >read_all( ) > >Read all data until EOF; block until connection closed. > > >So, what's EOF? > >Many thanks > >Wenxin >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From eric at digitalert.net Thu Sep 9 20:26:00 2004 From: eric at digitalert.net (Eric) Date: Thu Sep 9 20:24:53 2004 Subject: [Tutor] Search text file, perform action if a given item found in file In-Reply-To: <6.1.0.6.0.20040909081224.028926a0@mail4.skillsoft.com> References: <414019B2.8080807@digitalert.net> <41401B8C.1000708@digitalert.net> <6.1.0.6.0.20040909081224.028926a0@mail4.skillsoft.com> Message-ID: <4140A038.9040504@digitalert.net> Thanks for the help.. I'm writing this just for Windows for the time being. Here is the output of a netstat -an Active Connections Proto Local Address Foreign Address State TCP 0.0.0.0:135 0.0.0.0:0 LISTENING TCP 0.0.0.0:445 0.0.0.0:0 LISTENING TCP 127.0.0.1:1028 0.0.0.0:0 LISTENING TCP 127.0.0.1:1051 127.0.0.1:1052 ESTABLISHED TCP 127.0.0.1:1052 127.0.0.1:1051 ESTABLISHED TCP 127.0.0.1:1116 127.0.0.1:1117 ESTABLISHED TCP 127.0.0.1:1117 127.0.0.1:1116 ESTABLISHED TCP 172.16.0.2:139 0.0.0.0:0 LISTENING TCP 192.168.0.250:139 0.0.0.0:0 LISTENING TCP 192.168.0.250:1049 192.168.0.1:22 ESTABLISHED TCP 192.168.0.250:1050 192.168.0.1:22 ESTABLISHED UDP 0.0.0.0:445 *:* UDP 0.0.0.0:500 *:* UDP 0.0.0.0:4500 *:* UDP 127.0.0.1:123 *:* UDP 127.0.0.1:1039 *:* UDP 127.0.0.1:1900 *:* UDP 172.16.0.2:123 *:* UDP 172.16.0.2:137 *:* UDP 172.16.0.2:138 *:* UDP 172.16.0.2:1900 *:* UDP 192.168.0.250:123 *:* UDP 192.168.0.250:137 *:* UDP 192.168.0.250:138 *:* UDP 192.168.0.250:1900 *:* After taking your advice I have come up with this so far... import os o=os.popen('netstat -an') for l in o: print l.split() and this is the output... [] ['Active', 'Connections'] [] ['Proto', 'Local', 'Address', 'Foreign', 'Address', 'State'] ['TCP', '0.0.0.0:135', '0.0.0.0:0', 'LISTENING'] ['TCP', '0.0.0.0:445', '0.0.0.0:0', 'LISTENING'] ['TCP', '127.0.0.1:1028', '0.0.0.0:0', 'LISTENING'] ['TCP', '127.0.0.1:1051', '127.0.0.1:1052', 'ESTABLISHED'] ['TCP', '127.0.0.1:1052', '127.0.0.1:1051', 'ESTABLISHED'] ['TCP', '172.16.0.2:139', '0.0.0.0:0', 'LISTENING'] ['TCP', '192.168.0.250:139', '0.0.0.0:0', 'LISTENING'] ['TCP', '192.168.0.250:1049', '192.168.0.1:22', 'ESTABLISHED'] ['TCP', '192.168.0.250:1050', '192.168.0.1:22', 'ESTABLISHED'] ['UDP', '0.0.0.0:445', '*:*'] ['UDP', '0.0.0.0:500', '*:*'] ['UDP', '0.0.0.0:4500', '*:*'] ['UDP', '127.0.0.1:123', '*:*'] ['UDP', '127.0.0.1:1039', '*:*'] ['UDP', '127.0.0.1:1900', '*:*'] ['UDP', '172.16.0.2:123', '*:*'] ['UDP', '172.16.0.2:137', '*:*'] ['UDP', '172.16.0.2:138', '*:*'] ['UDP', '172.16.0.2:1900', '*:*'] ['UDP', '192.168.0.250:123', '*:*'] ['UDP', '192.168.0.250:137', '*:*'] ['UDP', '192.168.0.250:138', '*:*'] ['UDP', '192.168.0.250:1900', '*:*'] I'll mess around with the rest of it later tonite. > Eric, > > First, I suggest you read the output of popen directly, you don't have > to pipe it to a temp file. If you read it by lines, then you can > process each line looking for the data you want. > > For example: > >>> import os > >>> o=os.popen('netstat -an') > >>> for l in o: > ... print l, > ... > > Active Connections > > Proto Local Address Foreign Address State > TCP 0.0.0.0:25 0.0.0.0:0 LISTENING > TCP 0.0.0.0:135 0.0.0.0:0 LISTENING > TCP 0.0.0.0:445 0.0.0.0:0 LISTENING > TCP 0.0.0.0:1052 0.0.0.0:0 LISTENING > etc... > >>> o.close() > > Next you probably want to split() the line to divide it into fields. > Then you can look at the specific fields. You might be able to use > endswith() or find() to search for the port; in my example > endswith(':25') for example would find the line with port 25. The > details depend on what your data looks like. > > Give this a try and let us know how far you get. Also it would be > helpful to see an example of the output of netstat on your computer, > it is different on Windows and MacOSX. > > Kent From s.varun at gmail.com Thu Sep 9 20:37:42 2004 From: s.varun at gmail.com (Varun Soundararajan) Date: Thu Sep 9 20:37:48 2004 Subject: [Tutor] Doubt in RPC XML lib Message-ID: <32b5ee7604090911376994ad31@mail.gmail.com> I hv attached the two files. Actually what i am trying to do is that, i replicate the gethosts.py and servers.py code in every system. in every system when i start my python code, i check all servers of the same type and add to my active hosts list. ( i do taht in gethosts.py) in the servers.py, i serve my own server at 10001 and rpc server at 8000 using thread. My server at 10001 authenticates with other server of my type by sending some hashed data and getting it back (just to ensure that i am not adding some other server listening at 10001). Now my qn is, if i want to access a code i call: server.somefunction() now since i have the list of functions of form (['1.fn1', '1.fn2','2.fn1' etc] ) when i want to call the fn1 of server 0 i shd call hosts_server_access[0].fn1() . but i want the user to choose that. Now how do i do that. in other words. if i wanna call fn1 of server 0 i shd be able to call(say) hosts_server_access[0][1]() or something like that. pls help thanks in advance -Varun -------------- next part -------------- import ConfigParser import xmlrpclib import md5 import socket class Hosts: """ Hosts: On instantiating, the object reads from file hosts.ini and finds all live hosts""" hostlist=[] alivehosts=[] PORT=10001 hosts_functions=[] hosts_server_access=[] def __init__(self): self.hostlist=self.gethosts("hosts.ini") for host in self.hostlist: if self.isAlive(host,self.PORT): self.alivehosts.append(host) def __str__(self): return str(self.alivehosts) def gethosts(self,filename): """ Gets a list of hostnames from the file <i>fFilename</i>. returns a list of hosts declared in the filename """ f=open(filename) configobj=ConfigParser.ConfigParser() configobj.readfp(f) hosts=[] values=configobj.items("hosts") for i in configobj.options("hosts"): hosts.append(configobj.get("hosts",i)) return hosts def isAlive(self,HOST,PORT): """ Checks if the particular host <i> hostname</i>is alive and running at port <i>port</i> Todo: send some arbitrary encrypted string accepted only if that server is of my type """ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.setdefaulttimeout(0.5) try: s.connect((HOST, PORT)) m=md5.new() m.update(socket.gethostbyname(socket.gethostname())) s.send(m.hexdigest()) recvdata=s.recv(1024) #i send and receive the same data #just to ensure that i am recognizing #a server of my type. Cant help if #some custom server listens to same port #and sends back the received data #without changing the data if recvdata == m.hexdigest(): return True else: return False except socket.error, msg: s.close() return False def updateFunctionList(self): """ Updates hosts_functions list with the list of functions avaliable in live servers """ self.hosts_functions=[] for host in range(0,len(self.alivehosts)): hostname="http://"+self.alivehosts[host]+":8000" #print "hostname=",hostname server=xmlrpclib.ServerProxy(uri=hostname) self.hosts_server_access.append(server) #print server.system.listMethods() fnlist=[] fnlist=server.system.listMethods() for fn in fnlist: apdata="%d.%s" %(host,fn) self.hosts_functions.append(apdata) return self.hosts_functions def access_list(self): return self.hosts_server_access if __name__=="__main__": hosts=Hosts() print hosts.updateFunctionList() -------------- next part -------------- import socket import threading from SimpleXMLRPCServer import * import md5 def myserver(): HOST = 'localhost' # Symbolic name meaning the local host PORT = 10001 # Arbitrary non-privileged port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) while 1: s.listen(1) conn, addr = s.accept() print 'Connected by', addr data = conn.recv(1024) if not data: pass conn.send(data) conn.close() print "Connection closed" def MyRPCServer(): server = SimpleXMLRPCServer(("localhost", 8000)) server.register_function(pow) server.register_function(lambda x,y: x+y, 'add') server.register_introspection_functions() # server.register_instance(MyFuncs()) print server.system_listMethods() server.serve_forever() if __name__=="__main__": mys=threading.Thread(target=myserver) rpcs=threading.Thread(target=MyRPCServer) mys.start() rpcs.start() From dyoo at hkn.eecs.berkeley.edu Thu Sep 9 21:56:13 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Sep 9 21:56:18 2004 Subject: [Tutor] What's EOF? In-Reply-To: <6.1.0.6.0.20040909140925.028755c8@mail4.skillsoft.com> Message-ID: <Pine.LNX.4.44.0409091254080.19699-100000@hkn.eecs.berkeley.edu> On Thu, 9 Sep 2004, Kent Johnson wrote: > End Of File - the condition when no more data is available from a file > or stream. Hi Wenxin, By the way, Eric Raymond's "Jargon File" page is a fun resource for definitions for all those wacky acronyms. Here's the Jargon File's entry on EOF: http://www.catb.org/~esr/jargon/html/E/EOF.html From dyoo at hkn.eecs.berkeley.edu Thu Sep 9 22:06:46 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Sep 9 22:06:50 2004 Subject: [Tutor] xml.dom.minidom key error In-Reply-To: <1094604062.413e551e9b1a9@www-mail.usyd.edu.au> Message-ID: <Pine.LNX.4.44.0409091257460.19699-100000@hkn.eecs.berkeley.edu> On Wed, 8 Sep 2004, Ajay wrote: > i am parsing the attached document. > the code is > > from xml.sax import make_parser > from xml.dom.minidom import parse > parser = make_parser('xml.sax.drivers2.drv_xmlproc') > ruleSet = parse(ruleSetFile, parser=parser) Hi Ajay, Hmmm... I haven't had time to look at this yet! Has anyone answered you about this? You may want to resend your question to the python-XML mailing list and see if anyone there can help with it. I may have some time later, but you may not want to wait for me... *grin* Here's the URL for the Python-XML mailing list: http://mail.python.org/mailman/listinfo/xml-sig Try to ask your question there; you may get better responses there. To help debug the problem, we need that 'ruleSetFile', or at least a small subset of it, since the problem appears sensitive to the XML content. In fact, the error that you're getting: > File > "C:\PYTHON23\Lib\site-packages\_xmlplus\sax\drivers2\drv_xmlproc.py", lin > e 368, in handle_start_tag > AttributesNSImpl(attrs, rawnames)) > File "C:\PYTHON23\Lib\site-packages\_xmlplus\dom\pulldom.py", line 98, in > star > tElementNS > prefix = self._current_context[a_uri] > KeyError: u'http://www.w3.org/2001/02/appelv1' looks really funky, and looks like it might have to do with XML namespaces. I'm not sure about this, but it may even be a bug in the pulldom module. We can't be sure until we trace the problem down. And for that, it'll really help if we can use that ruleSetFile to test the parser out. When you resend them your question, either attach your 'ruleSetFile' to the message if it's small, or post the 'ruleSetFile' on the web where someone can use it to investigate the problem. Good luck to you! From learning.python at dbmail.dk Thu Sep 9 23:23:04 2004 From: learning.python at dbmail.dk (Ole Jensen) Date: Fri Sep 10 01:38:51 2004 Subject: [Tutor] What's EOF? References: <1094749329.41408c91a876d@webmail.bath.ac.uk> <1094752729.414099d907573@webmail.bath.ac.uk> Message-ID: <003001c496b3$31ebb5e0$92c48f52@allmycore> ----- Original Message ----- From: "W X Liu" Subject: [Tutor] What's EOF? > read_all( ) > > Read all data until EOF; block until connection closed. > > > So, what's EOF? > A google search for that subject http://www.google.com/search?q=%22what+is+EOF%22&hl=en&btnG=Google+Search reveals it to be EndOfFile From bvande at po-box.mcgill.ca Fri Sep 10 01:44:59 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Fri Sep 10 01:46:33 2004 Subject: [Tutor] list copy and remove question Message-ID: <4140EAFB.7010304@po-box.mcgill.ca> Hi all, I'm back to Python after long enough of an interruption to make me feel a bit like a fresh-faced newbie again. I've read around in the docs and done a bit of google, but haven't managed to understand: Python 2.3.4 (#53, May 25 2004, 21:17:02) >>> r = [1, 2, 3] >>> s = r[:].remove(2) >>> print s None >>> t = r[:] >>> t.remove(2) >>> print t [1, 3] >>> Both times I expected the second procedure's result. I get that remove modifies in place, but it seems to me like the condensed version should work. My thinking is that it first creates a copy, then modifies the copy in place, then assigns the modified copy to s. But it would seem that that's not what happens. The 2 questions then are: why doesn't the first way work?, and, in the first way, from what (if anything) is 2 being removed? Pointers to the doc's explanation that I must have overlooked are welcome. Thanks and best to all, Brian vdB From pythonTutor at venix.com Fri Sep 10 02:47:41 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Fri Sep 10 02:47:55 2004 Subject: [Tutor] list copy and remove question In-Reply-To: <4140EAFB.7010304@po-box.mcgill.ca> References: <4140EAFB.7010304@po-box.mcgill.ca> Message-ID: <1094777260.4551.3.camel@laptop.venix.com> On Thu, 2004-09-09 at 19:44, Brian van den Broek wrote: > Hi all, > > I'm back to Python after long enough of an interruption to make me feel a > bit like a fresh-faced newbie again. > > I've read around in the docs and done a bit of google, but haven't managed > to understand: > > Python 2.3.4 (#53, May 25 2004, 21:17:02) > >>> r = [1, 2, 3] > >>> s = r[:].remove(2) > >>> print s > None > >>> t = r[:] > >>> t.remove(2) > >>> print t > [1, 3] > >>> > > Both times I expected the second procedure's result. I get that remove > modifies in place, but it seems to me like the condensed version should > work. My thinking is that it first creates a copy, then modifies the copy > in place, then assigns the modified copy to s. That would happen if remove returned self. However, it returns None. So s is set to None. 2 is removed from r[:], but that object is no longer accessible since it is not bound to any name. > But it would seem that > that's not what happens. > > The 2 questions then are: why doesn't the first way work?, and, in the > first way, from what (if anything) is 2 being removed? > > Pointers to the doc's explanation that I must have overlooked are welcome. > > Thanks and best to all, > > Brian vdB > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From kent_johnson at skillsoft.com Fri Sep 10 03:44:47 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Sep 10 03:45:28 2004 Subject: [Tutor] Network programming In-Reply-To: <1094717689.4427.10.camel@linux.site> References: <1094473155.4233.23.camel@linux.site> <6.1.0.6.0.20040907085123.02869dd8@mail4.skillsoft.com> <1094717689.4427.10.camel@linux.site> Message-ID: <6.1.0.6.0.20040909180124.0297de28@mail4.skillsoft.com> Johan, It looks to me like your program will get stuck in the inner while loop. There is no way inside this loop to get a new value for indata or outdata. There are two approaches you could use to solve your problem - either put the two sides of the transfer into separate threads, or use some kind of polling to look for data available on either socket. The thread approach usually uses three threads: - a master thread that listens to the server socket and accepts the incoming connection. It then opens the forwarding socket and spawns two forwarding threads. - the forwarding threads read from one socket and write to another. They are symmetric - one thread reads from socket A and writes to socket B; the other thread reads from socket B and writes to socket A. Each thread uses blocking I/O - the master thread blocks on socket.accept(); the forwarding threads block on socket.recv(). A simple example that uses the treaded approach to do something similar to what you want to do is here: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/114642 In this case the Pinhole class is the master thread; when it gets a connection it creates two PipeThreads to do the reading and writing. The polling approach uses non-blocking I/O. In it's crudest form its loop looks like this: forever: if data available on socket A: read from socket A write to socket B if data available on socket B: read from socket B write to socket A sleep for a bit This is crude because it is either unresponsive (if the sleep is long) or wasteful of CPU (if the sleep is short and there is not much to do). It might be fine for a simple use with just one connection, though. The Python asyncore and asynchat modules use a more sophisticated version of this; instead of sleeping, they use a system call that blocks until there is activity on any of the sockets it is watching. This is very efficient, as the polling loop only wakes up when there is something for it to do. Medusa <http://www.nightmare.com/medusa/index.html> and Twisted <http://www.twistedmatrix.com/> are two servers that are based on this approach. It can be more efficient for large numbers of connections because it doesn't have to create a thread for each one. asyncore and asynchat hide the actual polling loop from you. You interact with them by defining callback methods that get called when data is available or when a channel is available for writing. This tutorial is a good introduction to this approach. The proxy server at the end is similar to what you are trying to do. http://www.nightmare.com/medusa/programming.html Medusa includes a chat server which is also similar to your application. I hope this helps get you on the right track! Kent At 10:14 AM 9/9/2004 +0200, Johan Geldenhuys wrote: >I still have trouble when I want to send data out as soon as it comes in >from one side. >My server listens and accepts the calls and then builds the client >connection to the destination. Please see if you can assist. > >Thanks > >Johan >#################################################### > ># we have an incoming socket connect > newConn, addr = self._serverSocket.accept() > self.log('Connection received from: %s:%s' % addr) > > #while connection is active on server: > while 1: > #self._ne1_id = '1234' > #self._ne2_id = '1111' > > indata = newConn.recv(8192) > self.log('First Data received from LCT:' + > `indata`) > > if '\xff' in indata: > continue > > if '\x01' in indata: > continue > > #Look for string of 1234 in indata: > if indata[0:4] == self._ne1_id: > self.log('indata 0:4 is:' + `indata[0:4]`) > self.sock = socket(AF_INET, SOCK_STREAM) > > #connect to this destination if the string is > 1234 > self.sock.connect((self._ne1_ip, > self._ne1_port)) # This is previously defined > self.log('Connection established to NE1: > %s:%i' % (self._ne1_ip, self._ne1_port)) > outdata = self.sock.recv(8192) > #when connection to destination is up: > while 1: > if indata: > self.sock.send(indata) > self.log('indata send to NE, line > 106: ' + `indata`) > > # If break sequence is received from > server side, close the client connection > if '\x11' in indata: > self.log('Break character received') > break > self.sock.close() > self.log('connection to NE1 now closed') > > if oudata: > newConn.send(outdata) > self.log('Data from NE:' + `outdata`) >########################################################### > > > > > > > > > > > >On Tue, 2004-09-07 at 14:58, Kent Johnson wrote: >> >> >>We might be better able to help if you post your code. >> >>Here is a list of HTTP proxy servers written in Python, you might find >>something helpful there: >><http://xhaus.com/alan/python/proxies.html>http://xhaus.com/alan/python/proxies.html >> >>Kent >> >>At 02:19 PM 9/6/2004 +0200, Johan Geldenhuys wrote: >> >Hi, >> > >> >I am new to Python and would like to know more about network programming >> >in particilar. >> > >> >I have a script that sets up a socket server and must wait for incoming >> >connections. Once a call has been accepted, it must make another socket >> >connection to a destination. >> > >> >Now, I want to let these two "talk" to each other. Once the server >> >receives data it must be send out to the destination and when the >> >destination has data, it must be send out to the connection that made the >> >first call to the server. >> > >> >Does anybody have any examples or tips on how I can let this happen. My >> >calls work for the first batch of data and then when new data is received, >> >the calls break. >> > >> >Thanks >> > >> >-- >> > Johan Geldenhuys >> >Access Telecommunication Systems >> > Mail to: johan@accesstel.co.za >> >-- >> >This message has been scanned for viruses and >> >dangerous content by >> <<http://www.azitech.co.za>http://www.azitech.co.za>Azitech, and is >> >believed to be clean. >> >_______________________________________________ >> >Tutor maillist - Tutor@python.org >> ><http://mail.python.org/mailman/listinfo/tutor>http://mail.python.org/ma >> ilman/listinfo/tutor > > > > > >-- > Johan Geldenhuys >Access Telecommunication Systems > Mail to: johan@accesstel.co.za > >-- >This message has been scanned for viruses and >dangerous content by <http://www.azitech.co.za>Azitech, and is >believed to be clean. From isrgish at fastem.com Fri Sep 10 04:20:46 2004 From: isrgish at fastem.com (Isr Gish) Date: Fri Sep 10 04:20:58 2004 Subject: [Tutor] String Formatting Message-ID: <20040910022056.049551E4008@bag.python.org> Hi, How can I format a integer in a format string with a comma for example print 'Your Account has %f' %amount That should print: Your Account has 1,000.00 Thanks Isr From orbitz at ezabel.com Fri Sep 10 04:55:22 2004 From: orbitz at ezabel.com (orbitz) Date: Fri Sep 10 04:55:39 2004 Subject: [Tutor] String Formatting In-Reply-To: <20040910022056.049551E4008@bag.python.org> References: <20040910022056.049551E4008@bag.python.org> Message-ID: <4141179A.8070705@ezabel.com> Easiest way would probably be using locale.format in some code I do: oldloc = locale.setlocale(locale.LC_ALL) locale.setlocale(locale.LC_ALL, 'en_US') locale.format('%d', some_num, True) locale.setlocale(locale.LC_ALL, oldloc) Isr Gish wrote: >Hi, > >How can I format a integer in a format string with a comma for example >print 'Your Account has %f' %amount >That should print: >Your Account has 1,000.00 > >Thanks >Isr > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > > From bvande at po-box.mcgill.ca Fri Sep 10 06:11:13 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Fri Sep 10 06:12:23 2004 Subject: [Tutor] list copy and remove question In-Reply-To: <1094777260.4551.3.camel@laptop.venix.com> References: <4140EAFB.7010304@po-box.mcgill.ca> <1094777260.4551.3.camel@laptop.venix.com> Message-ID: <41412961.6060400@po-box.mcgill.ca> Lloyd Kvam said unto the world upon 2004-09-09 20:47: > On Thu, 2004-09-09 at 19:44, Brian van den Broek wrote: <SNIP> >>Python 2.3.4 (#53, May 25 2004, 21:17:02) >> >>> r = [1, 2, 3] >> >>> s = r[:].remove(2) >> >>> print s >>None >> >>> t = r[:] >> >>> t.remove(2) >> >>> print t >>[1, 3] >> >>> >> >>Both times I expected the second procedure's result. I get that remove >>modifies in place, but it seems to me like the condensed version should >>work. My thinking is that it first creates a copy, then modifies the copy >>in place, then assigns the modified copy to s. > > > That would happen if remove returned self. However, it returns None. > So s is set to None. 2 is removed from r[:], but that object is no > longer accessible since it is not bound to any name. Hi Lloyd, Slap! (Sound of palm to forehead.) Thanks, Brian From s4046441 at student.uq.edu.au Fri Sep 10 08:02:20 2004 From: s4046441 at student.uq.edu.au (Ms Soo Chong) Date: Fri Sep 10 08:02:28 2004 Subject: [Tutor] question Message-ID: <41507e4127d6.4127d641507e@uq.edu.au> Hi, Can someone please help me by going through my python script + html script and see if I have done something stupid, because I can't get it running on the web browser. I did used import cgitb; cgitb.enable() and it showed the follwing error. ------------------------------------------------------- Server error! The server encountered an internal error and was unable to complete your request. Error message: Premature end of script headers: trial1.html If you think this is a server error, please contact the webmaster Error 500 localhost Fri 10 Sep 2004 15:57:51 EST Apache/2.0.40 (Red Hat Linux) ------------------------------------------------------- I know this it kinda of long so please ignored it if you don't have time but hopefully there are kind soul around to help me. Thanks for any help, it is greatly appreciated. Shufen -------------- next part -------------- A non-text attachment was scrubbed... Name: trial1.py Type: application/octet-stream Size: 2540 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20040910/dcaca879/trial1.obj -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040910/dcaca879/trial1.html From eric at digitalert.net Fri Sep 10 10:31:31 2004 From: eric at digitalert.net (Eric) Date: Fri Sep 10 10:30:33 2004 Subject: [Tutor] Search text file, perform action if a given item found in file In-Reply-To: <4140A038.9040504@digitalert.net> References: <414019B2.8080807@digitalert.net> <41401B8C.1000708@digitalert.net> <6.1.0.6.0.20040909081224.028926a0@mail4.skillsoft.com> <4140A038.9040504@digitalert.net> Message-ID: <41416663.5080809@digitalert.net> I'm still new to this so please bare with me. I have spent a few hours searching google, and trying different combinations and can't seem to figure out how to use endswith() to search a list, and to then take a action. In my case I would want to search through "l.split()[1:2]" for the port number, and from there depending on if it finds a match it would go through a if-else statement, and then loop back to he start to continue monitoring. I think I can handle the second part, but searching a list, and taking a action based on that search is somehting that I am having a hard time grasping. Any help would be greatly greatly appreciated. This is the output of print l.split()[1:2] [] ['Connections'] [] ['Local'] ['0.0.0.0:135'] ['0.0.0.0:445'] ['127.0.0.1:1028'] ['127.0.0.1:1067'] ['127.0.0.1:1068'] ['127.0.0.1:1205'] ['127.0.0.1:1206'] ['172.16.0.2:139'] ['192.168.0.250:139'] ['192.168.0.250:1158'] ['192.168.0.250:1159'] ['192.168.0.250:1507'] ['0.0.0.0:445'] ['0.0.0.0:500'] ['0.0.0.0:4500'] ['127.0.0.1:123'] ['127.0.0.1:1057'] ['127.0.0.1:1900'] ['172.16.0.2:123'] ['172.16.0.2:137'] ['172.16.0.2:138'] ['172.16.0.2:1900'] ['192.168.0.250:123'] ['192.168.0.250:137'] ['192.168.0.250:138'] ['192.168.0.250:1900'] >> >> Next you probably want to split() the line to divide it into fields. >> Then you can look at the specific fields. You might be able to use >> endswith() or find() to search for the port; in my example >> endswith(':25') for example would find the line with port 25. The >> details depend on what your data looks like. >> >> Give this a try and let us know how far you get. Also it would be >> helpful to see an example of the output of netstat on your computer, >> it is different on Windows and MacOSX. >> >> Kent > From bvande at po-box.mcgill.ca Fri Sep 10 11:05:25 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Fri Sep 10 11:08:46 2004 Subject: [Tutor] sentence case module for comments and possible cookbook submission Message-ID: <41416E55.9080903@po-box.mcgill.ca> Hi all, earlier today, I needed to change some ALL CAPS text to sentence case. To my surprise, searching the docs, the Cookbook, and a browse of the 70+ google hits for: Python "sentence case" turned up nothing. I've produced something that I think works. But, as regular readers of the list might know, I'm still learning. I'd appreciate any comments on it. I realize it is a bit long, but I intend to refine and submit to the cookbook. (Unless the likely "But what about using X instead?" comments are forthcoming. :-) If for some reason you comment but don't want to be mentioned should I post to the cookbook, please let me know. Also, I still can't believe I'm not reinventing the wheel. If there is something available, I couldn't find it. So, if you know, I'd be happy to hear. Thanks and best to all, Brian vdB #! /usr/bin/env python # sentence_caser.py # Version 0.1 # Brian van den Broek # bvande@po-box.mcgill.ca # This module is released under the Python License. (See www.python.org.) punctuation_indexes = {} punctuation = ['!', '?'] def punctuation_stripper(data_string): '''punctuation_stripper(data_string) -> data_string Stores the indexes of each type of punctuation (other than '.') in the punctuation_indexes dict and replaces them with '.'s. (This makes splitting the string easier, and, thanks to the dict, is reversible.)''' for mark in punctuation: punctuation_indexes[mark] = [] offset = 0 while True: try: i = data_string.index(mark, offset) punctuation_indexes[mark].append(i) offset = i + 1 except ValueError: break data_string = data_string.replace(mark, '.') return data_string def change_to_sentence_case(sentence_list): '''change_to_sentence_case(sentence_list) -> cap_sentences_list Takes a list of sentence strings and transforms it so that the first and only the first) letter is capitalized. It is a bit more complicated than just calling the capitalize string method as the strings in the sentence list may well start with ' ', '(', '[', etc. The while loop travels the string, looking for the first letter and calling capitalize on the substring it commences. restore_Is() is also called, in an attempt to undo lower-casing of the pronoun "I".''' cap_sentences_list = [] for s in sentence_list: offset = 0 while offset < len(s): if s[offset].isalpha(): s = s[:offset] + s[offset:].capitalize() break offset += 1 s += '.' s = restore_Is(s) cap_sentences_list.append(s) return cap_sentences_list def restore_Is(sentence): '''restore_Is(sentence) -> sentence Takes a sentence string and tries to restore any "I"s incorrectly changed to "i"s by change_to_sentence_case()'s use of .capitalize().''' sentence = sentence.replace(' i ', ' I ') sentence = sentence.replace(' i,', ' I,') sentence = sentence.replace(' i.', ' I.') return sentence def restore_punctuation(data_sentences): '''restore_punctuation(data_sentences) -> data_sentences Consulting the punctuation_indexes dict, restore_punctuation() reverts non '.' punctuation that was changed to '.' to facilitate splitting the string.''' for mark in punctuation: for i in punctuation_indexes[mark]: data_sentences = data_sentences[:i] + mark + data_sentences[i + 1:] return data_sentences def sentence_caser(data_string): '''sentence_caser(data_string) -> data_string Takes a string and returns it into sentence case (it is hoped). To do so, it runs it through various helper functions. sentence_caser() does almost no work on its own; consult the functions punctuation_stripper(), change_to_sentence_case(), and restore_punctuation() for details of the processing.''' working_data = punctuation_stripper(data_string) data_sentences_list = working_data.split('.') data_sentences_list = change_to_sentence_case(data_sentences_list) data_sentences = ''.join(data_sentences_list) data_sentences = restore_punctuation(data_sentences) data_sentences = data_sentences[:len(data_string)] # To remove possibly spurious trailing '.' added when original string ended # with non-'.' character (as in data below). return data_sentences if __name__ == '__main__': data = '''STRINGS IN ALL CAPS ARE HARD TO READ! SOME PEOPLE THINK THEY ARE LIKE SHOUTING. DO YOU THINK SO? I ONLY WRITE THEM WHEN I HAVE A CAPS-LOCK ACCIDENT. (OR WHEN CREATING TEST DATA.) THEY ARE NO FUN. (OK, ENOUGH NOW.)''' print data print print sentence_caser(data) From bvande at po-box.mcgill.ca Fri Sep 10 11:22:02 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Fri Sep 10 11:22:40 2004 Subject: [Tutor] Search text file, perform action if a given item found in file In-Reply-To: <41416663.5080809@digitalert.net> References: <414019B2.8080807@digitalert.net> <41401B8C.1000708@digitalert.net> <6.1.0.6.0.20040909081224.028926a0@mail4.skillsoft.com> <4140A038.9040504@digitalert.net> <41416663.5080809@digitalert.net> Message-ID: <4141723A.5030003@po-box.mcgill.ca> Eric said unto the world upon 2004-09-10 04:31: > I'm still new to this so please bare with me. I have spent a few hours > searching google, and trying different combinations > and can't seem to figure out how to use endswith() to search a list, and > to then take a action. In my case I would want to search through > "l.split()[1:2]" for > the port number, and from there depending on if it finds a match it > would go through a if-else statement, and then loop back > to he start to continue monitoring. I think I can handle the second > part, but searching a list, and taking a action based on that search is > somehting > that I am having a hard time grasping. Any help would be greatly greatly > appreciated. > > > > This is the output of print l.split()[1:2] > > [] > ['Connections'] > [] > ['Local'] > ['0.0.0.0:135'] > ['0.0.0.0:445'] > ['127.0.0.1:1028'] > ['127.0.0.1:1067'] > ['127.0.0.1:1068'] > ['127.0.0.1:1205'] > ['127.0.0.1:1206'] > ['172.16.0.2:139'] > ['192.168.0.250:139'] > ['192.168.0.250:1158'] > ['192.168.0.250:1159'] > ['192.168.0.250:1507'] > ['0.0.0.0:445'] > ['0.0.0.0:500'] > ['0.0.0.0:4500'] > ['127.0.0.1:123'] > ['127.0.0.1:1057'] > ['127.0.0.1:1900'] > ['172.16.0.2:123'] > ['172.16.0.2:137'] > ['172.16.0.2:138'] > ['172.16.0.2:1900'] > ['192.168.0.250:123'] > ['192.168.0.250:137'] > ['192.168.0.250:138'] > ['192.168.0.250:1900'] > > >>> >>> Next you probably want to split() the line to divide it into fields. >>> Then you can look at the specific fields. You might be able to use >>> endswith() or find() to search for the port; in my example >>> endswith(':25') for example would find the line with port 25. The >>> details depend on what your data looks like. >>> >>> Give this a try and let us know how far you get. Also it would be >>> helpful to see an example of the output of netstat on your computer, >>> it is different on Windows and MacOSX. >>> >>> Kent >> Hi Eric, I haven't followed your thread, so I might be missing the level needed. But: Then, iterate over the list of strings, checking if your endswith condition is met, and, if so, do your stuff. A silly example: >>> months = ['January', 'February', 'March', 'April', 'May', 'June', 'July'] >>> y_count = 0 >>> for m in months: if m.endswith('y'): y_count += 1 print 'Got', y_count, 'y-months so far' Got 1 y-months so far Got 2 y-months so far Got 3 y-months so far Got 4 y-months so far >>> From kent_johnson at skillsoft.com Fri Sep 10 12:02:13 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Sep 10 12:02:18 2004 Subject: [Tutor] Search text file, perform action if a given item found in file In-Reply-To: <41416663.5080809@digitalert.net> References: <414019B2.8080807@digitalert.net> <41401B8C.1000708@digitalert.net> <6.1.0.6.0.20040909081224.028926a0@mail4.skillsoft.com> <4140A038.9040504@digitalert.net> <41416663.5080809@digitalert.net> Message-ID: <6.1.0.6.0.20040910055620.0296f1b8@mail4.skillsoft.com> Eric, l.split()[1:2] gives a list containing a string, rather than a bare string, so endswith() won't work on it. You should use l.split()[1] instead: >>> l='a b c' >>> l.split() ['a', 'b', 'c'] >>> l.split()[1:2] ['b'] That is a list containing a string so endswith won't work >>> l.split()[1:2].endswith('b') Traceback (most recent call last): File "<stdin>", line 1, in ? AttributeError: 'list' object has no attribute 'endswith' >>> l.split()[1] 'b' Now it's just a string and split works fine >>> l.split()[1].endswith('b') True Then you will need a string containing the port number preceded by a colon. You can do this with ':' + str(port) Finally, put an if statement inside your loop to test for the port string and do something with it. Brian's post shows how to do that. Kent At 04:31 AM 9/10/2004 -0400, Eric wrote: >I'm still new to this so please bare with me. I have spent a few hours >searching google, and trying different combinations >and can't seem to figure out how to use endswith() to search a list, and >to then take a action. In my case I would want to search through >"l.split()[1:2]" for >the port number, and from there depending on if it finds a match it would >go through a if-else statement, and then loop back >to he start to continue monitoring. I think I can handle the second part, >but searching a list, and taking a action based on that search is somehting >that I am having a hard time grasping. Any help would be greatly greatly >appreciated. > > > >This is the output of print l.split()[1:2] > >[] >['Connections'] >[] >['Local'] >['0.0.0.0:135'] >['0.0.0.0:445'] >['127.0.0.1:1028'] >['127.0.0.1:1067'] >['127.0.0.1:1068'] >['127.0.0.1:1205'] >['127.0.0.1:1206'] >['172.16.0.2:139'] >['192.168.0.250:139'] >['192.168.0.250:1158'] >['192.168.0.250:1159'] >['192.168.0.250:1507'] >['0.0.0.0:445'] >['0.0.0.0:500'] >['0.0.0.0:4500'] >['127.0.0.1:123'] >['127.0.0.1:1057'] >['127.0.0.1:1900'] >['172.16.0.2:123'] >['172.16.0.2:137'] >['172.16.0.2:138'] >['172.16.0.2:1900'] >['192.168.0.250:123'] >['192.168.0.250:137'] >['192.168.0.250:138'] >['192.168.0.250:1900'] > > >>> >>>Next you probably want to split() the line to divide it into fields. >>>Then you can look at the specific fields. You might be able to use >>>endswith() or find() to search for the port; in my example >>>endswith(':25') for example would find the line with port 25. The >>>details depend on what your data looks like. >>> >>>Give this a try and let us know how far you get. Also it would be >>>helpful to see an example of the output of netstat on your computer, it >>>is different on Windows and MacOSX. >>> >>>Kent >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From Q852913745 at aol.com Fri Sep 10 13:17:50 2004 From: Q852913745 at aol.com (Q852913745@aol.com) Date: Fri Sep 10 13:18:03 2004 Subject: [Tutor] An old newbies "escape sequence" confusion Message-ID: <190.2e873c6d.2e72e75e@aol.com> I am just beginning to learn Python from: "Python programming for the absolute beginner" In the first few pages I am already confused. The following escape sequences do not appear to be recognised \a \b \f \r \v they all produce a small square on the screen. I have tried the version of Python supplied with the book, Python-2.2.3.exe and have also tried Python-2.3.4.exe. I am installing on Windows XP Home, both produce the same results even when pasting source code samples supplied from the book cd. I am "just" beginning so simple answers would be appreciated! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040910/25ad67f4/attachment.htm From nick at javacat.f2s.com Fri Sep 10 13:37:39 2004 From: nick at javacat.f2s.com (Nick Lunt) Date: Fri Sep 10 13:34:08 2004 Subject: [Tutor] An old newbies "escape sequence" confusion In-Reply-To: <190.2e873c6d.2e72e75e@aol.com> Message-ID: <FBEKICNGPAKNIMBBNHGKIEJKCBAA.nick@javacat.f2s.com> Hi, it appears to be an issue with 'idle'. Have you tried it with pythonwin http://www.python.org/windows/pythonwin/ ? Here's what I get with idle: >>> l = ['\a','\b','\f','\r','\w'] >>> l ['\x07', '\x08', '\x0c', '\r', '\\w'] >>> for i in l: print i \w >>> and here's what I get with pythonwin: >>> l = ['\a','\b','\f','\r','\w'] >>> l ['\x07', '\x08', '\x0c', '\r', '\\w'] >>> for i in l: ... print i ... BEL BS FF \w >>> I had to write in the BEL, BS and FF sequences cos outlook turned them into squares, same as idle did. Hope that helps a bit Nick. -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On Behalf Of Q852913745@aol.com Sent: 10 September 2004 12:18 To: tutor@python.org Subject: [Tutor] An old newbies "escape sequence" confusion I am just beginning to learn Python from: "Python programming for the absolute beginner" In the first few pages I am already confused. The following escape sequences do not appear to be recognised \a \b \f \r \v they all produce a small square on the screen. I have tried the version of Python supplied with the book, Python-2.2.3.exe and have also tried Python-2.3.4.exe. I am installing on Windows XP Home, both produce the same results even when pasting source code samples supplied from the book cd. I am "just" beginning so simple answers would be appreciated! --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.759 / Virus Database: 508 - Release Date: 09/09/2004 -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040910/cb7ea0c4/attachment.html From MLists at romulo.de Fri Sep 10 13:49:21 2004 From: MLists at romulo.de (Rainer Mansfeld) Date: Fri Sep 10 13:50:05 2004 Subject: [Tutor] Unicode Problem In-Reply-To: <41416E55.9080903@po-box.mcgill.ca> References: <41416E55.9080903@po-box.mcgill.ca> Message-ID: <414194C1.50302@romulo.de> Hi tutors, I'm a Python newbie from Germany and in our language we have funny letters like ?, ? and ?. (That would be ä ö and ü in HTML.) Playing around with these, I stumbled upon the following: >>> print u'?', '?' ? ? So print can handle Unicode and non-Unicode. >>> print u'?' + 'a' ?a Concatenation seems to be no problem either, except in some cases: >>> print u'?' + '?' Traceback (most recent call last): File "<interactive input>", line 1, in ? UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128) What's happening here? Can somebody please explain this to me? Thanks in advance Rainer From kent_johnson at skillsoft.com Fri Sep 10 13:53:35 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Sep 10 13:53:38 2004 Subject: [Tutor] Network programming In-Reply-To: <6.1.0.6.0.20040909180124.0297de28@mail4.skillsoft.com> References: <1094473155.4233.23.camel@linux.site> <6.1.0.6.0.20040907085123.02869dd8@mail4.skillsoft.com> <1094717689.4427.10.camel@linux.site> <6.1.0.6.0.20040909180124.0297de28@mail4.skillsoft.com> Message-ID: <6.1.0.6.0.20040910075032.02860ff8@mail4.skillsoft.com> By the way, the book "Python in a Nutshell" has an excellent chapter on socket programming. It shows how to implement a simple echo server using several different methods: bare sockets, SocketServer, bare select, asyncore, asynchat and Twisted. Kent At 09:44 PM 9/9/2004 -0400, Kent Johnson wrote: >Johan, > >It looks to me like your program will get stuck in the inner while loop. >There is no way inside this loop to get a new value for indata or outdata. > >There are two approaches you could use to solve your problem - either put >the two sides of the transfer into separate threads, or use some kind of >polling to look for data available on either socket. From Q852913745 at aol.com Fri Sep 10 16:31:56 2004 From: Q852913745 at aol.com (Q852913745@aol.com) Date: Fri Sep 10 16:32:15 2004 Subject: [Tutor] An old newbies "escape sequence" confusion Message-ID: <7f.4ba7f3f5.2e7314dc@aol.com> In a message dated 10/09/2004 12:35:13 GMT Standard Time, nick@javacat.f2s.com writes: > ... here's what I get with pythonwin: > > >>>l = ['\a','\b','\f','\r','\w'] > >>>l > ['\x07', '\x08', '\x0c', '\r', '\\w'] > >>>for i in l: > ... print i > ... > BEL > BS > FF > > \w > >>> > > I had to write in the BEL, BS and FF sequences cos outlook turned them into > squares, same as idle did. > > Hope that helps a bit > Nick. > > Thanks for the help, pythonwin does recognise the escape sequences although I still don't understand why for example: print "\a" does not sound a beep when run from the script window or interactive window (within the programming environment), but it does beep when run from the command line window outside the programming environment. I may understand later in time. Thanks again. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040910/0aef3d87/attachment.html From isrgish at fastem.com Fri Sep 10 16:34:24 2004 From: isrgish at fastem.com (Isr Gish) Date: Fri Sep 10 16:37:12 2004 Subject: [Tutor] String Formatting Message-ID: <20040910143710.0A1A41E4007@bag.python.org> Thanks orbitz, But... >oldloc = locale.setlocale(locale.LC_ALL) >locale.setlocale(locale.LC_ALL, 'en_US') >locale.format('%d', some_num, True) >locale.setlocale(locale.LC_ALL, oldloc) > I would rather not use this way, iit takes about 25 times longer then a regular % format. And I'm using it for about 1,000,000 times. Isr -----Original Message----- >From: "orbitz"<orbitz@ezabel.com> >Sent: 9/9/04 10:55:22 PM >To: "Isr Gish"<isrgish@fastem.com>, "tutor@python.org"<tutor@python.org> >Subject: Re: [Tutor] String Formatting > >Easiest way would probably be using locale.format in some code I do: > >oldloc = locale.setlocale(locale.LC_ALL) >locale.setlocale(locale.LC_ALL, 'en_US') >locale.format('%d', some_num, True) >locale.setlocale(locale.LC_ALL, oldloc) > > >Isr Gish wrote: > >>Hi, >> >>How can I format a integer in a format string with a comma for example >>print 'Your Account has %f' %amount >>That should print: >>Your Account has 1,000.00 >> >>Thanks >>Isr >> >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor >> >> >> > From orbitz at ezabel.com Fri Sep 10 17:54:00 2004 From: orbitz at ezabel.com (orbitz) Date: Fri Sep 10 17:54:07 2004 Subject: [Tutor] String Formatting In-Reply-To: <20040910143707.C342F4089@mail.ezabel.com> References: <20040910143707.C342F4089@mail.ezabel.com> Message-ID: <4141CE18.1090900@ezabel.com> Your choices then are most likely either using regexp or manually doing it. Isr Gish wrote: >Thanks orbitz, > >But... > > >oldloc = locale.setlocale(locale.LC_ALL) > >locale.setlocale(locale.LC_ALL, 'en_US') > >locale.format('%d', some_num, True) > >locale.setlocale(locale.LC_ALL, oldloc) > > > >I would rather not use this way, iit takes about 25 times longer then a regular % format. And I'm using it for about 1,000,000 times. > >Isr > >-----Original Message----- > >From: "orbitz"<orbitz@ezabel.com> > >Sent: 9/9/04 10:55:22 PM > >To: "Isr Gish"<isrgish@fastem.com>, "tutor@python.org"<tutor@python.org> > >Subject: Re: [Tutor] String Formatting > > > >Easiest way would probably be using locale.format in some code I do: > > > >oldloc = locale.setlocale(locale.LC_ALL) > >locale.setlocale(locale.LC_ALL, 'en_US') > >locale.format('%d', some_num, True) > >locale.setlocale(locale.LC_ALL, oldloc) > > > > > >Isr Gish wrote: > > > >>Hi, > >> > >>How can I format a integer in a format string with a comma for example > >>print 'Your Account has %f' %amount > >>That should print: > >>Your Account has 1,000.00 > >> > >>Thanks > >>Isr > >> > >>_______________________________________________ > >>Tutor maillist - Tutor@python.org > >>http://mail.python.org/mailman/listinfo/tutor > >> > >> > >> > > > > > > From kent_johnson at skillsoft.com Fri Sep 10 18:08:16 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Sep 10 18:08:20 2004 Subject: [Tutor] String Formatting In-Reply-To: <20040910143710.0A1A41E4007@bag.python.org> References: <20040910143710.0A1A41E4007@bag.python.org> Message-ID: <6.1.0.6.0.20040910115837.029fc0d0@mail4.skillsoft.com> I'm always up for an optimization challenge :-) I tried several methods. Other than the locale-based solution, they all work for non-negative integers only. Here is the fastest one I found. It takes about 1/10 the time of the locale version and wouldn't be too hard to modify to work for negative integers also. def commafy(val): ''' Straightforward approach using string slices ''' s = str(val) start = len(s) % 3 chunks = [] if start > 0: chunks.append(s[:start]) for i in range(start, len(s), 3): chunks.append(s[i:i+3]) return ','.join(chunks) Note that much of the time of the locale version is in accessing and switching locales. If you can set the locale once before doing the conversions, it is about 3x faster than the version that sets and restores the locale. Here are all the versions I tried and a timing harness to compare them. The output I get is this: commafy1: 1.052021 secs commafy2: 1.116770 secs commafy3: 1.067124 secs commafy4: 2.469994 secs commafy5: 1.125030 secs commafyLocale: 7.309395 secs commafyLocale2: 3.077568 secs Kent ############################################### # commafy 1 to 3 are all variations on string slice and join def commafy1(val): ''' Straightforward approach using string slices ''' s = str(val) start = len(s) % 3 chunks = [] if start > 0: chunks.append(s[:start]) for i in range(start, len(s), 3): chunks.append(s[i:i+3]) return ','.join(chunks) def commafy2(val): ''' Use list.extend() instead of an append loop ''' s = str(val) start = len(s) % 3 chunks = [] if start > 0: chunks.append(s[:start]) chunks.extend([s[i:i+3] for i in range(start, len(s), 3)]) return ','.join(chunks) def commafy3(val): ''' Use a list comprehension instead of a loop. The initial segment is a problem. ''' s = str(val) start = len(s) % 3 chunks = [s[i:i+3] for i in range(start, len(s), 3)] if start > 0: chunks.insert(0, s[:start]) return ','.join(chunks) def commafy4(val): ''' Iterate over the input and insert the commas directly ''' s = list(str(val)) s.reverse() i = iter(s) result = [] while True: try: result.append(i.next()) result.append(i.next()) result.append(i.next()) result.append(',') except StopIteration: if result[-1] == ',': result.pop() break result.reverse() return ''.join(result) def commafy5(val): ''' Use divmod to make the chunks ''' if val == 0: return '0' chunks = [] while val > 999: val, rem = divmod(val, 1000) chunks.append(str(rem).zfill(3)) chunks.append(str(val)) chunks.reverse() return ','.join(chunks) import locale def commafyLocale(val): ''' Official solution using locale module ''' oldloc = locale.setlocale(locale.LC_ALL) locale.setlocale(locale.LC_ALL, 'en') result = locale.format('%d', val, True) locale.setlocale(locale.LC_ALL, oldloc) return result locale.setlocale(locale.LC_ALL, 'en') # This line speeds up the ABOVE version by 30% ! def commafyLocale2(val): ''' Use locale module but don't change locale ''' result = locale.format('%d', val, True) return result # timing test import timeit def test(f): return [f(10**i) for i in range(11)] correctAnswer = [ '1', '10', '100', '1,000', '10,000', '100,000', '1,000,000', '10,000,000', '100,000,000', '1,000,000,000', '10,000,000,000', ] def timeOne(fn): # First run the function and check that it gets the correct results actualAnswer = test(fn) if actualAnswer != correctAnswer: print fn.__name__, 'does not give the correct answer' print actualAnswer return # Now time it setup = "from __main__ import test, " + fn.__name__ stmt = 'test(%s)' % fn.__name__ t = timeit.Timer(stmt, setup) secs = t.timeit(10000) print '%s: %f secs' % (fn.__name__, secs) fnsToTest = [ commafy1, commafy2, commafy3, commafy4, commafy5, commafyLocale, commafyLocale2, ] for fn in fnsToTest: timeOne(fn) At 10:34 AM 9/10/2004 -0400, Isr Gish wrote: >Thanks orbitz, > >But... > > >oldloc = locale.setlocale(locale.LC_ALL) > >locale.setlocale(locale.LC_ALL, 'en_US') > >locale.format('%d', some_num, True) > >locale.setlocale(locale.LC_ALL, oldloc) > > > >I would rather not use this way, iit takes about 25 times longer then a >regular % format. And I'm using it for about 1,000,000 times. > >Isr > >-----Original Message----- > >From: "orbitz"<orbitz@ezabel.com> > >Sent: 9/9/04 10:55:22 PM > >To: "Isr Gish"<isrgish@fastem.com>, "tutor@python.org"<tutor@python.org> > >Subject: Re: [Tutor] String Formatting > > > >Easiest way would probably be using locale.format in some code I do: > > > >oldloc = locale.setlocale(locale.LC_ALL) > >locale.setlocale(locale.LC_ALL, 'en_US') > >locale.format('%d', some_num, True) > >locale.setlocale(locale.LC_ALL, oldloc) > > > > > >Isr Gish wrote: > > > >>Hi, > >> > >>How can I format a integer in a format string with a comma for example > >>print 'Your Account has %f' %amount > >>That should print: > >>Your Account has 1,000.00 > >> > >>Thanks > >>Isr > >> > >>_______________________________________________ > >>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 jtk at yahoo.com Fri Sep 10 19:16:07 2004 From: jtk at yahoo.com (Jeff Kowalczyk) Date: Fri Sep 10 19:15:51 2004 Subject: [Tutor] write to /dev/stdin during call to posix command? Message-ID: <pan.2004.09.10.17.16.06.556269@yahoo.com> How can I write to /dev/stdin during a call to a posix command? The pdftotext command will write to stdout if given '-' as the output filename, but it lacks the same paramater for reading from stdin. However, using /dev/stdin and directing a file to the input works fine: # pdftotext -layout /dev/stdin - < sample.pdf Reading from stdout with a physical file input is no problem: r,w,e = os.popen3('pdftotext -layout sample.pdf -') w.read() # gives the text string I am looking for But I don't quite understand how I should send a string representing the input pdf (pdfinput) to the version of the command using /dev/stdin: pdfinput = open('sample.pdf','r').read() r,w,e = os.popen3('pdftotext -layout /dev/stdin -') Any ideas? I'm using python-2.3.4, linux. Thanks. Jeff From lonetwin at gmail.com Fri Sep 10 20:40:42 2004 From: lonetwin at gmail.com (Steve) Date: Fri Sep 10 20:40:44 2004 Subject: [Tutor] Unicode Problem In-Reply-To: <414194C1.50302@romulo.de> References: <41416E55.9080903@po-box.mcgill.ca> <414194C1.50302@romulo.de> Message-ID: <5a309bd3040910114022b0cea9@mail.gmail.com> Hi Rainer, A disclaimer first: This is what I have learnt, I could be wrong. Please do correct me if I am. > >>> print u'?', '?' > ? ? > So print can handle Unicode and non-Unicode. Although that is correct, you should remember that python will only treat, as unicode those strings that you prefix with an 'u'. >>> print type(u'?'), type('?') <type 'unicode'> <type 'str'> >>> So, you see here, the print statement thinks that the second '?' is a normal "str". > >>> print u'?' + '?' > Traceback (most recent call last): > File "<interactive input>", line 1, in ? > UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in > position 0: ordinal not in range(128) What is happening here is that, python is trying to 'promote' the second '?' to unicode before doing the concatenation (since the first '?' is an unicode string, the resulting concatenated string would also be unicoded). To do this the print statement tries to decode, what it thinks is an normal ascii str using the default encoding, which well, normally is set to ascii. So; >>> print u'?' + '?' is the equivalent of: >>> print u'?' + '?'.decode('ascii') # what I don't get is why this is called decode ?? when instead you instead probably wanted the behaviour >>> print u'?' + '?'.decode('iso-8859-1') ?? >>> HTH Regards Steve From isrgish at fastem.com Fri Sep 10 23:21:49 2004 From: isrgish at fastem.com (Isr Gish) Date: Fri Sep 10 23:22:08 2004 Subject: [Tutor] String Formatting Message-ID: <20040910212206.9FC431E4007@bag.python.org> Thanks Kent, I'll try it when I get a chence. All the best, Isr -----Original Message----- >From: "Kent Johnson"<kent_johnson@skillsoft.com> >Sent: 9/10/04 12:08:16 PM >To: "tutor@python.org"<tutor@python.org> >Subject: Re: [Tutor] String Formatting > >I'm always up for an optimization challenge :-) I tried several methods. >Other than the locale-based solution, they all work for non-negative >integers only. Here is the fastest one I found. It takes about 1/10 the >time of the locale version and wouldn't be too hard to modify to work for >negative integers also. > >def commafy(val): > ''' Straightforward approach using string slices ''' > s = str(val) > start = len(s) % 3 > > chunks = [] > if start > 0: > chunks.append(s[:start]) > > for i in range(start, len(s), 3): > chunks.append(s[i:i+3]) > > return ','.join(chunks) > >Note that much of the time of the locale version is in accessing and >switching locales. If you can set the locale once before doing the >conversions, it is about 3x faster than the version that sets and restores >the locale. > >Here are all the versions I tried and a timing harness to compare them. The >output I get is this: >commafy1: 1.052021 secs >commafy2: 1.116770 secs >commafy3: 1.067124 secs >commafy4: 2.469994 secs >commafy5: 1.125030 secs >commafyLocale: 7.309395 secs >commafyLocale2: 3.077568 secs > >Kent > >############################################### ># commafy 1 to 3 are all variations on string slice and join >def commafy1(val): > ''' Straightforward approach using string slices ''' > s = str(val) > start = len(s) % 3 > > chunks = [] > if start > 0: > chunks.append(s[:start]) > > for i in range(start, len(s), 3): > chunks.append(s[i:i+3]) > > return ','.join(chunks) > > >def commafy2(val): > ''' Use list.extend() instead of an append loop ''' > s = str(val) > start = len(s) % 3 > > chunks = [] > if start > 0: > chunks.append(s[:start]) > > chunks.extend([s[i:i+3] for i in range(start, len(s), 3)]) > > return ','.join(chunks) > > >def commafy3(val): > ''' Use a list comprehension instead of a loop. The initial > segment is a problem. ''' > s = str(val) > start = len(s) % 3 > > chunks = [s[i:i+3] for i in range(start, len(s), 3)] > if start > 0: > chunks.insert(0, s[:start]) > > return ','.join(chunks) > > >def commafy4(val): > ''' Iterate over the input and insert the commas directly ''' > s = list(str(val)) > s.reverse() > i = iter(s) > result = [] > while True: > try: > result.append(i.next()) > result.append(i.next()) > result.append(i.next()) > result.append(',') > except StopIteration: > if result[-1] == ',': result.pop() > break > result.reverse() > return ''.join(result) > > >def commafy5(val): > ''' Use divmod to make the chunks ''' > if val == 0: return '0' > > chunks = [] > while val > 999: > val, rem = divmod(val, 1000) > chunks.append(str(rem).zfill(3)) > chunks.append(str(val)) > chunks.reverse() > return ','.join(chunks) > > >import locale >def commafyLocale(val): > ''' Official solution using locale module ''' > oldloc = locale.setlocale(locale.LC_ALL) > locale.setlocale(locale.LC_ALL, 'en') > result = locale.format('%d', val, True) > locale.setlocale(locale.LC_ALL, oldloc) > return result > > >locale.setlocale(locale.LC_ALL, 'en') # This line speeds up the ABOVE >version by 30% ! >def commafyLocale2(val): > ''' Use locale module but don't change locale ''' > result = locale.format('%d', val, True) > return result > > ># timing test >import timeit >def test(f): > return [f(10**i) for i in range(11)] > >correctAnswer = [ >'1', >'10', >'100', >'1,000', >'10,000', >'100,000', >'1,000,000', >'10,000,000', >'100,000,000', >'1,000,000,000', >'10,000,000,000', >] > >def timeOne(fn): > # First run the function and check that it gets the correct results > actualAnswer = test(fn) > if actualAnswer != correctAnswer: > print fn.__name__, 'does not give the correct answer' > print actualAnswer > return > > # Now time it > setup = "from __main__ import test, " + fn.__name__ > stmt = 'test(%s)' % fn.__name__ > > t = timeit.Timer(stmt, setup) > secs = t.timeit(10000) > print '%s: %f secs' % (fn.__name__, secs) > > >fnsToTest = [ > commafy1, > commafy2, > commafy3, > commafy4, > commafy5, > commafyLocale, > commafyLocale2, >] > >for fn in fnsToTest: > timeOne(fn) > > >At 10:34 AM 9/10/2004 -0400, Isr Gish wrote: >>Thanks orbitz, >> >>But... >> >> >oldloc = locale.setlocale(locale.LC_ALL) >> >locale.setlocale(locale.LC_ALL, 'en_US') >> >locale.format('%d', some_num, True) >> >locale.setlocale(locale.LC_ALL, oldloc) >> > >> >>I would rather not use this way, iit takes about 25 times longer then a >>regular % format. And I'm using it for about 1,000,000 times. >> >>Isr >> >>-----Original Message----- >> >From: "orbitz"<orbitz@ezabel.com> >> >Sent: 9/9/04 10:55:22 PM >> >To: "Isr Gish"<isrgish@fastem.com>, "tutor@python.org"<tutor@python.org> >> >Subject: Re: [Tutor] String Formatting >> > >> >Easiest way would probably be using locale.format in some code I do: >> > >> >oldloc = locale.setlocale(locale.LC_ALL) >> >locale.setlocale(locale.LC_ALL, 'en_US') >> >locale.format('%d', some_num, True) >> >locale.setlocale(locale.LC_ALL, oldloc) >> > >> > >> >Isr Gish wrote: >> > >> >>Hi, >> >> >> >>How can I format a integer in a format string with a comma for example >> >>print 'Your Account has %f' %amount >> >>That should print: >> >>Your Account has 1,000.00 >> >> >> >>Thanks >> >>Isr >> >> >> >>_______________________________________________ >> >>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 missive at hotmail.com Fri Sep 10 23:16:36 2004 From: missive at hotmail.com (Lee Harr) Date: Fri Sep 10 23:27:42 2004 Subject: [Tutor] Re: question Message-ID: <BAY2-F9CUyZqoG8Zy4V0000588a@hotmail.com> >Can someone please help me by going through my >python script + html script and see if I have done >something stupid, because I can't get it running on >the web browser. I did used import cgitb; >cgitb.enable() and it showed the follwing error. > >------------------------------------------------------- >Server error! > >The server encountered an internal error and was >unable to complete your request. > > Error message: >Premature end of script headers: trial1.html > >If you think this is a server error, please contact >the webmaster >Error 500 > > localhost > Fri 10 Sep 2004 15:57:51 EST > Apache/2.0.40 (Red Hat Linux) > I made a couple of changes and it gets as far as the database queries before bombing out... fp=open("/var/www/html/sf/frame.html", "r") -> fp=open("trial1.html", "r") print"""<FORM METHOD="POST" ACTION="/cgi-bin/sf/trial1.py"> -> print"""<FORM METHOD="POST" ACTION="trial1.py"> Just to make it point at the right places... How are you calling the script? (in other words, should you be calling trial1.py and not trying to load -- or force python to process -- trial1.html ?) The error message you are getting looks more like a problem with the server being misconfigured ... Try to get the most basic script running first ("hello world") before you start adding in other things. I used a twisted webserver to run the script ... pwd /usr/home/lee/python/cgi ls acgi.rpy trial1.html trial1.py cat acgi.rpy from twisted.web import static, twcgi class PyScript(twcgi.FilteredScript): filter = '/usr/local/bin/python' resource = static.File("/home/lee/python/cgi/") resource.processors = {".py": PyScript} mktap web --port 9999 --path /usr/home/lee/python/cgi twistd -f web.tap Then I accessed it as: http://localhost:9999/acgi.rpy/trial1.py _________________________________________________________________ Add photos to your messages with MSN 8. Get 2 months FREE*. http://join.msn.com/?page=features/featuredemail From mhansen at cso.atmel.com Fri Sep 10 23:50:55 2004 From: mhansen at cso.atmel.com (Mike Hansen) Date: Fri Sep 10 23:50:57 2004 Subject: [Tutor] String Formatting In-Reply-To: <20040910212741.24B981E400D@bag.python.org> References: <20040910212741.24B981E400D@bag.python.org> Message-ID: <414221BF.2090106@cso.atmel.com> I found this in the Activestate Python Cookbook titled "Commafying an integer" http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146461 It might help. Mike > > Subject: > Re: [Tutor] String Formatting > From: > "Isr Gish" <isrgish@fastem.com> > Date: > Fri, 10 Sep 2004 17:21:49 -0400 > To: > <kent_johnson@skillsoft.com>, <tutor@python.org> > > To: > <kent_johnson@skillsoft.com>, <tutor@python.org> > > >Thanks Kent, I'll try it when I get a chence. > >All the best, >Isr > > >-----Original Message----- > >From: "Kent Johnson"<kent_johnson@skillsoft.com> > >Sent: 9/10/04 12:08:16 PM > >To: "tutor@python.org"<tutor@python.org> > >Subject: Re: [Tutor] String Formatting > > > >I'm always up for an optimization challenge :-) I tried several methods. > >Other than the locale-based solution, they all work for non-negative > >integers only. Here is the fastest one I found. It takes about 1/10 the > >time of the locale version and wouldn't be too hard to modify to work for > >negative integers also. > > > >def commafy(val): > > ''' Straightforward approach using string slices ''' > > s = str(val) > > start = len(s) % 3 > > > > chunks = [] > > if start > 0: > > chunks.append(s[:start]) > > > > for i in range(start, len(s), 3): > > chunks.append(s[i:i+3]) > > > > return ','.join(chunks) > > > >Note that much of the time of the locale version is in accessing and > >switching locales. If you can set the locale once before doing the > >conversions, it is about 3x faster than the version that sets and restores > >the locale. > > > >Here are all the versions I tried and a timing harness to compare them. The > >output I get is this: > >commafy1: 1.052021 secs > >commafy2: 1.116770 secs > >commafy3: 1.067124 secs > >commafy4: 2.469994 secs > >commafy5: 1.125030 secs > >commafyLocale: 7.309395 secs > >commafyLocale2: 3.077568 secs > > > >Kent > > > >############################################### > ># commafy 1 to 3 are all variations on string slice and join > >def commafy1(val): > > ''' Straightforward approach using string slices ''' > > s = str(val) > > start = len(s) % 3 > > > > chunks = [] > > if start > 0: > > chunks.append(s[:start]) > > > > for i in range(start, len(s), 3): > > chunks.append(s[i:i+3]) > > > > return ','.join(chunks) > > > > > >def commafy2(val): > > ''' Use list.extend() instead of an append loop ''' > > s = str(val) > > start = len(s) % 3 > > > > chunks = [] > > if start > 0: > > chunks.append(s[:start]) > > > > chunks.extend([s[i:i+3] for i in range(start, len(s), 3)]) > > > > return ','.join(chunks) > > > > > >def commafy3(val): > > ''' Use a list comprehension instead of a loop. The initial > > segment is a problem. ''' > > s = str(val) > > start = len(s) % 3 > > > > chunks = [s[i:i+3] for i in range(start, len(s), 3)] > > if start > 0: > > chunks.insert(0, s[:start]) > > > > return ','.join(chunks) > > > > > >def commafy4(val): > > ''' Iterate over the input and insert the commas directly ''' > > s = list(str(val)) > > s.reverse() > > i = iter(s) > > result = [] > > while True: > > try: > > result.append(i.next()) > > result.append(i.next()) > > result.append(i.next()) > > result.append(',') > > except StopIteration: > > if result[-1] == ',': result.pop() > > break > > result.reverse() > > return ''.join(result) > > > > > >def commafy5(val): > > ''' Use divmod to make the chunks ''' > > if val == 0: return '0' > > > > chunks = [] > > while val > 999: > > val, rem = divmod(val, 1000) > > chunks.append(str(rem).zfill(3)) > > chunks.append(str(val)) > > chunks.reverse() > > return ','.join(chunks) > > > > > >import locale > >def commafyLocale(val): > > ''' Official solution using locale module ''' > > oldloc = locale.setlocale(locale.LC_ALL) > > locale.setlocale(locale.LC_ALL, 'en') > > result = locale.format('%d', val, True) > > locale.setlocale(locale.LC_ALL, oldloc) > > return result > > > > > >locale.setlocale(locale.LC_ALL, 'en') # This line speeds up the ABOVE > >version by 30% ! > >def commafyLocale2(val): > > ''' Use locale module but don't change locale ''' > > result = locale.format('%d', val, True) > > return result > > > > > ># timing test > >import timeit > >def test(f): > > return [f(10**i) for i in range(11)] > > > >correctAnswer = [ > >'1', > >'10', > >'100', > >'1,000', > >'10,000', > >'100,000', > >'1,000,000', > >'10,000,000', > >'100,000,000', > >'1,000,000,000', > >'10,000,000,000', > >] > > > >def timeOne(fn): > > # First run the function and check that it gets the correct results > > actualAnswer = test(fn) > > if actualAnswer != correctAnswer: > > print fn.__name__, 'does not give the correct answer' > > print actualAnswer > > return > > > > # Now time it > > setup = "from __main__ import test, " + fn.__name__ > > stmt = 'test(%s)' % fn.__name__ > > > > t = timeit.Timer(stmt, setup) > > secs = t.timeit(10000) > > print '%s: %f secs' % (fn.__name__, secs) > > > > > >fnsToTest = [ > > commafy1, > > commafy2, > > commafy3, > > commafy4, > > commafy5, > > commafyLocale, > > commafyLocale2, > >] > > > >for fn in fnsToTest: > > timeOne(fn) > > > > > >At 10:34 AM 9/10/2004 -0400, Isr Gish wrote: > >>Thanks orbitz, > >> > >>But... > >> > >> >oldloc = locale.setlocale(locale.LC_ALL) > >> >locale.setlocale(locale.LC_ALL, 'en_US') > >> >locale.format('%d', some_num, True) > >> >locale.setlocale(locale.LC_ALL, oldloc) > >> > > >> > >>I would rather not use this way, iit takes about 25 times longer then a > >>regular % format. And I'm using it for about 1,000,000 times. > >> > >>Isr > >> > >>-----Original Message----- > >> >From: "orbitz"<orbitz@ezabel.com> > >> >Sent: 9/9/04 10:55:22 PM > >> >To: "Isr Gish"<isrgish@fastem.com>, "tutor@python.org"<tutor@python.org> > >> >Subject: Re: [Tutor] String Formatting > >> > > >> >Easiest way would probably be using locale.format in some code I do: > >> > > >> >oldloc = locale.setlocale(locale.LC_ALL) > >> >locale.setlocale(locale.LC_ALL, 'en_US') > >> >locale.format('%d', some_num, True) > >> >locale.setlocale(locale.LC_ALL, oldloc) > >> > > >> > > >> >Isr Gish wrote: > >> > > >> >>Hi, > >> >> > >> >>How can I format a integer in a format string with a comma for example > >> >>print 'Your Account has %f' %amount > >> >>That should print: > >> >>Your Account has 1,000.00 > >> >> > >> >>Thanks > >> >>Isr > >> >> > >> >>_______________________________________________ > >> >>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 MLists at romulo.de Sat Sep 11 12:14:14 2004 From: MLists at romulo.de (Rainer Mansfeld) Date: Sat Sep 11 12:13:56 2004 Subject: [Tutor] Unicode Problem In-Reply-To: <5a309bd3040910114022b0cea9@mail.gmail.com> References: <41416E55.9080903@po-box.mcgill.ca> <414194C1.50302@romulo.de> <5a309bd3040910114022b0cea9@mail.gmail.com> Message-ID: <4142CFF6.5010504@romulo.de> Hi Steve, thanks for your explanation. > >>> print u'?' + '?' > > is the equivalent of: > > >>>print u'?' + '?'.decode('ascii') # what I don't get is why > > this is called decode ?? > I think that's because the value which is 'encoded' in Latin-1 or whatever and gets 'decoded' to ascii. Maybe they should've called it 'recode', since ascii is a code too. What I still don't understand, is why the Python interpreter is able to deal with u'?' but fails to handle unicode('?') >>> u'?' u'\xe4' >>> unicode('?') Traceback (most recent call last): File "<interactive input>", line 1, in ? UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128) >>> unicode('?'.decode('Latin-1')) u'\xe4' Wouldn't it be nicer if the unicode function used the current locale to decode values in range(128,256)? Thanks again Rainer I apologize for 'kidnapping' a running thread. From kent_johnson at skillsoft.com Sun Sep 12 02:45:44 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sun Sep 12 02:45:48 2004 Subject: [Tutor] Unicode Problem In-Reply-To: <4142CFF6.5010504@romulo.de> References: <41416E55.9080903@po-box.mcgill.ca> <414194C1.50302@romulo.de> <5a309bd3040910114022b0cea9@mail.gmail.com> <4142CFF6.5010504@romulo.de> Message-ID: <6.1.0.6.0.20040911202054.029dadc8@mail4.skillsoft.com> You can set the default encoding used to convert between 8-bit strings and unicode strings. Normally the default encoding is 'ascii'. You can change it by creating a file called sitecustomize.py. Put the file in the directory Python/Lib/site-packages. The contents of the file should be import sys sys.setdefaultencoding('latin-1') (or whatever default encoding you want to use.) With the default encoding set to latin-1 and using the IDLE shell, I can do this: >>> u=u'?' >>> u u'\xe4' >>> a='?' >>> a '\xe4' >>> u+a u'\xe4\xe4' >>> print u ? >>> print a ? >>> unicode(a) u'\xe4' Note that the interpretation of '?' and u'?' depends on the encoding of the _shell_ you are using! IDLE uses Latin-1 so it works as expected. The Windows command shell uses cp437 which is not compatible with Latin-1 and gives some strange results. Here is what happens when the default encoding is set to cp437: >>> u=u'?' >>> u u'\x84' Note that the value of u is the cp437 code for ?, NOT the unicode for ?! >>> a='?' >>> a '\x84' With the default encoding set to cp437, u+a converts a to the correct unicode value; the result has two different codes" >>> u+a u'\x84\xe4' So if your console is set to an encoding other than latin-1, you are better off using explicit unicode values for your unicode strings, e.g. >>> u'\N{LATIN SMALL LETTER A WITH DIAERESIS}' u'\xe4' Kent At 12:14 PM 9/11/2004 +0200, Rainer Mansfeld wrote: >Hi Steve, >thanks for your explanation. > >> >>> print u'?' + '?' >>is the equivalent of: >> >>>print u'?' + '?'.decode('ascii') # what I don't get is why >>this is called decode ?? > >I think that's because the value which is 'encoded' in Latin-1 or whatever >and gets 'decoded' to ascii. Maybe they should've called it 'recode', >since ascii is a code too. > >What I still don't understand, is why the Python interpreter is able to >deal with u'?' but fails to handle unicode('?') > > >>> u'?' > u'\xe4' > >>> unicode('?') > Traceback (most recent call last): > File "<interactive input>", line 1, in ? > UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in > position 0: ordinal not in range(128) > >>> unicode('?'.decode('Latin-1')) > u'\xe4' > >Wouldn't it be nicer if the unicode function used the current locale to >decode values in range(128,256)? > >Thanks again > > Rainer > > >I apologize for 'kidnapping' a running thread. > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From klas.martelleur at telia.com Sun Sep 12 10:06:37 2004 From: klas.martelleur at telia.com (Klas Marteleur) Date: Sun Sep 12 10:08:21 2004 Subject: [Tutor] Proxies and pdf's Message-ID: <200409121006.37576.klas.martelleur@telia.com> Hello Question one: Proxies and Mechanize. At work i wanna reach an "internal" web page using the Mechanize module. But i get an error 404 in return. I suspect i get this error for one of the following reasons: 1.The proxy settings. The proxy settings in windows are like "use the proxy proxy.company.com port 8800 for http, but dont use the proxy for internal sites". I can reach google using Mechanize for example. But when i try the internal site i get a error 404 2. The fact that the page i wanna reach is using javascript. Does anyone know what could be wrong? Question two: Postscript to PDF I wanna convert postscripts to pdf's under windows, is there a module that could do that for me? Without accessing a third part program as distiller or a command line program. Thanks for a great mailing list Klas From MLists at romulo.de Sun Sep 12 16:52:22 2004 From: MLists at romulo.de (Rainer Mansfeld) Date: Sun Sep 12 16:52:27 2004 Subject: [Tutor] Unicode Problem In-Reply-To: <6.1.0.6.0.20040911202054.029dadc8@mail4.skillsoft.com> References: <41416E55.9080903@po-box.mcgill.ca> <414194C1.50302@romulo.de> <5a309bd3040910114022b0cea9@mail.gmail.com> <4142CFF6.5010504@romulo.de> <6.1.0.6.0.20040911202054.029dadc8@mail4.skillsoft.com> Message-ID: <414462A6.2010009@romulo.de> Hi Kent, > You can set the default encoding used to convert between 8-bit strings > and unicode strings. Normally the default encoding is 'ascii'. You can > change it by creating a file called sitecustomize.py. Put the file in > the directory Python/Lib/site-packages. The contents of the file should be > import sys > sys.setdefaultencoding('latin-1') > Thanks a lot. That solves my problem. This really is a great list. Rainer From bgailer at alum.rpi.edu Sun Sep 12 18:18:55 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sun Sep 12 18:17:54 2004 Subject: {Spam?} [Tutor] How to represent "enter" In-Reply-To: <1094669804.413f55ec57e7f@webmail.bath.ac.uk> References: <1094669804.413f55ec57e7f@webmail.bath.ac.uk> Message-ID: <6.1.2.0.0.20040912101749.04dd0420@mail.mric.net> At 12:56 PM 9/8/2004, W X Liu wrote: >Hi everyone, > >who can tell me that how to represent "enter" key in python? If you have not yet got a satisfactory answer, please tell us the context of your question. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From tim at johnsons-web.com Sun Sep 12 18:53:21 2004 From: tim at johnsons-web.com (Tim Johnson) Date: Sun Sep 12 18:45:17 2004 Subject: [Tutor] Trapping High-Level Exceptions As Strings Message-ID: <20040912165321.GB19983@johnsons-web.com> By "High-Level", I mean using the except label without any error object as a parameters, so that I may trap any error that "falls" through more structured traps. Currently, I'm using something like this code fragment below: ############################################################### except PrjError, err: print "AN INTERNAL PROGRAMMING ERROR WAS FOUND:" print "Below is the report:\n" print err.err exit_code = 1 except HaltError, err: print "A PROGRAM TERMINATION HAS OCCURRED:" print "REASON: %s\n" % (err.err) exit_code = 1 except: print "WE HAVE ERRORS: Report the information below to your technical support" print "----------------------------------------------------------------------------------------" exit_code = 1 traceback.print_exc() ############################################################### In the first two examples, I'm initializing an error object and obtaining a string which I can print, or write to a logfile at will. In the last example, I'm using a call to traceback.print_exc(), which does the printing itself. The traceback information is very good, and I want to trap that also. If I have a divide by zero error, traceback gives me the following: ############################################################### Traceback (most recent call last): File "./nwmls_cron.py", line 98, in ? process(args) File "./nwmls_cron.py", line 16, in process 1 / 0 # test exception handling and logging ZeroDivisionError: integer division or modulo by zero integer division or modulo by zero ############################################################### Which is very helpful, but I don't know how to obtain that message as a string. Using err_msg = format_list(extract_tb()) print err_msg # gets a string for me to print, write to file # or both, I presume, but I only get the last # line. Example: "integer division or modulo by zero" So how may I get more information, which can point to the origin of the error? help(traceback) indicates that extract_tb() has an optional "tb" parameter, but I'm not clear on how to use it. TIA Tim -- Tim Johnson <tim@johnsons-web.com> http://www.alaska-internet-solutions.com From kent_johnson at skillsoft.com Sun Sep 12 21:05:44 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sun Sep 12 21:05:58 2004 Subject: [Tutor] Trapping High-Level Exceptions As Strings In-Reply-To: <20040912165321.GB19983@johnsons-web.com> References: <20040912165321.GB19983@johnsons-web.com> Message-ID: <6.1.0.6.0.20040912145946.029b4818@mail4.skillsoft.com> If you want to capture exactly what print_exc() outputs, you can use the StringIO module and the optional file parameter to print_exc(): >>> import StringIO, traceback >>> try: ... raise RuntimeError ... except: ... buf = StringIO.StringIO() ... traceback.print_exc(None, buf) ... print buf.getvalue() ... Traceback (most recent call last): File "<stdin>", line 2, in ? RuntimeError If you want to format the traceback differently, you can use some of the other functions in the traceback module, for example the various format functions. Take a look at traceback.py to see how print_exc() works and make your own version that does what you want. Kent At 08:53 AM 9/12/2004 -0800, Tim Johnson wrote: >By "High-Level", I mean using the except label >without any error object as a parameters, so >that I may trap any error that "falls" through >more structured traps. > >Currently, I'm using something like this >code fragment below: >############################################################### > except PrjError, err: > print "AN INTERNAL PROGRAMMING ERROR WAS FOUND:" > print "Below is the report:\n" > print err.err > exit_code = 1 > except HaltError, err: > print "A PROGRAM TERMINATION HAS OCCURRED:" > print "REASON: %s\n" % (err.err) > exit_code = 1 > except: > print "WE HAVE ERRORS: Report the information below to your > technical support" > print > "----------------------------------------------------------------------------------------" > exit_code = 1 > traceback.print_exc() >############################################################### >In the first two examples, I'm initializing an error object and >obtaining a string which I can print, or write to a logfile at >will. > >In the last example, I'm using a call to traceback.print_exc(), >which does the printing itself. The traceback information is >very good, and I want to trap that also. If I have a divide by >zero error, traceback gives me the following: >############################################################### >Traceback (most recent call last): > File "./nwmls_cron.py", line 98, in ? > process(args) > File "./nwmls_cron.py", line 16, in process > 1 / 0 # test exception handling and logging >ZeroDivisionError: integer division or modulo by zero >integer division or modulo by zero >############################################################### >Which is very helpful, but I don't know how to obtain that >message as a string. > >Using > err_msg = format_list(extract_tb()) > print err_msg ># gets a string for me to print, write to file ># or both, I presume, but I only get the last ># line. Example: >"integer division or modulo by zero" > >So how may I get more information, which can point >to the origin of the error? > >help(traceback) indicates that extract_tb() has an >optional "tb" parameter, but I'm not clear on >how to use it. > >TIA >Tim > >-- >Tim Johnson <tim@johnsons-web.com> > http://www.alaska-internet-solutions.com >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From leomandy at hotmail.com Sun Sep 12 23:00:54 2004 From: leomandy at hotmail.com (mandy bowen) Date: Sun Sep 12 23:00:58 2004 Subject: [Tutor] email capabilities in Python Message-ID: <BAY16-F28oqdNKn64sa000bc867@hotmail.com> I am a little confused by the email capabilities - I am trying to send an email from a program (under certain circumstances) and I have found a lot of different answers to this, but none of them can be added to my program because they all import smtplib and I get an ImportError: No module named base64MIME. Something from inside the import??!! Is there another way to send an email? _________________________________________________________________ Don’t just search. Find. Check out the new MSN Search! http://search.msn.click-url.com/go/onm00200636ave/direct/01/ From kent_johnson at skillsoft.com Sun Sep 12 23:52:00 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sun Sep 12 23:52:08 2004 Subject: [Tutor] email capabilities in Python In-Reply-To: <BAY16-F28oqdNKn64sa000bc867@hotmail.com> References: <BAY16-F28oqdNKn64sa000bc867@hotmail.com> Message-ID: <6.1.0.6.0.20040912174945.029b0530@mail4.skillsoft.com> base64MIME is part of the Python 2.3 distribution. What version are you using? Do you have a file Python/Lib/email/base64MIME.py? What happens if you run a Python shell and type import email.base64MIME Kent At 09:00 PM 9/12/2004 +0000, mandy bowen wrote: >I am a little confused by the email capabilities - I am trying to send an >email from a program (under certain circumstances) and I have found a lot >of different answers to this, but none of them can be added to my program >because they all import smtplib and I get an ImportError: No module named >base64MIME. Something from inside the import??!! Is there another way to >send an email? > >_________________________________________________________________ >Don't just search. Find. Check out the new MSN Search! >http://search.msn.click-url.com/go/onm00200636ave/direct/01/ > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From andre.roberge at ns.sympatico.ca Mon Sep 13 01:15:15 2004 From: andre.roberge at ns.sympatico.ca (=?ISO-8859-1?Q?Andr=E9_Roberge?=) Date: Mon Sep 13 01:15:14 2004 Subject: [Tutor] How to? Using the GUI interface of PyUnit under Windows (XP) Message-ID: <4144D883.3020509@ns.sympatico.ca> Sorry for the simple question; my last real programming experiences were years ago using C under MS-DOS (and FORTRAN on mainframes). Back then, dealing with environment variables and paths seemed second nature. After many years of doing other stuff, I'm starting to program again, just for the fun of it (and to teach my kids), learning Python along the way. I find that I am now addicted to the simplicity of using GUI programs instead of command lines, and now I am stuck :-( I want to learn the "test-driven development" using the unittestgui that comes with PyUnit. I found that I could run the tests examples by moving everything (i.e. unittestguy.py as well as the python modules and test-modules) in the same directory, but can't seem to get it to work otherwise. I would like to keep my tests and the corresponding modules in separate directories, just to keep things better organised, and not have to move unittestgui all the time. Any pointers would be appreciated. A very embarrassed "old fart/newbie", Andr? Roberge From tim at johnsons-web.com Mon Sep 13 01:41:15 2004 From: tim at johnsons-web.com (Tim Johnson) Date: Mon Sep 13 01:33:13 2004 Subject: [Tutor] Trapping High-Level Exceptions As Strings In-Reply-To: <6.1.0.6.0.20040912145946.029b4818@mail4.skillsoft.com> References: <20040912165321.GB19983@johnsons-web.com> <6.1.0.6.0.20040912145946.029b4818@mail4.skillsoft.com> Message-ID: <20040912234115.GE19983@johnsons-web.com> * Kent Johnson <kent_johnson@skillsoft.com> [040912 11:21]: <...> If you want to format the traceback differently, you can use some of the > other functions in the traceback module, for example the various format > functions. Take a look at traceback.py to see how print_exc() works and > make your own version that does what you want. Thanks Kent: ## the code fragment below is what I'm looking for: etype, value, tb = sys.exc_info() print "value = " , value print "tb = " , tb print "etype = " , etype print "ERROR LIST = " , traceback.extract_tb(tb) ## shows the following: value = integer division or modulo by zero tb = <traceback object at 0x40700c34> etype = exceptions.ZeroDivisionError ERROR LIST = [('./nwmls_cron.py', 98, '?', 'process(args)'), ('./nwmls_cron.py', 16, 'process', '1 / 0 # test exception handling and logging') ] cheers! tim <..> At 08:53 AM 9/12/2004 -0800, Tim Johnson wrote: > >By "High-Level", I mean using the except label > >without any error object as a parameters, so > >that I may trap any error that "falls" through > >more structured traps. -- Tim Johnson <tim@johnsons-web.com> http://www.alaska-internet-solutions.com From isrgish at fastem.com Mon Sep 13 03:49:30 2004 From: isrgish at fastem.com (Isr Gish) Date: Mon Sep 13 03:49:49 2004 Subject: [Tutor] Proxies and pdf's Message-ID: <20040913014948.384B81E400D@bag.python.org> Hi Klas, -----Original Message----- >From: "Klas Marteleur"<klas.martelleur@telia.com> >Sent: 9/12/04 4:06:37 AM >To: "tutor@python.org"<tutor@python.org> >Subject: [Tutor] Proxies and pdf's > >Hello [snip] >Question two: Postscript to PDF >I wanna convert postscripts to pdf's under windows, is there a module that >could do that for me? Without accessing a third part program as distiller or >a command line program. > There is a package on sourceforge called reportlab and a package on top ofsthat called xtopdf. I think these packages may help you. Have a look. All the best, Isr >Thanks for a great mailing list >Klas >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From chandrakirti at gmail.com Mon Sep 13 04:59:19 2004 From: chandrakirti at gmail.com (Lloyd Hugh Allen) Date: Mon Sep 13 04:59:23 2004 Subject: {Spam?} [Tutor] How to represent "enter" In-Reply-To: <6.1.2.0.0.20040912101749.04dd0420@mail.mric.net> References: <1094669804.413f55ec57e7f@webmail.bath.ac.uk> <6.1.2.0.0.20040912101749.04dd0420@mail.mric.net> Message-ID: <24d253d90409121959784835a3@mail.gmail.com> Do you mean '\n' as a string representation of a newline? On Sun, 12 Sep 2004 10:18:55 -0600, Bob Gailer <bgailer@alum.rpi.edu> wrote: > At 12:56 PM 9/8/2004, W X Liu wrote: > >Hi everyone, > > > >who can tell me that how to represent "enter" key in python? > > If you have not yet got a satisfactory answer, please tell us the context > of your question. > > 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 kent_johnson at skillsoft.com Mon Sep 13 05:48:25 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Mon Sep 13 05:48:33 2004 Subject: [Tutor] How to? Using the GUI interface of PyUnit under Windows (XP) In-Reply-To: <4144D883.3020509@ns.sympatico.ca> References: <4144D883.3020509@ns.sympatico.ca> Message-ID: <6.1.0.6.0.20040912234301.029c14d8@mail4.skillsoft.com> I think if your tests are in a package, you can run them in unittestgui by giving the full package name of the test suite function. Of course the package will have to be in your sys.path. e.g. mypackage/ __init__.py # needed to create a package mymodule.py contains mytest() then in unittestgui tell it to run mypackage.mymodule.mytest Kent At 08:15 PM 9/12/2004 -0300, Andr? Roberge wrote: >Sorry for the simple question; my last real programming experiences >were years ago using C under MS-DOS (and FORTRAN on mainframes). Back >then, dealing with environment variables and paths seemed second nature. >After many years of doing other stuff, I'm starting to program again, >just for the fun of it (and to teach my kids), >learning Python along the way. >I find that I am now addicted to the simplicity of using GUI programs >instead of command lines, and now I am stuck :-( > >I want to learn the "test-driven development" using the unittestgui >that comes with PyUnit. I found that I could run >the tests examples by moving everything >(i.e. unittestguy.py as well as the python modules and test-modules) >in the same directory, but can't seem to get it to work otherwise. > >I would like to keep my tests and the corresponding modules in separate >directories, >just to keep things better organised, >and not have to move unittestgui all the time. > >Any pointers would be appreciated. > >A very embarrassed "old fart/newbie", > >Andr? Roberge > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From eric at digitalert.net Mon Sep 13 08:55:25 2004 From: eric at digitalert.net (Eric) Date: Mon Sep 13 08:55:18 2004 Subject: [Tutor] Search text file, perform action if a given item found in file In-Reply-To: <6.1.0.6.0.20040910055620.0296f1b8@mail4.skillsoft.com> References: <414019B2.8080807@digitalert.net> <41401B8C.1000708@digitalert.net> <6.1.0.6.0.20040909081224.028926a0@mail4.skillsoft.com> <4140A038.9040504@digitalert.net> <41416663.5080809@digitalert.net> <6.1.0.6.0.20040910055620.0296f1b8@mail4.skillsoft.com> Message-ID: <4145445D.9050506@digitalert.net> Ok, I'm still trying to figure this out.. This is on Windows XP computer with Python version 2.3.4 >>> import os >>> o=os.popen("netstat -an") >>> for l in o: print l.split()[1] Traceback (most recent call last): File "<pyshell#173>", line 2, in -toplevel- print l.split()[1] IndexError: list index out of range And this is the same series of commands on a FreeBSD computer running Python version 2.2.2 >>> import os >>> o=os.popen("netstat -an") >>> for l in o: ... print l.split()[1] ... Internet Recv-Q 0 0 0 0 0 0 0 0 0 0 0 0 UNIX Type stream stream stream stream stream stream dgram dgram dgram dgram dgram So it seems to be working with a older version of python but not the newer version? Is this a bug? If so that would explain why I have been having so many problems with this. Kent Johnson wrote: > Eric, > > l.split()[1:2] gives a list containing a string, rather than a bare > string, so endswith() won't work on it. You should use l.split()[1] > instead: > >>> l='a b c' > >>> l.split() > ['a', 'b', 'c'] > >>> l.split()[1:2] > ['b'] > > That is a list containing a string so endswith won't work > >>> l.split()[1:2].endswith('b') > Traceback (most recent call last): > File "<stdin>", line 1, in ? > AttributeError: 'list' object has no attribute 'endswith' > >>> l.split()[1] > 'b' > > Now it's just a string and split works fine > >>> l.split()[1].endswith('b') > True > > Then you will need a string containing the port number preceded by a > colon. You can do this with ':' + str(port) > > Finally, put an if statement inside your loop to test for the port > string and do something with it. Brian's post shows how to do that. > > Kent From johan at accesstel.co.za Mon Sep 13 09:48:57 2004 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Mon Sep 13 09:49:49 2004 Subject: [Tutor] Network programming In-Reply-To: <6.1.0.6.0.20040909180124.0297de28@mail4.skillsoft.com> References: <1094473155.4233.23.camel@linux.site> <6.1.0.6.0.20040907085123.02869dd8@mail4.skillsoft.com> <1094717689.4427.10.camel@linux.site> <6.1.0.6.0.20040909180124.0297de28@mail4.skillsoft.com> Message-ID: <1095061736.4429.10.camel@linux.site> Thanks Kent, I will look at my loop and at the links you gave. My links stays up, but as you noticed, I must get away of sending the data received from either connections. Will I be able to use the select.select for this. There are three file desriptors in this. One for incoming, one for outgoing and the other for errors. Can I use the outgoing one to send the data the incoming list received? Thanks Johan On Fri, 2004-09-10 at 03:44, Kent Johnson wrote: > Johan, > > It looks to me like your program will get stuck in the inner while loop. > There is no way inside this loop to get a new value for indata or outdata. > > There are two approaches you could use to solve your problem - either put > the two sides of the transfer into separate threads, or use some kind of > polling to look for data available on either socket. > > The thread approach usually uses three threads: > - a master thread that listens to the server socket and accepts the > incoming connection. It then opens the forwarding socket and spawns two > forwarding threads. > - the forwarding threads read from one socket and write to another. They > are symmetric - one thread reads from socket A and writes to socket B; the > other thread reads from socket B and writes to socket A. > > Each thread uses blocking I/O - the master thread blocks on > socket.accept(); the forwarding threads block on socket.recv(). > > A simple example that uses the treaded approach to do something similar to > what you want to do is here: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/114642 > In this case the Pinhole class is the master thread; when it gets a > connection it creates two PipeThreads to do the reading and writing. > > > The polling approach uses non-blocking I/O. In it's crudest form its loop > looks like this: > forever: > if data available on socket A: > read from socket A > write to socket B > if data available on socket B: > read from socket B > write to socket A > sleep for a bit > > This is crude because it is either unresponsive (if the sleep is long) or > wasteful of CPU (if the sleep is short and there is not much to do). It > might be fine for a simple use with just one connection, though. > > The Python asyncore and asynchat modules use a more sophisticated version > of this; instead of sleeping, they use a system call that blocks until > there is activity on any of the sockets it is watching. This is very > efficient, as the polling loop only wakes up when there is something for it > to do. Medusa <http://www.nightmare.com/medusa/index.html> and Twisted > <http://www.twistedmatrix.com/> are two servers that are based on this > approach. It can be more efficient for large numbers of connections because > it doesn't have to create a thread for each one. > > asyncore and asynchat hide the actual polling loop from you. You interact > with them by defining callback methods that get called when data is > available or when a channel is available for writing. This tutorial is a > good introduction to this approach. The proxy server at the end is similar > to what you are trying to do. http://www.nightmare.com/medusa/programming.html > > Medusa includes a chat server which is also similar to your application. > > I hope this helps get you on the right track! > Kent > > At 10:14 AM 9/9/2004 +0200, Johan Geldenhuys wrote: > >I still have trouble when I want to send data out as soon as it comes in > >from one side. > >My server listens and accepts the calls and then builds the client > >connection to the destination. Please see if you can assist. > > > >Thanks > > > >Johan > >#################################################### > > > ># we have an incoming socket connect > > newConn, addr = self._serverSocket.accept() > > self.log('Connection received from: %s:%s' % addr) > > > > #while connection is active on server: > > while 1: > > #self._ne1_id = '1234' > > #self._ne2_id = '1111' > > > > indata = newConn.recv(8192) > > self.log('First Data received from LCT:' + > > `indata`) > > > > if '\xff' in indata: > > continue > > > > if '\x01' in indata: > > continue > > > > #Look for string of 1234 in indata: > > if indata[0:4] == self._ne1_id: > > self.log('indata 0:4 is:' + `indata[0:4]`) > > self.sock = socket(AF_INET, SOCK_STREAM) > > > > #connect to this destination if the string is > > 1234 > > self.sock.connect((self._ne1_ip, > > self._ne1_port)) # This is previously defined > > self.log('Connection established to NE1: > > %s:%i' % (self._ne1_ip, self._ne1_port)) > > outdata = self.sock.recv(8192) > > #when connection to destination is up: > > while 1: > > if indata: > > self.sock.send(indata) > > self.log('indata send to NE, line > > 106: ' + `indata`) > > > > # If break sequence is received from > > server side, close the client connection > > if '\x11' in indata: > > self.log('Break character received') > > break > > self.sock.close() > > self.log('connection to NE1 now closed') > > > > if oudata: > > newConn.send(outdata) > > self.log('Data from NE:' + `outdata`) > >########################################################### > > > > > > > > > > > > > > > > > > > > > > > >On Tue, 2004-09-07 at 14:58, Kent Johnson wrote: > >> > >> > >>We might be better able to help if you post your code. > >> > >>Here is a list of HTTP proxy servers written in Python, you might find > >>something helpful there: > >><http://xhaus.com/alan/python/proxies.html>http://xhaus.com/alan/python/proxies.html > >> > >>Kent > >> > >>At 02:19 PM 9/6/2004 +0200, Johan Geldenhuys wrote: > >> >Hi, > >> > > >> >I am new to Python and would like to know more about network programming > >> >in particilar. > >> > > >> >I have a script that sets up a socket server and must wait for incoming > >> >connections. Once a call has been accepted, it must make another socket > >> >connection to a destination. > >> > > >> >Now, I want to let these two "talk" to each other. Once the server > >> >receives data it must be send out to the destination and when the > >> >destination has data, it must be send out to the connection that made the > >> >first call to the server. > >> > > >> >Does anybody have any examples or tips on how I can let this happen. My > >> >calls work for the first batch of data and then when new data is received, > >> >the calls break. > >> > > >> >Thanks > >> > > >> >-- > >> > Johan Geldenhuys > >> >Access Telecommunication Systems > >> > Mail to: johan@accesstel.co.za > >> >-- > >> >This message has been scanned for viruses and > >> >dangerous content by > >> <<http://www.azitech.co.za>http://www.azitech.co.za>Azitech, and is > >> >believed to be clean. > >> >_______________________________________________ > >> >Tutor maillist - Tutor@python.org > >> ><http://mail.python.org/mailman/listinfo/tutor>http://mail.python.org/ma > >> ilman/listinfo/tutor > > > > > > > > > > > >-- > > Johan Geldenhuys > >Access Telecommunication Systems > > Mail to: johan@accesstel.co.za > > > >-- > >This message has been scanned for viruses and > >dangerous content by <http://www.azitech.co.za>Azitech, and is > >believed to be clean. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Johan Geldenhuys Access Telecommunication Systems Mail to: johan@accesstel.co.za -- This message has been scanned for viruses and dangerous content by Azitech, and is believed to be clean. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040913/b95aaba7/attachment.html From kent_johnson at skillsoft.com Mon Sep 13 11:57:19 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Mon Sep 13 11:57:25 2004 Subject: [Tutor] Search text file, perform action if a given item found in file In-Reply-To: <4145445D.9050506@digitalert.net> References: <414019B2.8080807@digitalert.net> <41401B8C.1000708@digitalert.net> <6.1.0.6.0.20040909081224.028926a0@mail4.skillsoft.com> <4140A038.9040504@digitalert.net> <41416663.5080809@digitalert.net> <6.1.0.6.0.20040910055620.0296f1b8@mail4.skillsoft.com> <4145445D.9050506@digitalert.net> Message-ID: <6.1.0.6.0.20040913055421.0299a848@mail4.skillsoft.com> Eric, It's a difference between netstat on Windows and FreeBSD. The windows version includes a few header lines that don't split the way you expect - the resulting list doesn't have two elements: >>> import os >>> f=os.popen('netstat -an') >>> for l in f: ... print len(l.split()) ... 0 2 0 6 4 4 etc... You could check the length of the split before you do further processing, or you could catch the exception and continue the loop. Kent At 02:55 AM 9/13/2004 -0400, Eric wrote: >Ok, I'm still trying to figure this out.. > >This is on Windows XP computer with Python version 2.3.4 > > >>> import os > >>> o=os.popen("netstat -an") > >>> for l in o: > print l.split()[1] > > >Traceback (most recent call last): > File "<pyshell#173>", line 2, in -toplevel- > print l.split()[1] >IndexError: list index out of range > > > >And this is the same series of commands on a FreeBSD computer running >Python version 2.2.2 > > > >>> import os > >>> o=os.popen("netstat -an") > >>> for l in o: >... print l.split()[1] >... >Internet >Recv-Q >0 >0 >0 >0 >0 >0 >0 >0 >0 >0 >0 >0 >UNIX >Type >stream >stream >stream >stream >stream >stream >dgram >dgram >dgram >dgram >dgram > > > >So it seems to be working with a older version of python but not the newer >version? Is this a bug? If so that would explain >why I have been having so many problems with this. > > >Kent Johnson wrote: > >>Eric, >> >>l.split()[1:2] gives a list containing a string, rather than a bare >>string, so endswith() won't work on it. You should use l.split()[1] instead: >> >>> l='a b c' >> >>> l.split() >>['a', 'b', 'c'] >> >>> l.split()[1:2] >>['b'] >> >>That is a list containing a string so endswith won't work >> >>> l.split()[1:2].endswith('b') >>Traceback (most recent call last): >> File "<stdin>", line 1, in ? >>AttributeError: 'list' object has no attribute 'endswith' >> >>> l.split()[1] >>'b' >> >>Now it's just a string and split works fine >> >>> l.split()[1].endswith('b') >>True >> >>Then you will need a string containing the port number preceded by a >>colon. You can do this with ':' + str(port) >> >>Finally, put an if statement inside your loop to test for the port string >>and do something with it. Brian's post shows how to do that. >> >>Kent > > From kent_johnson at skillsoft.com Mon Sep 13 12:03:59 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Mon Sep 13 12:04:12 2004 Subject: [Tutor] Network programming In-Reply-To: <1095061736.4429.10.camel@linux.site> References: <1094473155.4233.23.camel@linux.site> <6.1.0.6.0.20040907085123.02869dd8@mail4.skillsoft.com> <1094717689.4427.10.camel@linux.site> <6.1.0.6.0.20040909180124.0297de28@mail4.skillsoft.com> <1095061736.4429.10.camel@linux.site> Message-ID: <6.1.0.6.0.20040913060048.0299a328@mail4.skillsoft.com> At 09:48 AM 9/13/2004 +0200, Johan Geldenhuys wrote: >Thanks Kent, > >I will look at my loop and at the links you gave. My links stays up, but >as you noticed, I must get away of sending the data received from either >connections. Will I be able to use the select.select for this. Yes, you can use select, or either of the modules built on top of select - asyncore and asynchat. >There are three file desriptors in this. One for incoming, one for >outgoing and the other for errors. Can I use the outgoing one to send the >data the incoming list received? Yes, that is the right approach. Kent >Thanks > >Johan > >On Fri, 2004-09-10 at 03:44, Kent Johnson wrote: >> >>Johan, >> >>It looks to me like your program will get stuck in the inner while loop. >>There is no way inside this loop to get a new value for indata or outdata. >> >>There are two approaches you could use to solve your problem - either put >>the two sides of the transfer into separate threads, or use some kind of >>polling to look for data available on either socket. >> >>The thread approach usually uses three threads: >>- a master thread that listens to the server socket and accepts the >>incoming connection. It then opens the forwarding socket and spawns two >>forwarding threads. >>- the forwarding threads read from one socket and write to another. They >>are symmetric - one thread reads from socket A and writes to socket B; the >>other thread reads from socket B and writes to socket A. >> >>Each thread uses blocking I/O - the master thread blocks on >>socket.accept(); the forwarding threads block on socket.recv(). >> >>A simple example that uses the treaded approach to do something similar to >>what you want to do is here: >><http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/114642>http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/114642 >>In this case the Pinhole class is the master thread; when it gets a >>connection it creates two PipeThreads to do the reading and writing. >> >> >>The polling approach uses non-blocking I/O. In it's crudest form its loop >>looks like this: >>forever: >> if data available on socket A: >> read from socket A >> write to socket B >> if data available on socket B: >> read from socket B >> write to socket A >> sleep for a bit >> >>This is crude because it is either unresponsive (if the sleep is long) or >>wasteful of CPU (if the sleep is short and there is not much to do). It >>might be fine for a simple use with just one connection, though. >> >>The Python asyncore and asynchat modules use a more sophisticated version >>of this; instead of sleeping, they use a system call that blocks until >>there is activity on any of the sockets it is watching. This is very >>efficient, as the polling loop only wakes up when there is something for it >>to do. Medusa >><<http://www.nightmare.com/medusa/index.html>http://www.nightmare.com/medusa/index.html> >>and Twisted >><<http://www.twistedmatrix.com/>http://www.twistedmatrix.com/> are two >>servers that are based on this >>approach. It can be more efficient for large numbers of connections because >>it doesn't have to create a thread for each one. >> >>asyncore and asynchat hide the actual polling loop from you. You interact >>with them by defining callback methods that get called when data is >>available or when a channel is available for writing. This tutorial is a >>good introduction to this approach. The proxy server at the end is similar >>to what you are trying to do. >><http://www.nightmare.com/medusa/programming.html>http://www.nightmare.com/medusa/programming.html >> >>Medusa includes a chat server which is also similar to your application. >> >>I hope this helps get you on the right track! >>Kent >> >>At 10:14 AM 9/9/2004 +0200, Johan Geldenhuys wrote: >> >I still have trouble when I want to send data out as soon as it comes in >> >from one side. >> >My server listens and accepts the calls and then builds the client >> >connection to the destination. Please see if you can assist. >> > >> >Thanks >> > >> >Johan >> >#################################################### >> > >> ># we have an incoming socket connect >> > newConn, addr = self._serverSocket.accept() >> > self.log('Connection received from: %s:%s' % addr) >> > >> > #while connection is active on server: >> > while 1: >> > #self._ne1_id = '1234' >> > #self._ne2_id = '1111' >> > >> > indata = newConn.recv(8192) >> > self.log('First Data received from LCT:' + >> > `indata`) >> > >> > if '\xff' in indata: >> > continue >> > >> > if '\x01' in indata: >> > continue >> > >> > #Look for string of 1234 in indata: >> > if indata[0:4] == self._ne1_id: >> > self.log('indata 0:4 is:' + `indata[0:4]`) >> > self.sock = socket(AF_INET, SOCK_STREAM) >> > >> > #connect to this destination if the string is >> > 1234 >> > self.sock.connect((self._ne1_ip, >> > self._ne1_port)) # This is previously defined >> > self.log('Connection established to NE1: >> > %s:%i' % (self._ne1_ip, self._ne1_port)) >> > outdata = self.sock.recv(8192) >> > #when connection to destination is up: >> > while 1: >> > if indata: >> > self.sock.send(indata) >> > self.log('indata send to NE, line >> > 106: ' + `indata`) >> > >> > # If break sequence is received from >> > server side, close the client connection >> > if '\x11' in indata: >> > self.log('Break character received') >> > break >> > self.sock.close() >> > self.log('connection to NE1 now >> closed') >> > >> > if oudata: >> > newConn.send(outdata) >> > self.log('Data from NE:' + >> `outdata`) >> >########################################################### >> > >> > >> > >> > >> > >> > >> > >> > >> > >> > >> > >> >On Tue, 2004-09-07 at 14:58, Kent Johnson wrote: >> >> >> >> >> >>We might be better able to help if you post your code. >> >> >> >>Here is a list of HTTP proxy servers written in Python, you might find >> >>something helpful there: >> >><<http://xhaus.com/alan/python/proxies.html>http://xhaus.com/alan/pytho >> n/proxies.html>http://xhaus.com/alan/python/proxies.html >> >> >> >>Kent >> >> >> >>At 02:19 PM 9/6/2004 +0200, Johan Geldenhuys wrote: >> >> >Hi, >> >> > >> >> >I am new to Python and would like to know more about network programming >> >> >in particilar. >> >> > >> >> >I have a script that sets up a socket server and must wait for incoming >> >> >connections. Once a call has been accepted, it must make another socket >> >> >connection to a destination. >> >> > >> >> >Now, I want to let these two "talk" to each other. Once the server >> >> >receives data it must be send out to the destination and when the >> >> >destination has data, it must be send out to the connection that >> made the >> >> >first call to the server. >> >> > >> >> >Does anybody have any examples or tips on how I can let this happen. My >> >> >calls work for the first batch of data and then when new data is >> received, >> >> >the calls break. >> >> > >> >> >Thanks >> >> > >> >> >-- >> >> > Johan Geldenhuys >> >> >Access Telecommunication Systems >> >> > Mail to: johan@accesstel.co.za >> >> >-- >> >> >This message has been scanned for viruses and >> >> >dangerous content by >> >> >> <<<http://www.azitech.co.za>http://www.azitech.co.za>http://www.azitech.co.za>Azitech, >> and is >> >> >believed to be clean. >> >> >_______________________________________________ >> >> >Tutor maillist - Tutor@python.org >> >> ><<http://mail.python.org/mailman/listinfo/tutor>http://mail.python.or >> g/mailman/listinfo/tutor>http://mail.python.org/ma >> >> ilman/listinfo/tutor >> > >> > >> > >> > >> > >> >-- >> > Johan Geldenhuys >> >Access Telecommunication Systems >> > Mail to: johan@accesstel.co.za >> > >> >-- >> >This message has been scanned for viruses and >> >dangerous content by >> <<http://www.azitech.co.za>http://www.azitech.co.za>Azitech, and is >> >believed to be clean. >> >>_______________________________________________ >>Tutor maillist - Tutor@python.org >><http://mail.python.org/mailman/listinfo/tutor>http://mail.python.org/mailman/listinfo/tutor > > > > > >-- > Johan Geldenhuys >Access Telecommunication Systems > Mail to: johan@accesstel.co.za > >-- >This message has been scanned for viruses and >dangerous content by <http://www.azitech.co.za>Azitech, and is >believed to be clean. From s.varun at gmail.com Mon Sep 13 13:38:26 2004 From: s.varun at gmail.com (Varun Soundararajan) Date: Mon Sep 13 13:38:55 2004 Subject: [Tutor] Doubt in RPC XML lib In-Reply-To: <32b5ee7604090911376994ad31@mail.gmail.com> References: <32b5ee7604090911376994ad31@mail.gmail.com> Message-ID: <32b5ee760409130438734b3ad5@mail.gmail.com> I hv attached the two files. Actually what i am trying to do is that, i replicate the gethosts.py and servers.py code in every system. in every system when i start my python code, i check all servers of the same type and add to my active hosts list. ( i do taht in gethosts.py) in the servers.py, i serve my own server at 10001 and rpc server at 8000 using thread. My server at 10001 authenticates with other server of my type by sending some hashed data and getting it back (just to ensure that i am not adding some other server listening at 10001). Now my qn is, if i want to access a code i call: server.somefunction() now since i have the list of functions of form (['1.fn1', '1.fn2','2.fn1' etc] ) when i want to call the fn1 of server 0 i shd call hosts_server_access[0].fn1() . but i want the user to choose that. Now how do i do that. in other words. if i wanna call fn1 of server 0 i shd be able to call(say) hosts_server_access[0][1]() or something like that. pls help thanks in advance -Varun -------------- next part -------------- import ConfigParser import xmlrpclib import md5 import socket class Hosts: """ Hosts: On instantiating, the object reads from file hosts.ini and finds all live hosts""" hostlist=[] alivehosts=[] PORT=10001 hosts_functions=[] hosts_server_access=[] def __init__(self): self.hostlist=self.gethosts("hosts.ini") for host in self.hostlist: if self.isAlive(host,self.PORT): self.alivehosts.append(host) def __str__(self): return str(self.alivehosts) def gethosts(self,filename): """ Gets a list of hostnames from the file <i>fFilename</i>. returns a list of hosts declared in the filename """ f=open(filename) configobj=ConfigParser.ConfigParser() configobj.readfp(f) hosts=[] values=configobj.items("hosts") for i in configobj.options("hosts"): hosts.append(configobj.get("hosts",i)) return hosts def isAlive(self,HOST,PORT): """ Checks if the particular host <i> hostname</i>is alive and running at port <i>port</i> Todo: send some arbitrary encrypted string accepted only if that server is of my type """ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.setdefaulttimeout(0.5) try: s.connect((HOST, PORT)) m=md5.new() m.update(socket.gethostbyname(socket.gethostname())) s.send(m.hexdigest()) recvdata=s.recv(1024) #i send and receive the same data #just to ensure that i am recognizing #a server of my type. Cant help if #some custom server listens to same port #and sends back the received data #without changing the data if recvdata == m.hexdigest(): return True else: return False except socket.error, msg: s.close() return False def updateFunctionList(self): """ Updates hosts_functions list with the list of functions avaliable in live servers """ self.hosts_functions=[] for host in range(0,len(self.alivehosts)): hostname="http://"+self.alivehosts[host]+":8000" #print "hostname=",hostname server=xmlrpclib.ServerProxy(uri=hostname) self.hosts_server_access.append(server) #print server.system.listMethods() fnlist=[] fnlist=server.system.listMethods() for fn in fnlist: apdata="%d.%s" %(host,fn) self.hosts_functions.append(apdata) return self.hosts_functions def access_list(self): return self.hosts_server_access if __name__=="__main__": hosts=Hosts() print hosts.updateFunctionList() -------------- next part -------------- import socket import threading from SimpleXMLRPCServer import * import md5 def myserver(): HOST = 'localhost' # Symbolic name meaning the local host PORT = 10001 # Arbitrary non-privileged port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) while 1: s.listen(1) conn, addr = s.accept() print 'Connected by', addr data = conn.recv(1024) if not data: pass conn.send(data) conn.close() print "Connection closed" def MyRPCServer(): server = SimpleXMLRPCServer(("localhost", 8000)) server.register_function(pow) server.register_function(lambda x,y: x+y, 'add') server.register_introspection_functions() # server.register_instance(MyFuncs()) print server.system_listMethods() server.serve_forever() if __name__=="__main__": mys=threading.Thread(target=myserver) rpcs=threading.Thread(target=MyRPCServer) mys.start() rpcs.start() From kent_johnson at skillsoft.com Mon Sep 13 14:20:26 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Mon Sep 13 14:20:37 2004 Subject: [Tutor] Doubt in RPC XML lib In-Reply-To: <32b5ee760409130438734b3ad5@mail.gmail.com> References: <32b5ee7604090911376994ad31@mail.gmail.com> <32b5ee760409130438734b3ad5@mail.gmail.com> Message-ID: <6.1.0.6.0.20040913081008.0288d4a0@mail4.skillsoft.com> Varun, You can use eval() or getattr() to do what you want. For example, with your server running on port 8000, I can do this: >>> import xmlrpclib >>> server = xmlrpclib.ServerProxy('http://localhost:8000') >>> server.system.listMethods() ['add', 'pow', 'system.listMethods', 'system.methodHelp', 'system.methodSignature'] >>> server.add(1, 2) 3 >>> eval('server.add(1, 2)') 3 >>> getattr(server, 'add')(1,2) 3 I suggest you change your data structure to hold the actual server object and the names of the methods. Then you can use getattr to get the function object from the server and call it. I would create a list of (server, list of functions) where server is the actual server object, i.e. something like servers = [ (server1, ['add', 'pow']), (server2, ['foo', 'bar']) ] Then given serverNum, funcNum and args you can do server, funcNames = servers[serverNum] funcName = funcNames[funcNum] getattr(server, funcName)(args) By the way instead of for host in range(0,len(self.alivehosts)): hostname="http://"+self.alivehosts[host]+":8000" you can say for host in self.alivehosts: hostname="http://"+host+":8000" Kent At 05:08 PM 9/13/2004 +0530, Varun Soundararajan wrote: >I hv attached the two files. Actually what i am trying to do is that, >i replicate the gethosts.py and servers.py code in every system. in >every system when i start my python code, i check all servers of the >same type and add to my active hosts list. ( i do taht in gethosts.py) >in the servers.py, i serve my own server at 10001 and rpc server at >8000 using thread. My server at 10001 authenticates with other server >of my type by sending some hashed data and getting it back (just to >ensure that i am not adding some other server listening at 10001). >Now my qn is, >if i want to access a code i call: >server.somefunction() >now since i have the list of functions of form (['1.fn1', >'1.fn2','2.fn1' etc] ) when i want to call the fn1 of server 0 i shd >call >hosts_server_access[0].fn1() . but i want the user to choose that. Now >how do i do that. >in other words. >if i wanna call fn1 of server 0 i shd be able to call(say) >hosts_server_access[0][1]() or something like that. >pls help >thanks in advance >-Varun > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From vineeth at gmail.com Mon Sep 13 14:45:24 2004 From: vineeth at gmail.com (Vineeth S) Date: Mon Sep 13 14:46:13 2004 Subject: [Tutor] cgi client-pull Message-ID: <383854e0040913054542ecf17f@mail.gmail.com> Hi all, I have been trying to get a cgi script to display a wait status until a process completes, and then display the results. so the way i figured i could do this was : call the cgi script check if there is a flag set, if there is a flag set do a client pull with a refresh in the headers and a url to the same script if the flag is not, do a fork-exec to get the actual job running for some reason, this is not working, the request just waits for the process including the fork-exec to finish. i even tried an explicit exit on the process. i am pasting the code below. (a weekend has been eaten away :-( ) tia vineeth #!/usr/bin/python import cgi from math import sqrt import sys import os def genPrimes(num): primes = [] for toChek in range(3, num): primeFlag = 1 for div in range(2, int(sqrt(toChek))+1): if not (toChek % div): primeFlag = 0 break if primeFlag: primes.append(toChek) return primes form = cgi.FieldStorage() if form.has_key("repFlag"): if os.access("/tmp/done", os.F_OK): print "Content-Type: text/html\n\n" print "<html>" print "<body>" print "The output" for num in open("/tmp/op","r").readlines(): print "%s" % num.strip() print "</body>" print "</html>" else: print "Content-Type: text/html\n\n" print """ <html> <head> <META HTTP-EQUIV="Refresh" CONTENT="1; URL=http://10.1.38.233/cgi-bin/sessions.py?repFlag=1&sid=s123"> </head> <body> Please wait the results will be fetched in a short time. HeHeHe. </body> </html> """ sys.stdout.flush() else: try: os.remove("/tmp/done") except OSError: pass print "Content-Type: text/html\n\n" print """ <html> <head> <META HTTP-EQUIV="Refresh" CONTENT="1; URL=http://10.1.38.233/cgi-bin/sessions.py?repFlag=1&sid=s123"> </head> <body> Please wait the results will be fetched in a short time </body> </html> """ sys.stdout.flush() pid = os.fork() if pid == 0: os.execlp('python','python','getPrimes.py',form['num'].value.strip()) else: sys.exit() From s.varun at gmail.com Mon Sep 13 18:42:10 2004 From: s.varun at gmail.com (Varun Soundararajan) Date: Mon Sep 13 18:42:21 2004 Subject: [Tutor] Doubt in RPC XML lib In-Reply-To: <6.1.0.6.0.20040913081008.0288d4a0@mail4.skillsoft.com> References: <32b5ee7604090911376994ad31@mail.gmail.com> <32b5ee760409130438734b3ad5@mail.gmail.com> <6.1.0.6.0.20040913081008.0288d4a0@mail4.skillsoft.com> Message-ID: <32b5ee760409130942470268fa@mail.gmail.com> cool, any other comment/ like general prog structural changes, and any programming style changes that i shd do? -Varun On Mon, 13 Sep 2004 08:20:26 -0400, Kent Johnson <kent_johnson@skillsoft.com> wrote: > Varun, > > You can use eval() or getattr() to do what you want. For example, with your > server running on port 8000, I can do this: > >>> import xmlrpclib > >>> server = xmlrpclib.ServerProxy('http://localhost:8000') > >>> server.system.listMethods() > ['add', 'pow', 'system.listMethods', 'system.methodHelp', > 'system.methodSignature'] > >>> server.add(1, 2) > 3 > >>> eval('server.add(1, 2)') > 3 > >>> getattr(server, 'add')(1,2) > 3 > > I suggest you change your data structure to hold the actual server object > and the names of the methods. Then you can use getattr to get the function > object from the server and call it. > > I would create a list of (server, list of functions) where server is the > actual server object, i.e. something like > servers = [ (server1, ['add', 'pow']), (server2, ['foo', 'bar']) ] > > Then given serverNum, funcNum and args you can do > server, funcNames = servers[serverNum] > funcName = funcNames[funcNum] > getattr(server, funcName)(args) > > By the way instead of > for host in range(0,len(self.alivehosts)): > hostname="http://"+self.alivehosts[host]+":8000" > > you can say > for host in self.alivehosts: > hostname="http://"+host+":8000" > > Kent > > > > At 05:08 PM 9/13/2004 +0530, Varun Soundararajan wrote: > >I hv attached the two files. Actually what i am trying to do is that, > >i replicate the gethosts.py and servers.py code in every system. in > >every system when i start my python code, i check all servers of the > >same type and add to my active hosts list. ( i do taht in gethosts.py) > >in the servers.py, i serve my own server at 10001 and rpc server at > >8000 using thread. My server at 10001 authenticates with other server > >of my type by sending some hashed data and getting it back (just to > >ensure that i am not adding some other server listening at 10001). > >Now my qn is, > >if i want to access a code i call: > >server.somefunction() > >now since i have the list of functions of form (['1.fn1', > >'1.fn2','2.fn1' etc] ) when i want to call the fn1 of server 0 i shd > >call > >hosts_server_access[0].fn1() . but i want the user to choose that. Now > >how do i do that. > >in other words. > >if i wanna call fn1 of server 0 i shd be able to call(say) > >hosts_server_access[0][1]() or something like that. > >pls help > >thanks in advance > >-Varun > > > > > >_______________________________________________ > >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 tim at johnsons-web.com Mon Sep 13 23:55:17 2004 From: tim at johnsons-web.com (Tim Johnson) Date: Mon Sep 13 23:47:23 2004 Subject: [Tutor] Python -> uname -n Message-ID: <20040913215517.GB2024@johnsons-web.com> using python 2.0+ (versions 2.0 and later).. How may I obtain the network node hostname with python? On linux, it would be the value returned by 'uname -n' TIA tim -- Tim Johnson <tim@johnsons-web.com> http://www.alaska-internet-solutions.com From tim at johnsons-web.com Tue Sep 14 00:17:20 2004 From: tim at johnsons-web.com (Tim Johnson) Date: Tue Sep 14 00:09:25 2004 Subject: [Tutor] Python -> uname -n In-Reply-To: <20040913215517.GB2024@johnsons-web.com> References: <20040913215517.GB2024@johnsons-web.com> Message-ID: <20040913221720.GC2024@johnsons-web.com> * Tim Johnson <tim@johnsons-web.com> [040913 13:58]: > using python 2.0+ (versions 2.0 and later).. > > How may I obtain the network node hostname with python? > > On linux, it would be the value returned by > 'uname -n' Found it all by my lonesome, under Python Library Reference, the 'commands' module. commands.getstatusoutput('uname -n') returns a 2 - member tuple with status code as the first item and response string as second item. Unix only, I guess. Any comments, caveats, cautions are welcome. Wow! Is python like a Swiss Army Knife or what? cheers tim -- Tim Johnson <tim@johnsons-web.com> http://www.alaska-internet-solutions.com From dyoo at hkn.eecs.berkeley.edu Tue Sep 14 00:19:36 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Sep 14 00:20:37 2004 Subject: [Tutor] Python -> uname -n In-Reply-To: <20040913221720.GC2024@johnsons-web.com> Message-ID: <Pine.LNX.4.44.0409131517060.855-100000@hkn.eecs.berkeley.edu> On Mon, 13 Sep 2004, Tim Johnson wrote: > > How may I obtain the network node hostname with python? > > > > On linux, it would be the value returned by 'uname -n' > > Found it all by my lonesome, under Python Library Reference, the > 'commands' module. > > commands.getstatusoutput('uname -n') returns a 2 - member tuple with > status code as the first item and response string as second item. Hi Tim, You might be able to get it with 'socket.gethostname()' as well: ### >>> import socket >>> socket.gethostname() 'shoebox' ### See: http://www.python.org/doc/lib/module-socket.html#l2h-2417 for more details on socket.gethostname(). Good luck! From tim at johnsons-web.com Tue Sep 14 01:34:44 2004 From: tim at johnsons-web.com (Tim Johnson) Date: Tue Sep 14 01:26:50 2004 Subject: [Tutor] Python -> uname -n In-Reply-To: <Pine.LNX.4.44.0409131517060.855-100000@hkn.eecs.berkeley.edu> References: <20040913221720.GC2024@johnsons-web.com> <Pine.LNX.4.44.0409131517060.855-100000@hkn.eecs.berkeley.edu> Message-ID: <20040913233444.GD2024@johnsons-web.com> * Danny Yoo <dyoo@hkn.eecs.berkeley.edu> [040913 14:35]: > > > On Mon, 13 Sep 2004, Tim Johnson wrote: > > > > How may I obtain the network node hostname with python? > > > > > > On linux, it would be the value returned by 'uname -n' > > > > Found it all by my lonesome, under Python Library Reference, the > > 'commands' module. > > > > commands.getstatusoutput('uname -n') returns a 2 - member tuple with > > status code as the first item and response string as second item. > > > Hi Tim, > > > You might be able to get it with 'socket.gethostname()' as well: The commands module will prove to be very helpful in other issues for me, but I see that the socket module is more portable and won't make python barf in Windows, so it looks like the 'socket' aproach is preferable. Thanks Danny tim > ### > >>> import socket > >>> socket.gethostname() > 'shoebox' > ### > > > See: > > http://www.python.org/doc/lib/module-socket.html#l2h-2417 > > for more details on socket.gethostname(). > > > Good luck! > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Tim Johnson <tim@johnsons-web.com> http://www.alaska-internet-solutions.com From lysdexia at crackrabbit.com Tue Sep 14 08:14:03 2004 From: lysdexia at crackrabbit.com (Douglas N. Shawhan) Date: Tue Sep 14 08:14:45 2004 Subject: [Tutor] Reading an html file into a cgi script. Message-ID: <41468C2B.8070403@crackrabbit.com> I would like to pull lines from an html file and include them in a cgi script. (python2.1, openbsd 3.5, apache) I have a file called 'header.html', which contains the lines: '''Content-type: text/html\n\n''' '''<table><tr>''' I then attempt to load it from the script: HEADER = open('header.html', 'r') HEADER = HEADER.readlines() for line in HEADER: print line The "Content-type" line may or may not be parsed correctly - it doesn't show up in the output, but the html contained in the file is definitely not parsed: '''<table><tr>''' Tue Sep 14 00:58:30 2004 | None | 1313 Mockingbird ln.| None | 1095141610.24 | 1095142510.24 <td>Tue Sep 14 00:58:30 2004 | None | 1313 Mockingbird ln.| None | 1095141610.24 | 1095142510.24</td> <td>Tue Sep 14 00:58:30 2004 | None | 1313 Mockingbird ln.| None | 1095141610.24 | 1095142510.24</td> <td>Tue Sep 14 00:58:30 2004 | None | 1313 Mockingbird ln.| None | 1095141610.24 | 1095142510.24</td> <td>Tue Sep 14 00:58:30 2004 | None | 1313 Mockingbird ln.| None | 1095141610.24 | 1095142510.24</td> '''</table>''' Note that the first line has no <td> tags. *scratch* *scratch* What am I missing here? From eric at digitalert.net Tue Sep 14 08:28:52 2004 From: eric at digitalert.net (Eric) Date: Tue Sep 14 08:28:20 2004 Subject: [Tutor] Search text file, perform action if a given item found in file In-Reply-To: <6.1.0.6.0.20040913055421.0299a848@mail4.skillsoft.com> References: <414019B2.8080807@digitalert.net> <41401B8C.1000708@digitalert.net> <6.1.0.6.0.20040909081224.028926a0@mail4.skillsoft.com> <4140A038.9040504@digitalert.net> <41416663.5080809@digitalert.net> <6.1.0.6.0.20040910055620.0296f1b8@mail4.skillsoft.com> <4145445D.9050506@digitalert.net> <6.1.0.6.0.20040913055421.0299a848@mail4.skillsoft.com> Message-ID: <41468FA4.4060801@digitalert.net> Here is the result of the first part of my script. I figure it may help out another newbie someday. Thanks for the help though. I would not have made it this far without it. import os o=os.popen("netstat -an") PORT = int(raw_input("What tcp/udp should I watch for?: ")) for l in o: try: if l.split()[1].endswith(str(PORT)): print "\a\a\a\aHere is a match!" else: print "Nothing" except IndexError: print "Index Excpetion" raw_input("Press enter to close") Kent Johnson wrote: > Eric, > > It's a difference between netstat on Windows and FreeBSD. The windows > version includes a few header lines that don't split the way you > expect - the resulting list doesn't have two elements: > >>> import os > >>> f=os.popen('netstat -an') > >>> for l in f: > ... print len(l.split()) > ... > 0 > 2 > 0 > 6 > 4 > 4 > etc... > > You could check the length of the split before you do further > processing, or you could catch the exception and continue the loop. > > Kent From pathall at gmail.com Tue Sep 14 09:49:09 2004 From: pathall at gmail.com (Patrick Hall) Date: Tue Sep 14 09:49:12 2004 Subject: [Tutor] Reading an html file into a cgi script. In-Reply-To: <41468C2B.8070403@crackrabbit.com> References: <41468C2B.8070403@crackrabbit.com> Message-ID: <6465924d0409140049691445d0@mail.gmail.com> Hi, > I have a file called 'header.html', which contains the lines: > > '''Content-type: text/html\n\n''' > '''<table><tr>''' Are those quotes really in header.html? If so, try removing them. Also, I think you'll have to change those \n's to actual newlines. The Content-type line doesn't get seen in the source of the rendered html page. It's an HTTP header -- it indicates what kind of file the content is. If your browser is at least trying to render the page as html, then the Content-type line has done its job. Hope that helps, Pat From padmaja at agere.com Tue Sep 14 12:31:10 2004 From: padmaja at agere.com (Jayanthi, Satya Padmaja (Satya Padmaja)) Date: Tue Sep 14 12:31:18 2004 Subject: [Tutor] Debug Assertion Failed !!! Message-ID: <DFCB7C708B1AA94FABFBF6E1F7E984542E6E19@iiex2ku01.agere.com> Hi all : I am running a python program, which is internally calling TCL APIs. I am using Tkinter as an interface between the two languages, Python and TCL. The whole script runs pretty well, without any problem. But, at the end of the run, a window pops up with the following message, Debug Assertion Failed !!! Program : F\Python23\python.exe File : dbgheap.c Line : 1044 Expression : _CrtIsValidHeapPointer(pUserData)... Can anyone please tell me why I am getting this error and how can I avoid it ? Thanks in advance, Padmaja -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040914/75a5a8fc/attachment.htm From s.e.murdock at soton.ac.uk Tue Sep 14 12:31:30 2004 From: s.e.murdock at soton.ac.uk (Stuart Murdock) Date: Tue Sep 14 12:31:56 2004 Subject: [Tutor] Latex from docstrings Message-ID: <4146C882.3060606@soton.ac.uk> Hi I have lots of Python code which is well commented (docstrings) and I want to create a reference manual for this code using latex. I need to include the Python docstrings in my latex document. The trouble is that most of the document generators produce (pydoc etc.) the documentation in a way which I find difficult to include in latex i.e. the documentation generators produce pdf or html quite easily. Are there any documentation generators out there which produce latex files, or can anyone see a nice solution to my problem? The extract_doc.py package seems to be on the case but they dont seem to have implemented the latex flag yet. http://www.rexx.com/~dkuhlman/extract_doc.html *-l, *--latex** Generate LaTeX for the Python LaTeX documentation system. Not yet implemented. Thanks for your help Stuart -- Stuart Murdock Ph.D, Research Fellow, Dept. of Chemistry / E-Science, University of Southampton, Highfield, Southampton, SO17 1BJ, United Kingdom http://www.biosimgrid.org From kent_johnson at skillsoft.com Tue Sep 14 12:38:02 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Tue Sep 14 12:38:28 2004 Subject: [Tutor] Reading an html file into a cgi script. In-Reply-To: <41468C2B.8070403@crackrabbit.com> References: <41468C2B.8070403@crackrabbit.com> Message-ID: <6.1.0.6.0.20040914063638.028a2710@mail4.skillsoft.com> You don't seem to have shown us the code that generates the <td> lines. If the header file ends with the <table> line, where are the next lines generated? Kent At 01:14 AM 9/14/2004 -0500, Douglas N. Shawhan wrote: >I would like to pull lines from an html file and include them in a cgi >script. (python2.1, openbsd 3.5, apache) > >I have a file called 'header.html', which contains the lines: > >'''Content-type: text/html\n\n''' >'''<table><tr>''' > >I then attempt to load it from the script: > >HEADER = open('header.html', 'r') >HEADER = HEADER.readlines() >for line in HEADER: > print line > >The "Content-type" line may or may not be parsed correctly - it doesn't >show up in the output, but the html contained in the file is definitely >not parsed: > >'''<table><tr>''' > > > >Tue Sep 14 00:58:30 2004 | None | 1313 Mockingbird ln.| None | >1095141610.24 | 1095142510.24 ><td>Tue Sep 14 00:58:30 2004 | None | 1313 Mockingbird ln.| None | >1095141610.24 | 1095142510.24</td> ><td>Tue Sep 14 00:58:30 2004 | None | 1313 Mockingbird ln.| None | >1095141610.24 | 1095142510.24</td> ><td>Tue Sep 14 00:58:30 2004 | None | 1313 Mockingbird ln.| None | >1095141610.24 | 1095142510.24</td> ><td>Tue Sep 14 00:58:30 2004 | None | 1313 Mockingbird ln.| None | >1095141610.24 | 1095142510.24</td> > >'''</table>''' > > > >Note that the first line has no <td> tags. *scratch* *scratch* > >What am I missing here? > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From s4046441 at student.uq.edu.au Tue Sep 14 12:41:09 2004 From: s4046441 at student.uq.edu.au (Ms Soo Chong) Date: Tue Sep 14 12:41:18 2004 Subject: [Tutor] Question on open and read html files and psycopg Message-ID: <48ec2848d429.48d42948ec28@uq.edu.au> Hi all, Thanks for your reply (Lee Harr). I have a question regarding python script opening and reading HTML files. Can python read a html file containing frames? Because when I include this portion in my script: ------------------------------------------------------------------------------------- fp=open("/var/www/cgi-bin/sf/frame.html", "r") listOfLines= fp.readlines() for eachline in listOfLines: print eachline.strip() fp.close() ------------------------------------------------------------------------------------- This is the frame.html: ------------------------------------------------------------------------------------- <html> <head> <title>T4 Web Browser</title></head> <frameset rows="80,*" BORDER=0> <frame name="banner" scrolling="no" noresize target="contents" src="title_bar.html"> <frameset cols="150,*" border=1> <frame name="contents" target="main" src="side_bar.html" scrolling="auto"> <frame name="main" src="trial1.html" scrolling="auto"> </frameset> <noframes><p>Hi, the page you are attempting to enter has frames and if you're reading this message, you don't have the ability to see it. In order to view this page, you will need to update your browser. <p>Updates are available from <a href="http://www.microsoft.com/">www.microsoft.com</a> for Internet Explorer or <a href="http://www.netscape.com/">www.netscape.com</a> for Netscape Navigator. </noframes> </frameset> </html> -------------------------------------------------------------------------------------- what the web browser returned is a web page containing the frames that I have set up but not the contents of them. The frame.html consists of three more html files - title_bar.html, side_bar.html and trial1.html. That is trial1.py is capable of opening up and reading the frame.html file and display the frames but can't read the rest. Thus, when i changed the frame.html to any of the html files, trial1.py runs perfectly. I just wonder if anyone can tell me whether I'm right that python can't read html files within another html file. (I hope someone get what I said);O Or please explain to me why does this happened? Thanks for any help. One more question on psycopg Finally, my machine is installed with psycopg and I'm wanna to try out it. Because, I'm a newbie so I find it difficult to write a program that is capable of querying the database and display the result via a web browser whenever a user do a keyword search. I have a postgreSQL DB up and running, my problem is with the code. Are there anyone that is willing to share his/her source code that does similar stuffs as mine do? Any help will be greatly appreciate. Thank you. Cheers, Shufen -------------- next part -------------- #!/usr/bin/env python #Author: Chong Soo Fern #Created on: 31/08/04 import sys sys.stderr = sys.stdout #Import the CGI module. import cgi #Turn on CGI debugging info. import cgitb; cgitb.enable() #Required header that tells the browser how to render the HTML. print"Content-Type: text/html\n\n" #Get the content from the HTML file. try: fp=open("/var/www/cgi-bin/sf/trial1.html", "r") listOfLines= fp.readlines() for eachline in listOfLines: print eachline.strip() fp.close() except Exception: print 'hello 2' #Get the form data, if any form = cgi.FieldStorage() #No form data means this is the first access; output the form. if not form.has_key("data"): print"""<FORM METHOD="POST" ACTION="/cgi-bin/sf/trial1.py"> <P> Type your query here:<BR> <TEXTAREA NAME=data VALUE="" ROWS=3 COLS=90 TYPE=text></TEXTAREA><BR> <P> <INPUT TYPE=submit VALUE="Submit Query"><BR> </FORM>""" else: #We do have form data; just show it. print "You typed this:" my_query = form.getvalue("data") print my_query # It seems that we need to have an appropriate username that matches # an entry in the postgresql table of users. import os username = os.environ.get('USER') # print "username: ", username, type(username) if username == None: # Assume that the web server has started this script and has the # username 'apache'. To allow this to access the database, we had # to create a postgresql user of that name and have no password. # This new user is also able to create tables and new users, # otherwise the access seems to be blocked. (This might be a # security problem but only for our database tables.) username = 'apache' # Now, we can get to the database... import pg db = pg.connect("moncdata", user=username, passwd=None) qresult = db.query(my_query) listOfResults = qresult.dictresult() # Have a look at http://www.pygresql.org/README.txt to get documentation # on the pgqueryobject methods. # Make sure that we have a string. resultString = repr(listOfResults) print "<P>Raw result obtained from database:</P>" print resultString print "" print "<P>Example of pulling the list of dictionary results apart.</P>" for record in listOfResults: print "<P><table>" for k in record.keys(): print "<tr> <td>key:</td> <td>", k, "</td> <td>value:</td> <td>", \ record[k], "</td> </tr>" print "</table></P>" db.close() #HTML end print"</BODY></HTML>" From kent_johnson at skillsoft.com Tue Sep 14 12:48:32 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Tue Sep 14 12:48:37 2004 Subject: [Tutor] Latex from docstrings In-Reply-To: <4146C882.3060606@soton.ac.uk> References: <4146C882.3060606@soton.ac.uk> Message-ID: <6.1.0.6.0.20040914064715.028a1b88@mail4.skillsoft.com> It looks like you can use extract_doc to create reStructured text, then use DocUtils to convert that to latex, have you tried that? Kent At 10:31 AM 9/14/2004 +0000, Stuart Murdock wrote: >Hi > >I have lots of Python code which is well commented (docstrings) and I want >to create a reference manual for this code using latex. > >I need to include the Python docstrings in my latex document. The trouble >is that most of the document generators produce (pydoc etc.) >the documentation in a way which I find difficult to include in latex i.e. >the documentation generators produce pdf or html quite >easily. Are there any documentation generators out there which produce >latex files, or can anyone see a nice solution to my problem? > >The extract_doc.py package seems to be on the case but they dont seem to >have implemented the latex flag yet. > >http://www.rexx.com/~dkuhlman/extract_doc.html > >*-l, *--latex** > Generate LaTeX for the Python LaTeX documentation system. Not yet >implemented. > > > >Thanks for your help > >Stuart > >-- > >Stuart Murdock Ph.D, >Research Fellow, >Dept. of Chemistry / E-Science, >University of Southampton, >Highfield, Southampton, >SO17 1BJ, United Kingdom >http://www.biosimgrid.org > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From my.mailing.lists at noos.fr Tue Sep 14 12:52:09 2004 From: my.mailing.lists at noos.fr (nik) Date: Tue Sep 14 12:52:46 2004 Subject: [Tutor] extracting lists from lists of lists In-Reply-To: <6.1.0.6.0.20040912174945.029b0530@mail4.skillsoft.com> References: <BAY16-F28oqdNKn64sa000bc867@hotmail.com> <6.1.0.6.0.20040912174945.029b0530@mail4.skillsoft.com> Message-ID: <4146CD59.9040406@noos.fr> hi, I have a class which is just a holder for a data structure, and for some reason I've decided to hold the data in the following form; class myData: data = [ ["name", ""], ["age", ""], ["gender", ""] ] I'm not totally sure it's the best way, but it strikes me as something that can be easily manipulated into maps etc. I had started out with class myData: name = "" age = "" gender = "" but I found that I had to put most of those items into lists to do anything with them. So apart from any advice on holding data like that, I was wondering if there's any cool way to get the values into a tuple? ie [ ["name", "john"], ["age", "88"], ["gender", "M"] ] -> ("john", "88", "M") I can use a for loop probably, but I've seen people do some very clever stuff with slicing and multiple assignment (which I'm still getting to grips with, but loving). Any suggestions? Suggestions for holding the data differently initially are welcome too (I'd like the data to be obvious to users that they shouldn't change the names, but be able to easily add/change/manipulate the values). thanks, nik From bill.mill at gmail.com Tue Sep 14 13:05:44 2004 From: bill.mill at gmail.com (Bill Mill) Date: Tue Sep 14 13:05:48 2004 Subject: [Tutor] extracting lists from lists of lists In-Reply-To: <4146CD59.9040406@noos.fr> References: <BAY16-F28oqdNKn64sa000bc867@hotmail.com> <6.1.0.6.0.20040912174945.029b0530@mail4.skillsoft.com> <4146CD59.9040406@noos.fr> Message-ID: <797fe3d404091404054511ab05@mail.gmail.com> Nik, Take a look at dictionaries - http://docs.python.org/tut/node7.html#SECTION007400000000000000000 . They let you create a mapping from keys to data. See: In [34]: stuff = {'name': 'john', 'age': '88', 'gender': 'M'} In [35]: stuff['name'] Out[35]: 'john' In [36]: stuff['age'] Out[36]: '88' In [37]: (stuff['name'], stuff['age'], stuff['gender']) Out[37]: ('john', '88', 'M') Hope this helps. Peace Bill Mill On Tue, 14 Sep 2004 12:52:09 +0200, nik <my.mailing.lists@noos.fr> wrote: > hi, > > I have a class which is just a holder for a data structure, and for some > reason I've decided to hold the data in the following form; > > class myData: > data = [ ["name", ""], ["age", ""], ["gender", ""] ] > > I'm not totally sure it's the best way, but it strikes me as something > that can be easily manipulated into maps etc. I had started out with > class myData: > name = "" > age = "" > gender = "" > > but I found that I had to put most of those items into lists to do > anything with them. > > So apart from any advice on holding data like that, I was wondering if > there's any cool way to get the values into a tuple? > > ie [ ["name", "john"], ["age", "88"], ["gender", "M"] ] -> ("john", > "88", "M") > > I can use a for loop probably, but I've seen people do some very clever > stuff with slicing and multiple assignment (which I'm still getting to > grips with, but loving). Any suggestions? > > Suggestions for holding the data differently initially are welcome too > (I'd like the data to be obvious to users that they shouldn't change the > names, but be able to easily add/change/manipulate the values). > > thanks, > nik > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From chandrashekar.mc at c2silicon.com Tue Sep 14 13:16:11 2004 From: chandrashekar.mc at c2silicon.com (Chandrashekar M.C.) Date: Tue Sep 14 13:16:37 2004 Subject: [Tutor] extracting lists from lists of lists In-Reply-To: <4146CD59.9040406@noos.fr> Message-ID: <000001c49a4c$47886690$142aa8c0@kaveri.c2silicon.com> Hi Nik, The better data structure for your data is 'dictionary' and not 'list of list'. Strings like 'name', 'age', 'gender' can be dictionary_keys and their corresponding values will be dictionary_values. Once you store the data in the dictionary, there are several dictionary methods(functions) to print only values or keys. -Chandru -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of nik Sent: Tuesday, September 14, 2004 4:22 PM To: tutor@python.org Subject: [Tutor] extracting lists from lists of lists hi, I have a class which is just a holder for a data structure, and for some reason I've decided to hold the data in the following form; class myData: data = [ ["name", ""], ["age", ""], ["gender", ""] ] I'm not totally sure it's the best way, but it strikes me as something that can be easily manipulated into maps etc. I had started out with class myData: name = "" age = "" gender = "" but I found that I had to put most of those items into lists to do anything with them. So apart from any advice on holding data like that, I was wondering if there's any cool way to get the values into a tuple? ie [ ["name", "john"], ["age", "88"], ["gender", "M"] ] -> ("john", "88", "M") I can use a for loop probably, but I've seen people do some very clever stuff with slicing and multiple assignment (which I'm still getting to grips with, but loving). Any suggestions? Suggestions for holding the data differently initially are welcome too (I'd like the data to be obvious to users that they shouldn't change the names, but be able to easily add/change/manipulate the values). thanks, nik _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From lysdexia at crackrabbit.com Tue Sep 14 14:44:31 2004 From: lysdexia at crackrabbit.com (Douglas N. Shawhan) Date: Tue Sep 14 14:45:28 2004 Subject: [Fwd: Re: [Tutor] Reading an html file into a cgi script.] Message-ID: <4146E7AF.3060706@crackrabbit.com> -------------- next part -------------- An embedded message was scrubbed... From: "Douglas N. Shawhan" <lysdexia@crackrabbit.com> Subject: Re: [Tutor] Reading an html file into a cgi script. Date: Tue, 14 Sep 2004 07:43:29 -0500 Size: 1471 Url: http://mail.python.org/pipermail/tutor/attachments/20040914/a9195eb3/TutorReadinganhtmlfileintoacgiscript.mht From kent_johnson at skillsoft.com Tue Sep 14 15:12:15 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Tue Sep 14 15:12:18 2004 Subject: [Tutor] extracting lists from lists of lists In-Reply-To: <4146CD59.9040406@noos.fr> References: <BAY16-F28oqdNKn64sa000bc867@hotmail.com> <6.1.0.6.0.20040912174945.029b0530@mail4.skillsoft.com> <4146CD59.9040406@noos.fr> Message-ID: <6.1.0.6.0.20040914090220.028ac9a8@mail4.skillsoft.com> At 12:52 PM 9/14/2004 +0200, nik wrote: >hi, > >I have a class which is just a holder for a data structure, and for some >reason I've decided to hold the data in the following form; > >class myData: > data = [ ["name", ""], ["age", ""], ["gender", ""] ] > >I'm not totally sure it's the best way, but it strikes me as something >that can be easily manipulated into maps etc. I had started out with >class myData: > name = "" > age = "" > gender = "" > >but I found that I had to put most of those items into lists to do >anything with them. What kinds of things are you doing that you need these values in a list? It sounds like maybe you are trying to pull the data out of the class to pass to another function, but maybe it would be better to pass the class itself around? Or maybe you should get rid of the class entirely and just use a dictionary. >So apart from any advice on holding data like that, I was wondering if >there's any cool way to get the values into a tuple? > >ie [ ["name", "john"], ["age", "88"], ["gender", "M"] ] -> ("john", >"88", "M") List comprehension to the rescue! >>> tuple( [ item[1] for item in [ ["name", "john"], ["age", "88"], ["gender", "M"] ] ] ) ('john', '88', 'M') >I can use a for loop probably, but I've seen people do some very clever >stuff with slicing and multiple assignment (which I'm still getting to >grips with, but loving). Any suggestions? > >Suggestions for holding the data differently initially are welcome too >(I'd like the data to be obvious to users that they shouldn't change the >names, but be able to easily add/change/manipulate the values). A class is good for that. Kent >thanks, >nik > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From MLists at romulo.de Tue Sep 14 15:28:12 2004 From: MLists at romulo.de (Rainer Mansfeld) Date: Tue Sep 14 15:28:21 2004 Subject: [Tutor] Python -> uname -n In-Reply-To: <20040913233444.GD2024@johnsons-web.com> References: <20040913221720.GC2024@johnsons-web.com> <Pine.LNX.4.44.0409131517060.855-100000@hkn.eecs.berkeley.edu> <20040913233444.GD2024@johnsons-web.com> Message-ID: <4146F1EC.2000806@romulo.de> Tim Johnson wrote: > The commands module will prove to be very helpful in other issues > for me, but I see that the socket module is more portable and > won't make python barf in Windows, so it looks like the > 'socket' aproach is preferable. > Hi Tim, just in case you don't have access to a windows box. On windows I got: >>> import commands >>> commands.getstatusoutput('uname -n') (0, '') >>> import socket >>> socket.gethostname() 'Mars' HTH Rainer From my.mailing.lists at noos.fr Tue Sep 14 15:45:42 2004 From: my.mailing.lists at noos.fr (nik) Date: Tue Sep 14 15:45:47 2004 Subject: [Tutor] extracting lists from lists of lists In-Reply-To: <6.1.0.6.0.20040914090220.028ac9a8@mail4.skillsoft.com> References: <BAY16-F28oqdNKn64sa000bc867@hotmail.com> <6.1.0.6.0.20040912174945.029b0530@mail4.skillsoft.com> <4146CD59.9040406@noos.fr> <6.1.0.6.0.20040914090220.028ac9a8@mail4.skillsoft.com> Message-ID: <4146F606.4040503@noos.fr> Kent Johnson wrote: > At 12:52 PM 9/14/2004 +0200, nik wrote: > >> hi, >> >> I have a class which is just a holder for a data structure, and for >> some reason I've decided to hold the data in the following form; >> >> class myData: >> data = [ ["name", ""], ["age", ""], ["gender", ""] ] >> >> I'm not totally sure it's the best way, but it strikes me as >> something that can be easily manipulated into maps etc. I had started >> out with >> class myData: >> name = "" >> age = "" >> gender = "" >> >> but I found that I had to put most of those items into lists to do >> anything with them. > > > What kinds of things are you doing that you need these values in a > list? It sounds like maybe you are trying to pull the data out of the > class to pass to another function, but maybe it would be better to > pass the class itself around? Or maybe you should get rid of the class > entirely and just use a dictionary. > I'm thinking in terms of a C struct - it's a handy parcel to move a set of data around, and quite likely there'll be stacks of sets. There's no extra functionality required from the set, and I'm not planning on deriving any other classes from this one. The dictionary seems a very good idea, but I think I still need to put it into a class since I'll have multiple instances of it - is that right? or can I do the equivalent of a typedef? >> So apart from any advice on holding data like that, I was wondering >> if there's any cool way to get the values into a tuple? >> >> ie [ ["name", "john"], ["age", "88"], ["gender", "M"] ] -> >> ("john", "88", "M") > > > List comprehension to the rescue! > >>> tuple( [ item[1] for item in [ ["name", "john"], ["age", "88"], > ["gender", "M"] ] ] ) > ('john', '88', 'M') > shortly after sending my first email I managed to come up with tuple ( y for x,y in [ ["name", "john"], ["age", "88"], ["gender", "M"] ] ] ) which is the same thing I guess. I felt very smug with myself :-) I wish I could have similar smug moments with the firebird database I'm trying to connect this all to.... If I use a dictionary, ie what Bill said; (stuff['name'], stuff['age'], stuff['gender']) # stuff being the dictionary object it's going to be longer, but I realise that there'll be no confusion over the order of the resulting tuple, whereas if my user alters the order of my list it would create a messed up tuple. nik >> I can use a for loop probably, but I've seen people do some very >> clever stuff with slicing and multiple assignment (which I'm still >> getting to grips with, but loving). Any suggestions? >> >> Suggestions for holding the data differently initially are welcome >> too (I'd like the data to be obvious to users that they shouldn't >> change the names, but be able to easily add/change/manipulate the >> values). > > > A class is good for that. > > Kent > > >> thanks, >> 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 kent_johnson at skillsoft.com Tue Sep 14 16:12:23 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Tue Sep 14 16:12:30 2004 Subject: [Tutor] extracting lists from lists of lists In-Reply-To: <4146F606.4040503@noos.fr> References: <BAY16-F28oqdNKn64sa000bc867@hotmail.com> <6.1.0.6.0.20040912174945.029b0530@mail4.skillsoft.com> <4146CD59.9040406@noos.fr> <6.1.0.6.0.20040914090220.028ac9a8@mail4.skillsoft.com> <4146F606.4040503@noos.fr> Message-ID: <6.1.0.6.0.20040914100556.029df340@mail4.skillsoft.com> I still don't understand why you can't use a simple class for this. You can pass around instances of the class instead of tuples. You can make lists or sets of class instances when you need more than one. Or if you decide to use a dict, you can pass that directly to clients instead of making it into a tuple. Can you give an example of how you will use the tuples? Finally, you might be interested in some recipes in the online Python Cookbook (http://aspn.activestate.com/ASPN/Cookbook/Python) for making tuples with named members. They are immutable though, I think you said you want users to be able to change the values. Kent At 03:45 PM 9/14/2004 +0200, nik wrote: >Kent Johnson wrote: > >>At 12:52 PM 9/14/2004 +0200, nik wrote: >> >>>hi, >>> >>>I have a class which is just a holder for a data structure, and for some >>>reason I've decided to hold the data in the following form; >>> >>>class myData: >>> data = [ ["name", ""], ["age", ""], ["gender", ""] ] >>> >>>I'm not totally sure it's the best way, but it strikes me as something >>>that can be easily manipulated into maps etc. I had started out with >>>class myData: >>> name = "" >>> age = "" >>> gender = "" >>> >>>but I found that I had to put most of those items into lists to do >>>anything with them. >> >> >>What kinds of things are you doing that you need these values in a list? >>It sounds like maybe you are trying to pull the data out of the class to >>pass to another function, but maybe it would be better to pass the class >>itself around? Or maybe you should get rid of the class entirely and just >>use a dictionary. > >I'm thinking in terms of a C struct - it's a handy parcel to move a set >of data around, and quite likely there'll be stacks of sets. There's no >extra functionality required from the set, and I'm not planning on >deriving any other classes from this one. The dictionary seems a very good >idea, but I think I still need to put it into a class since I'll have >multiple instances of it - is that right? or can I do the equivalent of a >typedef? From my.mailing.lists at noos.fr Tue Sep 14 16:58:17 2004 From: my.mailing.lists at noos.fr (nik) Date: Tue Sep 14 16:58:23 2004 Subject: [Tutor] extracting lists from lists of lists In-Reply-To: <6.1.0.6.0.20040914100556.029df340@mail4.skillsoft.com> References: <BAY16-F28oqdNKn64sa000bc867@hotmail.com> <6.1.0.6.0.20040912174945.029b0530@mail4.skillsoft.com> <4146CD59.9040406@noos.fr> <6.1.0.6.0.20040914090220.028ac9a8@mail4.skillsoft.com> <4146F606.4040503@noos.fr> <6.1.0.6.0.20040914100556.029df340@mail4.skillsoft.com> Message-ID: <41470709.8050103@noos.fr> Kent Johnson wrote: > I still don't understand why you can't use a simple class for this. > You can pass around instances of the class instead of tuples. You can > make lists or sets of class instances when you need more than one. > > Or if you decide to use a dict, you can pass that directly to clients > instead of making it into a tuple. > > Can you give an example of how you will use the tuples? > > Finally, you might be interested in some recipes in the online Python > Cookbook (http://aspn.activestate.com/ASPN/Cookbook/Python) for making > tuples with named members. They are immutable though, I think you said > you want users to be able to change the values. > > Kent > The tuples are for the kinterbasDB commands, like; newPeople = ( ('Lebed' , 53), ('Zhirinovsky' , 57), ) for person in newPeople: cur.execute("insert into people (name_last, age) values (?, ?)", person) That's the only place I need a tuple from my data structure, I have no other need to pass a tuple anywhere. My (C++) application continually creates the data structures which ends up in a list in a python module. The items in the list can then pass through various actions like values getting changed (mapping or mathmatical operations), database entry and manipulation, or even sent through a socket to somewhere else. All the actions are in various python scripts which I'm allowing my users to edit freely (since they all have different requirements). I'd like to keep their life as simple as possible, and at the heart of that is this data structure. Maybe I'm thinking too hard about it, and the original class myData: name = "" age = "" gender = "" was actually the simplest and clearest. I was concerned that a user would delete some of the items, causing problems later in the system. Also possibly I'm hung up on the idea of member variables in C++? nik > At 03:45 PM 9/14/2004 +0200, nik wrote: > >> Kent Johnson wrote: >> >>> At 12:52 PM 9/14/2004 +0200, nik wrote: >>> >>>> hi, >>>> >>>> I have a class which is just a holder for a data structure, and for >>>> some reason I've decided to hold the data in the following form; >>>> >>>> class myData: >>>> data = [ ["name", ""], ["age", ""], ["gender", ""] ] >>>> >>>> I'm not totally sure it's the best way, but it strikes me as >>>> something that can be easily manipulated into maps etc. I had >>>> started out with >>>> class myData: >>>> name = "" >>>> age = "" >>>> gender = "" >>>> >>>> but I found that I had to put most of those items into lists to do >>>> anything with them. >>> >>> >>> >>> What kinds of things are you doing that you need these values in a >>> list? It sounds like maybe you are trying to pull the data out of >>> the class to pass to another function, but maybe it would be better >>> to pass the class itself around? Or maybe you should get rid of the >>> class entirely and just use a dictionary. >> >> >> I'm thinking in terms of a C struct - it's a handy parcel to move a >> set of data around, and quite likely there'll be stacks of sets. >> There's no extra functionality required from the set, and I'm not >> planning on deriving any other classes from this one. The dictionary >> seems a very good idea, but I think I still need to put it into a >> class since I'll have multiple instances of it - is that right? or >> can I do the equivalent of a typedef? > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > From kent_johnson at skillsoft.com Tue Sep 14 17:36:26 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Tue Sep 14 17:36:27 2004 Subject: [Tutor] extracting lists from lists of lists In-Reply-To: <41470709.8050103@noos.fr> References: <BAY16-F28oqdNKn64sa000bc867@hotmail.com> <6.1.0.6.0.20040912174945.029b0530@mail4.skillsoft.com> <4146CD59.9040406@noos.fr> <6.1.0.6.0.20040914090220.028ac9a8@mail4.skillsoft.com> <4146F606.4040503@noos.fr> <6.1.0.6.0.20040914100556.029df340@mail4.skillsoft.com> <41470709.8050103@noos.fr> Message-ID: <6.1.0.6.0.20040914111228.0297eec0@mail4.skillsoft.com> OK, thanks for the explanation! I'm still thinking a class is a good idea. You want a data abstraction that is easy to use and whose use is clear. Classes are good at this. For example you could create an asTuple() method to return the class data as a tuple for use in the database calls. You can use class properties and __slots__ to make it so fields can't be added to or deleted from the class. You have a place to put other methods that work with the same data. If you use a dict to hold the data, users can delete entries in their own code, they don't even have to change the source you give them. Plus the code to convert to a tuple has no home unless you make a class to wrap the dict, but then you're back to using a class. For the database access, you might want to provide some kind of wrapper class that makes it easy for users to access the database correctly. The example you give is fragile with any implementation of the data - if a table column is added or the order of columns in the insert is changed then the insert will break. If you are giving the users complete source, you can't really make the application bulletproof. Your best bet is to provide useful abstractions organized into functional layers so they aren't tempted to change your code so much. By the way your class definition should assign the instance variables in the constructor, something like this: class myData: def __init__(self, name, age, gender): self.name = name self.age = age self.gender = gender def asTuple(self): return (self.name, self.age, self.gender) And what is wrong with C++ member variables? A C++ struct is just a class with no methods, just fields. Kent At 04:58 PM 9/14/2004 +0200, nik wrote: >Kent Johnson wrote: > >>I still don't understand why you can't use a simple class for this. You >>can pass around instances of the class instead of tuples. You can make >>lists or sets of class instances when you need more than one. >> >>Or if you decide to use a dict, you can pass that directly to clients >>instead of making it into a tuple. >> >>Can you give an example of how you will use the tuples? >> >>Finally, you might be interested in some recipes in the online Python >>Cookbook (http://aspn.activestate.com/ASPN/Cookbook/Python) for making >>tuples with named members. They are immutable though, I think you said >>you want users to be able to change the values. >> >>Kent > >The tuples are for the kinterbasDB commands, like; > >newPeople = ( > ('Lebed' , 53), > ('Zhirinovsky' , 57), > ) > >for person in newPeople: > cur.execute("insert into people (name_last, age) values (?, ?)", person) > >That's the only place I need a tuple from my data structure, I have no >other need to pass a tuple anywhere. My (C++) application continually >creates the data structures which ends up in a list in a python module. >The items in the list can then pass through various actions like values >getting changed (mapping or mathmatical operations), database entry and >manipulation, or even sent through a socket to somewhere else. >All the actions are in various python scripts which I'm allowing my users >to edit freely (since they all have different requirements). I'd like to >keep their life as simple as possible, and at the heart of that is this >data structure. > >Maybe I'm thinking too hard about it, and the original > >class myData: > name = "" > age = "" > gender = "" > >was actually the simplest and clearest. I was concerned that a user would >delete some of the items, causing problems later in the system. Also >possibly I'm hung up on the idea of member variables in C++? > >nik > >>At 03:45 PM 9/14/2004 +0200, nik wrote: >> >>>Kent Johnson wrote: >>> >>>>At 12:52 PM 9/14/2004 +0200, nik wrote: >>>> >>>>>hi, >>>>> >>>>>I have a class which is just a holder for a data structure, and for >>>>>some reason I've decided to hold the data in the following form; >>>>> >>>>>class myData: >>>>> data = [ ["name", ""], ["age", ""], ["gender", ""] ] >>>>> >>>>>I'm not totally sure it's the best way, but it strikes me as something >>>>>that can be easily manipulated into maps etc. I had started out with >>>>>class myData: >>>>> name = "" >>>>> age = "" >>>>> gender = "" >>>>> >>>>>but I found that I had to put most of those items into lists to do >>>>>anything with them. >>>> >>>> >>>> >>>>What kinds of things are you doing that you need these values in a >>>>list? It sounds like maybe you are trying to pull the data out of the >>>>class to pass to another function, but maybe it would be better to pass >>>>the class itself around? Or maybe you should get rid of the class >>>>entirely and just use a dictionary. >>> >>> >>>I'm thinking in terms of a C struct - it's a handy parcel to move a set >>>of data around, and quite likely there'll be stacks of sets. There's no >>>extra functionality required from the set, and I'm not planning on >>>deriving any other classes from this one. The dictionary seems a very >>>good idea, but I think I still need to put it into a class since I'll >>>have multiple instances of it - is that right? or can I do the >>>equivalent of a typedef? >> >> >>_______________________________________________ >>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 lbblair at adaptisinc.com Tue Sep 14 19:29:15 2004 From: lbblair at adaptisinc.com (Larry Blair) Date: Tue Sep 14 19:30:53 2004 Subject: [Tutor] WIN32SERVICE Message-ID: <AEDF6343B4BDD41195AF00508BEEF26D09FA5B16@EXCHANGE_SERVER> We are using this to do Windows jobs i.e. start- stop services, remote execute of commands etc. It appears that who ever install the "python" wrapper code to use this is the owner and when someone else logs into the workstation they get a message can't find file win32service. We have tried several things to make the permissions more generic but still get this error most of the time. Does anyone have an idea of how to make this visible to whoever logs in and executes a python job? Thanks Larry __________________________________ Confidentiality Notice: This e-mail message, including any attachments, is for the sole use of the intended recipient(s) and may contain information that is confidential privileged and/or exempt from disclosure under applicable law. Any unauthorized review, use, disclosure or distribution is prohibited. If you are not the intended recipient, please contact the sender by reply e-mail and destroy all copies of the original message. Thank you. From Gregory.H.Bartz at usa-spaceops.com Tue Sep 14 21:26:27 2004 From: Gregory.H.Bartz at usa-spaceops.com (Bartz, Gregory H.) Date: Tue Sep 14 21:26:34 2004 Subject: [Tutor] Writing to a file... Message-ID: <A8110BCD9F91F245B88738FC5DB830B30AE0F944@usatxcms02.tx.usa-spaceops.com> I'm somewhat new to Python and this is my first question to the list. In the example below you can see that it takes four write statements to equal one print statement. At the moment I'm using print statements and redirecting them to a file when I run the script (foo.py > outfile). Example using print: dimes = 3 nickels = 5 numofcoins = dimes + nickels money = dimes * 0.1 + nickels * 0.5 print 'You have ', numofcoins, 'coins totaling $', money >>>You have 8 coins totaling $ 0.55 for the same line, write() is more cumbersome: outfile.write('You have ') outfile.write(numofcoins) outfile.write(' coins totaling $') outfile.write(money) Is there a more efficient way of doing this, or some way I can redirect the output internally? -Greg Bartz -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040914/024ad7a9/attachment.htm From kent_johnson at skillsoft.com Tue Sep 14 21:48:11 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Tue Sep 14 21:59:54 2004 Subject: [Tutor] Writing to a file... In-Reply-To: <A8110BCD9F91F245B88738FC5DB830B30AE0F944@usatxcms02.tx.usa -spaceops.com> References: <A8110BCD9F91F245B88738FC5DB830B30AE0F944@usatxcms02.tx.usa-spaceops.com> Message-ID: <6.1.0.6.0.20040914153747.02993ad0@mail4.skillsoft.com> Use "print chevron" to direct the print to the file: print >> outfile, 'You have', numofcoins, 'coins totaling $', money or use the string format operator % to create a single string for write: outfile.write('You have %d coins totalling $%d\n' % (numofcoins, money)) Note that print appends a newline and write doesn't, so to get equivalent output you need to explicitly write the newline. Kent At 02:26 PM 9/14/2004 -0500, Bartz, Gregory H. wrote: >I'm somewhat new to Python and this is my first question to the list. > >In the example below you can see that it takes four write statements to >equal one print statement. >At the moment I'm using print statements and redirecting them to a file >when I run the script (foo.py > outfile). > >Example using print: > >dimes = 3 >nickels = 5 >numofcoins = dimes + nickels >money = dimes * 0.1 + nickels * 0.5 >print 'You have ', numofcoins, 'coins totaling $', money > > >>>You have 8 coins totaling $ 0.55 > >for the same line, write() is more cumbersome: > >outfile.write('You have ') >outfile.write(numofcoins) >outfile.write(' coins totaling $') >outfile.write(money) > >Is there a more efficient way of doing this, or some way I can redirect >the output internally? > >-Greg Bartz > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From juicebypi216 at yahoo.com Tue Sep 14 22:01:09 2004 From: juicebypi216 at yahoo.com (Bryan) Date: Tue Sep 14 22:01:12 2004 Subject: [Tutor] Changing files names Message-ID: <20040914200109.79116.qmail@web51001.mail.yahoo.com> Hi everyone, Basically, what I'm trying to do is change all of the file names under one directory. There are probably about 500 different files, but they all have similar names, just numbered from lets say 5000 to 5500. So far, I've written a program that looks somewhat like this, trying to convert the first three files in the folder: >>import glob, os >>from sets import Set >>skip = Set(['1.2.20.5000.raw', '1.2.27.5001.raw', '1.2.31.5002.raw', ]) >>basedir = r'F:\Python\Renaming\Data' >>for fname in glob.glob(basedir + '*.raw'): if fname in skip: continue newname = basedir + 'bryfile.' + fname[-8:] print 'renaming', fname, newname os.rename(fname, newname) So basically, I'm trying to change the file name so it looks like bryfile.5000.raw, bryfile..5001.raw, bryfile.5002.raw, and so on. This program does not work, and does not print out, and I'm not sure why. Also, do I really have to enter in all of the original file names? Is there a way to tell Python to read all files in the folder, or all files with a 1.2.20.* extension? As you can see, the problem with this method is that the last 4 numbers of the file tell where the file lies in the list (for example, 5000), But the middle section of the file name (the 20) does not go in numeric order. Thanks for the help Bryan __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040914/db32b772/attachment.htm From pythonTutor at venix.com Tue Sep 14 22:03:21 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Tue Sep 14 22:03:34 2004 Subject: [Tutor] Writing to a file... In-Reply-To: <A8110BCD9F91F245B88738FC5DB830B30AE0F944@usatxcms02.tx.usa-spaceops.com> References: <A8110BCD9F91F245B88738FC5DB830B30AE0F944@usatxcms02.tx.usa-spaceops.com> Message-ID: <1095192200.2182.16.camel@laptop.venix.com> On Tue, 2004-09-14 at 15:26, Bartz, Gregory H. wrote: > I'm somewhat new to Python and this is my first question to the list. > > In the example below you can see that it takes four write statements > to equal one print statement. > At the moment I'm using print statements and redirecting them to a > file when I run the script (foo.py > outfile). > > > Example using print: > > dimes = 3 > nickels = 5 > numofcoins = dimes + nickels > money = dimes * 0.1 + nickels * 0.5 > print 'You have ', numofcoins, 'coins totaling $', money print >> outfile, 'You have ', numofcoins, 'coins totaling $', money This redirects print statements to a file. For this kind of filling variables into a string, you can use the string % operater (string interpolation) "You have %d coins totaling $%.2f\n" % (numofcoins, money) builds your output line with a terminating new-line so that it is ready for write. Omit the \n if it will be printed. For details see: http://docs.python.org/lib/typesseq-strings.html It's worth reading because it can do more than this simple illustration. > > >>>You have 8 coins totaling $ 0.55 > > for the same line, write() is more cumbersome: > > outfile.write('You have ') > outfile.write(numofcoins) > outfile.write(' coins totaling $') > outfile.write(money) > > Is there a more efficient way of doing this, or some way I can > redirect the output internally? > > -Greg Bartz > > > > > ______________________________________________________________________ > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From dyoo at hkn.eecs.berkeley.edu Wed Sep 15 01:30:18 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Sep 15 01:30:39 2004 Subject: [Tutor] Changing files names In-Reply-To: <20040914200109.79116.qmail@web51001.mail.yahoo.com> Message-ID: <Pine.LNX.4.44.0409141621250.15764-100000@hkn.eecs.berkeley.edu> On Tue, 14 Sep 2004, Bryan wrote: > >>import glob, os > >>from sets import Set > >>skip = Set(['1.2.20.5000.raw', > '1.2.27.5001.raw', > '1.2.31.5002.raw', > ]) > > >>basedir = r'F:\Python\Renaming\Data' > >>for fname in glob.glob(basedir + '*.raw'): > if fname in skip: continue > newname = basedir + 'bryfile.' + fname[-8:] > print 'renaming', fname, newname > os.rename(fname, newname) > So basically, I'm trying to change the file name so it looks like > bryfile.5000.raw, bryfile..5001.raw, bryfile.5002.raw, and so on. Hi Bryan, Ok, sounds good so far. > This program does not work, and does not print out, and I'm not sure > why. This is actually very valuable information. From the control flow of the program, this suggests two possibilities: 1. All the 'fnames' are in 'skip'. 2. glob.glob(basedir + '*.raw') is returning the empty list. I don't think possibility 1 is actually possible. *grin* But possibility 2 seems very probable. Check the return value that you're getting from the blob again. I see why it's failing, but you should try to find it too. If you don't see the problem in a few minutes, look at the end of this message for spoilers. *** Spoiler space ahead *** *** Spoilers **** You need to make sure the path separator comes before the globbing '*'. Instead for asking for all the files from: r'F:\Python\Renaming\Data*.rar' you probably want: r'F:\Python\Renaming\Data\*.rar' instead. Good luck! From kent_johnson at skillsoft.com Wed Sep 15 03:35:16 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Wed Sep 15 03:35:24 2004 Subject: [Tutor] Python and Unicode essay Message-ID: <6.1.0.6.0.20040914213237.02859708@mail4.skillsoft.com> A few recent questions about Python and Unicode inspired me to do some research. I have written an essay about two issues that are not well documented elsewhere: the handling of non-Ascii characters in the Python interpreter, and use of the default system encoding. You can read the essay here: http://www.pycs.net/users/0000323/stories/14.html Kent From rob.benton at conwaycorp.net Wed Sep 15 05:09:17 2004 From: rob.benton at conwaycorp.net (Rob Benton) Date: Wed Sep 15 04:28:04 2004 Subject: [Tutor] static PyObject * or non-static In-Reply-To: <00a501c4910a$06853470$6401a8c0@xp> References: <4137366F.5070006@conwaycorp.net> <00a501c4910a$06853470$6401a8c0@xp> Message-ID: <4147B25D.3030703@conwaycorp.net> Alan Gauld wrote: >>static PyObject * >>Noddy_name(Noddy* self) >>{ >> static PyObject *format = NULL; >> PyObject *args, *result; >> >> >>make everything static that can be? >> >> > >No that will only waste memory. temporary variables within >functions should go on the stack so that they can be deleted. > >Alan G. > > > > In that chunk of code why isn't the format object temporary? I guess that's what confusing me. From missive at hotmail.com Wed Sep 15 01:49:27 2004 From: missive at hotmail.com (Lee Harr) Date: Wed Sep 15 09:41:05 2004 Subject: [Tutor] Re: Question on open and read html files and psycopg Message-ID: <BAY2-F28xTF3rpIDV4800003e61@hotmail.com> >One more question on psycopg > >Finally, my machine is installed with psycopg and I'm wanna to try out it. >Because, >I'm a newbie so I find it difficult to write a program that is capable of >querying the database a >I have a postgreSQL DB up and running, my problem is with the code. Are >there anyone that is will >Any help will be greatly appreciate. Thank you. > This is based on the code you posted before... #We do have form data; just show it. print "You typed this:" my_query = form.getvalue("data") print my_query # It seems that we need to have an appropriate username that matches # an entry in the postgresql table of users. import os username = os.environ.get('USER') # print "username: ", username, type(username) if username == None: # Assume that the web server has started this script and has the # username 'apache'. To allow this to access the database, we had # to create a postgresql user of that name and have no password. # This new user is also able to create tables and new users, # otherwise the access seems to be blocked. (This might be a # security problem but only for our database tables.) username = 'apache' # Now, we can get to the database... import psycopg db = psycopg.connect("dbname=test user=%s"%username) qresult = db.query(my_query) listOfResults = qresult.dictresult() _________________________________________________________________ MSN 8 with e-mail virus protection service: 2 months FREE* http://join.msn.com/?page=features/virus From missive at hotmail.com Tue Sep 14 22:28:56 2004 From: missive at hotmail.com (Lee Harr) Date: Wed Sep 15 10:06:28 2004 Subject: [Tutor] RE: Question on open and read html files and psycopg Message-ID: <BAY2-F22KUMpyZjxszo00004b62@hotmail.com> >I have a question regarding python script opening and reading HTML files. >Can python >read a html file containing frames? Because when I include this portion in >my script: > well... a file is file. Python does not really care what is in the file. Have you ever made a frame-based website just using html? As far as I know, the frameset needs to be in a separate file from each of the framed pages. >------------------------------------------------------------------------------------- >fp=open("/var/www/cgi-bin/sf/frame.html", "r") > listOfLines= fp.readlines() > for eachline in listOfLines: > print eachline.strip() > fp.close() >------------------------------------------------------------------------------------- > >This is the frame.html: > >------------------------------------------------------------------------------------- ><html> ><head> ><title>T4 Web Browser</title></head> ><frameset rows="80,*" BORDER=0> ><frame name="banner" scrolling="no" noresize target="contents" >src="title_bar.html"> <frameset cols="150,*" border=1> So, here, the browser is now going to try to fetch a completely separate file called title_bar.html and stuff its contents in to this frame. ><frame name="contents" target="main" src="side_bar.html" scrolling="auto"> ><frame name="main" src="trial1.html" scrolling="auto"> Same thing with each of these frames... ></frameset> ><noframes><p>Hi, the page you are attempting to enter has frames and if >you're reading this message, you don't have the ability to see it. In order >to view this page, you will need to update your browser. <p>Updates >are available from ><a href="http://www.microsoft.com/">www.microsoft.com</a> for Internet >Explorer or <a href="http://www.netscape.com/">www.netscape.com</a> for >Netscape Navigator. ></noframes> ></frameset> ></html> > >-------------------------------------------------------------------------------------- > >what the web browser returned is a web page containing the frames that I >have set up >but not the contents of them. The frame.html consists of three more html >files - title_bar.html, side_bar.html and trial1.html. That is trial1.py is >capable of opening >up and reading the frame.html file and display the frames but can't read >the rest. Thus, when i changed the frame.html to any of the html files, >trial1.py runs perfectly. >I just wonder if anyone can tell me whether I'm right that python can't >read html files >within another html file. (I hope someone get what I said);O >Or please explain to me why does this happened? Thanks for any help. I don' t think the problem is that python cannot read the files, but you need to make sure that when the browser requests (for example) side_bar.html that the response it gets is the contents of side_bar.html and nothing else. The easiest way to do that may be to keep it as a completely separate file. > > >One more question on psycopg > >Finally, my machine is installed with psycopg and I'm wanna to try out it. >Because, >I'm a newbie so I find it difficult to write a program that is capable of >querying the database and display the result via a web browser whenever a >user do a keyword search. >I have a postgreSQL DB up and running, my problem is with the code. Are >there anyone that is willing to share his/her source code that does similar >stuffs as mine do? >Any help will be greatly appreciate. Thank you. > Your code worked perfectly well for me once I set it up for psycopg. It looked to me like it was written for pypgsql. Have you tried the psycopg examples? Those should get you started.... I do not have the code that I based on yours right here... I will try to find it later today. _________________________________________________________________ MSN 8 with e-mail virus protection service: 2 months FREE* http://join.msn.com/?page=features/virus From Mark.Kels at gmail.com Wed Sep 15 11:22:55 2004 From: Mark.Kels at gmail.com (Mark Kels) Date: Wed Sep 15 11:23:02 2004 Subject: [Tutor] What GUI to use with python? Message-ID: <d120265304091502224a2c57a7@mail.gmail.com> Hello, I want to start with GUI programing,but I dont know which GUI package to use. I need it to bo easy to use and portable between Un*x and windows. any suggestions ?? Thanks. From chandrakirti at gmail.com Wed Sep 15 12:11:09 2004 From: chandrakirti at gmail.com (Lloyd Hugh Allen) Date: Wed Sep 15 12:11:17 2004 Subject: [Tutor] What GUI to use with python? In-Reply-To: <d120265304091502224a2c57a7@mail.gmail.com> References: <d120265304091502224a2c57a7@mail.gmail.com> Message-ID: <24d253d90409150311172b3bea@mail.gmail.com> Tk/TCL is good, accessed through Tkinter: http://www.python.org/topics/tkinter/ On Wed, 15 Sep 2004 11:22:55 +0200, Mark Kels <mark.kels@gmail.com> wrote: > Hello, > > I want to start with GUI programing,but I dont know which GUI package to use. > I need it to bo easy to use and portable between Un*x and windows. > any suggestions ?? > > Thanks. > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From kent_johnson at skillsoft.com Wed Sep 15 14:11:59 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Wed Sep 15 14:12:03 2004 Subject: [Tutor] What GUI to use with python? In-Reply-To: <d120265304091502224a2c57a7@mail.gmail.com> References: <d120265304091502224a2c57a7@mail.gmail.com> Message-ID: <6.1.0.6.0.20040915075125.02a24568@mail4.skillsoft.com> Tkinter and wxWidgets/wxPython are the main choices. I haven't done much with either but my impression is - Tkinter is easier to get started with as a programmer - Tkinter comes with Python so there is nothing extra to install - wxPython has a greater selection of widgets and may be a better choice for a full-featured application. - wxPython is harder to program for than Tkinter - there are at least two GUI toolkits built on top of wxPython aimed at making it easier to use - Wax and PythonCard. You can also use Jython and Swing. I have written a few applications this way, but I think I would make the Jython/Python choice based on other factors than the GUI toolkit available. If your needs are very modest (dialog boxes asking the user for various types of input) then EasyGui may be enough. http://www.ferg.org/easygui/ You might find these pages interesting: http://www.awaretek.com/toolkits.html http://www.python.org/cgi-bin/moinmoin/GuiProgramming BTW do you mean easy to use for the programmer or the user of the program? Kent At 11:22 AM 9/15/2004 +0200, Mark Kels wrote: >Hello, > >I want to start with GUI programing,but I dont know which GUI package to use. >I need it to bo easy to use and portable between Un*x and windows. >any suggestions ?? > >Thanks. >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From gubitz at netcologne.de Wed Sep 15 14:04:45 2004 From: gubitz at netcologne.de (Hans Gubitz) Date: Wed Sep 15 14:26:49 2004 Subject: [Tutor] IDLE 2.3 (Python) Message-ID: <20040915120445.GA26600@redwitz79.de> Hallo, I have to start IDLE 2.3 with the -n command line switch. Unfortunately this doesn't work. IDLE comes up for less than a second with some error-messages. What might be wrong? (I'm working on a Debian-Sarge server.) Hans -- Hans Gubitz <gubitz@netcologne.de> From s4046441 at student.uq.edu.au Wed Sep 15 16:34:09 2004 From: s4046441 at student.uq.edu.au (Ms Soo Chong) Date: Wed Sep 15 16:34:16 2004 Subject: [Tutor] RE: Question on open and read html files and psycopg Message-ID: <4da1fa4dd676.4dd6764da1fa@uq.edu.au> Hi, Hmm..actually, this is the first time I'm tried a frame-based website. In fact, this is my first time to write a python script, first time deal with postgreSQL and HTML. So please bear with my simple or stupid questions. Thanks. A friend of mine taught me about the frameset and I understand that it needs to be in a separate file from each of the framed pages. I'm just curious why python is able to open and read the frame.html but not the files within, or there is something wrong with my script which I'm not sure. Anyways, my thesis supervisor don't like the idea of using a frame-based website as not all browser supports that. (he just told me today that he don't prefer that)Thus, I combined all the html files into one and separate them using tables now. Anyway, thanks alot for your reply. As for psycopg... My code was based on python and pg module and I wanna to switch to DB-API, such as psycopg. I havn't really tried psycopg examples yet? BTW, where to get them? You mean try connecting with psycopg? Just to correct my previous mail, psycopg has not been installed yet because there seems to have some stuffs missing (postgresql header and etc) which stopped the configuration, but should be fixed in a day or two. So, I have not try psycopg yet. How to grab the query input from the user? Right now, the user have to type in SQL statements (SELECT * FROM ....)to search for data. Thats not what I want, I need the grab the input from the user (keywords) and match with the meta-data in the tables (postgresql) and return the results. This is the part where I'm stucked. Any help will very much appreciated. Thank you. Cheers, Shufen From marilyn at deliberate.com Wed Sep 15 18:23:37 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Wed Sep 15 18:23:40 2004 Subject: [Tutor] signals and frame objects Message-ID: <Pine.LNX.4.44.0409150919440.8998-100000@Kuna> Hello Tutors, I'm setting a signal.alarm() and I am successful in catching it in my handler function. The parameters given to me in my handler include the stack frame. Is there some way I can use that stack frame to continue processing? Thank you for any help anyone can give. Marilyn Davis -- From kent_johnson at skillsoft.com Wed Sep 15 20:00:28 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Wed Sep 15 20:00:37 2004 Subject: [Tutor] signals and frame objects In-Reply-To: <Pine.LNX.4.44.0409150919440.8998-100000@Kuna> References: <Pine.LNX.4.44.0409150919440.8998-100000@Kuna> Message-ID: <6.1.0.6.0.20040915135106.02930c18@mail4.skillsoft.com> If you return from the handler, processing will continue where it was interrupted. If you want to inspect the frame object in your handler, some information about it is available here: http://docs.python.org/ref/types.html#l2h-142 For example, running this program in IDLE on MacOSX: ############################# import signal done = 0 def handler(signum, frame): print frame print dir(frame) print 'Signal handler called with signal', signum global done done = 1 # Set the signal handler and an alarm signal.signal(signal.SIGALRM, handler) signal.alarm(3) print "Looping" while not done: pass print "Out of loop" signal.alarm(0) # Disable the alarm print "Done" ##############################3 gives this output: >>> ================================ RESTART ================================ >>> Looping <frame object at 0x4fd6c0> ['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'f_back', 'f_builtins', 'f_code', 'f_exc_traceback', 'f_exc_type', 'f_exc_value', 'f_globals', 'f_lasti', 'f_lineno', 'f_locals', 'f_restricted', 'f_trace'] Signal handler called with signal 14 Out of loop Done >>> Kent At 09:23 AM 9/15/2004 -0700, Marilyn Davis wrote: >Hello Tutors, > >I'm setting a signal.alarm() and I am successful in catching it in my >handler function. The parameters given to me in my handler include >the stack frame. Is there some way I can use that stack frame to >continue processing? > >Thank you for any help anyone can give. > >Marilyn Davis > >-- > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From python_newbie at vedorian.com Wed Sep 15 20:23:14 2004 From: python_newbie at vedorian.com (Kevin) Date: Wed Sep 15 20:25:17 2004 Subject: [Tutor] bind problem Message-ID: <000f01c49b51$10c1a940$30e57218@basp.phub.net.cable.rogers.com> Skipped content of type multipart/alternative-------------- next part -------------- #!/usr/local/bin/python # # mmaker.py - main program stuff # # SERVER_PORT = 4000 import sys import time import sServer import mWorld # # Main Program # print "Starting MUD Maker Server" if len(sys.argv) > 1: port = int(eval(sys.argv[1])) else: port = SERVER_PORT world = mWorld.World() world.boot() server = sServer.Server(port, world) # # Main Loop # print "Waiting for connections" lastSec = time.time() while world._running: # try: time0 = time.time() server.checkConnections(0.1) server.processConnections() if time0 - lastSec >= 1: # 1 second lastSec = time0 world.processTimers() time1 = time.time() # sleep the time that was left to fill 1 cycle wait = 0.1 - (time1 - time0) if wait > 0: # print 'waiting extra free time ', wait time.sleep(wait) # except KeyboardInterrupt: # print "Got KeyboardInterrupt: shutting down." # server.shutdown() # break print "Shutting down." -------------- next part -------------- # server.py - handles client connections and related stuff # # # from socket import * import select import sConnection class Server: def __init__(self, port, world): self._sock = socket(AF_INET, SOCK_STREAM) # # Relationships # self._connections = {} # Connection # # Other Data # self._world = world # World self._descriptors = [] self._sock.bind('', port) self._sock.setblocking(0) self._sock.listen(5) def shutdown(self): self._sock.close() for c in self._connections.items(): _, con = c con.destroy() def removeConnection(self, conn): self._descriptors.remove(conn._fd) del self._connections[conn._fd] def closeConnection(self, conn): print 'closing connection' self.removeConnection(self, conn) conn.destroy() def checkConnections(self, timeout): fd = self._sock.fileno() ind, outd, exd = select.select(self._descriptors + [fd], \ self._descriptors, self._descriptors, timeout) # accept new connection if fd in ind: print 'new connection' new = self._sock.accept() conn = sConnection.Connection(self, new, self._world) self._descriptors.append(conn._fd) self._connections[conn._fd] = conn ind.remove(fd) # read inputs for f in ind: if self._connections[f].receiveInput() < 0: # connection was closed self.closeConnection(self, f) # send outputs for f in self._descriptors: self._connections[f].setCanSendOutput(f in outd) # close other stuff for f in exd: self.closeConnection(self, f) def processConnections(self): for item in self._connections.items(): _, client = item if client.checkStatus(): cmdline = client.getNextInput() if cmdline != None: if cmdline == '': client.putPrompt() else: if client.handleInput: client.handleInput(client, cmdline) else: self._world.execute(client._player, cmdline, 1) client.putPrompt() client.flush() From dyoo at hkn.eecs.berkeley.edu Wed Sep 15 20:49:13 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Sep 15 20:49:23 2004 Subject: [Tutor] bind problem In-Reply-To: <000f01c49b51$10c1a940$30e57218@basp.phub.net.cable.rogers.com> Message-ID: <Pine.LNX.4.44.0409151143110.17809-100000@hkn.eecs.berkeley.edu> On Wed, 15 Sep 2004, Kevin wrote: > I can't seem to find what is wrong here I keep getting this error: > Traceback (most recent call last): > File "./mmaker.py", line 39, in ? > server =3D3D sServer.Server(port, world) > File "./sServer.py", line 29, in __init__ > self._sock.bind(' ',port) > TypeError: bind() takes exactly one argument (2 given) > > I have also attached the files for anyone to take a look at. If anyone > could help me out and tell me what whent wrong that would be great Hi Kevin, It looks like you're making a connection using stuff from the 'socket' module. http://www.python.org/doc/lib/socket-objects.html According to the documentation on bind(): """ bind() Bind the socket to address. The socket must not already be bound. (The format of address depends on the address family -- see above.) Note: This method has historically accepted a pair of parameters for AF_INET addresses instead of only a tuple. This was never intentional and is no longer available in Python 2.0 and later. """ The very last part is the important part. At the moment, the initializer of your server is calling: self._sock.bind(' ',port) and this doesn't work: you need to modify this to pass a 2-tuple instead. Like this: self._sock.bind( (' ',port) ) See: http://www.python.org/doc/lib/socket-example.html for an example. In this particular case, the parentheses are significant. That being said, since we're using AF_INET, I thought that bind had to take a 2-tuple of the host and the port. Is it ok to leave the 'host' part blank? Good luck to you! From debe at comp.leeds.ac.uk Wed Sep 15 20:52:33 2004 From: debe at comp.leeds.ac.uk (D Elliott) Date: Wed Sep 15 20:52:36 2004 Subject: [Tutor] comparing files Message-ID: <Pine.LNX.4.58.0409151933070.19014@cslin-gps.csunix.comp.leeds.ac.uk> I am completely new to programming and have been learning Python for about a week. I have looked through and worked through the first few chapters of: - Python Tutorial (Rossum et al) - Non-Programmers Tutorial for Python (Cogliati) - Learn to program using Python (Gauld) - How to think like a computer scientist (Downey et al) For my PhD in machine translation evaluation, my first programming task is to try to automatically detect (and then count) all words that were not translated (into English) by the system (ie. they are still in French). The idea I have is as follows: - Read in a file containing MT output (usually about 400 words) - Compare it with a file containing a complete English word list - Print all words that do not appear in the wordlist in a separate file - Count the words in the file and print the percentage of not found words (The assumption is that these will be untranslated words - obviously this will have to be tested and tweaked) I now know how to read and write files, but not compare them. Would you say this is a particularly advanced task to do? My supervisor seemed to think that I could learn how to do this within a week by just skimming through the books and finding the relevant code. Is this realistic for a complete beginner? I, on the other hand, prefer to fully understand what I am doing! (BTW - my supervisor does not know Python) Could anyone please tell me how long you think it should take a keen beginner to get to that level, and which aspects of Python would you recommend that I learn first? Does anyone know of a book/tutorial that shows how to do the above tasks? Thanks in advance to anyone who can enlighten me:) Debbie -- *************************************************** Debbie Elliott Computer Vision and Language Research Group, School of Computing, University of Leeds, Leeds LS2 9JT United Kingdom. Tel: 0113 3437288 Email: debe@comp.leeds.ac.uk *************************************************** From marilyn at deliberate.com Wed Sep 15 21:31:16 2004 From: marilyn at deliberate.com (Marilyn Davis) Date: Wed Sep 15 21:31:20 2004 Subject: [Tutor] signals and frame objects In-Reply-To: <6.1.0.6.0.20040915135106.02930c18@mail4.skillsoft.com> Message-ID: <Pine.LNX.4.44.0409151228180.8998-100000@Kuna> Oh wow. That is so easy. I thought I had to manipulate the frame object somehow to get back to where I was. Thank you so much Kent. Marilyn On Wed, 15 Sep 2004, Kent Johnson wrote: > If you return from the handler, processing will continue where it was > interrupted. If you want to inspect the frame object in your handler, some > information about it is available here: > http://docs.python.org/ref/types.html#l2h-142 > > For example, running this program in IDLE on MacOSX: > ############################# > import signal > > done = 0 > def handler(signum, frame): > print frame > print dir(frame) > print 'Signal handler called with signal', signum > global done > done = 1 > > # Set the signal handler and an alarm > signal.signal(signal.SIGALRM, handler) > signal.alarm(3) > > print "Looping" > while not done: > pass > > print "Out of loop" > > signal.alarm(0) # Disable the alarm > > print "Done" > ##############################3 > > gives this output: > >>> ================================ RESTART ================================ > >>> > Looping > <frame object at 0x4fd6c0> > ['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__', > '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', > '__setattr__', '__str__', 'f_back', 'f_builtins', 'f_code', > 'f_exc_traceback', 'f_exc_type', 'f_exc_value', 'f_globals', 'f_lasti', > 'f_lineno', 'f_locals', 'f_restricted', 'f_trace'] > Signal handler called with signal 14 > Out of loop > Done > >>> > > Kent > > > At 09:23 AM 9/15/2004 -0700, Marilyn Davis wrote: > >Hello Tutors, > > > >I'm setting a signal.alarm() and I am successful in catching it in my > >handler function. The parameters given to me in my handler include > >the stack frame. Is there some way I can use that stack frame to > >continue processing? > > > >Thank you for any help anyone 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 nvettese at pdistributors.com Wed Sep 15 21:39:58 2004 From: nvettese at pdistributors.com (Nicholas Vettese) Date: Wed Sep 15 21:43:00 2004 Subject: [Tutor] Learning Python by example Message-ID: <41489A8E.3010508@pdistributors.com> I am new to programming, as in don't understand it at all, and I am looking to start by creating a program that I need. Since I am in the process of becoming a small business owner, I am looking to create a product that can handle many aspects of the business (Inventory, A/R, A/P, Sales, etc...), so I want to start from scratch. I know this sounds like some crazy plan, but I have something to model it by. There is a program where I work now (Ultimate Triad System), and it can do all of that, but it costs 50,000 USD, and another 5,000 USD/month if you want technical help. I want to GPL this piece for all to use. My real question, I apologize for the preamble, is whether or not to use a GUI toolkit right away. I would like to write the program as a regular command line program, and then convert it to a GUI based application once it is working. I am not sure if this will increase my workload, or help me understand the best of both worlds. Remember, I know nothing about this, and I will be learning along the way. I appreciate all comments and help. Thanks, Nick From bvande at po-box.mcgill.ca Wed Sep 15 22:08:10 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Wed Sep 15 22:08:31 2004 Subject: [Tutor] comparing files In-Reply-To: <Pine.LNX.4.58.0409151933070.19014@cslin-gps.csunix.comp.leeds.ac.uk> References: <Pine.LNX.4.58.0409151933070.19014@cslin-gps.csunix.comp.leeds.ac.uk> Message-ID: <4148A12A.2070306@po-box.mcgill.ca> D Elliott said unto the world upon 2004-09-15 14:52: > I am completely new to programming and have been learning Python for about > a week. I have looked through and worked through the first few chapters > of: > > - Python Tutorial (Rossum et al) > - Non-Programmers Tutorial for Python (Cogliati) > - Learn to program using Python (Gauld) > - How to think like a computer scientist (Downey et al) > > For my PhD in machine translation evaluation, my first programming task is > to try to automatically detect (and then count) all words that were not > translated (into English) by the system (ie. they are still in French). > The idea I have is as follows: > > - Read in a file containing MT output (usually about 400 words) > - Compare it with a file containing a complete English word list > - Print all words that do not appear in the wordlist in a separate file > - Count the words in the file and print the percentage of not found words > (The assumption is that these will be untranslated words - obviously this > will have to be tested and tweaked) > > I now know how to read and write files, but not compare them. Would you > say this is a particularly advanced task to do? My supervisor seemed to > think that I could learn how to do this within a week by just skimming > through the books and finding the relevant code. Is this realistic for a > complete beginner? I, on the other hand, prefer to fully understand what I > am doing! (BTW - my supervisor does not know Python) > > Could anyone please tell me how long you think it should take a keen > beginner to get to that level, and which aspects of Python would you > recommend that I learn first? Does anyone know of a book/tutorial that > shows how to do the above tasks? > > Thanks in advance to anyone who can enlighten me:) > Debbie Hi Debbie, I'm learning Python as a hobby and distraction from my thesis in Philosophy, so I'm no expert. But I'd be surprised if anyone in a comp sci related PhD program would take a week to learn enough Python to do what you describe. It took me less than a few full days worth of effort (albeit spread over a few weeks) to be confident in doing similar tasks. Some general learning advice: I started with How to think like a computer scientist. Finding it a bit low in its pitch (I believe it is aimed at high school students) I used Lutz and Ascher Learning Python <http://www.oreilly.com/catalog/lpython2/>. It is likely worth a purchase. Though, depending on your uni's arrangements, you might be able to read it online for free through safari <http://safari.oreilly.com/> Also, if you intend to use Python in anger, I'd suggest buying Martelli Python in a Nutshell <http://www.oreilly.com/catalog/pythonian/>. Its not so much for learning (at least early on) as it is a very useful memory jogger. I have, though, used it to learn how to do a number of things, too. This one, safari or no, you will want to have at hand. And, since you posted to the Tutor list, you found one of the very best resources already! I think you'd likely learn more skimming through the docs and trying to build it from scratch than you would skimming through books looking for code to use. Perhaps more knowledgeable folks will disagree, but at the early stages, learning how to do it from scratch seems better to me even though it does overlook the great strength of the open source community that you get to stand on the shoulders of giants. Advice about your task: I'm going to make the simplifying assumptions a) that there are only ASCII characters at play and b) no words in your MT output file have line-ending hyphenations. What I would do as a first approach to this would (in broad outline) be: 1) read both the MT output and the reference word files into strings, using the .read() method of a file object. This will give you two strings, each of which is the contents of one of the original files. Then, 2) Split each file contents string at whitespace to separate them into words (assumption (b) kicking in here), using the .split() method of the string object. This will give you two lists, each of all the words in the original files. (You might also use .lower() on the original strings to discard case differences.) Then, 3) for each element in the MT output word list, check if it is in the reference word list. That will need a for loop and the in keyword. Using if test, augment appropriate counters as you go. There are several ways that I can think of where you could speed this up, and surely a good many more that I haven't seen. For instance, once you get something like that going, you might think about breaking the standard word list up into sub-lists, one for words that start with 'a', etc. (This would reduce how many comparisons you have to make for each word.) You might also look to serialize (or store) those canonical word lists to save the step of constructing them each time. But, once you've got it done as I outline above, you should be well on your way to knowing how to improve it in these or other ways. Doc pages that you will find helpful -- these are also in your Python installation on (many?/all?) platforms: http://www.python.org/doc/2.3.4/lib/string-methods.html http://www.python.org/doc/2.3.4/lib/typesseq-mutable.html http://www.python.org/doc/2.3.4/lib/built-in-funcs.html These will cover various methods that you will find useful. I'd suggest looking through them briefly so you get a general 'lay of the land' and then consulting in detail if/as the need arises. Above all, though: remember this advice is from a relative newcomer! Good luck and best, Brian vdB From dyoo at hkn.eecs.berkeley.edu Wed Sep 15 22:33:44 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Sep 15 22:33:50 2004 Subject: [Tutor] comparing files In-Reply-To: <Pine.LNX.4.58.0409151933070.19014@cslin-gps.csunix.comp.leeds.ac.uk> Message-ID: <Pine.LNX.4.44.0409151302290.31718-100000@hkn.eecs.berkeley.edu> On Wed, 15 Sep 2004, D Elliott wrote: > I am completely new to programming and have been learning Python for > about a week. I have looked through and worked through the first few > chapters of: > > - Python Tutorial (Rossum et al) > - Non-Programmers Tutorial for Python (Cogliati) > - Learn to program using Python (Gauld) > - How to think like a computer scientist (Downey et al) Hi Debbie, I'd say it's ambitious, but still realistic. You may want to stretch the time for another week or two, but doing it in a week is still possible if you work hard at it. I recommend focusing on getting the core concepts of programming down. The tutorials that you're looking at should be of great help. If you see something that talks about how to write a class, or how to use modules, skim it for now: you can get that material later, when you're more familiar with the language. I'd also recommend skimming the Python Tutorial, and not read it too deeply yet. The material in Guido's tutorial touches mostly on the differences between Python and other languages. Its target audience is for folks who are already programmers. The other three tutorials are tailored toward beginners, and those should be more approachable. > The idea I have is as follows: > > - Read in a file containing MT output (usually about 400 words) > - Compare it with a file containing a complete English word list > - Print all words that do not appear in the wordlist in a separate file > - Count the words in the file and print the percentage of not found words > (The assumption is that these will be untranslated words - obviously this > will have to be tested and tweaked) Yes, if you finish and understand the material from those tutorials, you should be able to do this. A straightforward solution requires the following concepts: 1. File IO and string manipulation: you'll need to break your two input files (MT text and English words) into words. 2. Basic data structures to hold the list of words in memory. "Dictionaries", in particular, will help you do the comparisons in an efficient way. You can actually get away with using basic "lists" too, although your program may be a little less efficient. 3. Control flow. You should feel comfortable with things like 'loops' and conditional 'if' statements. I'd strongly suggest one more concept: 4. Functions. They're great for managing the complexity of programs. I've seen programs written that don't use functions, and frankly, most of them are a big mess. *grin* Those areas seem core to writing interesting programs; does anyone have other suggestions? > I, on the other hand, prefer to fully understand what I am doing! (BTW - > my supervisor does not know Python) Please feel free to bring up programming questions on this Tutor list; we're here to help. We won't do homework, of course, but we can help you identify useful programming concepts and to help clarify the material that you're reading. If you see something that you don't understand, ask. The volunteers on this list will either try to explain it, or point you toward online material that explains it well. Good luck to you. From bgailer at alum.rpi.edu Wed Sep 15 22:46:49 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Wed Sep 15 22:45:23 2004 Subject: {Spam?} [Tutor] Learning Python by example In-Reply-To: <41489A8E.3010508@pdistributors.com> References: <41489A8E.3010508@pdistributors.com> Message-ID: <6.1.2.0.0.20040915144303.04eb4ab0@mail.mric.net> At 01:39 PM 9/15/2004, Nicholas Vettese wrote: >I am new to programming, as in don't understand it at all, and I am >looking to start by creating a program that I need. Since I am in the >process of becoming a small business owner, I am looking to create a >product that can handle many aspects of the business (Inventory, A/R, A/P, >Sales, etc...), so I want to start from scratch. >I know this sounds like some crazy plan, but I have something to model it >by. There is a program where I work now (Ultimate Triad System), and it >can do all of that, but it costs 50,000 USD, and another 5,000 USD/month >if you want technical help. I want to GPL this piece for all to use. >My real question, I apologize for the preamble, is whether or not to use a >GUI toolkit right away. I would like to write the program as a regular >command line program, and then convert it to a GUI based application once >it is working. I am not sure if this will increase my workload, or help >me understand the best of both worlds. My 2 cents worth: Sounds like a HUGE undertaking. I think it will cost you more than the price of the other system to do it from scratch. Also I guess there are other accounting systems that can do what you want for a lot less. That said: I like your idea of starting with a command line app, then adding GUI later. Another important consideration is choice of a data base management system. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From dyoo at hkn.eecs.berkeley.edu Wed Sep 15 23:04:13 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Sep 15 23:04:25 2004 Subject: [Tutor] Writing to a file... In-Reply-To: <A8110BCD9F91F245B88738FC5DB830B30AE0F944@usatxcms02.tx.usa-spaceops.com> Message-ID: <Pine.LNX.4.44.0409151352050.31718-100000@hkn.eecs.berkeley.edu> On Tue, 14 Sep 2004, Bartz, Gregory H. wrote: > Example using print: > > dimes = 3 > nickels = 5 > numofcoins = dimes + nickels > money = dimes * 0.1 + nickels * 0.5 > print 'You have ', numofcoins, 'coins totaling $', money > > >>>You have 8 coins totaling $ 0.55 > > for the same line, write() is more cumbersome: > > outfile.write('You have ') > outfile.write(numofcoins) > outfile.write(' coins totaling $') > outfile.write(money) > > Is there a more efficient way of doing this, or some way I can redirect > the output internally? Hi Greg, Yes, there is a way of redirecting the standard output to somewhere else. Given that we have an 'outfile' ready, we can do something like this: ### import sys sys.stdout = outfile ### This tosses the old 'stdout' standard output file aside, and uses 'outfile' as the new stdout. After doing the redirection, all your print statement should get sent over to the 'outfile'. (It's a useful kludge to know if you have to deal with a maladjusted function that just uses "print" instead of properly returning a value. *grin*) When you want to restore the old stdout file, you can then do: ### sys.stdout = sys.__stdout__ ### See: http://www.python.org/doc/lib/module-sys.html#l2h-388 for a little bit more information about this. The approach above, with redirecting sys.stdout, is nifty, but since it's twiddling the global values of the system itself, it can cause maintenence problems if we're not careful. Imagine doing the redirection technique above, and then using another module that also uses this technique. Pandemonium! *grin* So munging global variables like this is usually a bad idea. If you're going to do things like report formatting, then using Lloyd's approach, with the string formatting, is probably a better idea than using separate 'print' statements. From dyoo at hkn.eecs.berkeley.edu Wed Sep 15 23:12:58 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Sep 15 23:13:02 2004 Subject: [Tutor] bind problem In-Reply-To: <000701c49b5d$4c9df2a0$30e57218@basp.phub.net.cable.rogers.com> Message-ID: <Pine.LNX.4.44.0409151407090.31718-100000@hkn.eecs.berkeley.edu> On Wed, 15 Sep 2004, Kevin wrote: > Ya that seemed to fix it by changing (' ',port) to ((' ',port)) Thanks > for the help. This is not a code that I have created it was a mud that > was posted on sourceforge.net. Hi Kevin, No problem. You'd be surprised how much code out there is buggy. *grin* > I have always wanted to do a mud in python so this will give a good idea > on how to go about doing it. I will need to read up on the socket stuff > though so that when I go to create my own server I will be able to be up > to date on it. Sounds awesome! When you get more of it working, feel free to tell us about in on Tutor; it'll be great to hear about it, and the things you did to make it work. It sounds like a lot of Python programmers are gravitating toward the 'Twisted' framework for doing network apps. You may want to look at it if you have time. Good luck to you! From dyoo at hkn.eecs.berkeley.edu Wed Sep 15 23:27:17 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Sep 15 23:27:23 2004 Subject: [Tutor] Debug Assertion Failed !!! In-Reply-To: <DFCB7C708B1AA94FABFBF6E1F7E984542E6E19@iiex2ku01.agere.com> Message-ID: <Pine.LNX.4.44.0409151415240.31718-100000@hkn.eecs.berkeley.edu> On Tue, 14 Sep 2004, Jayanthi, Satya Padmaja (Satya Padmaja) wrote: > I am running a python program, which is internally calling TCL APIs. I > am using Tkinter as an interface between the two languages, Python and > TCL. > > The whole script runs pretty well, without any problem. But, at the end > of the run, a window pops up with the following message, > > Debug Assertion Failed !!! > > Program : F\Python23\python.exe > File : dbgheap.c > Line : 1044 > > Expression : _CrtIsValidHeapPointer(pUserData)... Hi Padmaja, Hmm... since you haven't gotten a response about this yet, you may want to ask on the comp.lang.python newsgroup about that problem. I don't think we have the expertise on Tutor to debug Tcl or the Python runtime, and the error message above sounds like it involves one of those things. So try getting the gurus on comp.lang.python to take a look at it. If you can, include the script that you're using to let them trigger the error. Best of wishes to you! From missive at hotmail.com Wed Sep 15 23:44:04 2004 From: missive at hotmail.com (Lee Harr) Date: Wed Sep 15 23:48:07 2004 Subject: [Tutor] Re: Question on open and read html files and psycopg Message-ID: <BAY2-F30rMh0R1hY55Z0000a9fa@hotmail.com> Please wrap your long lines at < 75 characters ... >As for psycopg... >My code was based on python and pg module and I wanna to switch to DB-API, >such as psycopg. I > havn't really tried psycopg examples yet? BTW, where to get them? The examples come with the psycopg distribution. If you have not downloaded that and looked through it and read the instructions included with it, I am not quite sure why you are asking here first. >You mean try connecting with > psycopg? Just to correct my previous mail, psycopg has not been installed >yet because there seems > to have some stuffs missing (postgresql header and etc) which stopped the >configuration, but > should be fixed in a day or two. So, I have not try psycopg yet. > Well. That seems like the first step. Maybe there are pre-built packages available for your operating system. >How to grab the query input from the user? Right now, the user have to type >in SQL statements > (SELECT * FROM ....)to search for data. Thats not what I want, I need the >grab the input from the > user (keywords) and match with the meta-data >in the tables (postgresql) and return the results. > This is the part where I'm stucked. > Your code previously worked just fine to get the input from the user through the web. Just instead of asking for a complete SQL query (which would be a bad idea) Just ask for keywords and build up a string from there. You need to learn things one step at a time. If you do not yet know how to create a string from other strings you need to learn that first. By the way. The code I posted yesterday was bogus... some kind of bad mix between your code and my code. This works w/ psycopg: # Now, we can get to the database... import psycopg db = psycopg.connect("dbname=test user=%s"%username) cursor = db.cursor() cursor.execute(my_query) listOfResults = cursor.dictfetchall() Sorry about that. _________________________________________________________________ Tired of spam? Get advanced junk mail protection with MSN 8. http://join.msn.com/?page=features/junkmail From CwiklaJ at diebold.com Wed Sep 15 23:56:19 2004 From: CwiklaJ at diebold.com (Cwikla, Joe) Date: Wed Sep 15 23:55:34 2004 Subject: [Tutor] signals and frame objects Message-ID: <00319B4EF1ADAC42808F9C79C6F5EBD157ACF4@msexch26.diebold.com> But if you wanted to use the stack frame there's a great example here: http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&selm=Y35XKKAZKTi%24Ewl3%4 0jessikat.fsnet.co.uk No SIGALRM on Windows so substituting SIGBREAK and combining the above with Kent's example: ###################################################################### breaks=0 action=None def looper(): print "Looping" while(True): pass import signal def handler(signum, frame): import sys c=frame.f_code print 'Signal handler called with signal', signum print 'called from ', c.co_filename, c.co_name, frame.f_lineno global breaks breaks+=1 if breaks==7: signal.signal(signal.SIGBREAK, action) # Set the signal handler action=signal.signal(signal.SIGBREAK, handler) looper() ##################################################################### Yields (with 8 CTRL-BREAK): Looping Signal handler called with signal 21 called from C:\test\SignalFrame.py looper 7 Signal handler called with signal 21 called from C:\test\SignalFrame.py looper 7 Signal handler called with signal 21 called from C:\test\SignalFrame.py looper 6 Signal handler called with signal 21 called from C:\test\SignalFrame.py looper 7 Signal handler called with signal 21 called from C:\test\SignalFrame.py looper 6 Signal handler called with signal 21 called from C:\test\SignalFrame.py looper 6 Signal handler called with signal 21 called from C:\test\SignalFrame.py looper 6 ^C - Joe >Date: Wed, 15 Sep 2004 12:31:16 -0700 (PDT) >From: Marilyn Davis <marilyn@deliberate.com> >Subject: Re: [Tutor] signals and frame objects >To: Kent Johnson <kent_johnson@skillsoft.com> >Cc: tutor@python.org >Message-ID: <Pine.LNX.4.44.0409151228180.8998-100000@Kuna> >Content-Type: TEXT/PLAIN; charset=US-ASCII > >Oh wow. That is so easy. I thought I had to manipulate the frame object somehow to get back to where I was. Thank you >so much Kent. > >Marilyn > >On Wed, 15 Sep 2004, Kent Johnson wrote: > >> If you return from the handler, processing will continue where it was >> interrupted. If you want to inspect the frame object in your handler, >> some information about it is available here: >> http://docs.python.org/ref/types.html#l2h-142 >> >> For example, running this program in IDLE on MacOSX: >> ############################# >> import signal >> >> done = 0 >> def handler(signum, frame): >> print frame >> print dir(frame) >> print 'Signal handler called with signal', signum >> global done >> done = 1 >> >> # Set the signal handler and an alarm >> signal.signal(signal.SIGALRM, handler) >> signal.alarm(3) >> >> print "Looping" >> while not done: >> pass >> >> print "Out of loop" >> >> signal.alarm(0) # Disable the alarm >> >> print "Done" >> ##############################3 >> >> gives this output: >> >>> ================================ RESTART >> ================================ >>> Looping <frame object at >> 0x4fd6c0> ['__class__', '__delattr__', '__doc__', '__getattribute__', >> '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', >> '__repr__', '__setattr__', '__str__', 'f_back', 'f_builtins', >> 'f_code', 'f_exc_traceback', 'f_exc_type', 'f_exc_value', 'f_globals', >> 'f_lasti', 'f_lineno', 'f_locals', 'f_restricted', 'f_trace'] Signal >> handler called with signal 14 Out of loop Done >>> >> >> Kent From dyoo at hkn.eecs.berkeley.edu Thu Sep 16 00:09:45 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Sep 16 00:09:51 2004 Subject: [Tutor] static PyObject * or non-static In-Reply-To: <4147B25D.3030703@conwaycorp.net> Message-ID: <Pine.LNX.4.44.0409151430190.31718-100000@hkn.eecs.berkeley.edu> On Tue, 14 Sep 2004, Rob Benton wrote: > Alan Gauld wrote: > > >>static PyObject * > >>Noddy_name(Noddy* self) > >>{ > >> static PyObject *format = NULL; > >> PyObject *args, *result; > >> > >> > >>make everything static that can be? > > > > > In that chunk of code why isn't the format object temporary? I guess > that's what confusing me. [Note: skip if you're starting to learn Python. This has more to do with the Python/C API, which isn't relevant to most Python programmers.] Hi Rob, It's an optimization hack. *grin* Let's take a look again at the code. This thread seems like it's been running for a bit without a good resolution, so let's summarize what we're talking about. In the Extending and Embedding documentation, there's a function called Noddy_name(): http://docs.python.org/ext/node22.html This Noddy_name() implements the name() method for a Noddy object, in C. Part of this name() method involves making the format string: "%s %s" so that it can later apply string formatting. To generate that format string, we need to do this: format = PyString_FromString("%s %s"); Remember, though, that we're in C, so as a C programmer, we try to overoptimize everything, even if it's not appropriate. *grin* In this case, though, the optimization with static variables is sorta is nice to do, and we'll see why in a moment. What the code in Noddy_name is trying to do is cache the result of this PyString_FromString() call in a static variable. Static variables in C live practically forever, so every time we enter Noddy_name(), the code checks to see if the 'format' string has been initialized yet, using NULL as a sentinel to mark that's something's uninitialized: if (format == NULL) { format = PyString_FromString("%s %s"); if (format == NULL) return NULL; } Why does the system check for (format == NULL) after PyString_FromString()? Because we could have run out of memory, trying to construct a 5 character string. Remember, this is C: we have to worry about memory allocation and error trapping ALL THE TIME. *grin* In summary, the Noddy_name() code that looks like this: /******/ static PyObject * Noddy_name(Noddy* self) { static PyObject *format = NULL; PyObject *args, *result; if (format == NULL) { format = PyString_FromString("%s %s"); if (format == NULL) return NULL; } if (self->first == NULL) { PyErr_SetString(PyExc_AttributeError, "first"); return NULL; } if (self->last == NULL) { PyErr_SetString(PyExc_AttributeError, "last"); return NULL; } args = Py_BuildValue("OO", self->first, self->last); if (args == NULL) return NULL; result = PyString_Format(format, args); Py_DECREF(args); return result; } /******/ can be written like this: /******/ static PyObject * Noddy_name(Noddy* self) { PyObject *format = NULL; PyObject *args = NULL; PyObject *result = NULL; if (self->first == NULL) { PyErr_SetString(PyExc_AttributeError, "first"); goto error; } if (self->last == NULL) { PyErr_SetString(PyExc_AttributeError, "last"); goto error; } args = Py_BuildValue("OO", self->first, self->last); if (args == NULL) goto error; format = PyString_FromString("%s %s"); if (format == NULL) goto error; result = PyString_Format(format, args); Py_DECREF(args); Py_DECREF(format); return result; error: Py_XDECREF(args); Py_XDECREF(format); return NULL; } /******/ So here we've gotten rid of the static variable. This should have same functionality as the old code, although it will run slightly slower since it constructs/destructs the format string on each function call. But the code ends up being a little bit more ugly, because we have to go through some hoops to make sure we don't leak memory. That involves things like making sure all the heap-allocated variables are freed, and to make sure we don't try to free something that hasn't been initialized yet. If anything "bad" happens, we need to make sure to deallocate memory for both the 'args' and 'format'. And the revised code does this using a 'goto' to an error handling block. Py_XDECREF is like Py_DECREF, but it still works right even if the pointer given is NULL. See: http://docs.python.org/api/countingRefs.html#l2h-68 and http://docs.python.org/api/exceptions.html#l2h-26 for another example of this Python/C idiom for handling exceptions. In the original code, since we intend to make 'format' live forever anyway, we can omit the code to DECREF it. So we get two benefits: the original program's a little faster, and ends up being shorter to type. Aren't you glad you can program in Python and not in C? *grin* Hope this helps! From nvettese at pdistributors.com Thu Sep 16 04:06:19 2004 From: nvettese at pdistributors.com (nvettese@pdistributors.com) Date: Thu Sep 16 04:06:27 2004 Subject: [Tutor] Learning Python by example Message-ID: <230210-2200494162619613@M2W024.mail2web.com> I removed the {Spam} from the subject because this isn't spam. Thanks for the input, but this is not something that I am expecting to finish it any specific amount of time. It is something I wanted to do to teach me different aspects of programming and the language. Also, this would be something I would open up to the community to add and change as it grows. For the database, I would like to use Postrges. I have used MySQL in the past, but due to rumored licensing changes, I think Postgres is the way to go. My biggest issue is knowing the undertaking in converting a command line application to GUI with Python. Thanks, Nick Original Message: ----------------- From: Bob Gailer bgailer@alum.rpi.edu Date: Wed, 15 Sep 2004 14:46:49 -0600 To: nvettese@pdistributors.com, tutor@python.org Subject: Re: {Spam?} [Tutor] Learning Python by example At 01:39 PM 9/15/2004, Nicholas Vettese wrote: >I am new to programming, as in don't understand it at all, and I am >looking to start by creating a program that I need. Since I am in the >process of becoming a small business owner, I am looking to create a >product that can handle many aspects of the business (Inventory, A/R, A/P, >Sales, etc...), so I want to start from scratch. >I know this sounds like some crazy plan, but I have something to model it >by. There is a program where I work now (Ultimate Triad System), and it >can do all of that, but it costs 50,000 USD, and another 5,000 USD/month >if you want technical help. I want to GPL this piece for all to use. >My real question, I apologize for the preamble, is whether or not to use a >GUI toolkit right away. I would like to write the program as a regular >command line program, and then convert it to a GUI based application once >it is working. I am not sure if this will increase my workload, or help >me understand the best of both worlds. My 2 cents worth: Sounds like a HUGE undertaking. I think it will cost you more than the price of the other system to do it from scratch. Also I guess there are other accounting systems that can do what you want for a lot less. That said: I like your idea of starting with a command line app, then adding GUI later. Another important consideration is choice of a data base management system. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell -------------------------------------------------------------------- mail2web - Check your email from the web at http://mail2web.com/ . From Kent_Johnson at skillsoft.com Thu Sep 16 04:40:43 2004 From: Kent_Johnson at skillsoft.com (Kent Johnson) Date: Thu Sep 16 04:40:52 2004 Subject: [Tutor] comparing files Message-ID: <3639B18DEF0CE2439DDDD5A828CA25B203ED6C64@EXMAILNAS01.amr.smtf.ds> The easiest way to speed up the search of the English word list is to put it in a dictionary (or set) instead of a list. Searching a long list can slow your program down a lot. Another way to approach the problem would be to see if any of the original French words appear in the English text. Kent -----Original Message----- From: tutor-bounces@python.org on behalf of Brian van den Broek 3) for each element in the MT output word list, check if it is in the reference word list. That will need a for loop and the in keyword. Using if test, augment appropriate counters as you go. There are several ways that I can think of where you could speed this up, and surely a good many more that I haven't seen. For instance, once you get something like that going, you might think about breaking the standard word list up into sub-lists, one for words that start with 'a', etc. (This would reduce how many comparisons you have to make for each word.) You might also look to serialize (or store) those canonical word lists to save the step of constructing them each time. But, once you've got it done as I outline above, you should be well on your way to knowing how to improve it in these or other ways. From rob.benton at conwaycorp.net Thu Sep 16 07:02:02 2004 From: rob.benton at conwaycorp.net (Rob Benton) Date: Thu Sep 16 06:20:42 2004 Subject: [Tutor] static PyObject * or non-static In-Reply-To: <Pine.LNX.4.44.0409151430190.31718-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0409151430190.31718-100000@hkn.eecs.berkeley.edu> Message-ID: <41491E4A.7040401@conwaycorp.net> Danny Yoo wrote: >Hi Rob, > > >It's an optimization hack. *grin* >See: > > http://docs.python.org/api/countingRefs.html#l2h-68 > >and > > http://docs.python.org/api/exceptions.html#l2h-26 > >for another example of this Python/C idiom for handling exceptions. > > >In the original code, since we intend to make 'format' live forever >anyway, we can omit the code to DECREF it. So we get two benefits: the >original program's a little faster, and ends up being shorter to type. > > >Aren't you glad you can program in Python and not in C? *grin* > > >Hope this helps! > > > > > Thanks Danny, that explains a lot. It's my fault for dragging this thread out such a long time (I forgot I even posted it). One thing I did notice in the C API is you can use C++ if you wrap your code inside "extern C" statements. Now since I'm more of a C++ guy, it seems like using a try catch block would be a lot easier than the gotos or am I wrong again :) ? From blk20 at cam.ac.uk Thu Sep 16 11:28:53 2004 From: blk20 at cam.ac.uk (bernhard) Date: Thu Sep 16 10:25:47 2004 Subject: [Tutor] Learning Python by example In-Reply-To: <230210-2200494162619613@M2W024.mail2web.com> References: <230210-2200494162619613@M2W024.mail2web.com> Message-ID: <1095326932.17779.3.camel@localhost> Hi Nick, > For the database, I would like to use Postrges. I have used MySQL in the > past, but due to rumored licensing changes, I think Postgres is the way to > go. What kind of kind of license change are you talking about? All license changes of MySQL in the past were towards GPL. So that should not be a problem if you want to license your program under GPL yourself. Cheers, --Bernhard From thomi at imail.net.nz Thu Sep 16 12:30:43 2004 From: thomi at imail.net.nz (Thomas Clive Richards) Date: Thu Sep 16 12:30:49 2004 Subject: [Tutor] visual development environs? Message-ID: <200409162230.43711.thomi@imail.net.nz> Hi all, I'm looking for a visual development environment (I'm not sure this si the right term) similar to blackadder (http://www.thekompany.com/products/blackadder/). I've seen Boa Constructor, but IMHO it needs a bit more polishing before it's totally usable. I'm not using this for myself, but rather for a friend I've just managed to convince to start learning python; for this reason, additional documentation (tutorials, guides et al) are a huge bonus. Can anyone recommend a good solution? Thanks, -- Thomi Richards, thomi@once.net.nz From thomi at imail.net.nz Thu Sep 16 12:35:15 2004 From: thomi at imail.net.nz (Thomas Clive Richards) Date: Thu Sep 16 12:49:24 2004 Subject: [Tutor] visual development environs? In-Reply-To: <200409162230.43711.thomi@imail.net.nz> References: <200409162230.43711.thomi@imail.net.nz> Message-ID: <200409162235.15598.thomi@imail.net.nz> On Thu, 16 Sep 2004 10:30 pm, Thomas Clive Richards wrote: > Hi all, Forgive me, I'm tired - I forgot to mention that it has to run under Linux (thus the MS visual studio plugins are out of the picture).... 'night ! -- Thomi Richards, thomi@once.net.nz From rschroev_nospam_ml at fastmail.fm Thu Sep 16 13:53:29 2004 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Thu Sep 16 13:53:36 2004 Subject: [Tutor] Re: Learning Python by example In-Reply-To: <230210-2200494162619613@M2W024.mail2web.com> References: <230210-2200494162619613@M2W024.mail2web.com> Message-ID: <ciburp$38n$1@sea.gmane.org> nvettese@pdistributors.com wrote: > My biggest issue is knowing the undertaking in converting a command line > application to GUI with Python. My advice is to put all application-specific functionality in functions and/or classes within modules. That way you can access the functionality from a command line or a GUI application. Another option is a GUI that wraps around a command line application, as e.g. k3b does with cdrecord. But I think it is more difficult (because of the extra complexity of communication between GUI and command line) and it often results in a less integrated package. -- "Codito ergo sum" Roel Schroeven From renderpipe at speedpost.net Thu Sep 16 15:41:58 2004 From: renderpipe at speedpost.net (RenderPipe) Date: Thu Sep 16 15:42:00 2004 Subject: [Tutor] Import tabular data file and assign to variables Message-ID: <1095342118.22368.204507221@webmail.messagingengine.com> Hello, I'm having difficulty trying to figure out how to read in tabular data to variables. I have a file with about 700 lines that look like this: -31.5227 7.7864 -74.4018 -2.4335 -8.7991 -31.5227 7.7864 -74.4018 -2.4335 -8.7991 These are coordinates for a 3d object in 3 translation axis and 2 rotations axis. Each line is 1 frame in time. I need to be able to assign each field value to a variable but I don't understand how to parse the list. Essentially what I need is Frame 1 transx = -31.5227 transy = 7.7864 transz = -74.4018 rotx = -2.4335 roty = -8.7991 Frame 2 etc I was thinking of creating a dictionary object for each frame but I do not know how to extract the data in the colums and assing them to a dictionary. Here's what i have come up with so far: import string myfile = open("MyFile") data = myfile.readlines() for line in data: rs = line.split("\t") print rs The problem with this is it also prints \r\n characters. The example output of this code is: [' -31.5227 7.7864 -74.4018 -2.4335 -8.7991\r\n'] [' -31.5227 7.7864 -74.4018 -2.4335 -8.7991\r\n'] ['\r\n'] I appreciate any input you can offer. TIA From python_newbie at vedorian.com Thu Sep 16 15:52:07 2004 From: python_newbie at vedorian.com (Kevin) Date: Thu Sep 16 15:54:11 2004 Subject: [Tutor] About ansi color Message-ID: <000a01c49bf4$5b92f660$30e57218@basp.phub.net.cable.rogers.com> I was playing around with ansi color in python. What I did to get color was this: fRed = chr(27) + '[31m' so that when I type print fRed+'Hello World' would print in red. The only thing is that the color shows up no problem on linux but but I get a wierd thing showing up an windows. How would I go about making it work on windows? Thanks Kevin -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040916/c46a5e2a/attachment.htm From flaxeater at yahoo.com Thu Sep 16 19:49:41 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Thu Sep 16 19:49:43 2004 Subject: [Tutor] Learning Python by example Message-ID: <20040916174941.44649.qmail@web52610.mail.yahoo.com> nvettese@pdistributors.com wrote: >I removed the {Spam} from the subject because this isn't spam. > >Thanks for the input, but this is not something that I am expecting to >finish it any specific amount of time. It is something I wanted to do to >teach me different aspects of programming and the language. Also, this >would be something I would open up to the community to add and change as it >grows. > >For the database, I would like to use Postrges. I have used MySQL in the >past, but due to rumored licensing changes, I think Postgres is the way to >go. > >My biggest issue is knowing the undertaking in converting a command line >application to GUI with Python. > >Thanks, >Nick > > Well I have in my resent past had the ambition of writing a complex command line tool. I feel that it may be more worth your while to try the Gui first, because it is possible to separate logic completely from presentation but in my (limited) experience it's easier said than done. If you would be happy with a command line only program do that or if you really envision a GUI primary app then do that first. I feel personally that the payouts in learning the GUI toolkit make it a little easier to manage when making the program. As a caveat my Gui projects have been very modest. __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From flaxeater at yahoo.com Thu Sep 16 19:53:14 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Thu Sep 16 19:53:21 2004 Subject: [Tutor] visual development environs? Message-ID: <20040916175314.48113.qmail@web52604.mail.yahoo.com> Thomas Clive Richards wrote: >On Thu, 16 Sep 2004 10:30 pm, Thomas Clive Richards wrote: > > >>Hi all, >> >> > >Forgive me, I'm tired - I forgot to mention that it has to run under Linux >(thus the MS visual studio plugins are out of the picture).... > > >'night ! > > > the two others that I know of are wxglade and pythoncard. __________________________________ Do you Yahoo!? Take Yahoo! Mail with you! Get it on your mobile phone. http://mobile.yahoo.com/maildemo From flaxeater at yahoo.com Thu Sep 16 19:59:42 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Thu Sep 16 19:59:45 2004 Subject: [Tutor] Import tabular data file and assign to variables Message-ID: <20040916175942.48434.qmail@web52607.mail.yahoo.com> RenderPipe wrote: >Hello, > >I'm having difficulty trying to figure out how to read in tabular data >to variables. > >I have a file with about 700 lines that look like this: > -31.5227 7.7864 -74.4018 -2.4335 -8.7991 > -31.5227 7.7864 -74.4018 -2.4335 -8.7991 > >These are coordinates for a 3d object in 3 translation axis and 2 >rotations axis. Each line is 1 frame in time. >I need to be able to assign each field value to a variable but I don't >understand how to parse the list. > >Essentially what I need is >Frame 1 >transx = -31.5227 >transy = 7.7864 >transz = -74.4018 >rotx = -2.4335 >roty = -8.7991 > >Frame 2 >etc > >I was thinking of creating a dictionary object for each frame but I do >not know how to extract the data in the colums and assing them to a >dictionary. >Here's what i have come up with so far: > >import string > >myfile = open("MyFile") >data = myfile.readlines() >for line in data: > rs = line.split("\t") > print rs > >The problem with this is it also prints \r\n characters. The example >output of this code is: >[' -31.5227 7.7864 -74.4018 -2.4335 -8.7991\r\n'] >[' -31.5227 7.7864 -74.4018 -2.4335 -8.7991\r\n'] >['\r\n'] > >I appreciate any input you can offer. > > here try this instead for line in data: rs = line.strip().split() print rs this should give you what you want. For additional information .split() automaticly splits on whitespace, anywhite space, the reason this may not be working right is because what you think is \t is actually spaces. Good luck __________________________________ Do you Yahoo!? New and Improved Yahoo! Mail - Send 10MB messages! http://promotions.yahoo.com/new_mail From renderpipe at speedpost.net Thu Sep 16 20:00:50 2004 From: renderpipe at speedpost.net (RenderPipe) Date: Thu Sep 16 20:00:53 2004 Subject: [Tutor] Import tabular data file and assign to variables In-Reply-To: <20040916175942.48434.qmail@web52607.mail.yahoo.com> References: <20040916175942.48434.qmail@web52607.mail.yahoo.com> Message-ID: <1095357650.13957.204528392@webmail.messagingengine.com> ahh! very cool thanks > here try this instead > > for line in data: > rs = line.strip().split() > print rs > > this should give you what you want. For additional information > .split() > automaticly splits on whitespace, anywhite space, the reason this may > > not be working right is because what you think is \t is actually > spaces. Good luck > > > > __________________________________ > Do you Yahoo!? > New and Improved Yahoo! Mail - Send 10MB messages! > http://promotions.yahoo.com/new_mail From flaxeater at yahoo.com Thu Sep 16 20:03:04 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Thu Sep 16 20:03:13 2004 Subject: [Tutor] About ansi color Message-ID: <20040916180304.40701.qmail@web52602.mail.yahoo.com> Kevin wrote: > I was playing around with ansi color in python. What I did to get > color was this: fRed = chr(27) + '[31m' so that when I type print > fRed+'Hello World' would print in red. The only thing is that the > color shows up no problem on linux but but I get a wierd thing showing > up an windows. How would I go about making it work on windows? > > Thanks > Kevin > >------------------------------------------------------------------------ > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > > You need an ansi driver for things to work right on windows. This article might be helpful for you. http://support.microsoft.com/default.aspx?scid=kb;en-us;Q101875 Good Day _______________________________ Do you Yahoo!? Declare Yourself - Register online to vote today! http://vote.yahoo.com From jeff at ccvcorp.com Thu Sep 16 20:16:34 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu Sep 16 20:14:53 2004 Subject: [Tutor] Import tabular data file and assign to variables In-Reply-To: <1095342118.22368.204507221@webmail.messagingengine.com> References: <1095342118.22368.204507221@webmail.messagingengine.com> Message-ID: <4149D882.2090207@ccvcorp.com> RenderPipe wrote: > I was thinking of creating a dictionary object for each frame but I do > not know how to extract the data in the colums and assing them to a > dictionary. That sounds like a pretty good plan. If you want to get slightly more advanced, you could write a small class and then create an instance of that class for each line. The big advantage here is that you can encapsulate a lot of the code to process each line into the class, and you can later add methods that do interesting things with your data. But for a simple approach, dictionaries (or even tuples) will work well. > Here's what i have come up with so far: > > import string You're not actually using the string module here, so you can skip the import. > myfile = open("MyFile") > data = myfile.readlines() > for line in data: > rs = line.split("\t") > print rs If you call split() with no arguments, then it will default to splitting on all whitespace. If there's multiple whitespace characters together, this default mode will treat them as one. So, for example, when I do this on one of your sample lines, I get this: >>> x ' -31.5227 7.7864 -74.4018 -2.4335 -8.7991\r\n' >>> x.split() ['-31.5227', '7.7864', '-74.4018', '-2.4335', '-8.7991'] >>> Note that this has also eliminated the extra \r\n characters at the end. However, there's a slight catch here -- these are still strings, not floating-point numbers. You'll need to convert them, which we can do to the whole list easily with a list comprehension: >>> x ' -31.5227 7.7864 -74.4018 -2.4335 -8.7991\r\n' >>> rs = [float(num) for num in x.split()] >>> rs [-31.5227, 7.7864000000000004, -74.401799999999994, -2.4335, -8.7990999999999993] >>> (The numbers aren't displaying exactly, because there's tiny representation errors when switching between decimal fractions and binary fractions. It's normal, and shouldn't be a problem unless you need *very* exact precision.) With that, you should be able to put your data into a dictionary or a class pretty easily. Just as an example of how convenient using a class can be, look at this: >>> class Pos3D: ... def __init__(self, transx, transy, transz, rotx, roty): ... self.transx = transx ... self.transy = transy ... self.transz = transz ... self.rotx = rotx ... self.roty = roty ... >>> instance = Pos3D(*rs) >>> instance <__main__.Pos3D instance at 0x02C9EA00> >>> instance.transx, instance.transy, instance.transz (-31.5227, 7.7864000000000004, -74.401799999999994) >>> instance.rotx, instance.roty (-2.4335, -8.7990999999999993) >>> Because the Pos3D class knows what order to expect data in, I can simply tell Python to expand the list of data into a normal argument list for __init__() -- that's what the * in Pos3D(*rs) means. Now I can conveniently refer to all of this data with simple dotted-name syntax. I could also easily write methods like gettrans(), which would return (transx, transy, transz), and getrot(), which would return (rotx, roty), making further work with the data that much simpler. Hope that this helps. Jeff Shannon Technician/Programmer Credit International From renderpipe at speedpost.net Thu Sep 16 22:30:53 2004 From: renderpipe at speedpost.net (RenderPipe) Date: Thu Sep 16 22:30:57 2004 Subject: [Tutor] Import tabular data file and assign to variables In-Reply-To: <4149D882.2090207@ccvcorp.com> References: <1095342118.22368.204507221@webmail.messagingengine.com> <4149D882.2090207@ccvcorp.com> Message-ID: <1095366653.26115.204538414@webmail.messagingengine.com> Thanks for the help and explanation. I have been avoiding classes but I think this is a good time to give it a try. On Thu, 16 Sep 2004 11:16:34 -0700, "Jeff Shannon" <jeff@ccvcorp.com> said: > RenderPipe wrote: > > > I was thinking of creating a dictionary object for each frame but I do > > not know how to extract the data in the colums and assing them to a > > dictionary. > > That sounds like a pretty good plan. If you want to get slightly more > advanced, you could write a small class and then create an instance of > that class for each line. The big advantage here is that you can > encapsulate a lot of the code to process each line into the class, and > you can later add methods that do interesting things with your data. > But for a simple approach, dictionaries (or even tuples) will work well. > > > Here's what i have come up with so far: > > > > import string > > You're not actually using the string module here, so you can skip the > import. > > > myfile = open("MyFile") > > data = myfile.readlines() > > for line in data: > > rs = line.split("\t") > > print rs > > If you call split() with no arguments, then it will default to > splitting on all whitespace. If there's multiple whitespace > characters together, this default mode will treat them as one. So, > for example, when I do this on one of your sample lines, I get this: > > >>> x > ' -31.5227 7.7864 -74.4018 -2.4335 -8.7991\r\n' > >>> x.split() > ['-31.5227', '7.7864', '-74.4018', '-2.4335', '-8.7991'] > >>> > > Note that this has also eliminated the extra \r\n characters at the > end. However, there's a slight catch here -- these are still strings, > not floating-point numbers. You'll need to convert them, which we can > do to the whole list easily with a list comprehension: > > >>> x > ' -31.5227 7.7864 -74.4018 -2.4335 -8.7991\r\n' > >>> rs = [float(num) for num in x.split()] > >>> rs > [-31.5227, 7.7864000000000004, -74.401799999999994, -2.4335, > -8.7990999999999993] > >>> > > (The numbers aren't displaying exactly, because there's tiny > representation errors when switching between decimal fractions and > binary fractions. It's normal, and shouldn't be a problem unless you > need *very* exact precision.) > > With that, you should be able to put your data into a dictionary or a > class pretty easily. Just as an example of how convenient using a > class can be, look at this: > > >>> class Pos3D: > ... def __init__(self, transx, transy, transz, rotx, roty): > ... self.transx = transx > ... self.transy = transy > ... self.transz = transz > ... self.rotx = rotx > ... self.roty = roty > ... > >>> instance = Pos3D(*rs) > >>> instance > <__main__.Pos3D instance at 0x02C9EA00> > >>> instance.transx, instance.transy, instance.transz > (-31.5227, 7.7864000000000004, -74.401799999999994) > >>> instance.rotx, instance.roty > (-2.4335, -8.7990999999999993) > >>> > > Because the Pos3D class knows what order to expect data in, I can > simply tell Python to expand the list of data into a normal argument > list for __init__() -- that's what the * in Pos3D(*rs) means. Now I > can conveniently refer to all of this data with simple dotted-name > syntax. I could also easily write methods like gettrans(), which > would return (transx, transy, transz), and getrot(), which would > return (rotx, roty), making further work with the data that much simpler. > > Hope that this helps. > > Jeff Shannon > Technician/Programmer > Credit International > > From kent_johnson at skillsoft.com Fri Sep 17 01:40:38 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Sep 17 01:40:43 2004 Subject: [Tutor] sentence case module for comments and possible cookbook submission In-Reply-To: <41416E55.9080903@po-box.mcgill.ca> References: <41416E55.9080903@po-box.mcgill.ca> Message-ID: <6.1.0.6.0.20040916190538.029d8030@mail4.skillsoft.com> This is a bit late but I have some suggestions inline below. Kent At 05:05 AM 9/10/2004 -0400, Brian van den Broek wrote: >#! /usr/bin/env python ># sentence_caser.py ># Version 0.1 ># Brian van den Broek ># bvande@po-box.mcgill.ca ># This module is released under the Python License. (See www.python.org.) > >punctuation_indexes = {} >punctuation = ['!', '?'] > >def punctuation_stripper(data_string): > '''punctuation_stripper(data_string) -> data_string > > Stores the indexes of each type of punctuation (other than '.') in the > punctuation_indexes dict and replaces them with '.'s. (This makes > splitting > the string easier, and, thanks to the dict, is reversible.)''' > > for mark in punctuation: > punctuation_indexes[mark] = [] > offset = 0 > while True: > try: > i = data_string.index(mark, offset) > punctuation_indexes[mark].append(i) > offset = i + 1 > except ValueError: > break > data_string = data_string.replace(mark, '.') > return data_string I think you can do without this entirely with a better use of split; see below >def change_to_sentence_case(sentence_list): > '''change_to_sentence_case(sentence_list) -> cap_sentences_list > > Takes a list of sentence strings and transforms it so that the first and > only the first) letter is capitalized. It is a bit more complicated than > just calling the capitalize string method as the strings in the sentence > list may well start with ' ', '(', '[', etc. The while loop travels the > string, looking for the first letter and calling capitalize on the > substring it commences. restore_Is() is also called, in an attempt to > undo > lower-casing of the pronoun "I".''' > > cap_sentences_list = [] > for s in sentence_list: > offset = 0 > while offset < len(s): This would be more idiomatic: for offset in range(len(s)): It's tempting to use re.search here but that's probably overkill. Or you could use re.sub with a class instance that keeps enough state to lower-case just the first alpha as the sub parameter :-) > if s[offset].isalpha(): > s = s[:offset] + s[offset:].capitalize() > break > offset += 1 > s += '.' You don't need this extra period, see below > s = restore_Is(s) > cap_sentences_list.append(s) > return cap_sentences_list > >def restore_Is(sentence): > '''restore_Is(sentence) -> sentence > > Takes a sentence string and tries to restore any "I"s incorrectly changed > to "i"s by change_to_sentence_case()'s use of .capitalize().''' > > sentence = sentence.replace(' i ', ' I ') > sentence = sentence.replace(' i,', ' I,') > sentence = sentence.replace(' i.', ' I.') > return sentence You could do this very nicely with a regular expression and catch i? i! i; etc as well: >>> sentence = "i'll i will i?" >>> import re >>> sentence = re.sub(r'\bi\b', 'I', sentence) >>> sentence "I'll I will I?" The regular expression says to match an 'i' that is a word by itself. >def restore_punctuation(data_sentences): > '''restore_punctuation(data_sentences) -> data_sentences > > Consulting the punctuation_indexes dict, restore_punctuation() reverts > non '.' punctuation that was changed to '.' to facilitate splitting the > string.''' > for mark in punctuation: > for i in punctuation_indexes[mark]: > data_sentences = data_sentences[:i] + mark + data_sentences[i > + 1:] > return data_sentences You don't need this either, see below >def sentence_caser(data_string): > '''sentence_caser(data_string) -> data_string > > Takes a string and returns it into sentence case (it is hoped). To do so, > it runs it through various helper functions. sentence_caser() does almost > no work on its own; consult the functions punctuation_stripper(), > change_to_sentence_case(), and restore_punctuation() for details of the > processing.''' > > working_data = punctuation_stripper(data_string) > data_sentences_list = working_data.split('.') > data_sentences_list = change_to_sentence_case(data_sentences_list) > data_sentences = ''.join(data_sentences_list) > data_sentences = restore_punctuation(data_sentences) > > data_sentences = data_sentences[:len(data_string)] > # To remove possibly spurious trailing '.' added when original string > ended > # with non-'.' character (as in data below). > > return data_sentences If you use data_sentences_list = re.split(r'([.!?])', data_string) you will split on all the punctuation you care about and retain the punctuation as individual list entries in the sentence list. When you rejoin the sentences you will get the correct punctuation back. Then punctuation_stripper, restore_punctuation and the hack with the extra period are not needed. This whole block of code reduces to data_sentences_list = re.split(r'([.!?])', data_string) data_sentences_list = change_to_sentence_case(data_sentences_list) data_sentences = ''.join(data_sentences_list) return data_sentences >if __name__ == '__main__': > data = '''STRINGS IN ALL CAPS ARE HARD TO READ! SOME PEOPLE THINK > THEY ARE >LIKE SHOUTING. DO YOU THINK SO? I ONLY WRITE THEM WHEN I HAVE A CAPS-LOCK >ACCIDENT. (OR WHEN CREATING TEST DATA.) THEY ARE NO FUN. (OK, ENOUGH NOW.)''' > print data > print > print sentence_caser(data) Here's the whole rewrite: #! /usr/bin/env python # sentence_caser.py # Version 0.1 # Brian van den Broek # bvande@po-box.mcgill.ca # This module is released under the Python License. (See www.python.org.) import re def change_to_sentence_case(sentence_list): '''change_to_sentence_case(sentence_list) -> cap_sentences_list Takes a list of sentence strings and transforms it so that the first and only the first) letter is capitalized. It is a bit more complicated than just calling the capitalize string method as the strings in the sentence list may well start with ' ', '(', '[', etc. The while loop travels the string, looking for the first letter and calling capitalize on the substring it commences. restore_Is() is also called, in an attempt to undo lower-casing of the pronoun "I".''' cap_sentences_list = [] for s in sentence_list: for offset in range(len(s)): if s[offset].isalpha(): s = s[:offset] + s[offset:].capitalize() break s = restore_Is(s) cap_sentences_list.append(s) return cap_sentences_list def restore_Is(sentence): '''restore_Is(sentence) -> sentence Takes a sentence string and tries to restore any "I"s incorrectly changed to "i"s by change_to_sentence_case()'s use of .capitalize().''' sentence = re.sub(r'\bi\b', 'I', sentence) return sentence def sentence_caser(data_string): '''sentence_caser(data_string) -> data_string Takes a string and returns it into sentence case (it is hoped). To do so, it runs it through various helper functions. sentence_caser() does almost no work on its own; consult the functions punctuation_stripper(), change_to_sentence_case(), and restore_punctuation() for details of the processing.''' data_sentences_list = re.split(r'([.!?])', data_string) data_sentences_list = change_to_sentence_case(data_sentences_list) data_sentences = ''.join(data_sentences_list) return data_sentences if __name__ == '__main__': data = '''STRINGS IN ALL CAPS ARE HARD TO READ! SOME PEOPLE THINK THEY ARE LIKE SHOUTING. DO YOU THINK SO? I ONLY WRITE THEM WHEN I HAVE A CAPS-LOCK ACCIDENT. (OR WHEN CREATING TEST DATA.) THEY ARE NO FUN. (OK, ENOUGH NOW.)''' print data print print sentence_caser(data) From kent_johnson at skillsoft.com Fri Sep 17 01:45:09 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Sep 17 01:45:13 2004 Subject: [Tutor] write to /dev/stdin during call to posix command? In-Reply-To: <pan.2004.09.10.17.16.06.556269@yahoo.com> References: <pan.2004.09.10.17.16.06.556269@yahoo.com> Message-ID: <6.1.0.6.0.20040916194345.029d9678@mail4.skillsoft.com> Did you try pdfinput = open('sample.pdf','r').read() r,w,e = os.popen3('pdftotext -layout /dev/stdin -') r.write(pdfinput) ? Kent At 01:16 PM 9/10/2004 -0400, Jeff Kowalczyk wrote: >How can I write to /dev/stdin during a call to a posix command? The >pdftotext command will write to stdout if given '-' as the output >filename, but it lacks the same paramater for reading from stdin. > >However, using /dev/stdin and directing a file to the input works fine: > ># pdftotext -layout /dev/stdin - < sample.pdf > >Reading from stdout with a physical file input is no problem: > >r,w,e = os.popen3('pdftotext -layout sample.pdf -') >w.read() # gives the text string I am looking for > >But I don't quite understand how I should send a string representing the >input pdf (pdfinput) to the version of the command using /dev/stdin: > >pdfinput = open('sample.pdf','r').read() >r,w,e = os.popen3('pdftotext -layout /dev/stdin -') > >Any ideas? I'm using python-2.3.4, linux. Thanks. > >Jeff > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From python_newbie at vedorian.com Fri Sep 17 04:24:22 2004 From: python_newbie at vedorian.com (Kevin) Date: Fri Sep 17 04:26:22 2004 Subject: [Tutor] More about ANSI color Message-ID: <000801c49c5d$726798a0$30e57218@basp.phub.net.cable.rogers.com> I am trying to figure out if this can be done or not. As of right now the way I add color to a string is like this fRed = chr(27) + '[31m' bOff = chr(27) + '[22m' #Turn bold off cEnd = chr(27) + '[0m' #Reset the color back to normal print fRed+'Hello world'+cEnd #turn bold off would be print bOff+fRed+'Hello world'+cEnd Is there a way to make it so that there is less typing for example you could mabey right the "Hello world" like this print '{RHello world{X' where {R is red or {r would be unbold red and {X is reset. Thanks Kevin -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040916/08554c47/attachment.html From bvande at po-box.mcgill.ca Fri Sep 17 05:33:55 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Fri Sep 17 06:07:41 2004 Subject: [Tutor] sentence case module for comments and possible cookbook submission In-Reply-To: <6.1.0.6.0.20040916190538.029d8030@mail4.skillsoft.com> References: <41416E55.9080903@po-box.mcgill.ca> <6.1.0.6.0.20040916190538.029d8030@mail4.skillsoft.com> Message-ID: <414A5B23.1020904@po-box.mcgill.ca> Kent Johnson said unto the world upon 2004-09-16 19:40: > This is a bit late but I have some suggestions inline below. > > Kent > > At 05:05 AM 9/10/2004 -0400, Brian van den Broek wrote: > >> #! /usr/bin/env python >> # sentence_caser.py >> # Version 0.1 >> # Brian van den Broek >> # bvande@po-box.mcgill.ca >> # This module is released under the Python License. (See www.python.org.) <SNIP> Thanks Kent! (Help then, help now, whatever. There's no such thing as free help that comes too late.) I'll have a close look some time this weekend, but wanted to say thanks now. Best to all, Brian vdB From kent_johnson at skillsoft.com Fri Sep 17 12:02:03 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Sep 17 12:02:15 2004 Subject: [Tutor] More about ANSI color In-Reply-To: <000801c49c5d$726798a0$30e57218@basp.phub.net.cable.rogers. com> References: <000801c49c5d$726798a0$30e57218@basp.phub.net.cable.rogers.com> Message-ID: <6.1.0.6.0.20040917055645.029c7880@mail4.skillsoft.com> Why not make a function to convert the tokens you want to use to the actual tokens and another function that converts and prints? Then you could say colorPrint('{RHello world{X') colorPrint would be def colorPrint(s): print colorize(s) colorize() could be based on this Python Cookbook recipe which does multiple replacements in a string with a single call to re.sub(): http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81330 Put the functions into a module and you can import them and use them wherever you like. Kent At 10:24 PM 9/16/2004 -0400, Kevin wrote: >I am trying to figure out if this can be done or not. As of right now the >way I add color to a string is like this > >fRed = chr(27) + '[31m' >bOff = chr(27) + '[22m' #Turn bold off >cEnd = chr(27) + '[0m' #Reset the color back to normal > >print fRed+'Hello world'+cEnd >#turn bold off would be >print bOff+fRed+'Hello world'+cEnd > >Is there a way to make it so that there is less typing for example you >could mabey right the "Hello world" like this > >print '{RHello world{X' > >where {R is red or {r would be unbold red and {X is reset. >Thanks > >Kevin >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From dyoo at hkn.eecs.berkeley.edu Fri Sep 17 19:20:32 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Sep 17 19:20:37 2004 Subject: [Tutor] static PyObject * or non-static In-Reply-To: <41491E4A.7040401@conwaycorp.net> Message-ID: <Pine.LNX.4.44.0409170958150.6882-100000@hkn.eecs.berkeley.edu> > One thing I did notice in the C API is you can use C++ if you wrap your > code inside "extern C" statements. Now since I'm more of a C++ guy, it > seems like using a try catch block would be a lot easier than the gotos Hi Rob, Yes, that will probably work. I have to admit that I haven't touched C++ in a long time, so I might be more incompetent about it than I realize. But yes, in theory, using exceptions instead of GOTOs should work. In fact, when the C++ Special Interest Group stated, that was Point Six of its agenda: http://groups.google.com/groups?selm=b9wwsk79l0.fsf%40laura.llnl.gov&output=gplain *grin* If you're interested in C++/Python integration stuff, the c++-sig is probably the best place to ask questions. They appear very active! Here's a link to their mailing list: http://mail.python.org/mailman/listinfo/c++-sig I hope this helps! From nick at javacat.f2s.com Fri Sep 17 19:39:21 2004 From: nick at javacat.f2s.com (Nick Lunt) Date: Fri Sep 17 19:35:41 2004 Subject: [Tutor] pythoncard installation Message-ID: <1095442761.3090.10.camel@localhost.localdomain> Hi Folks, this if off topic but I hope someone can point me in the right direction, to save me from having to subscribe to the pythoncard mailing list. I just installed PythonCard-0.8 on Fedora Core 2 running python-2.3.3 . I'd already installed wxPython so PythonCard installed fine. However, I now want to run the resource.py to open the GUI creating tool, but I get the following error: [nickl@custard PythonCard]$ pwd /usr/lib/python2.3/site-packages/PythonCard [nickl@custard PythonCard]$ python resource.py Traceback (most recent call last): File "resource.py", line 227, in ? SpecDoc( 'spec.py', 'ComponentSpecHtmlFormat' ) NameError: name 'SpecDoc' is not defined resource.py calls a function called SpecDoc, which I cannot find anywhere. The following command searches all *.py files on my system and looks for SpecDoc, and here's the results: [nickl@custard python2.3]$ find . -name "*.py" -exec grep -l SpecDoc {} \; ./site-packages/PythonCard/build/lib/PythonCard/resource.py ./site-packages/PythonCard/resource.py But both of these versions of resource.py fail with the error as shown above. Im sorry this is off topic, but I've seen that several folk on here use PythonCard (hopefully on linux), so Im just wondering if someone can tell me where Im going wrong here :) Many thanks Nick. From kent_johnson at skillsoft.com Fri Sep 17 19:59:02 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Sep 17 19:59:13 2004 Subject: [Tutor] pythoncard installation In-Reply-To: <1095442761.3090.10.camel@localhost.localdomain> References: <1095442761.3090.10.camel@localhost.localdomain> Message-ID: <6.1.0.6.0.20040917135710.0285a298@mail4.skillsoft.com> It looks like the main in resource.py is not being maintained. To run the resource editor try \site-packages\PythonCard\tools\resourceEditor\resourceEditor.py Kent At 06:39 PM 9/17/2004 +0100, Nick Lunt wrote: >Hi Folks, > >this if off topic but I hope someone can point me in the right >direction, to save me from having to subscribe to the pythoncard mailing >list. > >I just installed PythonCard-0.8 on Fedora Core 2 running python-2.3.3 . > >I'd already installed wxPython so PythonCard installed fine. >However, I now want to run the resource.py to open the GUI creating >tool, but I get the following error: > >[nickl@custard PythonCard]$ pwd >/usr/lib/python2.3/site-packages/PythonCard >[nickl@custard PythonCard]$ python resource.py >Traceback (most recent call last): > File "resource.py", line 227, in ? > SpecDoc( 'spec.py', 'ComponentSpecHtmlFormat' ) >NameError: name 'SpecDoc' is not defined > >resource.py calls a function called SpecDoc, which I cannot find >anywhere. > >The following command searches all *.py files on my system and looks for >SpecDoc, and here's the results: > >[nickl@custard python2.3]$ find . -name "*.py" -exec grep -l SpecDoc {} >\; >./site-packages/PythonCard/build/lib/PythonCard/resource.py >./site-packages/PythonCard/resource.py > >But both of these versions of resource.py fail with the error as shown >above. > >Im sorry this is off topic, but I've seen that several folk on here use >PythonCard (hopefully on linux), so Im just wondering if someone can >tell me where Im going wrong here :) > >Many thanks >Nick. > > > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From nick at javacat.f2s.com Fri Sep 17 20:08:07 2004 From: nick at javacat.f2s.com (Nick Lunt) Date: Fri Sep 17 20:04:27 2004 Subject: [Tutor] pythoncard installation In-Reply-To: <6.1.0.6.0.20040917135710.0285a298@mail4.skillsoft.com> References: <1095442761.3090.10.camel@localhost.localdomain> <6.1.0.6.0.20040917135710.0285a298@mail4.skillsoft.com> Message-ID: <1095444486.7102.2.camel@localhost.localdomain> Hi Kent, On Fri, 2004-09-17 at 18:59, Kent Johnson wrote: > It looks like the main in resource.py is not being maintained. To run the > resource editor try > \site-packages\PythonCard\tools\resourceEditor\resourceEditor.py your absolutely right of course. I should of looked in the tools dir. Many thanks for the speedy response. Nick. From davholla2002 at yahoo.co.uk Sat Sep 18 10:53:54 2004 From: davholla2002 at yahoo.co.uk (David Holland) Date: Sat Sep 18 10:53:56 2004 Subject: [Tutor] : Question on open and read html files and psycopg In-Reply-To: <20040916100041.A13011E4011@bag.python.org> Message-ID: <20040918085354.85672.qmail@web25404.mail.ukl.yahoo.com> ------------------------------------------------------------- Just instead of asking for a complete SQL query (which would be a bad idea) Just ask for keywords and build up a string from there. 7, Issue 44 ************************************ Asking for a complete sql query would be a very bad idea. You would open yourself to the risk of sql injection make sure that users can not enter sql via a form. I am not that good at python but I know about this. --------------------------------- 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/20040918/ae57ad80/attachment.html From johan at accesstel.co.za Mon Sep 20 12:41:05 2004 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Mon Sep 20 12:42:19 2004 Subject: [Tutor] Network programming In-Reply-To: <6.1.0.6.0.20040913060048.0299a328@mail4.skillsoft.com> References: <1094473155.4233.23.camel@linux.site> <6.1.0.6.0.20040907085123.02869dd8@mail4.skillsoft.com> <1094717689.4427.10.camel@linux.site> <6.1.0.6.0.20040909180124.0297de28@mail4.skillsoft.com> <1095061736.4429.10.camel@linux.site> <6.1.0.6.0.20040913060048.0299a328@mail4.skillsoft.com> Message-ID: <1095676864.4358.33.camel@linux.site> Hi all ye good people, I have a incomming data stream on a socket and are forwarding all the data to a client connection. I want to look for a certain data sequence in the incomming data and if that is received, the socket connection must be closed. In the following code, newdata is received from a socket server and send out to a client connection self.sock(). Now if 'brsq' is in the data received, the connection 'conn' must be closed. Or the preceeding while loop must be broken. At this stage the 'brsq' is not recognised. Any suggestions? Thanks Johan if conn in inFds: newdata = conn.recv(8192) self.log('Newdata recveived in line 129:' + `newdata`) self.sock.send(newdata) brsq = '\x71\x0D\0A' if brsq in newdata: self.log('Break signal received on line 134' + `newdata`) break else: continue On Mon, 2004-09-13 at 12:03, Kent Johnson wrote: > At 09:48 AM 9/13/2004 +0200, Johan Geldenhuys wrote: > >Thanks Kent, > > > >I will look at my loop and at the links you gave. My links stays up, but > >as you noticed, I must get away of sending the data received from either > >connections. Will I be able to use the select.select for this. > > Yes, you can use select, or either of the modules built on top of select - > asyncore and asynchat. > > >There are three file desriptors in this. One for incoming, one for > >outgoing and the other for errors. Can I use the outgoing one to send the > >data the incoming list received? > > Yes, that is the right approach. > > Kent > > > > >Thanks > > > >Johan > > > >On Fri, 2004-09-10 at 03:44, Kent Johnson wrote: > >> > >>Johan, > >> > >>It looks to me like your program will get stuck in the inner while loop. > >>There is no way inside this loop to get a new value for indata or outdata. > >> > >>There are two approaches you could use to solve your problem - either put > >>the two sides of the transfer into separate threads, or use some kind of > >>polling to look for data available on either socket. > >> > >>The thread approach usually uses three threads: > >>- a master thread that listens to the server socket and accepts the > >>incoming connection. It then opens the forwarding socket and spawns two > >>forwarding threads. > >>- the forwarding threads read from one socket and write to another. They > >>are symmetric - one thread reads from socket A and writes to socket B; the > >>other thread reads from socket B and writes to socket A. > >> > >>Each thread uses blocking I/O - the master thread blocks on > >>socket.accept(); the forwarding threads block on socket.recv(). > >> > >>A simple example that uses the treaded approach to do something similar to > >>what you want to do is here: > >><http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/114642>http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/114642 > >>In this case the Pinhole class is the master thread; when it gets a > >>connection it creates two PipeThreads to do the reading and writing. > >> > >> > >>The polling approach uses non-blocking I/O. In it's crudest form its loop > >>looks like this: > >>forever: > >> if data available on socket A: > >> read from socket A > >> write to socket B > >> if data available on socket B: > >> read from socket B > >> write to socket A > >> sleep for a bit > >> > >>This is crude because it is either unresponsive (if the sleep is long) or > >>wasteful of CPU (if the sleep is short and there is not much to do). It > >>might be fine for a simple use with just one connection, though. > >> > >>The Python asyncore and asynchat modules use a more sophisticated version > >>of this; instead of sleeping, they use a system call that blocks until > >>there is activity on any of the sockets it is watching. This is very > >>efficient, as the polling loop only wakes up when there is something for it > >>to do. Medusa > >><<http://www.nightmare.com/medusa/index.html>http://www.nightmare.com/medusa/index.html> > >>and Twisted > >><<http://www.twistedmatrix.com/>http://www.twistedmatrix.com/> are two > >>servers that are based on this > >>approach. It can be more efficient for large numbers of connections because > >>it doesn't have to create a thread for each one. > >> > >>asyncore and asynchat hide the actual polling loop from you. You interact > >>with them by defining callback methods that get called when data is > >>available or when a channel is available for writing. This tutorial is a > >>good introduction to this approach. The proxy server at the end is similar > >>to what you are trying to do. > >><http://www.nightmare.com/medusa/programming.html>http://www.nightmare.com/medusa/programming.html > >> > >>Medusa includes a chat server which is also similar to your application. > >> > >>I hope this helps get you on the right track! > >>Kent > >> > >>At 10:14 AM 9/9/2004 +0200, Johan Geldenhuys wrote: > >> >I still have trouble when I want to send data out as soon as it comes in > >> >from one side. > >> >My server listens and accepts the calls and then builds the client > >> >connection to the destination. Please see if you can assist. > >> > > >> >Thanks > >> > > >> >Johan > >> >#################################################### > >> > > >> ># we have an incoming socket connect > >> > newConn, addr = self._serverSocket.accept() > >> > self.log('Connection received from: %s:%s' % addr) > >> > > >> > #while connection is active on server: > >> > while 1: > >> > #self._ne1_id = '1234' > >> > #self._ne2_id = '1111' > >> > > >> > indata = newConn.recv(8192) > >> > self.log('First Data received from LCT:' + > >> > `indata`) > >> > > >> > if '\xff' in indata: > >> > continue > >> > > >> > if '\x01' in indata: > >> > continue > >> > > >> > #Look for string of 1234 in indata: > >> > if indata[0:4] == self._ne1_id: > >> > self.log('indata 0:4 is:' + `indata[0:4]`) > >> > self.sock = socket(AF_INET, SOCK_STREAM) > >> > > >> > #connect to this destination if the string is > >> > 1234 > >> > self.sock.connect((self._ne1_ip, > >> > self._ne1_port)) # This is previously defined > >> > self.log('Connection established to NE1: > >> > %s:%i' % (self._ne1_ip, self._ne1_port)) > >> > outdata = self.sock.recv(8192) > >> > #when connection to destination is up: > >> > while 1: > >> > if indata: > >> > self.sock.send(indata) > >> > self.log('indata send to NE, line > >> > 106: ' + `indata`) > >> > > >> > # If break sequence is received from > >> > server side, close the client connection > >> > if '\x11' in indata: > >> > self.log('Break character received') > >> > break > >> > self.sock.close() > >> > self.log('connection to NE1 now > >> closed') > >> > > >> > if oudata: > >> > newConn.send(outdata) > >> > self.log('Data from NE:' + > >> `outdata`) > >> >########################################################### > >> > > >> > > >> > > >> > > >> > > >> > > >> > > >> > > >> > > >> > > >> > > >> >On Tue, 2004-09-07 at 14:58, Kent Johnson wrote: > >> >> > >> >> > >> >>We might be better able to help if you post your code. > >> >> > >> >>Here is a list of HTTP proxy servers written in Python, you might find > >> >>something helpful there: > >> >><<http://xhaus.com/alan/python/proxies.html>http://xhaus.com/alan/pytho > >> n/proxies.html>http://xhaus.com/alan/python/proxies.html > >> >> > >> >>Kent > >> >> > >> >>At 02:19 PM 9/6/2004 +0200, Johan Geldenhuys wrote: > >> >> >Hi, > >> >> > > >> >> >I am new to Python and would like to know more about network programming > >> >> >in particilar. > >> >> > > >> >> >I have a script that sets up a socket server and must wait for incoming > >> >> >connections. Once a call has been accepted, it must make another socket > >> >> >connection to a destination. > >> >> > > >> >> >Now, I want to let these two "talk" to each other. Once the server > >> >> >receives data it must be send out to the destination and when the > >> >> >destination has data, it must be send out to the connection that > >> made the > >> >> >first call to the server. > >> >> > > >> >> >Does anybody have any examples or tips on how I can let this happen. My > >> >> >calls work for the first batch of data and then when new data is > >> received, > >> >> >the calls break. > >> >> > > >> >> >Thanks > >> >> > > >> >> >-- > >> >> > Johan Geldenhuys > >> >> >Access Telecommunication Systems > >> >> > Mail to: johan@accesstel.co.za > >> >> >-- > >> >> >This message has been scanned for viruses and > >> >> >dangerous content by > >> >> > >> <<<http://www.azitech.co.za>http://www.azitech.co.za>http://www.azitech.co.za>Azitech, > >> and is > >> >> >believed to be clean. > >> >> >_______________________________________________ > >> >> >Tutor maillist - Tutor@python.org > >> >> ><<http://mail.python.org/mailman/listinfo/tutor>http://mail.python.or > >> g/mailman/listinfo/tutor>http://mail.python.org/ma > >> >> ilman/listinfo/tutor > >> > > >> > > >> > > >> > > >> > > >> >-- > >> > Johan Geldenhuys > >> >Access Telecommunication Systems > >> > Mail to: johan@accesstel.co.za > >> > > >> >-- > >> >This message has been scanned for viruses and > >> >dangerous content by > >> <<http://www.azitech.co.za>http://www.azitech.co.za>Azitech, and is > >> >believed to be clean. > >> > >>_______________________________________________ > >>Tutor maillist - Tutor@python.org > >><http://mail.python.org/mailman/listinfo/tutor>http://mail.python.org/mailman/listinfo/tutor > > > > > > > > > > > >-- > > Johan Geldenhuys > >Access Telecommunication Systems > > Mail to: johan@accesstel.co.za > > > >-- > >This message has been scanned for viruses and > >dangerous content by <http://www.azitech.co.za>Azitech, and is > >believed to be clean. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Johan Geldenhuys Access Telecommunication Systems Mail to: johan@accesstel.co.za -- This message has been scanned for viruses and dangerous content by Azitech, and is believed to be clean. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040920/a373490c/attachment.html From kent_johnson at skillsoft.com Mon Sep 20 14:31:30 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Mon Sep 20 14:31:49 2004 Subject: [Tutor] Network programming In-Reply-To: <1095676864.4358.33.camel@linux.site> References: <1094473155.4233.23.camel@linux.site> <6.1.0.6.0.20040907085123.02869dd8@mail4.skillsoft.com> <1094717689.4427.10.camel@linux.site> <6.1.0.6.0.20040909180124.0297de28@mail4.skillsoft.com> <1095061736.4429.10.camel@linux.site> <6.1.0.6.0.20040913060048.0299a328@mail4.skillsoft.com> <1095676864.4358.33.camel@linux.site> Message-ID: <6.1.0.6.0.20040920075315.02874778@mail4.skillsoft.com> Are you using Python 2.3? Prior to 2.3, 'x in y' would throw a TypeError if y is a string and x is a string longer than one character. Is it working sometimes but missing sometimes? If the brsq spans an 8192-byte boundary you will miss it. Are you sure the brsq is in the data sent? Maybe it has just a newline terminator, or a space after the \x71 or some other difference from what you are expecting. Kent At 12:41 PM 9/20/2004 +0200, you wrote: >Hi all ye good people, >I have a incomming data stream on a socket and are forwarding all the data >to a client connection. > >I want to look for a certain data sequence in the incomming data and if >that is received, the socket connection must be closed. In the following >code, newdata is received from a socket server and send out to a client >connection self.sock(). Now if 'brsq' is in the data received, the >connection 'conn' must be closed. Or the preceeding while loop must be >broken. At this stage the 'brsq' is not recognised. > >Any suggestions? > >Thanks >Johan > >if conn in inFds: > newdata = conn.recv(8192) > self.log('Newdata recveived in line 129:' + `newdata`) > self.sock.send(newdata) > > brsq = '\x71\x0D\0A' > > if brsq in newdata: > self.log('Break signal received on line 134' + `newdata`) > break > > else: > continue > From johan at accesstel.co.za Mon Sep 20 14:48:46 2004 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Mon Sep 20 14:49:50 2004 Subject: [Tutor] Network programming In-Reply-To: <6.1.0.6.0.20040920075315.02874778@mail4.skillsoft.com> References: <1094473155.4233.23.camel@linux.site> <6.1.0.6.0.20040907085123.02869dd8@mail4.skillsoft.com> <1094717689.4427.10.camel@linux.site> <6.1.0.6.0.20040909180124.0297de28@mail4.skillsoft.com> <1095061736.4429.10.camel@linux.site> <6.1.0.6.0.20040913060048.0299a328@mail4.skillsoft.com> <1095676864.4358.33.camel@linux.site> <6.1.0.6.0.20040920075315.02874778@mail4.skillsoft.com> Message-ID: <1095684526.4358.68.camel@linux.site> I am using 2.3.4. It is for sure in the data stream and not outside the 8192 boundary. It is characters that I send myslef to the port and nothing happens. I can see that the other end gets it. Johan On Mon, 2004-09-20 at 14:31, Kent Johnson wrote: > Are you using Python 2.3? Prior to 2.3, 'x in y' would throw a TypeError if > y is a string and x is a string longer than one character. > > Is it working sometimes but missing sometimes? If the brsq spans an > 8192-byte boundary you will miss it. > > Are you sure the brsq is in the data sent? Maybe it has just a newline > terminator, or a space after the \x71 or some other difference from what > you are expecting. > > Kent > > At 12:41 PM 9/20/2004 +0200, you wrote: > >Hi all ye good people, > >I have a incomming data stream on a socket and are forwarding all the data > >to a client connection. > > > >I want to look for a certain data sequence in the incomming data and if > >that is received, the socket connection must be closed. In the following > >code, newdata is received from a socket server and send out to a client > >connection self.sock(). Now if 'brsq' is in the data received, the > >connection 'conn' must be closed. Or the preceeding while loop must be > >broken. At this stage the 'brsq' is not recognised. > > > >Any suggestions? > > > >Thanks > >Johan > > > >if conn in inFds: > > newdata = conn.recv(8192) > > self.log('Newdata recveived in line 129:' + `newdata`) > > self.sock.send(newdata) > > > > brsq = '\x71\x0D\0A' > > > > if brsq in newdata: > > self.log('Break signal received on line 134' + `newdata`) > > break > > > > else: > > continue > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Johan Geldenhuys Access Telecommunication Systems Mail to: johan@accesstel.co.za -- This message has been scanned for viruses and dangerous content by Azitech, and is believed to be clean. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040920/23473ab4/attachment.html From csmwxl at bath.ac.uk Mon Sep 20 17:12:10 2004 From: csmwxl at bath.ac.uk (W X Liu) Date: Mon Sep 20 17:12:12 2004 Subject: [Tutor] What's the difference between raw_input and input? In-Reply-To: <Pine.LNX.4.44.0409091254080.19699-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0409091254080.19699-100000@hkn.eecs.berkeley.edu> Message-ID: <1095693130.414ef34a11188@webmail.bath.ac.uk> Hi all, Does anybody know What's the difference between raw_input and input? Many thanks Wenxin From olavi at city.ee Mon Sep 20 17:19:55 2004 From: olavi at city.ee (Olavi Ivask) Date: Mon Sep 20 17:20:00 2004 Subject: [Tutor] What's the difference between raw_input and input? In-Reply-To: <1095693130.414ef34a11188@webmail.bath.ac.uk> References: <Pine.LNX.4.44.0409091254080.19699-100000@hkn.eecs.berkeley.edu> <1095693130.414ef34a11188@webmail.bath.ac.uk> Message-ID: <200409201819.55998.olavi@city.ee> input simply gets raw input, sends it to eval, and then returns the result. Raw_input returns input in unprocessed form. Olavi Ivask On Monday 20 September 2004 18:12, W X Liu wrote: > Hi all, > > Does anybody know What's the difference between raw_input and input? > > Many thanks > > Wenxin > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From bgailer at alum.rpi.edu Mon Sep 20 18:00:08 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Mon Sep 20 17:58:18 2004 Subject: {Spam?} [Tutor] What's the difference between raw_input and input? In-Reply-To: <1095693130.414ef34a11188@webmail.bath.ac.uk> References: <Pine.LNX.4.44.0409091254080.19699-100000@hkn.eecs.berkeley.edu> <1095693130.414ef34a11188@webmail.bath.ac.uk> Message-ID: <6.1.2.0.0.20040920095743.0471fe90@mail.mric.net> At 09:12 AM 9/20/2004, W X Liu wrote: >Hi all, > >Does anybody know What's the difference between raw_input and input? Have you looked them up in the Python Reference? I suggest you do so. We like to help, but we hesitate to spend valuable time answering questions that can be easily looked up. If you do not understand what the reference says, come back and tell us what the problem is. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From jtk at yahoo.com Mon Sep 20 19:22:04 2004 From: jtk at yahoo.com (Jeff Kowalczyk) Date: Mon Sep 20 19:21:22 2004 Subject: [Tutor] Re: write to /dev/stdin during call to posix command? References: <pan.2004.09.10.17.16.06.556269@yahoo.com> <6.1.0.6.0.20040916194345.029d9678@mail4.skillsoft.com> Message-ID: <pan.2004.09.20.17.22.03.141955@yahoo.com> Kent Johnson wrote: | Did you try: | pdfinput = open('sample.pdf','r').read() | r,w,e = os.popen3('pdftotext -layout /dev/stdin -') | r.write(pdfinput) Yes, but a subsequent call to w.read() will hang until interrupted. I also tried to w.seek(0) before reading. There doesn't seem to be any communication between writing to r and the process awaiting stdin. I ran a version with a file hardcoded in place of '-' (stdout) and it didn't write anything, even an empty file. From rdm at rcblue.com Mon Sep 20 20:12:05 2004 From: rdm at rcblue.com (Dick Moores) Date: Mon Sep 20 20:12:09 2004 Subject: [Tutor] What's the difference between raw_input and input? In-Reply-To: <6.1.2.0.0.20040920095743.0471fe90@mail.mric.net> References: <Pine.LNX.4.44.0409091254080.19699-100000@hkn.eecs.berkeley.edu> <1095693130.414ef34a11188@webmail.bath.ac.uk> <6.1.2.0.0.20040920095743.0471fe90@mail.mric.net> Message-ID: <6.1.2.0.2.20040920110448.04a70dc0@rcblue.com> Bob Gailer wrote at 09:00 9/20/2004: >At 09:12 AM 9/20/2004, W X Liu wrote: >>Hi all, >> >>Does anybody know What's the difference between raw_input and input? > >Have you looked them up in the Python Reference? I suggest you do so. We >like to help, but we hesitate to spend valuable time answering questions >that can be easily looked up. If you do not understand what the >reference says, come back and tell us what the problem is. The question made me realize I didn't know the difference either. My attempts to get the answer turned up only this description of raw_imput(): =============================== raw_input( [prompt]) If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised. Example: >>> s = raw_input('--> ') --> Monty Python's Flying Circus >>> s "Monty Python's Flying Circus" If the readline module was loaded, then raw_input() will use it to provide elaborate line editing and history features. ================================= But nothing about input() in the "Python 2.3 Documentation" relevant to the question. But I probably don't yet know my way perfectly around the docs. Dick Moores From bvande at po-box.mcgill.ca Mon Sep 20 20:36:42 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Mon Sep 20 20:38:33 2004 Subject: [Tutor] What's the difference between raw_input and input? In-Reply-To: <6.1.2.0.2.20040920110448.04a70dc0@rcblue.com> References: <Pine.LNX.4.44.0409091254080.19699-100000@hkn.eecs.berkeley.edu> <1095693130.414ef34a11188@webmail.bath.ac.uk> <6.1.2.0.0.20040920095743.0471fe90@mail.mric.net> <6.1.2.0.2.20040920110448.04a70dc0@rcblue.com> Message-ID: <414F233A.5080602@po-box.mcgill.ca> Dick Moores said unto the world upon 2004-09-20 14:12: > Bob Gailer wrote at 09:00 9/20/2004: > >> At 09:12 AM 9/20/2004, W X Liu wrote: >> >>> Hi all, >>> >>> Does anybody know What's the difference between raw_input and input? >> >> >> Have you looked them up in the Python Reference? I suggest you do so. >> We like to help, but we hesitate to spend valuable time answering >> questions that can be easily looked up. If you do not understand what >> the reference says, come back and tell us what the problem is. > > > The question made me realize I didn't know the difference either. My > attempts to get the answer turned up only this description of raw_imput(): > > =============================== > raw_input( [prompt]) > > If the prompt argument is present, it is written to standard output > without a trailing newline. The function then reads a line from input, > converts it to a string (stripping a trailing newline), and returns > that. When EOF is read, EOFError is raised. Example: > > >>> s = raw_input('--> ') > --> Monty Python's Flying Circus > >>> s > "Monty Python's Flying Circus" > > If the readline module was loaded, then raw_input() will use it to > provide elaborate line editing and history features. > ================================= > > But nothing about input() in the "Python 2.3 Documentation" relevant to > the question. But I probably don't yet know my way perfectly around the > docs. > > Dick Moores > Hey Dick, W X Liu, and all, To elaborate on what Olavi Ivask said up-thread and from the docs: <docs> input( [prompt]) Equivalent to eval(raw_input(prompt)). Warning: This function is not safe from user errors! It expects a valid Python expression as input; if the input is not syntactically valid, a SyntaxError will be raised. Other exceptions may be raised if there is an error during evaluation. (On the other hand, sometimes this is exactly what you need when writing a quick script for expert use.) If the readline module was loaded, then input() will use it to provide elaborate line editing and history features. Consider using the raw_input() function for general input from users. </docs> The point is that raw_input() returns a string obtained from the user, whereas input() evaluates (as in -- more or less -- runs) a string obtained from the user assuming it is valid Python code. The two pitfalls of input() pointed out are: 1) Exceptions are raised for non-well-formed Python expressions, and, more ominously, 2) Well formed Python expressions can wreak havoc. The user could, after all, type a string consisting of the Python expressions to delete all files from C:\Windows. IMHO, you certainly wouldn't want to give a script using input() to someone with enough knowledge to be dangerous and a habit of typing stuff "to see what happens". I've yet to come across a situation where I'd want to use input(). And, even though I'm the only user of my scripts, I don't trust the 4am me enough to ask me(him?) for arbitrary code to execute. (Particularly since I now know enough to be dangerous.) This way lies tears ;-) Best to all, Brian vdB From dyoo at hkn.eecs.berkeley.edu Mon Sep 20 20:42:46 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Sep 20 20:42:52 2004 Subject: [Tutor] What's the difference between raw_input and input? In-Reply-To: <200409201819.55998.olavi@city.ee> Message-ID: <Pine.LNX.4.44.0409201135100.20801-100000@hkn.eecs.berkeley.edu> On Mon, 20 Sep 2004, Olavi Ivask wrote: > input simply gets raw input, sends it to eval, and then returns the > result. Raw_input returns input in unprocessed form. Yes. As an example: ### >>> input_result = input() 42 >>> raw_input_result = raw_input() 42 >>> input_result 42 >>> raw_input_result '42' ### Note that there are quotes around raw_input_result: that's a hint that it's actually a string, not just a number: ### >>> type(input_result) <type 'int'> >>> type(raw_input_result) <type 'str'> ### There's some kind of interpretation that happens with input(). In fact, stuff that's input()ted has access to all of Python: ### >>> input() 3 * 4 ** 5 3072 >>> raw_input() 3 * 4 ** 5 '3 * 4 ** 5' ### This is what Olavi means about eval(): It's actually "evaluating" what's being entered: it uses Python itself to interpret the expression. So input() and raw_input() are significantly different in their effects. I hardly use input() because it is a bit too powerful. When I prompt the user for something in my own programs, I usually want to control the interpretation of their answer: I don't want Python getting at it first. From csmwxl at bath.ac.uk Tue Sep 21 00:56:06 2004 From: csmwxl at bath.ac.uk (W X Liu) Date: Tue Sep 21 00:56:09 2004 Subject: [Tutor] Problem to recognize string In-Reply-To: <Pine.LNX.4.44.0409201135100.20801-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0409201135100.20801-100000@hkn.eecs.berkeley.edu> Message-ID: <1095720966.414f600613893@webmail.bath.ac.uk> Hi all, I am writing a piece of program to interact with telnet, here is the program import telnetlib import sys a=telnetlib.Telnet(host='mudlib.anarres.org',port='5000') a.read_until('Anarres II login:') b=str('acb'+chr(5)) a.write(b+ "\n") b=str('y'+chr(2)) a.write(b+ "\n") b=str('spam hi'+chr(15)) a.write(b+ "\n") if a.read_until('hi'): b=str('spam hello') a.write(b+ "\n") print a.read_all() The question is that I want to wait for somebody to say 'hi' to this program instead of program itself. So it cannot recognize who said 'hi', everytime I run it, it will print doubly the 'hi', in fact I want this progran say hi and somebody replies it with saying 'hi', then program say hello. So anyone can help me to solve this problem? Wenxin From python at bernardlebel.com Tue Sep 21 11:59:29 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Tue Sep 21 11:59:37 2004 Subject: [Tutor] Copy without overwrite? Message-ID: <003001c49fc1$b1b43ba0$0d01a8c0@studioaction.local> Hello, Is there a simple way to copy files and directory without any overwriting if the destination tree structure contains files and directory of the same name? Basically that would just add new elements to the destination structure, and leave the existing structure intact. Thanks Bernard From chandrakirti at gmail.com Tue Sep 21 12:53:05 2004 From: chandrakirti at gmail.com (Lloyd Hugh Allen) Date: Tue Sep 21 12:53:08 2004 Subject: [Tutor] Copy without overwrite? In-Reply-To: <003001c49fc1$b1b43ba0$0d01a8c0@studioaction.local> References: <003001c49fc1$b1b43ba0$0d01a8c0@studioaction.local> Message-ID: <24d253d904092103532808618f@mail.gmail.com> I don't know whether this would be considered to be cheating (thePath is a string containing the relevant path; theFile was created by opening and reading the old file): def notOverwrite(thePath, theFile): try: attempt = open(thePath) #default argument for mode is 'r', read attempt.close() #we successfully opened thePath. It exists. Leave it alone. except IOError: newFile = open(thePath, 'w') #if we're here, then we weren't allowed to read the old file #PROBABLYbecause it wasn't there. It would be worth #putting this in another try in case the file is protected or exists #but we don't have read/write permission; I'm not sure how to tell #(easily) whether it exists if we don't have read, unless we have #read access to the directory in order to manually check the dir. data = theFile.read() newFile.write(data) newFile.close() ###### also ensure that you close theFile. The try/except is very, very powerful; but like I tried to say in the comment, try to be aware of all the cases in which your statement will raise that particular exception. And don't use else, unless you enjoy spending lots of time guessing why your program is doing unpredictable (and wrong) things. I thougt that I wrote something about being totally hosed as far as applying this function within a path for which you have access permission and write permission but not read permission (a drop box), but I don't see that explicitly looking back through my message. I would only feel comfortable applying this if you have "7" permission (read/write/access) to the directory and "6" (read/write) permission to the file. On Tue, 21 Sep 2004 11:59:29 +0200, Bernard Lebel <python@bernardlebel.com> wrote: > Hello, > > Is there a simple way to copy files and directory without any overwriting if the destination tree > structure contains files and directory of the same name? Basically that would just add new elements > to the destination structure, and leave the existing structure intact. > > Thanks > Bernard > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From chandrakirti at gmail.com Tue Sep 21 12:58:25 2004 From: chandrakirti at gmail.com (Lloyd Hugh Allen) Date: Tue Sep 21 12:58:34 2004 Subject: [Tutor] Copy without overwrite? In-Reply-To: <24d253d904092103532808618f@mail.gmail.com> References: <003001c49fc1$b1b43ba0$0d01a8c0@studioaction.local> <24d253d904092103532808618f@mail.gmail.com> Message-ID: <24d253d904092103586b7000c4@mail.gmail.com> By "don't use else", what I meant was "don't use except without arguments." Sorry. See http://docs.python.org/ref/try.html and/or http://skunkweb.sourceforge.net/stmlrefer/node19.html On Tue, 21 Sep 2004 06:53:05 -0400, Lloyd Hugh Allen <chandrakirti@gmail.com> wrote: > I don't know whether this would be considered to be cheating (thePath > is a string containing the relevant path; theFile was created by > opening and reading the old file): > > def notOverwrite(thePath, theFile): > try: > attempt = open(thePath) #default argument for mode is 'r', read > attempt.close() #we successfully opened thePath. It exists. > Leave it alone. > except IOError: > newFile = open(thePath, 'w') > #if we're here, then we weren't > allowed to read the old file > #PROBABLYbecause it wasn't there. > It would be worth > #putting this in another try in > case the file is protected or exists > #but we don't have read/write > permission; I'm not sure how to tell > #(easily) whether it exists if we > don't have read, unless we have > #read access to the directory in > order to manually check the dir. > data = theFile.read() > newFile.write(data) > newFile.close() > > ###### > also ensure that you close theFile. The try/except is very, very > powerful; but like I tried to say in the comment, try to be aware of > all the cases in which your statement will raise that particular > exception. And don't use else, unless you enjoy spending lots of time > guessing why your program is doing unpredictable (and wrong) things. > > I thougt that I wrote something about being totally hosed as far as > applying this function within a path for which you have access > permission and write permission but not read permission (a drop box), > but I don't see that explicitly looking back through my message. I > would only feel comfortable applying this if you have "7" permission > (read/write/access) to the directory and "6" (read/write) permission > to the file. > > > > > On Tue, 21 Sep 2004 11:59:29 +0200, Bernard Lebel > <python@bernardlebel.com> wrote: > > Hello, > > > > Is there a simple way to copy files and directory without any overwriting if the destination tree > > structure contains files and directory of the same name? Basically that would just add new elements > > to the destination structure, and leave the existing structure intact. > > > > Thanks > > Bernard > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > > > From s4046441 at student.uq.edu.au Tue Sep 21 13:50:28 2004 From: s4046441 at student.uq.edu.au (Ms Soo Chong) Date: Tue Sep 21 13:50:33 2004 Subject: [Tutor] Help on psycopg installation Message-ID: <57c58d580c64.580c6457c58d@uq.edu.au> Hi all, I have trouble installing psycopg, kept getting errors on "missing PostgreSQL headers". Can someone please help me? Can someone please tell me specifically what one needs to copy to get the headers all together. I'm using a Redhat 8 Linux installation and a Fedora Core 2 installation. Any help is greatly appreciated. Here is the log of the install attempt: [peterj@euler psycopg-1.1.15]$ ./configure checking for python... /usr/bin/python checking python version... 2.3 checking python installation prefix... /usr checking python installation exec_prefix... /usr checking definitions in Python library makefile... done checking location of python library... $(prefix)/lib/python2.3/site-packages checking location of python shared modules... $(exec_prefix)/lib/python2.3/site-packages checking for gcc... gcc -pthread checking for C compiler default output file name... a.out checking whether the C compiler works... yes checking whether we are cross compiling... no checking for suffix of executables... checking for suffix of object files... o checking whether we are using the GNU C compiler... yes checking whether gcc -pthread accepts -g... yes checking for gcc -pthread option to accept ANSI C... none needed checking how to run the C preprocessor... gcc -pthread -E checking whether make sets $(MAKE)... yes checking for inline... inline checking PostgreSQL version... configure: error: missing PostgreSQL headers [peterj@euler psycopg-1.1.15]$ Thank you in advance. Shufen From kent_johnson at skillsoft.com Tue Sep 21 14:17:06 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Tue Sep 21 14:17:09 2004 Subject: [Tutor] Copy without overwrite? In-Reply-To: <003001c49fc1$b1b43ba0$0d01a8c0@studioaction.local> References: <003001c49fc1$b1b43ba0$0d01a8c0@studioaction.local> Message-ID: <6.1.0.6.0.20040921081525.02a02a20@mail4.skillsoft.com> shutil.copytree() is almost what you want. You could copy it (from Python/Lib/shutil.py) and check os.path.exists() before the actual copying is done. At 11:59 AM 9/21/2004 +0200, Bernard Lebel wrote: >Hello, > >Is there a simple way to copy files and directory without any overwriting >if the destination tree >structure contains files and directory of the same name? Basically that >would just add new elements >to the destination structure, and leave the existing structure intact. > > >Thanks >Bernard > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From python at bernardlebel.com Tue Sep 21 14:31:25 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Tue Sep 21 14:31:35 2004 Subject: [Tutor] Copy without overwrite? References: <003001c49fc1$b1b43ba0$0d01a8c0@studioaction.local> <6.1.0.6.0.20040921081525.02a02a20@mail4.skillsoft.com> Message-ID: <004501c49fd6$eadf0a80$0d01a8c0@studioaction.local> Hi Kent, Unless I'm missing something... os.copytree() expects the destination directory to not exists. It it exists, the function aborts instead of visiting the said directory and go further down the tree. Plus, I don't think it handles individual files (files are copied, but no determining of existence is performed). Let me know if I'm missing something. Thanks Bernard ----- Original Message ----- From: "Kent Johnson" <kent_johnson@skillsoft.com> To: <tutor@python.org> Sent: Tuesday, September 21, 2004 2:17 PM Subject: Re: [Tutor] Copy without overwrite? > shutil.copytree() is almost what you want. You could copy it (from > Python/Lib/shutil.py) and check os.path.exists() before the actual copying > is done. > > At 11:59 AM 9/21/2004 +0200, Bernard Lebel wrote: > >Hello, > > > >Is there a simple way to copy files and directory without any overwriting > >if the destination tree > >structure contains files and directory of the same name? Basically that > >would just add new elements > >to the destination structure, and leave the existing structure intact. > > > > > >Thanks > >Bernard > > > > > >_______________________________________________ > >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 kent_johnson at skillsoft.com Tue Sep 21 14:59:12 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Tue Sep 21 14:59:23 2004 Subject: [Tutor] Copy without overwrite? In-Reply-To: <004501c49fd6$eadf0a80$0d01a8c0@studioaction.local> References: <003001c49fc1$b1b43ba0$0d01a8c0@studioaction.local> <6.1.0.6.0.20040921081525.02a02a20@mail4.skillsoft.com> <004501c49fd6$eadf0a80$0d01a8c0@studioaction.local> Message-ID: <6.1.0.6.0.20040921085540.028a19f8@mail4.skillsoft.com> You are right about copytree(). But you can open shutil.py, copy the method to your own code, and modify it easily to do what you want. (Just add a test of os.path.exists().) The doc comment even hints that that is the expected usage :-) Looking at copytree() I'm actually not sure what keeps it from working if the directory already exists; the docs for os.mkdir() don't say it will fail if the dir exists. Kent At 02:31 PM 9/21/2004 +0200, Bernard Lebel wrote: >Hi Kent, > >Unless I'm missing something... os.copytree() expects the destination >directory to not exists. It it >exists, the function aborts instead of visiting the said directory and go >further down the tree. >Plus, I don't think it handles individual files (files are copied, but no >determining of existence >is performed). > >Let me know if I'm missing something. > > >Thanks >Bernard > >----- Original Message ----- >From: "Kent Johnson" <kent_johnson@skillsoft.com> >To: <tutor@python.org> >Sent: Tuesday, September 21, 2004 2:17 PM >Subject: Re: [Tutor] Copy without overwrite? > > > > shutil.copytree() is almost what you want. You could copy it (from > > Python/Lib/shutil.py) and check os.path.exists() before the actual copying > > is done. > > > > At 11:59 AM 9/21/2004 +0200, Bernard Lebel wrote: > > >Hello, > > > > > >Is there a simple way to copy files and directory without any overwriting > > >if the destination tree > > >structure contains files and directory of the same name? Basically that > > >would just add new elements > > >to the destination structure, and leave the existing structure intact. > > > > > > > > >Thanks > > >Bernard > > > > > > > > >_______________________________________________ > > >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 johan at accesstel.co.za Tue Sep 21 15:21:33 2004 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Tue Sep 21 15:22:33 2004 Subject: [Tutor] Python in South Africa? In-Reply-To: <6.1.0.6.0.20040921085540.028a19f8@mail4.skillsoft.com> References: <003001c49fc1$b1b43ba0$0d01a8c0@studioaction.local> <6.1.0.6.0.20040921081525.02a02a20@mail4.skillsoft.com> <004501c49fd6$eadf0a80$0d01a8c0@studioaction.local> <6.1.0.6.0.20040921085540.028a19f8@mail4.skillsoft.com> Message-ID: <1095772892.4229.9.camel@linux.site> Does anybody in this mailing list stay in south Africa? I want to know if there is a place that presents python training. Thanks Johan -- This message has been scanned for viruses and dangerous content by Azitech, and is believed to be clean. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040921/dd489cb3/attachment.html From dactex at swbell.net Tue Sep 21 18:07:10 2004 From: dactex at swbell.net (David Carter) Date: Tue Sep 21 18:07:15 2004 Subject: [Tutor] Houston Python Meetup group Message-ID: <000001c49ff5$0db86a10$2800005a@gobot> Please pardon the slightly off-topic-type content. I would like to let those of you in the Houston, TX area know of the Houston Python Meetup Group. When: Tuesday, Oct 19, 2004 @ 7:00 PM For location information, join the group at the meetup.com website: http://python.meetup.com/14 David Carter From s4046441 at student.uq.edu.au Tue Sep 21 20:37:05 2004 From: s4046441 at student.uq.edu.au (Ms Soo Chong) Date: Tue Sep 21 20:37:12 2004 Subject: [Tutor] Calling for help...@ Brisbane Message-ID: <587efe5879be.5879be587efe@uq.edu.au> Hi all, Please pardon the off topic type content. I'm looking for some assistance from python programmers located at Brisbane, Australia. Because I'm a newbie to programming and required to finish a program in a short time, I wonder if there is any kind soul around that can meet me up ONCE and clarify some of my doubts. (I really need some face to face explanation in order to move on) I did check on the python meet up group but there seems to be no response for the upcoming event so I decided to try to post this message out. Sorry if it sounds ridi but thats what I really need. Thank you in advance. Shufen From missive at hotmail.com Tue Sep 21 23:05:20 2004 From: missive at hotmail.com (Lee Harr) Date: Tue Sep 21 23:05:29 2004 Subject: [Tutor] Re: Copy without overwrite? Message-ID: <BAY2-F18Dh9vXsFFsAi000567b8@hotmail.com> >Is there a simple way to copy files and directory without >any overwriting if the destination tree >structure contains files and directory of >the same name? Basically that would just add new elemen >to the destination structure, and leave the >existing structure intact. I would probably use rsync. That has both -u, --update update only (don't overwrite newer files) and --ignore-existing ignore files that already exist on receiver _________________________________________________________________ Help STOP SPAM with the new MSN 8 and get 2 months FREE* http://join.msn.com/?page=features/junkmail From missive at hotmail.com Tue Sep 21 23:09:47 2004 From: missive at hotmail.com (Lee Harr) Date: Tue Sep 21 23:27:19 2004 Subject: [Tutor] Re: Help on psycopg installation Message-ID: <BAY2-F15zF5ldfZWjSe00000a14@hotmail.com> >I have trouble installing psycopg, kept getting errors on "missing >PostgreSQL headers". >Can someone please help me? Can someone please tell me specifically what >one needs to >copy to get the headers all together. I'm using a Redhat 8 Linux >installation >and a Fedora Core 2 installation. If you browse here: http://initd.org/software/initd/psycopg There is a section that says "Fedora RPMs": http://www.bluetwanger.de/~mbertheau/psycopg/fc2/ Have you tried that way yet? If you need to build it from scratch, you need to be sure that you have the full postgres installation (including the headers... ) That is probably in a separate install. _________________________________________________________________ Add photos to your messages with MSN 8. Get 2 months FREE*. http://join.msn.com/?page=features/featuredemail From jeff at ccvcorp.com Tue Sep 21 23:46:23 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue Sep 21 23:44:25 2004 Subject: [Tutor] Copy without overwrite? In-Reply-To: <6.1.0.6.0.20040921085540.028a19f8@mail4.skillsoft.com> References: <003001c49fc1$b1b43ba0$0d01a8c0@studioaction.local> <6.1.0.6.0.20040921081525.02a02a20@mail4.skillsoft.com> <004501c49fd6$eadf0a80$0d01a8c0@studioaction.local> <6.1.0.6.0.20040921085540.028a19f8@mail4.skillsoft.com> Message-ID: <4150A12F.6000802@ccvcorp.com> Kent Johnson wrote: > Looking at copytree() I'm actually not sure what keeps it from working > if the directory already exists; the docs for os.mkdir() don't say it > will fail if the dir exists. I'm not sure what the docs say, but... [.... jeff]$ ls -ld example drwxrwxr-x 2 jeff jeff 4096 Sep 21 14:45 example [.... jeff]$ python 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. >>> import os >>> os.mkdir('example') Traceback (most recent call last): File "<stdin>", line 1, in ? OSError: [Errno 17] File exists: 'example' >>> Jeff Shannon Technician/Programmer Credit International From jonathan.hayward at pobox.com Wed Sep 22 04:29:20 2004 From: jonathan.hayward at pobox.com (Jonathan Hayward) Date: Wed Sep 22 04:30:51 2004 Subject: [Tutor] Willing to look at code? Message-ID: <4150E380.20405@pobox.com> I have a bug that I'm trying to track down and was wondering if someone would look at it. I have a combination search engine/weblog that has working keyword searches, and I'm trying to add searches for quotations. What I'm trying to do is let the boolean parser know that there's one more primitive besides word, 'and', 'or', and 'not': 'quotation', which is calculated as follows: 1: Break the quotation into tokens. 2: Calculate a relevance score which is 0 if one or more token is absent. (An optimization.) 3: If the relevance score is positive, check if the sequence of tokens is found in the document. The matches are the ones which pass steps 2 and 3. The problem I'm having is that a quotation search matches everything. Any takers? -- ++ Jonathan Hayward, jonathan.hayward@pobox.com ** To see an award-winning website with stories, essays, artwork, ** games, and a four-dimensional maze, why not visit my home page? ** All of this is waiting for you at http://JonathansCorner.com From isrgish at fastem.com Wed Sep 22 06:09:21 2004 From: isrgish at fastem.com (Isr Gish) Date: Wed Sep 22 06:09:41 2004 Subject: [Tutor] *.rar decompress Message-ID: <20040922040939.026911E4006@bag.python.org> Hi, I'm looking to decompress *.rar files. Does anyone know of a way to do that in python. Thanks, All the best, Isr From dyoo at hkn.eecs.berkeley.edu Wed Sep 22 09:53:06 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Sep 22 09:53:14 2004 Subject: [Tutor] Willing to look at code? In-Reply-To: <4150E380.20405@pobox.com> Message-ID: <Pine.LNX.4.44.0409220051270.8223-100000@hkn.eecs.berkeley.edu> On Tue, 21 Sep 2004, Jonathan Hayward wrote: > I have a bug that I'm trying to track down and was wondering if someone > would look at it. Ok, point us to code; one of us is probably curious to look at it. *grin* If it's large, just link it up on a web page. If it's fairly short, you can post it on the Tutor list. From dyoo at hkn.eecs.berkeley.edu Wed Sep 22 10:06:08 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Sep 22 10:06:19 2004 Subject: [Tutor] *.rar decompress In-Reply-To: <20040922040939.026911E4006@bag.python.org> Message-ID: <Pine.LNX.4.44.0409220053380.8223-100000@hkn.eecs.berkeley.edu> On Wed, 22 Sep 2004, Isr Gish wrote: > I'm looking to decompress *.rar files. > Does anyone know of a way to do that in python. Hi Isr, I googled around, and found a third-party library for dealing with RAR files: http://www.averdevelopment.com/python/UnRAR.html Oh, it's Jimmy's module! That's cool! He's a regular at the Bay Area Python Interest Group (http://baypiggies.net). Let me just CC him so he knows that I'm plugging his module. *grin* RAR appears to be a compression format used on the Windows platform, so, unfortunately, I can't test his module very easily. Does anyone else have experience with it? From dyoo at hkn.eecs.berkeley.edu Wed Sep 22 10:18:35 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Sep 22 10:18:47 2004 Subject: [Tutor] Python in South Africa? In-Reply-To: <1095772892.4229.9.camel@linux.site> Message-ID: <Pine.LNX.4.44.0409220111000.8223-100000@hkn.eecs.berkeley.edu> On Tue, 21 Sep 2004, Johan Geldenhuys wrote: > Does anybody in this mailing list stay in south Africa? I want to know > if there is a place that presents python training. Hi Johan, David Carter just mentioned a website that appears to be keeping a "Meetup" group database of Python User Groups. There's one in Pretoria: http://python.meetup.com/106/ I'm not sure how close that is to you, but it's a start: you might be able to contact folks there. I'd also recommend asking on the comp.lang.python newsgroup, which has a large readership. If you do find a good Python group in South Africa, please try to get that group listed on the "User Groups" page on Python.org: http://python.org/community/user-groups.html to make it easier for people to find. Good luck to you. From dyoo at hkn.eecs.berkeley.edu Wed Sep 22 10:33:27 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Sep 22 10:33:32 2004 Subject: [Tutor] Calling for help...@ Brisbane In-Reply-To: <587efe5879be.5879be587efe@uq.edu.au> Message-ID: <Pine.LNX.4.44.0409220118420.8223-100000@hkn.eecs.berkeley.edu> On Wed, 22 Sep 2004, Ms Soo Chong wrote: > I'm looking for some assistance from python programmers located at > Brisbane, Australia. [text cut] (Gosh, we seem to be getting a streak of similar messages today!) There are Python programmers around there in Brisbane. I just don't know if they desire consultation fees. *grin* Your best bet is probably to contact the technically-oriented user groups in Australia. According to: http://python.org/community/user-groups.html there's a Python Interest Group in Sydney: http://pig.slug.org.au/ .... hmmm... but that's a bit far from Brisbane. Ok... there is a Brisbane Red Hat group that might host programmers: http://redhat.meetup.com/12/ So it can't hurt to ask if any of the folks there do Python programming. You should also try the comp.lang.python newsgroup and see if there are folks who are local to you. Your local university might also be a possible place to ask for help. That being said, please feel free to ask questions here on Tutor. Doing a face-to-face is obviously the nice way of learning this stuff, but in a pinch, you can still ask folks on this list. From johan at accesstel.co.za Wed Sep 22 10:56:30 2004 From: johan at accesstel.co.za (Johan Geldenhuys) Date: Wed Sep 22 10:57:30 2004 Subject: [Tutor] basic Web page design Message-ID: <1095843390.4312.15.camel@linux.site> Hi, I want to start with the basics of writing a simple webpage in python. Where to I start? I have done any webpage programming before. Thanks -- Johan -- This message has been scanned for viruses and dangerous content by Azitech, and is believed to be clean. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040922/8e1a6ba9/attachment.html From python at bernardlebel.com Wed Sep 22 11:05:19 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Wed Sep 22 11:05:36 2004 Subject: [Tutor] Re: Copy without overwrite? References: <BAY2-F18Dh9vXsFFsAi000567b8@hotmail.com> Message-ID: <005d01c4a083$4ab607e0$0d01a8c0@studioaction.local> Thanks to everyone! Attached is my final script, in txt format. Bernard begin 666 copydir.txt M(R M+2TM+2TM+2TM+2TM+2TM+2TM+2TM+2TM+2TM+2TM+2TM+2TM+2TM+2TM M+2TM+2TM+2TM+2T-"B,@8V]P>61I<@T*(PT*(R!"97)N87)D($QE8F5L#0HC M(%-E<'1E;6)E<B R,# T#0HC#0HC($-O<&EE<R!O;F4@9&ER96-T;W)Y("AA M;F0@86QL(&ET<R!C;VYT96YT*2!T;R!A;F]T:&5R( T*(R!D:7)E8W1O<GD@ M;F]N+61E<W1R=6-T:79E;'D@*&5X:7-T:6YG(&1I<F5C=&]R:65S#0HC(&%N M9"!F:6QE<R!A<F4@;F]T(&]V97)W<FET=&5N*2X-"B,@5&AI<R!I<R!A(&QI M;F5A<B!T>7!E(&]F(&-O<'D@*&-O<&EE<R!!('1O($(@:6X@82!L;V]P*2P- M"B,@<V\@;F]T(&%S('!E<F9O<FUA;G0@87,@=VET:"!A('!A<F%L;&5L(&-O M<'D@9G5N8W1I;VXN#0HC(%-O=7)C92!A;F0@9&5S=&EN871I;VX@87)E('-P M96-I9FEE9"!B>2!U<V5R('9I82!R87=?:6YP=70N#0HC#0HC(%5S86=E.@T* M(R!%;G1E<B!S;W5R8V4@<&%T:"X@5&AI<R!I<R!T:&4@9&ER96-T;W)Y('EO M=2!W:7-H('1O(&-O<'DN#0HC($5N=&5R(&1E<W1I;F%T:6]N('!A=&@N(%1H M:7,@:7,@=VAE<F4@=&AE(&1I<F5C=&]R>2!W:6QL(&)E(&-O<&EE9"X-"B,- M"B,@+2TM+2TM+2TM+2TM+2TM+2TM+2TM+2TM+2TM+2TM+2TM+2TM+2TM+2TM M+2TM+2TM+2TM+2T-"B,@26UP;W)T(&)L;V-K#0H-"FEM<&]R="!O<PT*:6UP M;W)T('-H=71I;"!A<R!S#0H-"B,@+2TM+2TM+2TM+2TM+2TM+2TM+2TM+2TM M+2TM+2TM+2TM+2TM+2TM+2TM+2TM+2TM+2TM+2T-"B,@1G5N8W1I;VYS(&)L M;V-K#0H-"@T*9&5F('-O9G1#;W!Y*"!S<F,L(&1S=" I.@T*#0H)(B(B#0H) M<W)C(&%N9"!D<W0@87)E(&%L=V%Y<R!A(&1I<F5C=&]R>2X-"@E0<F]G<F5S M<R!M97-S86=E<R H0V]P>6EN9RXN+BP@1$].12P@1D%)3$5$*2!A<F4@;F]T M('5S960@=VET:"!F:6QE<RP-"@ES:6YC92!I="!C86X@<VQO=R!T:&4@97AE M8W5T:6]N('%U:71E(&$@8FET+@T*"0T*"51H92!S;V9T0V]P>2!F=6YC=&EO M;B!I<R!A;&UO<W0@97AA8W1L>2!T:&4@8V]P>71R964@9G5N8W1I;VX-"@EF M<F]M('-H=71I;"YP>2P@=VET:"!O;FQY('-L:6=H="!M;V1I9FEC871I;VYS M+@T*"51H86YK<R!T;R!+96YT($IO:&YS;VX@9F]R('1H92!S=6=G97-T:6]N M+@T*"2(B(@T*"0T*"2,@1V5T(&YA;65S(&]F(&5L96UE;G1S(&EN('-O=7)C M92!D:7)E8W1O<GD-"@EA4W)C1&ER16QE;7,@/2!O<RYL:7-T9&ER*"!S<F,@ M*0T*"0T*"2,@0W)E871E(&5M<'1Y(&QI<W0@=&\@<W1O<F4@97)R;W)S#0H) M97)R;W)S(#T@6UT-"@D-"@D-"@DC($ET97)A=&4@;&ES="!O9B!E;&5M96YT M<R!F<F]M('-O=7)C92!D:7(-"@EF;W(@<U-R8T5L96T@:6X@85-R8T1I<D5L M96US.@T*#0H)"2,@2F]I;B!E;&5M96YT(&YA;64@=&\@9&5S=&EN871I;VX@ M86YD('-O=7)C92 -"@D)<W)C;F%M92 ](&]S+G!A=&@N:F]I;B@@<W)C+"!S M4W)C16QE;2 I#0H)"61S=&YA;64@/2!O<RYP871H+FIO:6XH(&1S="P@<U-R M8T5L96T@*0T*"0D-"@D-"@D)(R!#:&5C:R!I9B!S;W5R8V4@96QE;65N="!I M<R!A(&1I<F5C=&]R>0T*"0EI9B!O<RYP871H+FES9&ER*"!S<F-N86UE("D@ M/3T@5')U93H-"@D)"0T*"0D)(R!#:&5C:R!I9B!D97-T:6YA=&EO;B!E>&ES M=',-"@D)"6EF(&]S+G!A=&@N97AI<W1S*"!D<W1N86UE("DZ#0H)"0D)<')I M;G0@)T9O=6YD(&1E<W1I;F%T:6]N(&1I<F5C=&]R>2 B)7,B('=I=&@@<V%M M92!N86UE(&%S('-O=7)C92P@86YA;'EZ:6YG('1H870@9&ER96-T;W)Y+B<@ M)2 H(&1S=&YA;64@*0T*"0D)"2,@0T%,3"!&54Y#5$E/3B!!1T%)3BP@0E54 M($-(04Y'12!$25)%0U1/4DE%4PT*"0D)"7-O9G1#;W!Y*"!S<F-N86UE+"!D M<W1N86UE("D-"@D)"0D-"@D)"2,@1&5S=&EN871I;VX@9&ER96-T;W)Y(&1O M97,@;F]T(&5X:7-T<PT*"0D)96QS93H-"@D)"0EP<FEN=" G0V]P>6EN9R E M<RXN+B<@)2 H('-R8VYA;64@*0T*"0D)"71R>3H-"@D)"0D)<RYC;W!Y=')E M92@@<W)C;F%M92P@9'-T;F%M92 I#0H)"0D)"7!R:6YT("=$3TY%)PT*"0D) M"65X8V5P=" H24]%<G)O<BP@;W,N97)R;W(I+"!W:'DZ#0H)"0D)"7!R:6YT M("=&04E,140G#0H)"0D)"65R<F]R<RYA<'!E;F0H("@@<W)C;F%M92P@9'-T M;F%M92P@=VAY("D@*0T*#0H)"0T*"0DC(%-O=7)C92!E;&5M96YT(&ES(&$@ M9FEL90T*"0EE;'-E.@T*"0D)(R!#:&5C:R!I9B!D97-T:6YA=&EO;B!F:6QE M(&5X:7-T<PT*"0D):68@;W,N<&%T:"YE>&ES=',H(&1S=&YA;64@*3H-"@D) M"0EP87-S#0H)"0DC($1E<W1I;F%T:6]N(&9I;&4@9&]E<R!N;W0@97AI<W1S M+"!C;W!Y('-O=7)C92!F:6QE#0H)"0EE;'-E.@T*"0D)"71R>3H-"@D)"0D) M<RYC;W!Y*"!S<F-N86UE+"!D<W0@*0T*"0D)"65X8V5P=" H24]%<G)O<BP@ M;W,N97)R;W(I+"!W:'DZ#0H)"0D)"65R<F]R<RYA<'!E;F0H("@@<W)C;F%M M92P@9'-T;F%M92P@=VAY("D@*0T*"0T*"2,@0VAE8VL@:68@=&AE(&9U;F-T M:6]N(&5N8V]U;G1E<F5D(&5R<F]R<R!D=7)I;F<@=&AE(&QO;W L(&EF('-O M+"!P<FEN="!T:&5M#0H):68@97)R;W)S.@T*"0ER86ES92!S+D5R<F]R+"!E M<G)O<G,-"@D-"@D-"@T*(R M+2TM+2TM+2TM+2TM+2TM+2TM+2TM+2TM+2TM M+2TM+2TM+2TM+2TM+2TM+2TM+2TM+2TM+0T*(R!38W)I<'0@8FQO8VL-"@T* M#0HC($=E="!U<V5R(&EN<'5T#0IS<F,@/2!R87=?:6YP=70H(")%;G1E<B!S M;W5R8V4@<&%T:"(@*0T*9'-T(#T@<F%W7VEN<'5T*" B16YT97(@9&5S=&EN M871I;VX@<&%T:"(@*0T*#0H-"B,@5F5R:69Y('-O=7)C92!P871H#0II9B!N M;W0@;W,N<&%T:"YE>&ES=',H('-R8R I.@T*"7!R:6YT("=3;W5R8V4@(B5S M(B!P871H(&YO="!V86QI9"XG("4@*"!S<F,@*0T*#0HC(%-O=7)C92!P871H M('9A;&ED+"!V97)I9GD@=&%R9V5T('!A=&@-"F5L:68@;F]T(&]S+G!A=&@N M97AI<W1S*"!D<W0@*3H-"@EP<FEN=" G1&5S=&EN871I;VX@(B5S(B!P871H M(&YO="!V86QI9"XG("4@*"!D<W0@*0T*#0HC($)O=&@@<&%T:',@=F%L:60- M"F5L<V4Z#0H)85-O=7)C941I<B ](&]S+G!A=&@N<W!L:70H('-R8R I#0H) M<U-O=7)C941I<B ](&%3;W5R8V5$:7);+3%=#0H)#0H)9'-T(#T@9'-T("L@ M)UQ<)R K('-3;W5R8V5$:7(-"@D-"@EI9B!N;W0@;W,N<&%T:"YE>&ES=',H M(&1S=" I.@T*"0D-"@D)(R!$97-T:6YA=&EO;B!D;V5S;B=T(&5X:7-T<RP@ M=V4@8V%N('-A9F5L>2!C;W!Y('1H92!E;G1I<F4@<V]U<F-E#0H)"71R>3H- M"@D)"7!R:6YT("=3=&%R=&EN9R!C;W!Y+BXN)PT*"0D)<RYC;W!Y=')E92@@ M<W)C+"!D<W0@*0T*"0D)<')I;G0@)T1/3D4G#0H)"0D-"@D)97AC97!T.@T* M"0D)<')I;G0@)T9!24Q%1"<-"@D)"0T*"65L<V4Z#0H)"0T*"0DC($-R87 L M('1H92!D97-T:6YA=&EO;B!D:7)E8W1O<GD@97AI<W1S+B!792!H879E('1O M(&%N86QY>F4@=&AE(&5N=&ER92!S;W5R8V4@86YD(&1E<W1I;F%T:6]N#0H) M"2,@<W1R=6-T=7)E('1O(&9I;F0@;W5T('=H870@9FEL92!A;F0@9&ER96-T M;W)Y(&5X<VET<RP@<V\@=V4@9&\@;F]T(&]V97)W<FET92!A;GET:&EN9PT* M"0D-"@D)(R!#86QL(&9U;F-T:6]N#0H)"7-O9G1#;W!Y*"!S<F,L(&1S=" I (#0H-"@T*#0H` ` end From olavi at city.ee Wed Sep 22 11:25:13 2004 From: olavi at city.ee (Olavi Ivask) Date: Wed Sep 22 11:25:21 2004 Subject: [Tutor] basic Web page design In-Reply-To: <1095843390.4312.15.camel@linux.site> References: <1095843390.4312.15.camel@linux.site> Message-ID: <200409221225.13949.olavi@city.ee> Hello Johan, You should start with reading web programming tutorials, for example: http://www.python.org/topics/web/ http://www.w3j.com/6/s3.vanrossum.html Olavi Ivask On Wednesday 22 September 2004 11:56, Johan Geldenhuys wrote: > Hi, > I want to start with the basics of writing a simple webpage in python. > Where to I start? I have done any webpage programming before. > > Thanks > -- > Johan From kent_johnson at skillsoft.com Wed Sep 22 12:11:41 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Wed Sep 22 12:11:48 2004 Subject: [Tutor] Re: Copy without overwrite? In-Reply-To: <005d01c4a083$4ab607e0$0d01a8c0@studioaction.local> References: <BAY2-F18Dh9vXsFFsAi000567b8@hotmail.com> <005d01c4a083$4ab607e0$0d01a8c0@studioaction.local> Message-ID: <6.1.0.6.0.20040922055943.02a0da50@mail4.skillsoft.com> Hi Bernard, Congratulations on getting this working! Of course I have a couple of suggestions :-) - I notice you call shutil.copytree() if the destination directory is not there. This is fine but not necessary - you could just create the directory and call softcopy() again. That would make the program self-contained and maybe easier to understand - it wouldn't have the two different paths for recursion. OTOH you could consider the call to copytree() an optimization, since at that point you know you don't have to check for existence of the destination files anymore. Either way is fine, really. - If you do call copytree() you should change your exception handler. Just like softcopy(), copytree() catches IOError and wraps them in a shutil.Error. The data in the Error is a list of failures. So for the call to copytree(), instead of (or in addition to) catching IOError and creating a new error list entry, you should catch Error and extend your list with the list the Error contains: try: s.copytree( srcname, dstname ) print 'DONE' except os.error, why: print 'FAILED' errors.append( ( srcname, dstname, why ) ) except (s.Error), why: print 'FAILED' errors.extend( why ) Kent At 11:05 AM 9/22/2004 +0200, Bernard Lebel wrote: >Thanks to everyone! > >Attached is my final script, in txt format. > > >Bernard > > > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From python at bernardlebel.com Wed Sep 22 13:20:26 2004 From: python at bernardlebel.com (Bernard Lebel) Date: Wed Sep 22 13:20:41 2004 Subject: [Tutor] Re: Copy without overwrite? References: <BAY2-F18Dh9vXsFFsAi000567b8@hotmail.com><005d01c4a083$4ab607e0$0d01a8c0@studioaction.local> <6.1.0.6.0.20040922055943.02a0da50@mail4.skillsoft.com> Message-ID: <002301c4a096$2e541f20$0d01a8c0@studioaction.local> Hi Kent, I implemented your suggestions. I have one question about the error handling thing. Do you keep at the end of the loop the raise statement? if errors: raise s.Error, errors Thanks Bernard ----- Original Message ----- From: "Kent Johnson" <kent_johnson@skillsoft.com> To: <tutor@python.org> Sent: Wednesday, September 22, 2004 12:11 PM Subject: Re: [Tutor] Re: Copy without overwrite? > Hi Bernard, > > Congratulations on getting this working! Of course I have a couple of > suggestions :-) > > - I notice you call shutil.copytree() if the destination directory is not > there. This is fine but not necessary - you could just create the directory > and call softcopy() again. That would make the program self-contained and > maybe easier to understand - it wouldn't have the two different paths for > recursion. OTOH you could consider the call to copytree() an optimization, > since at that point you know you don't have to check for existence of the > destination files anymore. Either way is fine, really. > > - If you do call copytree() you should change your exception handler. Just > like softcopy(), copytree() catches IOError and wraps them in a > shutil.Error. The data in the Error is a list of failures. So for the call > to copytree(), instead of (or in addition to) catching IOError and creating > a new error list entry, you should catch Error and extend your list with > the list the Error contains: > > try: > s.copytree( srcname, dstname ) > print 'DONE' > except os.error, why: > print 'FAILED' > errors.append( ( srcname, dstname, > why ) ) > except (s.Error), why: > print 'FAILED' > errors.extend( why ) > > Kent > > At 11:05 AM 9/22/2004 +0200, Bernard Lebel wrote: > >Thanks to everyone! > > > >Attached is my final script, in txt format. > > > > > >Bernard > > > > > > > > > >_______________________________________________ > >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 kent_johnson at skillsoft.com Wed Sep 22 13:55:17 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Wed Sep 22 13:55:33 2004 Subject: [Tutor] Re: Copy without overwrite? In-Reply-To: <002301c4a096$2e541f20$0d01a8c0@studioaction.local> References: <BAY2-F18Dh9vXsFFsAi000567b8@hotmail.com> <005d01c4a083$4ab607e0$0d01a8c0@studioaction.local> <6.1.0.6.0.20040922055943.02a0da50@mail4.skillsoft.com> <002301c4a096$2e541f20$0d01a8c0@studioaction.local> Message-ID: <6.1.0.6.0.20040922075307.028bfc18@mail4.skillsoft.com> Yes, that is the way the errors are reported to the caller. In your program, you don't have an exception handler for the call to softcopy() at the top level so the interpreter will catch the Error and print the details. Kent At 01:20 PM 9/22/2004 +0200, Bernard Lebel wrote: >Hi Kent, I implemented your suggestions. I have one question about the >error handling thing. >Do you keep at the end of the loop the raise statement? > >if errors: > raise s.Error, errors > > >Thanks >Bernard > >----- Original Message ----- >From: "Kent Johnson" <kent_johnson@skillsoft.com> >To: <tutor@python.org> >Sent: Wednesday, September 22, 2004 12:11 PM >Subject: Re: [Tutor] Re: Copy without overwrite? > > > > Hi Bernard, > > > > Congratulations on getting this working! Of course I have a couple of > > suggestions :-) > > > > - I notice you call shutil.copytree() if the destination directory is not > > there. This is fine but not necessary - you could just create the directory > > and call softcopy() again. That would make the program self-contained and > > maybe easier to understand - it wouldn't have the two different paths for > > recursion. OTOH you could consider the call to copytree() an optimization, > > since at that point you know you don't have to check for existence of the > > destination files anymore. Either way is fine, really. > > > > - If you do call copytree() you should change your exception handler. Just > > like softcopy(), copytree() catches IOError and wraps them in a > > shutil.Error. The data in the Error is a list of failures. So for the call > > to copytree(), instead of (or in addition to) catching IOError and creating > > a new error list entry, you should catch Error and extend your list with > > the list the Error contains: > > > > try: > > s.copytree( srcname, dstname ) > > print 'DONE' > > except os.error, why: > > print 'FAILED' > > errors.append( ( srcname, dstname, > > why ) ) > > except (s.Error), why: > > print 'FAILED' > > errors.extend( why ) > > > > Kent > > > > At 11:05 AM 9/22/2004 +0200, Bernard Lebel wrote: > > >Thanks to everyone! > > > > > >Attached is my final script, in txt format. > > > > > > > > >Bernard > > > > > > > > > > > > > > >_______________________________________________ > > >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 zsolt.botykai at online.hu Wed Sep 22 16:18:49 2004 From: zsolt.botykai at online.hu (Botykai Zsolt) Date: Wed Sep 22 16:18:56 2004 Subject: [Tutor] regexp help Message-ID: <200409221618.50482.zsolt.botykai@online.hu> Hi for everyone, just dived in to regexp, and have some problem, wrote this script to work as a pipe for multiline text input. My problem is - how to cut out all the empty lines (empty line: content only space or tab) from f_body? import sys import re data = sys.stdin.read() ... match_body = re.compile( r"""--==--==--==--==--.(.+).--==--==--==--==--""", re.DOTALL | re.MULTILINE | re.VERBOSE) f_body = match_body.search(data) f_body = match_body.search(data) o_output = f_body.group(0) ... sys.stdout.write(o_output) Thx for any help, Zsoltik@ from Hungary (sorry about the disclaimer...) -------------------------------------------------------------------------- Opinions, conclusions and other information in this message that do not relate to the official business of Online Business Technologies Corp. shall be understood as neither given nor endorsed by it. In such cases Online Business Technologies Corp. will not bear the responsibility of consequences. If you have received this communication in error, please notify the system manager immediately by responding to this email and then delete it from your system. A levelben foglalt, nem az Online Rt. hivatalos uzletmenetevel kapcsolatos velemenyek vagy mas informaciok vonatkozasaban az Online Rt. nem vallal felelosseget. Amennyiben a level valamely hiba folytan jutott Onhoz, kerjuk, hogy valaszlevelben azonnal ertesitse a rendszer uzemeltetojet, majd torolje ki a levelet rendszerebol! From olavi at city.ee Wed Sep 22 17:16:33 2004 From: olavi at city.ee (Olavi Ivask) Date: Wed Sep 22 17:16:37 2004 Subject: [Tutor] Reload my modules dir Message-ID: <200409221816.33257.olavi@city.ee> Hello i made a folder(pythonscripts), where i hold my python scripts. Now, i added this dir to modules path list >>>import sys >>>sys.path.append('/home/olavi/pythonscripts') After closing python, my script path dissapears, in sys.path list. How must i add this path, that every time i open python, it reloads that dir automatically? i use debian, kernel2.6 and python 2.3.4 Thanks for your response Olavi Ivask From isrgish at fastem.com Wed Sep 22 18:18:31 2004 From: isrgish at fastem.com (Isr Gish) Date: Wed Sep 22 18:20:12 2004 Subject: [Tutor] *.rar decompress Message-ID: <20040922162010.C8B811E4006@bag.python.org> Thanks Jimmy and Danny, I'll take a look at this. All the best, Isr -----Original Message----- >From: "Jimmy Retzlaff"<jimmy@retzlaff.com> >Sent: 9/22/04 6:57:30 AM >To: "Isr Gish"<isrgish@fastem.com> >Cc: "Tutor"<tutor@python.org>, "Danny Yoo"<dyoo@hkn.eecs.berkeley.edu> >Subject: RE: [Tutor] *.rar decompress >Danny Yoo wrote: >> On Wed, 22 Sep 2004, Isr Gish wrote: >> >> > I'm looking to decompress *.rar files. >> > Does anyone know of a way to do that in python. >> >> I googled around, and found a third-party library for dealing with RAR >> files: >> >> http://www.averdevelopment.com/python/UnRAR.html >> >> Oh, it's Jimmy's module! That's cool! He's a regular at the Bay Area >> Python Interest Group (http://baypiggies.net). Let me just CC him so >he >> knows that I'm plugging his module. *grin* > >Yep, that's me! I'm not on the Tutor list so it's nice that you copied >me. > >> RAR appears to be a compression format used on the Windows platform, >so, >> unfortunately, I can't test his module very easily. Does anyone else >have >> experience with it? > >I have a little experience with it. :) I've been using it on and off >for almost 2 years (I used it for quite a while as it evolved before I >released it). I've also corresponded with a few others who are using it >successfully. If you try it and have any problems, please let me know. >If you don't have any problems using it, I enjoy hearing about that too. >;) > >There are also freely available implementations of command line unrar >utilities that you could call from Python. Many platforms are covered by >the author of RAR and contributors at: > >http://www.rarlab.com/rar_add.htm > >When I have some time, I plan to make another release of pyUnRAR - >hopefully in the next couple of weeks. I haven't heard of any bugs since >I released 0.1 over a year ago so I'll probably call it 1.0. The only >change planned in the next release is the ability to access the >dates/times of files within the archive which I added at the request of >a user. > >Jimmy > From kent_johnson at skillsoft.com Wed Sep 22 18:55:34 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Wed Sep 22 18:55:39 2004 Subject: [Tutor] Reload my modules dir In-Reply-To: <200409221816.33257.olavi@city.ee> References: <200409221816.33257.olavi@city.ee> Message-ID: <6.1.0.6.0.20040922125233.0288c670@mail4.skillsoft.com> Two choices: 1. Put your scripts into the folder python/lib/site-packages (not sure what the actual path is for you, but lib is the folder where the standard library files are found). This folder is automatically added to sys.path. 2. Make a file called sitecustomize.py. Put the file in python/lib/site-packages. In the file put the two lines import sys sys.path.append('/home/olavi/pythonscripts') Kent At 06:16 PM 9/22/2004 +0300, Olavi Ivask wrote: >Hello > >i made a folder(pythonscripts), where i hold my python scripts. Now, i added >this dir to modules path list > > >>>import sys > >>>sys.path.append('/home/olavi/pythonscripts') > >After closing python, my script path dissapears, in sys.path list. How must i >add this path, that every time i open python, it reloads that dir >automatically? > >i use debian, kernel2.6 and python 2.3.4 > >Thanks for your response > >Olavi Ivask >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From John.Ertl at fnmoc.navy.mil Wed Sep 22 19:36:10 2004 From: John.Ertl at fnmoc.navy.mil (Ertl, John) Date: Wed Sep 22 19:27:33 2004 Subject: [Tutor] What self is this ? Message-ID: <E338ADD616B66043824B9ABF5CA6EF2332C35C@lanexc107p.fnmoc.navy.mil> I was working on a class and I want to assign the class instance name (if that is the correct term) to an attribute in the class instance. For example class XZY: def __init__(self): self.instenceName = ???? def who(self): Print self.instenceName test1 = XZY() I want test1.who() to print test1 I know this looks very "Why would you do that?" but I am trying to give a simple example. This is coming up in the context of a list of classes that is going to be iterated over. Thanks, John Ertl From kent_johnson at skillsoft.com Wed Sep 22 19:51:56 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Wed Sep 22 19:52:02 2004 Subject: [Tutor] What self is this ? In-Reply-To: <E338ADD616B66043824B9ABF5CA6EF2332C35C@lanexc107p.fnmoc.na vy.mil> References: <E338ADD616B66043824B9ABF5CA6EF2332C35C@lanexc107p.fnmoc.navy.mil> Message-ID: <6.1.0.6.0.20040922134505.028b5100@mail4.skillsoft.com> I don't think you can do that. The name you want is not a property of the instance, it is a property of the namespace where the instance is bound. A particular instance could be bound to 0, 1 or more names. For example, aList = [XYZ()] aList[0].who() aList contains an XYZ that is not bound to any name; what should print? (Stricly speaking, aList is bound to a list that contains an XYZ.) Or how about test1 = XYZ() test2 = test1 test2.who() test1 and test2 are bound to the same XYZ instance; what should print? If you give us an idea what it is you are trying to accomplish maybe we can figure out a different way to do it. Kent At 10:36 AM 9/22/2004 -0700, Ertl, John wrote: >I was working on a class and I want to assign the class instance name (if >that is the correct term) to an attribute in the class instance. > >For example > >class XZY: > def __init__(self): > self.instenceName = ???? > > def who(self): > Print self.instenceName > > >test1 = XZY() > >I want test1.who() to print test1 > >I know this looks very "Why would you do that?" but I am trying to give a >simple example. This is coming up in the context of a list of classes that >is going to be iterated over. > >Thanks, > >John Ertl > > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From olavi at city.ee Wed Sep 22 20:20:37 2004 From: olavi at city.ee (Olavi Ivask) Date: Wed Sep 22 20:20:40 2004 Subject: [Tutor] Reload my modules dir In-Reply-To: <6.1.0.6.0.20040922125233.0288c670@mail4.skillsoft.com> References: <200409221816.33257.olavi@city.ee> <6.1.0.6.0.20040922125233.0288c670@mail4.skillsoft.com> Message-ID: <200409222120.37679.olavi@city.ee> Thank you Kent and Nathan for your help. O. On Wednesday 22 September 2004 19:55, Kent Johnson wrote: > Two choices: > > 1. Put your scripts into the folder python/lib/site-packages (not sure what > the actual path is for you, but lib is the folder where the standard > library files are found). This folder is automatically added to sys.path. > > 2. Make a file called sitecustomize.py. Put the file in > python/lib/site-packages. In the file put the two lines > import sys > sys.path.append('/home/olavi/pythonscripts') > > Kent > > At 06:16 PM 9/22/2004 +0300, Olavi Ivask wrote: > >Hello > > > >i made a folder(pythonscripts), where i hold my python scripts. Now, i > > added this dir to modules path list > > > > >>>import sys > > >>>sys.path.append('/home/olavi/pythonscripts') > > > >After closing python, my script path dissapears, in sys.path list. How > > must i add this path, that every time i open python, it reloads that dir > > automatically? > > > >i use debian, kernel2.6 and python 2.3.4 > > > >Thanks for your response > > > >Olavi Ivask > >_______________________________________________ > >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 jonathan.hayward at pobox.com Wed Sep 22 22:53:42 2004 From: jonathan.hayward at pobox.com (Jonathan Hayward) Date: Wed Sep 22 22:55:17 2004 Subject: [Tutor] Re: Willing to look at code? In-Reply-To: <4150E380.20405@pobox.com> References: <4150E380.20405@pobox.com> Message-ID: <4151E656.7080104@pobox.com> Jonathan Hayward wrote: > I have a bug that I'm trying to track down and was wondering if > someone would look at it. > > I have a combination search engine/weblog that has working keyword > searches, and I'm trying to add searches for quotations. What I'm > trying to do is let the boolean parser know that there's one more > primitive besides word, 'and', 'or', and 'not': 'quotation', which is > calculated as follows: > > 1: Break the quotation into tokens. > 2: Calculate a relevance score which is 0 if one or more token is > absent. (An optimization.) > 3: If the relevance score is positive, check if the sequence of tokens > is found in the document. > > The matches are the ones which pass steps 2 and 3. > > The problem I'm having is that a quotation search matches everything. > > Any takers? > As per Danny Yoo's suggestion that I post the source, I've placed a tarball at http://haywardfamily.org/jonathan/searchlog1_0_1.tar.gz -- ++ Jonathan Hayward, jonathan.hayward@pobox.com ** To see an award-winning website with stories, essays, artwork, ** games, and a four-dimensional maze, why not visit my home page? ** All of this is waiting for you at http://JonathansCorner.com From dyoo at hkn.eecs.berkeley.edu Thu Sep 23 00:45:27 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Sep 23 00:45:30 2004 Subject: [Tutor] Re: Willing to look at code? In-Reply-To: <4151E656.7080104@pobox.com> Message-ID: <Pine.LNX.4.44.0409221544500.8415-100000@hkn.eecs.berkeley.edu> > As per Danny Yoo's suggestion that I post the source, I've placed a > tarball at http://haywardfamily.org/jonathan/searchlog1_0_1.tar.gz Hi Jonathan, Can you check that URL again? I'm having trouble finding it from the url above. From keridee at jayco.net Thu Sep 23 05:29:19 2004 From: keridee at jayco.net (Jacob S.) Date: Thu Sep 23 05:28:56 2004 Subject: [Tutor] Printing to a parallel port Message-ID: <000b01c4a11d$872b6c70$ad5428cf@JSLAPTOP> Hi, I'm an intermediate python prgrammer -- I do things like command apps for simple tasks like creatings zip files, copying files, computing things like area, etc. Also, I have used VPython to create a function graphing program, etc. Ugh, enough about me ---- I would like to know if there is a way in Python to send a string to a printer on a parallel port or usb port. I do have one idea, but it's messy. Ex. -- import os ask = raw_input('What string do you want to print? ') filetoprint = open( 'Temp.txt ' ,'w' ) filetoprint.write( ask ) filetoprint.close() batch = open( 'print.bat','w' ) batch.write( 'Temp.txt > LPT1' ) batch.close() os.startfile( 'print.bat' ) os.remove( 'Temp.txt' ) os.remove( 'print.bat' ) ## End example Soo, I was wondering if there was a way to print directly -- without writing the batch file, etc. Thanks... -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040922/0b2a9ef8/attachment.html From flaxeater at yahoo.com Thu Sep 23 06:24:23 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Thu Sep 23 06:24:25 2004 Subject: [Tutor] What self is this ? Message-ID: <20040923042423.47792.qmail@web52603.mail.yahoo.com> Ertl, John wrote: >I was working on a class and I want to assign the class instance name (if >that is the correct term) to an attribute in the class instance. > >For example > >class XZY: > def __init__(self): > self.instenceName = ???? > > def who(self): > Print self.instenceName > > >test1 = XZY() > >I want test1.who() to print test1 > >I know this looks very "Why would you do that?" but I am trying to give a >simple example. This is coming up in the context of a list of classes that >is going to be iterated over. > > > Ok. I'm not really sure about this but here goes. #####CODE##### >>> class ABC(object): >>> def __init__(self): >>> self.instance="" >>>a=ABC() >>>print globals() {'a': <__main__.ABC object at 0x01611430>, 'shell': <wx.py.shell.Shell; proxy of C++ wxStyledTextCtrl instance at _00575601_p_wxStyledTextCtrl>, '__builtins__': <module '__builtin__' (built-in)>, '__file__': 'C:\\Python23\\Scripts\\pyshell', 'ABC': <class '__main__.ABC'>, '__name__': '__main__', '__doc__': None} >>>type(a) <class '__main__.ABC'> >>>for k,v in globals().items(): >>> if type(v)==type(ABC()): >>> v.instance=k >>> print "Intance Name=%s" %k Intance Name=a #####/CODE##### Ok.. this session explained. builtin functions named globals() and locals() shows the namespaces represented as python dictionaries. Now you could look at the globals and locals dictionary (you can assign to them directly also) check for type and then know the variable name and do such. I don't think this is very sane but perhaps you can do what you want with this. Good Luck _______________________________ Do you Yahoo!? Declare Yourself - Register online to vote today! http://vote.yahoo.com From flaxeater at yahoo.com Thu Sep 23 06:34:14 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Thu Sep 23 06:34:18 2004 Subject: [Tutor] Printing to a parallel port Message-ID: <20040923043414.99840.qmail@web52602.mail.yahoo.com> Jacob S. wrote: > Hi, > > I'm an intermediate python prgrammer -- I do things like command > apps for simple tasks like creatings zip files, copying files, > computing things like area, etc. Also, I have used VPython to create a > function graphing program, etc. Ugh, enough about me ---- I would > like to know if there is a way in Python to send a string to a printer > on a parallel port or usb port. I do have one idea, but it's messy. > > Ex. -- > > import os > > ask = raw_input('What string do you want to print? ') > filetoprint = open( 'Temp.txt ' ,'w' ) > filetoprint.write( ask ) > filetoprint.close() > batch = open( 'print.bat','w' ) > batch.write( 'Temp.txt > LPT1' ) > batch.close() > os.startfile( 'print.bat' ) > os.remove( 'Temp.txt' ) > os.remove( 'print.bat' ) > > ## End example > Well I saw this earlier on this list here's the link http://aspn.activestate.com/ASPN/Mail/Message/2070242 I looked a little further into it but was unable to find much more information. __________________________________ Do you Yahoo!? New and Improved Yahoo! Mail - 100MB free storage! http://promotions.yahoo.com/new_mail From kabads at gmail.com Thu Sep 23 11:19:22 2004 From: kabads at gmail.com (Adam Cripps) Date: Thu Sep 23 11:19:25 2004 Subject: [Tutor] Deleting an instance of an object Message-ID: <c7ff3855040923021926a93882@mail.gmail.com> I've designed an OOP program, where I keep a catalogue of publications. I want to be able to delete an instance of Article (Article is a subclass of Issue, which is a subclass of Title, which is a subclass of MagazineCollection). Each instance of Article has an attribute name (article.name). I've created a loop which searches through the article.name(s) and found the one I want. The user has specified which one they want to delete and I've collected that. The problem I'm having is finding out the instantiation of self.name - is there a hard and fast way of identifying a particular instance of self.name? I'm getting the error: AttributeError: 'str' object has no attribute '__del__' Deleted which is strange, as the Deleted is coming from a __del__ function that I placed in the Article class. -- proj: http://jiletters.sf.net site: http://www.monkeez.org wiki: http://wiki.monkeez.org From kabads at gmail.com Thu Sep 23 11:21:47 2004 From: kabads at gmail.com (Adam Cripps) Date: Thu Sep 23 11:21:50 2004 Subject: [Tutor] Re: Deleting an instance of an object In-Reply-To: <c7ff3855040923021926a93882@mail.gmail.com> References: <c7ff3855040923021926a93882@mail.gmail.com> Message-ID: <c7ff385504092302215b55d234@mail.gmail.com> <snip>> which is strange, as the Deleted is coming from a __del__ function > that I placed in the Article class. Damn! Pressed the send button by accident and hadn't finished. If you want to see the code [1] - look in the deletearticles function within MagazineCollection class. Any advice appreciated - thanks. Adam [1] http://www.nongnu.org/newmag/code.html -- proj: http://jiletters.sf.net site: http://www.monkeez.org wiki: http://wiki.monkeez.org From andrea.valle at unito.it Thu Sep 23 12:42:00 2004 From: andrea.valle at unito.it (andrea valle) Date: Thu Sep 23 12:42:04 2004 Subject: [Tutor] wave.readframes() (or conversion?) Message-ID: <333E0C85-0D4D-11D9-A089-0003939C968C@unito.it> Hi to all, I'm using wave module with success. I'm writing data to wave file. Typically I create a list of values (data) and pass it to .writeframes(data) methods. a = wave.open("/test.wav", "w") a.writeframes([32000, 0]) This sets the first sample to 32000 and the 2nd to 0 But when I use the .readframes() method I don't know exactly what values I extract from the open wave. >>> a = wave.open("/test.wav", "r") >>> a.readframes(1) '\x00\x00' How do I convert it to an integer? I'd like to have it like 32000 or 0, so to make some maths on it. Thanks a lot -a- Andrea Valle Laboratorio multimediale "G. Quazza" Facolt? di Scienze della Formazione Universit? degli Studi di Torino andrea.valle@unito.it From kent_johnson at skillsoft.com Thu Sep 23 14:17:08 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Thu Sep 23 14:17:20 2004 Subject: [Tutor] Deleting an instance of an object In-Reply-To: <c7ff3855040923021926a93882@mail.gmail.com> References: <c7ff3855040923021926a93882@mail.gmail.com> Message-ID: <6.1.0.6.0.20040923075618.028be778@mail4.skillsoft.com> Adam, First, I'll try to shed a little light on some misconceptions you seem to have. The name that you have stored in the collect_results list is not really associated with the Article any more, it is just a reference to a string. That is why you get the error 'str' object has no attribute '__del__'. You shouldn't be calling __del__ yourself. __del__ is an internal method that implements the del statement. Objects are deleted from a container by calling del on the container. In other words, you don't ask an object to delete itself from a container, you ask the container to delete the object. OK, so how should you accomplish what you want? There are two ways to delete from a list, by index and by reference (see http://docs.python.org/lib/typesseq-mutable.html). For example, here is a simple Article class that has a name and shows the name when printed: >>> class Article: ... def __init__(self, name): ... self.name = name ... def __repr__(self): ... return self.name ... Make a few articles and put them in a list: >>> a=Article('Learning Python') >>> a Learning Python >>> b=Article('Python Networking') >>> c=Article('Using Twisted') >>> articles = [a, b, c] >>> articles [Learning Python, Python Networking, Using Twisted] Delete the first article by index: >>> del articles[0] >>> articles [Python Networking, Using Twisted] Delete article b by reference: >>> articles.remove(b) >>> articles [Using Twisted] Notice that in each case I do something with the list, and in each case I need to know something about the article object besides its name - either its index in the list, or a reference to the actual article object. So, what does this mean for you? I suggest that you save more information about an article in the collect_results list. You could save the articlesheld list, and the article object. You don't need the name as it is in the article. A simple way to do this is to store a tuple in the list : result = (issue_object.articlesheld, article_object) collect_results.append(result) To print the list, you need to unpack the tuple and get the article name back: for article_list, article in collect_results: print article.name (You can read a little more about tuples here: http://docs.python.org/tut/node7.html#SECTION007300000000000000000) To delete an entry, get the list and article from the entry and remove the article from the list: article_list, article = collect_results[del_choice_int] article_list.remove(article) Kent At 10:19 AM 9/23/2004 +0100, Adam Cripps wrote: >I've designed an OOP program, where I keep a catalogue of >publications. I want to be able to delete an instance of Article >(Article is a subclass of Issue, which is a subclass of Title, which >is a subclass of MagazineCollection). Each instance of Article has an >attribute name (article.name). > >I've created a loop which searches through the article.name(s) and >found the one I want. The user has specified which one they want to >delete and I've collected that. > >The problem I'm having is finding out the instantiation of self.name - >is there a hard and fast way of identifying a particular instance of >self.name? > >I'm getting the error: >AttributeError: 'str' object has no attribute '__del__' >Deleted > >which is strange, as the Deleted is coming from a __del__ function >that I placed in the Article class. > >-- >proj: http://jiletters.sf.net >site: http://www.monkeez.org >wiki: http://wiki.monkeez.org >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From kent_johnson at skillsoft.com Thu Sep 23 16:14:25 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Thu Sep 23 16:14:28 2004 Subject: [Tutor] regexp help In-Reply-To: <200409221618.50482.zsolt.botykai@online.hu> References: <200409221618.50482.zsolt.botykai@online.hu> Message-ID: <6.1.0.6.0.20040922130006.028935d8@mail4.skillsoft.com> I'm not sure what you are trying to do here. It would help to see a sample of input and output data. If you are trying to process stdin by lines, maybe you want to use something like for data in sys.stdin: # process one line... The code you have will read all input from stdin and process it at once. The regex will match everything from the first --==--==--==--==-- to the last, even spanning many lines. Is that what you want? Kent At 04:18 PM 9/22/2004 +0200, Botykai Zsolt wrote: >Hi for everyone, >just dived in to regexp, and have some problem, wrote this script to work >as a >pipe for multiline text input. > >My problem is >- how to cut out all the empty lines (empty line: content only space or tab) >from f_body? > >import sys >import re >data = sys.stdin.read() >... >match_body = re.compile( > r"""--==--==--==--==--.(.+).--==--==--==--==--""", > re.DOTALL | > re.MULTILINE | > re.VERBOSE) >f_body = match_body.search(data) >f_body = match_body.search(data) >o_output = f_body.group(0) >... >sys.stdout.write(o_output) > >Thx for any help, >Zsoltik@ from Hungary >(sorry about the disclaimer...) > >-------------------------------------------------------------------------- > >Opinions, conclusions and other information in this message that do not >relate to the official business of Online Business Technologies Corp. >shall be understood as neither given nor endorsed by it. In such cases >Online Business Technologies Corp. will not bear the responsibility of >consequences. >If you have received this communication in error, please notify the >system manager immediately by responding to this email and then delete >it from your system. > > >A levelben foglalt, nem az Online Rt. hivatalos uzletmenetevel kapcsolatos >velemenyek vagy mas informaciok vonatkozasaban az Online Rt. nem vallal >felelosseget. >Amennyiben a level valamely hiba folytan jutott Onhoz, kerjuk, hogy >valaszlevelben azonnal ertesitse a rendszer uzemeltetojet, majd torolje ki >a levelet rendszerebol! > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From zsolt.botykai at online.hu Thu Sep 23 16:25:47 2004 From: zsolt.botykai at online.hu (Botykai Zsolt) Date: Thu Sep 23 16:25:51 2004 Subject: [Tutor] regexp help In-Reply-To: <6.1.0.6.0.20040922130006.028935d8@mail4.skillsoft.com> References: <200409221618.50482.zsolt.botykai@online.hu> <6.1.0.6.0.20040922130006.028935d8@mail4.skillsoft.com> Message-ID: <200409231625.47869.zsolt.botykai@online.hu> cs?t?rt?k 23 szeptember 2004 16:14 d?tummal Kent Johnson ezt ?rta: > The code you have will read all input from stdin and process it at once. > The regex will match everything from the first --==--==--==--==-- to the > last, even spanning many lines. Is that what you want? yes. these are not so big text file, with contents like this: <some useless row> <delimiter> <some useful rows or empty lines (where empty lines contains only \n or spaces and/or tabs + \n> <some useful rows> <some useful rows or empty lines (where empty lines contains only \n or spaces and/or tabs + \n> <some useful rows> <some useful rows or empty lines (where empty lines contains only \n or spaces and/or tabs + \n> <delimiter> <useless rows> AFAIK the first solution is to handle STDIN in a cycle and print process like you suggested, but I wanted to resolve this with regexp and without cycles. So you are right, I wanted to match all the lines between --==--==--==--==--s except the above defined empty lines. Zsoltik@ -------------------------------------------------------------------------- Opinions, conclusions and other information in this message that do not relate to the official business of Online Business Technologies Corp. shall be understood as neither given nor endorsed by it. In such cases Online Business Technologies Corp. will not bear the responsibility of consequences. If you have received this communication in error, please notify the system manager immediately by responding to this email and then delete it from your system. A levelben foglalt, nem az Online Rt. hivatalos uzletmenetevel kapcsolatos velemenyek vagy mas informaciok vonatkozasaban az Online Rt. nem vallal felelosseget. Amennyiben a level valamely hiba folytan jutott Onhoz, kerjuk, hogy valaszlevelben azonnal ertesitse a rendszer uzemeltetojet, majd torolje ki a levelet rendszerebol! From kabads at gmail.com Thu Sep 23 17:15:43 2004 From: kabads at gmail.com (Adam Cripps) Date: Thu Sep 23 17:15:49 2004 Subject: [Tutor] Deleting an instance of an object In-Reply-To: <6.1.0.6.0.20040923075618.028be778@mail4.skillsoft.com> References: <c7ff3855040923021926a93882@mail.gmail.com> <6.1.0.6.0.20040923075618.028be778@mail4.skillsoft.com> Message-ID: <c7ff385504092308153029619f@mail.gmail.com> On Thu, 23 Sep 2004 08:17:08 -0400, Kent Johnson <kent_johnson@skillsoft.com> wrote: > Adam, > > First, I'll try to shed a little light on some misconceptions you seem to have. > > The name that you have stored in the collect_results list is not really > associated with the Article any more, it is just a reference to a string. > That is why you get the error 'str' object has no attribute '__del__'. > > You shouldn't be calling __del__ yourself. __del__ is an internal method > that implements the del statement. > > Objects are deleted from a container by calling del on the container. In > other words, you don't ask an object to delete itself from a container, you > ask the container to delete the object. > > OK, so how should you accomplish what you want? There are two ways to > delete from a list, by index and by reference (see > http://docs.python.org/lib/typesseq-mutable.html). For example, here is a > simple Article class that has a name and shows the name when printed: > > >>> class Article: > ... def __init__(self, name): > ... self.name = name > ... def __repr__(self): > ... return self.name > ... > > Make a few articles and put them in a list: > > >>> a=Article('Learning Python') > >>> a > Learning Python > >>> b=Article('Python Networking') > >>> c=Article('Using Twisted') > >>> articles = [a, b, c] > >>> articles > [Learning Python, Python Networking, Using Twisted] > > Delete the first article by index: > > >>> del articles[0] > >>> articles > [Python Networking, Using Twisted] > > Delete article b by reference: > > >>> articles.remove(b) > >>> articles > [Using Twisted] > > Notice that in each case I do something with the list, and in each case I > need to know something about the article object besides its name - either > its index in the list, or a reference to the actual article object. > > So, what does this mean for you? I suggest that you save more information > about an article in the collect_results list. You could save the > articlesheld list, and the article object. You don't need the name as it is > in the article. A simple way to do this is to store a tuple in the list : > result = (issue_object.articlesheld, article_object) > collect_results.append(result) > > To print the list, you need to unpack the tuple and get the article name back: > for article_list, article in collect_results: > print article.name > > (You can read a little more about tuples here: > http://docs.python.org/tut/node7.html#SECTION007300000000000000000) > > To delete an entry, get the list and article from the entry and remove the > article from the list: > article_list, article = collect_results[del_choice_int] > article_list.remove(article) > > Kent <snip> Kent, Thanks very much - I understand this a lot more now. I'll implement your suggestion. Thanks again. Adam From kent_johnson at skillsoft.com Thu Sep 23 17:26:45 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Thu Sep 23 17:26:51 2004 Subject: [Tutor] regexp help In-Reply-To: <200409231625.47869.zsolt.botykai@online.hu> References: <200409221618.50482.zsolt.botykai@online.hu> <6.1.0.6.0.20040922130006.028935d8@mail4.skillsoft.com> <200409231625.47869.zsolt.botykai@online.hu> Message-ID: <6.1.0.6.0.20040923111059.02a27080@mail4.skillsoft.com> OK. I suggest you use re.sub() on the match data to remove the blank lines. So you would use one re to get the data and another one to remove the blank lines. For example: >>> import re >>> data = ' \n \nhere\nis\n \nsome data\n\nwith\nblank lines \n \n ' >>> rx = re.compile(r'(^|\n)\s*(\n|$)') >>> rx.sub(r'\1', data) 'here\nis\nsome data\nwith\nblank lines \n' >>> rx.sub(r'\1', '\n\n\ntest\n\n\n') 'test\n' The re to match blank lines is a little tricky because you want to match ' \n' - a blank line at the beginning '\n \n' - a blank line in the middle ' ' - a blank line at the end The solution I used was to allow either beginning of string ^ or newline \n before the blank, and either newline or end of string $ at the end. Then I replace by whatever matched at the beginning so the blank line at start is not replaced by a newline itself. If your data uses \r\n for newlines you will have to modify the regex a little bit. Kent At 04:25 PM 9/23/2004 +0200, Botykai Zsolt wrote: >cs?t?rt?k 23 szeptember 2004 16:14 d?tummal Kent Johnson ezt ?rta: > > The code you have will read all input from stdin and process it at once. > > The regex will match everything from the first --==--==--==--==-- to the > > last, even spanning many lines. Is that what you want? > >yes. these are not so big text file, with contents like this: > ><some useless row> ><delimiter> ><some useful rows or empty lines (where empty lines contains only \n or >spaces >and/or tabs + \n> ><some useful rows> ><some useful rows or empty lines (where empty lines contains only \n or >spaces >and/or tabs + \n> ><some useful rows> ><some useful rows or empty lines (where empty lines contains only \n or >spaces >and/or tabs + \n> ><delimiter> ><useless rows> > >AFAIK the first solution is to handle STDIN in a cycle and print process like >you suggested, but I wanted to resolve this with regexp and without cycles. >So you are right, I wanted to match all the lines between --==--==--==--==--s >except the above defined empty lines. > >Zsoltik@ From abli at freemail.hu Thu Sep 23 18:33:37 2004 From: abli at freemail.hu (Abel Daniel) Date: Thu Sep 23 18:33:45 2004 Subject: [Tutor] Re: What self is this ? In-Reply-To: <E338ADD616B66043824B9ABF5CA6EF2332C35C@lanexc107p.fnmoc.navy.mil> (John Ertl's message of "Wed, 22 Sep 2004 10:36:10 -0700") References: <E338ADD616B66043824B9ABF5CA6EF2332C35C@lanexc107p.fnmoc.navy.mil> Message-ID: <E1CAWXL-0000E0-00@hooloovoo> "Ertl, John" writes: > I was working on a class and I want to assign the class instance name (if > that is the correct term) to an attribute in the class instance. > > For example > > class XZY: > def __init__(self): > self.instenceName = ???? > > def who(self): > Print self.instenceName > > > test1 = XZY() > > I want test1.who() to print test1 ok, how about: test2 = test1 = XZY() After that, test2 is test1 (the names 'test1' and 'test2' refer to the same object, to see that try 'print test1' you will get something like <__main__.XYZ instance at 0x40517b0c> that octal number will be the same for test1 and test2), would test1.who() print test1 or test2? and how about: l=[] l.append(XZY()) l[0].who() what do you think should be printed? You should really read http://effbot.org/zone/python-objects.htm > I know this looks very "Why would you do that?" but I am trying to give a > simple example. This is coming up in the context of a list of classes that > is going to be iterated over. When you are trying to do something like this, its a sure sign that your program's design needs to be changed. -- Abel Daniel From dyoo at hkn.eecs.berkeley.edu Thu Sep 23 19:34:34 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Sep 23 19:34:42 2004 Subject: [Tutor] Re: What self is this ? In-Reply-To: <E1CAWXL-0000E0-00@hooloovoo> Message-ID: <Pine.LNX.4.44.0409231025240.3895-100000@hkn.eecs.berkeley.edu> > > For example > > > > class XZY: > > def __init__(self): > > self.instenceName = ???? > > > > def who(self): > > Print self.instenceName > > > > > > test1 = XZY() > > > > I want test1.who() to print test1 > > ok, how about: > > test2 = test1 = XZY() > > After that, test2 is test1 (the names 'test1' and 'test2' refer to the > same object, to see that try 'print test1' you will get something like > <__main__.XYZ instance at 0x40517b0c> that octal number will be the same > for test1 and test2), would test1.who() print test1 or test2? Hi John, Abel is showing that asking Python to try to infer the name of the instance is ambiguous, since an instance can go by several variable names. Rather than force Python to infer it, would it be ok if you explicitely give your instance a name? For example: ### class XZY: def __init__(self, name): self.name = name def who(self): print self.name test1 = XYZ('test1') test2 = XYZ('test2') test3 = XYZ('test3') ### There's some repetition here. We can fix this by storing the testX names in a dictionary: ### tests = [] for name in ['test1', 'test2', 'test3']: tests[name] = XYZ(name) ### > > I know this looks very "Why would you do that?" but I am trying to > > give a simple example. This is coming up in the context of a list of > > classes that is going to be iterated over. If you're iterating across a collection of classes, to make a bunch of instances, then you may want the instances themselves to be collected somewhere, like a dictionary. It may make it easier to manage them, since you can do mass-actions on them, like passing them all off of a function at once. Hope this helps! From John.Ertl at fnmoc.navy.mil Thu Sep 23 19:49:19 2004 From: John.Ertl at fnmoc.navy.mil (Ertl, John) Date: Thu Sep 23 19:40:38 2004 Subject: [Tutor] Re: What self is this ? Message-ID: <E338ADD616B66043824B9ABF5CA6EF2332C360@lanexc107p.fnmoc.navy.mil> Danny, Thanks, I have come to the same conclusion. I was trying to avoid it if possible but OOOhhh well. Thanks again. John Ertl -----Original Message----- From: Danny Yoo [mailto:dyoo@hkn.eecs.berkeley.edu] Sent: Thursday, September 23, 2004 10:35 To: Abel Daniel Cc: Ertl, John; Tutor Subject: Re: [Tutor] Re: What self is this ? > > For example > > > > class XZY: > > def __init__(self): > > self.instenceName = ???? > > > > def who(self): > > Print self.instenceName > > > > > > test1 = XZY() > > > > I want test1.who() to print test1 > > ok, how about: > > test2 = test1 = XZY() > > After that, test2 is test1 (the names 'test1' and 'test2' refer to the > same object, to see that try 'print test1' you will get something like > <__main__.XYZ instance at 0x40517b0c> that octal number will be the same > for test1 and test2), would test1.who() print test1 or test2? Hi John, Abel is showing that asking Python to try to infer the name of the instance is ambiguous, since an instance can go by several variable names. Rather than force Python to infer it, would it be ok if you explicitely give your instance a name? For example: ### class XZY: def __init__(self, name): self.name = name def who(self): print self.name test1 = XYZ('test1') test2 = XYZ('test2') test3 = XYZ('test3') ### There's some repetition here. We can fix this by storing the testX names in a dictionary: ### tests = [] for name in ['test1', 'test2', 'test3']: tests[name] = XYZ(name) ### > > I know this looks very "Why would you do that?" but I am trying to > > give a simple example. This is coming up in the context of a list of > > classes that is going to be iterated over. If you're iterating across a collection of classes, to make a bunch of instances, then you may want the instances themselves to be collected somewhere, like a dictionary. It may make it easier to manage them, since you can do mass-actions on them, like passing them all off of a function at once. Hope this helps! From jeff at ccvcorp.com Thu Sep 23 19:56:50 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu Sep 23 19:58:43 2004 Subject: [Tutor] Deleting an instance of an object In-Reply-To: <c7ff3855040923021926a93882@mail.gmail.com> References: <c7ff3855040923021926a93882@mail.gmail.com> Message-ID: <41530E62.6000800@ccvcorp.com> Adam Cripps wrote: >(Article is a subclass of Issue, which is a subclass of Title, which >is a subclass of MagazineCollection). Each instance of Article has an >attribute name (article.name). > > I haven't looked closely at your code, but this strikes me as not being a very good design. Remember, inheritance (subclassing) should normally be expressing an "is a type of" relationship. For instance, a "shape" class might have a subclass called "square", because a square is a type of shape. You seem to be using subclassing to express an entirely different sort of relationship -- a "contains" relationship. That relationship is a poor fit for inheritance -- in this scheme, each and every Article instance is also a full MagazineCollection instance. Rather than using subclassing, you may want to use a technique called aggreggation. Instead of having Title be a subclass of MagazineCollection, you should have MagazineCollection hold a list (or a dict) of Titles. You can give MagazineCollection a set of methods for adding and removing Title instances from its internal collection, getting information about contained Titles, etc. Similarly, each Title should hold a list (or dict) of Issues, and each Issue a list or dict of Articles. Hmmm... glancing at your code a bit more, it *does* look like you have internal collections of each subclass in the next-higher class, so it seems that you've got that idea down. So why are you subclassing? It looks like Article instances aren't using any of the MagazineCollection code or the Issue code (and sharing code is the main benefit of subclassing), so it seems to me that this provides no benefit... You can probably make each subclass a fully independent class, with no subclassing involved, without requiring any significant changes to your code. Jeff Shannon Technician/Programmer Credit International From csmwxl at bath.ac.uk Thu Sep 23 22:54:19 2004 From: csmwxl at bath.ac.uk (W X Liu) Date: Thu Sep 23 22:54:20 2004 Subject: [Tutor] Get confused by self In-Reply-To: <Pine.LNX.4.44.0409201135100.20801-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0409201135100.20801-100000@hkn.eecs.berkeley.edu> Message-ID: <1095972859.415337fb11181@webmail.bath.ac.uk> I am learning the class section for Pyhton, but I get confused by self, what does it really mean? Wenxin From rob.andrews at gmail.com Fri Sep 24 00:20:06 2004 From: rob.andrews at gmail.com (Rob Andrews) Date: Fri Sep 24 00:20:19 2004 Subject: [Tutor] Get confused by self In-Reply-To: <1095972859.415337fb11181@webmail.bath.ac.uk> References: <Pine.LNX.4.44.0409201135100.20801-100000@hkn.eecs.berkeley.edu> <1095972859.415337fb11181@webmail.bath.ac.uk> Message-ID: <8d757d2e04092315203e208ed3@mail.gmail.com> 'self' refers to an instance of a class, so if you do something to 'self', you are doing it to the class instance instead of to the class itself. I don't know if that really gave you what you were looking for, but hopefully it's a little helpful. -Rob On Thu, 23 Sep 2004 21:54:19 +0100, W X Liu <csmwxl@bath.ac.uk> wrote: > I am learning the class section for Pyhton, but I get confused by self, what > does it really mean? From python at pointcontrol.com Fri Sep 24 01:05:18 2004 From: python at pointcontrol.com (Barry Tice) Date: Fri Sep 24 01:05:22 2004 Subject: [Tutor] Get confused by self In-Reply-To: <1095972859.415337fb11181@webmail.bath.ac.uk> References: <Pine.LNX.4.44.0409201135100.20801-100000@hkn.eecs.berkeley.edu> <1095972859.415337fb11181@webmail.bath.ac.uk> Message-ID: <1095980717.3527.18.camel@localhost.localdomain> Perhaps an analogy would help. Consider that you and I are both instances of the class Person. In python, I might be: barry = Person("male") Now, any method or function that I do has to know who it is I'm doing it to. Perhaps my Person class looks like this: class Person: def __init__(self, whatGender): self.gender = whatGender hand = BodyPart("hand") face = BodyPart("face") def washFace(self): # code here to wash a face self.hand.getSoap() self.hand.getWetWashcloth() self.hand.scrubFace(self.face) # etc. If I need to wash my face, I can use this: barry.washFace() the washFace method has to know whose face is being washed. It also provides a way to refer to all the component parts of the current object (Person) and not get them confused with the component parts of another person object. This way, I'm explicitly washing my own face and not someone else's. In this example, self refers to me, so self.hand is MY hand, and self.face is MY face, and self.gender is MY gender. Outside of the object itself, those would all be barry.face and barry.hand and barry.gender, but from within the object, which doesn't know what name it's going to be going by, they're all just referred to as self. In other situations, there may be functions within my Person class that do something to another object unrelated to me. It may have this function, for example: def openDoor(self, door): door.open() In this case, the door is the only thing we really care about, so the self variable isn't used. (It still has to be there, though.) But in a more elaborate function, it might be: def openDoor(self, door): self.hand.turn(door.doorknob) self.hand.pull(door.doorknob) In this case, we use the self variable to refer to the Person object being asked to perform the action, so we can get access to that Person object's hand component to do the work. Does this help any? -- Barry Tice On Thu, 2004-09-23 at 15:54, W X Liu wrote: > I am learning the class section for Pyhton, but I get confused by self, what > does it really mean? > > Wenxin > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From dyoo at hkn.eecs.berkeley.edu Fri Sep 24 03:08:33 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri Sep 24 03:08:46 2004 Subject: [Tutor] Get confused by self In-Reply-To: <1095972859.415337fb11181@webmail.bath.ac.uk> Message-ID: <Pine.LNX.4.44.0409231743350.3895-100000@hkn.eecs.berkeley.edu> On Thu, 23 Sep 2004, W X Liu wrote: > I am learning the class section for Python, but I get confused by self, > what does it really mean? Hello! Here's a small example that might help clear things up. Let's say that we have a few people around: ### >>> yoo = {'name': 'Danny', 'friends':[]} >>> liu = {'name': 'Wenxin', 'friends': []} ### I'm being a bit informal here: I'm just representing a "person" as a dictionary. Please ignore the fact that I'm not technically using classes for the moment. *grin* We'll get to that in the end. Maybe we might want to make it easier to make more people; when I make a new person, I could accidently mistype the 'friends' as 'freinds', and that would be tragic. Let's write a small function to make that mistake less likely: ### >>> def makePerson(name): ... return {'name': name, 'friends': []} ... >>> andrews = makePerson('Rob') >>> andrews {'friends': [], 'name': 'Rob'} ### Ok, so now we have these three people: 'liu', 'andrews', and 'yoo'. We can have these three people greet each other as friends: ### >>> def greetFriends(person): ... for f in person['friends']: ... print 'hello', f ... >>> greetFriends(liu) >>> ### But 'liu' has an empty list of friends! Ok, lets make another function to add a friend to any person: ### >>> def addFriend(person, other): ... person['friends'].append(other) ... >>> addFriend(liu, yoo) >>> addFriend(liu, andrews) >>> greetFriends(liu) hello {'friends': [], 'name': 'Danny'} hello {'friends': [], 'name': 'Rob'} ### That looks a little funky: let's get greetFriends() to just print out the name of the other folks. We can make it easier to grab the name of a person by adding a getName() function. Oh, at the same time, let's make it easier to get the friends of a person with a getFriends() function: ### >>> def getName(person): ... return person['name'] ... >>> def getFriends(person): ... return person['friends'] ... ### Once we have these two helper functions, now we can rewrite greetFriends(): ### >>> def greetFriends(person): ... for f in getFriends(person): ... print "hello", getName(f) ... ### And now let's see what happens when we call greetFriends() on liu: ### >>> greetFriends(liu) hello Danny hello Rob ### That looks nicer. *grin* Ok, the punchline here is that all that we've been doing about is pretty much what 'classes' do. Python's classes do more, but the core of it is what we've been doing above, with a bit more syntax support from Python. Remember that we wrote this: ### def makePerson(name): """A constructor for a person.""" return {'name': name, 'friends': []} def getName(person): """Gets the name of a person.""" return person['name'] def getFriends(person): """Gets the friends of a person.""" return person['friends'] def greetFriends(person): """Sends a warm greeting to all of the person's friends.""" for f in getFriends(person): print "hello", getName(f) ### Here's what that would look like, if we use Python's class notation: ### class Person: def __init__(self, name): """An initializer for a person.""" self.name, self.friends = name, [] def getName(self): """Gets the name of a person.""" return self.name def getFriends(self): """Gets the friends of a person.""" return self.friends def greetFriends(self): """Sends a warm greeting to all of the person's friends.""" for f in self.getFriends(): print "hello", f.getName() ### The main difference is that 'self' in the class definition plays the role of the 'person' that we had used to store a person's name and friends. Does this make sense so far? From tony at tcapp.com Fri Sep 24 03:48:42 2004 From: tony at tcapp.com (Tony Cappellini) Date: Fri Sep 24 03:47:03 2004 Subject: [Tutor] Looking for the nomenclature of an HTML "link checker" Message-ID: <20040923184538.L8564@yamato.yamato.com> I'm sure ther eis a python recipe for this, but I don't know wha tthe correct nomenclature is. I'm looking for a Python program that will Walk through all of the links in an html page, to validate that the ALL of the links are correct (no typos). I'm not looking for an html validator to tell me that an html page doens tcomply with a spec. I want the program to actually go out to the URL, and simulate clicking on the links, and tell me if any links are broken. What is this functionality called ?? thanks From pathall at gmail.com Fri Sep 24 07:05:13 2004 From: pathall at gmail.com (Patrick Hall) Date: Fri Sep 24 07:05:16 2004 Subject: [Tutor] Looking for the nomenclature of an HTML "link checker" In-Reply-To: <20040923184538.L8564@yamato.yamato.com> References: <20040923184538.L8564@yamato.yamato.com> Message-ID: <6465924d04092322053c802a56@mail.gmail.com> Hi Tony, > I'm looking for a Python program that will Walk through all of the links > in an html page, to validate that the ALL of the links are correct (no > typos). I think you're looking for what's called a "link checker." Googling for "linkchecker.py" turns up a few things (although what i've seen looks a bit old). The phrase should get you started, in any case. Best, Patrick From pathall at gmail.com Fri Sep 24 07:13:28 2004 From: pathall at gmail.com (Patrick Hall) Date: Fri Sep 24 07:13:30 2004 Subject: [Tutor] Looking for the nomenclature of an HTML "link checker" In-Reply-To: <20040923184538.L8564@yamato.yamato.com> References: <20040923184538.L8564@yamato.yamato.com> Message-ID: <6465924d040923221318fb4bdb@mail.gmail.com> Hi Tony, > I'm looking for a Python program that will Walk through all of the links > in an html page, to validate that the ALL of the links are correct (no > typos). I think you're looking for what's called a "link checker." Googling for "linkchecker.py" turns up a few things (although what i've seen looks a bit old). The phrase should get you started, in any case. Best, Patrick From kabads at gmail.com Fri Sep 24 09:36:15 2004 From: kabads at gmail.com (Adam Cripps) Date: Fri Sep 24 09:36:18 2004 Subject: [Tutor] Deleting an instance of an object In-Reply-To: <41530E62.6000800@ccvcorp.com> References: <c7ff3855040923021926a93882@mail.gmail.com> <41530E62.6000800@ccvcorp.com> Message-ID: <c7ff38550409240036163f4be6@mail.gmail.com> On Thu, 23 Sep 2004 10:56:50 -0700, Jeff Shannon <jeff@ccvcorp.com> wrote: > Adam Cripps wrote: > > >(Article is a subclass of Issue, which is a subclass of Title, which > >is a subclass of MagazineCollection). Each instance of Article has an > >attribute name (article.name). > > > > > > I haven't looked closely at your code, but this strikes me as not being > a very good design. > <snip> > Hmmm... glancing at your code a bit more, it *does* look like you have > internal collections of each subclass in the next-higher class, so it > seems that you've got that idea down. So why are you subclassing? It > looks like Article instances aren't using any of the MagazineCollection > code or the Issue code (and sharing code is the main benefit of > subclassing), so it seems to me that this provides no benefit... You > can probably make each subclass a fully independent class, with no > subclassing involved, without requiring any significant changes to your > code. > > Jeff Shannon > Technician/Programmer Jeff, Thanks very much for the feedback - very useful and provides a lot of food for thought. It's this kind of community feedback that makes Python so enjoyable to use. This is the first program where I've used OO strictly, and so I'm not completely clear why I made them subclasses. I think you're right - they don't need to be. I'll try and make the changes later this evening (UTC), wife permitting ;-) Thanks again Adam -- proj: http://jiletters.sf.net site: http://www.monkeez.org wiki: http://wiki.monkeez.org From paul.baines at ecb.int Fri Sep 24 09:46:37 2004 From: paul.baines at ecb.int (paul.baines@ecb.int) Date: Fri Sep 24 09:47:15 2004 Subject: [Tutor] Deleting an instance of an object Message-ID: <71CEC1FA9395784A826B525D0E1AB21503901E@cimexc21.ecb01.ecb.de> I think it's good to use the phrase "is a" when thinking about subclassing. A mammal is an animal, so mammal is a subclass of animal, but "article is an issue" doesn't really make sense, so it's probably not a good candidate for a subclass. -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org] On Behalf Of Adam Cripps Sent: Friday 24 September 2004 09:36 To: tutor@python.org Subject: Re: [Tutor] Deleting an instance of an object On Thu, 23 Sep 2004 10:56:50 -0700, Jeff Shannon <jeff@ccvcorp.com> wrote: > Adam Cripps wrote: > > >(Article is a subclass of Issue, which is a subclass of Title, which > >is a subclass of MagazineCollection). Each instance of Article has an > >attribute name (article.name). > > > > > > I haven't looked closely at your code, but this strikes me as not being > a very good design. > <snip> > Hmmm... glancing at your code a bit more, it *does* look like you have > internal collections of each subclass in the next-higher class, so it > seems that you've got that idea down. So why are you subclassing? It > looks like Article instances aren't using any of the MagazineCollection > code or the Issue code (and sharing code is the main benefit of > subclassing), so it seems to me that this provides no benefit... You > can probably make each subclass a fully independent class, with no > subclassing involved, without requiring any significant changes to your > code. > > Jeff Shannon > Technician/Programmer Jeff, Thanks very much for the feedback - very useful and provides a lot of food for thought. It's this kind of community feedback that makes Python so enjoyable to use. This is the first program where I've used OO strictly, and so I'm not completely clear why I made them subclasses. I think you're right - they don't need to be. I'll try and make the changes later this evening (UTC), wife permitting ;-) Thanks again Adam -- proj: http://jiletters.sf.net site: http://www.monkeez.org wiki: http://wiki.monkeez.org _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor Any e-mail message from the European Central Bank (ECB) is sent in good faith but shall neither be binding nor construed as constituting a commitment by the ECB except where provided for in a written agreement. This e-mail is intended only for the use of the recipient(s) named above. Any unauthorised disclosure, use or dissemination, either in whole or in part, is prohibited. If you have received this e-mail in error, please notify the sender immediately via e-mail and delete this e-mail from your system. From kent_johnson at skillsoft.com Fri Sep 24 12:10:02 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Fri Sep 24 12:10:10 2004 Subject: [Tutor] Looking for the nomenclature of an HTML "link checker" In-Reply-To: <20040923184538.L8564@yamato.yamato.com> References: <20040923184538.L8564@yamato.yamato.com> Message-ID: <6.1.0.6.0.20040924060853.0287fe78@mail4.skillsoft.com> It's called a link checker. Here is one you might want to look at: http://linkchecker.sourceforge.net/ At 06:48 PM 9/23/2004 -0700, Tony Cappellini wrote: >I'm sure ther eis a python recipe for this, but I don't know wha tthe >correct nomenclature is. > >I'm looking for a Python program that will Walk through all of the links >in an html page, to validate that the ALL of the links are correct (no >typos). > >I'm not looking for an html validator to tell me that an html page doens >tcomply with a spec. > >I want the program to actually go out to the URL, and simulate clicking on >the links, and tell me if any links are broken. > >What is this functionality called ?? > > >thanks > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From kabads at gmail.com Fri Sep 24 12:33:33 2004 From: kabads at gmail.com (Adam Cripps) Date: Fri Sep 24 12:33:37 2004 Subject: [Tutor] Deleting an instance of an object In-Reply-To: <71CEC1FA9395784A826B525D0E1AB21503901E@cimexc21.ecb01.ecb.de> References: <71CEC1FA9395784A826B525D0E1AB21503901E@cimexc21.ecb01.ecb.de> Message-ID: <c7ff385504092403336004ac90@mail.gmail.com> On Fri, 24 Sep 2004 09:46:37 +0200, paul.baines@ecb.int <paul.baines@ecb.int> wrote: > I think it's good to use the phrase "is a" when thinking about > subclassing. A mammal is an animal, so mammal is a subclass of animal, > but "article is an issue" doesn't really make sense, so it's probably > not a good candidate for a subclass. > Again, another excellent tip. This is turning into more than a python tutor list, to a general programming, which I for one need and which is much appreciated. Keep them coming - or perhaps I should put them on the wiki? Adam -- proj: http://jiletters.sf.net site: http://www.monkeez.org wiki: http://wiki.monkeez.org From zsolt.botykai at online.hu Fri Sep 24 15:42:51 2004 From: zsolt.botykai at online.hu (Botykai Zsolt) Date: Fri Sep 24 15:42:53 2004 Subject: [Tutor] regexp help In-Reply-To: <6.1.0.6.0.20040923111059.02a27080@mail4.skillsoft.com> References: <200409221618.50482.zsolt.botykai@online.hu> <200409231625.47869.zsolt.botykai@online.hu> <6.1.0.6.0.20040923111059.02a27080@mail4.skillsoft.com> Message-ID: <200409241542.51649.zsolt.botykai@online.hu> thanx, workx as it should have. Zsoltik@ cs?t?rt?k 23 szeptember 2004 17:26 d?tummal Kent Johnson ezt ?rta: > OK. I suggest you use re.sub() on the match data to remove the blank lines. > So you would use one re to get the data and another one to remove the blank > > lines. For example: > >>> import re > >>> data = ' \n \nhere\nis\n \nsome data\n\nwith\nblank > lines \n \n ' > >>> rx = re.compile(r'(^|\n)\s*(\n|$)') > >>> rx.sub(r'\1', data) > 'here\nis\nsome data\nwith\nblank lines \n' > >>> rx.sub(r'\1', '\n\n\ntest\n\n\n') > 'test\n' > The re to match blank lines is a little tricky because you want to match > ' \n' - a blank line at the beginning > '\n \n' - a blank line in the middle > ' ' - a blank line at the end > > The solution I used was to allow either beginning of string ^ or newline \n > before the blank, and either newline or end of string $ at the end. Then I > replace by whatever matched at the beginning so the blank line at start is > not replaced by a newline itself. > > If your data uses \r\n for newlines you will have to modify the regex a > little bit. > -------------------------------------------------------------------------- Opinions, conclusions and other information in this message that do not relate to the official business of Online Business Technologies Corp. shall be understood as neither given nor endorsed by it. In such cases Online Business Technologies Corp. will not bear the responsibility of consequences. If you have received this communication in error, please notify the system manager immediately by responding to this email and then delete it from your system. A levelben foglalt, nem az Online Rt. hivatalos uzletmenetevel kapcsolatos velemenyek vagy mas informaciok vonatkozasaban az Online Rt. nem vallal felelosseget. Amennyiben a level valamely hiba folytan jutott Onhoz, kerjuk, hogy valaszlevelben azonnal ertesitse a rendszer uzemeltetojet, majd torolje ki a levelet rendszerebol! From barry at angleinc.com Fri Sep 24 18:00:57 2004 From: barry at angleinc.com (Barry Sperling) Date: Fri Sep 24 18:00:00 2004 Subject: [Tutor] Should I learn Python? Message-ID: <415444B9.2040808@angleinc.com> Hello, I want to access an Oracle ( 8i ) database through a webpage in Windows 2000. I have done this in a very clunky manner with pl/sql, but was hoping to use a programming language. I learned enough Ruby to discover that it couldn't be done ( eRuby didn't work on Windows and Rails didn't work with Oracle ). If I learn Python is it possible? A quick pointer to the appropriate tools would also be appreciated ( Cold Fusion is out, for admin reasons. Don't ask :) ) Barry From jonathan.hayward at pobox.com Fri Sep 24 18:15:08 2004 From: jonathan.hayward at pobox.com (Jonathan Hayward) Date: Fri Sep 24 18:16:40 2004 Subject: [Fwd: Re: [Tutor] Re: Willing to look at code?] Message-ID: <4154480C.4090702@pobox.com> I posted a request to look at code, and mistyped the URL. (Thanks, Kent Johnson, for bringing this to my attention.) The correct URL is http://haywardfamily.org/jonathan/searchlog1_0_1b.tar.gz . -- ++ Jonathan Hayward, jonathan.hayward@pobox.com ** To see an award-winning website with stories, essays, artwork, ** games, and a four-dimensional maze, why not visit my home page? ** All of this is waiting for you at http://JonathansCorner.com -------------- next part -------------- An embedded message was scrubbed... From: Kent Johnson <kent_johnson@skillsoft.com> Subject: Re: [Tutor] Re: Willing to look at code? Date: Wed, 22 Sep 2004 17:21:21 -0400 Size: 3033 Url: http://mail.python.org/pipermail/tutor/attachments/20040924/5e535413/Willingtolookatcode.mht From project5 at redrival.net Fri Sep 24 18:59:50 2004 From: project5 at redrival.net (Andrei) Date: Fri Sep 24 19:00:56 2004 Subject: [Tutor] Re: Should I learn Python? References: <415444B9.2040808@angleinc.com> Message-ID: <1wqapitwxofog$.1b8yqw9illntj.dlg@40tude.net> Barry Sperling wrote on Fri, 24 Sep 2004 12:00:57 -0400: > I want to access an Oracle ( 8i ) database through a webpage in Windows > 2000. I have done this in a very clunky manner with pl/sql, but was I have no experience on this matter, but a quick search on Google delivers a module which makes it possible to approach Oracle from Python: http://www.computronix.com/utilities.shtml#Oracle As for the web part, there are plenty of solutions out there, varying from CGI (built into the main library) to things like Zope, modpython, Spyce, Cherrypy, Webware, etc. You can Google for them or have a look at http://www.python.org/cgi-bin/moinmoin/WebProgramming -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From jonathan.hayward at pobox.com Fri Sep 24 21:17:41 2004 From: jonathan.hayward at pobox.com (Jonathan Hayward) Date: Fri Sep 24 21:19:12 2004 Subject: [Tutor] Found one error Message-ID: <415472D5.5020608@pobox.com> The program I requested had a == in what should have been an assignment question. I may ask for further help, but I'm going to see what I could do with that fixed. -- ++ Jonathan Hayward, jonathan.hayward@pobox.com ** To see an award-winning website with stories, essays, artwork, ** games, and a four-dimensional maze, why not visit my home page? ** All of this is waiting for you at http://JonathansCorner.com From jonathan.hayward at pobox.com Fri Sep 24 21:32:31 2004 From: jonathan.hayward at pobox.com (Jonathan Hayward) Date: Fri Sep 24 21:34:02 2004 Subject: [Tutor] List comparisons Message-ID: <4154764F.9020609@pobox.com> Is there a good way to tell if a potential sublist is in another list? I'm doing the following: for index in range(len(document_tokens) - len(self.tokenized)): if document_tokens[index:index + len(self.tokenized)] == \ self.tokenized: match_found = 1 but that seems lower level than one would expect of Python. -- ++ Jonathan Hayward, jonathan.hayward@pobox.com ** To see an award-winning website with stories, essays, artwork, ** games, and a four-dimensional maze, why not visit my home page? ** All of this is waiting for you at http://JonathansCorner.com From cmeesters at ucdavis.edu Fri Sep 24 22:36:50 2004 From: cmeesters at ucdavis.edu (Christian Meesters) Date: Fri Sep 24 22:36:54 2004 Subject: [Tutor] OSX and installation of new Python versions Message-ID: <76318685-0E69-11D9-B430-000393D8EC3A@ucdavis.edu> Hi Is there a way to install 2.4 or 2.3.4 on the Mac (OSX 10.3.5) so that there is only one Python version? I would prefer version 2.4, because I'd like to use at least one of the new features (easy sorting of dictionaries for keys). But the reason I'm asking is actually that is becomes highly annoying to have the Mac preinstalled Python version (2.3) always present, whereas any other version explicitly has to be called with the full path. Installing third party modules like wxPython and numarray isn't fun this way. Not knowing whether wxPython would run with Python 2.4, I might have to live with 2.3.4, but that's ok (for most of my purposes 2.3.2 would be ok). Any ideas how to achieve all this? (Parameters during setup and compiling?) Frankly: The MacPython FAQ didn't help me any further and I fear I have to live with this until Apple will include an updated version in its OS. Or do I? And one last question: If there is any solution - what will be the impact on pythonw? Thanks Christian From kent_johnson at skillsoft.com Sat Sep 25 03:26:42 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sat Sep 25 03:28:51 2004 Subject: [Tutor] wave.readframes() (or conversion?) In-Reply-To: <333E0C85-0D4D-11D9-A089-0003939C968C@unito.it> References: <333E0C85-0D4D-11D9-A089-0003939C968C@unito.it> Message-ID: <6.1.0.6.0.20040924211913.028b9638@mail4.skillsoft.com> You can use the struct module to do this. You will have to find out whether the wave data is stored in big-endian or little-endian format. >>> import struct >>> hex(32000) '0x7d00' >>> d='\x7d\x00\x00\x00' >>> struct.unpack('<hh', d) (125, 0) >>> struct.unpack('>hh', d) (32000, 0) Kent At 12:42 PM 9/23/2004 +0200, andrea valle wrote: >Hi to all, >I'm using wave module with success. I'm writing data to wave file. >Typically I create a list of values (data) and pass it to >.writeframes(data) methods. > >a = wave.open("/test.wav", "w") >a.writeframes([32000, 0]) > >This sets the first sample to 32000 and the 2nd to 0 > >But when I use the .readframes() method I don't know exactly what >values I extract from the open wave. > > >>> a = wave.open("/test.wav", "r") > >>> a.readframes(1) >'\x00\x00' > >How do I convert it to an integer? I'd like to have it like 32000 or 0, so >to make some maths on it. > >Thanks a lot > >-a- > >Andrea Valle >Laboratorio multimediale "G. Quazza" >Facolt? di Scienze della Formazione >Universit? degli Studi di Torino >andrea.valle@unito.it >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From andrea.valle at unito.it Sat Sep 25 08:29:55 2004 From: andrea.valle at unito.it (andrea valle) Date: Sat Sep 25 08:30:00 2004 Subject: [Tutor] wave.readframes() (or conversion?) In-Reply-To: <6.1.0.6.0.20040924211913.028b9638@mail4.skillsoft.com> References: <333E0C85-0D4D-11D9-A089-0003939C968C@unito.it> <6.1.0.6.0.20040924211913.028b9638@mail4.skillsoft.com> Message-ID: <50E28A60-0EBC-11D9-A0CE-0003939C968C@unito.it> Thanks a lot, I will try as soon as I can. Best -a- On 25 Sep 2004, at 03:26, Kent Johnson wrote: > You can use the struct module to do this. You will have to find out > whether the wave data is stored in big-endian or little-endian format. > > >>> import struct > >>> hex(32000) > '0x7d00' > >>> d='\x7d\x00\x00\x00' > >>> struct.unpack('<hh', d) > (125, 0) > >>> struct.unpack('>hh', d) > (32000, 0) > > Kent > > At 12:42 PM 9/23/2004 +0200, andrea valle wrote: >> Hi to all, >> I'm using wave module with success. I'm writing data to wave file. >> Typically I create a list of values (data) and pass it to >> .writeframes(data) methods. >> >> a = wave.open("/test.wav", "w") >> a.writeframes([32000, 0]) >> >> This sets the first sample to 32000 and the 2nd to 0 >> >> But when I use the .readframes() method I don't know exactly what >> values I extract from the open wave. >> >> >>> a = wave.open("/test.wav", "r") >> >>> a.readframes(1) >> '\x00\x00' >> >> How do I convert it to an integer? I'd like to have it like 32000 or >> 0, so to make some maths on it. >> >> Thanks a lot >> >> -a- >> >> Andrea Valle >> Laboratorio multimediale "G. Quazza" >> Facolt? di Scienze della Formazione >> Universit? degli Studi di Torino >> andrea.valle@unito.it >> _______________________________________________ >> Tutor maillist - Tutor@python.org >> http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > Andrea Valle Laboratorio multimediale "G. Quazza" Facolt? di Scienze della Formazione Universit? degli Studi di Torino andrea.valle@unito.it From alipolatel at yahoo.com Sat Sep 25 10:45:06 2004 From: alipolatel at yahoo.com (Ali Polatel) Date: Sat Sep 25 10:45:09 2004 Subject: [Tutor] A request Message-ID: <20040925084506.72331.qmail@web61010.mail.yahoo.com> Dear Python Programmers, I have a request from a Python programmer who can do me a favor... This year I'll graduate from my high-school... I'll host a chat-server so that we will be able to chat as all friends will leave the city to go to different universities... I was looking around if there is one written in Python...I found this below: " # A simple "chat" server. Creates a server on port 4000.# Users telnet to your machine, port 4000, and can chat with each# other. Use "quit" to disconnect yourself, and "shutdown" to# shut down the server. Requires sockets.## 7/31/96 J. Strout http://www.strout.net/# import needed modules:from socket import * # get sockets, for well, socketsimport string # string functionsimport time # for sleep(1) function# define global variablesHOST = '' # Symbolic name meaning the local hostPORT = 4000 # Arbitrary non-privileged serverendl = "\r\n" # standard terminal line endinguserlist = [] # list of connected usersdone = 0 # set to 1 to shut this downkAskName = 0 # some constants used to flagkWaitName = 1 # the state of each userkOK = 2# class to store info about connected usersclass User: def __init__(self): self.name = "" self.addr = "" self.conn = None self.step = kAskName def Idle(self): if self.step == kAskName: self.AskName() def AskName(self): self.conn.send("Name? ") self.step = kWaitName def HandleMsg(self, msg): print "Handling message: ",msg global userlist # if waiting for name, record it if self.step == kWaitName: # try to trap garb initiall sent by some telnets: if len(msg) < 2 or msg=="#": return print "Setting name to: ",msg self.name = msg self.step = kOK self.conn.send("Hello, "+self.name+endl) broadcast(self.name+" has connected."+endl) return # check for commands if msg == "quit": broadcast(self.name+" has quit.\n") self.conn.close() userlist.remove(self) return # otherwise, broadcast msg broadcast( self.name+": "+msg+endl )# routine to check for incoming connectionsdef pollNewConn(): try: conn, addr = s.accept() except: return None print "Connection from", addr conn.setblocking(0) user = User(); user.conn = conn user.addr = addr return user# routine to broadcast a message to all connected usersdef broadcast(msg): for u in userlist: u.conn.send(msg)# MAIN PROGRAM# set up the servers = socket(AF_INET, SOCK_STREAM)s.bind(HOST, PORT)s.setblocking(0)s.listen(1)print "Waiting for connection(s)..."# loop until done, handling connections and incoming messageswhile not done: time.sleep(1) # sleep to reduce processor usage u = pollNewConn() # check for incoming connections if u: userlist.append(u) print len(userlist),"connection(s)" for u in userlist: # check all connected users u.Idle() try: data = u.conn.recv(1024) data = filter(lambda x: x>=' ' and x<='z', data) data = string.strip(data) if data: print "From",u.name,': ['+data+']' u.HandleMsg(data) if data == "shutdown": done=1 except: passfor u in userlist: u.conn.close()" But this is too primitive to be a chat server I believe... I have really no time to make it better... Can any of you add it some functions? like adding admin functions,and other chat functions that you can dream of and make it similar to an IRC channel... I'll appreciate any kind of help... Regards and thanks all, Ali Polatel --------------------------------- Do you Yahoo!? New and Improved Yahoo! Mail - 100MB free storage! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040925/12313657/attachment.htm From project5 at redrival.net Sat Sep 25 10:49:23 2004 From: project5 at redrival.net (Andrei) Date: Sat Sep 25 10:50:29 2004 Subject: [Tutor] Re: List comparisons References: <4154764F.9020609@pobox.com> Message-ID: <76rsbnj93rw7$.csjqz3gupv76$.dlg@40tude.net> Jonathan Hayward wrote on Fri, 24 Sep 2004 14:32:31 -0500: > Is there a good way to tell if a potential sublist is in another list? Assuming that you want to know if the elements in the one list appear in that particular order in the other list, I can't think of a better way to do it - unless the elements happen to be chars, in which case you could covert the list to a string and use the find() method. You might also consider - if speed is an issue - using the index() method of the superlist to locate occurences of the first item of the sublist and only test starting at those occurences a subslice for equality. This should save you some Python looping. You could also break your loop at the first match. Or you could do something like this: >>> def findsub(sub, full): ... L = len(sub) ... matches = [ i for i in range(len(full)) if sub == full[i:i+L] ] ... return matches >>> findsub([1,2], [0,1,2,3]) [1] >>> findsub([4], [0,1,2,3]) [] >>> findsub([1,2], [0,1,2,3,1,2,1,2]) [1, 4, 6] This has the advantage - if you need it - that it also gives you the location of the sublists in the full list, while you can still use its results in a boolean context. But your solution seems good to me and unless you have other concerns (like speed or position of the matches), I wouldn't bother changing it. > but that seems lower level than one would expect of Python. Getting in a single line/loop the positions of all occurences of a sublist inside another list seems pretty high-level to me :). -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From Frank at snapafun.co.nz Sat Sep 25 10:56:25 2004 From: Frank at snapafun.co.nz (SnapafunFrank) Date: Sat Sep 25 10:52:34 2004 Subject: [Tutor] webbrowser.Error: could not locate runnable browser Message-ID: <415532B9.1020008@snapafun.co.nz> Hi New here and to python. The subject is my current problem with blender <Help Menu> and this site is the only one I have found that has made any mention of it. ( The only one listed in a search using www.vivisimo.com ). Your thread: http://mail.python.org/pipermail/tutor/2003-September/025151.html applies. It seems by this thread that there is a fix but as a newbie I have no idea where to look to install the syntax. [ eg. Quote............. <snipped> Tracking it down, it appears that the "BROWSER" key of the os.environ dictionary is used. Under Gnome, this is defined as '/usr/bin/galeon'. Under KDE, it's 'kfmclient openProfile webbrowsing'. I have no idea what that's supposed to mean - whatever it does, it doesn't start the browser. However, if we change this to "konqueror" before importing the webbrowser module, it works: === import os if os.environ["BROWSER"] == 'kfmclient openProfile webbrowsing': os.environ["BROWSER"] = "konqueror" import webbrowser webbrowser.open("http://google.com") ] <http://google.com%22> Anyone care to entertain an old tinkerer and help me get this prob dealt to? -- Regards SnapafunFrank Big or small, a challenge requires the same commitment to resolve. Registered Linux User # 324213 From project5 at redrival.net Sat Sep 25 10:57:29 2004 From: project5 at redrival.net (Andrei) Date: Sat Sep 25 10:58:31 2004 Subject: [Tutor] Re: A request References: <20040925084506.72331.qmail@web61010.mail.yahoo.com> Message-ID: <1d903o8xi2o3y.q57xnpn1085u$.dlg@40tude.net> Ali Polatel wrote on Sat, 25 Sep 2004 01:45:06 -0700 (PDT): > I have a request from a Python programmer who can do me a favor... > This year I'll graduate from my high-school... <snip> > But this is too primitive to be a chat server I believe... I have a question: why don't you do it yourself? Learn Python and work on it. > I have really no time to make it better... Ah, there's the reason. Fortunately everyone else (the people with, you know, jobs, or w/o jobs but with plenty of projects of their own) has loads of spare time. :) > I'll appreciate any kind of help... If you can't be bothered to learn Python and DIY, why don't you use IRC or Jabber or MSN or ICQ or Yahoo chat? -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From project5 at redrival.net Sat Sep 25 11:05:56 2004 From: project5 at redrival.net (Andrei) Date: Sat Sep 25 11:06:58 2004 Subject: [Tutor] Re: webbrowser.Error: could not locate runnable browser References: <415532B9.1020008@snapafun.co.nz> Message-ID: <1eyubtvldxb4l.3x112utqhyrh.dlg@40tude.net> SnapafunFrank wrote on Sat, 25 Sep 2004 20:56:25 +1200: Hi, > The subject is my current problem with blender <Help Menu> and this site > is the only one I have found that has made any mention of it. ( The only > one listed in a search using www.vivisimo.com ). > > Your thread: > http://mail.python.org/pipermail/tutor/2003-September/025151.html applies. <snip> > Anyone care to entertain an old tinkerer and help me get this prob dealt to? Being the one with the problem at the time, I can tell you that it occurs under KDE, where the BROWSER environment variable is set to some very weird string, which will in fact not launch the browser. What you should do is locate the "import webbrowser" string in the Blender code (*.py) and place in front of it the following code. Note that Python is indentation-sensitive, so the indentation needs to start from the same level where "import webbrowser" starts. if os.environ.has_key("BROWSER") and \ os.environ["BROWSER"]=='kfmclient openProfile webbrowsing': os.environ["BROWSER"] = 'konqueror' # set it to konqueror import webbrowser # MUST be imported only AFTER os.environ modified -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From alipolatel at yahoo.com Sat Sep 25 11:07:01 2004 From: alipolatel at yahoo.com (Ali Polatel) Date: Sat Sep 25 11:07:04 2004 Subject: [Tutor] Re: A request In-Reply-To: <1d903o8xi2o3y.q57xnpn1085u$.dlg@40tude.net> Message-ID: <20040925090701.31612.qmail@web61002.mail.yahoo.com> I have no time and with Python it will be more practical I believe __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040925/90492c10/attachment.html From kalle at lysator.liu.se Sat Sep 25 12:06:06 2004 From: kalle at lysator.liu.se (Kalle Svensson) Date: Sat Sep 25 12:06:05 2004 Subject: [Tutor] Re: A request In-Reply-To: <20040925090701.31612.qmail@web61002.mail.yahoo.com> References: <1d903o8xi2o3y.q57xnpn1085u$.dlg@40tude.net> <20040925090701.31612.qmail@web61002.mail.yahoo.com> Message-ID: <20040925100606.GE6665@i92.ryd.student.liu.se> Hello! [Ali Polatel] > I have no time and with Python it will be more practical I believe I think you're wrong. For common tasks, and setting up a chat environment is a common task, writing your own software is rarely better than using something that's already available. Whether it's implemented in Python or not is a minor detail. I'd suggest that you set up a channel on some IRC network. The administration involved for you is close to zero, and IRC clients are common and easy to install. Peace, Kalle -- http://juckapan.org/~kalle/ http://laxmasteriet.se/04-05/ From vibrations at cetlink.net Sat Sep 25 12:55:03 2004 From: vibrations at cetlink.net (SGD) Date: Sat Sep 25 12:55:10 2004 Subject: [Tutor] Re: A request In-Reply-To: <20040925090701.31612.qmail@web61002.mail.yahoo.com> Message-ID: <000d01c4a2ee$1cecbe90$0100a8c0@whiterhino2> I've never used this so I nothing about it, but I've heard a few nice things about achat... http://opensource.aventus.nu/4.php?HIST=,1 -----Original Message----- From: Ali Polatel [mailto:alipolatel@yahoo.com] Sent: Saturday, September 25, 2004 5:07 AM To: project5@redrival.net; tutor@python.org Subject: Re: [Tutor] Re: A request I have no time and with Python it will be more practical I believe __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From jonathan.hayward at pobox.com Sat Sep 25 16:54:15 2004 From: jonathan.hayward at pobox.com (Jonathan Hayward) Date: Sat Sep 25 16:55:47 2004 Subject: [Tutor] Search tool Message-ID: <41558697.1070803@pobox.com> I found out what was causing the bug I was struggling with in the tool I was working on. At present the search engine is intended to allow any of three basic operations, and any appropriate combination: 1: Keyword, with "*" wildcard allowed ("read*" should match read, reads, readable, reading, etc.). 2: Boolean, allowing and, or, not, and parentheses. 3: Quotations enclosed in double quotes. Right now everything but the wildcard works, but they don't work together. I'd like to have them all working, and working when you use them together. If you could look at http://haywardfamily.org/jonathan/searchlog1_0_1_b.tar.gz , I'd appreciate it. -- ++ Jonathan Hayward, jonathan.hayward@pobox.com ** To see an award-winning website with stories, essays, artwork, ** games, and a four-dimensional maze, why not visit my home page? ** All of this is waiting for you at http://JonathansCorner.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040925/a28524a4/attachment.htm From bgailer at alum.rpi.edu Sat Sep 25 18:29:09 2004 From: bgailer at alum.rpi.edu (Bob Gailer) Date: Sat Sep 25 18:28:20 2004 Subject: [Tutor] Should I learn Python? In-Reply-To: <415444B9.2040808@angleinc.com> References: <415444B9.2040808@angleinc.com> Message-ID: <6.1.2.0.0.20040925102505.039d1ab8@mail.mric.net> At 10:00 AM 9/24/2004, Barry Sperling wrote: >Hello, > I want to access an Oracle ( 8i ) database through a webpage in > Windows 2000. I have done this in a very clunky manner with pl/sql, > but was hoping to use a programming language. Having worked with pl/sql I consider it to be a programming language. In what ways does it fall short for you, and why would you not consider it to be a programming language? I have used Computronix's cx_oracle http://www.computronix.com/utilities.shtml#Oracle with no problem to access Oracle databases. With it you can do SQL as well as (send and) invoke pl/sql programs. Bob Gailer bgailer@alum.rpi.edu 303 442 2625 home 720 938 2625 cell From s4046441 at student.uq.edu.au Sat Sep 25 21:08:52 2004 From: s4046441 at student.uq.edu.au (Ms Soo Chong) Date: Sat Sep 25 21:08:59 2004 Subject: [Tutor] Please advice me on my code Message-ID: <5f87d05f7aca.5f7aca5f87d0@uq.edu.au> Hi all, First, thanks for your reply (jonahfish & Danny) regarding calling help @ Brisbane. Can anyone please help me to go thru the attached files. They are quite similar and intend to serve the same purpose. I know that they are absolutely wrong but I just wanna to show my idea of approaching as I don't know the correct way of coding it, thus I need someone to guide me thru. I hope there is someone can understand what I trying to put across... though is very crappy. Details: (the simplest case I can think of)I wanna a web page that show a radio button named shot number and a textarea. When the user select the radio button and type a number in the textarea and press search, my python program process it by sending the query to the PostgreSQL database and response by displaying the results back to the web browser. Any help is greatly appreciated. Thank you. Shufen -------------- next part -------------- A non-text attachment was scrubbed... Name: search.py Type: application/octet-stream Size: 2858 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20040926/2645c0b8/search.obj -------------- next part -------------- A non-text attachment was scrubbed... Name: try1.py Type: application/octet-stream Size: 2005 bytes Desc: not available Url : http://mail.python.org/pipermail/tutor/attachments/20040926/2645c0b8/try1.obj From csmwxl at bath.ac.uk Sat Sep 25 23:04:55 2004 From: csmwxl at bath.ac.uk (W X Liu) Date: Sat Sep 25 23:04:59 2004 Subject: [Tutor] A problem in read_until(expected[,timeout]) Message-ID: <1096146295.4155dd7738294@webmail.bath.ac.uk> Hello, I want use read_until object to interact with telnet. The problem is that if I just want to match the expected string, then it will be fine. code would be read_until(expected) But if I want to just want to match the timeout seconds, I don't know how to write it. I code it as read_until([,seconds]) Then invalid syntax occurs. Or if I add a expected string together with timeout, then I code it as read_until(ten [,10]) ten is the string I want to match, and 10 is the expected timeout second, butinvalid syntax occurs again. So anyone can help me to solve this? Many thanks Wenxin From pythonTutor at venix.com Sat Sep 25 23:38:37 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Sat Sep 25 23:39:11 2004 Subject: [Tutor] A problem in read_until(expected[,timeout]) In-Reply-To: <1096146295.4155dd7738294@webmail.bath.ac.uk> References: <1096146295.4155dd7738294@webmail.bath.ac.uk> Message-ID: <1096148317.3154.171.camel@laptop.venix.com> I think this should work: obj.read_until(timeout=10) # no expect string or obj.read_until("ten",10) # "ten" or 10 seconds read_until is a method of the telnet object so your code should have the name you gave the telnet object before the read_until. I used obj simply to indicate there should be some name there. The documentation can be confusing because it uses [] to mark optional parameters while Python uses [] to mark lists. When you do not need all of the arguments, you can specify the names of the arguments that you want to use. That's why timeout=10 should work in the first suggestion. On Sat, 2004-09-25 at 17:04, W X Liu wrote: > Hello, > > I want use read_until object to interact with telnet. The problem is that if I > just want to match the expected string, then it will be fine. code would be > > read_until(expected) > > But if I want to just want to match the timeout seconds, I don't know how to > write it. > > I code it as > > read_until([,seconds]) > > Then invalid syntax occurs. Or if I add a expected string together with > timeout, then I code it as > > read_until(ten [,10]) > > ten is the string I want to match, and 10 is the expected timeout second, > butinvalid syntax occurs again. So anyone can help me to solve this? Many thanks > > > Wenxin > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From rdm at rcblue.com Sun Sep 26 06:08:14 2004 From: rdm at rcblue.com (Dick Moores) Date: Sun Sep 26 06:09:19 2004 Subject: [Tutor] large number question Message-ID: <6.1.2.0.2.20040925194232.04457880@rcblue.com> I've written a program that will take a range of integers and tell me which are prime, and also tell me the prime factors of the non-primes (reinventing the wheel). It works well and efficiently, I believe, but I'm wondering if there's a way around the apparent limit on the size of integers. If I enter anything larger than about 4,610,000,000,000,000,000 (4 quintillion, 610 quadrillion in American English), I get "OverflowError: long int too large to convert to int" I won't attach my program here, but an obviously important function is ================================ def isPrime(n): """returns True if n is prime; False if not""" prime = True if n < 2: prime = False else: for x in xrange(2,int(n**.5 + 1)): if n % x == 0: prime = False break return prime ============================== If I use just isPrime alone, I get the same error message. Where does this limit come from? From Python? From Windows XP? From Dell (which made my computer)? Python v2.3.4, Windows XP. Thanks, tutors. Dick Moores rdm@rcblue.com From Frank at snapafun.co.nz Sun Sep 26 06:49:19 2004 From: Frank at snapafun.co.nz (SnapafunFrank) Date: Sun Sep 26 06:45:17 2004 Subject: [Tutor] Re: webbrowser.Error: could not locate runnable Re: webbrowser.Error: could not locate running browser In-Reply-To: <20040925100044.948501E4015@bag.python.org> References: <20040925100044.948501E4015@bag.python.org> Message-ID: <41564A4F.5070401@snapafun.co.nz> Message: 6 Date: Sat, 25 Sep 2004 11:05:56 +0200 From: Andrei <project5@redrival.net> Subject: [Tutor] Re: webbrowser.Error: could not locate runnable browser To: tutor@python.org Message-ID: <1eyubtvldxb4l.3x112utqhyrh.dlg@40tude.net> Content-Type: text/plain; charset="us-ascii" SnapafunFrank wrote on Sat, 25 Sep 2004 20:56:25 +1200: Hi, >> The subject is my current problem with blender <Help Menu> and this site >> is the only one I have found that has made any mention of it. ( The only >> one listed in a search using www.vivisimo.com ). >> >> Your thread: >> http://mail.python.org/pipermail/tutor/2003-September/025151.html applies. <snip> >> Anyone care to entertain an old tinkerer and help me get this prob dealt to? >Being the one with the problem at the time, I can tell you that it occurs >under KDE, where the BROWSER environment variable is set to some very weird >string, which will in fact not launch the browser. What you should do is >locate the "import webbrowser" string in the Blender code (*.py) and place >in front of it the following code. >Note that Python is indentation-sensitive, so the indentation needs to >start from the same level where "import webbrowser" starts. >if os.environ.has_key("BROWSER") and \ > os.environ["BROWSER"]=='kfmclient openProfile webbrowsing': > os.environ["BROWSER"] = 'konqueror' # set it to konqueror >import webbrowser # MUST be imported only AFTER os.environ modified >-- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va >choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. Thanks Andrei, I found it in the "help_web_devcomm.py" file. I now have the Help option showing me the 'About - " screen and doing some benchmark test -- ( I'll get there! ) I just need to go back there and figure out why I'm not getting the "web links" to show, though I think it may well be that I'm using a PIII with a C-Media 16MB card and not a python script 'to-do'. -- Regards SnapafunFrank Big or small, a challenge requires the same commitment to resolve. Registered Linux User # 324213 From isrgish at fastem.com Sun Sep 26 07:02:12 2004 From: isrgish at fastem.com (Isr Gish) Date: Sun Sep 26 07:02:30 2004 Subject: [Tutor] *.rar decompress Message-ID: <20040926050229.0519B1E4003@bag.python.org> Hi Jimmy, After taking a look at your module, I see it needs ctypes. I'm working on a Pocket PC, and as far as I know ctypes wasn't ported to the pocket PC. So now I'm looking for a different option to be able to decompress *.rar file. Can someone give a pointer to this. Thanks All the best, Isr -----Original Message----- >From: "Jimmy Retzlaff"<jimmy@retzlaff.com> >Sent: 9/22/04 6:57:30 AM >To: "Isr Gish"<isrgish@fastem.com> >Cc: "Tutor"<tutor@python.org>, "Danny Yoo"<dyoo@hkn.eecs.berkeley.edu> >Subject: RE: [Tutor] *.rar decompress >Danny Yoo wrote: >> On Wed, 22 Sep 2004, Isr Gish wrote: >> >> > I'm looking to decompress *.rar files. >> > Does anyone know of a way to do that in python. >> >> I googled around, and found a third-party library for dealing with RAR >> files: >> >> http://www.averdevelopment.com/python/UnRAR.html >> >> Oh, it's Jimmy's module! That's cool! He's a regular at the Bay Area >> Python Interest Group (http://baypiggies.net). Let me just CC him so >he >> knows that I'm plugging his module. *grin* > >Yep, that's me! I'm not on the Tutor list so it's nice that you copied >me. > >> RAR appears to be a compression format used on the Windows platform, >so, >> unfortunately, I can't test his module very easily. Does anyone else >have >> experience with it? > >I have a little experience with it. :) I've been using it on and off >for almost 2 years (I used it for quite a while as it evolved before I >released it). I've also corresponded with a few others who are using it >successfully. If you try it and have any problems, please let me know. >If you don't have any problems using it, I enjoy hearing about that too. >;) > >There are also freely available implementations of command line unrar >utilities that you could call from Python. Many platforms are covered by >the author of RAR and contributors at: > >http://www.rarlab.com/rar_add.htm > >When I have some time, I plan to make another release of pyUnRAR - >hopefully in the next couple of weeks. I haven't heard of any bugs since >I released 0.1 over a year ago so I'll probably call it 1.0. The only >change planned in the next release is the ability to access the >dates/times of files within the archive which I added at the request of >a user. > >Jimmy > From kent_johnson at skillsoft.com Sun Sep 26 14:21:11 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Sun Sep 26 14:21:22 2004 Subject: [Tutor] large number question In-Reply-To: <6.1.2.0.2.20040925194232.04457880@rcblue.com> References: <6.1.2.0.2.20040925194232.04457880@rcblue.com> Message-ID: <6.1.0.6.0.20040926081339.028b8480@mail4.skillsoft.com> The problem is that xrange requires an int argument; it is the call to xrange() that is generating the error: >>> import sys >>> sys.maxint 2147483647 >>> for i in xrange(2,2147483648L): ... pass ... Traceback (most recent call last): File "<stdin>", line 1, in ? OverflowError: long int too large to convert to int >>> for i in xrange(2,2147483647L): ... pass ... (wait a while and ^C) Traceback (most recent call last): File "<stdin>", line 1, in ? KeyboardInterrupt One solution is to rewrite your loop to compute the index yourself: x = 2 limit = int(n**.5 + 1) while x < limit if n % x == 0: prime = False break x += 1 or write your own generator function that does the same thing as xrange: >>> def longRange(beg,end): ... val = beg ... while val < end: ... yield val ... val += 1 ... >>> list(longRange(2147483640, 2147483649L)) [2147483640, 2147483641, 2147483642, 2147483643, 2147483644, 2147483645, 2147483646, 2147483647, 2147483648L] The first solution is likely to be faster. Kent At 09:08 PM 9/25/2004 -0700, Dick Moores wrote: >I've written a program that will take a range of integers and tell me >which are prime, and also tell me the prime factors of the non-primes >(reinventing the wheel). It works well and efficiently, I believe, but I'm >wondering if there's a way around the apparent limit on the size of >integers. If I enter anything larger than about 4,610,000,000,000,000,000 >(4 quintillion, 610 quadrillion in American English), I get >"OverflowError: long int too large to convert to int" > >I won't attach my program here, but an obviously important function is >================================ >def isPrime(n): > """returns True if n is prime; False if not""" > prime = True > if n < 2: > prime = False > else: > for x in xrange(2,int(n**.5 + 1)): > if n % x == 0: > prime = False > break > return prime >============================== > >If I use just isPrime alone, I get the same error message. Where does this >limit come from? From Python? From Windows XP? From Dell (which made my >computer)? > >Python v2.3.4, Windows XP. > >Thanks, tutors. > >Dick Moores >rdm@rcblue.com > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From project5 at redrival.net Sun Sep 26 14:24:35 2004 From: project5 at redrival.net (Andrei) Date: Sun Sep 26 14:25:38 2004 Subject: [Tutor] Re: large number question References: <6.1.2.0.2.20040925194232.04457880@rcblue.com> Message-ID: <1x87o5emvqcuz$.1aiinklhnea71$.dlg@40tude.net> Dick Moores wrote on Sat, 25 Sep 2004 21:08:14 -0700: <snip> > I'm wondering if there's a way around the apparent limit on the size of > integers. If I enter anything larger than about 4,610,000,000,000,000,000 > (4 quintillion, 610 quadrillion in American English), I get > "OverflowError: long int too large to convert to int" <snip> The nice thing is that Python shows you *exactly* where the error occurs in a traceback, but you didn't provide that information. I think the xrange function doesn't like very large integers. I don't know where the limit of 4.6e18 comes from though. For me it refuses to work from 2**31 onward (2.15e9), which is basically what you'd expect on a 32-bit system. You'll probably want to write your own iterator for this purpose instead of using xrange, e.g. (without input validation, but you can add that if you want it): >>> def HugeNumberIterator(start, stop): ... i = start ... while i<stop: ... yield i ... i += 1 And then you can do something like: >>> for i in HugeNumberIterator(int(2e35), int(2e35)+5): ... print i <snip output> This should work with virtually any number, as long as it fits in your system's memory. -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From rschroev_nospam_ml at fastmail.fm Sun Sep 26 15:01:06 2004 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sun Sep 26 15:01:16 2004 Subject: [Tutor] Re: large number question In-Reply-To: <1x87o5emvqcuz$.1aiinklhnea71$.dlg@40tude.net> References: <6.1.2.0.2.20040925194232.04457880@rcblue.com> <1x87o5emvqcuz$.1aiinklhnea71$.dlg@40tude.net> Message-ID: <cj6eij$6ur$1@sea.gmane.org> Andrei wrote: > Dick Moores wrote on Sat, 25 Sep 2004 21:08:14 -0700: > >>I'm wondering if there's a way around the apparent limit on the size of >>integers. If I enter anything larger than about 4,610,000,000,000,000,000 >>(4 quintillion, 610 quadrillion in American English), I get >>"OverflowError: long int too large to convert to int" > > The nice thing is that Python shows you *exactly* where the error occurs in > a traceback, but you didn't provide that information. I think the xrange > function doesn't like very large integers. I don't know where the limit of > 4.6e18 comes from though. For me it refuses to work from 2**31 onward > (2.15e9), which is basically what you'd expect on a 32-bit system. That's easy: the 4.6e18 is not the input to xrange; xrange sees the square root of that (plus one to be precise), which happens to be relatively close to 2**31: >>> 4.6e18**.5 + 1 2144761059.9527216 >>> 2**31 2147483648L >>> (4.6e18**.5+1)/2**31 0.99873219614509567 -- "Codito ergo sum" Roel Schroeven From project5 at redrival.net Sun Sep 26 18:05:51 2004 From: project5 at redrival.net (Andrei) Date: Sun Sep 26 18:06:59 2004 Subject: [Tutor] Re: large number question References: <6.1.2.0.2.20040925194232.04457880@rcblue.com> <1x87o5emvqcuz$.1aiinklhnea71$.dlg@40tude.net> <cj6eij$6ur$1@sea.gmane.org> Message-ID: <dwx0kljojti0$.ftjpravkzkhq$.dlg@40tude.net> Roel Schroeven wrote on Sun, 26 Sep 2004 15:01:06 +0200: > That's easy: the 4.6e18 is not the input to xrange; xrange sees the > square root of that (plus one to be precise), which happens to be > relatively close to 2**31: Duh, that's what I get from not reading the code properly. Thanks. -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From isrgish at fastem.com Mon Sep 27 02:49:48 2004 From: isrgish at fastem.com (Isr Gish) Date: Mon Sep 27 02:50:07 2004 Subject: [Tutor] *.rar decompress Message-ID: <20040927005005.1886E1E4003@bag.python.org> Thanks Jimmy (see below) -----Original Message----- >From: "Jimmy Retzlaff"<jimmy@retzlaff.com> >Sent: 9/26/04 4:34:00 AM >To: "Isr Gish"<isrgish@fastem.com> >Cc: "tutor@python.org"<tutor@python.org> >Subject: RE: [Tutor] *.rar decompress >Isr Gish wrote: >> After taking a look at your module, I see it needs ctypes. I'm working >on >> a Pocket PC, and as far as I know ctypes wasn't ported to the pocket >PC. >> So now I'm looking for a different option to be able to decompress >*.rar >> file. Can someone give a pointer to this. > >The WinRAR site offers a GUI de-compressor for Pocket PC. I've never >done any Pocket PC programming, so I have no idea how hard it would be >to control a GUI from Python or any other language there. I wouldn't know how to control a GUI from python on any platform. I'm a relative newbee. > >Does the port of Python you're using on the Pocket PC have the zip >module? If so, could you convert the RAR to Zip on the PC before it gets >to the mobile device and then use the zip module there? It has the zip module, but I have a lot of .rar files. And the zip compression is much large. (the Pocket PC doesn't have much space to begin with.) > >There is also "portable" C code for decompression on the WinRAR site - >you could try compiling that for the Pocket PC and wrapping it up as a >Python extension. I'll have a look at this. But I don't have much hope, because I never compiled anything before. You never know there is always a first. Thanks again and all the best, Isr > >Jimmy > From tktucker at gmail.com Mon Sep 27 05:58:59 2004 From: tktucker at gmail.com (Tom Tucker) Date: Mon Sep 27 05:59:03 2004 Subject: [Tutor] What am I missing? Message-ID: <2a278ffe040926205866e40963@mail.gmail.com> Good evening! Any thoughts on this one? The goal is to 'tail -f /var/log/messages' and if the line contains "CROND" for example, then print that line. The below script does a great job of tailing and printing, but it prints EVERYTHING. ################## #!/usr/bin/python import os, re findme = re.compile('CROND') logfile = os.system('tail -f /var/log/messages') for line in logfile: found = re.search(findme, line) if found: print line, else: print "not found" #################### Thanks, Tom From bvande at po-box.mcgill.ca Mon Sep 27 06:32:46 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Mon Sep 27 06:33:01 2004 Subject: [Tutor] What am I missing? In-Reply-To: <2a278ffe040926205866e40963@mail.gmail.com> References: <2a278ffe040926205866e40963@mail.gmail.com> Message-ID: <415797EE.1010401@po-box.mcgill.ca> Tom Tucker said unto the world upon 2004-09-26 23:58: > Good evening! Any thoughts on this one? > > The goal is to 'tail -f /var/log/messages' and if the line contains > "CROND" for example, then print that line. The below script does a > great job of tailing and printing, but it prints EVERYTHING. > > ################## > #!/usr/bin/python > > import os, re > > findme = re.compile('CROND') > logfile = os.system('tail -f /var/log/messages') > for line in logfile: > found = re.search(findme, line) > if found: > print line, > else: > print "not found" > #################### > > > Thanks, > > Tom Hi Tom, with the line: > found = re.search(findme, line) you assign found a value which evaluates as True. Then, for each subsequent line through the for loop you are testing if found evaluates as True. And it does, because you made it so. ;-) One fix would be to say this instead: if found: print line, found = '' # or [], (), None, etc. Anything that # evaluates as False will do. Then, next time through, your if test will fail (unless of course your re.search matched again). I'm not sure of your intent; if you want "not found" to be printed only when you had no matches, you will need to add a bit more. HTH, Brian vdB From bvande at po-box.mcgill.ca Mon Sep 27 07:36:04 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Mon Sep 27 07:37:16 2004 Subject: [Fwd: Re: [Tutor] What am I missing?] Message-ID: <4157A6C4.2000304@po-box.mcgill.ca> Tom, glad you felt helped! It's a bit past my bed-time, so I've fwd'ed your reply to the tutor list -- if you send your replies there, you have a much better chance of getting help. (I'm pretty new at programming, too.) But a couple of things: Are you sure you need regular expressions for your task? I'm not very familiar with the re module, so my response didn't consider if you were using it correctly. But for simple searches, you can use string methods. (Also, rather than import string in the code below, you should use the string methods -- the string module, as I understand it, is still there for backwards compatibility, but it is not the preferred technique.) Best, Brian vdB -------- Original Message -------- Subject: Re: [Tutor] What am I missing? Date: Mon, 27 Sep 2004 01:03:40 -0400 From: Tom Tucker <tktucker@gmail.com> Reply-To: Tom Tucker <tktucker@gmail.com> To: Brian van den Broek <bvande@po-box.mcgill.ca> References: <2a278ffe040926205866e40963@mail.gmail.com> <415797EE.1010401@po-box.mcgill.ca> Brain, Thanks for the help. I APPRECIATE IT! I think, I understand. I have to zero out or empty the "found" variable. Below is the /var/log/messages log, the Python script, and the script output when executed. If you notice, my search criteria is based on the word 'CROND', my log (/var/log/messages) does NOT contain that word. WIth that being said, when the script is excuted, technically nothing should be printed to STDOUT. Correct? /var/log/messages ########### root@loki ttucker/Python/isalog # cat /var/log/messages Sep 27 00:49:46 loki syslogd 1.4.1: restart. Sep 27 00:49:46 loki kernel: klogd 1.4.1, log source = /proc/kmsg started. Sep 27 00:49:46 loki kernel: Inspecting /boot/System.map-2.6.3-7mdk-i686-up-4GB Sep 27 00:49:46 loki kernel: Loaded 29391 symbols from /boot/System.map-2.6.3-7mdk-i686-up-4GB. Sep 27 00:49:46 loki kernel: Symbols match kernel version 2.6.3. Sep 27 00:49:46 loki kernel: No module symbols loaded - kernel modules not enabled. Sep 27 00:50:03 loki su(pam_unix)[21569]: session opened for user root by (uid=0) root@loki ttucker/Python/isalog # Test Script (HAS CHANGED) ######## import os, re, string findme = re.compile('CROND') logfile = os.system('tail -f /var/log/messages') for line in logfile: found = re.search(findme, line) if found: print line, found = '' else: print "not found" found = '' SCRIPT OUTPUT ############### root@loki ttucker/Python/isalog # ./newv5.py Sep 27 00:49:46 loki syslogd 1.4.1: restart. Sep 27 00:49:46 loki kernel: klogd 1.4.1, log source = /proc/kmsg started. Sep 27 00:49:46 loki kernel: Inspecting /boot/System.map-2.6.3-7mdk-i686-up-4GB Sep 27 00:49:46 loki kernel: Loaded 29391 symbols from /boot/System.map-2.6.3-7mdk-i686-up-4GB. Sep 27 00:49:46 loki kernel: Symbols match kernel version 2.6.3. Sep 27 00:49:46 loki kernel: No module symbols loaded - kernel modules not enabled. Sep 27 00:50:03 loki su(pam_unix)[21569]: session opened for user root by (uid=0) On Mon, 27 Sep 2004 00:32:46 -0400, Brian van den Broek <bvande@po-box.mcgill.ca> wrote: > Tom Tucker said unto the world upon 2004-09-26 23:58: > > > > Good evening! Any thoughts on this one? > > > > The goal is to 'tail -f /var/log/messages' and if the line contains > > "CROND" for example, then print that line. The below script does a > > great job of tailing and printing, but it prints EVERYTHING. > > > > ################## > > #!/usr/bin/python > > > > import os, re > > > > findme = re.compile('CROND') > > logfile = os.system('tail -f /var/log/messages') > > for line in logfile: > > found = re.search(findme, line) > > if found: > > print line, > > else: > > print "not found" > > #################### > > > > > > Thanks, > > > > Tom > > Hi Tom, > > with the line: > > > found = re.search(findme, line) > > you assign found a value which evaluates as True. > > Then, for each subsequent line through the for loop you are testing if > found evaluates as True. And it does, because you made it so. ;-) > > One fix would be to say this instead: > > if found: > print line, > found = '' # or [], (), None, etc. Anything that > # evaluates as False will do. > > Then, next time through, your if test will fail (unless of course your > re.search matched again). > > I'm not sure of your intent; if you want "not found" to be printed only > when you had no matches, you will need to add a bit more. > > HTH, > > Brian vdB > From tktucker at gmail.com Mon Sep 27 07:47:46 2004 From: tktucker at gmail.com (Tom Tucker) Date: Mon Sep 27 07:49:20 2004 Subject: [Fwd: Re: [Tutor] What am I missing?] In-Reply-To: <4157A6C4.2000304@po-box.mcgill.ca> References: <4157A6C4.2000304@po-box.mcgill.ca> Message-ID: <2a278ffe0409262247132bff50@mail.gmail.com> Brian, I think I found the issue. My "for" and "if" statement were never reached. The system call "os.system('tail -f /var/log/messages')" doesn't appears to be communicating outside of itself. Back to the drawing board! Thanks! Tom On Mon, 27 Sep 2004 01:36:04 -0400, Brian van den Broek <bvande@po-box.mcgill.ca> wrote: > Tom, > > glad you felt helped! > > It's a bit past my bed-time, so I've fwd'ed your reply to the tutor list > -- if you send your replies there, you have a much better chance of > getting help. (I'm pretty new at programming, too.) > > But a couple of things: > > Are you sure you need regular expressions for your task? I'm not very > familiar with the re module, so my response didn't consider if you were > using it correctly. But for simple searches, you can use string methods. > (Also, rather than import string in the code below, you should use the > string methods -- the string module, as I understand it, is still there > for backwards compatibility, but it is not the preferred technique.) > > Best, > > Brian vdB > > > > > -------- Original Message -------- > Subject: Re: [Tutor] What am I missing? > Date: Mon, 27 Sep 2004 01:03:40 -0400 > From: Tom Tucker <tktucker@gmail.com> > Reply-To: Tom Tucker <tktucker@gmail.com> > To: Brian van den Broek <bvande@po-box.mcgill.ca> > References: <2a278ffe040926205866e40963@mail.gmail.com> > <415797EE.1010401@po-box.mcgill.ca> > > Brain, > Thanks for the help. I APPRECIATE IT! > I think, I understand. I have to zero out or empty the "found" > variable. Below is the /var/log/messages log, the Python script, and > the script output when executed. > > If you notice, my search criteria is based on the word 'CROND', my log > (/var/log/messages) does NOT contain that word. WIth that being said, > when the script is excuted, technically nothing should be printed to > STDOUT. Correct? > > /var/log/messages > ########### > root@loki ttucker/Python/isalog # cat /var/log/messages > Sep 27 00:49:46 loki syslogd 1.4.1: restart. > Sep 27 00:49:46 loki kernel: klogd 1.4.1, log source = /proc/kmsg started. > Sep 27 00:49:46 loki kernel: Inspecting > /boot/System.map-2.6.3-7mdk-i686-up-4GB > Sep 27 00:49:46 loki kernel: Loaded 29391 symbols from > /boot/System.map-2.6.3-7mdk-i686-up-4GB. > Sep 27 00:49:46 loki kernel: Symbols match kernel version 2.6.3. > Sep 27 00:49:46 loki kernel: No module symbols loaded - kernel modules > not enabled. > Sep 27 00:50:03 loki su(pam_unix)[21569]: session opened for user root > by (uid=0) > root@loki ttucker/Python/isalog # > > Test Script (HAS CHANGED) > ######## > import os, re, string > > findme = re.compile('CROND') > logfile = os.system('tail -f /var/log/messages') > for line in logfile: > found = re.search(findme, line) > if found: > print line, > found = '' > else: > print "not found" > found = '' > > SCRIPT OUTPUT > ############### > root@loki ttucker/Python/isalog # ./newv5.py > Sep 27 00:49:46 loki syslogd 1.4.1: restart. > Sep 27 00:49:46 loki kernel: klogd 1.4.1, log source = /proc/kmsg started. > Sep 27 00:49:46 loki kernel: Inspecting > /boot/System.map-2.6.3-7mdk-i686-up-4GB > Sep 27 00:49:46 loki kernel: Loaded 29391 symbols from > /boot/System.map-2.6.3-7mdk-i686-up-4GB. > Sep 27 00:49:46 loki kernel: Symbols match kernel version 2.6.3. > Sep 27 00:49:46 loki kernel: No module symbols loaded - kernel modules > not enabled. > Sep 27 00:50:03 loki su(pam_unix)[21569]: session opened for user root > by (uid=0) > > On Mon, 27 Sep 2004 00:32:46 -0400, Brian van den Broek > <bvande@po-box.mcgill.ca> wrote: > > Tom Tucker said unto the world upon 2004-09-26 23:58: > > > > > > > Good evening! Any thoughts on this one? > > > > > > The goal is to 'tail -f /var/log/messages' and if the line contains > > > "CROND" for example, then print that line. The below script does a > > > great job of tailing and printing, but it prints EVERYTHING. > > > > > > ################## > > > #!/usr/bin/python > > > > > > import os, re > > > > > > findme = re.compile('CROND') > > > logfile = os.system('tail -f /var/log/messages') > > > for line in logfile: > > > found = re.search(findme, line) > > > if found: > > > print line, > > > else: > > > print "not found" > > > #################### > > > > > > > > > Thanks, > > > > > > Tom > > > > Hi Tom, > > > > with the line: > > > > > found = re.search(findme, line) > > > > you assign found a value which evaluates as True. > > > > Then, for each subsequent line through the for loop you are testing if > > found evaluates as True. And it does, because you made it so. ;-) > > > > One fix would be to say this instead: > > > > if found: > > print line, > > found = '' # or [], (), None, etc. Anything that > > # evaluates as False will do. > > > > Then, next time through, your if test will fail (unless of course your > > re.search matched again). > > > > I'm not sure of your intent; if you want "not found" to be printed only > > when you had no matches, you will need to add a bit more. > > > > HTH, > > > > Brian vdB > > > > From tktucker at gmail.com Mon Sep 27 07:47:46 2004 From: tktucker at gmail.com (Tom Tucker) Date: Mon Sep 27 07:52:08 2004 Subject: [Fwd: Re: [Tutor] What am I missing?] In-Reply-To: <4157A6C4.2000304@po-box.mcgill.ca> References: <4157A6C4.2000304@po-box.mcgill.ca> Message-ID: <2a278ffe0409262247132bff50@mail.gmail.com> Brian, I think I found the issue. My "for" and "if" statement were never reached. The system call "os.system('tail -f /var/log/messages')" doesn't appears to be communicating outside of itself. Back to the drawing board! Thanks! Tom On Mon, 27 Sep 2004 01:36:04 -0400, Brian van den Broek <bvande@po-box.mcgill.ca> wrote: > Tom, > > glad you felt helped! > > It's a bit past my bed-time, so I've fwd'ed your reply to the tutor list > -- if you send your replies there, you have a much better chance of > getting help. (I'm pretty new at programming, too.) > > But a couple of things: > > Are you sure you need regular expressions for your task? I'm not very > familiar with the re module, so my response didn't consider if you were > using it correctly. But for simple searches, you can use string methods. > (Also, rather than import string in the code below, you should use the > string methods -- the string module, as I understand it, is still there > for backwards compatibility, but it is not the preferred technique.) > > Best, > > Brian vdB > > > > > -------- Original Message -------- > Subject: Re: [Tutor] What am I missing? > Date: Mon, 27 Sep 2004 01:03:40 -0400 > From: Tom Tucker <tktucker@gmail.com> > Reply-To: Tom Tucker <tktucker@gmail.com> > To: Brian van den Broek <bvande@po-box.mcgill.ca> > References: <2a278ffe040926205866e40963@mail.gmail.com> > <415797EE.1010401@po-box.mcgill.ca> > > Brain, > Thanks for the help. I APPRECIATE IT! > I think, I understand. I have to zero out or empty the "found" > variable. Below is the /var/log/messages log, the Python script, and > the script output when executed. > > If you notice, my search criteria is based on the word 'CROND', my log > (/var/log/messages) does NOT contain that word. WIth that being said, > when the script is excuted, technically nothing should be printed to > STDOUT. Correct? > > /var/log/messages > ########### > root@loki ttucker/Python/isalog # cat /var/log/messages > Sep 27 00:49:46 loki syslogd 1.4.1: restart. > Sep 27 00:49:46 loki kernel: klogd 1.4.1, log source = /proc/kmsg started. > Sep 27 00:49:46 loki kernel: Inspecting > /boot/System.map-2.6.3-7mdk-i686-up-4GB > Sep 27 00:49:46 loki kernel: Loaded 29391 symbols from > /boot/System.map-2.6.3-7mdk-i686-up-4GB. > Sep 27 00:49:46 loki kernel: Symbols match kernel version 2.6.3. > Sep 27 00:49:46 loki kernel: No module symbols loaded - kernel modules > not enabled. > Sep 27 00:50:03 loki su(pam_unix)[21569]: session opened for user root > by (uid=0) > root@loki ttucker/Python/isalog # > > Test Script (HAS CHANGED) > ######## > import os, re, string > > findme = re.compile('CROND') > logfile = os.system('tail -f /var/log/messages') > for line in logfile: > found = re.search(findme, line) > if found: > print line, > found = '' > else: > print "not found" > found = '' > > SCRIPT OUTPUT > ############### > root@loki ttucker/Python/isalog # ./newv5.py > Sep 27 00:49:46 loki syslogd 1.4.1: restart. > Sep 27 00:49:46 loki kernel: klogd 1.4.1, log source = /proc/kmsg started. > Sep 27 00:49:46 loki kernel: Inspecting > /boot/System.map-2.6.3-7mdk-i686-up-4GB > Sep 27 00:49:46 loki kernel: Loaded 29391 symbols from > /boot/System.map-2.6.3-7mdk-i686-up-4GB. > Sep 27 00:49:46 loki kernel: Symbols match kernel version 2.6.3. > Sep 27 00:49:46 loki kernel: No module symbols loaded - kernel modules > not enabled. > Sep 27 00:50:03 loki su(pam_unix)[21569]: session opened for user root > by (uid=0) > > On Mon, 27 Sep 2004 00:32:46 -0400, Brian van den Broek > <bvande@po-box.mcgill.ca> wrote: > > Tom Tucker said unto the world upon 2004-09-26 23:58: > > > > > > > Good evening! Any thoughts on this one? > > > > > > The goal is to 'tail -f /var/log/messages' and if the line contains > > > "CROND" for example, then print that line. The below script does a > > > great job of tailing and printing, but it prints EVERYTHING. > > > > > > ################## > > > #!/usr/bin/python > > > > > > import os, re > > > > > > findme = re.compile('CROND') > > > logfile = os.system('tail -f /var/log/messages') > > > for line in logfile: > > > found = re.search(findme, line) > > > if found: > > > print line, > > > else: > > > print "not found" > > > #################### > > > > > > > > > Thanks, > > > > > > Tom > > > > Hi Tom, > > > > with the line: > > > > > found = re.search(findme, line) > > > > you assign found a value which evaluates as True. > > > > Then, for each subsequent line through the for loop you are testing if > > found evaluates as True. And it does, because you made it so. ;-) > > > > One fix would be to say this instead: > > > > if found: > > print line, > > found = '' # or [], (), None, etc. Anything that > > # evaluates as False will do. > > > > Then, next time through, your if test will fail (unless of course your > > re.search matched again). > > > > I'm not sure of your intent; if you want "not found" to be printed only > > when you had no matches, you will need to add a bit more. > > > > HTH, > > > > Brian vdB > > > > From tktucker at gmail.com Mon Sep 27 07:47:46 2004 From: tktucker at gmail.com (Tom Tucker) Date: Mon Sep 27 07:52:10 2004 Subject: [Fwd: Re: [Tutor] What am I missing?] In-Reply-To: <4157A6C4.2000304@po-box.mcgill.ca> References: <4157A6C4.2000304@po-box.mcgill.ca> Message-ID: <2a278ffe0409262247132bff50@mail.gmail.com> Brian, I think I found the issue. My "for" and "if" statement were never reached. The system call "os.system('tail -f /var/log/messages')" doesn't appears to be communicating outside of itself. Back to the drawing board! Thanks! Tom On Mon, 27 Sep 2004 01:36:04 -0400, Brian van den Broek <bvande@po-box.mcgill.ca> wrote: > Tom, > > glad you felt helped! > > It's a bit past my bed-time, so I've fwd'ed your reply to the tutor list > -- if you send your replies there, you have a much better chance of > getting help. (I'm pretty new at programming, too.) > > But a couple of things: > > Are you sure you need regular expressions for your task? I'm not very > familiar with the re module, so my response didn't consider if you were > using it correctly. But for simple searches, you can use string methods. > (Also, rather than import string in the code below, you should use the > string methods -- the string module, as I understand it, is still there > for backwards compatibility, but it is not the preferred technique.) > > Best, > > Brian vdB > > > > > -------- Original Message -------- > Subject: Re: [Tutor] What am I missing? > Date: Mon, 27 Sep 2004 01:03:40 -0400 > From: Tom Tucker <tktucker@gmail.com> > Reply-To: Tom Tucker <tktucker@gmail.com> > To: Brian van den Broek <bvande@po-box.mcgill.ca> > References: <2a278ffe040926205866e40963@mail.gmail.com> > <415797EE.1010401@po-box.mcgill.ca> > > Brain, > Thanks for the help. I APPRECIATE IT! > I think, I understand. I have to zero out or empty the "found" > variable. Below is the /var/log/messages log, the Python script, and > the script output when executed. > > If you notice, my search criteria is based on the word 'CROND', my log > (/var/log/messages) does NOT contain that word. WIth that being said, > when the script is excuted, technically nothing should be printed to > STDOUT. Correct? > > /var/log/messages > ########### > root@loki ttucker/Python/isalog # cat /var/log/messages > Sep 27 00:49:46 loki syslogd 1.4.1: restart. > Sep 27 00:49:46 loki kernel: klogd 1.4.1, log source = /proc/kmsg started. > Sep 27 00:49:46 loki kernel: Inspecting > /boot/System.map-2.6.3-7mdk-i686-up-4GB > Sep 27 00:49:46 loki kernel: Loaded 29391 symbols from > /boot/System.map-2.6.3-7mdk-i686-up-4GB. > Sep 27 00:49:46 loki kernel: Symbols match kernel version 2.6.3. > Sep 27 00:49:46 loki kernel: No module symbols loaded - kernel modules > not enabled. > Sep 27 00:50:03 loki su(pam_unix)[21569]: session opened for user root > by (uid=0) > root@loki ttucker/Python/isalog # > > Test Script (HAS CHANGED) > ######## > import os, re, string > > findme = re.compile('CROND') > logfile = os.system('tail -f /var/log/messages') > for line in logfile: > found = re.search(findme, line) > if found: > print line, > found = '' > else: > print "not found" > found = '' > > SCRIPT OUTPUT > ############### > root@loki ttucker/Python/isalog # ./newv5.py > Sep 27 00:49:46 loki syslogd 1.4.1: restart. > Sep 27 00:49:46 loki kernel: klogd 1.4.1, log source = /proc/kmsg started. > Sep 27 00:49:46 loki kernel: Inspecting > /boot/System.map-2.6.3-7mdk-i686-up-4GB > Sep 27 00:49:46 loki kernel: Loaded 29391 symbols from > /boot/System.map-2.6.3-7mdk-i686-up-4GB. > Sep 27 00:49:46 loki kernel: Symbols match kernel version 2.6.3. > Sep 27 00:49:46 loki kernel: No module symbols loaded - kernel modules > not enabled. > Sep 27 00:50:03 loki su(pam_unix)[21569]: session opened for user root > by (uid=0) > > On Mon, 27 Sep 2004 00:32:46 -0400, Brian van den Broek > <bvande@po-box.mcgill.ca> wrote: > > Tom Tucker said unto the world upon 2004-09-26 23:58: > > > > > > > Good evening! Any thoughts on this one? > > > > > > The goal is to 'tail -f /var/log/messages' and if the line contains > > > "CROND" for example, then print that line. The below script does a > > > great job of tailing and printing, but it prints EVERYTHING. > > > > > > ################## > > > #!/usr/bin/python > > > > > > import os, re > > > > > > findme = re.compile('CROND') > > > logfile = os.system('tail -f /var/log/messages') > > > for line in logfile: > > > found = re.search(findme, line) > > > if found: > > > print line, > > > else: > > > print "not found" > > > #################### > > > > > > > > > Thanks, > > > > > > Tom > > > > Hi Tom, > > > > with the line: > > > > > found = re.search(findme, line) > > > > you assign found a value which evaluates as True. > > > > Then, for each subsequent line through the for loop you are testing if > > found evaluates as True. And it does, because you made it so. ;-) > > > > One fix would be to say this instead: > > > > if found: > > print line, > > found = '' # or [], (), None, etc. Anything that > > # evaluates as False will do. > > > > Then, next time through, your if test will fail (unless of course your > > re.search matched again). > > > > I'm not sure of your intent; if you want "not found" to be printed only > > when you had no matches, you will need to add a bit more. > > > > HTH, > > > > Brian vdB > > > > From tktucker at gmail.com Mon Sep 27 07:52:06 2004 From: tktucker at gmail.com (Tom Tucker) Date: Mon Sep 27 07:55:18 2004 Subject: [Fwd: Re: [Tutor] What am I missing?] In-Reply-To: <4157A6C4.2000304@po-box.mcgill.ca> References: <4157A6C4.2000304@po-box.mcgill.ca> Message-ID: <2a278ffe0409262252267e92e4@mail.gmail.com> Brian, I think I found the issue. My "for" and "if" statements were never reached. The system call "logfile = os.system('tail -f /var/log/messages')" doesn't appears to be communicating outside of itself. It was just printing to STDOUT. Back to the drawing board! Thanks! Tom On Mon, 27 Sep 2004 01:36:04 -0400, Brian van den Broek <bvande@po-box.mcgill.ca> wrote: > Tom, > > glad you felt helped! > > It's a bit past my bed-time, so I've fwd'ed your reply to the tutor list > -- if you send your replies there, you have a much better chance of > getting help. (I'm pretty new at programming, too.) > > But a couple of things: > > Are you sure you need regular expressions for your task? I'm not very > familiar with the re module, so my response didn't consider if you were > using it correctly. But for simple searches, you can use string methods. > (Also, rather than import string in the code below, you should use the > string methods -- the string module, as I understand it, is still there > for backwards compatibility, but it is not the preferred technique.) > > Best, > > Brian vdB > > > > > -------- Original Message -------- > Subject: Re: [Tutor] What am I missing? > Date: Mon, 27 Sep 2004 01:03:40 -0400 > From: Tom Tucker <tktucker@gmail.com> > Reply-To: Tom Tucker <tktucker@gmail.com> > To: Brian van den Broek <bvande@po-box.mcgill.ca> > References: <2a278ffe040926205866e40963@mail.gmail.com> > <415797EE.1010401@po-box.mcgill.ca> > > Brain, > Thanks for the help. I APPRECIATE IT! > I think, I understand. I have to zero out or empty the "found" > variable. Below is the /var/log/messages log, the Python script, and > the script output when executed. > > If you notice, my search criteria is based on the word 'CROND', my log > (/var/log/messages) does NOT contain that word. WIth that being said, > when the script is excuted, technically nothing should be printed to > STDOUT. Correct? > > /var/log/messages > ########### > root@loki ttucker/Python/isalog # cat /var/log/messages > Sep 27 00:49:46 loki syslogd 1.4.1: restart. > Sep 27 00:49:46 loki kernel: klogd 1.4.1, log source = /proc/kmsg started. > Sep 27 00:49:46 loki kernel: Inspecting > /boot/System.map-2.6.3-7mdk-i686-up-4GB > Sep 27 00:49:46 loki kernel: Loaded 29391 symbols from > /boot/System.map-2.6.3-7mdk-i686-up-4GB. > Sep 27 00:49:46 loki kernel: Symbols match kernel version 2.6.3. > Sep 27 00:49:46 loki kernel: No module symbols loaded - kernel modules > not enabled. > Sep 27 00:50:03 loki su(pam_unix)[21569]: session opened for user root > by (uid=0) > root@loki ttucker/Python/isalog # > > Test Script (HAS CHANGED) > ######## > import os, re, string > > findme = re.compile('CROND') > logfile = os.system('tail -f /var/log/messages') > for line in logfile: > found = re.search(findme, line) > if found: > print line, > found = '' > else: > print "not found" > found = '' > > SCRIPT OUTPUT > ############### > root@loki ttucker/Python/isalog # ./newv5.py > Sep 27 00:49:46 loki syslogd 1.4.1: restart. > Sep 27 00:49:46 loki kernel: klogd 1.4.1, log source = /proc/kmsg started. > Sep 27 00:49:46 loki kernel: Inspecting > /boot/System.map-2.6.3-7mdk-i686-up-4GB > Sep 27 00:49:46 loki kernel: Loaded 29391 symbols from > /boot/System.map-2.6.3-7mdk-i686-up-4GB. > Sep 27 00:49:46 loki kernel: Symbols match kernel version 2.6.3. > Sep 27 00:49:46 loki kernel: No module symbols loaded - kernel modules > not enabled. > Sep 27 00:50:03 loki su(pam_unix)[21569]: session opened for user root > by (uid=0) > > On Mon, 27 Sep 2004 00:32:46 -0400, Brian van den Broek > <bvande@po-box.mcgill.ca> wrote: > > Tom Tucker said unto the world upon 2004-09-26 23:58: > > > > > > > Good evening! Any thoughts on this one? > > > > > > The goal is to 'tail -f /var/log/messages' and if the line contains > > > "CROND" for example, then print that line. The below script does a > > > great job of tailing and printing, but it prints EVERYTHING. > > > > > > ################## > > > #!/usr/bin/python > > > > > > import os, re > > > > > > findme = re.compile('CROND') > > > logfile = os.system('tail -f /var/log/messages') > > > for line in logfile: > > > found = re.search(findme, line) > > > if found: > > > print line, > > > else: > > > print "not found" > > > #################### > > > > > > > > > Thanks, > > > > > > Tom > > > > Hi Tom, > > > > with the line: > > > > > found = re.search(findme, line) > > > > you assign found a value which evaluates as True. > > > > Then, for each subsequent line through the for loop you are testing if > > found evaluates as True. And it does, because you made it so. ;-) > > > > One fix would be to say this instead: > > > > if found: > > print line, > > found = '' # or [], (), None, etc. Anything that > > # evaluates as False will do. > > > > Then, next time through, your if test will fail (unless of course your > > re.search matched again). > > > > I'm not sure of your intent; if you want "not found" to be printed only > > when you had no matches, you will need to add a bit more. > > > > HTH, > > > > Brian vdB > > > > From dyoo at hkn.eecs.berkeley.edu Mon Sep 27 08:11:29 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Sep 27 08:11:32 2004 Subject: [Tutor] Re: large number question In-Reply-To: <dwx0kljojti0$.ftjpravkzkhq$.dlg@40tude.net> Message-ID: <Pine.LNX.4.44.0409262247090.5386-100000@hkn.eecs.berkeley.edu> On Sun, 26 Sep 2004, Andrei wrote: > Roel Schroeven wrote on Sun, 26 Sep 2004 15:01:06 +0200: > > > That's easy: the 4.6e18 is not the input to xrange; xrange sees the > > square root of that (plus one to be precise), which happens to be > > relatively close to 2**31: > > Duh, that's what I get from not reading the code properly. Thanks. But that's still very surprising! I didn't realise that xrange() has that limitation! Let me check something... ### >>> range(2**32, 2**32 + 1) [4294967296L] >>> xrange(2**32, 2**32 + 1) Traceback (most recent call last): File "<stdin>", line 1, in ? OverflowError: long int too large to convert to int ### Wow. Ok, that has the smell of a bug to me. *grin* I thought that xrange() was supposed to be able to take the same arguments as range()! Let me see if anyone else has noticed this... https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1003935&group_id=5470 Ok, it's a known issue. From what I understand from the bug report, xrange() isn't supposed to work on long ints because it hurts performance, and that's why we're getting the OverflowErrors. The implementors plan to add documentation to xrange that explains why it won't take arbitrarily-large integers. The Library Reference in the upcoming 2.4 release now reads: """ Note: xrange() is intended to be simple and fast. Implementations may impose restrictions to achieve this. The C implementation of Python restricts all arguments to native C longs ("short" Python integers), and also requires that that number of elements fit in a native C long. """ http://www.python.org/dev/doc/devel/lib/built-in-funcs.html#l2h-77 So in short, yeah, xrange() will overflow on large ints. So if you ever want to do iterate across distant ranges, you may need to brew up something like a generator: ### def my_xrange(start, end, step=1): n = start while n < end: yield n n += step ### But that seems like a shame to think about xrange() limitations like this; this feels like an optimization detail that should be hidden from us! I wonder how costly it would be to do something like: ### def xrange(start, end, step): ## pseudocode if the start and the end can be handled by the fast C implementation: use the fast C implementation else: use my_xrange ### From dyoo at hkn.eecs.berkeley.edu Mon Sep 27 08:43:18 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Sep 27 08:43:23 2004 Subject: [Fwd: Re: [Tutor] What am I missing?] In-Reply-To: <2a278ffe0409262252267e92e4@mail.gmail.com> Message-ID: <Pine.LNX.4.44.0409262311560.5386-100000@hkn.eecs.berkeley.edu> On Mon, 27 Sep 2004, Tom Tucker wrote: > I think I found the issue. My "for" and "if" statements were never > reached. The system call "logfile = os.system('tail -f > /var/log/messages')" doesn't appears to be communicating outside of > itself. It was just printing to STDOUT. Back to the drawing board! Hi Tom, Ah! Use os.popen(), not os.system(). The problem is that os.system() waits until the command is finished. But 'tail -f' never terminates. *grin* There are a few more issues with something like filtering 'tail -f' through Python efficiently. The big one is "blocking": if we do something like: print os.popen("tail -f foobar").read() we may actually end up waiting forever. *grin* read(), by default, is a "blocking" call that waits until the file is closed. But we can't afford to wait that long. The trick is to make it "unblocked". Here's a small example that might help you on your way: ### """A little demonstration of the 'select' module with 'popen'.""" import os import select import sys import fcntl def unblock(f): """Given file 'f', sets its unblock flag to true.""" fcntl.fcntl(f.fileno(), fcntl.F_SETFL, os.O_NONBLOCK) if __name__ == '__main__': f = os.popen("tail -f %r" % sys.argv[1]) unblock(f) while True: ins, outs, excs = select.select([f], [], []) sys.stdout.write("Got another bit of information:\n") sys.stdout.write(ins[0].read()) ### There's a little voodoo at the beginning to turn on the "nonblock" flag on a file. (Does anyone know a more obvious way to do this?) Anyway, the code is also using a 'select' event loop to avoid spinning around until there's actually new content in the files. We could have written the loop like this: ### while True: try: newText = f.read() sys.stdout.write(newText) except IOError: ## ignore IOErrors due to reading on a file that doesn't ## have anything yet pass ### This is a "busy-waiting" loop that will cause the system to spiral through the loop fast, regardless if there's actual content in the unblocked file or not. So this is acutally not a good thing to do. Using select.select() allows us to be more sympathetic with our machine. *grin* See: http://www.python.org/doc/lib/module-select.html for more details about select. I'm actually not so sure where to point to about the nonblocking IO stuff though. Hope this helps! From dyoo at hkn.eecs.berkeley.edu Mon Sep 27 09:04:09 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Sep 27 09:04:12 2004 Subject: [Fwd: Re: [Tutor] What am I missing?] In-Reply-To: <Pine.LNX.4.44.0409262311560.5386-100000@hkn.eecs.berkeley.edu> Message-ID: <Pine.LNX.4.44.0409262353320.5386-100000@hkn.eecs.berkeley.edu> On Sun, 26 Sep 2004, Danny Yoo wrote: > > > On Mon, 27 Sep 2004, Tom Tucker wrote: > > > I think I found the issue. My "for" and "if" statements were never > > reached. The system call "logfile = os.system('tail -f > > /var/log/messages')" doesn't appears to be communicating outside of > > itself. It was just printing to STDOUT. Back to the drawing board! > > > Ah! Use os.popen(), not os.system(). The problem is that os.system() > waits until the command is finished. But 'tail -f' never terminates. > *grin* Hi Tom, I should clarify that os.popen() and os.system() are used for different purposes. Their main difference is return type value. Both of them start up external processes. But os.popen() gives us back an open file object. os.system() waits until the external commands finishes, and then returns the "errorlevel" status code. So os.system() is definitely not what you want, since you want to do some post-processing on the STDOUT of the program. The blocking stuff that I mentioned in the previous mail is one additional complication. Usually people don't have to worry about blocking issues at all. But it applies to your situation because you're dealing with an external process ("tail -f") that just won't terminate. In that case, we have to do a bit extra to make things work right. Hope this clears things up! From dyoo at hkn.eecs.berkeley.edu Mon Sep 27 09:20:05 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Sep 27 09:20:10 2004 Subject: [Tutor] OSX and installation of new Python versions In-Reply-To: <76318685-0E69-11D9-B430-000393D8EC3A@ucdavis.edu> Message-ID: <Pine.LNX.4.44.0409270004330.5386-100000@hkn.eecs.berkeley.edu> On Fri, 24 Sep 2004, Christian Meesters wrote: > Is there a way to install 2.4 or 2.3.4 on the Mac (OSX 10.3.5) so that > there is only one Python version? Hi Christian, I would not replace the current version of Python on your system. Mac OS Panther uses Python 2.3 to drive some Quartz stuff, and those modules are probably not ported to 2.4 yet. And 2.4 isn't even out of alpha yet! *grin* So I'd strongly recommend leaving Apple's version of Python on your system. But what you can do is install a local copy of Python somewhere, and then point your personal PATH so that your customized copy takes precedence in your own programs. > whereas any other version explicitly has to be called with the full > path. Installing third party modules like wxPython and numarray isn't > fun this way. If you install Python to the default location ('/usr/local'), things might not be so bad. You can put '/usr/local/' in your path, and then start up Python by using: $ python2.4 This makes sure that we're getting at Python 2.4, and not the one under /usr/bin. (Apple actually keeps Python 2.3 in: /System/Library/Frameworks/Python.framework/Versions/2.3/bin/python and they seem to be pretty good about following the right version of Python so far. I wouldn't be surprised if Tiger brings Python 2.4 along for the ride.) > Any ideas how to achieve all this? (Parameters during setup and > compiling?) Frankly: The MacPython FAQ didn't help me any further and I > fear I have to live with this until Apple will include an updated > version in its OS. Or do I? Default parameters during compilation should work. The installed version will end up living in '/usr/local/'. You can redirect this to some other place by adding a '--prefix' flag during the './configure' step when you compile Python. > And one last question: If there is any solution - what will be the > impact on pythonw? I'm not sure; I haven't noticed anything funny yet, but I'm still tinkering with Tkinter. *grin* You should probably talk to folks on the PythonMac-SIG group. I'm sure that there are a lot of other MacPython users on that list that can help you get Python 2.4 set up nicely, or to work with wxPython on Macs. Here's a link to their mailing list: http://www.python.org/sigs/pythonmac-sig/ Best of wishes to you! From dyoo at hkn.eecs.berkeley.edu Mon Sep 27 09:33:30 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Sep 27 09:33:34 2004 Subject: [Fwd: Re: [Tutor] What am I missing?] In-Reply-To: <Pine.LNX.4.44.0409262353320.5386-100000@hkn.eecs.berkeley.edu> Message-ID: <Pine.LNX.4.44.0409270024250.5386-100000@hkn.eecs.berkeley.edu> > The blocking stuff that I mentioned in the previous mail is one > additional complication. Usually people don't have to worry about > blocking issues at all. But it applies to your situation because you're > dealing with an external process ("tail -f") that just won't terminate. > In that case, we have to do a bit extra to make things work right. Hi Tom, Sorry about emailing you again; I just keep screwing up. *grin* I just realized that the blocking stuff actually is fine, as long as we stick with readline() instead of read(). So the code I sent can be simplified to: ### import os import sys if __name__ == '__main__': f = os.popen("tail -f %r" % sys.argv[1]) while True: print "next line:", print f.readline() ### If we exhaust the content of 'f', then the call to: f.readline() blocks. But this is fine, since it'll unblock itself as soon as a new line of output shows up in the system log. Things all work out fine because we're dealing with text files. I guess I'm trying to say: forget everything I said about the blocking stuff. *grin* It's more applicable when we have to do more complicated stuff, but your filtering problem shouldn't need it. Again, my apologies: my problem is that I see complicated solutions first. Too much college, I think. *grin* Anyway, I hope this helps! From abra9823 at mail.usyd.edu.au Mon Sep 27 09:43:41 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Mon Sep 27 09:43:48 2004 Subject: [Tutor] ImportError: DLL load failed Message-ID: <1096271021.4157c4ad69dae@www-mail.usyd.edu.au> hi! I wrote a simple C code to work with OpenSSL and it builds fine. however when i import it, i get an error ImportError: DLL load failed. The specified module could not be found. the file is in Python/Lib directory. the code is below. thanks #include <Python.h> #include "openssl/bio.h" #include "openssl/ssl.h" #include "openssl/err.h" static PyObject * start(PyObject *self, PyObject *args) { int x; BIO * bio; char buf[1024]; int len = 512; SSL_load_error_strings(); ERR_load_BIO_strings(); OpenSSL_add_all_algorithms(); bio = BIO_new_connect("www.ibm.com:80"); if(bio==NULL) { //handle error x = -5; } if(BIO_do_connect(bio) <= 0) { //handle failed connection x = -4; } x = BIO_read(bio, buf, len); if(x == 0) { //handle closed connection x = -3; } else if(x<0) { if(! BIO_should_retry(bio)) { //handle failed read x = -2; } //do something to handle the retry } return Py_BuildValue("i", x); } static PyMethodDef testSSLMethods[] = { {"start", start, METH_VARARGS, "start and test SSL."}, {NULL, NULL, 0, NULL} }; PyMODINIT_FUNC inittestSSL(void) { (void) Py_InitModule("testSSL", testSSLMethods); } please help. thanks cheers ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From kent_johnson at skillsoft.com Mon Sep 27 11:59:28 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Mon Sep 27 11:59:33 2004 Subject: [Tutor] What am I missing? In-Reply-To: <415797EE.1010401@po-box.mcgill.ca> References: <2a278ffe040926205866e40963@mail.gmail.com> <415797EE.1010401@po-box.mcgill.ca> Message-ID: <6.1.0.6.0.20040927055356.028b69d0@mail4.skillsoft.com> Brian, The variable found is assigned each time through the loop. re.search() will return either a Match object or None and found will have one of these values assigned to it. There is no need to re-assign a False value to found. Kent At 12:32 AM 9/27/2004 -0400, Brian van den Broek wrote: >Tom Tucker said unto the world upon 2004-09-26 23:58: >>Good evening! Any thoughts on this one? >>The goal is to 'tail -f /var/log/messages' and if the line contains >>"CROND" for example, then print that line. The below script does a >>great job of tailing and printing, but it prints EVERYTHING. >>################## >>#!/usr/bin/python >>import os, re >>findme = re.compile('CROND') >>logfile = os.system('tail -f /var/log/messages') >>for line in logfile: >> found = re.search(findme, line) >> if found: >> print line, >> else: >> print "not found" >>#################### >> >>Thanks, >>Tom > >Hi Tom, > >with the line: > > > found = re.search(findme, line) > >you assign found a value which evaluates as True. > >Then, for each subsequent line through the for loop you are testing if >found evaluates as True. And it does, because you made it so. ;-) > >One fix would be to say this instead: > > if found: > print line, > found = '' # or [], (), None, etc. Anything that > # evaluates as False will do. > >Then, next time through, your if test will fail (unless of course your >re.search matched again). > >I'm not sure of your intent; if you want "not found" to be printed only >when you had no matches, you will need to add a bit more. > >HTH, > >Brian vdB >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From gustabares at verizon.net Mon Sep 27 13:27:02 2004 From: gustabares at verizon.net (Gus Tabares) Date: Mon Sep 27 13:26:37 2004 Subject: [Tutor] ImportError: DLL load failed In-Reply-To: <1096271021.4157c4ad69dae@www-mail.usyd.edu.au> References: <1096271021.4157c4ad69dae@www-mail.usyd.edu.au> Message-ID: <200409270727.03054.gustabares@verizon.net> Did you try running the Python script from the command line? Usually it will tell you the DLL that you are missing. HTH, Gus On Monday 27 September 2004 03:43 am, Ajay wrote: > hi! > > I wrote a simple C code to work with OpenSSL and it builds fine. > however when i import it, i get an error > ImportError: DLL load failed. The specified module could not be found. > > the file is in Python/Lib directory. > > the code is below. > > thanks > > #include <Python.h> > #include "openssl/bio.h" > #include "openssl/ssl.h" > #include "openssl/err.h" > > static PyObject * start(PyObject *self, PyObject *args) > { > int x; > BIO * bio; > char buf[1024]; > int len = 512; > SSL_load_error_strings(); > ERR_load_BIO_strings(); > OpenSSL_add_all_algorithms(); > bio = BIO_new_connect("www.ibm.com:80"); > if(bio==NULL) > { > //handle error > x = -5; > } > if(BIO_do_connect(bio) <= 0) > { > //handle failed connection > x = -4; > } > x = BIO_read(bio, buf, len); > if(x == 0) > { > //handle closed connection > x = -3; > } > else if(x<0) > { > if(! BIO_should_retry(bio)) > { > //handle failed read > x = -2; > } > //do something to handle the retry > } > return Py_BuildValue("i", x); > } > > static PyMethodDef testSSLMethods[] = { > {"start", start, METH_VARARGS, "start and test SSL."}, > {NULL, NULL, 0, NULL} > }; > > PyMODINIT_FUNC > inittestSSL(void) > { > (void) Py_InitModule("testSSL", testSSLMethods); > } > > please help. > > thanks > cheers > > > > > ---------------------------------------------------------------- > This message was sent using IMP, the Internet Messaging Program. > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From abra9823 at mail.usyd.edu.au Mon Sep 27 15:36:47 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Mon Sep 27 15:36:53 2004 Subject: [Tutor] ImportError: DLL load failed In-Reply-To: <200409270727.03054.gustabares@verizon.net> References: <1096271021.4157c4ad69dae@www-mail.usyd.edu.au> <200409270727.03054.gustabares@verizon.net> Message-ID: <1096292207.4158176f60f6f@www-mail.usyd.edu.au> Quoting Gus Tabares <gustabares@verizon.net>: > > Did you try running the Python script from the command line? Usually it > will > tell you the DLL that you are missing. the code i posted earlier, is the DLL that it cannot find. i compiled it to a DLL and when i import it i get the DLL load failed error, even though the path to is in sys.path could it be because it can't find the OpenSSL dll's? i added the path to \OpenSSL which contains the dll's, to my sys.path before i tried importing my dll. i really cant understand whats throwing the error. i have already run tests on the OpenSSL dll's and they all work fine. my code built fine. so why does import give an error? > > > HTH, > Gus > > > > > On Monday 27 September 2004 03:43 am, Ajay wrote: > > hi! > > > > I wrote a simple C code to work with OpenSSL and it builds fine. > > however when i import it, i get an error > > ImportError: DLL load failed. The specified module could not be found. > > > > the file is in Python/Lib directory. > > > > the code is below. > > > > thanks > > > > #include <Python.h> > > #include "openssl/bio.h" > > #include "openssl/ssl.h" > > #include "openssl/err.h" > > > > static PyObject * start(PyObject *self, PyObject *args) > > { > > int x; > > BIO * bio; > > char buf[1024]; > > int len = 512; > > SSL_load_error_strings(); > > ERR_load_BIO_strings(); > > OpenSSL_add_all_algorithms(); > > bio = BIO_new_connect("www.ibm.com:80"); > > if(bio==NULL) > > { > > //handle error > > x = -5; > > } > > if(BIO_do_connect(bio) <= 0) > > { > > //handle failed connection > > x = -4; > > } > > x = BIO_read(bio, buf, len); > > if(x == 0) > > { > > //handle closed connection > > x = -3; > > } > > else if(x<0) > > { > > if(! BIO_should_retry(bio)) > > { > > //handle failed read > > x = -2; > > } > > //do something to handle the retry > > } > > return Py_BuildValue("i", x); > > } > > > > static PyMethodDef testSSLMethods[] = { > > {"start", start, METH_VARARGS, "start and test SSL."}, > > {NULL, NULL, 0, NULL} > > }; > > > > PyMODINIT_FUNC > > inittestSSL(void) > > { > > (void) Py_InitModule("testSSL", testSSLMethods); > > } > > > > please help. > > > > thanks > > cheers > > > > > > > > > > ---------------------------------------------------------------- > > This message was sent using IMP, the Internet Messaging Program. > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://mail.python.org/mailman/listinfo/tutor > ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From kabads at gmail.com Mon Sep 27 16:01:03 2004 From: kabads at gmail.com (Adam Cripps) Date: Mon Sep 27 16:01:14 2004 Subject: [Tutor] Acting on objects in a list - how to make the change permanent? Message-ID: <c7ff3855040927070139ffeb56@mail.gmail.com> My python project (http://savannah.nongnu.org/projects/newmag) is teaching me a fair bit about how to write python code. However, I'm still a long way away from being remotely good, as some of my recent posts have shown. I'm working on deleting instance objects and I've created a list of objects which is then piped through a menu to allow the user to choose which one is deleted. The basic structure of the code is this: * choose_what_to_edit - creates a list which calls return_object_list * return_object_list - return_object_list -chooses what level the user wants to select an object * choosetitle - selects a title * chooseissue - if necssary selects an issue from the selected title * choosearticle - and if nescessary, selects an article from the selected issue. Basically, from this code, I get a list, which has objects within it. If I alter the objects within this list, how do I make them permanent? I'm currently trying to delete an item/object of the list the command del returned_list[choice] - however, this doesn't seem to be a permanent change. For the full code listing, please see the CVS project page. Am I right in thinking that the list of objects will be referenced through to the actual instances, and if so, why aren't they being deleted? I've read some of the python docs, but can't see the solution here and would appreciate a more informed/specialised approach. TIA. Adam From bvande at po-box.mcgill.ca Mon Sep 27 17:07:36 2004 From: bvande at po-box.mcgill.ca (Brian van den Broek) Date: Mon Sep 27 17:10:47 2004 Subject: [Tutor] What am I missing? In-Reply-To: <6.1.0.6.0.20040927055356.028b69d0@mail4.skillsoft.com> References: <2a278ffe040926205866e40963@mail.gmail.com> <415797EE.1010401@po-box.mcgill.ca> <6.1.0.6.0.20040927055356.028b69d0@mail4.skillsoft.com> Message-ID: <41582CB8.1040909@po-box.mcgill.ca> Hi Kent, Tom, and all, Re-reading in the light of day, of course Kent is right. :-[ Sorry for giving a 'too late for thinking' answer, Tom. Brian vdB Kent Johnson said unto the world upon 2004-09-27 05:59: > Brian, > > The variable found is assigned each time through the loop. re.search() > will return either a Match object or None and found will have one of > these values assigned to it. There is no need to re-assign a False value > to found. > > Kent > > At 12:32 AM 9/27/2004 -0400, Brian van den Broek wrote: > >> Tom Tucker said unto the world upon 2004-09-26 23:58: >> >>> Good evening! Any thoughts on this one? >>> The goal is to 'tail -f /var/log/messages' and if the line contains >>> "CROND" for example, then print that line. The below script does a >>> great job of tailing and printing, but it prints EVERYTHING. >>> ################## >>> #!/usr/bin/python >>> import os, re >>> findme = re.compile('CROND') >>> logfile = os.system('tail -f /var/log/messages') >>> for line in logfile: >>> found = re.search(findme, line) >>> if found: >>> print line, >>> else: >>> print "not found" >>> #################### >>> >>> Thanks, >>> Tom >> >> >> Hi Tom, >> <SNIP useless answer> >> HTH, >> >> Brian vdB From pythonTutor at venix.com Mon Sep 27 17:19:57 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Mon Sep 27 17:21:04 2004 Subject: [Tutor] Acting on objects in a list - how to make the change permanent? In-Reply-To: <c7ff3855040927070139ffeb56@mail.gmail.com> References: <c7ff3855040927070139ffeb56@mail.gmail.com> Message-ID: <1096298396.16995.112.camel@laptop.venix.com> I did NOT read your source code, so this is simply a guess. Assigning a modified list to a name does NOT change the original list. Here's a simple example: >>> def odd_only(numlist): ... odds = [n for n in numlist if n%2] ... numlist = odds ... return odds ... >>> numlist = range(10) >>> odd_only(numlist) [1, 3, 5, 7, 9] >>> numlist [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] The original numlist is NOT modified by the assignment in odd_only. Since you are passing lists between functions, I am guessing that somewhere you have logic like the example above. The simple fix here is to do: numlist = odd_only(numlist) Hope this helps. On Mon, 2004-09-27 at 10:01, Adam Cripps wrote: > My python project (http://savannah.nongnu.org/projects/newmag) is > teaching me a fair bit about how to write python code. However, I'm > still a long way away from being remotely good, as some of my recent > posts have shown. > > I'm working on deleting instance objects and I've created a list of > objects which is then piped through a menu to allow the user to choose > which one is deleted. > > The basic structure of the code is this: > > * choose_what_to_edit - creates a list which calls return_object_list > * return_object_list - return_object_list -chooses what level > the user wants to select an object > * choosetitle - selects a title > * chooseissue - if necssary selects an issue from the selected title > * choosearticle - and if nescessary, selects an article > from the selected issue. > > Basically, from this code, I get a list, which has objects within it. > If I alter the objects within this list, how do I make them permanent? > I'm currently trying to delete an item/object of the list the command > del returned_list[choice] - however, this doesn't seem to be a > permanent change. For the full code listing, please see the CVS > project page. > > Am I right in thinking that the list of objects will be referenced > through to the actual instances, and if so, why aren't they being > deleted? I've read some of the python docs, but can't see the solution > here and would appreciate a more informed/specialised approach. > > TIA. > Adam > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From iqbala-python at qwestip.net Mon Sep 27 19:12:47 2004 From: iqbala-python at qwestip.net (Asif Iqbal) Date: Mon Sep 27 19:12:50 2004 Subject: [Tutor] List intersect Message-ID: <20040927171247.GA22220@qwestip.net> Hi All I never wrote a python script. I am looking for a script that I can use to generate a uniq list out of five lists. These lists are bunch of usernames. So one list might look like this list1: usera auser userb buser list2: userc cuser userd duser usera Generated list: usera auser userb buser userc cuser userd duser Thanks for any help -- Asif Iqbal PGP Key: 0xE62693C5 KeyServer: pgp.mit.edu "...it said: Install Windows XP or better...so I installed Solaris..." From nsandver at gmail.com Mon Sep 27 19:25:22 2004 From: nsandver at gmail.com (Nathan Sandver) Date: Mon Sep 27 19:26:17 2004 Subject: [Tutor] List intersect In-Reply-To: <20040927171247.GA22220@qwestip.net> References: <20040927171247.GA22220@qwestip.net> Message-ID: <2b6e52204092710255c4287d1@mail.gmail.com> On Mon, 27 Sep 2004 13:12:47 -0400, Asif Iqbal <iqbala-python@qwestip.net> wrote: > Hi All > > I never wrote a python script. I am looking for a script that I can use > to generate a uniq list out of five lists. These lists are bunch of > usernames. So one list might look like this > > list1: > > usera > auser > userb > buser > > list2: > userc > cuser > userd > duser > usera > > Generated list: > usera > auser > userb > buser > userc > cuser > userd > duser > > Thanks for any help Unless I'm mistaken about what you're trying to do, writing a Python script sounds like making things harder than necessary. Assuming you're on a Unix-like system and your lists are in separate files: cat list1 list2 list3 list4 list5 | uniq > newlist should do what you're after. -- Nathan Sandver, KC7SQK From fant at pobox.com Mon Sep 27 20:48:59 2004 From: fant at pobox.com (Andrew Fant) Date: Mon Sep 27 20:49:16 2004 Subject: [Tutor] Binarry files and large files Message-ID: <92180000.1096310939@flux.usg.tufts.edu> Hello, I am looking at using python to process unix system accounting files from a number of servers that I manage. While I could use simple shell scripts and the sa command, I have found that sa doesn't have large file support, so it can only process 2GB of files at once. I therefore have 2 main questions to ask of the group: 1) By default does python handle large file sizes cleanly under linux, or do I need to do something special to enable 64 bit file pointers? 2) Does anyone have any worlds of wisdom about handling binary files like unix pacct files with python? If anyone has any code that they can share for parsing process accounting files or they know where I might find some, I would be most grateful for pointers. Thanks, Andy From dyoo at hkn.eecs.berkeley.edu Mon Sep 27 20:52:56 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon Sep 27 20:53:01 2004 Subject: [Tutor] List intersect In-Reply-To: <2b6e52204092710255c4287d1@mail.gmail.com> Message-ID: <Pine.LNX.4.44.0409271140440.22740-100000@hkn.eecs.berkeley.edu> > > I never wrote a python script. I am looking for a script that I can use > > to generate a uniq list out of five lists. These lists are bunch of > > usernames. [text cut] > Unless I'm mistaken about what you're trying to do, writing a Python > script sounds like making things harder than necessary. Assuming you're > on a Unix-like system and your lists are in separate files: > > cat list1 list2 list3 list4 list5 | uniq > newlist Yes, the Unix shell solution should be really straightforward. But don't forget to sort! $ cat list1 list2 list3 list4 list5 | sort | uniq > newlist The 'uniquing' algorithm that uniq uses won't see duplicates unless they're adjacent to each other. The 'uniq' utility does something like this: ### def unique(sequence): if len(sequence) == 1: return sequence results = [sequence[0]] i = 1 while i < len(sequence): if sequence[i] != sequence[i-1]: results.append(sequence[i]) i += 1 return results ### And we can see that it works, just as long as the sequence is sorted: ### >>> unique([1, 1, 2, 4, 6, 8, 9, 9, 10]) [1, 2, 4, 6, 8, 9, 10] ### But if the elements are not in sorted order, then unique() won't catch all duplicate elements: ### >>> import random >>> l = [1, 1, 2, 4, 6, 8, 9, 9, 10] >>> random.shuffle(l) >>> l [4, 6, 8, 1, 10, 1, 9, 9, 2] >>> unique(l) [4, 6, 8, 1, 10, 1, 9, 2] ### So if you use this approach, don't forget to sort first. An alternative way to solve the uniqueness problem is to use dictionaries or sets to maintain a unique list of elements. All of the tutorials on: http://www.python.org/topics/learn/non-prog.html should cover how to use dictionaries. From pathall at gmail.com Mon Sep 27 21:30:01 2004 From: pathall at gmail.com (Patrick Hall) Date: Mon Sep 27 21:30:19 2004 Subject: [Tutor] List intersect In-Reply-To: <Pine.LNX.4.44.0409271140440.22740-100000@hkn.eecs.berkeley.edu> References: <2b6e52204092710255c4287d1@mail.gmail.com> <Pine.LNX.4.44.0409271140440.22740-100000@hkn.eecs.berkeley.edu> Message-ID: <6465924d0409271230af269f8@mail.gmail.com> Hi folks, On Mon, 27 Sep 2004 11:52:56 -0700 (PDT), Danny Yoo <dyoo@hkn.eecs.berkeley.edu> wrote: > An alternative way to solve the uniqueness problem is to use dictionaries > or sets to maintain a unique list of elements. All of the tutorials on: > > http://www.python.org/topics/learn/non-prog.html > > should cover how to use dictionaries. Here's one such approach: ### def collect_unique(inputlist): """Use a dictionary to return a list of unique elements in inputlist""" seen = {} for element in inputlist: if element not in seen: seen[element] = 1 unique = seen.keys() unique.sort() # just for readability in this case return unique if __name__ == "__main__": userlists = \ (['buser', 'usera', 'userb', 'userc'], ['userb', 'userc', 'cuser', 'userc'], ['usera', 'duser', 'userb', 'userb'], ['userc', 'userc', 'userb', 'userb'], ['userc', 'userb', 'auser', 'userb']) # flatten into one big list biglist = [] for userlist in userlists: biglist.extend(userlist) unique_list = collect_unique(biglist) print unique_list # or whatever. ### I believe one can also do this sort of thing with Sets in more recent Pythons. By the way, does anyone know if using Set intersections is an efficient way to handle this sort of thing? -Pat From kabads at gmail.com Mon Sep 27 21:59:01 2004 From: kabads at gmail.com (Adam Cripps) Date: Mon Sep 27 21:59:32 2004 Subject: [Tutor] Acting on objects in a list - how to make the change permanent? In-Reply-To: <1096298396.16995.112.camel@laptop.venix.com> References: <c7ff3855040927070139ffeb56@mail.gmail.com> <1096298396.16995.112.camel@laptop.venix.com> Message-ID: <c7ff3855040927125968c003f1@mail.gmail.com> On 27 Sep 2004 11:19:57 -0400, Lloyd Kvam <pythontutor@venix.com> wrote: > I did NOT read your source code, so this is simply a guess. Assigning > a modified list to a name does NOT change the original list. Here's a > simple example: > > >>> def odd_only(numlist): > ... odds = [n for n in numlist if n%2] > ... numlist = odds > ... return odds > ... > >>> numlist = range(10) > >>> odd_only(numlist) > [1, 3, 5, 7, 9] > >>> numlist > [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] > > The original numlist is NOT modified by the assignment in odd_only. > > Since you are passing lists between functions, I am guessing that > somewhere you have logic like the example above. The simple fix here is > to do: > numlist = odd_only(numlist) > > Hope this helps. > > > > Lloyd Kvam > Venix Corp > > Thanks Lloyd - What would the syntax be for deleting an object from a list? I've tried (with an error) returned_list = del returned_list [intchoice] Is there some other syntax that I should be trying here? Thanks again. -- -- proj: http://jiletters.sf.net site: http://www.monkeez.org wiki: http://wiki.monkeez.org From tktucker at gmail.com Mon Sep 27 22:02:35 2004 From: tktucker at gmail.com (Tom Tucker) Date: Mon Sep 27 22:02:45 2004 Subject: [Tutor] What am I missing? In-Reply-To: <41582CB8.1040909@po-box.mcgill.ca> References: <2a278ffe040926205866e40963@mail.gmail.com> <415797EE.1010401@po-box.mcgill.ca> <6.1.0.6.0.20040927055356.028b69d0@mail4.skillsoft.com> <41582CB8.1040909@po-box.mcgill.ca> Message-ID: <2a278ffe04092713023d1a19da@mail.gmail.com> Thanks everyone! I got it working and learned quite a bit in the process. ;-) Tom On Mon, 27 Sep 2004 11:07:36 -0400, Brian van den Broek <bvande@po-box.mcgill.ca> wrote: > Hi Kent, Tom, and all, > > Re-reading in the light of day, of course Kent is right. :-[ > > Sorry for giving a 'too late for thinking' answer, Tom. > > Brian vdB > > Kent Johnson said unto the world upon 2004-09-27 05:59: > > Brian, > > > > The variable found is assigned each time through the loop. re.search() > > will return either a Match object or None and found will have one of > > these values assigned to it. There is no need to re-assign a False value > > to found. > > > > Kent > > > > At 12:32 AM 9/27/2004 -0400, Brian van den Broek wrote: > > > >> Tom Tucker said unto the world upon 2004-09-26 23:58: > >> > >>> Good evening! Any thoughts on this one? > >>> The goal is to 'tail -f /var/log/messages' and if the line contains > >>> "CROND" for example, then print that line. The below script does a > >>> great job of tailing and printing, but it prints EVERYTHING. > >>> ################## > >>> #!/usr/bin/python > >>> import os, re > >>> findme = re.compile('CROND') > >>> logfile = os.system('tail -f /var/log/messages') > >>> for line in logfile: > >>> found = re.search(findme, line) > >>> if found: > >>> print line, > >>> else: > >>> print "not found" > >>> #################### > >>> > >>> Thanks, > >>> Tom > >> > >> > >> Hi Tom, > >> > > <SNIP useless answer> > > >> HTH, > >> > >> Brian vdB > > From pythonTutor at venix.com Mon Sep 27 22:05:09 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Mon Sep 27 22:05:53 2004 Subject: [Tutor] Acting on objects in a list - how to make the change permanent? In-Reply-To: <c7ff3855040927125361e6c90@mail.gmail.com> References: <c7ff3855040927070139ffeb56@mail.gmail.com> <1096298396.16995.112.camel@laptop.venix.com> <c7ff3855040927125361e6c90@mail.gmail.com> Message-ID: <1096315508.16995.216.camel@laptop.venix.com> On Mon, 2004-09-27 at 15:53, Adam Cripps wrote: > On 27 Sep 2004 11:19:57 -0400, Lloyd Kvam <pythontutor@venix.com> wrote: > > I did NOT read your source code, so this is simply a guess. Assigning > > a modified list to a name does NOT change the original list. Here's a > > simple example: > > > > >>> def odd_only(numlist): > > ... odds = [n for n in numlist if n%2] > > ... numlist = odds > > ... return odds > > ... > > >>> numlist = range(10) > > >>> odd_only(numlist) > > [1, 3, 5, 7, 9] > > >>> numlist > > [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] > > > > The original numlist is NOT modified by the assignment in odd_only. > > > > Since you are passing lists between functions, I am guessing that > > somewhere you have logic like the example above. The simple fix here is > > to do: > > numlist = odd_only(numlist) > > > > Hope this helps. > > Lloyd Kvam > > Venix Corp > > > > Thanks Lloyd - > > What would the syntax be for deleting an object from a list? > I've tried (with an error) > returned_list = del returned_list [intchoice] > > Is there some other syntax that I should be trying here? del is a statement so it can't be part of an assignment statement. Use: del returned_list[intchoice] which modifies the list "in place". There is no need for the assignment. > > Thanks again. > > Adam -- Lloyd Kvam Venix Corp From kabads at gmail.com Mon Sep 27 22:36:16 2004 From: kabads at gmail.com (Adam Cripps) Date: Mon Sep 27 22:37:03 2004 Subject: [Tutor] Acting on objects in a list - how to make the change permanent? In-Reply-To: <1096315508.16995.216.camel@laptop.venix.com> References: <c7ff3855040927070139ffeb56@mail.gmail.com> <1096298396.16995.112.camel@laptop.venix.com> <c7ff3855040927125361e6c90@mail.gmail.com> <1096315508.16995.216.camel@laptop.venix.com> Message-ID: <c7ff385504092713361cf971b@mail.gmail.com> On 27 Sep 2004 16:05:09 -0400, Lloyd Kvam <pythontutor@venix.com> wrote: > > > On Mon, 2004-09-27 at 15:53, Adam Cripps wrote: > > On 27 Sep 2004 11:19:57 -0400, Lloyd Kvam <pythontutor@venix.com> wrote: > > > I did NOT read your source code, so this is simply a guess. Assigning > > > a modified list to a name does NOT change the original list. Here's a > > > simple example: > > > > > > >>> def odd_only(numlist): > > > ... odds = [n for n in numlist if n%2] > > > ... numlist = odds > > > ... return odds > > > ... > > > >>> numlist = range(10) > > > >>> odd_only(numlist) > > > [1, 3, 5, 7, 9] > > > >>> numlist > > > [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] > > > > > > The original numlist is NOT modified by the assignment in odd_only. > > > > > > Since you are passing lists between functions, I am guessing that > > > somewhere you have logic like the example above. The simple fix here is > > > to do: > > > numlist = odd_only(numlist) > > > > > > Hope this helps. > > > Lloyd Kvam > > > Venix Corp > > > > > > > Thanks Lloyd - > > > > What would the syntax be for deleting an object from a list? > > I've tried (with an error) > > returned_list = del returned_list [intchoice] > > > > Is there some other syntax that I should be trying here? > > del is a statement so it can't be part of an assignment statement. Use: > > del returned_list[intchoice] > > which modifies the list "in place". There is no need for the > assignment. > > > > > Thanks again. > > > > Adam > -- > Lloyd Kvam > Venix Corp Hrmm - this kind of brings me full-circle, as that was the command that I originally tried and it doesn't seem to change the object. When I go through and look at the object again, it's still there. I don't get any errors with this either. I don't return the list, so I'm not sure if the object is being returned. Here's the small piece of code that I'm working with: for i in returned_list: if intchoice == iter_count: action = raw_input ("""Would you like to delete this object? (y/n)""") if action == "y": intchoice = intchoice -1 # First one is zero - need to take one off del returned_list[intchoice] print "deleted" return # Do I need to return the new list? else: print "You chose not to delete" return iter_count = iter_count + 1 # This goes through the loop Does this shed any light on what I'm trying to do? Adam From jeff at ccvcorp.com Mon Sep 27 23:12:14 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Mon Sep 27 23:12:27 2004 Subject: [Tutor] Acting on objects in a list - how to make the change permanent? In-Reply-To: <c7ff385504092713361cf971b@mail.gmail.com> References: <c7ff3855040927070139ffeb56@mail.gmail.com> <1096298396.16995.112.camel@laptop.venix.com> <c7ff3855040927125361e6c90@mail.gmail.com> <1096315508.16995.216.camel@laptop.venix.com> <c7ff385504092713361cf971b@mail.gmail.com> Message-ID: <4158822E.4020705@ccvcorp.com> Adam Cripps wrote: >for i in returned_list: > if intchoice == iter_count: > action = raw_input ("""Would you like to delete this object? (y/n)""") > if action == "y": > intchoice = intchoice -1 # First one is zero - need to take one off > del returned_list[intchoice] > print "deleted" > return # Do I need to return the new list? > else: > print "You chose not to delete" > return > iter_count = iter_count + 1 # This goes through the loop > > > I'm not sure if this is the cause of your problem, but in this code you're never incrementing iter_count, and you'll never execute this loop for more than one iteration anyhow. You're returning out of the function that this loop is in as soon as you've processed the first element, regardless of what you do with it. Presumably, you want to run this loop over everything in returned_list; you can do this simply by removing both return statements. If, in one of the two cases, you want to avoid the iter_count increment at the end of the loop, you can use 'continue' to start the next iteration at the top of the loop, or 'break' to break out of the for loop but continue with the rest of the function that this is in. Jeff Shannon Technician/Programmer Credit International From pythonTutor at venix.com Mon Sep 27 23:18:31 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Mon Sep 27 23:19:28 2004 Subject: [Tutor] Acting on objects in a list - how to make the change permanent? In-Reply-To: <c7ff385504092713361cf971b@mail.gmail.com> References: <c7ff3855040927070139ffeb56@mail.gmail.com> <1096298396.16995.112.camel@laptop.venix.com> <c7ff3855040927125361e6c90@mail.gmail.com> <1096315508.16995.216.camel@laptop.venix.com> <c7ff385504092713361cf971b@mail.gmail.com> Message-ID: <1096319911.16995.246.camel@laptop.venix.com> On Mon, 2004-09-27 at 16:36, Adam Cripps wrote: > On 27 Sep 2004 16:05:09 -0400, Lloyd Kvam <pythontutor@venix.com> wrote: > > > > > > On Mon, 2004-09-27 at 15:53, Adam Cripps wrote: > > > On 27 Sep 2004 11:19:57 -0400, Lloyd Kvam <pythontutor@venix.com> wrote: > > > > I did NOT read your source code, so this is simply a guess. Assigning > > > > a modified list to a name does NOT change the original list. Here's a > > > > simple example: > > > > > > > > >>> def odd_only(numlist): > > > > ... odds = [n for n in numlist if n%2] > > > > ... numlist = odds > > > > ... return odds > > > > ... > > > > >>> numlist = range(10) > > > > >>> odd_only(numlist) > > > > [1, 3, 5, 7, 9] > > > > >>> numlist > > > > [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] > > > > > > > > The original numlist is NOT modified by the assignment in odd_only. > > > > > > > > Since you are passing lists between functions, I am guessing that > > > > somewhere you have logic like the example above. The simple fix here is > > > > to do: > > > > numlist = odd_only(numlist) > > > > > > > > Hope this helps. > > > > Lloyd Kvam > > > > Venix Corp > > > > > > > > > > Thanks Lloyd - > > > > > > What would the syntax be for deleting an object from a list? > > > I've tried (with an error) > > > returned_list = del returned_list [intchoice] > > > > > > Is there some other syntax that I should be trying here? > > > > del is a statement so it can't be part of an assignment statement. Use: > > > > del returned_list[intchoice] > > > > which modifies the list "in place". There is no need for the > > assignment. > > > > > > > > Thanks again. > > > > > > Adam > > -- > > Lloyd Kvam > > Venix Corp > > > Hrmm - this kind of brings me full-circle, as that was the command > that I originally tried and it doesn't seem to change the object. When > I go through and look at the object again, it's still there. I don't > get any errors with this either. I don't return the list, so I'm not > sure if the object is being returned. Here's the small piece of code > that I'm working with: > > for i in returned_list: > if intchoice == iter_count: > action = raw_input ("""Would you like to delete this object? (y/n)""") > if action == "y": > intchoice = intchoice -1 # First one is zero - need to take one off > del returned_list[intchoice] > print "deleted" > return # Do I need to return the new list? > else: > print "You chose not to delete" > return > iter_count = iter_count + 1 # This goes through the loop > > Does this shed any light on what I'm trying to do? Maybe. You will have difficulties deleting items from a list within a loop that steps through the list. Normally you would loop through a copy for i in returned_list[:]: # loop through copy of list But that does not explain getting NO deletions. You should get deletions - but usually some of the wrong elements get deleted. With modest sized lists, I think it is usually better to build a new list, return it, and bind the original name to the new list. Your symptoms suggest that you have two lists with deletions occurring against one while you wind up looking at the other. You're sure your debug line of print "deleted" is adequate? You could use print returned_list To explicitly see the list and confirm the deletion. > > Adam > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From shitizb at yahoo.com Tue Sep 28 01:56:31 2004 From: shitizb at yahoo.com (Shitiz Bansal) Date: Tue Sep 28 01:56:38 2004 Subject: [Tutor] yahoo messenger and python Message-ID: <20040927235631.7940.qmail@web53804.mail.yahoo.com> hello ppl, i am working on a windows machine. i need to automate sending IMs via my yahoo messenger using python. anybody has any idea how it can be done..i tried curphoo but it doesnt run properly on windows. shitiz __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040927/2ed36ce8/attachment.html From flaxeater at yahoo.com Tue Sep 28 03:11:32 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Tue Sep 28 03:11:39 2004 Subject: [Tutor] ImportError: DLL load failed Message-ID: <20040928011132.95043.qmail@web52603.mail.yahoo.com> Ajay wrote: >Quoting Gus Tabares <gustabares@verizon.net>: > > > >>Did you try running the Python script from the command line? Usually it >>will >>tell you the DLL that you are missing. >> >> > >the code i posted earlier, is the DLL that it cannot find. i compiled it to >a DLL and when i import it i get the DLL load failed error, even though the >path to is in sys.path > >could it be because it can't find the OpenSSL dll's? i added the path to >\OpenSSL which contains the dll's, to my sys.path before i tried importing >my dll. > >i really cant understand whats throwing the error. i have already run tests >on the OpenSSL dll's and they all work fine. my code built fine. so why >does import give an error? > > > Well maybe OpenSSL needs to be in $PATH, or $LIB or something or other are you using *nix or Win? __________________________________ Do you Yahoo!? New and Improved Yahoo! Mail - 100MB free storage! http://promotions.yahoo.com/new_mail From abra9823 at mail.usyd.edu.au Tue Sep 28 03:16:39 2004 From: abra9823 at mail.usyd.edu.au (Ajay) Date: Tue Sep 28 03:16:45 2004 Subject: [Tutor] ImportError: DLL load failed In-Reply-To: <20040928011132.95043.qmail@web52603.mail.yahoo.com> References: <20040928011132.95043.qmail@web52603.mail.yahoo.com> Message-ID: <1096334199.4158bb77a2f00@www-mail.usyd.edu.au> Quoting Chad Crabtree <flaxeater@yahoo.com>: > Ajay wrote: > > >Quoting Gus Tabares <gustabares@verizon.net>: > > > > > > > >>Did you try running the Python script from the command line? > Usually it > >>will > >>tell you the DLL that you are missing. > >> > >> > > > >the code i posted earlier, is the DLL that it cannot find. i > compiled it to > >a DLL and when i import it i get the DLL load failed error, even > though the > >path to is in sys.path > > > >could it be because it can't find the OpenSSL dll's? i added the > path to > >\OpenSSL which contains the dll's, to my sys.path before i tried > importing > >my dll. > > > >i really cant understand whats throwing the error. i have already > run tests > >on the OpenSSL dll's and they all work fine. my code built fine. so > why > >does import give an error? > > > > > > > Well maybe OpenSSL needs to be in $PATH, or $LIB or something or > other > are you using *nix or Win? > windows CE, and i have added it to sys.path, isn't that $PATH? cheers > > > > __________________________________ > Do you Yahoo!? > New and Improved Yahoo! Mail - 100MB free storage! > http://promotions.yahoo.com/new_mail > ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From kent_johnson at skillsoft.com Tue Sep 28 04:13:05 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Tue Sep 28 04:13:12 2004 Subject: [Tutor] Acting on objects in a list - how to make the change permanent? In-Reply-To: <c7ff3855040927070139ffeb56@mail.gmail.com> References: <c7ff3855040927070139ffeb56@mail.gmail.com> Message-ID: <6.1.0.6.0.20040927220012.028bcfc0@mail4.skillsoft.com> Adam, You are confusing a "list of things that should be deleted" with the list from which they should be deleted. For example suppose I have the list [1, 2, 3, 4, 5]: >>> a=[1, 2, 3, 4, 5] >>> a [1, 2, 3, 4, 5] Now I get a list of things to delete from a: >>> d=[1, 3] Deleting something from d will not be helpful! >>> d.remove(1) >>> a [1, 2, 3, 4, 5] >>> d [3] I have to remove from a: >>> d=[1, 3] >>> for i in d: ... a.remove(i) ... >>> d [1, 3] >>> a [2, 4, 5] OK, now in your real code, you have a nested structure of lists - a magazine collection has titles which have issues which have articles. So it's not so simple, when you have just the list d, to figure out what list to delete from - it could be any of the issues in any of the titles. The solution is to remember which list the item to be deleted occurs in. Say we have two lists: >>> a=[1, 2, 3, 4, 5] >>> b=[3, 4, 5, 6] If I tell you to remove item 3, what will you do? But if I tell you to remove item 3 from list b, you know what to do. So the list of things to delete has to include information about the list to delete from. Say we want to remove 3 from b and 4 from a: >>> d=[ (3, b), (4, a) ] Now d is a list of tuples. Each tuple tells me an item to delete from a specific list. Here's how to remove them: >>> for val, lst in d: ... lst.remove(val) ... >>> a [1, 2, 3, 5] >>> b [4, 5, 6] You need to do something like this. Your list of things to remove has to include a reference to the list from which to remove it. Kent At 03:01 PM 9/27/2004 +0100, Adam Cripps wrote: >My python project (http://savannah.nongnu.org/projects/newmag) is >teaching me a fair bit about how to write python code. However, I'm >still a long way away from being remotely good, as some of my recent >posts have shown. > >I'm working on deleting instance objects and I've created a list of >objects which is then piped through a menu to allow the user to choose >which one is deleted. > >The basic structure of the code is this: > > * choose_what_to_edit - creates a list which calls return_object_list > * return_object_list - return_object_list -chooses what level >the user wants to select an object > * choosetitle - selects a title > * chooseissue - if necssary selects an issue from the > selected title > * choosearticle - and if nescessary, selects an article >from the selected issue. > >Basically, from this code, I get a list, which has objects within it. >If I alter the objects within this list, how do I make them permanent? >I'm currently trying to delete an item/object of the list the command >del returned_list[choice] - however, this doesn't seem to be a >permanent change. For the full code listing, please see the CVS >project page. > >Am I right in thinking that the list of objects will be referenced >through to the actual instances, and if so, why aren't they being >deleted? I've read some of the python docs, but can't see the solution >here and would appreciate a more informed/specialised approach. > >TIA. >Adam >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From flaxeater at yahoo.com Tue Sep 28 06:25:02 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Tue Sep 28 06:25:07 2004 Subject: [Tutor] Acting on objects in a list - how to make the change permanent? Message-ID: <20040928042502.42853.qmail@web52605.mail.yahoo.com> Kent Johnson wrote: > Adam, > > You are confusing a "list of things that should be deleted" with the > list from which they should be deleted. > > For example suppose I have the list [1, 2, 3, 4, 5]: > >>> a=[1, 2, 3, 4, 5] > >>> a > [1, 2, 3, 4, 5] > > Now I get a list of things to delete from a: > >>> d=[1, 3] > > Deleting something from d will not be helpful! > >>> d.remove(1) > >>> a > [1, 2, 3, 4, 5] > >>> d > [3] > > I have to remove from a: > >>> d=[1, 3] > >>> for i in d: > ... a.remove(i) > ... > >>> d > [1, 3] > >>> a > [2, 4, 5] > > OK, now in your real code, you have a nested structure of lists - a > magazine collection has titles which have issues which have articles. > So it's not so simple, when you have just the list d, to figure out > what list to delete from - it could be any of the issues in any of the > titles. > > The solution is to remember which list the item to be deleted occurs > in. Say we have two lists: > >>> a=[1, 2, 3, 4, 5] > >>> b=[3, 4, 5, 6] > > If I tell you to remove item 3, what will you do? But if I tell you to > remove item 3 from list b, you know what to do. So the list of things > to delete has to include information about the list to delete from. > Say we want to remove 3 from b and 4 from a: > >>> d=[ (3, b), (4, a) ] > > Now d is a list of tuples. Each tuple tells me an item to delete from > a specific list. Here's how to remove them: > >>> for val, lst in d: > ... lst.remove(val) > ... > >>> a > [1, 2, 3, 5] > >>> b > [4, 5, 6] > I like this however if you use remove it only removes the first value of that not an index. If you have duplicate values then this may not work this is how I normally remove certain items from a list. >>> a=range(10) >>> b=[] >>> for index,value in enumerate(a): if value%2==0: b.append(index) >>> b [0, 2, 4, 6, 8] >>> b.reverse() >>> for x in b: del a[x] >>> a [1, 3, 5, 7, 9] >>> I reverse b because it holds the values of indexes that I need, if I delete them in the orignal order than I will get out of index errors (I know from experience) so when deleting a series from lists do it from back to front. Just another way. __________________________________ Do you Yahoo!? Yahoo! Mail is new and improved - Check it out! http://promotions.yahoo.com/new_mail From kabads at gmail.com Tue Sep 28 07:47:52 2004 From: kabads at gmail.com (Adam Cripps) Date: Tue Sep 28 07:47:57 2004 Subject: [Tutor] Acting on objects in a list - how to make the change permanent? In-Reply-To: <6.1.0.6.0.20040927220012.028bcfc0@mail4.skillsoft.com> References: <c7ff3855040927070139ffeb56@mail.gmail.com> <6.1.0.6.0.20040927220012.028bcfc0@mail4.skillsoft.com> Message-ID: <c7ff385504092722473dfcc798@mail.gmail.com> On Mon, 27 Sep 2004 22:13:05 -0400, Kent Johnson <kent_johnson@skillsoft.com> wrote: > Adam, > > You are confusing a "list of things that should be deleted" with the list > from which they should be deleted. > > For example suppose I have the list [1, 2, 3, 4, 5]: > >>> a=[1, 2, 3, 4, 5] > >>> a > [1, 2, 3, 4, 5] > > Now I get a list of things to delete from a: > >>> d=[1, 3] > > Deleting something from d will not be helpful! > >>> d.remove(1) > >>> a > [1, 2, 3, 4, 5] > >>> d > [3] > > I have to remove from a: > >>> d=[1, 3] > >>> for i in d: > ... a.remove(i) > ... > >>> d > [1, 3] > >>> a > [2, 4, 5] > > OK, now in your real code, you have a nested structure of lists - a > magazine collection has titles which have issues which have articles. So > it's not so simple, when you have just the list d, to figure out what list > to delete from - it could be any of the issues in any of the titles. > > The solution is to remember which list the item to be deleted occurs in. > Say we have two lists: > >>> a=[1, 2, 3, 4, 5] > >>> b=[3, 4, 5, 6] > > If I tell you to remove item 3, what will you do? But if I tell you to > remove item 3 from list b, you know what to do. So the list of things to > delete has to include information about the list to delete from. Say we > want to remove 3 from b and 4 from a: > >>> d=[ (3, b), (4, a) ] > > Now d is a list of tuples. Each tuple tells me an item to delete from a > specific list. Here's how to remove them: > >>> for val, lst in d: > ... lst.remove(val) > ... > >>> a > [1, 2, 3, 5] > >>> b > [4, 5, 6] > > You need to do something like this. Your list of things to remove has to > include a reference to the list from which to remove it. > > Kent > <snip> Kent, What you're suggesting sounds like the kind of thing that was going on in my head, without me being to articulate it - I knew I had the list, but not how to refer it to all the other data, which is crucial. Thanks for this excellent advice. I will try and build a function which creates a whole collection of lists (should be three, nested within one another) holding all the instances, which the user will then choose through the items (through the hierarchy of nests) and then delete one. Should that then delete the item? Thanks again Adam From Pawel_Kraszewski at wp.pl Tue Sep 28 09:05:40 2004 From: Pawel_Kraszewski at wp.pl (Pawel Kraszewski) Date: Tue Sep 28 09:06:01 2004 Subject: [Tutor] List intersect In-Reply-To: <20040927171247.GA22220@qwestip.net> References: <20040927171247.GA22220@qwestip.net> Message-ID: <200409280905.40529.Pawel_Kraszewski@wp.pl> Hello! I guess it may be done like this: >>> import sets >>> a=sets.Set() >>> a=a.union(['a','b','c']) >>> print a Set(['a', 'c', 'b']) >>> a=a.union(['b','c','d']) >>> print a Set(['a', 'c', 'b', 'd']) So, for the price of loosing original order of items, we have pretty intuitive usage. 'Set' keeps one copy of item, no matter how many times added. Oh, by the way - 'list intersect' is a common part of intersecting lists (the result would be just ['b','c']). You are talking of list union. Being a teacher I couldn't resist. :) Hope it helps. -- Pawel Kraszewski FreeBSD/Linux E-Mail/Jabber Phone ICQ GG Pawel_Kraszewski@wp.pl +48 604 777447 45615564 69381 From nick at javacat.f2s.com Tue Sep 28 10:22:53 2004 From: nick at javacat.f2s.com (nick@javacat.f2s.com) Date: Tue Sep 28 10:22:55 2004 Subject: [Tutor] Advice on storing data Message-ID: <1096359773.41591f5d33658@webmail.freedom2surf.net> Hi folks, if this isn't too far off topic I'd just like some advice please. Here at work we regularly get in contact with hardware/software suppliers to report bugs/problems etc, and the problem and related fix info is kept in a book !! Im thinking of making a software version of this book, so that a user can search past problems and see what was done to resolve it. Only problem is I cant really use a database to store the data, so I guess a text file is the only way ? The text file is likely to be a couple of megs in size. Also when the program runs would it be best for the program to read the whole text file into a dictionary then search the dictionary ? Or search the text file, and create a dictionary from the closes matches, then maybe search the dictionary again for more exact matches ? I realise this is quite an open question, but I'd appreciate any info on the best non-database way to approach this problem. Many thanks Nick. ------------------------------------------------- Everyone should have http://www.freedom2surf.net/ From amonroe at columbus.rr.com Tue Sep 28 12:44:07 2004 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Tue Sep 28 12:44:15 2004 Subject: [Tutor] Advice on storing data In-Reply-To: <1096359773.41591f5d33658@webmail.freedom2surf.net> References: <1096359773.41591f5d33658@webmail.freedom2surf.net> Message-ID: <1581336339714.20040928064407@columbus.rr.com> > Im thinking of making a software version of this book, so that a user can search > past problems and see what was done to resolve it. > Only problem is I cant really use a database to store the data, so I guess a Why not? This is the type of thing databases were made for. Alan From nick at javacat.f2s.com Tue Sep 28 13:33:29 2004 From: nick at javacat.f2s.com (nick@javacat.f2s.com) Date: Tue Sep 28 13:33:32 2004 Subject: [Tutor] Advice on storing data In-Reply-To: <1581336339714.20040928064407@columbus.rr.com> References: <1096359773.41591f5d33658@webmail.freedom2surf.net> <1581336339714.20040928064407@columbus.rr.com> Message-ID: <1096371209.41594c0998a12@webmail.freedom2surf.net> Quoting "R. Alan Monroe" <amonroe@columbus.rr.com>: > > Im thinking of making a software version of this book, so that a user can > search > > past problems and see what was done to resolve it. > > > Only problem is I cant really use a database to store the data, so I guess > a > > Why not? This is the type of thing databases were made for. Because this is being developed on my under developed laptop :) When it's finished I'll put it on a windows server so everyone can use it, but I wont be allowed to create a DB just for it (unless it proves really useful). Actually, I could put mysql on the windows server and use that .... Hmm answered my own question! All our databases here are Oracle on HPUX, but a little mysql db would do the job. Thanks for kicking my head into gear ;) Nick. ------------------------------------------------- Everyone should have http://www.freedom2surf.net/ From kent_johnson at skillsoft.com Tue Sep 28 13:54:44 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Tue Sep 28 13:54:47 2004 Subject: [Tutor] Advice on storing data In-Reply-To: <1096371209.41594c0998a12@webmail.freedom2surf.net> References: <1096359773.41591f5d33658@webmail.freedom2surf.net> <1581336339714.20040928064407@columbus.rr.com> <1096371209.41594c0998a12@webmail.freedom2surf.net> Message-ID: <6.1.0.6.0.20040928075351.028bb7d0@mail4.skillsoft.com> You could also use an embedded database like SQLite or MetaKit and no one even needs to know it is there, it is just an implementation detail :-) Kent At 12:33 PM 9/28/2004 +0100, nick@javacat.f2s.com wrote: >Quoting "R. Alan Monroe" <amonroe@columbus.rr.com>: > > > > Im thinking of making a software version of this book, so that a user can > > search > > > past problems and see what was done to resolve it. > > > > > Only problem is I cant really use a database to store the data, so I > guess > > a > > > > Why not? This is the type of thing databases were made for. > >Because this is being developed on my under developed laptop :) >When it's finished I'll put it on a windows server so everyone can use it, >but I >wont be allowed to create a DB just for it (unless it proves really useful). > >Actually, I could put mysql on the windows server and use that .... Hmm >answered >my own question! All our databases here are Oracle on HPUX, but a little mysql >db would do the job. > >Thanks for kicking my head into gear ;) > >Nick. > > > > >------------------------------------------------- >Everyone should have http://www.freedom2surf.net/ >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From nick at javacat.f2s.com Tue Sep 28 14:12:03 2004 From: nick at javacat.f2s.com (nick@javacat.f2s.com) Date: Tue Sep 28 14:12:04 2004 Subject: [Tutor] Advice on storing data In-Reply-To: <6.1.0.6.0.20040928075351.028bb7d0@mail4.skillsoft.com> References: <1096359773.41591f5d33658@webmail.freedom2surf.net> <1581336339714.20040928064407@columbus.rr.com> <1096371209.41594c0998a12@webmail.freedom2surf.net> <6.1.0.6.0.20040928075351.028bb7d0@mail4.skillsoft.com> Message-ID: <1096373523.415955134d653@webmail.freedom2surf.net> Quoting Kent Johnson <kent_johnson@skillsoft.com>: > You could also use an embedded database like SQLite or MetaKit and no one > even needs to know it is there, it is just an implementation detail :-) Ha good idea. I'll go get sqlite and pysqlite and have a play. Thanks Nick. ------------------------------------------------- Everyone should have http://www.freedom2surf.net/ From amonroe at columbus.rr.com Tue Sep 28 14:48:51 2004 From: amonroe at columbus.rr.com (R. Alan Monroe) Date: Tue Sep 28 14:48:58 2004 Subject: [Tutor] Advice on storing data In-Reply-To: <1096371209.41594c0998a12@webmail.freedom2surf.net> References: <1096359773.41591f5d33658@webmail.freedom2surf.net> <1581336339714.20040928064407@columbus.rr.com> <1096371209.41594c0998a12@webmail.freedom2surf.net> Message-ID: <541343823115.20040928084851@columbus.rr.com> > Quoting "R. Alan Monroe" <amonroe@columbus.rr.com>: >> > Im thinking of making a software version of this book, so that a user can >> search >> > past problems and see what was done to resolve it. >> >> > Only problem is I cant really use a database to store the data, so I guess >> a >> >> Why not? This is the type of thing databases were made for. > Because this is being developed on my under developed laptop :) > When it's finished I'll put it on a windows server so everyone can use it, but I > wont be allowed to create a DB just for it (unless it proves really useful). > Actually, I could put mysql on the windows server and use that .... Hmm answered > my own question! All our databases here are Oracle on HPUX, but a little mysql > db would do the job. mysql might even be overkill, sqlite could do it, and there's a python module for it. Alan From flaxeater at yahoo.com Tue Sep 28 17:23:58 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Tue Sep 28 17:29:17 2004 Subject: [Tutor] ImportError: DLL load failed Message-ID: <20040928152359.46871.qmail@web52609.mail.yahoo.com> Ajay wrote: >windows CE, and i have added it to sys.path, isn't that $PATH? > >cheers > > No $PATH is an os environment variable, try going to command shell then type >path and you will see the path. This is where the os looks for things whenever it told to find a file that does not have an absolute path to it. If your openssl directory i s not in there then this will cause this problem. I'm not really sure about how to do this on CE so look up how to add directories to CE on google. Good Day _______________________________ Do you Yahoo!? Declare Yourself - Register online to vote today! http://vote.yahoo.com From tktucker at gmail.com Tue Sep 28 17:47:31 2004 From: tktucker at gmail.com (Tom Tucker) Date: Tue Sep 28 17:47:33 2004 Subject: [Tutor] Modify a string multiple times Message-ID: <2a278ffe04092808474c4ffe98@mail.gmail.com> Hello all! I am struggling again with something minor. I suspect I am making this more complicable than what is required. Ha! I am trying to modify a simple string twice when it is being readin from a file. As you can see in the below Python example this code does work, however the string name changes from line, to newstring, and then to newstring2. I want the string name to remain as "line" as seen in the Perl example. Make sense? Any recommendations on how to achieve this? Python ######## < extra lines removed> line = 'python and perl are both programming languages.' newstring = re.sub('python','Python',line) newstring2 = re.sub('perl','Perl',newstring) print newstring2 Perl ######### $line = "python and perl are both programming languages"; $line =~ s/python/Python/g; $line =~ s/perl/Perl/g; print "$line\n"; * Notice how the Perl variable $line remains the same. END RESULT: Python and Perl are both programming Languages Thanks, Tom From flaxeater at yahoo.com Tue Sep 28 19:00:57 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Tue Sep 28 19:10:43 2004 Subject: [Tutor] Modify a string multiple times Message-ID: <20040928170057.23424.qmail@web52608.mail.yahoo.com> Tom Tucker wrote: >Python >######## >< extra lines removed> >line = 'python and perl are both programming languages.' >newstring = re.sub('python','Python',line) >newstring2 = re.sub('perl','Perl',newstring) >print newstring2 > Yup I think you are making this to hard. line='python and perl are both programming languages.' line=re.sub("python",'Python',line) line=re.sub("perl","Perl",.line) print line __________________________________ Do you Yahoo!? New and Improved Yahoo! Mail - 100MB free storage! http://promotions.yahoo.com/new_mail From dyoo at hkn.eecs.berkeley.edu Tue Sep 28 19:28:44 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Sep 28 19:28:49 2004 Subject: [Tutor] Modify a string multiple times In-Reply-To: <20040928170057.23424.qmail@web52608.mail.yahoo.com> Message-ID: <Pine.LNX.4.44.0409281021520.4918-100000@hkn.eecs.berkeley.edu> On Tue, 28 Sep 2004, Chad Crabtree wrote: > >line = 'python and perl are both programming languages.' > >newstring = re.sub('python','Python',line) > >newstring2 = re.sub('perl','Perl',newstring) > >print newstring2 > > > Yup I think you are making this to hard. > > line='python and perl are both programming languages.' > line=re.sub("python",'Python',line) > line=re.sub("perl","Perl",.line) > print line Hi Tom, Yes, the '=' operator stands for "assignment", not "equality". The difference is that assignment is an action, and timing's involved. The way that Python deals with assignments: left_hand_side = right_hand_side is to first figure out the value of the right_hand_side, and then set that value into left_hand_side. So that's why it's ok to say: line = re.sub("python",'Python', line) because even though "line" appears on both the left hand and right hand sides, Python doesn't do both sides simultaneously. Instead, it'll first compute the substitution string from the expression: re.sub("python",'Python', line) and after it's done computing the value, it'll then plug it right back into 'line'. Hope this helps! From s.e.murdock at soton.ac.uk Tue Sep 28 20:31:31 2004 From: s.e.murdock at soton.ac.uk (Stuart Murdock) Date: Tue Sep 28 20:31:43 2004 Subject: [Tutor] Unity matrix Message-ID: <4159AE03.7070601@soton.ac.uk> Hi python dudes, Does anyone know if there is a builtin to numarray (or an add on ) to give me a unity matrix. It would look better than trying to add ones along the diagonal of a zeros. I want something like A = unity((2)) to produce the same as A = array([[1 0],[0,1]]) Thanks Stuart -- Stuart Murdock Ph.D, Research Fellow, Dept. of Chemistry / E-Science, University of Southampton, Highfield, Southampton, SO17 1BJ, United Kingdom http://www.biosimgrid.org From jeff at ccvcorp.com Tue Sep 28 20:44:52 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Tue Sep 28 20:43:04 2004 Subject: [Tutor] Advice on storing data In-Reply-To: <1096359773.41591f5d33658@webmail.freedom2surf.net> References: <1096359773.41591f5d33658@webmail.freedom2surf.net> Message-ID: <4159B124.70304@ccvcorp.com> nick@javacat.f2s.com wrote: >Here at work we regularly get in contact with hardware/software suppliers to >report bugs/problems etc, and the problem and related fix info is kept in a >book !! > >Im thinking of making a software version of this book, so that a user can search >past problems and see what was done to resolve it. > > While, as others have said, you can implement a little database-driven tracker yourself, it often makes more sense to build on what others have already done. You might want to take a look at Roundup ( http://roundup.sourceforge.net ) -- it's designed primarily as a bug-tracker, but flexible enough to be useful for a much wider range of things. It can be used with a variety of backend databases (such as mysql, sqlite, or bsddb) to more easily fit particular needs, and includes a web interface and an email interface so it's easy to use. And it's written in Python. :) (The most difficult part of customizing it, IMO, is dealing with the web interface's HTML templating...) Jeff Shannon Technician/Programmer Credit International From tktucker at gmail.com Tue Sep 28 20:55:28 2004 From: tktucker at gmail.com (Tom Tucker) Date: Tue Sep 28 20:55:32 2004 Subject: [Tutor] Modify a string multiple times In-Reply-To: <Pine.LNX.4.44.0409281021520.4918-100000@hkn.eecs.berkeley.edu> References: <20040928170057.23424.qmail@web52608.mail.yahoo.com> <Pine.LNX.4.44.0409281021520.4918-100000@hkn.eecs.berkeley.edu> Message-ID: <2a278ffe04092811554248df37@mail.gmail.com> Thank you guys! <sigh> If you only knew how long I spent screw'n with this last night. Ha! Have a good one, Tom On Tue, 28 Sep 2004 10:28:44 -0700 (PDT), Danny Yoo <dyoo@hkn.eecs.berkeley.edu> wrote: > > > On Tue, 28 Sep 2004, Chad Crabtree wrote: > > > >line = 'python and perl are both programming languages.' > > >newstring = re.sub('python','Python',line) > > >newstring2 = re.sub('perl','Perl',newstring) > > >print newstring2 > > > > > Yup I think you are making this to hard. > > > > line='python and perl are both programming languages.' > > line=re.sub("python",'Python',line) > > line=re.sub("perl","Perl",.line) > > print line > > > Hi Tom, > > Yes, the '=' operator stands for "assignment", not "equality". The > difference is that assignment is an action, and timing's involved. > > The way that Python deals with assignments: > > left_hand_side = right_hand_side > > is to first figure out the value of the right_hand_side, and then set that > value into left_hand_side. > > So that's why it's ok to say: > > line = re.sub("python",'Python', line) > > because even though "line" appears on both the left hand and right hand > sides, Python doesn't do both sides simultaneously. Instead, it'll first > compute the substitution string from the expression: > > re.sub("python",'Python', line) > > and after it's done computing the value, it'll then plug it right back > into 'line'. > > Hope this helps! > > From prospero at prosperosisland.co.uk Tue Sep 28 21:47:31 2004 From: prospero at prosperosisland.co.uk (Prospero) Date: Tue Sep 28 21:46:36 2004 Subject: [Tutor] Files and such Message-ID: <000901c4a593$fe90e220$e7f22ad9@user> Greetings! I have a question which is almost certainly similar or identical to one I asked some months or years back. However, since I have been away from programming for a while and cannot access my email archive due to arguments between my computers, I hope the group will be tolerant about this. I need to save some numbers in a text file. This bit I can do no problem but then I need a different part of the program to read these numbers one set at a time, starting at the beginning and stopping at the end. For preference the file should be plain text so that I can amend it by hand if necessary. Any clues about how to do this would be much appreciated. All the best, Prospero. From flaxeater at yahoo.com Tue Sep 28 22:51:14 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Tue Sep 28 23:06:02 2004 Subject: [Tutor] Files and such Message-ID: <20040928205115.31499.qmail@web52608.mail.yahoo.com> Prospero wrote: >Greetings! > >I have a question which is almost certainly similar or identical to one I asked >some months or years back. However, since I have been away from programming for >a while and cannot access my email archive due to arguments between my >computers, I hope the group will be tolerant about this. > >I need to save some numbers in a text file. This bit I can do no problem but >then I need a different part of the program to read these numbers one set at a >time, starting at the beginning and stopping at the end. For preference the file >should be plain text so that I can amend it by hand if necessary. Any clues >about how to do this would be much appreciated. > >All the best, > >Prospero. > > Tell us what you would like the format to look like. Or rather what it does look like __________________________________ Do you Yahoo!? Y! Messenger - Communicate in real time. Download now. http://messenger.yahoo.com From dyoo at hkn.eecs.berkeley.edu Tue Sep 28 23:21:54 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Tue Sep 28 23:22:00 2004 Subject: [Tutor] Unity matrix In-Reply-To: <4159AE03.7070601@soton.ac.uk> Message-ID: <Pine.LNX.4.44.0409281415430.13192-100000@hkn.eecs.berkeley.edu> On Tue, 28 Sep 2004, Stuart Murdock wrote: > Does anyone know if there is a builtin to numarray (or an add on ) to > give me a unity matrix. It would look better than trying to add ones > along the diagonal of a zeros. Hi Stuart, You're probably looking for the identity() function: ### >>> numarray.identity(5) array([[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]]) ### Numarray has extensive documentation --- you can find more information on the array-generating functions here: http://stsdas.stsci.edu/numarray/Doc/node22.html#l2h-36 From s.e.murdock at soton.ac.uk Tue Sep 28 23:28:42 2004 From: s.e.murdock at soton.ac.uk (Stuart Murdock) Date: Tue Sep 28 23:29:06 2004 Subject: [Tutor] Unity matrix In-Reply-To: <Pine.LNX.4.44.0409281415430.13192-100000@hkn.eecs.berkeley.edu> References: <Pine.LNX.4.44.0409281415430.13192-100000@hkn.eecs.berkeley.edu> Message-ID: <4159D78A.4020806@soton.ac.uk> Hi Danny, Danny Yoo wrote: >On Tue, 28 Sep 2004, Stuart Murdock wrote: > > > >>Does anyone know if there is a builtin to numarray (or an add on ) to >>give me a unity matrix. It would look better than trying to add ones >>along the diagonal of a zeros. >> >> > >Hi Stuart, > > >You're probably looking for the identity() function: > >### > > Brilliant, thats exactly what I am looking for. Stuart >>>>numarray.identity(5) >>>> >>>> >array([[1, 0, 0, 0, 0], > [0, 1, 0, 0, 0], > [0, 0, 1, 0, 0], > [0, 0, 0, 1, 0], > [0, 0, 0, 0, 1]]) >### > >Numarray has extensive documentation --- you can find more information on >the array-generating functions here: > > http://stsdas.stsci.edu/numarray/Doc/node22.html#l2h-36 > > >. > > > -- Stuart Murdock Ph.D, Research Fellow, Dept. of Chemistry / E-Science, University of Southampton, Highfield, Southampton, SO17 1BJ, United Kingdom http://www.biosimgrid.org From missive at hotmail.com Tue Sep 28 23:29:59 2004 From: missive at hotmail.com (Lee Harr) Date: Tue Sep 28 23:35:11 2004 Subject: [Tutor] Re: Please advice me on my code Message-ID: <BAY2-F224DVvm24TzmK0000f8a6@hotmail.com> import sys, os import cgi import cgitb; cgitb.enable() import pg def form(): print """<form method="post" action=""> <p><input type=radio name="qtype"value="shot_number" checked />Shot Number<br /> <input type=radio name="qtype" value="project" />Project </p> <p>Type your keywords search here:<br> <textarea name="qtext" value="" rows=2 cols=80 type="text"></textarea> </p> <input type="submit" value="SEARCH"><br> </form>""" print "Content-Type: text/html\n\n" print '<head><title>The Title</title></head><body>' if __name__ == "__main__": data = cgi.FieldStorage() if data: qtype = data['qtype'].value try: qtext = data['qtext'].value except KeyError: qtext = '' if qtext and qtype=="shot_number": print "You typed this:", qtext # Now, we can get to the database... db = pg.connect('test', user='test', passwd='testpasswd') # This next line is not the right way to do this. You want # to use the db connector's quoting system, but I do not see # how to do that with the pg module. This method will leave # you wide open to SQL injection attacks... be forewarned! # # I recommend asking on comp.lang.python if you cannot find # more assistance here on tutor. query = "select * from a where x=%(qtext)s" % {'qtext': qtext} # a is a table with 2 columns (x int, y text) qresult = db.query(query) listOfResults = qresult.dictresult() print "<p>Example of pulling the list of dictionary results apart.</p>" for record in listOfResults: print "<p><table>" for k in record.keys(): print '<tr>' print '<td>key:</td> <td>', k, '</td>' print '<td>value:</td><td>', record[k], '</td>' print '</tr>' print '</table></p>' db.close() elif qtext and qtype == "project": print "You typed this:", qtext elif not qtext: print 'no text entered' else: form() print '<body></html>' _________________________________________________________________ The new MSN 8: smart spam protection and 2 months FREE* http://join.msn.com/?page=features/junkmail From nick at javacat.f2s.com Tue Sep 28 23:55:54 2004 From: nick at javacat.f2s.com (Nick Lunt) Date: Tue Sep 28 23:51:44 2004 Subject: [Tutor] Advice on storing data In-Reply-To: <4159B124.70304@ccvcorp.com> Message-ID: <FBEKICNGPAKNIMBBNHGKMELPCBAA.nick@javacat.f2s.com> Thanks for the info Jeff. However, I fancy reinventing the wheel, to teach myself something along the way :) Cheers Nick. -----Original Message----- From: tutor-bounces@python.org [mailto:tutor-bounces@python.org]On Behalf Of Jeff Shannon Sent: 28 September 2004 19:45 Cc: tutor@python.org Subject: Re: [Tutor] Advice on storing data nick@javacat.f2s.com wrote: >Here at work we regularly get in contact with hardware/software suppliers to >report bugs/problems etc, and the problem and related fix info is kept in a >book !! > >Im thinking of making a software version of this book, so that a user can search >past problems and see what was done to resolve it. > > While, as others have said, you can implement a little database-driven tracker yourself, it often makes more sense to build on what others have already done. You might want to take a look at Roundup ( http://roundup.sourceforge.net ) -- it's designed primarily as a bug-tracker, but flexible enough to be useful for a much wider range of things. It can be used with a variety of backend databases (such as mysql, sqlite, or bsddb) to more easily fit particular needs, and includes a web interface and an email interface so it's easy to use. And it's written in Python. :) (The most difficult part of customizing it, IMO, is dealing with the web interface's HTML templating...) Jeff Shannon Technician/Programmer Credit International _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor --- Incoming mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.770 / Virus Database: 517 - Release Date: 27/09/2004 --- Outgoing mail is certified Virus Free. Checked by AVG anti-virus system (http://www.grisoft.com). Version: 6.0.770 / Virus Database: 517 - Release Date: 27/09/2004 From tony at tcapp.com Wed Sep 29 03:15:09 2004 From: tony at tcapp.com (Tony Cappellini) Date: Wed Sep 29 03:12:43 2004 Subject: [Tutor] Documentation on properties In-Reply-To: <20040928100144.8D34B1E4012@bag.python.org> References: <20040928100144.8D34B1E4012@bag.python.org> Message-ID: <20040928180034.W3671@yamato.yamato.com> The following is straight out of the python documentation property( [fget[, fset[, fdel[, doc]]]]) Return a property attribute for new-style classes (classes that derive from object). fget is a function for getting an attribute value, likewise fset is a function for setting, and fdel a function for del'ing, an attribute. Typical use is to define a managed attribute x: class C(object): def getx(self): return self.__x def setx(self, value): self.__x = value def delx(self): del self.__x x = property(getx, setx, delx, "I'm the 'x' property.") Why is x not referred to as self.x in the x=property(getx, setx, delx, "") line ? From s4046441 at student.uq.edu.au Wed Sep 29 04:51:34 2004 From: s4046441 at student.uq.edu.au (Ms Soo Chong) Date: Wed Sep 29 04:53:41 2004 Subject: [Tutor] Re: Please advice me on my code Message-ID: <66f88a66d350.66d35066f88a@uq.edu.au> Lee Harr, Thank you so much for your help! It is very much appreciated. I know how it want to show but I don't know how to code. And you helped me greatly by doing this code!!! Thank you. Though, some of the functions are very new to me but with this I can learned faster by referring to an actual output and assist with python tutes. Perfect way of learning (at least to a newbie like me). I'm so grateful... I will try out the code and hopefully I can managed. Thanks again. Oh, one question, I don't really understand that which method of my code will leave wide open to SQL injection attacks? Can you please explain to me...sorry for that, I'm abit slow. Thank you. Shufen ----- Original Message ----- From: Lee Harr <missive@hotmail.com> Date: Wednesday, September 29, 2004 7:29 am Subject: [Tutor] Re: Please advice me on my code > import sys, os > import cgi > import cgitb; cgitb.enable() > > import pg > > > def form(): > print """<form method="post" action=""> > > <p><input type=radio name="qtype"value="shot_number" checked > />Shot > Number<br /> > <input type=radio name="qtype" value="project" />Project > </p> > > <p>Type your keywords search here:<br> > <textarea name="qtext" value="" rows=2 cols=80 type="text"></textarea> > </p> > > <input type="submit" value="SEARCH"><br> > </form>""" > > > > print "Content-Type: text/html\n\n" > print '<head><title>The Title</title></head><body>' > > > if __name__ == "__main__": > > data = cgi.FieldStorage() > > if data: > qtype = data['qtype'].value > try: > qtext = data['qtext'].value > except KeyError: > qtext = '' > > if qtext and qtype=="shot_number": > print "You typed this:", qtext > > # Now, we can get to the database... > db = pg.connect('test', user='test', passwd='testpasswd') > > # This next line is not the right way to do this. You want > # to use the db connector's quoting system, but I do > not see > # how to do that with the pg module. This method will > leave # you wide open to SQL injection attacks... be > forewarned! # > # I recommend asking on comp.lang.python if you cannot > find # more assistance here on tutor. > query = "select * from a where x=%(qtext)s" % > {'qtext': qtext} > # a is a table with 2 columns (x int, y text) > > qresult = db.query(query) > > listOfResults = qresult.dictresult() > > print "<p>Example of pulling the list of dictionary > results > apart.</p>" > > for record in listOfResults: > print "<p><table>" > for k in record.keys(): > print '<tr>' > print '<td>key:</td> <td>', k, '</td>' > print '<td>value:</td><td>', record[k], '</td>' > print '</tr>' > print '</table></p>' > > db.close() > > > elif qtext and qtype == "project": > print "You typed this:", qtext > > > elif not qtext: > print 'no text entered' > > else: > form() > > print '<body></html>' > > _________________________________________________________________ > The new MSN 8: smart spam protection and 2 months FREE* > http://join.msn.com/?page=features/junkmail > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From Derek.Weber at dsto.defence.gov.au Wed Sep 29 09:48:24 2004 From: Derek.Weber at dsto.defence.gov.au (Weber, Derek) Date: Wed Sep 29 09:53:44 2004 Subject: [Tutor] Question concerning splitting of arrays Message-ID: <8D98BD395C94D7119DF800306E0159660344B1A4@ednex506.dsto.defence.gov.au> Hi all, I'm actually doing something like translating some matlab code to Python and am wondering whether it's possible to split multi-dimensional arrays as such: >>> array = [[11, 12, 13], [21, 22, 23], [31, 32, 33]] >>> firstColumn = array[:][0] >>> lowerRightCorner = array[1:][1:] >>> print firstColumn [[11], [21], [31]] >>> print lowerRightCorner [[22, 23], [32, 33]] I seem to get errors when I do this, so I thought I'd ask people who knew a great deal more about the language than I did to see if there's an easy way to do this, or do I have to write some functions to do it for me? I think the issue is making the first array reference a range. Any suggestions would be gratefully accepted. Also, if there's a way to search the archive of the list, I'd do that, but I haven't had any luck with the one referred to by python.org. Thanks very much. D. ============================================================ Derek Weber derek.weber@dsto.defence.gov.au Information Exploitation Group Rm: 2.H.06 205Labs Defence Science & Technology Organisation Ph: 61 8 8259 7699 PO Box 1500, Edinburgh SA 5111 Fx: 61 8 8259 5619 ============================================================ From kent_johnson at skillsoft.com Tue Sep 28 11:51:17 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Wed Sep 29 10:28:28 2004 Subject: [Tutor] Acting on objects in a list - how to make the change permanent? In-Reply-To: <c7ff385504092722473dfcc798@mail.gmail.com> References: <c7ff3855040927070139ffeb56@mail.gmail.com> <6.1.0.6.0.20040927220012.028bcfc0@mail4.skillsoft.com> <c7ff385504092722473dfcc798@mail.gmail.com> Message-ID: <6.1.0.6.0.20040928054640.028c1c50@mail4.skillsoft.com> Adam, You don't need to recreate the hierarchy of lists in your list of things to delete. When you create the list of things to delete, you must save a reference to the _containing_ list. Look at what is in the tuples in my example below - it is the item to delete, and the list to delete it from. Take another look at my original answer to your question as well, it shows the same thing another way. http://mail.python.org/pipermail/tutor/2004-September/032027.html Kent At 06:47 AM 9/28/2004 +0100, Adam Cripps wrote: >On Mon, 27 Sep 2004 22:13:05 -0400, Kent Johnson ><kent_johnson@skillsoft.com> wrote: > > Adam, > > > > You are confusing a "list of things that should be deleted" with the list > > from which they should be deleted. > > > > For example suppose I have the list [1, 2, 3, 4, 5]: > > >>> a=[1, 2, 3, 4, 5] > > >>> a > > [1, 2, 3, 4, 5] > > > > Now I get a list of things to delete from a: > > >>> d=[1, 3] > > > > Deleting something from d will not be helpful! > > >>> d.remove(1) > > >>> a > > [1, 2, 3, 4, 5] > > >>> d > > [3] > > > > I have to remove from a: > > >>> d=[1, 3] > > >>> for i in d: > > ... a.remove(i) > > ... > > >>> d > > [1, 3] > > >>> a > > [2, 4, 5] > > > > OK, now in your real code, you have a nested structure of lists - a > > magazine collection has titles which have issues which have articles. So > > it's not so simple, when you have just the list d, to figure out what list > > to delete from - it could be any of the issues in any of the titles. > > > > The solution is to remember which list the item to be deleted occurs in. > > Say we have two lists: > > >>> a=[1, 2, 3, 4, 5] > > >>> b=[3, 4, 5, 6] > > > > If I tell you to remove item 3, what will you do? But if I tell you to > > remove item 3 from list b, you know what to do. So the list of things to > > delete has to include information about the list to delete from. Say we > > want to remove 3 from b and 4 from a: > > >>> d=[ (3, b), (4, a) ] > > > > Now d is a list of tuples. Each tuple tells me an item to delete from a > > specific list. Here's how to remove them: > > >>> for val, lst in d: > > ... lst.remove(val) > > ... > > >>> a > > [1, 2, 3, 5] > > >>> b > > [4, 5, 6] > > > > You need to do something like this. Your list of things to remove has to > > include a reference to the list from which to remove it. > > > > Kent > > <snip> > >Kent, > >What you're suggesting sounds like the kind of thing that was going on >in my head, without me being to articulate it - I knew I had the list, >but not how to refer it to all the other data, which is crucial. > >Thanks for this excellent advice. I will try and build a function >which creates a whole collection of lists (should be three, nested >within one another) holding all the instances, which the user will >then choose through the items (through the hierarchy of nests) and >then delete one. Should that then delete the item? > >Thanks again >Adam >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From max_russell2000 at yahoo.co.uk Wed Sep 29 11:20:01 2004 From: max_russell2000 at yahoo.co.uk (Max Russell) Date: Wed Sep 29 11:20:05 2004 Subject: [Tutor] anagram solving algorithm Message-ID: <20040929092001.39718.qmail@web25403.mail.ukl.yahoo.com> Hello here is a breakdown of an algorithm I'm using to write my own anagram solver: Prompt for location of dictionary file. take input letters from user. (error check that they are in range A..Z) read total number of input letters (x) read dictionary file for words that contain same number letters (y), as input letters (x) into (array 1) sort input letters & test against words in (array1) print output. My problem is at the sorting bit: what I am thinking of doing is looking first of all for all words in the wordlist of the same length, then eliminating those that do not start with one of the lestters contained within the anagram-word. Next I'd need to look at the second position in my worldlist word; if it is not a letter in my anagram word, then eliminate it, if it is in the anagram-word continue to the next position an check it, until the end position of the anagram word. My problem here is that it how to structure looking at each possibe word in the list: how to set up the loop for that, also how to do the sort/inspection of each word. I'm really only starting out with Python so any help would be appreciated. I've included what I have so far: #!/usr/bin/python import os, sys whichlist = "" whichlist = raw_input("Path to desired wordlist: "\n) file = open(whichlist, "r") wordlist = file.readlines() file.close() ana = "" ana = raw_input("Please enter anagram:") analength = len(ana) ___________________________________________________________ALL-NEW Yahoo! Messenger - all new features - even more fun! http://uk.messenger.yahoo.com From kent_johnson at skillsoft.com Wed Sep 29 11:50:31 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Wed Sep 29 11:50:37 2004 Subject: [Tutor] Documentation on properties In-Reply-To: <20040928180034.W3671@yamato.yamato.com> References: <20040928100144.8D34B1E4012@bag.python.org> <20040928180034.W3671@yamato.yamato.com> Message-ID: <6.1.0.6.0.20040929054732.028ca558@mail4.skillsoft.com> Tony, x is a property of the class, not of an instance of the class. That's why there is no self. The name 'x' is bound in the namespace of the class. This is actually what happens when you define a method, too - the method is a property of the class, it's name is bound in the class namespace. In fact there is no name 'self' at the point where x is defined; if you changed it to self.x you would get an error. Kent At 06:15 PM 9/28/2004 -0700, Tony Cappellini wrote: >The following is straight out of the python documentation > > property( [fget[, fset[, fdel[, doc]]]]) > >Return a property attribute for new-style classes (classes that derive >from object). >fget is a function for getting an attribute value, likewise fset is a >function for setting, and fdel a function for del'ing, an attribute. >Typical use is to define a managed attribute x: > > >class C(object): > def getx(self): return self.__x > def setx(self, value): self.__x = value > def delx(self): del self.__x > x = property(getx, setx, delx, "I'm the 'x' property.") > > > > > >Why is x not referred to as self.x in the x=property(getx, setx, delx, "") > line ? > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From s4046441 at student.uq.edu.au Wed Sep 29 14:09:26 2004 From: s4046441 at student.uq.edu.au (Ms Soo Chong) Date: Wed Sep 29 14:09:33 2004 Subject: [Tutor] Please advice me this code Message-ID: <67e58b680285.68028567e58b@uq.edu.au> Hi, Can someone please scan thru the attached code and tell me how should I code it in order to include more than one qtype? Any help is greatly appreciated. p/s: Lee Harr, Thanks so much for you help. You helped me to start up the whole thing. Thanks again Cheers, Shufen -------------- next part -------------- #!/usr/bin/env python #Created on: 29/09/04 #Help from Lee Harr - Python Tutor import sys, os import cgi import cgitb; cgitb.enable() import pg def form(): print """<form method="post" action=""> <p> <input type=checkbox name="qtype" value="all" checked /> All<br /> <input type=checkbox name="qtype" value="project" /> Project<br /> <input type=checkbox name="qtype" value="date_string" /> Date<br /> <input type=checkbox name="qtype" value="blame" /> Blame<br /> <input type=checkbox name="qtype" value="notes" /> Notes<br /></p> <p>Search by shot number:<br> <input type=text name="qtext" value="" /> <input type="submit" value="SEARCH"><br> </form>""" print "Content-Type: text/html\n\n" print '<head><title>Searching by using Shot Number</title></head><body>' if __name__ == "__main__": data = cgi.FieldStorage() if data: qtype = data['qtype'].value try: qtext = data['qtext'].value except KeyError: qtext = '' if qtype=="project": print "Shot Number:", qtext # Take care of the security problems after finishing the code. username = os.environ.get('USER') if username == None: username = 'apache' # Now, we can get to the database... db = pg.connect("moncdata", user=username, passwd=None) query = "select project from shot_descriptions where shot_number=%(qtext)s" % {'qtext': qtext} qresult = db.query(query) listOfResults = qresult.dictresult() print """<p>Example of pulling the list of dictionary results apart.</p>""" for record in listOfResults: print "<p><table>" for k in record.keys(): print '<tr>' print '<td>key:</td> <td>', k, '</td>' print '<td>value:</td><td>', record[k], '</td>' print '</tr>' print '</table></p>' db.close() #How should I code it, in order to get more than one qtype? elif qtype=="project" and "date_string": print "Shot Number:", qtext # Now, we can get to the database... username = os.environ.get('USER') if username == None: username = 'apache' db = pg.connect("moncdata", user=username, passwd=None) query = "select project, date_string from shot_descriptions where shot_number=%(qtext)s" % {'qtext': qtext} qresult = db.query(query) listOfResults = qresult.dictresult() print """<p>Example of pulling the list of dictionary results apart.</p>""" for record in listOfResults: print "<p><table>" for k in record.keys(): print '<tr>' print '<td>key:</td> <td>', k, '</td>' print '<td>value:</td><td>', record[k], '</td>' print '</tr>' print '</table></p>' db.close() elif qtype=="all": print "Shot Number:", qtext # Now, we can get to the database... username = os.environ.get('USER') if username == None: username = 'apache' db = pg.connect("moncdata", user=username, passwd=None) query = "select * from shot_descriptions where shot_number=%(qtext)s" % {'qtext': qtext} qresult = db.query(query) listOfResults = qresult.dictresult() print """<p>Example of pulling the list of dictionary results apart.</p>""" for record in listOfResults: print "<p><table>" for k in record.keys(): print '<tr>' print '<td>key:</td> <td>', k, '</td>' print '<td>value:</td><td>', record[k], '</td>' print '</tr>' print '</table></p>' db.close() elif not qtext: print 'Please type in shot number in order to perform a search!' else: form() print '<body></html>' From kent_johnson at skillsoft.com Wed Sep 29 14:38:52 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Wed Sep 29 14:38:57 2004 Subject: [Tutor] Question concerning splitting of arrays In-Reply-To: <8D98BD395C94D7119DF800306E0159660344B1A4@ednex506.dsto.def ence.gov.au> References: <8D98BD395C94D7119DF800306E0159660344B1A4@ednex506.dsto.defence.gov.au> Message-ID: <6.1.0.6.0.20040929055424.028ca038@mail4.skillsoft.com> Derek, You should look into the numarray package, it can do what you want. See http://stsdas.stsci.edu/numarray/numarray-1.1.html/node26.html for some examples. In standard Python, lists of lists are used to represent multi-dimensional arrays. Operations on multidimensional arrays are applied sequentially to the lists that represent the arrays. As you found out, this is not really a good model for full-featured matrix operations. Here is what is happening: >>> array = [[11, 12, 13], [21, 22, 23], [31, 32, 33]] array is a list of three elements. Each element is also a list of three elements. What does this mean? >>> array[1][2] 23 array[1][2] is the same as (array[1])[2]. It takes element 1 of array, which is the list [21, 22, 23], then takes element 2 of that list, which is 23. This is what you expect. What about this? >>> array[:][0] [11, 12, 13] Again, array[:][0] is the same as (array[:])[0]. array[:] is a copy of all of array! So you are copying array, then taking the first element of the copy. Not what you wanted at all. Finally, how about this? >>> array[1:][1:] [[31, 32, 33]] As before, array[1:][1:] is (array[1:])[1:]. array[1:] is everything but the first element of array; this is a list containing two lists: >>> array[1:] [[21, 22, 23], [31, 32, 33]] Now you take the slice [1:] of that list, and you are dropping the first element again. array[1:][1:] is the same as array[2:]! Kent At 05:18 PM 9/29/2004 +0930, Weber, Derek wrote: >Hi all, > >I'm actually doing something like translating some matlab code to Python >and am wondering whether it's possible to split multi-dimensional arrays >as such: > > >>> array = [[11, 12, 13], [21, 22, 23], [31, 32, 33]] > >>> firstColumn = array[:][0] > >>> lowerRightCorner = array[1:][1:] > >>> print firstColumn >[[11], [21], [31]] > >>> print lowerRightCorner >[[22, 23], [32, 33]] > >I seem to get errors when I do this, so I thought I'd ask people who knew >a great deal more about the language than I did to see if there's an easy >way to do this, or do I have to write some functions to do it for me? > >I think the issue is making the first array reference a range. > >Any suggestions would be gratefully accepted. Also, if there's a way to >search the archive of the list, I'd do that, but I haven't had any luck >with the one referred to by python.org. > >Thanks very much. > >D. > >============================================================ >Derek Weber derek.weber@dsto.defence.gov.au >Information Exploitation Group Rm: 2.H.06 205Labs >Defence Science & Technology Organisation Ph: 61 8 8259 7699 >PO Box 1500, Edinburgh SA 5111 Fx: 61 8 8259 5619 >============================================================ > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From project5 at redrival.net Wed Sep 29 19:54:23 2004 From: project5 at redrival.net (Andrei) Date: Wed Sep 29 19:54:28 2004 Subject: [Tutor] Re: Advice on storing data References: <4159B124.70304@ccvcorp.com> <FBEKICNGPAKNIMBBNHGKMELPCBAA.nick@javacat.f2s.com> Message-ID: <1iwjk09jh3f07.ynheots0tqog.dlg@40tude.net> Nick Lunt wrote on Tue, 28 Sep 2004 22:55:54 +0100: > Thanks for the info Jeff. However, I fancy reinventing the wheel, to teach > myself something along the way :) You can also use bsddb. It comes with Python and you can use it just like a dictionary. -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From dyoo at hkn.eecs.berkeley.edu Wed Sep 29 20:34:37 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Sep 29 20:34:43 2004 Subject: [Tutor] Please advice me this code In-Reply-To: <67e58b680285.68028567e58b@uq.edu.au> Message-ID: <Pine.LNX.4.44.0409291126120.23970-100000@hkn.eecs.berkeley.edu> On Wed, 29 Sep 2004, Ms Soo Chong wrote: > Can someone please scan thru the attached code and tell me how should I > code it in order to include more than one qtype? Hi Shufen, You may want to look through: http://www.python.org/doc/current/lib/node404.html The documentation there shows how to get multiple values off a checkboxed form element. The approach that you're taking now: #### qtype = data['qtype'].value try: qtext = data['qtext'].value except KeyError: qtext = '' ### is the older way of talking with the cgi module. There's a nicer "high level" interface that you may want to use: ### qtype = data.getfirst('qtype') qtext = data.getfirst('qtext', '') ### This approach is a bit cleaner as code. As a bonus, it's also easier to restructure this to read multiple qtype values. Good luck to you. From dyoo at hkn.eecs.berkeley.edu Wed Sep 29 20:44:25 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed Sep 29 20:44:29 2004 Subject: [Tutor] anagram solving algorithm In-Reply-To: <20040929092001.39718.qmail@web25403.mail.ukl.yahoo.com> Message-ID: <Pine.LNX.4.44.0409291135070.23970-100000@hkn.eecs.berkeley.edu> On Wed, 29 Sep 2004, Max Russell wrote: > Hello here is a breakdown of an algorithm I'm using to write my own > anagram solver: [text cut] > My problem here is that it how to structure looking at each possibe word > in the list: how to set up the loop for that, also how to do the > sort/inspection of each word. Hi Max, It sounds like you want to run a 'for' loop across every word in your wordlist. Here's an example of a for loop, just so you get the idea of what it can do: ### >>> def isEven(x): ... return x % 2 == 0 ... >>> numbers = [3, 1, 4, 1, 5, 9, 2, 6] >>> for n in numbers: ... print "I'm looking at", n ... if isEven(n): ... print n, "is even" ... else: ... print n, "is odd" ... I'm looking at 3 3 is odd I'm looking at 1 1 is odd I'm looking at 4 4 is even I'm looking at 1 1 is odd I'm looking at 5 5 is odd I'm looking at 9 9 is odd I'm looking at 2 2 is even I'm looking at 6 6 is even ### For more examples of loops, take a look at a tutorial like Alan's: http://www.freenetpages.co.uk/hp/alan.gauld/tutloops.htm There are two kinds of loops in Python: 1. for --- good for going across sequences. 2. while --- good for repeating something until some condition changes. 'for' can go across lists easily, so it's a good tool here. You can loop across a list with 'while' too, but it's not so idiomatic. Just as a last note: there's a very clever way to solve the anagram problem, and it does involve sorting. But let's see try to get your first solution working: we can talk about the clever approach later. *grin* Good luck to you! From kabads at gmail.com Wed Sep 29 22:08:31 2004 From: kabads at gmail.com (Adam Cripps) Date: Wed Sep 29 22:08:55 2004 Subject: [Tutor] Acting on objects in a list - how to make the change permanent? In-Reply-To: <6.1.0.6.0.20040928054640.028c1c50@mail4.skillsoft.com> References: <c7ff3855040927070139ffeb56@mail.gmail.com> <6.1.0.6.0.20040927220012.028bcfc0@mail4.skillsoft.com> <c7ff385504092722473dfcc798@mail.gmail.com> <6.1.0.6.0.20040928054640.028c1c50@mail4.skillsoft.com> Message-ID: <c7ff3855040929130854e86cee@mail.gmail.com> On Tue, 28 Sep 2004 05:51:17 -0400, Kent Johnson <kent_johnson@skillsoft.com> wrote: > Adam, > > You don't need to recreate the hierarchy of lists in your list of things to > delete. When you create the list of things to delete, you must save a > reference to the _containing_ list. Look at what is in the tuples in my > example below - it is the item to delete, and the list to delete it from. > Take another look at my original answer to your question as well, it shows > the same thing another way. > http://mail.python.org/pipermail/tutor/2004-September/032027.html > > Kent <snip> Kent, Thanks for this - I've gone underground since your last email and have managed to partly get my head around this to produce some code which works in deleting an object. However, it doesn't currently delete the correct object in the list. I'm finding it pass the instance location of the object. Passing the list itself now works, but currently the code always deletes the same item position which isn't effective. Currently the code [1] drills right down to the article level, with no other option, so the level code is really not important. The returned_list holds the list to delete from in [0] and the item to delete in [1]. However, how do I pass the location of the actual item, rather than the object itself? If I pass the object itself, it correctly throws an error up as only allowing to del with an integer. Is there a built in function for returning the position of an item? Once again, thanks for all the help. Adam [1] def return_a_list(self, level): if level == 0: level = raw_input("What would you like to search for? a - article / i - issue / t - title ") else: if level == "t" or level == "i" or level == "a": # Only doing a at the moment print " I got this far" chosen_title_object = self.choosetitle() chosen_issue_object = self.chooseissue(chosen_title_object) chosen_article_object = self.choosearticle(chosen_issue_object) returned_list = [chosen_issue_object.articlesheld, chosen_article_object] print returned_list return [returned_list] def choose_what_to_edit(self): # New attempt to try this one now level = 0 print " I got to choose_what_to_edit" returned_list = self.return_a_list("a") print returned_list raw_input("OK?") confirm = raw_input("Do you wish to delete this article? (y/n)") if confirm == "y": print "will be deleted" for list, item in returned_list: del list[1] # OK this is deleting, but always the first item else: print " will not be deleted " From missive at hotmail.com Wed Sep 29 23:00:28 2004 From: missive at hotmail.com (Lee Harr) Date: Wed Sep 29 23:11:14 2004 Subject: [Tutor] Re: Please advice me on my code Message-ID: <BAY2-F42IOp37Q6p2dz0002185e@hotmail.com> >Oh, one question, I don't really understand that which method of my code >will leave wide open to SQL injection attacks? >Can you please explain to me...sorry for that, I'm abit slow. > qtext = 5 query = "select * from a where x=%(qtext)s" % {'qtext': qtext} print query qtext = '5; delete from b;' query = "select * from a where x=%(qtext)s" % {'qtext': qtext} print query That is the basic problem. The db connector should have another way to quote your variables which is pretty much bulletproof. I am not sure how to do it with the pg module. You need to research that and make sure you do it right... _________________________________________________________________ Add photos to your messages with MSN 8. Get 2 months FREE*. http://join.msn.com/?page=features/featuredemail From kent_johnson at skillsoft.com Wed Sep 29 23:54:37 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Wed Sep 29 23:54:43 2004 Subject: [Tutor] Acting on objects in a list - how to make the change permanent? In-Reply-To: <c7ff3855040929130854e86cee@mail.gmail.com> References: <c7ff3855040927070139ffeb56@mail.gmail.com> <6.1.0.6.0.20040927220012.028bcfc0@mail4.skillsoft.com> <c7ff385504092722473dfcc798@mail.gmail.com> <6.1.0.6.0.20040928054640.028c1c50@mail4.skillsoft.com> <c7ff3855040929130854e86cee@mail.gmail.com> Message-ID: <6.1.0.6.0.20040929175248.028dae08@mail4.skillsoft.com> Adam, list.remove(item) will remove item from list without needing the index of item in list. Kent At 09:08 PM 9/29/2004 +0100, Adam Cripps wrote: >On Tue, 28 Sep 2004 05:51:17 -0400, Kent Johnson ><kent_johnson@skillsoft.com> wrote: > > Adam, > > > > You don't need to recreate the hierarchy of lists in your list of things to > > delete. When you create the list of things to delete, you must save a > > reference to the _containing_ list. Look at what is in the tuples in my > > example below - it is the item to delete, and the list to delete it from. > > Take another look at my original answer to your question as well, it shows > > the same thing another way. > > http://mail.python.org/pipermail/tutor/2004-September/032027.html > > > > Kent ><snip> > >Kent, > >Thanks for this - I've gone underground since your last email and have >managed to partly get my head around this to produce some code which >works in deleting an object. However, it doesn't currently delete the >correct object in the list. I'm finding it pass the instance location >of the object. Passing the list itself now works, but currently the >code always deletes the same item position which isn't effective. > >Currently the code [1] drills right down to the article level, with no >other option, so the level code is really not important. The >returned_list holds the list to delete from in [0] and the item to >delete in [1]. However, how do I pass the location of the actual item, >rather than the object itself? If I pass the object itself, it >correctly throws an error up as only allowing to del with an integer. >Is there a built in function for returning the position of an item? > >Once again, thanks for all the help. > >Adam > >[1] >def return_a_list(self, level): > if level == 0: > level = raw_input("What would you like to search > for? a - article / >i - issue / t - title ") > else: > if level == "t" or level == "i" or level == "a": > # Only doing a at the moment > print " I got this far" > chosen_title_object = self.choosetitle() > chosen_issue_object = > self.chooseissue(chosen_title_object) > chosen_article_object = > self.choosearticle(chosen_issue_object) > returned_list = > [chosen_issue_object.articlesheld, chosen_article_object] > print returned_list > return [returned_list] > > > def choose_what_to_edit(self): > # New attempt to try this one now > level = 0 > print " I got to choose_what_to_edit" > > returned_list = self.return_a_list("a") > print returned_list > raw_input("OK?") > confirm = raw_input("Do you wish to delete this article? > (y/n)") > if confirm == "y": > print "will be deleted" > for list, item in returned_list: > del list[1] # OK this is deleting, but > always the first item > else: > print " will not be deleted " >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From tony at tcapp.com Thu Sep 30 03:47:33 2004 From: tony at tcapp.com (Tony Cappellini) Date: Thu Sep 30 03:44:58 2004 Subject: [Tutor] conditionally defining classes In-Reply-To: <20040929215444.3BC781E400C@bag.python.org> References: <20040929215444.3BC781E400C@bag.python.org> Message-ID: <20040929183035.I26056@yamato.yamato.com> I've read some posts from Guido (I think) about defining a class within a class. From what I remember this was frowned upon, but I would expect arguments on both sides. Going off in another direction- is it Pythonic to conditionally define a class as in .. import sys OSVer= sys.getwindowsversion()[0] if OSVer == 5: class OSWinXp(object): def __init__(self): # XP specific code goes here elif OSVer == 4: class OsWin98(object): def __init__(self): # W98 specifc code goes here From jeff at ccvcorp.com Thu Sep 30 04:07:29 2004 From: jeff at ccvcorp.com (Jeff Shannon) Date: Thu Sep 30 04:05:51 2004 Subject: [Tutor] conditionally defining classes In-Reply-To: <20040929183035.I26056@yamato.yamato.com> References: <20040929215444.3BC781E400C@bag.python.org> <20040929183035.I26056@yamato.yamato.com> Message-ID: <415B6A61.4050003@ccvcorp.com> Tony Cappellini wrote: >Going off in another direction- is it Pythonic to conditionally define a >class as in .. > >import sys >OSVer= sys.getwindowsversion()[0] > >if OSVer == 5: > class OSWinXp(object): > def __init__(self): > # XP specific code goes here >elif OSVer == 4: > class OsWin98(object): > def __init__(self): > # W98 specifc code goes here > > That seems acceptable to me, but I'd probably define both classes and then use only the appropriate one -- class OSWinXp(object): # stuff class OSWin98(object): # stuff if OSVer == 5: OSWin = OSWinXp else: OSWin = OSWin98 my_os = OSWin() If you stuff all of the conditional stuff inside of a module, then you get a nice clean interface, with the client code never needing to know/care about the details. import OSWin my_os = OSWin.OSWin() This is roughly how the built-in os module works... Jeff Shannon Technician/Programmer Credit International From s4046441 at student.uq.edu.au Thu Sep 30 05:42:59 2004 From: s4046441 at student.uq.edu.au (Ms Soo Chong) Date: Thu Sep 30 05:43:04 2004 Subject: [Tutor] Sorry, Please advice me on this code Message-ID: <68f6d769320d.69320d68f6d7@uq.edu.au> Thanks to Lee Harr and Danny Yoo for the help. It is very much appreciated. Sorry, I know what I wanna to do but don't really know how to implement it in the code, so I need help again, sorry for that. As attached, shot_no1 & shot_no2, I changed : #### qtype = data['qtype'].value try: qtext = data['qtext'].value except KeyError: qtext = '' ### to ### qtype = data.getfirst('qtype') qtext = data.getfirst('qtext', '') ### but I still cant' quite get it rite. In shot_no1, I have to precode every single option ( checkedbox) the user ticked, which then my script will be very very long.(and I don't want it to be the case) In shot_no2, I try to code it in the way that the script get the value from the form and process it which have some errors in it (I know that the way that I do is wrong). Thus, can someone please help me to scan thru both of them and advice me on how should I code it so that I can keep my script clean and more readable. Sorry for all the trouble. I'm really not good in programming and still very new to it. Thanks for any help. Cheers, Shufen -------------- next part -------------- #!/usr/bin/env python #Created on: 30/09/04 #Help from Lee Harr and Danny Yoo - Python Tutor import sys, os import cgi import cgitb; cgitb.enable() import pg def form(): print """<form method="post" action=""> <p> <input type=checkbox name="qtype" value="all" checked /> All<br /> <input type=checkbox name="qtype" value="project" /> Project<br /> <input type=checkbox name="qtype" value="date_string" /> Date<br /> <input type=checkbox name="qtype" value="blame" /> Blame<br /> <input type=checkbox name="qtype" value="notes" /> Notes<br /></p> <p>Search by shot number:<br> <input type=text name="qtext" value="" /> <input type="submit" value="SEARCH"><br> </form>""" print "Content-Type: text/html\n\n" print "<head><title>Searching by using Shot Number</title></head><body>" if __name__ == "__main__": data = cgi.FieldStorage() if data: qtype = data.getfirst('qtype') qtext = data.getfirst('qtext','') if qtype == "all": print "You typed in Shot Number:", qtext #Now, we can get to the database... username = os.environ.get('USER') if username == None: username = 'apache' db = pg.connect("moncdata", user=username, passwd=None) query = "select * from shot_descriptions where shot_number=%(qtext)s" % {'qtext': qtext} qresult = db.query(query) listOfResults = qresult.dictresult() print """<p>Example of pulling the list of dictionary results apart.</p>""" for record in listOfResults: print "<p><table>" for k in record.keys(): print '<tr>' print '<td>key:</td> <td>', k, '</td>' print '<td>value:</td><td>', record[k], '</td>' print '</tr>' print '</table></p>' db.close() elif qtype == "project": print "You typed in Shot Number:", qtext #Now, we can get to the database... username = os.environ.get('USER') if username == None: username = 'apache' db = pg.connect("moncdata", user=username, passwd=None) query = "select project from shot_descriptions where shot_number=%(qtext)s" % {'qtext': qtext} qresult = db.query(query) listOfResults = qresult.dictresult() print """<p>Example of pulling the list of dictionary results apart.</p>""" for record in listOfResults: print "<p><table>" for k in record.keys(): print '<tr>' print '<td>key:</td> <td>', k, '</td>' print '<td>value:</td><td>', record[k], '</td>' print '</tr>' print '</table></p>' db.close() elif qtype == "date_string": print "You typed in Shot Number:", qtext #Now, we can get to the database... username = os.environ.get('USER') if username == None: username = 'apache' db = pg.connect("moncdata", user=username, passwd=None) query = "select date_string from shot_descriptions where shot_number=%(qtext)s" % {'qtext': qtext} qresult = db.query(query) listOfResults = qresult.dictresult() print """<p>Example of pulling the list of dictionary results apart.</p>""" for record in listOfResults: print "<p><table>" for k in record.keys(): print '<tr>' print '<td>key:</td> <td>', k, '</td>' print '<td>value:</td><td>', record[k], '</td>' print '</tr>' print '</table></p>' db.close() elif not qtext: print "You have no enter a shot number!" print "Please type a in shot number in order to perform a search!" else: form() print "</body></html>" -------------- next part -------------- #!/usr/bin/env python #Created on: 30/09/04 #Help from Lee Harr and Danny Yoo - Python Tutor import sys, os import cgi import cgitb; cgitb.enable() import pg def form(): print """<form method="post" action=""> <p> <input type=checkbox name="qtype" value="all" checked /> All<br /> <input type=checkbox name="qtype" value="project" /> Project<br /> <input type=checkbox name="qtype" value="date_string" /> Date<br /> <input type=checkbox name="qtype" value="blame" /> Blame<br /> <input type=checkbox name="qtype" value="notes" /> Notes<br /></p> <p>Search by shot number:<br> <input type=text name="qtext" value="" /> <input type="submit" value="SEARCH" /> <input type="reset" value="RESET" /><br /> </form>""" print "Content-Type: text/html\n\n" print "<head><title>Searching by using Shot Number</title></head><body>" if __name__ == "__main__": data = cgi.FieldStorage() if data: qtype = data.getfirst('qtype') qtext = data.getfirst('qtext','') for qtype in data.getlist('qtype'): print "You typed in Shot Number:", qtext #Now, we can get to the database... username = os.environ.get('USER') if username == None: username = 'apache' db = pg.connect("moncdata", user=username, passwd=None) query = "select %(qtype)s from shot_descriptions where shot_number=%(qtext)s", qtype, qtext qresult = db.query(query) listOfResults = qresult.dictresult() print """<p>Example of pulling the list of dictionary results apart.</p>""" for record in listOfResults: print "<p><table>" for k in record.keys(): print '<tr>' print '<td>key:</td> <td>', k, '</td>' print '<td>value:</td><td>', record[k], '</td>' print '</tr>' print '</table></p>' db.close() else: print "You have no enter a shot number!" print "Please type a in shot number in order to perform a search!" else: form() print "</body></html>" From max_russell2000 at yahoo.co.uk Thu Sep 30 10:13:25 2004 From: max_russell2000 at yahoo.co.uk (Max Russell) Date: Thu Sep 30 10:13:28 2004 Subject: [Tutor] anagram solving algorithm In-Reply-To: <Pine.LNX.4.44.0409291135070.23970-100000@hkn.eecs.berkeley.edu> Message-ID: <20040930081325.36509.qmail@web25406.mail.ukl.yahoo.com> I'm going to sort the input word (i.e the anagram) then get all words of equal length to the anagram, sort them, then do a match. I'll return the original words (unsorted) for all those that match. --- Danny Yoo <dyoo@hkn.eecs.berkeley.edu> wrote: > > > On Wed, 29 Sep 2004, Max Russell wrote: > > > Hello here is a breakdown of an algorithm I'm > using to write my own > > anagram solver: > > [text cut] > > > My problem here is that it how to structure > looking at each possibe word > > in the list: how to set up the loop for that, also > how to do the > > sort/inspection of each word. > > > Hi Max, > > It sounds like you want to run a 'for' loop across > every word in your > wordlist. > > > Here's an example of a for loop, just so you get the > idea of what it can > do: > > ### > >>> def isEven(x): > ... return x % 2 == 0 > ... > >>> numbers = [3, 1, 4, 1, 5, 9, 2, 6] > >>> for n in numbers: > ... print "I'm looking at", n > ... if isEven(n): > ... print n, "is even" > ... else: > ... print n, "is odd" > ... > I'm looking at 3 > 3 is odd > I'm looking at 1 > 1 is odd > I'm looking at 4 > 4 is even > I'm looking at 1 > 1 is odd > I'm looking at 5 > 5 is odd > I'm looking at 9 > 9 is odd > I'm looking at 2 > 2 is even > I'm looking at 6 > 6 is even > ### > > > For more examples of loops, take a look at a > tutorial like Alan's: > > > http://www.freenetpages.co.uk/hp/alan.gauld/tutloops.htm > > > There are two kinds of loops in Python: > > 1. for --- good for going across sequences. > > 2. while --- good for repeating something until > some condition > changes. > > > 'for' can go across lists easily, so it's a good > tool here. You can loop > across a list with 'while' too, but it's not so > idiomatic. > > > Just as a last note: there's a very clever way to > solve the anagram > problem, and it does involve sorting. But let's see > try to get your first > solution working: we can talk about the clever > approach later. *grin* > > > Good luck to you! > > ___________________________________________________________ALL-NEW Yahoo! Messenger - all new features - even more fun! http://uk.messenger.yahoo.com From my.mailing.lists at noos.fr Thu Sep 30 16:01:01 2004 From: my.mailing.lists at noos.fr (nik) Date: Thu Sep 30 16:01:09 2004 Subject: [Tutor] python by cgi Message-ID: <415C119D.2020405@noos.fr> hi all, I'm trying to access my firebird database using python and cgi. I've installed the latest apache web server (on linux), and using a simple script like; #!/usr/local/bin/python def main(): print "Content-type: text/html" print print "<TITLE> Hello, World!</TITLE>" if (__name__ == "__main__"): main() is working just fine. However, if I add an import kinterbasdb at the start, I get an import error. Using the command line interpreter I don't have a problem though. I'm a bit confused by the sys.path a bit, it seems to vary depending on how I start python; in command line iterpreter, it's; '', '/usr/lib/python23.zip', '/usr/lib/python2.3', '/usr/lib/python2.3/plat-linux2', '/usr/lib/python2.3/lib-tk', '/usr/lib/python2.3/lib-dynload', '/usr/lib/python2.3/site-packages', '/usr/lib/python2.3/site-packages/Numeric', '/usr/lib/python2.3/site-packages/gtk-2.0' by cgi it's; '/usr/local/apache2/cgi-bin', '/usr/local/lib/python23.zip', '/usr/local/lib/python2.3', '/usr/local/lib/python2.3/plat-linux2', '/usr/local/lib/python2.3/lib-tk', '/usr/local/lib/python2.3/lib-dynload', '/usr/local/lib/python2.3/site-packages' however, the difference doesn't seem to imply why kinterbasdb can't be imported. I tried doing import sys sys.path.append('/usr/lib/python2.3/site-packages/kinterbasdb') in the script, but it didn't help. Any ideas? Is it a permissions thing perhaps? nik From Mark.Kels at gmail.com Thu Sep 30 16:08:11 2004 From: Mark.Kels at gmail.com (Mark Kels) Date: Thu Sep 30 16:08:19 2004 Subject: [Tutor] A simple problem with Tkinter Message-ID: <d1202653040930070822405fb2@mail.gmail.com> hello, I wrote this basic Tkinter code: from Tkinter import * root=Tk() w=Label(root,text="Hello!!") b=Button(root,text="Bye",command='exit') root.mainloop() But the output is an empty TK window (without the text and the button)... What is the problem ? From flaxeater at yahoo.com Thu Sep 30 16:05:28 2004 From: flaxeater at yahoo.com (Chad Crabtree) Date: Thu Sep 30 16:10:02 2004 Subject: [Tutor] python by cgi Message-ID: <20040930140528.22955.qmail@web52603.mail.yahoo.com> Could you give us your error message. This sounds like a problem I had, make sure that the filename is not colliding with any of the packages file names. nik wrote: > hi all, > > I'm trying to access my firebird database using python and cgi. I've > installed the latest apache web server (on linux), and using a simple > script like; > #!/usr/local/bin/python > > def main(): > print "Content-type: text/html" > print > print "<TITLE> Hello, World!</TITLE>" > > if (__name__ == "__main__"): > main() > > is working just fine. > > However, if I add an import kinterbasdb at the start, I get an import > error. > > Using the command line interpreter I don't have a problem though. > > I'm a bit confused by the sys.path a bit, it seems to vary depending > on how I start python; > > in command line iterpreter, it's; > '', '/usr/lib/python23.zip', '/usr/lib/python2.3', > '/usr/lib/python2.3/plat-linux2', '/usr/lib/python2.3/lib-tk', > '/usr/lib/python2.3/lib-dynload', '/usr/lib/python2.3/site-packages', > '/usr/lib/python2.3/site-packages/Numeric', > '/usr/lib/python2.3/site-packages/gtk-2.0' > > by cgi it's; > '/usr/local/apache2/cgi-bin', '/usr/local/lib/python23.zip', > '/usr/local/lib/python2.3', '/usr/local/lib/python2.3/plat-linux2', > '/usr/local/lib/python2.3/lib-tk', > '/usr/local/lib/python2.3/lib-dynload', > '/usr/local/lib/python2.3/site-packages' > > however, the difference doesn't seem to imply why kinterbasdb can't be > imported. > > I tried doing > import sys > sys.path.append('/usr/lib/python2.3/site-packages/kinterbasdb') > __________________________________ Do you Yahoo!? New and Improved Yahoo! Mail - Send 10MB messages! http://promotions.yahoo.com/new_mail From my.mailing.lists at noos.fr Thu Sep 30 16:20:41 2004 From: my.mailing.lists at noos.fr (nik) Date: Thu Sep 30 16:21:10 2004 Subject: [Tutor] python by cgi In-Reply-To: <20040930140528.22955.qmail@web52603.mail.yahoo.com> References: <20040930140528.22955.qmail@web52603.mail.yahoo.com> Message-ID: <415C1639.3000207@noos.fr> A reply in four minutes flat - not bad going! :-) There's not a lot to go on - Apache gives the error 500 internal server error. The server error log then gives; [Thu Sep 30 16:13:14 2004] [error] [client 127.0.0.1] Traceback (most recent call last): [Thu Sep 30 16:13:14 2004] [error] [client 127.0.0.1] File "/usr/local/apache2/cgi-bin/testpyscript", line 3, in ? [Thu Sep 30 16:13:14 2004] [error] [client 127.0.0.1] [Thu Sep 30 16:13:14 2004] [error] [client 127.0.0.1] import kinterbasdb [Thu Sep 30 16:13:14 2004] [error] [client 127.0.0.1] ImportError [Thu Sep 30 16:13:14 2004] [error] [client 127.0.0.1] : [Thu Sep 30 16:13:14 2004] [error] [client 127.0.0.1] No module named kinterbasdb [Thu Sep 30 16:13:14 2004] [error] [client 127.0.0.1] [Thu Sep 30 16:13:14 2004] [error] [client 127.0.0.1] Premature end of script headers: testpyscript I've just tried adding SetEnv PYTHONPATH /usr/lib/python2.3/site-packages/kinterbasdb to the httpd.conf file of apache, which makes it appear in the sys.path ok, but it still can't load the kinterbasdb module. nik Chad Crabtree wrote: >Could you give us your error message. This sounds like a problem I >had, >make sure that the filename is not colliding with any of the packages > >file names. > >nik wrote: > > > >>hi all, >> >>I'm trying to access my firebird database using python and cgi. >> >> >I've > > >>installed the latest apache web server (on linux), and using a >> >> >simple > > >>script like; >>#!/usr/local/bin/python >> >>def main(): >> print "Content-type: text/html" >> print >> print "<TITLE> Hello, World!</TITLE>" >> >>if (__name__ == "__main__"): >> main() >> >>is working just fine. >> >>However, if I add an import kinterbasdb at the start, I get an >> >> >import > > >>error. >> >>Using the command line interpreter I don't have a problem though. >> >>I'm a bit confused by the sys.path a bit, it seems to vary >> >> >depending > > >>on how I start python; >> >>in command line iterpreter, it's; >>'', '/usr/lib/python23.zip', '/usr/lib/python2.3', >>'/usr/lib/python2.3/plat-linux2', '/usr/lib/python2.3/lib-tk', >>'/usr/lib/python2.3/lib-dynload', >> >> >'/usr/lib/python2.3/site-packages', > > >>'/usr/lib/python2.3/site-packages/Numeric', >>'/usr/lib/python2.3/site-packages/gtk-2.0' >> >>by cgi it's; >>'/usr/local/apache2/cgi-bin', '/usr/local/lib/python23.zip', >>'/usr/local/lib/python2.3', '/usr/local/lib/python2.3/plat-linux2', >> >> > > > >>'/usr/local/lib/python2.3/lib-tk', >>'/usr/local/lib/python2.3/lib-dynload', >>'/usr/local/lib/python2.3/site-packages' >> >>however, the difference doesn't seem to imply why kinterbasdb can't >> >> >be > > >>imported. >> >>I tried doing >>import sys >>sys.path.append('/usr/lib/python2.3/site-packages/kinterbasdb') >> >> >> > > > > >__________________________________ >Do you Yahoo!? >New and Improved Yahoo! Mail - Send 10MB messages! >http://promotions.yahoo.com/new_mail > > > > From alipolatel at yahoo.com Thu Sep 30 16:27:30 2004 From: alipolatel at yahoo.com (Ali Polatel) Date: Thu Sep 30 16:27:36 2004 Subject: [Tutor] A simple problem with Tkinter In-Reply-To: <d1202653040930070822405fb2@mail.gmail.com> Message-ID: <20040930142730.50638.qmail@web61010.mail.yahoo.com> you should pack them! from Tkinter import * root=Tk() w=Label(root,text="Hello!!") Correct is w=Label(root,text="Hello!!").pack() b=Button(root,text="Bye",command='exit') Correct is b=Button(root,text="Bye",command='exit').pack() root.mainloop() --------------------------------- Do you Yahoo!? Yahoo! Mail Address AutoComplete - You start. We finish. -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040930/34ae0606/attachment.htm From rick at niof.net Thu Sep 30 16:36:58 2004 From: rick at niof.net (Rick Pasotto) Date: Thu Sep 30 16:37:02 2004 Subject: [Tutor] A simple problem with Tkinter In-Reply-To: <20040930142730.50638.qmail@web61010.mail.yahoo.com> References: <d1202653040930070822405fb2@mail.gmail.com> <20040930142730.50638.qmail@web61010.mail.yahoo.com> Message-ID: <20040930143658.GG7345@niof.net> On Thu, Sep 30, 2004 at 07:27:30AM -0700, Ali Polatel wrote: > you should pack them! > from Tkinter import * > root=Tk() > w=Label(root,text="Hello!!") Correct is w=Label(root,text="Hello!!").pack() Not really. Better would be: w=Label(root,text="Hello!!") w.pack() This retains a reference to the label for later modification if desired. What you have done is to assign the useless return value of pack() to w. > b=Button(root,text="Bye",command='exit') > Correct is b=Button(root,text="Bye",command='exit').pack() Same as above. > root.mainloop() The main point is that creating a label or button does not display it. You need to use pack() or grid() to place and display it. -- "Certainly virtue is like precious odours, most fragrant when they are incensed, or crushed: for prosperity doth best discover vice, but adversity doth best discover virtue." -- Francis Bacon, essayist, philosopher, and statesman (1561-1626) Rick Pasotto rick@niof.net http://www.niof.net From kent_johnson at skillsoft.com Thu Sep 30 16:37:03 2004 From: kent_johnson at skillsoft.com (Kent Johnson) Date: Thu Sep 30 16:37:07 2004 Subject: [Tutor] A simple problem with Tkinter In-Reply-To: <d1202653040930070822405fb2@mail.gmail.com> References: <d1202653040930070822405fb2@mail.gmail.com> Message-ID: <6.1.0.6.0.20040930103610.02a50f20@mail4.skillsoft.com> You have to call pack() on the components to get them to appear: from Tkinter import * root=Tk() w=Label(root,text="Hello!!") w.pack() b=Button(root,text="Bye",command='exit') b.pack() root.mainloop() Kent At 04:08 PM 9/30/2004 +0200, Mark Kels wrote: >hello, > >I wrote this basic Tkinter code: > >from Tkinter import * >root=Tk() >w=Label(root,text="Hello!!") >b=Button(root,text="Bye",command='exit') >root.mainloop() > >But the output is an empty TK window (without the text and the button)... >What is the problem ? >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From pythonTutor at venix.com Thu Sep 30 17:01:26 2004 From: pythonTutor at venix.com (Lloyd Kvam) Date: Thu Sep 30 17:01:34 2004 Subject: [Tutor] python by cgi In-Reply-To: <415C119D.2020405@noos.fr> References: <415C119D.2020405@noos.fr> Message-ID: <1096556485.2951.57.camel@laptop.venix.com> On Thu, 2004-09-30 at 10:01, nik wrote: > hi all, > > I'm trying to access my firebird database using python and cgi. I've > installed the latest apache web server (on linux), and using a simple > script like; > #!/usr/local/bin/python > > def main(): > print "Content-type: text/html" > print > print "<TITLE> Hello, World!</TITLE>" > > if (__name__ == "__main__"): > main() > > is working just fine. > > However, if I add an import kinterbasdb at the start, I get an import error. > > Using the command line interpreter I don't have a problem though. > > I'm a bit confused by the sys.path a bit, it seems to vary depending on > how I start python; > > in command line iterpreter, it's; > '', '/usr/lib/python23.zip', '/usr/lib/python2.3', > '/usr/lib/python2.3/plat-linux2', '/usr/lib/python2.3/lib-tk', > '/usr/lib/python2.3/lib-dynload', '/usr/lib/python2.3/site-packages', > '/usr/lib/python2.3/site-packages/Numeric', > '/usr/lib/python2.3/site-packages/gtk-2.0' Here Python is installed in /usr/lib > > by cgi it's; > '/usr/local/apache2/cgi-bin', '/usr/local/lib/python23.zip', > '/usr/local/lib/python2.3', '/usr/local/lib/python2.3/plat-linux2', > '/usr/local/lib/python2.3/lib-tk', > '/usr/local/lib/python2.3/lib-dynload', > '/usr/local/lib/python2.3/site-packages' > Here Python is installed in /usr/local/lib You have two installed versions of Python. I would assume that kinterbasdb is in /usr/lib AND not in /usr/local/lib. Quick fix is to install kinterbasdb into the other python. Better is to get down to a single Python2.3 - presumably remove the /usr/local/lib version, but that depends on the nature of your linux setup. > however, the difference doesn't seem to imply why kinterbasdb can't be > imported. > > I tried doing > import sys > sys.path.append('/usr/lib/python2.3/site-packages/kinterbasdb') > > in the script, but it didn't help. > > > Any ideas? Is it a permissions thing perhaps? > > nik > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Lloyd Kvam Venix Corp From my.mailing.lists at noos.fr Thu Sep 30 17:30:31 2004 From: my.mailing.lists at noos.fr (nik) Date: Thu Sep 30 17:30:37 2004 Subject: [Tutor] python by cgi In-Reply-To: <1096556485.2951.57.camel@laptop.venix.com> References: <415C119D.2020405@noos.fr> <1096556485.2951.57.camel@laptop.venix.com> Message-ID: <415C2697.2040009@noos.fr> ah, well spotted. One version was installed by the mandrake install disks (the usr/lib one), the other I did myself since I thought upgrading was a good idea before I realised that I wasn't sure of the side effects of removing the old one. Now I've no idea of what on my system uses which version... I might go for the quick fix right now (why not put off something today that you can put off for quite a while more until it bites you on the ass again, or something like that :-) ) many thanks, nik Lloyd Kvam wrote: >On Thu, 2004-09-30 at 10:01, nik wrote: > > >>hi all, >> >>I'm trying to access my firebird database using python and cgi. I've >>installed the latest apache web server (on linux), and using a simple >>script like; >>#!/usr/local/bin/python >> >>def main(): >> print "Content-type: text/html" >> print >> print "<TITLE> Hello, World!</TITLE>" >> >>if (__name__ == "__main__"): >> main() >> >>is working just fine. >> >>However, if I add an import kinterbasdb at the start, I get an import error. >> >>Using the command line interpreter I don't have a problem though. >> >>I'm a bit confused by the sys.path a bit, it seems to vary depending on >>how I start python; >> >>in command line iterpreter, it's; >>'', '/usr/lib/python23.zip', '/usr/lib/python2.3', >>'/usr/lib/python2.3/plat-linux2', '/usr/lib/python2.3/lib-tk', >>'/usr/lib/python2.3/lib-dynload', '/usr/lib/python2.3/site-packages', >>'/usr/lib/python2.3/site-packages/Numeric', >>'/usr/lib/python2.3/site-packages/gtk-2.0' >> >> > >Here Python is installed in /usr/lib > > > >>by cgi it's; >>'/usr/local/apache2/cgi-bin', '/usr/local/lib/python23.zip', >>'/usr/local/lib/python2.3', '/usr/local/lib/python2.3/plat-linux2', >>'/usr/local/lib/python2.3/lib-tk', >>'/usr/local/lib/python2.3/lib-dynload', >>'/usr/local/lib/python2.3/site-packages' >> >> >> > >Here Python is installed in /usr/local/lib > >You have two installed versions of Python. I would assume that >kinterbasdb is in /usr/lib AND not in /usr/local/lib. > >Quick fix is to install kinterbasdb into the other python. Better is to >get down to a single Python2.3 - presumably remove the /usr/local/lib >version, but that depends on the nature of your linux setup. > > > > >>however, the difference doesn't seem to imply why kinterbasdb can't be >>imported. >> >>I tried doing >>import sys >>sys.path.append('/usr/lib/python2.3/site-packages/kinterbasdb') >> >>in the script, but it didn't help. >> >> >>Any ideas? Is it a permissions thing perhaps? >> >>nik >>_______________________________________________ >>Tutor maillist - Tutor@python.org >>http://mail.python.org/mailman/listinfo/tutor >> >> From davholla2002 at yahoo.co.uk Thu Sep 30 17:16:02 2004 From: davholla2002 at yahoo.co.uk (David Holland) Date: Thu Sep 30 17:33:52 2004 Subject: [Tutor] Install shield In-Reply-To: <20040930100037.965C01E4011@bag.python.org> Message-ID: <20040930151602.61915.qmail@web25402.mail.ukl.yahoo.com> Does anyone know if python can be used to add functionality to install shield or a similar application ? --------------------------------- 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/20040930/3fe943c5/attachment.htm From kabads at gmail.com Thu Sep 30 17:48:26 2004 From: kabads at gmail.com (Adam Cripps) Date: Thu Sep 30 17:48:29 2004 Subject: [Tutor] Acting on objects in a list - how to make the change permanent? In-Reply-To: <6.1.0.6.0.20040929175248.028dae08@mail4.skillsoft.com> References: <c7ff3855040927070139ffeb56@mail.gmail.com> <6.1.0.6.0.20040927220012.028bcfc0@mail4.skillsoft.com> <c7ff385504092722473dfcc798@mail.gmail.com> <6.1.0.6.0.20040928054640.028c1c50@mail4.skillsoft.com> <c7ff3855040929130854e86cee@mail.gmail.com> <6.1.0.6.0.20040929175248.028dae08@mail4.skillsoft.com> Message-ID: <c7ff3855040930084818cf4f84@mail.gmail.com> On Wed, 29 Sep 2004 17:54:37 -0400, Kent Johnson <kent_johnson@skillsoft.com> wrote: > Adam, > > list.remove(item) will remove item from list without needing the index of > item in list. > > Kent Just like to say thanks to all who contributed to this thread - I managed to get it working with the code that Kent suggested. This is quite a milestone for me and python. Thanks again. Adam From prospero at prosperosisland.co.uk Thu Sep 30 18:45:00 2004 From: prospero at prosperosisland.co.uk (Prospero) Date: Thu Sep 30 18:44:10 2004 Subject: [Tutor] Re: Files and such Message-ID: <000f01c4a70c$d8057920$fd199a51@user> Greetings! Still hoping someone can give me an answer on this. (Problem repeated below.) It seems such an obvious thing but neither the online information I have seen nor the one book I own on Python seem to address it. I need to save some numbers in a text file. This bit I can do no problem but then I need a different part of the program to read these numbers one set at a time, starting at the beginning and stopping at the end. For preference the file should be plain text so that I can amend it by hand if necessary. Any clues about how to do this would be much appreciated. The numbers are in groups of six, all single- or double-digit integers. The file would be added to one group at a time. The image I have in mind is of each group occupying one line, separated either by commas or spaces, but this does not matter as long as the format is clear enough to allow human editing. All the best, Prospero. From project5 at redrival.net Thu Sep 30 19:13:22 2004 From: project5 at redrival.net (Andrei) Date: Thu Sep 30 19:13:27 2004 Subject: [Tutor] Re: Install shield References: <20040930100037.965C01E4011@bag.python.org> <20040930151602.61915.qmail@web25402.mail.ukl.yahoo.com> Message-ID: <17a4l8c1bf6me$.rsxtb328gcn5.dlg@40tude.net> David Holland wrote on Thu, 30 Sep 2004 16:16:02 +0100 (BST): > Does anyone know if python can be used to add functionality to install shield or a similar application ? It probably can; if you include the required modules and Python itself in the setup routine, you can extract them to a temp dir at installation time and run them from there for example. -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From copellifulvio at yahoo.it Wed Sep 29 12:04:51 2004 From: copellifulvio at yahoo.it (Fulvio Copex) Date: Thu Sep 30 19:21:12 2004 Subject: [Tutor] invoking system commands from python Message-ID: <20040929100451.97501.qmail@web86910.mail.ukl.yahoo.com> Hello, i'm new to this list and to python too. I'm using active state python 2.3 on win32, my problem is the following: I want learn how to execute system command passing parameters. for example to copy a file I've tried to write this script: ***************************** import os os.chdir(''myDirectory") cmd="copy" parameters="file1 file1_backup" myCmd = os.popen(cmd,'w') myCmd.write(parameters) exitCode = myCmd.close() if exitCode: print '%s failed, this probably says why:\n%s' % (cmd, myCmd) ****************************** the problem is that it doesn't work (the file file1_backup is not created) and it writes the following line: copy failed, this probably says why: <closed file 'copy', mode 'w' at 0x01177660> have tou any idea? thanks, cop --------------------------------- Scopri Mister Yahoo! - il fantatorneo sul calcio di Yahoo! Sport' -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/tutor/attachments/20040929/ff4caa42/attachment.html From project5 at redrival.net Thu Sep 30 19:17:52 2004 From: project5 at redrival.net (Andrei) Date: Thu Sep 30 19:21:17 2004 Subject: [Tutor] Re: conditionally defining classes References: <20040929215444.3BC781E400C@bag.python.org> <20040929183035.I26056@yamato.yamato.com> Message-ID: <g3jqzm1ahvfb$.euipermtngtz.dlg@40tude.net> Tony Cappellini wrote on Wed, 29 Sep 2004 18:47:33 -0700 (PDT): > I've read some posts from Guido (I think) about defining a class within a > class. From what I remember this was frowned upon, but I would expect > arguments on both sides. I don't like defining things (be they functions or classes) inside other functions/classes. It's ugly and decreases the maintainability of the code. > Going off in another direction- is it Pythonic to conditionally define a > class as in .. > > import sys > > OSVer= sys.getwindowsversion()[0] > > if OSVer == 5: > class OSWinXp(object): > def __init__(self): > # XP specific code goes here > elif OSVer == 4: > class OsWin98(object): > def __init__(self): > # W98 specifc code goes here I agree with Jeff that you'd better define both of them and then create an object based on one of them depending on the OS. The example above makes particularly little sense because you a) define them in an if-statemt and b) give them different names after all. So you'll have to implement another if-statement to decide whether you want to create a WinXP or a Win98 object. -- Yours, Andrei ===== Real contact info (decode with rot13): cebwrpg5@jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur yvfg, fb gurer'f ab arrq gb PP. From s4046441 at student.uq.edu.au Thu Sep 30 20:37:25 2004 From: s4046441 at student.uq.edu.au (Ms Soo Chong) Date: Thu Sep 30 20:37:30 2004 Subject: [Tutor] comp.lang.python Message-ID: <69eb4769e444.69e44469eb47@uq.edu.au> Hi, How can I post questions to comp.lang.python? What is the email add for that? Is there an archive of the newsgroup? Sorry, I can't find the information for the above. Thank you for any help. Cheers, Shufen From s4046441 at student.uq.edu.au Thu Sep 30 20:45:40 2004 From: s4046441 at student.uq.edu.au (Ms Soo Chong) Date: Thu Sep 30 20:45:47 2004 Subject: [Tutor] Please ignore the previous mail on "comp.lang.python" Message-ID: <682e9f680c4b.680c4b682e9f@uq.edu.au> Hi all, Sorry for that, I found the answer. Please ignore my previous msg. Thank you. Shufen From dyoo at hkn.eecs.berkeley.edu Thu Sep 30 21:00:48 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Sep 30 21:00:53 2004 Subject: [Tutor] anagram solving algorithm In-Reply-To: <20040930081325.36509.qmail@web25406.mail.ukl.yahoo.com> Message-ID: <Pine.LNX.4.44.0409301149090.1697-100000@hkn.eecs.berkeley.edu> On Thu, 30 Sep 2004, Max Russell wrote: > I'm going to sort the input word (i.e the anagram) then get all words of > equal length to the anagram, sort them, then do a match. I'll return the > original words (unsorted) for all those that match. Hi Max, Yup, that sounds exactly right. One more trick to make this really fast is to do the letter-sorting on your whole dictionary of words way in advance, even before getting the input word If you this preparation early on, and keep a separate "word -> sorted word" file, then the anagram check becomes an exact-matching problem. And Python dictionaries are designed to make exact matching fast: ### >>> word_entries = { 'one' : 1, ... 'two' : 2, ... 'three' : 3 } >>> 'one' in word_entries True >>> 'five' in word_entries False >>> word_entries['three'] 3 ### Hope this helps! From dyoo at hkn.eecs.berkeley.edu Thu Sep 30 21:23:58 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Sep 30 21:24:03 2004 Subject: [Tutor] Re: Files and such In-Reply-To: <000f01c4a70c$d8057920$fd199a51@user> Message-ID: <Pine.LNX.4.44.0409301212010.1697-100000@hkn.eecs.berkeley.edu> On Thu, 30 Sep 2004, Prospero wrote: > I need to save some numbers in a text file. This bit I can do no problem > but then I need a different part of the program to read these numbers > one set at a time, starting at the beginning and stopping at the end. Hi Prospero, When you're reading lines back from a file, all that Python knows is that the file contains a bunch of string lines. For example: ### [dyoo@shoebox dyoo]$ cat >somenumbers 3 2 1 [dyoo@shoebox dyoo]$ python Python 2.3.3 (#1, Aug 9 2004, 10:11:39) [GCC 3.3.3 20040412 (Gentoo Linux 3.3.3-r6, ssp-3.3.2-2, pie-8.7.6)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> >>> >>> lines = myfile.readlines() >>> lines ['3\n', '2\n', '1\n'] ### So you may need to do some additional interpretation to get back the numbers instead of the strings. Python simply doesn't know enough at this point to guess that those strings are really supposed to be interpreted as numbers. But it sounds like the text file that you want to work with will contain just integers. One way to transform a string into an integer is through the 'int()' function: ### >>> for line in lines: ... n = int(line) ... print "I see a", n ... I see a 3 I see a 2 I see a 1 ### And this will work as long as there's just one number per line. If each line is tab or comma delimited, then we can first "split" the line, and then "int()" each chunk: ### >>> line = 'this,is,a,line,with,commas,separating,columns' >>> chunks = line.split(',') >>> chunks ['this', 'is', 'a', 'line', 'with', 'commas', 'separating', 'columns'] ### So the loading of data back from files into Python usually involves something that looks like: ### Pseudocode def doLoad(): for line in some_file: break up the line into chunks do something (like type conversion) to each chunk ### Does this make sense so far? The process here is a little ad-hoc, but it's usually effective for simple data like this. *grin* Please feel free to ask more questions about this. (Aside: If your file has a bit more regular tab-delimited structure, you can take advantage of the 'csv' Comma Separated Values parser in the Standard Library: http://www.python.org/doc/lib/module-csv.html ) Hope this helps! From dyoo at hkn.eecs.berkeley.edu Thu Sep 30 21:36:58 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Sep 30 21:37:04 2004 Subject: [Tutor] invoking system commands from python In-Reply-To: <20040929100451.97501.qmail@web86910.mail.ukl.yahoo.com> Message-ID: <Pine.LNX.4.44.0409301226520.1697-100000@hkn.eecs.berkeley.edu> On Wed, 29 Sep 2004, Fulvio Copex wrote: > i'm new to this list and to python too. > I'm using active state python 2.3 on win32, > my problem is the following: > I want learn how to execute system command passing parameters. > > for example to copy a file I've tried to write this script: > > ***************************** > import os > os.chdir(''myDirectory") > cmd="copy" > parameters="file1 file1_backup" > myCmd = os.popen(cmd,'w') > myCmd.write(parameters) > exitCode = myCmd.close() > if exitCode: > print '%s failed, this probably says why:\n%s' % (cmd, myCmd) Hi Fulvio, There's a syntax problem here: > os.chdir(''myDirectory") ^^ but you probably have fixed this already. There's a more important problem in the use of os.popen(): > myCmd = os.popen(cmd,'w') > myCmd.write(parameters) Your 'copy' command may need to take in the parameters at the same time as the popen call, as additional "command-line arguments". I'm not sure how your 'copy' command works, but it may not be listening to standard input. So you may need to do something like this: os.popen("%s %s" % (cmd, parameters)) where we construct the command line all at once, and then pass that off to popen(). That being said, when you're programming in Python, you actually want to avoid using os.popen() or os.system() if you can help it. *grin* The reason is because they're really OS-specific: you can't then take the same program on Windows and expect it to work on a Unix system, at least, not without a lot of work. It's also fraught with security problems. There's already a file-copying function in the 'shutil' shell utilities module in the Standard Library: http://www.python.org/doc/lib/module-shutil.html So a better way to do file copying is to use shutils.copy(). ### import os import shutils os.chdir("myDirectory") shutils.copy("file1", "file1_backup") ### Not only is this easier to read, but it should be much more portable across operating systems. If you have more questions, please feel free to ask. Good luck! From dyoo at hkn.eecs.berkeley.edu Thu Sep 30 21:39:19 2004 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu Sep 30 21:39:23 2004 Subject: [Tutor] Re: Files and such In-Reply-To: <Pine.LNX.4.44.0409301212010.1697-100000@hkn.eecs.berkeley.edu> Message-ID: <Pine.LNX.4.44.0409301237240.1697-100000@hkn.eecs.berkeley.edu> On Thu, 30 Sep 2004, Danny Yoo wrote: > When you're reading lines back from a file, all that Python knows is that > the file contains a bunch of string lines. For example: > > ### > [dyoo@shoebox dyoo]$ cat >somenumbers > 3 > 2 > 1 > [dyoo@shoebox dyoo]$ python > Python 2.3.3 (#1, Aug 9 2004, 10:11:39) > [GCC 3.3.3 20040412 (Gentoo Linux 3.3.3-r6, ssp-3.3.2-2, pie-8.7.6)] on > linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> > >>> > >>> lines = myfile.readlines() > >>> lines > ['3\n', '2\n', '1\n'] Gah! *grin* There's a missing line there, right before the readlines() statement: ### >>> myfile = open('somenumbers') ### Sorry about that! I made a mistake when I copied/pasted the output from my window. From kabads at gmail.com Thu Sep 30 22:19:48 2004 From: kabads at gmail.com (Adam Cripps) Date: Thu Sep 30 22:20:07 2004 Subject: [Tutor] comp.lang.python In-Reply-To: <69eb4769e444.69e44469eb47@uq.edu.au> References: <69eb4769e444.69e44469eb47@uq.edu.au> Message-ID: <c7ff385504093013195e97887e@mail.gmail.com> On Fri, 01 Oct 2004 04:37:25 +1000, Ms Soo Chong <s4046441@student.uq.edu.au> wrote: > Hi, > > How can I post questions to comp.lang.python? > What is the email add for that? > Is there an archive of the newsgroup? > > Sorry, I can't find the information for the above. > > Thank you for any help. > > Cheers, > Shufen > Try http://www.python.org/community/lists.html - also includes some information on receiving this usenet list as a mailing list. HTH Adam