From cpsoct@lycos.com Mon Jan 1 06:59:01 2001 From: cpsoct@lycos.com (kevin parks) Date: Mon, 01 Jan 2001 15:59:01 +0900 Subject: [Tutor] how to flatten and lump lists Message-ID: I got it! just so the tutors here know there is no need to reply. i got the usual entertaining and informative lesson from Mr. Peters. Still absorbing the nuances of his answer which is son-like (jp:zen). Grateful to all on this list for their help. Happy new year everyone. kevin parks seoul, korea Get FREE Email/Voicemail with 15MB at Lycos Communications at http://comm.lycos.com From dpm@softdesigns.com Mon Jan 1 17:12:48 2001 From: dpm@softdesigns.com (David Metzler) Date: Mon, 1 Jan 2001 09:12:48 -0800 Subject: [Tutor] Web client programming Message-ID: <002001c07416$10f57c40$0501a8c0@softdesigns.com> This is a multi-part message in MIME format. ------=_NextPart_000_001D_01C073D3.026D8700 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable I have several Linux hosted PHP 4 and MySql databases hosted at my = office. The clients accessing these databases are all win98 with = Explorer 5.50 This works well enough but the web browser based application has several = limitations. The biggest limitation being the user-interface.=20 I have this vision that I could build a Python program that could = connect to the MySql based data and have all the features a modern GUI = program would expect to have and be Gnome, and win98 compatible. I've looked at the telnet module for python and it seems as though it = might work. Just telnet to my server and run the mysql client and send = data back and forth to a buffer and only show on the screnn what I want. I have seen exactly one example script in the help. Is this the best way to do this? Where are their more examples of this = type of programming? I know I could just use the mysql module and connect directly to the = database but will it work well over a wan connection? ------=_NextPart_000_001D_01C073D3.026D8700 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
I have several Linux hosted PHP 4 and = MySql=20 databases hosted at my office. The clients accessing these databases are = all=20 win98 with Explorer 5.50
This works well enough but the web = browser based=20 application has several limitations. The biggest limitation being the=20 user-interface.
I have this vision that I could build a = Python=20 program that could connect to the MySql based data and have all the = features a=20 modern GUI program would expect to have and be Gnome, and win98=20 compatible.
I've looked at the telnet module for = python and it=20 seems as though it might work. Just telnet to my server and run the = mysql client=20 and send data back and forth to a buffer and only show on the screnn = what I=20 want.
I have seen exactly one example script = in the=20 help.
Is this the best way to do this? Where = are their=20 more examples of this type of programming?
 
I know I could just use the mysql = module and=20 connect directly to the database but will it work well over a wan=20 connection?
------=_NextPart_000_001D_01C073D3.026D8700-- From deirdre@deirdre.net Mon Jan 1 21:56:41 2001 From: deirdre@deirdre.net (Deirdre Saoirse) Date: Mon, 1 Jan 2001 13:56:41 -0800 (PST) Subject: [Tutor] Web client programming In-Reply-To: <002001c07416$10f57c40$0501a8c0@softdesigns.com> Message-ID: On Mon, 1 Jan 2001, David Metzler wrote: > I have several Linux hosted PHP 4 and MySql databases hosted at my > office. The clients accessing these databases are all win98 with > Explorer 5.50 This works well enough but the web browser based > application has several limitations. The biggest limitation being the > user-interface. I have this vision that I could build a Python > program that could connect to the MySql based data and have all the > features a modern GUI program would expect to have and be Gnome, and > win98 compatible. The modern trend is away from proprietary UI programs and toward browser-based programs as it doesn't require a specific set of underlying system calls. And Gnome and win98 don't work well together. > I've looked at the telet module for python and it seems as though it > might work. Just telnet to my server and run the mysql client and send > data back and forth to a buffer and only show on the screnn what I > want. For security reasons, you should never use telnet. > I know I could just use the mysql module and connect directly to the > database but will it work well over a wan connection? Yes. I do it all the time. -- _Deirdre * http://www.sfknit.org * http://www.deirdre.net "We have an open door policy." -- Sheridan "And an open airlock policy." -- Ivanova From dyoo@hkn.eecs.berkeley.edu Tue Jan 2 03:19:54 2001 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Mon, 1 Jan 2001 19:19:54 -0800 (PST) Subject: [Tutor] list problem In-Reply-To: <00123115060200.02657@vdbroekw> Message-ID: On Sun, 31 Dec 2000, W.W.van den Broek wrote: > Trying to make a little "program" for myself, i am working my way > through: "Teach yourself python..". Found out that mathematical > subject are the topics to begin with in simple programming. I am a > psychiatrist so i am used to associative thinking and pattern > recognition instead of logical thinking so bare with me please. As a > psychiatrist i am doing some research. I wanted to You don't need to go straight into mathy territory --- at least, not traditional mathy territory. You can try string or list-related stuff like this: Let's say we have a name: name = ["john", "doe"] One common thing we can do is get the initials of a name. We could do this manually: initials = name[0][0], name[1][0] But doing this manually might be a little tedious. For example, if we had a list of names, like: names = [ ["john", "doe"], ["jane", "doe"] ] then trying to get the initials of each names becomes twice as tedious. However, things don't need to be so bad: let's try writing a function that takes in a name, and returns its initials. ### def getInitials(name): first_name, last_name = name return first_name[0], last_name[0] ### Then we can use this to get the initials of each name in names: ### print getInitials(names[0]) print getInitials(names[1]) ### or, more generally: ### for name in names: print getInitials(name) ### Things like this might appeal more to you than taking the average of a list of numbers. > program some simple statistics, like finding the median of a list or a > mean, range and quartiles. Lists are probably useful in this, so > started making a list in a file: list.txt: l= [n, n1, n2,.....] This sounds reasonable. However, it might be better for list.txt to contain only numbers. For example, you can enter into your list.txt the following: ### 3 1 4 1 5 9 2 6 ### The reason for this is because data files should be treated as pure data. By default, they won't be interpreted as Python statements (unless we do something special like an exec_file function). Here's a interpreter session that shows how to read such a file: ### >>> file = open("example.txt") >>> file >>> numbers = file.readlines() >>> numbers ['3\012', '1\012', '4\012', '1\012', '5\012', '9\012', '2\012', '6\012'] >>> numbers = map(int, numbers) >>> numbers [3, 1, 4, 1, 5, 9, 2, 6] ### I'm using the readlines() method of a file to get all the input, since it makes it easier to read in a list of lines. Using read() will work, but it returns back the results as one single string --- it requires an extra step to break it down back to a list. However, the tricky part is to realize that Python really doesn't know that we have numbers --- as far as it can tell, they are strings. So to do any number stuff with them (like numerical sorting or comparisons), we need to change all those strings into integers. That's what the "map(int, numbers)" comes in --- semantically, it means: "apply this int() function on each element in numbers". The int() function takes anything and tries to coerse it into an integer. Afterwards, you should be able to do stuff like: numbers.sort() successfully. What you had before: ### x = open("list.txt", "rb") x.read () x.sort () ### doesn't quite work because the result of x.read() just "falls off" --- you hadn't stored the result of x.read(), so it just disappears. To make things easier for you, here's a function that takes in a file name, slurps each line of that file, and returns a list containing the respective numbers: ### def getNumbers(filename): file = open(filename) return map(int, file.readlines()) ### Use getNumbers() above to read in your file data, and that should simplify your file reading. If you have any questions on this, please feel free to ask. From dyoo@hkn.eecs.berkeley.edu Tue Jan 2 03:30:09 2001 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Mon, 1 Jan 2001 19:30:09 -0800 (PST) Subject: [Tutor] list problem In-Reply-To: <00123115060200.02657@vdbroekw> Message-ID: On Sun, 31 Dec 2000, W.W.van den Broek wrote: > to begin with in simple programming. I am a psychiatrist so i am used > to associative thinking and pattern recognition instead of logical > thinking so bare with me please. As a psychiatrist i am doing some > research. I wanted to One other thing: if you're doing research on how people learn how to program, you may want to speak with the edu-sig python newsgroup --- they talk about material that may interest you as a researcher: http://python.org/sigs/edu-sig/ I'd better point out that there are more resources that you can look at besides Python. For example, the Scheme language community is a good resource on this subject: http://www.teach-scheme.org Scheme is one of the lisp-based AI languages, and by that heritage, may be interesting for its symbolic processing capabilities. Scheme also does a lot of list stuff. *grin* Also, the language Prolog is all about pattern recognition, so perhaps it might be interesting to you. Good luck! From dyoo@hkn.eecs.berkeley.edu Tue Jan 2 03:39:26 2001 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Mon, 1 Jan 2001 19:39:26 -0800 (PST) Subject: [Tutor] Where to find example source codes. In-Reply-To: <00123121220400.01627@localhost.localdomain> Message-ID: On Sun, 31 Dec 2000, John Murray wrote: > This reminds me of something I've been thinking about for a while, ie; > should we be making our individual python project's code available to > each other? As long as the code isn't too long, small snippets should be fine. Of course, there's no requirement to post code to each other... *grin* But if you want to share your code, go ahead! If your program is a bit long, the source code repositories (like sourceforge) might be a better place to put it. Post a link to the code, and we can take a look. > as well as python), I would normally be embarrassed about releasing my > hideously amateurish code, though I would have no problems sharing it > with other list members. Ugly as my code may be, some of it has A good thing about sharing code is that we all learn to recognize ugly code. *grin* Sharing imperfect solutions is important, since that's how peer review works. Happy New Year! From dpm@softdesigns.com Tue Jan 2 06:50:18 2001 From: dpm@softdesigns.com (David Metzler) Date: Mon, 1 Jan 2001 22:50:18 -0800 Subject: [Tutor] Web client programming References: Message-ID: <002701c07488$4b17d040$0501a8c0@softdesigns.com> Deirdre Just for the record that telnet idea was not mine. I just installed a program for a client. It was a law firm and the program was a java app that connected via telnet to the main search site. It was westlaw I believe. Westlaw has very tight security as it is an expensive service so I wonder how they manage with telnet? Anyway that got me thinking about telnet, which as you say is probably not a great idea in general. In any event it is certainly a lot more work that just connecting with the mysql lib. So making my question more specific. Given: Linux server hosting myself.connected to Internet via dsl line 256k Some Windows 9x clients on same LAN segment as mysql server Some Windows 9x clients at home offices connected to internet via dsl or cable Some Windows 9x clients at home offices connected via dial-up modem Some Linux clients with all three connection options The client does not want to accept the limitations of a web browser environment. I am considering a Python client. What is the best way to program a connection to the backend sql database? What are the other options and why are the problems with them? What is necessary to make this code cross platform, IE: Linux, Win98 ----- Original Message ----- From: "Deirdre Saoirse" To: "David Metzler" Cc: Sent: Monday, January 01, 2001 1:56 PM Subject: Re: [Tutor] Web client programming > On Mon, 1 Jan 2001, David Metzler wrote: > > > I have several Linux hosted PHP 4 and MySql databases hosted at my > > office. The clients accessing these databases are all win98 with > > Explorer 5.50 This works well enough but the web browser based > > application has several limitations. The biggest limitation being the > > user-interface. I have this vision that I could build a Python > > program that could connect to the MySql based data and have all the > > features a modern GUI program would expect to have and be Gnome, and > > win98 compatible. > > The modern trend is away from proprietary UI programs and toward > browser-based programs as it doesn't require a specific set of underlying > system calls. And Gnome and win98 don't work well together. > > > I've looked at the telet module for python and it seems as though it > > might work. Just telnet to my server and run the mysql client and send > > data back and forth to a buffer and only show on the screnn what I > > want. > > For security reasons, you should never use telnet. > > > I know I could just use the mysql module and connect directly to the > > database but will it work well over a wan connection? > > Yes. I do it all the time. > > -- > _Deirdre * http://www.sfknit.org * http://www.deirdre.net > "We have an open door policy." -- Sheridan > "And an open airlock policy." -- Ivanova > > From dsh8290@rit.edu Tue Jan 2 04:10:20 2001 From: dsh8290@rit.edu (D-Man) Date: Mon, 1 Jan 2001 23:10:20 -0500 Subject: [Tutor] Web client programming In-Reply-To: <002701c07488$4b17d040$0501a8c0@softdesigns.com>; from dpm@softdesigns.com on Mon, Jan 01, 2001 at 10:50:18PM -0800 References: <002701c07488$4b17d040$0501a8c0@softdesigns.com> Message-ID: <20010101231020.A31465@westsidecnc.rh.rit.edu> Python is capable of being extremely portable across platforms -- if you stay away from the stuff marked as only available on certian platforms (ie. the Posix module, the win32 module, etc). For the GUI part of it there are several options: GTK has been ported to windows (check with the gimpwin team) and has python bindings (I don't know if the bindings work on windows, but I hope so since I want to use them in the future). Qt works on Linux and Windows and has python bindings. Someone else recently said that using PyQt in windows is free since the PyQt maintainer got a license for Qt from TrollTech and PyQt is an app which doesn't require you to get another license. Another alternative is wxPython -- python bindings for wxWindows. wxWindows is a cross-platform gui system that basically defines an interface which is then implemented in terms of the native gui system. ie Windows users would be using wxMFC which will look like a windows app while Linux users can use wxGTK or wxMotif which will make it look like a GTK or Motif app. All three solutions have GUI designers. GTK has a cool library associated with it called "libglade". libglade reads the output of the Glade gui designer and creates the gui at runtime (as opposed to the traditional method of generating code that is statically compiled). I don't know if it works in windows (it is written in C) but I really hope so. If not we could get together and make it portable (maybe re-code it in python ;-)). As for connecting to the backend database, I think using the database's given library for client connections would be the best route. HTH, -D On Mon, Jan 01, 2001 at 10:50:18PM -0800, David Metzler wrote: > The client does not want to accept the limitations of a web browser > environment. > I am considering a Python client. > What is the best way to program a connection to the backend sql database? > What are the other options and why are the problems with them? > What is necessary to make this code cross platform, IE: Linux, Win98 From spirou@carolo.com Tue Jan 2 05:20:14 2001 From: spirou@carolo.com (Denis) Date: Tue, 2 Jan 2001 06:20:14 +0100 Subject: [Tutor] Web client programming In-Reply-To: <20010101231020.A31465@westsidecnc.rh.rit.edu>; from dsh8290@rit.edu on Mon, Jan 01, 2001 at 11:10:20PM -0500 References: <002701c07488$4b17d040$0501a8c0@softdesigns.com> <20010101231020.A31465@westsidecnc.rh.rit.edu> Message-ID: <20010102062014.B343@carolo.com> Le Mon, Jan 01, 2001 at 11:10:20PM -0500, D-Man pianota: > > Python is capable of being extremely portable across platforms -- if > you stay away from the stuff marked as only available on certian > platforms (ie. the Posix module, the win32 module, etc). > > For the GUI part of it there are several options: > GTK (...) > Qt (...) > wxPython (...) And pure Tkinter would be another one. Not uninteresting. > As for connecting to the backend database, I think using the > database's given library for client connections would be the best > route. So do I. Have fun. -- Denis FRERE P3B : Club Free-Pytho-Linuxien Caroloregien http://www.p3b.org Aragne : Internet - Reseaux - Formations http://www.aragne.com From kjohnston@rcsi.ie Tue Jan 2 11:29:20 2001 From: kjohnston@rcsi.ie (Catriona Johnston) Date: Tue, 2 Jan 2001 11:29:20 -0000 Subject: [Tutor] chi-squared calculations Message-ID: <9921C1171939D3119D860090278AECA2DEC7FA@EXCHANGE> Happy New Year All! I really don't want to reinvent the wheel if I can at all help it and so was wondering if anyone out there knows of a Python module which can calculate chi-squares? Your help as always is appreciated! Kate From tescoil@irtc.net Tue Jan 2 15:36:12 2001 From: tescoil@irtc.net (Tesla Coil) Date: Tue, 02 Jan 2001 09:36:12 -0600 Subject: [Tutor] chi-squared calculations References: <9921C1171939D3119D860090278AECA2DEC7FA@EXCHANGE> Message-ID: <3A51F56C.105C25FD@irtc.net> On 2 Jan 2001, Catriona Johnston wrote: > I really don't want to reinvent the wheel if I can at all help it > and so was wondering if anyone out there knows of a Python > module which can calculate chi-squares? http://numpy.sourceforge.net/ --From the documentation: chi_square (df, shape=ReturnFloat) The chi_square() function returns an array of the specified shape that contains double precision floating point numbers with the chi square distribution with df degrees of freedom. If no shape is specified, a single number is returned. From alan.gauld@freenet.co.uk Tue Jan 2 17:29:02 2001 From: alan.gauld@freenet.co.uk (Alan Gauld) Date: Tue, 02 Jan 2001 17:29:02 +0000 Subject: [Tutor] Re: Web Client programming Message-ID: <3.0.1.32.20010102172902.018ee92c@mail.freenet.co.uk> There is another way to do this which is to use the http connection from within a Python GUI app. This will generally be faster than a web browser but slower than a dedicated mySql connection. But its as safe as any other web connection... The urllib library module should help here. And O'Reilly have/had a book entitled Web Client programming that showed how to do it (albeit mainly in Perl!) I've seen this book on magazine cover CDs so maybe its published on the net somewhere too. Essentially you will be calling the same CGI functions the browser solution would use and parsing the HTML returned. It means you can still use a browser interface if no Python is installed but get faster and more slicker GUI features where Python is available. Just something else to add to the mix... Alan g. From mbc2@netdoor.com Tue Jan 2 18:18:25 2001 From: mbc2@netdoor.com (mbc2@netdoor.com) Date: Tue, 2 Jan 2001 12:18:25 -0600 (CST) Subject: [Tutor] Class inheiritance question In-Reply-To: <20001231125205.A27300@westsidecnc.rh.rit.edu> Message-ID: Ok, I ran into some problems trying to redefine a variable set in the constructor. The problem was that I not only had variables that initialized my class from the database row passed to it, but I had also set variables in the constructor using some of the class's methods. For example: class Position: def __init__ (self, dbrow): self.calenrate = .1 #this is just a constant #I decided to pass a dictionary to the class using the db #field name as the key, in order to make the program a #little more flexible. self.CURYRSAL = dbrow.get("curyrsal","unknown") self.basesalary = self.Basesalary() def Basesalary (self): x = self.CURYRSAL*(1+self.calenrate) return x I did this because there were other methods of the class which needed to use the basesalary number. I found that even if I redefined CURYRSAL in the sub class, the Basesalary method still used the old figure because it was being called in the constructor. For example: class Positionrlgn(Position): def __init__(self,dbrow): Position.__init__(self,dbrow) #Basesalary gets called now self.CURYRSAL = 100000 #Redefined CURYRSAL but it doesn't #matter because basesalary has #already been set. This caused me to think that it was probably best to only put initializing data into the constructor and not to call any of the methods in the contructor. So I rewrote my class that way. The problem I ran into (which is the same problem that caused me to call those methods in the constructor in the first place) is that I cannot call a method to set a varialbe. For example: def Basesalary (self): x = self.CURYRSAL*(1+self.calenrate) return x basesalary = Basesalary() #Type Error: expected 1 argument, got 0 basesalary = Basesalary(self) #Name Error: there is no variable named self basesalary = self.Basealary() #Name Error: there is no variable named self basesalary = Position.Basesalary() #Name Error: there is no variable named #Position So what I ended up doing was setting basesalary = self.Basesalary inside each function that needed it. That works but results in those functions being called many times, which has slowed my program down alot. Am I doing this correctly? Is there a more efficient way. I don't want to call Basesalary() in the constructor, but I don't want to call it multiple times either. From deirdre@deirdre.net Tue Jan 2 18:31:55 2001 From: deirdre@deirdre.net (Deirdre Saoirse) Date: Tue, 2 Jan 2001 10:31:55 -0800 (PST) Subject: [Tutor] On asking for help Message-ID: I wish I didn't feel it necessary to write this, but I've had eight requests for help over the weekend that didn't go through the list. Please ask any questions about python coding ON the list. Please do NOT email questions directly to the list owners (i.e. myself and Wes Chun) or to frequent posters. Frankly, that's what leads to burnout on help lists. A variant on this is: you post a question, someone answers, and then you follow up to them privately, omitting the list. Please don't, unless it's an acknowledgement. If you still have questions, please post them to the list. We don't get paid for this. We help on this list so everyone can learn and, much as it might seem odd, so that we learn more. If you single out one of us, you may reach someone who doesn't know the answer to your question. You may reach someone who won't be reading their email right away. Even if we read our email, we may not be in a situation to devote our attention to the problem -- like while I was in the middle of debugging email setup on a server migration this weekend -- and received three of the eight requests. In other words, you will lengthen the time until you have the help you need if you omit the list. Most of us have jobs and lives. In my case, I work full-time, am a newlywed and am completing one master's degree (Computer Science) while starting another (Creative Writing). My spare time is negative already. If that isn't bad enough, I've received 228 emails so far today; yesterday, I received 594. Thus, please understand that, if I say I won't help you offlist, it's not personal. I have a lot to do -- especially this week. Homework Homework is something of a special case. One person recently has posted a problem that is clearly a homework problem they don't understand -- but didn't identify it as such. No one has helped. If you paste code or an abtract problem and ask for help, you probably won't get any. However, if you say, "this is the problem, this is what I understand about it and this is what I'm confused about," likely you'll get more help. -- _Deirdre * http://www.sfknit.org * http://www.deirdre.net "We have an open door policy." -- Sheridan "And an open airlock policy." -- Ivanova From tutor@python.org Tue Jan 2 19:34:24 2001 From: tutor@python.org (Tim Peters) Date: Tue, 2 Jan 2001 14:34:24 -0500 Subject: [Tutor] On asking for help In-Reply-To: Message-ID: [Deirdre Saoirse] > ... > Most of us have jobs and lives. In my case, I work full-time, am a > newlywed and am completing one master's degree (Computer Science) > while starting another (Creative Writing). My spare time is negative > already. If that isn't bad enough, I've received 228 emails so far > today; yesterday, I received 594. It sounds like you're behind schedule in starting a family too -- luckily, most people testify that having a baby or two around the house makes their schedule much easier to manage . > Thus, please understand that, if I say I won't help you offlist, it's > not personal. I have a lot to do -- especially this week. A small tip: if you can, have your email software set the Reply-To field to tutor@python.org when replying to the list. That should cut way back on the number of "personal" emails that end up in your inbox due to people just hitting (as I did with this reply ) *their* email software's "Reply All" button. we-should-all-be-grateful-we're-not-attached-to-guido's-inbox-ly y'rs - tim From brad_c@umailme.com Tue Jan 2 23:33:31 2001 From: brad_c@umailme.com (Brad C.) Date: Tue, 2 Jan 2001 15:33:31 -0800 Subject: [Tutor] Interpreter? Message-ID: <002101c07514$6b31dec0$686aaccf@k0g4f0> This is a multi-part message in MIME format. ------=_NextPart_000_001E_01C074D1.5C684CA0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable I have read part of your great tutorial, but I am stuck on one = thing. What is the interpreter? I have lots of small programs written up = on WorPad, but how do I turn them into python executable programs? Yes, = I have gone to the Python page for their tutorial and information about = the interpreter, but it doesn't seem to help that much. If you could = take a little time and tell me how to get to the interpreter, that will = be great. I am running Windows 98 and SuSe Linux 7.0=20 My e-mail adress is: brad_c@umailme.com=20 =20 = Brad C. ------=_NextPart_000_001E_01C074D1.5C684CA0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
         I=20 have read part of your great tutorial, but I am stuck = on one=20 thing. What is the interpreter? I have lots of small = programs=20 written up on WorPad, but how do I turn them into python executable = programs?=20 Yes, I have gone to the Python page for their tutorial and information = about the=20 interpreter, but it doesn't seem to help that much. If = you=20 could take a little time and tell me how to get to the interpreter, that = will be=20 great. I am running Windows 98 and SuSe Linux = 7.0=20
My e-mail adress is: brad_c@umailme.com
          &nbs= p;            = ;            =             &= nbsp;           &n= bsp;           
       =20             =    =20             =    =20             =    =20             =    =20  Brad C.
------=_NextPart_000_001E_01C074D1.5C684CA0-- From fredws_snb@ionet.net Tue Jan 2 20:40:23 2001 From: fredws_snb@ionet.net (Fred Schroeder) Date: Tue, 02 Jan 2001 14:40:23 -0600 Subject: [Tutor] Interpreter? References: <002101c07514$6b31dec0$686aaccf@k0g4f0> Message-ID: <006501c074fc$3b585840$16494e8b@okstate.edu> This is a multi-part message in MIME format. --Boundary_(ID_+WRmIftx9Js8ua7+jy9iSg) Content-type: text/plain; charset=iso-8859-1 Content-transfer-encoding: quoted-printable The interpreter is the component of Python that changes your text file = into bytecode and executes the file. To run your programs you have in = WordPad, type "python filename" without the quotes of course and = replacing filename with the real filename you gave your programs. You = will have to do this in the directory that the program exists in, or = give the full path to the file. If by interpreter you mean interactive interpreter, you get this by = typing "python" at the command line, without the quotes of course. ----- Original Message -----=20 From: Brad C.=20 To: tutor@python.org=20 Sent: Tuesday, January 02, 2001 5:33 PM Subject: [Tutor] Interpreter? I have read part of your great tutorial, but I am stuck on = one thing. What is the interpreter? I have lots of small programs = written up on WorPad, but how do I turn them into python executable = programs? Yes, I have gone to the Python page for their tutorial and = information about the interpreter, but it doesn't seem to help that = much. If you could take a little time and tell me how to get to the = interpreter, that will be great. I am running Windows 98 and SuSe Linux = 7.0=20 My e-mail adress is: brad_c@umailme.com=20 = = Brad C. --Boundary_(ID_+WRmIftx9Js8ua7+jy9iSg) Content-type: text/html; charset=iso-8859-1 Content-transfer-encoding: quoted-printable
The interpreter is the component of = Python that=20 changes your text file into bytecode and executes the file.  To run = your=20 programs you have in WordPad, type "python filename" without the quotes = of=20 course and replacing filename with the real filename you gave your=20 programs.  You will have to do this in the directory that the = program=20 exists in, or give the full path to the file.
If by interpreter you mean interactive=20 interpreter, you get this by typing "python" at the command line, = without the=20 quotes of course.
 
----- Original Message -----
From:=20 Brad = C.=20
Sent: Tuesday, January 02, 2001 = 5:33=20 PM
Subject: [Tutor] = Interpreter?

        =20 I have read part of your great tutorial, but I am = stuck on=20 one thing. What is the interpreter? I have lots of = small=20 programs written up on WorPad, but how do I turn them into python = executable=20 programs? Yes, I have gone to the Python page for their tutorial and=20 information about the interpreter, but it doesn't = seem to=20 help that much. If you could take a little time and tell me how to get = to the=20 interpreter, that will be great. I am running Windows 98 = and=20 SuSe Linux 7.0
My e-mail adress is: brad_c@umailme.com =
          &nbs= p;            = ;            =             &= nbsp;           &n= bsp;           
        =             =    =20             =    =20             =    =20             =    =20  Brad C.
--Boundary_(ID_+WRmIftx9Js8ua7+jy9iSg)-- From dsh8290@rit.edu Tue Jan 2 20:58:12 2001 From: dsh8290@rit.edu (D-Man) Date: Tue, 2 Jan 2001 15:58:12 -0500 Subject: [Tutor] Class inheiritance question In-Reply-To: ; from mbc2@netdoor.com on Tue, Jan 02, 2001 at 12:18:25PM -0600 References: <20001231125205.A27300@westsidecnc.rh.rit.edu> Message-ID: <20010102155812.A1761@westsidecnc.rh.rit.edu> Here's a sample interpreter session : >>> class Parent : ... def __init__( self ) : ... self.val1 = 5 ... self.set_val2() ... def set_val2( self ) : ... self.val2 = self.val1 + 3 ... >>> class Child( Parent ) : ... def __init__( self ) : ... Parent.__init__( self ) ... self.val1 = 9 ... self.set_val2() ... >>> c = Child() >>> c.val1 9 >>> c.val2 12 >>> This is the sort of effect you are looking for, right? The child class must explicitly call the init function in the parent (super) class. Also, if any values are computed in the super class's init based on other variables (such as 'val2' here), they must be recomputed after the other variable has been given it's new value. That is why I call set_val2 in the child's init. Another difference here is that my set_val2 function doesn't return a value, but instead sets the instance member directly. On Tue, Jan 02, 2001 at 12:18:25PM -0600, mbc2@netdoor.com wrote: > > Ok, I ran into some problems trying to redefine a variable set in the > constructor. The problem was that I not only had variables that > initialized my class from the database row passed to it, but I had also > set variables in the constructor using some of the class's methods. For > example: > > class Position: > def __init__ (self, dbrow): > self.calenrate = .1 #this is just a constant > #I decided to pass a dictionary to the class using the db > #field name as the key, in order to make the program a > #little more flexible. > self.CURYRSAL = dbrow.get("curyrsal","unknown") > self.basesalary = self.Basesalary() > > def Basesalary (self): > x = self.CURYRSAL*(1+self.calenrate) > return x > > I did this because there were other methods of the class which needed to > use the basesalary number. I found that even if I redefined CURYRSAL in > the sub class, the Basesalary method still used the old figure because it > was being called in the constructor. For example: > Just out of curiosity, is there a reason why the other methods can't use the data member 'basesalary' instead of the function 'Basesalary' ? > class Positionrlgn(Position): > def __init__(self,dbrow): > Position.__init__(self,dbrow) #Basesalary gets called now > self.CURYRSAL = 100000 #Redefined CURYRSAL but it doesn't > #matter because basesalary has > #already been set. As I mentioned above, you must call the 'Basesalary' function again since when it ran self.CURYRSAL was the old value. This would be a good reason to make 'Basesalary' a separate function from the init function. However, since it will set a member I don't think it should be used by any functions except the init. > > This caused me to think that it was probably best to only put initializing > data into the constructor and not to call any of the methods in the > contructor. So I rewrote my class that way. The problem I ran into (which > is the same problem that caused me to call those methods in the > constructor in the first place) is that I cannot call a method to set a > varialbe. For example: > > def Basesalary (self): > x = self.CURYRSAL*(1+self.calenrate) > return x > These errors are to be expected. Here 'Basesalary' is a free-standing function that has nothing whatsoever to do with the class you have. > basesalary = Basesalary() #Type Error: expected 1 argument, got 0 You declared the function to take an argument. Since it is not a class, there is no magic here with passing the new object as the first argument. > basesalary = Basesalary(self) #Name Error: there is no variable named self Just as the error says, there is no variable 'self' here. Self is just the name commonly given to the first argument for functions inside classes. > basesalary = self.Basealary() #Name Error: there is no variable named self Same here. You haven't created a local variable named 'self'. > basesalary = Position.Basesalary() #Name Error: there is no variable named > #Position You haven't created a variable named 'Position' in the local namespace. I don't know exactly why this error, but I know that you must have the 'Position' class defined somewhere else (not where you executed this line of code). > > So what I ended up doing was setting basesalary = self.Basesalary inside > each function that needed it. That works but results in those functions > being called many times, which has slowed my program down alot. > > Am I doing this correctly? Is there a more efficient way. I don't want to > call Basesalary() in the constructor, but I don't want to call it multiple > times either. Basesalary should be called in the init function. This will init the instance member to the correct value. Then in each of the other functions you have, use the instance member instead of recomputing the value. Are you familiar with OO design? If not, let the list know and someone (maybe me if I get to it first :-)) will explain it. HTH, -D From deirdre@deirdre.net Tue Jan 2 21:02:27 2001 From: deirdre@deirdre.net (Deirdre Saoirse) Date: Tue, 2 Jan 2001 13:02:27 -0800 (PST) Subject: [Tutor] Re: python help In-Reply-To: Message-ID: I'm answering part of this email on-list; I've removed the name as it was a private email. On Tue, 2 Jan 2001, wrote: > I started my job back in mid-September and still have no idea how to > manipulate the Python legacy I have been "willed" from the previous 3 > programmers [...]. We'd be happy to help answer any questions you have on the list. It's even possible that some of the former programmers are on the list (python is still a relatively small community) and they may be able to offer more specific help. > I was wondering if you answer case-specific programming questions or > if they are just generalized questions about code. We answer case-specific questions, but it's probably best if you formulate specific questions. We don't mind code snippets, but long stretches of code are harder to deal with in this medium. My best advice is to post a snippet you don't understand and ask specific questions about its design. Other good questions are of the "how do I do X?" format. -- _Deirdre * http://www.sfknit.org * http://www.deirdre.net "We have an open door policy." -- Sheridan "And an open airlock policy." -- Ivanova From cruciatuz Tue Jan 2 21:01:48 2001 From: cruciatuz (cruciatuz) Date: Tue, 2 Jan 2001 22:01:48 +0100 Subject: [Tutor] Re:Where to find example source codes. In-Reply-To: <20010102170111.64EEFEB6B@mail.python.org> References: <20010102170111.64EEFEB6B@mail.python.org> Message-ID: <1003995718.20010102220148@gmx.de> Hello tutor-request, Tuesday, January 02, 2001, 6:01:11 PM, you wrote: I am a beginner, too in python and in programming in general. I would really like a kind of snippet repository for the "Python beginners community", because i've learned a lot about Java within 20 minutes of looking in a file with the format: how do i ... 1. print something to stdout 1.1 format this output 1.2 ... 2. open a file 2.1 open a file in binary mode and why 2.2 ... . . . 34. ... I don't remember where i found this file and i already deleted it since it was for java programmers and i am not a java programmer (was not the right language for me). but it was a bigger help for me than the very technical and indirect official java-tutorial. a single question which is answered with a few lines of example code and a short explanation is better than a whole technically chapter in a bloated book :) let's set up something like that at python.org or somewhere else, that would be great! PS: It should be a single html file with well chosen examples in perfect and elegant but readable syntax -> we need a few sentences about the criteria which is a "good" example and a "not so good example". Every Addition should be discussed in this list and a single person should finally decide if it should be added to the list or not. + ---------------------------------- + | Best regards: Cruciatuz_AH | + ---------------------------------- + | AKA: Stefan Antoni | + ---------------------------------- + | mobile: +49 (0)171 9587067 | | ICQ: 72292815 | | PGP-Key: AVAILABLE | + ---------------------------------- + 21:42 / Dienstag, 2. Januar 2001 From deirdre@deirdre.net Tue Jan 2 21:32:21 2001 From: deirdre@deirdre.net (Deirdre Saoirse) Date: Tue, 2 Jan 2001 13:32:21 -0800 (PST) Subject: [Tutor] Re:Where to find example source codes. In-Reply-To: <1003995718.20010102220148@gmx.de> Message-ID: On Tue, 2 Jan 2001, cruciatuz wrote: > Hello tutor-request, tutor@python.org is the list address. Thus, I've changed it. Tutor-request is an address for requesting subscription changes. > 1. print something to stdout print "foo" (goes to stdout by default) > 1.1 format this output you can use c-like formatting. You can also see the strings module for some formatting (such as strings.zfill) See also: http://www.python.org/doc/current/tut/node9.html#SECTION009100000000000000000 > 2. open a file f = open('filename', 'r') See the same URL above for file info. > I don't remember where i found this file and i > already deleted it since it was for java > programmers and i am not a java programmer (was > not the right language for me). but it was a > bigger help for me than the very technical and > indirect official java-tutorial. a single > question which is answered with a few lines of > example code and a short explanation is better than > a whole technically chapter in a bloated book :) > > let's set up something like that at python.org > or somewhere else, that would be great! There's already a tutorial at python.org, but if you want to write another with a specific format, you're welcome to. :) -- _Deirdre * http://www.sfknit.org * http://www.deirdre.net "We have an open door policy." -- Sheridan "And an open airlock policy." -- Ivanova From tbrauch@mindless.com Tue Jan 2 21:37:50 2001 From: tbrauch@mindless.com (Timothy M. Brauch) Date: Tue, 02 Jan 2001 16:37:50 -0500 Subject: [Tutor] Closing an urllib.urlopen Message-ID: <3A524A2E.36CE4BD3@mindless.com> I've opened a web page in the following way: top_ten_html=urllib.urlopen('http://www.cbs.com/latenight/lateshow/') Do I have to close this? I know with files you don't necessarily need to close any files you open, but it is good to do so. Is it the same way with urlopen? Tim From dpm@softdesigns.com Wed Jan 3 04:27:43 2001 From: dpm@softdesigns.com (David Metzler) Date: Tue, 2 Jan 2001 20:27:43 -0800 Subject: [Tutor] mysql on windows with python 2.0 Message-ID: <001601c0753d$84ada040$0501a8c0@softdesigns.com> This is a multi-part message in MIME format. ------=_NextPart_000_0013_01C074FA.760D4100 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable I found the following archive MySQL-python-0.3.0-win32-2.zip on = http://home.t-online.de/home/err666/ My goal is to get mysql support into my windows Python 2.0 and connect = to a remote Linux server running the most current Mysql . I have installed the windows version of python 2.0 I put c:\python in my windows path C:\ >Cd \pymysql (this is where I unzipped the above archive) C:\pymysql> Python setup.py I get an error about distutils.core not being available. Could you tell me how to get distutils and make it available? The source of install.py implies that I have mysql loaded on the windows = machine and is linking against it. I want connect to the mysql on a = remote linux box perhaps on another network (but both computers are = connected via the internet). Can I make this work? How? The install.py in the above archive starts like this: #!/usr/bin/env python =20 """Setup script for the MySQLdb module distribution.""" =20 import os, sys from distutils.core import setup from distutils.extension import Extension =20 YES =3D 1 NO =3D 0 =20 # set this to 1 if you have the thread-safe mysqlclient library thread_safe_library =3D NO =20 # You probably don't have to do anything past this point. If you # do, please mail me the configuration for your platform. Don't # forget to include the value of sys.platform and os.name. =20 mysqlclient =3D thread_safe_library and "mysqlclient_r" or "mysqlclient" =20 if sys.platform =3D=3D "linux-i386": # Red Hat include_dirs =3D ['/usr/include/mysql'] library_dirs =3D ['/usr/lib/mysql'] libraries =3D [mysqlclient, "z"] runtime_library_dirs =3D [] extra_objects =3D [] elif sys.platform =3D=3D "win32": include_dirs =3D [r'd:\MySQL\include'] library_dirs =3D [r'd:\MySQL\lib\opt'] libraries =3D [mysqlclient, 'zlib', 'msvcrt', 'libcmt', 'wsock32', 'advapi32'] runtime_library_dirs =3D [] extra_objects =3D [r'd:\MySQL\lib\opt\mysqlclient.lib'] elif os.name =3D=3D "posix": # most Linux/UNIX platforms include_dirs =3D ['/usr/include/mysql'] library_dirs =3D ['/usr/lib/mysql'] # MySQL-3.23 seems to need libz libraries =3D [mysqlclient, "z"] # On some platorms, this can be used to find the shared libraries # at runtime, if they are in a non-standard location. Doesn't # work for Linux gcc. ## runtime_library_dirs =3D library_dirs runtime_library_dirs =3D [] # This can be used on Linux to force use of static mysqlclient lib ## extra_objects =3D ['/usr/lib/mysql/libmysqlclient.a'] extra_objects =3D [] else: raise "UnknownPlatform", "sys.platform=3D%s, os.name=3D%s" % \ (sys.platform, os.name) =20 =20 ------=_NextPart_000_0013_01C074FA.760D4100 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
 I=20 found the following archive MySQL-python-0.3.0-win32-2.zip on http://home.t-online.de/hom= e/err666/

 My goal is to get mysql support into my = windows Python=20 2.0 and connect to a remote Linux server running the most current Mysql = .

I have installed the windows version of python = 2.0

I put c:\python in my windows path

C:\ >Cd \pymysql =20 (this is where I unzipped the above archive)

C:\pymysql> Python setup.py

 I get an error about distutils.core not being = available.

 Could you tell me how to get distutils and = make it=20 available?

The=20 source of install.py implies that I have mysql loaded on the windows = machine and=20 is linking against it. I want connect to the mysql on a remote linux box = perhaps=20 on another network (but both computers are connected via the internet). = Can I=20 make this work? How?

The install.py in the above archive starts like = this:

#!/usr/bin/env=20 python

 

"""Setup script for the = MySQLdb=20 module distribution."""

 

import=20 os, sys

from=20 distutils.core import setup

from=20 distutils.extension import Extension

 

YES =3D=20 1

NO =3D=20 0

 

# set=20 this to 1 if you have the thread-safe mysqlclient = library

thread_safe_library =3D=20 NO

 

# You=20 probably don't have to do anything past this point. If = you

# do,=20 please mail me the configuration for your platform. = Don't

#=20 forget to include the value of sys.platform and = os.name.

 

mysqlclient =3D = thread_safe_library=20 and "mysqlclient_r" or "mysqlclient"

 

if=20 sys.platform =3D=3D "linux-i386": # Red Hat

    include_dirs =3D=20 ['/usr/include/mysql']

    library_dirs =3D=20 ['/usr/lib/mysql']

    libraries =3D = [mysqlclient,=20 "z"]

    = runtime_library_dirs =3D=20 []

    extra_objects =3D=20 []

elif=20 sys.platform =3D=3D "win32":

    include_dirs =3D=20 [r'd:\MySQL\include']

    library_dirs =3D=20 [r'd:\MySQL\lib\opt']

    libraries =3D = [mysqlclient,=20 'zlib', 'msvcrt', 'libcmt',

           &n= bsp;    =20 'wsock32', 'advapi32']

    = runtime_library_dirs =3D=20 []

    extra_objects =3D=20 [r'd:\MySQL\lib\opt\mysqlclient.lib']

elif=20 os.name =3D=3D "posix": # most Linux/UNIX = platforms

    include_dirs =3D=20 ['/usr/include/mysql']

    library_dirs =3D=20 ['/usr/lib/mysql']

    # MySQL-3.23 seems = to need=20 libz

    libraries =3D = [mysqlclient,=20 "z"]

    # On some = platorms, this can=20 be used to find the shared libraries

    # at runtime, if = they are in=20 a non-standard location. Doesn't

    # work for Linux=20 gcc.

    ## = runtime_library_dirs =3D=20 library_dirs

    = runtime_library_dirs =3D=20 []

    # This can be used = on Linux=20 to force use of static mysqlclient lib

    ## extra_objects = =3D=20 ['/usr/lib/mysql/libmysqlclient.a']

    extra_objects =3D=20 []

else:

    raise = "UnknownPlatform",=20 "sys.platform=3D%s, os.name=3D%s" % \

         =20 (sys.platform, os.name)

 

 

------=_NextPart_000_0013_01C074FA.760D4100-- From dyoo@hkn.eecs.berkeley.edu Wed Jan 3 02:20:24 2001 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Tue, 2 Jan 2001 18:20:24 -0800 (PST) Subject: [Tutor] how to flatten and lump lists In-Reply-To: Message-ID: First, let's start off by showing what we want flatten() to do. We'd expect that: flatten([1, 2, 3, 4]), flatten([ [1], 2, [3, [4]] ]), and flatten([ [1], [2], [3], [4] ]) to all return the list [1, 2, 3, 4]. One simple way to solve this problem is to use recursion --- if we have some list L that we'd like to flatten, we can pretend that flatten() will work on a smaller version of a list. So, a partial definition of flatten() would be: ### def flatten(L): return flatten(L[0]) + flatten(L[1:]) ### What this means is, let's flatten the first element of our list L, and let's flatten the rest of L. Finally, concatenate the lists together, and we'll be done. All we need to do now is tell Python our "base cases" --- stuff that should be so obvious that we don't need to call flatten() recursively. Here's the first: if L is not a list, return a list containing L. and we can write this in Python as: if type(L) != type([]): return [L] Another obvious case is trying to flatten the empty list --- when we say: flatten([]) we should just get back the empty list. Putting everything together, here's the complete version of the flatten() function: ### def flatten(L): if type(L) != type([]): return [L] if L == []: return L return flatten(L[0]) + flatten(L[1:]) ### Let's test it out. ### >>> flatten([1, 2, 3, 4, 5]) [1, 2, 3, 4, 5] >>> flatten([1, [2, 3, [4], [5]]]) [1, 2, 3, 4, 5] >>> flatten([[1], [2], [3], [4], [5]]) [1, 2, 3, 4, 5] ### Hope this helps! On Tue, 2 Jan 2001, kevin parks wrote: > > Sure. Maybe i'll learn something from it. Thanks! > > -- > > On Mon, 1 Jan 2001 19:31:51 > Daniel Yoo wrote: > >On Mon, 1 Jan 2001, kevin parks wrote: > > > >> I got it! just so the tutors here know there is no need to reply. i > >> got the usual entertaining and informative lesson from Mr. Peters. > >> Still absorbing the nuances of his answer which is son-like (jp:zen). > > > >Are you still interested in the list flattening code? If you'd like, I > >can post it to the tutor list. From bwinton@iname.com Wed Jan 3 04:26:15 2001 From: bwinton@iname.com (Blake Winton) Date: 02 Jan 2001 23:26:15 -0500 Subject: [Tutor] Re:Where to find example source codes. In-Reply-To: Message-ID: <200101030426.XAA11731@tor.dhs.org> On 02 Jan 2001 13:32:21 -0800, Deirdre Saoirse wrote: > > I don't remember where i found this file and i > > already deleted it since it was for java > > a single > > question which is answered with a few lines of > > example code and a short explanation is better than > > a whole technically chapter in a bloated book :) > There's already a tutorial at python.org, but if you want to write another > with a specific format, you're welcome to. :) And there are some snippets at http://tor.dhs.org/~zephyrfalcon/snippets/ Later, Blake. -- 9:40pm up 52 days, 21:07, 2 users, load average: 0.02, 0.09, 0.07 From dyoo@hkn.eecs.berkeley.edu Wed Jan 3 05:35:10 2001 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Tue, 2 Jan 2001 21:35:10 -0800 (PST) Subject: [Tutor] Closing an urllib.urlopen In-Reply-To: <3A524A2E.36CE4BD3@mindless.com> Message-ID: On Tue, 2 Jan 2001, Timothy M. Brauch wrote: > I've opened a web page in the following way: > > top_ten_html=urllib.urlopen('http://www.cbs.com/latenight/lateshow/') > > Do I have to close this? I know with files you don't necessarily need > to close any files you open, but it is good to do so. Is it the same > way with urlopen? It's the same thing with urlopen() --- you don't have to close it, since Python figures out when a resource becomes inaccessible and automatically calls close(). Still, it can't hurt to do the close() manually. From cpsoct@lycos.com Wed Jan 3 07:11:17 2001 From: cpsoct@lycos.com (kevin parks) Date: Wed, 03 Jan 2001 16:11:17 +0900 Subject: [Tutor] Re: aksing for help Message-ID: additionally, i would like to kindly request that only text be sent to the list. HTML mail is very bothersome, particularly to those who get the digest form, since none of the tags can then be interpreted. If you are new, please look in your edit/preferences dialog and uncheck "send as HTML mail". Or whatever the specifics may be on your program. thank you very much. -kp-- Get FREE Email/Voicemail with 15MB at Lycos Communications at http://comm.lycos.com From alan.gauld@bt.com Wed Jan 3 11:32:57 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 3 Jan 2001 11:32:57 -0000 Subject: [Tutor] Re:Where to find example source codes. Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D49C@mbtlipnt02.btlabs.bt.co.uk> > bigger help for me than the very technical and > indirect official java-tutorial. a single > question which is answered with a few lines of > example code and a short explanation is better than > a whole technically chapter in a bloated book :) That depends on whether you just want to solve the immediate problem or to understand how to solve similar problems in the general case. Code snippets are great for the former but lousy at the latter. OTOH I have to confess that I haven't yet found a good book on Java - I'm just started Bruce Eckels "Thinking in Java" and it looks promising.... Alan g From moshez@zadka.site.co.il Wed Jan 3 19:55:00 2001 From: moshez@zadka.site.co.il (Moshe Zadka) Date: Wed, 3 Jan 2001 21:55:00 +0200 (IST) Subject: [Tutor] Re:Where to find example source codes. In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20751D49C@mbtlipnt02.btlabs.bt.co.uk> References: <5104D4DBC598D211B5FE0000F8FE7EB20751D49C@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <20010103195500.0CC44A84F@darjeeling.zadka.site.co.il> On Wed, 3 Jan 2001, alan.gauld@bt.com wrote: > OTOH I have to confess that I haven't yet found a good > book on Java - I'm just started Bruce Eckels "Thinking > in Java" and it looks promising.... For the record, I was througholy unimpressed with it, particularily after I found a couple of nasty bugs. -- Moshe Zadka This is a signature anti-virus. Please stop the spread of signature viruses! From alan.gauld@bt.com Wed Jan 3 16:56:49 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 3 Jan 2001 16:56:49 -0000 Subject: [Tutor] web page for book Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D4A4@mbtlipnt02.btlabs.bt.co.uk> My book is now available but unfortunately contains the usual collection of typos etc. Most are harmless(spelling mistakes, layout hiccups etc) but a few more serious ones sneaked thru' - including at least one case of losing some lines of source code! To remedy this I have set up a web site for errata and feedback etc. http;//www.crosswinds.net/~agauld/book/ Aplologies to anyone who has bought the book and is confused! (FWIW The CD ROM source code is OK.) Alan G. From shaleh@valinux.com Wed Jan 3 17:04:07 2001 From: shaleh@valinux.com (Sean 'Shaleh' Perry) Date: Wed, 03 Jan 2001 09:04:07 -0800 (PST) Subject: [Tutor] when string,join won't work Message-ID: string.join assumes that the sequence is all strings. What do i do if this is not the case. A friend is trying to make db requests and print the returned data. Not every field is a string, so join won't work. Suggestions? From arcege@shore.net Wed Jan 3 17:40:34 2001 From: arcege@shore.net (Michael P. Reilly) Date: Wed, 3 Jan 2001 12:40:34 -0500 (EST) Subject: [Tutor] when string,join won't work In-Reply-To: from "Sean 'Shaleh' Perry" at Jan 03, 2001 09:04:07 AM Message-ID: <200101031740.MAA09297@northshore.shore.net> > string.join assumes that the sequence is all strings. What do i do if this is > not the case. A friend is trying to make db requests and print the returned > data. Not every field is a string, so join won't work. Suggestions? Just convert them all to strings and join the resulting list: >>> class Toast: ... pass ... >>> req = ['spam', 1, 'eggs', Toast()] >>> req ['spam', 1, 'eggs', <__main__.Toast instance at 80d5f00>] >>> string.join(map(str, req)) 'spam 1 eggs <__main__.Toast instance at 80d5f00>' >>> I would hope that any data you have in the sequence would have a nice __str__ or __repr__ method (unlike my deliberately naughty Toast class above). -Arcege -- ------------------------------------------------------------------------ | Michael P. Reilly, Release Manager | Email: arcege@shore.net | | Salem, Mass. USA 01970 | | ------------------------------------------------------------------------ From curtis.larsen@Covance.Com Wed Jan 3 17:44:24 2001 From: curtis.larsen@Covance.Com (Curtis Larsen) Date: Wed, 03 Jan 2001 11:44:24 -0600 Subject: [Tutor] 'Name Genereator' Question Message-ID: I'm writing a quickie little script that generates names, to better understand string manipulation. What I'd like to have is something like "map" that can be used against a number of occurrences of a character in a string and replace it -- without using a lot of loops. Here's an example: # Create names based on a filter where "." equals a random consonant and "," is a random vowel. # The first argument is the # of names to generate, the second is the filter, # and other letters can be used (including spaces) to fix a certain character for that spot. # Example: namegen.py 10 ".,..,." might generate ten names like "becker", while # namegen.py 5 "j,.. r,bb,t" would only create five names like "jack rabbit". import random, string, sys vowels = "aeiou" cons = "bcdfghjklmnpqrstvwxyz" name_count = int(sys.argv[1]) name_filter = sys.argv[2] for names in range(name_count): name = name_filter # The following doesn't work of course (since 'name' is a string), # but its close to what I'd LIKE to do: for "." in name: map(string.replace(name,".",cons[random.randint(0,21)],1)) for "," in name: map(string.replace(name,",",vowels[random.randint(0,5)],1)) print name The kicker (to me) is how to call "randint" for each character replacement target in "name". The easy way would be to "while" loop for "'.' in name", etc., or I could create a function to do the replacement and call it each time, but I thought there would be a more straightforward answer. (I'm probably missing something really, really simple here, right??) Thanks, Curtis PS: I know "randrange" replaces "randint", but I'm not using 2.0 on the system in question. ----------------------------------------------------- Confidentiality Notice: This e-mail transmission may contain confidential or legally privileged information that is intended only for the individual or entity named in the e-mail address. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or reliance upon the contents of this e-mail is strictly prohibited. If you have received this e-mail transmission in error, please reply to the sender, so that we can arrange for proper delivery, and then please delete the message from your inbox. Thank you. From moshez@zadka.site.co.il Thu Jan 4 02:18:45 2001 From: moshez@zadka.site.co.il (Moshe Zadka) Date: Thu, 4 Jan 2001 04:18:45 +0200 (IST) Subject: [Tutor] when string,join won't work In-Reply-To: References: Message-ID: <20010104021845.97175A84F@darjeeling.zadka.site.co.il> On Wed, 03 Jan 2001 09:04:07 -0800 (PST), "Sean 'Shaleh' Perry" wrote: > string.join assumes that the sequence is all strings. What do i do if this is > not the case. A friend is trying to make db requests and print the returned > data. Not every field is a string, so join won't work. Suggestions? Make them strings: string.join(map(str, sequence)) Read about ``map'' and ``str'' at your friendly neighbourhood library reference guide. (http://www.python.org/doc/) -- Moshe Zadka This is a signature anti-virus. Please stop the spread of signature viruses! From shaleh@valinux.com Wed Jan 3 18:17:33 2001 From: shaleh@valinux.com (Sean 'Shaleh' Perry) Date: Wed, 03 Jan 2001 10:17:33 -0800 (PST) Subject: [Tutor] when string,join won't work In-Reply-To: <20010104021845.97175A84F@darjeeling.zadka.site.co.il> Message-ID: On 04-Jan-2001 Moshe Zadka wrote: > On Wed, 03 Jan 2001 09:04:07 -0800 (PST), "Sean 'Shaleh' Perry" > wrote: >> string.join assumes that the sequence is all strings. What do i do if this >> is >> not the case. A friend is trying to make db requests and print the returned >> data. Not every field is a string, so join won't work. Suggestions? > > Make them strings: > > string.join(map(str, sequence)) > > Read about ``map'' and ``str'' at your friendly neighbourhood library > reference guide. (http://www.python.org/doc/) yeah, I was just hoping there was a better way. one of the reason to use a scripting language is to get away from: string foo; foo = 'hello'; kind of code. Python requiring me to know that the sequence is 100% strings is kind of silly in my book. From brad_c@umailme.com Thu Jan 4 03:46:41 2001 From: brad_c@umailme.com (Brad C.) Date: Wed, 3 Jan 2001 19:46:41 -0800 Subject: [Tutor] TK?? Creating exe extentions... Message-ID: <000801c07600$f3ac3240$cfb4accf@k0g4f0> This is a multi-part message in MIME format. ------=_NextPart_000_0005_01C075BD.E4F1E260 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hello agian. I'm back with probably a simple question. What is TK? WHat = can it be used for? What is it used for, if anything? Also, how would I = create an exe file extencion instead of .py?Thanks for the help. Happy = New Year! ------=_NextPart_000_0005_01C075BD.E4F1E260 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
Hello agian. I'm back with probably a = simple=20 question. What is TK? WHat can it be used for? What is it used for, if = anything?=20 Also, how would I create an exe file extencion instead of .py?Thanks for = the=20 help. Happy New Year!
------=_NextPart_000_0005_01C075BD.E4F1E260-- From rmallett@rational.com Thu Jan 4 01:02:48 2001 From: rmallett@rational.com (Mallett, Roger) Date: Wed, 3 Jan 2001 17:02:48 -0800 Subject: [Tutor] setting object to None doesn't kill Word Message-ID: <78D9B26221DBD411B7EE00D0B73EB0EA06730E@cupex2.rational.com> System: Windows 2000, Office 2000 I am on page 67-68 of Mark Hammond's book "Python Programming on Win32" and I can't seem to kill Word by setting the object to None. I did the following: >>> import win32com.client >>> x1 = win32.com.client.Dispatch('Excel.Application') At this point an instance of Excel has been created and I see it listed in the Task Manager. Next I will kill the Excel object >>>x1 = None The Excel instance has been terminated. I can now longer see it listed in Task Manager Now, if I try the same with Word >>> x1=win32.com.client.Dispatch('Word.Application') I can see Word in the Task Manager. However, if I try to kill it, it doesn't go away. >>> x1=None # this doesn't work. Why Not? I am wondering if this is a Win2K specific issue and if there is another way to kill the task besides changing the python object. Any assistance in understanding this is greatly appreciated. Thank you, Roger Mallett From tescoil@irtc.net Thu Jan 4 01:55:46 2001 From: tescoil@irtc.net (Tesla Coil) Date: Wed, 03 Jan 2001 19:55:46 -0600 Subject: [Tutor] 'Name Genereator' Question References: Message-ID: <3A53D822.9CE5BCA7@irtc.net> On 03 Jan 2001, Curtis Larsen wrote: > What I'd like to have is something like "map" that can be used > against a number of occurrences of a character in a string and > replace it -- without using a lot of loops. [...] The kicker (to > me) is how to call "randint" for each character replacement > target in "name". Okay, it looks like a circus performer spinning plates, but here it's done in a nested loop with a couple conditionals: # Create names based on a filter where "." equals a random # consonant and "," is a random vowel. The first argument # is the # of names to generate, the second is the filter, and # other letters can be used (including spaces) to fix a certain # character for that spot. Example: namegen.py 10 ".,..,." # might generate ten names like "becker", while namegen.py 5 # "j,.. r,bb,t" would only create five names like "jack rabbit". import random, string, sys vowels = "aeiou" cons = "bcdfghjklmnpqrstvwxyz" count = int(sys.argv[1]) filter = sys.argv[2] for names in range(count): name = filter for letter in range(len(name)): name = name[1:len(name)]+name[0] if name[0]==".": name = cons[random.randint(0,20)]+name[1:len(name)] if name[0]==",": name = vowels[random.randint(0,4)]+name[1:len(name)] print name From tescoil@irtc.net Thu Jan 4 02:12:15 2001 From: tescoil@irtc.net (Tesla Coil) Date: Wed, 03 Jan 2001 20:12:15 -0600 Subject: [Tutor] 'Name Genereator' Question References: <3A53D822.9CE5BCA7@irtc.net> Message-ID: <3A53DBFF.4D1BECBC@irtc.net> On 03 Jan 2001, I wrote: > import random, string, sys Oh, no longer any need to import the string module. on_chalkboard = "Check for vestigal imports in all rewrites." for punishment in range(100): print on_chalkboard From rmallett@rational.com Thu Jan 4 01:21:59 2001 From: rmallett@rational.com (Mallett, Roger) Date: Wed, 3 Jan 2001 17:21:59 -0800 Subject: [Tutor] server won't register because attribute win32com.server not found Message-ID: <78D9B26221DBD411B7EE00D0B73EB0EA067320@cupex2.rational.com> Operating System: Window 2000, Service Pack 1 Using PythonWin, Active Python, build 202 I can't seem to register the python COM server below. The code I am using comes from pp 102-103 of Mark Hammond's book "Programming on Win32". As shown in the Interactive Session below, I get the error: "AttributeError: server" What might I be doing wrong? (the code is below) import win32com class COMBookSet: _reg_clsid_ = '{A927B116-A485-479B-9084-EA59E99C8818}' _reg_progid_ = 'Doubletalk.BookServer' _public_methods_ = ['double'] def __init__(self): self.__BookSet = doubletalk.bookset.Bookset() def double(self,arg): #trivial test function to check that it's alive return arg * 2 if __name__ == '__main__': win32com.server.register.UseCommandLine(COMBookSet) (from Interactive Window) >>> # getting a GUID for the server >>> import pythoncom # getting a guid for the server >>> print pythoncom.CreateGuid() {A927B116-A485-479B-9084-EA59E99C8818} >>> >>> # next I run the script listed above >>> Traceback (most recent call last): File "C:\Python20\Pythonwin\pywin\framework\scriptutils.py", line 301, in RunScript exec codeObject in __main__.__dict__ File "C:\Python20\win32\MyPythonScripts\comservers.py", line 14, in ? win32com.server.register.UseCommandLine(COMBookSet) NameError: There is no variable named 'win32com' Traceback (most recent call last): File "C:\Python20\Pythonwin\pywin\framework\scriptutils.py", line 301, in RunScript exec codeObject in __main__.__dict__ File "C:\Python20\win32\MyPythonScripts\comservers.py", line 15, in ? AttributeError: server >>> Indeed, the server does not get registered. I looked at the object browser and located win32com.server.register.UserCommandLine, but it doesn't seem to be located by Python. Any assistance in this matter is greatly appreciated. Sincerely, Roger Mallett From dsh8290@rit.edu Thu Jan 4 01:16:59 2001 From: dsh8290@rit.edu (D-Man) Date: Wed, 3 Jan 2001 20:16:59 -0500 Subject: [Tutor] setting object to None doesn't kill Word In-Reply-To: <78D9B26221DBD411B7EE00D0B73EB0EA06730E@cupex2.rational.com>; from rmallett@rational.com on Wed, Jan 03, 2001 at 05:02:48PM -0800 References: <78D9B26221DBD411B7EE00D0B73EB0EA06730E@cupex2.rational.com> Message-ID: <20010103201659.B7834@westsidecnc.rh.rit.edu> I recall someone on the list mentioning having some problems with COM and python. Check the archives. I think that the COM objects had some sort of close function that should be used before removing the reference. HTH, -D On Wed, Jan 03, 2001 at 05:02:48PM -0800, Mallett, Roger wrote: > System: Windows 2000, Office 2000 > > I am on page 67-68 of Mark Hammond's book "Python Programming on Win32" and > I can't seem to kill Word by setting the object to None. From dyoo@hkn.eecs.berkeley.edu Thu Jan 4 02:12:41 2001 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Wed, 3 Jan 2001 18:12:41 -0800 (PST) Subject: [Tutor] when string,join won't work In-Reply-To: Message-ID: > > Make them strings: > > > > string.join(map(str, sequence)) > > > > Read about ``map'' and ``str'' at your friendly neighbourhood library > > reference guide. (http://www.python.org/doc/) > > yeah, I was just hoping there was a better way. > > one of the reason to use a scripting language is to get away from: > > string foo; > > foo = 'hello'; > > kind of code. Python requiring me to know that the sequence is 100% > strings is kind of silly in my book. True, but it's not so bad if you write a function that does the string conversion implicitely: ### def myStrJoin(L): return string.join(map(str, L)) ### is a one shot thing, so it's not too bad. If something doesn't work, make it work. *grin* From dyoo@hkn.eecs.berkeley.edu Thu Jan 4 02:23:08 2001 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Wed, 3 Jan 2001 18:23:08 -0800 (PST) Subject: [Tutor] TK?? Creating exe extentions... In-Reply-To: <000801c07600$f3ac3240$cfb4accf@k0g4f0> Message-ID: On Wed, 3 Jan 2001, Brad C. wrote: > Hello agian. I'm back with probably a simple question. What is TK? > WHat can it be used for? What is it used for, if anything? Also, how > would I create an exe file extencion instead of .py?Thanks for the > help. Happy New Year! You'll hear a bit about Tk/Tcl when you make graphical-based programs. Tk is a graphical interface language --- buttonbars, windows, labels, images --- and Python lets you use Tk to build fancy graphical interfaces through the Tkinter module. One nice example of Tkinter stuff is with PySol, the Python solitare game: http://pysol.tsx.org Anyway, if you're interested in it, there's a topic guide about Tkinter here: http://python.org/topics/tkinter/ About the .exe thing: you can build .exe's by bundling the interpreter along with your .py file. There's a utility by Gordon McMillian that does this: http://www.mcmillan-inc.com/install1.html There are a few people on tutor that have successfully worked with it, so if you have any questions, it can't hurt to ask us. *grin* From dpm@softdesigns.com Thu Jan 4 06:29:31 2001 From: dpm@softdesigns.com (David Metzler) Date: Wed, 3 Jan 2001 22:29:31 -0800 Subject: [Tutor] Windows, mysql python Message-ID: <004101c07617$b9172100$0501a8c0@softdesigns.com> This is a multi-part message in MIME format. ------=_NextPart_000_0038_01C075D4.A480E0C0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable I found the following archive MySQL-python-0.3.0-win32-2.zip on = http://home.t-online.de/home/err666/ My goal is to get mysql support into my windows Python 2.0 and connect = to a remote Linux server running the most current Mysql . I have installed the windows version of python 2.0 I put c:\python in my windows path C:\ >Cd \pymysql (this is where I unzipped the above archive) C:\pymysql> Python setup.py I get an error about distutils.core not being available. Could you tell me how to get distutils and make it available? The source of install.py implies that I have mysql loaded on the windows = machine and is linking against it. I want connect to the mysql on a = remote linux box perhaps on another network (but both computers are = connected via the internet). Can I make this work? How? The install.py in the above archive starts like this: #!/usr/bin/env python =20 """Setup script for the MySQLdb module distribution.""" =20 import os, sys from distutils.core import setup from distutils.extension import Extension =20 YES =3D 1 NO =3D 0 =20 # set this to 1 if you have the thread-safe mysqlclient library thread_safe_library =3D NO =20 # You probably don't have to do anything past this point. If you # do, please mail me the configuration for your platform. Don't # forget to include the value of sys.platform and os.name. =20 mysqlclient =3D thread_safe_library and "mysqlclient_r" or "mysqlclient" =20 if sys.platform =3D=3D "linux-i386": # Red Hat include_dirs =3D ['/usr/include/mysql'] library_dirs =3D ['/usr/lib/mysql'] libraries =3D [mysqlclient, "z"] runtime_library_dirs =3D [] extra_objects =3D [] elif sys.platform =3D=3D "win32": include_dirs =3D [r'd:\MySQL\include'] library_dirs =3D [r'd:\MySQL\lib\opt'] libraries =3D [mysqlclient, 'zlib', 'msvcrt', 'libcmt', 'wsock32', 'advapi32'] runtime_library_dirs =3D [] extra_objects =3D [r'd:\MySQL\lib\opt\mysqlclient.lib'] elif os.name =3D=3D "posix": # most Linux/UNIX platforms include_dirs =3D ['/usr/include/mysql'] library_dirs =3D ['/usr/lib/mysql'] # MySQL-3.23 seems to need libz libraries =3D [mysqlclient, "z"] # On some platorms, this can be used to find the shared libraries # at runtime, if they are in a non-standard location. Doesn't # work for Linux gcc. ## runtime_library_dirs =3D library_dirs runtime_library_dirs =3D [] # This can be used on Linux to force use of static mysqlclient lib ## extra_objects =3D ['/usr/lib/mysql/libmysqlclient.a'] extra_objects =3D [] else: raise "UnknownPlatform", "sys.platform=3D%s, os.name=3D%s" % \ (sys.platform, os.name) =20 =20 ------=_NextPart_000_0038_01C075D4.A480E0C0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
I found the following archive=20 MySQL-python-0.3.0-win32-2.zip on http://home.t-online.de/home/err666/

 My goal is to get mysql support into my = windows Python=20 2.0 and connect to a remote Linux server running the most current Mysql = .

I have installed the windows version of python = 2.0

I put c:\python in my windows path

C:\ >Cd \pymysql =20 (this is where I unzipped the above archive)

C:\pymysql> Python setup.py

 I get an error about distutils.core not being = available.

 Could you tell me how to get distutils and = make it=20 available?

The=20 source of install.py implies that I have mysql loaded on the windows = machine and=20 is linking against it. I want connect to the mysql on a remote linux box = perhaps=20 on another network (but both computers are connected via the internet). = Can I=20 make this work? How?

The install.py in the above archive starts like = this:

#!/usr/bin/env=20 python

 

"""Setup script for the = MySQLdb=20 module distribution."""

 

import=20 os, sys

from=20 distutils.core import setup

from=20 distutils.extension import Extension

 

YES =3D=20 1

NO =3D=20 0

 

# set=20 this to 1 if you have the thread-safe mysqlclient = library

thread_safe_library =3D=20 NO

 

# You=20 probably don't have to do anything past this point. If = you

# do,=20 please mail me the configuration for your platform. = Don't

#=20 forget to include the value of sys.platform and = os.name.

 

mysqlclient =3D = thread_safe_library=20 and "mysqlclient_r" or "mysqlclient"

 

if=20 sys.platform =3D=3D "linux-i386": # Red Hat

    include_dirs =3D=20 ['/usr/include/mysql']

    library_dirs =3D=20 ['/usr/lib/mysql']

    libraries =3D = [mysqlclient,=20 "z"]

    = runtime_library_dirs =3D=20 []

    extra_objects =3D=20 []

elif=20 sys.platform =3D=3D "win32":

    include_dirs =3D=20 [r'd:\MySQL\include']

    library_dirs =3D=20 [r'd:\MySQL\lib\opt']

    libraries =3D = [mysqlclient,=20 'zlib', 'msvcrt', 'libcmt',

           &n= bsp;    =20 'wsock32', 'advapi32']

    = runtime_library_dirs =3D=20 []

    extra_objects =3D=20 [r'd:\MySQL\lib\opt\mysqlclient.lib']

elif=20 os.name =3D=3D "posix": # most Linux/UNIX = platforms

    include_dirs =3D=20 ['/usr/include/mysql']

    library_dirs =3D=20 ['/usr/lib/mysql']

    # MySQL-3.23 seems = to need=20 libz

    libraries =3D = [mysqlclient,=20 "z"]

    # On some = platorms, this can=20 be used to find the shared libraries

    # at runtime, if = they are in=20 a non-standard location. Doesn't

    # work for Linux=20 gcc.

    ## = runtime_library_dirs =3D=20 library_dirs

    = runtime_library_dirs =3D=20 []

    # This can be used = on Linux=20 to force use of static mysqlclient lib

    ## extra_objects = =3D=20 ['/usr/lib/mysql/libmysqlclient.a']

    extra_objects =3D=20 []

else:

    raise = "UnknownPlatform",=20 "sys.platform=3D%s, os.name=3D%s" % \

         =20 (sys.platform, os.name)

 

 

------=_NextPart_000_0038_01C075D4.A480E0C0-- From brett42@flex.com Thu Jan 4 04:14:18 2001 From: brett42@flex.com (Brett) Date: Wed, 03 Jan 2001 18:14:18 -1000 Subject: [Tutor] how to tell if strings have numbers in them Message-ID: <4.3.2.7.0.20010103181049.00ac3d40@mail.flex.com> I'm trying to get input and checking to see if it's a number. x==int(x) works if it is a number, but causes an error if you input a string. I made a list of 0-9 and tried for z in x/if z in list, and that seems to work, but its takes a lot of typing, is there an existing function that can check to see if a variable is a number? When Schrodinger's cat's away, the mice may or may not play, no one can tell. From dyoo@hkn.eecs.berkeley.edu Thu Jan 4 04:15:17 2001 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Wed, 3 Jan 2001 20:15:17 -0800 (PST) Subject: [Tutor] 'Name Genereator' Question In-Reply-To: Message-ID: On Wed, 3 Jan 2001, Curtis Larsen wrote: > I'm writing a quickie little script that generates names, to better > understand string manipulation. What I'd like to have is something like > "map" that can be used against a number of occurrences of a character in > a string and replace it -- without using a lot of loops. Here are small things that might improve your program: The whrandom module has a function called "choice()" which lets you grab at a random element out of a list. So, instead of: cons[random.randint(0,21)] you could use: whrandom.choice(cons) which is a bit nicer to read. whrandom.choice() works on strings as well as lists, so its a nice function. > The kicker (to me) is how to call "randint" for each character > replacement target in "name". The easy way would be to "while" loop for > "'.' in name", etc., or I could create a function to do the replacement > and call it each time, but I thought there would be a more > straightforward answer. (I'm probably missing something really, really > simple here, right??) Creating a function that does the replacement would be nice. Here's something: ### def replaceStuff(str): # Let's first make str a mutable list. # The reason for this is because we can modify a # list "in-place". templist = list(str) # Time for the replacement stuff for i in range(len(templist)): if templist[i] == '.": templist[i] = whrandom.choice(vowels) # skipping consonant stuff # finally, bring the list back as a string: return string.join(templist, "") ### So the loop goes through each character on your list, but you only do something if that character is a '.' or a ','. I haven't tested the code above yet, but I hope that it makes sense. From dyoo@hkn.eecs.berkeley.edu Thu Jan 4 04:22:14 2001 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Wed, 3 Jan 2001 20:22:14 -0800 (PST) Subject: [Tutor] 'Name Genereator' Question In-Reply-To: Message-ID: > The kicker (to me) is how to call "randint" for each character > replacement target in "name". The easy way would be to "while" loop for > "'.' in name", etc., or I could create a function to do the replacement > and call it each time, but I thought there would be a more > straightforward answer. (I'm probably missing something really, really > simple here, right??) Wait! Yes, on a second thought, you _can_ do a map() on a string --- but you need to first convert it to a list. So you could write a character-replacing function (let's call it replaceChar()), and then do this: ### def replaceString(str): result = map(replaceChar, list(str)) return string.join(result, "") ### where replaceChar() looks like: ### def replaceChar(ch): if ch == '.': return whrandom.choice(consonants) elif ch == ',': return whrandom.choice(vowels) else: return ch ### And that would be a much nicer solution, I think. Hope this helps! From dyoo@hkn.eecs.berkeley.edu Thu Jan 4 04:44:33 2001 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Wed, 3 Jan 2001 20:44:33 -0800 (PST) Subject: [Tutor] how to tell if strings have numbers in them In-Reply-To: <4.3.2.7.0.20010103181049.00ac3d40@mail.flex.com> Message-ID: On Wed, 3 Jan 2001, Brett wrote: > I'm trying to get input and checking to see if it's a number. x==int(x) > works if it is a number, but causes an error if you input a string. I made > a list of 0-9 and tried for z in x/if z in list, and that seems to work, > but its takes a lot of typing, is there an existing function that can check > to see if a variable is a number? Hmmm... let's take a look: ### >>> int("42") 42 >>> int("forty-two") Traceback (innermost last): File "", line 1, in ? ValueError: invalid literal for int(): forty-two ### I see, so it throws a ValueError if something goes wrong in the conversion. I can't think of a built-in isNumber() function that checks if something is a number. However, there are several nice ways of writing one. Here's one: ### def isNumber(x): try: int(x) except: return 0 return 1 ### and it seems to work pretty well: ### >>> isNumber("forty-two") 0 >>> isNumber("42") 1 >>> isNumber(42) 1 ### This version of isNumber() depends on the fact that bad things will cause exceptions: that's where isNumber() returns zero. Otherwise, isNumber() will be happy and return one. You might not be familiar with try/except. It's mentioned a little bit in the official tutorial here: http://python.org/doc/current/tut/node10.html Hope this helps! From dsh8290@rit.edu Thu Jan 4 04:48:36 2001 From: dsh8290@rit.edu (D-Man) Date: Wed, 3 Jan 2001 23:48:36 -0500 Subject: [Tutor] how to tell if strings have numbers in them In-Reply-To: <4.3.2.7.0.20010103181049.00ac3d40@mail.flex.com>; from brett42@flex.com on Wed, Jan 03, 2001 at 06:14:18PM -1000 References: <4.3.2.7.0.20010103181049.00ac3d40@mail.flex.com> Message-ID: <20010103234836.A3050@westsidecnc.rh.rit.edu> >>> str = "234" >>> str.isdigit() 1 >>> str2 = "asdf" >>> str2.isdigit() 0 >>> -D On Wed, Jan 03, 2001 at 06:14:18PM -1000, Brett wrote: > I'm trying to get input and checking to see if it's a number. From tutor@python.org Thu Jan 4 04:58:24 2001 From: tutor@python.org (Tim Peters) Date: Wed, 3 Jan 2001 23:58:24 -0500 Subject: [Tutor] 'Name Genereator' Question In-Reply-To: Message-ID: [Daniel Yoo] > Wait! Yes, on a second thought, you _can_ do a map() on a > string --- but you need to first convert it to a list. So you could > write a character-replacing function (let's call it replaceChar()), > and then do this: Actually, a string is one of Python's sequence types (and, for example, lists and tuples are also sequences), and map works on any sequence: >>> map(ord, "ABC") [65, 66, 67] >>> map(chr, _) ['A', 'B', 'C'] >>> So: > ### > def replaceString(str): > result = map(replaceChar, list(str)) ^^^^^ ^ you really don't need the list() function there. But it's OK to use it if you want to . From moshez@zadka.site.co.il Thu Jan 4 17:08:50 2001 From: moshez@zadka.site.co.il (Moshe Zadka) Date: Thu, 4 Jan 2001 19:08:50 +0200 (IST) Subject: [Tutor] when string,join won't work In-Reply-To: References: Message-ID: <20010104170850.19936A84F@darjeeling.zadka.site.co.il> On Wed, 03 Jan 2001, "Sean 'Shaleh' Perry" wrote: > one of the reason to use a scripting language is to get away from: It's not PC to call Python a scripting language. "High-level interpreted language" is the common description. I'm only pointing that out because I think you're mixed up about what Python *is*, as well as what Python is *called*. > string foo; > > foo = 'hello'; > > kind of code. Python requiring me to know that the sequence is 100% strings is > kind of silly in my book. But it doesn't: ``str'' works on any type (almost). Python is strongly typed: you can't treat a number as a string, or vice versa. I can't begin to explain how many times it caused potentially yucky bugs into obvious ones. It is, however, polymorphic to extremes, which is why map(str, seq) works always: you don't need to promise what types are in seq. Explicit is Better then Implicit is one of the Python rules of living. Python will stay explicit, so whether you think it's silly or not, this is an essential feature, not a quirk. -- Moshe Zadka This is a signature anti-virus. Please stop the spread of signature viruses! From moshez@zadka.site.co.il Thu Jan 4 17:20:26 2001 From: moshez@zadka.site.co.il (Moshe Zadka) Date: Thu, 4 Jan 2001 19:20:26 +0200 (IST) Subject: [Tutor] how to tell if strings have numbers in them In-Reply-To: <4.3.2.7.0.20010103181049.00ac3d40@mail.flex.com> References: <4.3.2.7.0.20010103181049.00ac3d40@mail.flex.com> Message-ID: <20010104172026.C47DEA84F@darjeeling.zadka.site.co.il> On Wed, 03 Jan 2001 18:14:18 -1000, Brett wrote: > I'm trying to get input and checking to see if it's a number. x==int(x) > works if it is a number, but causes an error if you input a string. I made > a list of 0-9 and tried for z in x/if z in list, and that seems to work, > but its takes a lot of typing, is there an existing function that can check > to see if a variable is a number? I usually use: import re is_integer = re.compile('[0-9]+').match I'm not sure what you mean by a number (float? scientific notation? negative?) -- Moshe Zadka This is a signature anti-virus. Please stop the spread of signature viruses! From deirdre@deirdre.net Thu Jan 4 09:06:17 2001 From: deirdre@deirdre.net (Deirdre Saoirse) Date: Thu, 4 Jan 2001 01:06:17 -0800 (PST) Subject: [Tutor] when string,join won't work In-Reply-To: <20010104170850.19936A84F@darjeeling.zadka.site.co.il> Message-ID: On Thu, 4 Jan 2001, Moshe Zadka wrote: > On Wed, 03 Jan 2001, "Sean 'Shaleh' Perry" wrote: > > > one of the reason to use a scripting language is to get away from: > > It's not PC to call Python a scripting language. "High-level > interpreted language" is the common description. I'm only pointing > that out because I think you're mixed up about what Python *is*, as > well as what Python is *called*. Sean's pretty cool though, helps out a lot here. Still, calling Python a scripting language IS one of the ways of getting the Glare Of Doom from Guido. :) -- _Deirdre * http://www.sfknit.org * http://www.deirdre.net "We have an open door policy." -- Sheridan "And an open airlock policy." -- Ivanova From emack@glade.net Thu Jan 4 10:32:18 2001 From: emack@glade.net (emack) Date: Thu, 4 Jan 2001 04:32:18 -0600 Subject: [Tutor] when string,join won't work References: <20010104170850.19936A84F@darjeeling.zadka.site.co.il> Message-ID: <00f501c07639$9e04c4e0$ac1f5d3f@oemcomputer> I don't know what "scripting" *really* means. There seem to be various ideas about its meaning. I programmed in ASM, SAP [old IBM704], SDS metasymbol, fortran, jovial, cssl, pdp mach., etc., [not to mention analog computers], for almost 30 years and the term scripting never came up. But search engines now often associate scripting with with Python as well as Java, Perl, PHP, .... Of course these terms never came up either when I was a programmer. Neither did "object oriented language" and seldom UNIX. I'm amazed that we got the Apollo off the ground! I worry that you guys apparently haven't come up with a consensus. ----- Original Message ----- From: "Moshe Zadka" To: "Sean 'Shaleh' Perry" Cc: Sent: Thursday, January 04, 2001 11:08 AM Subject: Re: [Tutor] when string,join won't work > On Wed, 03 Jan 2001, "Sean 'Shaleh' Perry" wrote: > > > one of the reason to use a scripting language is to get away from: > > It's not PC to call Python a scripting language. "High-level interpreted > language" is the common description. > I'm only pointing that out because I think you're mixed up about what > Python *is*, as well as what Python is *called*. > From rob@jam.rr.com Thu Jan 4 12:58:02 2001 From: rob@jam.rr.com (R. A.) Date: Thu, 04 Jan 2001 06:58:02 -0600 Subject: [Tutor] Where to find example source codes. References: <00123121220400.01627@localhost.localdomain> <20001231100159.C577@nomad.n0nb.ampr.org> Message-ID: <3A54735A.44B562FC@jam.rr.com> I'd be glad to volunteer the server space. The Tutor Archives are a great resource, of course, but if anyone would like to work on a new angle of some kind, don't let lack of server space slow ya down. Rob A. Nate Bargmann wrote: > > On Sun, Dec 31, 2000 at 09:01:43PM +1100, John Murray wrote: > > > It is said that the best way of learning a programing language > > > is that you read some example souces and write some by your own. > > > > This reminds me of something I've been thinking about for a while, ie; should > > we be making our individual python project's code available to each other? > > There must be quite a few scripts in various stages of completion spread > > throughout the tutor subscribers. As a newbie (to programming as well as > > python), I would normally be embarrassed about releasing my hideously amateurish > > code, though I would have no problems sharing it with other list members. Ugly > > as my code may be, some of it has actually proven to be useful, so surely others > > here have written useful stuff as well. Making projects available to each other > > would give those without a project something to get into, and who knows, some > > stuff might get developed to the point of public release. What do you think? > > Sorry to sound like an open source evangelist........... > > Happy New Year > > Johnno > > Hi John and all. > > I think this would be an excellent idea. Perhaps there could be some > space made available at Python.org (I wouldn't know firsthand). One > thing I've found, is that in the process of learning anything there is a > certain amount of "re-inventing the wheel" that happens. However, the > list archives to the Tutor List contain a number of code snippets and > good examples posted in response to questions asked. > > Perhaps some kind of "How do I...?" web page that collates these > snippets would be of some value. I'm sure there are beginners as myself > who have no formal computer science training (and our algebra is > lackinga bit as well) find trying to work out some algorithm to seem > like a tough task. Fortunately, I have garnered many clues by lurking > on this list and have saved a number of messages for quick reference. > > More food for thought. > > - Nate >> > > -- > Wireless | Amateur Radio Station N0NB | "None can love freedom > Internet | n0nb@networksplus.net | heartily, but good > Location | Wichita, Kansas USA EM17hs | men; the rest love not > Wichita area exams; ham radio; Linux info @ | freedom, but license." > http://www.qsl.net/n0nb/ | -- John Milton > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://www.python.org/mailman/listinfo/tutor -- Mississippi Python Interest Group http://www.lowerstandard.com/python/mspiggie From alan.gauld@bt.com Thu Jan 4 17:39:18 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Thu, 4 Jan 2001 17:39:18 -0000 Subject: [Tutor] how to tell if strings have numbers in them Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D4AA@mbtlipnt02.btlabs.bt.co.uk> > a list of 0-9 and tried for z in x/if z in list, and that > seems to work, but its takes a lot of typing, is there > an existing function import string if x in string.digits: # do it here Alan g From scarblac@pino.selwerd.nl Thu Jan 4 18:15:00 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Thu, 4 Jan 2001 19:15:00 +0100 Subject: [Tutor] how to tell if strings have numbers in them In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20751D4AA@mbtlipnt02.btlabs.bt.co.uk>; from alan.gauld@bt.com on Thu, Jan 04, 2001 at 05:39:18PM -0000 References: <5104D4DBC598D211B5FE0000F8FE7EB20751D4AA@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <20010104191500.A29924@pino.selwerd.nl> On Thu, Jan 04, 2001 at 05:39:18PM -0000, alan.gauld@bt.com wrote: > > a list of 0-9 and tried for z in x/if z in list, and that > > seems to work, but its takes a lot of typing, is there > > an existing function > > import string > if x in string.digits: > # do it here Someone else already posted this, but not many people seem aware of it. (I know I wasn't). In Python 2.0, strings have the useful isdigit() method, that tests if all characters in the strings are digits: >>> x="123" >>> x.isdigit() 1 >>> x="123a" >>> x.isdigit() 0 Nifty. There are several more methods as well, see dir(x) and their docstrings. -- Remco Gerlich From deirdre@deirdre.net Thu Jan 4 18:32:28 2001 From: deirdre@deirdre.net (Deirdre Saoirse) Date: Thu, 4 Jan 2001 10:32:28 -0800 (PST) Subject: [Tutor] how to tell if strings have numbers in them In-Reply-To: <20010104191500.A29924@pino.selwerd.nl> Message-ID: On Thu, 4 Jan 2001, Remco Gerlich wrote: > Someone else already posted this, but not many people seem aware of > it. (I know I wasn't). In Python 2.0, strings have the useful > isdigit() method, that tests if all characters in the strings are > digits: Actually, it's also in 1.6. I don't remember quite when it was introduced. Under 1.6, dir(x) gives: ['capitalize', 'center', 'count', 'endswith', 'expandtabs', 'find', 'index', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'replace', 'rfind', 'rindex', 'rjust', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper'] > >>> x="123" > >>> x.isdigit() > 1 -- _Deirdre * http://www.sfknit.org * http://www.deirdre.net "We have an open door policy." -- Sheridan "And an open airlock policy." -- Ivanova From deirdre@deirdre.net Thu Jan 4 19:59:25 2001 From: deirdre@deirdre.net (Deirdre Saoirse) Date: Thu, 4 Jan 2001 11:59:25 -0800 (PST) Subject: [Tutor] when string,join won't work In-Reply-To: <00f501c07639$9e04c4e0$ac1f5d3f@oemcomputer> Message-ID: On Thu, 4 Jan 2001, emack wrote: > I don't know what "scripting" *really* means. There seem to be > various ideas about its meaning. I programmed in ASM, SAP [old > IBM704], SDS metasymbol, fortran, jovial, cssl, pdp mach., etc., [not > to mention analog computers], for almost 30 years and the term > scripting never came up. But search engines now often associate > scripting with with Python as well as Java, Perl, PHP, .... Of course > these terms never came up either when I was a programmer. Neither did > "object oriented language" and seldom UNIX. I'm amazed that we got > the Apollo off the ground! I worry that you guys apparently haven't > come up with a consensus. Oh, there's a consensus. :) You *can* write scripts with Python, but it's not a scripting language. For the same reasons, Java's not a scripting language. Both are high-level, interpreted, object-oriented languages. Scripting languages include: any shell (bash, tcsh, ksh), awk, sed, and perl (which is really awk on steroids). PHP really started as a set of add-ons for perl, but I find it much more C-like than Perl-like. Still, its intent is as a scripting language; when trying to use it for more general problems, I've always been frustrated enough that I started over in Python. -- _Deirdre * http://www.sfknit.org * http://www.deirdre.net "We have an open door policy." -- Sheridan "And an open airlock policy." -- Ivanova From tim.one@home.com Fri Jan 5 04:11:21 2001 From: tim.one@home.com (Tim Peters) Date: Thu, 4 Jan 2001 23:11:21 -0500 Subject: [Tutor] when string,join won't work In-Reply-To: <20010104170850.19936A84F@darjeeling.zadka.site.co.il> Message-ID: [Moshe Zadka] > ... > But it doesn't: ``str'' works on any type (almost). Python is > strongly typed: you can't treat a number as a string, or vice > versa. I can't begin to explain how many times it caused > potentially yucky bugs into obvious ones. It is, however, > polymorphic to extremes, which is why map(str, seq) > works always: you don't need to promise what types are in seq. > > Explicit is Better then Implicit is one of the Python rules of > living. Python will stay explicit, so whether you think it's > silly or not, this is an essential feature, not a quirk. In the specific case of string.join, though, it is indeed pointless to make the user explicitly convert everything to a string themself. While errors about mixing strings with (for example) integers in arithmetic catches *many* genuine bugs in code that (for example) Perl lets pass silently, I've never seen string.join griping about a non-string sequence element catch a *logic* error. Of *course* the user wants everything converted to a string, else they wouldn't have called string.join to begin with! The failure to convert all the sequence elements to strings first by hand is simply a failure to comply with an anal implementation restriction. IOW, in every case I've seen where string.join raised this error, the fix was *invariably* to do the map(str, seq) business by hand first: the problem was never deeper than that. The same isn't true of, e.g., griping about "4" + 2 (6 or "42" intended?). But there's no ambiguity about what the user intends when they call string.join(["4", 2]): they've already been explicit about their intent. if-i-ask-for-a-string-i-shouldn't-be-surprised-if-i-get-a-string-ly y'rs - tim From tescoil@irtc.net Fri Jan 5 05:18:51 2001 From: tescoil@irtc.net (Tesla Coil) Date: Thu, 04 Jan 2001 23:18:51 -0600 Subject: [Tutor] Where to find example source codes. References: <00123121220400.01627@localhost.localdomain> Message-ID: <3A55593B.50FE3D77@irtc.net> On 31 Dec 2000, John Murray wrote: > This reminds me of something I've been thinking about for > a while, ie; should we be making our individual python project's > code available to each other? There must be quite a few scripts > in various stages of completion spread throughout the tutor > subscribers. As a newbie (to programming as well as python), > I would normally be embarrassed about releasing my hideously > amateurish code, though I would have no problems sharing it > with other list members. Ugly as my code may be, some of it > has actually proven to be useful, so surely others here have > written useful stuff as well. I've often thought an Interesting list would have posts of Python source as its topic. What typically motivates an initial post of source to the Tutor list is that the author finds it to be deficient. What's lost are the one-shot scripts you've knocked off, maybe with little alteration of repeated use to someone else, not deemed important enough to publish on your web page, and no one expects to find it scattered off on your URL anyway. And perhaps utility wasn't even the point. Perhaps you had in mind a clever function to reduce the iterations in calculating a large factorial. A nice conversation piece, provided an audience who might appreciate that your only interest in the usual method would be comparing the performance of this approach. You could post it to comp.lang.python, but again, too unimportant to bother distracting anyone from the latest debate on whether this or that fundamental aspect of the language is a Good Thing. Ideally, the list topic would be *unimportant* Python source. I'd be compelled to subscribe to that one. > Sorry to sound like an open source evangelist........... Beats listening to a closed source evangelist... From dpm@softdesigns.com Fri Jan 5 08:01:51 2001 From: dpm@softdesigns.com (David Metzler) Date: Fri, 5 Jan 2001 00:01:51 -0800 Subject: [Tutor] Web programming not using zope Message-ID: <002d01c076ed$c3b63980$0501a8c0@softdesigns.com> This is a multi-part message in MIME format. ------=_NextPart_000_002A_01C076AA.B5051160 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable One of the programmers I work with uses PHP4 and apache a great deal. = I'm interested in using Python especially the apache py module. I have not been able to find any tutorials or sample code that = demonstrates this environment. What are the advantages and disadvantages = to using Python as a PHP replacement? Is their any docs for this? ------=_NextPart_000_002A_01C076AA.B5051160 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
One of the programmers I work with uses = PHP4 and=20 apache a great deal. I'm interested in using Python especially the = apache py=20 module.
I have not been able to find any = tutorials or=20 sample code that demonstrates this environment. What are the advantages = and=20 disadvantages to using Python as a PHP replacement? Is their any docs = for=20 this?
 
------=_NextPart_000_002A_01C076AA.B5051160-- From tim.one@home.com Fri Jan 5 06:50:45 2001 From: tim.one@home.com (Tim Peters) Date: Fri, 5 Jan 2001 01:50:45 -0500 Subject: [Tutor] how to tell if strings have numbers in them In-Reply-To: Message-ID: [Deirdre Saoirse] > Actually, it's [string.isdigit()] also in 1.6. I don't remember > quite when it was introduced. These things (.isdigit(), .isspace(), istitle(), etc) came along with Unicode support, and indeed for the first time in 1.6. Answering "is this is a digit?" is a lot harder in Unicode! So Python does it for you. The same methods were added to regular (8-bit) strings at the same time, for uniformity. although-they-may-get-used-more-on-8-bit-strings-in-the-end-ly y'rs - tim From moshez@zadka.site.co.il Sat Jan 6 02:28:07 2001 From: moshez@zadka.site.co.il (Moshe Zadka) Date: Sat, 6 Jan 2001 04:28:07 +0200 (IST) Subject: [Tutor] when string,join won't work In-Reply-To: References: Message-ID: <20010106022807.BA19CA84F@darjeeling.zadka.site.co.il> On Thu, 4 Jan 2001, "Tim Peters" wrote: > In the specific case of string.join, though, it is indeed pointless to make > the user explicitly convert everything to a string themself. While errors > about mixing strings with (for example) integers in arithmetic catches > *many* genuine bugs in code that (for example) Perl lets pass silently, I've > never seen string.join griping about a non-string sequence element catch a > *logic* error. Of *course* the user wants everything converted to a string, > else they wouldn't have called string.join to begin with! Well, that may be so in the old world. In the new world, when the user is calling string.join(l, sep) he's *really* calling sep.join(l). If sep is Unicode, it should convert to unicode (unicode()?). The semantics seem weird... -- Moshe Zadka This is a signature anti-virus. Please stop the spread of signature viruses! From michaelbaker@operamail.com Fri Jan 5 20:21:53 2001 From: michaelbaker@operamail.com (michaelbaker@operamail.com) Date: Fri, 05 Jan 2001 12:21:53 -0800 Subject: [Tutor] multiple list creation In-Reply-To: <20010105170129.977F3E9C1@mail.python.org> Message-ID: <4.3.2.7.1.20010105120529.00b993c0@operamail.com> I wonder how to create an empty list with a unique name for each item in a sequence?? >>>a=['one','two','three'] >>>for b in a: b+'buffer'=[] SyntaxError: can't assign to operator (line 2) this isn't it either: >>>def listmaker(x): y=[] return y >>>for b in a: listmaker(b) [] [] [] surely I'm missing something simple?? thanks, m baker From arcege@shore.net Fri Jan 5 20:35:36 2001 From: arcege@shore.net (Michael P. Reilly) Date: Fri, 5 Jan 2001 15:35:36 -0500 (EST) Subject: [Tutor] multiple list creation In-Reply-To: <4.3.2.7.1.20010105120529.00b993c0@operamail.com> from "michaelbaker@operamail.com" at Jan 05, 2001 12:21:53 PM Message-ID: <200101052035.PAA19585@northshore.shore.net> > I wonder how to create an empty list with a unique name for each item in a > sequence?? > > >>>a=['one','two','three'] > >>>for b in a: > b+'buffer'=[] If you want to put these as global variables in a specific module, say __main__, then you can use setattr to assigh a new variable. >>> import __main__ # we may be in the __main__ module, but we need the >>> # the reference to the module here; we could use the ... # name of any mdoule we wished here really ... >>> a = [ 'one' ,'two', 'three' ] >>> dir(__main__) ['__builtins__', '__doc__', '__main__', '__name__', 'a'] >>> for b in a: ... setattr(__main__, '%sbuffer' % b, []) ... >>> dir() ['__builtins__', '__doc__', '__main__', '__name__', 'a', 'b', 'onebuffer', 'threebuffer', 'twobuffer'] >>> But more generally, try using the "exec" statement which takes a string an executes it as a Python statement: >>> a = [ 'one', 'two', 'three' ] >>> dir() ['__builtins__', '__doc__', '__name__', 'a'] >>> for b in a: ... exec '%sbuffer = []' % b ... >>> dir() ['__builtins__', '__doc__', '__name__', 'a', 'b', 'onebuffer', 'threebuffer', 'twobuffer'] >>> The value of using exec instead of "import __main__; setattr(__main__, ...)" is that exec will create the variables in the proper current namespace (local, global). You cannot use eval() because the assignment is a statement, eval works only with expressions. Enjoy, -Arcege -- ------------------------------------------------------------------------ | Michael P. Reilly, Release Manager | Email: arcege@shore.net | | Salem, Mass. USA 01970 | | ------------------------------------------------------------------------ From pursang@interact.net.au Fri Jan 5 22:50:27 2001 From: pursang@interact.net.au (John Murray) Date: Sat, 6 Jan 2001 09:50:27 +1100 Subject: [Tutor] Re: Example source code.. Message-ID: <01010612405300.00619@localhost.localdomain> Tesla Coil wrote: >I've often thought an Interesting list would have posts of Python >source as its topic. What typically motivates an initial post of >source to the Tutor list is that the author finds it to be deficient. >What's lost are the one-shot scripts you've knocked off, maybe >with little alteration of repeated use to someone else, not deemed >important enough to publish on your web page, and no one expects >to find it scattered off on your URL anyway. > >And perhaps utility wasn't even the point. Perhaps you had in >mind a clever function to reduce the iterations in calculating a >large factorial. A nice conversation piece, provided an audience >who might appreciate that your only interest in the usual method >would be comparing the performance of this approach. > >You could post it to comp.lang.python, but again, too unimportant >to bother distracting anyone from the latest debate on whether >this or that fundamental aspect of the language is a Good Thing. > >Ideally, the list topic would be *unimportant* Python source. >I'd be compelled to subscribe to that one. Nicely put. I'd like to see something like this, perhaps we could take up Rob.A's kind offer of server space (I think using SourceForge might be overkill?). All we would need is a simple web page with links to the various scripts. Tutor list members could post their code with a name and brief description; author names would be optional for the anon. cowards:-) Periodically (every fortnight?), the site address and any new additions could be posted in a brief tutor-list message. Would we set it up so that list members can ftp their files directly to the site? Or would it be better to have them sent to the site's maintainer, who would then list them on the download page? I'd be happy to help in any way I can. Cheers, Johnno From rob@jam.rr.com Sat Jan 6 03:36:19 2001 From: rob@jam.rr.com (R. A.) Date: Fri, 05 Jan 2001 21:36:19 -0600 Subject: [Tutor] Re: Example source code.. Message-ID: <3A5692B3.89F4A5FF@jam.rr.com> While enabling people to ftp material up to the site might prove problematic, some interesting alternatives come to mind. I'd also like to encourage list members to take a look at the site as it is now and see if I have a link to your own sites yet. If not, drop a line and let me know so I can add you (and feel free to suggest how you'd like the site to be classified if you like). The URL should be in my signature file down at the bottom of this message somewhere. 1) Someone with greater skill than I have could script a way for people to post their code via CGI. 2) Folks could email the source to be posted. 3) We could devise some way to implement a comment system on the site so viewers could add their own two cents' worth. 4) We could, of course, post the source of any scripts we put to use on the site. 5) While I maintain the Mississippi Python Interest Group site, this project could be called anything we like, and I would not consider it my property (just for the record). :-) Any other ideas? Rob Andrews John Murray wrote: > > Tesla Coil wrote: > >I've often thought an Interesting list would have posts of Python > >source as its topic. What typically motivates an initial post of > >source to the Tutor list is that the author finds it to be deficient. > > >What's lost are the one-shot scripts you've knocked off, maybe > >with little alteration of repeated use to someone else, not deemed > >important enough to publish on your web page, and no one expects > >to find it scattered off on your URL anyway. > > > >And perhaps utility wasn't even the point. Perhaps you had in > >mind a clever function to reduce the iterations in calculating a > >large factorial. A nice conversation piece, provided an audience > >who might appreciate that your only interest in the usual method > >would be comparing the performance of this approach. > > > >You could post it to comp.lang.python, but again, too unimportant > >to bother distracting anyone from the latest debate on whether > >this or that fundamental aspect of the language is a Good Thing. > > > >Ideally, the list topic would be *unimportant* Python source. > >I'd be compelled to subscribe to that one. > > Nicely put. I'd like to see something like this, perhaps we could take up > Rob.A's kind offer of server space (I think using SourceForge might be > overkill?). All we would need is a simple web page with links to the various > scripts. Tutor list members could post their code with a name and brief > description; author names would be optional for the anon. cowards:-) > Periodically (every fortnight?), the site address and any new additions could > be posted in a brief tutor-list message. Would we set it up so that list > members can ftp their files directly to the site? Or would it be better to have > them sent to the site's maintainer, who would then list them on the download > page? I'd be happy to help in any way I can. > Cheers, > Johnno -- Mississippi Python Interest Group http://www.lowerstandard.com/python/mspiggie From facelle@tiscalinet.it Sat Jan 6 10:57:28 2001 From: facelle@tiscalinet.it (Fabrizio Cellerini) Date: Sat, 6 Jan 2001 11:57:28 +0100 Subject: [Tutor] Path References: <20010105170130.367A7E9C6@mail.python.org> Message-ID: <008301c077cf$b053ee40$fc220b3e@oemcomputer> Hi, I am a newbie both to Python and programming in general, so my questions will be trivial; I hope somebody can help. I use Python 2.0 and Idle 0.6 on Windows 98. My question is : How can I setup the Python interpreter (I am not talking about Idle now !) so that it searches for modules in a specific directory without having to enter the full path in the script (e.g. using sys.path) ? i.e. if my_module.py is in c:\my_modules and in a script I need to use it with : import my_module It doesn't work, as python doesn't search in c:\my_modules by default. I also would like to know how to set it up so that it searches in the current working directory too (useful if I want to move my program and related modules in a different directory). I apologise if this is a recurrent question, but I could not find it in the faqs. Reading the documention, I guess I have to add paths into the PYTHONPATH variable or something : but can I do that ? Thanks in advance. Fabrizio From rmallett@rational.com Sat Jan 6 16:29:58 2001 From: rmallett@rational.com (Mallett, Roger) Date: Sat, 6 Jan 2001 08:29:58 -0800 Subject: [Tutor] setting object to None doesn't kill Word Message-ID: <78D9B26221DBD411B7EE00D0B73EB0EA3F59F4@cupex2.rational.com> Per D-Man's recommendation, in an attempt to get information about win32 and Python, I combed the tutor archives for all messages that concerned COM and come up with only a couple, none of which gave any hint to the problem I'm looking at. Question: Where is the best place to ask questions about Python for win32? Does Mark Hammond answer such question directly, or should I post to another Python list?... Roger Mallett -----Original Message----- From: D-Man [mailto:dsh8290@rit.edu] Sent: Wednesday, January 03, 2001 5:17 PM To: tutor@python.org Subject: Re: [Tutor] setting object to None doesn't kill Word I recall someone on the list mentioning having some problems with COM and python. Check the archives. I think that the COM objects had some sort of close function that should be used before removing the reference. HTH, -D On Wed, Jan 03, 2001 at 05:02:48PM -0800, Mallett, Roger wrote: > System: Windows 2000, Office 2000 > > I am on page 67-68 of Mark Hammond's book "Python Programming on Win32" and > I can't seem to kill Word by setting the object to None. _______________________________________________ Tutor maillist - Tutor@python.org http://www.python.org/mailman/listinfo/tutor From dman@res137a-039.rh.rit.edu Sat Jan 6 12:32:58 2001 From: dman@res137a-039.rh.rit.edu (D-Man) Date: Sat, 6 Jan 2001 07:32:58 -0500 Subject: [Tutor] setting object to None doesn't kill Word In-Reply-To: <78D9B26221DBD411B7EE00D0B73EB0EA3F59F4@cupex2.rational.com>; from rmallett@rational.com on Sat, Jan 06, 2001 at 08:29:58AM -0800 References: <78D9B26221DBD411B7EE00D0B73EB0EA3F59F4@cupex2.rational.com> Message-ID: <20010106073258.A914@dman.rh.rit.edu> Maybe it was on python-list that I saw the discussion. I'm pretty sure that the other person was using Excel via win32com. -D On Sat, Jan 06, 2001 at 08:29:58AM -0800, Mallett, Roger wrote: | Per D-Man's recommendation, in an attempt to get information about win32 and | Python, I combed the tutor archives for all messages that concerned COM and | come up with only a couple, none of which gave any hint to the problem I'm | looking at. | | Question: Where is the best place to ask questions about Python for win32? | Does Mark Hammond answer such question directly, or should I post to another | Python list?... | | Roger Mallett | | From rob@jam.rr.com Sat Jan 6 18:21:18 2001 From: rob@jam.rr.com (R. A.) Date: Sat, 06 Jan 2001 12:21:18 -0600 Subject: [Tutor] Python-friendly web hosts Message-ID: <3A57621E.885E67A@jam.rr.com> I'm always on the hunt for web hosting services that provide for Python scripting (or at the very least allow it). The one I have is okay, but the tech support is non-existent. Anyone know of any? Rob Andrews -- Mississippi Python Interest Group http://www.lowerstandard.com/python/mspiggie From tescoil@irtc.net Sat Jan 6 19:47:40 2001 From: tescoil@irtc.net (Tesla Coil) Date: Sat, 06 Jan 2001 13:47:40 -0600 Subject: [Tutor] Re: Example source code.. References: <3A5692B3.89F4A5FF@jam.rr.com> Message-ID: <3A57765C.61CEF844@irtc.net> On 05 Jan 2001, R. A. wrote: > 3) We could devise some way to implement a comment system > on the site so viewers could add their own two cents' worth. That would be essential. Peer review would be major motive to post. You want people to be able to say "here's a different implementation of the same thing," or "wow, that one function you've got there is simply Not Of This Earth." But regarding it all as unimportant source, a web comment board tends to grace an inital post with the false value of Definitive Unimportant Version, while a mailing list presents any followup as The Last Word For The Moment Anyway. From a subscriber's perspective, a list suggests, like Alan Perlis, "is it possible that software is not like anything else, that it is meant to be discarded: that the whole point is to see it as a soap bubble?" Subscribers can preserve what soap bubbles particularly interest them, and still consult the archive for what may have floated past earlier. Another advantage to a list over a web comment board is that participants in the latter may cease to contribute for no other reason than that they wandered off and kinda forgot it existed. Enough forgetting, and you don't even have the fortnightly new additions bulletin John suggested to remind people. A mailing list can go quiet for a while, but any single member deciding to post reminds everyone that it's still there, and among those will be persons to whom it then occurs, "oh yeah, I oughta post that one script I wrote a couple days ago." Whatever form it takes, occasionally someone posts to Tutor and says "I'm starting out with Python and need suggestions on programs to write for exercise." It wouldn't be a bad idea to have a web page collect proposals for unimportant Python programs. You'd still want this to be on a web page if the project were undertaken as a list, so it wouldn't become the "someone do my homework for me" request line. From rob@jam.rr.com Sat Jan 6 20:01:56 2001 From: rob@jam.rr.com (R. A.) Date: Sat, 06 Jan 2001 14:01:56 -0600 Subject: [Tutor] Re: Example source code.. References: <3A5692B3.89F4A5FF@jam.rr.com> <3A57765C.61CEF844@irtc.net> Message-ID: <3A5779B4.F38EFCD2@jam.rr.com> In my mind's eye, I see this whole idea as an interesting way to help the tutorial process. We could take examples from the list interaction and add them to the website collection, and use the comment feature to enhance the tutorial nature of it. A great strength of the list is that newbie-type people like me can ask a newbie-type question and get back interesting answers with commentary built-in. There are a number of Python tutorials out in the void, but what we have here is special. If the website we're proposing can take on some of this feel, I think it will really help a lot of people. People approaching Python often need something of a *light in the darkness* to help them get a feel for the Python landscape. Tutorials often have enough examples to demonstrate things like the difference between common data structures and other features of the language (which is great). However, when people completely new to programming run through a couple of these tutorials, they often feel like they have a basic feel for the Python language but no idea what they can do with it, because they lack the foundation in programming to start experimenting with *useful* programs. The site we're talking about could easily become a tutorial on Python programming by example, which would be nice indeed. And the comments could provide people the opportunity to add things like *and this is how I did the same thing in Perl* or whatever. I'd be more interested in developing this into a resource for good Python examples than just an archive of useless code (which is a cool idea in its own right). And there's no real reason why the maintainer(s) couldn't take good examples from current list discussion and post them to the site with some context. When people post to the list asking where to find Python source code on the web, I honestly think that something like this is often what they're looking for. Rob Andrews Tesla Coil wrote: > > On 05 Jan 2001, R. A. wrote: > > 3) We could devise some way to implement a comment system > > on the site so viewers could add their own two cents' worth. > > That would be essential. Peer review would be major motive > to post. You want people to be able to say "here's a different > implementation of the same thing," or "wow, that one function > you've got there is simply Not Of This Earth." > > But regarding it all as unimportant source, a web comment > board tends to grace an inital post with the false value of > Definitive Unimportant Version, while a mailing list presents > any followup as The Last Word For The Moment Anyway. From > a subscriber's perspective, a list suggests, like Alan Perlis, > "is it possible that software is not like anything else, that it > is meant to be discarded: that the whole point is to see it as > a soap bubble?" Subscribers can preserve what soap bubbles > particularly interest them, and still consult the archive for > what may have floated past earlier. > > Another advantage to a list over a web comment board is that > participants in the latter may cease to contribute for no other > reason than that they wandered off and kinda forgot it existed. > Enough forgetting, and you don't even have the fortnightly new > additions bulletin John suggested to remind people. A mailing > list can go quiet for a while, but any single member deciding to > post reminds everyone that it's still there, and among those will > be persons to whom it then occurs, "oh yeah, I oughta post that > one script I wrote a couple days ago." > > Whatever form it takes, occasionally someone posts to Tutor > and says "I'm starting out with Python and need suggestions > on programs to write for exercise." It wouldn't be a bad idea > to have a web page collect proposals for unimportant Python > programs. You'd still want this to be on a web page if the > project were undertaken as a list, so it wouldn't become the > "someone do my homework for me" request line. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://www.python.org/mailman/listinfo/tutor -- Mississippi Python Interest Group http://www.lowerstandard.com/python/mspiggie From budgester@budgester.com Sat Jan 6 20:12:48 2001 From: budgester@budgester.com (Budgester) Date: Sat, 6 Jan 2001 20:12:48 -0000 Subject: [Tutor] How to set a timer. Message-ID: <000001c0781d$0b058630$0300000a@budgester> Hi all, Can anyone point me in the right direction with a problem I'm having. What I want to do is read a web page on an internal server every 10 seconds. So far I've can get the information I want from the web page working using 'urllib', but this is only a one time routine. The bit i am having problems with is calling the function at regular intervals. Any help apprieciated. TIA Budgester mailto:budgester@budgester.com http://www.budgester.com From curtishorn@home.com Sat Jan 6 20:37:01 2001 From: curtishorn@home.com (Curtis Horn) Date: Sat, 06 Jan 2001 12:37:01 -0800 Subject: [Tutor] New to Python and programming and need suggestion Message-ID: <4.3.2.7.0.20010106122517.00aa8b60@mail> Hello, I'm new to programming and python (just bought Learn to Program Using Python by Alan Gauld, I'm on ch 14). I feel like I have learned alot so far, and I look forward to finally bieng able to do something with all the ideas I get. My first project is work related ( of course :) and basically boils down to this: 1. There is a text file that I want to monitor for certain key words, it is organized by date time msg. The msg can be more than one word, and each date time msg is on a seperate line. There are several computers that need to be monitored in this way. 2. For the lines with those keywords I'd like to have them uploaded onto a database running on a server. 3. I'd like people on the LAN to be able to look on a intranet page and access the data on the database, visually and if they need more detail with text. maybe there is another way to monitor text files remotly with a web page other than using a database as an in-between? since I'm new to python, some things are not clear to me, like how to go about having data sent to the database, and how to access the info with a web page. I'm assuming it can be done with python and some other tools, like maybe gadfly or mySQL and a web server? Curtis From curtishorn@home.com Sat Jan 6 21:08:58 2001 From: curtishorn@home.com (Curtis Horn) Date: Sat, 06 Jan 2001 13:08:58 -0800 Subject: [Tutor] New to Python and programming and need suggestion Message-ID: <4.3.2.7.0.20010106130751.00abcde0@mail> Hello, I'm new to programming and python (just bought Learn to Program Using Python by Alan Gauld, I'm on ch 14). I feel like I have learned alot so far, and I look forward to finally bieng able to do something with all the ideas I get. My first project is work related ( of course :) and basically boils down to this: 1. There is a text file that I want to monitor for certain key words, it is organized by date time msg. The msg can be more than one word, and each date time msg is on a seperate line. There are several computers that need to be monitored in this way. 2. For the lines with those keywords I'd like to have them uploaded onto a database running on a server. 3. I'd like people on the LAN to be able to look on a intranet page and access the data on the database, visually and if they need more detail with text. maybe there is another way to monitor text files remotly with a web page other than using a database as an in-between? since I'm new to python, some things are not clear to me, like how to go about having data sent to the database, and how to access the info with a web page. I'm assuming it can be done with python and some other tools, like maybe gadfly or mySQL and a web server? Curtis From kalle@gnupung.net Sat Jan 6 22:48:49 2001 From: kalle@gnupung.net (Kalle Svensson) Date: Sat, 6 Jan 2001 23:48:49 +0100 Subject: [Tutor] How to set a timer. In-Reply-To: <000001c0781d$0b058630$0300000a@budgester>; from budgester@budgester.com on Sat, Jan 06, 2001 at 08:12:48PM -0000 References: <000001c0781d$0b058630$0300000a@budgester> Message-ID: <20010106234849.A877@apone.network.loc> --vtzGhvizbBRQ85DL Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable Sez Budgester: > What I want to do is read a web page on an internal server every 10 secon= ds. >=20 > So far I've can get the information I want from the web page working using > 'urllib', but this is only a one time routine. >=20 > The bit i am having problems with is calling the function at regular > intervals. The easiest way is probably a loop like this: import time while 1: time.sleep(10) #get page #do something with page contents if finished: break If you are creating a GUI program with Tkinter, I think there is some more elegant mechanism, but I don't know for sure. HTH, Kalle --=20 Email: kalle@gnupung.net | You can tune a filesystem, but you Web: http://www.gnupung.net/ | can't tune a fish. -- man tunefs(8) PGP fingerprint: 0C56 B171 8159 327F 1824 F5DE 74D7 80D7 BF3B B1DD --vtzGhvizbBRQ85DL Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.2 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE6V6DRdNeA1787sd0RAqiUAKCOx2w93qUABXhEoYl437lo58fc4QCgoRPG X9GkR9WtwYFQD2ibgr3UbcA= =9NRb -----END PGP SIGNATURE----- --vtzGhvizbBRQ85DL-- From dyoo@hkn.eecs.berkeley.edu Sat Jan 6 23:19:03 2001 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Sat, 6 Jan 2001 15:19:03 -0800 (PST) Subject: [Tutor] How to set a timer. In-Reply-To: <000001c0781d$0b058630$0300000a@budgester> Message-ID: > Can anyone point me in the right direction with a problem I'm having. > > What I want to do is read a web page on an internal server every 10 seconds. > > So far I've can get the information I want from the web page working using > 'urllib', but this is only a one time routine. There are several ways to approach this. One way is to use an infinite loop. The pseudocode for this would be: ### while 1: read that web page wait for 10 seconds ### Python provides the function time.sleep to let a program delay itself for an interval. You can read more about time.sleep() here: http://python.org/doc/current/lib/module-time.html The only problem with this approach is that, as it stands, it doesn't let us do anything else outside of this while loop, since we're perpetually repeating that code. I'm not sure if this is what you want. Another alternative is in the "sched" module --- sched allows you to schedule a fuction to be called every few times. I haven't worked with it myself yet, but the documentation appears to have a good example in there. Here's the link: http://python.org/doc/current/lib/module-sched.html Good luck! From dyoo@hkn.eecs.berkeley.edu Sat Jan 6 23:24:21 2001 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Sat, 6 Jan 2001 15:24:21 -0800 (PST) Subject: [Tutor] setting object to None doesn't kill Word In-Reply-To: <78D9B26221DBD411B7EE00D0B73EB0EA3F59F4@cupex2.rational.com> Message-ID: On Sat, 6 Jan 2001, Mallett, Roger wrote: > Per D-Man's recommendation, in an attempt to get information about win32 and > Python, I combed the tutor archives for all messages that concerned COM and > come up with only a couple, none of which gave any hint to the problem I'm > looking at. > > Question: Where is the best place to ask questions about Python for win32? > Does Mark Hammond answer such question directly, or should I post to another > Python list?... Hmmm... you might want to talk to the usenet newsgroup: comp.lang.python. It has a large (overwhelming) following of Python programmers, and I'm sure there's someone out there with COM experience. You might also check with your bookstore for "Python Programming on Win32" by Mark Hammond and Andy Robinson. Since Mark Hammond is a coauthor, it's certainly authoritative. *grin* I haven't read it yet, but I've heard it's an essential reference if you're going to do COM stuff. Good luck to you! From pursang@interact.net.au Sat Jan 6 23:01:11 2001 From: pursang@interact.net.au (John Murray) Date: Sun, 7 Jan 2001 10:01:11 +1100 Subject: [tutor] example code Message-ID: <01010710215300.00622@localhost.localdomain> Rob A and Tesla Coil made some very good points in their last posts, I thought. I'd just like to add a couple more: I think the proposed page would fit in nicely with Rob's ms piggie site. Emailing source directly to the site would probably be easiest, in view of the small size of most scripts, and even if you do have a 30,000 line behemoth it should zip up to a reasonable size. The only exception might be stuff that is compiled into stand-alone executables. I agree that the list would probably be the best place for comments. I would like to see it strongly newbie oriented, so that raw newbies (like me!) can send in their stuff, no matter how crappy it might be. Even one-liners can be useful and interesting. I really hope this thing takes off! Cheers, Johnno From genius@idirect.com Sat Jan 6 23:45:04 2001 From: genius@idirect.com (Charles Takacs) Date: Sat, 06 Jan 2001 18:45:04 -0500 Subject: [Tutor] New to Python and programming and need suggestion References: <4.3.2.7.0.20010106130751.00abcde0@mail> Message-ID: <3A57AE00.7FEB3499@idirect.com> Since you bought Alan's book, I think it's only fair that he does some promotional work by responding to you :-)) Charles Curtis Horn wrote: > > Hello, I'm new to programming and python (just bought Learn to > Program Using Python by Alan Gauld, I'm on ch 14). I feel like > I have learned alot so far, and I look forward to finally bieng able > to do something with all the ideas I get. > My first project is work related ( of course :) and basically boils > down to this: > > 1. There is a text file that I want to monitor for certain key words, > it is organized by date time msg. The msg can be more than one > word, and each date time msg is on a seperate line. There are several > computers that need to be monitored in this way. > > 2. For the lines with those keywords I'd like to have them uploaded > onto a database running on a server. > > 3. I'd like people on the LAN to be able to look on a intranet page and > access the data on the database, visually and if they need more detail > with text. > > maybe there is another way to monitor text files remotly with a web page other > than using a database as an in-between? > > since I'm new to python, some things are not clear to me, like how to go about > having data sent to the database, and how to access the info with a web page. > I'm assuming it can be done with python and some other tools, like maybe > gadfly or mySQL and a web server? > > Curtis > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://www.python.org/mailman/listinfo/tutor From dyoo@hkn.eecs.berkeley.edu Sun Jan 7 00:51:37 2001 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Sat, 6 Jan 2001 16:51:37 -0800 (PST) Subject: [Tutor] Re: Example source code.. In-Reply-To: <3A5779B4.F38EFCD2@jam.rr.com> Message-ID: > archive of useless code (which is a cool idea in its own right). And > there's no real reason why the maintainer(s) couldn't take good examples > from current list discussion and post them to the site with some > context. When people post to the list asking where to find Python > source code on the web, I honestly think that something like this is > often what they're looking for. This sounds like a great idea! I'd like to contribute some scripts here: http://hkn.eecs.berkeley.edu/~dyoo/python/ I remember someone on the list asked for stuff on the A* search algorithm, but the code that they posted was just too painful to look at. I had a free afternoon, so I reimplemented A*. It's on my web site there, and I'd appreciate any comments on it. From dyoo@hkn.eecs.berkeley.edu Sun Jan 7 11:03:31 2001 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Sun, 7 Jan 2001 03:03:31 -0800 (PST) Subject: [Tutor] Path In-Reply-To: <008301c077cf$b053ee40$fc220b3e@oemcomputer> Message-ID: On Sat, 6 Jan 2001, Fabrizio Cellerini wrote: > How can I setup the Python interpreter (I am not talking about Idle > now !) so that it searches for modules in a specific directory without > having to enter the full path in the script (e.g. using sys.path) ? [some text cut] > Reading the documention, I guess I have to add paths into the PYTHONPATH > variable or something : but can I do that ? Yes, you'll want to include c:\my_modules within the PYTHONPATH environmental variable. However, adding an additional entry to your PYTHONPATH depends on what version of Windows that you're running. I'm running on UNIX, so the following might not be accurate... *grin* If you're working with Win2k, you should be able to modify environment variables within one of the My Computer property tabs. Look for a tab that says "Environment Variables" or something like that. You should see a list of variable names, along with their values. You'll probably need to add a new variable named PYTHONPATH --- it'll be convenient if you set that variable up systemwide. If you're in Win98, things are a little simpler. You'll probably need to edit your autoexec.bat with the line: SET PYTHONPATH="C:\my_modules" After a reboot, you should be able to do those imports nicely. > I also would like to know how to set it up so that it searches in the > current working directory too (useful if I want to move my program and > related modules in a different directory). Hmmm... by default, it should search the current directory already. Strange! Can you try it again? I hope that this helps fix your problems. Good luck! From dyoo@hkn.eecs.berkeley.edu Sun Jan 7 11:32:11 2001 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Sun, 7 Jan 2001 03:32:11 -0800 (PST) Subject: [Tutor] New to Python and programming and need suggestion In-Reply-To: <4.3.2.7.0.20010106122517.00aa8b60@mail> Message-ID: On Sat, 6 Jan 2001, Curtis Horn wrote: > Hello, I'm new to programming and python (just bought Learn to > Program Using Python by Alan Gauld, I'm on ch 14). I feel like > I have learned alot so far, and I look forward to finally bieng able > to do something with all the ideas I get. Cool! Let's see what you want to do: > 1. There is a text file that I want to monitor for certain key words, > it is organized by date time msg. The msg can be more than one word, > and each date time msg is on a seperate line. There are several > computers that need to be monitored in this way. Ok, it sounds like you may find the string splitting operations really useful to parse out the date, time, and message. Let's say that the text file separates each field with a space. Then, we could split each line up like this: date = string.split(line, ' ')[0] time = string.split(line, ' ')[1] msg = string.join(string.split(line, ' ')[2:], ' ') Regular expressions might be more appropriate and nicer to use. Now that I think about it, the above code might be buggy too --- you'll probably need to experiment a bit. *grin* > 2. For the lines with those keywords I'd like to have them uploaded > onto a database running on a server. This isn't too hard if you go with SQL --- you'll be executing an "insert" query on a database connection that you make. SQL database code has the following structure: Make a connection. Get a "cursor" from the connection: something that lets you execute queries. Execute some sort of query. Fetch results if you need it. Here's sample (untested) code that assumes that we're using MySQL: import MySQLdb connection = MySQLdb.connect(db='test') cursor = connection.cursor() cursor.execute("select first_name, last_name from names") names = cursor.fetchall() This shows that SQL stuff isn't too complicated. If you're going to do SQL inserts, you'll definitely want to learn about string interpolation: http://python.org/doc/current/tut/node9.html The stuff about '%' is the stuff on string interpolation. With '%', you can build up your SQL statements pretty easily: fname = 'Curtis' lname = 'horn' stmt = """insert into names (first_name, last_name) values ('%s', '%s')" % (fname, lname) is one example. > 3. I'd like people on the LAN to be able to look on a intranet page and > access the data on the database, visually and if they need more detail > with text. Ok, so that sounds like you'll be using either Python, PHP, or something else to present the database information. This should be very doable too. You might want to look at some of the CGI tutorials here: http://python.org/topics/web/ > maybe there is another way to monitor text files remotly with a web > page other than using a database as an in-between? Not quite sure --- it really depends on what sort of access the server has with those client computers. > since I'm new to python, some things are not clear to me, like how to > go about having data sent to the database, and how to access the info > with a web page. I'm assuming it can be done with python and some > other tools, like maybe gadfly or mySQL and a web server? Going with SQL will work, and it should be fun as well. You'll probably want to look here for database stuff: http://python.org/topics/database/ The important stuff there is the DB-API 2.0 --- most database drivers support this interface --- and the Database Modules link. If you go with MySQLdb, you'll want to use this link: http://dustman.net/andy/python/MySQLdb/ Whew! Lots of stuff here; forgive me for rambling! I feel a little uncomfortable about just mentioning these topics; is there anything in particular that you might want to start on? The project that you're planning ties together several topics, but if you take it slowly, it shouldn't be overwhelming. I hope this helps! From dyoo@hkn.eecs.berkeley.edu Sun Jan 7 11:36:04 2001 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Sun, 7 Jan 2001 03:36:04 -0800 (PST) Subject: [Tutor] Web programming not using zope In-Reply-To: <002d01c076ed$c3b63980$0501a8c0@softdesigns.com> Message-ID: On Fri, 5 Jan 2001, David Metzler wrote: > One of the programmers I work with uses PHP4 and apache a great deal. > I'm interested in using Python especially the apache py module. I have > not been able to find any tutorials or sample code that demonstrates > this environment. What are the advantages and disadvantages to using > Python as a PHP replacement? Is their any docs for this? You may want to ask this on comp.lang.python instead. Most of us here probably haven't worked with PHP. From what I've heard, PHP is supposed to be great for web development, and I'm sure that certain web-based tasks are easier to do with PHP than Python. Since your programmer uses PHP already, it might be to your advantage to stick with PHP. You might want to look at devshed.com's articles on PHP: http://devshed.com/Server_Side/PHP/ Devshed has a LOT of PHP tutorials, and I think you'll like their presentation style. Devshed also has some stuff on Python web programming: http://devshed.com/Server_Side/Python/ but you'll probably want to look at the Python CGI topic guide for more depth. http://python.org/topics/web/ I hope these resources help you find an ideal solution. Good luck! From dyoo@hkn.eecs.berkeley.edu Sun Jan 7 11:41:24 2001 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Sun, 7 Jan 2001 03:41:24 -0800 (PST) Subject: [Tutor] Python-friendly web hosts In-Reply-To: <3A57621E.885E67A@jam.rr.com> Message-ID: On Sat, 6 Jan 2001, R. A. wrote: > I'm always on the hunt for web hosting services that provide for Python > scripting (or at the very least allow it). The one I have is okay, but > the tech support is non-existent. Anyone know of any? Good question! There's a FAQTS entry about web hosting services: http://www.faqts.com/knowledge-base/view.phtml/aid/3008/fid/199/lang/en I haven't worked with web hosting services myself, so you might want to check with people with some experience with those hosts. From dyoo@hkn.eecs.berkeley.edu Sun Jan 7 11:47:27 2001 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Sun, 7 Jan 2001 03:47:27 -0800 (PST) Subject: [Tutor] New to Python and programming and need suggestion In-Reply-To: Message-ID: > The stuff about '%' is the stuff on string interpolation. With '%', you > can build up your SQL statements pretty easily: > > fname = 'Curtis' > lname = 'horn' > stmt = """insert into names (first_name, last_name) > values ('%s', '%s')" % (fname, lname) > > is one example. ... err... that is, if I had done it properly. Oops. The last line should have been: stmt = """insert into names (first_name, last_name) values ('%s', '%s')""" % (fname, lname) instead. I had forgotten to close off the triple quotes. From facelle@tiscalinet.it Sun Jan 7 14:59:41 2001 From: facelle@tiscalinet.it (Fabrizio) Date: Sun, 7 Jan 2001 15:59:41 +0100 Subject: [Tutor] Re: Path References: <20010107110504.A6EA8EA37@mail.python.org> Message-ID: <002301c078ea$b2803180$9f1affd5@oemcomputer> > If you're in Win98, things are a little simpler. You'll probably need to > edit your autoexec.bat with the line: > > SET PYTHONPATH="C:\my_modules" > > After a reboot, you should be able to do those imports nicely. Yes, that's it ! Now it works, thanks a lot !! > > I also would like to know how to set it up so that it searches in the > > current working directory too (useful if I want to move my program and > > related modules in a different directory). > > Hmmm... by default, it should search the current directory already. > Strange! Can you try it again? Yes it does search it when running from a DOS shell, but it does not when I run my scripts from IDLE,. It doesn't seem to search in the directory where the script is. Fabrizio From sheila@thinkspot.net Sun Jan 7 21:05:55 2001 From: sheila@thinkspot.net (Sheila King) Date: Sun, 07 Jan 2001 13:05:55 -0800 Subject: [Tutor] How to print out multiple lines Message-ID: <2300B7B6146@kserver.org> OK, I've been to python.org, I've gone through Guido's tutorial, I've looked at a few modules. I've even been able to sort of send mails through a SMTP server and retrieve articles off of an NNTP server. So I have *some* clue. But apparently not enough. How can I get an interactive Python session to read in something like this: ------------------------------ Hello. How are you? I'm fine. Thanks for asking. ------------------------------ So that the newline characters are preserved, and when I print them out, they are printed to the screen? When I retrieved the news articles off the NNTP server, for instance, the message body was just one big long string, with some numeric code for the newlines. It was just a mess to read. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From sheila@thinkspot.net Sun Jan 7 21:30:24 2001 From: sheila@thinkspot.net (Sheila King) Date: Sun, 07 Jan 2001 13:30:24 -0800 Subject: [Tutor] How to print out multiple lines In-Reply-To: <2300B7B6146@kserver.org> References: <2300B7B6146@kserver.org> Message-ID: <246461A327B@kserver.org> Replying to my own post: OK, it seems simple enough to accomplish this in the IDLE environment or at a command line prompt: >>> print '''Hello. ... How are you? ... Fine. ... Thanks for asking.''' Hello. How are you? Fine. Thanks for asking. >>> Just use triple quotes. But, how do I accomplish something like this (here is a small SMTP script I wrote for investigation): import smtplib, string servername=input("SMTP server name: ") Fromaddress=input("From address: ") Toaddress=input("To address: ") MessageText=input("message text: ") server=smtplib.SMTP(servername) server.sendmail(Fromaddress, Toaddress, MessageText) server.quit() The above script will not allow MessageText to have multiple lines. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ On Sun, 07 Jan 2001 13:05:55 -0800, Sheila King wrote about [Tutor] How to print out multiple lines: :OK, I've been to python.org, I've gone through Guido's tutorial, I've looked :at a few modules. : :I've even been able to sort of send mails through a SMTP server and retrieve :articles off of an NNTP server. So I have *some* clue. : :But apparently not enough. : :How can I get an interactive Python session to read in something like this: : :------------------------------ :Hello. :How are you? :I'm fine. :Thanks for asking. :------------------------------ : :So that the newline characters are preserved, and when I print them out, they :are printed to the screen? : :When I retrieved the news articles off the NNTP server, for instance, the :message body was just one big long string, with some numeric code for the :newlines. It was just a mess to read. From dyoo@hkn.eecs.berkeley.edu Sun Jan 7 21:53:05 2001 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Sun, 7 Jan 2001 13:53:05 -0800 (PST) Subject: [Tutor] How to print out multiple lines In-Reply-To: <2300B7B6146@kserver.org> Message-ID: > So that the newline characters are preserved, and when I print them > out, they are printed to the screen? > > When I retrieved the news articles off the NNTP server, for instance, the > message body was just one big long string, with some numeric code for the > newlines. It was just a mess to read. When you ask the interpreter for a string's value, you'll be getting its "representation", that is, all the special characters like newlines will be explicitely shown as escapes: ### >>> x = "Hello\nWorld" >>> x 'Hello\012World' ### Python does this because, in many cases, it's useful to see what particular escapes are within a string. However, asking for a string's value isn't quite the same as printing it out: ### >>> print x Hello World >>> ### Use "print". It will display things as you'd expect. Also, you can use stdout.write() with a similar effect. ### >>> from sys import stdout >>> stdout.write(x) Hello World>>> ### (side note: The main difference between stdout.write and print is that print will add an extra newline after every call. Also, print is a built-in statement --- it's not a function or expression, so it can't be passed around or used within lambda. In Scheme terms, its a "special form") From mbc2@netdoor.com Sun Jan 7 22:01:30 2001 From: mbc2@netdoor.com (mbc2@netdoor.com) Date: Sun, 7 Jan 2001 16:01:30 -0600 (CST) Subject: [Tutor] strange recursion result Message-ID: I wrote a short little program to perform a recursive calculation for me. #!/usr/local/bin/python def rlgncount(n): if (n<=1): return 0 else: return (n-1)+rlgncount(n-1) print rlgncount(1000) Basically it is meant to perform the following calculation where n=6: (6-1)+(5-1)+(4-1)+(3-1)+(2-1)+(1-1) = 5+4+3+2+1+0 = 15 It works fine if I feed it numbers between 1 and 999. Anything larger than 999 doesn't work. I get an error in the "return (n-1)+rlgncount(n-1)" line. I must be missing something simple, but I don't see it. Does anyone have any suggestions? From dyoo@hkn.eecs.berkeley.edu Sun Jan 7 22:05:15 2001 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Sun, 7 Jan 2001 14:05:15 -0800 (PST) Subject: [Tutor] How to print out multiple lines In-Reply-To: <246461A327B@kserver.org> Message-ID: > servername=input("SMTP server name: ") > Fromaddress=input("From address: ") > Toaddress=input("To address: ") > MessageText=input("message text: ") > server=smtplib.SMTP(servername) > server.sendmail(Fromaddress, Toaddress, MessageText) > server.quit() You may want to use raw_input() instead of input(): input() acts like the interpreter, so with it, you'll need to quote your strings. I'm quite sure that can get a bit annoying. raw_input(), on the other hand, always assumes that you want to get strings, so it doesn't require quotes. To read multiple lines of text... hmmm... there are several ways to do this. How should the program know when to stop reading lines? input() and raw_input() are set up only to work on single lines, so you could write a specialty inputting function instead that stops when it sees a certain "terminating" line. ### def readManyLines(): """Read lines from the user until they enter a line with a single period, and return a single string.""" result = "" while 1: line = raw_input() if line == '.': return result result = result + line ### Here's an example run: ### >>> msg = readManyLines() This is a test of the emergency broadcast system. . >>> msg 'This is a testof the emergencybroadcast system.' >>> print msg This is a testof the emergencybroadcast system. ### Hmmm... that's a bug! I needed to add newlines between the concatentations. I think you should be able to fix this ok. Hope this helps! From dyoo@hkn.eecs.berkeley.edu Sun Jan 7 22:22:48 2001 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Sun, 7 Jan 2001 14:22:48 -0800 (PST) Subject: [Tutor] strange recursion result In-Reply-To: Message-ID: On Sun, 7 Jan 2001 mbc2@netdoor.com wrote: > I wrote a short little program to perform a recursive calculation for me. > > #!/usr/local/bin/python > > def rlgncount(n): > if (n<=1): > return 0 > else: > return (n-1)+rlgncount(n-1) > > print rlgncount(1000) [some text cut] > I must be missing something simple, but I don't see it. Does anyone have > any suggestions? Ah! So it calculates the sum from 1 to n-1. Cool! The definition of your program is perfectly legitimate. The only problem is that Python doesn't support such a larger recursion depth. You probably got the following message: ### RuntimeError: Maximum recursion depth exceeded ### which means that it just hit its limits. The Python implementors are probably planning to support recursion to arbitrary depths in the future, but this hasn't been done yet. Are you coming from a Scheme background? Since Scheme's only iteration consists of recursion, the implementors of Scheme made extra sure that they didn't impose limits to recursion. Python, on the other hand, does recursive-like stuff with for/while loops, so it's a bit less functional in terms of recursion. ### for i in range(n): sum = sum + i ### is one way of performing your function, at the expense of requiring the use of variables. But Python also supports a bit of functional programming: ### sum = reduce(lambda x, y: x+y, range(n)) ### will also add the numbers from 0 to n-1. Apologies: it feels like a disappointing answer to say "It won't work yet"; does anyone have any suggestions or comments? From Nate Bargmann Sun Jan 7 22:26:41 2001 From: Nate Bargmann (Nate Bargmann) Date: Sun, 7 Jan 2001 16:26:41 -0600 Subject: [Tutor] strange recursion result In-Reply-To: ; from mbc2@netdoor.com on Sun, Jan 07, 2001 at 04:01:30PM -0600 References: Message-ID: <20010107162640.M257@nomad.n0nb.ampr.org> On Sun, Jan 07, 2001 at 04:01:30PM -0600, mbc2@netdoor.com wrote: > > It works fine if I feed it numbers between 1 and 999. Anything larger than > 999 doesn't work. I get an error in the "return > (n-1)+rlgncount(n-1)" line. I'm no expert in recursion. However, I ran your script both in Idle and as an executable script. It worked fine each time, using the values of 1000, 100, and 1001. When I set n to 10000 I received the following error: File "./recurse.py", line 7, in rlgncount return (n-1)+rlgncount(n-1) RuntimeError: Maximum recursion depth exceeded The first two lines were repeated quite a number of times, so I'm not sure of the limit to recursion depth. Whether or not that is something that may be changed, I don't know, but it's the only error I found. I'm running Debian 2.2r2 with Python 1.5.2. - Nate >> -- Wireless | Amateur Radio Station N0NB | "None can love freedom Internet | n0nb@networksplus.net | heartily, but good Location | Wichita, Kansas USA EM17hs | men; the rest love not Wichita area exams; ham radio; Linux info @ | freedom, but license." http://www.qsl.net/n0nb/ | -- John Milton From tescoil@irtc.net Mon Jan 8 00:18:23 2001 From: tescoil@irtc.net (Tesla Coil) Date: Sun, 07 Jan 2001 18:18:23 -0600 Subject: [tutor] example code References: <01010710215300.00622@localhost.localdomain> Message-ID: <3A59074F.29A34DC0@irtc.net> On 7 Jan 2001, John Murray wrote: > Emailing source directly to the site would probably > be easiest, in view of the small size of most scripts, Were the source posted to a list, the site could just draw directly from it, become a "best of" collection. Other site maintainers could do the same thing, with their different idea of what "best of" means. > I agree that the list would probably be the best > place for comments. I'd suggest that it could become a regular part of the Tutor list process: post source that does just what you wanted it to do, comment on what improvements you think could be made but haven't written, and let others point out those improvements that didn't occur to you. I think it could get out of hand when source can be a module waiting to happen; all someone needs to do is reorganize it and add related functions the original script didn't look to provide. That goes beyond tutoring and into development, but might well be a secondary school that could stand to be constructed. Going that far, one might as well say to post stuff you're confident reflects your competence. I'm not sure what the protocol is for proposing that python.org host a new list. It could be hosted elsewhere. And I don't have in mind any name to unambiguously describe such a list. > I would like to see it strongly newbie oriented, so that > raw newbies (like me!) can send in their stuff, no matter > how crappy it might be. Even one-liners can be useful > and interesting. That's some of the beauty of calling it unimportant source. It doesn't matter if you're a neophyte or wizard, whether your source is trivial or sublime, whether the program is a handy utility or a total waste of system resources with no output. You decide it's unimportant enough source to post; no one can look down on you given that standard. That it's unimportant doesn't prevent it from being valuable. One could provide valuable source and call it unimportant; everyone can just wonder what your important stuff must be like. One could provide genuinely unimportant source, just to demonstrate that you're at liberty not to have to do Real Work all the time... From tescoil@irtc.net Mon Jan 8 00:42:34 2001 From: tescoil@irtc.net (Tesla Coil) Date: Sun, 07 Jan 2001 18:42:34 -0600 Subject: [Tutor] 2.0 Readline Interpreter. Message-ID: <3A590CFA.34447054@irtc.net> I upgraded to BeOpen-Python-2.0-i386.rpm and, ouch, find I no longer have GNU readline editing behavior I had with the 1.5.2 interpreter. Is this because it's not compiled into the binary, or, that being installed to /usr/local has broken access to the library, or can anyone even say? I don't recall if I ignored any dependencies. I installed it and went some time before finding need for interpreter interaction. The only problems I immediately encountered were having to compile PySol from source and getting warnings about API version mismatch for module _tkinter (which hasn't had any devestating results). From scarblac@pino.selwerd.nl Mon Jan 8 00:08:56 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Mon, 8 Jan 2001 01:08:56 +0100 Subject: [tutor] example code In-Reply-To: <3A59074F.29A34DC0@irtc.net>; from tescoil@irtc.net on Sun, Jan 07, 2001 at 06:18:23PM -0600 References: <01010710215300.00622@localhost.localdomain> <3A59074F.29A34DC0@irtc.net> Message-ID: <20010108010856.A1917@pino.selwerd.nl> On Sun, Jan 07, 2001 at 06:18:23PM -0600, Tesla Coil wrote: > On 7 Jan 2001, John Murray wrote: > > Emailing source directly to the site would probably > > be easiest, in view of the small size of most scripts, > > Were the source posted to a list, the site could just > draw directly from it, become a "best of" collection. > Other site maintainers could do the same thing, with > their different idea of what "best of" means. (I've missed most of the previous discussion, I hope my points weren't discussed to death yet). I think that's quite a lot of work for a maintainer. Read the daily posts, judge what is suitable for the site, and turn the post into some sort of format that's usable (like a web page). The sort of job that you might find a volunteer for, but I wouldn't be surprised if it doesn't last for long. Also, there is already the Python snippets archive (although I currently can't locate the URL - recently erased the bookmarks file and Parnassus' find function is bugging). I'm not sure if it's still active. Anyway, any effort from the list should probably be combined with the snippets archive. And then there's a plan I've had in the back of my mind for a while - some people come here and ask the question "I've read the book and the tutorials, what now?". Apparently they don't learn programming just to get some job done or at least with a specific goal in mind. I'd love an archive with case studies, things to do after the tutorials - make a small programs that downloads comics, implement this game, whatever - I don't have ideas right now but it should be possible to think of plenty of things. The site could have an archive of ideas for projects, things that have been done often but that are useful to learn from. And have hints on where to start - you need to do this, this and this, and these modules will probably be useful. And people who have a working implementation can send them in. That would be a useful resource. Of course, I've already spent far too long on my CS study and I'm just starting my final thesis, there is no way I will volunteer for any of this in the next half year or so. I need the self protection. -- Remco Gerlich From ezesch@megsinet.net Mon Jan 8 00:42:38 2001 From: ezesch@megsinet.net (Eugene C. Zesch) Date: Sun, 07 Jan 2001 18:42:38 -0600 Subject: [tutor] example code References: <01010710215300.00622@localhost.localdomain> <3A59074F.29A34DC0@irtc.net> <20010108010856.A1917@pino.selwerd.nl> Message-ID: <3A590CFE.82552F62@megsinet.net> > > Also, there is already the Python snippets archive (although I currently > can't locate the URL - recently erased the bookmarks file and Parnassus' > find function is bugging). I'm not sure if it's still active. Snippets can be found at: http://tor.dhs.org/~zephyrfalcon/snippets/html/snippets.html Gene From rob@jam.rr.com Mon Jan 8 05:20:32 2001 From: rob@jam.rr.com (R. A.) Date: Sun, 07 Jan 2001 23:20:32 -0600 Subject: [tutor] example code References: <01010710215300.00622@localhost.localdomain> <3A59074F.29A34DC0@irtc.net> <20010108010856.A1917@pino.selwerd.nl> Message-ID: <3A594E20.258604E8@jam.rr.com> We could also come up with a CGI form people could use to submit code (personal info, filename, source code, commentary, etc.) and simplify maintenance. In the meantime, feel free to send any scripts ready to post to me privately, or post to the list (as long as it doesn't anger the gods and fierce rabbits). Also, if anyone has posted a question to the list that they felt they really got some great answers to, feel free to put it together and send it along. Just remember to provide the code (well-commented code is super fine) along with any notes on how to make it work and who you think deserves a little credit. I'd be happy to get some initial items posted while we work out other details. And remember to let me know if you have a site I can link to. The whole idea seems useful also as a way to put up example answers to FAQs here on the list. And why not have items such as a ROT-13 encoding script right next to it and a few *Stupid XML Tricks* that show people how to do things that prove to be simple enough if you happen to already know how to do them. Rob Andrews Remco Gerlich wrote: > > On Sun, Jan 07, 2001 at 06:18:23PM -0600, Tesla Coil wrote: > > On 7 Jan 2001, John Murray wrote: > > > Emailing source directly to the site would probably > > > be easiest, in view of the small size of most scripts, > > > > Were the source posted to a list, the site could just > > draw directly from it, become a "best of" collection. > > Other site maintainers could do the same thing, with > > their different idea of what "best of" means. > > (I've missed most of the previous discussion, I hope my points weren't > discussed to death yet). > > I think that's quite a lot of work for a maintainer. Read the daily posts, > judge what is suitable for the site, and turn the post into some sort of > format that's usable (like a web page). The sort of job that you might find > a volunteer for, but I wouldn't be surprised if it doesn't last for long. > > Also, there is already the Python snippets archive (although I currently > can't locate the URL - recently erased the bookmarks file and Parnassus' > find function is bugging). I'm not sure if it's still active. Anyway, any > effort from the list should probably be combined with the snippets archive. > > And then there's a plan I've had in the back of my mind for a while - some > people come here and ask the question "I've read the book and the tutorials, > what now?". Apparently they don't learn programming just to get some job done > or at least with a specific goal in mind. I'd love an archive with case > studies, things to do after the tutorials - make a small programs that > downloads comics, implement this game, whatever - I don't have ideas right > now but it should be possible to think of plenty of things. > > The site could have an archive of ideas for projects, things that have been > done often but that are useful to learn from. And have hints on where to > start - you need to do this, this and this, and these modules will probably > be useful. And people who have a working implementation can send them in. > That would be a useful resource. > > Of course, I've already spent far too long on my CS study and I'm just > starting my final thesis, there is no way I will volunteer for any of this > in the next half year or so. I need the self protection. > > -- > Remco Gerlich > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://www.python.org/mailman/listinfo/tutor -- Mississippi Python Interest Group http://www.lowerstandard.com/python/mspiggie From sheila@thinkspot.net Mon Jan 8 05:16:35 2001 From: sheila@thinkspot.net (Sheila King) Date: Sun, 07 Jan 2001 21:16:35 -0800 Subject: [Tutor] How to print out multiple lines In-Reply-To: References: <246461A327B@kserver.org> Message-ID: <628FBA29AB@kserver.org> On Sun, 7 Jan 2001 14:05:15 -0800 (PST), Daniel Yoo wrote about Re: [Tutor] How to print out multiple lines: :Hmmm... that's a bug! I needed to add newlines between the :concatentations. I think you should be able to fix this ok. : :Hope this helps! Yes, thanks very much. It helped a great deal. Here is my final code: ----------------------------------------------------------- import smtplib def readManyLines(): """Read lines from the user until they enter a line with a single period, and return a single string.""" result = "" while 1: line = raw_input() if line == '.': return result result = result + line + "\n" servername=raw_input("SMTP server name: ") Fromaddress=raw_input("From address: ") Toaddress=raw_input("To address: ") print "Enter your message. To end, enter a line that begins with a" print "period and has no other characters: " MessageText=readManyLines() server=smtplib.SMTP(servername) server.sendmail(Fromaddress, Toaddress, MessageText) server.quit() -------------------------------------------------------------- I was able to run that on a DOS prompt, and send out e-mails with it. Great. Now I'm getting ready to start working with input from files. My goal is to write some mail filtering scripts to use on my web hosting site, to automatically forward certain e-mails to Spamcop.net. (When I get this figured out, I'm planning to get an account with them.) I have other projects up my sleeve, too. But that's the first one. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From rob@jam.rr.com Mon Jan 8 05:54:30 2001 From: rob@jam.rr.com (R. A.) Date: Sun, 07 Jan 2001 23:54:30 -0600 Subject: [tutor] example code References: <01010710215300.00622@localhost.localdomain> <3A59074F.29A34DC0@irtc.net> <20010108010856.A1917@pino.selwerd.nl> <3A594E20.258604E8@jam.rr.com> Message-ID: <3A595616.383A6522@jam.rr.com> Aw, heck, I went ahead and made a starter page: http://www.lowerstandard.com/python/pythonsource.html Rob A. "R. A." wrote: > > We could also come up with a CGI form people could use to submit code > (personal info, filename, source code, commentary, etc.) and simplify > maintenance. In the meantime, feel free to send any scripts ready to > post to me privately, or post to the list (as long as it doesn't anger > the gods and fierce rabbits). > > Also, if anyone has posted a question to the list that they felt they > really got some great answers to, feel free to put it together and send > it along. Just remember to provide the code (well-commented code is > super fine) along with any notes on how to make it work and who you > think deserves a little credit. I'd be happy to get some initial items > posted while we work out other details. And remember to let me know if > you have a site I can link to. > > The whole idea seems useful also as a way to put up example answers to > FAQs here on the list. And why not have items such as a ROT-13 encoding > script right next to it and a few *Stupid XML Tricks* that show people > how to do things that prove to be simple enough if you happen to already > know how to do them. > > Rob Andrews > > Remco Gerlich wrote: > > > > On Sun, Jan 07, 2001 at 06:18:23PM -0600, Tesla Coil wrote: > > > On 7 Jan 2001, John Murray wrote: > > > > Emailing source directly to the site would probably > > > > be easiest, in view of the small size of most scripts, > > > > > > Were the source posted to a list, the site could just > > > draw directly from it, become a "best of" collection. > > > Other site maintainers could do the same thing, with > > > their different idea of what "best of" means. > > > > (I've missed most of the previous discussion, I hope my points weren't > > discussed to death yet). > > > > I think that's quite a lot of work for a maintainer. Read the daily posts, > > judge what is suitable for the site, and turn the post into some sort of > > format that's usable (like a web page). The sort of job that you might find > > a volunteer for, but I wouldn't be surprised if it doesn't last for long. > > > > Also, there is already the Python snippets archive (although I currently > > can't locate the URL - recently erased the bookmarks file and Parnassus' > > find function is bugging). I'm not sure if it's still active. Anyway, any > > effort from the list should probably be combined with the snippets archive. > > > > And then there's a plan I've had in the back of my mind for a while - some > > people come here and ask the question "I've read the book and the tutorials, > > what now?". Apparently they don't learn programming just to get some job done > > or at least with a specific goal in mind. I'd love an archive with case > > studies, things to do after the tutorials - make a small programs that > > downloads comics, implement this game, whatever - I don't have ideas right > > now but it should be possible to think of plenty of things. > > > > The site could have an archive of ideas for projects, things that have been > > done often but that are useful to learn from. And have hints on where to > > start - you need to do this, this and this, and these modules will probably > > be useful. And people who have a working implementation can send them in. > > That would be a useful resource. > > > > Of course, I've already spent far too long on my CS study and I'm just > > starting my final thesis, there is no way I will volunteer for any of this > > in the next half year or so. I need the self protection. > > > > -- > > Remco Gerlich > > > > _______________________________________________ > > Tutor maillist - Tutor@python.org > > http://www.python.org/mailman/listinfo/tutor > > -- > Mississippi Python Interest Group > http://www.lowerstandard.com/python/mspiggie > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://www.python.org/mailman/listinfo/tutor -- Mississippi Python Interest Group http://www.lowerstandard.com/python/mspiggie From pursang@interact.net.au Mon Jan 8 09:36:26 2001 From: pursang@interact.net.au (John Murray) Date: Mon, 8 Jan 2001 20:36:26 +1100 Subject: [tutor] example code In-Reply-To: <3A595616.383A6522@jam.rr.com> References: <01010710215300.00622@localhost.localdomain> <3A594E20.258604E8@jam.rr.com> <3A595616.383A6522@jam.rr.com> Message-ID: <01010820423200.00668@localhost.localdomain> On Mon, 08 Jan 2001, you wrote: > Aw, heck, I went ahead and made a starter page: > > http://www.lowerstandard.com/python/pythonsource.html > Rob, I just took a the useless python page and I think it's perfect!!! Hope it soon fills with silly scripts. Cheers, Johnno From alan.gauld@bt.com Mon Jan 8 13:09:04 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 8 Jan 2001 13:09:04 -0000 Subject: [Tutor] New to Python and programming and need suggestion Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D4B2@mbtlipnt02.btlabs.bt.co.uk> Its lunch time, so here's a reply. > Hello, I'm new to programming and python (just bought Learn to > Program Using Python by Alan Gauld, I'm on ch 14). First of all, thanks :-) I hope you have seen the support web page: http://www.crosswinds.net/~agauld/book/ I'm still adding errata as I go thru' the book myself. > 1. There is a text file that I want to monitor for > certain key words, it is organized by date time msg. > The msg can be more than one word, and each date time > msg is on a seperate line. Up to here you should have enough from the book to tackle this bit. > There are several > computers that need to be monitored in this way. This is more advanced and depends on things like whether you can see the files on the other computers as if they were local(ie via NFS or SMB etc) and what operating systems/networks are involved. > 2. For the lines with those keywords I'd like to > have them uploaded onto a database running on a server. That's not in the book so you will need to either buy a more advanced book or dig around on the Python web site. There is a lot of intro material there, it does depend a little bit on the database but for what you want there shouldn't be a problem. There is a generic API that will work with most of the different database modules. In turn Python modules exist for accessing most of the common databases. Of course if the volumes are not going to be enormous you might find that simply creating a text file suffices... It's surprising how much can be done with simple textfiles if you don't need to do sophisticated extracts. > 3. I'd like people on the LAN to be able to look on a > intranet page and access the data on the database, > visually and if they need more detail with text. Ok, This is the realm of CGI/ASP programming which is mentioned but not explained in the book. There are several guides/intros on the Python web site. > maybe there is another way to monitor text files > remotly with a web page other than using a database > as an in-between? Yes, you could simply have the CGI program read the original log files or an extracted text file you create (as mentioned above). The great thing about this approach is that with a very little thought you can create a module of functions that can do the reading/writing and import it for use in solving both both (1) and (3). This will however, depend on your web server having access to the machines with the log files and arranging that the CGI programs themselves also have access - this usually involves your sys admin setting up an access control list or similar. > having data sent to the database, > and how to access the info with a web page. Both topics have guides on the Python site, I'd try looking there first. Several of the more advanced Python books also have chapters on this. > I'm assuming it can be done with python and some other tools, It can most certainly be done in Python. I'd try reading a single log file first, and write the entries to a simple textbfile initially. Then try the CGI stuff because thats a fairly easy jump from what you know. Once you have that working try accessing the other machines and merging the data. Either by running multiple copies of your first program - one per machine or by reading the files over the network. [This shouldn't change the CGI web app at all.] Finally, if performance is poor, explore the database topic, but you will need to learn a bit of SQL if you don't know it already. Thats in addition to how to access the data via Python.... I found the following article on databases useful as a starter (its linked to the Topic on the Python site): http://www.amk.ca/python/writing/DB-API.html Other replies have been more specific but I'd go visit the Topic Guides on the web site first then come back to the mail messages after reading them. This list is always here for specific problems too. Good luck, Alan g. From alan.gauld@bt.com Mon Jan 8 13:12:44 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 8 Jan 2001 13:12:44 -0000 Subject: [Tutor] Wesley's book Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D4B3@mbtlipnt02.btlabs.bt.co.uk> For once I'm not promoting my own book ;-) I just saw Wesley Chun's new book in my local bookshop. Very impressive Wesley, nice work. I will probably buy it after my finances recover from their current state of impoverishment! Congrats, Alan G. From alan.gauld@bt.com Mon Jan 8 13:15:36 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 8 Jan 2001 13:15:36 -0000 Subject: [Tutor] setting object to None doesn't kill Word Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D4B4@mbtlipnt02.btlabs.bt.co.uk> > > Does Mark Hammond answer such question directly, I haven't tried directly but he certainly follows the comnp.lang.python newsgroup and posts answers to things nobody else knows :-) > sure there's someone out there with COM experience. Lots, its a regular topic on the newsgroup. > You might also check with your bookstore for "Python > Programming on Win32" by Mark Hammond and Andy Robinson. Absolutely essential for COM work. Without it you will struggle. Alan G. From rob@jam.rr.com Mon Jan 8 13:34:50 2001 From: rob@jam.rr.com (R. A.) Date: Mon, 08 Jan 2001 07:34:50 -0600 Subject: [Tutor] problems with website Message-ID: <3A59C1FA.94453804@jam.rr.com> For some reason I don't have time to figure out without becoming later for work than I already am, the main server is giving me problems this morning. The backup site to see what I've done so far is: http://home.jam.rr.com/mspiggie/pythonsource.html This is in reference to the Useless Python page. Rob -- Mississippi Python Interest Group http://www.lowerstandard.com/python/mspiggie From kalle@gnupung.net Mon Jan 8 19:03:39 2001 From: kalle@gnupung.net (Kalle Svensson) Date: Mon, 8 Jan 2001 20:03:39 +0100 Subject: [Tutor] strange recursion result In-Reply-To: ; from mbc2@netdoor.com on Sun, Jan 07, 2001 at 04:01:30PM -0600 References: Message-ID: <20010108200339.B2695@apone.network.loc> --f2QGlHpHGjS2mn6Y Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable Sez mbc2@netdoor.com: > I wrote a short little program to perform a recursive calculation for me. [snip] > I must be missing something simple, but I don't see it. Does anyone have > any suggestions? As others have said, you are probably hitting the recursion limit. Which version of Python are you using? If you are using 2.0 (the latest), try sys.setrecursionlimit(). It is documented on http://www.python.org/doc/current/lib/module-sys.html Otherwise, you were just about to upgrade anyway, right? HTH, Kalle --=20 Email: kalle@gnupung.net | You can tune a filesystem, but you Web: http://www.gnupung.net/ | can't tune a fish. -- man tunefs(8) PGP fingerprint: 0C56 B171 8159 327F 1824 F5DE 74D7 80D7 BF3B B1DD --f2QGlHpHGjS2mn6Y Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.4 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE6Wg8LdNeA1787sd0RAp4PAKCEOXQmHAlaaWrghukugVYU7tiE9ACgwGcJ ApAiygp32qNcTPSQDZRfY74= =N5S7 -----END PGP SIGNATURE----- --f2QGlHpHGjS2mn6Y-- From dsh8290@rit.edu Mon Jan 8 14:52:56 2001 From: dsh8290@rit.edu (D-Man) Date: Mon, 8 Jan 2001 09:52:56 -0500 Subject: [Tutor] strange recursion result In-Reply-To: ; from dyoo@hkn.eecs.berkeley.edu on Sun, Jan 07, 2001 at 02:22:48PM -0800 References: Message-ID: <20010108095256.A2693@rit.edu> On Sun, Jan 07, 2001 at 02:22:48PM -0800, Daniel Yoo wrote: | On Sun, 7 Jan 2001 mbc2@netdoor.com wrote: | [snip] | You probably got the following message: | | ### | RuntimeError: Maximum recursion depth exceeded | ### | | which means that it just hit its limits. The Python implementors are | probably planning to support recursion to arbitrary depths in the future, | but this hasn't been done yet. | | Are you coming from a Scheme background? Since Scheme's only iteration | consists of recursion, the implementors of Scheme made extra sure that | they didn't impose limits to recursion. Python, on the other hand, does Actually, Scheme does include a loop construct. (but it might, not, I might be confusing it with Common Lisp) Scheme doesn't have a recursion limit iff the fuction(s) are tail-recursive. The posted python function was not tail recursive, so it wouldn't have that optimization. Python doesn't do any tail-recursion optimization. | recursive-like stuff with for/while loops, so it's a bit less functional | in terms of recursion. | [snip] | Apologies: it feels like a disappointing answer to say "It won't work | yet"; does anyone have any suggestions or comments? | You could try Stackless Python. The recursion limit in (normal) Python comes from the python stack being intertwined with the C stack and the C stack has a limit. Stackless Python separates the stacks so that the C stack can be unwound before the Python stack is. This allows the python stack to be "inifinite" (until the machines memory is used up). I'd like to see python do tail-recursion optimizations, but I don't actually use recursion very often anyways. -D From fred@petlab.ptech.okstate.edu Mon Jan 8 20:04:50 2001 From: fred@petlab.ptech.okstate.edu (Fred Schroeder) Date: Mon, 08 Jan 2001 14:04:50 -0600 Subject: [Tutor] How to set up comboboxes Message-ID: <00d401c079ae$422400a0$16494e8b@okstate.edu> Hi! I have a question on setting up comboboxes, or listboxes with Tkinter. In my program, I want the user to select one of the fifty states in combo1, and based on this, select a city from combo2, armed with this information, the program will open an ascii datafile for the location. There will be about 10 cities for each state, is there a better way to specify what should show up in combo2 than 50 if statements? Also, how do I set the comboboxes so that the user can not enter information into them. TIA Fred From dsh8290@rit.edu Mon Jan 8 15:30:30 2001 From: dsh8290@rit.edu (D-Man) Date: Mon, 8 Jan 2001 10:30:30 -0500 Subject: [Tutor] How to set up comboboxes In-Reply-To: <00d401c079ae$422400a0$16494e8b@okstate.edu>; from fred@petlab.ptech.okstate.edu on Mon, Jan 08, 2001 at 02:04:50PM -0600 References: <00d401c079ae$422400a0$16494e8b@okstate.edu> Message-ID: <20010108103030.A2957@rit.edu> My recommendation would be to build a couple of arrays (lists) with all the data. Have 1 list with the states, and each state has an index. Have a second list that can be indexed by state (umm, actually, just use a dictionary -- this is python, not C after all). This dicitionary can hold a list of cities as the value. Then you can have a nice little loop to put those cities into the combo-box. HTH, -D On Mon, Jan 08, 2001 at 02:04:50PM -0600, Fred Schroeder wrote: | Hi! | I have a question on setting up comboboxes, or listboxes with Tkinter. | In my program, I want the user to select one of the fifty states in combo1, | and based on this, select a city from combo2, armed with this information, | the program will open an ascii datafile for the location. There will be | about 10 cities for each state, is there a better way to specify what should | show up in combo2 than 50 if statements? Also, how do I set the comboboxes | so that the user can not enter information into them. | TIA | Fred | | | _______________________________________________ | Tutor maillist - Tutor@python.org | http://www.python.org/mailman/listinfo/tutor From sheila@thinkspot.net Mon Jan 8 21:04:14 2001 From: sheila@thinkspot.net (Sheila King) Date: Mon, 08 Jan 2001 13:04:14 -0800 Subject: [Tutor] Questions about stdin, stdout, lists and tuples Message-ID: <3B4B6584E5C@kserver.org> Python newbie, here. I come from a C++/Pascal/VB type of background. My first goal is to write some mail filtering scripts in Python to manage my e-mail spam. My e-mail scripts will be fed the incoming e-mail on stdin and I have to write my e-mails to stdout if I want them to be delivered through my MTA. I have a couple of questions I want to ask, just to make sure I'm understanding things clearly: Here is a short practice script I just wrote: ----------------------------------------- import sys line = sys.stdin.readline() print line ----------------------------------------- It reads a single line from stdin and prints it to stdout. My understanding, is that this is equivalent to the C++ program: ---------------------------------------- #include #include int main() { string line; getline(cin,line); cout << line; return 0; } ---------------------------------------- If anyone would like to confirm/deny/comment on my conclusions about stdin/stdout, I would be interested. Am I overlooking any Python peculiarities (such as the difference between "input" and "raw_input" or something along those lines.)? Also, lists are like arrays, because I can reassign their values (they are not immutable), whereas tuples are like const arrays, their values cannot be altered? Have I got that right? -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From tescoil@irtc.net Mon Jan 8 22:20:39 2001 From: tescoil@irtc.net (Tesla Coil) Date: Mon, 08 Jan 2001 16:20:39 -0600 Subject: [Tutor] strange recursion result References: <20010108200339.B2695@apone.network.loc> Message-ID: <3A5A3D37.A49A2EA3@irtc.net> On 8 Jan 2001, Kalle Svensson wrote: > Which version of Python are you using? If you are using 2.0 > (the latest), try sys.setrecursionlimit(). It is documented on > http://www.python.org/doc/current/lib/module-sys.html "The highest possible limit is platform-dependent. A user may need to set the limit higher when she has a program that requires deep recursion and a platform that supports a higher limit. This should be done with care, because a too-high limit can lead to a crash." Okay, how to determine the limit for your platform without a stress test? (fun tho' that may be...) From sheila@thinkspot.net Mon Jan 8 21:25:04 2001 From: sheila@thinkspot.net (Sheila King) Date: Mon, 08 Jan 2001 13:25:04 -0800 Subject: [Tutor] strange recursion result In-Reply-To: <3A5A3D37.A49A2EA3@irtc.net> References: <20010108200339.B2695@apone.network.loc> <3A5A3D37.A49A2EA3@irtc.net> Message-ID: <3C744441450@kserver.org> On Mon, 08 Jan 2001 16:20:39 -0600, Tesla Coil wrote about Re: [Tutor] strange recursion result: :On 8 Jan 2001, Kalle Svensson wrote: :> Which version of Python are you using? If you are using 2.0 :> (the latest), try sys.setrecursionlimit(). It is documented on :> http://www.python.org/doc/current/lib/module-sys.html : :"The highest possible limit is platform-dependent. A user :may need to set the limit higher when she has a program :that requires deep recursion and a platform that supports :a higher limit. This should be done with care, because a :too-high limit can lead to a crash." : :Okay, how to determine the limit for your platform :without a stress test? (fun tho' that may be...) >From the same page, http://www.python.org/doc/current/lib/module-sys.html getrecursionlimit() I tried it out on my IDLE in interactive mode. I don't know what I was doing wrong, but it didn't work for me. Here is my session: Python 1.5.2 (#0, Apr 13 1999, 10:51:12) [MSC 32 bit (Intel)] on win32 Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam >>> import sys >>> print sys.getrecursionlimit() Traceback (innermost last): File "", line 1, in ? print sys.getrecursionlimit() AttributeError: getrecursionlimit >>> What am I doing wrong? (Be nice: newbie, here.) -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From dsh8290@rit.edu Mon Jan 8 16:29:25 2001 From: dsh8290@rit.edu (D-Man) Date: Mon, 8 Jan 2001 11:29:25 -0500 Subject: [Tutor] Questions about stdin, stdout, lists and tuples In-Reply-To: <3B4B6584E5C@kserver.org>; from sheila@thinkspot.net on Mon, Jan 08, 2001 at 01:04:14PM -0800 References: <3B4B6584E5C@kserver.org> Message-ID: <20010108112925.A3285@rit.edu> On Mon, Jan 08, 2001 at 01:04:14PM -0800, Sheila King wrote: | Python newbie, here. I come from a C++/Pascal/VB type of background. | | My first goal is to write some mail filtering scripts in Python to manage my | e-mail spam. My e-mail scripts will be fed the incoming e-mail on stdin and I | have to write my e-mails to stdout if I want them to be delivered through my | MTA. | It would probably be easier to use procmail for this. (Although the syntax for the "recipes" is confusing -- I only use it to put list mail in the right folder) You can probably find some non-warranted recipes on the web somewhere. | I have a couple of questions I want to ask, just to make sure I'm | understanding things clearly: | | Here is a short practice script I just wrote: | | ----------------------------------------- | import sys | line = sys.stdin.readline() | print line | ----------------------------------------- | | It reads a single line from stdin and prints it to stdout. | | My understanding, is that this is equivalent to the C++ program: | ---------------------------------------- | #include | #include | | int main() | { | string line; | getline(cin,line); | cout << line; | return 0; | } | ---------------------------------------- I'm not familiar with the getline() fuction in C++ (I don't recall seeing it in my C++ book, but it would have been useful many times). If I can assume that it will read all characters on cin until it finds a newline and inserts it into the string 'line', then that is the same. To duplicate print, you need to add " << endl " to your 'cout' line. | | If anyone would like to confirm/deny/comment on my conclusions about | stdin/stdout, I would be interested. Am I overlooking any Python peculiarities | (such as the difference between "input" and "raw_input" or something along | those lines.)? Input is (nearly?) equivalent to eval( raw_input() ). It will evaluate the input and return the appropriate object (ie, int, list, string, etc). Raw_input doesn't evaluate the input, but returns the raw string for you to deal with. | | Also, | lists are like arrays, because I can reassign their values (they are not | immutable), whereas tuples are like const arrays, their values cannot be | altered? | | Have I got that right? Lists are like arrays, but much better. They can grow, be sorted, reversed, and you can't overrun your memory bounds! As far as semantics (except for index bounds errors) and syntax they are basically the same. -D From dsh8290@rit.edu Mon Jan 8 16:34:43 2001 From: dsh8290@rit.edu (D-Man) Date: Mon, 8 Jan 2001 11:34:43 -0500 Subject: [Tutor] strange recursion result In-Reply-To: <3C744441450@kserver.org>; from sheila@thinkspot.net on Mon, Jan 08, 2001 at 01:25:04PM -0800 References: <20010108200339.B2695@apone.network.loc> <3A5A3D37.A49A2EA3@irtc.net> <3C744441450@kserver.org> Message-ID: <20010108113443.B3285@rit.edu> On Mon, Jan 08, 2001 at 01:25:04PM -0800, Sheila King wrote: | On Mon, 08 Jan 2001 16:20:39 -0600, Tesla Coil wrote about | Re: [Tutor] strange recursion result: | [snip] | >From the same page, | http://www.python.org/doc/current/lib/module-sys.html | | getrecursionlimit() | | I tried it out on my IDLE in interactive mode. I don't know what I was doing | wrong, but it didn't work for me. | | Here is my session: | | Python 1.5.2 (#0, Apr 13 1999, 10:51:12) [MSC 32 bit (Intel)] on win32 | Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam | >>> import sys | >>> print sys.getrecursionlimit() | Traceback (innermost last): | File "", line 1, in ? | print sys.getrecursionlimit() | AttributeError: getrecursionlimit | >>> | | What am I doing wrong? (Be nice: newbie, here.) Using python 1.5.2 ;-). The documentation you are using on python.org is for the latest relase, 2.0. 2.0 changed some things and added a number of features. getrecursionlimit() is one of them. I recently installed Debian 2.2 which comes with python 1.5.2 and it didn't have the function. RH7.0 is still on my system, so I did a chroot and ran it's python (I had upgraded it to 2.0). It had the function, which gave me 1000. (Intel PII, 64MB RAM) | | -- | Sheila King | http://www.thinkspot.net/sheila/ | http://www.k12groups.org/ | It is probably a good idea to upgrade to 2.0. One of the cool new features is the "+=" operator. If you are going to stick with 1.5.2, I can give you a copy of the 1.5.2 docs. -D From sheila@thinkspot.net Mon Jan 8 21:40:16 2001 From: sheila@thinkspot.net (Sheila King) Date: Mon, 08 Jan 2001 13:40:16 -0800 Subject: [Tutor] Questions about stdin, stdout, lists and tuples In-Reply-To: <20010108112925.A3285@rit.edu> References: <3B4B6584E5C@kserver.org> <20010108112925.A3285@rit.edu> Message-ID: <3D4CF834053@kserver.org> On Mon, 8 Jan 2001 11:29:25 -0500, D-Man wrote about Re: [Tutor] Questions about stdin, stdout, lists and tuples: :On Mon, Jan 08, 2001 at 01:04:14PM -0800, Sheila King wrote: :| Python newbie, here. I come from a C++/Pascal/VB type of background. :| :| My first goal is to write some mail filtering scripts in Python to manage my :| e-mail spam. My e-mail scripts will be fed the incoming e-mail on stdin and I :| have to write my e-mails to stdout if I want them to be delivered through my :| MTA. :| : :It would probably be easier to use procmail for this. (Although the :syntax for the "recipes" is confusing -- I only use it to put list :mail in the right folder) You can probably find some non-warranted :recipes on the web somewhere. Yes, I can't really figure out how to use procmail on my webhost, and believe me, I've tried. My web host is fantastic, but uses a proprietary mail system, and no one has yet figured out how to use procmail, although it is installed. :| I have a couple of questions I want to ask, just to make sure I'm :| understanding things clearly: :| :| Here is a short practice script I just wrote: :| :| ----------------------------------------- :| import sys :| line = sys.stdin.readline() :| print line :| ----------------------------------------- :| :| It reads a single line from stdin and prints it to stdout. :| :| My understanding, is that this is equivalent to the C++ program: :| ---------------------------------------- :| #include :| #include :| :| int main() :| { :| string line; :| getline(cin,line); :| cout << line; :| return 0; :| } :| ---------------------------------------- : :I'm not familiar with the getline() fuction in C++ (I don't recall :seeing it in my C++ book, but it would have been useful many times). :If I can assume that it will read all characters on cin until it finds :a newline and inserts it into the string 'line', then that is the :same. Yes, this is what it does. You need to include string.h for this ability. And it strips the newline character when it does this. :To duplicate print, you need to add " << endl " to your 'cout' line. Ah, thanks. The details like this can really much one up later. :| :| If anyone would like to confirm/deny/comment on my conclusions about :| stdin/stdout, I would be interested. Am I overlooking any Python peculiarities :| (such as the difference between "input" and "raw_input" or something along :| those lines.)? : :Input is (nearly?) equivalent to eval( raw_input() ). It will :evaluate the input and return the appropriate object (ie, int, list, :string, etc). : :Raw_input doesn't evaluate the input, but returns the raw string for :you to deal with. Thanks. Good info. ...... -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From sheila@thinkspot.net Mon Jan 8 21:54:01 2001 From: sheila@thinkspot.net (Sheila King) Date: Mon, 08 Jan 2001 13:54:01 -0800 Subject: [Tutor] strange recursion result In-Reply-To: <20010108113443.B3285@rit.edu> References: <20010108200339.B2695@apone.network.loc> <3A5A3D37.A49A2EA3@irtc.net> <3C744441450@kserver.org> <20010108113443.B3285@rit.edu> Message-ID: <3E13E501DE1@kserver.org> On Mon, 8 Jan 2001 11:34:43 -0500, D-Man wrote about Re: [Tutor] strange recursion result: :On Mon, Jan 08, 2001 at 01:25:04PM -0800, Sheila King wrote: :| >From the same page, :| http://www.python.org/doc/current/lib/module-sys.html :| :| getrecursionlimit() :| :| I tried it out on my IDLE in interactive mode. I don't know what I was doing :| wrong, but it didn't work for me. :| :| Here is my session: :| :| Python 1.5.2 (#0, Apr 13 1999, 10:51:12) [MSC 32 bit (Intel)] on win32 :| Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam :| >>> import sys :| >>> print sys.getrecursionlimit() :| Traceback (innermost last): :| File "", line 1, in ? :| print sys.getrecursionlimit() :| AttributeError: getrecursionlimit :| >>> :| :| What am I doing wrong? (Be nice: newbie, here.) : :Using python 1.5.2 ;-). Ah, thanks. :The documentation you are using on python.org is for the latest :relase, 2.0. 2.0 changed some things and added a number of features. :getrecursionlimit() is one of them. Right. I've gone over the changes between 2.0 and previous versions, but I guess this one didn't stick in my head, or something. Hmm. Or else, it's not noted in the docs. :It is probably a good idea to upgrade to 2.0. One of the cool new :features is the "+=" operator. If you are going to stick with 1.5.2, :I can give you a copy of the 1.5.2 docs. Well, I'm trying to use (close) to the same version as on my webhost. They are running 1.5.1 right now. I asked them to upgrade to 2.0, but they have a lot of other stuff going on right now, and don't want to, yet. (Plus, I guess they are using Python for some of their system scripts, and don't want stuff to "break".) I do have a copy of the 1.52 docs local on my machine. Thanks. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From tescoil@irtc.net Mon Jan 8 23:07:02 2001 From: tescoil@irtc.net (Tesla Coil) Date: Mon, 08 Jan 2001 17:07:02 -0600 Subject: [Tutor] strange recursion result References: <20010108200339.B2695@apone.network.loc> <3A5A3D37.A49A2EA3@irtc.net> <3C744441450@kserver.org> Message-ID: <3A5A4816.C30B43BC@irtc.net> On 08 Jan 2001, Shelia King replied: >> Okay, how to determine the limit for your platform >> without a stress test? (fun tho' that may be...) > > From the same page, > http://www.python.org/doc/current/lib/module-sys.html > > getrecursionlimit() Ah, but see, all that tells you is its current setting... >>> import sys >>> now = sys.getrecursionlimit() >>> print now 1000 >>> sys.setrecursionlimit(999) >>> now = sys.getrecursionlimit() >>> print now 999 I wanna know how to figure out the maximum setting for a specific platform without provoking a crash. Hmm, sys.setrecursionlimit() might be entertaining to use in a recursive function . From sheila@thinkspot.net Mon Jan 8 22:15:01 2001 From: sheila@thinkspot.net (Sheila King) Date: Mon, 08 Jan 2001 14:15:01 -0800 Subject: [Tutor] strange recursion result In-Reply-To: <3A5A4816.C30B43BC@irtc.net> References: <20010108200339.B2695@apone.network.loc> <3A5A3D37.A49A2EA3@irtc.net> <3C744441450@kserver.org> <3A5A4816.C30B43BC@irtc.net> Message-ID: <3F3C4EC39A8@kserver.org> On Mon, 08 Jan 2001 17:07:02 -0600, Tesla Coil wrote about Re: [Tutor] strange recursion result: :On 08 Jan 2001, Shelia King replied: :> From the same page, :> http://www.python.org/doc/current/lib/module-sys.html :> :> getrecursionlimit() : :Ah, but see, all that tells you is its current setting... : :I wanna know how to figure out the maximum setting :for a specific platform without provoking a crash. Oops. Sorry. I misunderstood. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From tim.one@home.com Mon Jan 8 22:33:36 2001 From: tim.one@home.com (Tim Peters) Date: Mon, 8 Jan 2001 17:33:36 -0500 Subject: [Tutor] strange recursion result In-Reply-To: <3A5A4816.C30B43BC@irtc.net> Message-ID: [Tesla Coil] > ... > I wanna know how to figure out the maximum setting > for a specific platform without provoking a crash. If the Python implementers had been able to figure that out, they would have done that internally rather than expose a stupid-ass gimmick like sys.setrecursionlimit() . The saving grace is that idiomatic Python rarely uses recursion heavily, and a recursion limit of 1000 (or so) is *way* more than most programs actually need. > Hmm, sys.setrecursionlimit() might be entertaining > to use in a recursive function . Less fun than you might think, but suit yourself . From dsh8290@rit.edu Mon Jan 8 18:24:28 2001 From: dsh8290@rit.edu (D-Man) Date: Mon, 8 Jan 2001 13:24:28 -0500 Subject: [Tutor] Questions about stdin, stdout, lists and tuples In-Reply-To: <3D4CF834053@kserver.org>; from sheila@thinkspot.net on Mon, Jan 08, 2001 at 01:40:16PM -0800 References: <3B4B6584E5C@kserver.org> <20010108112925.A3285@rit.edu> <3D4CF834053@kserver.org> Message-ID: <20010108132428.B3829@rit.edu> On Mon, Jan 08, 2001 at 01:40:16PM -0800, Sheila King wrote: [snip] | Yes, I can't really figure out how to use procmail on my webhost, and believe | me, I've tried. My web host is fantastic, but uses a proprietary mail system, | and no one has yet figured out how to use procmail, although it is installed. | If it is a Unix box, and if it follows conventions (standards?) you could put "| /usr/bin/procmail" in a file called '.forward' in your home directory. Otherwise enjoy working with python instead ;-). | [snip] | :| ---------------------------------------- | :| #include | :| #include | :| | :| int main() | :| { | :| string line; | :| getline(cin,line); | :| cout << line; | :| return 0; | :| } | :| ---------------------------------------- | : | :I'm not familiar with the getline() fuction in C++ (I don't recall | :seeing it in my C++ book, but it would have been useful many times). | :If I can assume that it will read all characters on cin until it finds | :a newline and inserts it into the string 'line', then that is the | :same. | | Yes, this is what it does. You need to include string.h for this ability. And | it strips the newline character when it does this. | I believe Python's readline() keeps the newline character. I am curious now as to your C++ compiler's environment. #include usually includes a header file that is part of the C standard library and contains only C string manipulation functions. #include will inlclude the C++ standard library's string class declaration. (If the compiler conforms to the ANSI standard of leave the '.h' off of include files) Interesting that you include string.h and get C++ fuctionality from it. (I've tried before but get a "type expected instead of 'string'" error message) -D From mbc2@netdoor.com Mon Jan 8 23:38:24 2001 From: mbc2@netdoor.com (mbc2@netdoor.com) Date: Mon, 8 Jan 2001 17:38:24 -0600 (CST) Subject: [Tutor] strange recursion result In-Reply-To: Message-ID: On Sun, 7 Jan 2001, Daniel Yoo wrote: > probably got the following message: > > ### > RuntimeError: Maximum recursion depth exceeded > ### > > which means that it just hit its limits. The Python implementors are > probably planning to support recursion to arbitrary depths in the future, > but this hasn't been done yet. Well, I didn't get that message but that appears to be what's happening. sys.getrecursionlimit() gives me 1000, which is where the problem started occuring. I'm using Python 2.0 on MkLinux R1. I upgraded to 2.0 soon after it came out, I was anxious to see what was new. So far the only thing I've noticed is the appearance of +=, which I was really glad to see, it just looks cleaner to me. > Are you coming from a Scheme background? Since Scheme's only iteration > consists of recursion, the implementors of Scheme made extra sure that > they didn't impose limits to recursion. Python, on the other hand, does > recursive-like stuff with for/while loops, so it's a bit less functional > in terms of recursion. I don't have much of a programming background, the first thing I tried to learn was C++, which I found to be impractical for the types of things I want to do. Then came PHP, which is great, but seemed limited to web pages (yeah I know it can be used for shell scripting too). Then after reading Phillip Greenspun's book, I looked at TCL. It was about that time that I started hearing alot of good things about python (Linux Journal had a special issue about it). The whitespace thing and the strange for statements initially turned me off, but after I started using python, I quickly found that those were big advantages and I really like it now. My only wish now is that I could use python like I use PHP, on a web page inside tags like (ie. non-cgi). Unless I've overlooked something, I don't think that's possible. > ### > for i in range(n): > sum = sum + i > ### That actually works alot better since its not limited by the recursion limit and its also easier to understand. I think I was making things more difficult by using recursion, although I'm glad to find out about the limit, I might need to know that some day. Brad From dyoo@hkn.eecs.berkeley.edu Mon Jan 8 23:41:11 2001 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Mon, 8 Jan 2001 15:41:11 -0800 (PST) Subject: [Tutor] Questions about stdin, stdout, lists and tuples In-Reply-To: <20010108112925.A3285@rit.edu> Message-ID: On Mon, 8 Jan 2001, D-Man wrote: > | Also, > | lists are like arrays, because I can reassign their values (they are not > | immutable), whereas tuples are like const arrays, their values cannot be > | altered? > | > | Have I got that right? > > Lists are like arrays, but much better. They can grow, be sorted, > reversed, and you can't overrun your memory bounds! > > As far as semantics (except for index bounds errors) and syntax they > are basically the same. One thing that tuples can do that lists can't is act as dictionary keys. For example, since Python knows that tuples are immutable: city_distances = {} city_distances[ ('los angeles', 'san francisco') ] = 384 will work. However, city_distances[ ['los angeles', 'san francisco'] ] = 384 won't. More technically, Python can calculate hash numbers from tuples, but not lists: ### >>> mytuple = (1, 2) >>> mylist = [1, 2] >>> hash(mytuple) 219750523 >>> hash(mylist) Traceback (innermost last): File "", line 1, in ? TypeError: unhashable type ### and that's why they can't be used as keys. Hope that makes some sort of sense... *grin* From dsh8290@rit.edu Mon Jan 8 19:40:20 2001 From: dsh8290@rit.edu (D-Man) Date: Mon, 8 Jan 2001 14:40:20 -0500 Subject: [Tutor] strange recursion result In-Reply-To: ; from mbc2@netdoor.com on Mon, Jan 08, 2001 at 05:38:24PM -0600 References: Message-ID: <20010108144020.H4159@rit.edu> On Mon, Jan 08, 2001 at 05:38:24PM -0600, mbc2@netdoor.com wrote: | My only wish now is that I could use python like I use PHP, on a web | page inside tags like (ie. non-cgi). Unless I've overlooked | something, I don't think that's possible. | Try Poor Man's Zope : pmz.sourceforge.net or PyHTML (I don't remember the URL off the top of my head). Poor Man's Zope is a python cgi script that will allow you to embed python code inside tags in your HTML. PyHTML applies the Python principle of indentation and no closing "braces" (tags) while allowing embedded python. I like the look of PyHTML, but it looks more complicated to install than pmz. Maybe I'll get around to it someday. (Probably when I get my web site together). -D From amoreira@mercury.ubi.pt Tue Jan 9 15:34:50 2001 From: amoreira@mercury.ubi.pt (Jose Amoreira) Date: Tue, 09 Jan 2001 15:34:50 +0000 Subject: [Tutor] Tkinter question Message-ID: <3A5B2F9A.564B7F3@mercury.ubi.pt> Hello! I'm not able to get information on the size of a widget using its cget method. For instance: ------------------------------------------ >>> r=Frame(None,height=300) >>> r.pack() >>> r=Frame(None,height=300,width=100) >>> r.pack() >>> r.cget('height') '300' >>> r.cget('width') '100' ------------------------------------------ So far, so good. But if we now resize the frame widget via the window manager, by dragging its border with the mouse, the changes are not updated in the widget's attributes (even if we call r.update()), and further querries with cget don't show the modifications. How can we get the value of these attributes? To be more specific, what I'd really need is a method to determine the number of visible lines in an expandable tkinter listbox, to handle keyboard events. I managed to get the height of the listbox in pixels using winfo methods, but the relation of this number to the number of visible lines depends on the font used, and probably on the border size, etc. Thanks for any help! ze amoreira@mercury.ubi.pt From alan.gauld@bt.com Tue Jan 9 17:46:17 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue, 9 Jan 2001 17:46:17 -0000 Subject: [Tutor] strange recursion result Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D4B9@mbtlipnt02.btlabs.bt.co.uk> > only wish now is that I could use python like I use > PHP, on a web page inside tags like (ie. non-cgi). You want PSP - Python Server Pages. Modelled on Microsoft's ASP (or Suns JSP) but using a slightly different delimiter. There was an article on them on Dr Dobbs Journal a year or so back - try searching their site? Also on Windoze you can use vanilla ASP via the win32all package and its Active Scripting support. But I don't know of any documentation and the Python indentation restrictions can cause some problems apparently when mixing code and HTML text. Finally you should look at Zope which is a much bigger solution - a full web development environment built around Python. The documentation for this is quite fulsome which is just as well since the mode of operation is quite different to PHP etc.. Alan g. From mbc2@netdoor.com Tue Jan 9 23:06:12 2001 From: mbc2@netdoor.com (Brad Chandler) Date: Tue, 9 Jan 2001 17:06:12 -0600 Subject: [Tutor] Question on rounding Message-ID: <000701c07a90$c30778e0$111c0d0a@spb.state.ms.us> I know this must have been discussed before, but I'm having a problem with rounding. My hand calculator gives me the following: 25350 * .0055 = 139.425 But Python gives me 139.42499999999998. Now what I want is to round that up to 139.43, so I've been using round(x,2). But my numbers have been slightly off in python and I've just now discovered why. I think I can just use round(x,3) and then round(x,2) to get the desired result, but that just seems messy and I'm wondering if there is a better, more correct way of doing it. Below is an example of my interpreter session. >>> x=25350.00*.0055 >>> x 139.42499999999998 >>> round(x,2) 139.41999999999999 >>> y = round(x,3) >>> y 139.42500000000001 >>> round(y,2) 139.43000000000001 From tbrauch@mindless.com Tue Jan 9 23:43:15 2001 From: tbrauch@mindless.com (Timothy M. Brauch) Date: Tue, 09 Jan 2001 18:43:15 -0500 Subject: [Tutor] 1.5.2 vs 2.0 Message-ID: <3A5BA213.23329627@mindless.com> I am running Python 1.5.2 right now. I have been thinking of changing to 2.0. I have it downloaded already. But, I have questions about the change. Will I still have all my modules, even the ones I've created or downloaded from elsewhere? Should I move these before I do the new install and then put them back afterwards, or will they be okay where they are? I am running Windows 98 with Python 1.5.2 right now, will I have to make any changes after installing 2.0 (such as to the autoexec file)? Is there much difference between 1.5.2 and 2.0, anything that I might notice or strugle with at first? - Tim From rob@jam.rr.com Wed Jan 10 00:06:12 2001 From: rob@jam.rr.com (R. A.) Date: Tue, 09 Jan 2001 18:06:12 -0600 Subject: [Tutor] 1.5.2 vs 2.0 References: <3A5BA213.23329627@mindless.com> Message-ID: <3A5BA774.FD5EEEB3@jam.rr.com> What to watch for depends in part on where you keep your modules. If you have been keeping them in the same directory as your Python 1.5.2 install, you might consider setting aside a folder just for such scripts. Then make sure you have the path to that directory in your autoexec file. That way, any time you upgrade, you shouldn't have to worry about that problem. You might want to uninstall 1.5.2 before installing 2.0 just to make sure any other surprises don't find you, by the way. I haven't noticed anything about 2.0 that should cause struggle. The scripts you wrote for 1.5.2 should all run just fine, and 2.0 adds a few niceties to boot. Got any nice useless scripts to contribute to the Useless Python Project, btw? ;-) Rob Andrews "Timothy M. Brauch" wrote: > > I am running Python 1.5.2 right now. I have been thinking of changing > to 2.0. I have it downloaded already. But, I have questions about the > change. > > Will I still have all my modules, even the ones I've created or > downloaded from elsewhere? > > Should I move these before I do the new install and then put them back > afterwards, or will they be okay where they are? > > I am running Windows 98 with Python 1.5.2 right now, will I have to make > any changes after installing 2.0 (such as to the autoexec file)? > > Is there much difference between 1.5.2 and 2.0, anything that I might > notice or strugle with at first? > > - Tim > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://www.python.org/mailman/listinfo/tutor -- Visit the Useless Python Repository! http://www.lowerstandard.com/python/pythonsource.html From mr804@users.757.org Wed Jan 10 00:08:46 2001 From: mr804@users.757.org (Mr 804) Date: Tue, 9 Jan 2001 19:08:46 -0500 (EST) Subject: [Tutor] string handling In-Reply-To: <3A5BA774.FD5EEEB3@jam.rr.com> Message-ID: Anyone got a howto or something with lots of examples on string handling? ie matching strings from a file you've just read, etc? From tescoil@irtc.net Wed Jan 10 01:44:36 2001 From: tescoil@irtc.net (Tesla Coil) Date: Tue, 09 Jan 2001 19:44:36 -0600 Subject: [Tutor] string handling References: Message-ID: <3A5BBE84.A1D34F04@irtc.net> On 9 Jan 2001, Mr 804 wrote: > Anyone got a howto or something with lots of examples on string > handling? ie matching strings from a file you've just read, etc? Andrew Kuchling's "Regular Expression HOWTO" is very useful... http://www.python.org/doc/howto/regex/regex.html From genius@idirect.com Wed Jan 10 01:28:23 2001 From: genius@idirect.com (Charles Takacs) Date: Tue, 09 Jan 2001 20:28:23 -0500 Subject: [Tutor] 1.5.2 vs 2.0 References: <3A5BA213.23329627@mindless.com> Message-ID: <3A5BBAB7.50D8B4FB@idirect.com> "Timothy M. Brauch" wrote: > > I am running Python 1.5.2 right now. I have been thinking of changing > to 2.0. I have it downloaded already. But, I have questions about the > change. > > Will I still have all my modules, even the ones I've created or > downloaded from elsewhere? > > Should I move these before I do the new install and then put them back > afterwards, or will they be okay where they are? > > I am running Windows 98 with Python 1.5.2 right now, will I have to make > any changes after installing 2.0 (such as to the autoexec file)? > > Is there much difference between 1.5.2 and 2.0, anything that I might > notice or strugle with at first? > > - Tim > I heard that the Snake in it is frienlier, but the bite of it is still OuCh :-)) Charles From sheila@thinkspot.net Wed Jan 10 01:55:00 2001 From: sheila@thinkspot.net (Sheila King) Date: Tue, 09 Jan 2001 17:55:00 -0800 Subject: [Tutor] Question on rounding In-Reply-To: <000701c07a90$c30778e0$111c0d0a@spb.state.ms.us> References: <000701c07a90$c30778e0$111c0d0a@spb.state.ms.us> Message-ID: <571FADF7D29@kserver.org> If you really want exact values, you would need to work with some sort of rational number class, that used integer types for its data members. Any time you do floating type arithmetic, your answers will be subject to a "machine error" that is equal to the "machine precision", which would be the smallest possible number that can be represented on the machine (obviously, limited by the size of the memory devoted to remembering each floating point number). What, exactly, are you trying to do? What is the purpose or point of these computations? -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ On Tue, 9 Jan 2001 17:06:12 -0600, "Brad Chandler" wrote about [Tutor] Question on rounding: :I know this must have been discussed before, but I'm having a problem with :rounding. My hand calculator gives me the following: 25350 * .0055 = :139.425 : :But Python gives me 139.42499999999998. Now what I want is to round that up :to 139.43, so I've been using round(x,2). But my numbers have been slightly :off in python and I've just now discovered why. I think I can just use :round(x,3) and then round(x,2) to get the desired result, but that just :seems messy and I'm wondering if there is a better, more correct way of :doing it. Below is an example of my interpreter session. : :>>> x=25350.00*.0055 :>>> x :139.42499999999998 :>>> round(x,2) :139.41999999999999 :>>> y = round(x,3) :>>> y :139.42500000000001 :>>> round(y,2) :139.43000000000001 : : : :_______________________________________________ :Tutor maillist - Tutor@python.org :http://www.python.org/mailman/listinfo/tutor From tim.one@home.com Wed Jan 10 06:14:12 2001 From: tim.one@home.com (Tim Peters) Date: Wed, 10 Jan 2001 01:14:12 -0500 Subject: [Tutor] Question on rounding In-Reply-To: <000701c07a90$c30778e0$111c0d0a@spb.state.ms.us> Message-ID: [Brad Chandler] > I know this must have been discussed before, Actually, it's been discussed a lot since binary computers first came into use by "real people" in the middle of the last century! > but I'm having a problem with rounding. My hand calculator gives > me the following: 25350 * .0055 = 139.425 Yup. Your calculator uses decimal arithmetic. Almost all computers use binary arithmetic instead, and most decimal real numbers can't be represented exactly in binary format. There's a detailed example here: http://www.python.org/cgi-bin/moinmoin/RepresentationError but you may find it hard to understand. In part that's because it simply doesn't have an easy answer. The odd truth is that 139.425 cannot be exactly represented in binary at all. This is similar to that your calculator can't represent 1/3 exactly. That's because 0.333333333333333... necessarily loses some information if you cut it off after any finite number of digits. For example, on an 8-digit calculator the closest you can get is 0.33333333 and while that's *close* to 1/3, it's not 1/3 exactly. When you're expecting 139.425 but getting things like 139.42499999999998 or 139.42500000000001 instead, the same thing is happening except in a different base: they can't be represented exactly in base 2, but you can get *close* in base 2. This isn't unique to Python, by the way. It's the same story in any language that uses all the "floating point" hardware you paid for . From alan.gauld@bt.com Wed Jan 10 12:44:44 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 10 Jan 2001 12:44:44 -0000 Subject: [Tutor] informIT Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D4BF@mbtlipnt02.btlabs.bt.co.uk> Blowing my own trumpet again, but I have a series of articles on the informIT web site this week. Mainly they deal with my day job of design and integration issues but there is one article extracted from my book: an intro to regular expressions in Python that might be of interest to this forum. http://www.informit.com/ Alan G. PS. If you look hard you can even find a picture of me - aargh!! From NHYTRO@compuserve.com Wed Jan 10 12:51:05 2001 From: NHYTRO@compuserve.com (Sharriff Aina) Date: Wed, 10 Jan 2001 07:51:05 -0500 Subject: [Tutor] Tutor digest, Vol 1 #539 - 13 msgs Message-ID: <200101100751_MC2-C145-E9FC@compuserve.com> Hi! Can someone explain exactly why I have to add "self" to a class function that I=B4ve defined? class blah: "the new class" def myfunction(self): print "Hello Class" the below code would not work: class blah: "the new class" def myfunction(): print "Hello Class" Thanks for your anticipated help Sharriff From scarblac@pino.selwerd.nl Wed Jan 10 13:09:59 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Wed, 10 Jan 2001 14:09:59 +0100 Subject: [Tutor] Tutor digest, Vol 1 #539 - 13 msgs In-Reply-To: <200101100751_MC2-C145-E9FC@compuserve.com>; from NHYTRO@compuserve.com on Wed, Jan 10, 2001 at 07:51:05AM -0500 References: <200101100751_MC2-C145-E9FC@compuserve.com> Message-ID: <20010110140959.A5798@pino.selwerd.nl> On Wed, Jan 10, 2001 at 07:51:05AM -0500, Sharriff Aina wrote: > Can someone explain exactly why I have to add "self" to a class function > that I´ve defined? > > class blah: > "the new class" > def myfunction(self): > print "Hello Class" > > the below code would not work: > > > class blah: > "the new class" > def myfunction(): > print "Hello Class" That's the way it works in Python. Methods get the instance they belong to as their 1st argument, so that they can reach its variables. class blah: def __init__(self): self.name = "bla" The init function uses the 'self' argument to set the variable 'name' in this instance. The name 'self' is not mandatory, but everybody uses it so you should as well :). Pure *class functions*, functions in a class not belonging to any instance, do not exist in Python. The convention is to make them normal functions, outside the class. It can be argued that when a class function does something that's not tied to any instance of the class, then it shouldn't be in that class at all. -- Remco Gerlich From NHYTRO@compuserve.com Wed Jan 10 21:08:24 2001 From: NHYTRO@compuserve.com (Sharriff Aina) Date: Wed, 10 Jan 2001 16:08:24 -0500 Subject: [Tutor] Gadfly tutorials Message-ID: <200101101608_MC2-C152-D275@compuserve.com> I would like to use gadfly to store URLs and headlines on a Newspaper li= ke Web-Site, can anyone point me to tutorials, or show me a snippet of code?= Zope is not a question since I=B4m writing my own CGI scripts. I would li= ke to present the Headlines and links automatically. Best regards Sharriff P:S thank you guys for the help with the "self" thing. = From dyoo@hkn.eecs.berkeley.edu Thu Jan 11 01:55:16 2001 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Wed, 10 Jan 2001 17:55:16 -0800 (PST) Subject: [Tutor] Gadfly tutorials In-Reply-To: <200101101608_MC2-C152-D275@compuserve.com> Message-ID: On Wed, 10 Jan 2001, Sharriff Aina wrote: > I would like to use gadfly to store URLs and headlines on a Newspaper li= ke > Web-Site, can anyone point me to tutorials, or show me a snippet of code? > Zope is not a question since I=B4m writing my own CGI scripts. I would li= ke > to present the Headlines and links automatically. To tell the truth, I don't know much at all about Gadfly. However, I found a good link: http://www.chordate.com/kwParsing/gadfly.html that has some samples that should help you get started. It sounds like you'll be making a CGI that makes a web page dynamically. = =20 You might want to start off simple --- you might want to use a text file as your initial "database", just to see that things are working. After you're happy with everything else, you should be able to switch the text file with a real database. Good luck! From dyoo@hkn.eecs.berkeley.edu Thu Jan 11 07:45:47 2001 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Wed, 10 Jan 2001 23:45:47 -0800 (PST) Subject: [Tutor] [Edu-sig] collection of ACM programming problems (fwd) Message-ID: >From the edu-sig list, Furman Smith mentioned a very nice site filled with sample problems. These problems are pretty neat, and I thought it might be fun to work some of them out. No time pressure or anything; just to see what strategies different people choose. Problem 136 in Volume One asks to write a program that finds the 1500th "ugly" number. http://acm.fi.uva.es/problemset/v1/136.html *grin* I think I'll try it out, and see how far I get. ---------- Forwarded message ---------- Date: Wed, 10 Jan 2001 21:25:33 -0600 (CST) From: Furman Smith To: edu-sig@python.org Subject: [Edu-sig] collection of ACM programming problems Jeffrey Elkner wrote that he wanted a perfect case study to add to his free content textbook "How to think like a computer scientist" ( http://www.ibiblio.org/obp/thinkCSpy/ ) -- something instructive, easy to understand, fun, and illustrating the programming ideas introduced earlier in the book. "Perfect" is a strong word but please allow me to mention that I've enjoyed reading some of the archived problems from the ACM International Collegiate Programming Contests; links to the various volumes of problems can be found at http://acm.fi.uva.es/problemset/ . From scarblac@pino.selwerd.nl Thu Jan 11 09:26:28 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Thu, 11 Jan 2001 10:26:28 +0100 Subject: [Tutor] [Edu-sig] collection of ACM programming problems (fwd) In-Reply-To: ; from dyoo@hkn.eecs.berkeley.edu on Wed, Jan 10, 2001 at 11:45:47PM -0800 References: Message-ID: <20010111102628.A7844@pino.selwerd.nl> On Wed, Jan 10, 2001 at 11:45:47PM -0800, Daniel Yoo wrote: > > >From the edu-sig list, Furman Smith mentioned a very nice site filled with > sample problems. These problems are pretty neat, and I thought it might > be fun to work some of them out. No time pressure or anything; just to > see what strategies different people choose. > > Problem 136 in Volume One asks to write a program that finds the 1500th > "ugly" number. > > http://acm.fi.uva.es/problemset/v1/136.html > > *grin* I think I'll try it out, and see how far I get. Coolness! And we'll put our results on the Useless Python pages, yes? :) This one looks pretty simple, going to hack right away :-) -- Remco Gerlich From scarblac@pino.selwerd.nl Thu Jan 11 10:03:36 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Thu, 11 Jan 2001 11:03:36 +0100 Subject: [Tutor] [Edu-sig] collection of ACM programming problems (fwd) In-Reply-To: <20010111102628.A7844@pino.selwerd.nl>; from scarblac@pino.selwerd.nl on Thu, Jan 11, 2001 at 10:26:28AM +0100 References: <20010111102628.A7844@pino.selwerd.nl> Message-ID: <20010111110336.B7844@pino.selwerd.nl> On Thu, Jan 11, 2001 at 10:26:28AM +0100, Remco Gerlich wrote: > Coolness! And we'll put our results on the Useless Python pages, yes? :) > > This one looks pretty simple, going to hack right away :-) Well, the first solution I thought of (changing the primes.py program) didn't work out, but it was still not that hard. Fun to do though :). Keeping the source secret for the home solvers, but the answer I get is 859963392L. (so the ACM bastards wanted you to implement long integers in Pascal as well). -- Remco Gerlich From scarblac@pino.selwerd.nl Thu Jan 11 11:45:47 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Thu, 11 Jan 2001 12:45:47 +0100 Subject: [Tutor] [Edu-sig] collection of ACM programming problems (fwd) In-Reply-To: ; from Lindsay.Davies@moonshine.co.uk on Thu, Jan 11, 2001 at 11:35:33AM +0000 References: <20010111102628.A7844@pino.selwerd.nl> <20010111110336.B7844@pino.selwerd.nl> Message-ID: <20010111124547.A8152@pino.selwerd.nl> On Thu, Jan 11, 2001 at 11:35:33AM +0000, Lindsay Davies wrote: > On 11/1/01, Remco Gerlich wrote about 'Re: [Tutor] [Edu-sig] > collection of ACM programming pro': > >On Thu, Jan 11, 2001 at 10:26:28AM +0100, Remco Gerlich wrote: > >> Coolness! And we'll put our results on the Useless Python pages, yes? :) > >> > >> This one looks pretty simple, going to hack right away :-) > > > >Well, the first solution I thought of (changing the primes.py program) > >didn't work out, but it was still not that hard. Fun to do though :). > >Keeping the source secret for the home solvers, but the answer I get is > >859963392L. > > OK, I could have got this completely wrong, but that seems -waaaay- > too big. I get 2385. But 2385/53 = 45, and 53 is a prime number. So that's not even an ugly number itself. Ugly numbers are the numbers that have 2, 3 and 5 as their *only* prime factors. Numbers of the form 2^x*3^y*5^z. Made the same mistake myself at first :) Hmm. Math. Maybe this belongs over on python-list... -- Remco Gerlich From scarblac@pino.selwerd.nl Thu Jan 11 12:07:53 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Thu, 11 Jan 2001 13:07:53 +0100 Subject: [Tutor] [Edu-sig] collection of ACM programming problems (fwd) In-Reply-To: <3A5DAC9C.32152.B24268@localhost>; from sgo@europeaninvestor.com on Thu, Jan 11, 2001 at 12:52:44PM +0200 References: ; <20010111124547.A8152@pino.selwerd.nl> <3A5DAC9C.32152.B24268@localhost> Message-ID: <20010111130753.A8240@pino.selwerd.nl> On Thu, Jan 11, 2001 at 12:52:44PM +0200, Stephane Gobillon wrote: > Sorry for this message. > I search the web reference for unsubscribe at this service .... Uh oh, I hope the short discussion on the ACM problems hasn't scared you away... Anyway, go to http://mail.python.org/mailman/listinfo/tutor and login at the bottom to unsubscribe. -- Remco Gerlich From rob@jam.rr.com Thu Jan 11 13:00:23 2001 From: rob@jam.rr.com (R. A.) Date: Thu, 11 Jan 2001 07:00:23 -0600 Subject: [Tutor] Re: More useless Python source References: <20010111120803.A8091@pino.selwerd.nl> Message-ID: <3A5DAE67.77C5C610@jam.rr.com> Thanks. I'm sending my reply to the group so I can say thanks to everyone who's willing to help create THE MOST USELESS PAGE EVER! ;-) Before the tutor list took an interest in the project, it was indeed a useless page, but in more of a *sadly pathetic* kinda way. There's now a section on *Useless* devoted to this problem, so I'd be tickled pink if a few more people take a shot at it and send me their code to add to the the special section. If anyone notices other challenges on that ACM site to tackle, we can change the special section header to encompass your interests. Heck, I look forward to having to divide *Useless* into sub-sections, so don't be afraid to bury me in source code. Just remember to let me know if I should post a link to your website or email, and life's simpler if there are a few words about what a script does and any meaningful comments in the source file. Thanks all, Rob Andrews Remco Gerlich wrote: > > Someone suggested doing the ACM excercises for fun, the ones from > http://acm.fi.uva.es/problemset/ . > > I implemented 136 and 100, and now I have to mail them away quickly or > else I'll be sitting here coding for a week or so without sleep... > > Too bad we can't check our results. But hopefully we get multiple solutions > that work in a different way. And the *cool* thing is that the Python > solutions will be very short. Making Python look good. I would hate to do > this in Pascal or C :) > > 'problem100.py' and 'uglies.py' are attached. > > -- > Remco Gerlich > > ------------------------------------------------------------------------ > > problem100.pyName: problem100.py > Type: Plain Text (text/plain) > > uglies.pyName: uglies.py > Type: Plain Text (text/plain) -- Visit the Useless Python Repository! http://www.lowerstandard.com/python/pythonsource.html From rob@jam.rr.com Thu Jan 11 13:36:52 2001 From: rob@jam.rr.com (R. A.) Date: Thu, 11 Jan 2001 07:36:52 -0600 Subject: [Tutor] email address verification Message-ID: <3A5DB6F4.DF3DBB6E@jam.rr.com> Remco Gerlich: Do I have your email address right on *Useless*? I received an error when I tested. Rob -- Visit the Useless Python Repository! http://www.lowerstandard.com/python/pythonsource.html From XQ.Xia@ccsr.cam.ac.uk Thu Jan 11 15:11:44 2001 From: XQ.Xia@ccsr.cam.ac.uk (XIA Xiao-Qin) Date: Thu, 11 Jan 2001 15:11:44 +0000 Subject: [Tutor] inquire In-Reply-To: <00c201c07bd2$a098f020$be679c3d@shi> References: <200012311007400203.00060A7B@mail-serv.ccsr.cam.ac.uk> <00c201c07bd2$a098f020$be679c3d@shi> Message-ID: <200101111511440763.015AA0E4@mail-serv.ccsr.cam.ac.uk> --=====_97922590441=_ Content-Type: text/plain; charset="us-ascii" Dear Sir/Madam, Does python offer the function like the "&" in FoxPro? i.e. in foxpro, some code like following: a="I am a" b="a" print &b may print the content of variable a. Can one do like this in python? Many Thanks, Xia XQ --=====_97922590441=_ Content-Type: text/html; charset="us-ascii"
Dear Sir/Madam,
 
Does python offer the function like the "&" in FoxPro?
i.e. in foxpro, some code like following:
 
            a="I am a"
            b="a"
            print &b
 
may print the content of variable a.
Can one do like this in python?
 
Many Thanks,
Xia XQ
 
--=====_97922590441=_-- From DOUGS@oceanic.com Thu Jan 11 15:20:02 2001 From: DOUGS@oceanic.com (Doug Stanfield) Date: Thu, 11 Jan 2001 05:20:02 -1000 Subject: [Tutor] inquire Message-ID: <8457258D741DD411BD3D0050DA62365907A52E@huina.oceanic.com> I don't think Python would do it in exactly that way. I'm sure there is a "Pythonic" way to do what you want. Try to describe the problem you're trying to solve and we'll probably be able to help. -Doug- -----Original Message----- From: XIA Xiao-Qin [mailto:XQ.Xia@ccsr.cam.ac.uk] Sent: Thursday, January 11, 2001 5:12 AM To: tutor@python.org Subject: [Tutor] inquire Dear Sir/Madam, Does python offer the function like the "&" in FoxPro? i.e. in foxpro, some code like following: a="I am a" b="a" print &b may print the content of variable a. Can one do like this in python? Many Thanks, Xia XQ From arcege@shore.net Thu Jan 11 15:50:46 2001 From: arcege@shore.net (Michael P. Reilly) Date: Thu, 11 Jan 2001 10:50:46 -0500 (EST) Subject: [Tutor] inquire In-Reply-To: <200101111511440763.015AA0E4@mail-serv.ccsr.cam.ac.uk> from "XIA Xiao-Qin" at Jan 11, 2001 03:11:44 PM Message-ID: <200101111550.KAA06846@northshore.shore.net> > > --=====_97922590441=_ > Content-Type: text/plain; charset="us-ascii" > > Dear Sir/Madam, > > Does python offer the function like the "&" in FoxPro? > i.e. in foxpro, some code like following: > > a="I am a" > b="a" > print &b > > may print the content of variable a. > Can one do like this in python? > > Many Thanks, > Xia XQ > You're thinking of "soft references". You can do that in Python, but not in the same way; everything is a reference after all. Because of the namespace rules in Python, it is easier to use eval (or exec) to do what you want. >>> a = "I am a" >>> b = "a" >>> print eval(b) I am a >>> exec 'print %s' % a I am a >>> def foobar(ref): ... c = 'I am not a' ... print eval(ref) ... >>> foobar('a') I am a >>> foobar('c') I am not a >>> foobar('d') Traceback (innermost last): File "", line 1, in ? File "", line 3, in foobar File "", line 0, in ? NameError: d >>> You'll notice that the function will either take the reference from the local variables or the global variables, and raise an exception if the reference cannot be found. Inspecting the programs "frames" can also be a means, but that can get complicated. What is usually more effective is putting these kinds of references as members or methods of class instances within your program. Usually, you'll find that soft references can be replaced with much better constructs. But if you would like to see a real example of these being used, then look at the source code for the "cmd" standard module. The class in the module builds command line interfaces by building method names from the input string and checking to see if the command exists (or if help exists for it). Good luck, -Arcege -- ------------------------------------------------------------------------ | Michael P. Reilly, Release Manager | Email: arcege@shore.net | | Salem, Mass. USA 01970 | | ------------------------------------------------------------------------ From dsh8290@rit.edu Thu Jan 11 17:10:21 2001 From: dsh8290@rit.edu (D-Man) Date: Thu, 11 Jan 2001 12:10:21 -0500 Subject: [Tutor] inquire In-Reply-To: <200101111550.KAA06846@northshore.shore.net>; from arcege@shore.net on Thu, Jan 11, 2001 at 10:50:46AM -0500 References: <200101111511440763.015AA0E4@mail-serv.ccsr.cam.ac.uk> <200101111550.KAA06846@northshore.shore.net> Message-ID: <20010111121021.C17772@dman.rh.rit.edu> On Thu, Jan 11, 2001 at 10:50:46AM -0500, Michael P. Reilly wrote: | > | > --=====_97922590441=_ | > Content-Type: text/plain; charset="us-ascii" | > | > Dear Sir/Madam, | > | > Does python offer the function like the "&" in FoxPro? | > i.e. in foxpro, some code like following: | > | > a="I am a" | > b="a" | > print &b | > | > may print the content of variable a. | > Can one do like this in python? | > | > Many Thanks, | > Xia XQ | > | I've never used FoxPro, but I'll try to help anyways. | You're thinking of "soft references". You can do that in Python, but | not in the same way; everything is a reference after all. Because of | the namespace rules in Python, it is easier to use eval (or exec) to do | what you want. | | >>> a = "I am a" | >>> b = "a" | >>> print eval(b) | I am a Couldn't you just do: a = "I am a" b = a print b ? In this case, changing the value of a won't affect b. To have this effect (without using eval as already demonstrated) you would need 2 layers of references -- a reference to the string, then a & b would be references to that reference. Then you would modify the external reference to make sure a & b refer to the new value. ex: class Pointer : def __init__( self , value ) : self.value = value c = Pointer( "The value" ) a = c b = c print a.value # The value print b.value # The value c.value = "A new value" print a.value # A new value print b.value # A new value In this case, c is an object that has a member called "value". When the assignment c.value = "A new value" is executed, the value of 'value' changes, but the value of 'c' doesn't. a and b are references to c. Since c didn't change, a and b refer to the same object, whose member changed. Does this help at all? -D PS. There is probably an easier way to have "pointers" in python, but someone more experienced will have to demonstrate this. From XQ.Xia@ccsr.cam.ac.uk Thu Jan 11 17:12:42 2001 From: XQ.Xia@ccsr.cam.ac.uk (XIA Xiao-Qin) Date: Thu, 11 Jan 2001 17:12:42 +0000 Subject: [Tutor] inquire Message-ID: <200101111712420921.006CF758@mail-serv.ccsr.cam.ac.uk> --=====_97923316241=_ Content-Type: text/plain; charset="WINDOWS-1250" Dear Sir/Madam, Does python offer any method or function to return the name of any object? eg. >>>aaa=None >>>print Wanted_Function(aaa) 'aaa' the question is if such a function like Wanted_Function() actually exists. Many Thanks, Xia XQ --=====_97923316241=_ Content-Type: text/html; charset="WINDOWS-1250"
Dear Sir/Madam,
 
Does python offer any method or function to return the name of any object?
eg.
 
>>>aaa=None
>>>print Wanted_Function(aaa)
'aaa'
 
the question is if such a function like Wanted_Function() actually exists.
 
Many Thanks,
Xia XQ
 
--=====_97923316241=_-- From arcege@shore.net Thu Jan 11 18:19:56 2001 From: arcege@shore.net (Michael P. Reilly) Date: Thu, 11 Jan 2001 13:19:56 -0500 (EST) Subject: [Tutor] inquire In-Reply-To: <200101111712420921.006CF758@mail-serv.ccsr.cam.ac.uk> from "XIA Xiao-Qin" at Jan 11, 2001 05:12:42 PM Message-ID: <200101111819.NAA09007@northshore.shore.net> > Dear Sir/Madam, > > Does python offer any method or function to return the name of any object? > eg. > > >>>aaa=None > >>>print Wanted_Function(aaa) > 'aaa' > > the question is if such a function like Wanted_Function() actually exists. > > Many Thanks, > Xia XQ Not easily, no. As D-Man was referring to, Python is not a variable- based language, but a name-binding one (that is why there is no pointer dereferencing). Take the following snippet: >>> brunch = [ "eggs", "spam", "spam", "toast"] >>> breakfast = brunch >>> dinner = brunch; snack = breakfast >>> brunch is breakfast 1 >>> Which is the "name" of the list object: "brunch", "dinner", "snack" or "breakfast"? All the names are valid, is "brunch" the name because it was first? What about if the reference is in two modules for the same object? The best you could be hoping for is looking in the "current" namespace, instead of having _one_ single name for an object. It is best to use the traceback and frame structure for this. Here are some helper functions to do this: def get_frame(): """Return the calling function's execution frame.""" import sys # import sys before the exception is raised try: raise Exception() except: exc, val, tb = sys.exc_info() frame_we_want = tb.tb_frame.f_back del tb # so we don't keep the reference to the traceback return frame_we_want def Wanted_Name(findsym): frame = get_frame() # now we get the calling frame from here frame = frame.f_back # go through each name binding and see if it is the object # search globals, builtins and f_locals, in that order # do not search globals since it would likely be in the calling # function's locals anyway, and I'm guessing we want a more global name for it for namespace in ('f_globals', 'f_builtins', 'f_locals'): for (nam, obj) in getattr(frame, namespace).items(): if findsym is obj: return nam # we didn't find it at all, could be in another module raise NameError(findsym) if __name__ == '__main__': if Wanted_Name(get_frame) != 'get_frame'): raise SystemExit('It is not working, Arg!') You might want to look at pdb and idle to see how those figure out this problem. Good luck, -Arcege -- ------------------------------------------------------------------------ | Michael P. Reilly, Release Manager | Email: arcege@shore.net | | Salem, Mass. USA 01970 | | ------------------------------------------------------------------------ From robert.groenewegen@zonnet.nl Thu Jan 11 18:38:40 2001 From: robert.groenewegen@zonnet.nl (Robert Groenewegen) Date: Thu, 11 Jan 2001 19:38:40 +0100 Subject: [Tutor] Pegasus plug-in In-Reply-To: <20010110170111.1B9FBEEEB@mail.python.org> Message-ID: <000001c07bfd$b89a34b0$c40213ac@e500nt4ukrg> Hi out there, I just downloaded the new version of Pegasus mail. Looks great, works fine but the real thrill was in the announcements. The Python plug-in would give access to all functionality. This is exactly what I want but ... does anyone knows where to get the stuff? I haven't found any link or pointer so far. Thanks, in advance, Robert From dsh8290@rit.edu Thu Jan 11 18:54:13 2001 From: dsh8290@rit.edu (D-Man) Date: Thu, 11 Jan 2001 13:54:13 -0500 Subject: [Tutor] inquire In-Reply-To: <200101111819.NAA09007@northshore.shore.net>; from arcege@shore.net on Thu, Jan 11, 2001 at 01:19:56PM -0500 References: <200101111712420921.006CF758@mail-serv.ccsr.cam.ac.uk> <200101111819.NAA09007@northshore.shore.net> Message-ID: <20010111135413.C18524@dman.rh.rit.edu> On Thu, Jan 11, 2001 at 01:19:56PM -0500, Michael P. Reilly wrote: | > Dear Sir/Madam, | > | > Does python offer any method or function to return the name of any object? | > eg. | > | > >>>aaa=None | > >>>print Wanted_Function(aaa) | > 'aaa' | > | > the question is if such a function like Wanted_Function() actually exists. | > | > Many Thanks, | > Xia XQ | | Not easily, no. As D-Man was referring to, Python is not a variable- | based language, but a name-binding one (that is why there is no pointer | dereferencing). [snip] On the other hand, some objects do have a __name__ attribute, but not variables. Those objects include modules, functions and classes. Try this: >>> import os >>> os.__name__ 'os' >>> foo = os >>> foo.__name__ 'os' :-) Not quite what you were looking for, right? -D From DOUGS@oceanic.com Thu Jan 11 19:33:23 2001 From: DOUGS@oceanic.com (Doug Stanfield) Date: Thu, 11 Jan 2001 09:33:23 -1000 Subject: FW: [Tutor] inquire Message-ID: <8457258D741DD411BD3D0050DA62365907A532@huina.oceanic.com> Forwarding this to the list to expedite more immediate help: > > If there is a table of data like this: > > record |name |gender |age |...... > 1 |'Jim' |m |23 |..... > 2 |'Mary' |f |19 |..... > > I don't know the structure of the table when I write my > program, so I have to dynamicsly design a class object to > simulate a record. I wish the properties of my class have the > name same to the table. How can I do it? > The matter is actually that, if I have string value, how can > I generate a variable with the string as its name? This reminds me of a Python dictionary. That would probably be the easiest route to finding a solution. For example I've done this before: tm = statcmd.readline()[:-1] heads = string.split(statcmd.readline()[:-1],",") heads[0] = 'IP' values = string.split(statcmd.readline()[:-1],",") tHeads = heads[0:16] tValues = values[0:16] stats = {} for key,value in map(None,tHeads,tValues): stats[key] = value stats['time'] = tm Where the format of the file I was reading was like this: Thu Jan 11 09:26:05 HST 2001 IP Addr,Name,Location,UpTime,ByteRx,ByteTx 10.254.91.57,139322038,8100lana1,... etc. In other words, the first line of the file has a date stamp which I put in the tm variable. Later I associate that with the dictionary key 'time'. The next line has the header of variable names. I put that in a list called heads. The next line has values associated with those headings, put into the list called variables. After some initialization I use the for loop to populate the dictionary called stats with key value pairs where the key is the header and the value is the corresponding value from the second line. With a little extra code this could be adapted to your multiple record line file. Good luck. -Doug- From dyoo@hkn.eecs.berkeley.edu Thu Jan 11 21:56:16 2001 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Thu, 11 Jan 2001 13:56:16 -0800 (PST) Subject: [Tutor] [Edu-sig] collection of ACM programming problems (fwd) In-Reply-To: <20010111124547.A8152@pino.selwerd.nl> Message-ID: On Thu, 11 Jan 2001, Remco Gerlich wrote: > On Thu, Jan 11, 2001 at 11:35:33AM +0000, Lindsay Davies wrote: > > On 11/1/01, Remco Gerlich wrote about 'Re: [Tutor] [Edu-sig] > > collection of ACM programming pro': > > >On Thu, Jan 11, 2001 at 10:26:28AM +0100, Remco Gerlich wrote: > > >> Coolness! And we'll put our results on the Useless Python pages, yes? :) > > >> > > >> This one looks pretty simple, going to hack right away :-) > > > > > >Well, the first solution I thought of (changing the primes.py program) > > >didn't work out, but it was still not that hard. Fun to do though :). > > >Keeping the source secret for the home solvers, but the answer I get is > > >859963392L. Confirmed on 859963392 --- I used an simplistic brute force method, and got the same numbers. (After about a few HOURS... I like Remco's program a lot better than mine.) It's definitely a good idea to try multiple solutions of this problem. In fact, my first program had reported 74649600 as the 1500th ugly number --- only later when I tried a different approach did I find a bug in the program. When we're talking in the range of hundreds of millions, double checking can't hurt... *grin* From rob@jam.rr.com Fri Jan 12 00:13:42 2001 From: rob@jam.rr.com (R. A.) Date: Thu, 11 Jan 2001 18:13:42 -0600 Subject: [Tutor] ACM collection becomes Useless Message-ID: <3A5E4C36.10469D31@jam.rr.com> Tesla has contributed some crypto, and there's a new section on the Useless page devoted to the ACM problems. Anyone who takes a stab at any of the ACM problems, feel free to email 'em to me for archiving there (as well as anything other source gracing your drives). I'm pleased to say that thanks to the generosity displayed so far, I have a grand excuse to start expanding the site a bit over the next few days, since it's beginning to outgrow its current format. :-) Rob Andrews -- Visit the Useless Python Repository! http://www.lowerstandard.com/python/pythonsource.html From joejava@dragoncat.net Fri Jan 12 00:22:59 2001 From: joejava@dragoncat.net (Joel Ricker) Date: Thu, 11 Jan 2001 19:22:59 -0500 Subject: [Tutor] [Edu-sig] collection of ACM programming problems (fwd) Message-ID: <007d01c07c2d$d34bb2e0$19a2d6d1@ceo> >> On 11/1/01, Remco Gerlich wrote about 'Re: [Tutor] [Edu-sig] >But 2385/53 = 45, and 53 is a prime number. So that's not even an ugly >number itself. > >Ugly numbers are the numbers that have 2, 3 and 5 as their *only* prime >factors. Numbers of the form 2^x*3^y*5^z. > >Made the same mistake myself at first :) My first attempt was pretty bad as well. Had to think long and hard about exactly what prime factorization was. Come to think of it, I didn't do so good on the prime factorization problem I had to do when I was in school. Back to work I guess. Remco, you mentioned before you worked on a prime number program. Here's a challenge to you if you or anyone else is interested. I assume you took the normal route of testing each number against an increasing number until either it divides evenly or gets larger than half the tested number. Well try doing a routine that finds a list of prime numbers, say 1 to 1000 using multiplication instead. Its faster and actually increases speed as it tests (ie, the number of calculations to test to see if 500 is prime is fewer than the number of tests to see if 250 is prime). -- Joel Ricker joejava@dragoncat.net Just Another Python Hacker ======================================================================= I have been Perl-Free for 6 Days, 21 Hours, 26 Minutes, and 4 Seconds. >Hmm. Math. Maybe this belongs over on python-list... > >-- >Remco Gerlich > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://www.python.org/mailman/listinfo/tutor From joejava@dragoncat.net Fri Jan 12 00:34:12 2001 From: joejava@dragoncat.net (Joel Ricker) Date: Thu, 11 Jan 2001 19:34:12 -0500 Subject: [Tutor] Silly directory problems... Message-ID: <008501c07c2f$63e91260$19a2d6d1@ceo> I've got two problems but I think they are both connected to one another. The first is reading in a file. I want my data to be in a directory called dat located from the current directory (the one the script is running in). The directory is there and so is the file but: fhandle = open("/dat/game.dat","r") doesn't work (file not found or similiar stated error). This works fine: fhandle = open("game.dat","r"). So I'm thinking I need to append the current directory before adding the /dat/ directory but I couldn't find where thats located. Also I created a module and when I first stared building it, I located just off one of the builtin module directories (I'm using activestate python so that directory is c:/python20/libs/) but when I moved it and tried to append the directory, it still couldn't find it. I think I did manage to get it to find the modules but dir(module_name) didn't produce any of the subroutines or variables inside it. I moved the modules back to where it was working but I'm going to need my modules to be run-time specific. Any ideas? These are probably silly and I'm just missing something minor. Thanks for the help -- Joel Ricker joejava@dragoncat.net Just Another Python Hacker ======================================================================= I have been Perl-Free for 6 Days, 21 Hours, 34 Minutes, and 28 Seconds. From scarblac@pino.selwerd.nl Fri Jan 12 00:54:29 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Fri, 12 Jan 2001 01:54:29 +0100 Subject: [Tutor] [Edu-sig] collection of ACM programming problems (fwd) In-Reply-To: ; from dyoo@hkn.eecs.berkeley.edu on Thu, Jan 11, 2001 at 01:56:16PM -0800 References: <20010111124547.A8152@pino.selwerd.nl> Message-ID: <20010112015429.A9655@pino.selwerd.nl> On Thu, Jan 11, 2001 at 01:56:16PM -0800, Daniel Yoo wrote: > > > >Well, the first solution I thought of (changing the primes.py program) > > > >didn't work out, but it was still not that hard. Fun to do though :). > > > >Keeping the source secret for the home solvers, but the answer I get is > > > >859963392L. > > Confirmed on 859963392 --- I used an simplistic brute force method, and > got the same numbers. (After about a few HOURS... I like Remco's program > a lot better than mine.) Thanks :). After several changes the computer scientist in me still thinks it could be improved a lot, and the pragmatist says there's no reason to... > It's definitely a good idea to try multiple solutions of this problem. > In fact, my first program had reported 74649600 as the 1500th ugly number > --- only later when I tried a different approach did I find a bug in the > program. When we're talking in the range of hundreds of millions, double > checking can't hurt... *grin* I love all the problems on that site. A collection of different solutions for them would be useful for a number of things - example Python code, checking your solutions, and certainly good marketing for Python - I bet that a Python solution will often be much shorter *and* faster than an implementation in C or Pascal. It seems the approach to solving most of these problems in Python is "use a dict." :) And if I were doing this in C my first idea would not be to use a hashing algorithm. Lots of speed gain simply because the higher concepts are less work to implement (it's already done). I think making such a collection is out of scope for this list though and I'd like to make an announcement on comp.lang.python, but Rob is the one who maintains the site. It could become quite some work. So let him decide how big he wants this to be. I've also got a pretty simplistic answer for problem 100 (using a dictionary as a cache) and I've been playing with 759, interpreting Roman numerals (but there are some complicated rules to take into account to make sure you notice every illegal Roman numeral). I love little CS problems like this :) -- Remco Gerlich From dsh8290@rit.edu Fri Jan 12 01:00:53 2001 From: dsh8290@rit.edu (D-Man) Date: Thu, 11 Jan 2001 20:00:53 -0500 Subject: [Tutor] Silly directory problems... In-Reply-To: <008501c07c2f$63e91260$19a2d6d1@ceo>; from joejava@dragoncat.net on Thu, Jan 11, 2001 at 07:34:12PM -0500 References: <008501c07c2f$63e91260$19a2d6d1@ceo> Message-ID: <20010111200053.C20125@dman.rh.rit.edu> On Thu, Jan 11, 2001 at 07:34:12PM -0500, Joel Ricker wrote: | I've got two problems but I think they are both connected to one another. | | The first is reading in a file. I want my data to be in a directory called | dat located from the current directory (the one the script is running in). | The directory is there and so is the file but: | | fhandle = open("/dat/game.dat","r") ^ I had the same silly typo in my procmailrc file that someone else on a list pointed out to me. You don't want that leading '/' for a relative path. | | doesn't work (file not found or similiar stated error). | | This works fine: fhandle = open("game.dat","r"). So I'm thinking I need to | append the current directory before adding the /dat/ directory but I | couldn't find where thats located. | | Also I created a module and when I first stared building it, I located just | off one of the builtin module directories (I'm using activestate python so | that directory is c:/python20/libs/) but when I moved it and tried to append Oh, a Windows machine. That's a really interesting path syntax. Could this be related to your above problem? The path you gave is perfectly legal and normal for a Unix path. (those most systems don't have a /dat directory by default) | the directory, it still couldn't find it. I think I did manage to get it to | find the modules but dir(module_name) didn't produce any of the subroutines | or variables inside it. I moved the modules back to where it was working | but I'm going to need my modules to be run-time specific. | | Any ideas? These are probably silly and I'm just missing something minor. | | Thanks for the help | -- | Joel Ricker joejava@dragoncat.net Just Another Python Hacker | ======================================================================= | I have been Perl-Free for 6 Days, 21 Hours, 34 Minutes, and 28 Seconds. | HTH, -D From rob@jam.rr.com Fri Jan 12 01:54:59 2001 From: rob@jam.rr.com (R. A.) Date: Thu, 11 Jan 2001 19:54:59 -0600 Subject: [Tutor] [Edu-sig] collection of ACM programming problems (fwd) References: <20010111124547.A8152@pino.selwerd.nl> <20010112015429.A9655@pino.selwerd.nl> Message-ID: <3A5E63F3.AAE910B0@jam.rr.com> My thoughts on the hazards of starting up a potentially high-maintenance Python code collection? Bring it on! Here's why: 1. The Python community benefits from published code, and people considering Python will be attracted by repositories of code. 2. I'm loosely planning on adding some CGI to allow people to upload their own code and have the pages and links generated more-or-less automatically. 3. Server space on my Python-friendly web host is not a factor for me. 4. My kitten likes to sit in my lap and watch the monitor. 5. Everybody seems to be having fun. Rob Remco Gerlich wrote: > I love all the problems on that site. A collection of different solutions > for them would be useful for a number of things - example Python code, > checking your solutions, and certainly good marketing for Python - I bet > that a Python solution will often be much shorter *and* faster than an > implementation in C or Pascal. > I think making such a collection is out of scope for this list though and > I'd like to make an announcement on comp.lang.python, but Rob is the one who maintains the site. It could become quite some work. So let him decide how big he wants this to be. > :) > > -- > Remco Gerlich -- Visit the Useless Python Repository! http://www.lowerstandard.com/python/pythonsource.html From bwinton@tor.dhs.org Fri Jan 12 02:05:56 2001 From: bwinton@tor.dhs.org (Blake Winton) Date: Thu, 11 Jan 2001 21:05:56 -0500 Subject: [Tutor] inquire In-Reply-To: Your message of "Thu, 11 Jan 2001 05:20:02 -1000." <8457258D741DD411BD3D0050DA62365907A52E@huina.oceanic.com> Message-ID: <200101120205.VAA08045@tor.dhs.org> Doug wrote: > XIA Xiao-Qin wrote: > > Does python offer the function like the "&" in FoxPro? > > i.e. in foxpro, some code like following: > > > > a="I am a" > > b="a" > > print &b > > > > may print the content of variable a. > > Can one do like this in python? > I don't think Python would do it in exactly that way. I'm sure there is a > "Pythonic" way to do what you want. Try to describe the problem you're > trying to solve and we'll probably be able to help. I very much agree with Doug, in that it's not really a Pythonic way of doing things, but you could use something like : Python 1.5.2 (#1, Sep 17 1999, 20:15:36) [GCC egcs-2.91.66 19990314/Linux (egcs- on linux-i386 Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam >>> a = "I am a" >>> b = "a" #Now you can use either: >>> l = locals() >>> l.get(b) 'I am a' #Or, alternately: >>> eval(b) 'I am a' But, I plead with you, as someone who may, someday in the future, read your code, or code from someone who might do something like that, don't use that construct. It makes your code _very_ hard to read, and there's usually a better way to do what you want. Good luck, Blake. From joejava@dragoncat.net Fri Jan 12 02:54:10 2001 From: joejava@dragoncat.net (Joel Ricker) Date: Thu, 11 Jan 2001 21:54:10 -0500 Subject: [Tutor] Silly directory problems... Message-ID: <001e01c07c42$f3369420$b8a3d6d1@ceo> D-man said: >I had the same silly typo in my procmailrc file that someone else on a >list pointed out to me. > >You don't want that leading '/' for a relative path. Oh yea. See, I told you it was silly :) >| Also I created a module and when I first stared building it, I located just >| off one of the builtin module directories (I'm using activestate python so >| that directory is c:/python20/libs/) but when I moved it and tried to append > >Oh, a Windows machine. That's a really interesting path syntax. >Could this be related to your above problem? The path you gave is >perfectly legal and normal for a Unix path. (those most systems don't >have a /dat directory by default) Quite right, I'm running Windows 98 (should have mentioned that at the start). The /dat directory is one of my own creation. The path that I'm trying to install my custom modules would will be in: c:\python20\work\lib\ The directory named "work" is where the python source is running from. Also, most of what I'm doing will be cgi stuff so I would like to install the path the modules at run time since the directory for that would be something like this: /www/cgi-bin/lib/ where cgi-bin is the directory the scripts run from. So to clarify my question: How do I properly add directories to the module search path? and How do I find the current directory? Thanks again, From NHYTRO@compuserve.com Fri Jan 12 09:59:16 2001 From: NHYTRO@compuserve.com (Sharriff Aina) Date: Fri, 12 Jan 2001 04:59:16 -0500 Subject: [Tutor] IDLE problem Message-ID: <200101120459_MC2-C16D-249@compuserve.com> Hi Guys! I cut and pasted my scipt into IDLE and this is what I got: Exception in Tkinter callback Traceback (most recent call last): File "c:\python20\lib\lib-tk\Tkinter.py", line 1287, in __call__ return apply(self.func, args) File "C:\PYTHON20\Tools\idle\PyShell.py", line 579, in enter_callback self.runit() File "C:\PYTHON20\Tools\idle\PyShell.py", line 598, in runit more =3D self.interp.runsource(line) File "C:\PYTHON20\Tools\idle\PyShell.py", line 183, in runsource return InteractiveInterpreter.runsource(self, source, filename) File "c:\python20\lib\code.py", line 61, in runsource code =3D compile_command(source, filename, symbol) File "c:\python20\lib\codeop.py", line 61, in compile_command code =3D compile(source, filename, symbol) UnicodeError: ASCII encoding error: ordinal not in range(128) Pasting the same script in Activestate python runs. Activestate is comfortable, but behaves in some cases strangely; I would prefer to use IDLE. Any ideas? Best regards Sharriff From NHYTRO@compuserve.com Fri Jan 12 10:31:44 2001 From: NHYTRO@compuserve.com (Sharriff Aina) Date: Fri, 12 Jan 2001 05:31:44 -0500 Subject: [Tutor] Class tests Message-ID: <200101120531_MC2-C177-ACDC@compuserve.com> Hi List! I have just finished coding a class withe several class methods, can someone show me how to programmatically test each function in the class safely? Best regards Sharriff From amoreira@mercury.ubi.pt Fri Jan 12 10:33:25 2001 From: amoreira@mercury.ubi.pt (Jose Amoreira) Date: Fri, 12 Jan 2001 10:33:25 +0000 Subject: [Tutor] [Edu-sig] collection of ACM programming problems (fwd) References: <007d01c07c2d$d34bb2e0$19a2d6d1@ceo> Message-ID: <3A5EDD75.B7F1F0B9@mercury.ubi.pt> Joel Ricker wrote: [...snip...] > ... I assume you took the > normal route of testing each number against an increasing number until > either it divides evenly or gets larger than half the tested number. Sorry to drop in, but I thought that you just have to go up to the *square root* (instead of half) of the tested number. This is not a formal demonstration, but if the tested number devides evenly by its half, it also devides evenly by 2, wich comes first in this increasing series of devides. > Well > try doing a routine that finds a list of prime numbers, say 1 to 1000 using > multiplication instead. Its faster and actually increases speed as it tests > (ie, the number of calculations to test to see if 500 is prime is fewer than > the number of tests to see if 250 is prime). I guess that the sieve of erastothenes is a partial candidate for your request; it is, at least, a multiplications only algorithm. It goes as this: 1 take a list of all integers from one to (say) n=1000; 2 remove all mutiples of k=2; 3 take the first element bigger than k not yet removed (the 1st time this step is done, that's 3) and remove all its multiples; 4 repeat step 3 while k is smaller the sqrt(n) What's left in the list after this procedure are all the primes up to n. Just my 2c... Cheers Ze From alan.gauld@bt.com Fri Jan 12 10:37:32 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri, 12 Jan 2001 10:37:32 -0000 Subject: [Tutor] inquire Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D4CE@mbtlipnt02.btlabs.bt.co.uk> > i.e. in foxpro, some code like following: > a="I am a" > b="a" > print &b > > may print the content of variable a. > Can one do like this in python? So print b would yield "a" and print &b would yield the value of variable a? If so then try: >>> a = "I am a" >>> b = "a" >>> print b a >>> print eval(b) I am a Does that do? Alan g. From alan.gauld@bt.com Fri Jan 12 10:58:40 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri, 12 Jan 2001 10:58:40 -0000 Subject: [Tutor] inquire Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D4CF@mbtlipnt02.btlabs.bt.co.uk> > Does python offer any method or function to return the name > of any object? > >>>aaa=None > >>>print Wanted_Function(aaa) > 'aaa' I don't know of any such but it might look like: def getname(var, scope=dir()): for name in scope: if eval(name) == var: return name foo = None print getname(foo) The problem is that because variables in Python are references if you have two variables pointing to the same object then getname retiurns the name of the first one. Thus in the case of None any name in the current scope pointing to None will cause the first one to be printed. Also using a default parameter isn't great since they are only set once. You probably need to pass dir() in as scope on each call. I'm sure some of the Python experts will have a better way... But that might give you a starter for 10? Alan G. From alan.gauld@bt.com Fri Jan 12 11:02:47 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri, 12 Jan 2001 11:02:47 -0000 Subject: [Tutor] Silly directory problems... Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D4D0@mbtlipnt02.btlabs.bt.co.uk> > Oh, a Windows machine. That's a really interesting path syntax. > Could this be related to your above problem? The path you gave is > perfectly legal and normal for a Unix path. (those most systems don't > have a /dat directory by default) The / should work Ok on a windoze box, the problem as you pointed out is the leading / causing it to be treated as an absolute path rather than a relative path. Alan G. From mbc2@netdoor.com Fri Jan 12 15:36:45 2001 From: mbc2@netdoor.com (Brad Chandler) Date: Fri, 12 Jan 2001 09:36:45 -0600 Subject: [Tutor] number formatting Message-ID: <002001c07cad$784be4c0$111c0d0a@spb.state.ms.us> Thanks for the answers on the rounding issue. I suspected it had something to do with floating point numbers but I just wasn't sure what was happening and why. I was trying to match some numbers produced by another program which apparently handles numbers differently. I was only off by about $1.50 over about $1.3 billion, so I guess that's close enough. Right now I'm trying to figure out how to format numbers as currency. For example, I want to turn this: 1314403624.57 into this: $1,314,403,624.57 Now I can easily add a $ to the front of the string, but how do I get those commas in there? I'm currently using '%.2f' % myfloatingpointnumber to format it to two decimal places, is there another option which adds commas? Brad From dyoo@hkn.eecs.berkeley.edu Fri Jan 12 15:53:25 2001 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Fri, 12 Jan 2001 07:53:25 -0800 (PST) Subject: [Tutor] Class tests In-Reply-To: <200101120531_MC2-C177-ACDC@compuserve.com> Message-ID: On Fri, 12 Jan 2001, Sharriff Aina wrote: > I have just finished coding a class withe several class methods, can > someone show me how to programmatically test each function in the > class safely? There's a Python idiom that lets you make a "main" function --- it looks like this: ### if __name__ == '__main__': # Rest of the body goes here ### The body of this if-statement is the traditional place to put stuff that tests out the class. You can make an instance of your class, and then start trying out the class's methods. Afterwards, running Python on your program will do the testing. Let's try one of the classic examples, an Account class that keeps track of someone's finances. ### account.py class Account: def __init__(self, amount): self.amount = amount def withdraw(self, x): self.amount -= x def report(self): return "Current balance: %s" % self.amount if __name__ == '__main__': myaccount = Account(100) print myaccount.report() myaccount.withdraw(42) print myaccount.report() ### Here, I'm just making sure that my member functions are doing the right thing --- I call each one in turn, and then ask my instance for a report(). One other thing you can do is use the interpreter --- since you can do anything in the interpreter, you can also make instances of classes that you've designed. Good luck! From mbc2@netdoor.com Fri Jan 12 16:28:22 2001 From: mbc2@netdoor.com (Brad Chandler) Date: Fri, 12 Jan 2001 10:28:22 -0600 Subject: [Tutor] upgrading idle References: <3A5F2B22.C1A85C93@early.com> Message-ID: <003501c07cb4$ae12d080$111c0d0a@spb.state.ms.us> ----- Original Message ----- From: "Tom Connor" <"duckpond(no spam)"@early.com> To: Sent: Friday, January 12, 2001 10:04 AM Subject: [Tutor] upgrading idle > I have python 1.5.2 installed on RH Linux 6.2 in /usr/bin/. I tried > updating idle from 0.4 to 0.5 but could not get it operating as the > default. So I upgraded to Python 2.0 and it is located in > /usr/local/bin. Python 1.5.2 is also there and I am having the same > idle problem, I get the old idle. Will uninstalling Python 1.5.2 solve > this problem? I had this same problem when I upgraded to python 2.0. I had both the old and new binaries on my system and everytime I started python, it used the old binary instead of the new one. I think it was because I had a symbolic link from python1.5.2 to python. I deleted the old binaries from my system, deleted the old symbolic link, and then created a new link from /usr/local/python2.0 to /usr/local/python. Its worked fine since then. Make sure you check in both usr/bin and usr/local/bin for the links. I think RedHat must install python in /usr/bin by default, but the fresh install puts it in /usr/local/bin. From mbc2@netdoor.com Fri Jan 12 17:01:48 2001 From: mbc2@netdoor.com (Brad Chandler) Date: Fri, 12 Jan 2001 11:01:48 -0600 Subject: [Tutor] number formatting References: <002001c07cad$784be4c0$111c0d0a@spb.state.ms.us> Message-ID: <004001c07cb9$5a9e6d60$111c0d0a@spb.state.ms.us> Nevermind about this question. I did what I should have done in the first place and searched the python website (actually the vaults of parnassus). I found an excellent 3rd party module at http://pythoncode.homestead.com/files/formatCurrency.py.txt Brad From arcege@shore.net Fri Jan 12 17:16:57 2001 From: arcege@shore.net (Michael P. Reilly) Date: Fri, 12 Jan 2001 12:16:57 -0500 (EST) Subject: [Tutor] number formatting In-Reply-To: <002001c07cad$784be4c0$111c0d0a@spb.state.ms.us> from "Brad Chandler" at Jan 12, 2001 09:36:45 AM Message-ID: <200101121716.MAA12676@northshore.shore.net> > Right now I'm trying to figure out how to format numbers as currency. For > example, I want to turn this: 1314403624.57 > into this: $1,314,403,624.57 > > Now I can easily add a $ to the front of the string, but how do I get those > commas in there? I'm currently using '%.2f' % myfloatingpointnumber to > format it to two decimal places, is there another option which adds commas? There are no string formatting options to do this. So how about a brute force approach: def add_commas(number, decimal=2, howmany=3): import string s = '%.*f' % (decimal, number) whole, fract = string.split(s, '.') # make the string into a multiple of how many we want l = ((len(whole) / howmany) + 1) * howmany zs = string.rjust(whole, l) # brake into groups of how many characters we want bucket = [] while zs: part, zs = zs[:howmany], zs[howmany:] bucket.append(part) if bucket[0] == (' ' * howmany): # we have a bug? del bucket[0] commas = string.join(bucket, ',') return string.lstrip(string.join([commas, fract], '.')) >From this you would just have to add the dollar sign. There are probably some nicer ways that I didn't invest time in thinking about (like instead of padding the string, group from the end by "howmany"), but this also gives you a view into some of the tools available. Good luck, -Arcege -- ------------------------------------------------------------------------ | Michael P. Reilly, Release Manager | Email: arcege@shore.net | | Salem, Mass. USA 01970 | | ------------------------------------------------------------------------ From bsass@freenet.edmonton.ab.ca Fri Jan 12 17:37:32 2001 From: bsass@freenet.edmonton.ab.ca (Bruce Sass) Date: Fri, 12 Jan 2001 10:37:32 -0700 (MST) Subject: [Tutor] upgrading idle (fwd) Message-ID: :/ you'd think I knew how to spell by now, eh. ---------- Forwarded message ---------- Date: Fri, 12 Jan 2001 09:52:47 -0700 (MST) From: Bruce Sass To: Tom Connor <"duckpond(no spam)"@early.com> Cc: tudor@python.org Subject: Re: [Tutor] upgrading idle On Fri, 12 Jan 2001, Tom Connor wrote: > I have python 1.5.2 installed on RH Linux 6.2 in /usr/bin/. I tried > updating idle from 0.4 to 0.5 but could not get it operating as the > default. So I upgraded to Python 2.0 and it is located in > /usr/local/bin. Python 1.5.2 is also there and I am having the same > idle problem, I get the old idle. Will uninstalling Python 1.5.2 solve > this problem? I noticed the same problem with 1.5.2 from Debian and 2.0 from ActiveState. Assuming you want both version on the system... Have a look at idle.py from py2.0, the first line is: #! /usr/bin/env python you will need to change it to: #! /usr/bin/env python2.0 and make sure python2.0 is on your path. You will probably also want to symlink distinctive names for the two versions of IDLE to the respective idle.py files. later, Bruce From facelle@tiscalinet.it Fri Jan 12 20:59:56 2001 From: facelle@tiscalinet.it (Fabrizio) Date: Fri, 12 Jan 2001 21:59:56 +0100 Subject: [Tutor] Two questions on MS-DOS References: <20010112170120.1EE8DF25B@mail.python.org> Message-ID: <000901c07cda$e9eb4a80$80250b3e@oemcomputer> Hi, everybody. Python 2.0 on Windows 98. Two questions: 1 - How can I keep my DOS shell from closing automatically upon the end of a Python scipt ? (It does not give time to read the parser exceptions and errors messages !) 2 - How can I keep the DOS shell from opening up upon the start of a Python script ? (I need this when using TKInter, and I do not want to see the DOS window under TKInter's). Thanks in advance. Fabrizio From deirdre@deirdre.net Fri Jan 12 23:21:14 2001 From: deirdre@deirdre.net (Deirdre Saoirse) Date: Fri, 12 Jan 2001 15:21:14 -0800 (PST) Subject: [Tutor] [Edu-sig] collection of ACM programming problems (fwd) In-Reply-To: <3A5EDD75.B7F1F0B9@mercury.ubi.pt> Message-ID: On Fri, 12 Jan 2001, Jose Amoreira wrote: > Sorry to drop in, but I thought that you just have to go up to the > *square root* (instead of half) of the tested number. This is not a > formal demonstration, but if the tested number devides evenly by its > half, it also devides evenly by 2, wich comes first in this increasing > series of devides. Yes, that's correct. If you haven't found a factor by the time you reach the square root, logic suggests you're not going to find one. -- _Deirdre * http://www.sfknit.org * http://www.deirdre.net "We have an open door policy." -- Sheridan "And an open airlock policy." -- Ivanova From deirdre@deirdre.net Sat Jan 13 00:28:54 2001 From: deirdre@deirdre.net (Deirdre Saoirse) Date: Fri, 12 Jan 2001 16:28:54 -0800 (PST) Subject: [Tutor] Wesley's book In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20751D4B3@mbtlipnt02.btlabs.bt.co.uk> Message-ID: On Mon, 8 Jan 2001 alan.gauld@bt.com wrote: > I will probably buy it after my finances recover from > their current state of impoverishment! You mean they recover? Oh good. Then I can get a copy of Wes's book as well.... -- _Deirdre * http://www.sfknit.org * http://www.deirdre.net "We have an open door policy." -- Sheridan "And an open airlock policy." -- Ivanova From kalle@gnupung.net Sat Jan 13 01:02:00 2001 From: kalle@gnupung.net (Kalle Svensson) Date: Sat, 13 Jan 2001 02:02:00 +0100 Subject: [Tutor] Two questions on MS-DOS In-Reply-To: <000901c07cda$e9eb4a80$80250b3e@oemcomputer>; from facelle@tiscalinet.it on Fri, Jan 12, 2001 at 09:59:56PM +0100 References: <20010112170120.1EE8DF25B@mail.python.org> <000901c07cda$e9eb4a80$80250b3e@oemcomputer> Message-ID: <20010113020200.D448@apone.network.loc> --MIdTMoZhcV1D07fI Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable Sez Fabrizio: > 1 - How can I keep my DOS shell from closing automatically upon the end o= f a > Python scipt ? (It does not give time to read the parser exceptions and > errors messages !) Oh, I wish I knew... The best I've come up with is either run the program from a DOS window you've opened "manually", or put a line like raw_input("Press enter...") at the end of your program. Both are bad, but I don't know a better way. > 2 - How can I keep the DOS shell from opening up upon the start of a Pyth= on > script ? (I need this when using TKInter, and I do not want to see the DOS > window under TKInter's). Rename the file with a .pyw extension. .pyw's use pythonw.exe to launch, which is the same as python.exe but without the DOS window. HTH, Kalle --=20 Email: kalle@gnupung.net | You can tune a filesystem, but you Web: http://www.gnupung.net/ | can't tune a fish. -- man tunefs(8) PGP fingerprint: 0C56 B171 8159 327F 1824 F5DE 74D7 80D7 BF3B B1DD --MIdTMoZhcV1D07fI Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.4 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE6X6kIdNeA1787sd0RAvJMAJ9ezgqU61jX2LH0d5rrrAv53w28YwCgxoKG Dffjmkc4xaLzGhstvVFgOzs= =jpmK -----END PGP SIGNATURE----- --MIdTMoZhcV1D07fI-- From moshez@zadka.site.co.il Sat Jan 13 09:53:56 2001 From: moshez@zadka.site.co.il (Moshe Zadka) Date: Sat, 13 Jan 2001 11:53:56 +0200 (IST) Subject: [Tutor] inquire In-Reply-To: <200101111511440763.015AA0E4@mail-serv.ccsr.cam.ac.uk> References: <200101111511440763.015AA0E4@mail-serv.ccsr.cam.ac.uk>, <200012311007400203.00060A7B@mail-serv.ccsr.cam.ac.uk> <00c201c07bd2$a098f020$be679c3d@shi> Message-ID: <20010113095356.87797A828@darjeeling.zadka.site.co.il> On Thu, 11 Jan 2001, "XIA Xiao-Qin" wrote: > Does python offer the function like the "&" in FoxPro? > i.e. in foxpro, some code like following: > > a="I am a" > b="a" > print &b > > may print the content of variable a. As a first approximation, try print eval(b) -- Moshe Zadka This is a signature anti-virus. Please stop the spread of signature viruses! From bobby_james_25@hotmail.com Sat Jan 13 01:02:04 2001 From: bobby_james_25@hotmail.com (Bobby Pennington) Date: Fri, 12 Jan 2001 20:02:04 -0500 Subject: [Tutor] stop subcription Message-ID: ------=_NextPart_001_0000_01C07CD2.88ED3FC0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable i no longer want the e-mail

Get your FREE download of = MSN Explorer at http://explorer.msn.c= om

------=_NextPart_001_0000_01C07CD2.88ED3FC0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
i no longer wa= nt the e-mail




Get= your FREE download of MSN Explorer at http://explorer.msn.com

------=_NextPart_001_0000_01C07CD2.88ED3FC0-- From moshez@zadka.site.co.il Sat Jan 13 10:03:25 2001 From: moshez@zadka.site.co.il (Moshe Zadka) Date: Sat, 13 Jan 2001 12:03:25 +0200 (IST) Subject: [Tutor] [Edu-sig] collection of ACM programming problems (fwd) In-Reply-To: <3A5EDD75.B7F1F0B9@mercury.ubi.pt> References: <3A5EDD75.B7F1F0B9@mercury.ubi.pt>, <007d01c07c2d$d34bb2e0$19a2d6d1@ceo> Message-ID: <20010113100325.4ADFBA828@darjeeling.zadka.site.co.il> On Fri, 12 Jan 2001, Jose Amoreira wrote: > Sorry to drop in, but I thought that you just have to go up to the *square > root* (instead of half) of the tested number. This is not a formal > demonstration, but if the tested number devides evenly by its half, it also > devides evenly by 2, wich comes first in this increasing series of devides. You're right, and here's a formal one: suppose a*b = n. Then either a or b are <=sqrt(n), otherwise a > sqrt(n) b > sqrt(n) ==> n = a*b > sqrt(n)*sqrt(n) = n which is a contradiction. QED. -- Moshe Zadka This is a signature anti-virus. Please stop the spread of signature viruses! From tuckerg@acm.org Sat Jan 13 14:44:22 2001 From: tuckerg@acm.org (Gregory Tucker) Date: Sat, 13 Jan 2001 23:44:22 +0900 Subject: [Tutor] Two questions on MS-DOS In-Reply-To: <20010113020200.D448@apone.network.loc> Message-ID: Hi, I think it would be cleaner to wrap the python script in a DOS batch. You can use the pause command in the batch file, without touching the Python. I believe your other question was answered already. And I just learned that answer as well. Regards, Greg --- Gregory Tucker Tokyo, Japan mailto:tuckerg@acm.org These opinions are my own. > -----Original Message----- > From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of > Kalle Svensson > Sent: Saturday, January 13, 2001 10:02 AM > To: Fabrizio > Cc: tutor@python.org > Subject: Re: [Tutor] Two questions on MS-DOS > > > Sez Fabrizio: > > 1 - How can I keep my DOS shell from closing automatically upon > the end of a > > Python scipt ? (It does not give time to read the parser exceptions and > > errors messages !) > > Oh, I wish I knew... The best I've come up with is either run the program > from a DOS window you've opened "manually", or put a line like > > raw_input("Press enter...") > > at the end of your program. Both are bad, but I don't know a better way. > > > 2 - How can I keep the DOS shell from opening up upon the start > of a Python > > script ? (I need this when using TKInter, and I do not want to > see the DOS > > window under TKInter's). > > Rename the file with a .pyw extension. .pyw's use pythonw.exe to launch, > which is the same as python.exe but without the DOS window. > > HTH, > Kalle > -- > Email: kalle@gnupung.net | You can tune a filesystem, but you > Web: http://www.gnupung.net/ | can't tune a fish. -- man tunefs(8) > PGP fingerprint: 0C56 B171 8159 327F 1824 F5DE 74D7 80D7 BF3B B1DD > From gtnorton@earthlink.net Sat Jan 13 08:20:47 2001 From: gtnorton@earthlink.net (gtnorton) Date: Sat, 13 Jan 2001 16:20:47 +0800 Subject: [Tutor] 1.5.2 slow going Message-ID: <200101140025.QAA22484@scaup.prod.itd.earthlink.net> Hi everyone, I just loaded 1.5.2 on to my old IBM Thinkpad(486, 20MB RAM, Windows 95)and it is running at a snails pace. To open IDLE takes approx. 35 seconds and the command-line is only slightly faster and once open, it's no better. Does anyone know if another version of Python that might run a little faster? 1.6?, 2.0?, Python for Win 3.x?. I know the obvious thought may be a system upgrade or new computer, but everything else runs great. Any help is appreciated. Regards, G.T. Norton From sheila@thinkspot.net Sun Jan 14 06:35:27 2001 From: sheila@thinkspot.net (Sheila King) Date: Sat, 13 Jan 2001 22:35:27 -0800 Subject: [Tutor] File I/O, rfc822, and stdin/stdout Message-ID: I'm getting really confused and frustrated here. Ultimately, my goal is to write some scripts to handle my incoming e-mail. My web host uses qmail as an MTA and with .qmail files I can invoke scripts to process my mail. The scripts receive the incoming e-mail from stdin and if they write output to stdout, that output can be delivered as the resulting e-mail message. Anyhow, I've started with some much simpler stuff. Some of it works, some of it doesn't. I'm wanting to work with the rfc822 module, for it's capabilities in handling headers. Here is one of my scripts: ---------------------------------------- #! /usr/bin/python import rfc822 raw_message=open("message3.txt","r") inheaders=rfc822.Message(raw_message) body=raw_message.read() print inheaders print print body ---------------------------------------- I run this in a DOS window on my home machine. The file "message3.txt" contains an e-mail message (in mbox format). It seems to work fine. It reads the message headers and the message body in separately, from a file, and then prints them to stdout. If I could just get them to read the message from stdin, changing the source of the input, then this should at least pipe a message through the script on my web host, without changing or in anyway sorting, filtering or redirecting it. Well, I can't seem to achieve that. I did have one script, that worked on my web host, that I invoked from a .qmail file: ----------------------------------------- #! /usr/bin/python import sys infile = sys.stdin text = infile.read() print text print "\nThis tag appended" print print "Python rules." ----------------------------------------- This one worked fine. It read the incoming mail from stdin, and wrote it back out to stdout, adding the lines "This tag appended" and "Python rules" to the end of the e-mail, and it was then delivered correctly. Of course, the problem with the above script, is it doesn't give me any easy way of handling the message headers, for filtering purposes. So, I now tried to combine them, into a script that would be of more use to me: ---------------------------------------- #! /usr/bin/python import sys, rfc822 raw_message = sys.stdin inheaders=rfc822.Message(raw_message) body=raw_message.read() print inheaders print print body ---------------------------------------- Supposedly, it should read from stdin, retrieve the headers and body separately, and then write them to stdout. But I'm getting no e-mail delivered. So, then I thought I'd try to just read an e-mail, and print it to a file. I used this script: --------------------------------------- #! /usr/bin/python import sys, os input = sys.stdin messagetext=input.read() outfile = open("outmessage.txt", "w") os.chmod("outmessage.txt", 0664) sys.stdout=outfile print messagetext outfile.close() --------------------------------------- I have to change the permissions in the script, because the mail script runs with a different UserID, and then I can't read the resulting file. Anyhow, the above script does appear to be called. The output file is created, and the permissions are correctly set. But the file is empty. So, I guess I'm not really reading stdin correctly, but I'm at a loss to figure out what's wrong. I've been looking through the tutorial and the module docs a lot today. I've even been searching on dejanews for some posts on these topics in comp.lang.python. But I haven't been able to figure this problem out. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From dyoo@hkn.eecs.berkeley.edu Sun Jan 14 06:56:03 2001 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Sat, 13 Jan 2001 22:56:03 -0800 (PST) Subject: [Tutor] stop subcription In-Reply-To: Message-ID: On Fri, 12 Jan 2001, Bobby Pennington wrote: > i no longer want the e-mail

Get your FREE download of > MSN Explorer at href="http://explorer.msn.com">http://explorer.msn.com

If you haven't been unsubscribed yet, you can unsubscribe yourself by visiting the tutor web page: http://mail.python.org/mailman/listinfo/tutor Go down to the part that talks about changing your subscription options --- you'll see an option to unsubscribe. Good luck! From dyoo@hkn.eecs.berkeley.edu Sun Jan 14 07:05:10 2001 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Sat, 13 Jan 2001 23:05:10 -0800 (PST) Subject: [Tutor] 1.5.2 slow going In-Reply-To: <200101140025.QAA22484@scaup.prod.itd.earthlink.net> Message-ID: On Sat, 13 Jan 2001, gtnorton wrote: > I just loaded 1.5.2 on to my old IBM Thinkpad(486, 20MB RAM, Windows > 95)and it is running at a snails pace. To open IDLE takes approx. 35 > seconds and the command-line is only slightly faster and once open, > it's no better. Hmmm. Hard question --- you're probably running into memory constraints with the 20mb's of ram. I'm guessing that the slowness comes from Windows having to grind for virtual memory. There's another Python implementation called Stackless Python ---- I have no idea of its memory use, but it can't hurt to try it: http://www.stackless.com/ > I know the obvious thought may be a system upgrade or new computer, > but everything else runs great. Good luck to you! From tescoil@irtc.net Sun Jan 14 16:06:07 2001 From: tescoil@irtc.net (Tesla Coil) Date: Sun, 14 Jan 2001 10:06:07 -0600 Subject: [Tutor] Up All Night with IDLE. Message-ID: <3A61CE6F.B954E0E8@irtc.net> I'm in IDLE and I write: def foobar(): print 'foobar' foobar() Save as krock.py, run it, prints foobar. I return to the editor and modify the function: def foobaz(): print 'foobaz' foobar() Save, run, prints foobar. Larger program, more complex functions, awake all night, rewriting foobaz, mystified that output is still foobar... Shut down, restart IDLE, reload krock.py run it again: NameError: There is no variable named 'foobar' I'll give myself a little credit: I figured it out without that. I would prefer to get a NameError without shutting down IDLE. Is there a line I could put at the top of programs to assure I'll be in uncorrupted namespace on every test run? From doering@u.washington.edu Sun Jan 14 17:17:17 2001 From: doering@u.washington.edu (jennifer l doering) Date: Sun, 14 Jan 2001 09:17:17 -0800 (PST) Subject: [Tutor] Re: Tutor digest, Vol 1 #546 - 5 msgs In-Reply-To: <20010114170111.A0EA9EB78@mail.python.org> Message-ID: Hi, > Hi everyone, > I just loaded 1.5.2 on to my old IBM Thinkpad(486, 20MB RAM, Windows 95)and it is running > at a snails pace. To open IDLE takes approx. 35 seconds and the command-line is only slightly > faster and once open, it's no better. It might be something with your computer or something else in Windows eating up memory. I ran python (both command line and IDLE) on a TI Extensa laptop with 8mb of memory for awhile. It certainly didn't take half a minute to load, though. Pax, Jen From robert.groenewegen@zonnet.nl Sun Jan 14 17:57:05 2001 From: robert.groenewegen@zonnet.nl (Robert Groenewegen) Date: Sun, 14 Jan 2001 18:57:05 +0100 Subject: [Tutor] Up All Night with IDLE. In-Reply-To: <3A61CE6F.B954E0E8@irtc.net> Message-ID: <3A61F681.13337.2A1048C@localhost> Dear Tesla, I have had the same trouble after using 'import' in the python shell. IDLE (and Python) have nice features (like ctrl-f5) but I can not get used to this stuff. I have red something about 'reload' in the manual but I prefer a more old-fashioned way. 1) I write a very simple script like 'test.py' # testscript import foo foo.foobar() open a command shell, and after saving the source in IDLE, I enter "python test.py" (and use F3 for the next test) 2) I create a link on my desktop which I double-click after saving the source 3) I create the source-file on my desktop and after defining the correct 'open' and 'edit' in the Windows Explorer, I can double-click the icons edit -> c:\python20\pythonw.exe c:\python20\tools\idle\idle.py -e "%1" open -> C:\Python20\pythonw.exe "%1" % The goal of these methods is to invoke a new shell (and clean environment too). The methods are a little bit Windows-style but they can be implemented in the Unix shell too. This way of testing (always do a fresh start) have saved me in several operating systems. Regards, Robert On 14 Jan 2001, at 10:06, Tesla Coil wrote: > I'm in IDLE and I write: > > def foobar(): > print 'foobar' > > foobar() > > Save as krock.py, run it, prints foobar. > I return to the editor and modify the function: > > def foobaz(): > print 'foobaz' > > foobar() > > Save, run, prints foobar. > > Larger program, more complex functions, awake all night, > rewriting foobaz, mystified that output is still foobar... > > Shut down, restart IDLE, reload krock.py run it again: > NameError: There is no variable named 'foobar' > > I'll give myself a little credit: I figured it out without that. > I would prefer to get a NameError without shutting down IDLE. > Is there a line I could put at the top of programs to assure > I'll be in uncorrupted namespace on every test run? > > > > > From sheila@thinkspot.net Mon Jan 15 03:12:03 2001 From: sheila@thinkspot.net (Sheila King) Date: Sun, 14 Jan 2001 19:12:03 -0800 Subject: [Tutor] Help with Python install Message-ID: My web host offers Python 1.5.1. It is not possible for the host to upgrade at this time, because it would require an entire rebuild of the server core (the servers are highly customized). But I really wanted to use a more recent version. I was given permission to install 2.0 in my own directory space. I have done so, and it appears to be working. The host is running RedHat Linux with Apache as the server. Python 1.5.1 is in the path, and anyplace I type >python, in any directory, the interpreter comes up. Even in the directory where I installed 2.0. To get the 2.0 interpreter to come up, I have to type the full path. The 2.0 install seems to be running fine. I used the smtplib and sent myself an e-mail. I added a few numbers. Printed some messages to the screen. Looks fine. However... I can't get some mail scripts that I had running before under 1.5.1 to run under 2.0. Using .qmail files I'm invoking these scripts when mail arrives for my account. The contents of my .qmail file are shown below: ------------------------------------------------ |/big/dom/xthinkspot/mailtofile.py |vdeliver ------------------------------------------------ So, when a mail arrives, it calls the script mailtofile.py and runs that, with the newly arrived mail being read on stdin. This is the first version of mailtofile.py: ------------------------------------------------ #! /usr/bin/python import sys, os rawmessage = sys.stdin.read() outfile = open("./outmessage.txt", "w") sys.stdout=outfile print rawmessage outfile.close() os.chmod("./outmessage.txt", 0664) ------------------------------------------------ When I send an e-mail, it gets copied to the textfile outmessage.txt. No problem. However, it is running the Python 1.5.1 from my host. So, I tried changing it to this: ----------------------------------------------- #! /big/dom/xthinkspot/thinker/python/Python-2.0/python import sys, os rawmessage = sys.stdin.read() outfile = open("./outmessage.txt", "w") sys.stdout=outfile print rawmessage outfile.close() os.chmod("./outmessage.txt", 0664) ---------------------------------------------- The only thing that has been changed is the path. I have not changed the file name, or anything else. But this doesn't appear to run at all. Well, the .qmail file tries to do something. I do get a blank e-mail as a result. But the python script doesn't appear to do it's thing. I'm wondering what I need to do? I suppose I need to set my .bash_profile so that my Python 2.0 is added to my path? or my environment? or something? Could someone help me out here? -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From sheila@thinkspot.net Mon Jan 15 05:33:42 2001 From: sheila@thinkspot.net (Sheila King) Date: Sun, 14 Jan 2001 21:33:42 -0800 Subject: [Tutor] Re: Help with Python install References: Message-ID: On Mon, 15 Jan 2001 03:12:04 GMT, Sheila King wrote in comp.lang.python in article : :My web host offers Python 1.5.1. ...... :But I really wanted to use a more recent version. I was given permission to :install 2.0 in my own directory space. I have done so, and it appears to be :working. ...... :I can't get some mail scripts that I had running before under 1.5.1 to run :under 2.0. I've been given a clue from the Sysadmin: I've installed Python in the wrong directory. The mail program doesn't have permission to access my $HOME directory, and I've installed Python2.0 in a subdirectory of HOME. So, I need to uninstall it, and then reinstall it into a directory that the mail program has access to. What is the recommended uninstall procedure? I'm tempted to simply delete the entire Python-2.0 folder, but don't want to get myself in trouble... -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From dyoo@hkn.eecs.berkeley.edu Mon Jan 15 05:34:15 2001 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Sun, 14 Jan 2001 21:34:15 -0800 (PST) Subject: [Tutor] Up All Night with IDLE. In-Reply-To: <3A61CE6F.B954E0E8@irtc.net> Message-ID: On Sun, 14 Jan 2001, Tesla Coil wrote: > I return to the editor and modify the function: > > def foobaz(): > print 'foobaz' > > foobar() ## <--- warning, warning! > > Save, run, prints foobar. Note: you're still running the foobar() function. I sincerly hope that you meant to do this. *grin* Don't you mean foobaz()? From dyoo@hkn.eecs.berkeley.edu Mon Jan 15 05:36:44 2001 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Sun, 14 Jan 2001 21:36:44 -0800 (PST) Subject: [Tutor] IDLE problem In-Reply-To: <200101120459_MC2-C16D-249@compuserve.com> Message-ID: On Fri, 12 Jan 2001, Sharriff Aina wrote: > Hi Guys! > > I cut and pasted my scipt into IDLE and this is what I got: > [long exception involving UnicodeError cut] > Pasting the same script in Activestate python runs. Activestate is > comfortable, but behaves in some cases strangely; I would prefer to use > IDLE. Hmmm... weird! Would you mind posting up a small test file that produces the same error? I have to admit --- I don't know anything about unicode, but maybe someone else on the list knows what's going on. Good luck! From dyoo@hkn.eecs.berkeley.edu Mon Jan 15 05:39:48 2001 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Sun, 14 Jan 2001 21:39:48 -0800 (PST) Subject: [Tutor] Re: Help with Python install In-Reply-To: Message-ID: > I've been given a clue from the Sysadmin: I've installed Python in the > wrong directory. The mail program doesn't have permission to access my > $HOME directory, and I've installed Python2.0 in a subdirectory of > HOME. So, I need to uninstall it, and then reinstall it into a > directory that the mail program has access to. > > What is the recommended uninstall procedure? I'm tempted to simply > delete the entire Python-2.0 folder, but don't want to get myself in > trouble... Actually, just deleting the folder should be ok. Make sure you're not wiping out anything else besides Python though. A safer thing to do it just rename the folders to something unique, like "python-backup" or something like that, just to make sure that you can recover if anything wacky happens. Good luck! From stephen@mochamail.com Mon Jan 15 09:12:14 2001 From: stephen@mochamail.com (Stephen Aichele) Date: Mon, 15 Jan 2001 01:12:14 -0800 Subject: [Tutor] teleconferencing apps Message-ID: <2922001111591214265@mochamail.com> Hello. I'm really interested in teleconferencing applications, and I'm on a hunt for anything remotely resembling one written in Python code. After searching all over this website, the only thing I found were several references to the same '5000 line' teleconferencing application written at CWI, but apparently it's not available or not open source (?)... I'm also debating whether or not to begin learning C because it seems that most of the 'popular' telecommunication apps are written in it. Python is my first language (yeah!), and I'd prefer to get more experience in it before taking on another, but I'm antsy to get cranking on some of my ideas and am having a hard time locating any code to learn from. Suggestions??? thanx! -Stephen From alan.gauld@bt.com Mon Jan 15 09:19:24 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 15 Jan 2001 09:19:24 -0000 Subject: [Tutor] Class tests Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D4D5@mbtlipnt02.btlabs.bt.co.uk> > I have just finished coding a class withe several class methods, can > someone show me how to programmatically test each function in > the class safely? Depends on how you define programmatically. I'd suggest the python interactive prompt... >>> c = Foo() >>> c.method1(1,2,3) >>> print c.someAttribute 42 >>> c.method2(2,34) >>> print c.anotherAttribute 24 >>> etc... Once you are happy it works you could put those tests in a "test" function for future regression testing: def test(): c = Foo() c.method1(1,2,3) # ... etc and have the usual stanza: if __name__ == "__main__": test() If you are using IDLE you can save your interactive session then edit out the prompts etc in Notepad or whatever... HTH, Alan g. From dsh8290@rit.edu Mon Jan 15 15:52:36 2001 From: dsh8290@rit.edu (D-Man) Date: Mon, 15 Jan 2001 10:52:36 -0500 Subject: [Tutor] Help with Python install In-Reply-To: ; from sheila@thinkspot.net on Sun, Jan 14, 2001 at 07:12:03PM -0800 References: Message-ID: <20010115105236.A8324@harmony.cs.rit.edu> On Sun, Jan 14, 2001 at 07:12:03PM -0800, Sheila King wrote: [snip] | This is the first version of mailtofile.py: | ------------------------------------------------ | #! /usr/bin/python This line is something to be careful with. It says to run /usr/bin/python which would be version 1.5.1 on your server. You will want to change it to /path/to/my/python to get 2.0 to run. (I don't know anything about qmail so I can't help with that part of the situation) -D From sheila@thinkspot.net Mon Jan 15 16:50:50 2001 From: sheila@thinkspot.net (Sheila King) Date: Mon, 15 Jan 2001 08:50:50 -0800 Subject: [Tutor] Help with Python install In-Reply-To: <20010115105236.A8324@harmony.cs.rit.edu> References: <20010115105236.A8324@harmony.cs.rit.edu> Message-ID: <70DA2777C0A@kserver.org> On Mon, 15 Jan 2001 10:52:36 -0500, D-Man wrote about Re: [Tutor] Help with Python install: :This line is something to be careful with. It says to run :/usr/bin/python which would be version 1.5.1 on your server. You will :want to change it to /path/to/my/python to get 2.0 to run. Yes, I did do that. It turns out, that I had installed Python2 in a directory that the mail program did not have permission to access. So I had to reinstall it in a different directory. Also, I had to modify my .qmail file. :(I don't know anything about qmail so I can't help with that part of :the situation) To summarize, I have at least solve this problem, for now. Here was the solution: (1) Install Python 2.0 in a directory that the mail program had permission to access. So, on my machine I put it here: /big/dom/xthinspot/Python-2.0/ (2) Put the following contents in my .qmail-pytest file, which is located in /big/dom/xthinkspot/ ---------------------------------------------------------------------------- |/big/dom/xdomain/Python-2.0/python /big/dom/xdomain/mailtofile.py |vdeliver ---------------------------------------------------------------------------- (3) The script, mailtofile.py, was located in the directory /big/dom/xthinkspot Here is the contents of that file: ------------------------------------------- #! /big/dom/xdomain/Python-2.0/python import sys, os rawmessage = sys.stdin.read() outfile = open("./outmessage.txt", "w") sys.stdout=outfile print rawmessage outfile.close() os.chmod("./outmessage.txt", 0664) ------------------------------------------- Then, when an email was sent to pytest, it would be printed to a file. So, that one is solved. Now I'm trying to work with the rfc822 module, and having problems again. Ah, well. Will keep working at it. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From tescoil@irtc.net Mon Jan 15 18:04:45 2001 From: tescoil@irtc.net (Tesla Coil) Date: Mon, 15 Jan 2001 12:04:45 -0600 Subject: [Tutor] Up All Night with IDLE. References: Message-ID: <3A633BBD.B2C9887B@irtc.net> On 14 Jan 2001, Daniel Yoo replied: >> I return to the editor and modify the function: >> >> def foobaz(): >> print 'foobaz' >> >> foobar() ## <--- warning, warning! >> >> Save, run, prints foobar. > > Note: you're still running the foobar() function. I sincerly hope > that you meant to do this. *grin* Don't you mean foobaz()? It's on purpose this time around anyway. I was talking about how IDLE doesn't return the expected NameError as long as it's kept running between revisions. One closes the python shell window, revises the file, Ctrl-f5, and it looks like a fresh new python shell, but one can still call functions and variables no longer named in the revised program. I'm not fussing about it--just wondering if there's a way that I can keep IDLE going and assure that I get a NameError when I deserve one... From alan.gauld@bt.com Mon Jan 15 17:56:26 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 15 Jan 2001 17:56:26 -0000 Subject: [Tutor] teleconferencing apps Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D4DA@mbtlipnt02.btlabs.bt.co.uk> > Hello. I'm really interested in teleconferencing applications, and > I'm on a hunt for anything remotely resembling one written in Python > Python is my first language (yeah!), and I'd prefer to get more > experience in it before taking on another, Given the above I think I'd better point out that a teleconferencing application is a pretty ambitious starting point! I'd try several other things first before even starting on teleconferencing. Maybe think about prototyping a GUI and database first - coz you'll need them later anyway. Maybe just fronting IRC or something. Then once you are fully conversant with Python try using the COM extensions to drive something like Netmeeting.(Although where you'll find documentation of the COM interface I don't know!) Finally you can try some real down 'n dirty stuff to build a teleconferencing app from scratch. All of that can be done in Python, you don't need C. But C/C++ does give advantages when it comes to distributing the final application, but its a big learning curve and you'll need to write an awful lot of code(*) compared to Python! Good luck, Alan G. (*) As in more than 10,000 lines probably! From alan.gauld@bt.com Mon Jan 15 18:00:56 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 15 Jan 2001 18:00:56 -0000 Subject: [Tutor] Up All Night with IDLE. Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D4DB@mbtlipnt02.btlabs.bt.co.uk> > I'm in IDLE and I write: > def foobar(): > foobar() > def foobaz(): > foobar() Yes thats a pain. Like another poster I tend to always have a DOS box running and test from there even when editing in IDLE. In this specific case you can get it to work by importing your module then "reload"ing it before every run. But that's actually harder than typing F3 in a DOS box.... > Shut down, restart IDLE, reload krock.py run it again: > NameError: There is no variable named 'foobar' You don't need to shut down IDLE just reload(krock). But a DOS box and F3 is still easier and safer. Alan g From XQ.Xia@ccsr.cam.ac.uk Mon Jan 15 18:38:03 2001 From: XQ.Xia@ccsr.cam.ac.uk (XIA Xiao-Qin) Date: Mon, 15 Jan 2001 18:38:03 +0000 Subject: [Tutor] inquire Message-ID: <200101151838030671.021465B6@mail-serv.ccsr.cam.ac.uk> --=====_97958388318467=_ Content-Type: text/plain; charset="WINDOWS-1250" Content-Transfer-Encoding: quoted-printable Dear Sir / Madam, Excuse me -- I have questions again. 1.Is there any way to know the type of a variable in Python. for example: def deal(*options): for k in options: if k is a list: # Can I get to know the type of k? my_function_for_list() elif k is a class: my_function_for_class() 2. Can a method know the name of the class in which the method is defined? class A: def fun(self): print self.__class__.__name__ # perhaps print 'A' or ''D', ... print A.fun.im_class.__name__ # Is here any way to print 'A' at= any time without using A directly? class B(A): pass class C(B): pass class D(C): def newfun(self): B.fun(self) And can we print the name of class B? by modify the methods fun(self) and= newfun(self)? Sincerely yours, Xia XQ --=====_97958388318467=_ Content-Type: text/html; charset="WINDOWS-1250"
Dear Sir / Madam,
 
Excuse me -- I have questions again.
 
1.Is there any way to know the type of a variable in Python.
for example:
 
def deal(*options):
    for k in options:
        if k is a list:    # Can I get to know the type of k?
            my_function_for_list()
        elif k is a class:
            my_function_for_class()
 
2. Can a method know the name of the class in which the method is defined?
 
class A:
   def fun(self):
      print self.__class__.__name__    #  perhaps print 'A' or ''D', ...
      print A.fun.im_class.__name__    # Is here any way to print 'A' at any time without using A directly?
 
class B(A):
   pass
 
class C(B):
   pass
 
class D(C):
   def newfun(self):
      B.fun(self)
And can we print the name of class B? by modify the methods fun(self) and newfun(self)?
 
 
Sincerely yours,
Xia XQ
 
--=====_97958388318467=_-- From sheila@thinkspot.net Mon Jan 15 19:03:10 2001 From: sheila@thinkspot.net (Sheila King) Date: Mon, 15 Jan 2001 11:03:10 -0800 Subject: [Tutor] Re: File I/O, rfc822, and stdin/stdout References: Message-ID: This situation has been brought to resolution. The script I was having trouble with before, quoted below, is now working on my web host, with the MTA invoking it. I have installed Python 2.0 and am using that now. The web host only had Python 1.5.1, and I believe that may have been the problem. Of course, I've had to change the path of the script to point to my install of Python 2.0. On Sun, 14 Jan 2001 06:35:28 GMT, Sheila King wrote in comp.lang.python in article : :Of course, the problem with the above script, is it doesn't give me any easy :way of handling the message headers, for filtering purposes. : :So, I now tried to combine them, into a script that would be of more use to :me: :---------------------------------------- :#! /usr/bin/python : :import sys, rfc822 : :raw_message = sys.stdin : :inheaders=rfc822.Message(raw_message) :body=raw_message.read() : :print inheaders :print :print body :---------------------------------------- : :Supposedly, it should read from stdin, retrieve the headers and body :separately, and then write them to stdout. But I'm getting no e-mail :delivered. I would also like to thank Eric Rahmig, who went to a great deal of trouble to write a similar script, which will actually be of great use to me, as I work to my final goal. Here is my adaptation of his script: ----------------------------------------- #! /my/path/to/Python-2.0/python import rfc822, sys origheaders=rfc822.Message(sys.stdin, 0) for h in origheaders.headers: print h, print for line in sys.stdin.readlines(): print line, print print print "This message was passed through a Python script" print ----------------------------------------- He sent me some assistance through e-mail. The above script is invoked on my system through a .qmail file, with the following contents: ------------------------------------------ |/my/path/to/Python-2.0/python /my/path/to/scriptname.py ------------------------------------------ The script reads in the e-mail from stdin, and then puts it back out to stdout, adding a short tag. The point is, now I will be able to do what I want: analyze the headers and decide how to handle the mails. Thanks to all for their assistance. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From amoreira@mercury.ubi.pt Mon Jan 15 19:08:48 2001 From: amoreira@mercury.ubi.pt (Jose Amoreira) Date: Mon, 15 Jan 2001 19:08:48 +0000 Subject: [Tutor] Up All Night with IDLE. References: <3A633BBD.B2C9887B@irtc.net> Message-ID: <3A634AC0.148CD2C6@mercury.ubi.pt> Tesla Coil wrote: > just wondering if there's a way that I can keep IDLE going > and assure that I get a NameError when I deserve one... Hi! But I don't think that you deserve a NameError! After all, you defined a function foobar, and then defined a function foobaz (or whatever it was), but foobar is still defined. You see, idle's main window is not a program editor, but rather a phyton shell: everything you define there is defined for as long as you dont remove it, using del(foobar), or else deleting the hole damn thing by shuting idle down. I think that i'm not too wrong here... Cheers, Ze From kalle@gnupung.net Mon Jan 15 22:00:51 2001 From: kalle@gnupung.net (Kalle Svensson) Date: Mon, 15 Jan 2001 23:00:51 +0100 Subject: [Tutor] inquire In-Reply-To: <200101151838030671.021465B6@mail-serv.ccsr.cam.ac.uk>; from XQ.Xia@ccsr.cam.ac.uk on Mon, Jan 15, 2001 at 06:38:03PM +0000 References: <200101151838030671.021465B6@mail-serv.ccsr.cam.ac.uk> Message-ID: <20010115230051.A1037@apone.network.loc> --M9NhX3UHpAaciwkO Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable Sez XIA Xiao-Qin: > Excuse me -- I have questions again. No problem, that's what we're here for! > 1.Is there any way to know the type of a variable in Python. > for example: [snip] Use the builtin type() and the module types. if type(var) =3D=3D type([]): # do list stuff or import types if type(var) =3D=3D types.ListType: # do list stuff Note that often it is better to check for interfaces, rather than types: try: print var[3] except AttributeError: print "var is not a sequence." In this case, I could make var an instance of a custom class, as long as I provide the magic method __getitem__: class Seq: def __getitem__(self, key): return 2 ** key var =3D Seq() try: print var[3] except AttributeError: print "var is not a sequence." prints 8. Read more in the language reference, chapter 3. http://python.org/doc/current/ref/datamodel.html > 2. Can a method know the name of the class in which the method is defined? import sys class A: def fun(self): try: raise except: name =3D sys.exc_info()[2].tb_frame.f_code.co_name print eval("self.%s.im_class.__name__" % name) works most of the time, at least. I'm a bit worried about the "get the function name" approach, but it seems to do the right thing. Again, more info in the language reference (3.2): http://python.org/doc/current/ref/types.html > And can we print the name of class B? by modify the methods fun(self) and > newfun(self)? That one is harder, I think. But I'll leave it to you or someone else with too much time to waste. Hope this helps, Kalle --=20 Email: kalle@gnupung.net | You can tune a filesystem, but you Web: http://www.gnupung.net/ | can't tune a fish. -- man tunefs(8) PGP fingerprint: 0C56 B171 8159 327F 1824 F5DE 74D7 80D7 BF3B B1DD --M9NhX3UHpAaciwkO Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.4 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE6Y3MTdNeA1787sd0RAoROAKCRMEaK+9P8C5v20czrc+QGu4BqqACbBQTH Rdn7hZm1ecFtB+x908yC75U= =YtMG -----END PGP SIGNATURE----- --M9NhX3UHpAaciwkO-- From dyoo@hkn.eecs.berkeley.edu Mon Jan 15 22:56:11 2001 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Mon, 15 Jan 2001 14:56:11 -0800 (PST) Subject: [Tutor] inquire In-Reply-To: <200101151838030671.021465B6@mail-serv.ccsr.cam.ac.uk> Message-ID: On Mon, 15 Jan 2001, XIA Xiao-Qin wrote: > 2. Can a method know the name of the class in which the method is defined? Hmmm.... I'm certain that this is not what you wanted: class A: def fun(self): print "A" class B(A): def fun(self): print "B" class C(B): def fun(self): print "C" ... That's one way I can see of working with the inheritance to get the classname where the method's declared. But this is exactly "A.fun.im_class.__name__" in a different disguise. Sorry, nothing else comes to mind at the moment. From marcus_python@lycos.com.br Tue Jan 16 01:22:49 2001 From: marcus_python@lycos.com.br (marcus_python@lycos.com.br) Date: Mon, 15 Jan 2001 20:22:49 -0500 Subject: [Tutor] comparing dates and file access Message-ID: <291302001121612249750@lycos.com.br> Hello, I need compare the last access file date with a today date. I only allow to access the file, if and just if, todays date is 5 days after the last access to the file. Any help? Thanks. Marcus _______________ Tenha seu correio eletrônico gratuito, grupos, calendário e mais! >> http://www.comunidade.lycos.com.br From arcege@shore.net Tue Jan 16 01:40:18 2001 From: arcege@shore.net (Michael P. Reilly) Date: Mon, 15 Jan 2001 20:40:18 -0500 (EST) Subject: [Tutor] comparing dates and file access In-Reply-To: <291302001121612249750@lycos.com.br> from "marcus_python@lycos.com.br" at Jan 15, 2001 08:22:49 PM Message-ID: <200101160140.UAA09123@northshore.shore.net> > I need compare the last access file date with a today date. I only > allow to access the file, if and just if, todays date is 5 days > after the last access to the file. Any help? You can use the os.path.getatime() (or you can get it directly out of os.stat). Then compare that integer with one from "today". def can_I_read(filename, when=5*24*60*60): import os, time access_time = os.path.getatime(filename) now = time.time() return (access_time + when > now) If the function returns true, then the file is less than five days old (five days is 5*24*60*60). You might also want to look into the mxDateTime module (). -Arcege -- ------------------------------------------------------------------------ | Michael P. Reilly, Release Manager | Email: arcege@shore.net | | Salem, Mass. USA 01970 | | ------------------------------------------------------------------------ From tescoil@irtc.net Tue Jan 16 04:43:24 2001 From: tescoil@irtc.net (Tesla Coil) Date: Mon, 15 Jan 2001 22:43:24 -0600 Subject: [Tutor] Humbly Announcing: cipher.py Message-ID: <3A63D16C.C18574A9@irtc.net> I've put together a small module of functions frequently used in a variety of pencil and paper cryptosystems--cipher.py is appropriately available at Rob Andrews' Useless Python page: http://www.lowerstandard.com/python/pythonsource.html I'm interested in review of the existing functions and deciding possible additions for a future release. Persons with too much time on their hands are invited to give a whack at using the module to write a Playfair cipher. This one turns up occasionally as a programming contest problem: http://www.pbs.org/wgbh/nova/decoding/playfair.html Currently wasting my own time to provide a demonstration of a completely different keysquare cipher... From dyoo@hkn.eecs.berkeley.edu Tue Jan 16 04:31:50 2001 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Mon, 15 Jan 2001 20:31:50 -0800 (PST) Subject: [Tutor] An example extension class Message-ID: Hello everyone! I was playing around with the Python/C API, and thought it would be fun to write a C extension. I've written a pybitmap module written in C, so it might help people who're trying to learn how to extend Python. Here's the link: http://hkn.eecs.berkeley.edu/~dyoo/python/pybitmap-0.1.tar.gz I'd be greatful for any comments about the code --- I know that it can use a lot of improvement. Thanks again! From sheila@thinkspot.net Tue Jan 16 09:18:19 2001 From: sheila@thinkspot.net (Sheila King) Date: Tue, 16 Jan 2001 01:18:19 -0800 Subject: [Tutor] Script performance: Filtering email Message-ID: I'd appreciate any analysis or tips on this task I'm trying to accomplish, and my actual Python code (which is at the bottom of this message). So, I'm writing a script to filter my e-mail. I'm using Python, but I'd assume performance would be more or less equivalent to a script in Perl. I tested it yesterday afternoon. Seemed fine. My host uses qmail as an MTA. I can invoke my python script using .qmail files each time an e-mail arrives. My plan: replace my .qmail default file, with a new version, that calls my script. Except for a few, well-chosen aliases, that have their own .qmail files, that skip over the script. I started using it for a while tonight. Further testing. It all seemed fine. What it does: checks for certain headers in the e-mail to determine whether it is a "good" email or a "bad" email. If good, it sends it to a private e-mail address that I have never published or shared with anyone. Otherwise, the mail is sent to a spam-bucket address. Like I say, seemed fine for a while. Then, late last night (after a few hours of using the script), my e-mails seemed to be disappearing into the void. I panicked, and took the script down. Before taking it down, I sent myself several test mails. Both ones that would qualify as "good" mails and as "bad" ones. None seemed to be delivered. So, I took my filter script down. Tested if mails could now go through. They did. Just fine. Strangely enough, these missing e-mails eventually appeared. Some of them, over an hour from the time they hit my web host's mail servers until they hit my mailbox. Some of them about a half hour. Some about seven minutes. Could my little 26 line Python script be causing this? It doesn't seem that 45 minutes to an hour is about normal for an email to go through on my web host. Performance there is usually very good, and I never saw it take that long before. Please examine the script below, if you would, and let me know if I'm overlooking some performance issues. I'm a real Python newbie, so maybe I'm doing something really dumb. Thanks, -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ Here is my script: Code Sample: #! /big/dom/xdomain/Python-2.0/python import rfc822, sys, string, smtplib ##check if to: and cc: addresses are in my approved file def goodmessage(addresseeslist, rcptlist): for addr in addresseeslist: for rcpt in rcptlist: if (upper(addr[1]) == upper(rcpt)): return 1 return 0 ## Retrieving data ## ##uncomment the below two lines if message data ## is read from stdin origheaders=rfc822.Message(sys.stdin, 0) body = sys.stdin.read() ##uncomment the below three lines if message data ## is read from a file #infile=open("message6.txt", "r") #origheaders=rfc822.Message(infile) #body = infile.read() ## Setting forwarding e-mails, sender e-mail ## and file with list of good recipients fwdgood = "privateaddr@domain.com" fwdbad = "spambucket@spamcop.net" sender = "myemail@mydomain.com" goodrcptfile = open("GoodToList.txt", "r") ##textfile with good address ## for To: and cc: fields goodrcptlist = string.split(goodrcptfile.read()) goodrcptfile.close() addressees =[] addressees = addressees + origheaders.getaddrlist("To") addressees = addressees + origheaders.getaddrlist("Cc") mssg = string.join(origheaders.headers,"") mssg = mssg + "\n" + string.join(body, "") server=smtplib.SMTP("mysmtp.com") if goodmessage(addressees, goodrcptlist): server.sendmail(sender, fwdgood, mssg) else: server.sendmail(sender, fwdbad, mssg) server.quit() From scarblac@pino.selwerd.nl Tue Jan 16 09:51:54 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Tue, 16 Jan 2001 10:51:54 +0100 Subject: [Tutor] Script performance: Filtering email In-Reply-To: ; from sheila@thinkspot.net on Tue, Jan 16, 2001 at 01:18:19AM -0800 References: Message-ID: <20010116105154.A16271@pino.selwerd.nl> On Tue, Jan 16, 2001 at 01:18:19AM -0800, Sheila King wrote: > Strangely enough, these missing e-mails eventually appeared. Some of them, > over an hour from the time they hit my web host's mail servers until they hit > my mailbox. Some of them about a half hour. Some about seven minutes. Maybe the script failed with some exception, and qmail noticed and sent the mail again later? I'm quite sure this is not a performance issue, but there may be a bug somewhere. > Could my little 26 line Python script be causing this? It doesn't seem that 45 > minutes to an hour is about normal for an email to go through on my web host. > Performance there is usually very good, and I never saw it take that long > before. > > Please examine the script below, if you would, and let me know if I'm > overlooking some performance issues. I'm a real Python newbie, so maybe I'm > doing something really dumb. > Here is my script: > Code Sample: > > #! /big/dom/xdomain/Python-2.0/python > > import rfc822, sys, string, smtplib > > ##check if to: and cc: addresses are in my approved file > def goodmessage(addresseeslist, rcptlist): > for addr in addresseeslist: > for rcpt in rcptlist: > if (upper(addr[1]) == upper(rcpt)): > return 1 > return 0 Are you sure you meant addr[1] there? If addresseeslist is simply a name of mail addresses, you are comparing the second character of addr to the whole recipient. I don't know what rfc822 does though, maybe addr is something else. This could be written: def goodmessage(addresseeslist, rcptlist): for rcpt in rcptlist: if rcpt in addresseeslist: return 1 return 0 (if addr[1] was an error) > ## Retrieving data ## > > ##uncomment the below two lines if message data > ## is read from stdin > origheaders=rfc822.Message(sys.stdin, 0) > body = sys.stdin.read() > > ##uncomment the below three lines if message data > ## is read from a file > #infile=open("message6.txt", "r") > #origheaders=rfc822.Message(infile) > #body = infile.read() > > ## Setting forwarding e-mails, sender e-mail > ## and file with list of good recipients > fwdgood = "privateaddr@domain.com" > fwdbad = "spambucket@spamcop.net" > sender = "myemail@mydomain.com" > goodrcptfile = open("GoodToList.txt", "r") ##textfile with good address > ## for To: and cc: fields > goodrcptlist = string.split(goodrcptfile.read()) > goodrcptfile.close() > > addressees =[] > addressees = addressees + origheaders.getaddrlist("To") > addressees = addressees + origheaders.getaddrlist("Cc") > > mssg = string.join(origheaders.headers,"") > mssg = mssg + "\n" + string.join(body, "") > > server=smtplib.SMTP("mysmtp.com") > > if goodmessage(addressees, goodrcptlist): > server.sendmail(sender, fwdgood, mssg) > else: > server.sendmail(sender, fwdbad, mssg) > server.quit() If the connection fails for some reason or other, an exception will be raised. Maybe you should wrap the whole thing in a try/except to log whatever goes wrong, like try: (the body of your script) except: import sys f=open("somelogfile","w") print >> f, sys.exc_info() f.close() raise # Re-raise the exception so that the program doesn't quit silently If that log file fills up, you know where to look. I can't really say more from here. -- Remco Gerlich From sheila@thinkspot.net Tue Jan 16 10:29:17 2001 From: sheila@thinkspot.net (Sheila King) Date: Tue, 16 Jan 2001 02:29:17 -0800 Subject: [Tutor] Script performance: Filtering email In-Reply-To: <20010116105154.A16271@pino.selwerd.nl> References: <20010116105154.A16271@pino.selwerd.nl> Message-ID: <2D4E9A23B44@kserver.org> On Tue, 16 Jan 2001 10:51:54 +0100, Remco Gerlich wrote about Re: [Tutor] Script performance: Filtering email: :On Tue, Jan 16, 2001 at 01:18:19AM -0800, Sheila King wrote: :> Strangely enough, these missing e-mails eventually appeared. Some of them, :> over an hour from the time they hit my web host's mail servers until they hit :> my mailbox. Some of them about a half hour. Some about seven minutes. : :Maybe the script failed with some exception, and qmail noticed and sent :the mail again later? : :I'm quite sure this is not a performance issue, but there may be a bug :somewhere. At this point, it seems likely that there must be a problem or bug in the script. :> Code Sample: :> :> #! /big/dom/xdomain/Python-2.0/python :> :> import rfc822, sys, string, smtplib :> :> ##check if to: and cc: addresses are in my approved file :> def goodmessage(addresseeslist, rcptlist): :> for addr in addresseeslist: :> for rcpt in rcptlist: :> if (upper(addr[1]) == upper(rcpt)): :> return 1 :> return 0 : :Are you sure you meant addr[1] there? If addresseeslist is simply a name :of mail addresses, you are comparing the second character of addr to :the whole recipient. I don't know what rfc822 does though, maybe addr is :something else. addresseeslist is a list of tuples, where the first element in the tuple is the users name (from the address field of an e-mail), such as mine should appear to be "Sheila King" in the From: field of this message, and the second element of the tuple is the actual e-mail address, which in this message From: field should appear to be sheila@thinkspot.net addr in addresseeslist would be one of those tuples out of the whole list. addr[1] would be the second element in the tuple, which is the e-mail address. :This could be written: : :def goodmessage(addresseeslist, rcptlist): : for rcpt in rcptlist: : if rcpt in addresseeslist: : return 1 : return 0 : :(if addr[1] was an error) Hmm. Maybe I should try to just cull the addresses from the addressees list of tuples, instead of having a nested loop. I could just us the "if blank1 in blank2" structure if I get the data types to match properly. That might be more efficient? ...... :> :> server=smtplib.SMTP("mysmtp.com") :> :> if goodmessage(addressees, goodrcptlist): :> server.sendmail(sender, fwdgood, mssg) :> else: :> server.sendmail(sender, fwdbad, mssg) :> server.quit() : :If the connection fails for some reason or other, an exception will :be raised. : :Maybe you should wrap the whole thing in a try/except to log whatever :goes wrong, like : :try: : (the body of your script) :except: : import sys : f=open("somelogfile","w") : print >> f, sys.exc_info() : f.close() : : raise # Re-raise the exception so that the program doesn't quit silently : :If that log file fills up, you know where to look. I can't really :say more from here. I've never worked with exceptions before. Is it really that easy? I will try it out tomorrow and see what I get in the log file. Surely something. Is the additional "import sys" command inside the "except" block necessary if I've already imported that module at the beginning of my script? Thanks, -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From lumbricus@gmx.net Tue Jan 16 12:33:55 2001 From: lumbricus@gmx.net (=?ISO-8859-1?Q?J=F6rg_W=F6lke?=) Date: Tue, 16 Jan 2001 13:33:55 +0100 (MET) Subject: [Tutor] dialer Message-ID: <17557.979648435@www20.gmx.net> Hi all!!! Is there any example code for a modem-dialer. My own using open(MODEMPORT,'r+') wouldn't work and I cannot figure out why. TIA Greeets Jö! -- Sent through GMX FreeMail - http://www.gmx.net From XQ.Xia@ccsr.cam.ac.uk Tue Jan 16 15:49:05 2001 From: XQ.Xia@ccsr.cam.ac.uk (XIA Xiao-Qin) Date: Tue, 16 Jan 2001 15:49:05 +0000 Subject: [Tutor] Another Question Message-ID: <200101161549050764.0165A854@mail-serv.ccsr.cam.ac.uk> --=====_97966014541=_ Content-Type: text/plain; charset="WINDOWS-1250" Content-Transfer-Encoding: quoted-printable Sorry, I have so many question. Here is another one: class A: def fun(self, *options): ... # some codes here class B(A): def fun(self, *options): ...# some codes here ...# I need to call fun in class A here How can the method fun in class B use its option tuple to call the fun= method in the class A? The problem is caused because we can change the tuple (options). Sincerely, Xia XQ --=====_97966014541=_ Content-Type: text/html; charset="WINDOWS-1250"
Sorry, I have so many question. Here is another one:
 
class A:
    def fun(self, *options):
        ... # some codes here
 
class B(A):
    def fun(self, *options):
        ...# some codes here
        ...# I need to call fun in class A here
 
How can the method fun in class B use its option tuple to call the fun method in the class A?
The problem is caused because we can change the tuple (options).
 
Sincerely,
Xia XQ
--=====_97966014541=_-- From dyoo@hkn.eecs.berkeley.edu Tue Jan 16 15:54:18 2001 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Tue, 16 Jan 2001 07:54:18 -0800 (PST) Subject: [Tutor] dialer In-Reply-To: <17557.979648435@www20.gmx.net> Message-ID: On Tue, 16 Jan 2001, [ISO-8859-1] J=F6rg W=F6lke wrote: > Is there any example code for a modem-dialer. > My own using open(MODEMPORT,'r+') wouldn't work and I cannot figure out > why. Hello! Hmmm; it sounds like you're working with a UNIX system; can you make sure that you have the correct permissions on your modem port? Make sure that a simple echo "ATDT 1234567" > MODEMPORT works first. Also, does the open call fail, or something afterwards? If you're working with Windows, you may need to use a serial port library. = =20 faqts.python.org mentions a Windows module here: http://www.faqts.com/knowledge_base/view.phtml/aid/3888/fid/235 The Vaults of Parnassus report that there are at least two serial port libraries you can choose from, win32comm and the Win32 Serial Communications Module: http://www.vex.net/parnassus/apyllo.py?find=3Dserial http://www.uconect.net/~wheineman/python/win32comm.zip http://starship.python.net/crew/roger/ Good luck! From arcege@shore.net Tue Jan 16 16:10:54 2001 From: arcege@shore.net (Michael P. Reilly) Date: Tue, 16 Jan 2001 11:10:54 -0500 (EST) Subject: [Tutor] Another Question In-Reply-To: <200101161549050764.0165A854@mail-serv.ccsr.cam.ac.uk> from "XIA Xiao-Qin" at Jan 16, 2001 03:49:05 PM Message-ID: <200101161610.LAA20970@northshore.shore.net> > > --=====_97966014541=_ > Content-Type: text/plain; charset="WINDOWS-1250" > Content-Transfer-Encoding: quoted-printable > > Sorry, I have so many question. Here is another one: > > class A: > def fun(self, *options): > ... # some codes here > > class B(A): > def fun(self, *options): > ...# some codes here > ...# I need to call fun in class A here > > How can the method fun in class B use its option tuple to call the fun= > method in the class A? > The problem is caused because we can change the tuple (options). Here is where the apply function comes in handy. A Python function's arguments are broken into two parts: positional (tuple) and named (dictionary). The apply function allows you to pass either or both types to a function: >>> def spam(*options, **keywords): ... print options, keywords ... >>> spam(1, 2, 3, name='Arcege') (1, 2, 3) {'name': 'Arcege'} >>> spam(1, 2, 3) (1, 2, 3) {} >>> spam(name='Arcege') () {'name': 'Arcege'} >>> apply(spam, (1, 2, 3), {'name': 'Arcege'}) (1, 2, 3) {'name': 'Arcege'} >>> apply(spam, (1, 2, 3)) (1, 2, 3) {} Python 2.0 also has a new syntax to use instead of apply: >>> spam(*(1,2,3), **{'name': 'Arcege'}) (1, 2, 3) {'name': 'Arcege'} >>> So in your example, the B.fun method could call: class B(A): def fun(self, *options): if sys.version[:3] == '2.0': A.fun( *( (self,) + options ) ) else: apply( A.fun, (self,) + options ) Don't forget to include self as the first argument when calling unbound methods. -Arcege -- ------------------------------------------------------------------------ | Michael P. Reilly, Release Manager | Email: arcege@shore.net | | Salem, Mass. USA 01970 | | ------------------------------------------------------------------------ From dsh8290@rit.edu Tue Jan 16 17:41:51 2001 From: dsh8290@rit.edu (D-Man) Date: Tue, 16 Jan 2001 12:41:51 -0500 Subject: [Tutor] Script performance: Filtering email In-Reply-To: <2D4E9A23B44@kserver.org>; from sheila@thinkspot.net on Tue, Jan 16, 2001 at 02:29:17AM -0800 References: <20010116105154.A16271@pino.selwerd.nl> <2D4E9A23B44@kserver.org> Message-ID: <20010116124150.B17678@harmony.cs.rit.edu> On Tue, Jan 16, 2001 at 02:29:17AM -0800, Sheila King wrote: | On Tue, 16 Jan 2001 10:51:54 +0100, Remco Gerlich [snip] | :Maybe you should wrap the whole thing in a try/except to log whatever | :goes wrong, like | : | :try: | : (the body of your script) | :except: | : import sys | : f=open("somelogfile","w") ^ Don't use "w" (write mode) here. It will clobber the existing file. Use "a" (append mode) instead. I would also suggest printing some text so that you know where the different errors are. (see 3 lines farther for an examle) | : print >> f, sys.exc_info() print >> f, "\n\n*****My Error Separator line****\n\n" | : f.close() | : | : raise # Re-raise the exception so that the program doesn't quit silently | : | :If that log file fills up, you know where to look. I can't really | :say more from here. | | I've never worked with exceptions before. Is it really that easy? I will try They are quite easy when you know what you want to do with them. In this case you just want to report it to a log file so it is easy. In some cases, such as a complete gui based application, deciding what do to isn't so easy (this is no different than dealing with "traditional" error handling such as in C). But the exception handling itself isn't hard (and I think is much better and easier than the nested if's that are very common in C). | it out tomorrow and see what I get in the log file. Surely something. | | Is the additional "import sys" command inside the "except" block necessary if | I've already imported that module at the beginning of my script? No. Remco probably put it there just to be on the safe side (or maybe he forgot you already imported it). The actual import will only happen once. If you want to force the interpreter to import the module again and run the module's init code use the reload function : reload( sys ) -D From dsh8290@rit.edu Tue Jan 16 17:45:26 2001 From: dsh8290@rit.edu (D-Man) Date: Tue, 16 Jan 2001 12:45:26 -0500 Subject: [Tutor] An example extension class In-Reply-To: ; from dyoo@hkn.eecs.berkeley.edu on Mon, Jan 15, 2001 at 08:31:50PM -0800 References: Message-ID: <20010116124526.C17678@harmony.cs.rit.edu> Just a note to clear any possible confusion : You can't write an extension *class* in C. It is an extension *type*. This is one of the few deficiencies in Python's design. The significance of this is C types can't be inherited from by a Python class. This is why classes like UserList UserString and UserDict exist in the standard distribution. (these Python classes wrap the C types using aggregation to allow subclassing) -D From alan.gauld@bt.com Tue Jan 16 17:44:10 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue, 16 Jan 2001 17:44:10 -0000 Subject: [Tutor] Another Question Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D4DE@mbtlipnt02.btlabs.bt.co.uk> > How can the method fun in class B use its option tuple to > call the fun method in the class A? I assume I'm missing the point here but this seems to do it... >>> class A: ... def fun(s,*o): ... print "A fun" ... >>> class B(A): ... def fun(s,*o): ... A.fun(s,o) ... >>> b = B() >>> b.fun(1,2,3) A fun >>> > The problem is caused because we can change the tuple (options). You can create a new tuple but you can't change the original. Tuples are immutable. I think I'm missing the issue. Alan G. From bobhicks@adelphia.net Tue Jan 16 18:46:39 2001 From: bobhicks@adelphia.net (Robert L Hicks) Date: Tue, 16 Jan 2001 13:46:39 -0500 Subject: [Tutor] First script Message-ID: #!/usr/local/bin/python #### # # Module: inetdconf.py # # Created: R.L. Hicks, 2001-01-16 # # Function: This is a small script to cause the inetd daemon # to re-read itself after a change to its conf file. # # Usage: Run the script as "python inetdconf.py" and answer "YES" # or "NO" when asked the question about restarting. ## r = "kill -HUP `ps cax|grep inetd|awk '{print $1}'`" # restarts the daemon n = "Inetd not restarted" w = "Answer needs to be 'yes' or 'no'. Try again!" answer = " " query = raw_input("Do you want to restart the INETD daemon? (yes/no): ") answer = query if len(answer) > 2: print r elif len(answer) < 2: print w else: print n How would you change it and why? Comments welcome...this is my first one after all. Bob From moshez@zadka.site.co.il Wed Jan 17 03:37:11 2001 From: moshez@zadka.site.co.il (Moshe Zadka) Date: Wed, 17 Jan 2001 05:37:11 +0200 (IST) Subject: [Tutor] An example extension class In-Reply-To: <20010116124526.C17678@harmony.cs.rit.edu> References: <20010116124526.C17678@harmony.cs.rit.edu>, Message-ID: <20010117033711.5E57CA828@darjeeling.zadka.site.co.il> On Tue, 16 Jan 2001 12:45:26 -0500, D-Man wrote: > Just a note to clear any possible confusion : > > You can't write an extension *class* in C. Yes you can: http://www.digicool.com/releases/ExtensionClass/ -- Moshe Zadka This is a signature anti-virus. Please stop the spread of signature viruses! From johnp@reportlab.com Tue Jan 16 20:16:29 2001 From: johnp@reportlab.com (John Precedo) Date: Tue, 16 Jan 2001 20:16:29 -0000 Subject: [Tutor] First script In-Reply-To: Message-ID: Robert L Hinks sent in the following script and asked > How would you change it and why? OK, before I go any further, I'd better say that I'm pretty much a Python beginner myself... but since I have written more than one script, I thought I'd try and "improve" this one :o) [remarks/header trimmed out for brevity] > > r = "kill -HUP `ps cax|grep inetd|awk '{print $1}'`" # restarts the daemon > n = "Inetd not restarted" > w = "Answer needs to be 'yes' or 'no'. Try again!" > > answer = " " > > query = raw_input("Do you want to restart the INETD daemon? (yes/no): ") > > answer = query > > if len(answer) > 2: > print r > elif len(answer) < 2: > print w > else: > print n You've been quite clever using 'len(answer)' as a decider for what you want to do. But what happens if the user (mis)types 'ye'? Or types 'noo'? Sticky keys can be a real pain! My version uses a while loop, so instead of just telling them to try again, you give them a chance to try again. (It saves them typing in the filename again :o) Oh, and I didn't see the logic in using 'query' as a temporary variable - why not just put the reply straight into answer? Well, this I'd how I'd implement it: [ - - - - - - - - START OF SNIPPET - - - - - - - - ] r = "kill -HUP `ps cax|grep inetd|awk '{print $1}'`" # restarts the daemon n = "Inetd not restarted" w = "Answer needs to be 'yes' or 'no'. Try again!" yesAnswers = ["yes", "YES", "Y", "y"] noAnswers = ["no", "NO", "N", "n"] validAnswers = yesAnswers + noAnswers answer = "" answer = raw_input("Do you want to restart the INETD daemon? (yes/no): ") while answer not in validAnswers: print w; print answer = raw_input("Do you want to restart the INETD daemon? (yes/no): ") if answer in yesAnswers: print r else: print n [ - - - - - - - - END OF SNIPPET - - - - - - - - ] Strictly speaking, pre-defining answer like that isn't necessary - or at least my test program works OK without it. But I'd rather have it in there and be safe :o) Anyway, I hope some of this helped. -- John Precedo (johnp@reportlab.com) Junior Developer, Reportlab, Inc From dsh8290@rit.edu Tue Jan 16 21:06:33 2001 From: dsh8290@rit.edu (D-Man) Date: Tue, 16 Jan 2001 16:06:33 -0500 Subject: [Tutor] Another Question In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20751D4DE@mbtlipnt02.btlabs.bt.co.uk>; from alan.gauld@bt.com on Tue, Jan 16, 2001 at 05:44:10PM +0000 References: <5104D4DBC598D211B5FE0000F8FE7EB20751D4DE@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <20010116160633.A18828@harmony.cs.rit.edu> On Tue, Jan 16, 2001 at 05:44:10PM +0000, alan.gauld@bt.com wrote: | > How can the method fun in class B use its option tuple to | > call the fun method in the class A? | | I assume I'm missing the point here but this seems to do it... | | >>> class A: | ... def fun(s,*o): | ... print "A fun" print o # try this instead, it's not quite right | ... | >>> class B(A): | ... def fun(s,*o): | ... A.fun(s,o) | ... | >>> b = B() | >>> b.fun(1,2,3) | A fun | >>> | | > The problem is caused because we can change the tuple (options). | | You can create a new tuple but you can't change the original. Tuples | are immutable. | | I think I'm missing the issue. | | Alan G. I think the "apply" response was correct. I thought it would be as simple as this, but then I tried it in the interpreter. When A.fun gets called, it has a 1-tuple as the argument "o". Then o[0] is the n-tuple of arguments that is desired. -D From dsh8290@rit.edu Tue Jan 16 21:11:03 2001 From: dsh8290@rit.edu (D-Man) Date: Tue, 16 Jan 2001 16:11:03 -0500 Subject: [Tutor] An example extension class In-Reply-To: <20010117033711.5E57CA828@darjeeling.zadka.site.co.il>; from moshez@zadka.site.co.il on Wed, Jan 17, 2001 at 05:37:11AM +0200 References: <20010116124526.C17678@harmony.cs.rit.edu> <20010116124526.C17678@harmony.cs.rit.edu> <20010117033711.5E57CA828@darjeeling.zadka.site.co.il> Message-ID: <20010116161103.B18828@harmony.cs.rit.edu> On Wed, Jan 17, 2001 at 05:37:11AM +0200, Moshe Zadka wrote: | On Tue, 16 Jan 2001 12:45:26 -0500, D-Man wrote: | | > Just a note to clear any possible confusion : | > | > You can't write an extension *class* in C. | | Yes you can: | http://www.digicool.com/releases/ExtensionClass/ Oh, that's cool. I didn't know about that. -D From tescoil@irtc.net Tue Jan 16 22:51:40 2001 From: tescoil@irtc.net (Tesla Coil) Date: Tue, 16 Jan 2001 16:51:40 -0600 Subject: [Tutor] First script References: Message-ID: <3A64D07C.A651BFF1@irtc.net> On 16 Jan 2001, John Precedo replied to Robert L Hicks: > You've been quite clever using 'len(answer)' as a decider > for what you want to do. But what happens if the user > (mis)types 'ye'? Or types 'noo'? Sticky keys can be a real > pain! > > Well, this I'd how I'd implement it: > > r = "kill -HUP `ps cax|grep inetd|awk '{print $1}'`" > # restarts the daemon > n = "Inetd not restarted" > w = "Answer needs to be 'yes' or 'no'. Try again!" > > yesAnswers = ["yes", "YES", "Y", "y"] > noAnswers = ["no", "NO", "N", "n"] > validAnswers = yesAnswers + noAnswers > answer = "" > > answer = raw_input("Do you want to restart the INETD daemon? > (yes/no): ") > > while answer not in validAnswers: > print w; print > answer = raw_input("Do you want to restart the INETD daemon? (yes/no): ") > > if answer in yesAnswers: > print r > else: > print n Here's a more compact recursive approach that, um, doesn't look like it blows up... def pester(): yesAnswers = ["yes", "YES", "Y", "y"] noAnswers = ["no", "NO", "N", "n"] validAnswers = yesAnswers + noAnswers answer = raw_input("Restart the INETD daemon? (yes/no): ") if answer not in validAnswers: print "Answer needs to be 'yes' or 'no'. Try again!" pester() elif answer in yesAnswers: print "kill -HUP `ps cax|grep inetd|awk '{print $1}'`" else: print "Inetd not restarted" pester() From Bruce Sass Tue Jan 16 23:10:12 2001 From: Bruce Sass (Bruce Sass) Date: Tue, 16 Jan 2001 16:10:12 -0700 (MST) Subject: [Tutor] First script In-Reply-To: Message-ID: Hi, On Tue, 16 Jan 2001, John Precedo wrote: > Robert L Hinks sent in the following script and asked > > How would you change it and why? > > r = "kill -HUP `ps cax|grep inetd|awk '{print $1}'`" # > restarts the daemon > n = "Inetd not restarted" > w = "Answer needs to be 'yes' or 'no'. Try again!" > > yesAnswers = ["yes", "YES", "Y", "y"] > noAnswers = ["no", "NO", "N", "n"] > validAnswers = yesAnswers + noAnswers > answer = "" > > answer = raw_input("Do you want to restart the INETD daemon? > (yes/no): ") > > while answer not in validAnswers: > print w; print > answer = raw_input("Do you want to restart the INETD > daemon? (yes/no): ") > > if answer in yesAnswers: > print r > else: > print n I'd want to do this (starting with John's code): ---8<--- import string def getYNanswer(ystring, nstring, qprompt=""): """Get "yes" or "no" interactively. Returns lowercase answer or "" """ yesAnswers = ["yes", "y"] noAnswers = ["no", "n"] exitAnswers = ["q", "quit", "e", "exit", "x"] helpAnswers = ["h", "help", "?"] validAnswers = yesAnswers + noAnswers + exitAnswers + helpAnswers answer = "" while 1: if answer in yesAnswers: print ystring break elif answer in noAnswers: print nstring break elif answer in exitAnswers: break elif answer in helpAnswers: print "Possible responses are:" print validAnswers print "(case is insignificant)." answer = "" else: answer = string.lower(raw_input(qprompt + " (h for help): ")) return answer r = "kill -HUP `ps cax|grep inetd|awk '{print $1}'`" # restarts the daemon n = "Inetd not restarted" prompt = "Do you want to restart the INETD daemon?" answer = getYNanswer(r, n, prompt) print "The answer was", answer --->8--- tested with 1.5.2 and 2.0 --- or maybe even... class YNAnswer, used like: inetd = YNAnswer(y_reply, n_reply, prompt) # ... if inetd.answer == None: pass # answer in exitAnswers elif inetd: pass # answer in yesAnswers else pass # answer in noAnswers Have fun, Bruce From martok@mattsmail.com Wed Jan 17 01:09:15 2001 From: martok@mattsmail.com (Matthias Hager) Date: Tue, 16 Jan 2001 17:09:15 -0800 Subject: [Tutor] Sign me up for mailing list. Message-ID: <200101161709.AA29491540@mail.mattsmail.com> -- martok@mattsmail.com -- Like my email address? Get your own for FREE at http://firstname.com Get you@JohnsMail.com or you@AlexsMail.com or pick from 500 more! From dyoo@hkn.eecs.berkeley.edu Wed Jan 17 03:46:13 2001 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Tue, 16 Jan 2001 19:46:13 -0800 (PST) Subject: [Tutor] Another Question In-Reply-To: <200101161549050764.0165A854@mail-serv.ccsr.cam.ac.uk> Message-ID: On Tue, 16 Jan 2001, XIA Xiao-Qin wrote: > Sorry, I have so many question. Here is another one: That's fine; it's perfectly ok to ask questions! > class A: > def fun(self, *options): > ... # some codes here > > class B(A): > def fun(self, *options): > ...# some codes here > ...# I need to call fun in class A here > > How can the method fun in class B use its option tuple to call the fun > method in the class A? The problem is caused because we can change the > tuple (options). You can call a specific class's version of a method if you do it explicitly: A.fun(self, options) will call the fun() that belongs to the A class. Hope this helps! From sheila@thinkspot.net Wed Jan 17 03:49:40 2001 From: sheila@thinkspot.net (Sheila King) Date: Tue, 16 Jan 2001 19:49:40 -0800 Subject: [Tutor] Script performance: Filtering email In-Reply-To: <20010116124150.B17678@harmony.cs.rit.edu> References: <20010116105154.A16271@pino.selwerd.nl> <2D4E9A23B44@kserver.org> <20010116124150.B17678@harmony.cs.rit.edu> Message-ID: <2B7D5B01699@kserver.org> On Tue, 16 Jan 2001 12:41:51 -0500, D-Man wrote about Re: [Tutor] Script performance: Filtering email: :On Tue, Jan 16, 2001 at 02:29:17AM -0800, Sheila King wrote: :| On Tue, 16 Jan 2001 10:51:54 +0100, Remco Gerlich :[snip] :| :Maybe you should wrap the whole thing in a try/except to log whatever :| :goes wrong, like :| : :| :try: :| : (the body of your script) :| :except: :| : import sys :| : f=open("somelogfile","w") : ^ : :Don't use "w" (write mode) here. It will clobber the existing file. :Use "a" (append mode) instead. I would also suggest printing some :text so that you know where the different errors are. (see 3 lines :farther for an examle) Good tips. Thanks. I have a question, about try/except blocks in general. (I am assuming they come in pairs, like if/else, right?) If I put try: (body of my script) and suppose the script tries to connect to the SMTP server, but fails, will it try more than once? Or it tries once, then gives up, and raises an exception? How many times does "try" try until it gives up? Once? Several times? If I had some code that was supposed to execute, like it needed to connect to some server, and for some reason that server was not available for connection, so it raised an error, how would I keep the script running and trying to connect to that server later? -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From sheila@thinkspot.net Wed Jan 17 04:31:23 2001 From: sheila@thinkspot.net (Sheila King) Date: Tue, 16 Jan 2001 20:31:23 -0800 Subject: [Tutor] Questions about stdin, stdout, lists and tuples In-Reply-To: <20010108132428.B3829@rit.edu> References: <3B4B6584E5C@kserver.org> <20010108112925.A3285@rit.edu> <3D4CF834053@kserver.org> <20010108132428.B3829@rit.edu> Message-ID: <2DDED313FEF@kserver.org> On Mon, 8 Jan 2001 13:24:28 -0500, D-Man wrote about Re: [Tutor] Questions about stdin, stdout, lists and tuples: :On Mon, Jan 08, 2001 at 01:40:16PM -0800, Sheila King wrote: :[snip] :| Yes, I can't really figure out how to use procmail on my webhost, and believe :| me, I've tried. My web host is fantastic, but uses a proprietary mail system, :| and no one has yet figured out how to use procmail, although it is installed. : :If it is a Unix box, and if it follows conventions (standards?) you :could put "| /usr/bin/procmail" in a file called '.forward' in your :home directory. Otherwise enjoy working with python instead ;-). I never replied to this, but my host does not follow conventions/standards. They have a proprietary mail system that uses Qmail which then hands off the mail to VManager to deliver to the popboxes. Many have tried to figure out how to use procmail on the system (supposedly installed), but no one, to my knowledge, has succeeded. So, I'm having fun using Python, instead... -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From sheila@thinkspot.net Wed Jan 17 05:01:10 2001 From: sheila@thinkspot.net (Sheila King) Date: Tue, 16 Jan 2001 21:01:10 -0800 Subject: [Tutor] Script performance: Filtering email In-Reply-To: <20010116105154.A16271@pino.selwerd.nl> References: <20010116105154.A16271@pino.selwerd.nl> Message-ID: <2F959311A69@kserver.org> On Tue, 16 Jan 2001 10:51:54 +0100, Remco Gerlich wrote about Re: [Tutor] Script performance: Filtering email: :Maybe you should wrap the whole thing in a try/except to log whatever :goes wrong, like : :try: : (the body of your script) :except: : import sys : f=open("somelogfile","w") : print >> f, sys.exc_info() : f.close() : : raise # Re-raise the exception so that the program doesn't quit silently Would someone please explain the last line above about re-raising the exception? I don't understand what that does. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From sheila@thinkspot.net Wed Jan 17 05:35:33 2001 From: sheila@thinkspot.net (Sheila King) Date: Tue, 16 Jan 2001 21:35:33 -0800 Subject: [Tutor] Script performance: Filtering email In-Reply-To: <20010116105154.A16271@pino.selwerd.nl> References: <20010116105154.A16271@pino.selwerd.nl> Message-ID: <318D67C0586@kserver.org> On Tue, 16 Jan 2001 10:51:54 +0100, Remco Gerlich wrote about Re: [Tutor] Script performance: Filtering email: : :If the connection fails for some reason or other, an exception will :be raised. : :Maybe you should wrap the whole thing in a try/except to log whatever :goes wrong, like : :try: : (the body of your script) :except: : import sys : f=open("somelogfile","w") : print >> f, sys.exc_info() : f.close() : : raise # Re-raise the exception so that the program doesn't quit silently : :If that log file fills up, you know where to look. I can't really :say more from here. OK, I'm definitely throwing exceptions. Here is the log file, after just a few minutes: ------------------------------------------------------------- (, , ) *****My Error Separator line**** (, , ) *****My Error Separator line**** (, , ) *****My Error Separator line**** (, , ) *****My Error Separator line**** ------------------------------------------------------------- I don't see how to track this one down. Can someone give me a tip? Something to point me in the correct direction? -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From sheila@thinkspot.net Wed Jan 17 07:24:04 2001 From: sheila@thinkspot.net (Sheila King) Date: Tue, 16 Jan 2001 23:24:04 -0800 Subject: [Tutor] Script performance: Filtering email In-Reply-To: References: Message-ID: <37C0A060712@kserver.org> Found my bug. The original code is show below. The correction follows. On Tue, 16 Jan 2001 01:18:19 -0800, Sheila King wrote about [Tutor] Script performance: Filtering email: : ##check if to: and cc: addresses are in my approved file : def goodmessage(addresseeslist, rcptlist): : for addr in addresseeslist: : for rcpt in rcptlist: : if (upper(addr[1]) == upper(rcpt)): : return 1 : return 0 Correction: def goodmessage(addresseeslist, rcptlist): for addr in addresseeslist: for rcpt in rcptlist: if (string.upper(addr[1]) == string.upper(rcpt)): return 1 return 0 Note this line, especially: if (string.upper(addr[1]) == string.upper(rcpt)): -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From alan.gauld@bt.com Wed Jan 17 10:10:07 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 17 Jan 2001 10:10:07 -0000 Subject: [Tutor] First script Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D4DF@mbtlipnt02.btlabs.bt.co.uk> > answer = " " this is not needed > query = raw_input("Do you want to restart the INETD daemon? > (yes/no): ") > > answer = query nor is this, just use query... > if len(answer) > 2: I'd make the test: if query[0] in "yY": > print r > elif len(answer) < 2: and this one: elif query[0] in "nN": otherwise if the user tries typing exit, quit or some other panic signal more than 3 chars you will do it anyway! Checkking for y/Y is more likely to respond as required. Alan g. From alan.gauld@bt.com Wed Jan 17 10:14:31 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 17 Jan 2001 10:14:31 -0000 Subject: [Tutor] Another Question Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D4E0@mbtlipnt02.btlabs.bt.co.uk> > | I assume I'm missing the point here but this seems to do it... > | > | >>> class A: > | ... def fun(s,*o): > | ... print "A fun" > print o # try this instead, it's not quite right Oh, you want to *use* the options as well?! :-) I said I thought I was missing something... > I think the "apply" response was correct. I knew the apply would work but it's a bit more obscure. The simple approach seemed to work but I didn't try accessing the parameter values - oops! Alan G From alan.gauld@bt.com Wed Jan 17 10:26:05 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 17 Jan 2001 10:26:05 -0000 Subject: [Tutor] Script performance: Filtering email Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D4E1@mbtlipnt02.btlabs.bt.co.uk> > I have a question, about try/except blocks in general. > (I am assuming they come in pairs, like if/else, right?) Correct, they are almost identical to C++ try/catch pairs. (ISTR YOu have a C++ background?) > If I put > > try: > (body of my script) > > and suppose the script tries to connect to the SMTP server, > but fails, will it try more than once? Only if you code it so. The try simply says "try executing this sequence of instructions and see what happens" ie once thru'. If the block of code raises an exception - either explicitly or because a function it calls does so internally - it will jump to the except part. If the specific exception is caught it will execute that handler otherwise it will percolate up thru' any outer except statements till it reaches the global system handler which will generate the familiar python stack trace etc. > it raised an error, how would I keep the script running and > trying to connect to that server later? use a loop with a timer/sleep inside. Test for success of the connection to break out of the loop. eg to do 3 retries: try: for attempt in range(4): # connect to service # if successful: break # else sleep except: print "failed to connect after 4 attempts" Now if your connect mechanism raises exceptions on failure instead of retirning error codes you simply nest try statements: try: for attempt in range(4): try: # connect to service break except: # sleep except: print "failed to connect after 4 attempts" HTH, Alan G. From alan.gauld@bt.com Wed Jan 17 10:30:44 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Wed, 17 Jan 2001 10:30:44 -0000 Subject: [Tutor] Script performance: Filtering email Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D4E2@mbtlipnt02.btlabs.bt.co.uk> > :try: > : (the body of your script) > :except: > : raise # Re-raise the exception so that the program > Would someone please explain the last line above about re-raising the > exception? I don't understand what that does. It simply prevents the exception handling stopping in your except. The exception gets passed up to the next level and if not handled there(or reraised again) eventually to the global handler which generates a Python stack dump. Normally an except clause handles the error in toto, but using except makes it more like an interception whereby you add some behavior. You might think of it as analogous to calling a super class method in an OO situation. class A: def foo(s): # whatever class B(A): def foo(s): # something else A.foo(s) # similar effect to using raise in exception handler HTH, Alan g. From arcege@shore.net Wed Jan 17 13:08:42 2001 From: arcege@shore.net (Michael P. Reilly) Date: Wed, 17 Jan 2001 08:08:42 -0500 (EST) Subject: [Tutor] Script performance: Filtering email In-Reply-To: <318D67C0586@kserver.org> from "Sheila King" at Jan 16, 2001 09:35:33 PM Message-ID: <200101171308.IAA23851@northshore.shore.net> > > On Tue, 16 Jan 2001 10:51:54 +0100, Remco Gerlich > wrote about Re: [Tutor] Script performance: Filtering email: > > : > :If the connection fails for some reason or other, an exception will > :be raised. > : > :Maybe you should wrap the whole thing in a try/except to log whatever > :goes wrong, like > : > :try: > : (the body of your script) > :except: > : import sys > : f=open("somelogfile","w") > : print >> f, sys.exc_info() > : f.close() > : > : raise # Re-raise the exception so that the program doesn't quit silently > : > :If that log file fills up, you know where to look. I can't really > :say more from here. > > OK, I'm definitely throwing exceptions. Here is the log file, after just a few > minutes: > > ------------------------------------------------------------- > > (, 0x81d2b24>, ) > > > *****My Error Separator line**** > > > (, 0x81d2b24>, ) > > > *****My Error Separator line**** > > > (, 0x81d2b24>, ) > > > *****My Error Separator line**** > > > (, 0x81d2b24>, ) > > > *****My Error Separator line**** > > ------------------------------------------------------------- > > I don't see how to track this one down. Can someone give me a tip? Something > to point me in the correct direction? Instead of printing the exception objects, you will want to print the formatted exception (like you get in the interpreter). For this import the traceback module (_before_ the exception is raised, so not in the except: clause; preferably at the top of the module). Then redirect the output to your logfile: import sys, traceback try: (the body of your script) except: # get the exception information, including exception class, the # exception instance (value) and the traceback object, which includes # the execution "stack" exc, val, tb = sys.exc_info() # append to the logfile logfile = open("somelogfile", "a") traceback.print_exception(exc, val, tb, file=logfile) logfile.close() # just to be sure there is no reference to the traceback del tb For example, within the interpreter, I ran: >>> import sys, traceback >>> try: ... raise Exception("hi there") ... except: ... s = sys.exc_info() ... traceback.print_exception(s[0], s[1], s[2], file=sys.stdout) ... Traceback (innermost last): File "", line 2, in ? Exception: hi there >>> The NameError exception you get means that some "variable" name in the code does not reference an object (i.e. not assigned to a value). -Arcege -- ------------------------------------------------------------------------ | Michael P. Reilly, Release Manager | Email: arcege@shore.net | | Salem, Mass. USA 01970 | | ------------------------------------------------------------------------ From phil.bertram@clear.net.nz Wed Jan 17 18:47:43 2001 From: phil.bertram@clear.net.nz (Phil Bertram) Date: Thu, 18 Jan 2001 07:47:43 +1300 Subject: [Tutor] Unpickling problem Message-ID: <003401c080ba$36a306a0$b23661cb@pf05> Hi all, I have some code in a module named NPCObjects, describing 'Players', 'Matches' and collections of them. This code works fine in command line mode. However I am trying to write a user interface using Tkinter. When try to contruct my NPC object from a menu in Tkinter I get the following error. Note that the __init__ method of my NPC object unpickles a file to create the object. What is going wrong ? Traceback (most recent call last): File "C:\Program Files\Python20\Pythonwin\pywin\framework\scriptutils.py", line 298, in RunScript debugger.run(codeObject, __main__.__dict__, start_stepping=0) File "C:\Program Files\Python20\Pythonwin\pywin\debugger\__init__.py", line 60, in run _GetCurrentDebugger().run(cmd, globals,locals, start_stepping) File "C:\Program Files\Python20\Pythonwin\pywin\debugger\debugger.py", line 582, in run _doexec(cmd, globals, locals) File "C:\Program Files\Python20\Pythonwin\pywin\debugger\debugger.py", line 921, in _doexec exec cmd in globals, locals File "C:\Program Files\Python20\myScripts\NPC_MainFrame.py", line 107, in ? app = NPC_MainFrame(root) File "C:\Program Files\Python20\myScripts\NPC_MainFrame.py", line 7, in __init__ self.npc=NPCObjects.NPC() File "C:\Program Files\Python20\myScripts\NPCObjects.py", line 6, in __init__ self.data=cPickle.load(file) SystemError: Failed to import class Player from module __main__ >>> Regards Phil Bertram phil.bertram@clear.net.nz 07 850 9305 025 426 825 From jack@moonshine.co.uk Tue Jan 16 19:42:57 2001 From: jack@moonshine.co.uk (Jack Green) Date: Tue, 16 Jan 2001 19:42:57 +0000 Subject: [Tutor] Testing CGI scripts offline Message-ID: <4.3.1.0.20010116193944.00a78a30@mail.moonshine.co.uk> Hi Guys, Just wondering if theres any way i can use my home PC to test my CGI python scripts, I'm sure theres a way to do it but i cant find one.. The script is a simple form checker. Thanks in advance, Jack From shaleh@valinux.com Wed Jan 17 19:55:00 2001 From: shaleh@valinux.com (Sean 'Shaleh' Perry) Date: Wed, 17 Jan 2001 11:55:00 -0800 (PST) Subject: [Tutor] Testing CGI scripts offline In-Reply-To: <4.3.1.0.20010116193944.00a78a30@mail.moonshine.co.uk> Message-ID: On 16-Jan-2001 Jack Green wrote: > Hi Guys, > > Just wondering if theres any way i can use my home PC to test my CGI python > scripts, I'm sure theres a way to do it but i cant find one.. > a) many cgi can be run from a prompt, if given the right info b) install a web server locally. From dyoo@hkn.eecs.berkeley.edu Wed Jan 17 20:01:38 2001 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Wed, 17 Jan 2001 12:01:38 -0800 (PST) Subject: [Tutor] Unpickling problem In-Reply-To: <003401c080ba$36a306a0$b23661cb@pf05> Message-ID: On Thu, 18 Jan 2001, Phil Bertram wrote: > Hi all, > > I have some code in a module named NPCObjects, describing 'Players', > 'Matches' and collections of them. This code works fine in command line > mode. However I am trying to write a user interface using Tkinter. > When try to contruct my NPC object from a menu in Tkinter I get the > following error. > Note that the __init__ method of my NPC object unpickles a file to create > the object. > > What is going wrong ? You'll probably need to first import those classes before doing the unpickling --- otherwise, Python won't know what you mean by Players or Matches. The documentation gives some explanation on this: http://python.org/doc/current/lib/module-pickle.html "First of all, the class must be defined at the top level in a module." is the line that's important --- you'll need to make sure that you've done something like: from NPCObjects import Players, Matches before de-pickling. Because you were in the interpreter, those classes were probably toplevel, but in your source code, you may need to add the above line to make things work again. Hope this helps! From dsh8290@rit.edu Wed Jan 17 21:58:10 2001 From: dsh8290@rit.edu (D-Man) Date: Wed, 17 Jan 2001 16:58:10 -0500 Subject: [Tutor] Two questions on MS-DOS In-Reply-To: <000901c07cda$e9eb4a80$80250b3e@oemcomputer>; from facelle@tiscalinet.it on Fri, Jan 12, 2001 at 09:59:56PM +0100 References: <20010112170120.1EE8DF25B@mail.python.org> <000901c07cda$e9eb4a80$80250b3e@oemcomputer> Message-ID: <20010117165810.B23790@harmony.cs.rit.edu> On Fri, Jan 12, 2001 at 09:59:56PM +0100, Fabrizio wrote: | Hi, everybody. | | Python 2.0 on Windows 98. | | Two questions: | | 1 - How can I keep my DOS shell from closing automatically upon the end of a | Python scipt ? (It does not give time to read the parser exceptions and | errors messages !) | I suppose you are double-clicking on a .py file? Set up the association to use 'cmd.exe /k'. (Ex on a particular NT4 system I use: c:\winnt\system32\cmd.exe /k d:\dman\apps\python20\python.exe %1 as the associated command) The /k option tells cmd.exe to remain open (gives you the DOS prompt) once the command that follows the option terminates. I seem to recall the following, but can't duplicate it on this NT system now: before the app closes the DOS window, right click on the title bar select Properties in the 'Properties' there is a checkbox option to close the window automatically when the app terminates | 2 - How can I keep the DOS shell from opening up upon the start of a Python | script ? (I need this when using TKInter, and I do not want to see the DOS | window under TKInter's). | already been answered | Thanks in advance. | | | Fabrizio | HTH, -D From kalle@gnupung.net Wed Jan 17 23:13:49 2001 From: kalle@gnupung.net (Kalle Svensson) Date: Thu, 18 Jan 2001 00:13:49 +0100 Subject: [Tutor] Testing CGI scripts offline In-Reply-To: ; from shaleh@valinux.com on Wed, Jan 17, 2001 at 11:55:00AM -0800 References: <4.3.1.0.20010116193944.00a78a30@mail.moonshine.co.uk> Message-ID: <20010118001349.A993@apone.network.loc> --3MwIy2ne0vdjdPXF Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable Sez Sean 'Shaleh' Perry: >=20 > On 16-Jan-2001 Jack Green wrote: > > Hi Guys, > >=20 > > Just wondering if theres any way i can use my home PC to test my CGI py= thon=20 > > scripts, I'm sure theres a way to do it but i cant find one.. > >=20 I'm just going to expand on these: > a) many cgi can be run from a prompt, if given the right info One way (The Way, most likely) to ensure a script is given the right info is setting the correct environment variables. One to test is QUERY_STRING. The value of QUERY_STRING is parsed for HTTP GET requests to CGI scripts, and the standard library module cgi understands it. The format is simple: "key1=3Dvalue&key2=3Dvalue&key3=3Dvalue" Thus, in a DOS shell (or whatever it's called in NT): c:\myscripts> set QUERY_STRING=3D"test_input=3Dfoo&checkbox1=3Dfish" c:\myscripts> python myformparse.py Content-type: text/html Test cgi

The value of the input field test_input is: "foo"
The checkbox checkbox1 with value "fish" was checked.

Of course assuming your cgi script generates such an output on that input. I hope you get the general idea. If you're on a UNIX machine, the commands are pretty much the same, a bit depending on your shell. On a Mac, I have no idea. > b) install a web server locally. Personal Web Server for Windows comes "free" with Windows 9x, but might be tricky to find and I don't know how it handles CGI. Apache is available both for Windows and UNIX. There are others. Good luck! HTH, Kalle --=20 Email: kalle@gnupung.net | You can tune a filesystem, but you Web: http://www.gnupung.net/ | can't tune a fish. -- man tunefs(8) PGP fingerprint: 0C56 B171 8159 327F 1824 F5DE 74D7 80D7 BF3B B1DD --3MwIy2ne0vdjdPXF Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.4 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE6ZictdNeA1787sd0RAhjQAKDLPa0O/LhXiUHqZI7e6UBNkUZdvQCgnqkc ukLMZPu/Baaz+mnSEnuSINM= =TVQY -----END PGP SIGNATURE----- --3MwIy2ne0vdjdPXF-- From rickp@telocity.com Thu Jan 18 00:31:19 2001 From: rickp@telocity.com (rickp@telocity.com) Date: Wed, 17 Jan 2001 19:31:19 -0500 Subject: [Tutor] event binding Message-ID: <20010117193119.C4954@tc.niof.net> There must be something I'm missing about event binding. What I would really like is to know whenever an Entry widget loses focus but I'll settle for trapping the or . I can bind successfully but the same statement using or does nothing. e_wid = Entry(win) e_wid.bind('',got_event) #doesn't work e_wid.bind('',got_event) #this works def got_event(ev): print "got one!" -- "I'm not interested in running for President. I'm not even interested in _being_ President. I'm interested in living in a free society. And I don't want it to happen just before I die." --- Harry Browne Rick Pasotto email: rickp@telocity.com From arcege@shore.net Wed Jan 17 23:54:25 2001 From: arcege@shore.net (Michael P. Reilly) Date: Wed, 17 Jan 2001 18:54:25 -0500 (EST) Subject: [Tutor] Testing CGI scripts offline In-Reply-To: <4.3.1.0.20010116193944.00a78a30@mail.moonshine.co.uk> from "Jack Green" at Jan 16, 2001 07:42:57 PM Message-ID: <200101172354.SAA20902@northshore.shore.net> > > Hi Guys, > > Just wondering if theres any way i can use my home PC to test my CGI python > scripts, I'm sure theres a way to do it but i cant find one.. > > The script is a simple form checker. > > Thanks in advance, > > Jack I suggest running the CGIHTTPServer that comes with Python ("Batteries Included"). Python 1.5.2 (#1, Aug 25 2000, 09:33:37) [GCC 2.96 20000731 (experimental)] on linux-i386 Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam >>> from BaseHTTPServer import HTTPServer >>> from CGIHTTPServer import CGIHTTPRequestHandler >>> import os >>> os.chdir('/var/www') >>> os.listdir('cgi-bin') ['printenv', 'test-cgi'] >>> serv = HTTPServer(("", 8080), CGIHTTPRequestHandler) >>> serv.serve_forever() Then set your browser to 'http://localhost:8080/cgi-bin/test-cgi' and it will run the /var/www/cgi-bin/test-cgi program. You can set the directory as you need to; it could be a directory on a windoze box or your home directory on UNIX or... -Arcege -- ------------------------------------------------------------------------ | Michael P. Reilly, Release Manager | Email: arcege@shore.net | | Salem, Mass. USA 01970 | | ------------------------------------------------------------------------ From conways5@earthlink.net Thu Jan 18 03:24:05 2001 From: conways5@earthlink.net (The Conways) Date: Wed, 17 Jan 2001 19:24:05 -0800 Subject: [Tutor] Active Python vs. BeOpen Python Message-ID: <000b01c080fe$22394140$fadbaec7@kitchen> Another newbie question: What is the difference between the ActivePython 2.0 release and the Beopen 2.0 release? Thanks Jim From wheelege@tsn.cc Thu Jan 18 05:14:36 2001 From: wheelege@tsn.cc (wheelege) Date: Thu, 18 Jan 2001 16:14:36 +1100 Subject: [Tutor] event binding References: <20010117193119.C4954@tc.niof.net> Message-ID: <000501c0810d$8de92a40$a410fea9@glen> I'm a newbie so this may be wrong, I'll make comments. > There must be something I'm missing about event binding. > > What I would really like is to know whenever an Entry widget loses focus Hmmm stop there... you can always use the binding. like say instead of e_wid.bind('',got_event) you could have e_wid.bind('',got_event) > but I'll settle for trapping the or . > > I can bind successfully but the same statement using or > does nothing. > > e_wid = Entry(win) > e_wid.bind('',got_event) #doesn't work try... e_wid.bind('',got_event) > e_wid.bind('',got_event) #this works > > def got_event(ev): > print "got one!" > Well if it doesn't work then hmmm well, what do you expect I'm a newbie! Glen. From matulya@iitg.ernet.in Thu Jan 18 03:41:59 2001 From: matulya@iitg.ernet.in (Matulya Bansal) Date: Thu, 18 Jan 2001 09:11:59 +0530 (IST) Subject: [Tutor] (no subject) Message-ID: From martok@mattsmail.com Thu Jan 18 23:15:56 2001 From: martok@mattsmail.com (Matthias Hager) Date: Thu, 18 Jan 2001 15:15:56 -0800 Subject: [Tutor] Mysterious .pyc Message-ID: <200101181515.AA170393908@mail.mattsmail.com> I'm learning python, and just read about functions. But whenever I call a function from another file, it creates a file. Say I import leap2 It creates a file called leap2.pyc Why is it doing that? The leap2.pyc has some unreadable junk in it, some of it looks sort of like what I had in leap2. What am I doing to make it do this? And how come I don't have to specify where Python is located on my system in a program? Danke Matthias -- martok@mattsmail.com -- Like my email address? Get your own for FREE at http://firstname.com Get you@JohnsMail.com or you@AlexsMail.com or pick from 500 more! From NHYTRO@compuserve.com Fri Jan 19 06:38:40 2001 From: NHYTRO@compuserve.com (Sharriff Aina) Date: Fri, 19 Jan 2001 01:38:40 -0500 Subject: [Tutor] Tutor digest, Vol 1 #552 - 11 msgs Message-ID: <200101190138_MC2-C245-1734@compuserve.com> Message text written by INTERNET:tutor@python.org >I suggest running the CGIHTTPServer that comes with Python ("Batteries Included"). Python 1.5.2 (#1, Aug 25 2000, 09:33:37) [GCC 2.96 20000731 (experimental)] on linux-i386 Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam >>> from BaseHTTPServer import HTTPServer >>> from CGIHTTPServer import CGIHTTPRequestHandler >>> import os >>> os.chdir('/var/www') >>> os.listdir('cgi-bin') ['printenv', 'test-cgi'] >>> serv =3D HTTPServer(("", 8080), CGIHTTPRequestHandler) >>> serv.serve_forever() Then set your browser to 'http://localhost:8080/cgi-bin/test-cgi' and it will run the /var/www/cgi-bin/test-cgi program. You can set the directory as you need to; it could be a directory on a windoze box or your home directory on UNIX or... -Arcege< Hi Arcege! wow thanks! I=B4ve scorged the net looking for an example to imlement thi= s Module and I came up wuith nothing, what is your experience with this server? have you done some sort of stress test on it? I would like to develop a small intranet application for 20-40 users and I thought it wou= ld be nice code everything in Python. Do you have any experince with MEDUSA(= python server framework)? I can=B4t get it to work, and the mailing list seems to ignore my newbie questions about it. Best regards Sharriff From dyoo@hkn.eecs.berkeley.edu Fri Jan 19 08:26:15 2001 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Fri, 19 Jan 2001 00:26:15 -0800 (PST) Subject: [Tutor] Mysterious .pyc In-Reply-To: <200101181515.AA170393908@mail.mattsmail.com> Message-ID: On Thu, 18 Jan 2001, Matthias Hager wrote: > I'm learning python, and just read about functions. But whenever I > call a function from another file, it creates a file. Say I import > leap2 > > It creates a file called leap2.pyc Why is it doing that? The leap2.pyc > has some unreadable junk in it, some of it looks sort of like what I > had in leap2. What am I doing to make it do this? And how come I don't > have to specify where Python is located on my system in a program? About the .pyc stuff --- it's called "byte-compiled" code. When you're calling something from another file, Python will invest some time in preprocessing the file, translating it into a form that it digests more easily. Usually, you can just ignore the .pyc files, since Python takes care of it on the fly. About Python being known... hmmm... well, isn't that a good thing? *grin* It's possible that Python's is in your system "path", that is, when you request for Python, your system will automatically know where to look. From matulya@iitg.ernet.in Thu Jan 18 03:41:59 2001 From: matulya@iitg.ernet.in (Matulya Bansal) Date: Thu, 18 Jan 2001 09:11:59 +0530 (IST) Subject: [Tutor] (no subject) Message-ID: From kojo@tamu.edu Fri Jan 19 09:15:03 2001 From: kojo@tamu.edu (Kojo Idrissa) Date: Fri, 19 Jan 2001 03:15:03 -0600 Subject: [Tutor] Learning 1.5.2 vs 2.0 In-Reply-To: <3A5BA213.23329627@mindless.com> Message-ID: <5.0.2.1.0.20010119031120.021789f0@pop3.norton.antivirus> This is related to Tim's question about diffs between the two languages. I know a few people wanting to learn Python (I'm still learning myself), but I'm not sure about: 1. Should I tell them to get 1.5.2 or 2.0? 2. If 2.0, are books like 'Learning Python' , 'Python Essential Reference', etc (the books I have)less applicable? If so, what books should they look at? Thanks, **************************** Kojo Idrissa KPMG Scholar Accounting Doctoral Student Texas A&M University Kojo@tamu.edu 401M Wehner Bldg. 979-862-2726 **************************** From kalle@gnupung.net Fri Jan 19 11:37:53 2001 From: kalle@gnupung.net (Kalle Svensson) Date: Fri, 19 Jan 2001 12:37:53 +0100 Subject: [Tutor] Learning 1.5.2 vs 2.0 In-Reply-To: <5.0.2.1.0.20010119031120.021789f0@pop3.norton.antivirus>; from kojo@tamu.edu on Fri, Jan 19, 2001 at 03:15:03AM -0600 References: <3A5BA213.23329627@mindless.com> <5.0.2.1.0.20010119031120.021789f0@pop3.norton.antivirus> Message-ID: <20010119123753.A22460@father> --HcAYCG3uE/tztfnV Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable Sez Kojo Idrissa: > This is related to Tim's question about diffs between the two languages. = I=20 > know a few people wanting to learn Python (I'm still learning myself), bu= t=20 > I'm not sure about: >=20 > 1. Should I tell them to get 1.5.2 or 2.0? I see no reason to recommend 1.5.2. 2.0 should be nicely backwards compatible, except for some standard library modules. But those changes are all for the better, so there's no reason not to learn them right away. > 2. If 2.0, are books like 'Learning Python' , 'Python Essential=20 > Reference', etc (the books I have)less applicable? If so, what books=20 > should they look at? 'Python Essential Reference' is somewhat outdated, but not much, IMO. I haven't read 'Learning Python', but I suspect it works well with 2.0. It should be possible to learn using 1.5.2 with 2.0, and it's easier to go on learning the new stuff if you have it... HTH, Kalle --=20 Email: kalle@gnupung.net | You can tune a filesystem, but you Web: http://www.gnupung.net/ | can't tune a fish. -- man tunefs(8) PGP fingerprint: 0C56 B171 8159 327F 1824 F5DE 74D7 80D7 BF3B B1DD --HcAYCG3uE/tztfnV Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.4 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE6aCcRdNeA1787sd0RAvONAJ9SBOOFHJ7Y8RfoTMAgegYJoBBTDQCgnkNI BvOWqHe0fJlYiqlO3PcskEw= =N4p3 -----END PGP SIGNATURE----- --HcAYCG3uE/tztfnV-- From NHYTRO@compuserve.com Fri Jan 19 12:47:12 2001 From: NHYTRO@compuserve.com (Sharriff Aina) Date: Fri, 19 Jan 2001 07:47:12 -0500 Subject: [Tutor] Tutor digest, Vol 1 #537 - 13 msgs Message-ID: <200101190747_MC2-C24B-BD86@compuserve.com> Hi Guys! heres something from my python console on NT4 Python 2.0 (#8, Oct 19 2000, 11:30:05) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. IDLE 0.6 -- press F1 for help >>> from os import * >>> test1 =3D open('junk.txt', 'w') Traceback (innermost last): File "", line 1, in ? test1 =3D open('junk.txt', 'w') TypeError: an integer is required >>> = the sytax is fine, I =B4ve tried it out several times. I=B4ve noticed tha= t this prooblem starts when I import the OS module, witrhout it, the sytax is ok= ay Could someone explain why this incosistency exists? it=B4s made me very unsure of the scipts that I=B4m writing with file access. Thanks Sharriff From kalle@gnupung.net Fri Jan 19 13:05:55 2001 From: kalle@gnupung.net (Kalle Svensson) Date: Fri, 19 Jan 2001 14:05:55 +0100 Subject: [Tutor] Tutor digest, Vol 1 #537 - 13 msgs In-Reply-To: <200101190747_MC2-C24B-BD86@compuserve.com>; from NHYTRO@compuserve.com on Fri, Jan 19, 2001 at 07:47:12AM -0500 References: <200101190747_MC2-C24B-BD86@compuserve.com> Message-ID: <20010119140555.A22760@father> --wac7ysb48OaltWcw Content-Type: text/plain; charset=iso-8859-1 Content-Disposition: inline Content-Transfer-Encoding: quoted-printable Sez Sharriff Aina: > >>> from os import * > >>> test1 =3D open('junk.txt', 'w') > Traceback (innermost last): > File "", line 1, in ? > test1 =3D open('junk.txt', 'w') > TypeError: an integer is required > >>>=20 >=20 > the sytax is fine, I =B4ve tried it out several times. I=B4ve noticed tha= t this > prooblem starts when I import the OS module, witrhout it, the sytax is ok= ay The problem is that you use from os import *, and os contains a function named open. Check it out: http://www.python.org/doc/current/lib/os-fd-ops.html The solution is: Don't do that. Use import os, not from os import *. Very generally, don't use from ... import * at all, or at least only when you are absolutely, positively sure that it's safe. HTH, Kalle --=20 Email: kalle@gnupung.net | You can tune a filesystem, but you Web: http://www.gnupung.net/ | can't tune a fish. -- man tunefs(8) PGP fingerprint: 0C56 B171 8159 327F 1824 F5DE 74D7 80D7 BF3B B1DD --wac7ysb48OaltWcw Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.4 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE6aDuzdNeA1787sd0RAt72AJ4jkT4tpL6kodKy5G9a5Ku3Y73rJACfS1yN HuZwDvdp6vw3MsEbZLsdvyU= =33JZ -----END PGP SIGNATURE----- --wac7ysb48OaltWcw-- From martok@mattsmail.com Fri Jan 19 14:07:31 2001 From: martok@mattsmail.com (Matthias Hager) Date: Fri, 19 Jan 2001 06:07:31 -0800 Subject: [Tutor] functions, system statements, sleep Message-ID: <200101190607.AA283574522@mail.mattsmail.com> I'm a complete idiot, but when I create a function in Python, how do I run it? Say I create a function that has a main menu. And after the user goes through the introductory, how can I run the main_menu function? How can I get the python interpreter to run a Unix system function? Like say I want it to use 'clear' (Adequately used to clear the screen) How can I get my program, runing in command line to do that? And is there a sleep function in Python, that will make it wait for a couple of seconds before doing anything? There is one in Perl, and I find it really useful. -- %%%################?????????###################^^^ martok@mattsmail.com http://mymymatthias.tripod.com/ %%%################????????####################^^^ -- Like my email address? Get your own for FREE at http://firstname.com Get you@JohnsMail.com or you@AlexsMail.com or pick from 500 more! From cpsoct@lycos.com Fri Jan 19 14:07:50 2001 From: cpsoct@lycos.com (kevin parks) Date: Fri, 19 Jan 2001 23:07:50 +0900 Subject: [Tutor] range query Message-ID: how come range only works with integers? Is there a way to do the same thing with floats-value steps? It seems very unPython like to me. why can't you do this: range(3, 0.5) [0.0 ,0.5, 1.0, 1.5, 2.0, 2.5, 3.0] hmm... inquiring minds want to know... cheers, kevin Seoul, Korea Get your small business started at Lycos Small Business at http://www.lycos.com/business/mail.html From amoreira@mercury.ubi.pt Fri Jan 19 14:36:34 2001 From: amoreira@mercury.ubi.pt (Jose Amoreira) Date: Fri, 19 Jan 2001 14:36:34 +0000 Subject: [Tutor] getpass Message-ID: <3A6850F2.3B60FABE@mercury.ubi.pt> Hello! Something odd happened to me with the getpass module. Let me cut and paste from my shell: pandora:pytut$ python Python 2.0 (#4, Nov 24 2000, 11:42:48) [GCC egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)] on linux2 Type "copyright", "credits" or "license" for more information. >>> import getpass >>> name = getpass.getpass('Type your name: ') Warning: Problem with getpass. Passwords may be echoed. Type your name: Rumpelstitskin >>> getpass gives this warning and indeed it echoes the typed input. I'm running Linux kernel 2.2.14, something vaguely based on a reasonably recent (2000) slackware distribution. Yesterday at home, I tried getpass on my windows box (running Python 2.0 as well) and it ran OK. (I'm not used to things working in mswin and failing in Linux; more often then not, it's the other way around). Can anybody help me with this? Many thanks! Cheers, Ze From amoreira@mercury.ubi.pt Fri Jan 19 14:58:04 2001 From: amoreira@mercury.ubi.pt (Jose Amoreira) Date: Fri, 19 Jan 2001 14:58:04 +0000 Subject: [Tutor] functions, system statements, sleep References: <200101190607.AA283574522@mail.mattsmail.com> Message-ID: <3A6855FC.FDC39B6@mercury.ubi.pt> Hello! Matthias Hager wrote: > I'm a complete idiot, but when I create a function in Python, how do I run it? Say I create a function that has a main menu. And after the user goes through the introductory, how can I run the main_menu function? > I'm much of a genius myself. Anyway, if you defined a function you can run it just by typing its name: pandora:scripts$ python Python 2.0 (#4, Nov 24 2000, 11:42:48) [GCC egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)] on linux2 Type "copyright", "credits" or "license" for more information. >>> def f(x): ... return x**2 ... >>> f(2) 4 >>> Maybe your problem is that you don't supply the parenthesis? Even if the function requires no arguments, you still have to put the parenthesis to run it, as in >>> my_function() I don't know if this answers your question, maybe you could give more details? > > How can I get the python interpreter to run a Unix system function? Like say I want it to use 'clear' (Adequately used to clear the screen) How can I get my program, runing in command line to do that? > You can use the os module, and the command os.system('command'), or the os.popen() commands > > And is there a sleep function in Python, that will make it wait for a couple of seconds before doing anything? There is one in Perl, and I find it really useful. > > -- Yes, but I've never used. It ist time.sleep() Hope it helps! From amoreira@mercury.ubi.pt Fri Jan 19 15:10:29 2001 From: amoreira@mercury.ubi.pt (Jose Amoreira) Date: Fri, 19 Jan 2001 15:10:29 +0000 Subject: [Tutor] range query References: Message-ID: <3A6858E5.41658551@mercury.ubi.pt> Hello kevin parks wrote: > how come range only works with integers? Is there a way to do the same thing with floats-value steps? It seems very unPython like to me. > > why can't you do this: > range(3, 0.5) > > [0.0 ,0.5, 1.0, 1.5, 2.0, 2.5, 3.0] > Yes, it seems that the arguments to range are converted to integers before any action. But if you are running python 2.0 you can do it using list comprehensions: >>> [float(i)/2 for i in range(7)] [0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0] Hope it helps, Ze From dsh8290@rit.edu Fri Jan 19 15:38:37 2001 From: dsh8290@rit.edu (D-Man) Date: Fri, 19 Jan 2001 10:38:37 -0500 Subject: [Tutor] more info about exceptions In-Reply-To: <2B7D5B01699@kserver.org>; from sheila@thinkspot.net on Tue, Jan 16, 2001 at 07:49:40PM -0800 References: <20010116105154.A16271@pino.selwerd.nl> <2D4E9A23B44@kserver.org> <20010116124150.B17678@harmony.cs.rit.edu> <2B7D5B01699@kserver.org> Message-ID: <20010119103837.A4478@harmony.cs.rit.edu> On Tue, Jan 16, 2001 at 07:49:40PM -0800, Sheila King wrote: [snip] | Good tips. Thanks. | | I have a question, about try/except blocks in general. | (I am assuming they come in pairs, like if/else, right?) | | If I put | | try: | (body of my script) | | and suppose the script tries to connect to the SMTP server, but fails, will it | try more than once? Or it tries once, then gives up, and raises an exception? | How many times does "try" try until it gives up? Once? Several times? If I had | some code that was supposed to execute, like it needed to connect to some | server, and for some reason that server was not available for connection, so | it raised an error, how would I keep the script running and trying to connect | to that server later? | I think this part was already answered, but I'm a bit behind in replying ;-). The "try" block simply means that the following block of statements might fail. If it does fail, then below it, in "except" blocks, you have specified the error handling that should be done. It will only try once unless you put a loop around it that specifies to repeat the operation. [ I recall you asking about how exceptions are used, but I can't find the right message to reply to, answer follows ] Suppose you have 2 functions, func1 and func2, that might fail. You call func1, and func1 calls func2 to do the work. In a C-ish system (ie no exceptions) you would have to write code like this: # some new "keywords" to improve readability true = 1 false = 0 success = func1() if not success : print "There was an error" # now check the global /int/ to get an idea of what the error # was perror() # (this is part of the std C lib, but can't produce # REALLY useful messages) return false # now continue with your work return true #################### def func1() : success = func2() if not success : return false # continue with operations Also, if you have several steps to perform that depend on the previous function succeeding, or you have different error handling to do, you can easily end up with several layers of nested if blocks that are ugly, hard to read, and obscure the purpose of your function. Each function must be sure to return success/failure and to check the return of all functions that are called. If you have a Pythonic system (ie you have exceptions) you can instead write stuff like this: try: func1() # some other operations except: print "A useful and informative error message" and func1 could be much simpler def func1() : func2() # func2 will throw an exception if it fails, # in that case, func1's operation will immediately # cease and control will be passed up to the # try/except block that will catch the exception With exceptions, when you are at a deep level of nesting where you don't want to actually handle the exception you can just ignore it and the higher level try/except block will take care of it. (think of a GUI app where opening a file fails, you want the GUI part not the file io part to display an error) Another benefit of exceptions is the following code (I have more practice with the Java std. lib's exceptions at the moment so I'll use those but the idea is the same) try : file = open( "somefilename.text" , "r" ) data = file.readline() do_something_with_data( data ) except IOException , e : print "There was an error reading the file:" print e.getMessage() except DataError , e : # you might define do_something_with_data so that it throws a # DataError exception if the data isn't good print "The data from the file was corrupt." print e.getMessage() The point here is that since an exception is an object it can contain state. The exception's state usually contains a message for the user (e.getMessage()) and can also hold information about what the exact problem was (something that C's errno variable can't do). You can also handle different types of errors in separate blocks and the syntax makes it quite simple. I posted a longer and much more detailed explanation on python-list a while back. Check the archives under the subject "Are exceptions really used in practice" (or something similar). HTH, -D From dsh8290@rit.edu Fri Jan 19 15:51:07 2001 From: dsh8290@rit.edu (D-Man) Date: Fri, 19 Jan 2001 10:51:07 -0500 Subject: [Tutor] range query In-Reply-To: ; from cpsoct@lycos.com on Fri, Jan 19, 2001 at 11:07:50PM +0900 References: Message-ID: <20010119105107.B4478@harmony.cs.rit.edu> On Fri, Jan 19, 2001 at 11:07:50PM +0900, kevin parks wrote: | how come range only works with integers? Is there a way to do the same thing with floats-value steps? It seems very unPython like to me. | | why can't you do this: | range(3, 0.5) This isn't how range orders its arguments. This says you want to count up from 3 to 0. Not exactly possible. ex: range( 0 , 3 ) [ 0 , 1 , 2 ] Also, range is defined only for integers, so if you do provide a step (the /third/ argument) it will be converted to an int first range( 0 , 3 , 0.5 ) **** Error : zero step size # (Oh, 0.5 was rounded down) range( 0 , 3 , 1.5 ) [ 0 , 1 , 2 ] | | [0.0 ,0.5, 1.0, 1.5, 2.0, 2.5, 3.0] This could be useful. Perhaps the following (untested) could work map( range( 0 , 6 ) , lambda x : x/2.0 ) : # My idea here is to double your range, then halve each value. This # ought to work . . . | | hmm... | | inquiring minds want to know... My guess is that floats are just bad things. Basically, ints are well-behaved while floats aren't. Floats are usually represented using binary bits and often in IEEE 754 format. The IEEE format can't represent all floating point numbers. It uses a Scientific Notation style ( 1.x**n ) to store it. Floats can therefore only represent numbers that exist as powers of 2. In C, C++, etc, you can't write the following (equivalent) : for( float i = 0 ; i < 3 ; i++ ) { ... } because the meaning of incrementing a float by 1 is undefined. Also, float comparisons rarely work right ex: if ( (0.0/3.0) == 0 ) : print "true" else : print "false" is likely to print "false". | | cheers, | kevin | Seoul, Korea | As someone else suggested, you could use a list comprehension. You could also define your own float_range function that behaves the way you want it to, but be careful with precision issues. HTH, -D From dsh8290@rit.edu Fri Jan 19 15:59:59 2001 From: dsh8290@rit.edu (D-Man) Date: Fri, 19 Jan 2001 10:59:59 -0500 Subject: [Tutor] functions, system statements, sleep In-Reply-To: <200101190607.AA283574522@mail.mattsmail.com>; from martok@mattsmail.com on Fri, Jan 19, 2001 at 06:07:31AM -0800 References: <200101190607.AA283574522@mail.mattsmail.com> Message-ID: <20010119105959.C4478@harmony.cs.rit.edu> On Fri, Jan 19, 2001 at 06:07:31AM -0800, Matthias Hager wrote: | I'm a complete idiot, but when I create a function in Python, how do I run it? Say I create a function that has a main menu. And after the user goes through the introductory, how can I run the main_menu function? | First you will have to un-learn all the bad habits Perl taught you. As the other poster mentioned, you need to use the parenthesis for all function calls. Also, there is no magic $_ variable that will be given to functions if you forget to specify the argument (you must explicitly pass all necessary arguments to functions). The python community takes the viewpoint that "explicit is better than implicit", in my opinion because it becomes easier to read, understand and debug when the interpreter (or compiler) doesn't do any automagic for you. | How can I get the python interpreter to run a Unix system function? Like say I want it to use 'clear' (Adequately used to clear the screen) How can I get my program, runing in command line to do that? | There is the os.system() function, but I would advise against making heavy use of it. Using it is likely to render your programs unportable to different platforms. An alternative to calling the program "clear" would be to print several blank lines. Suppose I assume the terminal has 24 lines (a vt100 emulator) : for i in range( 24 ) : print This could be extended by somehow (maybe, it might not be possible) querying the terminal for the number of lines it has, or just pick a number that is bigger than any terminal. (Say 500, for an extremist ;-)) There is also the ncurses module, but only exists for Unix systems. This would give you much more flexible and powerful control of the terminal's screen, but it still wouldn't work on other systems (ie Windows, Mac, VMS (?), Amiga, etc). -D From alan.gauld@bt.com Fri Jan 19 16:59:06 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri, 19 Jan 2001 16:59:06 -0000 Subject: [Tutor] Mysterious .pyc Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D4FF@mbtlipnt02.btlabs.bt.co.uk> > import leap2 > > It creates a file called leap2.pyc As already explained Python does that each time you import a module for the first time. On subsequent imports Python will use the .pyc file which makes the program run faster. Python is just trying to be helpful :-) > Why is it doing that? The leap2.pyc has some unreadable junk Yeah, its for python to read not humans. > And how come I don't have to specify where Python is located > on my system in a program? Because the python installer set up your PATH environment variable to point to where it installed Python. The same reason when you click on a document file you don't need to tell windows where your copy of MS Word is stored. Alan g. From martok@mattsmail.com Fri Jan 19 17:12:27 2001 From: martok@mattsmail.com (Matthias Hager) Date: Fri, 19 Jan 2001 09:12:27 -0800 Subject: [Tutor] functions Message-ID: <200101190912.AA214171940@mail.mattsmail.com> I have the () after it and it sometimes works but someimes doesn't. I finally got it to, never mind I'll try to show you. print "A brief intro here" main_menu() def main_menu(): print "Commands here" I finally got that to work, then I added a login function where it asks there name. So it is now: print "A brief intro here" login() main_menu() def main_menu(): print "Commands here" def login(): name = input("What is your name?") But it is giving me the same error, something like: variably login does not exist. What am I doing wrong? Matthias -- Programming isn't cool, it's awesome. %%%################?????????###################^^^ martok@mattsmail.com http://mymymatthias.tripod.com/ %%%################????????####################^^^ -- Like my email address? Get your own for FREE at http://firstname.com Get you@JohnsMail.com or you@AlexsMail.com or pick from 500 more! From alan.gauld@bt.com Fri Jan 19 17:08:24 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri, 19 Jan 2001 17:08:24 -0000 Subject: [Tutor] functions, system statements, sleep Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D501@mbtlipnt02.btlabs.bt.co.uk> > I'm a complete idiot, No you're a beginner that's all. Different concepts :-) > but when I create a function in Python, > how do I run it? Say I create a function that has a main > menu. And after the user goes through the introductory, how > can I run the main_menu function? Are you still using the python >>> prompt? If so you just type the name of the function with parentheses, possibly comntaining some argument values. >>> main_menu() If on the other hand your function is in a file called menu.py and you are writing a program that uses it you will have to >>> import menu first then call it by prepending the module name >>> menu.main_menu() If you are writing you main program in a file called myprog.py then within that you would define main_menu then call it: def main_menu(): # do whatever you do # do some other stuff main_menu() # call main_menu OR if main_menu is in menu.py: import menu menu.main_menu() > How can I get the python interpreter to run a Unix system > function? Like say I want it to use 'clear' import os os.system('clear') Noe that this won't return any values so something like cat, ls etc will just display to stdout, not give you any results back. For that you need popen()... > And is there a sleep function in Python, that will make it > wait for a couple of seconds before doing anything? import time time.sleep(2) > one in Perl, and I find it really useful. Most Perl functions are available in Python but they will be found in a module rather than builtin a Perl does it. If in doubt look in the Python documentation in the Standard Library Reference index. HTH, Alan G. From kalle@gnupung.net Fri Jan 19 17:29:58 2001 From: kalle@gnupung.net (Kalle Svensson) Date: Fri, 19 Jan 2001 18:29:58 +0100 Subject: [Tutor] getpass In-Reply-To: <3A6850F2.3B60FABE@mercury.ubi.pt>; from amoreira@mercury.ubi.pt on Fri, Jan 19, 2001 at 02:36:34PM +0000 References: <3A6850F2.3B60FABE@mercury.ubi.pt> Message-ID: <20010119182958.A23316@father> --W/nzBZO5zC0uMSeA Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable Sez Jose Amoreira: > Hello! > Something odd happened to me with the getpass module. Let me cut and > paste from my shell: >=20 > pandora:pytut$ python > Python 2.0 (#4, Nov 24 2000, 11:42:48) > [GCC egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)] on linux2 > Type "copyright", "credits" or "license" for more information. > >>> import getpass > >>> name =3D getpass.getpass('Type your name: ') > Warning: Problem with getpass. Passwords may be echoed. > Type your name: Rumpelstitskin > >>> >=20 I'm assuming Python 2.0. According to getpass.py, there are two reasons that you get default_getpass= (), which is the getpass implementation that prints the warning, instead of unix_getpass(), which should work. Either import termios, TERMIOS raises an ImportError, or fd =3D sys.stdin.fileno() raises an unspecified exception. Try to figure out which one it is. HTH, Kalle --=20 Email: kalle@gnupung.net | You can tune a filesystem, but you Web: http://www.gnupung.net/ | can't tune a fish. -- man tunefs(8) PGP fingerprint: 0C56 B171 8159 327F 1824 F5DE 74D7 80D7 BF3B B1DD --W/nzBZO5zC0uMSeA Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.4 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE6aHmVdNeA1787sd0RAqlFAKC4xw/YQKgJLt4D5kaEY+Jom6vWuACeLHdt iDHyrHor0W1E7mqjreIJsTA= =EQLA -----END PGP SIGNATURE----- --W/nzBZO5zC0uMSeA-- From alan.gauld@bt.com Fri Jan 19 17:25:59 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri, 19 Jan 2001 17:25:59 -0000 Subject: [Tutor] getpass Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D502@mbtlipnt02.btlabs.bt.co.uk> > >>> import getpass > >>> name = getpass.getpass('Type your name: ') > Warning: Problem with getpass. Passwords may be echoed. > Type your name: Rumpelstitskin > >>> FWIW I get the same result but without the warning on Solaris in Python 1.5.1 the docstring says: >>> import getpass >>> print getpass.__doc__ Utilities to get a password and/or the current user name. getpass(prompt) - prompt for a password, with echo turned off getuser() - get the user name from the environment or password database Authors: Piers Lauder (original) Guido van Rossum (Windows support and cleanup) >>> getpass.getpass('->') ->goo 'goo' >>> Clearly it echos the password. On NT4 it works as described in the docstring... Wierd. Lets take a lok at the code in getpass.py... Aha! On windows it uses the getch() function from msvcrt On unix it uses termios stuff to control the terminal but if import termios fails then it uses a default function which just calls _raw_input() This in turn just uses sys.stdin.readline() which by default echos input. This implies either the import or the termios calls are failing in both of our setups, now the question is why?! Back to the >>> prompt... >>> import termios Traceback (innermost last): File "", line 1, in ? ImportError: No module named termios >>> So that's why. But why is termios missing when getpass is there? And where do I get a valid termios module? And for that I have no answer... anyone else have an idea? Alan g. From shaleh@valinux.com Fri Jan 19 17:46:59 2001 From: shaleh@valinux.com (Sean 'Shaleh' Perry) Date: Fri, 19 Jan 2001 09:46:59 -0800 (PST) Subject: [Tutor] functions In-Reply-To: <200101190912.AA214171940@mail.mattsmail.com> Message-ID: > > login() > main_menu() > > def main_menu(): > print "Commands here" > > def login(): > name = input("What is your name?") > > But it is giving me the same error, something like: variably login does not > exist. > What am I doing wrong? > you need to declare the function before you use it. $ python /tmp/test.py Traceback (innermost last): File "/tmp/test.py", line 3, in ? foo() NameError: foo #!/usr/bin/python foo() def foo(): print "Foo" $ python /tmp/test.py Foo #!/usr/bin/python def foo(): print "Foo" foo() From dsh8290@rit.edu Fri Jan 19 18:34:07 2001 From: dsh8290@rit.edu (D-Man) Date: Fri, 19 Jan 2001 13:34:07 -0500 Subject: [Tutor] functions In-Reply-To: ; from shaleh@valinux.com on Fri, Jan 19, 2001 at 09:46:59AM -0800 References: <200101190912.AA214171940@mail.mattsmail.com> Message-ID: <20010119133407.A5411@harmony.cs.rit.edu> On Fri, Jan 19, 2001 at 09:46:59AM -0800, Sean 'Shaleh' Perry wrote: [snip] | > What am I doing wrong? | > | | you need to declare the function before you use it. | Almost. s/declare/define/ Unlike C and C++, Python doesn't have separate "declaration" and "definition" statements. In Python, "def" is an executable statement that will create a function object and create a binding to that object with the given name. Once the function object is created and bound to the name you can call it. -D From martok@mattsmail.com Fri Jan 19 19:13:45 2001 From: martok@mattsmail.com (Matthias Hager) Date: Fri, 19 Jan 2001 11:13:45 -0800 Subject: [Tutor] functions Message-ID: <200101191113.AA365887820@mail.mattsmail.com> Lindsay got it, I needed to define my functions first. (Which also declares them) I think that could be a major setback, the way I program. Oh, and thanx for all thous help. Matthias -- Programming isn't cool, it's awesome. %%%################?????????###################^^^ martok@mattsmail.com http://mymymatthias.tripod.com/ %%%################????????####################^^^ -- Like my email address? Get your own for FREE at http://firstname.com Get you@JohnsMail.com or you@AlexsMail.com or pick from 500 more! From Bruce Sass Fri Jan 19 20:49:59 2001 From: Bruce Sass (Bruce Sass) Date: Fri, 19 Jan 2001 13:49:59 -0700 (MST) Subject: [Tutor] getpass In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20751D502@mbtlipnt02.btlabs.bt.co.uk> Message-ID: Hi, I'm using 1.5.2 (in /usr) and ActiveState-2.0 (in /usr/local) on a Debian 2.2 system; getpass does not echo when called like "getpass.getpass()" from the interpreter. > >>> import termios > Traceback (innermost last): > File "", line 1, in ? > ImportError: No module named termios > >>> > So that's why. But why is termios missing when getpass is > there? And where do I get a valid termios module? This "termios" stuff is on this system... ~$ locate termios /home/usr/local/ActivePython-2.0/html/lib/module-termios.html /home/usr/local/ActivePython-2.0/html/lib/termios_Example.html /home/usr/local/ActivePython-2.0/lib/python2.0/lib-dynload/termios.so /home/usr/share/doc/python/html/lib/module-termios.html /home/usr/share/doc/python/html/lib/termios_Example.html /usr/include/asm/termios.h /usr/include/bits/termios.h /usr/include/linux/termios.h /usr/include/sys/termios.h /usr/include/termios.h /usr/lib/python1.5/lib-dynload/termios.so /usr/share/aclocal/termios.m4 /usr/share/man/man3/termios.3.gz ~$ There is no module to import because it is builtin. > And for that I have no answer... anyone else have an idea? Is your shared object (.so, .dll(?)) being shared? - Bruce From martok@mattsmail.com Fri Jan 19 21:53:43 2001 From: martok@mattsmail.com (Matthias Hager) Date: Fri, 19 Jan 2001 13:53:43 -0800 Subject: [Tutor] Uncle Sam wants your programs Message-ID: <200101191353.AA471728466@mail.mattsmail.com> I was wondering what programs all of you have developed in Python? I've found that one of the best way to learn is to study source code. So, if you could please help a newbie learn, and get more interest in your programs, email them or a link to them to me please. martok@mattsmail.com I especially am interested in applications with a GUI? But anything (everything) will do. Matthias -- Programming isn't cool, it's awesome. %%%################?????????###################^^^ martok@mattsmail.com http://mymymatthias.tripod.com/ %%%################????????####################^^^ -- Like my email address? Get your own for FREE at http://firstname.com Get you@JohnsMail.com or you@AlexsMail.com or pick from 500 more! From dyoo@hkn.eecs.berkeley.edu Sat Jan 20 02:07:47 2001 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Fri, 19 Jan 2001 18:07:47 -0800 (PST) Subject: [Tutor] Tutor digest, Vol 1 #537 - 13 msgs In-Reply-To: <20010119140555.A22760@father> Message-ID: > > >>> from os import * > > >>> test1 = open('junk.txt', 'w') > > Traceback (innermost last): > > File "", line 1, in ? > > test1 = open('junk.txt', 'w') > > TypeError: an integer is required > > The problem is that you use from os import *, and os contains a function > named open. Check it out: > http://www.python.org/doc/current/lib/os-fd-ops.html > > The solution is: Don't do that. Use import os, not from os import *. > Very generally, don't use from ... import * at all, or at least only when > you are absolutely, positively sure that it's safe. As a clarification, doing: from os import open as osopen would prevent the naming conflict. It's unfortunate that they have the same name, but Python lets us rename functions if we really need to. This only works with Python 2.0 though. From dyoo@hkn.eecs.berkeley.edu Sat Jan 20 02:27:48 2001 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Fri, 19 Jan 2001 18:27:48 -0800 (PST) Subject: [Tutor] functions, system statements, sleep In-Reply-To: <20010119105959.C4478@harmony.cs.rit.edu> Message-ID: On Fri, 19 Jan 2001, D-Man wrote: > On Fri, Jan 19, 2001 at 06:07:31AM -0800, Matthias Hager wrote: | I'm > a complete idiot, but when I create a function in Python, how do I run > it? Say I create a function that has a main menu. And after the user > goes through the introductory, how can I run the main_menu function? | > > First you will have to un-learn all the bad habits Perl taught you. Whoa, whoa --- it's not bad, only different. Perl has its own philosophy, and there isn't a need to classify it as bad. (Sorry about that --- I'm just touchy sometimes...) About calling conventions --- at least it isn't like Matlab: according to Matlab, if we have a function that doesn't have parameters, it's illegal to put: function() Matlab will refuse to accept something logical like this --- it's wants to just see function without parenthesis. Now that's evil. *grin* From dyoo@hkn.eecs.berkeley.edu Sat Jan 20 02:41:18 2001 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Fri, 19 Jan 2001 18:41:18 -0800 (PST) Subject: [Tutor] getpass In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20751D502@mbtlipnt02.btlabs.bt.co.uk> Message-ID: On Fri, 19 Jan 2001 alan.gauld@bt.com wrote: > >>> import termios > Traceback (innermost last): > File "", line 1, in ? > ImportError: No module named termios > >>> > > So that's why. But why is termios missing when getpass is > there? And where do I get a valid termios module? > > And for that I have no answer... anyone else have an idea? It's an optional module --- if you compiled Python maually, you'll need to turn it on from the Modules/Setup file. For example, here's the entry that's about termios: ### # Some more UNIX dependent modules -- off by default, since these # are not supported by all UNIX systems: #nis nismodule.c -lnsl # Sun yellow pages -- not everywhere #termios termios.c # Steen Lumholt's termios module #resource resource.c # Jeremy Hylton's rlimit interface ### So that's probably why the import wasn't working. You can just uncomment that line and recompile, and things should work then. From sheila@thinkspot.net Sat Jan 20 05:57:00 2001 From: sheila@thinkspot.net (Sheila King) Date: Fri, 19 Jan 2001 21:57:00 -0800 Subject: [Tutor] Translating a Perl script into Python Message-ID: As part of my learning exercises, I've been attempting to translate a short perl script into Python. I don't really know Perl, but when I was attempting to learn how to use the .qmail files at my web host and run scripts on it for filtering, etc... the sysadmin posted a sample script in Perl to give me an idea what some of the possibilities might be. I think I understand the Perl script well enough to try to translate it. So, here I will present the two scripts: (1) The original Perl script written by the sysadmin at my web host, and (2) my attempt at a Python translation. I've already tested it, and the output files are identical. I'm curious about style or good programming type comments. Note: the identifiers SENDER NEWSENDER RECIPIENT USER HOME HOST LOCAL EXT EXT2 EXT3 EXT4 DTLINE RPLINE UFLINE are environment variables passed by .qmail to the script. Here is the original Perl script: ------------------------------------------------------------ #!/usr/local/bin/perl @slurp = <>; @qmail = qw(SENDER NEWSENDER RECIPIENT USER HOME HOST LOCAL EXT EXT2 EXT3 EXT4 DTLINE RPLINE UFLINE); open PROC, ">proc.test" || die "Couldn't open file for write: $!"; $id = `/usr/bin/id`; print PROC "ID: $id\n"; print PROC "Environment Variables\n"; foreach $key (@qmail) { print PROC "$key = $ENV{$key}\n"; } print PROC "\nSlurp\n"; print PROC @slurp; close PROC; ------------------------------------------------------------ Here is my Python translation: ------------------------------------------------------------ #! /big/dom/xthinkspot/Python-2.0/python import sys, os, commands slurp = sys.stdin.read() qmail = ["SENDER", "NEWSENDER", "RECIPIENT", "USER", "HOME", "HOST", "LOCAL", "EXT", "EXT2", "EXT3", "EXT4", "DTLINE", "RPLINE", "UFLINE"] try: PROC = open("proc.test","w") except: sys.stderr << "Couldn't open file for write\n" raise id = commands.getoutput("/usr/bin/id") PROC.write("ID: "+id+"\n\n") PROC.write("Environment Variables\n") for key in qmail: PROC.write(key + " = " + os.environ[key] + "\n") PROC.write("\nSlurp\n") for line in slurp: PROC.write(line) PROC.close() ------------------------------------------------------------ I appreciate all comments, -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From dyoo@hkn.eecs.berkeley.edu Sat Jan 20 09:56:30 2001 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Sat, 20 Jan 2001 01:56:30 -0800 (PST) Subject: [Tutor] Translating a Perl script into Python In-Reply-To: Message-ID: On Fri, 19 Jan 2001, Sheila King wrote: > As part of my learning exercises, I've been attempting to translate a short > perl script into Python. Let's take a look at one particular line: > @qmail = qw(SENDER NEWSENDER RECIPIENT USER HOME HOST LOCAL EXT EXT2 EXT3 > EXT4 DTLINE RPLINE UFLINE); > qmail = ["SENDER", "NEWSENDER", "RECIPIENT", "USER", "HOME", "HOST", "LOCAL", > "EXT", "EXT2", "EXT3", "EXT4", "DTLINE", "RPLINE", "UFLINE"] You could also write that as: qmail = "SENDER NEWSENDER RECIPIENT USER HOME HOST LOCAL EXT\ EXT2 EXT3 EXT4 DTLINE RPLINE UFLINE".split() String methods are fun! I think this is close to the spirit of Perl's qw() "quoteword" function. If you don't have Python 2.0, then calling string.split() on the string will have the same effect. Let's look at another part of the program: @slurp = <>; # [some stuff cut] print PROC @slurp; versus: slurp = sys.stdin.read() # [some stuff cut] for line in slurp: PROC.write(line) This isn't quite equivalent because the Perl code is printing lines at a time, but the Python code is printing single characters at a time. We get the same effect eventually, but it's not as direct as: PROC.write(slurp) Just write thatwhole string out, since slurp already has those newlines embedded into it. The distinction makes more sense with a small interpreter session: ### >>> mystr = "test\nme" >>> for ch in mystr: print ch # commentary: iteration over chars ... t e s t m e >>> from sys import stdout >>> for ch in mystr: stdout.write(ch) ... # same thing, but hidden by write()'s behavior test me>>> print mystr test me >>> stdout.write(mystr) # almost the same, and easier to understand test me>>> ### Strings are sequences --- that is, you can go through each character with a for-loop. In your code above, though, this is probably not what you wanted. Hope this helps! From dyoo@hkn.eecs.berkeley.edu Sat Jan 20 10:10:04 2001 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Sat, 20 Jan 2001 02:10:04 -0800 (PST) Subject: [Tutor] Uncle Sam wants your programs In-Reply-To: <200101191353.AA471728466@mail.mattsmail.com> Message-ID: On Fri, 19 Jan 2001, Matthias Hager wrote: > I was wondering what programs all of you have developed in Python? > I've found that one of the best way to learn is to study source code. > So, if you could please help a newbie learn, and get more interest in > your programs, email them or a link to them to me please. > martok@mattsmail.com I especially am interested in applications with a > GUI? But anything (everything) will do. Here are a few links: Vaults of Parnassus http://www.vex.net/parnassus Useless Python Pages http://www.lowerstandard.com/python/pythonsource.html and the majority of the source code to the standard library modules is already installed with Python, so you can always take a look at how the Python Gods do it. The modules should be in the Lib/ directory where you installed Python. Good luck! From abreu@penguinpowered.com Sat Jan 20 14:29:54 2001 From: abreu@penguinpowered.com (Jose Alberto Abreu) Date: Sat, 20 Jan 2001 08:29:54 -0600 Subject: [Tutor] Re: Example source code.. References: <01010612405300.00619@localhost.localdomain> Message-ID: <3A69A0E2.64D2BB51@penguinpowered.com> Sounds good... you have my vote! John Murray wrote: > Tesla Coil wrote: > >I've often thought an Interesting list would have posts of Python > >source as its topic. What typically motivates an initial post of > >source to the Tutor list is that the author finds it to be deficient. > > >What's lost are the one-shot scripts you've knocked off, maybe > >with little alteration of repeated use to someone else, not deemed > >important enough to publish on your web page, and no one expects > >to find it scattered off on your URL anyway. > > > >And perhaps utility wasn't even the point. Perhaps you had in > >mind a clever function to reduce the iterations in calculating a > >large factorial. A nice conversation piece, provided an audience > >who might appreciate that your only interest in the usual method > >would be comparing the performance of this approach. > > > >You could post it to comp.lang.python, but again, too unimportant > >to bother distracting anyone from the latest debate on whether > >this or that fundamental aspect of the language is a Good Thing. > > > >Ideally, the list topic would be *unimportant* Python source. > >I'd be compelled to subscribe to that one. > > Nicely put. I'd like to see something like this, perhaps we could take up > Rob.A's kind offer of server space (I think using SourceForge might be > overkill?). All we would need is a simple web page with links to the various > scripts. Tutor list members could post their code with a name and brief > description; author names would be optional for the anon. cowards:-) > Periodically (every fortnight?), the site address and any new additions could > be posted in a brief tutor-list message. Would we set it up so that list > members can ftp their files directly to the site? Or would it be better to have > them sent to the site's maintainer, who would then list them on the download > page? I'd be happy to help in any way I can. > Cheers, > Johnno > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://www.python.org/mailman/listinfo/tutor From martok@mattsmail.com Sat Jan 20 17:25:15 2001 From: martok@mattsmail.com (Matthias Hager) Date: Sat, 20 Jan 2001 09:25:15 -0800 Subject: [Tutor] Text editor Message-ID: <200101200925.AA708051190@mail.mattsmail.com> I'm trying to create a simple text editor. From my knowledge, I have a save as command on the file menu. But I need a save command, that will save without having to open the dialog box, and make them confirm it and everything. I have an idea, that I could just use the open() command, and write it to the file that they have open. But how do I get the name of the file they have open for this function? And what code do I use to write what they have typed in the text bok to that file? One more thing, how could I check to see if they have made any changes to an open file in that editor? Thanks in advance Matthias -- Programming isn't cool, it's awesome. %%%################?????????###################^^^ martok@mattsmail.com http://mymymatthias.tripod.com/ %%%################????????####################^^^ -- Like my email address? Get your own for FREE at http://firstname.com Get you@JohnsMail.com or you@AlexsMail.com or pick from 500 more! From facelle@tiscalinet.it Sat Jan 20 17:42:42 2001 From: facelle@tiscalinet.it (Fabrizio) Date: Sat, 20 Jan 2001 18:42:42 +0100 Subject: [Tutor] More path questions Message-ID: <001f01c08308$a8180f60$50220b3e@oemcomputer> Hi, Newbie. Python 20 and Windows 98. Thanks to some of you, now I know that if I want the python interpreter to search for a specific directory where I keep my modules, I have to modify the PYTHONPATH variable. In my case (Win98) this can be done by adding to the autoexec.bat file a line like that : set PYTHONPATH = C:\MYMODULES Well, my question now is : how can I change it so that it searches all the subdirectories too ? e.g. I have c:\mymodules\program1 and c:\my modules\program2; is there a way to avoid adding TWO lines to my autoexec.bat file ? Thanks in advance. Fabrizio C. From sheila@thinkspot.net Sat Jan 20 20:42:23 2001 From: sheila@thinkspot.net (Sheila King) Date: Sat, 20 Jan 2001 12:42:23 -0800 Subject: [Tutor] Text editor In-Reply-To: <200101200925.AA708051190@mail.mattsmail.com> References: <200101200925.AA708051190@mail.mattsmail.com> Message-ID: <409E20E273A@kserver.org> On Sat, 20 Jan 2001 09:25:15 -0800, "Matthias Hager" wrote about [Tutor] Text editor: :I'm trying to create a simple text editor. From my knowledge, I have a save as command on the file menu. But I need a save command, that will save without having to open the dialog box, and make them confirm it and everything. I have an idea, that I cou ld just use the open() command, and write it to the file that they have open. But how do I get the name of the file they have open for this function? And what code do I use to write what they have typed in the text bok to that file? : :One more thing, how could I check to see if they have made any changes to an open file in that editor? I would think that, in order to use the "Save" command, the user would already have had to specify a file name, either to: (1) open an already existing file in the first place, or (2) to save the file the first time (using SaveAs). Somehow the user has already indicated the name of the file by this point. So, you should have that saved in some name, like currentFile or workingFile or something like that. The file shouldn't be open at the time that the user is typing and just before they save. You should be holding the changes in some list or temp file or something like that. Then when they "save" you open the currentFile and write the new changes on to it. And close it. At least, this is how I would approach it? -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From dsh8290@rit.edu Sat Jan 20 20:44:45 2001 From: dsh8290@rit.edu (D-Man) Date: Sat, 20 Jan 2001 15:44:45 -0500 Subject: [Tutor] functions, system statements, sleep In-Reply-To: ; from dyoo@hkn.eecs.berkeley.edu on Fri, Jan 19, 2001 at 06:27:48PM -0800 References: <20010119105959.C4478@harmony.cs.rit.edu> Message-ID: <20010120154445.A9183@harmony.cs.rit.edu> On Fri, Jan 19, 2001 at 06:27:48PM -0800, Daniel Yoo wrote: | On Fri, 19 Jan 2001, D-Man wrote: | | > On Fri, Jan 19, 2001 at 06:07:31AM -0800, Matthias Hager wrote: | I'm | > a complete idiot, but when I create a function in Python, how do I run | > it? Say I create a function that has a main menu. And after the user | > goes through the introductory, how can I run the main_menu function? | | > | > First you will have to un-learn all the bad habits Perl taught you. | | Whoa, whoa --- it's not bad, only different. Perl has its own philosophy, | and there isn't a need to classify it as bad. (Sorry about that --- I'm | just touchy sometimes...) | It is certainly different. I believe that taking shortcuts like omitting variable names (using the "magic" $_ instead) and omitting arguments (and/or parens) when calling functions is just asking for trouble. Thus I think it is bad. (but, of course, most (all?) classifications are just based on opinion anyways so there is no purpose in arguing the point) If you are simply writing a one-time script to change something it might not be so bad of a feature, but if you are trying to debug a full application it is a nightmare. | About calling conventions --- at least it isn't like Matlab: according to | Matlab, if we have a function that doesn't have parameters, it's illegal | to put: | | function() | | Matlab will refuse to accept something logical like this --- it's wants to | just see | | function | | without parenthesis. Now that's evil. *grin* | Of course. ;-) -D From martok@mattsmail.com Sat Jan 20 22:53:05 2001 From: martok@mattsmail.com (Matthias Hager) Date: Sat, 20 Jan 2001 14:53:05 -0800 Subject: [Tutor] functions, system statements, sleep Message-ID: <200101201453.AA484901154@mail.mattsmail.com> I'm trying to decide whether I like Perl or Python better. The use of a GUI in Python is good(Is there a way to use Tkinter or any other GUI with Perl?) I used indentation anyway on perl, so I don't mind that. I now don't like that you have to create your function first, I usually get my program out of the way, then make my functions. And I wouldn't mind if Windoze users couldn't use my program, but they do make up about 80% of all computer users (probably, I just picked a number that sounded good) But thanks all of you for the help. Matthias -- Programming isn't cool, it's awesome. %%%################?????????###################^^^ martok@mattsmail.com http://mymymatthias.tripod.com/ %%%################????????####################^^^ -- Like my email address? Get your own for FREE at http://firstname.com Get you@JohnsMail.com or you@AlexsMail.com or pick from 500 more! From martok@mattsmail.com Sat Jan 20 23:45:27 2001 From: martok@mattsmail.com (Matthias Hager) Date: Sat, 20 Jan 2001 15:45:27 -0800 Subject: [Tutor] text editor problems Message-ID: <200101201545.AA673972564@mail.mattsmail.com> That's what I thought(just see if those variables are there), I have(kind of, just reworded for less space) def save(): if sname: open sname and write to it elif oname: open oname and write to it else: saveas() def saveas(): sname = asksaveasfile blah blah def open(): oname = askopenfile blahblah Then it gives me the error: No variable named sname exists. I know you guys gotta be getting sick of me, but what am I doing wrong? I can't figure it out, and I've tried changing it to: if oname != "": elif sname != "": All kinds of stuff, but I'm still getting an error. Any help is appreciated Matthias -- Programming isn't cool, it's awesome. %%%################?????????###################^^^ martok@mattsmail.com http://mymymatthias.tripod.com/ %%%################????????####################^^^ -- Like my email address? Get your own for FREE at http://firstname.com Get you@JohnsMail.com or you@AlexsMail.com or pick from 500 more! From martok@mattsmail.com Sat Jan 20 23:47:15 2001 From: martok@mattsmail.com (Matthias Hager) Date: Sat, 20 Jan 2001 15:47:15 -0800 Subject: [Tutor] (no subject) Message-ID: <200101201547.AA416088308@mail.mattsmail.com> Now it justs gives me the save as dialog box all the time. Matthias -- Programming isn't cool, it's awesome. %%%################?????????###################^^^ martok@mattsmail.com http://mymymatthias.tripod.com/ %%%################????????####################^^^ -- Like my email address? Get your own for FREE at http://firstname.com Get you@JohnsMail.com or you@AlexsMail.com or pick from 500 more! From wheelege@tsn.cc Sun Jan 21 01:27:41 2001 From: wheelege@tsn.cc (wheelege) Date: Sun, 21 Jan 2001 12:27:41 +1100 Subject: [Tutor] More path questions References: <001f01c08308$a8180f60$50220b3e@oemcomputer> Message-ID: <004f01c08349$59758860$a410fea9@glen> What you CAN do is separate each path itch a semicolon- eg. set PYTHONPATH = C:\MYMODULES;C:\PYTHON20;C:\WINDOWS\COMMAND etc I don't know if this is the best solution, but it's the one that I use. Hope I helped, GLen. > Hi, > > Newbie. Python 20 and Windows 98. > > > Thanks to some of you, now I know that if I want the python interpreter to > search for a specific directory where I keep my modules, I have to modify > the PYTHONPATH variable. > In my case (Win98) this can be done by adding to the autoexec.bat file a > line like that : > > set PYTHONPATH = C:\MYMODULES > > Well, my question now is : how can I change it so that it searches all the > subdirectories too ? > e.g. I have c:\mymodules\program1 and c:\my modules\program2; is there a > way to avoid adding TWO lines to my autoexec.bat file ? > > Thanks in advance. > > Fabrizio C. > > > > > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From martok@mattsmail.com Sun Jan 21 01:56:09 2001 From: martok@mattsmail.com (Matthias Hager) Date: Sat, 20 Jan 2001 17:56:09 -0800 Subject: [Tutor] (no subject) Message-ID: <200101201756.AA702415188@mail.mattsmail.com> I know you guys are about to rip your hair out over me, I'm annoying I know! But I have some questions here on how to do some special stuff in Python. (And is it possible to use a GUI with Perl?) 1. How do I access the clipboard, so I can make cut and paste options? 2. What all does ScrollingText support? I've found background, fg, font. What else is there? How can I change the size of the text, and how can I add the ability to have the user change the text color and everything? How can I change how it rounds off its text on the right? It justs takes whatever you type to the next line, cutting words in two. How can I change the blinking | thing's color? And finally, how can I make it say stuff according to what they type? Like in idle, if you start typing askopenfilename() It will tell you what to type in? How do I do that? 3. What are, and how do I use classes? A program I saw, uses them, but what are they? 4. How do I open another window, that has more stuff in it, like buttons and stuff? 5. How can I change what it says when they hover over an icon to my program? 6. How do I check if they have made any changes to a file, and do something according to whether they have or not? Again, I'm sorry to bother you all. But thanks, A LOT. Matthias -- Programming isn't cool, it's awesome. %%%################?????????###################^^^ martok@mattsmail.com http://mymymatthias.tripod.com/ %%%################????????####################^^^ -- Like my email address? Get your own for FREE at http://firstname.com Get you@JohnsMail.com or you@AlexsMail.com or pick from 500 more! From moshez@zadka.site.co.il Sun Jan 21 13:52:59 2001 From: moshez@zadka.site.co.il (Moshe Zadka) Date: Sun, 21 Jan 2001 15:52:59 +0200 (IST) Subject: [Tutor] functions, system statements, sleep In-Reply-To: <200101201453.AA484901154@mail.mattsmail.com> References: <200101201453.AA484901154@mail.mattsmail.com> Message-ID: <20010121135259.8EB18A83E@darjeeling.zadka.site.co.il> On Sat, 20 Jan 2001, "Matthias Hager" wrote: > Is there a way to use Tkinter or any other GUI with Perl? There's Perl/Tk, and there are also Gtk+ Perl bindings. ) I now don't like that you have to create your function first, > I usually get my program out of the way, then make my functions. def main(): func1() func2() def func1(): pass def func2(): pass if __name__ == '__main__': main() -- Moshe Zadka This is a signature anti-virus. Please stop the spread of signature viruses! Fingerprint: 4BD1 7705 EEC0 260A 7F21 4817 C7FC A636 46D0 1BD6 From wheelege@tsn.cc Sun Jan 21 05:49:05 2001 From: wheelege@tsn.cc (wheelege) Date: Sun, 21 Jan 2001 16:49:05 +1100 Subject: [Tutor] Re: [Turor] text editor problems Message-ID: <00d301c0836d$de094fc0$a410fea9@glen> This is a multi-part message in MIME format. ------=_NextPart_000_00D0_01C083CA.110BEAC0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hi, I'm pretty sure that you need to pass those variables in as arguments = to the function save(). Like.. def save(sname, oname) # code and when you call it... save(sname, oname) # pass the variables sname and oname I'm still a newbie so don't flame me if it doesn't turn out... Glen. ----- Original Message ----- From: Matthias Hager To: Sent: Sunday, January 21, 2001 10:45 AM Subject: [Tutor] text editor problems > That's what I thought(just see if those variables are there), I = have(kind of, just reworded for less space) > > def save(): > if sname: > open sname and write to it > elif oname: > open oname and write to it > else: > saveas() > > def saveas(): > sname =3D asksaveasfile > blah blah > > def open(): > oname =3D askopenfile > blahblah > > Then it gives me the error: No variable named sname exists. > > I know you guys gotta be getting sick of me, but what am I doing = wrong? > I can't figure it out, and I've tried changing it to: > if oname !=3D "": > elif sname !=3D "": > > All kinds of stuff, but I'm still getting an error. > > Any help is appreciated > > Matthias > > > > > -- > Programming isn't cool, it's awesome. > > %%%################?????????###################^^^ > > martok@mattsmail.com > http://mymymatthias.tripod.com/ > > %%%################????????####################^^^ > > > -- > > > > Like my email address? Get your own for FREE at http://firstname.com > Get you@JohnsMail.com or you@AlexsMail.com or pick from 500 more! > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor ------=_NextPart_000_00D0_01C083CA.110BEAC0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable

  Hi,

  I'm pretty sure that you need to pass = those=20 variables in as arguments to
the function save().

 =20 Like..

def save(sname, oname)
  # code

and when = you call=20 it...

save(sname, oname) # pass the variables sname and=20 oname

  I'm still a newbie so don't flame me if it doesn't = turn=20 out...

  Glen.

----- Original Message -----
From: = Matthias=20 Hager <martok@mattsmail.com>
To: = <tutor@python.org>
Sent: = Sunday, January=20 21, 2001 10:45 AM
Subject: [Tutor] text editor = problems


>=20 That's what I thought(just see if those variables are there), I = have(kind
of,=20 just reworded for less space)
>
> def = save():
>   if=20 sname:
>     open sname and write to=20 it
>   elif oname:
>     open = oname=20 and write to it
>   = else:
>    =20 saveas()
>
> def saveas():
>   sname =3D=20 asksaveasfile
>   blah blah
>
> def=20 open():
>   oname =3D askopenfile
>  =20 blahblah
>
> Then it gives me the error: No variable named = sname=20 exists.
>
> I know you guys gotta be getting sick of me, but = what am=20 I doing wrong?
> I can't figure it out, and I've tried changing it = to:
> if oname !=3D "":
> elif sname !=3D = "":
>
> All kinds=20 of stuff, but I'm still getting an error.
>
> Any help is=20 appreciated
>
> = Matthias
>
>
>
>
>=20 --
> Programming isn't cool, it's awesome.
>
>=20 %%%################?????????###################^^^
>
> &= nbsp;        =20 martok@mattsmail.com
>&nbs= p;     =20 http://mymymatthias.tripod.com/<= /A>
>
>=20 %%%################????????####################^^^
>
>
>= ;=20 --
>
>
>
> Like my email address? Get your own = for FREE=20 at http://firstname.com
> Get = you@JohnsMail.com or you@AlexsMail.com or pick from 500 = more!
>
>
>=20 _______________________________________________
> Tutor = maillist =20 -  Tutor@python.org
> = http://mail.python= .org/mailman/listinfo/tutor
------=_NextPart_000_00D0_01C083CA.110BEAC0-- From wheelege@tsn.cc Sun Jan 21 05:58:20 2001 From: wheelege@tsn.cc (wheelege) Date: Sun, 21 Jan 2001 16:58:20 +1100 Subject: [Tutor] (no subject) References: <200101201756.AA702415188@mail.mattsmail.com> Message-ID: <00f301c0836f$28b912c0$a410fea9@glen> Alright, comments through. ----- Original Message ------ From: Matthias Hager To: Sent: Sunday, January 21, 2001 12:56 PM Subject: [Tutor] (no subject) > I know you guys are about to rip your hair out over me, I'm annoying I know! But I have some questions here on how to do some special stuff in Python. (And is it possible to use a GUI with Perl?) Yes, you can use Tcl with Perl. > > 1. How do I access the clipboard, so I can make cut and paste options? Don't know, try the tutorial or searching the docs. > 2. What all does ScrollingText support? I don't know if this is the answer you wanted, but the ScrollBar (or something) widget can be slapped on most things if neccessary. > I've found background, fg, font. What else is there? Look in the docs for those widgets in question. > How can I change the size of the text, and how can I add the ability to have the user change the text color and everything? Again, docs are the key. > How can I change how it rounds off its text on the right? It justs takes whatever you type to the next line, cutting words in two. Clever manipulating of the string module, or you could always set the text box up to do it - I think I saw a wordwrap option somewhere. Just punch in a carriage return if they are still typing a word (ie no spacebar character been pushed yet) > How can I change the blinking | thing's color? Don't know/look in documentation... > And finally, how can I make it say stuff according to what they type? Like in idle, if you start typing askopenfilename() It will tell you what to type in? How do I do that? Use a for loop, stick an if in there and compare it to a dictionary (at a guess..probably a much easier way) > > 3. What are, and how do I use classes? A program I saw, uses them, but what are they? Classes are really cool things. Read the tutorial - it explains it way better than I could. > 4. How do I open another window, that has more stuff in it, like buttons and stuff? Create a new toplevel widget, shove stuff in it. Or you could use a mega-widget. Again, look in the documentation for the toplevel widgets, pmw etc. > 5. How can I change what it says when they hover over an icon to my program? Say time how long a pointer has been over a widget - you can use events such as mouseenter, mouseleave (I think). > > 6. How do I check if they have made any changes to a file, and do something according to whether they have or not? > I haven't done much with files...but at a guess, just compare the two using.. if file == oldfile: code > Again, I'm sorry to bother you all. > But thanks, A LOT. > Hope I helped - I'm totally new too. Seems you have alot of reading ahead of you :) Glen. > Matthias > > > > > > -- > Programming isn't cool, it's awesome. > > %%%################?????????###################^^^ > > martok@mattsmail.com > http://mymymatthias.tripod.com/ > > %%%################????????####################^^^ > > > -- > > > > Like my email address? Get your own for FREE at http://firstname.com > Get you@JohnsMail.com or you@AlexsMail.com or pick from 500 more! > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From cpsoct@lycos.com Sun Jan 21 09:00:36 2001 From: cpsoct@lycos.com (kevin parks) Date: Sun, 21 Jan 2001 18:00:36 +0900 Subject: [Tutor] How to test a list for nesting Message-ID: Is there a way to test if a list in nested and if so how deep? so that you could type y=[1,2,3] x=[1,[2,3]] howDeep(y) howDeep(x) and it would return 0 (no nesting) for y and 1, for x (1 level of nesting) Is this possible? It would seem really useful, but i don't see anything in the docs about how to do this. cheers, kevin parks seoul korea Get your small business started at Lycos Small Business at http://www.lycos.com/business/mail.html From arcege@shore.net Sun Jan 21 13:39:05 2001 From: arcege@shore.net (Michael P. Reilly) Date: Sun, 21 Jan 2001 08:39:05 -0500 (EST) Subject: [Tutor] How to test a list for nesting In-Reply-To: from "kevin parks" at Jan 21, 2001 06:00:36 PM Message-ID: <200101211339.IAA14478@northshore.shore.net> > Is there a way to test if a list in nested and if so how deep? so that you could type > > y=[1,2,3] > x=[1,[2,3]] > > howDeep(y) > howDeep(x) > > and it would return 0 (no nesting) for y and 1, for x (1 level of nesting) > > Is this possible? It would seem really useful, but i don't see anything in the docs about how to do this. > That's because there is nothing to do this within Python itself. The "problem" is what type would this work on, only lists? To be Pythonic, it should handle any sequence - but why makes an object a sequence? __len__, __getitem__ and __getslice__ methods. Hmm... well, dictionaries have __len__ and __getitem__ method, but only sequences have __getslice__ methods.+ So we can test for slicing. >>> def howDeep(seq): ... # this will raise an exception if it is not a sequence ... seq[:] ... depths = [0] ... for obj in seq: ... try: ... depths.append( howDeep(obj) + 1 ) ... except: ... pass ... return max(tuple(depths)) ... >>> howDeep([1,2,3]) 0 >>> howDeep([1, [2], [3, [4]]]) 2 >>> Myself, I would have that this returns 1 for a sequence with no subsequences, but these were your specifications, not mine. :) -Arcege + Unfortunately, another "inovation" of Python 2.0 has made this distinction blury. -- ------------------------------------------------------------------------ | Michael P. Reilly, Release Manager | Email: arcege@shore.net | | Salem, Mass. USA 01970 | | ------------------------------------------------------------------------ From dreamz39@yahoo.com Sun Jan 21 15:02:09 2001 From: dreamz39@yahoo.com (Christopher Abrams) Date: Sun, 21 Jan 2001 07:02:09 -0800 (PST) Subject: [Tutor] newbie:Problem with arguments for methods Message-ID: <20010121150209.16084.qmail@web1004.mail.yahoo.com> --0-1540383426-980089329=:15969 Content-Type: text/plain; charset=us-ascii Python is my first programming language and I made a small change to a script on the Intro to Tkinter page: # File: hello2.py from Tkinter import * class App: def __init__(self, master): frame = Frame(master) frame.pack() self.button = Button(frame, text="QUIT", fg="red", command=frame.quit) self.button.pack(side=LEFT) self.hi_there = Button(frame, text="Hello", command=self.say_hi) self.hi_there.pack(side=LEFT) def say_hi(self): print "hi there, everyone!" root = Tk() app = App(root) root.mainloop() was chaged to: from Tkinter import * import Image class App: def __init__(self, master): frame = Frame(master) frame.pack() self.viewer = Canvas(frame) self.viewer.pack(side=BOTTOM) self.button = Button(frame, text="QUIT", fg="red", activebackground = "black", activeforeground = "yellow",command=frame.quit) self.button.pack(side=LEFT) self.hi_there = Button(frame, bitmap = "info", relief="raised", command=self.say_hi(self.viewer)) self.hi_there.pack(side=LEFT) def say_hi(self, canv): canv.create_oval(10,20,50,60) root = Tk() app = App(root) root.mainloop() Before the small changes the button would write "print this" to the console for each click of the button.The changes were made only to play around with Tkinter a little, but when I add the argument to self.say_hi it doesn't wait for me to press the button. It just runs straight through as if the has already been called. I am sure I must not understand something. Please help. Also how do I display images(.bmp, .jpg, .gif) on a Tkinter canvas. Thanks, C. Abrams --------------------------------- Do You Yahoo!? Yahoo! Auctions - Buy the things you want at great prices. --0-1540383426-980089329=:15969 Content-Type: text/html; charset=us-ascii

Python is my first programming language and I made a small change to a script on the Intro to Tkinter page:

# File: hello2.py

from Tkinter import *

class App:

    def __init__(self, master):

        frame = Frame(master)
        frame.pack()

        self.button = Button(frame, text="QUIT", fg="red", command=frame.quit)
        self.button.pack(side=LEFT)

        self.hi_there = Button(frame, text="Hello", command=self.say_hi)
        self.hi_there.pack(side=LEFT)

    def say_hi(self):
        print "hi there, everyone!"

root = Tk()

app = App(root)

root.mainloop()

 

was chaged to:

from Tkinter import *

import Image

class App:

def __init__(self, master):

frame = Frame(master)

frame.pack()

self.viewer = Canvas(frame)

self.viewer.pack(side=BOTTOM)

self.button = Button(frame, text="QUIT", fg="red", activebackground = "black", activeforeground = "yellow",command=frame.quit)

self.button.pack(side=LEFT)

self.hi_there = Button(frame, bitmap = "info", relief="raised", command=self.say_hi(self.viewer))

self.hi_there.pack(side=LEFT)

def say_hi(self, canv):

canv.create_oval(10,20,50,60)

root = Tk()

app = App(root)

root.mainloop()

 

Before the small changes the button would write "print this" to the console for each click of the button.The changes were made only to play around with Tkinter a little, but when I add the argument to self.say_hi it doesn't wait for me to press the button.  It just runs straight through as if the has already been called.  I am sure I must not understand something.  Please help.  Also how do I display images(.bmp, .jpg, .gif) on a Tkinter canvas. 

Thanks,

C. Abrams

 



Do You Yahoo!?
Yahoo! Auctions - Buy the things you want at great prices. --0-1540383426-980089329=:15969-- From bogus@does.not.exist.com Sun Jan 21 04:18:43 2001 From: bogus@does.not.exist.com () Date: Sun, 21 Jan 2001 12:18:43 +0800 Subject: [Tutor] attachments Message-ID: <200101212020.MAA26354@falcon.prod.itd.earthlink.net> Why does every fouth or fifth post to the board come with an attachment? If it's a snippet of code, put it in the original post. Please stop sending attachments, they are instantly deleted. G.T. Norton From sheila@thinkspot.net Sun Jan 21 20:50:26 2001 From: sheila@thinkspot.net (Sheila King) Date: Sun, 21 Jan 2001 12:50:26 -0800 Subject: [Tutor] attachments In-Reply-To: <200101212020.MAA26354@falcon.prod.itd.earthlink.net> References: <200101212020.MAA26354@falcon.prod.itd.earthlink.net> Message-ID: <2BDDF8C0CE0@kserver.org> On Sun, 21 Jan 2001 12:18:43 +0800, <> wrote about [Tutor] attachments: :Why does every fouth or fifth post to the board come with an attachment? :If it's a snippet of code, put it in the original post. :Please stop sending attachments, they are instantly deleted. What are you talking about? I scan back to late August 2000, and only count on the order of 8 or so attachments from then up until today. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From budgester@budgester.com Sun Jan 21 23:45:58 2001 From: budgester@budgester.com (Budgester) Date: Sun, 21 Jan 2001 23:45:58 -0000 Subject: [Tutor] Reading from a GUI Message-ID: <000001c08404$4e5bd270$0300000a@budgester> Hi all, I have posted to script to Rob, http://www.lowerstandard.com/python/pythonsource.html (Martin Stevens, TKinter thingy) What I'd like to do now is read the text string that is retrieved from the text box and find the line breaks/carriage returns. Should I use readlines ? This is eventually gonna be a html diary updater so what I want to be able to do is replace the line break from the text box with a
. Shouldn't be to difficult but I need to find the escape code for the line break. Any ideas would help Budgester mailto:budgester@budgester.com http://www.budgester.com From wheelege@tsn.cc Mon Jan 22 00:58:16 2001 From: wheelege@tsn.cc (wheelege) Date: Mon, 22 Jan 2001 11:58:16 +1100 Subject: [Tutor] Reading from a GUI References: <000001c08404$4e5bd270$0300000a@budgester> Message-ID: <002a01c0840e$68290060$a410fea9@glen> Hi, Is this what you meant.... PythonWin 2.0 (#8, Oct 19 2000, 11:30:05) [MSC 32 bit (Intel)] on win32. Portions Copyright 1994-2000 Mark Hammond (MarkH@ActiveState.com) - see 'Help/About PythonWin' for further copyright information. >>> a = "first line\nsecond line" >>> a 'first line\012second line' >>> print a first line second line From that I gather that the escape code is \012 ? HTH, Glen. ----- Original Message ----- From: Budgester To: Tutor (E-mail) Sent: Monday, January 22, 2001 10:45 AM Subject: [Tutor] Reading from a GUI > Hi all, > > I have posted to script to Rob, > http://www.lowerstandard.com/python/pythonsource.html > (Martin Stevens, TKinter thingy) > > > What I'd like to do now is read the text string that is retrieved from > the text box and find the line breaks/carriage returns. > > Should I use readlines ? > > This is eventually gonna be a html diary updater so what I want to be able > to > do is replace the line break from the text box with a
. > > Shouldn't be to difficult but I need to find the escape code for the line > break. > > Any ideas would help > > Budgester > > > mailto:budgester@budgester.com > http://www.budgester.com > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From dsh8290@rit.edu Mon Jan 22 02:40:12 2001 From: dsh8290@rit.edu (D-Man) Date: Sun, 21 Jan 2001 21:40:12 -0500 Subject: [Tutor] text editor problems In-Reply-To: <200101201545.AA673972564@mail.mattsmail.com>; from martok@mattsmail.com on Sat, Jan 20, 2001 at 03:45:27PM -0800 References: <200101201545.AA673972564@mail.mattsmail.com> Message-ID: <20010121214012.A15360@harmony.cs.rit.edu> On Sat, Jan 20, 2001 at 03:45:27PM -0800, Matthias Hager wrote: | That's what I thought(just see if those variables are there), I have(kind of, just reworded for less space) | | def save(): | if sname: | open sname and write to it | elif oname: | open oname and write to it | else: | saveas() | | def saveas(): | sname = asksaveasfile | blah blah | | def open(): | oname = askopenfile | blahblah | | Then it gives me the error: No variable named sname exists. | | I know you guys gotta be getting sick of me, but what am I doing wrong? If we were getting sick of you we would unsubscribe. We subscribed to the list to help. :-) | I can't figure it out, and I've tried changing it to: | if oname != "": | elif sname != "": | | All kinds of stuff, but I'm still getting an error. | The exact error is "NameError". That is, the name (variable) doesn't exist. Have you ever used a statically typed language like C, C++, Java, or Eiffel? In each of those languages you must declare all variables before you can use them. ie: int i ; i = 3 ; if j == 4 : print "i is 4" Oops. I used "j", but I didn't declare it. The compiler will then say something like "no identifier 'j' found in local namesapce". I haven't declared j, so it doesn't exist. Python is a bit different. You don't declare variables, but instead create them through the "assignment" operation. (I put it in quotes because it has more to do with name bindins than assignment, but that is a detail) If I write the following python code, I am ok: i = 3 if i == 4 : print "i is 4" else : print "i isn't 4" but if I make a typo and write: j = 3 if i == 4 : print "i is 4" I will get a NameError because the name 'i' isn't defined. You tried checking for sname == "", but since sname hadn't been assigned to it doesn't exist yet. (I think Perl implicitly gives all names the value 'undefined' which compares equal to "", the empty string) To solve your problem, somewhere during progam initialization set sname equal to "". I would prefer setting it to None since that better reflects your intent (and you don't have any static typing restrictions). If you do this, the variable sname will exist when the function is called and you won't get any NameError's. Then in the function check to see that sname has been set to something useful, rather than None. (I haven't tried, but I bet you will get an exception if you try to call open() with None as the filename argument). | Any help is appreciated | | Matthias | HTH, -D | | | -- | Programming isn't cool, it's awesome. | From rob@jam.rr.com Mon Jan 22 03:06:07 2001 From: rob@jam.rr.com (R. A.) Date: Sun, 21 Jan 2001 21:06:07 -0600 Subject: [Tutor] Tutor mini-FAQ Message-ID: <3A6BA39F.5288BAF@jam.rr.com> While working on the Useless Python and related pages, I've started to want to put together a mini-FAQ of common questions posed to the list. (Of course, there may be a maintained Tutor FAQ that I just haven't spotted.) A few that come to mind are: Can you recommend good books for learning Python? Can you recommend good tutorials for learning Python? How can I (do this certain thing) in Python? I figured I'd scan over the archives in my *copious free time* for some representative good answers to some of these questions and tack together the mini-FAQ. (And hopefully Useless Python will help with the "How do I....?" questions.) I just wondered if anyone had in mind any questions I could make a point to scan the archive for. Rob -- Visit the Useless Python Repository! http://www.lowerstandard.com/python/pythonsource.html From sheila@thinkspot.net Mon Jan 22 03:10:42 2001 From: sheila@thinkspot.net (Sheila King) Date: Sun, 21 Jan 2001 19:10:42 -0800 Subject: [Tutor] Tutor mini-FAQ In-Reply-To: <3A6BA39F.5288BAF@jam.rr.com> References: <3A6BA39F.5288BAF@jam.rr.com> Message-ID: <4189EFA1ADB@kserver.org> On Sun, 21 Jan 2001 21:06:07 -0600, "R. A." wrote about [Tutor] Tutor mini-FAQ: :I figured I'd scan over the archives in my *copious free time* for some :representative good answers to some of these questions and tack together :the mini-FAQ. (And hopefully Useless Python will help with the "How do :I....?" questions.) I just wondered if anyone had in mind any questions :I could make a point to scan the archive for. May I suggest that you automate the managing of the FAQ, especially in such a way that others from the community are able to help you maintain it. For instance, you might consider installing the FAQ-O-Matic script, you can see examples here: http://faqomatic.sourceforge.net/fom-serve/cache/1.html (You can see the FAQ-O-Matic that I maintain here: http://www.thinkspot.net/k12FAQOMATIC/cache/1.html ) As a matter of fact, there could be a category where people can submit snippets of code themselves, there. It might ease some of the burden of having to maintain a FAQ if you set it up so that others can easily help. I thought, in my many wanderings through various Pythonic websites, that I might have seen a similar script in Python? -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From dsh8290@rit.edu Mon Jan 22 03:13:03 2001 From: dsh8290@rit.edu (D-Man) Date: Sun, 21 Jan 2001 22:13:03 -0500 Subject: [Tutor] (no subject) In-Reply-To: <200101201756.AA702415188@mail.mattsmail.com>; from martok@mattsmail.com on Sat, Jan 20, 2001 at 05:56:09PM -0800 References: <200101201756.AA702415188@mail.mattsmail.com> Message-ID: <20010121221303.B15360@harmony.cs.rit.edu> On Sat, Jan 20, 2001 at 05:56:09PM -0800, Matthias Hager wrote: | I know you guys are about to rip your hair out over me, I'm annoying I know! But I have some questions here on how to do some special stuff in Python. (And is it possible to use a GUI with Perl?) Yes, but you'll have to find the bindings yourself. (I'm sure there are bindings for Tk, Gtk+, Qt, maybe more) I think there are GUI bindings for every language in use. | | 1. How do I access the clipboard, so I can make cut and paste options? MS Windows? X? I don't know for either, but if you are using Windows try the win32all module maintained by Mark Hammond. | 2. What all does ScrollingText support? I've found background, fg, font. What else is there? How can I change the size of the text, and how can I add the ability to have the user change the text color and everything? How can I change how it rounds off its text on the right? It justs takes whatever you type to the next line, cutting words in two. What gui toolkit? Tkinter? It depends on the gui a, you should check the docs. I like GTK myself, never used Tk. | How can I change the blinking | thing's color? And finally, how can I make it say stuff according to what they type? Like in idle, if you start typing askopenfilename() It will tell you what to type in? How do I do that? I expect that the text widget would have a Changed event (or something similar). You would need to register a listener for the event, then do what you want with the data. For example, have a string object somewhere. When you get the changed event it should give you the charecter entered (or deleted, and tell you which). If it is a space, clear your string object, else append the character to it. If the string matches somehting you want (ie askopenfilename) do what you want to have happen. | | 3. What are, and how do I use classes? A program I saw, uses them, but what are they? Classes are very cool. Read the tutorial, but I don't remember how much they teach about classses in general or how much they assume you already know. Classes are a way of describing an object. An object is a collection of data and a set of functions that operate on the data. Ideally you don't know what an object's implementation is, just the interface (functions is has). You would use the functins to get the work done, but don't have to deal with the data itself. I don't have time to give a tutorial right now, but read the chapter from the tutorial (Ch. 9 I think) and then come back with more questions :-). I'll be happy to answer them when I have a few minutes. | 4. How do I open another window, that has more stuff in it, like buttons and stuff? First read the stuff on classes. Every gui I've ever used (ok, just GTK and Swing, but I know Qt follows this as well) uses an object model. Once you understand classes and objects it will make more sense what you need to do. In GTK, import Gtk window = Gtk.Window() window.add( Gtk.Label( "Label Text" ) ) window.show() (basically, it's been a while so I might (propably) have the details wrong) | 5. How can I change what it says when they hover over an icon to my program? These are usually called "tooltips". It depends on your gui toolkit, but there should be some way to create a tooltip object and add it to the button object. The button then handles the displaying of it. (Objects rock!) | | 6. How do I check if they have made any changes to a file, and do something according to whether they have or not? I imagine that you have a Text Entry widget of some sort. The widget is upposed to represent the contents of a text file. You also have the name of the file. One solution, as wheelege hinted at, is to open the file, read it, and compare the text to the text in the widget. While functional, this would be slow and use a lot of memory (for large files). A better approach would be to have a flag (say 'is_modified'). Set this to false (0) at the beginning of the program and each time a save is successful. When you get the "Changed" event from the widget set the flag to true (1). This will be much more efficeint (and easier!) than checking the file on disk every time. | | Again, I'm sorry to bother you all. | But thanks, A LOT. No problem. This is the /Tutor/ list. It's meant for all these questions. :-) | | Matthias | -D (PS. Sorry for the many spelling mistakes and typos. I am using a slow dial-up connection and have very bad response. It makes it harder to fix the typos.) From dsh8290@rit.edu Mon Jan 22 03:26:55 2001 From: dsh8290@rit.edu (D-Man) Date: Sun, 21 Jan 2001 22:26:55 -0500 Subject: [Tutor] Re: [Turor] text editor problems In-Reply-To: <00d301c0836d$de094fc0$a410fea9@glen>; from wheelege@tsn.cc on Sun, Jan 21, 2001 at 04:49:05PM +1100 References: <00d301c0836d$de094fc0$a410fea9@glen> Message-ID: <20010121222655.C15360@harmony.cs.rit.edu> On Sun, Jan 21, 2001 at 04:49:05PM +1100, wheelege wrote: | | Hi, | | I'm pretty sure that you need to pass those variables in as arguments to | the function save(). It all depends on where the save funciton is and where the data is stored. If save is a stand-alone utility function, then your gui object should have the data and pass it to the function. If the function is a part of the gui object then it should be an instance member (see classes and objects :-)) and isn't needed as an argument. When I talk about your gui object, I mean you should write a class (I really like OO in case you didn't guess) for the main window of the ap. That object will have a reference in it to the window and any other widgets needed (like the text widget, buttons aren't needed once their events have been connected with the handlers). That object will also store state like the filenames and the is_modified flag I mentioned in my previous post. | | Like.. | | def save(sname, oname) | # code | | and when you call it... | | save(sname, oname) # pass the variables sname and oname | | I'm still a newbie so don't flame me if it doesn't turn out... | | Glen. | | ----- Original Message ----- | From: Matthias Hager | To: | Sent: Sunday, January 21, 2001 10:45 AM | Subject: [Tutor] text editor problems [snip] HTH, -D From amoreira@mercury.ubi.pt Mon Jan 22 11:17:40 2001 From: amoreira@mercury.ubi.pt (Jose Amoreira) Date: Mon, 22 Jan 2001 11:17:40 +0000 Subject: [Tutor] getpass References: Message-ID: <3A6C16D4.5E51A1D3@mercury.ubi.pt> Hello! I just uncommented the appropriate line in Modules/Setup, the one dealing with the termios module, and recompiled python. getpass now works as expected. Thank you all very much! Cheers, Ze From dyoo@hkn.eecs.berkeley.edu Mon Jan 22 11:27:55 2001 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Mon, 22 Jan 2001 03:27:55 -0800 (PST) Subject: [Tutor] (no subject) In-Reply-To: <20010121221303.B15360@harmony.cs.rit.edu> Message-ID: On Sun, 21 Jan 2001, D-Man wrote: > On Sat, Jan 20, 2001 at 05:56:09PM -0800, Matthias Hager wrote: | I > know you guys are about to rip your hair out over me, I'm annoying I > know! But I have some questions here on how to do some special stuff > in Python. (And is it possible to use a GUI with Perl?) Don't sweat about it; we like talking to people. *grin* I've heard that Perl/Tk is really good. In fact, the winner of this year's Obfuscated Perl contest is a Frogger game written in Perl/Tk. http://www.itknowledge.com/tpj/obfusc-5-awards.html > | 1. How do I access the clipboard, so I can make cut and paste options? > > MS Windows? X? I don't know for either, but if you are using Windows > try the win32all module maintained by Mark Hammond. Hard question. I don't know how Windows does it, but on UNIX platforms, it goes all over the place. I have a small example that uses Gtk+'s interface, but it's just awkward: http://hkn.eecs.berkeley.edu/~dyoo/python/ When I was trying to do selections, lots of people recommened me to jwz's page: http://www.jwz.org/doc/ especially the part about "X Cut and Paste": http://www.jwz.org/doc/x-cut-and-paste.html Supposedly, the details make even grown men cry. *grin* From alan.gauld@bt.com Mon Jan 22 12:51:08 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 22 Jan 2001 12:51:08 -0000 Subject: [Tutor] Tutor digest, Vol 1 #537 - 13 msgs Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D508@mbtlipnt02.btlabs.bt.co.uk> > As a clarification, doing: > > from os import open as osopen > > would prevent the naming conflict. > only works with Python 2.0 though. But wouldn't this work in older versions?: import os osopen = os.open Alan g From alan.gauld@bt.com Mon Jan 22 12:48:58 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 22 Jan 2001 12:48:58 -0000 Subject: [Tutor] functions Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D507@mbtlipnt02.btlabs.bt.co.uk> > also declares them) I think that could be a major setback, > the way I program. Heh, split screen editors are your friend. write the main program in one window, define the functions in the other... works for me using either vim or emacs :-) As you've seen Python tells you which functions you still have to define... Alan g. From alan.gauld@bt.com Mon Jan 22 13:03:16 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 22 Jan 2001 13:03:16 -0000 Subject: [Tutor] functions, system statements, sleep Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D509@mbtlipnt02.btlabs.bt.co.uk> > I'm trying to decide whether I like Perl or Python better. > The use of a GUI in Python is good(Is there a way to use > Tkinter or any other GUI with Perl?) There is a TK package for Perl too but it is not OO in the way that Tkinter is. It is much more like the original Tk package for Tcl. > anyway on perl, so I don't mind that. I now don't like that > you have to create your function first, I usually get my > program out of the way, then make my functions. So either use a split screen editor or just page up to the top of the file. Or better still put your functions in another file so you can reuse them, then import that file as a module. This is probably the best way IMHO. Really you are only concerned about where in the file you position them, you still have to define them to get the program to work, even in Perl! > wouldn't mind if Windoze users couldn't use my program, Don't understand this bit, why would windows users not be able to use it? Unless you use Unix specific bits but that's true of Perl too - even more true in my experience! Alan G From alan.gauld@bt.com Mon Jan 22 13:10:45 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 22 Jan 2001 13:10:45 -0000 Subject: [Tutor] (no subject) Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D50A@mbtlipnt02.btlabs.bt.co.uk> > some special stuff in Python. (And is it possible to use a > GUI with Perl?) Yes Tk is available in Perl. > 2. What all does ScrollingText support? It might be worth your while looking at the Tk widget demo program that installs with Tcl/Tk. Its written in Tcl but does show the various config settings for most of the widgets. Alternatively buy Tcl/Tk in a Nutshell from O'Reilly, its a very good reference to Tcl including Tk. > 3. What are, and how do I use classes? Try my beginners tutor at: http://www.crosswinds.net/~agauld Specifically the OO page, the event Driven page and the Case study. They all explain and/or demonstrate classes and OO programming. There is also a little bit of Tkinter in the last two but not very much. > 6. How do I check if they have made any changes to a file, > and do something according to whether they have or not? Normally you create something called a "dirtyflag". Everytime an edit function changes the contents ypu set the dirtyflag to true. After a sve you reset it to false. Then if they hit Save you can do: if dirtyflag: # save it here The textwidget may have something similar built in I don't remember, but I doubt it. Alan G From alan.gauld@bt.com Mon Jan 22 13:16:17 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 22 Jan 2001 13:16:17 -0000 Subject: [Tutor] text editor problems Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D50B@mbtlipnt02.btlabs.bt.co.uk> > def save(): > if sname: > open sname and write to it > elif oname: > open oname and write to it > else: > saveas() Here you are referencing a global variable sname, oname etc. > def saveas(): > sname = asksaveasfile > blah blah Here you are setting a local variable visible only within the saveas function. Tus the save function cannot see it. > Then it gives me the error: No variable named sname exists. You need to create the sbame variable outside the functions and then declare it as global inside saveas. This is all explained in my tuorial at: http://www.crosswinds.net/~agauld under Namespaces > I can't figure it out, and I've tried changing it to: > if oname != "": > elif sname != "": As explained above the variables don't exist so you can't compare them to anything yet! HTH, Alan G. From alan.gauld@bt.com Mon Jan 22 13:24:14 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 22 Jan 2001 13:24:14 -0000 Subject: [Tutor] newbie:Problem with arguments for methods Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D50C@mbtlipnt02.btlabs.bt.co.uk> > self.hi_there = Button(frame, bitmap = "info", > relief="raised", command=self.say_hi(self.viewer)) > def say_hi(self, canv): > > canv.create_oval(10,20,50,60) > Before the small changes the button would write "print this" > add the argument to self.say_hi it doesn't wait for me to > press the button. By putting parentheses after the say_hi you asked Python to call the function and put the result as the action of the command. command= must have a function *object*(usually the name!) as a value. Try something like this: command=lambda c=self.viewer: say_hi(c) lambda creates a new function which passes an argument, c to say hi. We set the default value to the current viewer. HTH, Alan G. From alan.gauld@bt.com Mon Jan 22 13:51:27 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 22 Jan 2001 13:51:27 -0000 Subject: [Tutor] (no subject) Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D50D@mbtlipnt02.btlabs.bt.co.uk> > I've heard that Perl/Tk is really good. In fact, the winner of this > year's Obfuscated Perl contest is a Frogger game written in Perl/Tk. Daniel, I nearly died laughing at that. Was the irony deliberate? :-) Alan g. From tamezi_2000@yahoo.com Mon Jan 22 15:08:33 2001 From: tamezi_2000@yahoo.com (IVAN TAMEZ) Date: Mon, 22 Jan 2001 07:08:33 -0800 (PST) Subject: [Tutor] remove me from tutor list Message-ID: <20010122150833.82466.qmail@web9502.mail.yahoo.com> --0-1287080345-980176113=:81180 Content-Type: text/plain; charset=us-ascii I want to be removed from the tution list thanks tamezi_2000@yahoo.com --------------------------------- Do You Yahoo!? Yahoo! Auctions - Buy the things you want at great prices. --0-1287080345-980176113=:81180 Content-Type: text/html; charset=us-ascii

I want to be removed from the tution list

thanks

tamezi_2000@yahoo.com



Do You Yahoo!?
Yahoo! Auctions - Buy the things you want at great prices. --0-1287080345-980176113=:81180-- From w.guldner@bfad.de Mon Jan 22 16:51:31 2001 From: w.guldner@bfad.de (Wolfgang Guldner) Date: Mon, 22 Jan 2001 17:51:31 +0100 Subject: [Tutor] simular function to pack (perl) Message-ID: <3A6C6513.80E9A8D3@bfad.de> --------------54A774226A93B1E0075F14A8 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit Hello erverybody, are there simular function to pack and unpack (perl) in python. Thanks Wolfgang -- _____________________________________________________________________ BFAD GmbH & Co. KG Wolfgang Guldner Kornblumenweg 36 D-78247 Hilzingen Tel.07731-9057-73 _o o Fax 07731-9057-66 -\<, /L E-Mail: w.guldner@bfad.de ~~o^~~ O / O /> Homepage: www.bfad.de --------------54A774226A93B1E0075F14A8 Content-Type: text/html; charset=us-ascii Content-Transfer-Encoding: 7bit Hello erverybody,

are there simular function to pack and unpack (perl) in python.

Thanks

Wolfgang

-- 

_____________________________________________________________________

BFAD GmbH & Co. KG 

Wolfgang Guldner
Kornblumenweg 36
D-78247 Hilzingen

Tel.07731-9057-73                             _o        o
Fax 07731-9057-66                            -\<,      /L
E-Mail: w.guldner@bfad.de        ~~o^~~     O / O     />
Homepage: www.bfad.de
  --------------54A774226A93B1E0075F14A8-- From alan.gauld@bt.com Mon Jan 22 16:55:02 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 22 Jan 2001 16:55:02 -0000 Subject: [Tutor] Perl/Tk Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D512@mbtlipnt02.btlabs.bt.co.uk> Those of a nervous disposition should avert their eyes now, here is some Tkinter equivalent code in Perl/Tk... Tkinter: ================= from Tkinter import * import sys main = Tk() Button(main, text="Hello world", command=sys.exit).pack() mainloop() Perl/Tk: ================= use Tk; my $main = Mainwindow->new; $main->Button(-text=>"Hello World", -command=>sub{exit})->pack; MainLoop; Its pretty similar, more OO than I remembered. HTH somebody ;-) Alan g. From arcege@shore.net Mon Jan 22 17:11:58 2001 From: arcege@shore.net (Michael P. Reilly) Date: Mon, 22 Jan 2001 12:11:58 -0500 (EST) Subject: [Tutor] simular function to pack (perl) In-Reply-To: <3A6C6513.80E9A8D3@bfad.de> from "Wolfgang Guldner" at Jan 22, 2001 05:51:31 PM Message-ID: <200101221711.MAA16625@northshore.shore.net> > Hello erverybody, > > are there simular function to pack and unpack (perl) in python. > > Thanks > > Wolfgang In Python, it is the struct module. import struct datastruct = 'ff2xh' # the data structure format s_sz = struct.calcsize(datastruct) # how many bytes in the structure f = open('form.dat', 'rb') graph_points = {} block = f.read(s_sz) # read the first structure from the binary file # into a character string while block: # decode the structure from the character string (x, y, count) = struct.unpack(datastruct, block) graph_points[x,y] = count block = f.read(s_sz) f.close() # do something with graph_points References: Python Library Reference manual, section 4.3 - struct -Arcege -- ------------------------------------------------------------------------ | Michael P. Reilly, Release Manager | Email: arcege@shore.net | | Salem, Mass. USA 01970 | | ------------------------------------------------------------------------ From alan.gauld@bt.com Mon Jan 22 17:47:07 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 22 Jan 2001 17:47:07 -0000 Subject: [Tutor] simular function to pack (perl) Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D514@mbtlipnt02.btlabs.bt.co.uk> > are there simular function to pack and unpack (perl) in python. I think the struct module is what you want. Alan G From cruciatuz Mon Jan 22 18:59:54 2001 From: cruciatuz (cruciatuz) Date: Mon, 22 Jan 2001 19:59:54 +0100 Subject: [Tutor] using a function and simultaneously accessing an array item(?) Message-ID: <146901377.20010122195954@gmx.de> Hello tutor, I found in the python documentation an example for fetching email. there is a snipped of code which i don't understand: numMessages = len(mymail.list()[1]) am I accessing the list which is (probably, i don't really know) returned from that function in the same line where I execute the function (or let's say the method)? I just want to be sure about it :) thx in advance. + ---------------------------------- + | Best regards: Cruciatuz_AH | + ---------------------------------- + | AKA: Stefan Antoni | + ---------------------------------- + | ICQ: 72292815 | | PGP-Key: AVAILABLE | + ---------------------------------- + 19:55 / Montag, 22. Januar 2001 From DOUGS@oceanic.com Mon Jan 22 19:19:48 2001 From: DOUGS@oceanic.com (Doug Stanfield) Date: Mon, 22 Jan 2001 09:19:48 -1000 Subject: [Tutor] using a function and simultaneously accessing an arra y item(?) Message-ID: <8457258D741DD411BD3D0050DA62365907A56A@huina.oceanic.com> Taking it from the inside out: mymail.list() is a method call of an instance of a class, presumably returning a list. mymail.list()[1] returns the second element of the list. len(mymail.list()[1]) should be the length of that second element An interesting thing to note is that it isn't acting on the list, but one element of it. The length gotten is of that element, not the list. Also the list isn't saved for a subsequent use, so if the list() function is called again and is processor intense this might be an inefficient program. -Doug- > -----Original Message----- > From: cruciatuz [mailto:sasoft@gmx.de] > Sent: Monday, January 22, 2001 9:00 AM > To: tutor@python.org > Subject: [Tutor] using a function and simultaneously > accessing an array > item(?) > > > Hello tutor, > > I found in the python documentation an example > for fetching email. there is a snipped of code > which i don't understand: > > numMessages = len(mymail.list()[1]) > > am I accessing the list which is (probably, i > don't really know) returned from that function > in the same line where I execute the function > (or let's say the method)? > > I just want to be sure about it :) > > thx in advance. > > + ---------------------------------- + > | Best regards: Cruciatuz_AH | > + ---------------------------------- + > | AKA: Stefan Antoni | > + ---------------------------------- + > | ICQ: 72292815 | > | PGP-Key: AVAILABLE | > + ---------------------------------- + > > 19:55 / Montag, 22. Januar 2001 > > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From shaleh@valinux.com Mon Jan 22 19:31:57 2001 From: shaleh@valinux.com (Sean 'Shaleh' Perry) Date: Mon, 22 Jan 2001 11:31:57 -0800 (PST) Subject: [Tutor] using a function and simultaneously accessing an arr In-Reply-To: <146901377.20010122195954@gmx.de> Message-ID: On 22-Jan-2001 cruciatuz wrote: > Hello tutor, > > I found in the python documentation an example > for fetching email. there is a snipped of code > which i don't understand: > > numMessages = len(mymail.list()[1]) > > am I accessing the list which is (probably, i > don't really know) returned from that function > in the same line where I execute the function > (or let's say the method)? > > I just want to be sure about it :) > certainly looks that way. What you are doing is treating the function call as a reference to the variable it returns. I personally would not write code like this. You have no way to catch errors (what if it could not read your mail?). it is also confusing unless you are carefully reading. From dyoo@hkn.eecs.berkeley.edu Mon Jan 22 19:50:28 2001 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Mon, 22 Jan 2001 11:50:28 -0800 (PST) Subject: [Tutor] Re: [Turor] text editor problems In-Reply-To: <00d301c0836d$de094fc0$a410fea9@glen> Message-ID: On Sun, 21 Jan 2001, wheelege wrote: > > def save(): > > if sname: > > open sname and write to it > > elif oname: > > open oname and write to it > > else: > > saveas() > > > > def saveas(): > > sname = asksaveasfile > > blah blah > > > > def open(): > > oname = askopenfile > > blahblah > > > > Then it gives me the error: No variable named sname exists. It helps to know that Python's rules for handling variables is different from Perl's: in Perl, your variables are global by default, and you get "local" variables by putting something like: my $foobar = 10; However, in Python, all your variables in function are "my" variables, so the rule is backwards. We expect to use more local than global variables, so Python makes globals a special case, where you have to say "global": global sname = saveasfile or global oname = askopenfile That being said, Pythonic style tries to avoid global variables whenever possible, so expect some resistance from us when you ask for a straight, direct translation. Hope that clears things up! From kalle@gnupung.net Mon Jan 22 20:02:34 2001 From: kalle@gnupung.net (Kalle Svensson) Date: Mon, 22 Jan 2001 21:02:34 +0100 Subject: [Tutor] attachments In-Reply-To: <2BDDF8C0CE0@kserver.org>; from sheila@thinkspot.net on Sun, Jan 21, 2001 at 12:50:26PM -0800 References: <200101212020.MAA26354@falcon.prod.itd.earthlink.net> <2BDDF8C0CE0@kserver.org> Message-ID: <20010122210234.B460@apone.network.loc> --GID0FwUMdk1T2AWN Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable Sez Sheila King: > On Sun, 21 Jan 2001 12:18:43 +0800, <> wrote about [Tutor] attachments: >=20 > :Why does every fouth or fifth post to the board come with an attachment? > :If it's a snippet of code, put it in the original post. > :Please stop sending attachments, they are instantly deleted. >=20 > What are you talking about? I scan back to late August 2000, and only cou= nt on > the order of 8 or so attachments from then up until today. I think he might be referring at least partly to my PGP signatures, that some mail user agents may show as attachments. It is nothing I intend to stop with. But Mr. Norton may of course delete my signatures instantly, this doesn't bother me much. I doubt that I'm responsible for 20-25% of the list traffic, though. Peace, Kalle --=20 Email: kalle@gnupung.net | You can tune a filesystem, but you Web: http://www.gnupung.net/ | can't tune a fish. -- man tunefs(8) PGP fingerprint: 0C56 B171 8159 327F 1824 F5DE 74D7 80D7 BF3B B1DD --GID0FwUMdk1T2AWN Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.4 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE6bJHadNeA1787sd0RAi+CAKCktLifT3lsuw7JJZFmq2WdNGwKSgCaA53t gROUEf8Pp1YITdcnFxBQjo8= =Qe5F -----END PGP SIGNATURE----- --GID0FwUMdk1T2AWN-- From shaleh@valinux.com Mon Jan 22 22:29:51 2001 From: shaleh@valinux.com (Sean 'Shaleh' Perry) Date: Mon, 22 Jan 2001 14:29:51 -0800 (PST) Subject: [Tutor] problems with HTMLParser Message-ID: I am trying to write a program that will parse the contents list of a howto index.html. Initial code: from formatter import NullFormatter from htmllib import HTMLParser class myHTML(HTMLParser): def __init__(self, formatter, verbose = 0): HTMLParser.__init__(self, formatter, verbose) self.section_list = [] # to be filled in later def start_ul(self, attributes): pass def end_ul(self, attributes): pass def start_li(self, attributes): pass def end_li(self, attributes): pass def start_a(self, attributes): print attributes I call this simply: foo = myHTML(NullFormatter) foo.feed(data) foo.close() the goal is to have the href and the text from the anchors inserted into section_list. Of course this should only happen when the anchor occurs in the
  • tag, so I will have a variable to ensure this case. The problem is that when i run the code I get: Traceback (innermost last): File "./import_toc.py", line 28, in ? foo.feed(data) File "/usr/lib/python1.5/sgmllib.py", line 83, in feed self.goahead(0) File "/usr/lib/python1.5/sgmllib.py", line 104, in goahead if i < j: self.handle_data(rawdata[i:j]) File "/usr/lib/python1.5/htmllib.py", line 42, in handle_data self.formatter.add_flowing_data(data) TypeError: unbound method must be called with class instance 1st argument From wheelege@tsn.cc Mon Jan 22 22:54:44 2001 From: wheelege@tsn.cc (Glen Wheeler) Date: Tue, 23 Jan 2001 09:54:44 +1100 Subject: [Tutor] problems with HTMLParser References: Message-ID: <009201c084c6$6c8dd780$a410fea9@glen> Hi, Just looking from the error... > The problem is that when i run the code I get: > > Traceback (innermost last): > File "./import_toc.py", line 28, in ? > foo.feed(data) > File "/usr/lib/python1.5/sgmllib.py", line 83, in feed > self.goahead(0) > File "/usr/lib/python1.5/sgmllib.py", line 104, in goahead > if i < j: self.handle_data(rawdata[i:j]) > File "/usr/lib/python1.5/htmllib.py", line 42, in handle_data > self.formatter.add_flowing_data(data) > TypeError: unbound method must be called with class instance 1st argument My guess is you might have forgotten a 'self' argument. HTH, Glen. ----- Original Message ----- From: Sean 'Shaleh' Perry To: Sent: Tuesday, January 23, 2001 9:29 AM Subject: [Tutor] problems with HTMLParser > I am trying to write a program that will parse the contents list of a howto > index.html. > > Initial code: > > from formatter import NullFormatter > from htmllib import HTMLParser > > class myHTML(HTMLParser): > def __init__(self, formatter, verbose = 0): > HTMLParser.__init__(self, formatter, verbose) > self.section_list = [] # to be filled in later > > def start_ul(self, attributes): > pass > > def end_ul(self, attributes): > pass > > def start_li(self, attributes): > pass > > def end_li(self, attributes): > pass > > def start_a(self, attributes): > print attributes > > I call this simply: > > foo = myHTML(NullFormatter) > foo.feed(data) > foo.close() > > the goal is to have the href and the text from the anchors inserted into > section_list. Of course this should only happen when the anchor occurs in the >
  • tag, so I will have a variable to ensure this case. > > The problem is that when i run the code I get: > > Traceback (innermost last): > File "./import_toc.py", line 28, in ? > foo.feed(data) > File "/usr/lib/python1.5/sgmllib.py", line 83, in feed > self.goahead(0) > File "/usr/lib/python1.5/sgmllib.py", line 104, in goahead > if i < j: self.handle_data(rawdata[i:j]) > File "/usr/lib/python1.5/htmllib.py", line 42, in handle_data > self.formatter.add_flowing_data(data) > TypeError: unbound method must be called with class instance 1st argument > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From shaleh@valinux.com Mon Jan 22 23:49:56 2001 From: shaleh@valinux.com (Sean 'Shaleh' Perry) Date: Mon, 22 Jan 2001 15:49:56 -0800 (PST) Subject: [Tutor] problems with HTMLParser In-Reply-To: <009201c084c6$6c8dd780$a410fea9@glen> Message-ID: On 22-Jan-2001 Glen Wheeler wrote: > > Hi, > > Just looking from the error... > > My guess is you might have forgotten a 'self' argument. > except the code I gave was all of the code, and each function has a self. From wheelege@tsn.cc Mon Jan 22 23:47:21 2001 From: wheelege@tsn.cc (Glen Wheeler) Date: Tue, 23 Jan 2001 10:47:21 +1100 Subject: [Tutor] problems with HTMLParser References: Message-ID: <00a001c084cd$aa177500$a410fea9@glen> ----- Original Message ----- From: Sean 'Shaleh' Perry To: Glen Wheeler Cc: Sent: Tuesday, January 23, 2001 10:49 AM Subject: Re: [Tutor] problems with HTMLParser > > On 22-Jan-2001 Glen Wheeler wrote: > > > > Hi, > > > > Just looking from the error... > > > > My guess is you might have forgotten a 'self' argument. > > > > except the code I gave was all of the code, and each function has a self. Oh. Well then I'm stumped too :) From dyoo@hkn.eecs.berkeley.edu Tue Jan 23 02:14:49 2001 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Mon, 22 Jan 2001 18:14:49 -0800 (PST) Subject: [Tutor] (no subject) In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20751D50D@mbtlipnt02.btlabs.bt.co.uk> Message-ID: On Mon, 22 Jan 2001 alan.gauld@bt.com wrote: > > I've heard that Perl/Tk is really good. In fact, the winner of this > > year's Obfuscated Perl contest is a Frogger game written in Perl/Tk. > > Daniel, > > I nearly died laughing at that. Was the irony deliberate? :-) Hmmm... not intentionally. From dyoo@hkn.eecs.berkeley.edu Tue Jan 23 02:23:05 2001 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Mon, 22 Jan 2001 18:23:05 -0800 (PST) Subject: [Tutor] problems with HTMLParser In-Reply-To: <009201c084c6$6c8dd780$a410fea9@glen> Message-ID: > > I call this simply: > > > > foo = myHTML(NullFormatter) ^^^^^^^^^^^^^ It's this part --- you need to pass in an instance of a NullFormatter when doing stuff with HTMLParser: foo = myHTML(NullFormatter()) Don't worry, I've seen this bug a LOT. From martok@mattsmail.com Tue Jan 23 04:03:46 2001 From: martok@mattsmail.com (Matthias Hager) Date: Mon, 22 Jan 2001 20:03:46 -0800 Subject: [Tutor] Hardware input Message-ID: <200101222003.AA70582560@mail.mattsmail.com> How do you receive input from hardware? Can python do it directly? Say I want to make a cd song player, can python do this and how? Or using microphone, printer, scanner, etc.. Thanks Matthias -- Programming isn't cool, it's awesome. %%%################?????????###################^^^ martok@mattsmail.com http://mymymatthias.tripod.com/ %%%################????????####################^^^ -- Like my email address? Get your own for FREE at http://firstname.com Get you@JohnsMail.com or you@AlexsMail.com or pick from 500 more! From dyoo@hkn.eecs.berkeley.edu Tue Jan 23 07:26:20 2001 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Mon, 22 Jan 2001 23:26:20 -0800 (PST) Subject: [Tutor] getpass In-Reply-To: <3A6C16D4.5E51A1D3@mercury.ubi.pt> Message-ID: On Mon, 22 Jan 2001, Jose Amoreira wrote: > I just uncommented the appropriate line in Modules/Setup, the one dealing > with the termios module, and recompiled python. getpass now works as > expected. Thank you all very much! Cool, that's good that it works now. From dyoo@hkn.eecs.berkeley.edu Tue Jan 23 08:04:39 2001 From: dyoo@hkn.eecs.berkeley.edu (Daniel Yoo) Date: Tue, 23 Jan 2001 00:04:39 -0800 (PST) Subject: [Tutor] Hardware input In-Reply-To: <200101222003.AA70582560@mail.mattsmail.com> Message-ID: On Mon, 22 Jan 2001, Matthias Hager wrote: > How do you receive input from hardware? Can python do it directly? Say > I want to make a cd song player, can python do this and how? Or using > microphone, printer, scanner, etc.. Hmmm... I'm not sure if there's a uniform way of doing all of this. There are modules available that let you fiddle with sound and recording: For example: http://213.93.58.229/alpy/ is a link to the ALPY library --- it lets you play sound in 3 dimensions. You may want to browse through the Vaults of Parnassus and see what kind of multimedia packages are out there: http://www.vex.net/parnassus/ http://www.vex.net/parnassus/apyllo.py/63131194 I hope this helps! From NHYTRO@compuserve.com Tue Jan 23 10:42:14 2001 From: NHYTRO@compuserve.com (Sharriff Aina) Date: Tue, 23 Jan 2001 05:42:14 -0500 Subject: [Tutor] Stopping evalualtion of inner Lists/ tuples Message-ID: <200101230542_MC2-C2BC-EFEA@compuserve.com> Hi Guys! Considering the following: tab1 =3D {"feld1": "varchar", "feld2": "varchar"} tab2 =3D {"feld3": "varchar", "feld4": "varchar"} virtuallist =3D [tab1, tab2] >>> vlist [{'feld2': 'varchar', 'feld1': 'varchar'}, {'feld3': 'varchar', 'feld4': 'varchar'}] >>> for x in vlist: print x = {'feld2': 'varchar', 'feld1': 'varchar'} {'feld3': 'varchar', 'feld4': 'varchar'} >>> for x in vlist: print `x` {'feld2': 'varchar', 'feld1': 'varchar'} {'feld3': 'varchar', 'feld4': 'varchar'} How can I stop the evaluation of the innner List or tuple? I would like t= o have for tables in virtuallist: print tables >>> tab1 tab2 I=B4m trying to init my Gadfly database programmatically. I=B4ve got a la= rge list of tables and fields to create and I would=B4nt like to type all the= "creates" per hand Thanks Sharriff From scarblac@pino.selwerd.nl Tue Jan 23 11:03:21 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Tue, 23 Jan 2001 12:03:21 +0100 Subject: [Tutor] Stopping evalualtion of inner Lists/ tuples In-Reply-To: <200101230542_MC2-C2BC-EFEA@compuserve.com>; from NHYTRO@compuserve.com on Tue, Jan 23, 2001 at 05:42:14AM -0500 References: <200101230542_MC2-C2BC-EFEA@compuserve.com> Message-ID: <20010123120321.A30580@pino.selwerd.nl> On Tue, Jan 23, 2001 at 05:42:14AM -0500, Sharriff Aina wrote: > Hi Guys! > > Considering the following: > > tab1 = {"feld1": "varchar", "feld2": "varchar"} > tab2 = {"feld3": "varchar", "feld4": "varchar"} > virtuallist = [tab1, tab2] Now, virtuallist stores *references* to tab1 and tab2. It doesn't know their names. > >>> vlist > [{'feld2': 'varchar', 'feld1': 'varchar'}, {'feld3': 'varchar', 'feld4': > 'varchar'}] > >>> for x in vlist: > print x > > {'feld2': 'varchar', 'feld1': 'varchar'} > {'feld3': 'varchar', 'feld4': 'varchar'} > > >>> for x in vlist: > print `x` > > {'feld2': 'varchar', 'feld1': 'varchar'} > {'feld3': 'varchar', 'feld4': 'varchar'} > > How can I stop the evaluation of the innner List or tuple? They were already evaluated at the "tab1 = " line. vlist keeps references to these lists, but doesn't know that there happen to be names for these lists. I would like to > have > > for tables in virtuallist: > print tables > > >>> tab1 > tab2 You probably want to make a dictionary instead of a list. Try: virtuallist = {'tab1': tab1, 'tab2': tab2 } for name, table in virtuallist.items(): print name, table Hope this helps. -- Remco Gerlich From alan.gauld@bt.com Tue Jan 23 12:47:34 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Tue, 23 Jan 2001 12:47:34 -0000 Subject: [Tutor] Bruce Eckel thinking in Python Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D51A@mbtlipnt02.btlabs.bt.co.uk> This may be old news but I just noticed that Bruce Eckel has an embryonic web site set up for a new "Thinking in Python book: http://www.BruceEckel.com/Python/ThinkingInPython.html Given the success and quality of his previous C++ and Java books this should be a great web site for newbie Pythoneers... One to watch, Alan g. From FxItAL@aol.com Tue Jan 23 14:05:21 2001 From: FxItAL@aol.com (FxItAL@aol.com) Date: Tue, 23 Jan 2001 09:05:21 EST Subject: [Tutor] Modem disconnect Message-ID: <21.66be9f2.279ee9a1@aol.com> --part1_21.66be9f2.279ee9a1_boundary Content-Type: text/plain; charset="US-ASCII" Content-Transfer-Encoding: 7bit Hello All, Would someone point me in the right direction as to where to learn about enabling and disabling a modem. I would like to be able to set the time range that the modem is enabled. Thanks for your time, Al --part1_21.66be9f2.279ee9a1_boundary Content-Type: text/html; charset="US-ASCII" Content-Transfer-Encoding: 7bit Hello All,

          Would someone point me in the right direction as to where to learn
    about enabling and disabling a modem.  I would like to be able to set the
    time range that the modem is enabled.

    Thanks for your time, Al
    --part1_21.66be9f2.279ee9a1_boundary-- From kalle@gnupung.net Tue Jan 23 17:11:50 2001 From: kalle@gnupung.net (Kalle Svensson) Date: Tue, 23 Jan 2001 18:11:50 +0100 Subject: [Tutor] Modem disconnect In-Reply-To: <21.66be9f2.279ee9a1@aol.com>; from FxItAL@aol.com on Tue, Jan 23, 2001 at 09:05:21AM -0500 References: <21.66be9f2.279ee9a1@aol.com> Message-ID: <20010123181150.B7058@father> --oLBj+sq0vYjzfsbl Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable Sez FxItAL@aol.com: >=20 > Would someone point me in the right direction as to where to learn= =20 > about enabling and disabling a modem. I would like to be able to set the= =20 > time range that the modem is enabled. I believe this is very much OS and modem dependent. If you're running GNU/Linux, check out http://www.linuxdoc.org, they've got a modem-howto which could be what you're looking for. This could be of value for other Unix variants too. Windows or Mac, I have no idea. Peace Kalle --=20 Email: kalle@gnupung.net | You can tune a filesystem, but you Web: http://www.gnupung.net/ | can't tune a fish. -- man tunefs(8) PGP fingerprint: 0C56 B171 8159 327F 1824 F5DE 74D7 80D7 BF3B B1DD --oLBj+sq0vYjzfsbl Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.4 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE6bbtWdNeA1787sd0RAk7eAJ9QhvVXQ9wOAiHTWXPiaKZqTrlXCwCgyGBs kV1hWyX2WO92CAdDZMtTyZE= =gfSv -----END PGP SIGNATURE----- --oLBj+sq0vYjzfsbl-- From rmack@eznet.net Tue Jan 23 18:04:52 2001 From: rmack@eznet.net (Randolph MacKenzie) Date: Tue, 23 Jan 2001 13:04:52 -0500 Subject: [Tutor] removing extra whitespace from all *.txt files in a directory Message-ID: <002201c08566$fc8050c0$6668d140@thunderbird> This is a multi-part message in MIME format. ------=_NextPart_000_001F_01C0853D.131C3990 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable # X2space.py is a Python module for removing extra whitespace from all = *.txt or *.html files in a directory. I explain what was needed, and = Fredrik Lundh and Greg Jorgenson independently submitted these = solutions:=20 -------------------------------------------------------------------------= ------- Fredrik Lundh: You probably want the "inplace" flag to fileinput.input = instead: Optional in-place filtering: if the keyword argument inplace=3D1 is = passed to input() or to the FileInput constructor, the file is moved to = a backup file and standard output is directed to the input file. This = makes it possible to write a filter that rewrites its input file in = place. target =3D "E:\\text\\" import glob, fileinput, os, string, filelist =3D glob.glob(target+"*.TXT"); #Fredrik Lundh Python code: # get a list of files files =3D glob.glob("e:/somewhere/*.txt") if not files: sys.exit("nothing to convert") # process all lines in those files for line in fileinput.input(files, inplace=3D1, backup=3D".bak"): print string.join(string.split(line)) # End of Fredrik Lundh's excellent Python code) # The original files are saved as .bak and may be or deleted. os.system('del ' +target +'*.bak') -------------------------------------------------------------------------= ------- # Greg Jorgenson: tempfile.TemporaryFile() creates a new temporary file = and opens it for you; the value you get back is a file object ready for = writing, so you don't need to open it. But since you need the temporary = file name so you can rename it, you need to use the mktemp() method = instead: import glob, fileinput, os, tempfile, string files =3D glob.glob(r'e:\text\*.txt') for filename in files: tempname =3D tempfile.mktemp() temp =3D open(tempname, 'w') for s in fileinput.input(filename): temp.write(string.strip(string.join(string.split(s)))) temp.close() os.remove(filename) os.rename(tempname, filename) -------------------------------------------------------------------------= ------- Further development: Need to pass parameters for various dirs and file = types ------=_NextPart_000_001F_01C0853D.131C3990 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable

    # X2space.py is a Python module for removing extra whitespace from = all *.txt=20 or *.html files in a directory. I explain what was needed, and Fredrik = Lundh and=20 Greg Jorgenson independently submitted these solutions:=20


    Fredrik Lundh: You probably want the "inplace" flag to = fileinput.input=20 instead:

    Optional in-place filtering: if the keyword argument = inplace=3D1 is=20 passed to input() or to the FileInput constructor, the file is moved to = a backup=20 file and standard output is directed to the input file. This makes it = possible=20 to write a filter that rewrites its input file in place.

    target =
    =3D "E:\\text\\"
    
    import glob, fileinput, os, string,
    filelist =3D glob.glob(target+"*.TXT");
    
    #Fredrik Lundh Python code:
    
    # get a list of files
    files =3D glob.glob("e:/somewhere/*.txt")
    if not files:
        sys.exit("nothing to convert")
    
    # process all lines in those files
    for line in fileinput.input(files, inplace=3D1, backup=3D".bak"):
        print string.join(string.split(line))
    
    # End of Fredrik Lundh's excellent Python code)
    
    # The original files are saved as .bak and may be or deleted.
    
    os.system('del ' +target +'*.bak')
    

    # Greg Jorgenson: tempfile.TemporaryFile() creates a new = temporary=20 file and opens it for you; the value you get back is a file object ready = for=20 writing, so you don't need to open it. But since you need the temporary = file=20 name so you can rename it, you need to use the mktemp() method = instead:

    import glob, fileinput, os, tempfile, string
    
    files =3D glob.glob(r'e:\text\*.txt')
    
    for filename in files:
        tempname =3D tempfile.mktemp()
        temp =3D open(tempname, 'w')
        for s in fileinput.input(filename):
            temp.write(string.strip(string.join(string.split(s))))
        temp.close()
        os.remove(filename)
        os.rename(tempname, filename)
    

    Further development: Need to pass parameters for various dirs and = file=20 types

    ------=_NextPart_000_001F_01C0853D.131C3990-- From lumbricus@gmx.net Tue Jan 23 18:55:48 2001 From: lumbricus@gmx.net (=?ISO-8859-1?Q?J=F6rg_W=F6lke?=) Date: Tue, 23 Jan 2001 19:55:48 +0100 (MET) Subject: OT: Re: [Tutor] Modem disconnect References: <21.66be9f2.279ee9a1@aol.com> Message-ID: <28392.980276148@www27.gmx.net> --part1_21.66be9f2.279ee9a1_boundary Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: 8bit > Hello All, > > Would someone point me in the right direction as to where to learn > about enabling and disabling a modem. I would like to be able to set the > time range that the modem is enabled. > > Thanks for your time, Al > http://www.computercraft.com/docs/hayescom.html describes the commands u can use for a hayes-compatible modem helped me very much GREETS Jö! -- Sent through GMX FreeMail - http://www.gmx.net --part1_21.66be9f2.279ee9a1_boundary Content-Type: text/html; charset="US-ASCII" Content-Transfer-Encoding: 7bit Hello All,

          Would someone point me in the right direction as to where to learn
    about enabling and disabling a modem.  I would like to be able to set the
    time range that the modem is enabled.

    Thanks for your time, Al
    --part1_21.66be9f2.279ee9a1_boundary-- _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor From shaleh@valinux.com Tue Jan 23 19:06:33 2001 From: shaleh@valinux.com (Sean 'Shaleh' Perry) Date: Tue, 23 Jan 2001 11:06:33 -0800 Subject: [Tutor] problems with HTMLParser In-Reply-To: ; from dyoo@hkn.eecs.berkeley.edu on Mon, Jan 22, 2001 at 06:23:05PM -0800 References: <009201c084c6$6c8dd780$a410fea9@glen> Message-ID: <20010123110633.A2021@valinux.com> On Mon, Jan 22, 2001 at 06:23:05PM -0800, Daniel Yoo wrote: > > > I call this simply: > > > > > > foo = myHTML(NullFormatter) > ^^^^^^^^^^^^^ > > It's this part --- you need to pass in an instance of a NullFormatter when > doing stuff with HTMLParser: > > foo = myHTML(NullFormatter()) > > Don't worry, I've seen this bug a LOT. with the change mentioned above: ./import_toc.py [('href', 'mailto:mdorman@debian.org')] # obviously start_a happens Traceback (innermost last): File "./import_toc.py", line 34, in ? foo.feed(data) File "/usr/lib/python1.5/sgmllib.py", line 83, in feed self.goahead(0) File "/usr/lib/python1.5/sgmllib.py", line 118, in goahead k = self.parse_endtag(i) File "/usr/lib/python1.5/sgmllib.py", line 271, in parse_endtag self.finish_endtag(tag) File "/usr/lib/python1.5/sgmllib.py", line 325, in finish_endtag self.handle_endtag(tag, method) File "/usr/lib/python1.5/sgmllib.py", line 336, in handle_endtag method() # seems to die on end_a? TypeError: not enough arguments; expected 2, got 1 gah, HTMLParser should not be this hard. Also, when I get this working eventually I want the text wrapped in the anchor too, how do i get that? From martok@mattsmail.com Wed Jan 24 01:13:29 2001 From: martok@mattsmail.com (Matthias Hager) Date: Tue, 23 Jan 2001 17:13:29 -0800 Subject: [Tutor] perl Message-ID: <200101231713.AA22282512@mail.mattsmail.com> I know this is off the subject of Python, but this is the only place I could think of to come to. But here's a Perl Q or two. 1. How can you get the current location of a user in *nix? Where they are at directory wise. And how can you change their location to a different directory? I want to kind of emulate the cd and evrything functions of bash. Thanks matthias -- Programming isn't cool, it's awesome. %%%################?????????###################^^^ martok@mattsmail.com http://mymymatthias.tripod.com/ %%%################????????####################^^^ -- Like my email address? Get your own for FREE at http://firstname.com Get you@JohnsMail.com or you@AlexsMail.com or pick from 500 more! From deirdre@deirdre.net Wed Jan 24 01:49:20 2001 From: deirdre@deirdre.net (Deirdre Saoirse) Date: Tue, 23 Jan 2001 17:49:20 -0800 (PST) Subject: [Tutor] perl In-Reply-To: <200101231713.AA22282512@mail.mattsmail.com> Message-ID: On Tue, 23 Jan 2001, Matthias Hager wrote: > I know this is off the subject of Python, but this is the only place I > could think of to come to. But here's a Perl Q or two. 1. How can you > get the current location of a user in *nix? Where they are at > directory wise. And how can you change their location to a different > directory? I want to kind of emulate the cd and evrything functions of > bash. This isn't a perl list. While the list moms can tolerate a question or two, this isn't the resource for you. Start at http://www.perl.com for more info on perl. _Deirdre (one of the list moms) From dsh8290@rit.edu Wed Jan 24 02:31:08 2001 From: dsh8290@rit.edu (D-Man) Date: Tue, 23 Jan 2001 21:31:08 -0500 Subject: [Tutor] perl In-Reply-To: <200101231713.AA22282512@mail.mattsmail.com>; from martok@mattsmail.com on Tue, Jan 23, 2001 at 05:13:29PM -0800 References: <200101231713.AA22282512@mail.mattsmail.com> Message-ID: <20010123213108.A24319@harmony.cs.rit.edu> On Tue, Jan 23, 2001 at 05:13:29PM -0800, Matthias Hager wrote: | I know this is off the subject of Python, but this is the only place I could think of to come to. But here's a Perl Q or two. | 1. How can you get the current location of a user in *nix? Where they are at directory wise. And how can you change their location to a different directory? I want to kind of emulate the cd and evrything functions of bash. Did you make a typo and type "perl" instead of "python" ? ;-) import os print os.getcwd() # works on all platforms :-) os.chdir( "/etc" ) # function works on all platforms, but the argument # might give you some sort of invalid path error print os.getcwd() Enjoy studying python on a python tutor list. :-) -D From dsh8290@rit.edu Wed Jan 24 02:46:07 2001 From: dsh8290@rit.edu (D-Man) Date: Tue, 23 Jan 2001 21:46:07 -0500 Subject: [Tutor] Reading from a GUI In-Reply-To: <002a01c0840e$68290060$a410fea9@glen>; from wheelege@tsn.cc on Mon, Jan 22, 2001 at 11:58:16AM +1100 References: <000001c08404$4e5bd270$0300000a@budgester> <002a01c0840e$68290060$a410fea9@glen> Message-ID: <20010123214607.B24319@harmony.cs.rit.edu> On Mon, Jan 22, 2001 at 11:58:16AM +1100, wheelege wrote: | | Hi, | | Is this what you meant.... | | PythonWin 2.0 (#8, Oct 19 2000, 11:30:05) [MSC 32 bit (Intel)] on win32. | Portions Copyright 1994-2000 Mark Hammond (MarkH@ActiveState.com) - see | 'Help/About PythonWin' for further copyright information. | >>> a = "first line\nsecond line" | >>> a | 'first line\012second line' | >>> print a | first line | second line | | From that I gather that the escape code is \012 ? What is meant by "escape code" can differ by useage. For example, in Eiffel you would use "%N" as the excape code for a newline. \012 is the octal value of the character. 0xA is the hexadeciaml value and 10 is the decimal value. In C/C++/Java/Perl and Python \n is used as the escape for a newline, but with the proper conversion you can use any of these. To "read from" a GUI you need to check the docs of the gui you are using. In GTK, for example, there is a funciton get_text in the Gtk.Text widget (or some similar name). The function returns a string object. import string my_str = text_widget.get_text() modified_str = string.replace( my_str, "\n" , "
    " ) print my_str pirnt modified_str The text widget (text_widget) has already been created and bound to the name. I use the replace() function in the string module to replace all newlines with "
    ". I probably have the arguments in the wrong order though. Use the following to find out which order to use: import string print string.replace.__doc__ HTH, -D From dsh8290@rit.edu Wed Jan 24 03:01:26 2001 From: dsh8290@rit.edu (D-Man) Date: Tue, 23 Jan 2001 22:01:26 -0500 Subject: [Tutor] Hardware input In-Reply-To: <200101222003.AA70582560@mail.mattsmail.com>; from martok@mattsmail.com on Mon, Jan 22, 2001 at 08:03:46PM -0800 References: <200101222003.AA70582560@mail.mattsmail.com> Message-ID: <20010123220126.C24319@harmony.cs.rit.edu> On Mon, Jan 22, 2001 at 08:03:46PM -0800, Matthias Hager wrote: | How do you receive input from hardware? Can python do it directly? Say I want to make a cd song player, can python do this and how? Or using microphone, printer, scanner, etc.. You want to make device drivers now? This can be interesting. Python is not particularly well suited for device drivers. It is better to write such things in C or some other low-level language, then make a python module that can interact with the driver. When I did a little bit of assembly language programming (Motorla 68K arch) we used memory mapped io. Basically, some addresses in memory were set to read/write to the device's registers (just the PI/T and DUART). Then the code would simply read/write to those "magic" locations. C can access arbitrary locations like this, but python can't. You would also need to know the specs for you the scanner, etc, communicate with the computer. Not a trivial thing. If all you want is a higher level control, then perhaps you can interact with an existing driver. I don't recall if you are working with Windows or *nix, but it would (probably) be different for each of them. To print you would want to work with the system's existing printing mechanisms. (lpr/lpd for *nix, try the win32all module for 'doze) I don't know about scanners. There is a standard called TWAIN but I don't have any experience in developer issues (I've only used scanners as a user, only in 'doze). There is probably a sound module you could use for the microphone. I suppose you could just read from the device file in /dev (*nix), but I don't know if that will produce useful data or if you would need to do some significant processing on it. To read a cd you could open /dev/cdrom. I imagine that you would have to handle the sector offsets for the tracks yourself. Maybe using seek()? If you know C you could look at programs like gtcd and see how they do it. HTH, -D From dyoo@hkn.eecs.berkeley.edu Wed Jan 24 08:30:50 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 24 Jan 2001 00:30:50 -0800 (PST) Subject: [Tutor] problems with HTMLParser In-Reply-To: <20010123110633.A2021@valinux.com> Message-ID: On Tue, 23 Jan 2001, Sean 'Shaleh' Perry wrote: > gah, HTMLParser should not be this hard. Also, when I get this working > eventually I want the text wrapped in the anchor too, how do i get that? Hmmm... let's take another look. From the last version of your source: ### class myHTML(HTMLParser): def __init__(self, formatter, verbose = 0): HTMLParser.__init__(self, formatter, verbose) self.section_list = [] # to be filled in later def start_ul(self, attributes): pass def end_ul(self, attributes): pass def start_li(self, attributes): pass def end_li(self, attributes): pass def start_a(self, attributes): print attributes ### So there's a definition for start_a(), but there needs to be a definition of end_a(); they act as a pair. That's probably why it's complaining: > File "/usr/lib/python1.5/sgmllib.py", line 336, in handle_endtag > method() # seems to die on end_a? > TypeError: not enough arguments; expected 2, got 1 Add a do-nothing end_a() method to your class, and with luck, that should fix that bug. About the line justification; I think that one of the regular formatters will actually do line justification for you, but I haven't looked too closely into them yet. Take a look at DumbWriter: http://python.org/doc/current/lib/writer-interface.html and see if it's suitable for your program. From dyoo@hkn.eecs.berkeley.edu Wed Jan 24 08:39:25 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 24 Jan 2001 00:39:25 -0800 (PST) Subject: [Tutor] perl In-Reply-To: <200101231713.AA22282512@mail.mattsmail.com> Message-ID: On Tue, 23 Jan 2001, Matthias Hager wrote: > I know this is off the subject of Python, but this is the only place I could think of to come to. But here's a Perl Q or two. > 1. How can you get the current location of a user in *nix? Where they > are at directory wise. And how can you change their location to a > different directory? I want to kind of emulate the cd and evrything > functions of bash. Don't know too much about Perl, but I know that perldoc is a good friend... *grin* Try "perldoc -f chdir", which should give you enough information to change directories pretty easily. About finding the current directory... hmmm... well, the quick fix is to do: $dirname = `pwd` if you're on a UNIX; otherwise, I'm not quite sure; I'm a Perl newbie myself. You might want to check with "perldoc perlfunc" and see if there's something useful there. Otherwise, check either the Camel book or talk to some people on comp.lang.perl. Good luck! From cpsoct@lycos.com Wed Jan 24 10:22:41 2001 From: cpsoct@lycos.com (kevin parks) Date: Wed, 24 Jan 2001 19:22:41 +0900 Subject: [Tutor] apply() Message-ID: I don't really understand when to use apply, when it is needed or useful. Can anyone think of a good example of when to use apply or a task that requires it. For some strange reason i can't seem to get my head around it and what it is used for. cheers, kevin parks seoul, korea Get your small business started at Lycos Small Business at http://www.lycos.com/business/mail.html From cpsoct@lycos.com Wed Jan 24 10:31:03 2001 From: cpsoct@lycos.com (kevin parks) Date: Wed, 24 Jan 2001 19:31:03 +0900 Subject: [Tutor] list (in)comprehensions Message-ID: The other thing that i am failing to understand is Python's new list comprehensions. They are new to 2.0 so are not discussed in any of the books that i have and the www.python.org site has very little on them, except for a few examples of someone fooling around with the interpreter. Some explanation would be helpful. I have been hacking lots of list processing tools and i have a feeling that they could all be rewritten more easily with list comprehensions if only i could (i can't say it) C O M P R E H E N D them (ok i said it). What are list comprehensions good for, what do they make easier, how to use them, etc. As a guy who uses map and filter everyday, it seems like something i better know. I sorely wish there was a howto with code and someone talking to me too! (Python documentation shouldn't just be a screenshot of someone's interpreter, though including an interactive session is helpful). Thanks and happy new year to everyone (year o' da snake it is!) kevin parks seoul, korea Get your small business started at Lycos Small Business at http://www.lycos.com/business/mail.html From scarblac@pino.selwerd.nl Wed Jan 24 14:11:55 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Wed, 24 Jan 2001 15:11:55 +0100 Subject: [Tutor] list (in)comprehensions In-Reply-To: ; from cpsoct@lycos.com on Wed, Jan 24, 2001 at 07:31:03PM +0900 References: Message-ID: <20010124151155.B451@pino.selwerd.nl> On Wed, Jan 24, 2001 at 07:31:03PM +0900, kevin parks wrote: > The other thing that i am failing to understand is Python's new list > comprehensions. They are new to 2.0 so are not discussed in any of the books > that i have and the www.python.org site has very little on them, except for > a few examples of someone fooling around with the interpreter. Some > explanation would be helpful. I have been hacking lots of list processing > tools and i have a feeling that they could all be rewritten more easily with > list comprehensions if only i could (i can't say it) C O M P R E H E N D > them (ok i said it). What are list comprehensions good for, what do they > make easier, how to use them, etc. As a guy who uses map and filter > everyday, it seems like something i better know. I sorely wish there was a > howto with code and someone talking to me too! (Python documentation > shouldn't just be a screenshot of someone's interpreter, though including an > interactive session is helpful). You already know map and filter, and more Python, so I'll try to explain it a bit better comparing list comprehensions to those. Say, you want a list of the squares of the numbers 0 to 9. You could do that with a for loop: squares = [] for x in range(10): squares.append(x**2) Or with a map/lambda call: squares = map(lambda x: x**2, range(10)) What both of these do, conceptually, is "take x's from the list range(10), and for each one of them, add x**2 to the list". With list comprehensions, you write that like this: squares = [x**2 for x in range(10)] For each x in the list 'range(10)', it computes the expression 'x**2', and puts the results in a list. This is faster than the for loop, more readable than map/lambda, it doesn't leave a variable 'x' in your namespace (it only exists in the list comprehension). It's also shorter than both alternatives. Also, lambda has its own namespace, meaning you sometimes need to do strange default parameter tricks to make it work. Say, if the power isn't 2, but is stored in the variable 'power': power = 4 powers = map(lambda x, power=power: x**power, range(10)) List comprehensions do not have this problem: power = 4 powers = [x**power for x in range(10)] works fine. It's also possible to have more than one 'for' clause. For instance, if you want to have a list of all the tuples (x,y) for 0 <= x,y <= 5 (like (1,3), (0,4), but not (2,6)), you could make this for loop: tuples = [] for y in range(6): for x in range(6): tuples.append((x,y)) This is the same as this list comprehension: tuples = [(x,y) for x in range(6) for y in range(6)] I hope this is clear. There is also the 'if' feature, which is similar to 'filter'. What if you only want the *odd* squares of the numbers 0 to 9? This is the for loop: squares = [] for x in range(10): if x%2 == 1: squares.append(x**2) Map/lambda/filter: squares = map(lambda x: x**2, filter(lambda x: x%2 == 1, range(10))) (note how complicated that gets) And the list comprehension is: squares = [x**2 for x in range(10) if x%2 == 1] So you use the 'if' clause to select suitable values from the list, like filter does, but you don't need a lambda. You can have multiple if clauses, then the value has to fit all of them. That's about it. Since 2.0 I've noticed that list comprehensions can become too complicated quite quickly as well, and that for loops are pretty nice for readability. But I usually prefer them over map/lambda/filter combinations, especially when the lambda would need a default argument. >From a mp3player script I wrote earlier today, a real life example, I need a list of the full pathnames of .mp3 files in directory d (and I have directories named *.mp3 as well...): listdir = [os.path.abspath(d+'/'+x) for x in os.listdir(d)] mp3s = [x for x in listdir if x.endswith('.mp3') if os.path.isfile(x)] (This could be one list comprehension except the other files in listdir were used elsewhere) (Note that I always used x for the variable name in these examples, but it can actually be anything) (heck, i thought this was a long post, but alex martelli has posts thrice this long *on average*..., I think) Well that should be enough. Back to work :) -- Remco Gerlich From dyoo@hkn.eecs.berkeley.edu Wed Jan 24 21:19:24 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 24 Jan 2001 13:19:24 -0800 (PST) Subject: [Tutor] list (in)comprehensions In-Reply-To: Message-ID: On Wed, 24 Jan 2001, kevin parks wrote: > can't say it) C O M P R E H E N D them (ok i said it). What are list > comprehensions good for, what do they make easier, how to use them, > etc. As a guy who uses map and filter everyday, it seems like > something i better know. I sorely wish there was a howto with code and > someone talking to me too! (Python documentation shouldn't just be a > screenshot of someone's interpreter, though including an interactive > session is helpful). List comprehensions make writing list-processing code a little easier. For example, let's say we had the list: L = list(range(20)) # [0, 1, ..., 19] What sort of things can we do with it? If we wanted to square each number, we could do this: squaredL = map(lambda x: x * x, L) But many people feel uncomforable about lambdas and maps. List comprehensions is 'map' in another disguise: squaredL = [x*x for x in L] Here, we just tell Python the expression we want to compute, over some sort of loop over a list. For people that know about for loops, this seems to be easier to handle than mapping a function across a list. Also, it reduces the need to use lambda. (Not that lambda is a bad thing, but it's initially weird to people.) Hope this helps! From dyoo@hkn.eecs.berkeley.edu Wed Jan 24 21:58:11 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 24 Jan 2001 13:58:11 -0800 (PST) Subject: [Tutor] apply() In-Reply-To: Message-ID: On Wed, 24 Jan 2001, kevin parks wrote: > I don't really understand when to use apply, when it is needed or > useful. Can anyone think of a good example of when to use apply or a > task that requires it. For some strange reason i can't seem to get my > head around it and what it is used for. To tell the truth, I haven't used apply() too often myself. apply()'s used in code that's very dynamic in nature (for example, interpreters), so examples that use it are usually complicated. I'm trying to think of an interesting program that could naturally use apply. Hmmm. Let's say we want to make a small calculator program. I'll pretend that it works already, and give a brief "simulation" of how I think it would work: ### square 5 25 add 4 7 Result: 11 quit bye ### So this calculator will make it easy to play around with functions, and depending on the function, it will either take in one or two arguments, and apply that function on the arguments. How could we write this? Let's try it: ### from sys import exit def add(x, y): return x + y def square(x): return x * x def divide(x, y): return x / y def quit(): print "bye" exit() class Calculator: def __init__(self): self.operations = {} def addOperation(self, name, function): self.operations[name] = function def execute(self, line): name, arguments = line.split()[0], map(float, line.split()[1:]) function = self.operations[name] return apply(function, arguments) if __name__ == '__main__': calc = Calculator() calc.addOperation('add', add) calc.addOperation('square', square) calc.addOperation('divide', divide) calc.addOperation('quit', quit) # we could add more if we wanted to ... try: while 1: print calc.execute(raw_input()), "\n" except KeyboardInterrupt: pass ### The program is simpler than it looks: the reason why apply() is used is because we need to call a function, but we don't know in advance how many arguments the user will input. We'll use apply(), which will take a function and a list, and use the list elements as the function's arguments. That way, we place very few restrictions on what our "calculator" can do. I hope that this made some sense; For me, it's hard to write a small example that uses apply(). From arcege@shore.net Wed Jan 24 22:46:46 2001 From: arcege@shore.net (Michael P. Reilly) Date: Wed, 24 Jan 2001 17:46:46 -0500 (EST) Subject: [Tutor] apply() In-Reply-To: from "kevin parks" at Jan 24, 2001 07:22:41 PM Message-ID: <200101242246.RAA00281@northshore.shore.net> > > I don't really understand when to use apply, when it is needed or useful. Can anyone think of a good example of when to use apply or a task that requires it. For some strange reason i can't seem to get my head around it and what it is used for. > The purpose of apply is to call a function or method with a variable, unknown number of arguments. Most of the time in practice, within Python, this is used in subclass methods to call a superclass's method. class SpamMeal: def __init__(self, *ingredients): self.d = list(ingredients) class BreakFast(SpamMeal): def __init__(self, howmany_eggs, *ingredients): apply(SpamMeal.__init__, # this is an unbound method, we have to pass self (self,) + ('eggs',) * howmany_eggs + ingredients ) The BreakFast.__init__ method gets called with some heretofore unknown number of ingredients, specifically some number of eggs and other ingredients. -Arcege -- ------------------------------------------------------------------------ | Michael P. Reilly, Release Manager | Email: arcege@shore.net | | Salem, Mass. USA 01970 | | ------------------------------------------------------------------------ From shaleh@valinux.com Wed Jan 24 23:20:53 2001 From: shaleh@valinux.com (Sean 'Shaleh' Perry) Date: Wed, 24 Jan 2001 15:20:53 -0800 (PST) Subject: [Tutor] problems with HTMLParser In-Reply-To: Message-ID: On 24-Jan-2001 Danny Yoo wrote: > On Tue, 23 Jan 2001, Sean 'Shaleh' Perry wrote: > >> gah, HTMLParser should not be this hard. Also, when I get this working >> eventually I want the text wrapped in the anchor too, how do i get that? > > Hmmm... let's take another look. From the last version of your source: > > > So there's a definition for start_a(), but there needs to be a definition > of end_a(); they act as a pair. That's probably why it's complaining: > >> File "/usr/lib/python1.5/sgmllib.py", line 336, in handle_endtag >> method() # seems to die on end_a? >> TypeError: not enough arguments; expected 2, got 1 > > Add a do-nothing end_a() method to your class, and with luck, that should > fix that bug. > you are right, another look at the source was needed, but your analysis was off (-: Problem was my declaration of my end_foo() functions: def end_li(self, attributes) there are no attributes of end tags, doh. Removing the extra option made everything happy. The error message is because the end_ function I defined had two parameters and the one it was expecting only took self. From shaleh@valinux.com Wed Jan 24 23:22:12 2001 From: shaleh@valinux.com (Sean 'Shaleh' Perry) Date: Wed, 24 Jan 2001 15:22:12 -0800 (PST) Subject: [Tutor] problems with HTMLParser In-Reply-To: Message-ID: > > About the line justification; I think that one of the regular formatters > will actually do line justification for you, but I haven't looked too > closely into them yet. Take a look at DumbWriter: > > http://python.org/doc/current/lib/writer-interface.html > > and see if it's suitable for your program. > > I was not clear on the last part. Go to example.com How do I get the text "Go to example.com"? From shaleh@valinux.com Wed Jan 24 23:48:13 2001 From: shaleh@valinux.com (Sean 'Shaleh' Perry) Date: Wed, 24 Jan 2001 15:48:13 -0800 (PST) Subject: [Tutor] problems with HTMLParser In-Reply-To: Message-ID: On 24-Jan-2001 Sean 'Shaleh' Perry wrote: >> >> About the line justification; I think that one of the regular formatters >> will actually do line justification for you, but I haven't looked too >> closely into them yet. Take a look at DumbWriter: >> >> http://python.org/doc/current/lib/writer-interface.html >> >> and see if it's suitable for your program. >> >> > > I was not clear on the last part. > > Go to example.com > > How do I get the text "Go to example.com"? > /me often forgets how easy python source is to read (-: reading sgmllib/htmllib I find that I need to define a handle_data() function. So, my TOC reader is now working, yay (-: Need to clean up the output and some other sundries, but below is a good idea of what is happening. Suggestions on code improvements and python idioms welcome. class myHTML(HTMLParser): def __init__(self, formatter, verbose = 0): HTMLParser.__init__(self, formatter, verbose) self.found_anchor = 0 self.want_anchor = 0 self.tmp_url = [] self.urls = [] def start_ul(self, attributes): pass def end_ul(self): self.want_anchor = 0 def start_li(self, attributes): self.want_anchor = 1 def end_li(self): self.want_anchor = 0 def start_a(self, attributes): if self.want_anchor: self.tmp_url.append(attributes[0][1]) self.found_anchor = 1 def end_a(self): if self.found_anchor: self.found_anchor = 0 self.tmp_url = [] def handle_data(self, data): if self.found_anchor: self.tmp_url.append(data) self.urls.append(self.tmp_url) if __name__ == '__main__': file = '/usr/share/doc/debian-policy/policy.html/index.html' fp = open(file) data = fp.read() fp.close() foo = myHTML(NullFormatter()) foo.feed(data) foo.close() for url in foo.urls: print "%s => %s" % (url[0], url[1]) From s349929@student.uq.edu.au Thu Jan 25 00:59:52 2001 From: s349929@student.uq.edu.au (Suzanne Little) Date: Thu, 25 Jan 2001 10:59:52 +1000 (GMT+1000) Subject: [Tutor] ValueError Message-ID: Hello, I'm hoping someone can suggest a potential solution for why I'm getting this error. Quick background: It's a script that generates an html page. There's a variable (BODY) with a large string of html (in ''') and %(var_name)s in various places. The function takes a dictionary and does some bit's and pieces before html_string.append(BODY % dictionary) is called. This is where the following error is occuring. <---> File formatter.py, line 271, in build_single html_string.append(BODY % dictionary) ValueError: unsupported format character '"' (0x22) I figured that I'd forgotten to escape one of my " in the BODY string but I'm fairly sure that I've gotten them all besides which, if I understand what I was just looking at in the tutorial, I can have double quotes in my string if it's inside single quotes and vice versa. (Is this true of triple quotes ''' " '''?) The string BODY appears valid and the dictionary seems fine. (The words appears and seems are deliberate since something's got to be causing the error :)) So I'm a bit puzzled. This is the second function of this type I've written and the first was fine. Any ideas where I should be looking? The code's really too long and ugly to post so hopefully the above is enough for someone to give me some clues. Thanks, Suzanne -------------------------------------------------------------------------- "Contrariwise," continued Tweedledee, "If it was so, it might be; and if it were so, it would be; but as it isn't, it ain't. That's logic" -Lewis Carroll -------------------------------------------------------------------------- From gt_geiger@yahoo.com Thu Jan 25 02:27:35 2001 From: gt_geiger@yahoo.com (Gregg T. Geiger) Date: Wed, 24 Jan 2001 18:27:35 -0800 (PST) Subject: [Tutor] Object Destruction Message-ID: <20010125022735.28128.qmail@web1104.mail.yahoo.com> What are scope rules for class objects and when are they destroyed, specifically with regards to for loops? That is, if a class Spam is defined somewhere and used in a for loop as follows: for i in [0, 1, 2, 3, 4]: spam = Spam() # end of for loop will an object be created and destroyed with each pass through the loop or does each instance remain "alive"? In a comparable C++ loop for (int i = 0; i < 5; ++i){ Spam spam; } the destructor is called 5 times. In my own experience with Python, files opened in Spam are not closed each time through the loop unless explicitly closed within the class. Any insight(s) would be appreciated. Thanks. Gregg __________________________________________________ Do You Yahoo!? Yahoo! Auctions - Buy the things you want at great prices. http://auctions.yahoo.com/ From dyoo@hkn.eecs.berkeley.edu Thu Jan 25 06:18:04 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 24 Jan 2001 22:18:04 -0800 (PST) Subject: [Tutor] problems with HTMLParser In-Reply-To: Message-ID: On Wed, 24 Jan 2001, Sean 'Shaleh' Perry wrote: > >> method() # seems to die on end_a? > >> TypeError: not enough arguments; expected 2, got 1 > > > > Add a do-nothing end_a() method to your class, and with luck, that should > > fix that bug. > > > > you are right, another look at the source was needed, but your > analysis was off (-: Nuts, I'm getting sloppy... *grin* Glad that bug's fixed though! From dyoo@hkn.eecs.berkeley.edu Thu Jan 25 06:34:05 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 24 Jan 2001 22:34:05 -0800 (PST) Subject: [Tutor] Object Destruction In-Reply-To: <20010125022735.28128.qmail@web1104.mail.yahoo.com> Message-ID: On Wed, 24 Jan 2001, Gregg T. Geiger wrote: > What are scope rules for class objects and when are they > destroyed, specifically with regards to for loops? > > That is, if a class Spam is defined somewhere and used in a > for loop as follows: > > for i in [0, 1, 2, 3, 4]: > spam = Spam() > # end of for loop Hmm... Python is reference garbage collected, so whenever an instance's reference count goes to zero, the instance should implode. We can experimentally test to see when an object gets garbage collected by overriding the '__del__' method. Since Python works well with the interpreter, let's try it out: ### >>> class TestDel: ... def __init__(self, name): ... self.name = name ... def __del__(self): ... print self.name, "garbage collected" ... >>> TestDel("Anna") <__main__.TestDel instance at 0x81ca2fc> # that's curious, I expected garbage collection at this point... Strange! # I'll have to think about that one later... >>> x = TestDel("Anna") >>> del(x) Anna garbage collected >>> x = TestDel("Anna") >>> x = TestDel("King") Anna garbage collected >>> for i in range(5): ... x = TestDel(i) ... King garbage collected 0 garbage collected 1 garbage collected 2 garbage collected 3 garbage collected ### So it pretty much does what you'd expect... except for that odd thing at the very beginning. Weird! > will an object be created and destroyed with each pass > through the loop or does each instance remain "alive"? In > a comparable C++ loop >From the results above, yes. > the destructor is called 5 times. In my own experience > with Python, files opened in Spam are not closed each time > through the loop unless explicitly closed within the class. Those files have to go out of scope, so that the reference counts go down; otherwise, Python might prematurely close things down. If you want, you can show us the file opening code, and we can make sure that things look ok. Try some more experiments with __del__. I'm somewhat bothered by what happened at the beginning of the interpreter session above, and might take a look again later to figure out why it didn't garbage collect initially. From dyoo@hkn.eecs.berkeley.edu Thu Jan 25 06:43:19 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 24 Jan 2001 22:43:19 -0800 (PST) Subject: [Tutor] ValueError In-Reply-To: Message-ID: On Thu, 25 Jan 2001, Suzanne Little wrote: > Quick background: > It's a script that generates an html page. There's a variable (BODY) with > a large string of html (in ''') and %(var_name)s in various places. The > function takes a dictionary and does some bit's and pieces before > html_string.append(BODY % dictionary) is called. This is where the > following error is occuring. > <---> > File formatter.py, line 271, in build_single > html_string.append(BODY % dictionary) > ValueError: unsupported format character '"' (0x22) Try searching through your body for the string '%"' --- from the error message, it sounds like that string is somewhere within your BODY. Let's see if we can duplicate that error message: ### >>> """This is a test.%" Hello world!""" % 42 Traceback (most recent call last): File "", line 1, in ? ValueError: unsupported format character '"' (0x22) ### Ok, so that's one of the stronger possibilities out there. > So I'm a bit puzzled. This is the second function of this type I've > written and the first was fine. Any ideas where I should be looking? > The code's really too long and ugly to post so hopefully the above is > enough for someone to give me some clues. Take a closer look at BODY --- a good approach is to selectively cut parts of the string out, and isolate what portion of BODY is causing problems. Don't worry: I think you'll find this one pretty quickly. Good luck! From dyoo@hkn.eecs.berkeley.edu Thu Jan 25 07:01:19 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Wed, 24 Jan 2001 23:01:19 -0800 (PST) Subject: [Tutor] Object Destruction In-Reply-To: Message-ID: > Try some more experiments with __del__. I'm somewhat bothered by what > happened at the beginning of the interpreter session above, and might take > a look again later to figure out why it didn't garbage collect initially. Ah! Now I know why! There's still a reference! >From the Python tutorial: http://python.org/doc/current/tut/node5.html "In interactive mode, the last printed expression is assigned to the variable _." Tricky little critter! In the situation here: ### >>> TestDel("Anna") <__main__.TestDel instance at 0x81ca2fc> ### the reason that it didn't garbage collect immediately was because the interactive interpreter itself has a reference to the instance with the "_" variable. Since there's still a reference, it doesn't die until "_" is reassigned to the next evaluated expression or statement. Ok, that nagging feeling is gone now. *grin* From scarblac@pino.selwerd.nl Thu Jan 25 08:27:28 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Thu, 25 Jan 2001 09:27:28 +0100 Subject: [Tutor] ValueError In-Reply-To: ; from s349929@student.uq.edu.au on Thu, Jan 25, 2001 at 10:59:52AM +1000 References: Message-ID: <20010125092728.A2068@pino.selwerd.nl> On Thu, Jan 25, 2001 at 10:59:52AM +1000, Suzanne Little wrote: > I'm hoping someone can suggest a potential solution for why I'm getting > this error. > > Quick background: > It's a script that generates an html page. There's a variable (BODY) with > a large string of html (in ''') and %(var_name)s in various places. The > function takes a dictionary and does some bit's and pieces before > html_string.append(BODY % dictionary) is called. This is where the > following error is occuring. > <---> > File formatter.py, line 271, in build_single > html_string.append(BODY % dictionary) > ValueError: unsupported format character '"' (0x22) > > I figured that I'd forgotten to escape one of my " in the BODY string but > I'm fairly sure that I've gotten them all besides which, if I understand > what I was just looking at in the tutorial, I can have double quotes in my > string if it's inside single quotes and vice versa. (Is this true of > triple quotes ''' " '''?) The string BODY appears valid and the > dictionary seems fine. (The words appears and seems are deliberate since > something's got to be causing the error :)) > > So I'm a bit puzzled. This is the second function of this type I've > written and the first was fine. Any ideas where I should be looking? > The code's really too long and ugly to post so hopefully the above is > enough for someone to give me some clues. It's the % operator that is complaining about a " somewhere. Do you have a combination like %" somewhere? -- Remco Gerlich From scarblac@pino.selwerd.nl Thu Jan 25 08:35:03 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Thu, 25 Jan 2001 09:35:03 +0100 Subject: [Tutor] Object Destruction In-Reply-To: ; from dyoo@hkn.eecs.berkeley.edu on Wed, Jan 24, 2001 at 10:34:05PM -0800 References: <20010125022735.28128.qmail@web1104.mail.yahoo.com> Message-ID: <20010125093503.B2068@pino.selwerd.nl> On Wed, Jan 24, 2001 at 10:34:05PM -0800, Danny Yoo wrote: > On Wed, 24 Jan 2001, Gregg T. Geiger wrote: > > > What are scope rules for class objects and when are they > > destroyed, specifically with regards to for loops? > > > > That is, if a class Spam is defined somewhere and used in a > > for loop as follows: > > > > for i in [0, 1, 2, 3, 4]: > > spam = Spam() > > # end of for loop > > Hmm... Python is reference garbage collected, so whenever an instance's > reference count goes to zero, the instance should implode. We can > experimentally test to see when an object gets garbage collected by > overriding the '__del__' method. Since Python works well with the > interpreter, let's try it out: > > ### > >>> class TestDel: > ... def __init__(self, name): > ... self.name = name > ... def __del__(self): > ... print self.name, "garbage collected" > ... > >>> TestDel("Anna") > <__main__.TestDel instance at 0x81ca2fc> > > # that's curious, I expected garbage collection at this point... Strange! > # I'll have to think about that one later... Things like this can be surprising in the interactive interpreter. It keeps a reference to the last result, try >>> _ <___main___.TestDel instance at 0x81ca2fc> >>> 3 Anna garbage collected 3 > >>> x = TestDel("Anna") > >>> del(x) > Anna garbage collected > >>> x = TestDel("Anna") > >>> x = TestDel("King") > Anna garbage collected > >>> for i in range(5): > ... x = TestDel(i) > ... > King garbage collected > 0 garbage collected > 1 garbage collected > 2 garbage collected > 3 garbage collected > ### > > So it pretty much does what you'd expect... except for that odd thing at > the very beginning. Weird! Apparently none of the things later return a result that the interpreter keeps as _... > > will an object be created and destroyed with each pass > > through the loop or does each instance remain "alive"? In > > a comparable C++ loop > > From the results above, yes. The objects will be destroyed, *unless* they initialize some things in their __init__, and those things still keep references back to the object. -- Remco Gerlich From randrews@planhouse.com Thu Jan 25 19:52:43 2001 From: randrews@planhouse.com (Rob Andrews) Date: Thu, 25 Jan 2001 13:52:43 -0600 Subject: [Tutor] removal of duplicates from .csv files Message-ID: <006501c08708$637257e0$dc00a8c0@Planhouse5> I have been given several comma-delimited (.csv) files, each containing as many as several thousand lines of entries. Among the tasks I've been charged with is to remove duplicate entries. The files each contain fields for Contact Name, Company Name, Phone Number, and Address, among other fields, which vary from file to file. I'm trying to determine a good way to sort for duplicates according to Phone Number and according to Address. It seems that sorting by Phone Number would be simpler due to minor differences in the way data entry clerks might have input the addresses (W, W., and West, for instance), but not all entries have phone numbers. I have already come up with some code to work around most of the obvious problems with the different ways addresses may be input, but I'm not sure what the best way to sort for duplicates might be. One suggestion I have received is to have lines with identical fields placed back to back with an equivalence check and manually read through the file. The equivalence check itself seems simple, but I'm not sure how to scan only the target field (split(), maybe?), and I certainly want to avoid having to manually remove the duplicates afterward. Has anyone already worked out a good approach? TIA, Rob Andrews Useless Python Repository http://www.lowerstandard.com/python/pythonsource.html From scott@zenplex.com Thu Jan 25 21:12:26 2001 From: scott@zenplex.com (Scott Comboni) Date: Thu, 25 Jan 2001 16:12:26 -0500 Subject: [Tutor] Python2.0 question Message-ID: <01012516122606.01083@scoot.zenplex.com> I just decided to check out Python 2.0 and all seems well but for one thing. When I execute the interpeter I cannot use my arrow keys to repeat a command. Is there something simple I missed. I really like this command history feature. Does anyone know how to turn it on? When I do hit the the arrow keys I just get garbage on the screen: Python 2.0 (#1, Jan 8 2001, 15:29:39) [GCC 2.95.3 19991030 (prerelease)] on linux2 Type "copyright", "credits" or "license" for more information. >>> ^[[D^[[C^[[A^[[B Thanks Scott From scarblac@pino.selwerd.nl Thu Jan 25 21:40:00 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Thu, 25 Jan 2001 22:40:00 +0100 Subject: [Tutor] Python2.0 question In-Reply-To: <01012516122606.01083@scoot.zenplex.com>; from scott@zenplex.com on Thu, Jan 25, 2001 at 04:12:26PM -0500 References: <01012516122606.01083@scoot.zenplex.com> Message-ID: <20010125224000.A6249@pino.selwerd.nl> On Thu, Jan 25, 2001 at 04:12:26PM -0500, Scott Comboni wrote: > I just decided to check out Python 2.0 and all seems well but for one thing. > When I execute the interpeter I cannot use my arrow keys to repeat a command. > Is there something simple I missed. I really like this command history > feature. Does anyone know how to turn it on? > When I do hit the the arrow keys I just get garbage on the screen: > > Python 2.0 (#1, Jan 8 2001, 15:29:39) > [GCC 2.95.3 19991030 (prerelease)] on linux2 > Type "copyright", "credits" or "license" for more information. > >>> ^[[D^[[C^[[A^[[B Did you install it from source? If you did, you need to edit Modules/Setup and uncomment the line that says readline readline.c -lreadline -ltermcap If you didn't, then your version still isn't built with libreadline. Readline is GPL'ed, and there is a silly discussion going on with RMS about the current Python license, which may or may not be GPL compatible (in my opinion it is, but IANAL, and in RMS's it's not, and he has a lawyer). That means you have to compile from source if you want to use GPL libraries... -- Remco Gerlich From tamezi_2000@yahoo.com Thu Jan 25 22:02:30 2001 From: tamezi_2000@yahoo.com (IVAN TAMEZ) Date: Thu, 25 Jan 2001 14:02:30 -0800 (PST) Subject: [Tutor] UNSUBSCRIBE PLEASE Message-ID: <20010125220230.4717.qmail@web9506.mail.yahoo.com> --0-429287096-980460150=:4461 Content-Type: text/plain; charset=us-ascii PLEASE UNSUBSCRIBE FROM MAILING LIST THANKS IVAN TAMEZ tamezi_2000@yahoo.com --------------------------------- Do You Yahoo!? Yahoo! Auctions - Buy the things you want at great prices. --0-429287096-980460150=:4461 Content-Type: text/html; charset=us-ascii

    PLEASE UNSUBSCRIBE FROM MAILING LIST

    THANKS

    IVAN TAMEZ

    tamezi_2000@yahoo.com

     



    Do You Yahoo!?
    Yahoo! Auctions - Buy the things you want at great prices. --0-429287096-980460150=:4461-- From kalle@gnupung.net Thu Jan 25 22:09:55 2001 From: kalle@gnupung.net (Kalle Svensson) Date: Thu, 25 Jan 2001 23:09:55 +0100 Subject: [Tutor] Python2.0 question In-Reply-To: <01012516122606.01083@scoot.zenplex.com>; from scott@zenplex.com on Thu, Jan 25, 2001 at 04:12:26PM -0500 References: <01012516122606.01083@scoot.zenplex.com> Message-ID: <20010125230955.A26393@apone.network.loc> --SLDf9lqlvOQaIe6s Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable Sez Scott Comboni: > I just decided to check out Python 2.0 and all seems well but for one thi= ng. =20 > When I execute the interpeter I cannot use my arrow keys to repeat a comm= and.=20 > Is there something simple I missed. I really like this command history= =20 > feature. Does anyone know how to turn it on? > When I do hit the the arrow keys I just get garbage on the screen: >=20 > Python 2.0 (#1, Jan 8 2001, 15:29:39) > [GCC 2.95.3 19991030 (prerelease)] on linux2 > Type "copyright", "credits" or "license" for more information. > >>> ^[[D^[[C^[[A^[[B=20 >=20 You are missing the readline module. How to get it back depends on the way you installed python. If you compiled from source, edit Modules/Setup and uncomment the line readline readline.c -lreadline (or something like that). You will need readline headers and libraries installed. Your distribution should have a readline-devel (or something) package. If you installed from rpm, you'll need to find a better rpm or compile the readline module yourself and copy it to /usr/lib/python2.0/lib-dynload. HTH, Kalle --=20 Email: kalle@gnupung.net | You can tune a filesystem, but you Web: http://www.gnupung.net/ | can't tune a fish. -- man tunefs(8) PGP fingerprint: 0C56 B171 8159 327F 1824 F5DE 74D7 80D7 BF3B B1DD --SLDf9lqlvOQaIe6s Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.4 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE6cKQzdNeA1787sd0RAvhmAJ478APllvLPTYORhnYUZqK1N79z/ACfSehG uLJDi6PYIliGr3uN9Z3NTkY= =lP9Z -----END PGP SIGNATURE----- --SLDf9lqlvOQaIe6s-- From rickp@telocity.com Fri Jan 26 03:01:32 2001 From: rickp@telocity.com (rickp@telocity.com) Date: Thu, 25 Jan 2001 22:01:32 -0500 Subject: [Tutor] INSERT using MySQLdb Message-ID: <20010125220132.F7229@tc.niof.net> What is the syntax for using escape_string()? How do I insert a datetime column? I currently have the datetime as seconds so I can convert it however it needs to be, but I don't know what that is. Do I need to use format_TIMESTAMP? If so, how? The docs I've seen are very confusing. Standard queries are no problem. -- "Censorship, like charity, should begin at home, but unlike charity, it should end there." -- Clare Boothe Luce Rick Pasotto email: rickp@telocity.com From rob@jam.rr.com Fri Jan 26 03:38:00 2001 From: rob@jam.rr.com (R. A.) Date: Thu, 25 Jan 2001 21:38:00 -0600 Subject: [Tutor] string replacement puzzlement Message-ID: <3A70F118.12D5B5E0@jam.rr.com> Okay, I'm stumped, and if anyone can de-stump me a bit, you'll have my gratitude. I'm trying to get the hang of replacing strings within a specified file, which I've managed to do with some success. However, my next move was to start trying to replace multiple items within the same file in one fell swoop. The following example is one of my attempts to do so, and the results were less than impressive. In my sample file, containing a random collection of punctuation marks, some replacement happened, but in each case, the original symbols were left behind, and the "?" replacement just didn't happen. (And I know the code is a kludge, but it looked a bit more elegant about 42 changes ago.) I've also tried other ways, such as telling it to open and close the files for each operation, but to no particular avail. import string inputfile = open('c:\windows\desktop\\inputfile.txt', 'r') outputfile = open('c:\windows\desktop\\outputfile.txt', 'w') outputfile.write(inputfile.read().replace("!", "exclamation point")) inputfile.seek(0) outputfile.write(inputfile.read().replace(".", "period")) inputfile.seek(0) outputfile.write(inputfile.read().replace("?", "question mark")) inputfile.close() outputfile.close() I don't know of a way to use replace() with multiple replacements as arguments, but it's what I had in mind before I started adding all this other foolishness. Rob -- Visit the Useless Python Repository! http://www.lowerstandard.com/python/pythonsource.html From dyoo@hkn.eecs.berkeley.edu Fri Jan 26 06:33:15 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 25 Jan 2001 22:33:15 -0800 (PST) Subject: [Tutor] string replacement puzzlement In-Reply-To: <3A70F118.12D5B5E0@jam.rr.com> Message-ID: On Thu, 25 Jan 2001, R. A. wrote: > I'm trying to get the hang of replacing strings within a specified file, > which I've managed to do with some success. However, my next move was > to start trying to replace multiple items within the same file in one > fell swoop. The following example is one of my attempts to do so, and > the results were less than impressive. In my sample file, containing a > random collection of punctuation marks, some replacement happened, but > in each case, the original symbols were left behind, and the "?" > replacement just didn't happen. (And I know the code is a kludge, but > it looked a bit more elegant about 42 changes ago.) Let's take a look at the code, and see if we can figure out why the replacement isn't complete: > import string > inputfile = open('c:\windows\desktop\\inputfile.txt', 'r') > outputfile = open('c:\windows\desktop\\outputfile.txt', 'w') > outputfile.write(inputfile.read().replace("!", "exclamation point")) > inputfile.seek(0) > outputfile.write(inputfile.read().replace(".", "period")) > inputfile.seek(0) > outputfile.write(inputfile.read().replace("?", "question mark")) > inputfile.close() > outputfile.close() Hmmm... Ok, let's make a small test file, and see how the program affects it. We'll do a thought experiment. Let's say we have the inputfile.txt: ### !.? ### What we want in our outputfile is the following: ### exclamation markperiodquestion mark ### Now we need to compare what we want with what we get, and once we understand what's going on, coaxing our program to do the "right" thing will be easy. Let's see what happens as we run through the program. Let's take an incremental look at what outputfile contains through sections of your program. > outputfile.write(inputfile.read().replace("!", "exclamation point")) > inputfile.seek(0) Ok, so the output file should contain: ### exclamation mark.? ### so far. Ok, let's continue. > outputfile.write(inputfile.read().replace(".", "period")) > inputfile.seek(0) Ok, now we add the result of that to the outputfile. Now it looks like this: ### exclamation mark.?!period? ### Finally: > outputfile.write(inputfile.read().replace("?", "question mark")) The outputfile should now contain: ### exclamation mark.?!period?!.question mark ### (as long as we haven't overlooked anything). Take a look at why it's doing weird stuff; it shouldn't be too hard to fix things. If you have more questions, please feel free to ask. Good luck! From michaelbaker@operamail.com Fri Jan 26 06:26:13 2001 From: michaelbaker@operamail.com (michaelbaker@operamail.com) Date: Thu, 25 Jan 2001 22:26:13 -0800 Subject: [Tutor] what does %s do? In-Reply-To: <20010125170110.221CDF394@mail.python.org> Message-ID: <4.3.2.7.1.20010125222146.00ba2b60@operamail.com> >hi tutors. I 've been going through some code sent here from arcege (thanks arcege) - it works great, but I wonder what %s does?? the code: >>> a = [ 'one', 'two', 'three' ] >>> dir() ['__builtins__', '__doc__', '__name__', 'a'] >>> for b in a: ... exec '%sbuffer = []' % b #here it is ... >>> dir() ['__builtins__', '__doc__', '__name__', 'a', 'b', 'onebuffer', 'threebuffer', 'twobuffer'] >>> as usual, thanks for the help m baker From pheff@halenet.com.au Fri Jan 26 07:02:03 2001 From: pheff@halenet.com.au (Patrick Heffernan) Date: Fri, 26 Jan 2001 17:02:03 +1000 (EST) Subject: [Tutor] Python 2 In-Reply-To: <5104D4DBC598D211B5FE0000F8FE7EB20751D50C@mbtlipnt02.btlabs.bt.co.uk> Message-ID: Hello Pythoners I have just successfully compiled Python 2. I did have a broken link to my realine library, but that issue has been resolved now. My question is, can I install Python 2 while still reatining Python 1.5 ? And if this is possible, how do I go about this ? Thanks -- ,-./\ Patrick Heffernan / \ Running on SuSE Linux 6.4 \_,-*_/ Warwick Queensland Australia v It's not a bug, it's tradition! From dyoo@hkn.eecs.berkeley.edu Fri Jan 26 06:57:00 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 25 Jan 2001 22:57:00 -0800 (PST) Subject: [Tutor] removal of duplicates from .csv files In-Reply-To: <006501c08708$637257e0$dc00a8c0@Planhouse5> Message-ID: On Thu, 25 Jan 2001, Rob Andrews wrote: > I have been given several comma-delimited (.csv) files, each containing as > many as several thousand lines of entries. Among the tasks I've been > charged with is to remove duplicate entries. The files each contain fields > for Contact Name, Company Name, Phone Number, and Address, among other > fields, which vary from file to file. > > I'm trying to determine a good way to sort for duplicates according to Phone > Number and according to Address. It seems that sorting by Phone Number > would be simpler due to minor differences in the way data entry clerks might > have input the addresses (W, W., and West, for instance), but not all > entries have phone numbers. Hello! sort() takes in an optional "comparison" function that tells Python how to order objects. For example, let's say we have a list of strings: L = ['this', 'is', 'a', 'test'] Let's say that we want to sort this list by last letter. We could write the following comparison function: def lastLetterCmp(x, y): return cmp(x[-1], y[1]) and sort L with it: L.sort(lastLetterCmp) > equivalence check and manually read through the file. The equivalence check > itself seems simple, but I'm not sure how to scan only the target field > (split(), maybe?), and I certainly want to avoid having to manually remove > the duplicates afterward. You'll want your home-grown comparison function to only check for the fields that you're interested it sorting. From dyoo@hkn.eecs.berkeley.edu Fri Jan 26 07:15:17 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 25 Jan 2001 23:15:17 -0800 (PST) Subject: [Tutor] what does %s do? In-Reply-To: <4.3.2.7.1.20010125222146.00ba2b60@operamail.com> Message-ID: On Thu, 25 Jan 2001 michaelbaker@operamail.com wrote: > I 've been going through some code sent here from arcege (thanks arcege) - > it works great, but I wonder what %s does?? Ah! This is string interpolation, and it does have a peculiar syntax. Let's take a look at the line: > ... exec '%sbuffer = []' % b #here it is The part we're interested in is: '%sbuffer = []' % b What this tells Python is that we want to insert 'b' into our string, and we tell where to place it in with the special marker '%s'. %s stands for string substitution, and there are different kinds of markers, or "format specifiers" available. They're explained more in the "Fancier Input Output" section on the Python Tutorial: http://python.org/doc/current/tut/node9.html#SECTION009100000000000000000 although I'm surprised that it's not more prominently displayed. Hope this helps! From toodles@yifan.net Fri Jan 26 08:15:38 2001 From: toodles@yifan.net (Andrew Wilkins) Date: Fri, 26 Jan 2001 16:15:38 +0800 Subject: [Tutor] what does %s do? In-Reply-To: <4.3.2.7.1.20010125222146.00ba2b60@operamail.com> Message-ID: Hi Michael, Okey dokey... with string manipulation comes the use of %. This prefixes other letters, such as in %s (which by the way is short for string). It replaces the %s in the string with whatever follows the % following the string. So with a string '%sbuffer' % ('one'), the resulting string will be 'onebuffer'. So it goes through a, which I assume is a list of strings: ['one','two','three']. It goes through and executes the string 'onebuffer = []', 'twobuffer = []', 'threebuffer = []'. I can't give you information on all the string substitution prefixes, sorry, I'm not at one with my Python documentation. Hope you can understand my odd way of thinking... Andrew Wilkins > -----Original Message----- > From: tutor-admin@python.org > [mailto:tutor-admin@python.org]On Behalf Of > michaelbaker@operamail.com > Sent: Friday, 26 January 2001 2:26 > To: tutor@python.org > Subject: [Tutor] what does %s do? > > > > >hi tutors. > > > I 've been going through some code sent here from arcege > (thanks arcege) - > it works great, but I wonder what %s does?? > the code: > > >>> a = [ 'one', 'two', 'three' ] > >>> dir() > ['__builtins__', '__doc__', '__name__', 'a'] > >>> for b in a: > ... exec '%sbuffer = []' % b #here it is > ... > >>> dir() > ['__builtins__', '__doc__', '__name__', 'a', 'b', 'onebuffer', > 'threebuffer', 'twobuffer'] > >>> > > as usual, thanks for the help > m baker > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From arcege@shore.net Fri Jan 26 16:16:22 2001 From: arcege@shore.net (Michael P. Reilly) Date: Fri, 26 Jan 2001 11:16:22 -0500 (EST) Subject: [Tutor] Python 2 In-Reply-To: from "Patrick Heffernan" at Jan 26, 2001 05:02:03 PM Message-ID: <200101261616.LAA00702@northshore.shore.net> > > Hello Pythoners > > I have just successfully compiled Python 2. I did have a broken link to my > realine library, but that issue has been resolved now. My question is, can > I install Python 2 while still reatining Python 1.5 ? And if this is > possible, how do I go about this ? It is certainly possible, you installed with "make altinstall" instead of the usual "make install". This will keep the program "python" as Python 1.5.x and create a new program called "python2.0". If you read a few paragraphs down from the top of the Makefile, it is explained for you. It is good to read this first before you proceed. -Arcege -- ------------------------------------------------------------------------ | Michael P. Reilly, Release Manager | Email: arcege@shore.net | | Salem, Mass. USA 01970 | | ------------------------------------------------------------------------ From slyskawa@yahoo.com Fri Jan 26 16:57:39 2001 From: slyskawa@yahoo.com (Steve) Date: Fri, 26 Jan 2001 11:57:39 -0500 Subject: [Tutor] Re: removal of duplicates from .csv files References: <006501c08708$637257e0$dc00a8c0@Planhouse5> Message-ID: <004e01c087b9$1b1a93c0$0201a8c0@sjlhome> > I have been given several comma-delimited (.csv) files, each containing as > many as several thousand lines of entries. Among the tasks I've been > charged with is to remove duplicate entries. The files each contain fields > for Contact Name, Company Name, Phone Number, and Address, among other > fields, which vary from file to file. > One approach you may want to consider is to create a dictionary with the phone number and/or address as a key. Read in a line at a time and split() out the field you are looking for. Format the string to remove as much ambiguity as possible. Then you can use the has_key() method to check if it exists. If it doesn't exist create a dictionary item using the string as a key for future compares and output the line to a "non-duplicate" file. If it does exist, output the line to a "duplicate" file. Using this method, you could first check if the record has a phone number and compare based on that. If it doesn't, you could then fall back to the less accurate address check. Hope this helps, Steve _________________________________________________________ Do You Yahoo!? Get your free @yahoo.com address at http://mail.yahoo.com From gm.bb@worldnet.att.net Fri Jan 26 17:51:01 2001 From: gm.bb@worldnet.att.net (Gary Kekich) Date: Fri, 26 Jan 2001 11:51:01 -0600 Subject: [Tutor] where to start? Message-ID: <000801c087c0$8cab96e0$3269fea9@spare> This is a multi-part message in MIME format. ------=_NextPart_000_0005_01C0878E.411561C0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable I'm interested in programming but I'm entirely new and would like to = know the best way to start. ------=_NextPart_000_0005_01C0878E.411561C0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
    I'm interested in programming but I'm = entirely new=20 and would like to know the best way to start.
    ------=_NextPart_000_0005_01C0878E.411561C0-- From alan.gauld@bt.com Fri Jan 26 17:41:47 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Fri, 26 Jan 2001 17:41:47 -0000 Subject: [Tutor] Re: removal of duplicates from .csv files Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D53A@mbtlipnt02.btlabs.bt.co.uk> > > I have been given several comma-delimited (.csv) files, > > charged with is to remove duplicate entries. > One approach you may want to consider is to create a > dictionary with the phone number and/or address as a key. That was the approach I was going to suggest provided you have enough memory... One question you must answer is which duplicate you want to emilinate. Assuming only the 2 key fields are duplicates which of the other data is the riught one to keep? If its always the first one then thats easier using sort and a custom compare function, if its always the last one thats easier with a dictionary... Alan G. From randrews@planhouse.com Fri Jan 26 19:44:28 2001 From: randrews@planhouse.com (Rob Andrews) Date: Fri, 26 Jan 2001 13:44:28 -0600 Subject: [Tutor] where to start? (having email problems, so forgive if duplicate) References: <000801c087c0$8cab96e0$3269fea9@spare> Message-ID: <003d01c087d0$657b4a60$dc00a8c0@Planhouse5> (having email problems, so forgive if duplicate) Hopefully we can help. Python is a great beginner's programming language, with several nice tutorials available. No matter what your favorite operating system is, Python almost certainly runs on it. The first thing to do is to download Python and check out the tutorial that comes with it. A little more advice may be found at the following page: http://www.lowerstandard.com/python/gettingstarted.html HTH, Rob ----- Original Message ----- From: Gary Kekich To: tutor@python.org Sent: Friday, January 26, 2001 11:51 AM Subject: [Tutor] where to start? I'm interested in programming but I'm entirely new and would like to know the best way to start. From bsass@freenet.edmonton.ab.ca Fri Jan 26 20:55:41 2001 From: bsass@freenet.edmonton.ab.ca (Bruce Sass) Date: Fri, 26 Jan 2001 13:55:41 -0700 (MST) Subject: [Tutor] where to start? In-Reply-To: <000801c087c0$8cab96e0$3269fea9@spare> Message-ID: On Fri, 26 Jan 2001, Gary Kekich wrote: > I'm interested in programming but I'm entirely new and would like to know the best way to start. Just do it, really... there is no substitute for actually firing up an editor/interpreter, writing some code, then figuring out why it doesn't do what you expected it to. Start hacking other people's code first, gradually move from simple modifications of existing features to adding new features... in no time you will be making a mess of code that is 100% your own. ;) Programming is a matter of reducing a problem to its core components, defining the relationships between them, then using that information to manipulate the pieces in a manner that solves the problem. That last line is often referred to as "coding", and it is usually pretty simple if you did a good job of the tasks in the first two lines. What makes coding simple is that there are only a few concepts to learn[1], what makes it appear difficult is that there are a lot of ways to apply those concepts and each problem (class) will best be handled by a particular "way"... and so we have different programming languages. I have to say it is best to start by doing all of these at the same time (because none is more important than the others): - Learn about logic, not just AND, OR, NOT, XOR, but also about sentential, predicate and modal logic. Sentential logic is what you generally write lines of code with, predicate logic is often the basis of the structure of a solution, modal logic will help get your head around the whole OOP thing and `step back' from a problem. - Check out "the way" of several languages; look at the patterns in command structure in and between languages, form reasonable opinions about why the basics have been implemented in the way they have been, think about what makes a particular language suitable for a given task. - Play with some languages. E.g., see how many different error messages you can generate. It sounds backwards, but if you understand how to make an error at will, you should also know how to avoid it. In general, once you get to serious problem solving... Don't write any code unless you have no other choice, procrastinate as long as possible with the stuff you think you have no choice about... saves on bloat, `re-inventing the wheel', and helps see the core components of a problem. HTH later, Bruce [1] The basic concepts of programming are: assignment, retrieval, testing, and looping, all using integers -- everything else is a combination or special case of these four things. From clickron@webtv.net Fri Jan 26 21:43:36 2001 From: clickron@webtv.net (clickron@webtv.net) Date: Fri, 26 Jan 2001 16:43:36 -0500 (EST) Subject: [Tutor] beep Message-ID: <2108-3A71EF88-3174@storefull-161.iap.bryant.webtv.net> I have windows 98 and when I try to use , inport winsound winsound.Beep(300,60) or any other frequencies and durations, all I can get is the windows ding. I'm brand spankin' new at this and was wondering if there was any way to change the settings on windows or another way to get sound of different frequencies and duration. Ron From randrews@planhouse.com Fri Jan 26 22:43:09 2001 From: randrews@planhouse.com (Rob Andrews) Date: Fri, 26 Jan 2001 16:43:09 -0600 Subject: [Tutor] Re: removal of duplicates from .csv files References: <5104D4DBC598D211B5FE0000F8FE7EB20751D53A@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <006c01c087e9$5f88bb60$dc00a8c0@Planhouse5> Belated thanks to everyone who's lent helpful thoughts on this question and on my question about working with replace(). I'm not quite there with either of them, and together they constitute the biggest Python challenge I've undertaken so far, so I look forward to hacking on this quite a bit over the next few days. My understanding is that the .csv project is a big enough challenge that if I make any real progress with it, it'll make a nice little Open Source contribution. So if I get very far with it, that's my plan. If nothing else, I find myself so engrossed that I'm learning more Python, which makes me happy 'nuff. Rob ----- Original Message ----- From: To: ; Sent: Friday, January 26, 2001 11:41 AM Subject: RE: [Tutor] Re: removal of duplicates from .csv files > > > I have been given several comma-delimited (.csv) files, > > > charged with is to remove duplicate entries. > > > One approach you may want to consider is to create a > > dictionary with the phone number and/or address as a key. > > That was the approach I was going to suggest provided > you have enough memory... > > One question you must answer is which duplicate you want to emilinate. > Assuming only the 2 key fields are duplicates > which of the other data is the riught one to keep? > > If its always the first one then thats easier using > sort and a custom compare function, if its always the > last one thats easier with a dictionary... > > Alan G. > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From britt_green@hotmail.com Sat Jan 27 01:30:49 2001 From: britt_green@hotmail.com (Britt Green) Date: Fri, 26 Jan 2001 17:30:49 -0800 Subject: [Tutor] Error Message Message-ID: Hello, I'm new to programming and Python, and I'm getting an error message that I can't quite seem to work around. This is my code: import msvcrt, sys print""" Type a key to see its ASCII value. Hit the space bar to end. """ while 1: #1 is true, so loop forever key = msvcrt.getch() if key != ' ': # handle special keys; real code is second if (key == '\000') or (key == '\xe0'): key = msvcrt.getch() doKeyEvent(key) else: doQuitEvent(key) def doKeyEvent(key): print ord(key) def doQuitEvent(key): sys.exit() After I save this and run it, Python replies with this: Type a key to see its ASCII value. Hit the space bar to end. Traceback (innermost last): File "C:/Program Files/Python20/Code/eventloop.py", line 14, in ? doKeyEvent(key) NameError: There is no variable named 'doKeyEvent' I'm stuck since doKeyEvent is a function, not a variable. Why doesn't Python recognize it as such? Thanks, Britt _________________________________________________________________ Get your FREE download of MSN Explorer at http://explorer.msn.com From dyoo@hkn.eecs.berkeley.edu Sat Jan 27 01:40:38 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 26 Jan 2001 17:40:38 -0800 (PST) Subject: [Tutor] Re: thank%s In-Reply-To: <4.3.2.7.1.20010126120051.00b92430@operamail.com> Message-ID: On Fri, 26 Jan 2001 michaelbaker@operamail.com wrote: > thanks once again (this is not the first time you have helped me out). I > almost looked at the Fancier Input/Output before sending to the list, > although now that I have I'm not so sure I wouldn't have sent to the list > anyway. I don't qutie follow this: > > >>> import string > >>> for x in range(1,11): > ... print '%2d %3d %4d' % (x, x*x, x*x*x) > ... > 1 1 1 > 2 4 8 > 3 9 27 > 4 16 64 > 5 25 125 > 6 36 216 > 7 49 343 > 8 64 512 > 9 81 729 > 10 100 1000 > > %2d, %3d, %4d ??????????? Actually, you'd be surprised; it's a documented BUG that string interpolation isn't explained! http://sourceforge.net/bugs/?func=detailbug&bug_id=121207&group_id=5470 The Python implementers forgot to explain how it works, so don't worry if you can't find information on this stuff. What '%2d' means is that when we interpolate, we should make sure that it fills up at least 2 spaces. I think that this term is called "padding to 2 spaces", and it's useful when we want more refined control over the format. Let's play around with the interpreter: ### >>> print '** %d **' % 42 ** 42 ** >>> print '** %1d **' % 42 ** 42 ** >>> print '** %2d **' % 42 ** 42 ** >>> print '** %3d **' % 42 ** 42 ** >>> print '** %4d **' % 42 ** 42 ** >>> print '** %5d **' % 42 ** 42 ** ### So it gives us a little more control over the format of whatever we print out. Often, we'll see this stuff when we need things to align just right. Although this is pretty powerful already, we can get more fine-tuned control when we try printing floating point numbers. Here's an example: ### >>> print '** %f **' % pi ** 3.141593 ** >>> print '** %3f **' % pi ** 3.141593 ** >>> print '** %3.0f **' % pi ** 3 ** >>> print '** %3.1f **' % pi ** 3.1 ** >>> print '** %3.2f **' % pi ** 3.14 ** >>> print '** %.40f **' % pi ** 3.1415926535897931159979634685441851615906 ** # wow... ### When we say: print '%3.2f' % pi we're telling Python: "Make it fit at least three spaces, and leave room for 2 decimal places." Play around with it a bit more. I was surprised that 'pi' was defined to so many decimals! *grin* Hope this helps! From toodles@yifan.net Sat Jan 27 01:44:27 2001 From: toodles@yifan.net (Andrew Wilkins) Date: Sat, 27 Jan 2001 09:44:27 +0800 Subject: [Tutor] Error Message In-Reply-To: Message-ID: Hi Britt, In python there is no declaration of functions, you must have already defined them before they are referenced. All you need to do is throw those definitions to the top of your code, and you're home free. Andrew Wilkins > -----Original Message----- > From: tutor-admin@python.org > [mailto:tutor-admin@python.org]On Behalf Of > Britt Green > Sent: Saturday, 27 January 2001 9:31 > To: tutor@python.org > Subject: [Tutor] Error Message > > > Hello, > > I'm new to programming and Python, and I'm getting an error > message that I > can't quite seem to work around. This is my code: > > import msvcrt, sys > > print""" > Type a key to see its ASCII value. > Hit the space bar to end. > """ > > while 1: #1 is true, so loop forever > key = msvcrt.getch() > if key != ' ': > # handle special keys; real code is second > if (key == '\000') or (key == '\xe0'): > key = msvcrt.getch() > doKeyEvent(key) > else: > doQuitEvent(key) > > > def doKeyEvent(key): > print ord(key) > > def doQuitEvent(key): > sys.exit() > > After I save this and run it, Python replies with this: > > Type a key to see its ASCII value. > Hit the space bar to end. > > Traceback (innermost last): > File "C:/Program Files/Python20/Code/eventloop.py", line 14, in ? > doKeyEvent(key) > NameError: There is no variable named 'doKeyEvent' > > I'm stuck since doKeyEvent is a function, not a variable. Why > doesn't Python > recognize it as such? > > Thanks, > > Britt > _________________________________________________________________ > Get your FREE download of MSN Explorer at http://explorer.msn.com > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > From dyoo@hkn.eecs.berkeley.edu Sat Jan 27 01:49:45 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Fri, 26 Jan 2001 17:49:45 -0800 (PST) Subject: [Tutor] where to start? In-Reply-To: Message-ID: On Fri, 26 Jan 2001, Bruce Sass wrote: > > I'm interested in programming but I'm entirely new and would like to > know the best way to start. > Programming is a matter of reducing a problem to its core components, > defining the relationships between them, then using that information > to manipulate the pieces in a manner that solves the problem. And it's also a way of playing around with processes. For example, we can try to simulate something interesting like: what happens during the "telephone" game? Can we write a program that will "simulate" the sort of mistakes that could happen when rumors spread? Programming is a playpen that lets us test out how things "might" work. It doesn't always have to be useful. > In general, once you get to serious problem solving... > Don't write any code unless you have no other choice, procrastinate I think it's perfectly ok to go on first instinct on a program, and gradually get things to look nicer. At least, when I'm learning something, I want to try writing small procedures, and gradually get a better understanding of a problem as I play with it. I guess you could call it "bottom-up" programming. On the other hand, it's good to plan for the future by try writing programs that that are easy to fix. > saves on bloat, `re-inventing the wheel', and helps see the core At least when learning a language, though, reinventing the wheel is important. It exercises our creative juices, and it's a good experience to try figuring alternative ways of doing things. Not that working with what's already written isn't a good thing --- it's wonderful to be able to reuse code! But it's also nice to rework solutions to old problems, and gain a better understanding of what's going inside too. I'm sorry; I'm just looking at programming from a hobbyist's perspective. But why program Python if it's not going to be fun? From martok@mattsmail.com Sat Jan 27 02:12:53 2001 From: martok@mattsmail.com (Matthias Hager) Date: Fri, 26 Jan 2001 18:12:53 -0800 Subject: [Tutor] Error Message Message-ID: <200101261812.AA504496384@mail.mattsmail.com> I had this problem when I was first starting with Python. (And I'm still new to it). You must define your functions first. Take them up to the top of your program, then it should work. I learned Perl first, where you don't have to, so I wasn't used to it. It still bugs me. Good luck. Matthias -- Programming isn't cool, it's awesome. %%%################?????????###################^^^ martok@mattsmail.com http://mymymatthias.tripod.com/ %%%################????????####################^^^ -- Like my email address? Get your own for FREE at http://firstname.com Get you@JohnsMail.com or you@AlexsMail.com or pick from 500 more! From pheff@halenet.com.au Sat Jan 27 02:07:18 2001 From: pheff@halenet.com.au (Patrick Heffernan) Date: Sat, 27 Jan 2001 12:07:18 +1000 (EST) Subject: [Tutor] Python 2 In-Reply-To: <200101261616.LAA00702@northshore.shore.net> Message-ID: On Fri, 26 Jan 2001, Michael P. Reilly wrote: > > It is certainly possible, you installed with "make altinstall" instead > of the usual "make install". This will keep the program "python" as > Python 1.5.x and create a new program called "python2.0". Thankyou. > If you read a few paragraphs down from the top of the Makefile, it is > explained for you. It is good to read this first before you proceed. > I never thought of looking in there :-) Again, thankyou for the help. -- .~. Patrick Heffernan /V\ Using SuSE Linux 6.4 -*- Kernel 2.2.14 // \\ /(_._)\ Warwick -*- Queensland -*- Australia ^^ ^^ It is easier to fix Unix than to live with NT. From tuckerg@acm.org Sat Jan 27 03:44:30 2001 From: tuckerg@acm.org (Gregory Tucker) Date: Sat, 27 Jan 2001 12:44:30 +0900 Subject: [Tutor] where to start? In-Reply-To: <000801c087c0$8cab96e0$3269fea9@spare> Message-ID: This is a multi-part message in MIME format. ------=_NextPart_000_0006_01C0885E.E447FBC0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: 7bit Gary, The following advice applies to life in general. I have always found that, in my own case, the most important thing is to have something that you want to accomplish, something burning deeply enough to inspire you to do it. Although I am a Comp Sci graduate, in the last several years I have not done much programming, despite several attempts. My problem always was that I didn't actually have anything I wanted to build; or everything was too large for me to handle on my own. Lately I have less a shortage of ideas. A couple I have implemented are: - A script that emails a message to a list of friends. Of course any standard mail package can do this, but Python allows me to give each friend a "nickname" that goes into the message. So although the message is canned, it looks more personalized to the recipients. - A script that deletes web cookies not on my approved list. In IE 5 each cookie is saved as a text file; the script searches each .txt filename for a keyword and deletes those not found. This method is cookie blocking is not effective within a single session, but less intrusive than other measures. Some ideas I am thinking about include: - Helping to manage my photo library. Probably I will use a commercial package (i.e. Adobe PhotoDeluxe), but Python may give me enough functionality cheaply enough to be interesting. - A simple "egg timer" utilitiy that "rings" when the specified time is up. Helps me to discipline my tasks. - A few web-based applications comes to mind, but they would be a little complicated for CGI forms (too much session orientation). Zope may give me what I want, but at a much steeper learning curve than the stuff I have built already. So my efforts to learn Python have been more successful lately because I view Python as simply a tool to accomplish what I want, and not as some knowledge in my arsenal. Given the pressures of society, do we really have time for anything else? So you might start by thinking "what do I really want to do" and then see how you can do it in Python; you can also look for another tool, if Python is not best suited. Several people have discussed modifying existing stuff. I will look into this pretty soon, though I haven't done much at this point. Regards, Greg --- Gregory Tucker Tokyo, Japan mailto:tuckerg@acm.org These opinions are my own. -----Original Message----- From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of Gary Kekich Sent: Saturday, January 27, 2001 2:51 AM To: tutor@python.org Subject: [Tutor] where to start? I'm interested in programming but I'm entirely new and would like to know the best way to start. ------=_NextPart_000_0006_01C0885E.E447FBC0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
    Gary,
     
    The following advice applies to life in = general. I have=20 always found that, in my own case, the most important thing is to have = something=20 that you want to accomplish, something burning deeply enough to inspire = you to=20 do it.
     
    Although I am a Comp Sci graduate, in the = last several=20 years I have not done much programming, despite several attempts. My = problem=20 always was that I didn't actually have anything I wanted to build; or = everything=20 was too large for me to handle on my own.
     
    Lately I have less a shortage of ideas. A = couple I have=20 implemented are:
     
    - A script that emails a message to a list of = friends.=20 Of course any standard mail package can do this, but Python allows me to = give=20 each friend a "nickname" that goes into the message. So although the = message is=20 canned, it looks more personalized to the = recipients.
     
    - A script that deletes web cookies not on my = approved=20 list. In IE 5 each cookie is saved as a text file; the script searches = each .txt=20 filename for a keyword and deletes those not found. This method is = cookie=20 blocking is not effective within a single session, but less intrusive = than other=20 measures.
     
    Some ideas I am thinking about=20 include:
     
    - Helping to manage my photo library. = Probably I will=20 use a commercial package (i.e. Adobe PhotoDeluxe), but Python may give = me enough=20 functionality cheaply enough to be interesting.
     
    - A simple "egg timer" utilitiy that "rings" = when the=20 specified time is up. Helps me to discipline my = tasks.
     
    - A few web-based applications comes to mind, = but they=20 would be a little complicated for CGI forms (too much session=20 orientation). Zope may give me what I want, but at a much steeper = learning=20 curve than the stuff I have built already.
     
    So my efforts to learn Python have been more = successful=20 lately because I view Python as simply a tool to accomplish what I want, = and not=20 as some knowledge in my arsenal. Given the pressures of society, do we = really=20 have time for anything else? So you might start by thinking "what do I = really=20 want to do" and then see how you can do it in Python; you can also look = for=20 another tool, if Python is not best suited.
     
    Several people have discussed modifying = existing stuff.=20 I will look into this pretty soon, though I haven't done much at this=20 point.
     
    Regards,
    Greg
     


    ---
      Gregory Tucker
      Tokyo,=20 Japan
      mailto:tuckerg@acm.org

      = These=20 opinions are my own.

    -----Original Message-----
    From: = tutor-admin@python.org=20 [mailto:tutor-admin@python.org]On Behalf Of Gary = Kekich
    Sent:=20 Saturday, January 27, 2001 2:51 AM
    To:=20 tutor@python.org
    Subject: [Tutor] where to=20 start?

    I'm interested in programming but I'm = entirely=20 new and would like to know the best way to=20 start.
    ------=_NextPart_000_0006_01C0885E.E447FBC0-- From sheila@thinkspot.net Sat Jan 27 04:51:25 2001 From: sheila@thinkspot.net (Sheila King) Date: Fri, 26 Jan 2001 20:51:25 -0800 Subject: [Tutor] Parsing an mbox mail file Message-ID: <72CE883676@kserver.org> OK, I'm using the mailbox module (see docs here: http://www.python.org/doc/current/lib/mailbox-objects.html ) to handle a file that has several messages saved in mbox format. The following script runs: -------------------------------------------------- import mailbox infile = open("spam2.txt", "r") messages = mailbox.UnixMailbox(infile) while (1): currentmssg = messages.next() if (currentmssg ==None): break print currentmssg -------------------------------------------------- where "spam2.txt" is my mail message file. However, it only prints out the message headers, which is how I understand rfc822 module to work. I've already written a few different scripts that use the rfc822 module. Basically, the rfc822 module seems to handle only the headers, and not the message body. In other scripts, I've retrieved the message body in this manner: -------------------------------------------------- #! /usr/bin/python import rfc822, sys raw_message=open("message.txt", "r") inheaders=rfc822.Message(raw_message) body=raw_message.read() print inheaders print print body -------------------------------------------------- However, there was only one message in the file. Basically, getting the message header reads until the first blank line, and then the file pointer is positioned at the beginning of the body of the message. If I use the mailbox module, and use mailboxInstance.next(), it will skip right over the message body to the next message's header. The whole reason I'm wanting to use the mailbox module, is so that I can easily get to the next message in the file, and get it's headers. So, I definitely want to use the "next()" command. How can I read the message body in between calls to next? -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From tim.one@home.com Sat Jan 27 08:31:57 2001 From: tim.one@home.com (Tim Peters) Date: Sat, 27 Jan 2001 03:31:57 -0500 Subject: [Tutor] beep In-Reply-To: <2108-3A71EF88-3174@storefull-161.iap.bryant.webtv.net> Message-ID: [clickron@webtv.net] > I have windows 98 and when I try to use , > inport winsound > winsound.Beep(300,60) > or any other frequencies and durations, all I can get is the windows > ding. Yes, I'm afraid that's right. This was discussed on comp.lang.python just this week, where it surprised the heck out of winsound's author. It turns out the Microsoft function Python calls ignores the frequency and duration arguments under Windows 95 and 98 (I *guess* also ME), and this is documented in Microsoft's docs. You have to be running under Windows NT or 2000 for .Beep() to work as advertised (which the Python docs for version 2.1 will explain). > I'm brand spankin' new at this and was wondering if there was any way to > change the settings on windows or another way to get sound of different > frequencies and duration. Well, the sound .Beep() plays under Win9x can be set via changing Start -> Settings -> Control Panel -> Sounds -> Windows -> Default sound but that's all the control you can get. Microsoft doesn't appear to offer any function under Win9x that does the same thing as .Beep() does under Win NT/2K. So it would require synthesizing wave data yourself, and using winsound.PlaySound() to play it. Unfortunately, that's A Project; wave data is complicated: http://ccrma-www.stanford.edu/CCRMA/Courses/422/projects/WaveFormat/ I don't know of any simpler alternative at the moment. Sorry! From dyoo@hkn.eecs.berkeley.edu Sat Jan 27 09:36:25 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 27 Jan 2001 01:36:25 -0800 (PST) Subject: [Tutor] Parsing an mbox mail file In-Reply-To: <72CE883676@kserver.org> Message-ID: On Fri, 26 Jan 2001, Sheila King wrote: > import mailbox > > infile = open("spam2.txt", "r") > messages = mailbox.UnixMailbox(infile) > > while (1): > currentmssg = messages.next() > if (currentmssg ==None): > break > print currentmssg > -------------------------------------------------- > > where "spam2.txt" is my mail message file. However, it only prints out > the message headers, which is how I understand rfc822 module to work. > I've already written a few different scripts that use the rfc822 > module. Basically, the rfc822 module seems to handle only the headers, > and not the message body. Hello! It turns out that messages.next() will return a Message instance: http://python.org/doc/current/lib/mailbox-objects.html If we look at what Messages can do, we find near the bottom of: http://python.org/doc/current/lib/message-objects.html that these Message instances should contain an "fp" file pointer that lets us look at the message body. So we could adjust your code like this: ### currentmssg = messages.next() if (currentmssg ==None): break print currentmssg.fp.read() # let's look at the msg contents ### I haven't tested this code yet, so you might need to fiddle with it to make it work. rewindbody()'ing the Message might also be useful. I hope that this is what you're looking for. Good luck! From facelle@tiscalinet.it Sat Jan 27 13:20:39 2001 From: facelle@tiscalinet.it (Fabrizio) Date: Sat, 27 Jan 2001 14:20:39 +0100 Subject: [Tutor] mxODBC help on Win98 Message-ID: <001601c08863$f22f4d60$85250b3e@oemcomputer> Hi, Newbie, Python2.0, Windows98. I just would like to try to access to some MS Access or MS Excel data to play around with Python. I am trying to install mxODBC on my system, but this is what I get if I run the included "test.py" script (I have installed Date Time and it seems to work fine): ======================================================================== mxODBC Test Suite ------------------------------------------------------------------------ Subpackage Name [Windows]: DriverConnect arguments [DSN=test;UID=test;PWD=test]: Clear AUTOCOMMIT ? (1/0) [1] Run tests continuously to check for leaks ? (y/n) [n] Show driver type information ? (y/n) [n] Output file [stdout]: Test suite: Connecting to the database. Traceback (innermost last): File "C:\Python20\Lib\ODBC\Misc\test.py", line 1054, in ? rc = main() File "C:\Python20\Lib\ODBC\Misc\test.py", line 1004, in main connection = apply(connectapi,connectargs) OperationalError: ('IM002', 0, '[Microsoft][ODBC Driver Manager] Nome origine dati non trovato e driver predefinito non specificato.', 4316) The last line, in Italian, sounds like : "Couldn't find data origin name and predefined driver not specified". What is wrong ? Thanks in advance. Fabrizio C. From mbc2@netdoor.com Sat Jan 27 14:37:05 2001 From: mbc2@netdoor.com (mbc2@netdoor.com) Date: Sat, 27 Jan 2001 08:37:05 -0600 (CST) Subject: [Tutor] where to start? In-Reply-To: Message-ID: On Sat, 27 Jan 2001, Gregory Tucker wrote: > - A script that deletes web cookies not on my approved list. In IE 5 each > cookie is saved as a text file; the script searches each .txt filename for a > keyword and deletes those not found. This method is cookie blocking is not > effective within a single session, but less intrusive than other measures. > Would you mind posting this one to the list. I've been thinking about doing something like this but I just haven't gotten around to it. I use Internet Junkbuster which prevents all unapproved cookies from ever being placed on my computer, but there are still a few that I'd like to get rid of at the end of each day for security purposes. One idea I've had is to take the cookies I want to keep and encrypt them somehow at the end of the day, and at the same time delete them from the cookies folder on Windows, thus preventing anyone using my computer to access password protected web sites that I have an account with. Then I could have another program that asked for a password before restoring the cookies. Just a few thoughts, Brad From sheila@thinkspot.net Sat Jan 27 18:30:15 2001 From: sheila@thinkspot.net (Sheila King) Date: Sat, 27 Jan 2001 10:30:15 -0800 Subject: [Tutor] Parsing an mbox mail file In-Reply-To: References: <72CE883676@kserver.org> Message-ID: <2DD6A0B1132@kserver.org> On Sat, 27 Jan 2001 01:36:25 -0800 (PST), Danny Yoo wrote about Re: [Tutor] Parsing an mbox mail file: :On Fri, 26 Jan 2001, Sheila King wrote: : :> import mailbox :> :> infile = open("spam2.txt", "r") :> messages = mailbox.UnixMailbox(infile) :> :> while (1): :> currentmssg = messages.next() :> if (currentmssg ==None): :> break :> print currentmssg :> -------------------------------------------------- :If we look at what Messages can do, we find near the bottom of: : : http://python.org/doc/current/lib/message-objects.html : :that these Message instances should contain an "fp" file pointer that lets :us look at the message body. Yes. : So we could adjust your code like this: : :### : currentmssg = messages.next() : if (currentmssg ==None): : break : print currentmssg.fp.read() # let's look at the msg contents :### Interesting. I tried this out, and it sort of prints the bodies without the headers. But not exactly. Every once in a while, it prints one to three lines of the header. I am going to play around with this a bit more, later. But for now, I've "solved" my problem, by not saving the messages in a strict mbox format. I'm preceding each message with a message separator line. Since I know what the message separator line is, I can read up to that line, and then discard it with no ill effects. My message separator is '========\n' Since I'm not saving in strict mbox format, I can't use the UnixMailbox component from the mailbox module. So, I'm back to the rfc822. Here is a simplified version of my current code: --------------------------------------------------------- import rfc822 def readToMessageSeparator(infile): lines =[] while(1): newline = infile.readline() if not newline: return lines if (newline != '========\n'): lines +=[newline] else: return lines ########################### ### Main Program Begins ### ########################### infile = open("spam4.txt", "r") discard = readToMessageSeparator(infile) ## retrieve each message while (1): header = rfc822.Message(infile) if not header: break headerString = ''.join(header.headers) body = ''.join(readToMessageSeparator(infile)) currentmessage = headerString + '\n' + body print currentmessage --------------------------------------------------------- -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ From tuckerg@acm.org Sat Jan 27 23:34:24 2001 From: tuckerg@acm.org (Gregory Tucker) Date: Sun, 28 Jan 2001 08:34:24 +0900 Subject: [Tutor] where to start? In-Reply-To: Message-ID: Hi, I am hesitant to post this, only because I know the code isn't very good. Feel free to make constructive criticism. The program requires another file called cookiesok.txt in the same directory that contains a list of keywords (1 on each line) that identify acceptable cookies. The keyword only needs to be a subset of acceptable cookie. On the encryption side, I am not taking care of it in Python. You might want to consider a program that creates encrypted, virtual disks from files that you pre-allocate on your real drives. I use PGP (commercial version), but I know there are others as well (and even one for Pocket PC). Everything stored inside the file / virtual drive are encrypted, and a password is required to mount it. Except for the password, it looks and acts just like a normal disk. Regards, Greg cookiekiller.py ----- import sys, os, string, time f = open("cookiesok.txt", 'r') ok = f.readlines() #ls = os.listdir(sys.argv[1]) while 1: os.chdir("c:/Documents and Settings/tucker/Cookies/") ls = os.listdir('.') for i in ls: flag = 0 for j in ok: sf = string.find(string.lower(i), string.lower(j[:-1])) if sf > -1: flag = 1 break if not flag: os.remove(i) print 'Cookie %s deleted.' % i time.sleep(10.0) --- Gregory Tucker Tokyo, Japan mailto:tuckerg@acm.org These opinions are my own. > -----Original Message----- > From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of > mbc2@netdoor.com > Sent: Saturday, January 27, 2001 11:37 PM > To: tutor@python.org > Subject: RE: [Tutor] where to start? > > > > > On Sat, 27 Jan 2001, Gregory Tucker wrote: > > > - A script that deletes web cookies not on my approved list. In > IE 5 each > > cookie is saved as a text file; the script searches each .txt > filename for a > > keyword and deletes those not found. This method is cookie > blocking is not > > effective within a single session, but less intrusive than > other measures. > > > > Would you mind posting this one to the list. I've been thinking about > doing something like this but I just haven't gotten around to it. I use > Internet Junkbuster which prevents all unapproved cookies from ever being > placed on my computer, but there are still a few that I'd like to get rid > of at the end of each day for security purposes. > > One idea I've had is to take the cookies I want to keep and encrypt them > somehow at the end of the day, and at the same time delete them from the > cookies folder on Windows, thus preventing anyone using my computer to > access password protected web sites that I have an account with. Then I > could have another program that asked for a password before restoring the > cookies. Just a few thoughts, > > Brad > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From dyoo@hkn.eecs.berkeley.edu Sun Jan 28 02:02:53 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 27 Jan 2001 18:02:53 -0800 (PST) Subject: [Tutor] where to start? In-Reply-To: Message-ID: On Sun, 28 Jan 2001, Gregory Tucker wrote: > I am hesitant to post this, only because I know the code isn't very > good. Don't worry about it. Let's take a look at a few lines: > f = open("cookiesok.txt", 'r') > ok = f.readlines() You might want to strip off the newlines within ok, as a preparation step for the searching later on, because that will make: > sf = string.find(string.lower(i), string.lower(j[:-1])) into sf = string.find(string.lower(i), string.lower(j)) which is a little simpler. Otherwise, I think it looks great. From dyoo@hkn.eecs.berkeley.edu Sun Jan 28 02:34:24 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sat, 27 Jan 2001 18:34:24 -0800 (PST) Subject: [Tutor] Parsing an mbox mail file In-Reply-To: <2DD6A0B1132@kserver.org> Message-ID: On Sat, 27 Jan 2001, Sheila King wrote: > : So we could adjust your code like this: > : > :### > : currentmssg = messages.next() > : if (currentmssg ==None): > : break > : print currentmssg.fp.read() # let's look at the msg contents > :### > > Interesting. I tried this out, and it sort of prints the bodies > without the headers. But not exactly. Every once in a while, it prints > one to three lines of the header. That is a bit strange! I tested the code on my own /var/spool/mail, and it skips over the headers for my mail file. You might want to check that your file is strickly in an mbox format --- that's one thing I can think of that would cause such behavior. > I am going to play around with this a bit more, later. But for now, I've > "solved" my problem, by not saving the messages in a strict mbox format. I'm > preceding each message with a message separator line. Since I know what the > message separator line is, I can read up to that line, and then discard it > with no ill effects. This will work. If you have time, maybe you could make a small test "mail" file that duplicates that weird behavior. I'm glad that your program works now! From martok@mattsmail.com Sun Jan 28 04:44:24 2001 From: martok@mattsmail.com (Matthias Hager) Date: Sat, 27 Jan 2001 20:44:24 -0800 Subject: [Tutor] Email python Message-ID: <200101272044.AA726860050@mail.mattsmail.com> I don't have access to internet pn my puter that has my python. And I don't know much about accessing email with Python, but I'm sure it's possible. What I need, is a python script, to go into my hotmail account, in a certain folder, and extract all the email from certain people, and save them to my puter, or an internet location, and delete all of the email from that folder. Could one of you guys help me with this. It would have to be done from your puter, and there's about 1.1 MB of email in there. How long would this take? And also, I need a script to go into my yahoo account, and delete all 7 MB of email from it. Any help on either one is appreciated. Thakns a bunch Matthias -- Programming isn't cool, it's awesome. %%%################?????????###################^^^ martok@mattsmail.com http://mymymatthias.tripod.com/ %%%################????????####################^^^ -- Like my email address? Get your own for FREE at http://firstname.com Get you@JohnsMail.com or you@AlexsMail.com or pick from 500 more! From chastin_am_i@hotmail.com Sun Jan 28 14:39:46 2001 From: chastin_am_i@hotmail.com (chastin cullifer) Date: Sun, 28 Jan 2001 08:39:46 -0600 Subject: [Tutor] (no subject) Message-ID:
    hello all
     
    im new to the python language and i dont know much
     
    but i was wondering if it is possible to make a game with python besides text adventures??


    Get your FREE download of MSN Explorer at http://explorer.msn.com

    From wilson@visi.com Sun Jan 28 14:46:44 2001 From: wilson@visi.com (Timothy Wilson) Date: Sun, 28 Jan 2001 08:46:44 -0600 (CST) Subject: [Tutor] (no subject) In-Reply-To: Message-ID: On Sun, 28 Jan 2001, chastin cullifer wrote: > but i was wondering if it is possible to make a game with python besides > text adventures?? Certainly. Check out PySol at http://wildsau.idv.uni-linz.ac.at/mfx/pysol/ -Tim -- Tim Wilson | Visit Sibley online: | Check out: Henry Sibley HS | http://www.isd197.k12.mn.us/ | http://www.zope.org/ W. St. Paul, MN | | http://slashdot.org/ wilson@visi.com | | http://linux.com/ From tescoil@irtc.net Sun Jan 28 18:17:05 2001 From: tescoil@irtc.net (Tesla Coil) Date: Sun, 28 Jan 2001 12:17:05 -0600 Subject: [Tutor] Games Besides Text Adventures (was: no subject) References: Message-ID: <3A746221.62C827BC@irtc.net> On 28 January 2001, Timothy Wilson replied to Chastin Cullifer: >> but i was wondering if it is possible to make a game >> with python besides text adventures?? > > Certainly. Check out PySol at > http://wildsau.idv.uni-linz.ac.at/mfx/pysol/ Another, Matt Gushee's peg solitaire... http://www.havenrock.com/softlab/pegboard/ ...which is less than 1500 lines of source, GPL, and an implementation of Fox and Geese waiting to happen: http://www.stainess.freeserve.co.uk/board/fgtbl.html From pythoperson@yahoo.com Sun Jan 28 20:15:43 2001 From: pythoperson@yahoo.com (Pythoperson) Date: Sun, 28 Jan 2001 12:15:43 -0800 (PST) Subject: [Tutor] Basic freeze question Message-ID: <20010128201543.47818.qmail@web12406.mail.yahoo.com> Hello all! I am just starting with python and TK and I am enjoying it. I have a nifty little TK program going and I am trying to freeze it. However, I get a screen-full of error messages! Are there any extensive help files or tutorials about freeze? If I cannot make an executable, then python is fairly useless to me, no matter the fun I am having. Any suggestions on where to look for help? Thanks, PythoPerson __________________________________________________ Do You Yahoo!? Yahoo! Auctions - Buy the things you want at great prices. http://auctions.yahoo.com/ From budgester@budgester.com Sun Jan 28 21:17:07 2001 From: budgester@budgester.com (Budgester) Date: Sun, 28 Jan 2001 21:17:07 -0000 Subject: [Tutor] String Replace..... Message-ID: <000801c0896f$ac50de50$0300000a@budgester> Hi people, Okay i'm having a bit of problem, Here's the code, after the file is written out from a Tkinter GUI ## Turn Text into HTML def htmlize(self): viewdiary = open("c:\diary.txt", 'r') print viewdiary print "---------------" L = viewdiary.readlines() print L modified_str = string.replace(L, "\012", "
    " ) print modified_str viewdiary.close and the error I'm getting --------------- ['this is a test\012', 'this is another test\012', 'one more test\012'] Exception in Tkinter callback Traceback (most recent call last): File "c:\python20\lib\lib-tk\Tkinter.py", line 1287, in __call__ return apply(self.func, args) File "C:\python-code\diary-update\diary.py", line 71, in htmlize modified_str = string.replace(L, "\012", "
    " ) File "c:\python20\lib\string.py", line 363, in replace return s.replace(old, new, maxsplit) AttributeError: replace I can get replace to work via the interpreter but as soon as I put it into a .py file i get the above error, i'm sure it's something simple that I'm not seeing, so a couple of more knowledgeable eyes should be able to point me in the right direction. I can post the full code if needed. Seperate note in the error report it says '(most recent call last)' i'm assuming that it is the last command that is failing, is that right? TIA Budgester mailto:budgester@budgester.com http://www.budgester.com From sheila@thinkspot.net Sun Jan 28 21:31:01 2001 From: sheila@thinkspot.net (Sheila King) Date: Sun, 28 Jan 2001 13:31:01 -0800 Subject: [Tutor] String Replace..... In-Reply-To: <000801c0896f$ac50de50$0300000a@budgester> References: <000801c0896f$ac50de50$0300000a@budgester> Message-ID: I'm only a Python newbie, myself, but I've done a fair number of scripts with strings in them, and I've never used '\012' in my code, only '\n'. Maybe, try replacing the "\012" in your code with "\n" ??? Well, I figured it was worth a try? -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ On Sun, 28 Jan 2001 21:17:07 -0000, "Budgester" wrote about [Tutor] String Replace.....: :## Turn Text into HTML : : def htmlize(self): : viewdiary = open("c:\diary.txt", 'r') : print viewdiary : print "---------------" : L = viewdiary.readlines() : print L : modified_str = string.replace(L, "\012", "
    " ) : print modified_str : viewdiary.close : :and the error I'm getting : : :--------------- :['this is a test\012', 'this is another test\012', 'one more test\012'] :Exception in Tkinter callback :Traceback (most recent call last): : File "c:\python20\lib\lib-tk\Tkinter.py", line 1287, in __call__ : return apply(self.func, args) : File "C:\python-code\diary-update\diary.py", line 71, in htmlize : modified_str = string.replace(L, "\012", "
    " ) : File "c:\python20\lib\string.py", line 363, in replace : return s.replace(old, new, maxsplit) :AttributeError: replace From budgester@budgester.com Sun Jan 28 21:36:05 2001 From: budgester@budgester.com (Budgester) Date: Sun, 28 Jan 2001 21:36:05 -0000 Subject: [Tutor] String Replace..... In-Reply-To: Message-ID: <000a01c08972$5210be80$0300000a@budgester> I'm new to Python as well, the reason I was using \012 was because that's what was returned when i did a debugging print statement, However I'll give it and go and see what it does. Thanks >I'm only a Python newbie, myself, but I've done a fair number >of scripts with >strings in them, and I've never used '\012' in my code, only '\n'. > >Maybe, try replacing the "\012" in your code with "\n" ??? > >Well, I figured it was worth a try? > >-- >Sheila King >http://www.thinkspot.net/sheila/ >http://www.k12groups.org/ > >On Sun, 28 Jan 2001 21:17:07 -0000, "Budgester" > >wrote about [Tutor] String Replace.....: > >:## Turn Text into HTML >: >: def htmlize(self): >: viewdiary = open("c:\diary.txt", 'r') >: print viewdiary >: print "---------------" >: L = viewdiary.readlines() >: print L >: modified_str = string.replace(L, "\012", "
    " ) >: print modified_str >: viewdiary.close >: >:and the error I'm getting >: >: >:--------------- >:['this is a test\012', 'this is another test\012', 'one more >test\012'] >:Exception in Tkinter callback >:Traceback (most recent call last): >: File "c:\python20\lib\lib-tk\Tkinter.py", line 1287, in __call__ >: return apply(self.func, args) >: File "C:\python-code\diary-update\diary.py", line 71, in htmlize >: modified_str = string.replace(L, "\012", "
    " ) >: File "c:\python20\lib\string.py", line 363, in replace >: return s.replace(old, new, maxsplit) >:AttributeError: replace > > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor > From tbrauch@mindless.com Sun Jan 28 22:09:38 2001 From: tbrauch@mindless.com (Timothy M. Brauch) Date: Sun, 28 Jan 2001 17:09:38 -0500 Subject: [Tutor] Upgraded to 2.0 Message-ID: <3A7498A2.A5D0E6D3@mindless.com> I had Python 1.5.2 installed on my Windows 98 machine. I uninstalled that versino and installed version 2.0. But, there are a few things different that I would like to change back, if possible. With version 1.5.2 if I right-clicked on a *.py or *.pyw file an option to Edit with Idle or Edit with Emacs always appeared. Is there a way to get this back? Also, when I would open Idle, I would not get the Python Shell, I would always get an "Untitled" window where I could start programming. Can I change this. Perhaps I just need to change the shortcut? I did change my autoexec file so that I can run Python from an MS-Dos prompt. I am proud of that (okay, it wasn't really hard at all, but I did do it myself). If anyone can tell me how to make these changes, I would really appreciate it. - Tim From tbrauch@mindless.com Sun Jan 28 22:18:59 2001 From: tbrauch@mindless.com (Timothy M. Brauch) Date: Sun, 28 Jan 2001 17:18:59 -0500 Subject: [Tutor] Upgraded to 2.0 References: <3A7498A2.A5D0E6D3@mindless.com> Message-ID: <3A749AD3.1EBB88D6@mindless.com> I now have Idle openning to the Editor window. But, I would still like to be able to right click and have the option of Edit with Idle or Edit with Emacs. If anyone can offer help with this, I would be a happy programmer (at least for the rest of the day). - Tim From martok@mattsmail.com Sun Jan 28 22:19:16 2001 From: martok@mattsmail.com (Matthias Hager) Date: Sun, 28 Jan 2001 14:19:16 -0800 Subject: [Tutor] Upgraded to 2.0 Message-ID: <200101281419.AA654901538@mail.mattsmail.com> With version 1.5.2 if I right-clicked on a *.py or *.pyw file an option to Edit with Idle or Edit with Emacs always appeared. Is there a way to get this back? >>>>>If you click choose program, and choose emacs or idle to open it with, it should give you options to open it with that program next time. My Win ME does anyhow. Also, when I would open Idle, I would not get the Python Shell, I would always get an "Untitled" window where I could start programming. Can I change this. Perhaps I just need to change the shortcut? >>>>>Probably just change shortcut would do it -- Programming isn't cool, it's awesome. %%%################?????????###################^^^ martok@mattsmail.com http://mymymatthias.tripod.com/ %%%################????????####################^^^ -- Like my email address? Get your own for FREE at http://firstname.com Get you@JohnsMail.com or you@AlexsMail.com or pick from 500 more! From dyoo@hkn.eecs.berkeley.edu Sun Jan 28 23:33:38 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Sun, 28 Jan 2001 15:33:38 -0800 (PST) Subject: [Tutor] (no subject) In-Reply-To: Message-ID: On Sun, 28 Jan 2001, Timothy Wilson wrote: > On Sun, 28 Jan 2001, chastin cullifer wrote: > > > but i was wondering if it is possible to make a game with python > > besides text adventures?? > > Certainly. Check out PySol at > http://wildsau.idv.uni-linz.ac.at/mfx/pysol/ Also, some people are making an RPG with a variant of Stackless Python: http://www.eve-online.com/ From scarblac@pino.selwerd.nl Sun Jan 28 23:28:21 2001 From: scarblac@pino.selwerd.nl (Remco Gerlich) Date: Mon, 29 Jan 2001 00:28:21 +0100 Subject: [Tutor] String Replace..... In-Reply-To: ; from sheila@thinkspot.net on Sun, Jan 28, 2001 at 01:31:01PM -0800 References: <000801c0896f$ac50de50$0300000a@budgester> Message-ID: <20010129002821.C9770@pino.selwerd.nl> I had written a more detailed reply first, but accidentally sent it to Sheila King. Her "SpamCop" system blocked my mail, giving me an URL to open it up that didn't work... I'm a bit irritated now and will only give short comments: On Sun, Jan 28, 2001 at 01:31:01PM -0800, Sheila King wrote: > I'm only a Python newbie, myself, but I've done a fair number of scripts with > strings in them, and I've never used '\012' in my code, only '\n'. > > Maybe, try replacing the "\012" in your code with "\n" ??? Try it in the interpreter: >>> "\n" "\012" They're the same thing. > :## Turn Text into HTML > : > : def htmlize(self): > : viewdiary = open("c:\diary.txt", 'r') > : print viewdiary > : print "---------------" > : L = viewdiary.readlines() > : print L > : modified_str = string.replace(L, "\012", "
    " ) > : print modified_str > : viewdiary.close > : > :and the error I'm getting > : > : > :--------------- > :['this is a test\012', 'this is another test\012', 'one more test\012'] > :Exception in Tkinter callback > :Traceback (most recent call last): > : File "c:\python20\lib\lib-tk\Tkinter.py", line 1287, in __call__ > : return apply(self.func, args) > : File "C:\python-code\diary-update\diary.py", line 71, in htmlize > : modified_str = string.replace(L, "\012", "
    " ) > : File "c:\python20\lib\string.py", line 363, in replace > : return s.replace(old, new, maxsplit) > :AttributeError: replace L is a list (result of readlines()), you try to use string.replace on a list. Either use read() instead of readlines(), or don't use replace but string.join("
    ") to put the lines back together. Or put the whole thing between
     and 
    tags. -- Remco Gerlich From sheila@thinkspot.net Sun Jan 28 23:46:49 2001 From: sheila@thinkspot.net (Sheila King) Date: Sun, 28 Jan 2001 15:46:49 -0800 Subject: [Tutor] String Replace..... In-Reply-To: <20010129002821.C9770@pino.selwerd.nl> References: <000801c0896f$ac50de50$0300000a@budgester> <20010129002821.C9770@pino.selwerd.nl> Message-ID: <14293F11423@kserver.org> On Mon, 29 Jan 2001 00:28:21 +0100, Remco Gerlich wrote about Re: [Tutor] String Replace.....: :I had written a more detailed reply first, but accidentally sent it to :Sheila King. Her "SpamCop" system blocked my mail, giving me an URL to open :it up that didn't work... I'm a bit irritated now and will only give short :comments: I'm surprised that the SpamCop link didn't work. I've tested it myself, and have had no problems with it. Hmm. (It's not "my" spamcop. It's a service anyone can subscribe to... http://www.spamcop.net/ ) In any case, I have your original, and much more detail message. Per your request, via e-mail, I am posting it to the list. Forwarded message follows. -- Sheila King http://www.thinkspot.net/sheila/ http://www.k12groups.org/ ------------------------------------------------------------------- To: Sheila King Subject: Re: [Tutor] String Replace..... From: Remco Gerlich Date: Mon, 29 Jan 2001 00:22:23 +0100 On Sun, Jan 28, 2001 at 01:31:01PM -0800, Sheila King wrote: > I'm only a Python newbie, myself, but I've done a fair number of scripts with > strings in them, and I've never used '\012' in my code, only '\n'. > > Maybe, try replacing the "\012" in your code with "\n" ??? Start a Python interpreter, and type it in: >>> "\n" "\012" On Unix, \n is equal to a single LF, which is ASCII 012 (I think that is octal, so it's 10 decimal, but I'm not sure). String representation translates control codes like that into octal escapes, iirc. So they're the same. > :## Turn Text into HTML > : > : def htmlize(self): > : viewdiary = open("c:\diary.txt", 'r') > : print viewdiary > : print "---------------" > : L = viewdiary.readlines() > : print L > : modified_str = string.replace(L, "\012", "
    " ) > : print modified_str > : viewdiary.close > : > :and the error I'm getting > : > : > :--------------- > :['this is a test\012', 'this is another test\012', 'one more test\012'] > :Exception in Tkinter callback > :Traceback (most recent call last): > : File "c:\python20\lib\lib-tk\Tkinter.py", line 1287, in __call__ > : return apply(self.func, args) > : File "C:\python-code\diary-update\diary.py", line 71, in htmlize > : modified_str = string.replace(L, "\012", "
    " ) > : File "c:\python20\lib\string.py", line 363, in replace > : return s.replace(old, new, maxsplit) > :AttributeError: replace You get L by means of readlines(). That function returns a *list* of strings. You call string.replace(L, ...), which calls L.replace(), but that function is only defined for strings, not for lists. Either don't use readlines() but instead use read(), which simple reads in the whole file as one string, *or* use the list of lines that readlines() gives you and put them together by means of L.join("
    ") so that the string.replace call isn't needed anymore. So either L = viewdiary.read() modified_str = string.replace(L, "\n", "
    ") # or even modified_str = L.replace("\n", "
    ") or L = viewdiary.readlines() modified_str = string.join(L, "
    ") # or modified_str = L.join("
    ") Or maybe the simplest way is to enclose the whole thing in
     tags,
    gives a different font, but the browser interprets the line breaks by
    itself...
    
    -- 
    Remco Gerlich
    
    
    
    
    From dyoo@hkn.eecs.berkeley.edu  Sun Jan 28 23:55:04 2001
    From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
    Date: Sun, 28 Jan 2001 15:55:04 -0800 (PST)
    Subject: [Tutor] String Replace.....  [octal numbers]
    In-Reply-To: <000a01c08972$5210be80$0300000a@budgester>
    Message-ID: 
    
    On Sun, 28 Jan 2001, Budgester wrote:
    
    > I'm new to Python as well, the reason I was using \012 was because
    > that's what was returned when i did a debugging print statement,
    
    Hmmm... let me go off on a tangent on '\012', and then go back to the
    original question.
    
    It turns out that Python thinks that '\012' and '\n' are the same thing:
    
    ###
    >>> '\n' == '\012'
    1
    ###
    
    What's neat is that characters can be thought of as numbers.  We can see
    this more clearly by using the ord() "ordinal" and chr() "character"
    functions, which let us explore this more:
    
    ###
    >>> ord('\n')
    10
    >>> chr(ord('\n'))
    '\012'
    ###
    
    But at first, this is weird!  Why is the ordinal value of '\012' equal to
    10?  Apparently, it's reversable, since we can go from a character back to
    its ordinal number back to its character, but where did that 10 come from?
    
    One way we can get 10 out of '\012' is like this:
    
        10 =   1 * 8**1
             + 2 * 8**0
    
    That is, it has to do with "octal" numbers, that is, numbers that are
    represented in terms of powers of 8's.  Python shows us the special
    characters (newlines, tabs, etc.) in octal.  To tell the truth, I'm not
    quite sure why, but there's probably a good reason for it.  *grin*
    
    Likewise, if we try something like this:
    
    ###
    >>> num = 0223
    >>> num
    147
    ###
    
    We can see that:
    
        147 = 2 * 8**2
            + 2 * 8**1
            + 3 * 8**0
    
    It's weird, but it's neat to see a glimpse of something a little foreign
    at times.
    
    
    
    
    Anyway, to go back to your original problem, the error that pops up:
    
    ###
     File "c:\python20\lib\string.py", line 363, in replace
        return s.replace(old, new, maxsplit)
    ###
    
    is really wacky, since that's part of the standard library.  I think that
    another part of your code might have accidently touched string's version
    of replace(), so let's take a look at the full code.
    
    
    
    From dyoo@hkn.eecs.berkeley.edu  Mon Jan 29 00:06:03 2001
    From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo)
    Date: Sun, 28 Jan 2001 16:06:03 -0800 (PST)
    Subject: [Tutor] Basic freeze question
    In-Reply-To: <20010128201543.47818.qmail@web12406.mail.yahoo.com>
    Message-ID: 
    
    On Sun, 28 Jan 2001, Pythoperson wrote:
    
    > I am just starting with python and TK and I am enjoying it.  I have a
    > nifty little TK program going and I am trying to freeze it.  However,
    > I get a screen-full of error messages!  Are there any extensive help
    > files or tutorials about freeze?  If I cannot make an executable, then
    > python is fairly useless to me, no matter the fun I am having.
    
    It might have to do with the Tk stuff --- I'm not sure if Freeze knows how
    to freeze graphical programs.  However, Gordon McMillian's "Installer"
    program does:
    
        http://www.mcmillan-inc.com/install1.html
    
    This one appears to have some more documentation (even a FAQ!), so it
    should be easier to use.
    
    Good luck!
    
    
    
    From jdrake@jam.rr.com  Mon Jan 29 02:20:42 2001
    From: jdrake@jam.rr.com (Jason Drake)
    Date: Sun, 28 Jan 2001 20:20:42 -0600
    Subject: [Tutor] HELP!
    Message-ID: <004c01c0899a$14974240$80c8a418@jam.rr.com>
    
    This is a multi-part message in MIME format.
    
    ------=_NextPart_000_0049_01C08967.C9C14FE0
    Content-Type: text/plain;
    	charset="iso-8859-1"
    Content-Transfer-Encoding: quoted-printable
    
    Hey all,=20
    
    I'm new to this list and Python and relatively new to programming at all =
    and am looking for a better tutorial than I have used so far for =
    figuring out how to process a form using Python/CGI. At present I have =
    made one attempt work utilizing a code example given, but the =
    information on what is going on with this code example and how to modify =
    it to suit my needs is seriously lacking. My next thought was to look =
    into the information given for the CGI module in python, noting that I =
    had used an import cgi line in the code only to find myself beating my =
    head against a wall for an inability to find clarity there... If anyone =
    knows where I can find some information regarding the CGI module that =
    will make a fair amount of sense, or a well written CGI tutorial I would =
    greatly appreciate hearing from you...=20
    
    Last time I dealt with CGI I used Perl and am relatively familiar with =
    the coding to split key/value pairs and parse out the form's =
    information, but expect that the cgi module will make me love it by =
    saving me alot of troubles in that area... TIA
    
    Jason
    
    ------=_NextPart_000_0049_01C08967.C9C14FE0
    Content-Type: text/html;
    	charset="iso-8859-1"
    Content-Transfer-Encoding: quoted-printable
    
    
    
    
    
    
    
    
    
    Hey all,
     
    I'm new to this list and Python and = relatively new=20 to programming at all and am looking for a better tutorial than I have = used so=20 far for figuring out how to process a form using Python/CGI. At present = I have=20 made one attempt work utilizing a code example given, but the = information on=20 what is going on with this code example and how to modify it to suit my = needs is=20 seriously lacking. My next thought was to look into the information = given for=20 the CGI module in python, noting that I had used an import cgi line in = the code=20 only to find myself beating my head against a wall for an inability to = find=20 clarity there... If anyone knows where I can find some information = regarding the=20 CGI module that will make a fair amount of sense, or a well written CGI = tutorial=20 I would greatly appreciate hearing from you...
     
    Last time I dealt with CGI I used Perl = and am=20 relatively familiar with the coding to split key/value pairs and = parse out=20 the form's information, but expect that the cgi module will make me love = it by=20 saving me alot of troubles in that area... TIA
     
    Jason
    ------=_NextPart_000_0049_01C08967.C9C14FE0-- From chastin_am_i@hotmail.com Mon Jan 29 02:51:01 2001 From: chastin_am_i@hotmail.com (chastin cullifer) Date: Sun, 28 Jan 2001 20:51:01 -0600 Subject: [Tutor] another ? Message-ID:
    another game question
     
    is it possible to make a graphic great game like, diablo or other RPG games like that??
     
    also is there like a sleep or wait command or something
    so it waits like 3 seconds before doing something


    Get your FREE download of MSN Explorer at http://explorer.msn.com

    From chastin_am_i@hotmail.com Mon Jan 29 02:56:55 2001 From: chastin_am_i@hotmail.com (chastin cullifer) Date: Sun, 28 Jan 2001 20:56:55 -0600 Subject: [Tutor] *.exe's Message-ID:
    how do you compile your code into a *.exe file??


    Get your FREE download of MSN Explorer at http://explorer.msn.com

    From jdrake@jam.rr.com Mon Jan 29 03:13:12 2001 From: jdrake@jam.rr.com (Jason Drake) Date: Sun, 28 Jan 2001 21:13:12 -0600 Subject: [Tutor] CGI/Python Message-ID: <007001c089a1$69fcf7a0$80c8a418@jam.rr.com> This is a multi-part message in MIME format. ------=_NextPart_000_006D_01C0896F.1F17C300 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Okay... I'm still battling with this and am currently fighting with the = example as given in the 'Support module for CGI (Common Gateway = Interface) scripts.' at the Python.org website. I am very near playing = cut'n'paste with this along with some information I know from my = previous forays into this langauge. At present my code looks like this: #!/usr/bin/python # # cheezy2.cgi # =20 import cgi =20 print "Content-type: text/html\n" =20 form =3D cgi.FieldStorage() form_ok =3D 0 if form.has_key("name") and form.has_key("addr"): form_ok =3D 1 if not form_ok: print "

    Error

    " print "Please fill in the name and addr fields." return print form["name"].value print form["addr"].value This code, coupled with a simple HTML Form using the post method = provides me with a basic "you're an idiot" error message from my web = server. I'm sitting here whistling "Always look on the bright side of = life" while considering the average velocity of an unladen PC as it = falls out a 2nd story window. Any help in explaining why this code just = doesn't want to work, and better yet, good info on how to actually = retrieve specific data from forms would be most appreciated at this = junction so that I can get on with the 'harder' aspects of what I will = do with the data once I can get it into my grubby lil hands. :) Jason ------=_NextPart_000_006D_01C0896F.1F17C300 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
    Okay... I'm still battling with this = and am=20 currently fighting with the example as given in the 'Support module for CGI (Common Gateway Interface) scripts.' at = the=20 Python.org website. I am very near playing cut'n'paste with this along = with some=20 information I know from my previous forays into this langauge. At = present my=20 code looks like this:
     
    #!/usr/bin/python
    #
    #=20 cheezy2.cgi
    #
     
    import cgi
     
     
    print "Content-type: = text/html\n"
     
    form=20 =3D cgi.FieldStorage()
    form_ok =3D 0
    if form.has_key("name") and=20 form.has_key("addr"):
        form_ok =3D 1
    if not=20 form_ok:
        print=20 "<H1>Error</H1>"
        print "Please fill in = the=20 name and addr fields."
        return
    print=20 form["name"].value
    print form["addr"].value
    This code, coupled with a simple HTML = Form using=20 the post method provides me with a basic "you're an idiot" error message = from my=20 web server. I'm sitting here whistling "Always look on the bright side = of life"=20 while considering the average velocity of an unladen PC as it falls out = a 2nd=20 story window. Any help in explaining why this code just doesn't want to = work,=20 and better yet, good info on how to actually retrieve specific data from = forms=20 would be most appreciated at this junction so that I can get on with the = 'harder' aspects of what I will do with the data once I can get it into = my=20 grubby lil hands. :)
     
    Jason
    ------=_NextPart_000_006D_01C0896F.1F17C300-- From jdrake@jam.rr.com Mon Jan 29 03:20:36 2001 From: jdrake@jam.rr.com (Jason Drake) Date: Sun, 28 Jan 2001 21:20:36 -0600 Subject: [Tutor] Ack... Message-ID: <008001c089a2$72b5d3c0$80c8a418@jam.rr.com> This is a multi-part message in MIME format. ------=_NextPart_000_007D_01C08970.27C77760 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Well... Okay. Before you tell me specifically what is wrong with this = code, I have found that not using the error checking for empty forms = that was supplied with this code works to give me the basic desired = result. From there I can happily use the data and go on to other things, = but I would still be very interested in knowing where the code for the = error checking went bad so I might be able to avoid it some at a later = date. Jason ------=_NextPart_000_007D_01C08970.27C77760 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
    Well... Okay. Before you tell me = specifically what=20 is wrong with this code, I have found that not using the error checking = for=20 empty forms that was supplied with this code works to give me the basic = desired=20 result. From there I can happily use the data and go on to other things, = but I=20 would still be very interested in knowing where the code for the error = checking=20 went bad so I might be able to avoid it some at a later = date.
     
    Jason
    ------=_NextPart_000_007D_01C08970.27C77760-- From martok@mattsmail.com Mon Jan 29 03:37:55 2001 From: martok@mattsmail.com (Matthias Hager) Date: Sun, 28 Jan 2001 19:37:55 -0800 Subject: [Tutor] CGI/Python Message-ID: <200101281937.AA1033502974@mail.mattsmail.com> #!/usr/bin/python # # cheezy2.cgi # import cgi print "Content-type: text/html\n" form = cgi.FieldStorage() form_ok = 0 if form.has_key("name") and form.has_key("addr"): form_ok = 1 ################################ if not form_ok: ## try changing to 'else:' ## I don't understand why you actually need the form_ok ## I could be wrong, it could be part of the CGI, but else it isn't ## needed, hope this works, I'm fairly new to Python print "

    Error

    " print "Please fill in the name and addr fields." return print form["name"].value print form["addr"].value -- Programming isn't cool, it's awesome. %%%################?????????###################^^^ martok@mattsmail.com http://mymymatthias.tripod.com/ %%%################????????####################^^^ -- Like my email address? Get your own for FREE at http://firstname.com Get you@JohnsMail.com or you@AlexsMail.com or pick from 500 more! From wheelege@tsn.cc Mon Jan 29 07:48:05 2001 From: wheelege@tsn.cc (Glen Wheeler) Date: Mon, 29 Jan 2001 18:48:05 +1100 Subject: [Tutor] String Replace..... [octal numbers] References: Message-ID: <00a601c089c7$d0e771e0$a410fea9@glen> tiny tiny comment about octals.... ----- Original Message ----- From: Danny Yoo To: Budgester Cc: 'Tutor (E-mail)' Sent: Monday, January 29, 2001 10:55 AM Subject: RE: [Tutor] String Replace..... [octal numbers] > On Sun, 28 Jan 2001, Budgester wrote: > > > I'm new to Python as well, the reason I was using \012 was because > > that's what was returned when i did a debugging print statement, > > Hmmm... let me go off on a tangent on '\012', and then go back to the > original question. > > It turns out that Python thinks that '\012' and '\n' are the same thing: > > ### > >>> '\n' == '\012' > 1 > ### > > What's neat is that characters can be thought of as numbers. We can see > this more clearly by using the ord() "ordinal" and chr() "character" > functions, which let us explore this more: > > ### > >>> ord('\n') > 10 > >>> chr(ord('\n')) > '\012' > ### > > But at first, this is weird! Why is the ordinal value of '\012' equal to > 10? Apparently, it's reversable, since we can go from a character back to > its ordinal number back to its character, but where did that 10 come from? > > One way we can get 10 out of '\012' is like this: > > 10 = 1 * 8**1 > + 2 * 8**0 > > That is, it has to do with "octal" numbers, that is, numbers that are > represented in terms of powers of 8's. Python shows us the special > characters (newlines, tabs, etc.) in octal. To tell the truth, I'm not > quite sure why, but there's probably a good reason for it. *grin* > Pretty sure it was because the first ASCII tables were 128 characters long, so could be easily represented with octal. Told ya it was short :) > Likewise, if we try something like this: > > ### > >>> num = 0223 > >>> num > 147 > ### > > We can see that: > > 147 = 2 * 8**2 > + 2 * 8**1 > + 3 * 8**0 > > It's weird, but it's neat to see a glimpse of something a little foreign > at times. > > > > > Anyway, to go back to your original problem, the error that pops up: > > ### > File "c:\python20\lib\string.py", line 363, in replace > return s.replace(old, new, maxsplit) > ### > > is really wacky, since that's part of the standard library. I think that > another part of your code might have accidently touched string's version > of replace(), so let's take a look at the full code. > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From dyoo@hkn.eecs.berkeley.edu Mon Jan 29 08:08:45 2001 From: dyoo@hkn.eecs.berkeley.edu (Danny Yoo) Date: Mon, 29 Jan 2001 00:08:45 -0800 (PST) Subject: [Tutor] See you later! Message-ID: Hiya everyone, I'll be taking a leave of absence from the tutor list for a while. I hope to come back to tutor@python.org again, but I need to do some stuff first. Until then, happy hacking! Sincerely, Danny Yoo From toodles@yifan.net Mon Jan 29 08:27:16 2001 From: toodles@yifan.net (Andrew Wilkins) Date: Mon, 29 Jan 2001 16:27:16 +0800 Subject: [Tutor] *.exe's In-Reply-To: Message-ID: This is a multi-part message in MIME format. ------=_NextPart_000_0000_01C08A10.58097AE0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: base64 SGkhDQoNCkdvIHRvIEdvcmRhbiBNY01pbGxhbidzIHNpdGUsIGl0IGhhcyBhIHVzZWZ1bCB1dGls aXR5IHRvIGNvbXBpbGUgcHl0aG9uIGNvZGUgaW50byBleGVjdXRhYmxlczoNCmh0dHA6Ly93d3cu bWNtaWxsYW4taW5jLmNvbS9pbnN0YWxsMS5odG1sDQoNClJlZ2FyZGluZyB5b3VyIG90aGVyIHF1 ZXN0aW9uLA0KDQoiaXMgaXQgcG9zc2libGUgdG8gbWFrZSBhIGdyYXBoaWMgZ3JlYXQgZ2FtZSBs aWtlLCBkaWFibG8gb3Igb3RoZXIgUlBHIGdhbWVzIGxpa2UgdGhhdD8/Ig0KDQpJJ2QgaGF2ZSB0 byBzYXkgeWVzLi4uYnV0IGl0IHdvdWxkIHRha2UgYSBsb3Qgb2YgaGFja2luZywgYW5kIHdvdWxk IGJhc2ljYWxseSBlbmQgdXAgaW4gQysrIG9yIHNvbWV0aGluZyBlbHNlIGFueXdheS4uLihJIHRo aW5rLCBJJ20gbm8ga25vdy1pdC1hbGwtcHl0aG9uLWd1cnUpDQpNeSBndWVzcyBpcyB0aGF0IHlv dSdkIHdhbnQgdG8gY3JlYXRlIGEgbmV3IG1vZHVsZSBpbiBDLCBJIGFzc3VtZSB5b3UncmUgdXNp bmcgV2luZG93cywgc28geW91J2QgdXNlIHNvbWUgbWVkaWEgbGlicmFyeSAoZWcuIERpcmVjdCBY LCBHTCkgYW5kIG1ha2UgYSB3cmFwcGVyIGluIFB5dGhvbi4NCg0KSSd2ZSBiZWVuIHRyeWluZyB0 byBtYWtlIGEgTVVEIG9uIHB5dGhvbi4uLmJ1dCBJIGZlYXIgSSdtIHRvbyBtdWNoIG9mIGEgbmV3 YmllIHRvIGRvIGl0Li4uDQpJIGhvcGUgeW91IG1ha2UgYSBjb29sIGdhbWUgc28gSSBjYW4gcGxh eSBpdCENCg0KQW5kcmV3IFdpbGtpbnMNCiAgLS0tLS1PcmlnaW5hbCBNZXNzYWdlLS0tLS0NCiAg RnJvbTogdHV0b3ItYWRtaW5AcHl0aG9uLm9yZyBbbWFpbHRvOnR1dG9yLWFkbWluQHB5dGhvbi5v cmddT24gQmVoYWxmIE9mIGNoYXN0aW4gY3VsbGlmZXINCiAgU2VudDogTW9uZGF5LCAyOSBKYW51 YXJ5IDIwMDEgMTA6NTcNCiAgVG86IHR1dG9yQHB5dGhvbi5vcmcNCiAgU3ViamVjdDogW1R1dG9y XSAqLmV4ZSdzDQoNCg0KICBob3cgZG8geW91IGNvbXBpbGUgeW91ciBjb2RlIGludG8gYSAqLmV4 ZSBmaWxlPz8NCg0KDQotLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0t LS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0NCiAgR2V0IHlvdXIgRlJFRSBkb3du bG9hZCBvZiBNU04gRXhwbG9yZXIgYXQgaHR0cDovL2V4cGxvcmVyLm1zbi5jb20NCg0KDQogIF9f X19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fIFR1dG9yIG1haWxs aXN0IC0gVHV0b3JAcHl0aG9uLm9yZyBodHRwOi8vbWFpbC5weXRob24ub3JnL21haWxtYW4vbGlz dGluZm8vdHV0b3IgDQo= ------=_NextPart_000_0000_01C08A10.58097AE0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: base64 PCFET0NUWVBFIEhUTUwgUFVCTElDICItLy9XM0MvL0RURCBIVE1MIDQuMCBUcmFuc2l0aW9uYWwv L0VOIj4NCjxIVE1MPjxIRUFEPg0KPE1FVEEgaHR0cC1lcXVpdj1Db250ZW50LVR5cGUgY29udGVu dD0idGV4dC9odG1sOyBjaGFyc2V0PWlzby04ODU5LTEiPg0KPE1FVEEgY29udGVudD0iTVNIVE1M IDUuNTAuNDUyMi4xODAwIiBuYW1lPUdFTkVSQVRPUj48L0hFQUQ+DQo8Qk9EWT4NCjxESVY+PEZP TlQgZmFjZT1UYWhvbWEgY29sb3I9IzAwMDBmZiBzaXplPTI+PFNQQU4gDQpjbGFzcz05NjAzMzIx MDgtMjkwMTIwMDE+SGkhPC9TUEFOPjwvRk9OVD48L0RJVj4NCjxESVY+PEZPTlQgZmFjZT1UYWhv bWEgY29sb3I9IzAwMDBmZiBzaXplPTI+PFNQQU4gDQpjbGFzcz05NjAzMzIxMDgtMjkwMTIwMDE+ PC9TUEFOPjwvRk9OVD4mbmJzcDs8L0RJVj4NCjxESVY+PEZPTlQgZmFjZT1UYWhvbWEgY29sb3I9 IzAwMDBmZiBzaXplPTI+PFNQQU4gY2xhc3M9OTYwMzMyMTA4LTI5MDEyMDAxPkdvIHRvIA0KR29y ZGFuIE1jTWlsbGFuJ3Mgc2l0ZSwgaXQgaGFzIGEgdXNlZnVsIHV0aWxpdHkgdG8gY29tcGlsZSBw eXRob24gY29kZSBpbnRvIA0KZXhlY3V0YWJsZXM6PC9TUEFOPjwvRk9OVD48L0RJVj4NCjxESVY+ PFNQQU4gY2xhc3M9OTYwMzMyMTA4LTI5MDEyMDAxPg0KPFA+PEEgaHJlZj0iaHR0cDovL3d3dy5t Y21pbGxhbi1pbmMuY29tL2luc3RhbGwxLmh0bWwiPjxGT05UIGZhY2U9VGFob21hIA0Kc2l6ZT0y Pmh0dHA6Ly93d3cubWNtaWxsYW4taW5jLmNvbS9pbnN0YWxsMS5odG1sPC9GT05UPjwvQT48L1A+ DQo8UD48U1BBTiBjbGFzcz05NjAzMzIxMDgtMjkwMTIwMDE+PEZPTlQgZmFjZT1UYWhvbWEgY29s b3I9IzAwMDBmZiANCnNpemU9Mj5SZWdhcmRpbmcgeW91ciBvdGhlciBxdWVzdGlvbiw8L0ZPTlQ+ PC9TUEFOPjxTUEFOIA0KY2xhc3M9OTYwMzMyMTA4LTI5MDEyMDAxPjwvUD4NCjxESVY+PEZPTlQg ZmFjZT1UYWhvbWE+PEZPTlQgY29sb3I9IzAwMDBmZj48Rk9OVCBzaXplPTI+PFNQQU4gDQpjbGFz cz05NjAzMzIxMDgtMjkwMTIwMDE+IjwvU1BBTj5pcyBpdCBwb3NzaWJsZSB0byBtYWtlIGEgZ3Jh cGhpYyBncmVhdCBnYW1lIA0KbGlrZSwgZGlhYmxvIG9yIG90aGVyIFJQRyBnYW1lcyBsaWtlIHRo YXQ/PzxTUEFOIA0KY2xhc3M9OTYwMzMyMTA4LTI5MDEyMDAxPiI8L1NQQU4+PC9GT05UPjwvRk9O VD48L0ZPTlQ+PC9ESVY+DQo8RElWPjxGT05UIGZhY2U9VGFob21hPjxGT05UIGNvbG9yPSMwMDAw ZmY+PEZPTlQgc2l6ZT0yPjxTUEFOIA0KY2xhc3M9OTYwMzMyMTA4LTI5MDEyMDAxPjwvU1BBTj48 L0ZPTlQ+PC9GT05UPjwvRk9OVD4mbmJzcDs8L0RJVj4NCjxESVY+PEZPTlQgZmFjZT1UYWhvbWE+ PEZPTlQgY29sb3I9IzAwMDBmZj48Rk9OVCBzaXplPTI+PFNQQU4gDQpjbGFzcz05NjAzMzIxMDgt MjkwMTIwMDE+SSdkIGhhdmUgdG8gc2F5IHllcy4uLmJ1dCBpdCB3b3VsZCB0YWtlIGEgbG90IG9m IA0KaGFja2luZywgYW5kIHdvdWxkIGJhc2ljYWxseSBlbmQgdXAgaW4gQysrIG9yIHNvbWV0aGlu ZyBlbHNlIGFueXdheS4uLihJIHRoaW5rLCANCkknbSBubyBrbm93LWl0LWFsbC1weXRob24tZ3Vy dSk8L1NQQU4+PC9GT05UPjwvRk9OVD48L0ZPTlQ+PC9ESVY+DQo8RElWPjxGT05UIGZhY2U9VGFo b21hPjxGT05UIGNvbG9yPSMwMDAwZmY+PEZPTlQgc2l6ZT0yPjxTUEFOIA0KY2xhc3M9OTYwMzMy MTA4LTI5MDEyMDAxPk15IGd1ZXNzIGlzIHRoYXQgeW91J2Qgd2FudCB0byBjcmVhdGUgYSBuZXcg bW9kdWxlIGluIA0KQywgSSBhc3N1bWUgeW91J3JlIHVzaW5nIFdpbmRvd3MsIHNvIHlvdSdkIHVz ZSBzb21lIG1lZGlhJm5ic3A7bGlicmFyeSAoZWcuIA0KRGlyZWN0IFgsIEdMKSBhbmQgbWFrZSBh IHdyYXBwZXIgaW4gUHl0aG9uLjwvU1BBTj48L0ZPTlQ+PC9GT05UPjwvRk9OVD48L0RJVj4NCjxE SVY+PEZPTlQgZmFjZT1UYWhvbWE+PEZPTlQgY29sb3I9IzAwMDBmZj48Rk9OVCBzaXplPTI+PFNQ QU4gDQpjbGFzcz05NjAzMzIxMDgtMjkwMTIwMDE+PC9TUEFOPjwvRk9OVD48L0ZPTlQ+PC9GT05U PiZuYnNwOzwvRElWPg0KPERJVj48Rk9OVCBmYWNlPVRhaG9tYT48Rk9OVCBjb2xvcj0jMDAwMGZm PjxGT05UIHNpemU9Mj48U1BBTiANCmNsYXNzPTk2MDMzMjEwOC0yOTAxMjAwMT5JJ3ZlIGJlZW4g dHJ5aW5nIHRvIG1ha2UgYSBNVUQgb24gcHl0aG9uLi4uYnV0IEkgZmVhciANCkknbSB0b28gbXVj aCBvZiBhJm5ic3A7bmV3YmllIHRvIGRvIGl0Li4uPC9TUEFOPjwvRk9OVD48L0ZPTlQ+PC9GT05U PjwvRElWPg0KPERJVj48Rk9OVCBmYWNlPVRhaG9tYT48Rk9OVCBjb2xvcj0jMDAwMGZmPjxGT05U IHNpemU9Mj48U1BBTiANCmNsYXNzPTk2MDMzMjEwOC0yOTAxMjAwMT48U1BBTiBjbGFzcz05NjAz MzIxMDgtMjkwMTIwMDE+SSBob3BlIHlvdSBtYWtlIGEgY29vbCANCmdhbWUgc28gSSBjYW4gcGxh eSBpdCE8L1NQQU4+PC9TUEFOPjwvRk9OVD48L0ZPTlQ+PC9GT05UPjwvRElWPg0KPERJVj48Rk9O VCBmYWNlPVRhaG9tYT48Rk9OVCBjb2xvcj0jMDAwMGZmPjxGT05UIHNpemU9Mj48U1BBTiANCmNs YXNzPTk2MDMzMjEwOC0yOTAxMjAwMT48L1NQQU4+PC9GT05UPjwvRk9OVD48L0ZPTlQ+Jm5ic3A7 PC9ESVY+DQo8RElWPjxGT05UIGZhY2U9VGFob21hPjxGT05UIGNvbG9yPSMwMDAwZmY+PEZPTlQg c2l6ZT0yPjxTUEFOIA0KY2xhc3M9OTYwMzMyMTA4LTI5MDEyMDAxPkFuZHJldyANCldpbGtpbnM8 L1NQQU4+PC9GT05UPjwvRk9OVD48L0ZPTlQ+PC9ESVY+PC9TUEFOPjwvU1BBTj48L0RJVj4NCjxC TE9DS1FVT1RFIA0Kc3R5bGU9IlBBRERJTkctTEVGVDogNXB4OyBNQVJHSU4tTEVGVDogNXB4OyBC T1JERVItTEVGVDogIzAwMDBmZiAycHggc29saWQiPg0KICA8RElWIGNsYXNzPU91dGxvb2tNZXNz YWdlSGVhZGVyIGRpcj1sdHIgYWxpZ249bGVmdD48Rk9OVCBmYWNlPVRhaG9tYSANCiAgc2l6ZT0y Pi0tLS0tT3JpZ2luYWwgTWVzc2FnZS0tLS0tPEJSPjxCPkZyb206PC9CPiB0dXRvci1hZG1pbkBw eXRob24ub3JnIA0KICBbbWFpbHRvOnR1dG9yLWFkbWluQHB5dGhvbi5vcmddPEI+T24gQmVoYWxm IE9mIDwvQj5jaGFzdGluIA0KICBjdWxsaWZlcjxCUj48Qj5TZW50OjwvQj4gTW9uZGF5LCAyOSBK YW51YXJ5IDIwMDEgMTA6NTc8QlI+PEI+VG86PC9CPiANCiAgdHV0b3JAcHl0aG9uLm9yZzxCUj48 Qj5TdWJqZWN0OjwvQj4gW1R1dG9yXSAqLmV4ZSdzPEJSPjxCUj48L0ZPTlQ+PC9ESVY+DQogIDxE SVY+aG93IGRvIHlvdSBjb21waWxlIHlvdXIgY29kZSBpbnRvIGEgKi5leGUgZmlsZT8/PC9ESVY+ PEJSIGNsZWFyPWFsbD4NCiAgPEhSPg0KICBHZXQgeW91ciBGUkVFIGRvd25sb2FkIG9mIE1TTiBF eHBsb3JlciBhdCA8QSANCiAgaHJlZj0iaHR0cDovL2V4cGxvcmVyLm1zbi5jb20iPmh0dHA6Ly9l eHBsb3Jlci5tc24uY29tPC9BPjxCUj4NCiAgPFA+PC9QPl9fX19fX19fX19fX19fX19fX19fX19f X19fX19fX19fX19fX19fX19fX19fX19fIFR1dG9yIG1haWxsaXN0IC0gDQogIFR1dG9yQHB5dGhv bi5vcmcgaHR0cDovL21haWwucHl0aG9uLm9yZy9tYWlsbWFuL2xpc3RpbmZvL3R1dG9yIA0KPC9C TE9DS1FVT1RFPjwvQk9EWT48L0hUTUw+DQo= ------=_NextPart_000_0000_01C08A10.58097AE0-- From toodles@yifan.net Mon Jan 29 09:50:43 2001 From: toodles@yifan.net (Andrew Wilkins) Date: Mon, 29 Jan 2001 17:50:43 +0800 Subject: [Tutor] another ? In-Reply-To: Message-ID: This is a multi-part message in MIME format. ------=_NextPart_000_0005_01C08A1C.002F6F80 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: base64 SGkgYWdhaW4sDQoNCkkgZGlkIGEgbGl0dGxlIHJlc2VhcmNoLi4uaXQgYXBwZWFycyB0aGF0IHRo ZXJlIGlzIGFuIE9wZW5HTCBQeXRob24gd3JhcHBlciBhbHJlYWR5LCBnZXQgaXQgaGVyZToNCmh0 dHA6Ly9weW9wZW5nbC5zb3VyY2Vmb3JnZS5uZXQvDQpJIGRvbid0IGtub3cgYW55dGhpbmcgYWJv dXQgT3BlbkdMLi4uYnV0IEknbSBhYm91dCB0byBsZWFybiwgc2VlaW5nIGFzIGl0J3MgaW4gUHl0 aG9uISA9KQ0KDQpBbmRyZXcgV2lsa2lucw0KICAtLS0tLU9yaWdpbmFsIE1lc3NhZ2UtLS0tLQ0K ICBGcm9tOiB0dXRvci1hZG1pbkBweXRob24ub3JnIFttYWlsdG86dHV0b3ItYWRtaW5AcHl0aG9u Lm9yZ11PbiBCZWhhbGYgT2YgY2hhc3RpbiBjdWxsaWZlcg0KICBTZW50OiBNb25kYXksIDI5IEph bnVhcnkgMjAwMSAxMDo1MQ0KICBUbzogdHV0b3JAcHl0aG9uLm9yZw0KICBTdWJqZWN0OiBbVHV0 b3JdIGFub3RoZXIgPw0KDQoNCiAgYW5vdGhlciBnYW1lIHF1ZXN0aW9uDQoNCiAgaXMgaXQgcG9z c2libGUgdG8gbWFrZSBhIGdyYXBoaWMgZ3JlYXQgZ2FtZSBsaWtlLCBkaWFibG8gb3Igb3RoZXIg UlBHIGdhbWVzIGxpa2UgdGhhdD8/DQoNCiAgYWxzbyBpcyB0aGVyZSBsaWtlIGEgc2xlZXAgb3Ig d2FpdCBjb21tYW5kIG9yIHNvbWV0aGluZw0KICBzbyBpdCB3YWl0cyBsaWtlIDMgc2Vjb25kcyBi ZWZvcmUgZG9pbmcgc29tZXRoaW5nDQoNCg0KLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0t LS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tDQogIEdldCB5 b3VyIEZSRUUgZG93bmxvYWQgb2YgTVNOIEV4cGxvcmVyIGF0IGh0dHA6Ly9leHBsb3Jlci5tc24u Y29tDQoNCg0KICBfX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19fX19f XyBUdXRvciBtYWlsbGlzdCAtIFR1dG9yQHB5dGhvbi5vcmcgaHR0cDovL21haWwucHl0aG9uLm9y Zy9tYWlsbWFuL2xpc3RpbmZvL3R1dG9yIA0K ------=_NextPart_000_0005_01C08A1C.002F6F80 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: base64 PCFET0NUWVBFIEhUTUwgUFVCTElDICItLy9XM0MvL0RURCBIVE1MIDQuMCBUcmFuc2l0aW9uYWwv L0VOIj4NCjxIVE1MPjxIRUFEPg0KPE1FVEEgaHR0cC1lcXVpdj1Db250ZW50LVR5cGUgY29udGVu dD0idGV4dC9odG1sOyBjaGFyc2V0PWlzby04ODU5LTEiPg0KPE1FVEEgY29udGVudD0iTVNIVE1M IDUuNTAuNDUyMi4xODAwIiBuYW1lPUdFTkVSQVRPUj48L0hFQUQ+DQo8Qk9EWT4NCjxESVY+PFNQ QU4gY2xhc3M9OTYwNDk0ODA5LTI5MDEyMDAxPjxGT05UIGZhY2U9VGFob21hIGNvbG9yPSMwMDAw ZmYgc2l6ZT0yPkhpIA0KYWdhaW4sPC9GT05UPjwvU1BBTj48L0RJVj4NCjxESVY+PFNQQU4gY2xh c3M9OTYwNDk0ODA5LTI5MDEyMDAxPjxGT05UIGZhY2U9VGFob21hIGNvbG9yPSMwMDAwZmYgDQpz aXplPTI+PC9GT05UPjwvU1BBTj4mbmJzcDs8L0RJVj4NCjxESVY+PFNQQU4gY2xhc3M9OTYwNDk0 ODA5LTI5MDEyMDAxPjxGT05UIGZhY2U9VGFob21hIGNvbG9yPSMwMDAwZmYgc2l6ZT0yPkkgZGlk IA0KYSBsaXR0bGUgcmVzZWFyY2guLi5pdCBhcHBlYXJzIHRoYXQgdGhlcmUgaXMgYW4gT3BlbkdM IFB5dGhvbiB3cmFwcGVyIGFscmVhZHksIA0KZ2V0IGl0IGhlcmU6PC9GT05UPjwvU1BBTj48L0RJ Vj4NCjxESVY+PFNQQU4gY2xhc3M9OTYwNDk0ODA5LTI5MDEyMDAxPjxGT05UIGZhY2U9VGFob21h IGNvbG9yPSMwMDAwZmYgc2l6ZT0yPjxBIA0KaHJlZj0iaHR0cDovL3B5b3BlbmdsLnNvdXJjZWZv cmdlLm5ldC8iPmh0dHA6Ly9weW9wZW5nbC5zb3VyY2Vmb3JnZS5uZXQvPC9BPjwvRk9OVD48L1NQ QU4+PC9ESVY+DQo8RElWPjxTUEFOIGNsYXNzPTk2MDQ5NDgwOS0yOTAxMjAwMT48Rk9OVCBmYWNl PVRhaG9tYSBjb2xvcj0jMDAwMGZmIHNpemU9Mj5JIA0KZG9uJ3Qga25vdyBhbnl0aGluZyBhYm91 dCBPcGVuR0wuLi5idXQgSSdtIGFib3V0IHRvIGxlYXJuLCBzZWVpbmcgYXMgaXQncyBpbiANClB5 dGhvbiEmbmJzcDs9KTwvRk9OVD48L1NQQU4+PC9ESVY+DQo8RElWPjxTUEFOIGNsYXNzPTk2MDQ5 NDgwOS0yOTAxMjAwMT48Rk9OVCBmYWNlPVRhaG9tYSBjb2xvcj0jMDAwMGZmIA0Kc2l6ZT0yPjwv Rk9OVD48L1NQQU4+Jm5ic3A7PC9ESVY+DQo8RElWPjxTUEFOIGNsYXNzPTk2MDQ5NDgwOS0yOTAx MjAwMT48Rk9OVCBmYWNlPVRhaG9tYSBjb2xvcj0jMDAwMGZmIA0Kc2l6ZT0yPkFuZHJldyBXaWxr aW5zPC9GT05UPjwvU1BBTj48L0RJVj4NCjxCTE9DS1FVT1RFIA0Kc3R5bGU9IlBBRERJTkctTEVG VDogNXB4OyBNQVJHSU4tTEVGVDogNXB4OyBCT1JERVItTEVGVDogIzAwMDBmZiAycHggc29saWQi Pg0KICA8RElWIGNsYXNzPU91dGxvb2tNZXNzYWdlSGVhZGVyIGRpcj1sdHIgYWxpZ249bGVmdD48 Rk9OVCBmYWNlPVRhaG9tYSANCiAgc2l6ZT0yPi0tLS0tT3JpZ2luYWwgTWVzc2FnZS0tLS0tPEJS PjxCPkZyb206PC9CPiB0dXRvci1hZG1pbkBweXRob24ub3JnIA0KICBbbWFpbHRvOnR1dG9yLWFk bWluQHB5dGhvbi5vcmddPEI+T24gQmVoYWxmIE9mIDwvQj5jaGFzdGluIA0KICBjdWxsaWZlcjxC Uj48Qj5TZW50OjwvQj4gTW9uZGF5LCAyOSBKYW51YXJ5IDIwMDEgMTA6NTE8QlI+PEI+VG86PC9C PiANCiAgdHV0b3JAcHl0aG9uLm9yZzxCUj48Qj5TdWJqZWN0OjwvQj4gW1R1dG9yXSBhbm90aGVy ID88QlI+PEJSPjwvRk9OVD48L0RJVj4NCiAgPERJVj5hbm90aGVyIGdhbWUgcXVlc3Rpb248L0RJ Vj4NCiAgPERJVj4mbmJzcDs8L0RJVj4NCiAgPERJVj5pcyBpdCBwb3NzaWJsZSB0byBtYWtlIGEg Z3JhcGhpYyBncmVhdCBnYW1lIGxpa2UsIGRpYWJsbyBvciBvdGhlciBSUEcgDQogIGdhbWVzIGxp a2UgdGhhdD8/PC9ESVY+DQogIDxESVY+Jm5ic3A7PC9ESVY+DQogIDxESVY+YWxzbyBpcyB0aGVy ZSZuYnNwO2xpa2UgYSBzbGVlcCBvciB3YWl0IGNvbW1hbmQgb3Igc29tZXRoaW5nPC9ESVY+DQog IDxESVY+c28gaXQgd2FpdHMgbGlrZSAzIHNlY29uZHMgYmVmb3JlIGRvaW5nIHNvbWV0aGluZzwv RElWPjxCUiBjbGVhcj1hbGw+DQogIDxIUj4NCiAgR2V0IHlvdXIgRlJFRSBkb3dubG9hZCBvZiBN U04gRXhwbG9yZXIgYXQgPEEgDQogIGhyZWY9Imh0dHA6Ly9leHBsb3Jlci5tc24uY29tIj5odHRw Oi8vZXhwbG9yZXIubXNuLmNvbTwvQT48QlI+DQogIDxQPjwvUD5fX19fX19fX19fX19fX19fX19f X19fX19fX19fX19fX19fX19fX19fX19fX19fXyBUdXRvciBtYWlsbGlzdCAtIA0KICBUdXRvckBw eXRob24ub3JnIGh0dHA6Ly9tYWlsLnB5dGhvbi5vcmcvbWFpbG1hbi9saXN0aW5mby90dXRvciAN CjwvQkxPQ0tRVU9URT48L0JPRFk+PC9IVE1MPg0K ------=_NextPart_000_0005_01C08A1C.002F6F80-- From kalle@gnupung.net Mon Jan 29 12:08:42 2001 From: kalle@gnupung.net (Kalle Svensson) Date: Mon, 29 Jan 2001 13:08:42 +0100 Subject: [Tutor] CGI/Python In-Reply-To: <007001c089a1$69fcf7a0$80c8a418@jam.rr.com>; from jdrake@jam.rr.com on Sun, Jan 28, 2001 at 09:13:12PM -0600 References: <007001c089a1$69fcf7a0$80c8a418@jam.rr.com> Message-ID: <20010129130842.A6791@father> --k+w/mQv8wyuph6w0 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable Sez Jason Drake: > if not form_ok: > print "

    Error

    " > print "Please fill in the name and addr fields." > return ------^^^^^^ This line is the problem. As this code is outside of any function, you can't return from it. Either put the code in a function: def main(): # All the code main() Or use sys.exit(). Sorry for the brief explanation, but I've got a lot to do. Hope it helps anyway. Peace, Kalle --=20 Email: kalle@gnupung.net | You can tune a filesystem, but you Web: http://www.gnupung.net/ | can't tune a fish. -- man tunefs(8) PGP fingerprint: 0C56 B171 8159 327F 1824 F5DE 74D7 80D7 BF3B B1DD --k+w/mQv8wyuph6w0 Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.4 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE6dV1KdNeA1787sd0RAu6BAJ4ttEp7wzJn31Vjb43pVvpXcUsWRQCcDrGU dYnyW4X6qTxVb5bhrc7hBHA= =Kzb5 -----END PGP SIGNATURE----- --k+w/mQv8wyuph6w0-- From mark_p43938@yahoo.com Mon Jan 29 12:37:42 2001 From: mark_p43938@yahoo.com (Mark Pyles) Date: Mon, 29 Jan 2001 04:37:42 -0800 (PST) Subject: [Tutor] practical uses for python Message-ID: <20010129123742.56850.qmail@web9505.mail.yahoo.com> Hello: Can someone tell me what some practical uses for python are? Mainly using python in the form of scripts similar to perl. Is there anything on the net that I look at to learn from? Thanks. Mark P. __________________________________________________ Do You Yahoo!? Yahoo! Auctions - Buy the things you want at great prices. http://auctions.yahoo.com/ From rob@jam.rr.com Mon Jan 29 12:52:25 2001 From: rob@jam.rr.com (R. A.) Date: Mon, 29 Jan 2001 06:52:25 -0600 Subject: [Tutor] See you later! References: Message-ID: <3A756789.7E475A3E@jam.rr.com> Thanks for everything, Danny! See ya next time. Rob Danny Yoo wrote: > > Hiya everyone, > > I'll be taking a leave of absence from the tutor list for a while. I hope > to come back to tutor@python.org again, but I need to do some stuff first. > > Until then, happy hacking! > > Sincerely, > Danny Yoo > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor -- Visit the Useless Python Repository! http://www.lowerstandard.com/python/pythonsource.html From deirdre@deirdre.net Mon Jan 29 14:51:51 2001 From: deirdre@deirdre.net (Deirdre Saoirse) Date: Mon, 29 Jan 2001 06:51:51 -0800 (PST) Subject: [Tutor] See you later! In-Reply-To: <3A756789.7E475A3E@jam.rr.com> Message-ID: On Mon, 29 Jan 2001, R. A. wrote: > Thanks for everything, Danny! See ya next time. Agreed -- he's been very helpful while several of our other regulars (like myself) have been overcommitted. Thanks a great deal. _Deirdre From kalle@gnupung.net Mon Jan 29 15:21:08 2001 From: kalle@gnupung.net (Kalle Svensson) Date: Mon, 29 Jan 2001 16:21:08 +0100 Subject: [Tutor] See you later! In-Reply-To: ; from deirdre@deirdre.net on Mon, Jan 29, 2001 at 06:51:51AM -0800 References: <3A756789.7E475A3E@jam.rr.com> Message-ID: <20010129162108.A7574@father> --d6Gm4EdcadzBjdND Content-Type: text/plain; charset=us-ascii Content-Disposition: inline Content-Transfer-Encoding: quoted-printable Sez Deirdre Saoirse: > On Mon, 29 Jan 2001, R. A. wrote: >=20 > > Thanks for everything, Danny! See ya next time. >=20 > Agreed -- he's been very helpful while several of our other regulars (like > myself) have been overcommitted. Thanks a great deal. Me too, me too! Danny, you da man! Peace, Kalle --=20 Email: kalle@gnupung.net | You can tune a filesystem, but you Web: http://www.gnupung.net/ | can't tune a fish. -- man tunefs(8) PGP fingerprint: 0C56 B171 8159 327F 1824 F5DE 74D7 80D7 BF3B B1DD --d6Gm4EdcadzBjdND Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.4 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE6dYpkdNeA1787sd0RAlG1AJ9DiqQIDJkDnH9L39pjXxlSbLddJACgv4HD +3zDasE8sRQziicrIH2PFU8= =wFix -----END PGP SIGNATURE----- --d6Gm4EdcadzBjdND-- From alan.gauld@bt.com Mon Jan 29 15:22:47 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 29 Jan 2001 15:22:47 -0000 Subject: [Tutor] Error Message Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D53E@mbtlipnt02.btlabs.bt.co.uk> > can't quite seem to work around. This is my code: Hmmm, I think I recognise this :-) > > import msvcrt, sys > > print""" > Type a key to see its ASCII value. > Hit the space bar to end. > """ > > while 1: #1 is true, so loop forever > key = msvcrt.getch() > if key != ' ': > # handle special keys; real code is second > if (key == '\000') or (key == '\xe0'): > key = msvcrt.getch() > doKeyEvent(key) > else: > doQuitEvent(key) > > The code above calls doKeyEvent but you haven't defined it yet! > def doKeyEvent(key): > print ord(key) > > def doQuitEvent(key): > sys.exit() Move these two functions to the top of the file and it should work. I'll reword the tutorial page to make that clearer. lso note that in IDLE you get an infinite loop that you can't break out of (at least I do, and don't know why... I assume because IDLE is running within Tks loop...) So you need to run the program from a DOS prompt. Sorry about that, Alan G. > > After I save this and run it, Python replies with this: > > Type a key to see its ASCII value. > Hit the space bar to end. > > Traceback (innermost last): > File "C:/Program Files/Python20/Code/eventloop.py", line 14, in ? > doKeyEvent(key) > NameError: There is no variable named 'doKeyEvent' > > I'm stuck since doKeyEvent is a function, not a variable. Why > doesn't Python > recognize it as such? > > Thanks, > > Britt > _________________________________________________________________ > Get your FREE download of MSN Explorer at http://explorer.msn.com > > > From alan.gauld@bt.com Mon Jan 29 15:37:09 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 29 Jan 2001 15:37:09 -0000 Subject: [Tutor] (no subject) Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D53F@mbtlipnt02.btlabs.bt.co.uk> > On Sun, 28 Jan 2001, chastin cullifer wrote: > > > but i was wondering if it is possible to make a game with > python besides > > text adventures?? Sure. In my book I have a chapter on writing guessing games. Specifically Hangman but I also include code for Mastermind and ideas on how to implement Minesweeper and Rock,Paper, Scissors. I'm sure you can think of other examples. I'm planning on posting the source to hangman and mastermind on the 'useless python' website soon once I comment it suitably(in the book the 'comments' are in the text of course.... Alan G http://www.crosswinds.net/~agauld From alan.gauld@bt.com Mon Jan 29 15:41:46 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 29 Jan 2001 15:41:46 -0000 Subject: [Tutor] Upgraded to 2.0 Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D540@mbtlipnt02.btlabs.bt.co.uk> > to be able to right click and have the option of Edit with > Idle or Edit with Emacs. You could do it manually thru the explorer file options. Just create new actions for the .py/.pyw file types. Alan G. From alan.gauld@bt.com Mon Jan 29 15:48:30 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 29 Jan 2001 15:48:30 -0000 Subject: [Tutor] String Replace..... [octal numbers] Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D541@mbtlipnt02.btlabs.bt.co.uk> > That is, it has to do with "octal" numbers, that is, > numbers that are represented in terms of powers of 8's. > Python shows us the special characters (newlines, > tabs, etc.) in octal. To tell the truth, I'm not > quite sure why, but there's probably a good reason for it. The PDP computers that Unix was born on used octal for representing binary data. So Unix did the same. C was built to write Unix so used the same convention. Python is written in C and so followed C I guess. Accidents of history are all around. :-) Alan g From dsh8290@rit.edu Mon Jan 29 16:49:30 2001 From: dsh8290@rit.edu (D-Man) Date: Mon, 29 Jan 2001 11:49:30 -0500 Subject: [Tutor] Re: thank%s In-Reply-To: ; from dyoo@hkn.eecs.berkeley.edu on Fri, Jan 26, 2001 at 05:40:38PM -0800 References: <4.3.2.7.1.20010126120051.00b92430@operamail.com> Message-ID: <20010129114930.B16071@harmony.cs.rit.edu> On Fri, Jan 26, 2001 at 05:40:38PM -0800, Danny Yoo wrote: [snip] | Actually, you'd be surprised; it's a documented BUG that string | interpolation isn't explained! | | http://sourceforge.net/bugs/?func=detailbug&bug_id=121207&group_id=5470 | | The Python implementers forgot to explain how it works, so don't worry if | you can't find information on this stuff. I think that python's string interpolation is (nearly) the same as C's. It might be helpful to take a look at some C documentation on printf(). Then again, if you don't know C, the docs might be a bit too confusing. -D From alan.gauld@bt.com Mon Jan 29 17:37:07 2001 From: alan.gauld@bt.com (alan.gauld@bt.com) Date: Mon, 29 Jan 2001 17:37:07 -0000 Subject: [Tutor] practical uses for python Message-ID: <5104D4DBC598D211B5FE0000F8FE7EB20751D543@mbtlipnt02.btlabs.bt.co.uk> > Can someone tell me what some practical uses for > python are? Pretty much any kind of programming can be done in Python. The exceptions are easier to list than what you can do. There is a lot of info on this on the Python web site: http://www.python.org/doc/Intros.html Look at the high level intros and comparisons. > Mainly using python in the form of scripts > similar to perl. Thats probably the most common arena. > Is there anything on the net that I > look at to learn from? There are lots of things. The Red Hat Linux admin tools are written in Python. I believe Infoseek use it. Digital Creations Zope site has some success stories of web sites using Zope - which is written (partly) in Python and uses Pythonm as its scripting language. There is an open source drawing program written in Python. And much more. Try SourceForge and search for Python for current projects. Alan G. From michaelbaker@operamail.com Mon Jan 29 18:43:22 2001 From: michaelbaker@operamail.com (michaelbaker@operamail.com) Date: Mon, 29 Jan 2001 10:43:22 -0800 Subject: [Tutor] %string formatting FYI In-Reply-To: <20010127035106.0399EEA77@mail.python.org> Message-ID: <4.3.2.7.1.20010129104010.00b8da80@operamail.com> At 10:51 PM 1/26/01 -0500, you wrote: >Date: Fri, 26 Jan 2001 17:40:38 -0800 (PST) >From: Danny Yoo >To: michaelbaker@operamail.com >Cc: tutor@python.org >Subject: [Tutor] Re: thank%s > >On Fri, 26 Jan 2001 michaelbaker@operamail.com wrote: > > > thanks once again (this is not the first time you have helped me out). I > > almost looked at the Fancier Input/Output before sending to the list, > > although now that I have I'm not so sure I wouldn't have sent to the list > > anyway. I don't qutie follow this: > > > > >>> import string > > >>> for x in range(1,11): > > ... print '%2d %3d %4d' % (x, x*x, x*x*x) > > ... > > 1 1 1 > > 2 4 8 > > 3 9 27 > > 4 16 64 > > 5 25 125 > > 6 36 216 > > 7 49 343 > > 8 64 512 > > 9 81 729 > > 10 100 1000 > > > > %2d, %3d, %4d ??????????? > > >Actually, you'd be surprised; it's a documented BUG that string >interpolation isn't explained! > >http://sourceforge.net/bugs/?func=detailbug&bug_id=121207&group_id=5470 > >The Python implementers forgot to explain how it works, so don't worry if >you can't find information on this stuff. I found some info on pp. 40 of 'Learning Python' by O'Reilly - they call it string formatting. pp.41 includes formatting codes and the 'string' module. From budgester@budgester.com Mon Jan 29 15:12:21 2001 From: budgester@budgester.com (Budgester) Date: Mon, 29 Jan 2001 15:12:21 -0000 Subject: [Tutor] String Replace..... In-Reply-To: <14293F11423@kserver.org> Message-ID: <000601c08a2c$d5de1770$0300000a@budgester> Thanks for all your help, I've now got it working, so my little project to write a diary updater with a Tkinter interface is well on its way, I'll be sending the finished script to Rob Andrews for inclusion on his useless python page when its done. Thanks again everyone Budgester From facelle@tiscalinet.it Mon Jan 29 21:39:28 2001 From: facelle@tiscalinet.it (Fabrizio) Date: Mon, 29 Jan 2001 22:39:28 +0100 Subject: [Tutor] Word count help Message-ID: <001b01c08a3c$0761e1a0$f9230b3e@oemcomputer> Hello, I am a newbie and I am trying to write a simple program that counts how many times each word in a text file appears in the text itself. It reads a line from file, converts it into a list, then counts it saving results to be added to those of next lines. The program returns two list: one contains the all the words that appears in the text, and the second one contains the associated frequencies of each word. See the attached script (I hope there are not mistakes, since I cut & pasted it and translated all function and variable names etc. from Italian... ). It seems to work fine, but it is very slow, and when working on large .txt files (500 Kb or more) it takes several hours (!) to finish. Is there any way to improve it and making it faster ? Thanks in advance, Fabrizio C. ----------------- class TextProcess : [......] def Wordcount (self, testo, tablett, freq): import string dic =[] for r in testo: if tablett.count(r)== 0 : tablett.append(r) k = testo.count(r) freq.append(k) dic.append(r) else : ind = tablett.index (r) if dic.count(r)== 0: k = testo.count (r) freq [ind] = freq[ind] + k dic.append(r) return tablett, freq #------------------------- class WordProcess(TextProcess): def operate (self, testo, tablett1, freq1): [....] tablett, freq = self.Wordcount(testo, tablett1, freq1) return tablett, freq #-------------------------- def ContaParole(self, event): tablett1, freq1, tablett2, freq2 =[], [], [],[] testo = open('text.txt, 'r') import string object = WordProcess() [.....] for text in testo.readlines(): par = string.split(text) tablett1, freq1 = object.operate(par, tablett2, freq2) file.close() From lumbricus@gmx.net Mon Jan 29 22:46:25 2001 From: lumbricus@gmx.net (=?ISO-8859-1?Q?J=F6rg_W=F6lke?=) Date: Mon, 29 Jan 2001 23:46:25 +0100 (MET) Subject: [Tutor] String Replace..... [octal numbers] References: <5104D4DBC598D211B5FE0000F8FE7EB20751D541@mbtlipnt02.btlabs.bt.co.uk> Message-ID: <1274.980808385@www23.gmx.net> > The PDP computers that Unix was born on used octal > for representing binary data. So Unix did the same. > C was built to write Unix so used the same convention. > Python is written in C and so followed C I guess. > > Accidents of history are all around. :-) > > Alan g > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor There's a practical reason: octal and hexadecimal numbers are easily translated to binary numbers and vice versa. you take your binary number, take four (hexa)/three(octal) digits and translate them and you get the right hexa/octal number right away. cuz computers can handle bin-nums for technical reasons only, it is easyer to take hex or oct nums instead of decimals. right? greets jö! -- Sent through GMX FreeMail - http://www.gmx.net From AquaRock7@aol.com Tue Jan 30 01:08:02 2001 From: AquaRock7@aol.com (AquaRock7@aol.com) Date: Mon, 29 Jan 2001 20:08:02 EST Subject: [Tutor] Newbie!! many questions Message-ID: <3b.fbc8bd3.27a76df2@aol.com> --part1_3b.fbc8bd3.27a76df2_boundary Content-Type: text/plain; charset="US-ASCII" Content-Transfer-Encoding: 7bit !). There is a way to define and call functions in Python, but is there a way to define and call a subroutine? Or a way to jump to another line of code? i.e.: n = input("Type a number: ") if n > 0: GOTO negativemsg elif n < 0: GOTO posativemsg else: GOTO zeromsg negativemsg: print "Negative" positivemsg: print "Positive" zeromsg: print "Zero" so I dont have to write repeated code over and over... 2). sys.stdout and sys.stdin what are they!? ok, sys.stdout is where the print statement goes... so how can I use that to my advantage? How can I manip[ulate this to my advantage? 3). Is there a graphics library for Python? To go along with the thread about making games in Python... Not games that use OS-like grpahics, like Tk... Like commercial games with grpahics lilke that. Like so you can plot a pixel on the screen at coordinate x,y, color=red. Microsoft QBasic did that (my first programming language(i know its obsolete, but its great for beginners)). Or locate text anywhere besides the next line down. Maybe there is a way to use DirectX with python? 4). making executables... so I can run it without Python installed! How? Someone posted about Freeze... I never heard of that, would someone care to explain? Is that what I am looking for? Thank you, ~Dustin --part1_3b.fbc8bd3.27a76df2_boundary Content-Type: text/html; charset="US-ASCII" Content-Transfer-Encoding: 7bit !).  There is a way to define and call functions in Python, but is there a
    way to define and call a subroutine?  Or a way to jump to another line of
    code? i.e.:

    n = input("Type a number: ")
    if n > 0:
          GOTO negativemsg
    elif n < 0:
          GOTO posativemsg
    else:
          GOTO zeromsg

    negativemsg: print "Negative"
    positivemsg: print "Positive"
    zeromsg: print "Zero"

    so I dont have to write repeated code over and over...

    2).  sys.stdout and sys.stdin
          what are they!?  ok, sys.stdout is where the print statement goes...
    so how can I use that to my advantage?  How can I manip[ulate this to my
    advantage?

    3).  Is there a graphics library for Python?  To go along with the thread
    about making games in Python... Not games that use OS-like grpahics, like
    Tk... Like commercial games with grpahics lilke that.  Like so you can plot a
    pixel on the screen at coordinate x,y, color=red.  Microsoft QBasic did that
    (my first programming language(i know its obsolete, but its great for
    beginners)).  Or locate text anywhere besides the next line down.  Maybe
    there is a way to use DirectX with python?

    4).  making executables... so I can run it without Python installed!  How?  
    Someone posted about Freeze... I never heard of that, would someone care to
    explain?  Is that what I am looking for?

    Thank you, ~Dustin
    --part1_3b.fbc8bd3.27a76df2_boundary-- From deirdre@deirdre.net Tue Jan 30 01:15:28 2001 From: deirdre@deirdre.net (Deirdre Saoirse) Date: Mon, 29 Jan 2001 17:15:28 -0800 (PST) Subject: [Tutor] Newbie!! many questions In-Reply-To: <3b.fbc8bd3.27a76df2@aol.com> Message-ID: On Mon, 29 Jan 2001 AquaRock7@aol.com wrote: > !). There is a way to define and call functions in Python, but is > there a way to define and call a subroutine? Or a way to jump to > another line of code? i.e.: def negativemsg(): print "this number is negative" Get out of the habit of thinking GOTO. > n = input("Type a number: ") > if n > 0: > GOTO negativemsg From htb@4dvision.net Tue Jan 30 02:18:49 2001 From: htb@4dvision.net (htb) Date: Mon, 29 Jan 2001 19:18:49 -0700 Subject: [Tutor] graphing and other forms of data presentation In-Reply-To: <20010129120601.CDF4AEF0A@mail.python.org> Message-ID: <000001c08a62$fc5c2820$02000101@dharma.org> Hi folks- I've written a very simple prog to generate cell growth data from observable counts. Eventually, I want to use this as a framework for a more complex program, but this is my first intro into python so I'm trying to keep it simple for now. My question- is there a convenient method to plot graphical data (e.g. XY data, or even waveform) using Tkinter, or is it easier to output into something like gnuplot? How would either of these solutions be implemented given a structure of data? thanks, htb htb@4dvision.net From rwilkins@bigpond.net.au Tue Jan 30 04:57:46 2001 From: rwilkins@bigpond.net.au (Richard Wilkins) Date: Tue, 30 Jan 2001 12:57:46 +0800 Subject: [Tutor] Bits 'n' fonts Message-ID: Hi folks, I'm fiddling with PyOpenGL. I was wondering if in Python there is a simple way to create a bitfield from a character...say with an existing function... Any help will be greatly appreciated! Andrew Wilkins From wheelege@tsn.cc Tue Jan 30 05:08:54 2001 From: wheelege@tsn.cc (Glen Wheeler) Date: Tue, 30 Jan 2001 16:08:54 +1100 Subject: [Tutor] See you later! References: Message-ID: <00ff01c08a7a$be943100$a410fea9@glen> Cya, thanks for all the help! ----- Original Message ----- From: Danny Yoo To: Sent: Monday, January 29, 2001 7:08 PM Subject: [Tutor] See you later! > Hiya everyone, > > I'll be taking a leave of absence from the tutor list for a while. I hope > to come back to tutor@python.org again, but I need to do some stuff first. > > Until then, happy hacking! > > Sincerely, > Danny Yoo > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From wheelege@tsn.cc Tue Jan 30 05:18:07 2001 From: wheelege@tsn.cc (Glen Wheeler) Date: Tue, 30 Jan 2001 16:18:07 +1100 Subject: [Tutor] graphing and other forms of data presentation References: <000001c08a62$fc5c2820$02000101@dharma.org> Message-ID: <015201c08a7c$09d362c0$a410fea9@glen> Hi htb, I think a canvas might suit your needs - look at the canvas class for Tkinter. I'm making a little arkanoid game using a canvas as a playing field - so I am almost certain a graph would be feasible using this medium. Glen. ----- Original Message ----- From: htb To: Sent: Tuesday, January 30, 2001 1:18 PM Subject: [Tutor] graphing and other forms of data presentation > > > Hi folks- > > I've written a very simple prog to generate cell growth data from observable > counts. Eventually, I want to use this as a framework for a more complex > program, but this is my first intro into python so I'm trying to keep it > simple for now. > > My question- is there a convenient method to plot graphical data (e.g. XY > data, or even waveform) using Tkinter, or is it easier to output into > something like gnuplot? How would either of these solutions be implemented > given a structure of data? > > thanks, > htb > htb@4dvision.net > > > _______________________________________________ > Tutor maillist - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor From NHYTRO@compuserve.com Tue Jan 30 07:42:49 2001 From: NHYTRO@compuserve.com (Sharriff Aina) Date: Tue, 30 Jan 2001 02:42:49 -0500 Subject: [Tutor] CGI output when reading HTML file Message-ID: <200101300243_MC2-C396-9186@compuserve.com> Hi guys! I=B4m creating HTML from an online HTML editor, my CGI script saves the H= TML code to a directory on the Server. My problem is, I can=B4t get my CGI co= de to read and then send (print) the HTML to the client. My code: #!C:/Python/python.exe -u print "Content-Type: text/html\n\n" import cgi import webbrowser # # form =3D cgi.FieldStorage() print "saving html to file..." htmlfile =3D open("./webpages/tester.html", "w") htmlfile.write(form["editarea"].value) #test =3D htmlfile.readlines() #print test does not print HTML to client!! print "test file output..." # the below line just display the HTML on the WEBserver machine, not the client webbrowser.open("./webpages/tester.html") I=B4d really appreciate any ideas as to going about this Regards Sharriff From NHYTRO@compuserve.com Tue Jan 30 13:40:29 2001 From: NHYTRO@compuserve.com (Sharriff Aina) Date: Tue, 30 Jan 2001 08:40:29 -0500 Subject: [Tutor] "replace" in String module Message-ID: <200101300840_MC2-C39D-51B9@compuserve.com> Hi Guys! Why does this fail? >>> import string >>> test =3D " the line " >>> string.find(test, "") 0 >>> string.replace(test, "", "") ' the line ' >>> = I would have thought that the "" would have been left untouched. regards Sharriff From Lindsay.Davies@moonshine.co.uk Tue Jan 30 13:59:48 2001 From: Lindsay.Davies@moonshine.co.uk (Lindsay Davies) Date: Tue, 30 Jan 2001 13:59:48 +0000 Subject: [Tutor] "replace" in String module In-Reply-To: <200101300840_MC2-C39D-51B9@compuserve.com> References: <200101300840_MC2-C39D-51B9@compuserve.com> Message-ID: Try... string.replace(test,"", "") The parameters are (str, old, new, [maxsplit]). You will also probably want to investigate the re module some time soon. Best wishes, Lindsay On 1/30/01, Sharriff Aina wrote about '[Tutor] "replace" in String module': >Hi Guys! > >Why does this fail? > >>>> import string >>>> test = " the line " >>>> string.find(test, "") >0 > >>> string.replace(test, "", "") >' the line ' >>>> > >I would have thought that the "" would have been left untouched. > > >regards > >Sharriff > >_______________________________________________ >Tutor maillist - Tutor@python.org >http://mail.python.org/mailman/listinfo/tutor From darrell@brogdon.net Tue Jan 30 16:08:59 2001 From: darrell@brogdon.net (Darrell Brogdon) Date: Tue, 30 Jan 2001 11:08:59 -0500 Subject: [Tutor] PostgreSQL and Python Message-ID: <3A76E71B.20002@brogdon.net> Where can I find info on talking to a PostgreSQL database with Python? -- Darrell Brogdon http://darrell.brogdon.net From martok@mattsmail.com Tue Jan 30 18:10:20 2001 From: martok@mattsmail.com (Matthias Hager) Date: Tue, 30 Jan 2001 10:10:20 -0800 Subject: [Tutor] Hard drive searching Message-ID: <200101301010.AA183107902@mail.mattsmail.com> I've been thinking about this for awhile, but can't figure anything out. What I need my python program to do is, go through my hard drive, as quickly as possible, and return all the files that end with a certain extension(like .html or .py). How could I do this? Thanks in advance Matthias -- Programming isn't cool, it's awesome. %%%################?????????###################^^^ martok@mattsmail.com http://mymymatthias.tripod.com/ %%%################????????####################^^^ -- Like my email address? Get your own for FREE at http://firstname.com Get you@JohnsMail.com or you@AlexsMail.com or pick from 500 more! From rmallett@rational.com Tue Jan 30 18:23:37 2001 From: rmallett@rational.com (Mallett, Roger) Date: Tue, 30 Jan 2001 10:23:37 -0800 Subject: [Tutor] Attempt to download web page failed due to use of Frames Message-ID: <78D9B26221DBD411B7EE00D0B73EB0EA71903E@CUPEX2> Using Python, I attempted to download a web page that contains frames. I received a message from the web site that my browser (which in this case, is the Python script below) doesn't support frames. What can I do to get all of the information that would normally display in my I.E. browser when frames are involved? Script Used: >>> import urllib >>> f=urllib.urlopen('http://www.transitionstrading.com/Quotespage.htm') >>> x=f.read() >>> x The value of "x" included the following: ...\015\012 <body>\015\012 <p>This page uses frames, but your browser doesn\'t support them.</p>\015\012 </body>\015\012 \015\012\015\012\015\012' >>> I greatly appreciate any assistance that you can provide, Roger Mallett From amoreira@mercury.ubi.pt Tue Jan 30 18:20:52 2001 From: amoreira@mercury.ubi.pt (Jose Amoreira) Date: Tue, 30 Jan 2001 18:20:52 +0000 Subject: [Tutor] Word count help References: <001b01c08a3c$0761e1a0$f9230b3e@oemcomputer> Message-ID: <3A770604.28E1E2E9@mercury.ubi.pt> Hello! I haven't really understood everything in your code, so maybe I'll be talking nonsense. Anyway, IMHO, your code can be made more readable if you use one dictionary instead of two lists. I'm not certain that it gets any faster, but using dictionaries, I'd code function Wordcount like this: #---------------------------- def Wordcount(testo,freqs): # freqs is a dictionary with words as keys and their frequencies as # values; testo is a part of the input file(I'm trying to keep your code # structure, but removed the OO because I didn't understand it for word in test.split(): if word in freqs.keys(): freqs[word] += 1 else: freqs[word] = 1 return freqs #---------------------------- But I really don't like this coming and going back and forth with the freqs dictionary, or, in your code, with the two lists tablett and freq. I'd rather open the file in the very function that computes the frequencies, or else send that function the hole text at once, instead of constantly updating the counting with partial results from each line stored in the string testo. Another possible thing to watch is that if you want to open big files it is probabbly better not to read the hole file at once using readlines. Instead, use readline() method wich reads one line at a time. This doesn't neccesarily mean more time because if you are short on memory, reading the file at once may force the computer to use virtual memory (disk) wich is a lot slower. Once again, I don't know if using dictionaries makes the code faster for large files. It probably won't. But you must take into account that a 500Kb contains quite a lot of words. As it runs, the code must store a few thousand words and, for each new word read, must make *a lot* of checks to see if it has already been entered in the lists, or dictionary, or whatever. My opinion is that this is a lot of work even for a fast computer, and python is not (and it doesn't pretend to be) a fully compiled language like C/C++ or fortran... I hope this helps! So long Ze Amoreira From kalle@gnupung.net Tue Jan 30 19:36:56 2001 From: kalle@gnupung.net (Kalle Svensson) Date: Tue, 30 Jan 2001 20:36:56 +0100 Subject: [Tutor] Attempt to download web page failed due to use of Frames In-Reply-To: <78D9B26221DBD411B7EE00D0B73EB0EA71903E@CUPEX2>; from rmallett@rational.com on Tue, Jan 30, 2001 at 10:23:37AM -0800 References: <78D9B26221DBD411B7EE00D0B73EB0EA71903E@CUPEX2> Message-ID: <20010130203656.A441@apone.network.loc> --huq684BweRXVnRxX Content-Type: text/plain; charset=iso-8859-1 Content-Disposition: inline Content-Transfer-Encoding: quoted-printable Sez Mallett, Roger: > Using Python, I attempted to download a web page that contains frames. I > received a message from the web site that my browser (which in this case,= is > the Python script below) doesn't support frames. What can I do to get a= ll > of the information that would normally display in my I.E. browser when > frames are involved? You will have to fetch the page, parse it to get the URLs of the subpages and fetch them. There should be a few tags that contain the addresses you are interested in. > Script Used: >=20 > >>> import urllib > >>> f=3Durllib.urlopen('http://www.transitionstrading.com/Quotespage.htm') > >>> x=3Df.read() >>> print x Quotes [...] These two lines are the ones you are interested in. One possible regexp to match the src attribute is: r =3D re.compile(r']*src=3D"([^"]*)"[^>]*>') Then, you can find all frames by looping: start =3D 0 frames =3D {} while 1: m =3D r.search(x) if not m: break frames[m.group(1)] =3D "" start =3D m.start(1) Then, you'll have to get the frame contents. for f in frames.keys(): # this is extremely crude. if f[:4] =3D=3D "http": frames[f] =3D urllib.urlopen(f).read() else: frames[f] =3D urllib.urlopen("http://www.transitionstrading.com/" + f).read()=20 The whole thing, untested: import urllib, re f =3D urllib.urlopen('http://www.transitionstrading.com/Quotespage.htm') x =3D f.read() f.close() # yeah, why not... r =3D re.compile(r']*src=3D"([^"]*)"[^>]*>') start =3D 0 frames =3D {} while 1: m =3D r.search(x) if not m: break frames[m.group(1)] =3D "" start =3D m.start(1) for f in frames.keys(): # this is extremely crude. if f[:4] =3D=3D "http": frames[f] =3D urllib.urlopen(f).read() else: frames[f] =3D urllib.urlopen("http://www.transitionstrading.com/" + f).read() There are other ways, this is just a beginning. HTH, Kalle --=20 Email: kalle@gnupung.net | You can tune a filesystem, but you Web: http://www.gnupung.net/ | can't tune a fish. -- man tunefs(8) PGP fingerprint: 0C56 B171 8159 327F 1824 F5DE 74D7 80D7 BF3B B1DD --huq684BweRXVnRxX Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.4 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE6dxfYdNeA1787sd0RArVmAJ0QkTQwTv0Osgs39dIKnKD8dODVxACgile4 IgNXUCFV14COBqQCUrzKjjg= =BNYz -----END PGP SIGNATURE----- --huq684BweRXVnRxX-- From kalle@gnupung.net Tue Jan 30 19:46:13 2001 From: kalle@gnupung.net (Kalle Svensson) Date: Tue, 30 Jan 2001 20:46:13 +0100 Subject: [Tutor] Hard drive searching In-Reply-To: <200101301010.AA183107902@mail.mattsmail.com>; from martok@mattsmail.com on Tue, Jan 30, 2001 at 10:10:20AM -0800 References: <200101301010.AA183107902@mail.mattsmail.com> Message-ID: <20010130204613.C441@apone.network.loc> --XOIedfhf+7KOe/yw Content-Type: text/plain; charset=iso-8859-1 Content-Disposition: inline Content-Transfer-Encoding: quoted-printable Sez Matthias Hager: > I've been thinking about this for awhile, but can't figure anything out. > What I need my python program to do is, go through my hard drive, as > quickly as possible, and return all the files that end with a certain > extension(like .html or .py). How could I do this? =20 You might want to look at os.path.walk(). Otherwise, I have no great ideas at this time. Peace, Kalle --=20 Email: kalle@gnupung.net | You can tune a filesystem, but you Web: http://www.gnupung.net/ | can't tune a fish. -- man tunefs(8) PGP fingerprint: 0C56 B171 8159 327F 1824 F5DE 74D7 80D7 BF3B B1DD --XOIedfhf+7KOe/yw Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.4 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE6dxoFdNeA1787sd0RAkgSAKCm3gCTh3D/Jh7bnCF0marGkkJocACfbCxE X2gqqYXnerDYumGR/G2A310= =RFzh -----END PGP SIGNATURE----- --XOIedfhf+7KOe/yw-- From kalle@gnupung.net Tue Jan 30 19:47:45 2001 From: kalle@gnupung.net (Kalle Svensson) Date: Tue, 30 Jan 2001 20:47:45 +0100 Subject: [Tutor] PostgreSQL and Python In-Reply-To: <3A76E71B.20002@brogdon.net>; from darrell@brogdon.net on Tue, Jan 30, 2001 at 11:08:59AM -0500 References: <3A76E71B.20002@brogdon.net> Message-ID: <20010130204745.D441@apone.network.loc> --vOmOzSkFvhd7u8Ms Content-Type: text/plain; charset=iso-8859-1 Content-Disposition: inline Content-Transfer-Encoding: quoted-printable Sez Darrell Brogdon: > Where can I find info on talking to a PostgreSQL database with Python? Try these: http://www.python.org/topics/database/ http://www.druid.net/pygresql/ Peace, Kalle --=20 Email: kalle@gnupung.net | You can tune a filesystem, but you Web: http://www.gnupung.net/ | can't tune a fish. -- man tunefs(8) PGP fingerprint: 0C56 B171 8159 327F 1824 F5DE 74D7 80D7 BF3B B1DD --vOmOzSkFvhd7u8Ms Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.4 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE6dxphdNeA1787sd0RAtDTAJ9+GO6XlJd/jAgOQJgfHk1ASHmt9ACfYPbM L9mrp6zT0DBGCFs67qDqZ8w= =yyuG -----END PGP SIGNATURE----- --vOmOzSkFvhd7u8Ms-- From kalle@gnupung.net Tue Jan 30 19:59:07 2001 From: kalle@gnupung.net (Kalle Svensson) Date: Tue, 30 Jan 2001 20:59:07 +0100 Subject: [Tutor] Newbie!! many questions In-Reply-To: <3b.fbc8bd3.27a76df2@aol.com>; from AquaRock7@aol.com on Mon, Jan 29, 2001 at 08:08:02PM -0500 References: <3b.fbc8bd3.27a76df2@aol.com> Message-ID: <20010130205907.E441@apone.network.loc> --uxuisgdDHaNETlh8 Content-Type: text/plain; charset=iso-8859-1 Content-Disposition: inline Content-Transfer-Encoding: quoted-printable Sez AquaRock7@aol.com: > !). There is a way to define and call functions in Python, but is there = a=20 > way to define and call a subroutine? Or a way to jump to another line of= =20 > code? i.e.: Ummm... You lost me there. What's the difference? > 2). sys.stdout and sys.stdin > what are they!? ok, sys.stdout is where the print statement goes.= ..=20 > so how can I use that to my advantage? How can I manip[ulate this to my= =20 > advantage? Note that sys.stdin, sys.stdout and sys.stderr are file objects. Thus, it's easier to change where your output goes. msg =3D "Hello, file world!" fname =3D raw_input("Where should I print the message? ") if fname in ["", "-", "stdout"]: sys.stdout.write(msg) else: open(fname).write(msg) > 3). Is there a graphics library for Python? To go along with the thread= =20 > about making games in Python... Not games that use OS-like grpahics, like= =20 > Tk... Like commercial games with grpahics lilke that. Like so you can pl= ot a=20 > pixel on the screen at coordinate x,y, color=3Dred. Microsoft QBasic did= that=20 > (my first programming language(i know its obsolete, but its great for=20 > beginners)). Or locate text anywhere besides the next line down. Maybe= =20 > there is a way to use DirectX with python? Check out pygame (http://pygame.seul.org/). > 4). making executables... so I can run it without Python installed! How= ? =20 > Someone posted about Freeze... I never heard of that, would someone care = to=20 > explain? Is that what I am looking for? There are a couple of ways. None is really nice, but if you really want to, it's possible. IIRC, there should be some kind of link on the pygame site. I always force my friends to install python... HTH, Kalle --=20 Email: kalle@gnupung.net | You can tune a filesystem, but you Web: http://www.gnupung.net/ | can't tune a fish. -- man tunefs(8) PGP fingerprint: 0C56 B171 8159 327F 1824 F5DE 74D7 80D7 BF3B B1DD --uxuisgdDHaNETlh8 Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.4 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE6dx0LdNeA1787sd0RAnS1AKCHV6WjY0oYNruXjl85z7JZ4zZT1gCgqIYP 9gmxn5UcoQ9AXmyIq8QwtSY= =ZwzT -----END PGP SIGNATURE----- --uxuisgdDHaNETlh8-- From DOUGS@oceanic.com Tue Jan 30 19:55:44 2001 From: DOUGS@oceanic.com (Doug Stanfield) Date: Tue, 30 Jan 2001 09:55:44 -1000 Subject: [Tutor] Hard drive searching Message-ID: <8457258D741DD411BD3D0050DA62365907A59C@huina.oceanic.com> You might find that the best way is to let the operating system do the hard work. It is usually optimised to do things like this. You can then use Python to deal with the results of the search. How would you do this task if you were at a command prompt. On a Linux system I'd do something with 'locate' or 'find'. To use that in Python look into the os.popen (http://www.python.org/doc/current/lib/os-newstreams.html#l2h-907) or os.spawnv (http://www.python.org/doc/current/lib/os-process.html#l2h-995) functions. If you're on windows, popen in particular only works reliably with Python 2.0 or better. HTH -Doug- > -----Original Message----- > From: Kalle Svensson [mailto:kalle@gnupung.net] > Sent: Tuesday, January 30, 2001 9:46 AM > To: Matthias Hager > Cc: tutor@python.org > Subject: Re: [Tutor] Hard drive searching > > > Sez Matthias Hager: > > I've been thinking about this for awhile, but can't figure > anything out. > > What I need my python program to do is, go through my hard drive, as > > quickly as possible, and return all the files that end with > a certain > > extension(like .html or .py). How could I do this? > > You might want to look at os.path.walk(). Otherwise, I have > no great ideas > at this time. > > Peace, > Kalle > -- > Email: kalle@gnupung.net | You can tune a filesystem, but you > Web: http://www.gnupung.net/ | can't tune a fish. -- man tunefs(8) > PGP fingerprint: 0C56 B171 8159 327F 1824 F5DE 74D7 80D7 BF3B B1DD > From bsass@freenet.edmonton.ab.ca Tue Jan 30 19:58:58 2001 From: bsass@freenet.edmonton.ab.ca (Bruce Sass) Date: Tue, 30 Jan 2001 12:58:58 -0700 (MST) Subject: [Tutor] Hard drive searching In-Reply-To: <200101301010.AA183107902@mail.mattsmail.com> Message-ID: Hi, > I've been thinking about this for awhile, but can't figure anything out. What I need my python program to do is, go through my hard drive, as quickly as possible, and return all the files that end with a certain extension(like .html or .py). How could I do this? If the Python glob module doesn't do it for you... I wouldn't do it. Python is just too slow for that kinda thing, IMHO. It may work ok on a modern system, but if someone tries it on an old/slow box it will be excruciating. This is what I would do with my old/slow Linux box... os.system("updatedb") # only if running as the superuser os.system("locate .ext > list-of-files-with-.ext-in-their-path") potential_files_of_type_ext = open("list-of-files...their-path", "r") "updatedb" updates the system's database of files, only really useful to the superuser in this case because only the superuser can see the entire system. "locate .ext" spits out very path that includes ".ext" somewhere in it, the results would need to be filtered through a regex. The unix "find" command would be better, but its use is more version dependent (a PITA to make portable). ">" redirects stdout to a file. How would this be done on a Windows, Mac, ...? Are there any collections of code snippets that compare the various ways of doing, in a Python program, the stuff that is best left to the native OS/kernel? later, Bruce From kalle@gnupung.net Tue Jan 30 20:18:44 2001 From: kalle@gnupung.net (Kalle Svensson) Date: Tue, 30 Jan 2001 21:18:44 +0100 Subject: [Tutor] Word count help In-Reply-To: <3A770604.28E1E2E9@mercury.ubi.pt>; from amoreira@mercury.ubi.pt on Tue, Jan 30, 2001 at 06:20:52PM +0000 References: <001b01c08a3c$0761e1a0$f9230b3e@oemcomputer> <3A770604.28E1E2E9@mercury.ubi.pt> Message-ID: <20010130211844.F441@apone.network.loc> --9crTWz/Z+Zyzu20v Content-Type: text/plain; charset=iso-8859-1 Content-Disposition: inline Content-Transfer-Encoding: quoted-printable Hi. Just a minor note... Sez Jose Amoreira: > #---------------------------- > def Wordcount(testo,freqs): > # freqs is a dictionary with words as keys and their frequencies as > # values; testo is a part of the input file(I'm trying to keep your c= ode > # structure, but removed the OO because I didn't understand it > for word in test.split(): > if word in freqs.keys(): Shouldn't this be if freqs.has_key(word): ? IIRC, dict.keys() and if x in list are both linear time. dict.has_key() is constant time. I repeat, IIRC. And somebody might have optimized i= t. Peace, Kalle --=20 Email: kalle@gnupung.net | You can tune a filesystem, but you Web: http://www.gnupung.net/ | can't tune a fish. -- man tunefs(8) PGP fingerprint: 0C56 B171 8159 327F 1824 F5DE 74D7 80D7 BF3B B1DD --9crTWz/Z+Zyzu20v Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.4 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE6dyGkdNeA1787sd0RAtTrAJ0VkcNebp1jbtyJGOBMflglzMYZRwCffx55 lYOimo1Xvzk9Ilmc/6MSOWQ= =T9uM -----END PGP SIGNATURE----- --9crTWz/Z+Zyzu20v-- From Lindsay.Davies@moonshine.co.uk Tue Jan 30 20:32:38 2001 From: Lindsay.Davies@moonshine.co.uk (Lindsay Davies) Date: Tue, 30 Jan 2001 20:32:38 +0000 Subject: [Tutor] Hard drive searching In-Reply-To: <200101301010.AA183107902@mail.mattsmail.com> References: <200101301010.AA183107902@mail.mattsmail.com> Message-ID: On 1/30/01, Matthias Hager wrote about '[Tutor] Hard drive searching': >I've been thinking about this for awhile, but can't figure anything >out. What I need my python program to do is, go through my hard >drive, as quickly as possible, and return all the files that end >with a certain extension(like .html or .py). How could I do this? Not necessarily elegant, but this should give you the idea... Best wishes, Lindsay def fish(suffix_list, dir, file_list): for file in file_list: for suffix in suffix_list: if string.rfind(file, suffix) >= 0: print dir + file import os, string args = ['.html', '.py'] os.path.walk("", fish, args) From kalle@gnupung.net Tue Jan 30 21:28:43 2001 From: kalle@gnupung.net (Kalle Svensson) Date: Tue, 30 Jan 2001 22:28:43 +0100 Subject: [Tutor] Attempt to download web page failed due to use of Frames In-Reply-To: <20010130203656.A441@apone.network.loc>; from kalle@gnupung.net on Tue, Jan 30, 2001 at 08:36:56PM +0100 References: <78D9B26221DBD411B7EE00D0B73EB0EA71903E@CUPEX2> <20010130203656.A441@apone.network.loc> Message-ID: <20010130222842.B1066@apone.network.loc> --cvVnyQ+4j833TQvp Content-Type: text/plain; charset=iso-8859-1 Content-Disposition: inline Content-Transfer-Encoding: quoted-printable Sez I: > start =3D 0 > frames =3D {} >=20 > while 1: > m =3D r.search(x) This should have been m =3D r.search(x, start) Ooops... > if not m: > break > frames[m.group(1)] =3D "" > start =3D m.start(1) Anyway, the whole loop thing could have been avoided if I hade read the docs... ms =3D r.findall(x) for m in ms: frames[m] =3D "" would have been better... Peace, Kalle -- Email: kalle@gnupung.net | You can tune a filesystem, but you Web: http://www.gnupung.net/ | can't tune a fish. -- man tunefs(8) PGP fingerprint: 0C56 B171 8159 327F 1824 F5DE 74D7 80D7 BF3B B1DD --cvVnyQ+4j833TQvp Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.4 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE6dzIKdNeA1787sd0RAhgpAJ4jTxIwh+tji3lkD2OwQTfIfECAtQCgvaOw A/pzw0VW7E1WzcACQ26e+lI= =+YI7 -----END PGP SIGNATURE----- --cvVnyQ+4j833TQvp-- From bseelinger@neteffectcorp.com Tue Jan 30 21:49:49 2001 From: bseelinger@neteffectcorp.com (Seelinger, Bruce) Date: Tue, 30 Jan 2001 16:49:49 -0500 Subject: [Tutor] Unpacking a Tuple - Can It Be Done with a CSV Line? Message-ID: <958398973B4A0343A904C2A4157EDEA54FDCDB@ATLEXC01.neteffect.neteffectcorp.com> This message is in MIME format. Since your mail reader does not understand this format, some or all of this message may not be legible. ------_=_NextPart_001_01C08B06.919E7700 Content-Type: text/plain; charset="iso-8859-1" Hello, I am writing a script which opens a file which consists of comma separated entries similar to the example below: value1, value2, value3, value4, etc. etc. The above line is read and assigned to a variable. At that point I was hoping it could be treated as a tuple or sequence of values. Unfortunately, the variable treats the entire line as a single string instead of separate values between the commas. Is there any way to have the line act as a tuple which can be unpacked? Essentially, I want to extract values from a comma separated list of values from each line. I am relatively new to Python and the only other language I have extensive programming with is VMS's DCL. Can anyone help? Thanks in advance for any help! Regards, Bruce Seelinger ------_=_NextPart_001_01C08B06.919E7700 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Unpacking a Tuple - Can It Be Done with a CSV Line?

    Hello,

    I am writing a script which opens a = file which consists of comma separated entries similar to the example = below:

    value1, value2, value3, value4,  = etc. etc.

    The above line is read and assigned to = a variable.  At that point I was hoping it could be treated as a = tuple or sequence of values.  Unfortunately, the variable treats = the entire line as a single string instead of separate values between = the commas.  Is there any way to have the line act as a tuple = which can be unpacked?  Essentially, I want to extract values from = a comma separated list of values from each line.

    I am relatively new to Python and the = only other language I have extensive programming with is VMS's = DCL.

    Can anyone help?

    Thanks in advance for any help!

    Regards,

    Bruce Seelinger

    ------_=_NextPart_001_01C08B06.919E7700-- From kalle@gnupung.net Tue Jan 30 22:13:14 2001 From: kalle@gnupung.net (Kalle Svensson) Date: Tue, 30 Jan 2001 23:13:14 +0100 Subject: [Tutor] Unpacking a Tuple - Can It Be Done with a CSV Line? In-Reply-To: <958398973B4A0343A904C2A4157EDEA54FDCDB@ATLEXC01.neteffect.neteffectcorp.com>; from bseelinger@neteffectcorp.com on Tue, Jan 30, 2001 at 04:49:49PM -0500 References: <958398973B4A0343A904C2A4157EDEA54FDCDB@ATLEXC01.neteffect.neteffectcorp.com> Message-ID: <20010130231314.D1066@apone.network.loc> --zS7rBR6csb6tI2e1 Content-Type: text/plain; charset=iso-8859-1 Content-Disposition: inline Content-Transfer-Encoding: quoted-printable Sez Seelinger, Bruce: > Hello, >=20 > I am writing a script which opens a file which consists of comma separated > entries similar to the example below: >=20 > value1, value2, value3, value4, etc. etc. [How to make unpack them to variables?] import string s =3D "value1, value2, value3, value4" var1, var2, var3, var4 =3D map(string.strip, string.split(s, ",")) > I am relatively new to Python and the only other language I have extensive > programming with is VMS's DCL. I hope and believe you will find python enjoyable, although I know nothing about DCL (or VMS). HTH, Kalle --=20 Email: kalle@gnupung.net | You can tune a filesystem, but you Web: http://www.gnupung.net/ | can't tune a fish. -- man tunefs(8) PGP fingerprint: 0C56 B171 8159 327F 1824 F5DE 74D7 80D7 BF3B B1DD --zS7rBR6csb6tI2e1 Content-Type: application/pgp-signature Content-Disposition: inline -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.4 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE6dzx6dNeA1787sd0RAliKAKCps24O9wobdM3et0HA4G5QnzKAQgCgifvi Zy5Q/9ibxN3Z72+1otYPODs= =oSJL -----END PGP SIGNATURE----- --zS7rBR6csb6tI2e1-- From DOUGS@oceanic.com Wed Jan 31 01:31:28 2001 From: DOUGS@oceanic.com (Doug Stanfield) Date: Tue, 30 Jan 2001 15:31:28 -1000 Subject: [Tutor] Unpacking a Tuple - Can It Be Done with a CSV Line? Message-ID: <8457258D741DD411BD3D0050DA62365907A5A1@huina.oceanic.com> What you're looking for is the string functions. There have been some changes in this area between Python 1.5.2 and 2.0. I'm most familiar with 1.5.2 so thats what I give you here: [dougs@lawehana dougs]$ python Python 1.5.2 (#1, Apr 18 1999, 16:03:16) [GCC pgcc-2.91.60 19981201 (egcs-1.1.1 on linux2 Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam >>> import string >>> line = 'value1, value2, value3, value4' >>> values = string.split(line,',') >>> print values ['value1', ' value2', ' value3', ' value4'] >>> -Doug- -----Original Message----- From: Seelinger, Bruce [mailto:bseelinger@neteffectcorp.com] Sent: Tuesday, January 30, 2001 11:50 AM To: 'tutor@python.org' Subject: [Tutor] Unpacking a Tuple - Can It Be Done with a CSV Line? Hello, I am writing a script which opens a file which consists of comma separated entries similar to the example below: value1, value2, value3, value4, etc. etc. The above line is read and assigned to a variable. At that point I was hoping it could be treated as a tuple or sequence of values. Unfortunately, the variable treats the entire line as a single string instead of separate values between the commas. Is there any way to have the line act as a tuple which can be unpacked? Essentially, I want to extract values from a comma separated list of values from each line. I am relatively new to Python and the only other language I have extensive programming with is VMS's DCL. Can anyone help? Thanks in advance for any help! Regards, Bruce Seelinger From amoreira@mercury.ubi.pt Wed Jan 31 10:04:10 2001 From: amoreira@mercury.ubi.pt (Jose Amoreira) Date: Wed, 31 Jan 2001 10:04:10 +0000 Subject: [Tutor] Word count help References: <001b01c08a3c$0761e1a0$f9230b3e@oemcomputer> <3A770604.28E1E2E9@mercury.ubi.pt> <20010130211844.F441@apone.network.loc> Message-ID: <3A77E31A.C8A7DB3F@mercury.ubi.pt> Kalle Svensson wrote: > > Shouldn't this be > if freqs.has_key(word): > ? > > IIRC, dict.keys() and if x in list are both linear time. dict.has_key() is > constant time. I repeat, IIRC. And somebody might have optimized it. Ah, well, I didn't know about that. Thanks for the tip. Actually what you say makes perfecct sense, since key in dict.keys() is a brute force solution to this problem, while dict.has_key(key) probably uses the dictionary hashing function to drop in fast at the (eventual) location of key in the dictionary. I once implemented a dictionary in fortran (I didn't know then that it is a common feature in more modern languages), and I also defined search functions that do the equivalent of dict.has_key(), instead of using the brute force method. Now that I'm spoiled by the use of language with all the proper tools built in, I tend to forget about them! Thanks anyway! Ze amoreira amoreira@mercury.ubi.pt From jpl@global.co.za Wed Jan 31 11:40:54 2001 From: jpl@global.co.za (James Lockley) Date: Wed, 31 Jan 2001 13:40:54 +0200 Subject: [Tutor] os.popen: writing to Message-ID: <001301c08b7a$ab8a1c40$2c829e89@poseidon> This is a multi-part message in MIME format. ------=_NextPart_000_0010_01C08B8B.6F0816D0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable hi all am tryng to automate a process using python to control the calling. At = the moment have pythin calling windows batch files using os.popen, which = works fine. i now want to go to the next step and get rid of the batch files... i need to open a pipe to a command and then write the command arguments = to it. as far as i could make out from the documentation, this should work: >>> abaqus=3D'c:\\abaqus\\5.8-14\\abaqus.exe' >>> abq=3Dos.popen(abaqus,'w') >>> abq.write('post') but i get this: Traceback (innermost last): File "", line 1, in ? IOError: [Errno 22] Invalid argument (this in a dos window works fine: = D:\Work\Current>c:\abaqus\5.8-14\abaqus.exe post) thanks in anticipation james P.S. any idea where to find out what the error numbers corelate to ? -------------------------------------------------------------------------= ------ Ever stop to think and then forget to start again........? -------------------------------------------------------------------------= ------ ------=_NextPart_000_0010_01C08B8B.6F0816D0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable
    hi all
     
    am tryng to automate a process using = python to=20 control the calling.  At the moment have pythin calling windows = batch files=20 using os.popen, which works fine.
     
    i now want to go to the next step and = get rid of=20 the batch files...
    i need to open a pipe to a command and = then write=20 the command arguments to it.
     
    as far as i could make out from the = documentation,=20 this should work:
     
    >>> abaqus=3D'c:\\abaqus\\5.8-14\\abaqus.exe'
    >>>=20 abq=3Dos.popen(abaqus,'w')
    >>>=20 abq.write('post')
     
    but i get this:
     
    Traceback (innermost = last):
     =20 File "<interactive input>", line 1, in ?
    IOError: [Errno 22] = Invalid=20 argument
     
    (this in a dos window works fine:=20 D:\Work\Current>c:\abaqus\5.8-14\abaqus.exe post)
     
    thanks in anticipation
    james
     
    P.S. any idea where to find out what = the error=20 numbers corelate to ?
     
    ----------------------------------------------------------------= ---------------
    Ever stop to think and then forget to = start=20 again........?
    ----------------------------------------------------------------= ---------------
    ------=_NextPart_000_0010_01C08B8B.6F0816D0-- From bseelinger@neteffectcorp.com Wed Jan 31 22:12:29 2001 From: bseelinger@neteffectcorp.com (Seelinger, Bruce) Date: Wed, 31 Jan 2001 17:12:29 -0500 Subject: [Tutor] Equivalent of a Subroutine in Python? Message-ID: <958398973B4A0343A904C2A4157EDEA54FDCDE@ATLEXC01.neteffect.neteffectcorp.com> This message is in MIME format. Since your mail reader does not understand this format, some or all of this message may not be legible. ------_=_NextPart_001_01C08BD2.E6AD3D40 Content-Type: text/plain; charset="iso-8859-1" Hello, Another question from someone totally new to Python. Is there an equivalent in Python to a sub-routine, (e.g. gosub and return). I want to create a modular program with sub-routines to perform distinct tasks wihin the program for organizational and debugging purposes, etc. Is the only (or best) way to do this is with modules? A function works but the values obtained within the function do not appear to be valid outside of that function. I guess I am looking for the best approach to create the subroutines for execution from the main flow of the program. Thanks for any assistance! Regards, Bruce Seelinger ------_=_NextPart_001_01C08BD2.E6AD3D40 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Equivalent of a Subroutine in Python?

    Hello,

    Another question from someone totally = new to Python. Is there an equivalent in Python to a sub-routine, (e.g. = gosub and return).  I want to create a modular program with = sub-routines to perform distinct tasks wihin the program for = organizational and debugging purposes, etc.  Is the only (or best) = way to do this is with modules?  A function works but the values = obtained within the function do not appear to be valid outside of that = function.  I guess I am looking for the best approach to create = the subroutines for execution from the main flow of the = program.

    Thanks for any assistance!

    Regards,

    Bruce Seelinger

    ------_=_NextPart_001_01C08BD2.E6AD3D40-- From AquaRock7@aol.com Wed Jan 31 21:52:06 2001 From: AquaRock7@aol.com (AquaRock7@aol.com) Date: Wed, 31 Jan 2001 16:52:06 EST Subject: [Tutor] NEWBIE!! pipes Message-ID: <50.10cfb61b.27a9e306@aol.com> --part1_50.10cfb61b.27a9e306_boundary Content-Type: text/plain; charset="US-ASCII" Content-Transfer-Encoding: 7bit What are pipes? The docs barely touched this subject, it assumed you already knew what they are... From context I am gathering that it is a connection to the kernel? (maybe?) How can I utilize this? 1 more quickie: >if __name__ == '__main__': > main() what is the pourpose if the above code? It runs the sub main() (duh :) but, why not just main() wihtout the if? what is the conditional testing for? and what are the variables __main__ and __name__? i dont believe they are defined in the program, so just what are they? and, what does putting "__" around a variable actually DO besides look cool ? Thank you, ~Dustin --part1_50.10cfb61b.27a9e306_boundary Content-Type: text/html; charset="US-ASCII" Content-Transfer-Encoding: 7bit What are pipes?  The docs barely touched this subject, it assumed you already
    knew what they are...  From context I am gathering that it is a connection to
    the kernel?  (maybe?)  How can I utilize this?

    1 more quickie:
    >if __name__ == '__main__':
    >     main()

    what is the pourpose if the above code?  It runs the sub main() (duh :) but,
    why not just main() wihtout the if?  what is the conditional testing for?  
    and what are the variables __main__ and __name__?  i dont believe they are
    defined in the program, so just what are they?  and, what does putting "__"
    around a variable actually DO besides look cool ?

    Thank you, ~Dustin
    --part1_50.10cfb61b.27a9e306_boundary-- From vdbroekw@wxs.nl Wed Jan 31 21:12:48 2001 From: vdbroekw@wxs.nl (W.W. van den Broek) Date: Wed, 31 Jan 2001 22:12:48 +0100 Subject: [Tutor] square root References: <20010130215307.C2537EECC@mail.python.org> Message-ID: <3A787FD0.4CD22F54@wxs.nl> How do you use the square root as operator in python? Dumb question, but thanks anyway, walter -- W.W. van den Broek e-mail: vandenbroek@psyd.azr.nl AZR-Dijkzigt fax: 010-4633217 afdeling psychiatrie tel: 010-4639222 Postbus 2040 e-mail vdbroekw@wxs.nl (thuis) 3000 CA Rotterdam homepage: http://home.planet.nl/~vdbroekw From budgester@budgester.com Wed Jan 24 22:59:09 2001 From: budgester@budgester.com (Budgester) Date: Wed, 24 Jan 2001 22:59:09 -0000 Subject: [Tutor] Reading from a GUI In-Reply-To: <20010123214607.B24319@harmony.cs.rit.edu> Message-ID: <000401c08659$4387f9d0$0300000a@budgester> >D-Man Wrote : > >What is meant by "escape code" can differ by useage. For example, in >Eiffel you would use "%N" as the excape code for a newline. \012 is >the octal value of the character. 0xA is the hexadeciaml value and 10 >is the decimal value. In C/C++/Java/Perl and Python \n is used as the >escape for a newline, but with the proper conversion you can use any >of these. They are the escape code I was looking for. >To "read from" a GUI you need to check the docs of the gui you are >using. In GTK, for example, there is a funciton get_text in the >Gtk.Text widget (or some similar name). The function returns a string >object. I'm currently using Tkinter, but from reading this list it seems like the most popular Toolkit is GTK, what is the general preference for python, i.e. best documentation, ease of use, samples etc < I'm not trying to start a holy war here, just peoples experiences ;-) > >import string > >my_str = text_widget.get_text() >modified_str = string.replace( my_str, "\n" , "
    " ) >print my_str >pirnt modified_str pretty much exactly the code I was after. >HTH, Loads thanks I'll let you know how it goes. >-D Budgester